@agentrix/cli 0.40.0 → 0.40.2

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.cjs CHANGED
@@ -1 +1 @@
1
- "use strict";var os=require("node:os"),fs=require("node:fs"),path=require("node:path"),yargs=require("yargs"),helpers=require("yargs/helpers"),chalk=require("chalk"),shared=require("@agentrix/shared"),node_crypto=require("node:crypto"),axios=require("axios"),machine=require("./logger-WoR-bbUU.cjs"),node_readline=require("node:readline"),fs$1=require("fs"),path$1=require("path"),open=require("open"),socket_ioClient=require("socket.io-client"),node_events=require("node:events"),promises=require("node:stream/promises"),node_module=require("node:module"),child_process=require("child_process"),psList=require("ps-list"),spawn=require("cross-spawn"),platform_js=require("@xmz-ai/sandbox-runtime/dist/utils/platform.js"),fastify=require("fastify"),zod=require("zod"),fastifyTypeProviderZod=require("fastify-type-provider-zod"),node_child_process=require("node:child_process"),claudeAgentSdk=require("@anthropic-ai/claude-agent-sdk"),node=require("@agentrix/shared/node"),promises$1=require("node:fs/promises"),node_util=require("node:util"),simpleGit=require("simple-git"),events=require("events"),Database=require("better-sqlite3"),url=require("url"),croner=require("croner"),mcp_js=require("@modelcontextprotocol/sdk/server/mcp.js"),streamableHttp_js=require("@modelcontextprotocol/sdk/server/streamableHttp.js"),crypto$1=require("crypto"),sandboxRuntime=require("@xmz-ai/sandbox-runtime"),lark=require("@larksuiteoapi/node-sdk"),os$1=require("os"),promises$2=require("fs/promises"),codexSdk=require("@openai/codex-sdk"),node_process=require("node:process"),promises$3=require("node:readline/promises");require("winston"),require("node:url");var _documentCurrentScript="undefined"!=typeof document?document.currentScript:null;function _interopNamespaceDefault(e){var t=Object.create(null);return e&&Object.keys(e).forEach(function(n){if("default"!==n){var a=Object.getOwnPropertyDescriptor(e,n);Object.defineProperty(t,n,a.get?a:{enumerable:!0,get:function(){return e[n]}})}}),t.default=e,Object.freeze(t)}var fs__namespace=_interopNamespaceDefault(fs),path__namespace=_interopNamespaceDefault(path),fs__namespace$1=_interopNamespaceDefault(fs$1),path__namespace$1=_interopNamespaceDefault(path$1),lark__namespace=_interopNamespaceDefault(lark);const ALWAYS_ON_ENV_KEYS=new Set(["AGENTRIX_CLAUDE_HOME","AGENTRIX_CODEX_HOME","AGENTRIX_GEMINI_HOME","AGENTRIX_CLAUDE_PATH","AGENTRIX_CODEX_PATH"]);function resolveHomePath$1(e){return e.replace(/^~(?=\/|$)/,os.homedir())}function resolveAgentrixHomeDir(e=process.env){const t=e.AGENTRIX_HOME_DIR||e.AGENTRIX_DIR;return t?resolveHomePath$1(t):path.join(os.homedir(),".agentrix")}function readDaemonEnvSettings(e=process.env){const t=path.join(resolveAgentrixHomeDir(e),"settings.json");if(!fs.existsSync(t))return null;try{const e=fs.readFileSync(t,"utf-8"),n=JSON.parse(e);return n?.daemonEnv||null}catch{return null}}function setProxyAliases(e,t,n){const a=t.toLowerCase();"http_proxy"===a?(e.HTTP_PROXY=n,e.http_proxy=n):"https_proxy"===a?(e.HTTPS_PROXY=n,e.https_proxy=n):"no_proxy"===a?(e.NO_PROXY=n,e.no_proxy=n):"all_proxy"===a?(e.ALL_PROXY=n,e.all_proxy=n):"global_agent_http_proxy"===a&&(e.GLOBAL_AGENT_HTTP_PROXY=n,e.global_agent_http_proxy=n)}function applyAgentHomeAliases(e,t,n){const a=n.trim();a&&("AGENTRIX_CLAUDE_HOME"===t?e.CLAUDE_CONFIG_DIR=resolveHomePath$1(a):"AGENTRIX_CODEX_HOME"===t&&(e.CODEX_HOME=resolveHomePath$1(a)))}function applyDaemonEnvSettings(e=process.env,t){if(!t?.variables)return e;const n=!0===t.enabled;for(const[a,s]of Object.entries(t.variables)){const t=a.trim();if(!t)continue;const i=String(s),o=ALWAYS_ON_ENV_KEYS.has(t);(n||o)&&(e[t]=i,setProxyAliases(e,t,i),applyAgentHomeAliases(e,t,i))}return e}function bootstrapDaemonEnv(e=process.env){return applyDaemonEnvSettings(e,readDaemonEnvSettings(e))}async function delay(e){return new Promise(t=>setTimeout(t,e))}function buildDaemonControlUrl(e,t){return`http://${"::1"===e.host?"[::1]":"127.0.0.1"}:${e.port}${t}`}async function daemonPost(e,t){const n=await machine.machine.readDaemonState();if(!n?.port){const e="No daemon running, no state file found";return machine.logger.debug(`[CONTROL CLIENT] ${e}`),{error:e}}try{const a=process.env.AGENTRIX_DAEMON_HTTP_TIMEOUT?parseInt(process.env.AGENTRIX_DAEMON_HTTP_TIMEOUT):1e4,s=buildDaemonControlUrl(n,e),i=await fetch(s,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t||{}),signal:AbortSignal.timeout(a)});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 machine.logger.debug(`[CONTROL CLIENT] ${n}`),{error:n}}return await i.json()}catch(t){const a=`Request failed: ${e} at ${buildDaemonControlUrl(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 machine.logger.debug(`[CONTROL CLIENT] ${a}`),{error:a}}}async function notifyDaemonSessionStarted(e,t){return await daemonPost("/session-started",{sessionId:e,metadata:t})}async function notifyDaemonDevOpsInitComplete(e,t,n){return await daemonPost("/devops-init-complete",{taskId:e,userId:t,action:n})}async function notifyDaemonStartDevOpsInit(e,t){return await daemonPost("/devops-init-start",{taskId:e,userId:t})}async function sendTaskChannelMessage(e,t,n){const a="string"==typeof t?{content:t}:t;return await daemonPost("/channels/task-message",{taskId:e,...a,...n?{target:n}:{}})}async function getTaskChannelGroupHistory(e,t,n={}){return await daemonPost("/channels/group-history",{taskId:e,target:t,...n})}async function listDaemonSessions(){return(await daemonPost("/list")).children||[]}async function stopDaemonSession(e){return(await daemonPost("/stop-session",{sessionId:e})).success||!1}async function stopDaemonHttp(){await daemonPost("/stop")}async function prepareDaemonGracefulRestart(e){return await daemonPost("/prepare-graceful-restart",{source:"agentrix-cli",reason:e})}async function bindGitServerViaDaemon(e){return await daemonPost("/git-server/bind",e)}async function listGitServersViaDaemon(){return await daemonPost("/git-server/list")}async function checkIfDaemonRunningAndCleanupStaleState(){const e=await machine.machine.readDaemonState();if(!e)return!1;try{return process.kill(e.pid,0),!0}catch{return machine.logger.debug("[DAEMON RUN] Daemon PID not running, cleaning up state"),await cleanupDaemonState(),!1}}async function isLatestDaemonRunning(){if(machine.logger.debug("[DAEMON CONTROL] Checking if daemon is running same version"),!await checkIfDaemonRunningAndCleanupStaleState())return machine.logger.debug("[DAEMON CONTROL] No daemon running, returning false"),!1;const e=await machine.machine.readDaemonState();if(!e)return machine.logger.debug("[DAEMON CONTROL] No daemon state found, returning false"),!1;try{const t=path$1.join(machine.projectPath(),"package.json"),n=JSON.parse(fs$1.readFileSync(t,"utf-8")).version;return machine.logger.debug(`[DAEMON CONTROL] Current CLI version: ${n}, Daemon started with version: ${e.cliVersion}`),n===e.cliVersion}catch(e){return machine.logger.debug("[DAEMON CONTROL] Error checking daemon version",e),!1}}async function cleanupDaemonState(){try{await machine.machine.clearDaemonState(),machine.logger.debug("[DAEMON RUN] Daemon state file removed")}catch(e){machine.logger.debug("[DAEMON RUN] Error cleaning up daemon metadata",e)}}async function stopDaemon(){try{const e=await machine.machine.readDaemonState();if(!e)return void machine.logger.debug("No daemon state found");machine.logger.debug(`Stopping daemon with PID ${e.pid}`);try{return await stopDaemonHttp(),void await waitForProcessDeath(e.pid,2e3)}catch(e){machine.logger.debug("HTTP stop failed, will force kill",e)}process.kill(e.pid,"SIGKILL")}catch(e){machine.logger.debug("Error stopping daemon",e)}}async function waitForProcessDeath(e,t){const n=Date.now();for(;Date.now()-n<t;)try{process.kill(e,0),await new Promise(e=>setTimeout(e,100))}catch{return}throw new Error("Process did not die within timeout")}function generateWebAuthUrl(e,t){const n={key:shared.encodeBase64(e,"base64"),machineId:t},a=JSON.stringify(n),s=shared.encodeBase64((new TextEncoder).encode(a),"base64url");return`${machine.machine.webappUrl}/terminal/connect?auth=${s}`}async function handleAuthLogout(){if(!await machine.machine.readCredentials())return void console.log(chalk.yellow("Not currently authenticated"));console.log(chalk.blue("This will log you out of Agentrix")),console.log(chalk.yellow("⚠️ You will need to re-authenticate to use Agentrix again"));const e=node_readline.createInterface({input:process.stdin,output:process.stdout}),t=await new Promise(t=>{e.question(chalk.yellow("Are you sure you want to log out? (y/N): "),t)});if(e.close(),"y"===t.toLowerCase()||"yes"===t.toLowerCase())try{try{await stopDaemon(),console.log(chalk.gray("Stopped daemon"))}catch{}await machine.machine.clearCredentials(),console.log(chalk.gray("Removed credentials")),console.log(chalk.green("✓ Successfully logged out"))}catch(e){throw new Error(`Failed to logout: ${e instanceof Error?e.message:"Unknown error"}`)}else console.log(chalk.blue("Logout cancelled"))}async function handleAuthStatus(){const e=await machine.machine.readCredentials();if(console.log(chalk.bold("\nAuthentication Status\n")),!e)return void console.log(chalk.red("✗ Not authenticated"));console.log(chalk.green("✓ Authenticated"));const t=e.token.substring(0,30)+"...";console.log(chalk.gray(` Token: ${t}`)),e.machineId?(console.log(chalk.green("✓ Machine registered")),console.log(chalk.gray(` Machine ID: ${e.machineId}`)),console.log(chalk.gray(` Host: ${os.hostname()}`))):console.log(chalk.yellow("⚠️ Machine not registered")),console.log(chalk.gray(`\n Data directory: ${machine.machine.agentrixHomeDir}`));try{await checkIfDaemonRunningAndCleanupStaleState()?console.log(chalk.green("✓ Daemon running")):console.log(chalk.gray("✗ Daemon not running"))}catch{console.log(chalk.gray("✗ Daemon not running"))}}async function openBrowser(e){try{return!process.stdout.isTTY||process.env.CI||process.env.HEADLESS?(machine.logger.debug("[browser] Headless environment detected, skipping browser open"),!1):(machine.logger.debug(`[browser] Attempting to open URL: ${e}`),await open(e),machine.logger.debug("[browser] Browser opened successfully"),!0)}catch(e){return machine.logger.debug("[browser] Failed to open browser:",e),!1}}function withReauthHint(e){return`${e}\nRun \`agentrix logout\` and bind this machine again.`}function formatMachineAuthError(e,t){if(axios.isAxiosError(e)){const n=e.response?.data?.message;return"string"==typeof n&&n.length>0?n.includes("Machine binding revoked")?withReauthHint(n):`${t}: ${n}`:"string"==typeof e.message&&e.message.includes("Machine binding revoked")?withReauthHint(e.message):`${t}: ${e.message}`}return e instanceof Error&&e.message.includes("Machine binding revoked")?withReauthHint(e.message):e instanceof Error?`${t}: ${e.message}`:t}function generateLocalAuthSecret(){return shared.encodeBase64(new Uint8Array(node_crypto.randomBytes(32)))}function readMachineAesKey(e){if(!e.machineAesKey)return null;try{const t=shared.decodeBase64(e.machineAesKey);return 32===t.length?t:null}catch{return null}}function ensureMachineAesKey(e){const t=readMachineAesKey(e);if(t)return t;const n=shared.generateAESKey();return e.machineAesKey=shared.encodeBase64(n),n}async function doAuth(){console.clear();const e=machine.machine.generateMachineId(),t=new Uint8Array(node_crypto.randomBytes(32)),n=await shared.createKeyPairWithUit8Array(t);try{console.log(`[AUTH] Sending auth request to: ${machine.machine.serverUrl}/v1/auth/machine`),console.log(`[AUTH] Public key: ${shared.encodeBase64(n.publicKey).substring(0,20)}...`);const t={machineId:e};await axios.post(`${machine.machine.serverUrl}/v1/auth/machine`,t),console.log("[AUTH] Auth request sent successfully")}catch(e){return console.log(formatMachineAuthError(e,"Failed to create authentication request, please try again later.")),{credentials:null,userPublicKey:null,keypair:n}}const a=await doWebAuth(n,e);return a.token?{credentials:{token:a.token,secret:shared.encodeBase64(t),machineId:e},userPublicKey:a?.userPublicKey,keypair:n}:{credentials:null,userPublicKey:null,keypair:n}}async function doWebAuth(e,t){console.clear(),console.log("\nWeb Authentication\n");const n=generateWebAuthUrl(e.publicKey,t);return console.log("Opening your browser..."),await openBrowser(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 waitForAuthentication(e,t)}async function waitForAuthentication(e,t){process.stdout.write("Waiting for authentication");let n=0,a=!1;const s=()=>{a=!0,console.log("\n\nAuthentication cancelled."),process.exit(0)};process.on("SIGINT",s);try{for(;!a;){try{const n=await axios.get(`${machine.machine.serverUrl}/v1/auth/machine?machineId=${t}`);if("authorized"===n.data.state){const t=n.data.token,a=n.data.content,s=shared.decryptWithEphemeralKey(shared.decodeBase64(a),e.secretKey);return s?{token:t,userPublicKey:JSON.parse((new TextDecoder).decode(s)).publicKey}:(console.log("\n\nFailed to decrypt authentication data. Please try again."),{token:null,userPublicKey:null})}}catch(e){return console.log(`\n\n${formatMachineAuthError(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 delay(1e3)}}finally{process.off("SIGINT",s)}return{token:null,userPublicKey:null}}async function syncMachine(e,t,n,a){try{const s={id:e.machineId,metadata:JSON.stringify(t)};if(a&&n){const t=ensureMachineAesKey(e);s.dataEncryptionKey=shared.encryptMachineEncryptionKey(a.publicKey,t,shared.decodeBase64(n))}await axios.post(`${machine.machine.serverUrl}/v1/machines/sync`,s,{headers:{Authorization:`Bearer ${e.token}`,"Content-Type":"application/json"},timeout:6e4})}catch(e){throw new Error(formatMachineAuthError(e,"Failed to sync machine data"))}}async function validateExistingCredentials(e){try{await axios.get(`${machine.machine.serverUrl}/v1/machines/validate`,{headers:{Authorization:`Bearer ${e.token}`},timeout:15e3})}catch(e){throw new Error(formatMachineAuthError(e,"Stored machine credentials are no longer valid"))}}async function authAndSetupMachineIfNeeded(){const e=await machine.machine.readCredentials();if(e){await validateExistingCredentials(e);let t=e;e.secret||(t={...e,secret:generateLocalAuthSecret()},await machine.machine.writeCredentials(t),machine.logger.info("[AUTH] Generated missing local auth secret"));try{await syncMachine(t,machine.machine.metadata()),machine.logger.info("[AUTH] Machine metadata synced")}catch(e){machine.logger.warn("[AUTH] Failed to sync machine metadata",e)}return machine.logger.info("[AUTH] Using existing credentials"),t}const t=process.env.CLOUD_AUTH_TOKEN;let n,a,s;if(t){const e=machine.machine.generateMachineId();n={token:t,secret:generateLocalAuthSecret(),machineId:e},machine.logger.info(`[AUTH] Cloud mode detected, generated machine ID: ${e}`)}else{const e=await doAuth();if(!e.credentials||!e.userPublicKey)throw new Error("Authentication failed or was cancelled");n=e.credentials,a=e.keypair,s=e.userPublicKey}return await syncMachine(n,machine.machine.metadata(),s,a),await machine.machine.writeCredentials(n),machine.logger.info("[AUTH] Machine setup completed"),n}bootstrapDaemonEnv();const logger$a=machine.createModuleLogger("undefined"==typeof document?require("url").pathToFileURL(__filename).href:_documentCurrentScript&&"SCRIPT"===_documentCurrentScript.tagName.toUpperCase()&&_documentCurrentScript.src||new URL("index.cjs",document.baseURI).href),REDACTED_LOG_VALUE="[REDACTED]",SENSITIVE_LOG_KEYS=new Set(["authorization","apikey","accesstoken","refreshtoken","machineaeskey","key","password","pat","secret","token"]);class KeepAliveManager{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 readSocketErrorData(e){const t=shared.SocketAuthErrorDataSchema.safeParse(e);return t.success?t.data:null}function getSocketErrorDetails(e){if(!e||"object"!=typeof e)return{message:String(e??"unknown error")};const t=e,n=readSocketErrorData(t.data);return n?{message:n.message||t.message||"Socket connection failed",...n.code?{code:n.code}:{},...n.action?{action:n.action}:{}}:{message:t.message||"unknown socket error"}}function formatSocketError(e){if(!e||"object"!=typeof e)return String(e??"unknown error");const t=e,n=getSocketErrorDetails(e);if(n.code||n.action)return[n.code?`[${n.code}]`:void 0,n.message,n.action].filter(Boolean).join(" ");const a=[];return t.message&&a.push(t.message),t.type&&a.push(`type=${t.type}`),void 0!==t.description&&a.push(`description=${stringifyForLog(t.description)}`),void 0!==t.data&&a.push(`data=${stringifyForLog(t.data)}`),void 0!==t.context&&a.push(`context=${stringifyForLog(t.context)}`),a.filter(Boolean).join(" ")||"unknown socket error"}function redactSocketPayloadForLog(e,t=0){if(t>8)return"[MaxDepth]";if(Array.isArray(e))return e.map(e=>redactSocketPayloadForLog(e,t+1));if(!e||"object"!=typeof e)return e;const n={};for(const[a,s]of Object.entries(e)){const e=a.replace(/[-_]/g,"").toLowerCase();n[a]=SENSITIVE_LOG_KEYS.has(e)?"[REDACTED]":redactSocketPayloadForLog(s,t+1)}return n}function stringifyForLog(e){try{return JSON.stringify(redactSocketPayloadForLog(e))}catch{return"[Unserializable]"}}function summarizeSocketPayloadForLog(e){if(!e||"object"!=typeof e||Array.isArray(e))return{};const t=e,n=t.data&&"object"==typeof t.data&&!Array.isArray(t.data)?t.data:void 0,a={},s=["eventId","taskId","chatId","from","senderType","messageType","opCode","sequence","status"];for(const e of s)void 0!==t[e]&&(a[e]=t[e]);void 0!==n?.sequence&&(a.ackSequence=n.sequence),void 0!==t.message&&(a.hasMessage=!0),"string"==typeof t.encryptedMessage&&(a.encrypted=!0,a.encryptedMessageChars=t.encryptedMessage.length);const i=new Set(s),o=Object.keys(t).filter(e=>!i.has(e)&&"message"!==e&&"encryptedMessage"!==e);return o.length>0&&(a.extraKeys=o.sort()),a}class SocketClient{socket=null;config;eventHandlers=new Map;eventEmitter=new node_events.EventEmitter;KeepAliveManager=null;healthCheckInterval=null;connectStartedAt=null;constructor(e){this.config=e,e.keepAliveConfig&&(this.KeepAliveManager=new KeepAliveManager(e.keepAliveConfig))}connect(){if(this.socket)return void this.targetLogger.debug("Already connected or connecting");const{serverUrl:e,path:t,auth:n={},options:a={}}=this.config,s={path:t,auth:n,transports:["websocket"],reconnection:!0,reconnectionDelay:1e3,reconnectionDelayMax:5e3,reconnectionAttempts:1/0,...a};this.connectStartedAt=Date.now(),this.socket=socket_ioClient.io(e,s),this.setupSocketHandlers(),this.targetLogger.debug(`Connecting to ${e}`)}disconnect(){this.socket&&(this.targetLogger.info("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.targetLogger.debug(`received event ${e}, summary: ${stringifyForLog(summarizeSocketPayloadForLog(n))}`),t(n)),a=this.eventHandlers.get(e);this.eventHandlers.set(e,n),this.replaceSocketHandler(e,a,n)}onEventWithAck(e,t){const n=async(n,a)=>(this.targetLogger.debug(`received event with ack ${e}, summary: ${stringifyForLog(summarizeSocketPayloadForLog(n))}`),t(n,a)),a=this.eventHandlers.get(e);this.eventHandlers.set(e,n),this.replaceSocketHandler(e,a,n)}unregisterHandler(e){this.eventHandlers.delete(e),this.socket&&this.socket.off(e)}send(e,t){this.socket?(this.targetLogger.debug(`send event ${e}, summary: ${stringifyForLog(summarizeSocketPayloadForLog(t))}`),void 0!==t?this.socket.emit(e,t):this.socket.emit(e)):this.targetLogger.warn("Cannot send - socket not connected")}async sendWithAck(e,t){if(!this.socket)throw new Error("Cannot send - socket not connected");return this.targetLogger.debug(`send event ${e}, summary: ${stringifyForLog(summarizeSocketPayloadForLog(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",()=>{const e=this.connectStartedAt?Date.now()-this.connectStartedAt:void 0;this.connectStartedAt=null,this.targetLogger.info(`socket.connected host=${this.config.serverUrl}${void 0!==e?` connectMs=${e}`:""}`),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.targetLogger.info(`Disconnected: ${e||"unknown"}`),this.eventEmitter.emit("lifecycle:disconnect",e),this.KeepAliveManager?.stop(),this.stopHealthCheck()}),this.socket.on("connect_error",e=>{this.targetLogger.warn(`Connection error: ${formatSocketError(e)}`),this.eventEmitter.emit("lifecycle:connect_error",e),setTimeout(()=>this.socket?.connect(),5e3)}),this.socket.on("error",e=>{this.targetLogger.warn(`Socket error: ${formatSocketError(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.targetLogger.warn("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)}get targetLogger(){return this.config.logger??logger$a}}const FALLBACK_FILE_NAME="attachment",MIME_EXTENSION_MAP={"image/jpeg":".jpg","image/png":".png","image/gif":".gif","image/webp":".webp","image/heic":".heic","application/pdf":".pdf"};function getChannelFilesDir(){const e=path.join(machine.machine.agentrixHomeDir,"tmp","channel-files");return fs.existsSync(e)||fs.mkdirSync(e,{recursive:!0}),e}function createChannelFilePath(e){const t=sanitizeFileName(e)||"attachment";return path.join(getChannelFilesDir(),`${node_crypto.randomUUID()}-${t}`)}function resolveChannelFilePath(e){const t=path.resolve(getChannelFilesDir()),n=path.resolve(e);if(n!==t&&!n.startsWith(`${t}${path.sep}`))throw new Error("Access denied: channel attachment path is outside channel files directory");return n}async function saveResponseToChannelFile(e,t){if(!e.ok)throw new Error(`HTTP ${e.status}: ${e.statusText}`);if(!e.body)throw new Error("Response body is null");const n=createChannelFilePath(resolveFileName(t||getFileNameFromContentDisposition(e.headers.get("content-disposition")),e.headers.get("content-type"))),a=fs.createWriteStream(n);return await promises.pipeline(e.body,a),n}async function downloadUrlToChannelFile(e,t,n){const a=await fetch(e,n),s=getFileNameFromUrl(e);return saveResponseToChannelFile(a,t||s)}function sanitizeFileName(e){if(e)return path.basename(e).replace(/[<>:"/\\|?*\x00-\x1F]/g,"_").trim()||void 0}function getFileNameFromContentDisposition(e){if(!e)return;const t=e.match(/filename\*=UTF-8''([^;]+)/i);if(t?.[1])return decodeURIComponent(t[1]);const n=e.match(/filename="?([^";]+)"?/i);return n?.[1]}function getFileNameFromUrl(e){try{const t=path.basename(new URL(e).pathname);return path.extname(t)?t:void 0}catch{return}}function resolveFileName(e,t){if(!e){const e=getExtensionFromContentType(t);return e?`attachment${e}`:void 0}if(path.extname(e))return e;const n=getExtensionFromContentType(t);return n?`${e}${n}`:e}function getExtensionFromContentType(e){const t=e?.split(";")[0]?.trim().toLowerCase();return t?MIME_EXTENSION_MAP[t]:void 0}var mimeDb,hasRequiredMimeDb,hasRequiredMimeTypes,mimeTypes={},require$$0={"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}};function requireMimeDb(){return hasRequiredMimeDb?mimeDb:(hasRequiredMimeDb=1,mimeDb=require$$0)}function requireMimeTypes(){return hasRequiredMimeTypes||(hasRequiredMimeTypes=1,function(e){var t,n,a,s=requireMimeDb(),i=path$1.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&&s[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 a=e.charset(n);a&&(n+="; charset="+a.toLowerCase())}return n},e.extension=function(t){if(!t||"string"!=typeof t)return!1;var n=o.exec(t),a=n&&e.extensions[n[1].toLowerCase()];return!(!a||!a.length)&&a[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,a=["nginx","apache",void 0,"iana"],Object.keys(s).forEach(function(e){var i=s[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=a.indexOf(s[n[c]].source),d=a.indexOf(i.source);if("application/octet-stream"!==n[c]&&(l>d||l===d&&"application/"===n[c].substr(0,12)))continue}n[c]=e}}})}(mimeTypes)),mimeTypes}var mimeTypesExports=requireMimeTypes();async function decryptDataEncryptionKey(e){try{const t=await machine.machine.getSecretKey();if(!t)return machine.logger.warn("[WORKSPACE] Machine secret key not available"),null;const n=shared.decodeBase64(e);return shared.decryptWithEphemeralKey(n,t)||(machine.logger.warn("[WORKSPACE] Failed to decrypt dataEncryptionKey"),null)}catch(e){return machine.logger.warn("[WORKSPACE] Error decrypting dataEncryptionKey:",e),null}}function resolveFilePath$1(e,t,n){if(n.startsWith("channel-attachment/")){const e=n.slice(19);return resolveChannelFilePath(decodeURIComponent(e))}return machine.machine.resolveWorkspaceFilePath(e,t,n)}function isWithinWorkspaceBase$1(e,t,n,a){const s=n.replace(/^\/+/,""),i="project"===s||s.startsWith("project/")?"project":"data"===s||s.startsWith("data/")?"data":"",o=path__namespace.normalize(machine.machine.resolveWorkspaceFilePath(e,t,i)),r=path__namespace.normalize(a);return r===o||r.startsWith(o+path__namespace.sep)}function sendResponse(e,t){e?e.send("workspace-file-response",t):machine.logger.error("[WORKSPACE] Cannot send workspace-file-response: client not available")}function sendMutationResponse(e,t){e?e.send("workspace-file-mutation-response",t):machine.logger.error("[WORKSPACE] Cannot send workspace-file-mutation-response: client not available")}function createErrorResponse(e,t,n,a){return{eventId:shared.createEventId(),requestId:e,taskId:t,success:!1,error:{code:n,message:a}}}function createMutationErrorResponse(e,t,n,a){return{eventId:shared.createEventId(),requestId:e,taskId:t,success:!1,error:{code:n,message:a}}}function handleNotModified(e,t,n,a){machine.logger.debug(`[WORKSPACE] File not modified: ${a}`),sendResponse(e,{eventId:shared.createEventId(),requestId:t,taskId:n,success:!0,notModified:!0})}async function handleDirectory(e,t,n,a,s,i){const o=await fs__namespace.promises.readdir(a,{withFileTypes:!0}),r=await Promise.all(o.map(async e=>{const t=path__namespace.join(a,e.name),n=await fs__namespace.promises.stat(t);return{name:e.name,type:e.isDirectory()?"directory":"file",size:n.size,modifiedAt:n.mtime.toISOString(),accessDenied:n.size>i}}));sendResponse(e,{eventId:shared.createEventId(),requestId:t,taskId:n,success:!0,data:{type:"directory",entries:r,metadata:{size:0,modifiedAt:s.mtime.toISOString()}}})}function handleFileTooLarge(e,t,n,a,s,i,o){machine.logger.warn(`[WORKSPACE] File too large (${s.size} bytes > ${o} bytes): ${a}`),sendResponse(e,{eventId:shared.createEventId(),requestId:t,taskId:n,success:!0,data:{type:"file",metadata:{size:s.size,mimeType:i,modifiedAt:s.mtime.toISOString(),accessDenied:!0}}})}async function handleFile(e,t,n,a,s,i){const o=mimeTypesExports.lookup(a)||"application/octet-stream",r=(await fs__namespace.promises.readFile(a)).toString("base64");let c=null;i&&(c=await decryptDataEncryptionKey(i));const l={type:"file",metadata:{size:s.size,mimeType:o,modifiedAt:s.mtime.toISOString()}};c?l.encryptedContent=shared.encryptFileContent(r,c):l.content=r,sendResponse(e,{eventId:shared.createEventId(),requestId:t,taskId:n,success:!0,data:l})}function workspaceFileMutationRequestHandler(e){return async t=>{const{taskId:n,userId:a,relativePath:s,requestId:i,operation:o,content:r,createOnly:c}=t;machine.logger.debug(`[WORKSPACE] File mutation request: taskId=${n}, userId=${a}, relativePath=${s}, operation=${o}, createOnly=${!!c}`);try{if(s.startsWith("channel-attachment/"))return void sendMutationResponse(e.client,createMutationErrorResponse(i,n,"permission_denied","Channel attachments are read-only"));const t=resolveFilePath$1(a,n,s);if(!isWithinWorkspaceBase$1(a,n,s,t))return void sendMutationResponse(e.client,createMutationErrorResponse(i,n,"permission_denied","Path escapes workspace"));if("delete"===o)return await fs__namespace.promises.rm(t,{force:!1}),void sendMutationResponse(e.client,{eventId:shared.createEventId(),requestId:i,taskId:n,success:!0,data:{relativePath:s,operation:o}});if(void 0===r)return void sendMutationResponse(e.client,createMutationErrorResponse(i,n,"bad_request","File content is required"));await fs__namespace.promises.mkdir(path__namespace.dirname(t),{recursive:!0});try{await fs__namespace.promises.writeFile(t,r,c?{flag:"wx"}:void 0)}catch(t){if("EEXIST"===t.code)return void sendMutationResponse(e.client,createMutationErrorResponse(i,n,"file_exists","File already exists"));throw t}const l=await fs__namespace.promises.stat(t);sendMutationResponse(e.client,{eventId:shared.createEventId(),requestId:i,taskId:n,success:!0,data:{relativePath:s,operation:o,modifiedAt:l.mtime.toISOString()}})}catch(t){machine.logger.error(`[WORKSPACE] Failed to handle workspace-file-mutation-request: ${t.message}`,t);const a="ENOENT"===t.code?"file_not_found":"EACCES"===t.code?"permission_denied":"unknown_error";sendMutationResponse(e.client,createMutationErrorResponse(i,n,a,t.message))}}}function workspaceFileRequestHandler(e){return async t=>{const{taskId:n,userId:a,relativePath:s,requestId:i,maxFileSizeMB:o,ifModifiedSince:r,dataEncryptionKey:c}=t;machine.logger.debug(`[WORKSPACE] File request: taskId=${n}, userId=${a}, relativePath=${s}, maxFileSizeMB=${o}, ifModifiedSince=${r}, hasEncryptionKey=${!!c}`);try{const t=1024*(o||10)*1024,l=resolveFilePath$1(a,n,s);if(!fs__namespace.existsSync(l))return machine.logger.warn(`[WORKSPACE] File not found: ${l}`),void sendResponse(e.client,createErrorResponse(i,n,"file_not_found","File or directory not found"));const d=await fs__namespace.promises.stat(l),p=d.mtime.toISOString();if(r&&p===r)return void handleNotModified(e.client,i,n,l);if(d.isDirectory())return void await handleDirectory(e.client,i,n,l,d,t);{const a=mimeTypesExports.lookup(l)||"application/octet-stream";return d.size>t?void handleFileTooLarge(e.client,i,n,l,d,a,t):void await handleFile(e.client,i,n,l,d,c)}}catch(t){machine.logger.error(`[WORKSPACE] Failed to handle workspace-file-request: ${t.message}`,t);const a="ENOENT"===t.code?"file_not_found":"EACCES"===t.code?"permission_denied":"unknown_error";sendResponse(e.client,createErrorResponse(i,n,a,t.message))}}}function failure(e,t){return{eventId:shared.createEventId(),status:"failed",opCode:e,message:t}}function assertSafeIssueId(e){if(!/^[A-Za-z0-9._-]+$/.test(e)||e.includes(".."))throw new Error("Invalid Vision Plan issue id")}function assertInside(e,t){const n=path__namespace.relative(t,e);if(n.startsWith("..")||path__namespace.isAbsolute(n))throw new Error("Vision Plan review path is outside the bound issue directory")}async function nextReviewFile(e){await fs__namespace.promises.mkdir(e,{recursive:!0});let t=(await fs__namespace.promises.readdir(e).catch(()=>[])).reduce((e,t)=>{const n=/^(\d{3})(?:-|\.md$)/.exec(t);return n?Math.max(e,Number(n[1])):e},0)+1;for(;;){const n=`${String(t).padStart(3,"0")}-vision-plan-review.md`,a=path__namespace.join(e,n);try{const e=await fs__namespace.promises.open(a,"wx");return await e.close(),a}catch(e){if("EEXIST"!==e.code)throw e;t+=1}}}function visionPlanReviewWriteHandler(){return async(e,t)=>{const n="string"==typeof e?.eventId?e.eventId:"vision-plan-review-write";try{const a=shared.VisionPlanReviewWriteEventSchema.parse(e);assertSafeIssueId(a.issueId);const s=`project/.agentrix/issues/${a.issueId}/review/user`;if(a.reviewDirRelativePath!==s)return void t(failure(n,"Vision Plan review write path does not match the bound issue"));const i=machine.machine.resolveWorkspaceFilePath(a.userId,a.taskId,s);assertInside(i,machine.machine.resolveWorkspaceFilePath(a.userId,a.taskId,`project/.agentrix/issues/${a.issueId}`));const o=await nextReviewFile(i);assertInside(o,i),await fs__namespace.promises.writeFile(o,a.content.endsWith("\n")?a.content:`${a.content}\n`,"utf8");const r=path__namespace.posix.join(s,path__namespace.basename(o)).replace(/^project\//,"");t({eventId:shared.createEventId(),status:"success",opCode:a.eventId,data:{relativePath:r}})}catch(e){machine.logger.error("[VisionPlanReviewWrite] Failed to write review:",e),t(failure(n,e instanceof Error?e.message:"Failed to write Vision Plan review"))}}}const GITLAB_PER_PAGE=100,GITLAB_PAGE_BATCH_SIZE=4,AGENTRIX_TRIGGER_DESCRIPTION="Agentrix webhook bridge",PROXY_ALLOWLIST=[{method:"GET",pattern:/^\/user$/},{method:"GET",pattern:/^\/projects$/},{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 GitLabExecutor{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}withMetadata(e,t={}){return{data:e,metadata:t}}truncateText(e,t=300){return e.length<=t?e:`${e.slice(0,t)}...`}async requestWithResponse(e,t="GET",n){const a=`${this.apiUrl}${e}`,s={Authorization:`Bearer ${this.pat}`,"Content-Type":"application/json"},i=Date.now();try{const o=await fetch(a,{method:t,headers:s,body:n?JSON.stringify(n):void 0}),r=Date.now()-i;if(!o.ok){const n=await o.text().catch(()=>"Unknown error"),a=this.truncateText(n);throw machine.logger.warn(`${this.logPrefix()} request failed: ${t} ${e}, status=${o.status}, elapsedMs=${r}, detail=${a}`),{status:o.status,message:`GitLab API error: ${o.status} ${o.statusText}`,detail:a}}return{data:await o.json(),headers:o.headers,status:o.status}}catch(n){if("object"==typeof n&&null!==n&&"status"in n)throw n;const a=n instanceof Error?n.message:"Unknown network error";throw machine.logger.error(`${this.logPrefix()} request exception: ${t} ${e}, message=${a}`),{status:0,message:`GitLab request failed: ${a}`}}}async requestForm(e,t){const n=`${this.apiUrl}${e}`,a={Authorization:`Bearer ${this.pat}`,"Content-Type":"application/x-www-form-urlencoded"},s=Date.now();try{const i=await fetch(n,{method:"POST",headers:a,body:t}),o=Date.now()-s;if(!i.ok){const t=await i.text().catch(()=>"Unknown error"),n=this.truncateText(t);throw machine.logger.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 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 machine.logger.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:a}=await this.requestWithResponse(e,t,n);return a}withQueryParams(e,t){const[n,a=""]=e.split("?"),s=new URLSearchParams(a);for(const[e,n]of Object.entries(t))s.set(e,String(n));const i=s.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 a=2;a<=e;a+=4){const s=Math.min(a+4-1,e),i=Array.from({length:s-a+1},(e,t)=>a+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:100,page:1}),n=await this.requestWithResponse(t),a=[...n.data],s=this.parseTotalPages(n.headers);if(s&&s>1){const t=await this.fetchRemainingPagesInBatches(s,async t=>{const n=this.withQueryParams(e,{per_page:100,page:t});return this.request(n)});return a.push(...t),a}if(!s&&100===n.data.length){let t=2;for(;;){const n=this.withQueryParams(e,{per_page:100,page:t}),s=await this.request(n);if(0===s.length)break;if(a.push(...s),s.length<100)break;t+=1}}return a}async executeOperation(e,t,n={}){return(await this.executeOperationWithMetadata(e,t,n)).data}async executeOperationWithMetadata(e,t,n={}){n.silent||machine.logger.info(`${this.logPrefix()} execute operation: op=${e}, payloadKeys=${Object.keys(t||{}).join(",")||"-"}`);try{let a;switch(e){case"listRepos":a=this.withMetadata(await this.listRepos());break;case"listBranches":a=this.withMetadata(await this.listBranches(t.owner,t.name));break;case"createMergeRequest":a=this.withMetadata(await this.createMergeRequest(t));break;case"getMergeRequest":a=this.withMetadata(await this.getMergeRequest(t.owner,t.name,t.iid));break;case"listMergeRequests":a=this.withMetadata(await this.listMergeRequests(t.owner,t.name));break;case"triggerPipeline":a=this.withMetadata(await this.triggerPipeline(t));break;case"ensurePipelineTriggerToken":a=this.withMetadata(await this.ensurePipelineTriggerToken(t));break;case"requestGitlabApi":a=await this.requestGitlabApi(t);break;case"resolveGitAuthContext":a=this.withMetadata({authMode:"local_pat",hasPat:!0});break;default:throw{status:400,message:`Unknown operation: ${e}`}}return n.silent||machine.logger.info(`${this.logPrefix()} operation success: op=${e}, summary=${this.summarizeResult(e,a.data)}`),a}catch(t){const a=t instanceof Error?t.message:"object"==typeof t&&null!==t&&"message"in t?String(t.message):"Unknown error";throw n.silent||machine.logger.error(`${this.logPrefix()} operation failed: op=${e}, message=${a}`),t}}async listRepos(){return(await this.requestPaginated("/projects?membership=true&order_by=updated_at&sort=desc")).map(e=>({id:e.id,owner:e.path_with_namespace.split("/").slice(0,-1).join("/")||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 a=encodeURIComponent(`${e}/${t}`),s=await this.request(`/projects/${a}/merge_requests/${n}`);return{number:s.iid,title:s.title,body:s.description,state:"opened"===s.state?"open":s.state,url:s.web_url,head:s.source_branch,base:s.target_branch,createdAt:s.created_at,updatedAt:s.updated_at}}async listMergeRequests(e,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"),a=this.parseOptionalString(e.repo??e.name,"repo");if(!n||!a)throw{status:400,message:"projectId, projectPath, or owner + repo is required"};return encodeURIComponent(`${n}/${a}`)}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,a]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!=a){if("string"!=typeof a&&"number"!=typeof a&&"boolean"!=typeof a)throw{status:400,message:`Pipeline variable value for "${n}" is invalid`};t[n]=String(a)}}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 a=this.parseOptionalString(t.triggerDescription,"triggerDescription")??"Agentrix webhook bridge",s=(await this.requestPaginated(`/projects/${e}/triggers`)).find(e=>e.description===a&&this.isUsableTriggerToken(e.token));if(s?.token)return s.token;const i=new URLSearchParams;i.set("description",a);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"),a=this.parsePipelineVariables(e.variables),s=await this.resolvePipelineTriggerToken(t,e),i=new URLSearchParams;i.set("token",s),i.set("ref",n);for(const[e,t]of Object.entries(a))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,a]of Object.entries(e))if(null!=a)if(Array.isArray(a))for(const e of a){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 a&&"number"!=typeof a&&"boolean"!=typeof a)throw{status:400,message:`Proxy query value for "${n}" is invalid`};t.append(n,String(a))}return t.toString()}isProxyAllowed(e,t){return PROXY_ALLOWLIST.some(n=>n.method===e&&n.pattern.test(t))}async requestGitlabApi(e){const t=this.parseProxyMethod(e.method),n=this.parseProxyPath(e.path),a=this.buildProxyQueryString(e.query),s=a.length>0?`${n}?${a}`:n;if(!this.isProxyAllowed(t,n))throw{status:403,message:`Proxy path not allowed: ${t} ${n}`};if("GET"===t){const e=await this.requestWithResponse(s,t);return this.withMetadata(e.data,{status:e.status})}const i=await this.requestWithResponse(s,t,e.body);return this.withMetadata(i.data,{status:i.status})}}function normalizeBaseUrl$1(e){return e.replace(/\/+$/,"")}function modelUrl(e){const t=normalizeBaseUrl$1(e);return t.endsWith("/v1")?`${t}/models`:`${t}/v1/models`}function inferProtocol(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}function safeEndpointLabel(e){try{const t=new URL(e);return`${t.protocol}//${t.host}${t.pathname.replace(/\/+$/,"")}`}catch{return e}}function summarizeError(e){return axios.isAxiosError(e)?{message:e.message,status:e.response?.status,code:e.code}:{message:e instanceof Error?e.message:String(e)}}async function fetchModels(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}`},a=await axios.get(modelUrl(e.baseUrl),{headers:n,timeout:1e4});return(a.data?.data||[]).map(e=>e&&"object"==typeof e&&"id"in e?String(e.id):null).filter(e=>Boolean(e))}async function fetchEndpointModels(e){const t=inferProtocol(e.baseUrl),n=t?[t]:["anthropic","openai"];let a;for(const s of n){machine.logger.info(`[MODELS] Requesting models: source=${e.source}, protocol=${s}, url=${safeEndpointLabel(modelUrl(e.baseUrl))}, officialProtocol=${t??"none"}`);try{const t=await fetchModels(e,s);return machine.logger.info(`[MODELS] Models request succeeded: source=${e.source}, protocol=${s}, count=${t.length}`),t}catch(t){a=t;const n=summarizeError(t);machine.logger.warn(`[MODELS] Models request failed: source=${e.source}, protocol=${s}, status=${n.status??"-"}, code=${n.code??"-"}, message=${n.message}`)}}throw a instanceof Error?a:new Error("failed to fetch models")}function readJsonFile(e){if(!fs.existsSync(e))return null;try{return JSON.parse(fs.readFileSync(e,"utf-8"))}catch{return null}}function readCodexProvider(){const e=path.join(machine.machine.codexHomeDir,"config.toml");if(!fs.existsSync(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=fs.readFileSync(e,"utf-8"),n=t.match(/^model_provider\s*=\s*"([^"]+)"/m)?.[1]||"openai",a=t.match(/^model\s*=\s*"([^"]+)"/m)?.[1],s=t.match(new RegExp(`\\[model_providers\\.${n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}\\]([\\s\\S]*?)(?=\\n\\[|$)`)),i=s?.[1]||"",o=i.match(/^\s*base_url\s*=\s*"([^"]+)"/m)?.[1]||process.env.OPENAI_BASE_URL||"https://api.openai.com",r=i.match(/^\s*env_key\s*=\s*"([^"]+)"/m)?.[1]||("agentrix"===n?"AGENTRIX_API_KEY":"OPENAI_API_KEY");return{baseUrl:o,apiKey:process.env[r],source:"codex",defaultModel:a}}function resolveClaudeDefaultModel(e,t){const n=t.ANTHROPIC_MODEL||e?.model||process.env.ANTHROPIC_MODEL;if(!n)return;const a=n.toLowerCase();return"opus"===a?t.ANTHROPIC_DEFAULT_OPUS_MODEL||process.env.ANTHROPIC_DEFAULT_OPUS_MODEL||"claude-opus-4-6":"sonnet"===a?t.ANTHROPIC_DEFAULT_SONNET_MODEL||process.env.ANTHROPIC_DEFAULT_SONNET_MODEL||"claude-sonnet-4-6":"haiku"===a?t.ANTHROPIC_DEFAULT_HAIKU_MODEL||process.env.ANTHROPIC_DEFAULT_HAIKU_MODEL||"claude-haiku-4-5":n}function readClaudeProvider(){const e=readJsonFile(path.join(machine.machine.claudeConfigDir,"settings.json")),t=e?.env||{},n=t.ANTHROPIC_BASE_URL||process.env.ANTHROPIC_BASE_URL||"https://api.anthropic.com",a=t.ANTHROPIC_AUTH_TOKEN||t.ANTHROPIC_API_KEY||process.env.ANTHROPIC_AUTH_TOKEN||process.env.ANTHROPIC_API_KEY;return a?{baseUrl:n,apiKey:a,source:"claude",defaultModel:resolveClaudeDefaultModel(e,t)}:null}async function listAvailableModels(e){const t=[];if(!e||"claude"===e){const e=readClaudeProvider();e&&t.push(e)}if(!e||"codex"===e){const e=readCodexProvider();e&&t.push(e)}machine.logger.info(`[MODELS] Listing available models: agentType=${e??"all"}, endpointCount=${t.length}, endpoints=${t.map(e=>`${e.source}:${safeEndpointLabel(e.baseUrl)}:hasKey=${Boolean(e.apiKey)}:defaultModel=${e.defaultModel??"-"}`).join(",")||"-"}`);const n=new Set,a=[],s=t.find(e=>e.defaultModel)?.defaultModel;for(const e of t)try{for(const t of await fetchEndpointModels(e))n.add(t)}catch(t){const n=summarizeError(t);a.push({source:e.source,baseUrl:safeEndpointLabel(e.baseUrl),message:n.message,status:n.status,code:n.code})}const i=Array.from(n).sort();return 0===i.length?machine.logger.warn(`[MODELS] No models available: endpointCount=${t.length}, failures=${JSON.stringify(a)}`):machine.logger.info(`[MODELS] Listed available models: count=${i.length}`),{models:i,defaultModel:s}}function createImmediateFailureAck(e,t){return{eventId:shared.createEventId(),status:"failed",opCode:e,message:t}}function truncateValue(e,t=300){return e.length<=t?e:`${e.slice(0,t)}...`}function getGitlabProxyLogMethod(e){return("string"==typeof e.method&&e.method.trim().length>0?e.method.trim():"GET").toUpperCase()}function getGitlabProxyLogPath(e){return"string"==typeof e.path&&e.path.length>0?e.path:"-"}function getGitlabProxyErrorStatus(e){return"number"==typeof e.status?e.status:0}function logGitlabProxyRequest(e,t){machine.logger.info(`[GITLAB PROXY] reqId=${e.requestId}, gitServer=${e.gitServerId}, method=${t.method}, path=${t.path}, status=${t.status}, elapsedMs=${t.elapsedMs}`)}function createTaskHandler(e){return async(t,n)=>{if(machine.logger.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 machine.logger.error(`[EVENT HANDLER] create-task expects task-message, got ${t.event} for task ${t.taskId}`),void n(createImmediateFailureAck(t.eventId,`create-task expects task-message, got ${t.event}`));try{const a=await e.workerManager.startWorker(t,"create-task");"success"!==a.status&&machine.logger.error(`[EVENT HANDLER] create-task startup failed for task ${t.taskId}: ${a.message||"unknown error"}`),n(a)}catch(e){machine.logger.error(`[EVENT HANDLER] create-task startup threw for task ${t.taskId}:`,e),n(createImmediateFailureAck(t.eventId,e instanceof Error?e.message:"create-task startup failed"))}}}function resumeTaskHandler(e){return async(t,n)=>{machine.logger.debug(`[EVENT HANDLER] resume-task: ${t.taskId}, agentSessionId=${t.agentSessionId}`),"shadow"!==t.taskType&&e.onCompanionInteraction?.(t.chatId);try{const a=await e.workerManager.startWorker(t,"resume-task");"success"!==a.status&&machine.logger.error(`[EVENT HANDLER] resume-task startup failed for task ${t.taskId}: ${a.message||"unknown error"}`),n(a)}catch(e){machine.logger.error(`[EVENT HANDLER] resume-task startup threw for task ${t.taskId}:`,e),n(createImmediateFailureAck(t.eventId,e instanceof Error?e.message:"resume-task startup failed"))}}}function listModelsHandler(e){return async(t,n)=>{if(machine.logger.info(`[EVENT HANDLER] list-models received: machineId=${t.machineId}, agentType=${t.agentType??"all"}, eventId=${t.eventId}`),t.machineId!==e.machineId)return machine.logger.warn(`[EVENT HANDLER] list-models target mismatch: requested=${t.machineId}, current=${e.machineId}`),void n(createImmediateFailureAck(t.eventId,"list-models target machine mismatch"));try{const{models:e,defaultModel:a}=await listAvailableModels(t.agentType);if(0===e.length&&!a)return machine.logger.warn(`[EVENT HANDLER] list-models found no models and no default model: machineId=${t.machineId}, agentType=${t.agentType??"all"}`),void n(createImmediateFailureAck(t.eventId,"No models available from configured endpoints"));machine.logger.info(`[EVENT HANDLER] list-models success: machineId=${t.machineId}, count=${e.length}, defaultModel=${a??"-"}`),n({eventId:shared.createEventId(),status:"success",opCode:t.eventId,data:{models:e,defaultModel:a}})}catch(e){machine.logger.error(`[EVENT HANDLER] list-models failed: machineId=${t.machineId}, agentType=${t.agentType??"all"}:`,e),n(createImmediateFailureAck(t.eventId,e instanceof Error?e.message:"Failed to list models"))}}}function shutdownMachineHandler(e){return async t=>{machine.logger.info("[EVENT HANDLER] shutdown-machine received",t),e.requestShutdown("agentrix-app",t.reason)}}function deployAgentHandler(e){return async(t,n)=>{machine.logger.info(`[EVENT HANDLER] deploy-agent received: taskId=${t.taskId}, draftAgentId=${t.draftAgentId}, targetAgentId=${t.targetAgentId}, sourcePath=${t.sourcePath}`);try{const a=await e.workerManager.startDeploymentWorker(t);"success"!==a.status&&machine.logger.error(`[EVENT HANDLER] deploy-agent startup failed for task ${t.taskId}: ${a.message||"unknown error"}`),n(a)}catch(e){machine.logger.error(`[EVENT HANDLER] deploy-agent startup threw for task ${t.taskId}:`,e),n(createImmediateFailureAck(t.eventId,e instanceof Error?e.message:"deploy-agent startup failed"))}}}function hivePublishHandler(e){return async(t,n)=>{machine.logger.info(`[EVENT HANDLER] hive-publish received: taskId=${t.taskId}, name=${t.name}, repoDir=${t.repoDir}`);try{const a=await e.workerManager.startHivePublishWorker(t);"success"!==a.status&&machine.logger.error(`[EVENT HANDLER] hive-publish startup failed for task ${t.taskId}: ${a.message||"unknown error"}`),n(a)}catch(e){machine.logger.error(`[EVENT HANDLER] hive-publish startup threw for task ${t.taskId}:`,e),n(createImmediateFailureAck(t.eventId,e instanceof Error?e.message:"hive-publish startup failed"))}}}function hiveInstallHandler(e){return async(t,n)=>{machine.logger.info(`[EVENT HANDLER] hive-install received: taskId=${t.taskId}, name=${t.name}, hiveListingId=${t.hiveListingId}`);try{const a=await e.workerManager.startHiveInstallWorker(t);"success"!==a.status&&machine.logger.error(`[EVENT HANDLER] hive-install startup failed for task ${t.taskId}: ${a.message||"unknown error"}`),n(a)}catch(e){machine.logger.error(`[EVENT HANDLER] hive-install startup threw for task ${t.taskId}:`,e),n(createImmediateFailureAck(t.eventId,e instanceof Error?e.message:"hive-install startup failed"))}}}function stopTaskHandler(e){return async t=>{machine.logger.info(`[EVENT HANDLER] stop-task: ${t.taskId}, reason=${t.reason||"n/a"}`),e.workerManager.stopSession(t.taskId)||machine.logger.warn(`[EVENT HANDLER] stop-task failed, task not found: ${t.taskId}`)}}function daemonGitlabRequestHandler(e){return async t=>{const n=Date.now(),a=getGitlabProxyLogMethod(t.payload),s=getGitlabProxyLogPath(t.payload),i=n=>{const a={eventId:t.requestId,requestId:t.requestId,machineId:e.machineId,...n};e.client?e.client.send("daemon-gitlab-response",a):machine.logger.error(`[GITLAB PROXY] response dropped: reqId=${t.requestId}, op=${t.operation}, reason=socket-client-unavailable`)};try{const e=t.accessToken?.trim();if(!e){const e=Date.now()-n;return machine.logger.warn(`[GITLAB PROXY] access token missing: reqId=${t.requestId}, op=${t.operation}, gitServer=${t.gitServerId}`),logGitlabProxyRequest(t,{method:a,path:s,status:0,elapsedMs:e}),void i({success:!1,errorCode:"PAT_MISSING",errorMessage:`No access token provided for git server ${t.gitServerId}`,executionTimeMs:e})}const o=t.payload.apiUrl;if(!o){const e=Date.now()-n;return machine.logger.warn(`[GITLAB PROXY] apiUrl missing in payload: reqId=${t.requestId}, op=${t.operation}, gitServer=${t.gitServerId}`),logGitlabProxyRequest(t,{method:a,path:s,status:0,elapsedMs:e}),void i({success:!1,errorCode:"PAT_MISSING",errorMessage:"GitLab API URL not provided in request",executionTimeMs:e})}const r=new GitLabExecutor(o,e,{requestId:t.requestId,gitServerId:t.gitServerId}),c=await r.executeOperationWithMetadata(t.operation,t.payload,{silent:!0}),l=Date.now()-n;logGitlabProxyRequest(t,{method:a,path:s,status:c.metadata.status??200,elapsedMs:l}),i({success:!0,data:c.data,executionTimeMs:l})}catch(e){const o=e;let r="GITLAB_CONNECTIVITY_FAILED";401===o.status?r="PAT_INVALID":403===o.status?r="PAT_SCOPE_INSUFFICIENT":404===o.status&&(r="RESOURCE_NOT_FOUND");const c="string"==typeof o.message?o.message:"Unknown error",l="string"==typeof o.detail?truncateValue(o.detail):void 0,d=getGitlabProxyErrorStatus(o),p=Date.now()-n;logGitlabProxyRequest(t,{method:a,path:s,status:d,elapsedMs:p}),machine.logger.error(`[GITLAB PROXY] execution failed: reqId=${t.requestId}, op=${t.operation}, errorCode=${r}, status=${d}, message=${c}${l?`, detail=${l}`:""}`),i({success:!1,errorCode:r,errorMessage:c,executionTimeMs:p})}}}function machineControlCommandHandler(e){return async(t,n)=>{e.machineControl?e.machineControl.handleCommand(t,n):n(createImmediateFailureAck(t.eventId,"Machine control is not available"))}}function workspaceCacheUpdateHandler(e){return async(t,n)=>{if(e.workspaceStatusSync)try{await e.workspaceStatusSync.applyCacheUpdate(t),n({eventId:shared.createEventId(),status:"success",opCode:t.eventId})}catch(e){machine.logger.warn("[WORKSPACE SYNC] Failed to apply workspace cache update",e),n(createImmediateFailureAck(t.eventId,e instanceof Error?e.message:"Failed to apply workspace cache update"))}else n(createImmediateFailureAck(t.eventId,"Workspace sync is not available"))}}function createEventHandlers(e){return{"create-task":createTaskHandler(e),"resume-task":resumeTaskHandler(e),"list-models":listModelsHandler(e),"stop-task":stopTaskHandler(e),"deploy-agent":deployAgentHandler(e),"hive-publish":hivePublishHandler(e),"hive-install":hiveInstallHandler(e),"shutdown-machine":shutdownMachineHandler(e),"workspace-file-request":workspaceFileRequestHandler({client:e.client}),"workspace-file-mutation-request":workspaceFileMutationRequestHandler({client:e.client}),"vision-plan-review-write":visionPlanReviewWriteHandler(),"daemon-gitlab-request":daemonGitlabRequestHandler(e),"machine-control-command":machineControlCommandHandler(e),"workspace-cache-update":workspaceCacheUpdateHandler(e)}}const CHUNK_SIZE=65536,DEFAULT_MAX_FILE_SIZE_MB=parseInt(process.env.MAX_WORKSPACE_FILE_SIZE_MB||"100",10);function getPeerConnectionConstructor(e){return e.RTCPeerConnection||e.PeerConnection||e.RTCConnection||e.PeerConnection}function normalizeIceServers(e){const t=[];return e.forEach(e=>{Array.isArray(e.urls)?t.push(...e.urls):t.push(e.urls)}),t}function sendChannelMessage(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)}function normalizeSignalDescription(e,t){return e&&"object"==typeof e&&"string"==typeof e.sdp?{sdp:e.sdp,type:e.type||t}:{sdp:String(e||""),type:t}}function normalizeCandidate(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}function resolveFilePath(e,t,n){if(n.startsWith("channel-attachment/")){const e=n.slice(19);return resolveChannelFilePath(decodeURIComponent(e))}return machine.machine.resolveWorkspaceFilePath(e,t,n)}function isWithinWorkspaceBase(e,t,n,a){const s=n.replace(/^\/+/,""),i="project"===s||s.startsWith("project/")?"project":"data"===s||s.startsWith("data/")?"data":"",o=path__namespace.normalize(machine.machine.resolveWorkspaceFilePath(e,t,i)),r=path__namespace.normalize(a);return r===o||r.startsWith(o+path__namespace.sep)}function isFileModified(e,t){return!t||e.mtime.toISOString()!==t}class MachineRtcManager{client;machineId;iceServers=[];sessions=new Map;rtcModule={};peerConstructor;constructor(e,t){this.client=e,this.machineId=t;const n=node_module.createRequire("undefined"==typeof document?require("url").pathToFileURL(__filename).href:_documentCurrentScript&&"SCRIPT"===_documentCurrentScript.tagName.toUpperCase()&&_documentCurrentScript.src||new URL("index.cjs",document.baseURI).href);try{this.rtcModule=n("node-datachannel"),this.peerConstructor=getPeerConnectionConstructor(this.rtcModule),this.rtcModule.setDebugLevel?.("warning")}catch(e){const t=e instanceof Error?e.message:String(e);machine.logger.warn(`[RTC] node-datachannel unavailable; RTC support disabled: ${t}`)}}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))):machine.logger.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:shared.createEventId()})}handleIceServersResponse(e){this.iceServers=normalizeIceServers(e.iceServers),machine.logger.info(`[RTC] Loaded ${this.iceServers.length} ICE servers`)}handleRtcRequest(e){if(!this.peerConstructor)return;const t=e.userId;if(!t)return void machine.logger.warn("[RTC] machine-rtc-request missing userId");const n=e.workspaceUserId||t,a=e.taskId;if(this.sessions.has(e.sessionId))return void this.sendMachineRtcResponse(e.sessionId,t,!0);const s=new this.peerConstructor(e.sessionId,{iceServers:this.iceServers}),i={sessionId:e.sessionId,userId:t,workspaceUserId:n,allowedTaskId:a||void 0,peerConnection:s,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,a){this.client.send("machine-rtc-response",{eventId:shared.createEventId(),machineId:this.machineId,sessionId:e,accepted:n,reason:a,userId:t,capabilities:{dataChannel:!0}})}handleRtcSignal(e){if(!this.peerConstructor)return;if("app"!==e.from)return;const t=e.userId;if(!t)return void machine.logger.warn("[RTC] rtc-signal missing userId");const n=e.workspaceUserId||t,a=e.taskId;let s=this.sessions.get(e.sessionId);if(!s){const i=new this.peerConstructor(e.sessionId,{iceServers:this.iceServers});s={sessionId:e.sessionId,userId:t,workspaceUserId:n,allowedTaskId:a||void 0,peerConnection:i,lastActivity:Date.now(),remoteDescriptionSet:!1,pendingCandidates:[]},this.sessions.set(e.sessionId,s),this.registerPeerHandlers(s)}try{this.applyRemoteSignal(s,e.signal)}catch(e){machine.logger.warn("[RTC] Failed to apply remote signal",e)}}registerPeerHandlers(e){const{peerConnection:t}=e;t.onStateChange?.(t=>{machine.logger.info(`[RTC] Peer state (${e.sessionId}): ${t}`)}),t.onGatheringStateChange?.(t=>{machine.logger.info(`[RTC] ICE gathering (${e.sessionId}): ${t}`)}),t.onLocalDescription?.((t,n)=>{const a=normalizeSignalDescription(t,n);this.client.send("rtc-signal",{eventId:shared.createEventId(),machineId:this.machineId,sessionId:e.sessionId,from:"machine",signal:a,userId:e.userId})}),t.onLocalCandidate?.((t,n,a)=>{const s=normalizeCandidate(t,n,a);s&&this.client.send("rtc-signal",{eventId:shared.createEventId(),machineId:this.machineId,sessionId:e.sessionId,from:"machine",signal:{candidate:s},userId:e.userId})}),t.onDataChannel?.(t=>{e.dataChannel=t,this.registerDataChannel(e,t)})}registerDataChannel(e,t){t.onOpen?.(()=>{machine.logger.info(`[RTC] Data channel open (${e.sessionId})`),e.lastActivity=Date.now(),sendChannelMessage(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?.(()=>{machine.logger.warn(`[RTC] Data channel closed (${e.sessionId})`),e.peerConnection.close?.(),this.sessions.delete(e.sessionId)}),t.onError?.(t=>{machine.logger.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{shared.splitRtcChunkFrame(new Uint8Array(t))}catch(e){machine.logger.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 a=null;try{a=JSON.parse(n)}catch(e){return void machine.logger.warn("[RTC] Non-JSON message",n)}a&&"string"==typeof a.type&&("file.request"!==a.type?"file.mutate"===a.type&&this.handleFileMutation(e,a).catch(e=>{machine.logger.error("[RTC] Failed to handle file mutation",e)}):this.handleFileRequest(e,a).catch(e=>{machine.logger.error("[RTC] Failed to handle file request",e)}))}validateFilePayload(e,t){const n=t.payload;return n?n.userId!==e.workspaceUserId?(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"}}),null):e.allowedTaskId&&n.taskId!==e.allowedTaskId?(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"}}),null):n:null}assertWorkspacePath(e,t,n){if(n.startsWith("channel-attachment/"))throw Object.assign(new Error("Channel attachments are read-only"),{code:"permission_denied"});const a=resolveFilePath(e,t,n);if(!isWithinWorkspaceBase(e,t,n,a))throw Object.assign(new Error("Path escapes workspace"),{code:"permission_denied"});return a}async handleFileRequest(e,t){const n=this.validateFilePayload(e,t);if(!n)return;const a=resolveFilePath(n.userId,n.taskId,n.relativePath);if(!fs__namespace.existsSync(a))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 s=await fs__namespace.promises.stat(a);if(!isFileModified(s,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(s.isDirectory()||"directory"===n.entryType){const n=await fs__namespace.promises.readdir(a,{withFileTypes:!0}),i={entries:await Promise.all(n.map(async e=>{const t=path__namespace.join(a,e.name),n=await fs__namespace.promises.stat(t);return{name:e.name,type:e.isDirectory()?"directory":"file",size:n.size,modifiedAt:n.mtime.toISOString()}})),modifiedAt:s.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:i})}const i=1024*(n.maxFileSizeMB??DEFAULT_MAX_FILE_SIZE_MB)*1024;if(s.size>i)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 o=mimeTypesExports.lookup(a)||"application/octet-stream",r={size:s.size,mimeType:"string"==typeof o?o:"application/octet-stream",modifiedAt:s.mtime.toISOString()};this.sendControl(e,{v:1,type:"file.meta",channel:"file",requestId:t.requestId,streamId:t.streamId,timestamp:(new Date).toISOString(),payload:r}),await this.sendFileChunks(e,t.streamId,a),this.sendControl(e,{v:1,type:"file.end",channel:"file",requestId:t.requestId,streamId:t.streamId,timestamp:(new Date).toISOString(),payload:{size:s.size}})}async handleFileMutation(e,t){const n=this.validateFilePayload(e,t);if(n)try{const a=this.assertWorkspacePath(n.userId,n.taskId,n.relativePath);if("delete"===n.operation)return await fs__namespace.promises.rm(a,{force:!1}),void this.sendMutationAck(e,t,{relativePath:n.relativePath,operation:n.operation});if(void 0===n.content)throw Object.assign(new Error("File content is required"),{code:"bad_request"});await fs__namespace.promises.mkdir(path__namespace.dirname(a),{recursive:!0});try{await fs__namespace.promises.writeFile(a,n.content,n.createOnly?{flag:"wx"}:void 0)}catch(e){if("EEXIST"===e.code)throw Object.assign(new Error("File already exists"),{code:"file_exists"});throw e}const s=await fs__namespace.promises.stat(a);this.sendMutationAck(e,t,{relativePath:n.relativePath,operation:n.operation,modifiedAt:s.mtime.toISOString()})}catch(n){this.sendControl(e,{v:1,type:"file.error",channel:"file",requestId:t.requestId,streamId:t.streamId,timestamp:(new Date).toISOString(),error:{code:n.code||"unknown_error",message:n.message||"File mutation failed"}})}}sendMutationAck(e,t,n){this.sendControl(e,{v:1,type:"file.mutation_ack",channel:"file",requestId:t.requestId,streamId:t.streamId,timestamp:(new Date).toISOString(),payload:n})}async sendFileChunks(e,t,n){const a=e.dataChannel;if(!a)return;const s=fs__namespace.createReadStream(n,{highWaterMark:65536});let i=0;await new Promise((e,n)=>{s.on("data",e=>{const n=shared.RtcChunkFlags.Binary|(0===i?shared.RtcChunkFlags.Start:0),s=Buffer.isBuffer(e)?e:Buffer.from(e),o=new Uint8Array(s.buffer,s.byteOffset,s.byteLength),r=shared.buildRtcChunkFrame({streamId:t,seq:i,flags:n,payloadLength:o.length},o);sendChannelMessage(a,r),i+=1}),s.on("end",()=>{if(i>0){const e=shared.buildRtcChunkFrame({streamId:t,seq:i,flags:shared.RtcChunkFlags.End|shared.RtcChunkFlags.Binary,payloadLength:0},new Uint8Array);sendChannelMessage(a,e)}e()}),s.on("error",e=>n(e))})}sendControl(e,t){const n=e.dataChannel;n&&sendChannelMessage(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){machine.logger.warn("[RTC] Failed to add queued candidate",e)}}),void(e.pendingCandidates=[]);if(t&&t.candidate){const a=t.candidate,s="string"==typeof a?a:a&&"string"==typeof a.candidate?a.candidate:null,i=t.sdpMid||a?.sdpMid||a?.mid||"0";if(s){if(!e.remoteDescriptionSet)return void e.pendingCandidates?.push({candidate:s,mid:i});n.addRemoteCandidate?.(s,i)}}}}class MachineClient{client;context;rtcManager;constructor(e,t,n){const{machineId:a,...s}=e;this.client=new SocketClient(s),this.context={machineId:a,workerManager:t,requestShutdown:n.requestShutdown,client:this.client,machineControl:n.machineControl,workspaceStatusSync:n.workspaceStatusSync},this.rtcManager=new MachineRtcManager(this.client,a),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=createEventHandlers(this.context);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.onEventWithAck("machine-control-command",e["machine-control-command"]),this.client.onEventWithAck("workspace-cache-update",e["workspace-cache-update"]),this.client.onEvent("shutdown-machine",e["shutdown-machine"]),this.client.onEvent("workspace-file-request",e["workspace-file-request"]),this.client.onEvent("workspace-file-mutation-request",e["workspace-file-mutation-request"]),this.client.onEventWithAck("vision-plan-review-write",e["vision-plan-review-write"]),this.client.onEvent("daemon-gitlab-request",e["daemon-gitlab-request"])}}let caffeinateProcess=null;function startCaffeinate(){if(machine.machine.disableCaffeinate)return machine.logger.debug("[caffeinate] Caffeinate disabled via AGENTRIX_DISABLE_CAFFEINATE environment variable"),!1;if("darwin"!==process.platform)return machine.logger.debug("[caffeinate] Not on macOS, skipping caffeinate"),!1;if(caffeinateProcess&&!caffeinateProcess.killed)return machine.logger.debug("[caffeinate] Caffeinate already running"),!0;try{return caffeinateProcess=child_process.spawn("caffeinate",["-im"],{stdio:"ignore",detached:!1}),caffeinateProcess.on("error",e=>{machine.logger.debug("[caffeinate] Error starting caffeinate:",e),caffeinateProcess=null}),caffeinateProcess.on("exit",(e,t)=>{machine.logger.debug(`[caffeinate] Process exited with code ${e}, signal ${t}`),caffeinateProcess=null}),machine.logger.info(`[caffeinate] Started with PID ${caffeinateProcess.pid}`),setupCleanupHandlers(),!0}catch(e){return machine.logger.info("[caffeinate] Failed to start caffeinate:",e),!1}}let isStopping=!1;async function stopCaffeinate(){if(isStopping)machine.logger.info("[caffeinate] Already stopping, skipping");else if(caffeinateProcess&&!caffeinateProcess.killed){isStopping=!0,machine.logger.info(`[caffeinate] Stopping caffeinate process PID ${caffeinateProcess.pid}`);try{caffeinateProcess.kill("SIGTERM"),await new Promise(e=>setTimeout(e,1e3)),caffeinateProcess&&!caffeinateProcess.killed&&caffeinateProcess.kill("SIGKILL"),caffeinateProcess=null,isStopping=!1}catch(e){machine.logger.info("[caffeinate] Error stopping caffeinate:",e),isStopping=!1}}}let cleanupHandlersSet=!1;function setupCleanupHandlers(){if(cleanupHandlersSet)return;cleanupHandlersSet=!0;const e=()=>{stopCaffeinate()};process.on("exit",e),process.on("SIGINT",e),process.on("SIGTERM",e),process.on("SIGUSR1",e),process.on("SIGUSR2",e),process.on("uncaughtException",t=>{machine.logger.debug("[caffeinate] Uncaught exception, cleaning up:",t),e()}),process.on("unhandledRejection",(t,n)=>{machine.logger.debug("[caffeinate] Unhandled rejection, cleaning up:",t),e()})}function parseAgentrixProcess(e){const{pid:t,name:n,cmd:a}=e;if(t===process.pid||t===process.ppid)return null;if(!(n.includes("agentrix")||"node"===n&&(a.includes("agentrix-cli")||a.includes("dist/index.mjs")||a.includes("dist\\index.mjs"))||("MainThread"===n||n.includes("MainThread"))&&(a.includes("agentrix-cli")||a.includes("dist/index.mjs")||a.includes("agentrix.mjs"))||a.includes("agentrix.mjs")||a.includes("agentrix-cli")||a.includes("tsx")&&a.includes("src/index.ts")&&a.includes("agentrix-cli")))return null;let s="unknown";const i=a.toLowerCase();return i.includes(" worker")?s="worker":i.includes(" daemon")?s="daemon":i.includes("doctor")&&(s="doctor"),{pid:t,command:a||n,type:s}}async function getWindowsProcessList(){try{const e=child_process.execSync("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 a=n[e];if(!a)continue;const s=a.indexOf(",");if(-1===s)continue;const i=a.substring(s+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[]}}async function findAllAgentrixProcesses(){try{let e;e="win32"===process.platform?await getWindowsProcessList():(await psList()).map(e=>({pid:e.pid,name:e.name||"",cmd:e.cmd||""}));const t=[];for(const n of e){const e=parseAgentrixProcess(n);e&&t.push(e)}return t}catch(e){return[]}}async function findRunawayAgentrixProcesses(){return(await findAllAgentrixProcesses()).filter(e=>e.pid!==process.pid&&("daemon"===e.type||"worker"===e.type)).map(e=>({pid:e.pid,command:e.command}))}async function killRunawayAgentrixProcesses(){const e=await findRunawayAgentrixProcesses(),t=[];let n=0;for(const{pid:a,command:s}of e)try{if(console.log(`Killing runaway process PID ${a}: ${s}`),"win32"===process.platform){const e=spawn.sync("taskkill",["/F","/PID",a.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(a,"SIGTERM"),await new Promise(e=>setTimeout(e,1e3));(await psList()).find(e=>e.pid===a)&&(console.log(`Process PID ${a} ignored SIGTERM, using SIGKILL`),process.kill(a,"SIGKILL"))}console.log(`Successfully killed runaway process PID ${a}`),n++}catch(e){const n=e.message;t.push({pid:a,error:n}),console.log(`Failed to kill process PID ${a}: ${n}`)}return{killed:n,errors:t}}function isCommandAvailable$1(e){try{const t="win32"===process.platform?"where":"which";return{available:!0,path:child_process.execSync(`${t} ${e}`,{encoding:"utf-8",stdio:["pipe","pipe","ignore"]}).trim()}}catch{return{available:!1}}}function getSandboxDependencies(e){if("macos"===e){const e=isCommandAvailable$1("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=isCommandAvailable$1("bwrap"),t=isCommandAvailable$1("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[]}function getCliDependencies(){const e=isCommandAvailable$1("git"),t=isCommandAvailable$1("claude"),n=isCommandAvailable$1("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}]}function checkAllDependencies(){const e=platform_js.getPlatform(),t=getCliDependencies(),n=getSandboxDependencies(e),a=t.filter(e=>e.required&&!e.installed),s=n.filter(e=>e.required&&!e.installed);return{cli:t,sandbox:n,allSatisfied:0===a.length&&0===s.length,missingSandbox:s,missingCli:a}}function displayDependencyStatus(e=!1){const t=checkAllDependencies(),n=platform_js.getPlatform();console.log(chalk.bold("\n🔧 CLI Dependencies"));for(const n of t.cli)if(n.installed)console.log(chalk.green(`✓ ${n.name}`),chalk.gray(`- ${n.description}`)),e&&n.path&&console.log(chalk.gray(` Location: ${n.path}`));else{const e=n.required?chalk.red("❌"):chalk.yellow("⚠️");console.log(`${e} ${n.name}`,chalk.gray(`- ${n.description}`)),n.installCommand&&console.log(chalk.blue(` Install: ${n.installCommand}`))}if(t.sandbox.length>0){console.log(chalk.bold("\n🔒 Sandbox Dependencies")),console.log(chalk.gray(`Platform: ${n}`));for(const n of t.sandbox)n.installed?(console.log(chalk.green(`✓ ${n.name}`),chalk.gray(`- ${n.description}`)),e&&n.path&&console.log(chalk.gray(` Location: ${n.path}`))):(console.log(chalk.red(`❌ ${n.name}`),chalk.gray(`- ${n.description}`)),n.installCommand&&console.log(chalk.blue(` Install: ${n.installCommand}`)))}else console.log(chalk.bold("\n🔒 Sandbox Dependencies")),console.log(chalk.yellow(`⚠️ Platform ${n} not supported - sandbox will be disabled`));if(t.allSatisfied)return console.log(chalk.bold.green("\n✓ All required dependencies are installed")),!0;{console.log(chalk.bold.red("\n⚠️ Missing Required Dependencies"));const e=[...t.missingCli,...t.missingSandbox];for(const t of e)console.log(chalk.red(` • ${t.name}`));return console.log(chalk.yellow("\nPlease install missing dependencies before starting the daemon.")),!1}}function checkCriticalDependencies(){const e=checkAllDependencies(),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 getEnvironmentInfo(){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:machine.machine.agentrixHomeDir,serverUrl:machine.machine.serverUrl,logsDir:machine.machine.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 runDoctorCommand(e){if(e||(e="all"),console.log(chalk.bold.cyan("\n🩺 Agentrix CLI Doctor\n")),"all"===e){console.log(chalk.bold("📋 Basic Information")),console.log(`Agentrix CLI Version: ${chalk.green(machine.packageJson.version)}`),console.log(`Platform: ${chalk.green(process.platform)} ${process.arch}`),console.log(`Node.js Version: ${chalk.green(process.version)}`),console.log(""),console.log(chalk.bold("🔧 Daemon Spawn Diagnostics"));const e=machine.projectPath(),t=path.join(e,"bin","agentrix.mjs"),n=path.join(e,"dist","index.mjs");console.log(`Project Root: ${chalk.blue(e)}`),console.log(`Wrapper Script: ${chalk.blue(t)}`),console.log(`CLI Entrypoint: ${chalk.blue(n)}`),console.log(`Wrapper Exists: ${fs.existsSync(t)?chalk.green("✓ Yes"):chalk.red("❌ No")}`),console.log(`CLI Exists: ${fs.existsSync(n)?chalk.green("✓ Yes"):chalk.red("❌ No")}`),console.log(""),console.log(chalk.bold("⚙️ Configuration")),console.log(`Agentrix Home: ${chalk.blue(machine.machine.agentrixHomeDir)}`),console.log(`Server URL: ${chalk.blue(machine.machine.serverUrl)}`),console.log(`Logs Dir: ${chalk.blue(machine.machine.getStatePaths().logsDir)}`),console.log(chalk.bold("\n🌍 Environment Variables"));const a=getEnvironmentInfo();console.log(`AGENTRIX_HOME_DIR: ${a.AGENTRIX_HOME_DIR?chalk.green(a.AGENTRIX_HOME_DIR):chalk.gray("not set")}`),console.log(`AGENTRIX_SERVER_URL: ${a.AGENTRIX_SERVER_URL?chalk.green(a.AGENTRIX_SERVER_URL):chalk.gray("not set")}`),console.log(`DANGEROUSLY_LOG_TO_SERVER: ${a.DANGEROUSLY_LOG_TO_SERVER_FOR_AI_AUTO_DEBUGGING?chalk.yellow("ENABLED"):chalk.gray("not set")}`),console.log(`DEBUG: ${a.DEBUG?chalk.green(a.DEBUG):chalk.gray("not set")}`),console.log(`NODE_ENV: ${a.NODE_ENV?chalk.green(a.NODE_ENV):chalk.gray("not set")}`),console.log(chalk.bold("\n🔐 Authentication"));try{await machine.machine.readCredentials()?console.log(chalk.green("✓ Authenticated (credentials found)")):console.log(chalk.yellow("⚠️ Not authenticated (no credentials)"))}catch(e){console.log(chalk.red("❌ Error reading credentials"))}displayDependencyStatus(!0)}console.log(chalk.bold("\n🤖 Daemon Status"));try{const t=await checkIfDaemonRunningAndCleanupStaleState(),n=await machine.machine.readDaemonState();if(t&&n?(console.log(chalk.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(chalk.yellow("⚠️ Daemon state exists but process not running (stale)")):console.log(chalk.red("❌ Daemon is not running")),n){console.log(chalk.bold("\n📄 Daemon State:"));const e=machine.machine.getStatePaths();console.log(chalk.blue(`Location: ${e.daemonStateFile}`)),console.log(chalk.gray(JSON.stringify(n,null,2)))}const a=await findAllAgentrixProcesses();if(a.length>0){console.log(chalk.bold("\n🔍 All Agentrix CLI Processes"));const e=a.reduce((e,t)=>(e[t.type]||(e[t.type]=[]),e[t.type].push(t),e),{});Object.entries(e).forEach(([e,t])=>{console.log(chalk.blue(`\n${{daemon:"🤖 Daemon",worker:"🔗 Workers",doctor:"🩺 Doctor",unknown:"❓ Unknown"}[e]||e}:`)),t.forEach(({pid:t,command:n})=>{const a=e.startsWith("dev")?chalk.cyan:e.includes("daemon")?chalk.blue:chalk.gray;console.log(` ${a(`PID ${t}`)}: ${chalk.gray(n)}`)})})}else console.log(chalk.red("❌ No agentrix processes found"));"all"===e&&a.length>1&&(console.log(chalk.bold("\n💡 Process Management")),console.log(chalk.gray("To clean up runaway processes: agentrix killall")))}catch(e){console.log(chalk.red("❌ Error checking daemon status"))}}const CACHE_TTL_MS=6048e5;let cachedOpeners=null;async function listOpeners(){const e=getOpenerOverrides(),t=getOpenerOverridesSignature(e);if(cachedOpeners&&cachedOpeners.expiresAt>Date.now()&&cachedOpeners.overridesSignature===t)return cachedOpeners.openers;const n=getOpenerDefinitions(e),a=[];for(const e of n){const t=e.isSupported();t&&a.push({id:e.id,label:e.label,kind:e.kind,method:e.method,urlTemplate:e.urlTemplate,supported:t})}return cachedOpeners={expiresAt:Date.now()+6048e5,openers:a,overridesSignature:t},a}async function openWithOpener({openerId:e,targetPath:t,userId:n,taskId:a}){const s=getOpenerDefinitions(getOpenerOverrides()).find(t=>t.id===e);if(!s)return{success:!1,error:"Unknown openerId"};if("cli"!==s.method||!s.open)return{success:!1,error:"Opener is not executable by CLI"};if(!s.isSupported())return{success:!1,error:"Opener is not supported on this system"};let i;try{i=resolveTargetPath(t,n,a)}catch(e){return{success:!1,error:e instanceof Error?e.message:"Invalid path"}}try{return s.open(i),{success:!0}}catch(e){const t=e instanceof Error?e.message:"Failed to open path";return machine.logger.warn(`[OPENERS] Failed to open path: ${t}`),{success:!1,error:t}}}function pickDirectory(e){const t=process.platform;if("darwin"===t)return pickDirectoryMac(e);if("win32"===t)return pickDirectoryWindows(e);if("linux"===t)return pickDirectoryLinux(e);throw new Error("Directory picker is not supported on this platform")}function resolveTargetPath(e,t,n){const a=path.resolve(e);if(!path.isAbsolute(a))throw new Error("Path must be absolute");if(!fs.statSync(a).isDirectory())throw new Error("Path must be a directory");if(t&&n){const e=machine.machine.getTaskCwd(t,n);if(e&&!isSubPath(a,path.resolve(e)))throw new Error("Path is outside the task workspace")}return a}function isSubPath(e,t){const n=path.relative(t,e);return""===n||!n.startsWith("..")&&!path.isAbsolute(n)}function getOpenerDefinitions(e){const t=process.platform,n=["Visual Studio Code","Visual Studio Code - Insiders"],a=["Cursor"],s=["IntelliJ IDEA","IntelliJ IDEA CE","IntelliJ IDEA Ultimate"],i=["WebStorm"],o=["PyCharm","PyCharm CE","PyCharm Professional"];return applyOpenerOverrides([{id:"vscode",label:"VS Code",kind:"editor",method:"scheme",urlTemplate:"vscode://file/{path}?windowId=_blank",scheme:"vscode",macAppNames:n,isSupported:()=>isSchemeRegistered("vscode",t,n)},{id:"cursor",label:"Cursor",kind:"editor",method:"scheme",urlTemplate:"cursor://file/{path}?windowId=_blank",scheme:"cursor",macAppNames:a,isSupported:()=>isSchemeRegistered("cursor",t,a)},{id:"idea",label:"IntelliJ IDEA",kind:"ide",method:"scheme",urlTemplate:"idea://open?file={path}&newWindow=true",scheme:"idea",macAppNames:s,isSupported:()=>isSchemeRegistered("idea",t,s)},{id:"pycharm",label:"PyCharm",kind:"ide",method:"scheme",urlTemplate:"pycharm://open?file={path}&newWindow=true",scheme:"pycharm",macAppNames:o,isSupported:()=>isSchemeRegistered("pycharm",t,o)},{id:"webstorm",label:"WebStorm",kind:"ide",method:"scheme",urlTemplate:"webstorm://open?file={path}&newWindow=true",scheme:"webstorm",macAppNames:i,isSupported:()=>isSchemeRegistered("webstorm",t,i)},{id:"terminal",label:"Terminal",kind:"terminal",method:"cli",isSupported:()=>isTerminalSupported(t),open:e=>openInTerminal(e,t)},{id:"file-manager",label:"darwin"===t?"Finder":"win32"===t?"Explorer":"Files",kind:"file-manager",method:"cli",isSupported:()=>isFileManagerSupported(t),open:e=>openInFileManager(e,t)},{id:"open-with",label:"Open With...",kind:"system",method:"cli",isSupported:()=>isOpenWithSupported(t),open:e=>openWithChooser(e,t)}],t,e)}function pickDirectoryMac(e){const t=resolvePickerDefaultPath(e),n=[];if(t){const e=escapeAppleScriptString(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"),normalizePickerOutput(runCommand$1("osascript",n,{captureOutput:!0}))}function pickDirectoryWindows(e){const t=commandExists$1("powershell")?"powershell":commandExists$1("pwsh")?"pwsh":null;if(!t)throw new Error("PowerShell is required to pick a directory");const n=resolvePickerDefaultPath(e),a=["Add-Type -AssemblyName System.Windows.Forms;","$dialog = New-Object System.Windows.Forms.FolderBrowserDialog;",n?`$dialog.SelectedPath = '${escapePowerShellString(n)}';`:"","$null = $dialog.ShowDialog();","$dialog.SelectedPath;"].filter(Boolean).join(" ");return normalizePickerOutput(runCommand$1(t,"powershell"===t?["-NoProfile","-STA","-Command",a]:["-NoProfile","-Sta","-Command",a],{captureOutput:!0}))}function pickDirectoryLinux(e){const t=resolvePickerDefaultPath(e);if(commandExists$1("zenity")){const e=["--file-selection","--directory","--title=Select Folder"];if(t){const n=t.endsWith("/")?t:`${t}/`;e.push(`--filename=${n}`)}return normalizePickerOutput(runCommand$1("zenity",e,{captureOutput:!0}))}if(commandExists$1("kdialog")){const e=["--getexistingdirectory"];return t&&e.push(t),normalizePickerOutput(runCommand$1("kdialog",e,{captureOutput:!0}))}throw new Error("No supported directory picker is available")}function resolvePickerDefaultPath(e){if(!e)return;const t=e.replace(/^~(?=$|[\\/])/,os.homedir());if(fs.existsSync(t)){try{if(!fs.statSync(t).isDirectory())return}catch{return}return t}}function normalizePickerOutput(e){if(!e)return null;return e.trim()||null}function isOpenWithSupported(e){return"darwin"===e?commandExists$1("osascript"):"win32"===e?commandExists$1("powershell")||commandExists$1("pwsh"):"linux"===e&&commandExists$1("gio")}function isFileManagerSupported(e){return"darwin"===e?commandExists$1("open"):"win32"===e||"linux"===e&&(commandExists$1("xdg-open")||commandExists$1("gio"))}function isTerminalSupported(e){return"darwin"===e?commandExists$1("osascript")&&isMacAppInstalled("Terminal"):"win32"===e?commandExists$1("wt")||commandExists$1("powershell")||commandExists$1("pwsh")||commandExists$1("cmd"):"linux"===e&&Boolean(getLinuxTerminalCommand())}function openInTerminal(e,t){if("darwin"!==t){if("win32"===t){if(commandExists$1("wt"))return void launchDetached("wt",["-d",e]);const t=commandExists$1("powershell")?"powershell":commandExists$1("pwsh")?"pwsh":null;return t?void launchDetached(t,["-NoExit","-Command",`Set-Location -LiteralPath '${escapePowerShellString(e)}'`]):void launchDetached("cmd",["/K",`cd /d "${e.replace(/"/g,'""')}"`])}if("linux"===t){const t=getLinuxTerminalCommand();if(!t)throw new Error("No supported terminal is available");return void launchDetached(t.command,t.args(e))}throw new Error("Terminal open is not supported on this platform")}if(!runCommand$1("osascript",["-e",'tell application "Terminal"',"-e",`do script "${escapeAppleScriptString(`cd ${shellQuotePosix(e)}`)}"`,"-e","activate","-e","end tell"]))throw new Error("Failed to open Terminal")}function openWithChooser(e,t){if("darwin"!==t)if("win32"!==t){if("linux"!==t)throw new Error("Open With is not supported on this platform");runCommand$1("gio",["open","--ask",e])}else runCommand$1(commandExists$1("powershell")?"powershell":"pwsh",["-NoProfile","-Command",`Start-Process -Verb OpenAs -FilePath '${escapePowerShellString(e)}'`]);else if(null===runCommand$1("osascript",["-e",`set targetPath to POSIX file "${escapeAppleScriptString(e)}"`,"-e","set appChoice to choose application","-e","tell appChoice to open targetPath"],{captureOutput:!0}))throw new Error("No application selected")}function getLinuxTerminalCommand(){const e=shellQuotePosix(process.env.SHELL||"/bin/sh"),t=process.env.TERMINAL;return t&&isSafeCommandReference(t)&&commandExists$1(t)?{command:t,args:t=>["-e","sh","-lc",`cd ${shellQuotePosix(t)} && exec ${e}`]}:[{command:"gnome-terminal",args:e=>["--working-directory",e]},{command:"kgx",args:e=>["--working-directory",e]},{command:"konsole",args:e=>["--workdir",e]},{command:"xfce4-terminal",args:e=>["--working-directory",e]},{command:"mate-terminal",args:e=>["--working-directory",e]},{command:"lxterminal",args:e=>["--working-directory",e]},{command:"alacritty",args:e=>["--working-directory",e]},{command:"kitty",args:e=>["--directory",e]},{command:"xterm",args:t=>["-e","sh","-lc",`cd ${shellQuotePosix(t)} && exec ${e}`]},{command:"x-terminal-emulator",args:t=>["-e","sh","-lc",`cd ${shellQuotePosix(t)} && exec ${e}`]}].find(e=>commandExists$1(e.command))??null}function openInFileManager(e,t){if("darwin"!==t){if("win32"!==t){if("linux"===t)return commandExists$1("xdg-open")?void runCommand$1("xdg-open",[e]):void runCommand$1("gio",["open",e]);throw new Error("File manager open is not supported on this platform")}runCommand$1("explorer",[e])}else runCommand$1("open",[e])}function applyOpenerOverrides(e,t,n){const a=n??getOpenerOverrides();return e.map(e=>{const n=a[e.id];if(!n)return e;if(!1===n.enabled)return{...e,isSupported:()=>!1};const s={...e,label:n.label??e.label,method:n.method??e.method,urlTemplate:n.urlTemplate??e.urlTemplate};if(n.command){const a=normalizeAppNames(n.appName??e.macAppNames);s.method="cli",s.isSupported=()=>isCommandAvailable(n.command,a,t),s.open=e=>openWithCommand(n.command,n.args,e)}return s})}function getOpenerOverrides(){try{const e=machine.machine.readSettings();if(!e||"object"!=typeof e)return{};const t=e.openersOverrides;return t&&"object"==typeof t?t:{}}catch(e){return machine.logger.warn("[OPENERS] Failed to read opener overrides",e),{}}}function getOpenerOverridesSignature(e){try{return JSON.stringify(e)}catch{return""}}function openWithCommand(e,t,n){if(!runCommand$1(e,(t&&t.length>0?t:["{path}"]).map(e=>e.split("{path}").join(n))))throw new Error(`Command failed: ${e}`)}function isCommandAvailable(e,t,n){return"darwin"===n&&t.length>0?t.some(e=>isMacAppInstalled(e)):path.isAbsolute(e)||e.includes(path.sep)?fs.existsSync(e):commandExists$1(e)}function normalizeAppNames(e){return e?Array.isArray(e)?e:[e]:[]}function isSchemeRegistered(e,t,n){return"darwin"===t?isSchemeRegisteredMac(e,n):"win32"===t?isSchemeRegisteredWindows(e):"linux"===t&&isSchemeRegisteredLinux(e)}function isSchemeRegisteredMac(e,t){if(commandExists$1("mdfind")){const t=runCommand$1("mdfind",[`kMDItemCFBundleURLSchemes == '${e}'`],{captureOutput:!0});if(t&&t.trim())return!0}if(commandExists$1("plutil")){const t=[path.join(os.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(!fs.existsSync(n))continue;const t=runCommand$1("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){machine.logger.debug("[OPENERS] Failed to parse LaunchServices handlers",e)}}}return!!(t&&t.length>0)&&t.some(e=>isMacAppInstalled(e))}function isMacAppInstalled(e){return"darwin"===process.platform&&Boolean(runCommand$1("open",["-Ra",e]))}function isSchemeRegisteredWindows(e){return commandExists$1("reg")&&(Boolean(runCommand$1("reg",["query",`HKCU\\Software\\Classes\\${e}`]))||Boolean(runCommand$1("reg",["query",`HKCR\\${e}`])))}function isSchemeRegisteredLinux(e){if(commandExists$1("xdg-settings")){const t=runCommand$1("xdg-settings",["get","default-url-scheme-handler",e],{captureOutput:!0});if(t&&t.trim()&&"null"!==t.trim())return!0}if(commandExists$1("gio")){const t=runCommand$1("gio",["mime",`x-scheme-handler/${e}`],{captureOutput:!0});if(t&&/Default application/.test(t))return!0}return!1}function commandExists$1(e){return"win32"===process.platform?Boolean(runCommand$1("where",[e])):Boolean(runCommand$1("sh",["-c",`command -v ${e}`]))}function isSafeCommandReference(e){return/^[A-Za-z0-9_./+-]+$/.test(e)}function runCommand$1(e,t,n){const a=node_child_process.spawnSync(e,t,{encoding:n?.captureOutput?"utf8":void 0,stdio:n?.captureOutput?"pipe":"ignore",windowsHide:!0});if(0!==a.status){if(n?.captureOutput){const n="string"==typeof a.stderr?a.stderr.trim():"";n&&machine.logger.warn(`[OPENERS] Command failed: ${e} ${t.join(" ")}: ${n}`)}return null}return n?.captureOutput?a.stdout:"ok"}function launchDetached(e,t){node_child_process.spawn(e,t,{detached:!0,stdio:"ignore",windowsHide:!1}).unref()}function escapePowerShellString(e){return e.replace(/'/g,"''")}function escapeAppleScriptString(e){return e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}function shellQuotePosix(e){return`'${e.replace(/'/g,"'\\''")}'`}function getVersionPath(e,t){if(t){const n=path.relative(t,e),a=!n||n.startsWith("..")||path.isAbsolute(n)?path.basename(e):n;return path.join(t,"versions",a)}let n=path.dirname(e),a=0;for(;a<10;){if(fs.existsSync(path.join(n,"agent.json"))){const t=e.slice(n.length).replace(/^\//,"");return path.join(n,"versions",t)}const t=path.dirname(n);if(t===n)break;n=t,a++}const s=path.dirname(e),i=path.basename(e);return path.join(s,`.${i}.version`)}function readFileVersion(e,t){const n=getVersionPath(e,t);if(!fs.existsSync(n))return"0.0.0";try{return fs.readFileSync(n,"utf-8").trim()}catch(e){return"0.0.0"}}function writeFileVersion(e,t,n){try{const a=getVersionPath(e,n),s=path.dirname(a);fs.existsSync(s)||fs.mkdirSync(s,{recursive:!0}),fs.writeFileSync(a,t,"utf-8")}catch(e){}}function compareVersions$1(e,t){const n=e.split(".").map(Number),a=t.split(".").map(Number);for(let e=0;e<3;e++){const t=n[e]||0,s=a[e]||0;if(t>s)return 1;if(t<s)return-1}return 0}function installTemplateFile(e,t,n){const a=readFileVersion(e,n),s=compareVersions$1(t.metadata.version,a);if(!fs.existsSync(e)){const a=path.dirname(e);return fs.existsSync(a)||fs.mkdirSync(a,{recursive:!0}),fs.writeFileSync(e,t.content,"utf-8"),writeFileVersion(e,t.metadata.version,n),{updated:!0,reason:"created"}}if(s<=0)return{updated:!1,reason:"up-to-date"};switch(t.metadata.updateStrategy){case"overwrite":return fs.writeFileSync(e,t.content,"utf-8"),writeFileVersion(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"}}}function checkPendingUpgrades(e,t,n={}){const a=[],s=[];for(const i of e){if("notify-user"!==i.metadata.updateStrategy)continue;const e=path.join(t,i.relativePath);if(!fs.existsSync(e))continue;const o=readFileVersion(e,t);if(compareVersions$1(i.metadata.version,o)>0){const r={template:i,targetPath:e,upgradePath:`${e}.upgrade`,versionPath:getVersionPath(e,t),currentVersion:o,newVersion:i.metadata.version},c=i.language??"common";if("common"!==c){if(!1===n.languageVerified){s.push({...r,reason:`Cannot safely determine installed Companion template language; refusing to generate ${c} upgrade content for ${i.relativePath}.`});continue}if(n.currentLanguage&&c!==n.currentLanguage){s.push({...r,reason:`Template language ${c} does not match installed Companion language ${n.currentLanguage}.`});continue}}a.push(r)}}return{pendingUpgrades:a,blockedUpgrades:s}}function generateUpgradeNotification(e){const t=e.pendingUpgrades,n=e.blockedUpgrades??[],a=t.length>0?t.map(e=>`### ${e.template.metadata.description||e.template.relativePath}\n\n- Relative path: \`${e.template.relativePath}\`\n- Template language: \`${e.template.language??"common"}\`\n- Current version: \`v${e.currentVersion}\`\n- New version: \`v${e.newVersion}\`\n- Target path: \`${e.targetPath}\`\n- Upgrade file path: \`${e.upgradePath}\`\n- Version marker path: \`${e.versionPath}\``).join("\n\n"):"None.",s=n.length>0?n.map(e=>`### ${e.template.metadata.description||e.template.relativePath}\n\n- Relative path: \`${e.template.relativePath}\`\n- Template language: \`${e.template.language??"common"}\`\n- Current version: \`v${e.currentVersion}\`\n- New version: \`v${e.newVersion}\`\n- Target path: \`${e.targetPath}\`\n- Upgrade file path: \`${e.upgradePath}\`\n- Version marker path: \`${e.versionPath}\`\n- Reason: ${e.reason}`).join("\n\n"):"None.";return`# Upgrades Available\n\nGenerated by Agentrix Companion upgrade detection.\n\n- Agent root: \`${e.agentDir}\`\n- Current Companion template language: \`${e.language}\`\n- Language source: \`${e.languageSource}\`\n\n## Ready Upgrades\n\n${a}\n\n## Blocked Upgrades\n\n${s}\n\n---\n\n**Shadow's Instructions:**\n\nWhen you detect this file:\n1. Read this file to identify available upgrades\n2. For each ready upgrade, read the exact \`Upgrade file path\`\n3. Integrate the new content into the target file while preserving local customizations when possible\n4. Update the exact \`Version marker path\` with the new version number\n5. Delete processed \`.upgrade\` files\n6. Delete this file when all ready upgrades are applied and there are no blocked upgrades\n7. If an upgrade cannot be applied safely, leave the files in place and write the reason under Blocked Upgrades in this file; do not notify the main companion\n`}function generateUpgradeFileContent(e){return`# Upgrade: ${e.template.metadata.description||e.template.relativePath}\n\n**Relative Path**: \`${e.template.relativePath}\`\n**Template Language**: \`${e.template.language??"common"}\`\n**Current Version**: v${e.currentVersion}\n**New Version**: v${e.newVersion}\n**Target Path**: \`${e.targetPath}\`\n**Upgrade File Path**: \`${e.upgradePath}\`\n**Version Marker Path**: \`${e.versionPath}\`\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 the exact target file: \`${e.targetPath}\`\n3. Integrate the new features in the Companion's current voice and language\n4. Keep existing customizations\n5. Use Write tool to update the exact version marker path \`${e.versionPath}\` with content: "${e.newVersion}"\n6. Delete this file when done: \`${e.upgradePath}\`\n`}async function installAgentFromGit(e){const{agentId:t,gitUrl:n,branch:a,subDir:s}=e,i=path.join(machine.machine.agentrixAgentsHomeDir,t);if(fs.existsSync(i))return{agentDir:i};const o=`${i}.tmp-${Date.now()}`;try{const e=["git","clone","--depth=1"];if(a&&e.push("--branch",a),e.push(n,o),node_child_process.execSync(e.join(" "),{stdio:"pipe"}),s){const e=path.join(o,s);if(!fs.existsSync(e))throw new Error(`Sub-directory "${s}" not found in cloned repository`);fs.renameSync(e,i),fs.rmSync(o,{recursive:!0,force:!0})}else fs.renameSync(o,i);return buildAgentPlugins(i),{agentDir:i}}catch(e){throw fs.existsSync(o)&&fs.rmSync(o,{recursive:!0,force:!0}),fs.existsSync(i)&&fs.rmSync(i,{recursive:!0,force:!0}),e}}function buildAgentPlugins(e){const t=[],n=path.join(e,"claude","plugins");if(fs.existsSync(n))for(const e of fs.readdirSync(n)){const a=path.join(n,e);fs.statSync(a).isDirectory()&&fs.existsSync(path.join(a,"package.json"))&&t.push(a)}const a=path.join(e,"claude","hooks");fs.existsSync(a)&&fs.existsSync(path.join(a,"package.json"))&&t.push(a);for(const e of t)node_child_process.execSync("yarn install --frozen-lockfile",{cwd:e,stdio:"pipe"}),node_child_process.execSync("yarn build",{cwd:e,stdio:"pipe"})}function trimIdent(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 CHANGE_TITLE_PROMPT=trimIdent("\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");function buildCodexEventBrokerTitlePrompt(e){return trimIdent(`\n ## Title Setting Protocol:\n - MUST set a descriptive title as your FIRST action when the user makes a request\n - Use the Agentrix event broker MCP tool for this: server "${e.serverName}", tool "${e.toolName}"\n - This is mandatory when the tool is available; do this before any other work\n - Update the title if the conversation direction changes substantially\n `)}function buildCodexEventBrokerPreviewPrompt(e){return trimIdent(`\n ## Task Preview URL Protocol:\n - Important: when a browser-viewable frontend preview URL is available, publishing it is required, not optional.\n - If the user provided a service startup port, relevant startup documentation, or you started/reused a frontend service yourself, publish the preview URL for the current Agentrix task whenever you know the running service port.\n - Use the Agentrix event broker MCP tool for this: server "${e.serverName}", tool "${e.toolName}".\n - Publish only absolute http or https URLs. Local preview URLs such as http://localhost:5173 are valid.\n - Do not publish URLs for backend-only services or endpoints that are not user-facing frontend previews.\n `)}function buildTaskPreviewPrompt(e){return trimIdent(`\n ## Task Preview URL Protocol:\n - Important: when a browser-viewable frontend preview URL is available, publishing it is required, not optional.\n - If the user provided a service startup port, relevant startup documentation, or you started/reused a frontend service yourself, publish the preview URL for the current Agentrix task whenever you know the running service port.\n - Use \`${e}\` to publish the preview URL.\n - Publish only absolute http or https URLs. Local preview URLs such as http://localhost:5173 are valid.\n - Do not publish URLs for backend-only services or endpoints that are not user-facing frontend previews.\n `)}function buildVisionArtifactPrompt(e){return trimIdent(`\n ## Agentrix Vision Artifact Protocol:\n - After you create or materially update the visual plan (\`plan/index.html\`), and again after you create or update the visual test report (\`test/index.html\`), use \`${e}\` to send the issue vision artifacts to the platform so the user can review them.\n - Pass only the repository root and issue id. The platform presents the available plan and test artifacts together.\n - Do not start the local Vision engine just to use this tool.\n - If this tool is unavailable, share the local artifact paths with the user and ask them to review.\n `)}function buildCodexEventBrokerVisionArtifactPrompt(e){return trimIdent(`\n ## Agentrix Vision Artifact Protocol:\n - After you create or materially update the visual plan (\`plan/index.html\`), and again after you create or update the visual test report (\`test/index.html\`), send the issue vision artifacts to the platform for review using the Agentrix event broker MCP tool: server "${e.serverName}", tool "${e.toolName}".\n - Pass only the repository root and issue id. The platform presents the available plan and test artifacts together.\n - Do not start the local Vision engine just to use this tool.\n - If this tool is unavailable, share the local artifact paths with the user and ask them to review.\n `)}function buildAgentrixComputerUsePrompt(e){return trimIdent(`\n ## Agentrix Computer Use Protocol:\n - When the user explicitly asks you to operate this local computer, use \`${e}\`.\n - Use it for desktop apps, Finder, documents, windows, menus, dialogs, and other GUI operations.\n - Pass a concrete natural-language operation instruction. Do not invent low-level click coordinates or try to perform the GUI operation yourself.\n - When the operation references a file, directory, document, download, or save location, include the absolute path in the instruction.\n - Only use this tool for user-requested local computer control.\n `)}const FILE_WRITE_CHUNKING_PROMPT=trimIdent("\n Important: If the content to be written to a file is too long, split it into chunks and write them to the file incrementally. Writing too much content at once can easily cause errors.\n");function formatChannelPlatform(e){const t=e?.trim();return t?{telegram:"Telegram",wechat:"WeChat",lark:"Lark"}[t.toLowerCase()]??t:null}function buildExternalChannelContextIntro(e){const t=formatChannelPlatform(e?.platform),n=[e?.chatType?`chat type: ${e.chatType}`:void 0,e?.chatName?`chat name: ${e.chatName}`:void 0,e?.chatId?`chat id: ${e.chatId}`:void 0].filter(Boolean).join(", ");return trimIdent(t?`\n This task was started from an external messaging channel on ${t}.\n The user is interacting with you through ${t}.\n ${n?`Channel context: ${n}.`:""}\n `:"\n This task was started from an external messaging channel such as Telegram, WeChat, or Lark.\n The user is interacting with you through that external platform.\n ")}function buildExternalChannelPrompt(e){const t="group"===e?.chatType?.toLowerCase();return trimIdent(`\n ## External Channel Context\n\n ${buildExternalChannelContextIntro(e)}\n\n ${t?trimIdent("\n This external channel is a group chat. Recent group history may already be injected into the current input as `<external_group_history>` with `<msg>` entries and sender metadata.\n\n If you need more context from earlier group messages, use `mcp__agentrix__get_channel_group_history` to page older saved group history. That tool is read-only and is only for understanding context/history.\n "):""}\n\n Your normal final result is NOT automatically sent to the external channel. It is stored in Agentrix/task history.\n\n The external user is waiting on the external platform. If you do not call \`mcp__agentrix__send_channel_message\` during this turn, the user will see absolutely nothing from your model-directed channel response. Any runtime fallback is only an emergency safety net; do not rely on it.\n\n You MUST use \`mcp__agentrix__send_channel_message\` to send anything the external user should see: acknowledgements, progress updates, questions, results, and failures.\n\n Before ending the task, you MUST ensure the external user has received an appropriate user-facing message via \`mcp__agentrix__send_channel_message\`.\n\n Do not put user-facing content only in the final internal result; the system will NOT forward the normal success result when you have used the channel message tool.\n\n For multi-step tasks, at minimum call \`mcp__agentrix__send_channel_message\` once before ending with the final conclusion.\n\n If the user receives no message at all, the answer is considered a failure regardless of how complete the internal result is.\n\n ## What to send with send_channel_message\n\n Use \`mcp__agentrix__send_channel_message\` to send user-facing conversational messages to the external channel.\n The purpose is to help the user understand that you are working, what state the work is in, and what the final result is.\n\n You should send:\n - Acknowledgement/progress when the task is long-running, multi-step, or requires waiting, so the user knows work started or is ongoing.\n - Questions/choices/permission requests when user input is needed or you are blocked.\n - User-understandable results when done: conclusion, summary, next steps, and key deliverable notes.\n - Clear failure/limitation messages when the task cannot be completed, a platform does not support something, permission is missing, or an external service fails.\n\n Do not send:\n - Internal reasoning, verbose execution logs, stack traces, debug dumps.\n - Internal summaries that only matter to Agentrix/task history.\n - Excessive implementation detail unless the user is explicitly collaborating technically and needs it.\n - Temporary paths, environment variables, tokens, secrets, or private data.\n\n Style:\n - External channel messages should feel like natural conversation: short, clear, useful.\n - For simple tasks, usually send only the final answer.\n - For long tasks, send a brief start/progress message and a final result message.\n - If attachments are sent, briefly explain what they are and what the user can do next.\n\n ## What attachments to send\n\n Attachments are part of \`send_channel_message\` and are only for deliverables the user should consume, save, view, or forward.\n\n Send attachments for:\n - Files the user explicitly asked to generate, export, package, send, or share.\n - Final deliverables such as images, posters, charts, PDFs, spreadsheets, reports, slides, archives, audio, or video.\n - Artifacts without which the channel answer would be incomplete.\n\n Do not send attachments for:\n - Files that were merely created, edited, read, downloaded, or used while doing the work.\n - Logs, caches, temporary files, build artifacts, intermediate screenshots, debug outputs unless the user explicitly asked for them.\n - Files containing secrets, credentials, private data, or local environment details.\n - Any file that is only part of the work process rather than a user deliverable.\n\n Decision rules:\n - A file generated for the user to use/view/save is usually an attachment deliverable.\n - A file created or modified while completing work is not automatically a deliverable; decide based on user intent.\n - Do not decide based on file location or directory.\n - A file inside the workspace can be a deliverable.\n - A file outside the workspace can still be unsafe or inappropriate.\n - Decide based on semantics and user intent, not path location.\n - When modifying files, do not send them automatically; summarize changes in text unless the user asked to receive, export, package, or forward those files.\n - If uncertain or risky, ask for confirmation via \`send_channel_message\` first.\n\n Do NOT send files just because they were created, edited, read, downloaded, or used during the task.\n After sending the external response, your final result can briefly summarize what you sent for Agentrix history.\n If the platform does not support sending that attachment type, explain that and provide the best available alternative.\n`)}buildExternalChannelPrompt();const GROUP_CHAT_MESSAGE_FORMAT=trimIdent('\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'),ORCHESTRATION_DECISION_FRAMEWORK=trimIdent('\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'),GROUP_CHAT_PLANNER_IDENTITY=trimIdent('\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'),CHAT_MODE_TASK_DELEGATION=trimIdent("\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"),PLANNER_BASE_PROMPT=trimIdent(`\n ${GROUP_CHAT_PLANNER_IDENTITY}\n\n ${GROUP_CHAT_MESSAGE_FORMAT}\n\n ${ORCHESTRATION_DECISION_FRAMEWORK}\n`),GROUP_MEMBER_MESSAGE_FORMAT=trimIdent('\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 buildAgentsListPrompt(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 buildAgentContextPrompt(e,t){const n=t.find(t=>t.id===e);if(!n)return buildAgentsListPrompt(t);const a=t.filter(t=>t.id!==e),s=["# Group Context","",`You are \`${n.name}\`. `,"You are a member of this group chat."];if(n.description&&s.push(`Your role: ${n.description}`),a.length>0){s.push(""),s.push("## Other Agents in This Group"),s.push("");for(const e of a)e.description?s.push(`- **${e.name}**: ${e.description}`):s.push(`- **${e.name}**`)}return s.push(""),s.push(GROUP_MEMBER_MESSAGE_FORMAT),s.join("\n")}function mergeEnvironment(e){const t={};for(const[n,a]of Object.entries(e))"string"==typeof a&&(t[n]=a);return t}function isTextBlock$1(e){if("object"!=typeof e||null===e)return!1;const t=e;return"text"===t.type&&"string"==typeof t.text}function normalizeClaudeUserMessage(e){return{type:"user",message:{role:"user",content:e},parent_tool_use_id:null,session_id:""}}function extractUserMessageText(e){const t=e.message?.content;return"string"==typeof t?t:Array.isArray(t)?t.filter(isTextBlock$1).map(e=>e.text).join("\n").trim():""}function createClaudeAssistantMessage(e){return{type:"assistant",session_id:"",uuid:crypto.randomUUID(),parent_tool_use_id:null,message:{role:"assistant",content:[{type:"text",text:e}]}}}function createSdkResultMessage(e){const t=e.usage.input_tokens-e.usage.cached_input_tokens,n=Math.max(0,Math.trunc(e.durationMs??0)),a={input_tokens:e.usage.input_tokens,output_tokens:e.usage.output_tokens,cache_creation:{ephemeral_1h_input_tokens:0,ephemeral_5m_input_tokens:0},cache_creation_input_tokens:0,cache_read_input_tokens:e.usage.cached_input_tokens,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:n,duration_api_ms:n,is_error:!1,num_turns:e.numTurns,result:e.result??"",stop_reason:null,total_cost_usd:0,usage:a,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 createSdkErrorResultMessage(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:""}}function parseStructuredOutputTextOrThrow(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 HOOK_TIMEOUT_MS=6e4;async function executeHook(e,t,n,a){if(!e)return;const s=e[t];if(!s)return;const i=a||(e=>console.log(e));try{i(`[${t}] Executing hook...`);const e=new AbortController,a=setTimeout(()=>{e.abort()},6e4);try{await s(n,"",{signal:e.signal}),i(`[${t}] Hook executed successfully`)}finally{clearTimeout(a)}}catch(e){console.warn(`[${t}] Hook failed (non-fatal):`,e)}}function buildHooksWithDelegation(e,t){const n={},a=e=>async(t,n,a)=>await e(t,n,a)??{},s=new Set([...Object.keys(e),...t?Object.keys(t):[]]);for(const i of s){const s=[],o=e[i];o&&s.push(a(o));const r=t?.[i];r&&s.push(a(r)),n[i]=[{hooks:s}]}return n}const DEFAULT_SERVER_NAME="agentrix",DEFAULT_SERVER_VERSION="1.0.0",formatToolName=(e,t)=>`mcp__${e}__${t}`;function buildAgentrixMcpServer(e){const{modeConfig:t,tools:n,agentType:a,allowAskUser:s=!0,supportedFeatures:i,channelBound:o,channelGroupBound:r,visionModel:c,enableTaskPreviewUrl:l=!0,enableVisionPlan:d=!1,enableComputerUse:p=!1,extraTools:u=[],serverName:m=DEFAULT_SERVER_NAME,serverVersion:h=DEFAULT_SERVER_VERSION}=e,{mode:g,supportChangeTitle:f}=t,y=[];switch(g){case"work":p&&y.push(n.computerUse),i?.includes("sub-task")&&(y.push(n.createTask),y.push(n.replyToSubTask),y.push(n.listSubTask)),f&&y.push(n.changeTaskTitle),s&&y.push(n.askUser),l&&y.push(n.publishTaskPreviewUrl),d&&y.push(n.sendVisionArtifact),y.push(n.getTaskHistory);break;case"chat":p&&y.push(n.computerUse),y.push(n.createTask),y.push(n.replyToSubTask),s&&y.push(n.askUser),y.push(n.getTaskHistory),y.push(n.listSubTask);break;case"group_chat":y.push(n.invoke),y.push(n.createSoloTask),y.push(n.createGroupTask),y.push(n.replyToSubTask),y.push(n.getTaskAgents),y.push(n.getTaskHistory);break;case"group_work":y.push(n.invoke),y.push(n.assign),f&&y.push(n.changeTaskTitle),l&&y.push(n.publishTaskPreviewUrl),d&&y.push(n.sendVisionArtifact),y.push(n.getTaskAgents),y.push(n.getTaskHistory);break;case"reply":y.push(n.getTaskHistory),s&&y.push(n.askUser);break;case"companion_chat":y.push(n.createTask),y.push(n.replyToSubTask),s&&y.push(n.askUser),y.push(n.getTaskHistory),y.push(n.uploadFile),y.push(n.listAgents),y.push(n.scheduleTask);break;case"companion_shadow":y.push(n.getTaskHistory),y.push(n.readConversation),y.push(n.listAgents),y.push(n.scheduleTask)}return("companion_chat"===g||"companion_shadow"===g)&&(y.push(n.listTasks),y.push(n.sendReminder),y.push(n.recordMemoryChange),y.push(n.prepareHiveRepository),y.push(n.publishToHive),y.push(n.updateHiveListingVersion),y.push(n.recordHiveInstall),y.push(n.createHiveReview),y.push(n.createHiveComment)),"companion"===a&&y.push(n.updateAgentInfo),o&&"companion_shadow"!==g&&y.push(n.sendChannelMessage),r&&"companion_shadow"!==g&&y.push(n.getChannelGroupHistory),c&&"companion_shadow"!==g&&"reply"!==g&&y.push(n.analyzeImage),y.push(...u),{server:claudeAgentSdk.createSdkMcpServer({name:m,version:h,tools:y}),toolNames:y.map(e=>formatToolName(m,e.name))}}const execFileAsync$6=node_util.promisify(node_child_process.execFile),logger$9=machine.createModuleLogger("undefined"==typeof document?require("url").pathToFileURL(__filename).href:_documentCurrentScript&&"SCRIPT"===_documentCurrentScript.tagName.toUpperCase()&&_documentCurrentScript.src||new URL("index.cjs",document.baseURI).href),COMPANION_SELF_EVOLUTION_GITIGNORE=["*","","!.gitignore","","!MEMORY.md","!USER.md","!SOUL.md","!IDENTITY.md","!SKILLS.md","!system_prompt.md","","!HEARTBEAT.md","!MEMORY_ORGANIZATION.md","!UPGRADES.md","!*.upgrade","","!memory/","!memory/**","!memory-changes/","!memory-changes/**","","!plugins/","!plugins/**","!versions/","!versions/**",""].join("\n"),TOP_LEVEL_ALLOWED_FILES=new Set(["MEMORY.md","USER.md","SOUL.md","IDENTITY.md","SKILLS.md","system_prompt.md","HEARTBEAT.md","MEMORY_ORGANIZATION.md","UPGRADES.md"]),ALLOWED_DIRECTORIES=["memory","memory-changes","plugins","versions"],GIT_AUTHOR_ENV={GIT_AUTHOR_NAME:"Agentrix Companion",GIT_AUTHOR_EMAIL:"companion@agentrix.local",GIT_COMMITTER_NAME:"Agentrix Companion",GIT_COMMITTER_EMAIL:"companion@agentrix.local"};function toGitPath(e){return e.split(path.sep).join("/")}function normalizeRelativePath$1(e){return toGitPath(path.normalize(e)).replace(/^\.\//,"")}function logGitError(e,t){logger$9.warn(e,t)}async function runGit(e,t){const{stdout:n}=await execFileAsync$6("git",t,{cwd:e,encoding:"utf-8",windowsHide:!0,env:{...process.env,...GIT_AUTHOR_ENV}});return n}async function ensureGitignore(e){const t=path.join(e,".gitignore");await promises$1.readFile(t,"utf-8").catch(()=>{})!==COMPANION_SELF_EVOLUTION_GITIGNORE&&await promises$1.writeFile(t,COMPANION_SELF_EVOLUTION_GITIGNORE,"utf-8")}async function hasStagedDiff(e){try{return await runGit(e,["diff","--cached","--quiet","--exit-code"]),!1}catch(e){if("number"==typeof e?.code&&1===e.code)return!0;throw e}}async function commitStaged(e,t,n){const a=["commit","-m",t];return n?.trim()&&a.push("-m",n.trim()),await runGit(e,a),(await runGit(e,["rev-parse","HEAD"])).trim()}async function listTrackedAllowedPaths(e){return(await runGit(e,["ls-files"])).split(/\r?\n/).map(e=>e.trim()).filter(e=>e.length>0).filter(isCompanionSelfEvolutionAllowedPath)}async function listExistingAllowlistStagePaths(e){const t=new Set;fs.existsSync(path.join(e,".gitignore"))&&t.add(".gitignore");for(const n of TOP_LEVEL_ALLOWED_FILES)fs.existsSync(path.join(e,n))&&t.add(n);const n=await promises$1.readdir(e).catch(()=>[]);for(const a of n)!a.includes("/")&&a.endsWith(".upgrade")&&fs.existsSync(path.join(e,a))&&t.add(a);for(const n of ALLOWED_DIRECTORIES)fs.existsSync(path.join(e,n))&&t.add(n);for(const n of await listTrackedAllowedPaths(e))t.add(n);return Array.from(t)}function isCompanionSelfEvolutionAllowedPath(e){const t=normalizeRelativePath$1(e);return!(!t||"."===t||t.startsWith("../")||t.includes("/../"))&&(!!TOP_LEVEL_ALLOWED_FILES.has(t)||!(t.includes("/")||!t.endsWith(".upgrade"))||ALLOWED_DIRECTORIES.some(e=>t===e||t.startsWith(`${e}/`)))}function resolveCompanionSelfEvolutionPath(e,t){const n=path.normalize(e),a=path.normalize(t),s=path.isAbsolute(a)?a:path.normalize(path.join(n,a)),i=normalizeRelativePath$1(path.relative(n,s));if(!i.startsWith("../")&&!path.isAbsolute(i)&&isCompanionSelfEvolutionAllowedPath(i))return{absolutePath:s,relativePath:i};if(!path.isAbsolute(a)){const e=path.normalize(path.join(n,"memory",a)),t=normalizeRelativePath$1(path.relative(n,e));if(!t.startsWith("../")&&!path.isAbsolute(t)&&isCompanionSelfEvolutionAllowedPath(t))return{absolutePath:e,relativePath:t}}throw new Error(`Companion self-evolution path is not allowlisted: ${t}`)}async function ensureCompanionSelfEvolutionGitRepo(e){const{companionHome:t}=e;if(!t)return logger$9.warn("Skipping self-evolution git repo ensure: companion home is not set"),!1;if(!fs.existsSync(t))return logger$9.warn(`Skipping self-evolution git repo ensure: companion home does not exist (${t})`),!1;try{await promises$1.mkdir(t,{recursive:!0});const e=fs.existsSync(path.join(t,".git"));return e||await runGit(t,["init"]),await ensureGitignore(t),e||(await stageCompanionSelfEvolutionAllowlist(t),await hasStagedDiff(t)&&await commitStaged(t,"Initialize Companion self-evolution history","Initial snapshot before automatic Companion run checkpoints.")),!0}catch(e){return logGitError("Failed to ensure Companion self-evolution git repo",e),!1}}async function stageCompanionSelfEvolutionAllowlist(e){const t=await listExistingAllowlistStagePaths(e);0!==t.length&&await runGit(e,["add","-A","--",...t])}async function stageCompanionSelfEvolutionPaths(e,t){const n=new Set(await listTrackedAllowedPaths(e)),a=Array.from(new Set(t.map(normalizeRelativePath$1))).filter(isCompanionSelfEvolutionAllowedPath).filter(t=>fs.existsSync(path.join(e,t))||n.has(t));return 0===a.length?[]:(await runGit(e,["add","-A","--",...a]),a)}function buildCheckpointTitle(e,t,n){const a="before_run"===n?"before":"after";return"companion_shadow"===e?"unknown"===t?`checkpoint: ${a} companion_shadow run`:`checkpoint: ${a} companion_shadow ${t} run`:`checkpoint: ${a} companion_chat run`}function buildCheckpointBody(e,t,n){return[`mode: ${e}`,`shadow_task: ${"companion_shadow"===e?t:"unknown"}`,`phase: ${n}`].join("\n")}function resolveCompanionShadowTask(e){return"heartbeat"===e?.COMPANION_SHADOW_TASK?"heartbeat":"memory_organization"===e?.COMPANION_SHADOW_TASK?"memory_organization":"unknown"}async function checkpointCompanionSelfEvolution(e){const{companionHome:t,mode:n,phase:a}=e;if("companion_chat"!==n&&"companion_shadow"!==n)return{committed:!1};try{if(!await ensureCompanionSelfEvolutionGitRepo({companionHome:t})||!t)return{committed:!1};if(await stageCompanionSelfEvolutionAllowlist(t),!await hasStagedDiff(t))return{committed:!1};const s="companion_shadow"===n?e.shadowTask??"unknown":"unknown",i=await commitStaged(t,buildCheckpointTitle(n,s,a),buildCheckpointBody(n,s,a));return logger$9.info(`Created Companion self-evolution ${a} checkpoint ${i}`),{committed:!0,commit:i}}catch(e){return logGitError(`Failed to create Companion self-evolution ${a} checkpoint`,e),{committed:!1}}}function buildMemoryChangeCommitBody(e){const t=["reasons:"];for(const n of e.reasons)t.push(`- ${n}`);return t.push("",`trigger: ${e.trigger}`,`source: ${e.source??"unspecified"}`),e.taskId&&t.push(`taskId: ${e.taskId}`),t.push(`action: ${e.action}`,`file: ${e.file}`),e.deletedFiles?.length&&t.push(`deletedFiles: ${e.deletedFiles.join(", ")}`),t.push(`notifiedCompanion: ${e.notifiedCompanion}`),t.join("\n")}async function commitCompanionMemoryChange(e){const{companionHome:t,title:n,body:a,paths:s}=e;try{return 0===(await stageCompanionSelfEvolutionPaths(t,s)).length?(logger$9.warn("Skipping Companion memory change commit: no allowlisted paths to stage"),null):await hasStagedDiff(t)?await commitStaged(t,n,a):null}catch(e){return logGitError("Failed to create Companion memory change semantic commit",e),null}}async function*oneShotPrompt(e){yield e}let claudePathOverrideCache;function resolveBinaryPath(e){const t="win32"===process.platform?"where":"which",n=node_child_process.spawnSync(t,[e],{encoding:"utf-8"});if(0===n.status)return n.stdout.split(/\r?\n/).map(e=>e.trim()).find(e=>e.length>0)}function normalizeClaudePath(e){const t=e.trim();if(t){if(t.includes("/")||t.includes("\\")||t.startsWith(".")){const e=path.isAbsolute(t)?t:path.resolve(t);return fs.existsSync(e)?e:void 0}return resolveBinaryPath(t)}}function resolveClaudePathOverride(){if(void 0!==claudePathOverrideCache)return claudePathOverrideCache??void 0;const e=process.env.AGENTRIX_CLAUDE_PATH?.trim();if(e){const t=normalizeClaudePath(e);if(t)return claudePathOverrideCache=t,t}claudePathOverrideCache=null}const CHAT_TOOLS=["Bash","Glob","Grep","ExitPlanMode","Read","Skill","SlashCommand","EnterPlanMode"],CLAUDE_PLAN_MODE_TOOLS=["EnterPlanMode","ExitPlanMode"],CLAUDE_PLAN_MODE_TOOL_SET=new Set(CLAUDE_PLAN_MODE_TOOLS),GROUP_REPLY_TOOLS=["Glob","Grep","Read","Skill"],GROUP_CHAT_TOOLS=["Read","Glob","Grep"],GROUP_WORK_TOOLS=["Read","Glob","Grep","TodoWrite"];function buildSdkTools(e){switch(e){case"work":case"companion_shadow":return;case"chat":case"companion_chat":return[...CHAT_TOOLS];case"reply":return[...GROUP_REPLY_TOOLS];case"group_chat":return[...GROUP_CHAT_TOOLS];case"group_work":return[...GROUP_WORK_TOOLS]}}function filterClaudePlanModeTools(e,t){return t&&e?e.filter(e=>!CLAUDE_PLAN_MODE_TOOL_SET.has(e)):e}function getModePrompt(e,t){const{mode:n,supportChangeTitle:a}=e,s=t?.enableTaskPreviewUrl??!0,i=[FILE_WRITE_CHUNKING_PROMPT];switch(n){case"work":a&&i.unshift(CHANGE_TITLE_PROMPT),s&&i.push(buildTaskPreviewPrompt("mcp__agentrix__publish_task_preview_url")),t?.enableVisionPlan&&i.push(buildVisionArtifactPrompt("mcp__agentrix__send_vision_artifact")),t?.enableAgentrixComputerUse&&i.push(buildAgentrixComputerUsePrompt("mcp__agentrix__agentrix_computer_use"));break;case"companion_shadow":case"companion_chat":case"reply":case"group_chat":break;case"chat":i.unshift(CHAT_MODE_TASK_DELEGATION),t?.enableAgentrixComputerUse&&i.push(buildAgentrixComputerUsePrompt("mcp__agentrix__agentrix_computer_use"));break;case"group_work":a&&i.unshift(CHANGE_TITLE_PROMPT),s&&i.push(buildTaskPreviewPrompt("mcp__agentrix__publish_task_preview_url")),t?.enableVisionPlan&&i.push(buildVisionArtifactPrompt("mcp__agentrix__send_vision_artifact"))}return i.join("\n\n")}function loadCompanionShadowRoutine(e,t){if(!e||!t)return;const n="memory_organization"===t?"MEMORY_ORGANIZATION.md":"HEARTBEAT.md",a=path.join(e,n);if(!fs.existsSync(a))return;const s=fs.readFileSync(a,"utf-8").trim();return s?[`## Injected Companion ${"memory_organization"===t?"Memory Organization":"Heartbeat"} Routine`,"",s].join("\n"):void 0}function getCompanionShadowTask(e){return"memory_organization"===e?.COMPANION_SHADOW_TASK?"memory_organization":"heartbeat"}function getAgentrixMonitorPromptValue(){const e=machine.machine.readSettings();if(!e||"object"!=typeof e)return"disable";const t=e["agentrix-monitor"];return t&&"object"==typeof t&&!0===t.enable?"enable":"disable"}function buildSystemPrompt(e){const{agentId:t,modeConfig:n,cwd:a,agentConfig:s,channelBound:i,channelContext:o,projectGuidance:r,promptPlaceholders:c,enableTaskPreviewUrl:l,enableVisionPlan:d,enableAgentrixComputerUse:p}=e,{mode:u,groupAgents:m}=n,h=s.customSystemPrompt,g=s.systemPromptMode??"append",f=getModePrompt(n,{enableTaskPreviewUrl:l,enableVisionPlan:d,enableAgentrixComputerUse:p});if("group_chat"===u||"group_work"===u){const e=[PLANNER_BASE_PROMPT];return m&&m.length>0&&e.push(buildAgentsListPrompt(m)),f&&e.push(f),i&&e.push(buildExternalChannelPrompt(o)),r?.systemPromptAppend&&e.push(r.systemPromptAppend),e.join("\n\n")}const y="reply"===u&&m&&m.length>0?buildAgentContextPrompt(t,m):void 0,v={},b=process.env.AGENTRIX_COMPANION_HOME||process.env.AGENTRIX_COMPANION_WORKSPACE,k="companion_shadow"===u?getCompanionShadowTask(c):void 0;b&&(v.COMPANION_HOME=b,v.COMPANION_MODE="companion_shadow"===u?"shadow":"chat","companion_shadow"===u&&(v.AGENTRIX_MONITOR=getAgentrixMonitorPromptValue(),v.COMPANION_SHADOW_TASK=k??"heartbeat")),Object.assign(v,c);const w=Object.keys(v).length>0?v:void 0,x=h?node.replacePromptPlaceholders(h,a,w):void 0,I="companion_shadow"===u?loadCompanionShadowRoutine(b,k):void 0;if("replace"===g&&x){const e=[x];return y&&e.push(y),f&&e.push(f),i&&e.push(buildExternalChannelPrompt(o)),I&&e.push(I),r?.systemPromptAppend&&e.push(r.systemPromptAppend),e.join("\n\n")}const S=[];return y&&S.push(y),f&&S.push(f),i&&S.push(buildExternalChannelPrompt(o)),x&&S.push(x),I&&S.push(I),r?.systemPromptAppend&&S.push(r.systemPromptAppend),{type:"preset",preset:"claude_code",append:S.length>0?S.join("\n\n"):void 0}}function buildQueryOptions(e,t,n,a,s,i,o,r){const c=buildSystemPrompt({agentId:e,modeConfig:n.modeConfig,cwd:n.cwd,agentConfig:a,channelBound:n.channelBound,channelContext:n.channelContext,projectGuidance:n.projectAgentrixGuidance,promptPlaceholders:n.promptPlaceholders,enableTaskPreviewUrl:n.enableTaskPreviewUrl,enableVisionPlan:n.enableVisionPlan,enableAgentrixComputerUse:n.enableAgentrixComputerUse}),l=filterClaudePlanModeTools(buildSdkTools(n.modeConfig.mode),Boolean(n.disableClaudePlanModeTools)),d=buildHooksWithDelegation(n.hooks??{},s),p=resolveClaudePathOverride(),u=o?buildAgentrixMcpServer({modeConfig:n.modeConfig,tools:o,agentType:t,allowAskUser:n.allowAskUser,supportedFeatures:n.supportedFeatures,channelBound:n.channelBound,channelGroupBound:n.channelGroupBound,visionModel:n.visionModel,enableTaskPreviewUrl:n.enableTaskPreviewUrl,enableVisionPlan:n.enableVisionPlan,enableComputerUse:n.enableAgentrixComputerUse,extraTools:n.agentrixExtraTools}):void 0,m={...u?.server?{agentrix:u.server}:{},...n.mcpServers??{},...i??{}};return{stderr:n.stderr,model:n.model||a.customModel,fallbackModel:a.customFallbackModel,cwd:n.cwd,resume:n.agentSessionId,permissionMode:n.initialPermissionMode??a.customPermissionMode??"bypassPermissions",settingSources:["user","project","local"],systemPrompt:c,tools:l,...n.disableClaudePlanModeTools?{disallowedTools:[...CLAUDE_PLAN_MODE_TOOLS]}:{},mcpServers:m,plugins:[...a.customPlugins,...n.projectAgentrixGuidance?.claudePlugins??[]],abortController:n.abortController,env:n.env?mergeEnvironment(n.env):void 0,pathToClaudeCodeExecutable:p,maxTurns:a.customMaxTurns??n.maxTurns??r,extraArgs:a.customExtraArgs,canUseTool:n.canUseTool,hooks:d,outputFormat:n.structuredOutputSchema}}class ClaudeRunner{constructor(e,t,n,a,s){this.agentId=e,this.agentType=t,this.agentConfig=n,this.agentHooks=a,this.agentMcpServers=s}getAgentConfiguration(){return this.agentConfig}getHooks(){return this.agentHooks}getMcpServers(){return this.agentMcpServers}async executeHook(e,t,n){await executeHook(this.agentHooks,e,t,n)}async run(e,t){const n=this.agentConfig,a="string"==typeof e?normalizeClaudeUserMessage(e):e;let s=null;await this.checkpointCompanionRun(t,"before_run");try{const e=claudeAgentSdk.query({prompt:oneShotPrompt(a),options:buildQueryOptions(this.agentId,this.agentType,t,n,this.agentHooks,this.agentMcpServers,t.agentrixTools)});for await(const t of e)if("result"===t.type){s=t;break}if(!s)throw new Error("ClaudeRunner.run: missing result message");return s}finally{await this.checkpointCompanionRun(t,"after_run")}}async*runStreamed(e,t){const n=this.agentConfig,a="string"==typeof e?normalizeClaudeUserMessage(e):e;await this.checkpointCompanionRun(t,"before_run");try{const e=claudeAgentSdk.query({prompt:oneShotPrompt(a),options:buildQueryOptions(this.agentId,this.agentType,t,n,this.agentHooks,this.agentMcpServers,t.agentrixTools)});for await(const t of e)if(yield t,"result"===t.type)break}finally{await this.checkpointCompanionRun(t,"after_run")}}loop(e){const t=this,n=e.abortController,a=this.agentConfig,s=buildQueryOptions(this.agentId,this.agentType,e,a,this.agentHooks,this.agentMcpServers,e.agentrixTools);let i=!1;const o=[];let r=null,c=null;const l=()=>{if(!i&&(i=!0,r)){const e=r;r=null,e(null)}},d=async function*(){for(;!i&&!n.signal.aborted;){if(o.length>0){yield o.shift();continue}const e=await new Promise(e=>{r=e});if(!e)break;yield e}},p=async function*(){try{await t.checkpointCompanionRun(e,"before_run");const n=claudeAgentSdk.query({prompt:d(),options:s});c=n;for await(const e of n)yield e}finally{c=null,await t.checkpointCompanionRun(e,"after_run"),l()}}();return n.signal.addEventListener("abort",l,{once:!0}),{push:e=>{if(i)return;const t="string"==typeof e?normalizeClaudeUserMessage(e):e;if(r){const e=r;return r=null,void e(t)}o.push(t)},events:p,stop:l,setPermissionMode:async e=>{c&&await c.setPermissionMode(e)},setModel:async e=>{c&&await c.setModel(e)}}}async checkpointCompanionRun(e,t){const n=e.modeConfig.mode;if("companion_chat"!==n&&"companion_shadow"!==n)return;const a=process.env.AGENTRIX_COMPANION_HOME||process.env.AGENTRIX_COMPANION_WORKSPACE;await checkpointCompanionSelfEvolution({companionHome:a,mode:n,shadowTask:"companion_shadow"===n?resolveCompanionShadowTask(e.promptPlaceholders):void 0,phase:t})}}const logger$8=machine.createModuleLogger("undefined"==typeof document?require("url").pathToFileURL(__filename).href:_documentCurrentScript&&"SCRIPT"===_documentCurrentScript.tagName.toUpperCase()&&_documentCurrentScript.src||new URL("index.cjs",document.baseURI).href);function createDefaultClaudeAgentConfiguration(){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}}async function loadClaudeAgentConfiguration(e){const{agentId:t,agentDir:n}=e;if(!t||"default"===t)return createDefaultClaudeAgentConfiguration();try{logger$8.info(`Loading agent: ${t}`);const e=await node.loadAgentConfig({agentId:t,framework:"claude",agentDir:n});if(!e.claude)return logger$8.warn(`No claude configuration found for agent ${t}`),createDefaultClaudeAgentConfiguration();const a=e.claude,s=a.plugins.map(e=>({type:"local",path:e})),i=n||node.getAgentContext().resolveAgentDir(t),o=a.config.sdkMcpTools?.map(e=>path.join(i,"claude",e)),r={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:s,systemPromptMode:a.config.systemPrompt?.mode??"append",customPRPromptTemplate:a.prPromptTemplate,prPromptMode:a.config.pullRequestPrompt?.mode??"append",customSdkMcpTools:o};return logger$8.info(`Agent ${t} loaded successfully (${s.length} plugins)`),r}catch{return logger$8.error(`Failed to load agent: ${t}`),createDefaultClaudeAgentConfiguration()}}const PROBE_TIMEOUT_MS=45e3;function buildProbeTimeoutMessage(){return`Companion probe timed out after ${Math.round(45)}s`}function normalizeProbeError(e){return e instanceof Error&&e.message?e.message:String(e)}function extractProbeFailureMessage(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 probeCompanionChain(){const e=path.join(machine.machine.agentrixHomeDir,"tmp","companion-probe");fs.mkdirSync(e,{recursive:!0});const t=new ClaudeRunner("default","claude",createDefaultClaudeAgentConfiguration()),n=new AbortController;let a=!1;const s=setTimeout(()=>{a=!0,n.abort()},45e3);try{const s=await t.run("hi",{cwd:e,abortController:n,modeConfig:{mode:"chat",supportChangeTitle:!1}});return s.is_error?{success:!1,error:a?buildProbeTimeoutMessage():extractProbeFailureMessage(s)}:{success:!0}}catch(e){return{success:!1,error:a?buildProbeTimeoutMessage():normalizeProbeError(e)}}finally{clearTimeout(s)}}const execFileAsync$5=node_util.promisify(node_child_process.execFile);function createGit(e){const t={baseDir:e,binary:"git",maxConcurrentProcesses:6,trimmed:!1};return"win32"===process.platform&&(t.spawnOptions={windowsHide:!0}),simpleGit(t)}async function isGitRepository(e){try{const t=createGit(e);return await t.checkIsRepo()}catch{return!1}}async function listWorktrees(e){const t=createGit(e),n=(await t.raw(["worktree","list","--porcelain"])).trim().split("\n").filter(Boolean),a=[];let s=null;for(const e of n)if(e.startsWith("worktree "))s&&a.push(s),s={path:e.replace("worktree ","").trim(),branch:null,commit:"",isMain:0===a.length};else if(s)if(e.startsWith("HEAD "))s.commit=e.replace("HEAD ","").trim();else{if(e.startsWith("branch ")){const t=e.replace("branch ","").trim();s.branch=t.replace("refs/heads/","");continue}e.startsWith("detached")&&(s.branch=null)}return s&&a.push(s),a}async function createWorktree(e,t,n,a="HEAD"){const s=path.dirname(t);if(fs.existsSync(s)||fs.mkdirSync(s,{recursive:!0}),fs.existsSync(t)&&!isDirectoryEmpty(t))throw new Error(`Worktree directory already exists at ${t}`);const i=createGit(e);await i.raw(["worktree","add","-b",n,t,a])}async function removeWorktree(e,t,n=!1){const a=createGit(e),s=["worktree","remove"];n&&s.push("--force"),s.push(t),await a.raw(s)}async function setGitConfig(e,t,n){await execFileAsync$5("git",["config","user.name",t],{cwd:e,windowsHide:!0}),await execFileAsync$5("git",["config","user.email",n],{cwd:e,windowsHide:!0})}async function gitInit(e){const t=createGit(e);await t.init()}async function initialCommit(e){const t=createGit(e);await t.add("."),await t.commit("Initial commit",{"--allow-empty":null})}async function gitClone(e,t){const n=path.dirname(t);fs.existsSync(n)||fs.mkdirSync(n,{recursive:!0});const a=createGit();await a.clone(e,t)}async function ensureTaskBranch(e,t,n){const a=createGit(e);(await a.branchLocal()).all.includes(t)?await a.checkout(t):(await listRemoteBranches(e).catch(()=>[])).includes(t)?await execFileAsync$5("git",["checkout","-B",t,`origin/${t}`],{cwd:e,windowsHide:!0}):n?await execFileAsync$5("git",["checkout","-b",t,n],{cwd:e,windowsHide:!0}):await a.checkoutLocalBranch(t)}async function hasUncommittedChanges(e){const t=createGit(e);return!(await t.status()).isClean()}async function gitStash(e,t){const n=createGit(e);await n.stash(["push"])}async function getCurrentCommitHash(e){const t=createGit(e),n=await t.log({maxCount:1});if(!n.latest)throw new Error("No commits found in repository");return n.latest.hash}async function hasAnyCommits(e){try{const t=createGit(e);return null!==(await t.log({maxCount:1})).latest}catch{return!1}}function isDirectoryEmpty(e){if(!fs.existsSync(e))return!0;const t=fs.readdirSync(e);return 0===t.length||1===t.length&&".git"===t[0]}async function commitWithMessage(e,t){const n=t.trim();if(!n)throw new Error("Commit message cannot be empty");const[a,...s]=n.split(/\n\s*\n/).map(e=>e.trim()).filter(Boolean);if(!a)throw new Error("Commit subject cannot be empty");const i=createGit(e);await i.add(["--all"]);const o=["commit","-m",a];for(const e of s)o.push("-m",e);return await i.raw(o),await getCurrentCommitHash(e)}function parseGitRenamePath(e){const t=e.match(/^(.*)?\{([^}]*) => ([^}]*)\}(.*)$/);if(!t)return e;const[,n="",,a,s=""]=t;return`${n}${a}${s}`}async function getDiffStats(e,t,n){const a=createGit(e),s=await a.diffSummary([`${t}..${n}`]);return{totalInsertions:s.insertions,totalDeletions:s.deletions,files:s.files.map(e=>({path:parseGitRenamePath(shared.decodeGitPath(e.file)),insertions:"insertions"in e?e.insertions:0,deletions:"deletions"in e?e.deletions:0}))}}function normalizePatch(e){const t=e.trim();return t?`${t}\n`:""}async function runGitDiffCommand(e,t){try{const{stdout:n}=await execFileAsync$5("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}}async function getUntrackedFiles(e){const{stdout:t}=await execFileAsync$5("git",["ls-files","--others","--exclude-standard","-z"],{cwd:e,maxBuffer:10485760,windowsHide:!0});return t.split("\0").filter(Boolean)}function parseNumstatLine(e){const[t,n,a]=e.split("\t");if(!t||!n||!a)return null;const s="-"===t?0:Number.parseInt(t,10),i="-"===n?0:Number.parseInt(n,10);if(Number.isNaN(s)||Number.isNaN(i))return null;const o=a.startsWith("/dev/null => ")?a.slice(13):a;return{path:parseGitRenamePath(shared.decodeGitPath(o)),insertions:s,deletions:i}}function parseNumstatOutput(e){return e.split("\n").map(e=>e.trim()).filter(Boolean).map(e=>parseNumstatLine(e)).filter(e=>null!==e)}function buildDiffStats(e){return{totalInsertions:e.reduce((e,t)=>e+t.insertions,0),totalDeletions:e.reduce((e,t)=>e+t.deletions,0),files:e}}function createArtifactVersion(e,t){return node_crypto.createHash("sha256").update(`${e}\n${t}`).digest("hex")}async function getWorkspaceArtifactsSnapshot(e,t){const n=await runGitDiffCommand(e,["diff","--binary","--find-renames",t,"--"]),a=parseNumstatOutput(await runGitDiffCommand(e,["diff","--numstat","--find-renames",t,"--"])),s=await getUntrackedFiles(e),i=await Promise.all(s.map(t=>runGitDiffCommand(e,["diff","--no-index","--binary","--","/dev/null",t]))),o=parseNumstatOutput((await Promise.all(s.map(t=>runGitDiffCommand(e,["diff","--no-index","--numstat","--","/dev/null",t])))).join("\n")),r=normalizePatch([n,...i].filter(Boolean).join("\n"));return r?{patch:r,stats:buildDiffStats([...a,...o]),artifactVersion:createArtifactVersion(t,r)}:null}async function getCurrentBranch(e){const t=createGit(e);return(await t.revparse(["--abbrev-ref","HEAD"])).trim()}async function gitPush(e,t,n=!1){const a=createGit(e),s=n?["--force"]:[];await a.push("origin",t,s)}async function hasUnpushedCommits(e,t){const n=createGit(e);try{return(await n.log([`origin/${t}..HEAD`])).total>0}catch{return!0}}async function updateRemoteUrl(e,t,n){const a=createGit(e);await a.remote(["set-url",t,n])}function sanitizeGitRemoteUrl(e){try{const t=new URL(e);return t.username="",t.password="",t.toString()}catch{return e}}async function ensureRemote(e,t,n){const a=createGit(e),s=(await a.getRemotes(!0)).find(e=>e.name===t);s?s.refs.fetch!==n&&await updateRemoteUrl(e,t,n):await a.addRemote(t,n)}async function listRemoteBranches(e,t="origin"){const{stdout:n}=await execFileAsync$5("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)}async function forceRefreshLocalBranchToStartPoint(e,t,n){await execFileAsync$5("git",["checkout","--force","-B",t,n],{cwd:e,windowsHide:!0}),await execFileAsync$5("git",["reset","--hard",n],{cwd:e,windowsHide:!0}),await execFileAsync$5("git",["clean","-fd"],{cwd:e,windowsHide:!0})}function parseRemoteInfoFromUrl(e){const t=e.match(/^git@([^:]+):(.+)\/(.+?)(?:\.git)?$/);if(t){const[,n,a,s]=t;return{url:e,host:n.split("-")[0],owner:a,repo:s}}const n=e.match(/^https?:\/\/([^/]+)\/(.+)\/(.+?)(?:\.git)?$/);if(n){const[,t,a,s]=n;return{url:e,host:t,owner:a,repo:s}}return null}async function getRemoteInfo(e){try{const t=createGit(e),n=(await t.getRemotes(!0)).find(e=>"origin"===e.name);return n?.refs?.fetch?parseRemoteInfoFromUrl(n.refs.fetch):null}catch(e){return console.error("[GIT] Failed to get remote info:",e),null}}const DEFAULT_GIT_HTTP_USERNAME="oauth2",ASKPASS_USERNAME_ENV="AGENTRIX_GIT_USERNAME",ASKPASS_PASSWORD_ENV="AGENTRIX_GIT_PASSWORD";function createAskPassScript(){const e=path.join(os.tmpdir(),`git-askpass-${node_crypto.randomUUID()}.sh`);return fs.writeFileSync(e,`#!/bin/sh\ncase "$1" in\n *Username*|*username*) printf '%s\\n' "\${${ASKPASS_USERNAME_ENV}:-oauth2}" ;;\n *) printf '%s\\n' "\${${ASKPASS_PASSWORD_ENV}:-}" ;;\nesac\n`,{mode:448}),e}function askPassEnv(e,t,n="oauth2"){return{...process.env,GIT_ASKPASS:e,GIT_TERMINAL_PROMPT:"0",[ASKPASS_USERNAME_ENV]:n,[ASKPASS_PASSWORD_ENV]:t}}function nonInteractiveGitEnv(){const e={...process.env};return delete e.GIT_ASKPASS,delete e.SSH_ASKPASS,delete e.VSCODE_GIT_ASKPASS_NODE,delete e.VSCODE_GIT_ASKPASS_MAIN,delete e.VSCODE_GIT_ASKPASS_EXTRA_ARGS,e.GIT_TERMINAL_PROMPT="0",e}async function cloneWithAskPass(e,t,n){const a=path.dirname(n);fs.existsSync(a)||fs.mkdirSync(a,{recursive:!0});const s=createAskPassScript();try{await execFileAsync$5("git",["-c","credential.helper=","clone",t,n],{env:askPassEnv(s,e),windowsHide:!0})}finally{fs.unlinkSync(s)}}async function pushWithAskPass(e,t,n,a=!1){const s=createAskPassScript();try{const i=["-c","credential.helper=","push","origin",n];a&&i.push("--force"),await execFileAsync$5("git",i,{cwd:t,env:askPassEnv(s,e),windowsHide:!0})}finally{fs.unlinkSync(s)}}async function fetchWithAskPass(e,t){const n=createAskPassScript();try{await execFileAsync$5("git",["-c","credential.helper=","fetch","--prune","origin"],{cwd:t,env:askPassEnv(n,e),windowsHide:!0})}finally{fs.unlinkSync(n)}}async function fetchWithRemoteUrl(e,t){await execFileAsync$5("git",["-c","credential.helper=","fetch","--prune",e,"+refs/heads/*:refs/remotes/origin/*","+refs/tags/*:refs/tags/*"],{cwd:t,env:nonInteractiveGitEnv(),windowsHide:!0})}async function pushWithRemoteUrl(e,t,n,a=!1){const s=["-c","credential.helper=","push",e,n];a&&s.push("--force"),await execFileAsync$5("git",s,{cwd:t,env:nonInteractiveGitEnv(),windowsHide:!0})}const execFileAsync$4=node_util.promisify(node_child_process.execFile),COMPANION_GIT_SERVER_ID="github",COMPANION_REPOSITORY_OWNER="xmz-ai",COMPANION_REPOSITORY_NAME="agentrix-agent",COMPANION_TEMPLATE_AGENT_ID="companion",COMPANION_FALLBACK_GIT_URL="https://github.com/xmz-ai/agentrix-agent.git",COMPANION_FALLBACK_BRANCH="main";async function fetchCompanionGitUrl(e){const t=`${machine.machine.serverUrl}/v1/agents/${encodeURIComponent("companion")}/git-url`;try{const n=await fetch(t,{headers:{Authorization:`Bearer ${e}`}});return n.ok?n.json():null}catch{return null}}async function resolveCompanionGitSource(e){if(e?.token){const t=await fetchCompanionGitUrl(e.token);if(t?.gitUrl)return{gitUrl:t.gitUrl,branch:t.branch||"main"}}return{gitUrl:COMPANION_FALLBACK_GIT_URL,branch:"main"}}async function cloneCompanionRepository(e,t,n){await execFileAsync$4("git",["clone","--depth=1","--branch",t,e,n]),await ensureRemote(n,"origin",sanitizeGitRemoteUrl(e))}async function pullCompanionRepository(e,t,n){await execFileAsync$4("git",["fetch","--depth=1",e,t],{cwd:n}),await execFileAsync$4("git",["merge","--ff-only","FETCH_HEAD"],{cwd:n}),await ensureRemote(n,"origin",sanitizeGitRemoteUrl(e))}function isRecoverableCheckoutHistoryError(e){const t=e instanceof Error?e.message:String(e);return t.includes("refusing to merge unrelated histories")||t.includes("Not possible to fast-forward")||t.includes("non-fast-forward")}async function replaceCompanionRepository(e,t,n){const a=path.join(path.dirname(n),`.agentrix-agent.tmp-${process.pid}-${Date.now()}`);try{await cloneCompanionRepository(e,t,a),fs.rmSync(n,{recursive:!0,force:!0}),fs.renameSync(a,n)}catch(e){throw fs.rmSync(a,{recursive:!0,force:!0}),e}}async function prepareCompanionTemplateRepository(e){const t=machine.machine.resolveRepoStoreCheckoutDir("github","xmz-ai","agentrix-agent"),n=path.join(t,"companion"),a=machine.machine.resolveRepoStoreLockPath("github","xmz-ai","agentrix-agent"),s=await machine.machine.acquireFileLock(a);if(!s)throw new Error(`Timed out waiting for Companion template repository lock at ${a}`);try{const{gitUrl:a,branch:s}=await resolveCompanionGitSource(e);if(!await isGitRepository(t)){if(!isDirectoryEmpty(t))return{path:t,companionDir:n,pullSucceeded:!1,error:`Companion template checkout exists but is not a git repository: ${t}`};try{return await cloneCompanionRepository(a,s,t),{path:t,companionDir:n,pullSucceeded:!0}}catch(e){return{path:t,companionDir:n,pullSucceeded:!1,error:e instanceof Error?e.message:String(e)}}}try{return await pullCompanionRepository(a,s,t),{path:t,companionDir:n,pullSucceeded:!0}}catch(e){if(isRecoverableCheckoutHistoryError(e))try{return await replaceCompanionRepository(a,s,t),{path:t,companionDir:n,pullSucceeded:!0}}catch(a){return{path:t,companionDir:n,pullSucceeded:!1,error:`${e instanceof Error?e.message:String(e)}; failed to replace checkout: ${a instanceof Error?a.message:String(a)}`}}return{path:t,companionDir:n,pullSucceeded:!1,error:e instanceof Error?e.message:String(e)}}}finally{await machine.machine.releaseFileLock(a,s)}}const TEMPLATE_LANGUAGE_MARKER_RELATIVE_PATH="versions/.companion-template-language.json";function ensureDir(e){fs.existsSync(e)||fs.mkdirSync(e,{recursive:!0})}function normalizeRelativePath(e){return e.split("\\").join("/")}function readTemplatesInDirectory(e){const t={};if(!fs.existsSync(e))return t;const n=a=>{const s=fs.readdirSync(a).sort();for(const i of s){const s=path.join(a,i);if(fs.statSync(s).isDirectory()){n(s);continue}if("versions.json"===i)continue;const o=normalizeRelativePath(path.relative(e,s));t[o]=fs.readFileSync(s,"utf-8")}};return n(e),t}function readVersionMetadata(e,t){const n=path.join(t,"template","versions",`${e}.json`);if(!fs.existsSync(n))return{};try{const e=fs.readFileSync(n,"utf-8");return JSON.parse(e)}catch(e){return console.warn(`[Companion] Failed to parse ${n}:`,e),{}}}function resolveCompanionTemplateLanguage(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"}function isCompanionTemplateLanguage(e){return"en"===e||"zh-Hans"===e}function getTemplateLanguageMarkerPath(e){return path.join(e,TEMPLATE_LANGUAGE_MARKER_RELATIVE_PATH)}function readTemplateLanguageMarker(e){const t=getTemplateLanguageMarkerPath(e);if(!fs.existsSync(t))return null;try{const e=JSON.parse(fs.readFileSync(t,"utf-8"));return isCompanionTemplateLanguage(e.language)?e.language:null}catch{return null}}function inferTemplateLanguageFromInstalledFiles(e){const t=path.join(e,"claude","HEARTBEAT.md");if(!fs.existsSync(t))return null;const n=fs.readFileSync(t,"utf-8");return/[\u3400-\u9fff]/.test(n)||n.includes("# 心跳")?"zh-Hans":n.includes("# Heartbeat")||n.includes("## Routine")?"en":null}function resolveInstalledTemplateLanguage(e,t,n){if(n)return{language:t,source:"initial-install",verified:!0};const a=readTemplateLanguageMarker(e);if(a)return{language:a,source:"marker",verified:!0};const s=inferTemplateLanguageFromInstalledFiles(e);return s?{language:s,source:"inferred",verified:!0}:{language:t,source:"unverified",verified:!1}}function writeTemplateLanguageMarker(e,t,n){if("unverified"===n)return;const a=getTemplateLanguageMarkerPath(e);ensureDir(path.dirname(a)),fs.writeFileSync(a,JSON.stringify({language:t,source:n,updatedAt:(new Date).toISOString()},null,2),"utf-8")}function getTemplatesForLanguage(e,t,n){const a=resolveCompanionTemplateLanguage(e),s=readVersionMetadata("common",t),i=readVersionMetadata(a,t),o=[],r={version:"1.0.0",updateStrategy:"create-only"};for(const[e,n]of Object.entries(s)){const a=path.join(t,e);fs.existsSync(a)&&o.push({relativePath:e,content:fs.readFileSync(a,"utf-8"),metadata:n,language:"common",sourcePath:a})}const c=path.join(t,"template","languages",a),l=readTemplatesInDirectory(c);for(const[e,t]of Object.entries(l)){const s=i[e]||(n?r:void 0);s&&o.push({relativePath:e,content:t,metadata:s,language:a,sourcePath:path.join(c,e)})}if(0===o.length)throw new Error(`Companion template files are missing in ${t}`);return{language:a,templates:o}}async function ensureCompanionAgent(e){const t=machine.machine.agentrixAgentsHomeDir,n=path.join(t,"companion"),a=path.join(n,"claude"),s=!fs.existsSync(path.join(n,"agent.json")),i=await prepareCompanionTemplateRepository(e?.credentials);let o=fs.existsSync(path.join(i.companionDir,"agent.json"))?i.companionDir:n;if(i.pullSucceeded||console.warn("[Companion] Template repository update failed:",i.error||"unknown error"),s){const e=await probeCompanionChain();if(!e.success)throw new Error(`Companion probe failed: ${e.error||"Unknown error"}`);if(fs.existsSync(path.join(o,"agent.json")))fs.cpSync(o,n,{recursive:!0}),buildAgentPlugins(n),console.log("[Companion] Installed from template repository");else try{await installAgentFromGit({agentId:"companion",gitUrl:COMPANION_FALLBACK_GIT_URL,branch:"main",subDir:"companion"}),console.log("[Companion] Installed from git fallback")}catch(e){console.warn("[Companion] Git install failed, will retry next boot:",e instanceof Error?e.message:e)}fs.existsSync(path.join(n,"agent.json"))||(console.log("[Companion] Falling back to public repo install..."),await installAgentFromGit({agentId:"companion",gitUrl:COMPANION_FALLBACK_GIT_URL,branch:"main",subDir:"companion"})),o=fs.existsSync(path.join(i.companionDir,"agent.json"))?i.companionDir:n}ensureDir(path.join(a,"memory"));const r=resolveCompanionTemplateLanguage(e?.preferredLanguage),c=resolveInstalledTemplateLanguage(n,r,s);"marker"===c.source&&c.language!==r&&console.log(`[Companion] Using installed template language ${c.language}; requested language ${r} ignored for safe upgrades`),c.verified||console.warn(`[Companion] Could not safely determine installed template language; language-specific pending upgrades will be diagnostic-only. Requested language: ${r}`);const{language:l,templates:d}=getTemplatesForLanguage(c.language,o,s);writeTemplateLanguageMarker(n,l,c.source);const p=[];for(const e of d){const t=installTemplateFile(path.join(n,e.relativePath),e,n);if(p.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}`)}}p.some(e=>e.updated&&(e.path.startsWith("claude/plugins/")||e.path.startsWith("claude/hooks/")))&&(buildAgentPlugins(n),console.log("[Companion] Rebuilt plugins after template updates"));const{pendingUpgrades:u,blockedUpgrades:m}=checkPendingUpgrades(d,n,{currentLanguage:l,languageVerified:c.verified});if(u.length>0||m.length>0)try{const e=path.join(a,"UPGRADES.md"),t=generateUpgradeNotification({pendingUpgrades:u,blockedUpgrades:m,agentDir:n,language:l,languageSource:c.source});fs.writeFileSync(e,t,"utf-8");for(const e of u)fs.writeFileSync(e.upgradePath,generateUpgradeFileContent(e),"utf-8");console.log(`[Companion] Created UPGRADES.md with ${u.length} pending upgrade(s) and ${m.length} blocked upgrade(s)`),console.log("[Companion] Shadow will process upgrades 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: ${l}`),{agentDir:n,homeDir:a}}const MIGRATIONS=[{version:1,fileName:"001_init.sql"}];function getTaskDb(e){return createTaskDb(resolveDbPath(e.dataDir),e.taskId)}function resolveDbPath(e){return path$1.join(e,"data.bin")}function createTaskDb(e,t){const n=new Database(e),a=new events.EventEmitter;n.pragma("journal_mode = WAL"),migrateSchema(n);const s=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 * FROM task_event\n WHERE event_type = 'task-message'\n ORDER BY COALESCE(sequence, 0) DESC, rowid DESC\n LIMIT ?\n "),d=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 "),u=n.prepare("\n SELECT * FROM task_message\n WHERE local_sequence > ?\n ORDER BY local_sequence ASC\n LIMIT ?\n "),m=n.prepare("\n SELECT * FROM task_message\n WHERE local_sequence < ?\n ORDER BY local_sequence DESC\n LIMIT ?\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 1 as has_row\n FROM task_message\n WHERE local_sequence > ?\n LIMIT 1\n "),f=n.prepare("\n SELECT * FROM task_message\n WHERE local_sequence > ?\n ORDER BY local_sequence DESC\n LIMIT ?\n "),y=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 "),b=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??shared.createEventId(),o=(new Date).toISOString(),r=s.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&&a.emit("message-saved",{eventId:n}),{eventId:n,localSequence:l,inserted:r}},saveTaskEvent:e=>{const t=e.eventId??shared.createEventId(),n=(new Date).toISOString(),a={...e.eventData,eventId:t};return o.run({eventId:t,taskId:e.taskId,chatId:e.chatId,sequence:e.sequence,eventType:e.eventType,eventData:JSON.stringify(a),createdAt:n}),t},updateTaskEventSequence:(e,t)=>{r.run(t,e,t)},pageTaskEventsAfter:(e,t)=>{const n=c.all(e,t).map(parseTaskEventRow),a=n.at(-1)?.sequence??null;return{data:n,hasMore:null!==a&&Boolean(d.get(a))}},pageRecentTaskEvents:e=>{const t=l.all(e);return{data:t.map(parseTaskEventRow).reverse(),hasMore:t.length>=e}},getLatestTaskEvent:e=>{if(0===e.length)return null;const t=e.map(()=>"?").join(","),a=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 a?parseTaskEventRow(a):null},pageRecentMessages:e=>{const t=p.all(e).map(parseTaskMessageRow).reverse(),n=t[0]?.localSequence??null;return{data:t,hasMore:!!n&&Boolean(h.get(n))}},pageMessagesAfter:(e,t)=>{const n=u.all(e,t).map(parseTaskMessageRow),a=n.at(-1)?.localSequence??null;return{data:n,hasMore:!!a&&Boolean(g.get(a))}},pageMessagesBefore:(e,t)=>{const n=m.all(e,t).map(parseTaskMessageRow).reverse(),a=n[0]?.localSequence??null;return{data:n,hasMore:!!a&&Boolean(h.get(a))}},pageRecentMessagesAfter:(e,t)=>{const n=f.all(e,t).map(parseTaskMessageRow).reverse(),a=n[0]?.localSequence??null;return{data:n,hasMore:!!a&&Boolean(h.get(a))}},getAgentSessions:()=>{const e=y.all(),t=new Map;for(const n of e)t.set(n.agent_id,n.session_id);return t},getAgentLastSequences:()=>{const e=y.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)=>{b.run(e,t,n,(new Date).toISOString())},on:(e,t)=>{a.on(e,t)},off:(e,t)=>{a.off(e,t)},close:()=>{a.removeAllListeners(),n.close()}}}function migrateSchema(e){const t=resolveMigrationsDir(),n=e.pragma("user_version",{simple:!0}),a=loadMigrationSql(t,MIGRATIONS[0].fileName);e.exec(a),n<MIGRATIONS[0].version&&e.pragma(`user_version = ${MIGRATIONS[0].version}`)}function resolveMigrationsDir(){const e=path$1.dirname(url.fileURLToPath("undefined"==typeof document?require("url").pathToFileURL(__filename).href:_documentCurrentScript&&"SCRIPT"===_documentCurrentScript.tagName.toUpperCase()&&_documentCurrentScript.src||new URL("index.cjs",document.baseURI).href)),t=[path$1.join(e,"migrations"),path$1.join(process.cwd(),"dist","migrations"),path$1.join(process.cwd(),"src","worker","history","migrations")];for(const e of t)if(fs$1.existsSync(e))return e;throw new Error(`Task history migrations directory not found at ${t[0]}`)}function loadMigrationSql(e,t){const n=path$1.join(e,t);return fs$1.readFileSync(n,"utf8")}function parseTaskMessageRow(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 parseTaskEventRow(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 DEFAULT_HEARTBEAT_INTERVAL_MS=9e5,DEFAULT_INITIAL_DELAY_MS=6e4,DEFAULT_MEMORY_ORGANIZATION_INTERVAL_HOURS=4,ALLOWED_MEMORY_ORGANIZATION_INTERVAL_HOURS=[1,2,4,6,8,12,24];function isAllowedMemoryOrganizationIntervalHours(e){return"number"==typeof e&&ALLOWED_MEMORY_ORGANIZATION_INTERVAL_HOURS.includes(e)}function normalizeMemoryOrganizationIntervalHours(e){return isAllowedMemoryOrganizationIntervalHours(e)?e:4}class CompanionScheduler{constructor(e,t,n={}){this.client=e,this.machineId=t;const a=machine.machine.agentrixAgentsHomeDir,s=path.join(a,"companion","claude");this.stateFilePath=n.stateFilePath??path.join(s,"state.json"),this.initialDelayMs=n.initialDelayMs??6e4}timer=null;initialDelay=null;intervalMs=9e5;enabled=!1;heartbeatTaskId=null;memoryOrganizationEnabled=!1;memoryOrganizationIntervalHours=4;memoryOrganizationTaskId=null;companionState=null;stateFilePath;initialDelayMs;started=!1;cronJobs=new Map;start(){this.started?this.reloadStateAndReschedule():(this.started=!0,this.loadState(),this.companionState?(machine.logger.info(`[COMPANION SCHEDULER] Ready: agent=${this.companionState.agentId}, chatId=${this.companionState.chatId}`),this.restoreScheduledTasks()):machine.logger.warn("[COMPANION SCHEDULER] No state.json found (companion not registered yet), will keep checking"),machine.logger.info(`[COMPANION SCHEDULER] Starting with interval ${this.intervalMs}ms`),this.initialDelay=setTimeout(()=>{this.initialDelay=null,this.tick(),this.scheduleNext()},this.initialDelayMs))}stop(){this.started=!1,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(),machine.logger.debug(`[COMPANION SCHEDULER] Stopped cron job: ${e}`);this.cronJobs.clear(),machine.logger.info("[COMPANION SCHEDULER] Stopped")}scheduleNext(){this.started&&(this.timer&&(clearTimeout(this.timer),this.timer=null),this.timer=setTimeout(()=>{this.timer=null,this.tick(),this.scheduleNext()},this.intervalMs))}reloadStateAndReschedule(){this.loadState()}reschedulePendingHeartbeatTimer(){this.initialDelay&&(clearTimeout(this.initialDelay),this.initialDelay=null),this.scheduleNext(),machine.logger.info(`[COMPANION SCHEDULER] Rescheduled pending heartbeat timer with interval ${this.intervalMs}ms`)}setHeartbeatTaskId(e){this.heartbeatTaskId=e,this.saveStateField("heartbeatTaskId",e)}clearHeartbeatTaskId(){this.heartbeatTaskId=null,this.saveStateField("heartbeatTaskId",void 0),machine.logger.info("[COMPANION SCHEDULER] Cleared heartbeat task ID")}setMemoryOrganizationTaskId(e){this.memoryOrganizationTaskId=e,this.saveStateField("memoryOrganizationTaskId",e)}clearMemoryOrganizationTaskId(){this.memoryOrganizationTaskId=null,this.saveStateField("memoryOrganizationTaskId",void 0),machine.logger.info("[COMPANION SCHEDULER] Cleared memory organization task ID")}recordInteraction(e){if(!this.companionState?.chatId||e!==this.companionState.chatId)return;const t=(new Date).toISOString();this.saveStateField("lastInteractionTimestamp",t),machine.logger.debug(`[COMPANION SCHEDULER] Recorded interaction at ${t}`)}loadState(){try{if(fs.existsSync(this.stateFilePath)){this.companionState=JSON.parse(fs.readFileSync(this.stateFilePath,"utf-8"));const e=this.intervalMs,t=this.companionState?.heartbeatIntervalMs??9e5;t!==this.intervalMs&&(machine.logger.info(`[COMPANION SCHEDULER] Interval changed: ${this.intervalMs}ms -> ${t}ms`),this.intervalMs=t,this.started&&(this.timer||this.initialDelay)&&e!==this.intervalMs&&this.reschedulePendingHeartbeatTimer()),this.enabled=this.companionState?.heartbeatEnabled??!1,this.heartbeatTaskId=this.companionState?.heartbeatTaskId??null,this.memoryOrganizationEnabled=this.companionState?.memoryOrganizationEnabled??!1,this.memoryOrganizationIntervalHours=normalizeMemoryOrganizationIntervalHours(this.companionState?.memoryOrganizationIntervalHours),this.memoryOrganizationTaskId=this.companionState?.memoryOrganizationTaskId??null,machine.logger.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"}, memoryOrganizationEnabled=${this.memoryOrganizationEnabled}, memoryOrganizationIntervalHours=${this.memoryOrganizationIntervalHours}, memoryOrganizationTaskId=${this.memoryOrganizationTaskId??"none"}`)}}catch(e){machine.logger.warn("[COMPANION SCHEDULER] Failed to load state.json",e)}}saveStateField(e,t){try{let n={};fs.existsSync(this.stateFilePath)&&(n=JSON.parse(fs.readFileSync(this.stateFilePath,"utf-8"))),void 0===t?delete n[e]:n[e]=t;const a=path.dirname(this.stateFilePath);fs.existsSync(a)||fs.mkdirSync(a,{recursive:!0}),fs.writeFileSync(this.stateFilePath,JSON.stringify(n,null,2),"utf-8"),machine.logger.debug(`[COMPANION SCHEDULER] Saved state field: ${e}=${t??"removed"}`)}catch(t){machine.logger.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")}`}isMemoryOrganizationDue(e,t){if(!this.memoryOrganizationEnabled)return!1;if(!(e.agentId&&e.machineId&&e.userId&&e.chatId))return!1;if(!e.lastMemoryOrganizationTimestamp)return!0;const n=new Date(e.lastMemoryOrganizationTimestamp).getTime();if(Number.isNaN(n))return!0;const a=60*this.memoryOrganizationIntervalHours*60*1e3;return t.getTime()-n>=a}triggerMemoryOrganization(e,t){const n=t.toISOString();this.saveStateField("lastMemoryOrganizationTimestamp",n);const a=t.toLocaleString(),s={type:"companion_memory_organization",timestamp:n,trigger:"scheduled",triggerTime:a,intervalHours:this.memoryOrganizationIntervalHours};if(this.memoryOrganizationTaskId)return machine.logger.debug(`[COMPANION SCHEDULER] Sending memory organization to existing task ${this.memoryOrganizationTaskId}`),void this.client.send("task-message",{eventId:shared.createEventId(),taskId:this.memoryOrganizationTaskId,chatId:e.chatId,from:"machine",message:s,senderType:"system",senderId:"system",senderName:"system"});machine.logger.debug("[COMPANION SCHEDULER] Requesting initial memory organization task"),this.client.send("request-companion-memory-organization",{eventId:shared.createEventId(),machineId:e.machineId,agentId:e.agentId,chatId:e.chatId,userId:e.userId,timestamp:n,trigger:"scheduled",triggerTime:a,intervalHours:this.memoryOrganizationIntervalHours})}addScheduledTask(e){const t={id:node_crypto.randomUUID(),...e,createdAt:(new Date).toISOString()};this.loadState();const n=this.companionState?.scheduledTasks??[];return n.push(t),this.saveStateField("scheduledTasks",n),this.startCronJob(t),machine.logger.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 a=this.cronJobs.get(e);return a&&(a.stop(),this.cronJobs.delete(e)),machine.logger.info(`[COMPANION SCHEDULER] Deleted scheduled task: id=${e}`),!0}startCronJob(e){try{const t={},n="utc"===e.timeType;let a;if(e.due){if(n){const n=new Date(e.due);a=`${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 machine.logger.warn(`[COMPANION SCHEDULER] Cannot parse due date: ${e.due}, skipping: ${e.id}`);a=`${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 machine.logger.warn(`[COMPANION SCHEDULER] Invalid task entry, skipping: ${e.id}`);a=e.cron,n?t.timezone="Etc/UTC":e.timezone&&(t.timezone=e.timezone)}const s=new croner.Cron(a,t,()=>{this.onScheduledTaskFired(e)});this.cronJobs.set(e.id,s),machine.logger.debug(`[COMPANION SCHEDULER] Started cron job: id=${e.id}, pattern="${a}"`)}catch(t){machine.logger.warn(`[COMPANION SCHEDULER] Failed to start cron job for task ${e.id}`,t)}}onScheduledTaskFired(e){machine.logger.info(`[COMPANION SCHEDULER] Scheduled task fired: id=${e.id}, task="${e.task}"`),this.loadState();const t=this.companionState;if(!t?.chatId)return;const n=t.chatTaskId??t.chatId;this.client.send("task-message",{eventId:shared.createEventId(),taskId:n,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()?machine.logger.debug(`[COMPANION SCHEDULER] Skipping expired one-time task: ${n.id}`):(this.startCronJob(n),t++);machine.logger.info(`[COMPANION SCHEDULER] Restored ${t}/${e.length} scheduled tasks`)}tick(){if(this.loadState(),!this.companionState)return void machine.logger.debug("[COMPANION SCHEDULER] Still no state.json, skipping heartbeat");const e=this.companionState,t=[],n=new Date;if(this.isMemoryOrganizationDue(e,n)&&(machine.logger.info("[COMPANION SCHEDULER] Memory organization triggered"),this.triggerMemoryOrganization(e,n)),!this.enabled)return void machine.logger.debug("[COMPANION SCHEDULER] Heartbeat disabled, skipping");e.lastInteractionTimestamp&&(!e.lastHeartbeatTimestamp||new Date(e.lastInteractionTimestamp).getTime()>new Date(e.lastHeartbeatTimestamp).getTime())&&t.push("new_interaction");const a=this.getTodayDateString();if(e.lastHeartbeatDate!==a&&t.push("first_today"),0===t.length)return void machine.logger.debug("[COMPANION SCHEDULER] No trigger conditions met, skipping heartbeat");machine.logger.info(`[COMPANION SCHEDULER] Heartbeat triggered: ${t.join(", ")}`);const s=("number"==typeof e.heartbeatTriggerCount?e.heartbeatTriggerCount:0)+1;this.saveStateField("lastHeartbeatTimestamp",n.toISOString()),this.saveStateField("lastHeartbeatDate",a),this.saveStateField("heartbeatTriggerCount",s);const i=n.toLocaleString(),o={type:"companion_heartbeat",timestamp:n.toISOString(),triggerTime:i,triggerReasons:t,heartbeatTriggerCount:s};this.heartbeatTaskId?(machine.logger.debug(`[COMPANION SCHEDULER] Sending heartbeat to existing task ${this.heartbeatTaskId}`),this.client.send("task-message",{eventId:shared.createEventId(),taskId:this.heartbeatTaskId,chatId:e.chatId,from:"machine",message:o,senderType:"system",senderId:"system",senderName:"system"})):(machine.logger.debug("[COMPANION SCHEDULER] Requesting new heartbeat task"),this.client.send("request-companion-heartbeat",{eventId:shared.createEventId(),machineId:e.machineId,agentId:e.agentId,chatId:e.chatId,userId:e.userId,timestamp:n.toISOString(),triggerTime:i,triggerReasons:t,heartbeatTriggerCount:s}))}}const store=new node.GitServerLocalStore({credentialsDir:path.join(machine.machine.agentrixHomeDir,"credentials")});async function getGitServerEncryptionKey(){const e=await machine.machine.readCredentials();return e?.secret?node.deriveLocalGitServerEncryptionKey(e.secret):null}function saveGitServerConfig(e,t){store.saveGitServerConfig(e,t)}function loadGitServerConfig(e){return store.loadGitServerConfig(e)}function loadGitLabWebhookBridgeSecrets(e,t){return store.loadGitLabWebhookBridgeSecrets(e,t)}function saveGitLabWebhookBridgeSecrets(e,t,n){store.saveGitLabWebhookBridgeSecrets(e,t,n)}function ensureGitLabWebhookSecret(e,t){return store.ensureGitLabWebhookSecret(e,t)}function loadPatMeta(e){return store.loadPatMeta(e)}function savePatMeta(e,t){store.savePatMeta(e,t)}function savePat(e,t,n){store.savePat(e,t,n)}function loadPat(e,t){return store.loadPat(e,t)}function hasPat(e){return store.hasPat(e)}const DEFAULT_BASE_URL="https://ilinkai.weixin.qq.com",WECHAT_CDN_BASE_URL="https://novac2c.cdn.weixin.qq.com/c2c",DEFAULT_POLL_TIMEOUT_MS=3e4,DEFAULT_REQUEST_TIMEOUT_MS=4e4,INITIAL_RETRY_DELAY_MS$1=1e3,MAX_RETRY_DELAY_MS$1=3e4,BOT_MESSAGE_TYPE=2,FINISH_MESSAGE_STATE=2,TEXT_ITEM_TYPE=1,IMAGE_ITEM_TYPE=2,FILE_ITEM_TYPE=4,IMAGE_MEDIA_TYPE=1,FILE_MEDIA_TYPE=3,WECHAT_CDN_ENCRYPT_TYPE=1,require$1=node_module.createRequire("undefined"==typeof document?require("url").pathToFileURL(__filename).href:_documentCurrentScript&&"SCRIPT"===_documentCurrentScript.tagName.toUpperCase()&&_documentCurrentScript.src||new URL("index.cjs",document.baseURI).href),qrcodeTerminal=require$1("qrcode-terminal");function requireString$2(e,t){if("string"!=typeof e||0===e.trim().length)throw new Error(`WeChat credential "${t}" is required`);return e.trim()}function optionalString$1(e){return"string"==typeof e&&e.trim().length>0?e.trim():void 0}function optionalNumber(e,t){if("number"==typeof e&&Number.isFinite(e)&&e>0)return e;if("string"==typeof e){const t=Number(e);if(Number.isFinite(t)&&t>0)return t}return t}function parseCredentials$2(e){const t=optionalString$1(e.token)??optionalString$1(e.botToken)??optionalString$1(e.bot_token)??optionalString$1(e.apiKey)??optionalString$1(e.api_key);return{baseUrl:optionalString$1(e.baseUrl)??optionalString$1(e.base_url)??DEFAULT_BASE_URL,token:t||requireString$2(t,"token"),routeTag:optionalString$1(e.routeTag)??optionalString$1(e.route_tag),getUpdatesBuf:optionalString$1(e.getUpdatesBuf)??optionalString$1(e.get_updates_buf)??"",channelVersion:optionalString$1(e.channelVersion)??optionalString$1(e.channel_version)??"1.0.0",pollTimeoutMs:optionalNumber(e.pollTimeoutMs??e.poll_timeout_ms,3e4),requestTimeoutMs:optionalNumber(e.requestTimeoutMs??e.request_timeout_ms,4e4),fileDownloadEndpoint:optionalString$1(e.fileDownloadEndpoint)??optionalString$1(e.file_download_endpoint)??optionalString$1(e.downloadEndpoint)??optionalString$1(e.download_endpoint)??"downloadfile"}}function normalizeTimestamp$1(e){if("number"==typeof e||"string"==typeof e){const t=Number(e);if(Number.isFinite(t))return new Date(t>1e10?t:1e3*t).toISOString();const n=new Date(e);if(!Number.isNaN(n.getTime()))return n.toISOString()}return(new Date).toISOString()}function getStringField(e,t){for(const n of t){const t=e[n];if("string"==typeof t&&t.trim())return t}}function getTextContent$1(e){if("string"==typeof e.text)return e.text;if("string"==typeof e.content)return e.content;if(e.text_item?.text)return e.text_item.text;for(const t of e.item_list??[]){if("string"==typeof t.text)return t.text;if("string"==typeof t.text_item?.text)return t.text_item.text}}function getMessageItems(e){return e.item_list??[]}function inferMessageType$1(e){const t=String(e.message_type??e.msg_type??"").toLowerCase();if(t.includes("image"))return"image";if(t.includes("file"))return"file";if(t.includes("voice")||t.includes("audio"))return"voice";if(e.image_item)return"image";if(e.file_item)return"file";for(const t of getMessageItems(e)){const e=String(t.type??"").toLowerCase();if(t.image_item||e.includes("image"))return"image";if(t.file_item||e.includes("file"))return"file";if(e.includes("voice")||e.includes("audio"))return"voice"}return"text"}function getImageKey$1(e){if(e.image_item?.media?.full_url)return encodeWechatMediaKey(e.image_item.media,e.image_item.aeskey,"image.jpg");if(e.image_item?.url)return e.image_item.url;if(e.image_item?.file_id)return e.image_item.file_id;if(e.image_item?.image_key)return e.image_item.image_key;for(const t of e.item_list??[]){if(t.image_item?.media?.full_url)return encodeWechatMediaKey(t.image_item.media,t.image_item.aeskey,"image.jpg");if(t.image_item?.url)return t.image_item.url;if(t.image_item?.file_id)return t.image_item.file_id;if(t.image_item?.image_key)return t.image_item.image_key}}function getFileData(e){if(e.file_item){const t=e.file_item.file_name??e.file_item.name;return{fileKey:e.file_item.media?.full_url?encodeWechatMediaKey(e.file_item.media,void 0,t):e.file_item.file_id??e.file_item.file_key,fileName:t}}for(const t of e.item_list??[])if(t.file_item){const e=t.file_item.file_name??t.file_item.name;return{fileKey:t.file_item.media?.full_url?encodeWechatMediaKey(t.file_item.media,void 0,e):t.file_item.file_id??t.file_item.file_key,fileName:e}}return{}}function encodeWechatMediaKey(e,t,n){const a={url:e.full_url||"",aesKey:e.aes_key||t,fileName:n};return`wechat-media:${Buffer.from(JSON.stringify(a)).toString("base64url")}`}function decodeWechatMediaKey(e){if(!e.startsWith("wechat-media:"))return null;try{const t=JSON.parse(Buffer.from(e.slice(13),"base64url").toString("utf-8"));return"string"==typeof t?.url&&t.url?{url:t.url,aesKey:"string"==typeof t.aesKey?t.aesKey:void 0,fileName:"string"==typeof t.fileName?t.fileName:void 0}:null}catch{return null}}function collectUpdates(e){return e?Array.isArray(e.updates)?e.updates:Array.isArray(e.msgs)?e.msgs:Array.isArray(e.message_list)?e.message_list:Array.isArray(e.items)?e.items:[]:[]}function getRetCode(e){return e.retcode??e.ret??e.errcode}function formatILinkError(e,t){const n=getRetCode(e);return[void 0===n?void 0:`ret=${n}`,e.errmsg||t].filter(Boolean).join(", ")}function buildApiUrl(e,t){const n=e.replace(/\/+$/,"");return n.endsWith("/ilink/bot")?`${n}/${t}`:`${n}/ilink/bot/${t}`}function renderTerminalQRCode(e){let t="";return qrcodeTerminal.generate(e,{small:!0},e=>{t=e}),t}class WechatAdapter{id;platform="wechat";capabilities={sendText:!0,sendImage:!0,sendFile:!0,sendAudio:!1,sendVideo:!1};messageHandler=null;stateHandler=null;connectionState="disconnected";credentials;polling=!1;pollController=null;pollPromise=null;retryTimer=null;resolveRetrySleep=null;retryDelayMs=1e3;contextTokens=new Map;clientId=node_crypto.randomBytes(8).toString("hex");constructor(e){this.id=e.id,this.credentials=parseCredentials$2(e.credentials)}static async createLoginQRCode(e={}){const t=e.baseUrl?.trim()||DEFAULT_BASE_URL,n={};e.routeTag?.trim()&&(n.SKRouteTag=e.routeTag.trim());const a=await fetch(`${buildApiUrl(t,"get_bot_qrcode")}?bot_type=3`,{method:"GET",headers:n}),s=await a.json().catch(()=>({}));if(!a.ok)throw new Error(`HTTP ${a.status}: ${JSON.stringify(s)}`);const i=getRetCode(s);if(i&&0!==i)throw new Error(formatILinkError(s,"WeChat QR login failed"));if(!s.qrcode||!s.qrcode_img_content)throw new Error("WeChat QR login response is missing qrcode data");return{qrcode:s.qrcode,qrcodeContent:s.qrcode_img_content,qrcodeTerminal:renderTerminalQRCode(s.qrcode_img_content),baseUrl:t}}static async getLoginStatus(e,t={}){const n=t.baseUrl?.trim()||DEFAULT_BASE_URL,a=await fetch(`${buildApiUrl(n,"get_qrcode_status")}?qrcode=${encodeURIComponent(e)}`,{method:"GET",headers:{"iLink-App-ClientVersion":"1"}}),s=await a.json().catch(()=>({}));if(!a.ok)throw new Error(`HTTP ${a.status}: ${JSON.stringify(s)}`);const i=getRetCode(s);if(i&&0!==i)throw new Error(formatILinkError(s,"WeChat QR status failed"));return{status:s.status||"wait",token:s.bot_token,baseUrl:s.baseurl,ilinkBotId:s.ilink_bot_id,ilinkUserId:s.ilink_user_id}}get state(){return this.connectionState}async connect(){"connected"!==this.connectionState&&"connecting"!==this.connectionState&&(this.polling=!0,this.retryDelayMs=1e3,this.setState("connecting"),this.pollPromise=this.pollLoop(),this.setState("connected"),machine.logger.info(`[CHANNEL][WECHAT] Connected: channel=${this.id}`))}async disconnect(){this.polling=!1,this.retryTimer&&(clearTimeout(this.retryTimer),this.retryTimer=null,this.resolveRetrySleep?.()),this.resolveRetrySleep=null,this.pollController?.abort(),this.pollController=null,await(this.pollPromise?.catch(()=>{})),this.pollPromise=null,this.setState("disconnected")}async sendMessage(e,t){const n=this.contextTokens.get(e);if(!n)throw new Error(`WeChat sendMessage requires an iLink context_token for chat ${e}; wait for this contact to send a message first`);const a=await this.request("sendmessage",{msg:{from_user_id:"",to_user_id:e,client_id:`agentrix-wechat:${Date.now()}-${node_crypto.randomBytes(4).toString("hex")}`,message_type:2,message_state:2,context_token:n,item_list:[{type:1,text_item:{text:t}}]}},{timeoutMs:this.credentials.requestTimeoutMs}),s=getRetCode(a);if(s&&0!==s)throw new Error(formatILinkError(a,"WeChat sendMessage failed"))}async sendChannelMessage(e,t){const n=t.content?.trim();n&&await this.sendMessage(e,n);for(const n of t.attachments??[])await this.sendAttachment(e,n)}async sendAttachment(e,t){const n=this.contextTokens.get(e);if(!n)throw new Error(`WeChat send attachment requires an iLink context_token for chat ${e}; wait for this contact to send a message first`);const a=t.fileName?.trim()||path.basename(t.filePath),s=await promises$1.readFile(t.filePath),i=this.resolveOutgoingKind(t),o="image"===i?1:3,r="image"===i?2:4,c=await this.uploadWechatMedia(e,s,a,o),l={full_url:c.fullUrl,aes_key:c.aesKey,encrypt_query_param:c.encryptQueryParam,encrypt_type:1},d="image"===i?{type:r,image_item:{media:l,aeskey:c.aesKeyHex,mid_size:c.encryptedSize}}:{type:r,file_item:{file_name:a,name:a,md5:c.md5,media:l,len:String(s.length)}},p=await this.request("sendmessage",{msg:{from_user_id:"",to_user_id:e,client_id:`agentrix-wechat:${Date.now()}-${node_crypto.randomBytes(4).toString("hex")}`,message_type:2,message_state:2,context_token:n,item_list:[d]}},{timeoutMs:this.credentials.requestTimeoutMs}),u=getRetCode(p);if(u&&0!==u)throw new Error(formatILinkError(p,"WeChat send attachment failed"))}resolveOutgoingKind(e){return"image"===e.kind?"image":e.kind&&"auto"!==e.kind&&"file"!==e.kind?"file":e.mimeType?.startsWith("image/")?"image":"file"}async uploadWechatMedia(e,t,n,a){const s=node_crypto.randomBytes(16).toString("hex"),i=node_crypto.randomBytes(16).toString("hex"),o=this.encryptWechatMedia(t,i),r=node_crypto.createHash("md5").update(t).digest("hex"),c=await this.request("getuploadurl",{media_type:a,to_user_id:e,filekey:s,rawsize:t.length,rawfilemd5:r,filesize:o.length,no_need_thumb:!0,aeskey:i},{timeoutMs:this.credentials.requestTimeoutMs}),l=getRetCode(c);if(l&&0!==l)throw new Error(formatILinkError(c,"WeChat getuploadurl failed"));const d=this.extractUploadParam(c),p=await fetch(`${WECHAT_CDN_BASE_URL}/upload?encrypted_query_param=${encodeURIComponent(d)}&filekey=${encodeURIComponent(s)}`,{method:"POST",headers:{"Content-Type":"application/octet-stream","Content-Length":String(o.length)},body:o});if(!p.ok){const e=await p.text().catch(()=>"");throw new Error(`WeChat CDN upload failed: HTTP ${p.status}: ${e||p.statusText}`)}const u=p.headers.get("x-encrypted-param");if(!u)throw new Error("WeChat CDN upload response missing x-encrypted-param");return{fullUrl:`${WECHAT_CDN_BASE_URL}/download?encrypted_query_param=${encodeURIComponent(u)}`,aesKey:Buffer.from(i,"utf-8").toString("base64"),aesKeyHex:i,encryptQueryParam:u,md5:r,encryptedSize:o.length}}extractUploadParam(e){const t=e.upload_param;if("string"==typeof t&&t.trim())return t.trim();const n=e.data;if(n&&"object"==typeof n){const e=n.upload_param;if("string"==typeof e&&e.trim())return e.trim()}throw new Error("WeChat getuploadurl response missing upload_param")}async getContacts(){return[]}async downloadFile(e,t={}){try{const n=decodeWechatMediaKey(e);if(n)return await this.downloadEncryptedMedia(n,t.fileName);if(/^https?:\/\//i.test(e))return await downloadUrlToChannelFile(e,t.fileName);const a=await this.requestDownloadFile(e);return await saveResponseToChannelFile(a,t.fileName||e)}catch(t){return machine.logger.warn(`[CHANNEL][WECHAT] Failed to download file: channel=${this.id}, fileKey=${e}`,t),null}}async getChatName(e){return e}async getUserName(e){return e}onMessage(e){this.messageHandler=e}onStateChange(e){this.stateHandler=e}setState(e,t){this.connectionState=e,this.stateHandler?.(e,t)}async pollLoop(){for(;this.polling;)try{const e=await this.request("getupdates",{get_updates_buf:this.credentials.getUpdatesBuf},{timeoutMs:Math.max(this.credentials.requestTimeoutMs,this.credentials.pollTimeoutMs+5e3)}),t=getRetCode(e);if(t&&0!==t)throw new Error(formatILinkError(e,"WeChat getupdates failed"));const n=e.data??e;this.credentials.getUpdatesBuf=n.get_updates_buf??this.credentials.getUpdatesBuf,this.retryDelayMs=1e3,"connected"!==this.connectionState&&this.setState("connected");for(const e of collectUpdates(n)){const t=this.normalizeMessage(e);t&&await(this.messageHandler?.(t))}}catch(e){if(!this.polling)break;if(this.isAbortError(e))continue;const t=e instanceof Error?e:new Error(String(e));machine.logger.warn(`[CHANNEL][WECHAT] Poll failed: channel=${this.id}, message=${t.message}`),this.setState("error",t),await this.sleepWithCancel(this.retryDelayMs),this.retryDelayMs=Math.min(2*this.retryDelayMs,3e4),this.polling&&this.setState("connecting")}}async request(e,t,n){const a=new AbortController;"getupdates"===e&&(this.pollController=a);const s=setTimeout(()=>a.abort(),n.timeoutMs);try{const n=this.buildHeaders(),s=await fetch(this.apiUrl(e),{method:"POST",headers:n,body:JSON.stringify({base_info:{channel_version:this.credentials.channelVersion},client_id:this.clientId,...t}),signal:a.signal}),i=await s.json().catch(()=>({}));if(!s.ok)throw new Error(`HTTP ${s.status}: ${JSON.stringify(i)}`);return i}finally{clearTimeout(s),"getupdates"===e&&this.pollController===a&&(this.pollController=null)}}async requestDownloadFile(e){const t=new AbortController,n=setTimeout(()=>t.abort(),this.credentials.requestTimeoutMs);try{const n=this.buildHeaders(),a=await fetch(this.apiUrl(this.credentials.fileDownloadEndpoint),{method:"POST",headers:n,body:JSON.stringify({base_info:{channel_version:this.credentials.channelVersion},client_id:this.clientId,file_id:e,file_key:e,image_key:e}),signal:t.signal});if(!a.ok){const e=await a.text().catch(()=>"");throw new Error(`HTTP ${a.status}: ${e||a.statusText}`)}return a}finally{clearTimeout(n)}}async downloadEncryptedMedia(e,t){const n=await fetch(e.url);if(!n.ok)throw new Error(`HTTP ${n.status}: ${n.statusText}`);const a=Buffer.from(await n.arrayBuffer()),s=e.aesKey?this.decryptWechatMedia(a,e.aesKey):a,i=createChannelFilePath(t||e.fileName||"attachment");return await promises$1.writeFile(i,s),i}decryptWechatMedia(e,t){const n=this.decodeWechatAesKey(t);try{const t=node_crypto.createDecipheriv("aes-128-ecb",n,null);return Buffer.concat([t.update(e),t.final()])}catch{const t=node_crypto.createDecipheriv("aes-128-ecb",n,null);return t.setAutoPadding(!1),Buffer.concat([t.update(e),t.final()])}}encryptWechatMedia(e,t){const n=Buffer.from(t,"hex");if(16!==n.length)throw new Error(`Invalid WeChat upload AES key length: ${n.length}`);const a=node_crypto.createCipheriv("aes-128-ecb",n,null);return Buffer.concat([a.update(e),a.final()])}decodeWechatAesKey(e){const t=Buffer.from(e,"base64").toString("utf-8"),n=/^[0-9a-f]{32}$/i.test(t)?t:e,a=/^[0-9a-f]{32}$/i.test(n)?Buffer.from(n,"hex"):Buffer.from(n,"utf-8");if(16!==a.length)throw new Error(`Invalid WeChat media AES key length: ${a.length}`);return a}buildHeaders(){const e={"Content-Type":"application/json",AuthorizationType:"ilink_bot_token",Authorization:`Bearer ${this.credentials.token}`,"X-WECHAT-UIN":this.generateWechatUin()};return this.credentials.routeTag&&(e.SKRouteTag=this.credentials.routeTag),e}apiUrl(e){return buildApiUrl(this.credentials.baseUrl,e)}generateWechatUin(){const e=node_crypto.randomBytes(4).readUInt32BE(0).toString();return Buffer.from(e).toString("base64")}sleepWithCancel(e){return new Promise(t=>{this.resolveRetrySleep=t,this.retryTimer=setTimeout(()=>{this.retryTimer=null,this.resolveRetrySleep=null,t()},e)})}isAbortError(e){return e instanceof Error&&"AbortError"===e.name}normalizeMessage(e){const t=e.chat_id??e.room_id??e.talker??e.from_user_id;if(!t)return machine.logger.warn(`[CHANNEL][WECHAT] Ignoring malformed message event: channel=${this.id}`),null;e.context_token&&this.contextTokens.set(t,e.context_token);const n=e,a=getFileData(e),s=e.from_user_id??e.sender??t,i=!0===n.is_at||!0===n.mentioned_bot||!0===n.at_bot,o=!0===n.reply_to_bot||!0===n.is_reply_to_bot;return{id:e.message_id??e.msg_id??String(e.id??e.seq??node_crypto.randomUUID()),channelId:this.id,platform:"wechat",chatId:t,chatType:e.room_id||String(t).endsWith("@chatroom")?"group":"p2p",senderId:s,senderName:getStringField(n,["sender_name","nickname","user_name"]),type:inferMessageType$1(e),text:getTextContent$1(e),fileKey:a.fileKey,fileName:a.fileName,imageKey:getImageKey$1(e),mentionedBot:i,replyToBot:o,triggered:i||o,rawContent:e.content??e.item_list,timestamp:normalizeTimestamp$1(e.timestamp??e.create_time),raw:e}}}const ChannelPlatforms=["telegram","wechat","lark"],ChannelPlatformSchema=zod.z.enum(ChannelPlatforms),ChannelConnectionStateSchema=zod.z.enum(["connecting","connected","disconnected","error"]),ChannelMessageTypeSchema=zod.z.enum(["text","image","file","voice"]),ChannelCredentialsSchema=zod.z.record(zod.z.string(),zod.z.unknown()),ChannelConfigSchema=zod.z.object({id:zod.z.string(),platform:ChannelPlatformSchema,name:zod.z.string().optional(),credentials:ChannelCredentialsSchema,enabled:zod.z.boolean(),connectionState:ChannelConnectionStateSchema,lastConnectedAt:zod.z.string().optional(),lastDisconnectedAt:zod.z.string().optional(),lastError:zod.z.string().optional(),createdAt:zod.z.string(),updatedAt:zod.z.string()}),AddChannelConfigSchema=zod.z.object({platform:ChannelPlatformSchema,name:zod.z.string().optional(),credentials:ChannelCredentialsSchema,enabled:zod.z.boolean().optional()}),ChannelBindingSchema=zod.z.object({id:zod.z.string(),channelId:zod.z.string(),chatId:zod.z.string(),taskId:zod.z.string(),chatName:zod.z.string().optional(),createdAt:zod.z.string(),updatedAt:zod.z.string()});zod.z.object({id:zod.z.string(),channelId:zod.z.string(),platform:ChannelPlatformSchema,chatId:zod.z.string(),chatType:zod.z.string().optional(),senderId:zod.z.string().optional(),senderType:zod.z.string().optional(),senderName:zod.z.string().optional(),type:ChannelMessageTypeSchema,text:zod.z.string().optional(),fileKey:zod.z.string().optional(),fileName:zod.z.string().optional(),imageKey:zod.z.string().optional(),attachmentPaths:zod.z.array(zod.z.string()).optional(),mentionedBot:zod.z.boolean().optional(),replyToBot:zod.z.boolean().optional(),triggered:zod.z.boolean().optional(),rawContent:zod.z.unknown().optional(),timestamp:zod.z.string(),raw:zod.z.unknown().optional()});const ChannelContactSchema=zod.z.object({id:zod.z.string(),name:zod.z.string(),avatar:zod.z.string().optional(),description:zod.z.string().optional(),chatStatus:zod.z.string().optional(),external:zod.z.boolean().optional()}),ChannelOutgoingAttachmentKindSchema=zod.z.enum(["auto","image","file","audio","video"]),ChannelOutgoingAttachmentSchema=zod.z.object({filePath:zod.z.string(),fileName:zod.z.string().optional(),mimeType:zod.z.string().optional(),kind:ChannelOutgoingAttachmentKindSchema.optional()});zod.z.object({content:zod.z.string().optional(),attachments:zod.z.array(ChannelOutgoingAttachmentSchema).optional()});const ChannelStoreSchema=zod.z.object({version:zod.z.literal(1),channels:zod.z.array(ChannelConfigSchema),bindings:zod.z.array(ChannelBindingSchema)}),GITLAB_WEBHOOK_TRIGGER_DEDUPE_TTL_MS=18e5,processedGitLabWebhookTriggerEvents=new Map;function asRecord(e){return!e||"object"!=typeof e||Array.isArray(e)?null:e}function getString(e){return"string"==typeof e&&e.trim().length>0?e.trim():void 0}function getNumber(e){return"number"==typeof e&&Number.isFinite(e)?e:void 0}function getBoolean(e){if("boolean"==typeof e)return e;if("string"!=typeof e)return;const t=e.trim().toLowerCase();return"true"===t||"1"===t||"yes"===t||"false"!==t&&"0"!==t&&"no"!==t&&void 0}function splitProjectPath(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}}function parseProject(e){const t=asRecord(e.project);return t?{id:getNumber(t.id),path:getString(t.path),path_with_namespace:getString(t.path_with_namespace),default_branch:getString(t.default_branch),web_url:getString(t.web_url)}:null}function getGitLabWebhookProjectKey(e){const t=parseProject(e);return t?.id?String(t.id):t?.path_with_namespace??null}function getGitLabWebhookProjectLocator(e){const t=parseProject(e);return t?.path_with_namespace?t.id?{projectId:t.id}:{projectPath:t.path_with_namespace}:null}function parseIssue(e){const t=asRecord(e.object_attributes);return t?{iid:getNumber(t.iid),title:getString(t.title),url:getString(t.url),action:getString(t.action),state:getString(t.state)}:null}function parseMergeRequest(e){const t=asRecord(e.object_attributes);if(!t)return null;const n=asRecord(t.last_commit),a=getLabelKeys(t.labels);return{iid:getNumber(t.iid),title:getString(t.title),description:getString(t.description),url:getString(t.url),action:getString(t.action),state:getString(t.state),source_branch:getString(t.source_branch),target_branch:getString(t.target_branch),oldrev:getString(t.oldrev)??getString(e.oldrev),last_commit_sha:getString(n?.id)??getString(n?.sha),labels:a.length>0?a:getLabelKeys(t.label_names)}}function parseNote(e){const t=asRecord(e.object_attributes);return t?{id:getNumber(t.id),note:getString(t.note),noteable_type:getString(t.noteable_type),url:getString(t.url),action:getString(t.action),system:getBoolean(t.system),isDiffNote:Boolean(t.position||t.diff_refs||t.line_code)}:null}function parsePipeline(e){const t=asRecord(e.object_attributes);return t?{id:getNumber(t.id),iid:getNumber(t.iid),status:getString(t.status),source:getString(t.source),ref:getString(t.ref),sha:getString(t.sha),url:getString(t.url)}:null}function resolveIssueUrl(e,t){return t.url?t.url:e.web_url&&"number"==typeof t.iid?`${e.web_url}/-/issues/${t.iid}`:void 0}function resolveMergeRequestUrl(e,t){return t.url?t.url:e.web_url&&"number"==typeof t.iid?`${e.web_url}/-/merge_requests/${t.iid}`:void 0}function resolvePipelineUrl(e,t){return t.url?t.url:e.web_url&&"number"==typeof t.id?`${e.web_url}/-/pipelines/${t.id}`:void 0}function parseEventType(e){return getString(e.event_type)||getString(e.object_kind)||"unknown"}function normalizeTriggerError(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}}function getTriggerDedupeKey(e,t){return`gitlab-webhook-trigger:${e}:${t}:pipeline`}function pruneProcessedGitLabWebhookTriggerEvents(e){for(const[t,n]of processedGitLabWebhookTriggerEvents.entries())n<=e&&processedGitLabWebhookTriggerEvents.delete(t)}function hasProcessedGitLabWebhookTriggerEvent(e,t,n){pruneProcessedGitLabWebhookTriggerEvents(n);const a=getTriggerDedupeKey(e,t),s=processedGitLabWebhookTriggerEvents.get(a);return"number"==typeof s&&s>n}function markGitLabWebhookTriggerEventProcessed(e,t,n){const a=getTriggerDedupeKey(e,t);processedGitLabWebhookTriggerEvents.set(a,n+18e5)}function hasAgentrixCommand(e){return!!e&&/(?:^|[^A-Za-z0-9._-])(?:@agentrix|\/agentrix)(?=$|[^A-Za-z0-9._-])/i.test(e)}function normalizeNoteableType(e){const t=e?.trim().toLowerCase();return"issue"===t?"issue":"mergerequest"===t||"merge_request"===t?"merge_request":void 0}function getChanges(e){return asRecord(e.changes)??{}}function readChangePair(e,t){if(!(t in e))return null;const n=e[t];if(Array.isArray(n)&&n.length>=2)return{previous:n[0],current:n[1]};const a=asRecord(n);return a?{previous:a.previous,current:a.current}:null}function readFirstChangePair(e,t){for(const n of t){const t=readChangePair(e,n);if(t)return t}return null}function asArray(e){return Array.isArray(e)?e:[]}function unique(e){return Array.from(new Set(e))}function getLabelKey(e){if("string"==typeof e)return getString(e);const t=asRecord(e);return getString(t?.title)??getString(t?.name)}function getLabelKeys(e){return unique(asArray(e).map(getLabelKey).filter(e=>Boolean(e)))}function getUserKey(e){const t=asRecord(e);return getString(t?.username)??getString(t?.name)??("number"==typeof t?.id?String(t.id):void 0)}function getCommitSha(e){if("string"==typeof e)return getString(e);const t=asRecord(e);return getString(t?.id)??getString(t?.sha)}function diffByKey(e,t,n){const a=unique(asArray(e).map(n).filter(e=>Boolean(e))),s=unique(asArray(t).map(n).filter(e=>Boolean(e)));return{added:s.filter(e=>!a.includes(e)),removed:a.filter(e=>!s.includes(e)),current:s,previous:a}}function isEmptyValue(e){return null==e||""===e}function booleanPair(e){if(!e)return null;const t=getBoolean(e.previous),n=getBoolean(e.current);return void 0===t||void 0===n||t===n?null:{previous:t,current:n}}function hasAnyChange(e,t){return t.some(t=>t in e)}function readHeadShaChange(e){const t=readFirstChangePair(e,["last_commit","head_sha","source_branch_sha","sha"]);if(!t)return null;const n=getCommitSha(t.previous),a=getCommitSha(t.current);return n||a?n===a?null:{previous:n,current:a}:null}function stableJsonStringify(e){if(Array.isArray(e))return`[${e.map(stableJsonStringify).join(",")}]`;const t=asRecord(e);return t?`{${Object.keys(t).sort().map(e=>`${JSON.stringify(e)}:${stableJsonStringify(t[e])}`).join(",")}}`:JSON.stringify(e)}function getGitLabWebhookDeliveryKey(e,t){const n=getString(t);return n||`payload-${node_crypto.createHash("sha256").update(stableJsonStringify(e)).digest("hex")}`}function encodeEventIdPart(e){return encodeURIComponent(String(e??"unknown"))}function buildNormalizedEventId(e,t){return[e,...t].map(encodeEventIdPart).join(":")}function setVariable(e,t,n){null!=n&&(e[t]=String(n))}function setJsonVariable(e,t,n){e[t]=JSON.stringify(n)}function setLabelListVariables(e,t){0!==t.length&&(setVariable(e,"AGENTRIX_LABELS",t.join(",")),setJsonVariable(e,"AGENTRIX_LABELS_JSON",t))}function buildBaseVariables(e){const{owner:t,name:n}=splitProjectPath(e.project.path_with_namespace??""),a={AGENTRIX_EVENT_NAME:e.eventName,AGENTRIX_EVENT_ACTION:e.eventAction,AGENTRIX_GIT_SERVER_ID:e.gitServerId,AGENTRIX_PROVIDER:"gitlab",AGENTRIX_REPOSITORY_OWNER:t,AGENTRIX_REPOSITORY_NAME:n,AGENTRIX_TRIGGER_SOURCE:"agentrix_daemon_webhook",AGENTRIX_COMPAT_KIND:e.compatKind,AGENTRIX_PROVIDER_EVENT_NAME:e.providerEventName,AGENTRIX_GITLAB_EVENT_NAME:e.providerEventName,AGENTRIX_GITLAB_CHANGED_KEYS:e.changedKeys.join(",")};return setVariable(a,"AGENTRIX_PROVIDER_EVENT_ACTION",e.providerEventAction),setVariable(a,"AGENTRIX_GITLAB_EVENT_ACTION",e.providerEventAction),setVariable(a,"AGENTRIX_SUBJECT_KIND",e.subjectKind),a}function addIssueVariables(e,t,n){setVariable(e,"AGENTRIX_ISSUE_NUMBER",n.iid),setVariable(e,"AGENTRIX_ISSUE_TITLE",n.title),setVariable(e,"AGENTRIX_ISSUE_URL",resolveIssueUrl(t,n))}function addMergeRequestVariables(e,t,n){setVariable(e,"AGENTRIX_PR_NUMBER",n.iid),setVariable(e,"AGENTRIX_HEAD_REF",n.source_branch),setVariable(e,"AGENTRIX_BASE_REF",n.target_branch),setVariable(e,"AGENTRIX_MR_TITLE",n.title),setVariable(e,"AGENTRIX_PR_BODY",n.description),setVariable(e,"AGENTRIX_MR_DESCRIPTION",n.description),setVariable(e,"AGENTRIX_MR_URL",resolveMergeRequestUrl(t,n)),setLabelListVariables(e,n.labels)}function buildOperationPayload(e,t,n,a){const s={ref:t,variables:n};return e.id?s.projectId=e.id:e.path_with_namespace&&(s.projectPath=e.path_with_namespace),a.triggerToken&&(s.triggerToken=a.triggerToken),void 0!==a.createTriggerIfMissing&&(s.createTriggerIfMissing=a.createTriggerIfMissing),s}function createDraft(e){const t={...buildBaseVariables(e),...e.variables??{}};return{project:e.project,ref:e.ref,normalizedEventIdParts:e.normalizedEventIdParts,eventName:e.eventName,eventAction:e.eventAction,providerEventName:e.providerEventName,providerEventAction:e.providerEventAction,compatKind:e.compatKind,subjectKind:e.subjectKind,changedKeys:e.changedKeys,variables:t}}function finalizeDrafts(e,t,n){return e.map((a,s)=>{const i=buildNormalizedEventId(n,a.normalizedEventIdParts),o={...a.variables,AGENTRIX_NORMALIZED_EVENT_ID:i,AGENTRIX_NORMALIZED_EVENT_INDEX:String(s),AGENTRIX_NORMALIZED_EVENT_COUNT:String(e.length)};return{normalizedEventId:i,eventName:a.eventName,eventAction:a.eventAction,providerEventName:a.providerEventName,providerEventAction:a.providerEventAction,compatKind:a.compatKind,operationPayload:buildOperationPayload(a.project,a.ref,o,t),action:a.eventAction}})}function buildIssueDrafts(e,t,n){const a=parseProject(t),s=parseIssue(t);if(!a?.path_with_namespace||!s?.iid)return[];const i=n.ref||a.default_branch;if(!i)throw{status:400,message:"Pipeline ref is required; pass ref or ensure GitLab payload includes project.default_branch"};const o=s.action,r=Object.keys(getChanges(t)),c={gitServerId:e,project:a,ref:i,providerEventName:"issue",providerEventAction:o,subjectKind:"issue",changedKeys:r},l=()=>{const e={};return addIssueVariables(e,a,s),e};if("open"===o||"opened"===o||!o&&"opened"===s.state)return[createDraft({...c,eventName:"issues",eventAction:"opened",compatKind:"exact",normalizedEventIdParts:["issues","opened",`issue-${s.iid}`],variables:l()})];if("close"===o||"closed"===o||!o&&"closed"===s.state)return[createDraft({...c,eventName:"issues",eventAction:"closed",compatKind:"exact",normalizedEventIdParts:["issues","closed",`issue-${s.iid}`],variables:l()})];if("reopen"===o||"reopened"===o)return[createDraft({...c,eventName:"issues",eventAction:"reopened",compatKind:"exact",normalizedEventIdParts:["issues","reopened",`issue-${s.iid}`],variables:l()})];const d=getChanges(t),p=[],u=readChangePair(d,"labels");if(u){const e=diffByKey(u.previous,u.current,getLabelKey);for(const t of e.added){const n=l();n.AGENTRIX_LABEL_NAME=t,setLabelListVariables(n,e.current),setJsonVariable(n,"AGENTRIX_LABEL_CHANGES_JSON",e),p.push(createDraft({...c,eventName:"issues",eventAction:"labeled",compatKind:"exact",normalizedEventIdParts:["issues","labeled",`issue-${s.iid}`,`label-${t}`],variables:n}))}for(const t of e.removed){const n=l();n.AGENTRIX_LABEL_NAME=t,setLabelListVariables(n,e.current),setJsonVariable(n,"AGENTRIX_LABEL_CHANGES_JSON",e),p.push(createDraft({...c,eventName:"issues",eventAction:"unlabeled",compatKind:"exact",normalizedEventIdParts:["issues","unlabeled",`issue-${s.iid}`,`label-${t}`],variables:n}))}}const m=readChangePair(d,"assignees");if(m){const e=diffByKey(m.previous,m.current,getUserKey);for(const t of e.added){const n=l();n.AGENTRIX_ASSIGNEE_LOGIN=t,setJsonVariable(n,"AGENTRIX_ASSIGNEE_CHANGES_JSON",e),p.push(createDraft({...c,eventName:"issues",eventAction:"assigned",compatKind:"exact",normalizedEventIdParts:["issues","assigned",`issue-${s.iid}`,`assignee-${t}`],variables:n}))}for(const t of e.removed){const n=l();n.AGENTRIX_ASSIGNEE_LOGIN=t,setJsonVariable(n,"AGENTRIX_ASSIGNEE_CHANGES_JSON",e),p.push(createDraft({...c,eventName:"issues",eventAction:"unassigned",compatKind:"exact",normalizedEventIdParts:["issues","unassigned",`issue-${s.iid}`,`assignee-${t}`],variables:n}))}}const h=readFirstChangePair(d,["milestone","milestone_id"]);if(h&&isEmptyValue(h.previous)!==isEmptyValue(h.current)){const e=isEmptyValue(h.previous)?"milestoned":"demilestoned",t=l();p.push(createDraft({...c,eventName:"issues",eventAction:e,compatKind:"exact",normalizedEventIdParts:["issues",e,`issue-${s.iid}`],variables:t}))}const g=booleanPair(readChangePair(d,"discussion_locked"));if(g){const e=g.current?"locked":"unlocked",t=l();p.push(createDraft({...c,eventName:"issues",eventAction:e,compatKind:"exact",normalizedEventIdParts:["issues",e,`issue-${s.iid}`],variables:t}))}return hasAnyChange(d,["title","description"])&&p.push(createDraft({...c,eventName:"issues",eventAction:"edited",compatKind:"exact",normalizedEventIdParts:["issues","edited",`issue-${s.iid}`],variables:l()})),p}function buildMergeRequestDrafts(e,t,n){const a=parseProject(t),s=parseMergeRequest(t);if(!a?.path_with_namespace||!s?.iid)return[];const i=n.ref||s.target_branch||a.default_branch||s.source_branch;if(!i)throw{status:400,message:"Pipeline ref is required; pass ref or ensure GitLab payload includes target_branch or project.default_branch"};const o=s.action,r=Object.keys(getChanges(t)),c={gitServerId:e,project:a,ref:i,providerEventName:"merge_request",providerEventAction:o,subjectKind:"pull_request",changedKeys:r},l=()=>{const e={};return addMergeRequestVariables(e,a,s),e};if("open"===o||"opened"===o)return[createDraft({...c,eventName:"pull_request",eventAction:"opened",compatKind:"exact",normalizedEventIdParts:["pull_request","opened",`mr-${s.iid}`],variables:l()})];if("reopen"===o||"reopened"===o)return[createDraft({...c,eventName:"pull_request",eventAction:"reopened",compatKind:"exact",normalizedEventIdParts:["pull_request","reopened",`mr-${s.iid}`],variables:l()})];if("merge"===o||"merged"===o||"merged"===s.state){const e=l();return e.AGENTRIX_PULL_REQUEST_MERGED="true",[createDraft({...c,eventName:"pull_request",eventAction:"closed",compatKind:"derived",normalizedEventIdParts:["pull_request","closed",`mr-${s.iid}`,"merged"],variables:e})]}if("close"===o||"closed"===o){const e=l();return e.AGENTRIX_PULL_REQUEST_MERGED="false",[createDraft({...c,eventName:"pull_request",eventAction:"closed",compatKind:"exact",normalizedEventIdParts:["pull_request","closed",`mr-${s.iid}`],variables:e})]}if("approved"===o||"approval"===o){const e=l();return e.AGENTRIX_REVIEW_STATE="approved",[createDraft({...c,eventName:"pull_request_review",eventAction:"submitted",compatKind:"derived",normalizedEventIdParts:["pull_request_review","submitted",`mr-${s.iid}`,"approved"],variables:e})]}if("unapproved"===o||"unapproval"===o){const e=l();return e.AGENTRIX_REVIEW_STATE="approved_removed",[createDraft({...c,eventName:"pull_request_review",eventAction:"dismissed",compatKind:"derived",normalizedEventIdParts:["pull_request_review","dismissed",`mr-${s.iid}`,"approved_removed"],variables:e})]}const d=getChanges(t),p=[],u=readHeadShaChange(d),m=s.oldrev??u?.current??s.last_commit_sha??"unknown";if(s.oldrev||u){const e=l();setVariable(e,"AGENTRIX_GITLAB_OLDREV",s.oldrev??u?.previous),setVariable(e,"AGENTRIX_HEAD_SHA",u?.current??s.last_commit_sha),p.push(createDraft({...c,eventName:"pull_request",eventAction:"synchronize",compatKind:"derived",normalizedEventIdParts:["pull_request","synchronize",`mr-${s.iid}`,m],variables:e}))}const h=readChangePair(d,"labels");if(h){const e=diffByKey(h.previous,h.current,getLabelKey);for(const t of e.added){const n=l();n.AGENTRIX_LABEL_NAME=t,setLabelListVariables(n,e.current),setJsonVariable(n,"AGENTRIX_LABEL_CHANGES_JSON",e),p.push(createDraft({...c,eventName:"pull_request",eventAction:"labeled",compatKind:"exact",normalizedEventIdParts:["pull_request","labeled",`mr-${s.iid}`,`label-${t}`],variables:n}))}for(const t of e.removed){const n=l();n.AGENTRIX_LABEL_NAME=t,setLabelListVariables(n,e.current),setJsonVariable(n,"AGENTRIX_LABEL_CHANGES_JSON",e),p.push(createDraft({...c,eventName:"pull_request",eventAction:"unlabeled",compatKind:"exact",normalizedEventIdParts:["pull_request","unlabeled",`mr-${s.iid}`,`label-${t}`],variables:n}))}}const g=readChangePair(d,"assignees");if(g){const e=diffByKey(g.previous,g.current,getUserKey);for(const t of e.added){const n=l();n.AGENTRIX_ASSIGNEE_LOGIN=t,setJsonVariable(n,"AGENTRIX_ASSIGNEE_CHANGES_JSON",e),p.push(createDraft({...c,eventName:"pull_request",eventAction:"assigned",compatKind:"exact",normalizedEventIdParts:["pull_request","assigned",`mr-${s.iid}`,`assignee-${t}`],variables:n}))}for(const t of e.removed){const n=l();n.AGENTRIX_ASSIGNEE_LOGIN=t,setJsonVariable(n,"AGENTRIX_ASSIGNEE_CHANGES_JSON",e),p.push(createDraft({...c,eventName:"pull_request",eventAction:"unassigned",compatKind:"exact",normalizedEventIdParts:["pull_request","unassigned",`mr-${s.iid}`,`assignee-${t}`],variables:n}))}}const f=readChangePair(d,"reviewers");if(f){const e=diffByKey(f.previous,f.current,getUserKey);for(const t of e.added){const n=l();n.AGENTRIX_REQUESTED_REVIEWER_LOGIN=t,setJsonVariable(n,"AGENTRIX_REVIEWER_CHANGES_JSON",e),p.push(createDraft({...c,eventName:"pull_request",eventAction:"review_requested",compatKind:"exact",normalizedEventIdParts:["pull_request","review_requested",`mr-${s.iid}`,`reviewer-${t}`],variables:n}))}for(const t of e.removed){const n=l();n.AGENTRIX_REQUESTED_REVIEWER_LOGIN=t,setJsonVariable(n,"AGENTRIX_REVIEWER_CHANGES_JSON",e),p.push(createDraft({...c,eventName:"pull_request",eventAction:"review_request_removed",compatKind:"exact",normalizedEventIdParts:["pull_request","review_request_removed",`mr-${s.iid}`,`reviewer-${t}`],variables:n}))}}const y=booleanPair(readFirstChangePair(d,["draft","work_in_progress"]));if(y){const e=y.current?"converted_to_draft":"ready_for_review";p.push(createDraft({...c,eventName:"pull_request",eventAction:e,compatKind:"derived",normalizedEventIdParts:["pull_request",e,`mr-${s.iid}`],variables:l()}))}return hasAnyChange(d,["title","description","target_branch"])&&p.push(createDraft({...c,eventName:"pull_request",eventAction:"edited",compatKind:"exact",normalizedEventIdParts:["pull_request","edited",`mr-${s.iid}`],variables:l()})),p}function buildNoteDrafts(e,t,n){const a=parseProject(t),s=parseNote(t);if(!a?.path_with_namespace||!s||!0===s.system)return[];const i=normalizeNoteableType(s.noteable_type);if(!i)return[];const o=asRecord("issue"===i?t.issue:t.merge_request),r=getNumber(o?.iid);if(!r)return[];const c=(()=>{switch(s.action){case void 0:case"create":case"created":return"created";case"update":case"updated":return"edited";case"delete":case"deleted":return"deleted";default:return null}})();if(!c)return[];const l="merge_request"===i?getString(o?.source_branch):void 0,d="merge_request"===i?getString(o?.target_branch):void 0,p=n.ref||d||a.default_branch||l;if(!p)throw{status:400,message:"Pipeline ref is required; pass ref or ensure GitLab payload includes a usable ref"};const u="merge_request"===i&&s.isDiffNote?"pull_request_review_comment":"issue_comment",m="merge_request"===i?"pull_request":"issue",h=Object.keys(getChanges(t)),g={AGENTRIX_COMMENT_COMMAND:hasAgentrixCommand(s.note)?"true":"false",AGENTRIX_GITLAB_NOTEABLE_TYPE:s.noteable_type??i};return setVariable(g,"AGENTRIX_COMMENT_BODY",s.note),setVariable(g,"AGENTRIX_COMMENT_ID",s.id),setVariable(g,"AGENTRIX_COMMENT_URL",s.url),"issue"===i?setVariable(g,"AGENTRIX_ISSUE_NUMBER",r):(setVariable(g,"AGENTRIX_PR_NUMBER",r),setVariable(g,"AGENTRIX_HEAD_REF",l),setVariable(g,"AGENTRIX_BASE_REF",d)),[createDraft({gitServerId:e,project:a,ref:p,eventName:u,eventAction:c,providerEventName:"note",providerEventAction:s.action,compatKind:"issue"===i?"exact":"derived",subjectKind:m,changedKeys:h,normalizedEventIdParts:[u,c,`${m}-${r}`,`comment-${s.id??"unknown"}`],variables:g})]}function getPipelineMergeRequestIid(e){const t=asRecord(e.merge_request);return getNumber(t?.iid)}function mapPipelineStatus(e){switch(e){case"created":case"pending":return{eventAction:"requested",workflowStatus:"pending"};case"running":return{eventAction:"in_progress",workflowStatus:e};case"success":return{eventAction:"completed",workflowStatus:"completed",conclusion:"success"};case"failed":return{eventAction:"completed",workflowStatus:"completed",conclusion:"failure"};case"canceled":case"cancelled":return{eventAction:"completed",workflowStatus:"completed",conclusion:"cancelled"};case"skipped":return{eventAction:"completed",workflowStatus:"completed",conclusion:"skipped"};default:return null}}function buildPipelineDrafts(e,t,n){const a=parseProject(t),s=parsePipeline(t);if(!a?.path_with_namespace||!s?.status||"trigger"===s.source)return[];const i=mapPipelineStatus(s.status);if(!i)return[];const o=n.ref||s.ref||a.default_branch;if(!o)throw{status:400,message:"Pipeline ref is required; pass ref or ensure GitLab payload includes object_attributes.ref or project.default_branch"};const r={AGENTRIX_WORKFLOW_RUN_STATUS:i.workflowStatus,AGENTRIX_PIPELINE_STATUS:s.status,AGENTRIX_REF:o};return setVariable(r,"AGENTRIX_WORKFLOW_RUN_CONCLUSION",i.conclusion),setVariable(r,"AGENTRIX_PIPELINE_SOURCE",s.source),setVariable(r,"AGENTRIX_PIPELINE_ID",s.id),setVariable(r,"AGENTRIX_PIPELINE_IID",s.iid),setVariable(r,"AGENTRIX_SHA",s.sha),setVariable(r,"AGENTRIX_PIPELINE_URL",resolvePipelineUrl(a,s)),setVariable(r,"AGENTRIX_PR_NUMBER",getPipelineMergeRequestIid(t)),[createDraft({gitServerId:e,project:a,ref:o,eventName:"workflow_run",eventAction:i.eventAction,providerEventName:"pipeline",providerEventAction:s.status,compatKind:"derived",subjectKind:"workflow_run",changedKeys:[],normalizedEventIdParts:["workflow_run",i.eventAction,`pipeline-${s.id??s.iid??"unknown"}`],variables:r})]}function buildGitLabWebhookPipelineTriggerPayloads(e,t,n){const a=getGitLabWebhookDeliveryKey(t,n.deliveryId),s=parseEventType(t);return finalizeDrafts((()=>{switch(s){case"issue":return buildIssueDrafts(e,t,n);case"note":return buildNoteDrafts(e,t,n);case"merge_request":return buildMergeRequestDrafts(e,t,n);case"pipeline":return buildPipelineDrafts(e,t,n);default:return[]}})(),n,a)}function getIgnoredReason(e){const t=parseEventType(e);if("note"===t){const t=parseNote(e);return!0===t?.system?"system_note":t?"unsupported_provider_specific_event":"missing_required_payload"}if("pipeline"===t){const t=parsePipeline(e);return"trigger"===t?.source?"pipeline_source_trigger_ignored":"unsupported_provider_specific_event"}if("issue"===t||"merge_request"===t){const n=parseProject(e),a="issue"===t?parseIssue(e):parseMergeRequest(e);return n?.path_with_namespace&&a?.iid?"unsupported_provider_specific_event":"missing_required_payload"}return"unsupported_provider_specific_event"}function getGitLabWebhookPipelineProjectKey(e){const t=getGitLabWebhookProjectKey(e);if(!t)return null;try{return buildGitLabWebhookPipelineTriggerPayloads("__probe__",e,{ref:"__probe__"}).length>0?t:null}catch{return t}}async function triggerPipelineFromGitLabWebhook({gitServerId:e,payload:t,config:n,pat:a}){const s=parseEventType(t),i=buildGitLabWebhookPipelineTriggerPayloads(e,t,n);if(0===i.length)return{status:"ignored",eventType:s,reason:getIgnoredReason(t),triggeredCount:0,failedCount:0,events:[]};if(!n.apiUrl)throw{status:400,message:"GitLab API URL is required"};const o=new GitLabExecutor(n.apiUrl,a,{gitServerId:e}),r=[];for(const t of i){const n=Date.now();if(hasProcessedGitLabWebhookTriggerEvent(e,t.normalizedEventId,n))r.push({status:"ignored",normalizedEventId:t.normalizedEventId,eventName:t.eventName,eventAction:t.eventAction,action:t.action,reason:"duplicate_delivery_event"});else try{const n=await o.executeOperation("triggerPipeline",t.operationPayload);markGitLabWebhookTriggerEventProcessed(e,t.normalizedEventId,Date.now()),r.push({status:"triggered",normalizedEventId:t.normalizedEventId,eventName:t.eventName,eventAction:t.eventAction,action:t.action,pipeline:n})}catch(e){const n=normalizeTriggerError(e);r.push({status:"failed",normalizedEventId:t.normalizedEventId,eventName:t.eventName,eventAction:t.eventAction,action:t.action,reason:"pipeline_trigger_failed",errorMessage:n.message,errorDetail:n.detail,upstreamStatus:n.upstreamStatus})}}const c=r.filter(e=>"failed"===e.status),l=r.filter(e=>"triggered"===e.status),d=r.filter(e=>"ignored"===e.status),p=r[0],u=c[0];return u?{status:"failed",eventType:s,eventName:p?.eventName,eventAction:p?.eventAction,action:p?.action,reason:u.reason,errorMessage:u.errorMessage,errorDetail:u.errorDetail,upstreamStatus:u.upstreamStatus,triggeredCount:l.length,failedCount:c.length,events:r}:0===l.length&&d.length>0?{status:"ignored",eventType:s,eventName:p?.eventName,eventAction:p?.eventAction,action:p?.action,reason:p?.reason,triggeredCount:0,failedCount:0,events:r}:{status:"triggered",eventType:s,eventName:p?.eventName,eventAction:p?.eventAction,action:p?.action,pipeline:1===r.length?p?.pipeline:void 0,triggeredCount:l.length,failedCount:0,events:r}}function getSigningSecret(e){return e.secret||e.token}function encodeBase64Url(e){return Buffer.from(e,"utf8").toString("base64url")}function decodeBase64Url(e){return Buffer.from(e,"base64url").toString("utf8")}function signPayload(e,t){return node_crypto.createHmac("sha256",t).update(e).digest("base64url")}function safeEqualString(e,t){const n=Buffer.from(e),a=Buffer.from(t);return n.length===a.length&&node_crypto.timingSafeEqual(n,a)}function signAgentrixEventMcpToken(e,t){const n={taskId:t.taskId,userId:t.userId,machineId:t.machineId??e.machineId,nonce:node_crypto.randomBytes(16).toString("base64url"),taskPreviewEnabled:t.taskPreviewEnabled,visionPlanEnabled:t.visionPlanEnabled},a=encodeBase64Url(JSON.stringify(n));return`${a}.${signPayload(a,getSigningSecret(e))}`}function verifyAgentrixEventMcpToken(e,t){const[n,a,s]=t.split(".");if(!n||!a||void 0!==s)throw new Error("Invalid Agentrix event MCP token format");if(!safeEqualString(a,signPayload(n,getSigningSecret(e))))throw new Error("Invalid Agentrix event MCP token signature");let i;try{i=JSON.parse(decodeBase64Url(n))}catch{throw new Error("Invalid Agentrix event MCP token payload")}if(!(i.taskId&&i.userId&&i.machineId&&i.nonce))throw new Error("Incomplete Agentrix event MCP token payload");if(i.machineId!==e.machineId)throw new Error("Agentrix event MCP token machine mismatch");return i}const SendVisionArtifactRequestSchema=zod.z.object({repoRoot:zod.z.string().min(1).describe("Absolute repository root containing .agentrix/issues"),issueId:zod.z.string().min(1).max(160).regex(/^[A-Za-z0-9._-]+$/).describe("Agentrix issue directory id, for example 478-vision-plan-agentrix-platform-bridge")});async function normalizeSendVisionArtifactRequest(e,t){return{issueId:SendVisionArtifactRequestSchema.parse(e).issueId}}const AGENTRIX_EVENT_MCP_SERVER_NAME="agentrix_event_broker",AGENTRIX_EVENT_MCP_ROUTE="/mcp/agentrix-event-broker",AGENTRIX_EVENT_MCP_TOKEN_ENV="AGENTRIX_EVENT_MCP_TOKEN",AGENTRIX_CHANGE_TITLE_EVENT_TOOL="change_title",AGENTRIX_PUBLISH_TASK_PREVIEW_URL_EVENT_TOOL="publish_task_preview_url",AGENTRIX_SEND_VISION_ARTIFACT_EVENT_TOOL="send_vision_artifact";function isAgentrixInternalMcpServerName(e){return"agentrix"===e||"agentrix_event_broker"===e}function extractBearerToken(e){const t=e.headers.authorization;if(!t)throw new Error("Missing Agentrix event MCP bearer token");const n=/^Bearer\s+(.+)$/i.exec(t);if(!n?.[1])throw new Error("Invalid Agentrix event MCP authorization header");return n[1]}async function sendChangeTitleMachineEvent(e,t,n){const a=e?.();if(!a?.connected)throw new Error("Agentrix daemon machine socket is not connected");const s={eventId:shared.createEventId(),taskId:t.taskId,title:n},i=await a.sendWithAck("change-task-title",s);if("success"!==i.status)throw new Error(i.message||"Failed to change task title")}async function sendTaskPreviewUrlUpdate(e,t,n){const a=await fetch(`${machine.machine.serverUrl}/v1/tasks/${encodeURIComponent(t.taskId)}/preview-url`,{method:"PUT",headers:{Authorization:`Bearer ${e.token}`,"Content-Type":"application/json","X-Agentrix-Task":t.taskId},body:JSON.stringify({previewUrl:n})});if(!a.ok){const e=await a.text().catch(()=>"");throw new Error(`Failed to publish task preview URL (${a.status}): ${e||a.statusText}`)}}function createDefaultAgentrixEventBrokerDispatcher(e,t){return{changeTitle:(e,n)=>sendChangeTitleMachineEvent(t,e,n),publishTaskPreviewUrl:(t,n)=>sendTaskPreviewUrlUpdate(e,t,n),sendVisionArtifact:async(e,n)=>{const a=await normalizeSendVisionArtifactRequest(n,{taskId:e.taskId}),s=t?.();if(!s?.connected)throw new Error("Agentrix daemon machine socket is not connected");const i=await s.sendWithAck("vision-plan-card",{eventId:shared.createEventId(),taskId:e.taskId,issueId:a.issueId,repoRoot:n.repoRoot,createdAt:(new Date).toISOString()});if("success"!==i.status)throw new Error(i.message||"Failed to send Vision Plan card");return{issueId:a.issueId}}}}async function dispatchAgentrixChangeTitleEventTool(e,t,n){const a=n.trim();if(!a)throw new Error("Title must not be empty");return await e.changeTitle(t,a),`Agentrix title change event emitted for task ${t.taskId}: ${a}`}async function dispatchAgentrixPublishTaskPreviewUrlEventTool(e,t,n){const a=shared.UpdateTaskPreviewUrlRequestSchema.parse({previewUrl:n});return await e.publishTaskPreviewUrl(t,a.previewUrl),`Agentrix preview URL updated for task ${t.taskId}: ${a.previewUrl}`}async function dispatchAgentrixSendVisionArtifactEventTool(e,t,n){const a=SendVisionArtifactRequestSchema.parse(n);return`Agentrix vision artifacts sent for issue ${(await e.sendVisionArtifact(t,a)).issueId}.`}function createAgentrixEventMcpServer(e){const t=new mcp_js.McpServer({name:"agentrix-event-broker",version:"1.0.0"});return t.registerTool("change_title",{title:"Change session title",description:["Emit an Agentrix event that changes the current session title.","Use this early in a task when the conversation has no user-provided title."].join(" "),inputSchema:{title:zod.z.string().min(1).max(200).describe("New title for the current Agentrix task")}},async({title:t})=>({content:[{type:"text",text:await dispatchAgentrixChangeTitleEventTool(e.dispatcher,e.context,t)}]})),!1!==e.context.taskPreviewEnabled&&t.registerTool("publish_task_preview_url",{title:"Publish task preview URL",description:["Record the frontend preview URL for the current Agentrix task.","Use this on a local machine when a browser-viewable frontend URL exists after starting or reusing the local environment.","The URL must be absolute http(s); localhost URLs are allowed."].join(" "),inputSchema:{previewUrl:zod.z.string().min(1).max(2048).describe("Absolute http(s) URL for the current task preview")}},async({previewUrl:t})=>({content:[{type:"text",text:await dispatchAgentrixPublishTaskPreviewUrlEventTool(e.dispatcher,e.context,t)}]})),!0===e.context.visionPlanEnabled&&t.registerTool("send_vision_artifact",{title:"Send Agentrix vision artifacts",description:["Send the issue vision artifacts (visual plan and test report) to the Agentrix platform so the user can review them.","Use this after generating or materially updating the visual plan, and again after generating the visual test report.","Pass only the repository root and issue id."].join(" "),inputSchema:{repoRoot:zod.z.string().min(1).describe("Absolute repository root containing .agentrix/issues"),issueId:zod.z.string().min(1).max(160).describe("Agentrix issue directory id")}},async({repoRoot:t,issueId:n})=>({content:[{type:"text",text:await dispatchAgentrixSendVisionArtifactEventTool(e.dispatcher,e.context,{repoRoot:t,issueId:n})}]})),t}async function handleMcpRequest(e,t,n){const a=extractBearerToken(e),s=createAgentrixEventMcpServer({context:verifyAgentrixEventMcpToken(n.credentials,a),dispatcher:n.dispatcher}),i=new streamableHttp_js.StreamableHTTPServerTransport({sessionIdGenerator:void 0});try{await s.connect(i),t.hijack(),await i.handleRequest(e.raw,t.raw,e.body)}catch(e){machine.logger.warn("[EVENT MCP] Failed to handle MCP request:",e),t.raw.headersSent||(t.raw.writeHead(500,{"Content-Type":"application/json"}),t.raw.end(JSON.stringify({jsonrpc:"2.0",error:{code:-32603,message:"Internal server error"},id:null})))}finally{await i.close().catch(()=>{}),await s.close().catch(()=>{})}}function registerAgentrixEventMcpBrokerRoutes(e,t){const n=t.getSocketClient??(()=>{}),a={credentials:t.credentials,getSocketClient:n,dispatcher:t.dispatcher??createDefaultAgentrixEventBrokerDispatcher(t.credentials,n)};e.post(AGENTRIX_EVENT_MCP_ROUTE,async(e,t)=>{try{await handleMcpRequest(e,t,a)}catch(e){const n=e instanceof Error?e.message:"Unauthorized Agentrix event MCP request";return machine.logger.warn(`[EVENT MCP] ${n}`),t.status(401).send({jsonrpc:"2.0",error:{code:-32001,message:n},id:null})}}),e.get(AGENTRIX_EVENT_MCP_ROUTE,async(e,t)=>t.status(405).send({jsonrpc:"2.0",error:{code:-32e3,message:"Method not allowed."},id:null})),e.delete(AGENTRIX_EVENT_MCP_ROUTE,async(e,t)=>t.status(405).send({jsonrpc:"2.0",error:{code:-32e3,message:"Method not allowed."},id:null}))}class MachineAesKeyUpdateError extends Error{constructor(e,t){super(e),this.statusCode=t,this.name="MachineAesKeyUpdateError"}}function decodeValidMachineAesKey(e){if(!e)return null;try{const t=shared.decodeBase64(e);return 32===t.length?t:null}catch{return null}}function hasValidMachineAesKey(e){return!!decodeValidMachineAesKey(e.machineAesKey)}async function storeRecoveredMachineAesKey(e,t,n=machine.machine){if(t.machineId!==e.machineId)throw new MachineAesKeyUpdateError("machineId does not match daemon credentials",409);if(!decodeValidMachineAesKey(t.machineAesKey))throw new MachineAesKeyUpdateError("machineAesKey must decode to a 32-byte key",400);const a=await n.readCredentials()??e;if(a.machineId!==e.machineId)throw new MachineAesKeyUpdateError("stored credentials machineId does not match daemon credentials",409);if(hasValidMachineAesKey(a))return e.machineAesKey=a.machineAesKey,{success:!0,updated:!1,hasMachineAesKey:!0};const s={...a,machineAesKey:t.machineAesKey};return await n.writeCredentials(s),e.machineAesKey=t.machineAesKey,{success:!0,updated:!0,hasMachineAesKey:!0}}const logger$7=machine.createModuleLogger("undefined"==typeof document?require("url").pathToFileURL(__filename).href:_documentCurrentScript&&"SCRIPT"===_documentCurrentScript.tagName.toUpperCase()&&_documentCurrentScript.src||new URL("index.cjs",document.baseURI).href),COMPUTER_USE_AGENT_ID="codex",COMPUTER_USE_TASK_STATE_AGENT_ID="agentrix-computer-use";function isTruthy(e){return["1","true","yes","on"].includes((e??"").trim().toLowerCase())}function resolveCodexHome(){const e=process.env.AGENTRIX_COMPUTER_USE_CODEX_HOME||process.env.AGENTRIX_CODEX_HOME_FOR_COMPUTER_USE;return e?.trim()?e.trim().replace(/^~(?=\/|$)/,os.homedir()):path.join(os.homedir(),".codex")}function resolveCodexPath(){const e=process.env.AGENTRIX_CODEX_PATH?.trim();if(e)return fs.existsSync(e)?{available:!0,path:e}:{available:!1,path:e};const t=node_child_process.spawnSync("win32"===process.platform?"where":"which",["codex"],{encoding:"utf8"}).stdout.split(/\r?\n/).map(e=>e.trim()).find(Boolean);return t?{available:!0,path:t}:{available:!1}}function resolveCommandPath(e,t){const n=t?.trim();if(n)return fs.existsSync(n)?{available:!0,path:n}:{available:!1,path:n};const a=node_child_process.spawnSync("win32"===process.platform?"where":"which",[e],{encoding:"utf8"}).stdout.split(/\r?\n/).map(e=>e.trim()).find(Boolean);if(a)return{available:!0,path:a};for(const e of[path.join(os.homedir(),".local","bin","cua-driver"),"/usr/local/bin/cua-driver","/Applications/CuaDriver.app/Contents/MacOS/cua-driver"])if(fs.existsSync(e))return{available:!0,path:e};return{available:!1}}function isDirectory(e){try{return fs.statSync(e).isDirectory()}catch{return!1}}function readTextIfExists(e){try{return fs.readFileSync(e,"utf8")}catch{return""}}function parseOptionalBoolean(e){return"boolean"==typeof e?e:void 0}function getCuaDriverPermissionStatus(e){if(!e||"darwin"!==process.platform)return{};const t=node_child_process.spawnSync(e,["doctor","--json"],{encoding:"utf8",timeout:1e4});try{const e=JSON.parse(t.stdout);return{accessibilityGranted:parseOptionalBoolean(e.ax_granted),screenRecordingGranted:parseOptionalBoolean(e.screen_recording_granted)}}catch(e){return 0!==t.status?{error:[t.stderr,t.stdout].map(e=>e?.trim()).filter(Boolean).join("\n")||"Failed to check Cua Driver permission status."}:{error:`Failed to parse Cua Driver permission status: ${e instanceof Error?e.message:String(e)}`}}}function normalizeHomePath(e){return e.replace(/^~(?=\/|$)/,os.homedir())}function getCodexSkillDirs(e){return[path.join(e,"skills","cua-driver"),path.join(os.homedir(),".agents","skills","cua-driver")]}function findPresentSkillDir(e){for(const t of getCodexSkillDirs(e))if(isDirectory(t)&&fs.existsSync(path.join(t,"SKILL.md")))return t;return null}function resolveCuaDriverSkillSource(){const e=process.env.AGENTRIX_CUA_DRIVER_SKILL_SOURCE?.trim();if(e){const t=normalizeHomePath(e);return fs.existsSync(path.join(t,"SKILL.md"))?t:null}const t=[path.join(os.homedir(),".agents","skills","cua-driver"),path.join(os.homedir(),".claude","skills","cua-driver"),path.join(os.homedir(),".openclaw","skills","cua-driver")].filter(e=>Boolean(e));for(const e of t){const t=path.resolve(normalizeHomePath(e));if(fs.existsSync(path.join(t,"SKILL.md")))return t}return null}function getEnablement(e,t){if(isTruthy(process.env.AGENTRIX_COMPUTER_USE_ENABLED))return"env";const n=e;return!1===n?.agentrixComputerUse?.enabled?null:!0===n?.agentrixComputerUse?.enabled?"settings":fs.existsSync(t)?"marker":null}function getComputerUseBridgeStatus(e=machine.machine.readSettings()){const t=resolveCodexHome(),n=path.join(machine.machine.agentrixHomeDir,"computer-use","enabled"),a=getEnablement(e,n),s=resolveCodexPath(),i=resolveCommandPath("cua-driver",process.env.AGENTRIX_CUA_DRIVER_PATH),o=path.join(t,"config.toml"),r=readTextIfExists(o),c=r.length>0,l=/\[mcp_servers\.(["']?cua-driver["']?|cua_driver)\]/.test(r)||/cua-driver/.test(r);path.join(t,"skills","cua-driver");const d=null!==findPresentSkillDir(t),p=resolveCuaDriverSkillSource()??void 0,u=getCuaDriverPermissionStatus(i.path),m=[];return s.available||m.push("Codex CLI is not available. Install Codex or set AGENTRIX_CODEX_PATH to the codex executable."),i.available||m.push("Cua Driver CLI is not available. Install Cua Driver or set AGENTRIX_CUA_DRIVER_PATH to the cua-driver executable."),u.error&&m.push(`Cua Driver permission status could not be checked: ${u.error}`),!1===u.accessibilityGranted&&m.push("Cua Driver Accessibility permission is not granted. Install Agentrix Computer Use to open the macOS permission prompt, then grant Accessibility access."),!1===u.screenRecordingGranted&&m.push("Cua Driver Screen Recording permission is not granted. Install Agentrix Computer Use to open the macOS permission prompt, then grant Screen Recording access."),c&&l||m.push(`Cua Driver MCP is not configured in ${o}. Run: cua-driver mcp-config --client codex`),d||m.push(`Cua Driver Codex skill is missing. Checked ${getCodexSkillDirs(t).join(" and ")}.`),{platform:process.platform,enabled:null!==a,enabledBy:a,codexHome:t,codexAvailable:s.available,codexPath:s.path,codexConfigPresent:c,cuaDriverAvailable:i.available,cuaDriverPath:i.path,cuaDriverAccessibilityGranted:u.accessibilityGranted,cuaDriverScreenRecordingGranted:u.screenRecordingGranted,cuaDriverMcpConfigured:l,cuaDriverSkillPresent:d,cuaDriverSkillSource:p,markerPath:n,missing:m}}function runCuaDriverMcpConfig(e){const t=resolveCommandPath("cua-driver",process.env.AGENTRIX_CUA_DRIVER_PATH);if(!t.available||!t.path)return"cua-driver command is not available. Install Cua Driver CLI or set AGENTRIX_CUA_DRIVER_PATH.";const n=resolveCodexPath();if(!n.available||!n.path)return"Codex CLI is not available. Install Codex or set AGENTRIX_CODEX_PATH to the codex executable.";fs.mkdirSync(e,{recursive:!0});const a=node_child_process.spawnSync(t.path,["mcp-config","--client","codex"],{encoding:"utf8",env:{...process.env,CODEX_HOME:e,AGENTRIX_CODEX_HOME:e}});if(0!==a.status){const e=[a.stderr,a.stdout].map(e=>e?.trim()).filter(Boolean).join("\n");return"Failed to run `cua-driver mcp-config --client codex`"+(e?`:\n${e}`:".")}const s=node_child_process.spawnSync(n.path,["mcp","add","cua-driver","--",t.path,"mcp"],{encoding:"utf8",env:{...process.env,CODEX_HOME:e}});if(0===s.status)return null;const i=[s.stderr,s.stdout].map(e=>e?.trim()).filter(Boolean).join("\n");return`Failed to run \`codex mcp add cua-driver -- ${t.path} mcp\`${i?`:\n${i}`:"."}`}function ensureCuaDriverSkillSymlink(e){const t=resolveCuaDriverSkillSource(),n=path.join(e,"skills","cua-driver");if(!t)return["Cua Driver skill source was not found.","Install or update Cua Driver so its installer auto-wires agent skills, or set AGENTRIX_CUA_DRIVER_SKILL_SOURCE to a directory containing SKILL.md."].join(" ");if(fs.existsSync(n)){if(fs.existsSync(path.join(n,"SKILL.md")))return null;try{return fs.lstatSync(n).isSymbolicLink()?`Existing Cua Driver skill symlink at ${n} does not resolve to a valid skill.`:`Existing path ${n} is not a valid Cua Driver skill directory.`}catch(e){return`Failed to inspect existing Cua Driver skill path ${n}: ${e instanceof Error?e.message:String(e)}`}}try{return fs.mkdirSync(path.dirname(n),{recursive:!0}),fs.symlinkSync(t,n,"dir"),null}catch(e){return`Failed to create Cua Driver skill symlink ${n} -> ${t}: ${e instanceof Error?e.message:String(e)}`}}function requestCuaDriverPermissions(e){const t=node_child_process.spawnSync(e,["call","check_permissions",'{"prompt":true}',"--raw","--compact"],{encoding:"utf8",timeout:3e4});if(0===t.status)return null;const n=[t.stderr,t.stdout].map(e=>e?.trim()).filter(Boolean).join("\n");return"Failed to open Cua Driver permission prompt"+(n?`:\n${n}`:".")}function enableComputerUseBridgeMarker(e){try{return fs.mkdirSync(path.dirname(e),{recursive:!0}),fs.writeFileSync(e,`${(new Date).toISOString()}\n`,"utf8"),null}catch(t){return`Failed to enable Agentrix Computer Use at ${e}: ${t instanceof Error?t.message:String(t)}`}}function enableComputerUseBridgeSettings(){try{const e=machine.machine.readSettings()??{};return machine.machine.writeSettings({...e,agentrixComputerUse:{...e.agentrixComputerUse??{},enabled:!0}}),null}catch(e){return`Failed to enable Agentrix Computer Use in settings: ${e instanceof Error?e.message:String(e)}`}}function disableComputerUseBridgeSettings(){try{const e=machine.machine.readSettings()??{};return machine.machine.writeSettings({...e,agentrixComputerUse:{...e.agentrixComputerUse??{},enabled:!1}}),null}catch(e){return`Failed to disable Agentrix Computer Use in settings: ${e instanceof Error?e.message:String(e)}`}}function removeComputerUseBridgeMarker(e){try{return fs.existsSync(e)&&fs.unlinkSync(e),null}catch(t){return`Failed to remove Agentrix Computer Use marker at ${e}: ${t instanceof Error?t.message:String(t)}`}}function installAgentrixComputerUse(){let e=getComputerUseBridgeStatus();const t=[],n=[];if("darwin"!==process.platform)return{success:!1,status:e,actions:t,error:"Agentrix Computer Use currently requires macOS because Cua Driver is macOS-only."};if(!e.cuaDriverAvailable)return{success:!1,status:e,actions:t,error:"Cua Driver is not installed or not available. Install Cua Driver from Desktop first, or set AGENTRIX_CUA_DRIVER_PATH."};if(e.cuaDriverAvailable&&t.push(`Detected Cua Driver at ${e.cuaDriverPath??"PATH"}`),e.cuaDriverPath){const a=requestCuaDriverPermissions(e.cuaDriverPath);a?n.push(a):t.push("Checked Cua Driver permissions and opened macOS permission prompts for any missing grants.")}if(e.cuaDriverMcpConfigured)t.push("Cua Driver MCP is already configured for Agentrix Computer Use.");else{const a=runCuaDriverMcpConfig(e.codexHome);a?n.push(a):t.push("Configured Cua Driver MCP for Agentrix Computer Use.")}if(e=getComputerUseBridgeStatus(),e.cuaDriverSkillPresent)t.push("Cua Driver skill is already available to Agentrix Computer Use.");else{const a=ensureCuaDriverSkillSymlink(e.codexHome);a?n.push(a):t.push("Linked Cua Driver skill for Agentrix Computer Use.")}const a=enableComputerUseBridgeMarker(e.markerPath);a?n.push(a):e.enabled?t.push("Agentrix Computer Use was already enabled."):t.push("Enabled Agentrix Computer Use.");const s=enableComputerUseBridgeSettings();s&&n.push(s);const i=getComputerUseBridgeStatus(),o=0===n.length&&i.enabled&&0===i.missing.length;return{success:o,status:0===n.length?i:{...i,missing:[...i.missing,...n.map(e=>`Agentrix Computer Use install failed: ${e}`)]},actions:t,error:o?void 0:[...n,...i.missing].join("\n")||"Agentrix Computer Use is not ready."}}function removePathIfExists(e){try{return(fs.existsSync(e)||fs.lstatSync(e).isSymbolicLink())&&fs.rmSync(e,{recursive:!0,force:!0}),null}catch(t){return"ENOENT"===t.code?null:`Failed to remove ${e}: ${t instanceof Error?t.message:String(t)}`}}function removeSymlinkIfExists(e){try{return fs.lstatSync(e).isSymbolicLink()?(fs.unlinkSync(e),null):null}catch(t){return"ENOENT"===t.code?null:`Failed to remove symlink ${e}: ${t instanceof Error?t.message:String(t)}`}}function removeSkillSymlinkIfExists(e){try{if(!fs.lstatSync(e).isSymbolicLink())return null;const t=fs.readlinkSync(e);return t.includes("CuaDriver.app")||t.includes("cua-driver")?(fs.unlinkSync(e),null):null}catch(t){return"ENOENT"===t.code?null:`Failed to remove Cua Driver skill symlink ${e}: ${t instanceof Error?t.message:String(t)}`}}function removeCodexCuaDriverMcpConfig(e){const t=path.join(e,"config.toml");try{const n=resolveCodexPath();if(n.available&&n.path&&node_child_process.spawnSync(n.path,["mcp","remove","cua-driver"],{encoding:"utf8",env:{...process.env,CODEX_HOME:e}}),!fs.existsSync(t))return null;const a=fs.readFileSync(t,"utf8"),s=a.replace(/\n?\[mcp_servers\.(?:"cua-driver"|'cua-driver'|cua-driver|cua_driver)\][\s\S]*?(?=\n\[[^\]]+\]|\s*$)/g,"").replace(/\n{3,}/g,"\n\n").trimEnd()+"\n";return s!==a&&fs.writeFileSync(t,s,"utf8"),null}catch(e){return`Failed to remove Cua Driver MCP config from ${t}: ${e instanceof Error?e.message:String(e)}`}}function uninstallCuaDriver(e){const t=[],n=[],a=e.cuaDriverPath;a&&(node_child_process.spawnSync(a,["stop"],{encoding:"utf8",timeout:1e4}),t.push("Stopped Cua Driver daemon if it was running."));const s=["/Applications/CuaDriver.app","/Applications/CuaDriverRs.app",path.join(os.homedir(),"Library","LaunchAgents","com.trycua.cua_driver_updater.plist"),path.join(os.homedir(),"Library","LaunchAgents","com.trycua.cua_driver_daemon.plist"),path.join(os.homedir(),"Library","LaunchAgents","com.trycua.cua-driver-rs.plist"),path.join(os.homedir(),"Library","Application Support","Cua Driver"),path.join(os.homedir(),"Library","Caches","cua-driver"),path.join(os.homedir(),".cua-driver-rs")];for(const e of s){const a=removePathIfExists(e);a?n.push(a):t.push(`Removed ${e}.`)}for(const e of[path.join(os.homedir(),".local","bin","cua-driver"),"/usr/local/bin/cua-driver"]){const a=removeSymlinkIfExists(e);a?n.push(a):t.push(`Removed ${e}.`)}for(const a of[path.join(e.codexHome,"skills","cua-driver"),path.join(os.homedir(),".agents","skills","cua-driver")]){const e=removeSkillSymlinkIfExists(a);e?n.push(e):t.push(`Removed ${a}.`)}const i=removeCodexCuaDriverMcpConfig(e.codexHome);return i?n.push(i):t.push("Removed Cua Driver MCP config from Codex when present."),{actions:t,errors:n}}function uninstallAgentrixComputerUse(){const e=getComputerUseBridgeStatus(),t=[],n=[],a=removeComputerUseBridgeMarker(e.markerPath);a?n.push(a):"marker"===e.enabledBy?t.push("Removed Agentrix Computer Use enablement marker."):t.push("Agentrix Computer Use enablement marker is already absent or not the active source.");const s=disableComputerUseBridgeSettings();s?n.push(s):t.push("Disabled Agentrix Computer Use in settings.");const i=uninstallCuaDriver(e);t.push(...i.actions),n.push(...i.errors);const o=getComputerUseBridgeStatus();"env"===o.enabledBy&&n.push("Agentrix Computer Use is still enabled by AGENTRIX_COMPUTER_USE_ENABLED. Remove that environment variable and restart the daemon to complete uninstall.");const r=0===n.length&&!o.enabled;return{success:r,status:o,actions:t,error:r?void 0:n.join("\n")||"Agentrix Computer Use is still enabled."}}function ensureComputerUseBridgeConfigured(e=machine.machine.readSettings()){const t=getComputerUseBridgeStatus(e);if(!t.enabled)return t;const n=[];if(!t.cuaDriverMcpConfigured){logger$7.info("computer_use.configure_mcp");const e=runCuaDriverMcpConfig(t.codexHome);e&&n.push(e)}if(!t.cuaDriverSkillPresent){logger$7.info("computer_use.configure_skill");const e=ensureCuaDriverSkillSymlink(t.codexHome);e&&n.push(e)}const a=getComputerUseBridgeStatus(e);return 0===n.length?a:{...a,missing:[...a.missing,...n.map(e=>`Automatic Cua Driver configuration failed: ${e}`)]}}function buildComputerUseSetupMessage(e){const t=["Agentrix Computer Use execution bridge is not ready.","","Enablement: "+(e.enabled?`enabled by ${e.enabledBy}`:"disabled"),`Codex home checked: ${e.codexHome}`,""];return e.enabled||t.push("Enable it with one of:","- set AGENTRIX_COMPUTER_USE_ENABLED=true for the worker/daemon environment;","- set settings.json field agentrixComputerUse.enabled=true;",`- create marker file ${e.markerPath}.`,""),e.missing.length>0&&t.push("Missing configuration:",...e.missing.map(e=>`- ${e}`),""),t.push("Agentrix tries to configure Codex automatically after this bridge is enabled:","1. cua-driver mcp-config --client codex","2. link the Cua Driver SKILL.md pack into Codex when a valid local skill source can be discovered","If automatic configuration fails, run the official Cua Driver installer/update flow or set AGENTRIX_CUA_DRIVER_PATH / AGENTRIX_CUA_DRIVER_SKILL_SOURCE.","Grant macOS Accessibility and Screen Recording permissions to Cua Driver when prompted."),t.join("\n")}function buildComputerUseCodexPrompt(e){const t=e.expectedResult?.trim();return["You are the Agentrix Computer Use execution worker for the current Agentrix task.","","Use the configured Cua Driver skill and MCP tools in this Codex environment to operate the local computer. Do not implement or modify Agentrix code unless the desktop operation explicitly requires editing a file. Prefer Cua Driver app-control tools over shell commands for GUI work. If the request needs a permission grant or user login that you cannot complete, stop and explain exactly what the user must do.","","Desktop operation instruction:",e.instruction.trim(),"",t?`Expected result:\n${t}`:void 0,"","Return a concise report of what you did, what result you observed, and any blocker or follow-up required."].filter(e=>Boolean(e)).join("\n")}async function executeComputerUseBridge(e,t){if(!e.instruction.trim())throw new Error("instruction is required.");const n=t.status??ensureComputerUseBridgeConfigured();if(!n.enabled||n.missing.length>0)throw new Error(buildComputerUseSetupMessage(n));const a=buildComputerUseCodexPrompt(e),s=e.title?.trim()||"Computer use",i=t.historyDb.getAgentSessions().get("agentrix-computer-use");if(i)return logger$7.info(`Emitting computer-use instruction to existing sub-task ${i} for task ${t.taskId}`),await t.sendMessage({taskId:i,target:"agent",message:{type:"user",message:{role:"user",content:a},parent_tool_use_id:null,session_id:""}}),{taskId:i,title:s,action:"emitted"};logger$7.info(`Starting computer-use sub-task for task ${t.taskId}`);const o=await t.startSubTask({agentId:"codex",message:{type:"user",message:{role:"user",content:a},parent_tool_use_id:null,session_id:"new"},title:s,cwd:t.cwd,forceUserCwd:!0,initPolicies:{uncommittedChanges:"Ignore",branchMismatch:"Keep"}});return t.historyDb.upsertAgentSession("agentrix-computer-use",o.taskId),{taskId:o.taskId,title:s,action:"created"}}function formatGitLabPatValidationError(e,t){if(e.valid)return"";switch(e.status){case"insufficient_scope":{const t=e.missingScopes?.filter(Boolean).join(", ");return t?`GitLab PAT is missing required scopes: ${t}. Update or recreate the PAT with these scopes, then run the command again.`:"GitLab PAT is missing required scopes. Update or recreate the PAT with the required GitLab scopes, then run the command again."}case"expired":return"GitLab rejected this PAT because it is expired, revoked, or no longer accepted. Create a new GitLab PAT and run the command again.";case"network_error":return`Cannot reach the GitLab API at ${t}. Check the GitLab URL, network, VPN, or intranet access, then run the command again.`;case"invalid":return"Token is empty"===e.error?"GitLab PAT is required. Provide a token with --pat-file, stdin, or the interactive prompt.":"GitLab rejected this PAT. Check that you copied the full token, or create a new GitLab PAT and run the command again.";default:return e.error||`GitLab PAT validation failed for ${t}/user`}}function normalizeUrl$1(e,t){const n=e.trim();if(!n)throw new Error(`${t} is required`);let a;try{a=new URL(n)}catch{throw new Error(`${t} must be a valid URL`)}if("http:"!==a.protocol&&"https:"!==a.protocol)throw new Error(`${t} must use http or https`);return a.toString().replace(/\/+$/,"")}function parseBooleanEnv(e,t){if(void 0===e||""===e.trim())return t;const n=e.trim().toLowerCase();if(["true","1","yes"].includes(n))return!0;if(["false","0","no"].includes(n))return!1;throw new Error(`Invalid boolean value: ${e}`)}function readPatFromEnv(e){const t=e.GITLAB_TOKEN?.trim();if(t)return t;const n=e.GITLAB_TOKEN_FILE?.trim();if(!n)return null;if(!fs.existsSync(n))throw new Error(`GITLAB_TOKEN_FILE is not readable: ${n}`);return fs.readFileSync(n,"utf8").trim()}function readGitServerAutoConfigFromEnv(e=process.env){if(!parseBooleanEnv(e.AGENTRIX_GITLAB_AUTO_CONFIG,!0))return null;const t=e.GITLAB_BASE_URL?.trim(),n=readPatFromEnv(e);if(!t&&!n)return null;if(!t)throw new Error("GITLAB_BASE_URL is required when GITLAB_TOKEN is configured");if(!n)throw new Error("GITLAB_TOKEN or GITLAB_TOKEN_FILE is required when GITLAB_BASE_URL is configured");const a=normalizeUrl$1(t,"GITLAB_BASE_URL"),s=normalizeUrl$1(e.GITLAB_API_URL?.trim()||`${a}/api/v4`,"GITLAB_API_URL");return{name:e.AGENTRIX_GITLAB_NAME?.trim()||new URL(a).hostname,baseUrl:a,apiUrl:s,pat:n,useAsProxy:parseBooleanEnv(e.AGENTRIX_GITLAB_USE_AS_PROXY,!0)}}function withTimeout$1(e,t,n){let a;const s=new Promise((e,s)=>{a=setTimeout(()=>s(new Error(n)),t)});return Promise.race([e,s]).finally(()=>{a&&clearTimeout(a)})}async function machineRpc$1(e,t,n,a,s=15e3){if(!e.connected)throw new Error("Machine WebSocket is not connected");const i={eventId:shared.createEventId(),method:t,path:n,body:a},o=await withTimeout$1(e.sendWithAck("machine-rpc-call",i),s,`Timed out waiting for machine RPC ${t} ${n}`);if(!o.success)throw new Error(o.error?.message||`Machine RPC failed: ${t} ${n}`);return o.data}async function bindGitServerWithLocalPat(e,t,n){const a=await node.validateGitLabPatToken(n.apiUrl,n.pat,{log:{warn:(e,t)=>machine.logger.warn(e,t),error:(e,t)=>machine.logger.warn(e,t)}});if(!a.result.valid||!a.user)throw new Error(formatGitLabPatValidationError(a.result,n.apiUrl));const s=await getGitServerEncryptionKey();if(!s)throw new Error("No Agentrix auth secret found for GitLab configuration");const i=await machineRpc$1(e,"POST","/v1/git-servers/machine-bind",{name:n.name,baseUrl:n.baseUrl,apiUrl:n.apiUrl,machineId:t.machineId,pat:n.pat,useAsProxy:n.useAsProxy});if(!i.success||!i.gitServer)throw new Error("Backend Git server bind failed");const o=i.gitServer,r={username:a.user.username,email:a.user.email||"",lastValidatedAt:(new Date).toISOString(),expiresAt:a.result.expiresAt};saveGitServerConfig(o.id,{baseUrl:o.baseUrl,apiUrl:o.apiUrl}),savePat(o.id,n.pat,s),savePatMeta(o.id,r);const c=ensureGitLabWebhookSecret(o.id,s);return{success:!0,gitServer:o,machineId:i.machineId,proxyRegistered:i.proxyRegistered,webhookEndpointPath:node.buildGitLabWebhookEndpointPath(o.id),webhookUrl:node.buildGitLabWebhookUrl(o.id,await machine.machine.readDaemonState()),patConfigured:!0,patMeta:r,webhookSecret:c}}async function configureGitServerFromEnvironment(e,t){const n=readGitServerAutoConfigFromEnv();if(!n)return null;const a=await bindGitServerWithLocalPat(e,t,n),s=a.gitServer,i={gitServerId:s.id,baseUrl:s.baseUrl,apiUrl:s.apiUrl,webhookEndpointPath:a.webhookEndpointPath,webhookUrl:a.webhookUrl,proxyRegistered:a.proxyRegistered};return machine.logger.info(`[GIT SERVER] auto-configured from environment: gitServer=${i.gitServerId}, proxyRegistered=${i.proxyRegistered}`),i}function listWorkspaceFiles(e,t){const n=[],a=fs.readdirSync(e,{withFileTypes:!0});for(const s of a){if(".gitkeep"===s.name)continue;const a=path.join(e,s.name),i=fs.statSync(a),o=path.relative(t,a);n.push({name:s.name,path:o,size:i.size,modifiedAt:i.mtimeMs,isDirectory:s.isDirectory()}),s.isDirectory()&&n.push(...listWorkspaceFiles(a,t))}return n}function resolveCompanionHomeDir(){return path.join(machine.machine.agentrixAgentsHomeDir,"companion","claude")}function safeCompanionPath(e,t){const n=path.normalize(path.join(e,t));return n.startsWith(e)?{absolutePath:n,relativePath:path.relative(e,n)}:null}function parseAfterDate(e){const t=new Date(e);return Number.isNaN(t.getTime())?null:t}function previousUtcDayKey(e){const t=parseAfterDate(e);if(!t)return null;const n=new Date(Date.UTC(t.getUTCFullYear(),t.getUTCMonth(),t.getUTCDate()));n.setUTCDate(n.getUTCDate()-1);const a=n.toISOString();return{key:n.toISOString().slice(0,10),nextAfter:a}}function dateDayKey(e){if(!/^\d{4}-\d{2}-\d{2}$/.test(e))return null;const t=new Date(`${e}T00:00:00.000Z`);return Number.isNaN(t.getTime())?null:{key:e,nextAfter:t.toISOString()}}function normalizeMemoryEventRecord(e,t,n){const a=Array.isArray(e?.changes)?e.changes:[e],s=a.map(e=>e?.summary).filter(Boolean),i=a.flatMap(e=>Array.isArray(e?.reasons)?e.reasons:[]).filter(Boolean),o=a.map(e=>e?.file).filter(Boolean),r=a.map(e=>e?.action).filter(Boolean);return{id:n,createdAt:e?.time||e?.timestamp||e?.createdAt||t,title:e?.title||s[0]||"记忆已更新",summary:i.length?i.join("\n"):"",files:o,actions:r,source:e?.source,trigger:e?.trigger,commit:e?.commit}}function readCompanionMemoryEventsForDay(e,t,n){const a=path.join(e,"memory-changes"),s=path.join(a,`${t.key}.jsonl`),i=`${t.key}T00:00:00.000Z`,o=fs.existsSync(s)?fs.readFileSync(s,"utf-8").split("\n").map((e,n)=>{const a=e.trim();if(!a)return null;try{return normalizeMemoryEventRecord(JSON.parse(a),i,`${t.key}-${n}`)}catch{return null}}).filter(Boolean):[],r=fs.existsSync(a)&&fs.readdirSync(a).some(e=>/^\d{4}-\d{2}-\d{2}\.jsonl$/.test(e)&&e.slice(0,10)<t.key);return{...n,nextAfter:t.nextAfter,events:o.sort((e,t)=>new Date(t.createdAt).getTime()-new Date(e.createdAt).getTime()),hasMore:r}}function readCompanionMemoryEventsForQuery(e,t){if(t.date){const n=dateDayKey(t.date);return n?readCompanionMemoryEventsForDay(e,n,{date:t.date}):null}if(t.after){const n=previousUtcDayKey(t.after);return n?readCompanionMemoryEventsForDay(e,n,{after:t.after}):null}return null}function runCompanionGit(e,t){if(!fs.existsSync(path.join(e,".git")))return"";try{return node_child_process.execFileSync("git",["-C",e,...t],{encoding:"utf8",timeout:1e4,stdio:["ignore","pipe","ignore"]})}catch{return""}}function listCompanionFileVersions(e,t,n={}){const a=Math.min(Math.max(n.limit??10,1),50),s=Math.max(n.skip??0,0),i=runCompanionGit(e,["log",`--max-count=${a+1}`,`--skip=${s}`,"--date=iso-strict","--pretty=format:%H%x1f%h%x1f%aI%x1f%s%x1f%b%x1e","--",t]).split("").map(e=>e.trim()).filter(Boolean).map(e=>{const[t,n,a,s,i]=e.split("");return{commit:t||"",shortCommit:n||"",authoredAt:a||"",subject:s||"没有详细变更说明",body:i?.trim()||""}}).filter(e=>e.commit.length>0);return{versions:i.slice(0,a),hasMore:i.length>a,nextSkip:s+Math.min(i.length,a)}}function readCompanionFileDiff(e,t,n){const a=n.replace(/[^0-9a-f]/gi,"");return a?runCompanionGit(e,["show","--format=","--no-ext-diff",a,"--",t]):""}function summarizeStructuredCompanionValue(e){if(!e||"object"!=typeof e)return"";const t=e,n=(Array.isArray(t.changes)?t.changes:[]).map(e=>e&&"object"==typeof e?e.summary:null).filter(e=>"string"==typeof e&&e.trim().length>0);if(n.length)return n.join(";");const a=t.input;if(a&&"object"==typeof a){const e=summarizeStructuredCompanionValue(a);if(e)return e}for(const e of["result","summary","title","content","text","message"]){const n=t[e];if("string"==typeof n&&n.trim())return n;if(n&&"object"==typeof n){const e=summarizeStructuredCompanionValue(n);if(e)return e}}return""}function stringifyMessageForConsole(e){if("string"==typeof e){const t=e.trim();if(t.startsWith("{")&&t.endsWith("}")||t.startsWith("[")&&t.endsWith("]"))try{const e=summarizeStructuredCompanionValue(JSON.parse(t));if(e)return e}catch{}return e}if(!e||"object"!=typeof e)return"";const t=summarizeStructuredCompanionValue(e);if(t)return t;const n=e.content;return"string"==typeof n?stringifyMessageForConsole(n):Array.isArray(n)?n.map(e=>stringifyMessageForConsole(e)).filter(Boolean).join("\n"):""}function companionDisplayText(e,t){return stringifyMessageForConsole(e).trim()||t}function companionRecordHasUpdate(e){return!/(no\s+(memory\s+)?changes?\s+(needed|required|found|detected)|no\s+updates?\s+(needed|required|found|detected)|无需.*(更新|变更|修改|创建|新增|删除)|不需要.*(更新|变更|修改|创建|新增|删除)|没有.*(更新|变更|修改|创建|新增|删除)|无.*(更新|变更|修改|创建|新增|删除)|未.*(发现|检测到).*(更新|变更|修改|创建|新增|删除))/i.test(e)&&/更新|updated|created|deleted|修改|创建|新增|删除|memory change|memory changes/i.test(e)}function isCompanionMemoryOrganizationTrigger(e){return!!e&&"object"==typeof e&&"companion_memory_organization"===e.type}function isRecordMemoryChangeToolUse(e){if(!e)return!1;if(Array.isArray(e))return e.some(isRecordMemoryChangeToolUse);if("object"!=typeof e)return!1;const t=e;return"tool_use"===t.type&&("mcp__agentrix__record_memory_change"===t.name||"record_memory_change"===t.name)||Object.values(t).some(isRecordMemoryChangeToolUse)}function extractResultText(e){if(!e||"object"!=typeof e)return"";const t=e;return"result"===t.type&&"string"==typeof t.result?t.result:""}function readRecentLocalTaskMessages(e,t,n=1){if(!e||!t)return[];try{const a=getTaskDb({dataDir:machine.machine.resolveDataDir(e,t),taskId:t});try{return[...a.pageRecentMessages(50).data].reverse().filter(e=>"system"!==e.senderType&&stringifyMessageForConsole(e.message).trim()).slice(0,n).map(e=>({summary:companionDisplayText(stringifyMessageForConsole(e.message),""),time:e.createdAt}))}finally{a.close()}}catch{return[]}}function readRecentCompanionChatActivity(e,t=1){return readRecentLocalTaskMessages("string"==typeof e.userId?e.userId:null,"string"==typeof e.chatTaskId?e.chatTaskId:null,t).map(e=>({type:"chat",title:"Companion Chat",summary:e.summary,time:e.time}))}async function readRecentCompanionTaskActivity(e,t,n=1){const a="string"==typeof e.chatId?e.chatId:null;if(!a)return[];try{const s=new URLSearchParams({chatId:a,limit:String(Math.min(Math.max(3*n,10),50))}),i=await machineRpc(t,"GET",`/v1/tasks/recent?${s.toString()}`,void 0,1e4);return Array.isArray(i.tasks)?i.tasks.filter(e=>!["completed","cancelled","error"].includes(String(e.state))).slice(0,n).map(t=>{const n="string"==typeof t.taskId?t.taskId:"",a="string"==typeof t.title&&t.title.trim()?t.title.trim():"Task",s=readRecentLocalTaskMessages("string"==typeof e.userId?e.userId:null,n,1)[0];return{type:"task",title:a,summary:s?.summary||"",time:s?.time||t.updatedAt||t.createdAt||(new Date).toISOString()}}):[]}catch{return[]}}function readRecentCompanionMemoryActivity(e,t=1){const n=path.join(e,"memory-changes");if(!fs.existsSync(n))return[];const a=fs.readdirSync(n).filter(e=>/^\d{4}-\d{2}-\d{2}\.jsonl$/.test(e)).sort().reverse(),s=[];for(const n of a){const a=n.slice(0,10),i=readCompanionMemoryEventsForDay(e,{key:a,nextAfter:`${a}T00:00:00.000Z`},{date:a});for(const e of i.events){const n=companionDisplayText(e.summary||e.files.join(", ")||e.title,"记忆已更新");if(s.push({type:"memory",title:e.title||"记忆已更新",summary:n,time:String(e.createdAt)}),s.length>=t)return s}}return s}function readCompanionMemoryOrganizationRecentRecords(e,t){const n=[],a=getTaskDb({dataDir:machine.machine.resolveDataDir(e,t),taskId:t});try{let e=!1,t=!1;for(const s of a.pageRecentTaskEvents(1e3).data){const a=s.eventData,i=a.message;if(isCompanionMemoryOrganizationTrigger(i)){e=!0,t=!1;continue}if(!e)continue;isRecordMemoryChangeToolUse(i)&&(t=!0);const o="agent"===a.senderType?extractResultText(i):"";o&&(n.push({time:s.createdAt,summary:companionDisplayText(o,"记忆整理已运行"),updated:t}),e=!1,t=!1)}}finally{a.close()}return n}function readCompanionRecentRecords(e,t,n=1){const a="string"==typeof e.userId?e.userId:null,s="string"==typeof e.chatTaskId?e.chatTaskId:null;if(!a||!s)return[];const i=("heartbeat"===t?[e.heartbeatTaskId,e.heartbeatShadowTaskId]:[e.memoryOrganizationTaskId,e.memoryOrganizationShadowTaskId]).filter(e=>"string"==typeof e&&e.length>0),o=[s,...i],r="heartbeat"===t?["heartbeat","心跳","reminder","待处理事项"]:["memory organization","memory-organization","记忆整理","companion_memory_organization","memory review","memory changes","记忆更新"],c=[];if("memory-organization"===t){for(const e of[...new Set(i)])try{c.push(...readCompanionMemoryOrganizationRecentRecords(a,e))}catch{}if(c.length>0)return normalizeCompanionRecentRecords(c,n)}for(const e of[...new Set(o)]){const n=i.includes(e);try{const s=getTaskDb({dataDir:machine.machine.resolveDataDir(a,e),taskId:e});try{for(const e of s.pageRecentMessages(160).data){if("agent"!==e.senderType)continue;const a=stringifyMessageForConsole(e.message);if(!a.trim())continue;if(!n&&!r.some(e=>a.toLowerCase().includes(e.toLowerCase())))continue;const s=companionDisplayText(a,"heartbeat"===t?"Heartbeat 已运行":"记忆整理已运行");c.push({time:e.createdAt,summary:s,updated:companionRecordHasUpdate(a)})}}finally{s.close()}}catch{}}return normalizeCompanionRecentRecords(c,n)}function normalizeCompanionRecentRecords(e,t=1){const n=new Set;return e.sort((e,t)=>new Date(t.time).getTime()-new Date(e.time).getTime()).filter(e=>{const t=`${e.time}:${e.summary}`;return!n.has(t)&&(n.add(t),!0)}).slice(0,t)}function secureTokenEquals(e,t){if("string"!=typeof e)return!1;const n=Buffer.from(e),a=Buffer.from(t);return n.length===a.length&&node_crypto.timingSafeEqual(n,a)}function isLoopbackAddress(e){return"127.0.0.1"===e||"::1"===e||"::ffff:127.0.0.1"===e}function getGitLabEventType(e){const t=e.event_type??e.object_kind;return"string"==typeof t?t:"unknown"}function summarizeGitLabWebhookPipeline(e){if(!e||"object"!=typeof e)return"-";const t=e,n=t.id??t.iid??"-",a=t.status??"-",s=t.ref??"-",i=t.web_url??t.webUrl??"-";return`id=${String(n)}, status=${String(a)}, ref=${String(s)}, webUrl=${String(i)}`}function summarizeGitLabWebhookResponse(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??"-"),a=String(t.eventType??"-"),s=String(t.eventName??"-"),i=String(t.action??"-"),o=String(t.reason??"-"),r=String(t.upstreamStatus??"-"),c=String(t.errorMessage??"-");return`status=${n}, eventType=${a}, eventName=${s}, action=${i}, reason=${o}, triggeredCount=${String(t.triggeredCount??"-")}, failedCount=${String(t.failedCount??"-")}, upstreamStatus=${r}, errorMessage=${c}, pipeline=${summarizeGitLabWebhookPipeline(t.pipeline)}`}const GitServerResponseSchema=zod.z.object({id:zod.z.string(),type:zod.z.string(),name:zod.z.string(),baseUrl:zod.z.string(),apiUrl:zod.z.string(),oauthServerId:zod.z.string().nullable().optional(),ownerId:zod.z.string().nullable().optional(),authModeDefault:zod.z.string().optional(),executionMode:zod.z.string().optional(),syncMode:zod.z.string().optional(),networkMode:zod.z.string().optional(),githubAppName:zod.z.string().nullable().optional(),enabled:zod.z.boolean().optional(),createdAt:zod.z.string().optional(),updatedAt:zod.z.string().optional()}).passthrough(),ComputerUseBridgeStatusSchema=zod.z.object({platform:zod.z.string(),enabled:zod.z.boolean(),enabledBy:zod.z.enum(["env","settings","marker"]).nullable(),codexHome:zod.z.string(),codexAvailable:zod.z.boolean(),codexPath:zod.z.string().optional(),codexConfigPresent:zod.z.boolean(),cuaDriverAvailable:zod.z.boolean(),cuaDriverPath:zod.z.string().optional(),cuaDriverAccessibilityGranted:zod.z.boolean().optional(),cuaDriverScreenRecordingGranted:zod.z.boolean().optional(),cuaDriverMcpConfigured:zod.z.boolean(),cuaDriverSkillPresent:zod.z.boolean(),cuaDriverSkillSource:zod.z.string().optional(),markerPath:zod.z.string(),missing:zod.z.array(zod.z.string())}),REPOSITORY_INBOX_WEBHOOK_ACK_TIMEOUT_MS=5e3;async function withTimeout(e,t,n){let a;try{return await Promise.race([e,new Promise((e,s)=>{a=setTimeout(()=>s(new Error(n)),t)})])}finally{a&&clearTimeout(a)}}function getHeaderString(e){return Array.isArray(e)?e[0]:e}function getGitLabWebhookDeliveryHeader(e){return getHeaderString(e["webhook-id"])??getHeaderString(e["idempotency-key"])??getHeaderString(e["x-gitlab-webhook-uuid"])??getHeaderString(e["x-gitlab-event-uuid"])??getHeaderString(e["x-gitlab-delivery"])}function formatApiError(e){return e instanceof Error?e.message:"Unknown error"}async function reportRepositoryInboxWebhook(e,t,n,a,s){if(!s?.connected)throw new Error("Machine WebSocket is not connected");const i={eventId:shared.createEventId(),provider:"gitlab",gitServerId:e,deliveryId:n,eventType:a,payload:t},o=await withTimeout(s.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")}async function machineRpc(e,t,n,a,s=15e3){if(!e?.connected)throw new Error("Machine WebSocket is not connected");const i={eventId:shared.createEventId(),method:t,path:n,body:a},o=await withTimeout(e.sendWithAck("machine-rpc-call",i),s,`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 startDaemonControlServer(e){const{getChildren:t,stopSession:n,startDevOpsInit:a,completeDevOpsInit:s,requestShutdown:i,registerSession:o,credentials:r,getSocketClient:c,prepareGracefulRestart:l,clearGracefulRestartGate:d}=e;return new Promise(p=>{const u=machine.machine.getDaemonControlHost(),m=machine.machine.getDaemonWebhookHost(),h=fastify({logger:!1});h.removeContentTypeParser("application/json"),h.addContentTypeParser("application/json",{parseAs:"string"},(e,t,n)=>{const a="string"==typeof t?t:t.toString("utf8");if(0!==a.trim().length)try{n(null,JSON.parse(a))}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(fastifyTypeProviderZod.validatorCompiler),h.setSerializerCompiler(fastifyTypeProviderZod.serializerCompiler);const g=h.withTypeProvider();registerAgentrixEventMcpBrokerRoutes(h,{credentials:r,getSocketClient:c});const f=e=>{e.header("Access-Control-Allow-Origin","*"),e.header("Access-Control-Allow-Methods","GET, POST, PUT, DELETE, OPTIONS"),e.header("Access-Control-Allow-Headers","Content-Type"),e.header("Access-Control-Allow-Private-Network","true")};g.post("/session-started",{schema:{body:zod.z.object({sessionId:zod.z.string(),metadata:zod.z.any()}),response:{200:zod.z.object({status:zod.z.literal("ok")})}}},async e=>{const{sessionId:t,metadata:n}=e.body;return machine.logger.debug(`[CONTROL SERVER] Session started: ${t}`),o(t,n),{status:"ok"}}),g.post("/devops-init-complete",{schema:{body:zod.z.object({taskId:zod.z.string(),userId:zod.z.string(),action:zod.z.enum(["continue","stop"])}),response:{200:zod.z.object({status:zod.z.literal("ok")})}}},async e=>{const{taskId:t,userId:n,action:a}=e.body;return machine.logger.info(`[CONTROL SERVER] Agentrix DevOps init complete for task ${t}, action=${a}`),s?.({taskId:t,userId:n,action:a}),{status:"ok"}}),g.post("/devops-init-start",{schema:{body:zod.z.object({taskId:zod.z.string(),userId:zod.z.string()}),response:{200:zod.z.object({status:zod.z.literal("ok")})}}},async e=>{const{taskId:t,userId:n}=e.body;return machine.logger.info(`[CONTROL SERVER] Starting Agentrix DevOps init for existing task ${t}`),a?.({taskId:t,userId:n}),{status:"ok"}}),g.post("/prepare-graceful-restart",{schema:{body:zod.z.object({source:zod.z.string().optional(),reason:zod.z.string().optional()}).optional(),response:{200:zod.z.object({state:zod.z.enum(["pending_restart","restarting"]),activeSessions:zod.z.number()}),503:zod.z.object({error:zod.z.string()}),403:zod.z.object({error:zod.z.string()})}}},async(e,t)=>isLoopbackAddress(e.ip)?l?l({source:e.body?.source??"control-server",reason:e.body?.reason}):t.code(503).send({error:"Graceful restart gate is not available"}):t.code(403).send({error:"Graceful restart control is only allowed from loopback"})),g.post("/clear-graceful-restart-gate",{schema:{response:{200:zod.z.object({success:zod.z.literal(!0)}),403:zod.z.object({error:zod.z.string()})}}},async(e,t)=>isLoopbackAddress(e.ip)?(d?.(),{success:!0}):t.code(403).send({error:"Graceful restart control is only allowed from loopback"})),g.options("/ping",async(e,t)=>(f(t),t.send())),g.get("/ping",{schema:{response:{200:zod.z.object({status:zod.z.literal("ok"),machineId:zod.z.string(),timestamp:zod.z.string(),controlHost:zod.z.string(),webhookHost:zod.z.string(),hasMachineAesKey:zod.z.boolean()})}}},async(e,t)=>(f(t),{status:"ok",machineId:r.machineId,timestamp:(new Date).toISOString(),controlHost:u,webhookHost:m,hasMachineAesKey:hasValidMachineAesKey(r)})),g.get("/computer-use/status",{schema:{response:{200:zod.z.object({status:ComputerUseBridgeStatusSchema}),403:zod.z.object({error:zod.z.string()})}}},async(e,t)=>isLoopbackAddress(e.ip)?{status:getComputerUseBridgeStatus()}:t.code(403).send({error:"Computer Use status is only allowed from loopback"})),g.post("/computer-use/install",{schema:{response:{200:zod.z.object({success:zod.z.boolean(),status:ComputerUseBridgeStatusSchema,actions:zod.z.array(zod.z.string()),error:zod.z.string().optional()}),403:zod.z.object({error:zod.z.string()})}}},async(e,t)=>{if(!isLoopbackAddress(e.ip))return t.code(403).send({error:"Computer Use installation is only allowed from loopback"});try{return installAgentrixComputerUse()}catch(e){return{success:!1,status:getComputerUseBridgeStatus(),actions:[],error:formatApiError(e)}}}),g.post("/computer-use/uninstall",{schema:{response:{200:zod.z.object({success:zod.z.boolean(),status:ComputerUseBridgeStatusSchema,actions:zod.z.array(zod.z.string()),error:zod.z.string().optional()}),403:zod.z.object({error:zod.z.string()})}}},async(e,t)=>{if(!isLoopbackAddress(e.ip))return t.code(403).send({error:"Computer Use uninstall is only allowed from loopback"});try{return uninstallAgentrixComputerUse()}catch(e){return{success:!1,status:getComputerUseBridgeStatus(),actions:[],error:formatApiError(e)}}}),g.post("/machine/aes-key",{schema:{body:zod.z.object({machineId:zod.z.string(),machineAesKey:zod.z.string()}),response:{200:zod.z.object({success:zod.z.literal(!0),updated:zod.z.boolean(),hasMachineAesKey:zod.z.literal(!0)}),400:zod.z.object({error:zod.z.string()}),403:zod.z.object({error:zod.z.string()}),409:zod.z.object({error:zod.z.string()}),500:zod.z.object({error:zod.z.string()})}}},async(e,t)=>{if(!isLoopbackAddress(e.ip))return t.code(403).send({error:"machine AES key recovery is only allowed from loopback"});try{const t=await storeRecoveredMachineAesKey(r,e.body);return machine.logger.info(t.updated?`[CONTROL SERVER] Recovered machine AES key stored for ${r.machineId}`:`[CONTROL SERVER] Machine AES key already present for ${r.machineId}`),t}catch(e){const n=e instanceof MachineAesKeyUpdateError?e.statusCode:500,a=400===n||409===n?n:500,s=e instanceof Error?e.message:"Failed to store machine AES key";return machine.logger.warn(`[CONTROL SERVER] Failed to store recovered machine AES key: ${s}`),t.code(a).send({error:s})}}),g.options("/openers",async(e,t)=>(f(t),t.send())),g.get("/openers",{schema:{response:{200:zod.z.object({openers:zod.z.array(zod.z.object({id:zod.z.string(),label:zod.z.string(),kind:zod.z.enum(["system","file-manager","terminal","editor","ide"]),method:zod.z.enum(["scheme","cli"]),urlTemplate:zod.z.string().optional(),supported:zod.z.boolean()}))})}}},async(e,t)=>(f(t),{openers:await listOpeners()})),g.options("/open",async(e,t)=>(f(t),t.send())),g.options("/pick-directory",async(e,t)=>(f(t),t.send())),g.options("/validate-directory",async(e,t)=>(f(t),t.send())),g.post("/open",{schema:{body:zod.z.object({path:zod.z.string(),openerId:zod.z.string(),userId:zod.z.string().optional(),taskId:zod.z.string().optional()}),response:{200:zod.z.object({success:zod.z.boolean(),error:zod.z.string().optional()})}}},async(e,t)=>{f(t);const{path:n,openerId:a,userId:s,taskId:i}=e.body;return await openWithOpener({openerId:a,targetPath:n,userId:s,taskId:i})}),g.post("/pick-directory",{schema:{body:zod.z.object({defaultPath:zod.z.string().optional()}),response:{200:zod.z.object({path:zod.z.string().nullable(),error:zod.z.string().optional()})}}},async(e,t)=>{f(t);try{return{path:pickDirectory(e.body.defaultPath)??null}}catch(e){return{path:null,error:e instanceof Error?e.message:"Failed to pick directory"}}}),g.post("/validate-directory",{schema:{body:zod.z.object({path:zod.z.string()}),response:{200:zod.z.object({ok:zod.z.boolean(),status:zod.z.enum(["active","missing","permission_lost"]),error:zod.z.string().optional()})}}},async(e,t)=>{f(t);try{if(!fs.statSync(e.body.path).isDirectory())return{ok:!1,status:"missing",error:"Path is not a directory"};try{fs.accessSync(e.body.path,fs.constants.R_OK|fs.constants.W_OK)}catch{return{ok:!1,status:"permission_lost",error:"Directory is not readable and writable"}}return{ok:!0,status:"active"}}catch(e){return{ok:!1,status:"missing",error:e instanceof Error?e.message:"Directory is unavailable"}}}),g.post("/companion/ensure",{schema:{body:zod.z.object({preferredLanguage:zod.z.enum(["en","zh-Hans"]).nullable().optional()}).optional(),response:{200:zod.z.object({agentDir:zod.z.string()})}}},async e=>await ensureCompanionAgent({preferredLanguage:e.body?.preferredLanguage,credentials:r})),g.post("/companion/probe",{schema:{response:{200:zod.z.object({success:zod.z.boolean(),error:zod.z.string().optional()})}}},async()=>await probeCompanionChain()),g.get("/companion/workspace/status",{schema:{response:{200:zod.z.object({exists:zod.z.boolean()})}}},async()=>{const e=resolveCompanionHomeDir();return{exists:fs.existsSync(e)}}),g.get("/companion/workspace",{schema:{response:{200:zod.z.object({files:zod.z.array(zod.z.object({name:zod.z.string(),path:zod.z.string(),size:zod.z.number(),modifiedAt:zod.z.number(),isDirectory:zod.z.boolean()}))})}}},async()=>{const e=resolveCompanionHomeDir();return fs.existsSync(e)?{files:listWorkspaceFiles(e,e)}:{files:[]}}),g.get("/companion/file",{schema:{querystring:zod.z.object({path:zod.z.string()}),response:{200:zod.z.object({content:zod.z.string()}),404:zod.z.object({error:zod.z.string()})}}},async(e,t)=>{const n=resolveCompanionHomeDir(),a=path.normalize(path.join(n,e.query.path));return a.startsWith(n)&&fs.existsSync(a)?{content:fs.readFileSync(a,"utf-8")}:t.code(404).send({error:"File not found"})}),g.put("/companion/file",{schema:{body:zod.z.object({path:zod.z.string(),content:zod.z.string()}),response:{200:zod.z.object({success:zod.z.boolean()}),400:zod.z.object({error:zod.z.string()})}}},async(e,t)=>{const n=resolveCompanionHomeDir(),a=path.normalize(path.join(n,e.body.path));return a.startsWith(n)?(fs.mkdirSync(path.dirname(a),{recursive:!0}),fs.writeFileSync(a,e.body.content,"utf-8"),{success:!0}):t.code(400).send({error:"Invalid path"})}),g.get("/companion/file/versions",{schema:{querystring:zod.z.object({path:zod.z.string(),limit:zod.z.coerce.number().int().positive().max(50).optional(),skip:zod.z.coerce.number().int().min(0).optional()}),response:{200:zod.z.object({versions:zod.z.array(zod.z.object({commit:zod.z.string(),shortCommit:zod.z.string(),subject:zod.z.string(),body:zod.z.string(),authoredAt:zod.z.string()})),hasMore:zod.z.boolean(),nextSkip:zod.z.number()}),404:zod.z.object({error:zod.z.string()})}}},async(e,t)=>{const n=resolveCompanionHomeDir(),a=safeCompanionPath(n,e.query.path);return a&&fs.existsSync(a.absolutePath)?listCompanionFileVersions(n,a.relativePath,{limit:e.query.limit??10,skip:e.query.skip??0}):t.code(404).send({error:"File not found"})}),g.get("/companion/file/diff",{schema:{querystring:zod.z.object({path:zod.z.string(),commit:zod.z.string()}),response:{200:zod.z.object({commit:zod.z.string(),path:zod.z.string(),diff:zod.z.string()}),404:zod.z.object({error:zod.z.string()})}}},async(e,t)=>{const n=resolveCompanionHomeDir(),a=safeCompanionPath(n,e.query.path);return a&&fs.existsSync(a.absolutePath)?{commit:e.query.commit,path:a.relativePath,diff:readCompanionFileDiff(n,a.relativePath,e.query.commit)}:t.code(404).send({error:"File not found"})}),g.get("/companion/memory-events",{schema:{querystring:zod.z.object({after:zod.z.string().optional(),date:zod.z.string().optional()}),response:{200:zod.z.object({after:zod.z.string().optional(),date:zod.z.string().optional(),nextAfter:zod.z.string(),events:zod.z.array(zod.z.object({id:zod.z.string(),createdAt:zod.z.union([zod.z.string(),zod.z.number()]),title:zod.z.string(),summary:zod.z.string(),files:zod.z.array(zod.z.string()),actions:zod.z.array(zod.z.string()).optional(),source:zod.z.string().optional(),trigger:zod.z.string().optional(),commit:zod.z.string().optional()})),hasMore:zod.z.boolean()}),400:zod.z.object({error:zod.z.string()})}}},async(e,t)=>{const n=resolveCompanionHomeDir();if(!e.query.after&&!e.query.date)return t.code(400).send({error:"Use after or date"});return readCompanionMemoryEventsForQuery(n,e.query)||t.code(400).send({error:"Invalid after or date"})}),g.get("/companion/recent-activity",{schema:{querystring:zod.z.object({limit:zod.z.coerce.number().int().positive().max(50).optional()}),response:{200:zod.z.object({chats:zod.z.array(zod.z.object({type:zod.z.literal("chat"),title:zod.z.string(),summary:zod.z.string(),time:zod.z.string(),status:zod.z.string().optional()})),tasks:zod.z.array(zod.z.object({type:zod.z.literal("task"),title:zod.z.string(),summary:zod.z.string(),time:zod.z.string(),status:zod.z.string().optional()})),memories:zod.z.array(zod.z.object({type:zod.z.literal("memory"),title:zod.z.string(),summary:zod.z.string(),time:zod.z.string(),status:zod.z.string().optional()}))})}}},async e=>{const t=resolveCompanionHomeDir(),n=e.query.limit??1,a=path.join(t,"state.json");let s={};if(fs.existsSync(a))try{s=JSON.parse(fs.readFileSync(a,"utf-8"))}catch{s={}}const[i,o,r]=await Promise.all([readRecentCompanionTaskActivity(s,c?.(),n),Promise.resolve(readRecentCompanionChatActivity(s,n)),Promise.resolve(readRecentCompanionMemoryActivity(t,n))]);return{chats:o,tasks:i,memories:r}}),g.get("/companion/config",{schema:{querystring:zod.z.object({recentLimit:zod.z.coerce.number().int().positive().max(50).optional()}),response:{200:zod.z.object({heartbeatIntervalMs:zod.z.number(),heartbeatEnabled:zod.z.boolean(),lastHeartbeatTimestamp:zod.z.string().nullable(),lastHeartbeatDate:zod.z.string().nullable(),lastMaintenanceHeartbeatTimestamp:zod.z.string().nullable(),heartbeatTriggerCount:zod.z.number(),lastInteractionTimestamp:zod.z.string().nullable(),memoryOrganizationEnabled:zod.z.boolean(),memoryOrganizationIntervalHours:zod.z.number(),allowedMemoryOrganizationIntervalHours:zod.z.array(zod.z.number()),lastMemoryOrganizationTimestamp:zod.z.string().nullable(),memoryOrganizationTaskId:zod.z.string().nullable(),heartbeatRecentRecords:zod.z.array(zod.z.object({time:zod.z.string(),summary:zod.z.string(),updated:zod.z.boolean()})),memoryOrganizationRecentRecords:zod.z.array(zod.z.object({time:zod.z.string(),summary:zod.z.string(),updated:zod.z.boolean()}))})}}},async e=>{const t=resolveCompanionHomeDir(),n=e.query.recentLimit??1,a=path.join(t,"state.json");let s=9e5,i=!1,o=null,r=null,c=null,l=0,d=null,p=!1,u=4,m=null,h=null,g={};if(fs.existsSync(a))try{g=JSON.parse(fs.readFileSync(a,"utf-8")),"number"==typeof g.heartbeatIntervalMs&&(s=g.heartbeatIntervalMs),"boolean"==typeof g.heartbeatEnabled&&(i=g.heartbeatEnabled),"string"==typeof g.lastHeartbeatTimestamp&&(o=g.lastHeartbeatTimestamp),"string"==typeof g.lastHeartbeatDate&&(r=g.lastHeartbeatDate),"string"==typeof g.lastMaintenanceHeartbeatTimestamp&&(c=g.lastMaintenanceHeartbeatTimestamp),"number"==typeof g.heartbeatTriggerCount&&(l=g.heartbeatTriggerCount),"string"==typeof g.lastInteractionTimestamp&&(d=g.lastInteractionTimestamp),"boolean"==typeof g.memoryOrganizationEnabled&&(p=g.memoryOrganizationEnabled),u=normalizeMemoryOrganizationIntervalHours(g.memoryOrganizationIntervalHours),"string"==typeof g.lastMemoryOrganizationTimestamp&&(m=g.lastMemoryOrganizationTimestamp),"string"==typeof g.memoryOrganizationTaskId&&(h=g.memoryOrganizationTaskId)}catch{}const f=readCompanionRecentRecords(g,"heartbeat",n),y=readCompanionRecentRecords(g,"memory-organization",n);return{heartbeatIntervalMs:s,heartbeatEnabled:i,lastHeartbeatTimestamp:o,lastHeartbeatDate:r,lastMaintenanceHeartbeatTimestamp:c,heartbeatTriggerCount:l,lastInteractionTimestamp:d,memoryOrganizationEnabled:p,memoryOrganizationIntervalHours:u,allowedMemoryOrganizationIntervalHours:[...ALLOWED_MEMORY_ORGANIZATION_INTERVAL_HOURS],lastMemoryOrganizationTimestamp:m,memoryOrganizationTaskId:h,heartbeatRecentRecords:f,memoryOrganizationRecentRecords:y}}),g.put("/companion/config",{schema:{body:zod.z.object({heartbeatIntervalMs:zod.z.number().optional(),heartbeatEnabled:zod.z.boolean().optional(),memoryOrganizationEnabled:zod.z.boolean().optional(),memoryOrganizationIntervalHours:zod.z.number().optional()}),response:{200:zod.z.object({success:zod.z.boolean()}),400:zod.z.object({error:zod.z.string()})}}},async(t,n)=>{const a=resolveCompanionHomeDir(),s=path.join(a,"state.json");let i={};if(fs.existsSync(s))try{i=JSON.parse(fs.readFileSync(s,"utf-8"))}catch{}const{heartbeatIntervalMs:o,heartbeatEnabled:r,memoryOrganizationEnabled:c,memoryOrganizationIntervalHours:l}=t.body;if(void 0!==o&&(i.heartbeatIntervalMs=o),void 0!==r&&(i.heartbeatEnabled=r),void 0!==c&&(i.memoryOrganizationEnabled=c),void 0!==l){if(!isAllowedMemoryOrganizationIntervalHours(l))return n.code(400).send({error:`memoryOrganizationIntervalHours must be one of: ${ALLOWED_MEMORY_ORGANIZATION_INTERVAL_HOURS.join(", ")}`});i.memoryOrganizationIntervalHours=l}return fs.mkdirSync(path.dirname(s),{recursive:!0}),fs.writeFileSync(s,JSON.stringify(i,null,2),"utf-8"),e.companionScheduler?.reloadStateAndReschedule(),{success:!0}}),g.post("/agent/install",{schema:{body:zod.z.object({agentId:zod.z.string(),gitUrl:zod.z.string(),branch:zod.z.string().optional(),subDir:zod.z.string().optional()}),response:{200:zod.z.object({agentDir:zod.z.string()}),500:zod.z.object({error:zod.z.string()})}}},async(e,t)=>{try{return await installAgentFromGit(e.body)}catch(e){const n=e instanceof Error?e.message:String(e);return t.code(500).send({error:n})}}),g.post("/git-server/bind",{schema:{body:zod.z.object({name:zod.z.string().min(1),baseUrl:zod.z.string().url(),apiUrl:zod.z.string().url(),pat:zod.z.string().min(1),useAsProxy:zod.z.boolean().optional().default(!0)}),response:{200:zod.z.object({success:zod.z.literal(!0),gitServer:GitServerResponseSchema,machineId:zod.z.string(),proxyRegistered:zod.z.boolean(),webhookEndpointPath:zod.z.string(),webhookUrl:zod.z.string().optional(),patConfigured:zod.z.literal(!0),patMeta:zod.z.object({username:zod.z.string(),email:zod.z.string(),lastValidatedAt:zod.z.string(),expiresAt:zod.z.string().nullable().optional()}),webhookSecret:zod.z.string()}),502:zod.z.object({error:zod.z.string()})}}},async(e,t)=>{try{const n=c?.();if(!n)throw new Error("Machine WebSocket is not connected");const a=await bindGitServerWithLocalPat(n,r,{name:e.body.name,baseUrl:e.body.baseUrl,apiUrl:e.body.apiUrl,pat:e.body.pat,useAsProxy:e.body.useAsProxy});return t.send(a)}catch(n){const a=formatApiError(n);return machine.logger.warn(`[GIT SERVER] bind failed: baseUrl=${e.body.baseUrl}, message=${a}`),t.code(502).send({error:a})}}),g.post("/git-server/list",{schema:{response:{200:zod.z.object({gitServers:zod.z.array(GitServerResponseSchema)}),502:zod.z.object({error:zod.z.string()})}}},async(e,t)=>{try{const e=await machineRpc(c?.(),"POST","/v1/git-servers/machine-list",{machineId:r.machineId});return t.send({gitServers:Array.isArray(e)?e:[]})}catch(e){const n=formatApiError(e);return machine.logger.warn(`[GIT SERVER] list failed: message=${n}`),t.code(502).send({error:n})}}),g.post("/git-server/delete",{schema:{body:zod.z.object({gitServerId:zod.z.string().min(1)}),response:{200:zod.z.object({success:zod.z.boolean(),machineId:zod.z.string()}),502:zod.z.object({error:zod.z.string()})}}},async(e,t)=>{try{const n=await machineRpc(c?.(),"POST",`/v1/git-servers/${encodeURIComponent(e.body.gitServerId)}/machine-unlink`,{machineId:r.machineId});return t.send({success:!0,machineId:r.machineId,...n&&"object"==typeof n?n:{}})}catch(n){const a=formatApiError(n);return machine.logger.warn(`[GIT SERVER] delete failed: gitServerId=${e.body.gitServerId}, message=${a}`),t.code(502).send({error:a})}}),g.post("/webhooks/gitlab/:gitServerId",{schema:{params:zod.z.object({gitServerId:zod.z.string()}),body:zod.z.record(zod.z.string(),zod.z.unknown()),response:{200:zod.z.object({status:zod.z.enum(["triggered","ignored","failed"]),eventType:zod.z.string(),eventName:zod.z.string().optional(),eventAction:zod.z.string().optional(),action:zod.z.string().optional(),pipeline:zod.z.unknown().optional(),reason:zod.z.string().optional(),errorMessage:zod.z.string().optional(),errorDetail:zod.z.string().optional(),upstreamStatus:zod.z.number().optional(),triggeredCount:zod.z.number().optional(),failedCount:zod.z.number().optional(),events:zod.z.array(zod.z.object({status:zod.z.enum(["triggered","failed","ignored"]),normalizedEventId:zod.z.string(),eventName:zod.z.string(),eventAction:zod.z.string(),action:zod.z.string(),pipeline:zod.z.unknown().optional(),reason:zod.z.string().optional(),errorMessage:zod.z.string().optional(),errorDetail:zod.z.string().optional(),upstreamStatus:zod.z.number().optional()})).optional()}),400:zod.z.object({error:zod.z.string()}),401:zod.z.object({error:zod.z.string()}),403:zod.z.object({error:zod.z.string()}),404:zod.z.object({error:zod.z.string()}),502:zod.z.object({error:zod.z.string()}),500:zod.z.object({error:zod.z.string()})}}},async(e,t)=>{const n=node_crypto.randomUUID(),a=Date.now(),s=getGitLabEventType(e.body),i=getGitLabWebhookPipelineProjectKey(e.body),o=e.ip||"-",r="string"==typeof e.headers["user-agent"]?e.headers["user-agent"]:"-",l=(s,i)=>{const o=Date.now()-a,r=summarizeGitLabWebhookResponse(i),c=s>=400?"warn":"info";return machine.logger[c](`[GITLAB WEBHOOK] response: hookId=${n}, gitServer=${e.params.gitServerId}, statusCode=${s}, elapsedMs=${o}, ${r}`),t.code(s).send(i)};machine.logger.info(`[GITLAB WEBHOOK] request received: hookId=${n}, gitServer=${e.params.gitServerId}, eventType=${s}, projectKey=${i??"-"}, remote=${o}, userAgent=${r}`);const d=await getGitServerEncryptionKey();if(!d)return l(500,{error:"Git server encryption key not available"});const p=loadGitLabWebhookBridgeSecrets(e.params.gitServerId,d),u=p?.webhookSecret;if(!u)return l(403,{error:`GitLab webhook bridge is not configured for git server ${e.params.gitServerId}`});if(!secureTokenEquals(e.headers["x-gitlab-token"],u))return l(401,{error:"Invalid GitLab webhook token"});const m=getGitLabWebhookDeliveryKey(e.body,getGitLabWebhookDeliveryHeader(e.headers)),h=s;if(reportRepositoryInboxWebhook(e.params.gitServerId,e.body,m,h,c?.()).catch(t=>{const a=t instanceof Error?t.message:String(t);machine.logger.warn(`[GITLAB WEBHOOK] inbox side-channel failed: hookId=${n}, gitServer=${e.params.gitServerId}, message=${a}`)}),!i)return l(200,await triggerPipelineFromGitLabWebhook({gitServerId:e.params.gitServerId,payload:e.body,pat:"",config:{deliveryId:m}}));const g=loadPat(e.params.gitServerId,d);if(!g)return l(403,{error:`No PAT configured for git server ${e.params.gitServerId}`});try{const t=loadGitServerConfig(e.params.gitServerId),a=t?.apiUrl;if(!a)return l(400,{error:`GitLab API URL is not configured for git server ${e.params.gitServerId}`});let o;if(i)if(o=p.projectTriggerTokens?.[i],o)machine.logger.info(`[GITLAB WEBHOOK] pipeline trigger token reused: hookId=${n}, gitServer=${e.params.gitServerId}, projectKey=${i}`);else{const t=getGitLabWebhookProjectLocator(e.body);if(!t)return l(400,{error:"GitLab webhook payload is missing project information"});machine.logger.info(`[GITLAB WEBHOOK] ensuring pipeline trigger token: hookId=${n}, gitServer=${e.params.gitServerId}, projectKey=${i}, mode=create_or_reuse`);const s=new GitLabExecutor(a,g,{gitServerId:e.params.gitServerId}),r=await s.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,saveGitLabWebhookBridgeSecrets(e.params.gitServerId,{webhookSecret:u,projectTriggerTokens:{...p.projectTriggerTokens??{},[i]:o}},d),machine.logger.info(`[GITLAB WEBHOOK] pipeline trigger token stored: hookId=${n}, gitServer=${e.params.gitServerId}, projectKey=${i}`)}return machine.logger.info(`[GITLAB WEBHOOK] triggering pipeline: hookId=${n}, gitServer=${e.params.gitServerId}, eventType=${s}, projectKey=${i??"-"}`),l(200,await triggerPipelineFromGitLabWebhook({gitServerId:e.params.gitServerId,payload:e.body,pat:g,config:{apiUrl:a,triggerToken:o,deliveryId:m}}))}catch(t){const a=t,s="number"==typeof a.status&&a.status>=400&&a.status<600?a.status:500,i="string"==typeof a.message?a.message:t instanceof Error?t.message:"Failed to process GitLab webhook";return machine.logger.warn(`[GITLAB WEBHOOK] failed: hookId=${n}, gitServer=${e.params.gitServerId}, statusCode=${s}, message=${i}`),l(s,{error:i})}}),g.post("/schedule",{schema:{body:zod.z.object({task:zod.z.string(),type:zod.z.enum(["once","recurring"]),due:zod.z.string().optional(),cron:zod.z.string().optional(),timezone:zod.z.string().optional(),timeType:zod.z.enum(["utc","local"]).optional()}),response:{200:zod.z.object({id:zod.z.string(),task:zod.z.string(),type:zod.z.enum(["once","recurring"]),due:zod.z.string().optional(),cron:zod.z.string().optional(),timezone:zod.z.string().optional(),timeType:zod.z.enum(["utc","local"]).optional(),createdAt:zod.z.string()}),400:zod.z.object({error:zod.z.string()}),503:zod.z.object({error:zod.z.string()})}}},async(t,n)=>{const a=e.companionScheduler;if(!a)return n.code(503).send({error:"Companion scheduler not available"});const{task:s,type:i,due:o,cron:r,timezone:c,timeType:l}=t.body;return"once"!==i||o?"recurring"!==i||r?a.addScheduledTask({task:s,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'})}),g.get("/schedule",{schema:{response:{200:zod.z.object({tasks:zod.z.array(zod.z.object({id:zod.z.string(),task:zod.z.string(),type:zod.z.enum(["once","recurring"]),due:zod.z.string().optional(),cron:zod.z.string().optional(),timezone:zod.z.string().optional(),timeType:zod.z.enum(["utc","local"]).optional(),createdAt:zod.z.string()}))}),503:zod.z.object({error:zod.z.string()})}}},async(t,n)=>{const a=e.companionScheduler;return a?{tasks:a.listScheduledTasks()}:n.code(503).send({error:"Companion scheduler not available"})}),g.delete("/schedule/:id",{schema:{params:zod.z.object({id:zod.z.string()}),response:{200:zod.z.object({success:zod.z.boolean()}),404:zod.z.object({error:zod.z.string()}),503:zod.z.object({error:zod.z.string()})}}},async(t,n)=>{const a=e.companionScheduler;return a?a.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"})});const y=t=>e.channelManager||(t.code(503).send({error:"Channel manager not available"}),null);g.options("/channels",async(e,t)=>(f(t),t.send())),g.options("/channels/platforms",async(e,t)=>(f(t),t.send())),g.options("/channels/wechat/login/qrcode",async(e,t)=>(f(t),t.send())),g.options("/channels/wechat/login/qrcode/:qrcode/status",async(e,t)=>(f(t),t.send())),g.options("/channels/:id",async(e,t)=>(f(t),t.send())),g.options("/channels/:id/connect",async(e,t)=>(f(t),t.send())),g.options("/channels/:id/disconnect",async(e,t)=>(f(t),t.send())),g.options("/channels/:id/contacts",async(e,t)=>(f(t),t.send())),g.options("/channels/:id/bindings",async(e,t)=>(f(t),t.send())),g.options("/channels/:id/bindings/:bindingId",async(e,t)=>(f(t),t.send())),g.options("/channels/task-message",async(e,t)=>(f(t),t.send())),g.options("/channels/group-history",async(e,t)=>(f(t),t.send())),g.get("/channels",{schema:{response:{200:zod.z.object({channels:zod.z.array(ChannelConfigSchema)}),503:zod.z.object({error:zod.z.string()})}}},async(e,t)=>{f(t);const n=y(t);if(n)return{channels:n.getChannels()}}),g.get("/channels/platforms",{schema:{response:{200:zod.z.object({platforms:zod.z.array(zod.z.enum(ChannelPlatforms))})}}},async(e,t)=>(f(t),{platforms:[...ChannelPlatforms]})),g.get("/channels/wechat/login/qrcode",{schema:{response:{200:zod.z.object({qrcode:zod.z.string(),qrcodeContent:zod.z.string(),qrcodeTerminal:zod.z.string(),baseUrl:zod.z.string()}),502:zod.z.object({error:zod.z.string()})}}},async(e,t)=>{f(t);try{return await WechatAdapter.createLoginQRCode()}catch(e){const n=e instanceof Error?e.message:String(e);return machine.logger.warn(`[CHANNEL][WECHAT] Failed to create login QR code: ${n}`),t.code(502).send({error:n})}}),g.get("/channels/wechat/login/qrcode/:qrcode/status",{schema:{params:zod.z.object({qrcode:zod.z.string()}),response:{200:zod.z.object({status:zod.z.string(),token:zod.z.string().optional(),baseUrl:zod.z.string().optional(),ilinkBotId:zod.z.string().optional(),ilinkUserId:zod.z.string().optional()}),502:zod.z.object({error:zod.z.string()})}}},async(e,t)=>{f(t);try{return await WechatAdapter.getLoginStatus(e.params.qrcode)}catch(e){const n=e instanceof Error?e.message:String(e);return machine.logger.warn(`[CHANNEL][WECHAT] Failed to get login QR status: ${n}`),t.code(502).send({error:n})}}),g.post("/channels",{schema:{body:AddChannelConfigSchema,response:{200:ChannelConfigSchema,503:zod.z.object({error:zod.z.string()})}}},async(e,t)=>{f(t);const n=y(t);if(n)return n.addChannel(e.body)}),g.delete("/channels/:id",{schema:{params:zod.z.object({id:zod.z.string()}),response:{200:zod.z.object({success:zod.z.boolean()}),404:zod.z.object({error:zod.z.string()}),503:zod.z.object({error:zod.z.string()})}}},async(e,t)=>{f(t);const n=y(t);if(n)return await n.removeChannel(e.params.id)?{success:!0}:t.code(404).send({error:`Channel ${e.params.id} not found`})}),g.post("/channels/:id/connect",{schema:{params:zod.z.object({id:zod.z.string()}),response:{200:ChannelConfigSchema,404:zod.z.object({error:zod.z.string()}),500:zod.z.object({error:zod.z.string()}),503:zod.z.object({error:zod.z.string()})}}},async(e,t)=>{f(t);const n=y(t);if(n)try{return await n.connectChannel(e.params.id)}catch(e){const n=e instanceof Error?e.message:String(e),a=n.includes("not found")?404:500;return t.code(a).send({error:n})}}),g.post("/channels/:id/disconnect",{schema:{params:zod.z.object({id:zod.z.string()}),response:{200:ChannelConfigSchema,404:zod.z.object({error:zod.z.string()}),500:zod.z.object({error:zod.z.string()}),503:zod.z.object({error:zod.z.string()})}}},async(e,t)=>{f(t);const n=y(t);if(n)try{return await n.disconnectChannel(e.params.id,{disable:!0})}catch(e){const n=e instanceof Error?e.message:String(e),a=n.includes("not found")?404:500;return t.code(a).send({error:n})}}),g.get("/channels/:id/contacts",{schema:{params:zod.z.object({id:zod.z.string()}),response:{200:zod.z.object({contacts:zod.z.array(ChannelContactSchema)}),404:zod.z.object({error:zod.z.string()}),500:zod.z.object({error:zod.z.string()}),503:zod.z.object({error:zod.z.string()})}}},async(e,t)=>{f(t);const n=y(t);if(n)try{return{contacts:await n.getContacts(e.params.id)}}catch(e){const n=e instanceof Error?e.message:String(e),a=n.includes("not found")?404:500;return t.code(a).send({error:n})}}),g.get("/channels/:id/bindings",{schema:{params:zod.z.object({id:zod.z.string()}),response:{200:zod.z.object({bindings:zod.z.array(ChannelBindingSchema)}),404:zod.z.object({error:zod.z.string()}),503:zod.z.object({error:zod.z.string()})}}},async(e,t)=>{f(t);const n=y(t);if(n)try{return{bindings:n.getBindings(e.params.id)}}catch(e){const n=e instanceof Error?e.message:String(e);return t.code(404).send({error:n})}}),g.post("/channels/task-message",{schema:{body:zod.z.object({taskId:zod.z.string(),content:zod.z.string().optional(),attachments:zod.z.array(zod.z.object({filePath:zod.z.string(),fileName:zod.z.string().optional(),mimeType:zod.z.string().optional(),kind:zod.z.enum(["auto","image","file","audio","video"]).optional()})).optional(),target:zod.z.object({channelId:zod.z.string(),chatId:zod.z.string()}).optional()}),response:{200:zod.z.object({success:zod.z.boolean()}),404:zod.z.object({error:zod.z.string()}),503:zod.z.object({error:zod.z.string()}),500:zod.z.object({error:zod.z.string()})}}},async(e,t)=>{f(t);const n=y(t);if(n)try{const a={content:e.body.content,attachments:e.body.attachments};return e.body.target?(await n.sendMessageToChannel(e.body.target,a),{success:!0}):await n.sendMessageToTaskChannel(e.body.taskId,a)?{success:!0}:t.code(404).send({error:`No channel binding for task ${e.body.taskId}`})}catch(e){const n=e instanceof Error?e.message:String(e);return t.code(500).send({error:n})}}),g.post("/channels/group-history",{schema:{body:zod.z.object({taskId:zod.z.string(),limit:zod.z.number().int().positive().max(100).optional(),beforeSeq:zod.z.number().int().positive().optional(),afterSeq:zod.z.number().int().nonnegative().optional(),target:zod.z.object({channelId:zod.z.string(),chatId:zod.z.string(),platform:zod.z.string().optional(),chatType:zod.z.string().optional(),chatName:zod.z.string().optional()})}),response:{200:zod.z.object({historyXml:zod.z.string(),hasMoreBefore:zod.z.boolean(),hasMoreAfter:zod.z.boolean()}),400:zod.z.object({error:zod.z.string()}),503:zod.z.object({error:zod.z.string()}),500:zod.z.object({error:zod.z.string()})}}},async(e,t)=>{f(t);const n=y(t);if(n)try{return void 0!==e.body.beforeSeq&&void 0!==e.body.afterSeq?t.code(400).send({error:"Use beforeSeq or afterSeq, not both"}):n.getChannelGroupHistory(e.body.target,{limit:e.body.limit,beforeSeq:e.body.beforeSeq,afterSeq:e.body.afterSeq})}catch(e){const n=e instanceof Error?e.message:String(e),a=n.includes("only available")?400:500;return t.code(a).send({error:n})}}),g.delete("/channels/:id/bindings/:bindingId",{schema:{params:zod.z.object({id:zod.z.string(),bindingId:zod.z.string()}),response:{200:zod.z.object({success:zod.z.boolean()}),404:zod.z.object({error:zod.z.string()}),503:zod.z.object({error:zod.z.string()})}}},async(e,t)=>{f(t);const n=y(t);if(n)try{return n.removeBinding(e.params.id,e.params.bindingId)?{success:!0}:t.code(404).send({error:`Binding ${e.params.bindingId} not found`})}catch(e){const n=e instanceof Error?e.message:String(e);return t.code(404).send({error:n})}}),g.post("/list",{schema:{response:{200:zod.z.object({children:zod.z.array(zod.z.object({startedBy:zod.z.string(),taskId:zod.z.string(),pid:zod.z.number()}))})}}},async()=>({children:t().filter(e=>void 0!==e.taskId).map(e=>({startedBy:e.startedBy,taskId:e.taskId,pid:e.pid}))})),g.post("/stop-session",{schema:{body:zod.z.object({sessionId:zod.z.string()}),response:{200:zod.z.object({success:zod.z.boolean()})}}},async e=>{const{sessionId:t}=e.body;return machine.logger.debug(`[CONTROL SERVER] Stop session request: ${t}`),{success:n(t)}}),g.post("/stop",{schema:{response:{200:zod.z.object({status:zod.z.string()})}}},async()=>(machine.logger.debug("[CONTROL SERVER] Stop daemon request received"),setTimeout(()=>{machine.logger.debug("[CONTROL SERVER] Triggering daemon shutdown"),i()},50),{status:"stopping"})),"127.0.0.1"!==u&&machine.logger.warn(`[CONTROL SERVER] Listening on ${u}; ensure daemon control endpoints are protected by network policy`);const v=e=>new Promise((t,n)=>{h.listen({port:e,host:u},(e,a)=>{e?n(e):t(a)})});(async()=>{let e;try{e=await v(30624)}catch(t){const n=t?.code;if("EADDRINUSE"!==n&&"EACCES"!==n)throw machine.logger.info("[CONTROL SERVER] Failed to start:",t),t;machine.logger.info(`[CONTROL SERVER] Port 30624 unavailable (${n??"error"}), falling back to dynamic port`),e=await v(0)}const t=parseInt(e.split(":").pop());machine.logger.info(`[CONTROL SERVER] Started on port ${t}`),p({port:t,host:u,webhookHost:m,stop:async()=>{await h.close(),machine.logger.info("[CONTROL SERVER] Server stopped")}})})().catch(e=>{throw machine.logger.info("[CONTROL SERVER] Failed to start:",e),e})})}function spawnAgentrixCLI(e,t={}){const n=machine.projectPath(),a=path.join(n,"dist","index.mjs"),s=["--no-warnings","--no-deprecation",a,...e];if(!fs.existsSync(a)){const e=`Entrypoint ${a} does not exist`;throw machine.logger.debug(`[SPAWN Agentrix CLI] ${e}`),new Error(e)}return child_process.spawn(process.execPath,s,t)}const MIME_TYPE_MAP={".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"};function detectMimeType(e){const t=e.toLowerCase();return MIME_TYPE_MAP[t]||"application/octet-stream"}const MIME_TO_EXT={"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"};function extensionFromMimeType(e){return MIME_TO_EXT[e]||""}function extractExtension(e){try{const t=new URL(e),n=path.extname(t.pathname);if(n)return n;const a=t.searchParams.get("filename")||t.searchParams.get("name")||t.searchParams.get("file");if(a){const e=path.extname(a);if(e)return e}return""}catch{return""}}async function downloadFile(e,t,n=!1){try{const a=await fetch(e);if(!a.ok)throw new Error(`Failed to download file: ${a.status} ${a.statusText}`);if(!a.body)throw new Error("Response body is null");const s=extractExtension(e),i=a.headers.get("content-type"),o=i?.split(";")[0].trim()||detectMimeType(s),r=s||extensionFromMimeType(o);let c;if(n)try{const t=new URL(e).pathname,n=path.basename(t);c=n&&path.extname(n)?n:`${node_crypto.randomUUID()}${r||".dat"}`}catch{c=`${node_crypto.randomUUID()}${r||".dat"}`}else c=`${node_crypto.randomUUID()}${r||".dat"}`;const l=path.join(t,c),d=a.body,p=fs.createWriteStream(l);return await promises.pipeline(d,p),{filePath:l,mimeType:o,filename:c}}catch(t){throw new Error(`Failed to download file from ${e}: ${t instanceof Error?t.message:String(t)}`)}}const logger$6=machine.createModuleLogger("undefined"==typeof document?require("url").pathToFileURL(__filename).href:_documentCurrentScript&&"SCRIPT"===_documentCurrentScript.tagName.toUpperCase()&&_documentCurrentScript.src||new URL("index.cjs",document.baseURI).href);async function processAttachments(e,t){const{attachmentsDir:n}=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?processImageBlock(e,n):"document"===e.type&&"url"===e.source?.type&&e.source?.url?processDocumentBlock(e,n):e));return{...e,message:{...e.message,content:a}}}async function processImageBlock(e,t){try{const n=e.source.url;logger$6.info(`image.download.started url=${n}`);const{filePath:a,mimeType:s}=await downloadFile(n,t,!0);return logger$6.info(`image.download.completed filePath=${a}`),{type:"text",text:`Image file: ${a}\nType: ${s}`}}catch(t){return logger$6.error(`image.download.failed error=${t}`),{type:"text",text:`[Image unavailable: failed to download from ${e.source.url}]`}}}async function processDocumentBlock(e,t){try{const n=e.source.url;logger$6.info(`document.download.started url=${n}`);const{filePath:a,mimeType:s,filename:i}=await downloadFile(n,t,!0);return logger$6.info(`document.download.completed filePath=${a}`),{type:"text",text:`Document: ${a}\nTitle: ${e.title||i}\nType: ${s}`}}catch(t){return logger$6.error(`document.download.failed error=${t}`),{type:"text",text:`[Document unavailable: failed to download from ${e.source?.url}]`}}}const AGENTRIX_DEVOPS_AGENT_ID="Agentrix-DevOps",AGENTRIX_DEVOPS_GIT_URL="https://github.com/xmz-ai/agentrix-agent.git",AGENTRIX_DEVOPS_GIT_SUBDIR="agentrix-dev-init",AGENTRIX_DEVOPS_GIT_BRANCH="main";function isAgentrixDevInitEnabled(e){return(e.supportedFeatures??[]).includes(shared.AGENTRIX_DEV_INIT_FEATURE)}function resolveDevOpsLanguage(e){return"zh-Hans"===e.preferredLanguage||`${process.env.AGENTRIX_LANG??""} ${process.env.LANG??""}`.toLowerCase().includes("zh")?"zh-Hans":"en"}function detectAgentrixInitState(e,t={}){const n=t.checkLocalState??!0,a=path.join(e,".agentrix"),s=path.join(a,"env"),i=path.join(s,"init"),o=path.join(i,"state","local"),r=!fs.existsSync(a),c=!fs.existsSync(path.join(s,"README.md")),l=!fs.existsSync(path.join(i,"README.md")),d=!(!n||fs.existsSync(o)&&0!==safeReadDir(o).length);return{needsInit:r||c||l||d,missingAgentrixDir:r,missingEnvReadme:c,missingEnvModeDocs:l,missingLocalInitState:d}}function safeReadDir(e){try{return fs.readdirSync(e)}catch{return[]}}async function ensureAgentrixDevOpsAgent(){const e=path.join(machine.machine.agentrixAgentsHomeDir,"Agentrix-DevOps"),t=path.join(machine.machine.agentrixHomeDir,"tmp","agentrix-agent-devops-init"),n=`${e}.tmp-${Date.now()}`,a=`${e}.backup-${Date.now()}`;fs.mkdirSync(path.join(machine.machine.agentrixHomeDir,"tmp"),{recursive:!0}),fs.existsSync(path.join(t,".git"))?(node_child_process.execFileSync("git",["fetch","--depth=1","origin","main:refs/remotes/origin/main"],{cwd:t,stdio:"pipe"}),node_child_process.execFileSync("git",["checkout","main"],{cwd:t,stdio:"pipe"}),node_child_process.execFileSync("git",["reset","--hard","origin/main"],{cwd:t,stdio:"pipe"})):(fs.rmSync(t,{recursive:!0,force:!0}),node_child_process.execFileSync("git",["clone","--depth=1","--branch","main",AGENTRIX_DEVOPS_GIT_URL,t],{stdio:"pipe"}));const s=path.join(t,"agentrix-dev-init");if(!fs.existsSync(path.join(s,"agent.json")))throw new Error(`Agentrix DevOps agent definition not found at ${s}`);fs.rmSync(n,{recursive:!0,force:!0}),fs.cpSync(s,n,{recursive:!0}),buildAgentPlugins(n);try{fs.existsSync(e)&&fs.renameSync(e,a),fs.renameSync(n,e),fs.rmSync(a,{recursive:!0,force:!0})}catch(t){throw fs.rmSync(e,{recursive:!0,force:!0}),fs.existsSync(a)&&fs.renameSync(a,e),fs.rmSync(n,{recursive:!0,force:!0}),t}return{agentDir:e}}function buildPreInitQuestion(e){return"zh-Hans"===e?{header:"初始化",question:"检测到当前项目尚未完成 Agentrix DevOps 初始化,或缺少本地初始化状态。是否先运行 Agentrix DevOps init,以便后续开发任务可以读取项目环境、启动方式和本地状态?",multiSelect:!1,options:[{label:"先初始化",description:"先运行 Agentrix DevOps init,再继续开发需求"},{label:"跳过,直接继续",description:"不运行初始化,直接开始当前开发任务"}]}:{header:"Init",question:"This project is missing Agentrix DevOps initialization or local init state. Run Agentrix DevOps init first so the development task can read project environment, startup, and local state guidance?",multiSelect:!1,options:[{label:"Initialize first",description:"Run Agentrix DevOps init before the development request"},{label:"Skip and continue",description:"Start the current development task without initialization"}]}}function buildPostInitQuestion(e){return"zh-Hans"===e?{header:"下一步",question:"初始化已经完成,是否继续实现您的需求?如果需要修改,请告诉我。",multiSelect:!1,options:[{label:"继续实现需求",description:"启动新的开发 session 并继续原需求"},{label:"停止任务",description:"停留在当前初始化结果,不启动开发 session"},{label:"输入修改建议",description:"把你的修改建议发送给 Agentrix DevOps init session",additionalInput:{enabled:!0,required:!0,placeholder:"请输入需要 Agentrix DevOps 调整的内容"}}]}:{header:"Next",question:"Initialization is complete. Continue implementing your request, stop, or provide modification suggestions?",multiSelect:!1,options:[{label:"Continue request",description:"Start a fresh development session and continue the original request"},{label:"Stop task",description:"Stay in the initialization result without starting implementation"},{label:"Provide changes",description:"Send modification suggestions to the Agentrix DevOps init session",additionalInput:{enabled:!0,required:!0,placeholder:"Describe what Agentrix DevOps should adjust"}}]}}function parsePostInitDecision(e,t){const n=e.trim();return"zh-Hans"===t?"继续实现需求"===n||"继续"===n?"continue":"输入修改建议"===n||"修改建议"===n?"modify":"停止任务"===n||"停止"===n?"stop":null:"Continue request"===n||"Continue"===n?"continue":"Provide changes"===n||"Modify"===n?"modify":"Stop task"===n||"Stop"===n?"stop":null}function computeOriginalWorkerHistoryStartAfter(e){return null===e?null:Math.max(0,e-1)}function buildDevOpsInitPrompt(e){return["Run Agentrix DevOps initialization for the current project.","You are running as the Agentrix-DevOps agent in a platform-managed pre-initialization worker before the user development request starts.",`User preferred language / ask-user language: ${"zh-Hans"===e?"Chinese (Simplified, zh-Hans)":"English (en)"}. When you need to ask the user questions or produce user-visible completion/status text, use this language preference.`,"The Agentrix platform has already asked the user whether to run this initialization before this prompt was delivered to you.","Check whether `.agentrix` and `.agentrix/env` are already initialized; if initialization already exists, do not overwrite it, only fill missing or stale environment guidance and local initialization state.","Focus on the local development/validation mode, commands, environment variables, authentication state, and safety constraints needed by future development tasks.","Ask the user with the normal Agentrix `ask_user` tool whenever user-answerable information is required.","Maintain project iteration memory and automated testing guidance so future Agentrix development workers can continue with concrete commands and known local constraints.","This is a pre-development initialization flow. Do not assume the platform treats a normal response or turn result as completion.","A normal assistant response, result message, or end of turn is not completion.","When, and only when, you have confirmed initialization is complete, call the `complete_devops_init` Agentrix tool. The platform will ask the user what to do next only after that tool is called.","If the user chooses to stop after initialization, remain available in this Agentrix-DevOps init session.","If the user later says they want to exit init, return to the development agent, continue the original request, or stop staying in the init session, call `complete_devops_init` again so the platform can ask and switch state."].join(" ")}function devOpsStateDir(e,t){return path.join(machine.machine.resolveDataDir(e,t),"devops-init")}function devOpsOriginalInputPath(e,t){return path.join(devOpsStateDir(e,t),"original-input.json")}function devOpsHandoffPath(e,t){return path.join(devOpsStateDir(e,t),"handoff.json")}function saveDevOpsOriginalInput(e){const t=devOpsStateDir(e.userId,e.taskId);fs.mkdirSync(t,{recursive:!0}),fs.writeFileSync(devOpsOriginalInputPath(e.userId,e.taskId),JSON.stringify(e,null,2))}function readDevOpsOriginalInput(e,t){const n=devOpsOriginalInputPath(e,t);return fs.existsSync(n)?JSON.parse(fs.readFileSync(n,"utf-8")):null}function writeDevOpsHandoff(e,t,n){const a=devOpsStateDir(e,t);fs.mkdirSync(a,{recursive:!0}),fs.writeFileSync(devOpsHandoffPath(e,t),JSON.stringify({action:n,createdAt:(new Date).toISOString()},null,2))}function consumeDevOpsHandoff(e,t){const n=devOpsHandoffPath(e,t);if(!fs.existsSync(n))return null;const a=JSON.parse(fs.readFileSync(n,"utf-8"));return fs.unlinkSync(n),a}class TaskWorkerManager{pidToTrackedSession;taskToStartPromise;sandboxPool;channelManager=null;socketClientProvider=null;acceptingNewWorkers=!0;workerStartGateCode=null;workerStartGateMessage=null;drainCallback=null;constructor(e){this.pidToTrackedSession=new Map,this.taskToStartPromise=new Map,this.sandboxPool=e||null}setChannelManager(e){this.channelManager=e}setSocketClientProvider(e){this.socketClientProvider=e}setWorkerStartGate(e,t,n){this.acceptingNewWorkers=e,this.workerStartGateCode=e?null:t??"daemon_control_busy",this.workerStartGateMessage=e?null:n??"Daemon is not accepting new workers"}isAcceptingNewWorkers(){return this.acceptingNewWorkers}setDrainCallback(e){this.drainCallback=e}createWorkerGateAck(e){return this.acceptingNewWorkers?null:{eventId:shared.createEventId(),status:"failed",opCode:e,message:this.workerStartGateMessage??"Daemon is not accepting new workers",data:{errorCode:this.workerStartGateCode??"daemon_control_busy"}}}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 machine.logger.warn(`[SESSION] Missing PID for task ${e}`);machine.logger.info(`[SESSION] Registered task ${e}, PID: ${n}`);const a=this.pidToTrackedSession.get(n);if(!(a&&a.taskId===e||a)){const t={startedBy:"cli",taskId:e,pid:n};this.pidToTrackedSession.set(n,t)}}async decryptTaskMessage(e){if(!e.dataEncryptionKey)return;const t=await machine.machine.getSecretKey();if(!t)return;const n=shared.decryptWithEphemeralKey(shared.decodeBase64(e.dataEncryptionKey),t);if(!n)return void machine.logger.warn("[SESSION] Failed to decrypt data encryption key");if(e.dataEncryptionKey=shared.encodeBase64(n),"task-message"!==e.event)return;const a=e.eventData;if(!a.encryptedMessage)return;const s=shared.decryptSdkMessage(a.encryptedMessage,n);s?e.eventData={...a,message:s,encryptedMessage:void 0}:machine.logger.warn("[SESSION] Failed to decrypt task message")}async persistCreateTaskStart(e){const t=machine.machine.resolveDataDir(e.userId,e.taskId),n=machine.machine.resolveAttachmentsDir(e.userId,e.taskId),a=getTaskDb({dataDir:t,taskId:e.taskId});try{const t=e.eventData;a.saveTaskEvent({eventType:e.event,eventId:t.eventId,eventData:t,taskId:e.taskId,chatId:e.chatId,sequence:t.sequence??0});let s=null;if(t.message){let e=t.message;shared.isSDKUserMessage(e)&&(e=await processAttachments(e,{attachmentsDir:n})),s=a.saveMessage({eventId:t.eventId,message:e,senderType:t.senderType,senderId:t.senderId,senderName:t.senderName}).localSequence}return s}finally{a.close()}}async persistResumeTaskStart(e){const t=machine.machine.resolveDataDir(e.userId,e.taskId),n=machine.machine.resolveAttachmentsDir(e.userId,e.taskId),a=getTaskDb({dataDir:t,taskId:e.taskId}),s=e.eventData.sequence;if(null==s)throw new Error(`Missing resume sequence for task ${e.taskId}`);try{const t=e.eventData;a.saveTaskEvent({eventType:e.event,eventId:t.eventId,eventData:t,taskId:e.taskId,chatId:e.chatId,sequence:s});let i=null;if(t.message){let e=t.message;shared.isSDKUserMessage(e)&&(e=await processAttachments(e,{attachmentsDir:n})),i=a.saveMessage({eventId:t.eventId,message:e,senderType:t.senderType,senderId:t.senderId,senderName:t.senderName}).localSequence}return i}finally{a.close()}}async processTaskMessageAttachments(e){if("task-message"!==e.event)return;const t=e.eventData;if(!t.message||!shared.isSDKUserMessage(t.message))return;const n=machine.machine.resolveAttachmentsDir(e.userId,e.taskId),a=await processAttachments(t.message,{attachmentsDir:n});e.eventData={...t,message:a}}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,a)=>{this.pidToTrackedSession.delete(t.pid),this.sandboxPool&&this.sandboxPool.disposeWorkerSandbox(e.taskId),this.maybeContinueAfterDevOpsInit(e).catch(t=>{machine.logger.error(`[DEVOPS_INIT] Failed to continue original worker for task ${e.taskId} after DevOps worker exit:`,t)}),0===this.pidToTrackedSession.size&&this.drainCallback?.()}),t.on("error",n=>{this.pidToTrackedSession.delete(t.pid),this.sandboxPool&&this.sandboxPool.disposeWorkerSandbox(e.taskId),0===this.pidToTrackedSession.size&&this.drainCallback?.()})}async maybeContinueAfterDevOpsInit(e){const t=consumeDevOpsHandoff(e.userId,e.taskId);t&&(machine.logger.info(`[DEVOPS_INIT] Consumed handoff for task ${e.taskId}, action=${t.action}`),"continue"===t.action&&await this.startOriginalWorkerAfterDevOpsInit(e.userId,e.taskId))}async startOriginalWorkerAfterDevOpsInit(e,t){const n=readDevOpsOriginalInput(e,t);if(!n)return void machine.logger.warn(`[DEVOPS_INIT] Missing original task input for ${t}; cannot continue original worker`);if(machine.logger.info(`[DEVOPS_INIT] Starting original worker for task ${t} after Agentrix DevOps init`),this.syncOriginalWorkerAgentSession(n),"agentSessionId"in n)return void this.restoreOriginalWorkerAfterSlashDevOpsInit(n);let a=null;a=await this.persistCreateTaskStart(n),this.positionOriginalWorkerHistoryCursor(n,a),machine.machine.writeTaskInput(n);const s={eventId:shared.createEventId(),status:"success",opCode:n.eventId};await this.startWorkerInternal(n,"create-task",s)}restoreOriginalWorkerAfterSlashDevOpsInit(e){const t=getTaskDb({dataDir:machine.machine.resolveDataDir(e.userId,e.taskId),taskId:e.taskId});try{const n=t.pageRecentMessages(1).data[0]?.localSequence??0;t.updateAgentLastSequence(e.agentId,n),machine.logger.info(`[DEVOPS_INIT] Restored original worker ${e.agentId} for task ${e.taskId} at sequence ${n}; waiting for the next user message`)}finally{t.close()}machine.machine.writeTaskInput(e)}positionOriginalWorkerHistoryCursor(e,t){if(null===t)return void machine.logger.warn(`[DEVOPS_INIT] Original worker message for task ${e.taskId} has no local sequence; cannot isolate DevOps init history`);const n=getTaskDb({dataDir:machine.machine.resolveDataDir(e.userId,e.taskId),taskId:e.taskId});try{const a=computeOriginalWorkerHistoryStartAfter(t);if(null===a)return;n.updateAgentLastSequence(e.agentId,a),machine.logger.info(`[DEVOPS_INIT] Positioned original worker ${e.agentId} at sequence ${a} for task ${e.taskId}`)}finally{n.close()}}syncOriginalWorkerAgentSession(e){const t=this.socketClientProvider?.();if(t){if("agentSessionId"in e&&e.agentSessionId)return t.send("update-task-agent-session-id",{eventId:shared.createEventId(),taskId:e.taskId,agentSessionId:e.agentSessionId,cwd:e.cwd??e.userCwd}),void machine.logger.info(`[DEVOPS_INIT] Restored original agent session for task ${e.taskId}`);t.send("reset-task-session",{eventId:shared.createEventId(),taskId:e.taskId}),machine.logger.info(`[DEVOPS_INIT] Cleared DevOps init agent session for task ${e.taskId}`)}else machine.logger.warn(`[DEVOPS_INIT] No daemon socket client available to sync task session for ${e.taskId}`)}completeDevOpsInit(e){machine.logger.info(`[DEVOPS_INIT] Completion received for task ${e.taskId}, action=${e.action}`),writeDevOpsHandoff(e.userId,e.taskId,e.action);const t=this.getAliveSessionByTaskId(e.taskId)?.pid;setTimeout(()=>{const n=this.getAliveSessionByTaskId(e.taskId);n&&n.pid===t&&this.stopSession(e.taskId),"continue"===e.action&&this.continueDevOpsInitWhenStopped(e.userId,e.taskId,t).catch(t=>{machine.logger.error(`[DEVOPS_INIT] Failed to continue original worker for task ${e.taskId} after completion signal:`,t)})},100)}startDevOpsInit(e){this.startDevOpsInitAsync(e).catch(t=>{machine.logger.error(`[DEVOPS_INIT] Failed to start slash-command DevOps init for task ${e.taskId}:`,t)})}async startDevOpsInitAsync(e){const t=machine.machine.readTaskInput(e.userId,e.taskId);saveDevOpsOriginalInput(t);const n=await this.buildDevOpsWorkerInput(t,!0);machine.machine.writeTaskInput(n),await this.persistCreateTaskStart(n),this.stopSession(e.taskId),this.startWorkerWhenPreviousStops(n,"create-task")}async startWorkerWhenPreviousStops(e,t){for(let n=0;n<20;n+=1){if(await new Promise(e=>setTimeout(e,250)),this.getAliveSessionByTaskId(e.taskId))continue;const n={eventId:shared.createEventId(),status:"success",opCode:e.eventId};return void await this.startWorkerInternal(e,t,n)}machine.logger.warn(`[DEVOPS_INIT] Timed out waiting to start switched worker for task ${e.taskId}`)}async continueDevOpsInitWhenStopped(e,t,n){for(let a=0;a<20;a+=1){await new Promise(e=>setTimeout(e,250));const a=this.getAliveSessionByTaskId(t);if(a&&a.pid!==n)return void machine.logger.info(`[DEVOPS_INIT] Original worker for task ${t} is already running with PID ${a.pid}`);if(a)continue;const s=consumeDevOpsHandoff(e,t);if(!s)return void machine.logger.info(`[DEVOPS_INIT] Handoff for task ${t} was already consumed`);if(machine.logger.info(`[DEVOPS_INIT] Consumed handoff for task ${t} from completion path, action=${s.action}`),"continue"!==s.action)return;return void await this.startOriginalWorkerAfterDevOpsInit(e,t)}machine.logger.warn(`[DEVOPS_INIT] Timed out waiting to continue original worker for task ${t}`)}shouldLookupChannelReplyTarget(e){const t="task-message"===e.event?e.eventData:null;return"channel"===t?.senderType||"companion"===e.agentType&&"work"===e.taskType&&!e.parentTaskId}resolveChannelReplyTarget(e){return e.channelReplyTarget?e.channelReplyTarget:this.shouldLookupChannelReplyTarget(e)?this.channelManager?.getReplyTargetForTask(e.taskId)??null:null}buildWorkerEnv(e){return{...process.env,...e?{AGENTRIX_CHANNEL_REPLY_TARGET:JSON.stringify(e)}:{}}}async startWorker(e,t){const n={eventId:shared.createEventId(),status:"success",opCode:e.eventId},a=this.createWorkerGateAck(e.eventId);if(a)return machine.logger.warn(`[SESSION] Rejecting ${t} for task ${e.taskId}: ${a.message}`),a;await this.decryptTaskMessage(e),await this.processTaskMessageAttachments(e),"create-task"===t?e=await this.resolveDevOpsInitCreateInput(e):"resume-task"===t&&(e=this.stripStaleDevOpsAgentSession(e)),machine.machine.writeTaskInput(e),"create-task"===t?await this.persistCreateTaskStart(e):await this.persistResumeTaskStart(e);const s=this.taskToStartPromise.get(e.taskId);if(s)return machine.logger.info(`[SESSION] Task ${e.taskId} is already starting, skip duplicate ${t}`),s;const i=this.startWorkerInternal(e,t,n).finally(()=>{this.taskToStartPromise.get(e.taskId)===i&&this.taskToStartPromise.delete(e.taskId)});return this.taskToStartPromise.set(e.taskId,i),i}stripStaleDevOpsAgentSession(e){if("Agentrix-DevOps"===e.agentId||!isAgentrixDevInitEnabled(e))return e;const t=readDevOpsOriginalInput(e.userId,e.taskId);if(!t||"agentSessionId"in t)return e;machine.logger.warn(`[DEVOPS_INIT] Clearing stale DevOps init agentSessionId for resumed original worker on task ${e.taskId}`);const{agentSessionId:n,...a}=e;return this.syncOriginalWorkerAgentSession(a),a}async resolveDevOpsInitCreateInput(e){if(!isAgentrixDevInitEnabled(e)||"Agentrix-DevOps"===e.agentId)return e;if(this.isLocalDirectoryDevOpsTarget(e)){if(!detectAgentrixInitState(machine.machine.resolveProjectCWD(e.userCwd,e.userId,e.taskId),{checkLocalState:!0}).needsInit)return machine.logger.info(`[DEVOPS_INIT] Local project init state complete for task ${e.taskId}; starting original worker`),e}else{if(!this.isCodeRepositoryDevOpsTarget(e))return machine.logger.info(`[DEVOPS_INIT] No project directory or code repository selected for task ${e.taskId}; skipping Agentrix DevOps init`),e;machine.logger.info(`[DEVOPS_INIT] Code repository target selected for task ${e.taskId}; starting Agentrix-DevOps without local init-state precheck`)}saveDevOpsOriginalInput(e);const t=await this.buildDevOpsWorkerInput(e,!1);return machine.logger.info(`[DEVOPS_INIT] Starting Agentrix-DevOps worker before original ${e.agentType}/${e.agentId} worker for task ${e.taskId}`),t}isLocalDirectoryDevOpsTarget(e){return"directory"===e.repositorySourceType&&Boolean(e.userCwd)}isCodeRepositoryDevOpsTarget(e){return"git-server"===e.repositorySourceType&&Boolean(e.repositoryId||e.gitUrl)}async buildDevOpsWorkerInput(e,t){const{agentDir:n}=await ensureAgentrixDevOpsAgent(),a=buildDevOpsInitPrompt(resolveDevOpsLanguage(e)),s=e.eventData,i=this.toCreateTaskInput(e);return{...i,eventId:t?shared.createEventId():i.eventId,agentId:"Agentrix-DevOps",agentType:"claude",agentDir:n,eventData:{...s,eventId:shared.createEventId(),senderType:"system",senderId:"agentrix-devops-init",senderName:"Agentrix DevOps init",message:{uuid:crypto$1.randomUUID(),type:"user",message:{role:"user",content:a},parent_tool_use_id:null,session_id:"new"},encryptedMessage:void 0}}}toCreateTaskInput(e){if(!("agentSessionId"in e))return e;const{agentSessionId:t,...n}=e;return n}async startWorkerInternal(e,t,n){const a=this.createWorkerGateAck(e.eventId);if(a)return machine.logger.warn(`[SESSION] Rejecting ${t} for task ${e.taskId}: ${a.message}`),a;const s=this.getAliveSessionByTaskId(e.taskId);if(s)return machine.logger.info(`[SESSION] Task ${e.taskId} already has worker PID ${s.pid}, skip duplicate ${t}`),n.message=`Worker already running (PID ${s.pid})`,n;const i=machine.machine.resolveProjectCWD(e.userCwd,e.userId,e.taskId),o=["worker","--type",e.agentType||"claude","--started-by","daemon","--task-id",e.taskId,"--user-id",e.userId,"--idle-timeout","120"],r=this.resolveChannelReplyTarget(e),c=this.buildWorkerEnv(r);let l;if(this.sandboxPool?.isEnabled())try{if(!await this.sandboxPool.createWorkerSandbox(e.taskId,e.userId,i))throw new Error("Failed to create sandbox instance");const{projectPath:t}=await Promise.resolve().then(function(){return require("./logger-WoR-bbUU.cjs")}).then(function(e){return e.machine$1}),{join:n}=await import("path"),a=["--no-warnings","--no-deprecation",n(t(),"dist","index.mjs"),...o],s=`"${process.execPath}" ${a.map(e=>`"${e}"`).join(" ")}`,r=await this.sandboxPool.wrapWorkerCommand(e.taskId,s);machine.logger.debug(`[SESSION] Sandboxed command for task ${e.taskId}: ${r}`),l=child_process.spawn(r,{shell:!0,cwd:i,detached:!0,stdio:["ignore","pipe","pipe"],env:c}),machine.logger.info(`[SESSION] Worker started with sandbox, PID: ${l.pid}`)}catch(t){return machine.logger.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 l=spawnAgentrixCLI(o,{cwd:i,detached:!0,stdio:["ignore","pipe","pipe"],env:c}),machine.logger.info(`[SESSION] Worker started without sandbox, PID: ${l.pid}`);return process.env.DEBUG&&(l.stdout?.on("data",e=>{machine.logger.debug(`[Daemon] worker stdout: ${e.toString()}`)}),l.stderr?.on("data",e=>{machine.logger.debug(`[Daemon] worker stderr: ${e.toString()}`)})),l.pid?(this.trackWorkerProcess(e,l),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"),machine.logger.info(`[SESSION] Task ${e} stopped`);const a=setTimeout(()=>{const n=this.pidToTrackedSession.get(t);if(n&&n.taskId===e&&this.isProcessAlive(t))try{process.kill(t,"SIGKILL"),machine.logger.warn(`[SESSION] Task ${e} did not exit after SIGTERM, sent SIGKILL to PID ${t}`)}catch(n){machine.logger.warn(`[SESSION] Failed to force kill task ${e} (PID ${t}):`,n)}},3e3);a.unref?.()}catch(n){machine.logger.warn(`[SESSION] Failed to stop task ${e}:`,n),this.isProcessAlive(t)||this.pidToTrackedSession.delete(t)}return!0}return machine.logger.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(){machine.logger.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){machine.logger.warn(`[SESSION] Failed to stop PID ${e}:`,t)}this.pidToTrackedSession.clear()}async startHivePublishWorker(e){const t={eventId:shared.createEventId(),status:"success",opCode:e.eventId},n=this.createWorkerGateAck(e.eventId);if(n)return machine.logger.warn(`[SESSION] Rejecting hive-publish for task ${e.taskId}: ${n.message}`),n;machine.machine.writeTaskInput(e);try{const n=spawnAgentrixCLI(["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=>{machine.logger.debug(`[HivePublish] worker stdout: ${e.toString()}`)}),n.stderr?.on("data",e=>{machine.logger.debug(`[HivePublish] worker stderr: ${e.toString()}`)})),!n.pid)return t.status="failed",t.message="Failed to start hive-publish worker - no PID",t;machine.logger.info(`[SESSION] Hive publish worker started, PID: ${n.pid}`);const a={taskId:e.taskId,userId:e.userId};return this.trackWorkerProcess(a,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:shared.createEventId(),status:"success",opCode:e.eventId},n=this.createWorkerGateAck(e.eventId);if(n)return machine.logger.warn(`[SESSION] Rejecting hive-install for task ${e.taskId}: ${n.message}`),n;machine.machine.writeTaskInput(e);try{const n=spawnAgentrixCLI(["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=>{machine.logger.debug(`[HiveInstall] worker stdout: ${e.toString()}`)}),n.stderr?.on("data",e=>{machine.logger.debug(`[HiveInstall] worker stderr: ${e.toString()}`)})),!n.pid)return t.status="failed",t.message="Failed to start hive-install worker - no PID",t;machine.logger.info(`[SESSION] Hive install worker started, PID: ${n.pid}`);const a={taskId:e.taskId,userId:e.userId};return this.trackWorkerProcess(a,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:shared.createEventId(),status:"success",opCode:e.eventId},n=this.createWorkerGateAck(e.eventId);if(n)return machine.logger.warn(`[SESSION] Rejecting deployment for task ${e.taskId}: ${n.message}`),n;machine.machine.writeTaskInput(e);try{const n=spawnAgentrixCLI(["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=>{machine.logger.debug(`[Deployment] worker stdout: ${e.toString()}`)}),n.stderr?.on("data",e=>{machine.logger.debug(`[Deployment] worker stderr: ${e.toString()}`)})),!n.pid)return t.status="failed",t.message="Failed to start deployment worker - no PID",t;machine.logger.info(`[SESSION] Deployment worker started, PID: ${n.pid}`);const a={taskId:e.taskId,userId:e.userId};return this.trackWorkerProcess(a,n),t}catch(e){return t.status="failed",t.message=`Failed to start deployment worker: ${e instanceof Error?e.message:String(e)}`,t}}}function setupGracefulShutdown(e){const{processType:t,onShutdownRequest:n,forceExitTimeoutMs:a=3e4}=e,s=`[${t.toUpperCase()}]`;let i,o=!1;const r=new Promise(e=>{i=(t,i)=>{o?machine.logger.debug(`${s} Shutdown already requested; ignoring duplicate request from ${t}`):(o=!0,machine.logger.info(`${s} Requesting shutdown (source: ${t}, errorMessage: ${i})`),n&&n(t,i),setTimeout(()=>process.exit(1),a).unref?.(),e({source:t,errorMessage:i}))}}),c=e=>{process.on(e,()=>{i("os-signal")})};return c("SIGINT"),c("SIGTERM"),process.on("uncaughtException",e=>{machine.logger.info(`${s} FATAL: Uncaught exception`,e),machine.logger.info(`${s} Stack trace: ${e.stack}`),i("exception",e.message)}),process.on("unhandledRejection",e=>{machine.logger.info(`${s} FATAL: Unhandled promise rejection`,e);const t=e instanceof Error?e:new Error(`Unhandled promise rejection: ${e}`);machine.logger.info(`${s} Stack trace: ${t.stack}`),i("exception",t.message)}),process.on("exit",e=>{machine.logger.info(`${s} Process exiting with code: ${e}`)}),{requestShutdown:i,shutdownPromise:r}}class SandboxPool{networkManager=null;workerSandboxes=new Map;settings=null;platform;constructor(){this.platform=platform_js.getPlatform()}async initialize(e){if(this.settings=e,!e.enabled)return machine.logger.info("[SANDBOX] Sandbox disabled via settings"),!1;if(!sandboxRuntime.isSupportedPlatform(this.platform))return machine.logger.warn("[SANDBOX] Platform not supported, sandbox disabled"),!1;try{const t={allowedDomains:[new URL(machine.machine.serverUrl).hostname,...e.network.allowedDomains],deniedDomains:e.network.deniedDomains,allowLocalBinding:!1};return this.networkManager=new sandboxRuntime.NetworkManager,await this.networkManager.initialize(t),machine.logger.info("[SANDBOX] Sandbox pool initialized successfully"),!0}catch(e){throw machine.logger.error("[SANDBOX] Failed to initialize:",e),e}}async createWorkerSandbox(e,t,n){if(!this.networkManager||!this.settings?.enabled)return null;try{const a=machine.machine.resolveUserWorkSpaceDir(t),s=machine.machine.getStatePaths().logsDir,i=this.settings.filesystem||{},o=this.settings.env||{},r={...i,allowWrite:[...i.allowWrite||[],a,n,s]};if("linux"===this.platform&&i.allowRead){const e=path$1.dirname(process.execPath);r.allowRead=[...i.allowRead,e]}const c={filesystem:r,env:o},l=new sandboxRuntime.SandboxManager(this.networkManager,c);return this.workerSandboxes.set(e,l),machine.logger.info(`[SANDBOX] Created sandbox for task ${e}`),l}catch(t){return machine.logger.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 a=await n.wrapWithSandbox(t);return machine.logger.debug(`[SANDBOX] Wrapped command for task ${e}`),a}disposeWorkerSandbox(e){const t=this.workerSandboxes.get(e);t&&(t.dispose(),this.workerSandboxes.delete(e),machine.logger.debug(`[SANDBOX] Disposed sandbox for task ${e}`))}async shutdown(){machine.logger.info("[SANDBOX] Shutting down sandbox pool");for(const[e,t]of this.workerSandboxes.entries())t.dispose(),machine.logger.debug(`[SANDBOX] Disposed sandbox for task ${e}`);this.workerSandboxes.clear(),this.networkManager&&(await this.networkManager.shutdown(),this.networkManager=null,machine.logger.info("[SANDBOX] Network manager shutdown complete"))}isEnabled(){return!0===this.settings?.enabled}}class CompanionBootstrapWatcher{constructor(e,t){this.client=e,this.machineId=t;const n=machine.machine.agentrixAgentsHomeDir,a=path.join(n,"companion"),s=path.join(a,"claude");this.bootstrapPath=path.join(s,"BOOTSTRAP.md"),this.countPath=path.join(a,"BOOTSTRAP.count"),this.stateFilePath=path.join(s,"state.json")}timer=null;intervalMs=18e4;maxAttempts=10;bootstrapPath;countPath;stateFilePath;start(){fs.existsSync(this.bootstrapPath)?this.readCount()>=this.maxAttempts?machine.logger.warn(`[COMPANION BOOTSTRAP] Already reached max attempts (${this.maxAttempts}), not starting watcher`):(machine.logger.info("[COMPANION BOOTSTRAP] BOOTSTRAP.md exists, starting watcher"),this.scheduleNext()):machine.logger.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(!fs.existsSync(this.bootstrapPath))return void machine.logger.info("[COMPANION BOOTSTRAP] BOOTSTRAP.md removed, companion init complete");const e=this.readCount();if(e>=this.maxAttempts)return void machine.logger.warn(`[COMPANION BOOTSTRAP] Max attempts (${this.maxAttempts}) reached, giving up`);const t=this.loadState();if(!t)return machine.logger.warn("[COMPANION BOOTSTRAP] No state.json available, will retry next interval"),void this.scheduleNext();this.writeCount(e+1),machine.logger.info(`[COMPANION BOOTSTRAP] Sending init request (attempt ${e+1}/${this.maxAttempts})`),this.client.send("request-companion-init",{eventId:shared.createEventId(),machineId:t.machineId,agentId:t.agentId,chatId:t.chatId,chatTaskId:t.chatTaskId,userId:t.userId}),this.scheduleNext()}readCount(){try{if(fs.existsSync(this.countPath)){const e=parseInt(fs.readFileSync(this.countPath,"utf-8").trim(),10);return isNaN(e)?0:e}}catch{}return 0}writeCount(e){try{fs.writeFileSync(this.countPath,String(e),"utf-8")}catch(e){machine.logger.warn("[COMPANION BOOTSTRAP] Failed to write BOOTSTRAP.count:",e)}}loadState(){try{if(fs.existsSync(this.stateFilePath)){const e=JSON.parse(fs.readFileSync(this.stateFilePath,"utf-8"));if(e?.agentId&&e?.machineId&&e?.userId&&e?.chatId)return e}}catch{}return null}}function requireString$1(e,t){if("string"!=typeof e||0===e.trim().length)throw new Error(`Lark credential "${t}" is required`);return e}function parseCredentials$1(e){return{appId:requireString$1(e.appId,"appId"),appSecret:requireString$1(e.appSecret,"appSecret")}}function safeJsonParse(e){try{return JSON.parse(e)}catch{return e}}function getTextContent(e){if("string"==typeof e)return e;if(!e||"object"!=typeof e)return;const t=e;return"string"==typeof t.text?t.text:void 0}function normalizeTimestamp(e){if(!e)return(new Date).toISOString();const t=Number(e);if(Number.isFinite(t))return new Date(t>1e10?t:1e3*t).toISOString();const n=new Date(e);return Number.isNaN(n.getTime())?(new Date).toISOString():n.toISOString()}function getLarkUserIdType(e){return e.startsWith("on_")?"union_id":e.startsWith("ou_")?"open_id":"user_id"}function extractSenderName(e){if(!e||"object"!=typeof e)return;const t=e;for(const e of["name","sender_name","user_name","nickname"]){const n=t[e];if("string"==typeof n&&n.trim())return n}}function larkMentionsBot(e,t,n){return!!Array.isArray(e)&&e.some(e=>{if(!e||"object"!=typeof e)return!1;const a=e;if("bot"===("string"==typeof a.mentioned_type?a.mentioned_type.toLowerCase():void 0))return!0;const s=a.id;if(s&&"object"==typeof s){const e=s;return e.open_id===n||e.app_id===t||e.open_id===t||e.user_id===t}return a.app_id===t||a.open_id===t||a.user_id===t})}function formatLarkError(e){const t=e?.response?.status,n=e?.response?.data,a=e?.response?.headers?.["x-tt-logid"]||e?.response?.headers?.["x-request-id"];return[t?`status=${t}`:void 0,n?`data=${JSON.stringify(n)}`:void 0,a?`logId=${a}`:void 0,e?.message||e?.msg||String(e)].filter(Boolean).join(", ")}function encodeLarkResourceKey(e,t,n){return[e,t,n].map(encodeURIComponent).join(":")}function decodeLarkResourceKey(e){const[t,n,a]=e.split(":").map(decodeURIComponent);if(!t||!n||!a)throw new Error("Invalid Lark resource key");return{messageId:t,resourceType:n,fileKey:a}}class LarkAdapter{id;platform="lark";capabilities={sendText:!0,sendImage:!0,sendFile:!0,sendAudio:!1,sendVideo:!1};client;wsClient=null;messageHandler=null;stateHandler=null;connectionState="disconnected";credentials;botOpenId;constructor(e){this.id=e.id,this.credentials=parseCredentials$1(e.credentials),this.client=new lark__namespace.Client({appId:this.credentials.appId,appSecret:this.credentials.appSecret,appType:lark__namespace.AppType.SelfBuild,domain:lark__namespace.Domain.Feishu})}get state(){return this.connectionState}async connect(){if("connected"===this.connectionState||"connecting"===this.connectionState)return;this.setState("connecting"),await this.fetchBotIdentity(),this.wsClient=new lark__namespace.WSClient({appId:this.credentials.appId,appSecret:this.credentials.appSecret,domain:lark__namespace.Domain.Feishu,loggerLevel:lark__namespace.LoggerLevel.info,onReady:()=>{machine.logger.info(`[CHANNEL][LARK] Connected: channel=${this.id}`),this.setState("connected")},onError:e=>{machine.logger.warn(`[CHANNEL][LARK] Connection error: channel=${this.id}, message=${e.message}`),this.setState("error",e)},onReconnecting:()=>{machine.logger.warn(`[CHANNEL][LARK] Reconnecting: channel=${this.id}`),this.setState("connecting")},onReconnected:()=>{machine.logger.info(`[CHANNEL][LARK] Reconnected: channel=${this.id}`),this.setState("connected")}});const e=new lark__namespace.EventDispatcher({}).register({"im.message.receive_v1":async e=>{const t=this.normalizeMessage(e);t&&await(this.messageHandler?.(t))}});try{await this.wsClient.start({eventDispatcher:e})}catch(e){const t=e instanceof Error?e:new Error(String(e));throw this.setState("error",t),t}}async disconnect(){this.wsClient&&(this.wsClient.close({force:!0}),this.wsClient=null),this.setState("disconnected")}async sendMessage(e,t){const n=await this.client.im.message.create({params:{receive_id_type:"chat_id"},data:{receive_id:e,msg_type:"text",content:JSON.stringify({text:t})}});if(n.code&&0!==n.code)throw new Error(n.msg||`Lark sendMessage failed with code ${n.code}`)}async sendChannelMessage(e,t){try{const n=t.content?.trim();n&&await this.sendMessage(e,n);for(const n of t.attachments??[])await this.sendAttachment(e,n)}catch(e){throw new Error(`Lark sendChannelMessage failed: ${formatLarkError(e)}`)}}async sendAttachment(e,t){if("image"===this.resolveOutgoingKind(t)){const n=await this.client.im.image.create({data:{image_type:"message",image:fs.createReadStream(t.filePath)}});if(!n?.image_key)throw new Error("Lark image upload did not return image_key");return void await this.sendRawMessage(e,"image",{image_key:n.image_key})}const n=t.fileName||path.basename(t.filePath),a=await this.client.im.file.create({data:{file_type:this.resolveLarkFileType(n,t.mimeType),file_name:n,file:fs.createReadStream(t.filePath)}});if(!a?.file_key)throw new Error("Lark file upload did not return file_key");await this.sendRawMessage(e,"file",{file_key:a.file_key})}async getChatName(e){try{const t=await this.client.im.chat.get({path:{chat_id:e}});return t.code&&0!==t.code?(machine.logger.warn(`[CHANNEL][LARK] getChatName failed: code=${t.code}, msg=${t.msg}`),e):t.data?.name?t.data.name:e}catch(t){return machine.logger.warn(`[CHANNEL][LARK] Failed to get chat name for ${e}`,t),e}}async getUserName(e){const t=getLarkUserIdType(e);try{const n=await this.client.request({url:"/open-apis/contact/v3/users/basic_batch",method:"POST",params:{user_id_type:t},data:{user_ids:[e]}});if(n.code&&0!==n.code)return machine.logger.warn(`[CHANNEL][LARK] contact.user.basic_batch failed: code=${n.code}, msg=${n.msg}`),e;const a=n.data?.users?.[0];return a?.name||a?.i18n_name?.zh_cn||a?.i18n_name?.en_us||a?.i18n_name?.ja_jp||e}catch(t){return machine.logger.warn(`[CHANNEL][LARK] contact.user.basic_batch failed for ${e}: ${formatLarkError(t)}`),e}}async getContacts(){const e=[];for await(const t of await this.client.im.chat.listWithIterator({params:{page_size:50,sort_type:"ByActiveTimeDesc"}}))for(const n of t?.items??[])n.chat_id&&e.push({id:n.chat_id,name:n.name||n.chat_id,avatar:n.avatar,description:n.description,chatStatus:n.chat_status,external:n.external});return e}async downloadFile(e,t={}){try{const n=decodeLarkResourceKey(e),a=createChannelFilePath(t.fileName||n.fileKey),s=await this.client.im.messageResource.get({path:{message_id:n.messageId,file_key:n.fileKey},params:{type:n.resourceType}});return await s.writeFile(a),a}catch(e){return machine.logger.warn(`[CHANNEL][LARK] Failed to download file: channel=${this.id}, ${formatLarkError(e)}`),null}}onMessage(e){this.messageHandler=e}onStateChange(e){this.stateHandler=e}setState(e,t){this.connectionState=e,this.stateHandler?.(e,t)}async sendRawMessage(e,t,n){const a=await this.client.im.message.create({params:{receive_id_type:"chat_id"},data:{receive_id:e,msg_type:t,content:JSON.stringify(n)}});if(a.code&&0!==a.code)throw new Error(a.msg||`Lark send ${t} failed with code ${a.code}`)}async fetchBotIdentity(){try{const e=await this.client.request({url:"/open-apis/bot/v3/info",method:"GET"});if(e.code&&0!==e.code)return void machine.logger.warn(`[CHANNEL][LARK] bot identity lookup failed: code=${e.code}, msg=${e.msg}`);this.botOpenId=e.bot?.open_id}catch(e){machine.logger.warn(`[CHANNEL][LARK] bot identity lookup failed: ${formatLarkError(e)}`)}}resolveOutgoingKind(e){return"image"===e.kind?"image":"auto"!==e.kind&&e.kind?"file":e.mimeType?.startsWith("image/")?"image":"file"}resolveLarkFileType(e,t){const n=path.extname(e).toLowerCase().replace(/^\./,"");return"pdf"===n||"application/pdf"===t?"pdf":["doc","docx"].includes(n)?"doc":["xls","xlsx","csv"].includes(n)?"xls":["ppt","pptx"].includes(n)?"ppt":"mp4"===n||"video/mp4"===t?"mp4":"opus"===n||"audio/opus"===t?"opus":"stream"}normalizeMessage(e){const t=e?.message;if(!t?.message_id||!t?.chat_id)return machine.logger.warn(`[CHANNEL][LARK] Ignoring malformed message event: channel=${this.id}`),null;const n=safeJsonParse(t.content??""),a=n&&"object"==typeof n?n:{},s=t.message_type,i="string"==typeof a.file_key?a.file_key:void 0,o="string"==typeof a.image_key?a.image_key:void 0,r=larkMentionsBot(t.mentions,this.credentials.appId,this.botOpenId);return{id:t.message_id,channelId:this.id,platform:"lark",chatId:t.chat_id,chatType:t.chat_type,senderId:e?.sender?.sender_id?.open_id??e?.sender?.sender_id?.user_id??e?.sender?.sender_id?.union_id,senderType:e?.sender?.sender_type,senderName:extractSenderName(e?.sender),type:"image"===s?"image":"file"===s?"file":"audio"===s?"voice":"text",text:getTextContent(n),fileKey:i?encodeLarkResourceKey(t.message_id,"audio"===s?"audio":"file",i):void 0,fileName:"string"==typeof a.file_name?a.file_name:void 0,imageKey:o?encodeLarkResourceKey(t.message_id,"image",o):void 0,mentionedBot:r,replyToBot:!1,triggered:r,rawContent:n,timestamp:normalizeTimestamp(t.create_time??e?.create_time??e?.ts),raw:e}}}const API_BASE_URL="https://api.telegram.org",POLL_TIMEOUT_SECONDS=30,REQUEST_TIMEOUT_MS=4e4,INITIAL_RETRY_DELAY_MS=1e3,MAX_RETRY_DELAY_MS=3e4;function requireString(e,t){if("string"!=typeof e||0===e.trim().length)throw new Error(`Telegram credential "${t}" is required`);return e.trim()}function optionalString(e){return"string"==typeof e&&e.trim().length>0?e.trim():void 0}function parseCredentials(e){const t=optionalString(e.token)??optionalString(e.botToken)??optionalString(e.bot_token);return{token:t||requireString(t,"token")}}function formatTelegramName(e){return[e.first_name,e.last_name].filter(Boolean).join(" ").trim()||(e.username?`@${e.username}`:void 0)}function normalizeChatType(e){return"private"===e?"p2p":"group"===e||"supergroup"===e?"group":e}function inferMessageType(e){return e.photo?.length?"image":e.document?"file":e.voice?"voice":"text"}function getImageKey(e){return e.photo?.[e.photo.length-1]?.file_id}class TelegramAdapter{id;platform="telegram";capabilities={sendText:!0,sendImage:!0,sendFile:!0,sendAudio:!1,sendVideo:!1};messageHandler=null;stateHandler=null;connectionState="disconnected";credentials;polling=!1;pollController=null;pollPromise=null;retryTimer=null;resolveRetrySleep=null;retryDelayMs=1e3;offset;botUser=null;constructor(e){this.id=e.id,this.credentials=parseCredentials(e.credentials)}get state(){return this.connectionState}async connect(){"connected"!==this.connectionState&&"connecting"!==this.connectionState&&(this.setState("connecting"),this.botUser=await this.request("getMe",{},{timeoutMs:4e4}),this.polling=!0,this.retryDelayMs=1e3,this.pollPromise=this.pollLoop(),this.setState("connected"),machine.logger.info(`[CHANNEL][TELEGRAM] Connected: channel=${this.id}`))}async disconnect(){this.polling=!1,this.retryTimer&&(clearTimeout(this.retryTimer),this.retryTimer=null,this.resolveRetrySleep?.()),this.resolveRetrySleep=null,this.pollController?.abort(),this.pollController=null,await(this.pollPromise?.catch(()=>{})),this.pollPromise=null,this.setState("disconnected")}async sendMessage(e,t){await this.request("sendMessage",{chat_id:e,text:t},{timeoutMs:4e4})}async sendChannelMessage(e,t){const n=t.attachments??[],a=t.content?.trim();if(0===n.length)return void(a&&await this.sendMessage(e,a));const s=1===n.length?a:void 0;a&&!s&&await this.sendMessage(e,a);for(let t=0;t<n.length;t+=1)await this.sendAttachment(e,n[t],0===t?s:void 0)}async sendAttachment(e,t,n){const a=this.resolveOutgoingKind(t),s="image"===a?"sendPhoto":"sendDocument",i="image"===a?"photo":"document",o=t.fileName||path.basename(t.filePath),r=await promises$1.readFile(t.filePath),c=new FormData;c.append("chat_id",e),c.append(i,new Blob([r],{type:t.mimeType||"application/octet-stream"}),o),n&&c.append("caption",n),await this.requestForm(s,c,{timeoutMs:4e4})}async getContacts(){return[]}async downloadFile(e,t={}){try{const n=await this.request("getFile",{file_id:e},{timeoutMs:4e4});if(!n.file_path)throw new Error("Telegram getFile response is missing file_path");const a=t.fileName||path.basename(n.file_path);return await downloadUrlToChannelFile(`${API_BASE_URL}/file/bot${this.credentials.token}/${n.file_path}`,a)}catch(t){return machine.logger.warn(`[CHANNEL][TELEGRAM] Failed to download file: channel=${this.id}, fileKey=${e}`,t),null}}async getChatName(e){try{const t=await this.request("getChat",{chat_id:e},{timeoutMs:4e4});return t.title||formatTelegramName(t)||t.username||e}catch(t){return machine.logger.warn(`[CHANNEL][TELEGRAM] Failed to get chat name for ${e}`,t),e}}async getUserName(e){try{const t=await this.request("getChat",{chat_id:e},{timeoutMs:4e4});return formatTelegramName(t)||t.username||e}catch(t){return machine.logger.warn(`[CHANNEL][TELEGRAM] Failed to get user name for ${e}`,t),e}}onMessage(e){this.messageHandler=e}onStateChange(e){this.stateHandler=e}setState(e,t){this.connectionState=e,this.stateHandler?.(e,t)}async pollLoop(){for(;this.polling;)try{const e=await this.request("getUpdates",{offset:this.offset,timeout:30,allowed_updates:["message"]},{timeoutMs:4e4,isPoll:!0});this.retryDelayMs=1e3,"connected"!==this.connectionState&&this.setState("connected");for(const t of e){this.offset=Math.max(this.offset??0,t.update_id+1);const e=this.normalizeMessage(t);e&&await(this.messageHandler?.(e))}}catch(e){if(!this.polling)break;if(this.isAbortError(e))continue;const t=e instanceof Error?e:new Error(String(e));machine.logger.warn(`[CHANNEL][TELEGRAM] Poll failed: channel=${this.id}, message=${t.message}`),this.setState("error",t),await this.sleepWithCancel(this.retryDelayMs),this.retryDelayMs=Math.min(2*this.retryDelayMs,3e4),this.polling&&this.setState("connecting")}}async request(e,t,n){const a=new AbortController;n.isPoll&&(this.pollController=a);const s=setTimeout(()=>a.abort(),n.timeoutMs);try{const n=await fetch(`${API_BASE_URL}/bot${this.credentials.token}/${e}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t),signal:a.signal}),s=await n.json().catch(()=>({}));if(!n.ok||!s.ok){const e=s.error_code?`code=${s.error_code}`:void 0,t=s.description||`HTTP ${n.status}`;throw new Error([e,t].filter(Boolean).join(", "))}if(void 0===s.result)throw new Error(`Telegram ${e} response is missing result`);return s.result}finally{clearTimeout(s),n.isPoll&&this.pollController===a&&(this.pollController=null)}}async requestForm(e,t,n){const a=new AbortController,s=setTimeout(()=>a.abort(),n.timeoutMs);try{const n=await fetch(`${API_BASE_URL}/bot${this.credentials.token}/${e}`,{method:"POST",body:t,signal:a.signal}),s=await n.json().catch(()=>({}));if(!n.ok||!s.ok){const e=s.error_code?`code=${s.error_code}`:void 0,t=s.description||`HTTP ${n.status}`;throw new Error([e,t].filter(Boolean).join(", "))}if(void 0===s.result)throw new Error(`Telegram ${e} response is missing result`);return s.result}finally{clearTimeout(s)}}resolveOutgoingKind(e){return"image"===e.kind?"image":"auto"!==e.kind&&e.kind?"file":e.mimeType?.startsWith("image/")?"image":"file"}sleepWithCancel(e){return new Promise(t=>{this.resolveRetrySleep=t,this.retryTimer=setTimeout(()=>{this.retryTimer=null,this.resolveRetrySleep=null,t()},e)})}isAbortError(e){return e instanceof Error&&"AbortError"===e.name}isTriggeredMessage(e){const t=this.botUser?.id,n=this.botUser?.username?.toLowerCase(),a=e.text??e.caption??"",s=e.text?e.entities:e.caption_entities,i=Boolean(void 0!==t&&e.reply_to_message?.from?.id===t);let o=!1;if(n){o=a.toLowerCase().includes(`@${n}`);for(const e of s??[]){if("mention"!==e.type&&"bot_command"!==e.type)continue;const t=a.slice(e.offset,e.offset+e.length).toLowerCase();if(t===`@${n}`||t.endsWith(`@${n}`)){o=!0;break}}}return{mentionedBot:o,replyToBot:i,triggered:o||i}}normalizeMessage(e){const t=e.message;if(!t?.chat?.id||!t.message_id)return machine.logger.warn(`[CHANNEL][TELEGRAM] Ignoring malformed message event: channel=${this.id}`),null;const n=String(t.chat.id),a=void 0===t.from?.id?void 0:String(t.from.id),s=this.isTriggeredMessage(t);return{id:String(t.message_id||e.update_id||node_crypto.randomUUID()),channelId:this.id,platform:"telegram",chatId:n,chatType:normalizeChatType(t.chat.type),senderId:a,senderName:t.from?formatTelegramName(t.from):void 0,type:inferMessageType(t),text:t.text??t.caption,fileKey:t.document?.file_id??t.voice?.file_id,fileName:t.document?.file_name,imageKey:getImageKey(t),mentionedBot:s.mentionedBot,replyToBot:s.replyToBot,triggered:s.triggered,rawContent:t.text??t.caption??t.photo??t.document??t.voice,timestamp:new Date(1e3*t.date).toISOString(),raw:e}}}function formatHistoryMessage(e){const t=buildHistoryMessageParts(e);return t?{type:"user",message:{role:"user",content:[{type:"text",text:`<msg ${buildAttributes({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 formatHistoryMessageXml(e){const t=buildHistoryMessageParts(e);return t?`<msg ${buildAttributes({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 buildAttributes(e){return Object.entries(e).filter(([,e])=>void 0!==e&&""!==e).map(([e,t])=>`${e}="${escapeXmlAttr(t)}"`).join(" ")}function escapeXmlAttr(e){return e.replaceAll("&","&amp;").replaceAll('"',"&quot;").replaceAll("<","&lt;").replaceAll(">","&gt;")}function formatHistoryXml(e){const t=[];for(const n of e){const e=formatHistoryMessageXml(n);e&&t.push(e)}return t.join("\n")}function formatAskUserMessage(e){return`Ask user: ${e.questions.map((e,t)=>{const n=e.options?.map(e=>e.label).filter(Boolean),a=n&&n.length>0?` options: ${n.join(", ")}`:"";return`Q${t+1}[${e.header}] ${e.question}${a}`}).join(" | ")}`}function formatAskUserResponse(e){const t=e.status?` status=${e.status}`:"",n=e.reason?` reason=${e.reason}`:"",a=e.answers?.length?e.answers.join(", "):"no answers",s=e.details?.filter(Boolean).join(" | ");return`Ask user response:${t}${n} answers: ${a}${s?` details: ${s}`:""}`}function buildHistoryMessageParts(e){const{text:t,nonTextBlocks:n}=formatMessageParts(e.message);return t?{seq:e.localSequence,at:e.createdAt,senderType:e.senderType,senderId:e.senderId,senderName:e.senderName,text:t,nonTextBlocks:n}:null}function formatMessageParts(e){return shared.isAskUserMessage(e)?{text:formatAskUserMessage(e),nonTextBlocks:[]}:shared.isAskUserResponseMessage(e)?{text:formatAskUserResponse(e),nonTextBlocks:[]}:shared.isSDKMessage(e)?formatSdkMessageParts(e):{text:"",nonTextBlocks:[]}}function formatSdkMessageParts(e){switch(e.type){case"user":case"assistant":return splitContentBlocks(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:[]}}function splitContentBlocks(e){if("string"==typeof e)return{text:e,nonTextBlocks:[]};if(Array.isArray(e)){const t=[],n=[];for(const a of e)"text"!==a.type||"string"!=typeof a.text?n.push(a):t.push(a.text);return{text:t.join("\n"),nonTextBlocks:n}}return{text:"",nonTextBlocks:[]}}function decodeMachineAesKey(e){if(!e.machineAesKey)return null;try{const t=shared.decodeBase64(e.machineAesKey);return 32===t.length?t:null}catch{return null}}async function createChannelTaskEncryptionPayload(e){if(!e.secret)return null;const t=decodeMachineAesKey(e);if(!t)return null;const n=await shared.createKeyPair(e.secret),a=shared.generateAESKey();return{taskDataKey:a,dataEncryptionKey:shared.encodeBase64(shared.encryptWithEphemeralKey(a,n.publicKey)),ownerEncryptedDataKey:shared.encodeBase64(shared.encryptAES(shared.encodeBase64(a),t))}}const RECONNECT_DELAY_MS=3e4,ATTACHMENT_BUFFER_TIMEOUT_MS=5e3,GROUP_HISTORY_CONTEXT_LIMIT=30,GROUP_HISTORY_TOOL_DEFAULT_LIMIT=30,GROUP_HISTORY_TOOL_MAX_LIMIT=100,GROUP_HISTORY_TRIGGER_SCAN_LIMIT=500;class ChannelManager{constructor(e,t){this.client=e,this.machineId=t,this.stateFilePath=path.join(machine.machine.agentrixHomeDir,"channels","state.json"),this.groupHistoryFilePath=path.join(machine.machine.agentrixHomeDir,"channels","group-history"),this.loadState()}stateFilePath;groupHistoryFilePath;adapters=new Map;reconnectTimers=new Map;pendingMessages=new Map;store={version:1,channels:[],bindings:[]};taskDataKeyCache=new Map;stopping=!1;createTaskLocks=new Map;async start(){this.loadState();const e=this.store.channels.filter(e=>e.enabled);for(const t of e)try{await this.connectChannel(t.id)}catch(e){machine.logger.warn(`[CHANNEL] Failed to auto-connect channel ${t.id}`,e)}machine.logger.info(`[CHANNEL] Manager started: machineId=${this.machineId}, channels=${this.store.channels.length}, enabled=${e.length}`)}async stop(){this.stopping=!0;for(const e of this.reconnectTimers.values())clearTimeout(e);this.reconnectTimers.clear();for(const e of this.pendingMessages.values())clearTimeout(e.timer);this.pendingMessages.clear();for(const e of this.adapters.values())await e.disconnect().catch(t=>{machine.logger.warn(`[CHANNEL] Failed to disconnect channel ${e.id}`,t)});this.adapters.clear(),machine.logger.info("[CHANNEL] Manager stopped")}getChannels(){return this.loadState(),this.store.channels.map(e=>({...e,credentials:this.redactCredentials(e.credentials)}))}addChannel(e){this.loadState();const t=(new Date).toISOString(),n={id:node_crypto.randomUUID(),platform:e.platform,name:e.name,credentials:e.credentials,enabled:e.enabled??!1,connectionState:"disconnected",createdAt:t,updatedAt:t};return this.store.channels.push(n),this.saveState(),machine.logger.info(`[CHANNEL] Added channel: id=${n.id}, platform=${n.platform}`),{...n,credentials:this.redactCredentials(n.credentials)}}async removeChannel(e){this.loadState();const t=this.store.channels.findIndex(t=>t.id===e);return-1!==t&&(await this.disconnectChannel(e,{disable:!0}).catch(()=>{}),this.store.channels.splice(t,1),this.store.bindings=this.store.bindings.filter(t=>t.channelId!==e),this.saveState(),machine.logger.info(`[CHANNEL] Removed channel: id=${e}`),!0)}async connectChannel(e){this.loadState();const t=this.requireChannel(e);let n;this.clearReconnect(e),this.updateChannel(e,{enabled:!0,connectionState:"connecting",lastError:void 0});try{const a=this.adapters.get(e);a&&"disconnected"!==a.state&&(await a.disconnect().catch(t=>{machine.logger.warn(`[CHANNEL] Failed to reset adapter before reconnect: channel=${e}`,t)}),this.adapters.delete(e),this.clearReconnect(e)),n=this.getOrCreateAdapter(t),await n.connect()}catch(t){const n=t instanceof Error?t.message:String(t);throw this.updateChannel(e,{connectionState:"error",lastError:n}),t}return this.updateChannel(e,{enabled:!0,connectionState:n.state,lastConnectedAt:"connected"===n.state?(new Date).toISOString():t.lastConnectedAt,lastError:"error"===n.state?"Connection failed":void 0}),this.getChannel(e)}async disconnectChannel(e,t={}){this.loadState(),this.requireChannel(e),this.clearReconnect(e),t.disable&&this.updateChannel(e,{enabled:!1});const n=this.adapters.get(e);return n&&(await n.disconnect(),this.adapters.delete(e)),this.updateChannel(e,{enabled:!t.disable&&this.requireChannel(e).enabled,connectionState:"disconnected",lastDisconnectedAt:(new Date).toISOString()}),this.getChannel(e)}async getContacts(e){this.loadState();const t=this.requireChannel(e);return this.getOrCreateAdapter(t).getContacts()}getBindings(e){return this.loadState(),this.requireChannel(e),this.store.bindings.filter(t=>t.channelId===e)}async sendMessageToTaskChannel(e,t){this.loadState();const n=this.getReplyTargetForTask(e);return n?(await this.sendMessageToChannel(n,t),machine.logger.info(`[CHANNEL] Sent task ${e} reply to ${n.channelId}/${n.chatId}`),!0):(machine.logger.debug(`[CHANNEL] No channel binding for task ${e}`),!1)}getReplyTargetForTask(e){this.loadState();const t=this.store.bindings.find(t=>t.taskId===e);if(!t)return null;const n=this.store.channels.find(e=>e.id===t.channelId);return{channelId:t.channelId,chatId:t.chatId,...n?.platform?{platform:n.platform}:{},...t.chatName?{chatName:t.chatName}:{}}}async sendMessageToChannel(e,t){const n=this.getOrCreateAdapter(this.requireChannel(e.channelId));"connected"!==n.state&&await this.connectChannel(e.channelId);const a="string"==typeof t?{content:t}:t,s=a.content?.trim(),i=a.attachments??[];if(!s&&0===i.length)throw new Error("Channel message requires content or attachments");const o=i.map(e=>({...e,kind:this.resolveAttachmentKind(e)}));for(const e of o)if(!this.isAttachmentKindSupported(n,e.kind))throw new Error(`Channel platform ${n.platform} does not support sending ${e.kind} attachments`);if(o.length>0){if(!n.sendChannelMessage)throw new Error(`Channel platform ${n.platform} does not support outgoing attachment messages`);await n.sendChannelMessage(e.chatId,{content:a.content,attachments:o})}else n.sendChannelMessage?await n.sendChannelMessage(e.chatId,{content:a.content}):await n.sendMessage(e.chatId,a.content??"")}getChannelGroupHistory(e,t={}){if("group"!==e.chatType?.toLowerCase())throw new Error("Channel group history is only available for external group chats");const n=Math.max(1,Math.min(t.limit??30,100)),a=this.buildGroupHistoryRef(e),s=this.openGroupHistoryDb(a);try{const i="number"==typeof t.beforeSeq?s.pageMessagesBefore(t.beforeSeq,n):"number"==typeof t.afterSeq?s.pageMessagesAfter(t.afterSeq,n):s.pageRecentMessages(n);return{historyXml:this.formatExternalGroupHistoryXml(a,i.data,e.chatName||e.chatId,{markTriggered:!1}),hasMoreBefore:"number"!=typeof t.afterSeq&&i.hasMore,hasMoreAfter:"number"==typeof t.afterSeq&&i.hasMore}}finally{s.close()}}removeBinding(e,t){this.loadState(),this.requireChannel(e);const n=this.store.bindings.findIndex(n=>n.channelId===e&&n.id===t);return-1!==n&&(this.store.bindings.splice(n,1),this.saveState(),machine.logger.info(`[CHANNEL] Removed binding: channel=${e}, binding=${t}`),!0)}getChannel(e){const t=this.requireChannel(e);return{...t,credentials:this.redactCredentials(t.credentials)}}getOrCreateAdapter(e){const t=this.adapters.get(e.id);if(t)return t;const n=this.createAdapter(e);return n.onMessage(e=>this.routeMessage(e)),n.onStateChange?.((t,n)=>this.handleAdapterState(e.id,t,n)),this.adapters.set(e.id,n),n}createAdapter(e){if("lark"===e.platform)return new LarkAdapter({id:e.id,credentials:e.credentials});if("wechat"===e.platform)return new WechatAdapter({id:e.id,credentials:e.credentials});if("telegram"===e.platform)return new TelegramAdapter({id:e.id,credentials:e.credentials});throw new Error(`Unsupported channel platform: ${e.platform}`)}resolveAttachmentKind(e){return e.kind&&"auto"!==e.kind?e.kind:e.mimeType?.startsWith("image/")?"image":e.mimeType?.startsWith("audio/")?"audio":e.mimeType?.startsWith("video/")?"video":"file"}isAttachmentKindSupported(e,t){const n=e.capabilities;return!n||("image"===t?!0===n.sendImage||!0===n.sendFile:"audio"===t?!0===n.sendAudio||!0===n.sendFile:"video"===t&&!0===n.sendVideo||!0===n.sendFile)}async routeMessage(e){machine.logger.info(`[CHANNEL] routeMessage raw: ${JSON.stringify(e)}`);const t=await this.downloadMessageAttachments(e),n=this.getPendingMessageKey(t);if(this.isAttachmentOnlyMessage(t))return void this.bufferPendingMessage(n,t);const a=this.takePendingMessages(n),s=a.length>0?this.mergePendingMessages(a,t):t;await this.routeRoutableMessage(s)}async routeRoutableMessage(e){this.loadState();let t=e;if(this.isGroupMessage(e)){if(await this.saveGroupHistoryMessage(e),!this.isGroupMessageTriggered(e))return void machine.logger.info(`[CHANNEL] Stored passive group message only: channel=${e.channelId}, chat=${e.chatId}, message=${e.id}`);const n=await this.resolveChatName(e),a=this.loadRecentGroupHistory(e,30);t=this.injectExternalGroupHistory(e,a,n)}const{binding:n,isNew:a}=await this.getOrCreateBindingForMessage(t);machine.logger.info(`[CHANNEL] routeMessage: isNew=${a}, taskId=${n.taskId}`),a||await this.forwardMessageToTask(t,n)}async flushPendingMessages(e){const t=this.takePendingMessages(e);for(const e of t)await this.routeRoutableMessage(e)}bufferPendingMessage(e,t){const n=this.pendingMessages.get(e);n&&clearTimeout(n.timer);const a=setTimeout(()=>{this.flushPendingMessages(e).catch(t=>{machine.logger.warn(`[CHANNEL] Failed to flush pending attachment messages: key=${e}`,t)})},5e3);this.pendingMessages.set(e,{messages:[...n?.messages??[],t],timer:a}),machine.logger.info(`[CHANNEL] Buffered attachment-only message: key=${e}, count=${(n?.messages.length??0)+1}`)}takePendingMessages(e){const t=this.pendingMessages.get(e);return t?(clearTimeout(t.timer),this.pendingMessages.delete(e),t.messages):[]}mergePendingMessages(e,t){const n=[...e.flatMap(e=>e.attachmentPaths??[]),...t.attachmentPaths??[]];return{...t,attachmentPaths:n,mentionedBot:t.mentionedBot||e.some(e=>e.mentionedBot),replyToBot:t.replyToBot||e.some(e=>e.replyToBot),triggered:t.triggered||e.some(e=>e.triggered),rawContent:{pendingMessages:e,textMessage:t.rawContent}}}isGroupMessage(e){return"group"===e.chatType?.toLowerCase()}isGroupMessageTriggered(e){return!0===e.mentionedBot||!0===e.replyToBot||!0===e.triggered}async saveGroupHistoryMessage(e){const t=this.openGroupHistoryDb(e);try{const n=await this.resolveGroupMessageSenderName(e);t.saveMessage({eventId:this.getGroupHistoryEventId(e),message:this.buildGroupHistorySdkMessage(e),senderType:"channel",senderId:e.senderId||"channel-user",senderName:n})}finally{t.close()}}loadRecentGroupHistory(e,t){const n=this.openGroupHistoryDb(e);try{const a=this.getGroupHistoryEventId(e),s=n.pageRecentMessages(500).data,i=s.findIndex(e=>e.eventId===a),o=i>=0?s.slice(0,i+1):s,r=this.findPreviousTriggerIndex(o,a),c=r>=0?r+1:0;return o.slice(c).slice(-t)}finally{n.close()}}injectExternalGroupHistory(e,t,n){return{...e,text:this.formatExternalGroupHistoryXml(e,t,n)}}formatExternalGroupHistoryXml(e,t,n,a={markTriggered:!0}){const s=[`<external_group_history ${[`platform="${this.escapeXmlAttribute(e.platform)}"`,`chatName="${this.escapeXmlAttribute(n)}"`,`chatId="${this.escapeXmlAttribute(e.chatId)}"`].join(" ")}>`];return t.forEach((t,n)=>{const i=buildAttributes({seq:t.localSequence.toString(),id:t.eventId,at:t.createdAt,senderType:t.senderType,senderId:t.senderId,senderName:t.senderName,mentionedBot:this.getHistoryEntryTriggerFlags(t).mentionedBot?"true":void 0,replyToBot:this.getHistoryEntryTriggerFlags(t).replyToBot?"true":void 0,triggered:!1===a.markTriggered?void 0:t.eventId===this.getGroupHistoryEventId(e)?"true":void 0});s.push(` <msg ${i}>`),s.push(` ${this.escapeXmlText(this.formatHistoryMessageContent(t))}`),s.push(" </msg>")}),s.push("</external_group_history>"),s.join("\n")}formatHistoryMessageContent(e){const t=e.message;if(!t||"object"!=typeof t||"user"!==t.type)return"[non-text message]";const n=t.message.content;return"string"==typeof n?n.trim()||"[non-text message]":Array.isArray(n)&&n.filter(e=>e&&"object"==typeof e&&"text"===e.type&&"string"==typeof e.text).map(e=>e.text).join("\n\n").trim()||"[non-text message]"}buildGroupHistorySdkMessage(e){const t=e.attachmentPaths?.length?`[attachments: ${e.attachmentPaths.join(", ")}]`:void 0;return{type:"user",message:{role:"user",content:[e.text?.trim(),t,e.text?.trim()||t?void 0:`[${e.type}]`].filter(Boolean).join("\n\n")},parent_tool_use_id:null,session_id:"",__channelGroupHistory:{mentionedBot:!0===e.mentionedBot,replyToBot:!0===e.replyToBot,triggered:this.isGroupMessageTriggered(e)}}}async resolveGroupMessageSenderName(e){if(e.senderName?.trim())return e.senderName.trim();const t=e.senderId?.trim(),n=this.adapters.get(e.channelId);if(t&&n?.getUserName)try{const e=await n.getUserName(t);if(e&&e!==t)return e}catch(n){machine.logger.debug(`[CHANNEL] Failed to resolve group sender name: channel=${e.channelId}, sender=${t}`,n)}return t||`${e.platform}:${e.chatId}`}getHistoryEntryTriggerFlags(e){const t=e.message.__channelGroupHistory;if(!t||"object"!=typeof t)return{mentionedBot:!1,replyToBot:!1,triggered:!1};const n=t;return{mentionedBot:!0===n.mentionedBot,replyToBot:!0===n.replyToBot,triggered:!0===n.triggered}}isTriggeredHistoryEntry(e){const t=this.getHistoryEntryTriggerFlags(e);return t.triggered||t.mentionedBot||t.replyToBot}findPreviousTriggerIndex(e,t){for(let n=e.length-1;n>=0;n-=1){const a=e[n];if(a.eventId!==t&&this.isTriggeredHistoryEntry(a))return n}return-1}openGroupHistoryDb(e){const t=this.getGroupHistoryDataDir(e);return fs.existsSync(t)||fs.mkdirSync(t,{recursive:!0}),getTaskDb({dataDir:t,taskId:this.getGroupHistoryTaskId(e)})}getGroupHistoryDataDir(e){return path.join(this.groupHistoryFilePath,this.encodePathPart(e.channelId),this.encodePathPart(e.chatId))}getGroupHistoryTaskId(e){return`channel-group:${e.channelId}:${e.chatId}`}getGroupHistoryEventId(e){return`channel-group:${e.channelId}:${e.chatId}:${e.id}`}buildGroupHistoryRef(e){const t="telegram"===e.platform||"wechat"===e.platform||"lark"===e.platform?e.platform:"lark";return{id:"__history_page__",channelId:e.channelId,platform:t,chatId:e.chatId,chatType:e.chatType,type:"text",timestamp:(new Date).toISOString()}}encodePathPart(e){return Buffer.from(e).toString("base64url")}escapeXmlText(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}escapeXmlAttribute(e){return this.escapeXmlText(e).replace(/"/g,"&quot;").replace(/'/g,"&apos;")}getPendingMessageKey(e){return`${e.channelId}:${e.chatId}`}isAttachmentOnlyMessage(e){const t="string"==typeof e.text&&e.text.trim().length>0,n=Boolean(e.fileKey||e.imageKey||e.attachmentPaths?.length);return!t&&n&&("image"===e.type||"file"===e.type)}async downloadMessageAttachments(e){const t=this.adapters.get(e.channelId);if(!t?.downloadFile)return e;const n=[e.imageKey,e.fileKey].filter(e=>Boolean(e)),a=[...new Set(n)];if(0===a.length)return e;const s=[];for(const n of a){const a=await t.downloadFile(n,{fileName:e.fileName});a&&(machine.logger.info(`[CHANNEL] Downloaded attachment: channel=${e.channelId}, chat=${e.chatId}, path=${a}`),s.push(a))}return s.length>0?{...e,attachmentPaths:[...e.attachmentPaths??[],...s]}:e}async forwardMessageToTask(e,t){if(machine.logger.info(`[CHANNEL] Message from ${e.platform} chat ${e.chatId} → task ${t.taskId}`),!this.client.connected)return void machine.logger.debug(`[CHANNEL] Socket not connected, cannot forward message to task ${t.taskId}`);if(t.taskId.startsWith("pending-"))return void machine.logger.warn(`[CHANNEL] Task ${t.taskId} is pending, skipping message forward`);const n=this.readCompanionState(),a=n?.chatId||t.taskId,s=await this.getTaskDataKeyForTask(t.taskId);if(!s)return void machine.logger.warn(`[CHANNEL] Missing task data key, skipping encrypted channel message forward: task=${t.taskId}`);const{plainMessage:i,encryptedMessage:o}=await this.buildEncryptedMessage(e,s);this.client.send("task-message",{eventId:shared.createEventId(),taskId:t.taskId,chatId:a,from:"machine",message:i,encryptedMessage:o,messageType:"text",senderType:"channel",senderId:e.senderId||"channel-user",senderName:e.senderName||`${e.platform}:${e.chatId}`,channelReplyTarget:{channelId:e.channelId,chatId:e.chatId,platform:e.platform,chatType:e.chatType,chatName:t.chatName}}),machine.logger.info(`[CHANNEL] Forwarded message to task ${t.taskId}`)}async buildEncryptedMessage(e,t){const n=e.attachmentPaths??[],a=n.length>0?`[User sent the following attachments: ${n.join(", ")}]`:void 0,s={type:"user",message:{role:"user",content:[a,e.text||(a?void 0:`[${e.type}]`)].filter(Boolean).join("\n\n")}};let i,o=s;if(t)try{i=shared.encryptSdkMessage(s,t),o=void 0}catch(e){machine.logger.warn("[CHANNEL] Failed to encrypt message, sending plaintext",e)}return{plainMessage:o,encryptedMessage:i}}async getOrCreateBindingForMessage(e){const t=this.store.bindings.find(t=>t.channelId===e.channelId&&t.chatId===e.chatId);if(t&&!this.isPendingTaskId(t.taskId))return{binding:t,isNew:!1};t&&(this.store.bindings=this.store.bindings.filter(e=>e.id!==t.id),this.saveState(),machine.logger.warn(`[CHANNEL] Removed pending binding before retry: channel=${t.channelId}, chat=${t.chatId}, task=${t.taskId}`));const n=await this.resolveChatName(e),a=await this.createTaskForChat(e,n),s=(new Date).toISOString(),i={id:node_crypto.randomUUID(),channelId:e.channelId,chatId:e.chatId,taskId:a,chatName:n,createdAt:s,updatedAt:s};return this.isPendingTaskId(a)?(machine.logger.warn(`[CHANNEL] Task creation did not complete; not persisting pending binding: channel=${e.channelId}, chat=${e.chatId}, task=${a}`),{binding:i,isNew:!0}):(this.store.bindings.push(i),this.saveState(),machine.logger.info(`[CHANNEL] Auto-created binding: channel=${e.channelId}, chat=${e.chatId}, task=${a}`),{binding:i,isNew:!0})}isPendingTaskId(e){return e.startsWith("pending-")}async createTaskForChat(e,t){const n=this.createTaskLocks.get(e.chatId);if(n)return n;const a=this.doCreateTaskForChat(e,t);this.createTaskLocks.set(e.chatId,a);try{return await a}finally{this.createTaskLocks.delete(e.chatId)}}async doCreateTaskForChat(e,t){const n=this.readCompanionState();if(!n)return machine.logger.error("[CHANNEL] Cannot create task: companion not registered"),`pending-no-companion-${node_crypto.randomUUID()}`;if(!this.client.connected)return machine.logger.warn("[CHANNEL] Socket not connected, cannot create task via API"),`pending-offline-${node_crypto.randomUUID()}`;const a=await this.createChannelTaskEncryptionPayload();if(!a)return machine.logger.error("[CHANNEL] Cannot create encrypted channel task: missing local machine encryption credentials"),`pending-encryption-unavailable-${node_crypto.randomUUID()}`;const{plainMessage:s,encryptedMessage:i}=await this.buildEncryptedMessage(e,a.taskDataKey);try{const o=await this.client.sendWithAck("channel-task-create",{eventId:shared.createEventId(),userId:n.userId,chatId:n.chatId,agentId:n.agentId,machineId:n.machineId,customTitle:"wechat"===e.platform?"wechat bot":`${e.platform}/${t}`,taskType:"work",supportedFeatures:["sub-task"],taskAgentIds:[n.agentId],dataEncryptionKey:a.dataEncryptionKey,ownerEncryptedDataKey:a.ownerEncryptedDataKey,message:s,encryptedMessage:i,senderType:"channel",senderId:e.senderId||"channel-user",senderName:e.senderName||`${e.platform}:${e.chatId}`,channelReplyTarget:{channelId:e.channelId,chatId:e.chatId,platform:e.platform,chatType:e.chatType,chatName:t}});return"success"===o?.status&&o.taskId?(this.taskDataKeyCache.set(o.taskId,a.taskDataKey),machine.logger.info(`[CHANNEL] Created task ${o.taskId} for chat ${e.chatId}`),o.taskId):(machine.logger.error(`[CHANNEL] API task creation failed: ${o?.message||"unknown"}`),`pending-api-error-${node_crypto.randomUUID()}`)}catch(e){return machine.logger.error("[CHANNEL] Failed to create task via API",e),`pending-error-${node_crypto.randomUUID()}`}}async resolveChatName(e){try{machine.logger.info(`[CHANNEL] resolveChatName: chatType=${e.chatType}, senderId=${e.senderId}, channelId=${e.channelId}`);const t=this.adapters.get(e.channelId),n="p2p"===e.chatType?.toLowerCase();if(n){if(e.senderName)return e.senderName;if(e.senderId&&t?.getUserName){const n=await t.getUserName(e.senderId);if(machine.logger.info(`[CHANNEL] resolveChatName: getUserName returned "${n}"`),n&&n!==e.senderId)return n}}if(t?.getChatName){const n=await t.getChatName(e.chatId);if(machine.logger.info(`[CHANNEL] resolveChatName: getChatName returned "${n}"`),n&&n!==e.chatId)return n}return!n&&e.senderName?e.senderName:e.senderId||e.chatId}catch(t){return machine.logger.warn(`[CHANNEL] Failed to resolve chat name for ${e.chatId}: ${t?.message||String(t)}`),e.senderName||e.senderId||e.chatId}}async createChannelTaskEncryptionPayload(){const e=await machine.machine.readCredentials();if(!e?.secret)return machine.logger.warn("[CHANNEL] Missing machine secret; cannot create encrypted channel task key"),null;return await createChannelTaskEncryptionPayload(e)||(machine.logger.warn("[CHANNEL] Missing machineAesKey in credentials; rebind this machine before creating encrypted channel tasks"),null)}async getTaskDataKeyForTask(e){const t=this.taskDataKeyCache.get(e);if(t)return t;if(!this.client.connected)return machine.logger.debug(`[CHANNEL] Socket not connected, cannot fetch encryption key for task ${e}`),null;try{const t=await this.client.sendWithAck("get-task-encryption-keys",{eventId:shared.createEventId(),taskId:e});if("success"===t?.status&&t.dataEncryptionKey){const n=await machine.machine.getSecretKey();if(!n)return machine.logger.warn(`[CHANNEL] Missing machine secret key while decrypting task key: task=${e}`),null;const a=shared.decryptWithEphemeralKey(shared.decodeBase64(t.dataEncryptionKey),n);return a&&32===a.length?(this.taskDataKeyCache.set(e,a),a):(machine.logger.warn(`[CHANNEL] Failed to decrypt valid task data key: task=${e}`),null)}machine.logger.warn(`[CHANNEL] Failed to fetch encryption keys for task ${e}: ${t?.message||"unknown"}`)}catch(t){machine.logger.warn(`[CHANNEL] Error fetching encryption keys for task ${e}`,t)}return null}readCompanionState(){const e=path.join(machine.machine.agentrixAgentsHomeDir,"companion","claude","state.json");if(!fs.existsSync(e))return machine.logger.warn("[CHANNEL] Companion state.json not found"),null;try{const t=JSON.parse(fs.readFileSync(e,"utf-8"));return t.userId&&t.agentId&&t.chatId&&t.machineId?{userId:t.userId,agentId:t.agentId,chatId:t.chatId,machineId:t.machineId}:(machine.logger.warn("[CHANNEL] Companion state.json missing required fields"),null)}catch(e){return machine.logger.warn("[CHANNEL] Failed to read companion state.json",e),null}}handleAdapterState(e,t,n){this.loadState();const a=this.store.channels.find(t=>t.id===e);a&&(this.updateChannel(e,{connectionState:t,lastConnectedAt:"connected"===t?(new Date).toISOString():a.lastConnectedAt,lastDisconnectedAt:"disconnected"===t?(new Date).toISOString():a.lastDisconnectedAt,lastError:n?.message}),this.stopping||"disconnected"!==t&&"error"!==t||!a.enabled||this.scheduleReconnect(e))}scheduleReconnect(e){if(this.reconnectTimers.has(e))return;const t=setTimeout(()=>{this.reconnectTimers.delete(e),this.connectChannel(e).catch(t=>{machine.logger.warn(`[CHANNEL] Reconnect failed: channel=${e}`,t),this.scheduleReconnect(e)})},3e4);this.reconnectTimers.set(e,t),machine.logger.info(`[CHANNEL] Scheduled reconnect: channel=${e}, delayMs=30000`)}clearReconnect(e){const t=this.reconnectTimers.get(e);t&&(clearTimeout(t),this.reconnectTimers.delete(e))}requireChannel(e){const t=this.store.channels.find(t=>t.id===e);if(!t)throw new Error(`Channel ${e} not found`);return t}updateChannel(e,t){const n=this.requireChannel(e);Object.assign(n,t,{updatedAt:(new Date).toISOString()}),this.saveState()}loadState(){try{if(!fs.existsSync(this.stateFilePath))return void(this.store={version:1,channels:[],bindings:[]});const e=JSON.parse(fs.readFileSync(this.stateFilePath,"utf-8"));this.store=ChannelStoreSchema.parse(e),(e.companionDataEncryptionKey||e.companionOwnerEncryptedDataKey||e.companionKeyMachineId||e.companionKeyChatId)&&this.saveState()}catch(e){machine.logger.warn("[CHANNEL] Failed to load channel state; using empty state",e),this.store={version:1,channels:[],bindings:[]}}}saveState(){const e=path.dirname(this.stateFilePath);fs.existsSync(e)||fs.mkdirSync(e,{recursive:!0}),fs.writeFileSync(this.stateFilePath,JSON.stringify(this.store,null,2),"utf-8")}redactCredentials(e){return Object.fromEntries(Object.entries(e).map(([e,t])=>[e,"string"==typeof t&&t.length>0?"********":t]))}}function getInstalledCliVersion(){try{const e=path$1.join(machine.projectPath(),"package.json"),t=JSON.parse(fs$1.readFileSync(e,"utf-8"));if("string"==typeof t.version&&t.version.trim().length>0)return t.version}catch{}return"0.0.0"}function getUpgradeLockPath(){return path$1.join(path$1.dirname(machine.machine.getStatePaths().daemonStateFile),"upgrade.lock")}function isProcessRunning$2(e){try{return process.kill(e,0),!0}catch{return!1}}function tryAcquireUpgradeLock(){const e=getUpgradeLockPath();if(fs$1.existsSync(e))try{const t=fs$1.readFileSync(e,"utf-8"),n=JSON.parse(t);"number"!=typeof n.pid||isProcessRunning$2(n.pid)||fs$1.unlinkSync(e)}catch{fs$1.unlinkSync(e)}try{const t=fs$1.openSync(e,"wx");fs$1.writeFileSync(t,JSON.stringify({pid:process.pid,createdAt:(new Date).toISOString()})),fs$1.closeSync(t)}catch{return null}return{release:()=>{try{const t=fs$1.readFileSync(e,"utf-8");JSON.parse(t).pid===process.pid&&fs$1.unlinkSync(e)}catch{}}}}async function checkForUpgrades(){const e=getInstalledCliVersion();try{const t=child_process.execSync("npm view @agentrix/cli version",{encoding:"utf-8",stdio:["pipe","pipe","pipe"],timeout:5e3}).trim();return{hasUpgrade:compareVersions(t,e)>0,currentVersion:e,latestVersion:t}}catch(t){return{hasUpgrade:!1,currentVersion:e,latestVersion:null}}}async function installLatestCli(e){await new Promise((t,n)=>{const a=child_process.spawn("npm",["install","-g","@agentrix/cli@latest"],{stdio:e,env:process.env});a.on("error",n),a.on("exit",e=>{0!==e?n(new Error(`npm install exited with code ${e??"unknown"}`)):t()})})}async function executeCliUpgrade(e,t={}){const n=tryAcquireUpgradeLock();if(!n)return{status:"busy",message:"CLI upgrade already in progress"};try{const n=e??await checkForUpgrades();if(!n.hasUpgrade)return{status:"already_latest",currentVersion:n.currentVersion,latestVersion:n.latestVersion};try{return await installLatestCli(t.stdio??"inherit"),{status:"upgraded",fromVersion:n.currentVersion,toVersion:n.latestVersion??"latest"}}catch(e){return{status:"failed",currentVersion:n.currentVersion,latestVersion:n.latestVersion,error:e instanceof Error?e.message:String(e)}}}finally{n.release()}}function compareVersions(e,t){const n=e.split(".").map(Number),a=t.split(".").map(Number);for(let e=0;e<Math.max(n.length,a.length);e++){const t=n[e]||0,s=a[e]||0;if(t>s)return 1;if(t<s)return-1}return 0}async function performAutoUpgrade(e){try{if(console.log(""),e||(console.log(chalk.blue("🔄 Checking for upgrades...")),e=await checkForUpgrades()),!e.hasUpgrade)return console.log(chalk.green("✓ Already on latest version")),console.log(""),!0;console.log(chalk.blue(`🔄 Upgrading from ${e.currentVersion} to ${e.latestVersion}...`));const t=await executeCliUpgrade(e,{stdio:"inherit"});if("busy"===t.status)return console.log(chalk.yellow(`⚠️ ${t.message}`)),!1;if("failed"===t.status)throw new Error(t.error);return console.log(chalk.green("✓ Upgrade complete")),console.log(""),!0}catch(e){return console.log(""),console.log(chalk.yellow("⚠️ CLI upgrade failed")),console.log(chalk.dim(" You can upgrade manually with: npm install -g @agentrix/cli@latest")),console.log(""),!1}}const execFileAsync$3=node_util.promisify(node_child_process.execFile),TASK_LOG_PATTERN$1=/^task-(.+)\.log(?:\.\d+)?(?:\.gz)?$/;function toProtocolRelative(e,t){return path.relative(e,t).split(path.sep).join("/")}function normalizeProtocolRelative(e){const t=e.trim().replace(/\\/g,"/");if(!t||t.includes("\0")||t.startsWith("/"))return null;const n=t.split("/").filter(Boolean);return 0===n.length||n.some(e=>"."===e||".."===e)?null:n.join("/")}async function resolveSafeRelativePath(e,t){const n=normalizeProtocolRelative(t);if(!n)return null;const a=await promises$1.realpath(e),s=path.resolve(a,...n.split("/"));if(s!==a&&!s.startsWith(a+path.sep))return null;if(!fs.existsSync(s))return{relativePath:n,absolutePath:s};const i=await promises$1.realpath(s);return i===a||i.startsWith(a+path.sep)?{relativePath:n,absolutePath:s}:null}async function getPathSize(e){let t=0;const n=[e];for(;n.length>0;){const e=n.pop();let a,s;try{a=await promises$1.lstat(e)}catch{continue}if(t+=a.size,a.isDirectory()&&!a.isSymbolicLink())try{s=await promises$1.opendir(e);for await(const t of s)n.push(path.join(e,t.name))}catch{continue}}return t}function readWorkspaceStateForTask(e,t){const n=path.join(machine.machine.agentrixWorkspaceHomeDir,"users",e,t,"data"),a=path.join(n,"workspace.json");if(fs.existsSync(a))try{return JSON.parse(fs.readFileSync(a,"utf-8"))}catch{return null}const s=path.join(n,"cwd.txt");if(!fs.existsSync(s))return null;try{const e=fs.readFileSync(s,"utf-8").trim();return e?{initialized:!0,initializedAt:new Date(fs.statSync(s).mtimeMs).toISOString(),cwd:e}:null}catch{return null}}function listWorkspaceTasks(){const e=machine.machine.agentrixWorkspaceHomeDir,t=path.join(e,"users");if(!fs.existsSync(t))return[];const n=[];for(const e of fs.readdirSync(t,{withFileTypes:!0})){if(!e.isDirectory())continue;const a=e.name,s=path.join(t,a);for(const e of fs.readdirSync(s,{withFileTypes:!0})){if(!e.isDirectory())continue;const t=e.name,i=path.join(s,t);n.push({userId:a,taskId:t,taskDir:i,projectDir:path.join(i,"project"),dataDir:path.join(i,"data"),state:readWorkspaceStateForTask(a,t)})}}return n}function isDirectUserDirectoryWorkspace(e){return"directory"===e?.repositorySourceType&&(!0===e.forceUserCwd||!1===e.useWorktree)}function makeStorageItem(e){const t=e.relativePath??toProtocolRelative(machine.machine.agentrixHomeDir,e.absolutePath);return{id:e.id,kind:e.kind,label:e.label,relativePath:t,pathDisplay:t,bytes:e.bytes,reclaimable:e.reclaimable,defaultSelected:e.defaultSelected??e.reclaimable,deleteMode:e.deleteMode,reasonCode:e.reasonCode,reason:e.reason,childrenSummary:e.childrenSummary}}async function findGitCommonDir(e){try{const{stdout:t}=await execFileAsync$3("git",["-C",e,"rev-parse","--path-format=absolute","--git-common-dir"],{windowsHide:!0}),n=t.trim();return n?n.endsWith(`${path.sep}.git`)?path.dirname(n):n:null}catch{return null}}async function getRegisteredWorktreeMainRepo(e){const t=await findGitCommonDir(e);if(!t)return null;try{const n=await listWorktrees(t),a=fs.realpathSync(e);return n.some(e=>{try{return fs.realpathSync(e.path)===a&&!e.isMain}catch{return!1}})?t:null}catch{return null}}function findWorkspaceForRelativePath(e){const t=e.split("/");if(t.length<4||"workspaces"!==t[0]||"users"!==t[1])return null;const[,,n,a]=t,s=path.join(machine.machine.agentrixWorkspaceHomeDir,"users",n,a);return{userId:n,taskId:a,taskDir:s,projectDir:path.join(s,"project"),dataDir:path.join(s,"data"),state:readWorkspaceStateForTask(n,a)}}function parseTaskIdFromLogRelativePath(e){const t=e.split("/");return"logs"!==t[0]?null:TASK_LOG_PATTERN$1.exec(t[t.length-1])?.[1]??null}async function planCleanItem(e,t){const n=await resolveSafeRelativePath(machine.machine.agentrixHomeDir,e);if(!n)return{relativePath:e,releasable:!1,reasonCode:"invalid_path",message:"Path must stay inside the Agentrix home directory"};const{relativePath:a,absolutePath:s}=n;if(!fs.existsSync(s))return{relativePath:a,absolutePath:s,releasable:!1,reasonCode:"missing",message:"Path no longer exists"};const i=a.split("/")[0];if("logs"===i){const e=parseTaskIdFromLogRelativePath(a);return e&&t.has(e)?{relativePath:a,absolutePath:s,releasable:!1,reasonCode:"active_task",message:"Task is currently running"}:{relativePath:a,absolutePath:s,kind:"logs",method:"rm",releasable:!0}}if("tmp"===i)return{relativePath:a,absolutePath:s,kind:"tmp",method:"rm",releasable:!0};if("repos"===i)return 4===a.split("/").length?{relativePath:a,absolutePath:s,kind:"repos",method:"rm",releasable:!0}:{relativePath:a,absolutePath:s,releasable:!1,reasonCode:"unsupported_repo_path",message:"Only repository-level paths are cleanable"};if("workspaces"!==i)return{relativePath:a,absolutePath:s,releasable:!1,reasonCode:"protected_area",message:"This Agentrix area is not cleanable"};const o=findWorkspaceForRelativePath(a);if(!o)return{relativePath:a,absolutePath:s,releasable:!1,reasonCode:"unsupported_workspace_path",message:"Only task project and task data paths are cleanable"};if(t.has(o.taskId))return{relativePath:a,absolutePath:s,releasable:!1,reasonCode:"active_task",message:"Task is currently running"};if(isDirectUserDirectoryWorkspace(o.state))return{relativePath:a,absolutePath:s,releasable:!1,reasonCode:"user_directory",message:"This task uses a user-owned directory"};const r=a.split("/").slice(4).join("/");if("project"===r){const e=await getRegisteredWorktreeMainRepo(s);return e?{relativePath:a,absolutePath:s,kind:"workspaces",method:"remove-worktree",releasable:!0,workspace:o,mainRepoDir:e}:{relativePath:a,absolutePath:s,kind:"workspaces",method:"rm-stale-directory",releasable:!0,workspace:o}}return"data"===r?{relativePath:a,absolutePath:s,kind:"workspaces",method:"rm",releasable:!0,workspace:o}:{relativePath:a,absolutePath:s,releasable:!1,reasonCode:"unsupported_workspace_path",message:"Only task project and task data paths are cleanable"}}async function executeCleanPlan(e){const t=await getPathSize(e.absolutePath);if("remove-worktree"===e.method){if(!e.mainRepoDir)throw new Error("Missing main repository for worktree removal");await removeWorktree(e.mainRepoDir,e.absolutePath,!0)}else{const t=fs.lstatSync(e.absolutePath);t.isDirectory()&&!t.isSymbolicLink()?await promises$1.rm(e.absolutePath,{recursive:!0,force:!1}):await promises$1.unlink(e.absolutePath)}return t}function removePathBestEffort(e){try{fs.statSync(e).isDirectory()?fs.rmSync(e,{recursive:!0,force:!0}):fs.unlinkSync(e)}catch{}}function validateDirectory(e){try{if(!fs$1.statSync(e).isDirectory())return{ok:!1,status:"missing",error:"Path is not a directory"};try{fs$1.accessSync(e,fs$1.constants.R_OK|fs$1.constants.W_OK)}catch{return{ok:!1,status:"permission_lost",error:"Directory is not readable and writable"}}return{ok:!0,status:"active"}}catch(e){return{ok:!1,status:"missing",error:e instanceof Error?e.message:"Directory is unavailable"}}}function directoryEntry(e,t,n){const a=fs$1.statSync(e);return{name:t,path:e,type:n,size:a.size,modifiedAt:a.mtime.toISOString()}}function listDirectory(e){const t=path$1.resolve(e?.trim()||os$1.homedir()),n=validateDirectory(t);if("active"!==n.status)return{ok:!1,status:n.status,path:t,parentPath:null,entries:[],error:n.error};const a=path$1.parse(t).root,s=t===a?null:path$1.dirname(t),i=fs$1.readdirSync(t,{withFileTypes:!0}).map(e=>{const n=path$1.join(t,e.name);try{if(e.isDirectory())return directoryEntry(n,e.name,"directory");if(e.isFile())return directoryEntry(n,e.name,"file")}catch{return null}return null}).filter(e=>Boolean(e)).sort((e,t)=>e.type!==t.type?"directory"===e.type?-1:1:e.name.localeCompare(t.name));return{ok:!0,status:"active",path:t,parentPath:s,entries:i}}function createDirectory(e,t){const n=t.trim();if(!n||"."===n||".."===n||n.includes("/")||n.includes("\\"))throw new Error("Directory name is invalid");const a=path$1.resolve(e),s=validateDirectory(a);if("active"!==s.status)throw new Error(s.error||"Parent directory is unavailable");const i=path$1.resolve(a,n);if(i!==a&&!i.startsWith(a.endsWith(path$1.sep)?a:a+path$1.sep))throw new Error("Directory path is invalid");return fs$1.mkdirSync(i),{path:i,validation:validateDirectory(i)}}class MachineControlCoordinator{state="ready";machineId;workerManager;getSocketClient;requestRestartCallback;restartRequested=!1;pendingRestartReport=null;activeStorageOperations={};constructor(e){this.machineId=e.machineId,this.workerManager=e.workerManager,this.getSocketClient=e.getSocketClient,this.requestRestartCallback=e.requestRestart,this.workerManager.setDrainCallback(()=>this.handleSessionDrain())}getState(){return this.state}isAcceptingNewWorkers(){return this.workerManager.isAcceptingNewWorkers()}clearGracefulRestartGate(){"pending_restart"===this.state&&(this.state="ready"),this.restartRequested=!1,this.pendingRestartReport=null,this.workerManager.setWorkerStartGate(!0)}rollbackGracefulRestart(){"pending_restart"!==this.state&&"restarting"!==this.state||(this.state="ready"),this.restartRequested=!1,this.pendingRestartReport=null,this.workerManager.setWorkerStartGate(!0)}prepareGracefulRestart(e,t,n){this.workerManager.setWorkerStartGate(!1,"daemon_pending_restart",t??"Daemon restart is pending"),this.workerManager.pruneStaleSessions();const a=this.workerManager.getCurrentSessions().length;if(0===a){this.state="restarting";const s=n??this.pendingRestartReport??void 0;return this.pendingRestartReport=null,this.requestRestart(e,t,s),{state:"restarting",activeSessions:a}}return this.state="pending_restart",this.pendingRestartReport=n??this.pendingRestartReport,{state:"pending_restart",activeSessions:a}}buildPingResult(){this.workerManager.pruneStaleSessions();const e="pending_restart"===this.state||"restarting"===this.state;return{machineId:this.machineId,runningCliVersion:machine.packageJson.version,installedCliVersion:getInstalledCliVersion(),restartRequired:e,restartPending:e,platform:process.platform,uptimeMs:Math.max(0,Math.floor(1e3*process.uptime())),activeSessions:this.workerManager.getCurrentSessions().length,capabilities:["ping","upgrade-cli","storage-scan","storage-clean","pick-directory","validate-directory","list-directory","create-directory"]}}handleCommand(e,t){if(this.matchesTarget(e))if("ping"!==e.action){if("validate-directory"===e.action){const n="string"==typeof e.params?.path?e.params.path:"";return n.trim()?void t({eventId:shared.createEventId(),status:"success",opCode:e.eventId,data:{result:validateDirectory(n)}}):void t(this.failedAck(e.eventId,"operation_failed","Directory path is required"))}if("pick-directory"!==e.action){if("list-directory"===e.action){const n="string"==typeof e.params?.path?e.params.path:void 0;return void t({eventId:shared.createEventId(),status:"success",opCode:e.eventId,data:{result:listDirectory(n)}})}if("create-directory"!==e.action)"upgrade-cli"!==e.action?"storage-scan"!==e.action&&"storage-clean"!==e.action?t(this.failedAck(e.eventId,"unsupported_operation","Unsupported machine control operation")):this.handleStorageManagement(e,t):this.handleUpgradeCli(e,t);else try{const n=createDirectory("string"==typeof e.params?.parentPath?e.params.parentPath:"","string"==typeof e.params?.name?e.params.name:"");t({eventId:shared.createEventId(),status:"success",opCode:e.eventId,data:{result:n}})}catch(n){const a=n instanceof Error?n.message:"Failed to create directory";t(this.failedAck(e.eventId,"operation_failed",a))}}else try{const n=pickDirectory("string"==typeof e.params?.defaultPath?e.params.defaultPath:void 0);t({eventId:shared.createEventId(),status:"success",opCode:e.eventId,data:{result:{path:n??null,...n?{validation:validateDirectory(n)}:{}}}})}catch(n){const a=n instanceof Error?n.message:"Failed to pick directory";t(this.failedAck(e.eventId,"operation_failed",a))}}else t({eventId:shared.createEventId(),status:"success",opCode:e.eventId,data:{result:this.buildPingResult()}});else t(this.failedAck(e.eventId,"machine_not_found","Machine control target does not match this daemon"))}handleUpgradeCli(e,t){"ready"===this.state?(this.state="upgrading",t({eventId:shared.createEventId(),status:"success",opCode:e.eventId}),this.runUpgrade(e).catch(t=>{machine.logger.error("[MACHINE CONTROL] upgrade-cli failed unexpectedly:",t),this.state="ready",this.sendProgress({eventId:shared.createEventId(),opCode:e.eventId,status:"failed",errorCode:"operation_failed",errorMessage:t instanceof Error?t.message:"CLI upgrade failed"})})):t(this.failedAck(e.eventId,"pending_restart"===this.state?"daemon_pending_restart":"daemon_control_busy","Daemon is not ready for CLI upgrade"))}async runUpgrade(e){this.sendProgress({eventId:shared.createEventId(),opCode:e.eventId,status:"running",message:"Checking and installing CLI upgrade"});const t=await executeCliUpgrade(void 0,{stdio:"ignore"});if("busy"===t.status)return this.state="ready",void this.sendProgress({eventId:shared.createEventId(),opCode:e.eventId,status:"failed",errorCode:"operation_busy",errorMessage:t.message});if("already_latest"===t.status)return this.state="ready",void this.sendProgress({eventId:shared.createEventId(),opCode:e.eventId,status:"succeeded",message:"CLI is already up to date",result:{alreadyLatest:!0,currentVersion:t.currentVersion,latestVersion:t.latestVersion,restartRequired:!1,restartDeferred:!1,activeSessions:this.workerManager.getCurrentSessions().length}});if("failed"===t.status)return this.state="ready",void this.sendProgress({eventId:shared.createEventId(),opCode:e.eventId,status:"failed",errorCode:"operation_failed",errorMessage:t.error});const n={opCode:e.eventId,target:e.target,fromVersion:t.fromVersion,toVersion:t.toVersion},a=this.prepareGracefulRestart("machine-control","CLI upgrade installed",n);this.sendProgress({eventId:shared.createEventId(),opCode:e.eventId,status:"running",message:"pending_restart"===a.state?"CLI upgrade installed; restart deferred until active sessions finish":"CLI upgrade installed; restarting daemon",result:{fromVersion:t.fromVersion,toVersion:t.toVersion,restartRequired:!0,restartDeferred:"pending_restart"===a.state,activeSessions:a.activeSessions}})}handleStorageManagement(e,t){if("ready"!==this.state)return void t(this.failedAck(e.eventId,"daemon_control_busy","Daemon is not ready for storage management"));const n="storage-scan"===e.action||"storage-clean"===e.action?e.action:null;if(!n)return void t(this.failedAck(e.eventId,"unsupported_operation","Unsupported storage operation"));if(this.activeStorageOperations[n])return void t(this.failedAck(e.eventId,"operation_busy",`Another ${n} operation is already running`));const a=this.buildStorageWorkerRequest(e);"storage-clean"!==e.action||a.items&&0!==a.items.length?(this.activeStorageOperations[n]=e.eventId,t({eventId:shared.createEventId(),status:"success",opCode:e.eventId}),this.runStorageManagementWorker(e,a).catch(t=>{machine.logger.error("[MACHINE CONTROL] storage management failed unexpectedly:",t),this.sendProgress({eventId:shared.createEventId(),opCode:e.eventId,status:"failed",errorCode:"operation_failed",errorMessage:t instanceof Error?t.message:"Storage operation failed"})}).finally(()=>{this.activeStorageOperations[n]===e.eventId&&delete this.activeStorageOperations[n]})):t(this.failedAck(e.eventId,"operation_failed","No storage items selected"))}buildStorageWorkerRequest(e){const t={activeTaskIds:this.workerManager.getCurrentSessions().map(e=>e.taskId)};if("storage-clean"===e.action){t.dryRun=!0===e.params?.dryRun;const n=Array.isArray(e.params?.items)?e.params.items:[];t.items=n.map(e=>e&&"object"==typeof e&&"string"==typeof e.relativePath?{relativePath:e.relativePath}:null).filter(e=>Boolean(e))}return t}async runStorageManagementWorker(e,t){let n=null;try{n=fs$1.mkdtempSync(path$1.join(os$1.tmpdir(),`agentrix-${e.action}-`));const a=path$1.join(n,"request.json");fs$1.writeFileSync(a,JSON.stringify(t));const s=e.action,i=spawnAgentrixCLI([s,"--op-code",e.eventId,"--request-file",a],{stdio:["ignore","pipe","pipe"],env:process.env});this.sendProgress({eventId:shared.createEventId(),opCode:e.eventId,status:"running",message:"storage-scan"===e.action?"Scanning Agentrix storage":"Cleaning Agentrix storage"}),await new Promise(t=>{let n="",a=!1;const o=t=>{"completed"!==t.type&&"failed"!==t.type||(a=!0),this.sendProgress(this.mapStorageWorkerEventToProgress(e,t))};i.stdout?.setEncoding("utf8"),i.stdout?.on("data",e=>{n+=e;const t=n.split(/\r?\n/);n=t.pop()??"";for(const e of t){const t=e.trim();if(t)try{o(JSON.parse(t))}catch(e){machine.logger.warn(`[MACHINE CONTROL] Ignoring malformed storage worker event: ${t}`,e)}}}),i.stderr?.setEncoding("utf8"),i.stderr?.on("data",e=>{machine.logger.warn(`[MACHINE CONTROL] ${s} stderr: ${e.trim()}`)}),i.on("error",t=>{a||(a=!0,this.sendProgress({eventId:shared.createEventId(),opCode:e.eventId,status:"failed",errorCode:"operation_failed",errorMessage:t.message}))}),i.on("close",s=>{if(n.trim())try{o(JSON.parse(n.trim()))}catch(e){machine.logger.warn(`[MACHINE CONTROL] Ignoring malformed trailing storage worker event: ${n.trim()}`,e)}a||this.sendProgress({eventId:shared.createEventId(),opCode:e.eventId,status:"failed",errorCode:"operation_failed",errorMessage:0===s?"Storage operation ended before reporting completion; please retry":`Storage worker exited with code ${s}`}),t()})})}finally{n&&removePathBestEffort(n)}}mapStorageWorkerEventToProgress(e,t){return"failed"===t.type?{eventId:shared.createEventId(),opCode:e.eventId,status:"failed",message:t.message,errorCode:"operation_failed",errorMessage:t.message,result:{phase:t.type,...t}}:"completed"===t.type?{eventId:shared.createEventId(),opCode:e.eventId,status:"succeeded",message:"storage-scan"===e.action?"Storage scan completed":"Storage clean completed",result:t.result??{summary:t.summary}}:{eventId:shared.createEventId(),opCode:e.eventId,status:"running",message:this.describeStorageWorkerEvent(e.action,t),result:{phase:t.type,...t}}}describeStorageWorkerEvent(e,t){return"category-started"===t.type?`Scanning ${t.label}`:"item"===t.type?`Scanned ${t.item.pathDisplay??t.item.relativePath}`:"item-validating"===t.type?`Validating ${t.relativePath}`:"item-cleaning"===t.type?`Cleaning ${t.relativePath}`:"item-completed"===t.type?`Cleaned ${t.relativePath}`:"item-skipped"===t.type?`Skipped ${t.relativePath}`:"item-failed"===t.type?`Failed ${t.relativePath}`:"storage-scan"===e?"Scanning Agentrix storage":"Cleaning Agentrix storage"}handleSessionDrain(){if("pending_restart"!==this.state)return;const e=this.pendingRestartReport??void 0,t=this.prepareGracefulRestart("machine-control","Active sessions drained after CLI upgrade",e);e&&this.sendProgress({eventId:shared.createEventId(),opCode:e.opCode,status:"running",message:"Active sessions drained; restarting daemon",result:{fromVersion:e.fromVersion,toVersion:e.toVersion,restartRequired:!0,restartDeferred:!1,activeSessions:t.activeSessions}})}requestRestart(e,t,n){this.restartRequested||(this.restartRequested=!0,this.requestRestartCallback(e,t,n))}sendProgress(e){const t=this.getSocketClient();t?.connected?t.send("machine-control-progress",e):machine.logger.warn(`[MACHINE CONTROL] Dropping progress ${e.opCode}; socket not connected`)}matchesTarget(e){return e.target.machineId===this.machineId}failedAck(e,t,n){return{eventId:shared.createEventId(),status:"failed",opCode:e,message:n,data:{errorCode:t}}}}const DEFAULT_OLD_DAEMON_EXIT_TIMEOUT_MS=12e4,DEFAULT_NEW_DAEMON_START_TIMEOUT_MS=3e4,POLL_INTERVAL_MS=100;function getPendingReportPath(){return path.join(path.dirname(machine.machine.getStatePaths().daemonStateFile),"daemon-restart-report.json")}function sleep(e){return new Promise(t=>setTimeout(t,e))}function isProcessRunning$1(e){try{return process.kill(e,0),!0}catch{return!1}}function readPendingReport(){const e=getPendingReportPath();if(!fs.existsSync(e))return null;try{const t=JSON.parse(fs.readFileSync(e,"utf-8"));return t.opCode&&t.target?.machineId?t:null}catch{return null}}function writePendingReport(e){fs.writeFileSync(getPendingReportPath(),JSON.stringify(e,null,2),"utf-8")}function clearPendingReport(){try{const e=getPendingReportPath();fs.existsSync(e)&&fs.unlinkSync(e)}catch{}}function buildDaemonRestartArgs(e){const t=["restart-daemon"];return void 0!==e.oldPid&&t.push("--old-pid",String(e.oldPid)),e.expectedCliVersion&&t.push("--expected-version",e.expectedCliVersion),e.reason&&t.push("--reason",e.reason),e.report&&t.push("--report-json",JSON.stringify(e.report)),t}function launchDaemonRestart(e){try{const t=spawnAgentrixCLI(buildDaemonRestartArgs(e),{detached:!0,stdio:"ignore",env:process.env});return t.unref(),t}catch(e){return machine.logger.error("[DAEMON RESTART] Failed to launch restart command",e),null}}async function waitForOldDaemonExit(e,t){const n=Date.now()+t;for(;Date.now()<n;){if(!isProcessRunning$1(e))return!0;await sleep(100)}return!isProcessRunning$1(e)}async function waitForReplacementDaemon(e,t,n){const a=Date.now()+n;for(;Date.now()<a;){const n=await machine.machine.readDaemonState();if(n&&n.pid!==e&&n.cliVersion===t&&isProcessRunning$1(n.pid))return n;await sleep(100)}return null}async function runDaemonRestart(e){const t=void 0===e.oldPid?await machine.machine.readDaemonState():null,n=e.oldPid??(t&&isProcessRunning$1(t.pid)?t.pid:void 0),a=e.expectedCliVersion??getInstalledCliVersion();if(e.report&&writePendingReport({...e.report,oldPid:n,expectedCliVersion:a,reason:e.reason,createdAt:(new Date).toISOString()}),e.stopExistingDaemon&&void 0!==n&&isProcessRunning$1(n)&&await stopDaemon(),void 0!==n&&!await waitForOldDaemonExit(n,e.oldDaemonExitTimeoutMs??12e4))return{success:!1,error:`Old daemon PID ${n} did not exit before timeout`};try{spawnAgentrixCLI(["daemon"],{detached:!0,stdio:"ignore",env:process.env}).unref()}catch(e){return{success:!1,error:e instanceof Error?e.message:String(e)}}return await waitForReplacementDaemon(n,a,e.newDaemonStartTimeoutMs??3e4)?{success:!0}:{success:!1,error:`Replacement daemon did not report version ${a} before timeout`}}async function flushPendingDaemonRestartReport(e){const t=readPendingReport();if(!t)return!1;const n=machine.packageJson.version,a={eventId:shared.createEventId(),opCode:t.opCode,status:"succeeded",message:"CLI upgrade installed; daemon restarted",result:{fromVersion:t.fromVersion,toVersion:t.toVersion??t.expectedCliVersion,currentVersion:n,runningCliVersion:n,installedCliVersion:n,restartRequired:!1,restartDeferred:!1,activeSessions:0}};return e.send("machine-control-progress",a),await e.flush(3e3).catch(e=>{machine.logger.warn("[DAEMON RESTART] Could not confirm restart report flush",e)}),clearPendingReport(),machine.logger.info(`[DAEMON RESTART] Flushed pending restart report for ${t.opCode}`),!0}const DEFAULT_WORKSPACE_SYNC_INTERVAL_MS=3e5,WORKSPACE_SYNC_STATE_VERSION=1;function workspaceStatus(e){return validateDirectory(e).status}function defaultWorkspaceSyncStateFile(){return path.join(machine.machine.agentrixHomeDir,"workspace-mode.state.json")}async function requestJson(e,t){const n=await fetch(e,t);if(!n.ok){const e=await n.text().catch(()=>"");throw new Error(`HTTP ${n.status}${e?`: ${e}`:""}`)}return n.json()}class WorkspaceStatusSync{constructor(e,t={}){this.credentials=e,this.intervalMs=t.intervalMs??3e5,this.stateFilePath=t.stateFilePath??defaultWorkspaceSyncStateFile()}timer=null;running=!1;intervalMs;stateFilePath;start(){this.timer||(this.syncOnce(),this.timer=setInterval(()=>{this.syncOnce()},this.intervalMs),this.timer.unref?.())}stop(){this.timer&&(clearInterval(this.timer),this.timer=null)}async syncOnce(){if(!this.running){this.running=!0;try{const e=await this.loadState(),t=this.buildStatusReports(e);if(0===t.length)return;const n=this.markStatusesObserved(e,t);await this.saveState(n);const a={statuses:t};await requestJson(`${machine.machine.serverUrl}/v1/workspaces/machine/path-statuses`,{method:"POST",headers:{Authorization:`Bearer ${this.credentials.token}`,"Content-Type":"application/json"},body:JSON.stringify(a)}),await this.saveState(this.markStatusesSynced(n,t))}catch(e){machine.logger.warn("[WORKSPACE SYNC] Failed to sync workspace path statuses",e)}finally{this.running=!1}}}async applyCacheUpdate(e){if(e.machineId!==this.credentials.machineId)return;const t=await this.loadState(),n=(new Date).toISOString(),a={...t.workspaces};if("replace"===e.action){const t={};for(const a of e.workspaces??[])t[a.id]=this.entryFromWorkspace(a,n);return void await this.saveState({version:1,machineId:this.credentials.machineId,workspaces:t})}if("upsert"===e.action&&e.workspace)return a[e.workspace.id]=this.entryFromWorkspace(e.workspace,n),void await this.saveState({...t,workspaces:a});"remove"===e.action&&e.workspaceId&&(delete a[e.workspaceId],await this.saveState({...t,workspaces:a}))}async loadState(){const e={version:1,machineId:this.credentials.machineId,workspaces:{}};if(!fs.existsSync(this.stateFilePath))return e;try{const t=JSON.parse(await promises$1.readFile(this.stateFilePath,"utf-8"));return 1===t.version&&t.machineId===this.credentials.machineId&&t.workspaces&&"object"==typeof t.workspaces?t:e}catch(t){return machine.logger.warn("[WORKSPACE SYNC] Failed to read workspace sync state; rebuilding cache",t),e}}async saveState(e){await promises$1.mkdir(path.dirname(this.stateFilePath),{recursive:!0}),await promises$1.writeFile(this.stateFilePath,JSON.stringify(e,null,2),"utf-8")}buildStatusReports(e){const t=[];for(const n of Object.values(e.workspaces)){const e=workspaceStatus(n.path);e!==n.lastSyncedStatus&&t.push({workspaceId:n.workspaceId,pathStatus:e})}return t}markStatusesSynced(e,t){const n={...e.workspaces};for(const e of t){const t=n[e.workspaceId];t&&(n[e.workspaceId]={...t,lastKnownStatus:e.pathStatus,lastSyncedStatus:e.pathStatus,updatedAt:(new Date).toISOString()})}return{...e,workspaces:n}}markStatusesObserved(e,t){const n={...e.workspaces};for(const e of t){const t=n[e.workspaceId];t&&(n[e.workspaceId]={...t,lastKnownStatus:e.pathStatus,updatedAt:(new Date).toISOString()})}return{...e,workspaces:n}}entryFromWorkspace(e,t){return{workspaceId:e.id,path:e.path,lastKnownStatus:e.pathStatus,lastSyncedStatus:e.pathStatus,updatedAt:t}}}function isReauthRequiredError(e){const t=getSocketErrorDetails(e);return"machine_binding_revoked"===t.code||t.message.includes("Machine binding revoked")}function getActionableSocketError(e){const t=getSocketErrorDetails(e);return t.code||t.action?t:null}function isGitlabProxySocketLog(e){return e.includes("daemon-gitlab-request")||e.includes("daemon-gitlab-response")}async function startDaemon(){machine.initializeLogger({type:"daemon"});const{requestShutdown:e,shutdownPromise:t}=setupGracefulShutdown({processType:"daemon"});console.log("[DAEMON RUN] Starting daemon process..."),machine.logger.debug("[DAEMON RUN] Environment",getEnvironmentInfo()),await isLatestDaemonRunning()&&(console.log("Daemon already running..."),process.exit(0));let n=await machine.machine.acquireDaemonLock(5,200);for(;!n;)await stopDaemon(),n=await machine.machine.acquireDaemonLock(5,200),n||(machine.logger.debug("[DAEMON RUN] cannot acquire daemon lock..."),process.exit(1));try{startCaffeinate()&&machine.logger.debug("[DAEMON RUN] Sleep prevention enabled");const a=await authAndSetupMachineIfNeeded();machine.logger.debug("[DAEMON RUN] Auth and machine setup complete");const s=new SandboxPool;await s.initialize(machine.machine.getSandboxSettings());const i=new TaskWorkerManager(s);let o,r,c,l,d=!1;i.setSocketClientProvider(()=>o?.client),l=new MachineControlCoordinator({machineId:a.machineId,workerManager:i,getSocketClient:()=>o?.client,requestRestart:(t,n,a)=>{launchDaemonRestart({oldPid:process.pid,expectedCliVersion:a?.toVersion??getInstalledCliVersion(),reason:n,report:a})?(d=!0,e("agentrix-cli",n)):l.rollbackGracefulRestart()}});const{port:p,host:u,webhookHost:m,stop:h}=await startDaemonControlServer({getChildren:()=>i.getCurrentSessions(),stopSession:e=>i.stopSession(e),startDevOpsInit:e=>i.startDevOpsInit(e),completeDevOpsInit:e=>i.completeDevOpsInit(e),requestShutdown:()=>e("agentrix-cli"),registerSession:(e,t)=>i.registerTaskWorker(e,t),prepareGracefulRestart:e=>l.prepareGracefulRestart(e.source,e.reason),clearGracefulRestartGate:()=>l.clearGracefulRestartGate(),getSocketClient:()=>o?.client,credentials:a,get companionScheduler(){return r},get channelManager(){return c}});try{await listOpeners(),machine.logger.debug("[DAEMON RUN] Openers detected")}catch(e){machine.logger.warn("[DAEMON RUN] Failed to detect openers",e)}const g={pid:process.pid,port:p,host:u,webhookHost:m,startTime:(new Date).toLocaleString(),cliVersion:machine.packageJson.version,logPath:machine.getLogPath({type:"daemon"})};machine.machine.writeDaemonState(g),machine.logger.debug("[DAEMON RUN] Daemon state written");const f=new WorkspaceStatusSync(a),y=new MachineClient({machineId:a.machineId,serverUrl:machine.machine.serverUrl.replace(/^http/,"ws"),path:"/v1/ws",auth:shared.machineAuth(a.token,a.machineId),keepAliveConfig:{intervalMs:2e4,event:"machine-alive",payloadGenerator:()=>({eventId:shared.createEventId(),machineId:a.machineId,timestamp:Date.now().toString(),controlPort:p})},healthCheckConfig:{enabled:!0,intervalMs:3e4,timeoutMs:5e3},logger:machine.createModuleLogger("undefined"==typeof document?require("url").pathToFileURL(__filename).href:_documentCurrentScript&&"SCRIPT"===_documentCurrentScript.tagName.toUpperCase()&&_documentCurrentScript.src||new URL("index.cjs",document.baseURI).href,void 0,{filter:e=>!isGitlabProxySocketLog(e)})},i,{requestShutdown:e,machineControl:l,workspaceStatusSync:f}),v=new ChannelManager(y.client,a.machineId);c=v,i.setChannelManager(v),await y.connect(),o=y,machine.logger.info("[DAEMON RUN] Machine client connected to server"),await flushPendingDaemonRestartReport(y.client).catch(e=>{machine.logger.warn("[DAEMON RUN] Failed to flush pending restart report",e)}),await configureGitServerFromEnvironment(y.client,a),f.start();const b=new CompanionScheduler(y.client,a.machineId);r=b,b.start(),await v.start(),y.setCompanionInteractionCallback(e=>{b.recordInteraction(e)});const k=new CompanionBootstrapWatcher(y.client,a.machineId);k.start(),y.client.onEvent("companion-heartbeat-response",e=>{e?.taskId&&b.setHeartbeatTaskId(e.taskId)}),y.client.onEvent("companion-memory-organization-response",e=>{e?.taskId&&b.setMemoryOrganizationTaskId(e.taskId)});const w=async(e,t)=>{await v.stop(),f.stop(),b.stop(),k.stop(),await y.disconnect(),await h(),await s.shutdown(),await cleanupDaemonState(),await stopCaffeinate(),await machine.machine.releaseDaemonLock(n),d&&machine.logger.info("[DAEMON RUN] Restart command owns replacement daemon startup"),machine.logger.info("[DAEMON RUN] Cleanup completed, exiting process"),process.exit(0)};machine.logger.info("[DAEMON RUN] Daemon started successfully, waiting for shutdown request");const x=await t;await w(x.source,x.errorMessage)}catch(e){const t=getActionableSocketError(e);t?(console.error(t.message),t.action&&console.error(t.action)):isReauthRequiredError(e)&&(console.error("Machine binding is no longer valid."),console.error("Run `agentrix logout` and bind this machine again.")),machine.logger.info("[DAEMON RUN][FATAL] Failed somewhere unexpectedly - exiting with code 1",e),process.exit(1)}}const TOOL_RESULT_CONTENT_LIMIT_BYTES=1024,TOOL_RESULT_TRUNCATION_MARKER="\n\n[Tool result truncated to 1024 bytes]";function truncateToolResultContent(e,t=1024){if(Buffer.byteLength(e,"utf8")<=t)return e;const n=Buffer.byteLength(TOOL_RESULT_TRUNCATION_MARKER,"utf8");return n>t?sliceUtf8Bytes(TOOL_RESULT_TRUNCATION_MARKER,t):`${sliceUtf8Bytes(e,t-n)}${TOOL_RESULT_TRUNCATION_MARKER}`}function truncateToolResultPayload(e,t=1024){if("string"==typeof e)return truncateToolResultContent(e,t);const n=safeStringify(e);return Buffer.byteLength(n,"utf8")<=t?e:Array.isArray(e)?truncateToolResultContent(e.map(e=>isTextBlock(e)?e.text:safeStringify(e)).join("\n"),t):truncateToolResultContent(n,t)}function truncateToolResultMessage(e,t=1024){const n=e,a=n?.message?.content;if(!Array.isArray(a))return e;let s=!1;const i=a.map(e=>{if("tool_result"!==e?.type||!("content"in e))return e;const n=truncateToolResultPayload(e.content,t);return n===e.content?e:(s=!0,{...e,content:n})});return s?{...n,message:{...n.message,content:i}}:e}function isTextBlock(e){return"object"==typeof e&&null!==e&&"text"in e&&"string"==typeof e.text}function safeStringify(e){try{return JSON.stringify(e)??String(e)}catch{return String(e)}}function sliceUtf8Bytes(e,t){let n="",a=0;for(const s of e){const e=Buffer.byteLength(s,"utf8");if(a+e>t)break;n+=s,a+=e}return n}function formatTaskMessageLogMeta(e,t){return[`eventId=${e.eventId}`,void 0!==e.sequence?`sequence=${e.sequence}`:void 0,e.opCode?`opCode=${e.opCode}`:void 0,`senderType=${e.senderType}`,`messageType=${t?.type??e.messageType??"unknown"}`,`encrypted=${Boolean(e.encryptedMessage)}`].filter(Boolean).join(" ")}function extractUserContentForLog(e){return shared.isSDKUserMessage(e)?extractUserMessageText(e):shared.isAskUserResponseMessage(e)?{answers:e.answers,...e.details?{details:e.details}:{},...e.status?{status:e.status}:{},...e.reason?{reason:e.reason}:{}}:null}function formatUserContentLogLine(e,t,n={}){const a=extractUserContentForLog(t);if(null===a)return null;const s="string"==typeof a?a:JSON.stringify(a);return["message.user_content",n.source?`source=${n.source}`:void 0,formatTaskMessageLogMeta(e,t),`chars=${s.length}`,`content=${JSON.stringify(a)}`].filter(Boolean).join(" ")}const logger$5=machine.createModuleLogger("undefined"==typeof document?require("url").pathToFileURL(__filename).href:_documentCurrentScript&&"SCRIPT"===_documentCurrentScript.tagName.toUpperCase()&&_documentCurrentScript.src||new URL("index.cjs",document.baseURI).href),system_sender={senderType:"system",senderId:"system",senderName:"system"};function createWorkerEventHandlers(e,t,n){return{"cancel-task":async t=>{t.taskId===e.taskId&&(logger$5.info(`worker.cancelled taskId=${e.taskId}`),await e.stopTask())},"stop-task":async t=>{t.taskId===e.taskId&&(logger$5.info(`worker.stopped taskId=${e.taskId} reason=${t.reason||"no reason"}`),await e.stopTask())},"task-message":async a=>{if(a.taskId!==e.taskId)return;logger$5.debug(`message.received ${formatTaskMessageLogMeta(a)}`);let s=a.message??null;if(!s&&a.encryptedMessage&&e.dataEncryptionKey&&(s=shared.decryptSdkMessage(a.encryptedMessage,e.dataEncryptionKey)??null),!s&&a.encryptedMessage&&!e.dataEncryptionKey)return void logger$5.warn(`message.decrypt_failed ${formatTaskMessageLogMeta(a)} reason=missing_data_encryption_key`);if(!s&&a.encryptedMessage)return void logger$5.warn(`message.decrypt_failed ${formatTaskMessageLogMeta(a)} reason=invalid_encrypted_payload`);if(!s)return void logger$5.warn(`message.empty ${formatTaskMessageLogMeta(a)} reason=missing_message_payload`);a.channelReplyTarget&&"object"==typeof s&&(s.__channelReplyTarget=a.channelReplyTarget);const i={senderType:a.senderType,senderId:a.senderId,senderName:a.senderName};if(e.attachmentsDir&&shared.isSDKUserMessage(s)&&(s=await processAttachments(s,{attachmentsDir:e.attachmentsDir})),e.shouldPersistTaskMessage&&!await e.shouldPersistTaskMessage(s,i))return void logger$5.debug(`message.dropped ${formatTaskMessageLogMeta(a,s)} reason=should_not_persist`);if(!t.saveMessage({eventId:a.eventId,message:s,senderType:a.senderType,senderId:a.senderId,senderName:a.senderName}).inserted)return n(a.eventId),void logger$5.debug(`message.duplicate ${formatTaskMessageLogMeta(a,s)} acked=true`);const o=formatUserContentLogLine(a,s,{source:"runtime"});o&&logger$5.info(o);const r={...a,message:s,encryptedMessage:void 0,chatId:a.chatId??e.chatId};t.saveTaskEvent({eventType:"task-message",eventId:a.eventId,eventData:r,taskId:e.taskId,chatId:a.chatId??e.chatId,sequence:a.sequence??null}),n(a.eventId),e.onTaskMessage&&await e.onTaskMessage(s,i),logger$5.info(`message.accepted ${formatTaskMessageLogMeta(a,s)} persisted=true duplicate=false acked=true dispatched=${Boolean(e.onTaskMessage)}`)},"task-info-update":async t=>{t.taskId===e.taskId&&e.onTaskInfoUpdate&&await e.onTaskInfoUpdate(t)},"worker-status-request":async t=>{t.taskId===e.taskId&&e.onWorkerStatusRequest&&await e.onWorkerStatusRequest(t)},"sub-task-result-updated":async t=>{t.parentTaskId===e.taskId&&e.onSubTaskResultUpdated&&await e.onSubTaskResultUpdated(t)},"sub-task-ask-user":async t=>{t.parentTaskId===e.taskId&&e.onSubTaskAskUser&&await e.onSubTaskAskUser(t)}}}class WorkerClient{client;context;historyDb;getPermissionMode;outbox=new Map;ackWaiters=new Map;hasConnectedOnce=!1;constructor(e,t){const{taskId:n,userId:a,machineId:s,cwd:i,chatId:o,...r}=e,c=i.endsWith("/")?i:`${i}/`;this.client=new SocketClient(r),this.context={taskId:n,chatId:o,userId:a,machineId:s,cwd:c,stopTask:t.stopTask,shouldPersistTaskMessage:t.shouldPersistTaskMessage,onTaskMessage:t.onTaskMessage,onReconnect:t.onReconnect,onTaskInfoUpdate:t.onTaskInfoUpdate,onWorkerStatusRequest:t.onWorkerStatusRequest,onSubTaskResultUpdated:t.onSubTaskResultUpdated,onSubTaskAskUser:t.onSubTaskAskUser,onGitPush:t.onGitPush,dataEncryptionKey:e.dataEncryptionKey,attachmentsDir:t.attachmentsDir},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 a=shared.createEventId();return this.historyDb.saveMessage({eventId:a,message:t,senderType:e.senderType,senderId:e.senderId,senderName:e.senderName}),this.sendTaskEvent(e,t,n),a}sendWorkerInitializing(e){const t={eventId:shared.createEventId(),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:shared.createEventId(),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:shared.createEventId(),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),logger$5.info([`worker.ready taskId=${this.context.taskId}`,void 0!==e?`activeMs=${e}`:void 0,null!==t?`permissionMode=${t}`:void 0].filter(Boolean).join(" "))}sendWorkRunning(e){const t=this.getPermissionModeSnapshot(),n={eventId:shared.createEventId(),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:shared.createEventId(),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:shared.createEventId(),taskId:this.context.taskId,machineId:this.context.machineId,timestamp:(new Date).toISOString(),reason:e};this.client.send("worker-exit",t)}async sendErrorMessageAndExit(e){await this.sendTerminalErrorResultAndWait(e),this.sendWorkerExit("error"),await this.disconnect()}async sendTerminalErrorResultAndWait(e,t){const n=this.sendTerminalErrorResult(e,t);await this.waitForEventAcks(n,2e3)}sendTerminalErrorResult(e,t){return[this.sendSystemErrorMessage(e,t),this.sendTaskEvent(system_sender,createSdkErrorResultMessage(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"}}]}};return this.sendTaskEvent(system_sender,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(system_sender,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(system_sender,t,{opCode:e})}sendTaskEvent(e,t,n){const a=truncateToolResultMessage(t),{eventId:s,opCode:i,artifacts:o,navigateToTaskId:r}=n||{},c=s??shared.createEventId(),l={eventId:c,taskId:this.context.taskId,chatId:this.context.chatId,from:"worker",messageType:a.type,message:a,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 d=this.buildTaskUsageReport(a,c);if(this.context.dataEncryptionKey){const e=shared.encryptSdkMessage(a,this.context.dataEncryptionKey);l.message=void 0,l.encryptedMessage=e}return this.outbox.set(c,{payload:l,usageReport:d??void 0,sentAt:Date.now(),messageType:l.messageType,isResult:"result"===a.type}),d&&this.client.send("task-usage-report",d),this.client.send("task-message",l),"result"===a.type&&logger$5.info([`outbound.result.sent eventId=${c}`,d?.eventId?`usageEventId=${d.eventId}`:"usageEventId=none",`encrypted=${Boolean(l.encryptedMessage)}`,`artifacts=${Boolean(o)}`,`outboxSize=${this.outbox.size}`].join(" ")),c}waitForEventAcks(e,t){const n=new Set(e.filter(e=>this.outbox.has(e)));return 0===n.size?Promise.resolve():new Promise(e=>{const a=t=>{this.ackWaiters.delete(t),n.delete(t),0===n.size&&(clearTimeout(s),e())},s=setTimeout(()=>{for(const e of n){const n=this.outbox.get(e),a=n?Date.now()-n.sentAt:t;logger$5.warn(`${n?.isResult?"outbound.result.ack_timeout":"outbound.event.ack_timeout"} eventId=${e} pendingMs=${a} outboxSize=${this.outbox.size}`),this.ackWaiters.delete(e)}e()},t);for(const e of n)this.ackWaiters.set(e,()=>a(e))})}buildTaskUsageReport(e,t){if("result"!==e.type)return null;const n=e.modelUsage;if(!n||"object"!=typeof n)return null;const a={};for(const[e,t]of Object.entries(n)){if(!e||!t||"object"!=typeof t)continue;const n=t,s={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(s).some(e=>e>0)&&(a[e]=s)}return 0===Object.keys(a).length?null:{eventId:shared.createEventId(),taskId:this.context.taskId,resultEventId:t,modelUsage:a}}normalizeUsageCount(e){return"number"!=typeof e||!Number.isFinite(e)||e<=0?0:Math.trunc(e)}sendUpdateTaskAgentSessionId(e){const t={eventId:shared.createEventId(),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:shared.createEventId(),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:shared.createEventId(),taskId:this.context.taskId,title:e};this.client.send("change-task-title",t),logger$5.info(`task.title_changed title=${e}`)}sendUpdateAgentInfo(e,t){const n={eventId:shared.createEventId(),taskId:this.context.taskId,agentId:e,...t};this.client.send("update-agent-info",n),logger$5.info(`agent.info_updated updates=${JSON.stringify(t)}`)}async sendVisionPlanCard(e){const t={eventId:shared.createEventId(),taskId:this.context.taskId,issueId:e.issueId,repoRoot:e.repoRoot,createdAt:(new Date).toISOString()},n=await this.client.sendWithAck("vision-plan-card",t);if("success"!==n.status)throw new Error(n.message||"Failed to send Vision Plan card");return logger$5.info(`vision_plan_card.sent issueId=${e.issueId}`),n}sendResetTaskSession(){const e={eventId:shared.createEventId(),taskId:this.context.taskId};this.client.send("reset-task-session",e),logger$5.info(`session.reset_requested taskId=${this.context.taskId}`)}async sendMergeRequest(e,t,n){const a={eventId:shared.createEventId(),taskId:this.context.taskId,summary:e,description:t,sourceBranch:n};logger$5.info(`merge_request.sent taskId=${this.context.taskId}`);const s=await this.client.sendWithAck("merge-request",a);if(!s.success)throw new Error(`Failed to create pull request: ${s.error||"Unknown error"}`);return logger$5.info(`merge_request.created pullRequestNumber=${s.data.pullRequestNumber}`),{pullRequestNumber:s.data.pullRequestNumber,pullRequestUrl:s.data.pullRequestUrl}}async sendMergePr(){const e={eventId:shared.createEventId(),taskId:this.context.taskId,mergeMethod:"squash"};return logger$5.info(`merge_pr.sent taskId=${this.context.taskId}`),await this.client.sendWithAck("merge-pr",e)}associateRepository(e,t,n,a){const s={eventId:shared.createEventId(),taskId:this.context.taskId,gitServerHost:e,owner:t,repo:n,remoteUrl:a};logger$5.info(`repo.association.sent repository=${e}/${t}/${n}`),this.client.send("associate-repo",s)}async dispatchTaskMessage(e){await this.context.onTaskMessage(e)}sendEventAck(e){this.client.send("event-ack",{eventId:shared.createEventId(),status:"success",opCode:e})}initHandlers(){const e=createWorkerEventHandlers(this.context,this.historyDb,e=>{this.sendEventAck(e)});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;if(void 0!==e.opCode){const n=this.outbox.get(e.opCode),a=n?Date.now()-n.sentAt:void 0;this.outbox.delete(e.opCode),this.ackWaiters.get(e.opCode)?.(),n?.isResult?logger$5.info([`outbound.result.acked eventId=${e.opCode}`,"number"==typeof t?`sequence=${t}`:"sequence=unknown",void 0!==a?`ackMs=${a}`:void 0].filter(Boolean).join(" ")):logger$5.debug([`outbound.event.acked eventId=${e.opCode}`,n?.messageType?`messageType=${n.messageType}`:void 0,"number"==typeof t?`sequence=${t}`:void 0,void 0!==a?`ackMs=${a}`:void 0].filter(Boolean).join(" "))}void 0!==e.opCode&&"number"==typeof t&&this.historyDb.updateTaskEventSequence(e.opCode,t)}),this.client.onLifecycle("connect",()=>{if(this.hasConnectedOnce){if(Promise.resolve(this.context.onReconnect?.()).catch(e=>{logger$5.warn(`reconnect.handler_failed error=${e instanceof Error?e.message:String(e)}`)}),this.outbox.size>0){logger$5.info(`reconnect.outbox_flush count=${this.outbox.size}`);for(const[e,t]of this.outbox.entries())t.usageReport&&this.client.send("task-usage-report",t.usageReport),this.outbox.set(e,{...t,sentAt:Date.now()}),this.client.send("task-message",t.payload)}}else this.hasConnectedOnce=!0})}}const execFileAsync$2=node_util.promisify(node_child_process.execFile),HIVE_REPOSITORY_OWNER="xmz-ai",HIVE_REPOSITORY_NAME="agentrix-hive",HIVE_REPOSITORY_URL="https://github.com/xmz-ai/agentrix-hive.git",HIVE_GIT_SERVER_ID="github";async function prepareHiveRepository(){const e=machine.machine.resolveRepoStoreCheckoutDir("github","xmz-ai","agentrix-hive"),t=machine.machine.resolveRepoStoreLockPath("github","xmz-ai","agentrix-hive"),n=await machine.machine.acquireFileLock(t);if(!n)throw new Error(`Timed out waiting for Hive repository lock at ${t}`);try{if(!await isGitRepository(e)){if(!isDirectoryEmpty(e))return{path:e,pullSucceeded:!1,error:`Hive repository checkout exists but is not a git repository: ${e}`};try{await gitClone(HIVE_REPOSITORY_URL,e)}catch(t){return{path:e,pullSucceeded:!1,error:t instanceof Error?t.message:String(t)}}return{path:e,pullSucceeded:!0}}await ensureRemote(e,"origin",sanitizeGitRemoteUrl(HIVE_REPOSITORY_URL));try{return await execFileAsync$2("git",["pull","--ff-only"],{cwd:e}),{path:e,pullSucceeded:!0}}catch(t){return{path:e,pullSucceeded:!1,error:t instanceof Error?t.message:String(t)}}}finally{await machine.machine.releaseFileLock(t,n)}}class AgentContextImpl{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 a=shared.createEventId();try{const s=await this.socketClient.sendWithAck("rpc-call",{eventId:a,taskId:this.taskId,method:e,path:t,query:n?.query,body:n?.body});if(!s.success){const n=s.error||{code:"unknown",message:"Unknown error"};throw new Error(`RPC ${e} ${t} failed: ${n.message} (${n.code})`)}return s.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,initPolicies:e.initPolicies};return this.taskDataKey?t.encryptedMessage=shared.encryptSdkMessage(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=shared.encryptSdkMessage(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,initPolicies:e.initPolicies};return this.taskDataKey?t.encryptedMessage=shared.encryptSdkMessage(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 prepareHiveRepository(){const e=await prepareHiveRepository();return e.pullSucceeded||this.logger.warn(`[Agent-Context] Hive repository update failed; continuing when local copy is usable: ${e.error}`),e}async recordHiveInstall(e,t){return this.call("POST",`/v1/hive/listings/${e}/record-install`,{body:t})}async installHiveListing(e,t){return this.call("POST",`/v1/hive/listings/${e}/install`,{body:t})}async publishToHive(e){return this.call("POST","/v1/hive/publish",{body:e})}async updateHiveListingVersion(e,t){return this.call("POST",`/v1/hive/listings/${e}/update-version`,{body:t})}async createHiveReview(e,t){return this.call("POST",`/v1/hive/listings/${e}/reviews`,{body:t})}async createHiveComment(e,t){return this.call("POST",`/v1/hive/listings/${e}/comments`,{body:t})}async listAgents(){return this.call("GET","/v1/user-agents")}async uploadFile(e){this.logger.info("[Agent-Context] Uploading file...");const t=await fs__namespace$1.promises.stat(e.path);this.logger.info("[Agent-Context] file stats");const n=t.size,a=e.contentType||mimeTypesExports.lookup(e.name)||"application/octet-stream",s=(await this.call("POST","/v1/files/upload-urls",{body:{count:1}})).files[0],i=s.url;this.logger.info(`[Agent-Context] FileUploadUrl: ${i}`);const o=await fs__namespace$1.promises.readFile(e.path),r=await fetch(i,{method:"PUT",headers:{"Content-Type":a},body:o});if(!r.ok)throw new Error(`Failed to upload file to S3: ${r.status} ${r.statusText}`);let c;return await this.call("POST","/v1/files/confirm-upload",{body:{fileId:s.id,name:e.name,size:n,contentType:a,visibility:e.visibility||"private"}}),c="public"===e.visibility?`${this.serverUrl}/v1/files/public/${s.id}`:i.split("?")[0],{fileId:s.id,name:e.name,size:n,contentType:a,url:c}}}function buildSubTaskResultMessage(e,t){let n=e.resultMessage;if(0===n.result.trim().length&&e.encryptedResultMessage&&t){const a=shared.decryptSdkMessage(e.encryptedResultMessage,t);a&&"result"===a.type&&(n={type:"result",result:"result"in a?a.result:"",is_error:a.is_error})}const a={...e,resultMessage:n};let s=`<sub-task-result-updated>\n${JSON.stringify(a,null,2)}\n</sub-task-result-updated>`;return s+=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:s}}}function buildSubTaskAskUserMessage(e,t){let n=e.message;if(!n&&e.encryptedMessage&&t){const a=shared.decryptSdkMessage(e.encryptedMessage,t);a&&"ask_user"===a.type&&(n=a)}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 createMessageFilter(){const e=new Set;return{filter(t){const n=t;if(!n.message||!n.message.content||"string"==typeof n.message.content)return t;const a=n.message.content.filter(t=>!("tool_result"===t.type&&e.has(t.tool_use_id)||"user"===n.type&&"tool_result"!==t.type));return 0===a.length?null:(n.message.content=a,n)},clear(){e.clear()}}}const logger$4=machine.createModuleLogger("undefined"==typeof document?require("url").pathToFileURL(__filename).href:_documentCurrentScript&&"SCRIPT"===_documentCurrentScript.tagName.toUpperCase()&&_documentCurrentScript.src||new URL("index.cjs",document.baseURI).href);function createAgentrixMcpTools(e){return{createTask:createTaskTool(e),createSoloTask:createSoloTaskTool(e),createGroupTask:createGroupTaskTool(e),replyToSubTask:createReplyToSubTaskTool(e),changeTaskTitle:createChangeTaskTitleTool(e),publishTaskPreviewUrl:createPublishTaskPreviewUrlTool(e),sendVisionArtifact:createSendVisionArtifactTool(e),askUser:createAskUserTool(e),getTaskHistory:createGetTaskHistoryTool(e),getTaskAgents:createGetTaskAgentsTool(e),listSubTask:createListSubTaskTool(e),invoke:createInvokeTool(e),assign:createAssignTool(e),updateAgentInfo:createUpdateAgentInfoTool(e),sendReminder:createSendReminderTool(e),recordMemoryChange:createRecordMemoryChangeTool(e),listTasks:createListTasksTool(e),readConversation:createReadConversationTool(e),uploadFile:createUploadFileTool(e),sendChannelMessage:createSendChannelMessageTool(e),getChannelGroupHistory:createGetChannelGroupHistoryTool(e),listAgents:createListAgentsTool(e),analyzeImage:createAnalyzeImageTool(e),scheduleTask:createScheduleTaskTool(),prepareHiveRepository:createPrepareHiveRepositoryTool(e),publishToHive:createPublishToHiveTool(e),updateHiveListingVersion:createUpdateHiveListingVersionTool(e),recordHiveInstall:createRecordHiveInstallTool(e),createHiveReview:createHiveReviewTool(e),createHiveComment:createHiveCommentTool(e),computerUse:createComputerUseTool(e)}}function createComputerUseTool(e){return claudeAgentSdk.tool("agentrix_computer_use","Execute a concrete operation on the user's local computer through Agentrix Computer Use.\n\nUse this tool when the user asks you to operate local desktop apps, windows, documents, menus, dialogs, browsers, Finder, or other GUI surfaces on this machine. Provide the requested operation as a natural-language instruction. Do not decompose the task into low-level click coordinates; Agentrix Computer Use will operate the GUI through its configured desktop-control tools.\n\nThis tool can control the local computer. Call it only for explicit user-requested computer operation.",{instruction:zod.z.string().describe("Concrete natural-language desktop operation to perform, including the app/document/target and desired outcome."),expectedResult:zod.z.string().optional().describe("Optional concise success condition the computer-use sub-task should verify before returning."),title:zod.z.string().optional().describe('Optional title for the computer-use sub-task. Defaults to "Computer use".')},async t=>{try{const n=await executeComputerUseBridge({instruction:t.instruction,expectedResult:t.expectedResult,title:t.title},{taskId:e.taskId,cwd:e.workingDirectory,historyDb:e.historyDb,startSubTask:t=>e.agentContext.startSubTask(t),sendMessage:t=>e.agentContext.sendMessage(t)});return{content:[{type:"text",text:"created"===n.action?[`computer-use sub-task created: ${n.taskId}`,`Title: ${n.title}`,"","The computer operation is now running asynchronously in that sub-task. Use this same agentrix_computer_use tool again for follow-up instructions or corrections; it will route them to the same computer-use sub-task."].join("\n"):[`computer-use instruction sent to existing sub-task: ${n.taskId}`,"","The computer-use sub-task will continue from its existing context."].join("\n")}]}}catch(e){return{content:[{type:"text",text:e instanceof Error?e.message:String(e)}],isError:!0}}})}function createChangeTaskTitleTool({workClient:e}){return claudeAgentSdk.tool("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:zod.z.string().describe("New title for the task")},async t=>(e.sendChangeTaskTitle(t.title),{content:[{type:"text",text:`Task title updated to: ${t.title}`}]}))}async function publishTaskPreviewUrl(e,t){const n=shared.UpdateTaskPreviewUrlRequestSchema.parse({previewUrl:t}),a=await fetch(`${machine.machine.serverUrl}/v1/tasks/${encodeURIComponent(e.taskId)}/preview-url`,{method:"PUT",headers:{Authorization:`Bearer ${e.credentials.token}`,"Content-Type":"application/json","X-Agentrix-Task":e.taskId},body:JSON.stringify(n)});if(!a.ok){const e=await a.text().catch(()=>"");throw new Error(`Failed to publish task preview URL (${a.status}): ${e||a.statusText}`)}}function createPublishTaskPreviewUrlTool(e){return claudeAgentSdk.tool("publish_task_preview_url","Publish the frontend preview URL for the current Agentrix task.\n\nUse this on a local machine when the user provided a service startup port or relevant startup documentation for a frontend app, and you have started or reused the local environment after completing the task.\nThe URL is recorded on the current task only. It must be an absolute http or https URL; localhost URLs are allowed.",{previewUrl:zod.z.string().describe("Absolute http(s) URL for the current task preview, such as http://localhost:5173")},async t=>(await publishTaskPreviewUrl(e,t.previewUrl),{content:[{type:"text",text:`Task preview URL published: ${t.previewUrl.trim()}`}]}))}function createSendVisionArtifactTool(e){return claudeAgentSdk.tool("send_vision_artifact","Send the issue vision artifacts (visual plan and test report) to the Agentrix platform so the user can review them.\n\nUse this after generating or materially updating the visual plan, and again after generating the visual test report. Pass only the repository root and issue id; Agentrix derives the current task routing from platform context.",{repoRoot:SendVisionArtifactRequestSchema.shape.repoRoot,issueId:SendVisionArtifactRequestSchema.shape.issueId},async t=>{const n=await normalizeSendVisionArtifactRequest(t);if(!e.workClient.sendVisionPlanCard)throw new Error("Vision artifact publishing is not available in this worker");return await e.workClient.sendVisionPlanCard({issueId:n.issueId,repoRoot:t.repoRoot}),{content:[{type:"text",text:`Agentrix vision artifacts sent for issue ${n.issueId}.`}]}})}function createReplyToSubTaskTool({agentContext:e}){return claudeAgentSdk.tool("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:zod.z.string().describe("Sub-task ID to send the message to"),instructions:zod.z.string().optional().describe("Follow-up instructions for the sub-task (used when not answering ask_user)"),answers:zod.z.array(zod.z.string()).optional().describe("Answers to the sub-task ask_user questions, one per question. When provided, sends as ask_user_response.")},async t=>{try{let n;return n=t.answers&&t.answers.length>0?{type:"ask_user_response",answers:t.answers}:{type:"user",message:{role:"user",content:t.instructions??""}},await e.sendMessage({taskId:t.taskId,message:n,target:"agent"}),{content:[{type:"text",text:`${t.answers?"Sent ask_user response":"Sent follow-up instructions"} to sub-task ${t.taskId}.`}]}}catch(e){return logger$4.error(`Failed to send message to sub-task ${t.taskId}:`,e),{content:[{type:"text",text:`Failed to send message to sub-task: ${e instanceof Error?e.message:"Unknown error"}`}],isError:!0}}})}function createGetTaskHistoryTool({historyDb:e}){return claudeAgentSdk.tool("get_task_history","Retrieve task history stored locally. Omit sequence to read the latest messages; only pass sequence when paginating to older messages.",{sequence:zod.z.number().int().min(0).optional().describe("Pagination cursor for older history. Omit this field, or pass 0, to read the latest messages. Only pass a positive sequence value that was returned by the previous result as “Use sequence=N to load earlier messages”; it means return messages before that local sequence, not start at that position."),limit:zod.z.number().int().min(1).max(50).default(20).describe("Maximum number of messages to return.")},async t=>{const n=t.limit??20,a=null!=t.sequence&&t.sequence>0,s=a?e.pageMessagesBefore(t.sequence,n):e.pageRecentMessages(n);if(0===s.data.length)return{content:[{type:"text",text:a?"No earlier messages found.":"No task history messages found."}]};let i=formatHistoryXml(s.data);return s.hasMore&&(i+=`\n\nMore messages available. Use sequence=${Math.min(...s.data.map(e=>e.localSequence))} to load earlier messages.`),{content:[{type:"text",text:i}]}})}function createGetTaskAgentsTool({agentContext:e}){return claudeAgentSdk.tool("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 createListSubTaskTool({agentContext:e}){return claudeAgentSdk.tool("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 logger$4.error("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 createTaskTool({agentContext:e,agentId:t,setPendingNavigateTaskId:n}){return claudeAgentSdk.tool("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:zod.z.string().optional().describe('Target agent ID (e.g., "agent-poster-generator"). If not provided, uses current agent.'),title:zod.z.string().min(1).max(200).describe("Task title for the agent to use (required)"),instructions:zod.z.string().describe("Detailed instructions for the agent. Be specific about what needs to be done."),briefSummary:zod.z.string().describe('One-line summary shown to user immediately (e.g., "Creating login page")'),cwd:zod.z.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:zod.z.boolean().optional().describe("Whether to create a git worktree for isolation. Defaults to false (work in-place)."),independent:zod.z.boolean().optional().describe("Create as independent top-level task (no parent). Defaults to false (sub-task mode)."),autoNavigate:zod.z.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 s=a.agentId||t;let i;return a.independent?(i=await e.startIndependentTask({agentId:s,message:{type:"user",message:{role:"user",content:a.instructions}},title:a.title,cwd:a.cwd,forceUserCwd:!a.useWorktree,autoNavigate:a.autoNavigate}),a.autoNavigate&&n(i.taskId),logger$4.info(`Created independent task ${i.taskId} for agent ${s} (autoNavigate: ${a.autoNavigate??!1})`)):(i=await e.startSubTask({agentId:s,message:{type:"user",message:{role:"user",content:a.instructions}},title:a.title,cwd:a.cwd,forceUserCwd:!a.useWorktree,initPolicies:{uncommittedChanges:"Ignore",branchMismatch:"Keep"}}),logger$4.info(`Created sub-task ${i.taskId} for agent ${s}`)),{content:[{type:"text",text:`🚀 Task created: ${i.taskId}\n${a.agentId?`Agent: ${s}\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 logger$4.error("Failed to create task:",e),{content:[{type:"text",text:`Failed to create task: ${e instanceof Error?e.message:"Unknown error"}`}],isError:!0}}})}function createSoloTaskTool({agentContext:e}){return claudeAgentSdk.tool("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:zod.z.string().min(1).max(200).describe("Task title"),instructions:zod.z.string().describe("Instructions for the owner agent"),briefSummary:zod.z.string().optional().describe("One-line summary shown to user immediately"),agentId:zod.z.string().describe("Target agent ID"),cwd:zod.z.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:zod.z.boolean().optional().describe("Whether to create a git worktree for isolation. Defaults to false (work in-place).")},async t=>{try{return{content:[{type:"text",text:`🚀 Task created: ${(await e.startSubTask({agentId:t.agentId,message:{type:"user",message:{role:"user",content:t.instructions}},title:t.title,cwd:t.cwd,forceUserCwd:!t.useWorktree,initPolicies:{uncommittedChanges:"Ignore",branchMismatch:"Keep"}})).taskId}\n${t.briefSummary?`Summary: ${t.briefSummary}\n`:""}\nYou'll receive a <sub-task-result-updated> notification when the task completes. Continue responding to the user.`}]}}catch(e){return logger$4.error("Create solo task failed:",e),{content:[{type:"text",text:`Create solo task failed: ${e instanceof Error?e.message:"Unknown error"}`}],isError:!0}}})}function createGroupTaskTool({agentContext:e}){return claudeAgentSdk.tool("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:zod.z.string().min(1).max(200).describe("Task title"),requirement:zod.z.string().describe("Overall requirement"),briefSummary:zod.z.string().optional().describe("One-line summary shown to user immediately"),todos:zod.z.array(zod.z.object({agentId:zod.z.string().describe("Agent ID responsible for the todo"),title:zod.z.string().min(1).max(200).describe("Todo title"),instructions:zod.z.string().describe("Detailed instructions for this todo")})).min(1).describe("Todo list for agents")},async t=>{try{return{content:[{type:"text",text:`🚀 Task created: ${(await e.startGroupTask({title:t.title,todos:t.todos,initPolicies:{uncommittedChanges:"Ignore",branchMismatch:"Keep"},message:{type:"user",message:{role:"user",content:t.requirement}}})).taskId}\n${t.briefSummary?`Summary: ${t.briefSummary}\n`:""}\nYou'll receive a <sub-task-result-updated> notification when the task completes. Continue responding to the user.`}]}}catch(e){return logger$4.error("Dispatch failed:",e),{content:[{type:"text",text:`Dispatch failed: ${e instanceof Error?e.message:"Unknown error"}`}],isError:!0}}})}function createAskUserTool({askUser:e}){return claudeAgentSdk.tool("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:zod.z.array(zod.z.object({question:zod.z.string().describe("The complete question to ask the user"),header:zod.z.string().max(12).describe("Short label displayed as a chip/tag (max 12 chars)"),multiSelect:zod.z.boolean().describe("Set to true to allow multiple option selections"),options:zod.z.array(zod.z.object({label:zod.z.string().describe("Option label (1-5 words)"),description:zod.z.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 t=>{try{const n=t.questions.map(e=>({...e,options:[...e.options,{label:"Other",description:""}]})),a=await e(n);return"answered"!==(a.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${a.answers.map(e=>e.startsWith("other:")?`Other: "${e.slice(6)}"`:e).join("\n")}`}]}}catch(e){return logger$4.error("Failed to get user response:",e),{content:[{type:"text",text:`Failed to get user response: ${e instanceof Error?e.message:"Unknown error"}`}]}}})}function createInvokeTool({invokeAgent:e}){return claudeAgentSdk.tool("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:zod.z.string().describe("Target agent ID"),hint:zod.z.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 createUpdateAgentInfoTool({workClient:e,agentId:t,uploadFile:n}){return claudeAgentSdk.tool("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:zod.z.string().optional().describe("Your display name"),avatarPath:zod.z.string().optional().describe("Local path to avatar image file (png/jpg/svg)"),signature:zod.z.string().optional().describe("Short status line or tagline shown under your name")},async a=>{let s;if(a.avatarPath)try{s=(await n({name:"avatar.png",path:a.avatarPath,visibility:"public"})).fileId}catch(e){return logger$4.error("Avatar upload failed:",e),{content:[{type:"text",text:`Avatar upload failed: ${e}`}],isError:!0}}e.sendUpdateAgentInfo(t,{displayName:a.displayName,avatar:s,signature:a.signature});const i=[];return a.displayName&&i.push(`name → ${a.displayName}`),s&&i.push("avatar → uploaded"),a.signature&&i.push(`signature → ${a.signature}`),{content:[{type:"text",text:`Profile updated: ${i.join(", ")}`}]}})}function createAssignTool({assign:e}){return claudeAgentSdk.tool("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:zod.z.string().describe("Target agent ID"),instruction:zod.z.string().describe("Task instruction for the agent"),acknowledgment:zod.z.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 createListTasksTool({agentContext:e}){return claudeAgentSdk.tool("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:zod.z.number().int().min(1).max(50).default(10).optional().describe("Maximum number of tasks to return (default 10)."),status:zod.z.enum(["all","active","completed"]).default("all").optional().describe("Filter by task status: all, active, or completed.")},async t=>{try{const n=await e.listTasks({limit:t.limit??10,status:t.status??"all"});return n.length?{content:[{type:"text",text:JSON.stringify(n,null,2)}]}:{content:[{type:"text",text:"No tasks found."}]}}catch(e){return logger$4.error("Failed to list tasks:",e),{content:[{type:"text",text:`Failed to list tasks: ${e instanceof Error?e.message:"Unknown error"}`}],isError:!0}}})}function createReadConversationTool({chatHistoryDb:e}){return claudeAgentSdk.tool("read_conversation","Read messages from the main conversation between you and the user. Omit before to read the latest messages; only pass before when paginating to older messages.",{limit:zod.z.number().int().min(1).max(200).default(50).optional().describe("Number of recent messages to return (default 50)."),before:zod.z.number().int().min(0).optional().describe("Pagination cursor for older conversation history. Omit this field, or pass 0, to read the latest messages. Only pass a positive before value that was returned by the previous result as “Use before=N to load earlier messages”; it means return messages before that sequence, not start at that position.")},async t=>{if(!e)return{content:[{type:"text",text:"Chat history not available in this mode."}],isError:!0};const n=t.limit??50,a=null!=t.before&&t.before>0?e.pageMessagesBefore(t.before,n):e.pageRecentMessages(n);if(0===a.data.length)return{content:[{type:"text",text:"No conversation messages found."}]};let s=formatHistoryXml(a.data);return a.hasMore&&(s+=`\n\nMore messages available. Use before=${Math.min(...a.data.map(e=>e.localSequence))} to load earlier messages.`),{content:[{type:"text",text:s}]}})}function createSendReminderTool({agentContext:e}){return claudeAgentSdk.tool("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:zod.z.string().describe('Brief reminder message (one sentence, e.g., "Heartbeat architecture discussion pending for 2 days, consider following up")'),filePath:zod.z.string().optional().describe("Path to detailed analysis file in workspace, if any")},async t=>{try{const n=e.getChatId();return await e.sendMessage({taskId:n,message:{type:"companion_reminder",content:t.content,filePath:t.filePath,timestamp:(new Date).toISOString()},target:"agent"}),{content:[{type:"text",text:"Reminder sent to main companion."}]}}catch(e){return logger$4.error("Failed to send reminder:",e),{content:[{type:"text",text:`Failed to send reminder: ${e instanceof Error?e.message:"Unknown error"}`}],isError:!0}}})}const MemoryChangeActionSchema=zod.z.enum(["created","updated","deleted"]);function createRecordMemoryChangeTool({taskId:e}){return claudeAgentSdk.tool("record_memory_change","Append a structured JSONL record for an actual Companion memory change.\nUse this from Companion chat, heartbeat shadow, or memory-organization shadow after memory files were really created, updated, deleted, merged, compressed, or cleaned.\nDo not call this tool when the memory review found nothing to change.\nAfter recording an actual change, use send_reminder separately if the main Companion should be awakened.",{title:zod.z.string().optional().describe("Deprecated compatibility field; each change.summary is used for the JSONL record and semantic git commit title."),trigger:zod.z.enum(["scheduled","user_request"]).describe("What triggered this memory change."),source:zod.z.string().optional().describe("Where the changed memory fact came from, such as user correction, recent conversation, task history, reminder, existing memory consolidation, or verified project evidence. This is the memory evidence source, not the Companion execution path."),notifiedCompanion:zod.z.boolean().describe("Whether a reminder has already been sent or will be sent immediately after this record."),changes:zod.z.array(zod.z.object({file:zod.z.string().describe("Current primary self-evolution file path, relative to Companion claude home, such as memory/agentrix-companion-memory/memory.md or MEMORY.md. Legacy memory/-relative paths are accepted and normalized."),action:MemoryChangeActionSchema,summary:zod.z.string().describe("One-sentence summary of what changed."),reasons:zod.z.array(zod.z.string()).min(1).describe("Short reasons for this change."),deletedFiles:zod.z.array(zod.z.string()).optional().describe("Optional old allowlisted files removed while consolidating into file.")})).min(1).describe("One or more concrete file-bound memory changes for this topic.")},async t=>{try{const n=process.env.AGENTRIX_COMPANION_HOME;if(!n)throw new Error("AGENTRIX_COMPANION_HOME is not set; memory changes can only be recorded by Companion workers.");const a=new Date,s=a.toISOString().slice(0,10),i=path.join(n,"memory-changes"),o=path.join(i,`${s}.jsonl`),r=t.changes.map(e=>({file:resolveCompanionSelfEvolutionPath(n,e.file).relativePath,action:e.action,summary:e.summary,reasons:e.reasons,deletedFiles:e.deletedFiles?.map(e=>resolveCompanionSelfEvolutionPath(n,e).relativePath)??[]}));await ensureCompanionSelfEvolutionGitRepo({companionHome:n});const c=new Map;for(const e of r){const t=c.get(e.file);t?t.push(e):c.set(e.file,[e])}const l=[];for(const s of c.values()){const i=s[0],o=Array.from(new Set(s.flatMap(e=>e.deletedFiles))),r=await commitCompanionMemoryChange({companionHome:n,title:i.summary,body:buildMemoryChangeCommitBody({trigger:t.trigger,source:t.source,action:i.action,file:i.file,reasons:s.flatMap(e=>e.reasons),deletedFiles:o,notifiedCompanion:t.notifiedCompanion,taskId:e}),paths:[i.file,...o]});if(r)for(const n of s)l.push(JSON.stringify({time:a.toISOString(),trigger:t.trigger,source:t.source,taskId:e,file:n.file,action:n.action,summary:n.summary,reasons:n.reasons,deletedFiles:n.deletedFiles,notifiedCompanion:t.notifiedCompanion,commit:r}));else logger$4.warn(`Skipping memory change JSONL record because no semantic git commit was created: file=${i.file}`)}return l.length>0&&(await promises$2.mkdir(i,{recursive:!0}),await promises$2.appendFile(o,`${l.join("\n")}\n`,"utf-8")),logger$4.info(`Memory changes recorded: path=${o}, source=${t.source??"unspecified"}, trigger=${t.trigger}, records=${l.length}, requestedChanges=${r.length}, taskId=${e}`),{content:[{type:"text",text:l.length>0?`Memory changes recorded: ${l.length} JSONL record(s) at ${o}`:"No memory change JSONL records were written because no semantic git commit was created."}]}}catch(e){return logger$4.error("Failed to record memory change:",e),{content:[{type:"text",text:`Failed to record memory change: ${e instanceof Error?e.message:"Unknown error"}`}],isError:!0}}})}function createUploadFileTool({uploadFile:e}){return claudeAgentSdk.tool("upload_file","Upload a local file to the platform and get a public URL.\nUse this to share images, documents, or other files with the user.\nReturns a public URL that can be embedded in markdown (e.g., ![screenshot](url)).",{filePath:zod.z.string().describe("Absolute path to the local file to upload"),name:zod.z.string().optional().describe("Display name for the file (defaults to filename)")},async t=>{try{const n=require("path"),a=t.name||n.basename(t.filePath);return{content:[{type:"text",text:(await e({name:a,path:t.filePath,visibility:"public"})).url}]}}catch(e){return logger$4.error("File upload failed:",e),{content:[{type:"text",text:`File upload failed: ${e}`}],isError:!0}}})}const MAX_CHANNEL_ATTACHMENT_BYTES=2147483648,SENSITIVE_ATTACHMENT_NAME_RE=/(^\.env($|\.)|\.pem$|\.key$|\.p12$|\.pfx$|^id_rsa$|^id_dsa$|^id_ecdsa$|^id_ed25519$|credential|credentials|secret|secrets|token)/i;function createSendChannelMessageTool({taskId:e,chatId:t,historyDb:n,getChannelReplyTarget:a,onChannelMessageInvoked:s}){return claudeAgentSdk.tool("send_channel_message","Send a user-facing message back to the external channel that started this task.\n\nFor channel-bound tasks, normal successful final results are NOT automatically forwarded to the external channel after this tool has been used. You MUST call this tool for anything the external user should see. Before ending the task, ensure the external user has received an appropriate message through this tool. If you end without calling it, the user may see no model-directed response; that is considered a failed channel interaction even if the internal task result is complete.\n\nUse this for user-facing conversational output: acknowledgements, progress updates for long work, questions/choices/permission requests, clear failures or limitations, final answers, and user-facing deliverable notes.\n\nMessages should feel like natural conversation: short, clear, useful. Do not send internal reasoning, verbose logs, stack traces, debug dumps, internal-only summaries, temporary paths, environment variables, tokens, secrets, or private data. Avoid excessive implementation detail unless the user is explicitly collaborating technically and needs it.\n\nAttachments are part of this channel message. Attach only deliverables the user is meant to consume, save, view, or forward: generated images, PDFs, spreadsheets, reports, slide decks, archives, audio/video, or requested exports/packages.\n\nDo NOT send files merely because they were created, edited, read, downloaded, or used. A file created or modified while completing work is not automatically a deliverable; decide based on user intent. Do not decide based on file location or directory: a file inside the workspace can be a deliverable, and a file outside the workspace can still be unsafe or inappropriate. Logs, caches, temporary files, build artifacts, intermediate screenshots, debug outputs, and internal workflow files should not be sent unless the user explicitly asked for them. When modifying files, summarize changes in text unless the user asked to receive, export, package, or forward those files. Never send files containing secrets, credentials, tokens, private data, or local environment details. If the deliverable status is uncertain or sending might expose unintended content, ask for confirmation with this tool first.\n\nThe tool automatically sends to the original channel/chat for this task. Do not provide channel IDs or chat IDs.",{content:zod.z.string().optional().describe("Text to send to the external user. Required when attachments are omitted."),attachments:zod.z.array(zod.z.object({filePath:zod.z.string().describe("Absolute path to an existing user-facing deliverable file. Relative paths are rejected."),fileName:zod.z.string().optional().describe("Optional display filename shown to the external user. Defaults to the local basename."),kind:zod.z.enum(["auto","image","file","audio","video"]).optional().describe("Attachment kind. Use auto unless you know the exact type.")})).optional().describe("Optional user-facing deliverable files to send with the message.")},async i=>{const o=a?.()??null;if(!o)return{content:[{type:"text",text:"Unsupported: this task is not bound to an external channel, so no channel message can be sent."}],isError:!0};s?.();try{const a=i.content?.trim(),s=await validateChannelAttachments(i.attachments??[]);if(!a&&0===s.length)throw new Error("send_channel_message requires content or attachments");const r=await sendTaskChannelMessage(e,{content:a||void 0,attachments:s.length>0?s:void 0},o);return r?.error?(n.saveTaskEvent({taskId:e,chatId:t,eventType:"channel-message-send",sequence:null,eventData:{status:"error",channelId:o.channelId,hasContent:Boolean(a),attachments:s.map(e=>({filePath:e.filePath,fileName:e.fileName,kind:e.kind})),error:r.error}}),{content:[{type:"text",text:`Failed to send channel message: ${r.error}`}],isError:!0}):(n.saveTaskEvent({taskId:e,chatId:t,eventType:"channel-message-send",sequence:null,eventData:{status:"sent",channelId:o.channelId,hasContent:Boolean(a),attachments:s.map(e=>({filePath:e.filePath,fileName:e.fileName,mimeType:e.mimeType,kind:e.kind}))}}),{content:[{type:"text",text:s.length>0?`Sent channel message with ${s.length} attachment(s).`:"Sent channel message."}]})}catch(e){return logger$4.warn("Channel message send rejected or failed:",e),{content:[{type:"text",text:`Failed to send channel message: ${e instanceof Error?e.message:String(e)}`}],isError:!0}}})}function createGetChannelGroupHistoryTool({taskId:e,getChannelReplyTarget:t}){return claudeAgentSdk.tool("get_channel_group_history","Read older saved history for the external group chat bound to this task.\n\nUse this only when the automatically injected recent group history is not enough to understand context. This tool is read-only and automatically reads the current external channel group; do not provide channel IDs or chat IDs.\n\nThe result is XML-style history with sender metadata. Use it to understand context/history.",{limit:zod.z.number().int().positive().max(100).optional().describe("Maximum messages to return. Defaults to 30; capped at 100."),beforeSeq:zod.z.number().int().positive().optional().describe("Return messages before this local sequence number for older pages."),afterSeq:zod.z.number().int().nonnegative().optional().describe("Return messages after this local sequence number for newer pages. Do not combine with beforeSeq.")},async n=>{const a=t?.()??null;if(!a||"group"!==a.chatType?.toLowerCase())return{content:[{type:"text",text:"Unsupported: this task is not bound to an external channel group chat."}],isError:!0};if(void 0!==n.beforeSeq&&void 0!==n.afterSeq)return{content:[{type:"text",text:"Use beforeSeq or afterSeq, not both."}],isError:!0};const s=await getTaskChannelGroupHistory(e,a,{limit:n.limit,beforeSeq:n.beforeSeq,afterSeq:n.afterSeq});return s?.error?{content:[{type:"text",text:`Failed to read channel group history: ${s.error}`}],isError:!0}:{content:[{type:"text",text:`${[`hasMoreBefore=${Boolean(s.hasMoreBefore)}`,`hasMoreAfter=${Boolean(s.hasMoreAfter)}`].join(" ")}\n\n${s.historyXml??"<external_group_history />"}`}]}})}async function validateChannelAttachments(e){const t=[];for(const n of e)t.push(await validateChannelAttachment(n));return t}async function validateChannelAttachment(e){if(!path.isAbsolute(e.filePath))throw new Error("filePath must be absolute");const t=await promises$2.stat(e.filePath).catch(e=>{throw new Error(`filePath does not exist or cannot be read: ${e instanceof Error?e.message:String(e)}`)});if(!t.isFile())throw new Error("filePath must point to a regular file");if(t.size<=0)throw new Error("file is empty");if(t.size>2147483648)throw new Error(`file is too large for channel delivery (${t.size} bytes; max 2147483648 bytes)`);const n=e.fileName||path.basename(e.filePath),a=path.basename(e.filePath);if(SENSITIVE_ATTACHMENT_NAME_RE.test(a)||SENSITIVE_ATTACHMENT_NAME_RE.test(n))throw new Error("refusing to send an attachment with a sensitive-looking filename");const s=mimeTypesExports.lookup(n)||mimeTypesExports.lookup(e.filePath)||"application/octet-stream",i="string"==typeof s?s:"application/octet-stream",o=e.kind||"auto";return{filePath:e.filePath,fileName:e.fileName,kind:o,mimeType:i}}function createListAgentsTool({agentContext:e}){return claudeAgentSdk.tool("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(),a=e=>`- **${e.displayName||e.name}** (${e.id})\n Type: ${e.type}\n`+(e.developerName?` Developer: ${e.developerName}\n`:"")+` ${e.description||"No description"}\n`;let s="# Available Agents\n\n";return t.length>0&&(s+="## Published Agents\n\n",s+=t.map(a).join("\n")),n.length>0&&(s+="\n## Draft Agents\n\n",s+=n.map(a).join("\n")),0===t.length&&0===n.length&&(s+="No agents available."),{content:[{type:"text",text:s}]}}catch(e){return logger$4.error("Failed to list agents:",e),{content:[{type:"text",text:`Failed to list agents: ${e instanceof Error?e.message:"Unknown error"}`}],isError:!0}}})}async function*singleVisionMessage(e){yield e}function createAnalyzeImageTool({visionModel:e}){return claudeAgentSdk.tool("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:zod.z.string().describe("Absolute path to the image file to analyze"),prompt:zod.z.string().optional().describe("Optional specific question or instruction about the image (default: describe the image)")},async t=>{if(!e)return{content:[{type:"text",text:"Vision analysis is not available (missing configuration)."}],isError:!0};try{const n=(await promises$2.readFile(t.imagePath)).toString("base64"),a={type:"user",message:{role:"user",content:[{type:"image",source:{type:"base64",media_type:{jpg:"image/jpeg",jpeg:"image/jpeg",png:"image/png",gif:"image/gif",webp:"image/webp"}[t.imagePath.split(".").pop()?.toLowerCase()??"jpeg"]??"image/jpeg",data:n}},{type:"text",text:t.prompt||"Describe this image in detail."}]},parent_tool_use_id:null,session_id:""},s=claudeAgentSdk.query({prompt:singleVisionMessage(a),options:{model:e,permissionMode:"bypassPermissions",maxTurns:1,tools:[]}});let i="";for await(const e of s)if("result"===e.type){i=e.result??"";break}return{content:[{type:"text",text:i||"No description returned."}]}}catch(e){return logger$4.error("Failed to analyze image:",e),{content:[{type:"text",text:`Failed to analyze image: ${e instanceof Error?e.message:"Unknown error"}`}],isError:!0}}})}function createScheduleTaskTool(e){return claudeAgentSdk.tool("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:zod.z.enum(["create","list","delete"]).describe("Operation to perform"),task:zod.z.string().optional().describe("Task description (required for create)"),type:zod.z.enum(["once","recurring"]).optional().describe("Task type (required for create)"),due:zod.z.string().optional().describe("ISO 8601 timestamp for one-time tasks"),cron:zod.z.string().optional().describe('Cron expression for recurring tasks (e.g., "0 18 * * *")'),timezone:zod.z.string().optional().describe('IANA timezone (e.g., Asia/Shanghai). Required when timeType is "local"'),timeType:zod.z.enum(["utc","local"]).optional().describe('How to interpret time — "utc" for absolute UTC, "local" (default) for user timezone'),id:zod.z.string().optional().describe("Task ID (required for delete)")},async e=>{try{const t=await machine.machine.readDaemonState();if(!t?.port)return{content:[{type:"text",text:"Daemon not running."}],isError:!0};const n=`http://127.0.0.1:${t.port}`;if("list"===e.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 a=t.tasks??[];return 0===a.length?{content:[{type:"text",text:"No scheduled tasks."}]}:{content:[{type:"text",text:a.map(e=>`- [${e.id}] ${"once"===e.type?`once at ${e.due}`:`recurring: ${e.cron}`} — "${e.task}"`).join("\n")}]}}if("create"===e.action){if(!e.task||!e.type)return{content:[{type:"text",text:"Missing required fields: task, type"}],isError:!0};const t=await fetch(`${n}/schedule`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({task:e.task,type:e.type,due:e.due,cron:e.cron,timezone:e.timezone,timeType:e.timeType})}),a=await t.json();if(!t.ok)return{content:[{type:"text",text:`Error: ${a.error}`}],isError:!0};const s="once"===a.type?`due=${a.due}`:`cron=${a.cron}`;return{content:[{type:"text",text:`Scheduled: id=${a.id}, ${s}`}]}}if("delete"===e.action){if(!e.id)return{content:[{type:"text",text:"Missing required field: id"}],isError:!0};const t=await fetch(`${n}/schedule/${e.id}`,{method:"DELETE"}),a=await t.json();return t.ok?{content:[{type:"text",text:`Deleted: ${e.id}`}]}:{content:[{type:"text",text:`Error: ${a.error}`}],isError:!0}}return{content:[{type:"text",text:`Unknown action: ${e.action}`}],isError:!0}}catch(e){return logger$4.error("Schedule task failed:",e),{content:[{type:"text",text:`Failed: ${e instanceof Error?e.message:String(e)}`}],isError:!0}}})}function createPrepareHiveRepositoryTool({agentContext:e}){return claudeAgentSdk.tool("hive_prepare_repository","Prepare the Agentrix Hive source repository in the local global repo store.\n\nUse this before discovering community agents or skills. This tool only clones/pulls\nthe repository and returns the absolute checkout path. It does not search and does\nnot define the repository layout. After calling it, use Explore with a\ntask-specific goal to find relevant candidates; do not catalog the whole repo\nunless the user explicitly asks for a catalog. If pullSucceeded is false, inspect\nerror and continue with the existing local checkout when it is usable.",{},async()=>{try{const t=await e.prepareHiveRepository();return{content:[{type:"text",text:JSON.stringify(t,null,2)}]}}catch(e){return logger$4.error("Failed to prepare Hive repository:",e),{content:[{type:"text",text:`Failed to prepare Hive repository: ${e instanceof Error?e.message:String(e)}`}],isError:!0}}})}function createPublishToHiveTool({agentContext:e}){return claudeAgentSdk.tool("hive_publish","Publish a newly created agent or skill to Agentrix Hive after the user explicitly agrees.\n\nUse this for content created by this agent/user. Do not use it to republish\nsomeone else's Hive content that was installed locally. To change an owned\nexisting listing, use hive_update. To suggest changes for someone else's listing,\nmodify locally if needed and leave a hive_comment.",{type:zod.z.enum(["agent","skill"]),draftAgentId:zod.z.string().optional().describe("DraftAgent ID for agent publishing"),sourceDir:zod.z.string().optional().describe("Absolute local skill directory for skill publishing"),name:zod.z.string().optional().describe("Listing name, lowercase kebab-case"),displayName:zod.z.string().optional().describe("Human-readable listing name"),description:zod.z.string().optional(),readme:zod.z.string().optional(),category:zod.z.string().optional(),tags:zod.z.array(zod.z.string()).optional(),authorType:zod.z.enum(["user","agent"]).default("user"),authorId:zod.z.string(),machineId:zod.z.string().optional(),cloudId:zod.z.string().optional()},async t=>{try{const n=await e.publishToHive(t);return{content:[{type:"text",text:JSON.stringify(n,null,2)}]}}catch(e){return logger$4.error("Hive publish failed:",e),{content:[{type:"text",text:`Hive publish failed: ${e instanceof Error?e.message:String(e)}`}],isError:!0}}})}function createUpdateHiveListingVersionTool({agentContext:e}){return claudeAgentSdk.tool("hive_update","Publish a new version for an owned Hive listing after the user explicitly agrees.\n\nUse this only when the listing belongs to the user/agent. Do not use it for\nsomeone else's installed Hive content; for those, keep changes local and leave a\nhive_comment with concrete suggestions.",{listingId:zod.z.string().describe("Owned HiveListing ID to update"),version:zod.z.string().optional().describe("Optional new version; defaults to next patch version"),changelog:zod.z.string().optional(),sourceDir:zod.z.string().optional().describe("Absolute local skill directory for skill listing updates"),machineId:zod.z.string().optional(),cloudId:zod.z.string().optional()},async t=>{try{const{listingId:n,...a}=t,s=await e.updateHiveListingVersion(n,a);return{content:[{type:"text",text:JSON.stringify(s,null,2)}]}}catch(e){return logger$4.error("Hive update failed:",e),{content:[{type:"text",text:`Hive update failed: ${e instanceof Error?e.message:String(e)}`}],isError:!0}}})}function createRecordHiveInstallTool({agentContext:e}){return claudeAgentSdk.tool("hive_record_install","Record a Hive agent or skill after installing it locally.\n\nDo not use this tool to install. First prepare the Hive repository, inspect the\nsource for safety and relevance, ask the user if needed, and perform the local\nagent/skill install yourself. Then read the HiveListing ID from\nagentrix-hive-id.txt in the Hive source directory and pass it as listingId.",{listingId:zod.z.string().describe("HiveListing ID read from agentrix-hive-id.txt in the Hive source directory"),agentDir:zod.z.string().describe("Absolute local directory where the agent or skill was installed"),name:zod.z.string().optional().describe("Optional local name for installed agent"),machineId:zod.z.string().optional(),cloudId:zod.z.string().optional(),installedVersion:zod.z.string().optional()},async t=>{try{const{listingId:n,...a}=t,s=await e.recordHiveInstall(n,a);return{content:[{type:"text",text:JSON.stringify(s,null,2)}]}}catch(e){return logger$4.error("Hive install record failed:",e),{content:[{type:"text",text:`Hive install record failed: ${e instanceof Error?e.message:String(e)}`}],isError:!0}}})}function createHiveReviewTool({agentContext:e}){return claudeAgentSdk.tool("hive_review","Leave or update structured feedback for a Hive listing after using it or evaluating user/Syn feedback.",{listingId:zod.z.string().describe("HiveListing ID"),rating:zod.z.number().int().min(1).max(5),comment:zod.z.string().optional().describe("Markdown review text")},async t=>{try{const n=await e.createHiveReview(t.listingId,{rating:t.rating,comment:t.comment??null});return{content:[{type:"text",text:JSON.stringify(n,null,2)}]}}catch(e){return logger$4.error("Hive review failed:",e),{content:[{type:"text",text:`Hive review failed: ${e instanceof Error?e.message:String(e)}`}],isError:!0}}})}function createHiveCommentTool({agentContext:e}){return claudeAgentSdk.tool("hive_comment","Leave a discussion comment, bug report, usage suggestion, or reply for a Hive listing.",{listingId:zod.z.string().describe("HiveListing ID"),content:zod.z.string().min(1).describe("Markdown comment content"),parentId:zod.z.string().optional().describe("Parent comment ID for replies")},async t=>{try{const n=await e.createHiveComment(t.listingId,{content:t.content,parentId:t.parentId});return{content:[{type:"text",text:JSON.stringify(n,null,2)}]}}catch(e){return logger$4.error("Hive comment failed:",e),{content:[{type:"text",text:`Hive comment failed: ${e instanceof Error?e.message:String(e)}`}],isError:!0}}})}function normalizeWorkspacePath(e){if(e)return e.replace(/\/+$/g,"")||"/"}async function checkUncommittedChanges(e){return!!await isGitRepository(e)&&await hasUncommittedChanges(e)}async function handleUncommittedChanges(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 gitStash(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")}}function buildWorkspaceOptions(e){return{eventData:e.eventData,gitUrl:e.gitUrl,baseBranch:e.baseBranch,branchName:e.branchName,branchBinding:e.branchBinding,cwd:normalizeWorkspacePath(e.cwd)||"",userCwd:normalizeWorkspacePath(e.userCwd),forceUserCwd:e.forceUserCwd,useWorktree:e.useWorktree,initPolicies:e.initPolicies,userId:e.userId,taskId:e.taskId,repositorySourceType:e.repositorySourceType,taskRepositoryId:e.repositoryId,workspaceId:e.workspaceId,gitServerId:e.gitServerId,channelReplyTarget:e.channelReplyTarget}}function isExternalChannelWorkspaceTask(e){if(e.channelReplyTarget)return!0;const t=e.eventData;return"object"==typeof t&&null!==t&&"senderType"in t&&"channel"===t.senderType}function hasStrongBranchBinding(e){return!!e.branchName&&"none"!==e.branchBinding&&"external-observed"!==e.branchBinding}function buildShortTaskId(e){return e.replace(/^task-/,"").replace(/[^a-zA-Z0-9]/g,"").toLowerCase().slice(0,8)||"task"}function buildSemanticBranchSlug(e){return e.replace(/^[a-z]+(?:\([^)]+\))?!?:\s*/i,"").normalize("NFKD").replace(/[\u0300-\u036f]/g,"").toLowerCase().replace(/['’]/g,"").replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,48).replace(/-+$/g,"")||"task"}function resolvePublishBranchName(e,t,n){return t||(n?.trim()?`agentrix/${buildSemanticBranchSlug(n)}-${buildShortTaskId(e)}`:`agentrix/${e}`)}async function checkoutPublishBranchAtHead(e,t){const n=simpleGit(e);await n.raw(["checkout","-B",t,"HEAD"])}function buildHeadPushRef(e){return`HEAD:refs/heads/${e}`}function buildMergeRequestBranchMismatchMessage(e,t){return`Cannot create PR: current branch is ${e}, but this task is bound to ${t}. Switch to ${t} or choose Keep during branch mismatch handling before creating the PR.`}async function tryLoadPat(e){if(!e)return null;const t=await getGitServerEncryptionKey();return t?loadPat(e,t):null}async function configureGitIdentity(e,t){const n=loadPatMeta(t);if(!n)return void console.warn("[GIT] No PAT user metadata found, skipping git config");const a=n.username,s=n.email||`${n.username}@gitlab.local`;await setGitConfig(e,a,s),console.log(`[GIT] Set local git config user.name=${a} user.email=${s}`)}async function fetchTaskRemote(e,t,n){const a=await tryLoadPat(n);a?await fetchWithAskPass(a,e):await fetchWithRemoteUrl(t,e)}function resolveManagedBaseBranch(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.")}async function ensureRepoStoreReady(e,t,n,a){const s=sanitizeGitRemoteUrl(t);if(!await isGitRepository(e)){if(!isDirectoryEmpty(e))throw new Error(`Repo store directory ${e} exists but is not a git repository`);await gitInit(e)}await ensureRemote(e,"origin",s),await fetchTaskRemote(e,t,n);const i=resolveManagedBaseBranch(await listRemoteBranches(e),a);return await forceRefreshLocalBranchToStartPoint(e,i,`origin/${i}`),{baseBranch:i}}async function setupGitRepository(e,t,n,a,s,i){const o=sanitizeGitRemoteUrl(t),r=await isGitRepository(e);if(!isDirectoryEmpty(e)&&!r)throw new Error(`Directory ${e} exists but is not a git repository`);const c=await tryLoadPat(s);return isDirectoryEmpty(e)?(c?(console.log("[GIT] Using GIT_ASKPASS credential injection for clone"),await cloneWithAskPass(c,o,e),s&&await configureGitIdentity(e,s)):await gitClone(t,e),await updateRemoteUrl(e,"origin",o),i&&await ensureTaskBranch(e,i,a),await getCurrentCommitHash(e)):(await ensureRemote(e,"origin",o),await fetchTaskRemote(e,t,s),s&&await configureGitIdentity(e,s),i&&await ensureTaskBranch(e,i,a),await getCurrentCommitHash(e))}async function pushForTask(e,t,n,a={}){const s=await tryLoadPat(a.gitServerId);s?await pushWithAskPass(s,e,t,n):a.gitUrl?await pushWithRemoteUrl(a.gitUrl,e,t,n):await gitPush(e,t,n)}async function setupGitServerWorktreeWorkspace(e,t,n,a,s,i){const o=normalizeWorkspacePath(e)||e,r=sanitizeGitRemoteUrl(n),c=parseRemoteInfoFromUrl(r);if(!c)throw new Error(`Unable to resolve repository owner/name from git URL: ${r}`);const l=machine.machine.resolveRepoStoreCheckoutDir(a,c.owner,c.repo),d=machine.machine.resolveRepoStoreLockPath(a,c.owner,c.repo),p=await machine.machine.acquireFileLock(d);if(!p)throw new Error(`Timed out waiting for repo store lock at ${d}`);try{await ensureRepoStoreReady(l,n,a,s);const e=i,t=await listWorktrees(l);if(t.find(e=>normalizeWorkspacePath(e.path)===o))return a&&await configureGitIdentity(o,a),{initialCommitHash:await getCurrentCommitHash(o)};const r=e?t.find(t=>t.branch===e&&normalizeWorkspacePath(t.path)!==o):void 0;if(e&&r)throw new Error(`Branch ${e} is already attached to worktree ${r.path}. Remove it before retrying.`);const c=simpleGit(l),d=await c.branchLocal(),p=!!e&&d.all.includes(e);if(fs.existsSync(o)&&!isDirectoryEmpty(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{e?p?await c.raw(["worktree","add",o,e]):await createWorktree(l,o,e,"HEAD"):await c.raw(["worktree","add",o,"HEAD"])}catch(e){try{await removeWorktree(l,o,!0)}catch{}throw e}return await configureGitIdentity(o,a),{initialCommitHash:await getCurrentCommitHash(o)}}finally{await machine.machine.releaseFileLock(d,p)}}async function initializeGitRepository(e){return await gitInit(e),await initialCommit(e),await getCurrentCommitHash(e)}async function tryAssociateRepository(e,t){try{const n=await getRemoteInfo(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)}}async function setupTmpRepoWorkspace(e){return{initialCommitHash:await initializeGitRepository(e)}}async function setupWorktreeWorkspace(e,t,n,a){const s=e.replace(/^~/,os.homedir()),i=normalizeWorkspacePath(t)||t;if(!await isGitRepository(s))throw new Error(`Directory ${s} is not a git repository. Worktrees can only be created from existing git repositories.`);if(!await hasAnyCommits(s))throw new Error(`Cannot create worktree: repository at ${s} has no commits. Please create an initial commit first: cd ${s} && git add . && git commit -m 'Initial commit'`);const o=a;if((await listWorktrees(s)).find(e=>normalizeWorkspacePath(e.path)===i))return{initialCommitHash:await getCurrentCommitHash(i)};const r=simpleGit(s),c=await r.branchLocal(),l=!!o&&c.all.includes(o);if(fs.existsSync(i)&&!isDirectoryEmpty(i))throw new Error(`Worktree directory already exists at ${i}. This may be from a previous task. To clean up: git worktree remove ${i} OR rm -rf ${i}`);try{o?l?await r.raw(["worktree","add",i,o]):await createWorktree(s,i,o,"HEAD"):await r.raw(["worktree","add",i,"HEAD"])}catch(e){try{await removeWorktree(s,i,!0)}catch{}throw e}return{initialCommitHash:await getCurrentCommitHash(i)}}async function saveTaskPatchDiff(e,t,n){const a=n.trim();if(!a)return;const s=machine.machine.resolveDataDir(e,t),i=path.join(s,"patch.diff");return await promises$1.mkdir(s,{recursive:!0}),await promises$1.writeFile(i,`${a}\n`),i}async function handleGitState(e,t,n,a){if(!await isGitRepository(e))return{currentCommitHash:"",hadUncommittedChanges:!1,hasNewArtifacts:!1,lastSentArtifactVersion:void 0,patchPath:"",diffStats:void 0};const s=await hasUncommittedChanges(e),i=await getCurrentCommitHash(e),o=a||machine.machine.getWorkspaceState(t,n)?.initialCommitHash;if(!o)throw new Error(`Initial commit hash not found for task ${n}`);const r=await getWorkspaceArtifactsSnapshot(e,o),c=r?await saveTaskPatchDiff(t,n,r.patch):void 0,l=await machine.machine.readLastSentArtifactVersion(t,n),d=!!r&&r.artifactVersion!==l;return{currentCommitHash:i,currentArtifactVersion:r?.artifactVersion,hadUncommittedChanges:s,hasNewArtifacts:d,lastSentArtifactVersion:l??void 0,patchPath:c,diffStats:r?.stats}}async function handleGitStateOnWorkerStart(e,t,n,a){return handleGitState(e,t,n,a)}async function markArtifactVersionAsSent(e,t,n){await machine.machine.writeLastSentArtifactVersion(e,t,n)}function applyTemplateVariables(e,t){return e.replace(/\{\{initialCommitHash\}\}/g,t.initialCommitHash).replace(/\{\{currentCommitHash\}\}/g,t.currentCommitHash).replace(/\{\{branchName\}\}/g,t.branchName)}function applyPRPromptTemplate(e,t){return applyTemplateVariables(e,t)}function buildPRRequestPrompt(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 createCommandResultMessage(e,t,n){return{type:"result",subtype:n?"error_during_execution":"success",duration_ms:0,duration_api_ms:0,is_error:n,num_turns:0,result:e,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:[],terminal_reason:n?`exit_code_${t}`:"completed",session_id:"",uuid:crypto$1.randomUUID()}}function createCommandAssistantMessage(e){return{type:"assistant",message:{role:"assistant",content:[{type:"text",text:e}]},parent_tool_use_id:null,session_id:"",uuid:crypto$1.randomUUID()}}function formatCommandOutput(e){const t="```sh\n",n="\n```";return`${t}${truncateToolResultContent(e.trim()?e:"[Command completed with no output]",1024-Buffer.byteLength(t,"utf8")-Buffer.byteLength(n,"utf8"))}${n}`}function executeCommandStreaming(e,t,n,a=6e4){return new Promise(s=>{const i=child_process.spawn("/bin/bash",["-c",e],{cwd:t,env:process.env,shell:!1});let o=null,r=!1;a>0&&(o=setTimeout(()=>{r=!0,i.kill("SIGTERM"),setTimeout(()=>{i.killed||i.kill("SIGKILL")},1e3)},a));let c="";i.stdout?.on("data",e=>{c+=e.toString()}),i.stderr?.on("data",e=>{c+=e.toString()}),i.on("close",(e,t)=>{let i,l,d;if(o&&clearTimeout(o),r){i=124,d=!0;const e=`\n[Command timed out after ${a/1e3} seconds]`;l=c?`${c}${e}`:e.trim()}else i=null!==e?e:"SIGTERM"===t?143:1,d=0!==i,l=c;const p=formatCommandOutput(l);n.onOutput(createCommandAssistantMessage(p)),n.onOutput(createCommandResultMessage(p,i,d)),n.onComplete(i),s(i)}),i.on("error",e=>{o&&clearTimeout(o);const t=formatCommandOutput(`[Error] ${e.message||"Command execution failed"}`);n.onOutput(createCommandAssistantMessage(t)),n.onOutput(createCommandResultMessage(t,1,!0)),n.onComplete(1),s(1)})})}const logger$3=machine.createModuleLogger("undefined"==typeof document?require("url").pathToFileURL(__filename).href:_documentCurrentScript&&"SCRIPT"===_documentCurrentScript.tagName.toUpperCase()&&_documentCurrentScript.src||new URL("index.cjs",document.baseURI).href);class Coordinator{config;messageQueue=[];agentMessageQueue=[];agentMessageResolver=null;workerState="idle";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}:"![agentrix-dev-init]"===t?{type:"agentrix-dev-init",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 logger$3.warn("Ignoring message - coordinator is stopped");if(!("user"!==e.type||e.message&&"object"==typeof e.message&&"content"in e.message))return void logger$3.warn("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),logger$3.debug(`message.enqueued id=${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();logger$3.debug(`message.processing id=${e.id} type=${e.type}`),await this.processMessage(e),logger$3.debug(`message.dispatched id=${e.id} type=${e.type}`)}catch(e){logger$3.error(`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"agentrix-dev-init":await this.processAgentrixDevInit(e);break;case"plan-mode":await this.processPlanMode(e);break;default:logger$3.warn(`Unknown message type: ${e.type}`)}}async processNormalMessage(e){logger$3.debug("message.dispatching_to_agent_queue type=normal");const t=await this.config.handlers.onNormalMessage(e.originalMessage);this.enqueueAgentMessage(t)}async processBashCommand(e){logger$3.info(`Processing bash command: ${e.content}`),await this.processCommand(async()=>{await this.config.handlers.onBashCommand(e.content,e.originalMessage)},e)}async processMergeRequest(e){logger$3.info("Processing merge-request command"),await this.processCommand(async()=>{await this.config.handlers.onMergeRequest(e.originalMessage)},e)}async processMergePr(e){logger$3.info("Processing merge-pr command"),await this.processCommand(async()=>{await this.config.handlers.onMergePr()},e)}async processNewSession(e){logger$3.info("Processing new-session command"),await this.processCommand(async()=>{await(this.config.handlers.onNewSession?.())},e)}async processAgentrixDevInit(e){logger$3.info("Processing agentrix-dev-init command"),await this.processCommand(async()=>{await(this.config.handlers.onAgentrixDevInit?.(e.originalMessage))},e)}async processPlanMode(e){logger$3.info("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");logger$3.debug("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.workerState=e,logger$3.info(`worker.state.changed from=${t} to=${e} activeAgents=${this.agentRunningMap.size} backgroundTasks=${this.backgroundTaskMap.size+this.anonymousBackgroundTaskCount}`),"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 a="running"===this.workerState,s=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(),a&&"running"===this.workerState&&i!==s&&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,logger$3.debug(`Background task ${e} completed via anonymous fallback (remaining: ${this.anonymousBackgroundTaskCount})`)),this.tryUpdateWorkerState())}setAnonymousBackgroundTaskRunning(e){e?(this.anonymousBackgroundTaskCount+=1,logger$3.debug(`Anonymous background task started (count: ${this.anonymousBackgroundTaskCount})`)):this.anonymousBackgroundTaskCount>0&&(this.anonymousBackgroundTaskCount-=1,logger$3.debug(`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)logger$3.warn("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||(logger$3.info(`worker.idle_timer.started timeoutMs=${this.idleTimeoutMs}`),this.idleTimeoutHandle=setTimeout(()=>{this.idleTimeoutHandle=null,this.isStopped||(logger$3.info(`worker.stop.requested reason=idle_timeout source=coordinator timeoutMs=${this.idleTimeoutMs}`),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.isStopped?logger$3.debug("coordinator.stop.ignored alreadyStopped=true"):(logger$3.info("coordinator.stop requested=true"),this.isStopped=!0,this.clearIdleTimer(),this.messageQueue=[],this.agentMessageQueue=[],this.backgroundTaskMap.clear(),this.anonymousBackgroundTaskCount=0,this.cancelAgentWait())}}function sendMessage(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(system_sender,n)}async function executeMergePr(e){const{workingDirectory:t,workClient:n,repositoryId:a,gitServerId:s,gitUrl:i,logger:o,allowInteractive:r=!0,askUser:c,commitChanges:l}=e;if(o.info("[MERGE-PR] Executing merge-pr command"),a){try{const e=await getCurrentBranch(t),a=await hasUncommittedChanges(t),d=await hasUnpushedCommits(t,e);if(a||d){if(!r)throw new Error("merge-pr requires user input to resolve git state, which is not supported in oneshot execution mode");const p=await askMergePrAction(a,d,c,o);if("Pause"===p)return void sendMessage(n,"Operation paused. Please handle git state and run merge again.");if(("Push"===p||"PushAndMerge"===p)&&(a&&(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 pushForTask(t,e,!1,{gitServerId:s,gitUrl:i}),"Push"===p))return void sendMessage(n,"✅ All changes pushed to remote. You can now review and run merge again if everything looks good.")}const p=await n.sendMergePr();if(p.success)sendMessage(n,`✅ PR merged successfully! Branch ${e} has been merged into the target branch.`);else{let e;switch(p.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: ${p.error||"Unknown error"}`;break;default:e=`Failed to merge PR: ${p.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.")}async function askMergePrAction(e,t,n,a){let s="";s=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:s,header:"Git Status",multiSelect:!1,options:[{label:"Pause",description:"Stop operation, handle git state manually"},{label:"Push",description:"Push changes and review before merging"},{label:"Push and Merge",description:"Push changes and merge PR immediately"}]}];try{const e=(await n(i)).answers[0];return e.startsWith("other:")?(a.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 a.error("[MERGE-PR] Ask user failed:",e),"Pause"}}async function applyTaskInfoUpdate(e,t,n){let a=!1;const s=e.updates??{};if(Object.prototype.hasOwnProperty.call(s,"model")){const e=s.model,n="string"==typeof e&&e.trim().length>0?e.trim():null===e?void 0:t.model;t.model!==n&&(n?t.model=n:delete t.model,a=!0)}const i={},o=s.repositoryId;"string"==typeof o&&o.length>0&&t.repositoryId!==o&&(t.repositoryId=o,i.taskRepositoryId=o,a=!0);const r=s.branchName;"string"==typeof r&&r.length>0&&t.branchName!==r&&(t.branchName=r,i.branchName=r,a=!0);const c=s.branchBinding;return"none"!==c&&"explicit"!==c&&"platform-managed"!==c&&"external-observed"!==c||t.branchBinding===c||(t.branchBinding=c,i.branchBinding=c,a=!0),Object.keys(i).length>0&&n&&await n.updateTaskMetadata(i),a}function normalizeAskUserResponse(e){const t=e.status??"answered";return e.status&&e.reason?e:{...e,status:t,reason:e.reason??("timeout"===t?"timeout":"user")}}function askUserWithTimeout(e,t,n,a={}){const s=n.sendAskUser(e),i=a.timeoutMs??18e5,o=a.onTimeout;return new Promise((e,a)=>{const r=setTimeout(()=>{t.delete(s);const i={type:"ask_user_response",answers:[],status:"timeout",reason:"timeout"};n.sendAskUserResponse(s,i),"abort_task"===o?(n.onTimeoutMessage?.("ask_user timed out. Task cancelled."),n.stopTask?.("ask_user_timeout"),a(new Error("Ask user request timed out"))):e(i)},i);t.set(s,t=>{clearTimeout(r),e(normalizeAskUserResponse(t))})})}function createSyntheticInitMessage(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:node_crypto.randomUUID(),session_id:e.sessionId}}function generateAndMapToolId(e,t){const n=node_crypto.randomUUID();return t.set(e,n),n}function getMappedToolId(e,t){return t.get(e)||e}function convertThreadEventToSDKMessage(e,t,n={}){return"thread.started"===e.type||"turn.started"===e.type||"turn.completed"===e.type||"turn.failed"===e.type?null:"error"===e.type?convertStreamError(e.message):"item.started"===e.type?convertItemStarted(e.item,t):"item.completed"===e.type?convertItemCompleted(e.item,t,n):null}function convertStreamError(e){return{type:"system",subtype:"temporary",content:e}}function convertItemStarted(e,t){switch(e.type){case"command_execution":return convertCommandExecutionStarted(e,t);case"file_change":return convertFileChangeStarted(e,t);case"mcp_tool_call":return convertMcpToolCallStarted(e,t);case"web_search":return convertWebSearchStarted(e,t);default:return null}}function convertItemCompleted(e,t,n){switch(e.type){case"agent_message":return convertAgentMessage(e);case"reasoning":default:return null;case"command_execution":return convertCommandExecutionCompleted(e,t);case"file_change":return convertFileChangeCompleted(e,t);case"mcp_tool_call":return convertMcpToolCallCompleted(e,t,n);case"web_search":return convertWebSearchCompleted(e,t);case"todo_list":return convertTodoList(e);case"error":return convertError(e)}}function convertAgentMessage(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:node_crypto.randomUUID().toString()}}function convertCommandExecutionStarted(e,t){return{type:"assistant",message:{role:"assistant",content:[{type:"tool_use",id:generateAndMapToolId(e.id,t),name:"Bash",input:{command:e.command}}]},parent_tool_use_id:null,session_id:""}}function convertCommandExecutionCompleted(e,t){return{type:"user",message:{role:"user",content:[{type:"tool_result",tool_use_id:getMappedToolId(e.id,t),content:"failed"===e.status?"Command execution failed":e.aggregated_output||""}]},parent_tool_use_id:null,session_id:""}}function convertFileChangeStarted(e,t){return{type:"assistant",message:{role:"assistant",content:[{type:"tool_use",id:generateAndMapToolId(e.id,t),name:"Edit",input:{changes:e.changes.map(e=>({kind:e.kind,path:e.path}))}}]},parent_tool_use_id:null,session_id:""}}function convertFileChangeCompleted(e,t){const n=t.get(e.id),a=n??generateAndMapToolId(e.id,t),s=!n;(e.changes||[]).map(e=>`${e.kind}: ${e.path}`);const i={type:"assistant",message:{role:"assistant",content:[{type:"tool_use",id:a,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:a,content:"failed"===e.status?"File changes failed":"File changes completed"}]},parent_tool_use_id:null,session_id:""};return s?[i,o]:o}function convertMcpToolCallStarted(e,t){return{type:"assistant",message:{role:"assistant",content:[{type:"tool_use",id:generateAndMapToolId(e.id,t),server_name:e.server,name:e.tool,input:e.arguments}]},parent_tool_use_id:null,session_id:""}}function convertMcpToolCallCompleted(e,t,n){const a=getMappedToolId(e.id,t),s="failed"===e.status&&e.error;return{type:"user",message:{role:"user",content:[{type:"tool_result",tool_use_id:a,is_error:s,content:s?e.error.message:normalizeMcpToolResultContent(e,n)}]},parent_tool_use_id:null,session_id:""}}function normalizeMcpToolResultContent(e,t){const n=e.result?.content||"";if(!t.taskDataDir||!isComputerUseImageTool(e.tool))return n;if(!Array.isArray(n)){const a=convertImageBlockToTaskDataReference(n,t.taskDataDir);if(a!==n)return[a];const s=convertScreenshotOutFileToTaskDataReference(e,t.taskDataDir);return s?[n,s]:n}const a=n.map(e=>convertImageBlockToTaskDataReference(e,t.taskDataDir)),s=convertScreenshotOutFileToTaskDataReference(e,t.taskDataDir);return s?[...a,s]:a}function isComputerUseImageTool(e){return"get_window_state"===e||"screenshot"===e||e.endsWith("__get_window_state")||e.endsWith("__screenshot")}function convertImageBlockToTaskDataReference(e,t){const n=extractImageData(e);if(!n)return e;try{const e=path.join(t,"attachments");fs.mkdirSync(e,{recursive:!0});const a=extensionForMimeType(n.mimeType),s=path.join(e,`${node_crypto.randomUUID()}${a}`);return fs.writeFileSync(s,Buffer.from(n.base64,"base64")),{type:"text",text:`Image file: ${s}\nType: ${n.mimeType}`}}catch(e){return{type:"text",text:`[Image unavailable: failed to save tool result image: ${e instanceof Error?e.message:String(e)}]`}}}function convertScreenshotOutFileToTaskDataReference(e,t){const n=getScreenshotOutFilePath(e);if(!n||!fs.existsSync(n))return null;try{const e=path.join(t,"attachments");fs.mkdirSync(e,{recursive:!0});const a=imageExtensionFromPath(n),s=mimeTypeForExtension(a),i=path.join(e,`${node_crypto.randomUUID()}${a}`);return fs.copyFileSync(n,i),{type:"text",text:`Image file: ${i}\nType: ${s}`}}catch(e){return{type:"text",text:`[Image unavailable: failed to copy screenshot_out_file: ${e instanceof Error?e.message:String(e)}]`}}}function getScreenshotOutFilePath(e){const t=e.arguments,n=t?.screenshot_out_file;return"string"==typeof n&&n.trim()?n.trim():null}function extractImageData(e){if("object"!=typeof e||null===e)return null;const t=e,n=t.data,a=n&&"object"==typeof n?n:void 0,s="string"==typeof t.mimeType?t.mimeType:"string"==typeof t.mime_type?t.mime_type:"string"==typeof a?.mimeType?a.mimeType:"string"==typeof a?.mime_type?a.mime_type:"image/png";if(!s.startsWith("image/"))return null;const i="string"==typeof t.base64String?t.base64String:"string"==typeof t.base64_string?t.base64_string:"string"==typeof a?.base64String?a.base64String:"string"==typeof a?.base64_string?a.base64_string:"string"==typeof n?n:void 0;return i?{base64:stripDataUrlPrefix(i),mimeType:s}:null}function stripDataUrlPrefix(e){const t=e.match(/^data:[^;]+;base64,(.*)$/s);return t?t[1]:e}function extensionForMimeType(e){switch(e.toLowerCase()){case"image/jpeg":case"image/jpg":return".jpg";case"image/webp":return".webp";case"image/gif":return".gif";default:return".png"}}function imageExtensionFromPath(e){const t=path.extname(e).toLowerCase();return[".png",".jpg",".jpeg",".webp",".gif"].includes(t)?".jpeg"===t?".jpg":t:".png"}function mimeTypeForExtension(e){switch(e.toLowerCase()){case".jpg":case".jpeg":return"image/jpeg";case".webp":return"image/webp";case".gif":return"image/gif";default:return"image/png"}}function convertWebSearchStarted(e,t){return{type:"assistant",message:{role:"assistant",content:[{type:"tool_use",id:generateAndMapToolId(e.id,t),name:"web_search",input:{query:e.query}}]},parent_tool_use_id:null,session_id:""}}function convertWebSearchCompleted(e,t){return{type:"user",message:{role:"user",content:[{type:"tool_result",tool_use_id:getMappedToolId(e.id,t),content:{type:"web_search_result",results:[]}}]},parent_tool_use_id:null,session_id:""}}function convertTodoList(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:""}}function convertError(e){return{type:"assistant",message:{role:"assistant",content:`❌ Error: ${e.message}`},parent_tool_use_id:null,session_id:""}}let cachedConfigModel,cachedConfigPath,codexPathOverrideCache;function stripInlineComment(e){let t=null,n=!1;for(let a=0;a<e.length;a+=1){const s=e[a];if(n)n=!1;else if("\\"!==s||'"'!==t)if('"'!==s&&"'"!==s||null!==t)if(s!==t){if("#"===s&&null===t)return e.slice(0,a)}else t=null;else t=s;else n=!0}return e}function parseTomlString(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 getCodexConfigPath(){const e=process.env.CODEX_HOME||process.env.AGENTRIX_CODEX_HOME||path.join(os.homedir(),".codex");return path.join(e.replace(/^~(?=\/|$)/,os.homedir()),"config.toml")}function readCodexDefaultModel(){const e=getCodexConfigPath();if(cachedConfigPath===e&&void 0!==cachedConfigModel)return cachedConfigModel;if(cachedConfigPath=e,cachedConfigModel=null,!fs.existsSync(e))return cachedConfigModel;let t;try{t=fs.readFileSync(e,"utf8")}catch{return cachedConfigModel}for(const e of t.split(/\r?\n/)){const t=stripInlineComment(e).trim();if(!t)continue;if(t.startsWith("["))break;const n=t.match(/^model\s*=\s*(.+)$/);if(!n)continue;const a=parseTomlString(n[1])?.trim();return cachedConfigModel=a||null,cachedConfigModel}return cachedConfigModel}function resolveCodexModel(e){const t=e?.trim();return t||readCodexDefaultModel()}function resolveCodexPathOverride(){if(void 0!==codexPathOverrideCache)return codexPathOverrideCache??void 0;const e=process.env.AGENTRIX_CODEX_PATH?.trim();if(e)return codexPathOverrideCache=e,e;codexPathOverrideCache=null}function buildDeveloperInstructions(e){const t=[];e.modeConfig.supportChangeTitle&&e.codexAgentrixEventMcp&&("work"===e.modeConfig.mode||"group_work"===e.modeConfig.mode)&&t.push(buildCodexEventBrokerTitlePrompt({serverName:e.codexAgentrixEventMcp.serverName,toolName:e.codexAgentrixEventMcp.titleToolName})),e.codexAgentrixEventMcp&&e.codexAgentrixEventMcp.previewToolName&&("work"===e.modeConfig.mode||"group_work"===e.modeConfig.mode)&&t.push(buildCodexEventBrokerPreviewPrompt({serverName:e.codexAgentrixEventMcp.serverName,toolName:e.codexAgentrixEventMcp.previewToolName})),e.codexAgentrixEventMcp&&e.codexAgentrixEventMcp.sendVisionArtifactToolName&&("work"===e.modeConfig.mode||"group_work"===e.modeConfig.mode)&&t.push(buildCodexEventBrokerVisionArtifactPrompt({serverName:e.codexAgentrixEventMcp.serverName,toolName:e.codexAgentrixEventMcp.sendVisionArtifactToolName}));const n=e.projectAgentrixGuidance?.systemPromptAppend?.trim();return n&&t.push(n),t.length>0?t.join("\n\n"):void 0}function applyCodexAgentrixEventMcpConfig(e,t){const n=t.codexAgentrixEventMcp;if(!n)return;const a=e.config??{},s=a.mcp_servers&&"object"==typeof a.mcp_servers&&!Array.isArray(a.mcp_servers)?a.mcp_servers:{};e.config={...a,mcp_servers:{...s,[n.serverName]:{url:n.url,bearer_token_env_var:n.tokenEnvVar}}}}class CodexRunner{createCodex(e){const t={},n=resolveCodexPathOverride();n&&(t.codexPathOverride=n),e.env&&(t.env=mergeEnvironment(e.env));const a=buildDeveloperInstructions(e);return a&&(t.config={...t.config??{},developer_instructions:a}),applyCodexAgentrixEventMcpConfig(t,e),new codexSdk.Codex(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,a=this.createCodex(t),s=resolveCodexModel(t.model),i={workingDirectory:t.cwd,model:s??void 0,sandboxMode:"danger-full-access",approvalPolicy:"never",skipGitRepoCheck:!0},o=t.agentSessionId?a.resumeThread(t.agentSessionId,i):a.startThread(i),r=Date.now(),c=await o.run("string"==typeof e?e:extractUserMessageText(e),{signal:n.signal,outputSchema:t.structuredOutputSchema?.schema||void 0}),l=Date.now()-r;return createSdkResultMessage({sessionId:o.id??t.agentSessionId??"unknown",model:s??"unknown",numTurns:1,usage:c.usage??{input_tokens:0,cached_input_tokens:0,output_tokens:0,reasoning_output_tokens:0},result:c.finalResponse??"",structuredOutput:parseStructuredOutputTextOrThrow(c.finalResponse??"",Boolean(t.structuredOutputSchema)),durationMs:l})}async*runStreamed(e,t){const n=t.abortController,a=this.createCodex(t),s=resolveCodexModel(t.model),i={workingDirectory:t.cwd,model:s??void 0,sandboxMode:"danger-full-access",approvalPolicy:"never",skipGitRepoCheck:!0},o=t.agentSessionId?a.resumeThread(t.agentSessionId,i):a.startThread(i),r=Date.now(),{events:c}=await o.runStreamed("string"==typeof e?e:extractUserMessageText(e),{signal:n.signal,outputSchema:t.structuredOutputSchema?.schema||void 0});let l=t.agentSessionId||"",d="",p={input_tokens:0,cached_input_tokens:0,output_tokens:0,reasoning_output_tokens:0};const u=new Map,m={get:e=>u.get(e),set:(e,t)=>{u.set(e,t)}};for await(const e of c){if("thread.started"===e.type&&(l=e.thread_id,yield createSyntheticInitMessage({sessionId:l,cwd:t.cwd,model:s??void 0})),"turn.completed"===e.type){e.usage&&(p=e.usage);break}if("turn.failed"===e.type)throw new Error(e.error.message);if("item.completed"===e.type&&"agent_message"===e.item.type&&e.item.text&&(d=e.item.text),"error"===e.type||"item.started"===e.type||"item.completed"===e.type){const n=convertThreadEventToSDKMessage(e,m,{taskDataDir:t.taskDataDir});if(!n)continue;const a=Array.isArray(n)?n:[n];for(const e of a)yield e}}const h=createSdkResultMessage({sessionId:l,model:s??"unknown",numTurns:1,usage:p,result:d,structuredOutput:parseStructuredOutputTextOrThrow(d,Boolean(t.structuredOutputSchema)),durationMs:Date.now()-r});yield h}loop(e){const t=e.abortController,n=this.createCodex(e),a={workingDirectory:e.cwd,sandboxMode:"danger-full-access",approvalPolicy:"never",skipGitRepoCheck:!0};let s=e.model;const i=()=>resolveCodexModel(e.getModel?e.getModel():s)??void 0;let o=i(),r=e.agentSessionId?n.resumeThread(e.agentSessionId,{...a,model:o??void 0}):n.startThread({...a,model:o??void 0}),c=!1;const l=[];let d=null,p=e.agentSessionId??null,u=0;const m=()=>{if(!c&&(c=!0,d)){const e=d;d=null,e(null)}},h=e=>"string"==typeof e?e:extractUserMessageText(e),g=async function*(){try{for(;!c&&!t.signal.aborted;){const s=l.length>0?l.shift():await new Promise(e=>{d=e});if(!s)break;let m="";const g=i();g!==o&&(o=g),p&&(r=n.resumeThread(p,{...a,model:o??void 0}));const f=new Map,y={get:e=>f.get(e),set:(e,t)=>{f.set(e,t)}},v=Date.now(),{events:b}=await r.runStreamed(h(s),{signal:t.signal,outputSchema:e.structuredOutputSchema?.schema||void 0});for await(const t of b){if(c)break;if("thread.started"!==t.type){if("turn.completed"===t.type){p&&(yield createSdkResultMessage({sessionId:p,model:o??"unknown",numTurns:u+1,usage:t.usage??{input_tokens:0,cached_input_tokens:0,output_tokens:0},result:m,structuredOutput:parseStructuredOutputTextOrThrow(m,Boolean(e.structuredOutputSchema)),durationMs:Date.now()-v}));break}if("turn.failed"===t.type)throw new Error(t.error.message);if("error"===t.type||"item.started"===t.type||"item.completed"===t.type){"item.completed"===t.type&&"agent_message"===t.item.type&&t.item.text&&(m=t.item.text);const n=convertThreadEventToSDKMessage(t,y,{taskDataDir:e.taskDataDir});if(!n)continue;const a=Array.isArray(n)?n:[n];for(const e of a)yield e}}else p=t.thread_id,yield createSyntheticInitMessage({sessionId:p,cwd:e.cwd,model:o??void 0})}u+=1}}finally{m()}}();return t.signal.addEventListener("abort",m,{once:!0}),{push:e=>{if(!c){if(d){const t=d;return d=null,void t(e)}l.push(e)}},events:g,stop:m,setModel:async e=>{s=e,o=resolveCodexModel(e)??void 0}}}}const runtimeImport=new Function("specifier","return import(specifier)");function importRuntimeModule(e){return runtimeImport(e)}const VALID_HOOK_NAMES=["PreToolUse","PostToolUse","SessionStart","SessionEnd","UserPromptSubmit","Stop","SubagentStop","PreCompact","Notification"];async function loadHooks(e,t){const n=path$1.join(e,"hooks");if(!fs$1.existsSync(n))return{};const a=[path$1.join(n,"dist","index.mjs"),path$1.join(n,"dist","index.js"),path$1.join(n,"index.mjs"),path$1.join(n,"index.js")];let s=null;for(const e of a)if(fs$1.existsSync(e)){s=e;break}if(!s)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] ${path$1.join(n,"index.js")} or ${path$1.join(n,"index.mjs")}`),{};try{console.log(`[Hook Loader] Loading hooks: ${s}`);const e=`${url.pathToFileURL(s).href}?t=${Date.now()}`,n=await importRuntimeModule(e);if("function"==typeof n.default){if(t)return console.log("[Hook Loader] Using factory pattern with AgentrixContext"),extractHooks(n.default(t));console.warn("[Hook Loader] Factory function found but no context provided, skipping factory")}return extractHooks(n)}catch(e){throw console.error(`[Hook Loader] Failed to load hooks from ${s}:`,e),new Error(`Hook loading failed: ${e instanceof Error?e.message:String(e)}`)}}function extractHooks(e){const t={};for(const n of VALID_HOOK_NAMES){const a=e[n];"function"==typeof a&&(t[n]=a,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}const logger$2=machine.createModuleLogger("undefined"==typeof document?require("url").pathToFileURL(__filename).href:_documentCurrentScript&&"SCRIPT"===_documentCurrentScript.tagName.toUpperCase()&&_documentCurrentScript.src||new URL("index.cjs",document.baseURI).href);async function loadAgentHooks(e,t,n){if(e&&"default"!==e)try{const a=shared.getAgentContext(),s=t||a.resolveAgentDir(e),i=path.join(s,"claude");return await loadHooks(i,n)}catch(e){return void console.warn("[AgentRunners] Failed to load hooks:",e)}}async function loadSdkMcpTools(e,t){const n={};for(const a of e)try{logger$2.info(`Loading SDK MCP tools from: ${a}`);const e=await importRuntimeModule(a),s=e.default||e;if(!s){logger$2.warn(`No default export found in ${a}`);continue}const i="function"==typeof s?s(t):s,o=i.name;n[o]=i,logger$2.info(`Loaded MCP server: ${o}`)}catch(e){const t=e instanceof Error?e.message:String(e);logger$2.error(`Failed to load SDK MCP tools from ${a}: ${t}`)}return n}class AgentRunners{static pool=new Map;static async create(e,t,n){const a=this.pool.get(t);if(a)return a;let s;if("claude"===e||"companion"===e){const a=await loadClaudeAgentConfiguration({agentId:t,agentDir:n?.agentDir});let i,o;n?.context&&t&&"default"!==t&&(i=await loadAgentHooks(t,n.agentDir,n.context)),n?.context&&a.customSdkMcpTools&&a.customSdkMcpTools.length>0&&(o=await loadSdkMcpTools(a.customSdkMcpTools,n.context)),s=new ClaudeRunner(t,e,a,i,o)}else s=new CodexRunner;return this.pool.set(t,s),s}static release(e){this.pool.delete(e)}static releaseAll(){this.pool.clear()}}class NodeFileSystemAdapter{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=path__namespace$1.join(this.workingDirectory,e);return fs__namespace$1.existsSync(t)?fs__namespace$1.readFileSync(t,"utf-8"):null}catch{return null}}async fileExists(e){const t=path__namespace$1.join(this.workingDirectory,e);return fs__namespace$1.existsSync(t)}listFilesRecursively(e,t,n,a,s){if(!(s>a))try{const i=fs__namespace$1.readdirSync(e,{withFileTypes:!0});for(const o of i){const i=n?`${n}/${o.name}`:o.name;o.isDirectory()?shared.IGNORED_DIRECTORIES.includes(o.name)||this.listFilesRecursively(path__namespace$1.join(e,o.name),t,i,a,s+1):o.isFile()&&t.push(i)}}catch(e){}}}async function detectPreviewMetadata(e){const t=new NodeFileSystemAdapter(e);return shared.detectPreview(t)}class Workspace{constructor(e){this.params=e}state=null;persistedState=null;async setup(){const{options:e,handlers:t}=this.params,{userId:n,taskId:a,cwd:s}=e;if(!s)throw new Error("[WORKSPACE] Missing cwd for workspace setup");const i=machine.machine.getWorkspaceState(n,a),o=e.repositorySourceType,r="string"==typeof e.branchName&&e.branchName.length>0,c="string"==typeof i?.branchName&&i.branchName.length>0,l={...e,repositorySourceType:o,taskRepositoryId:e.taskRepositoryId??i?.taskRepositoryId,branchName:r?e.branchName:c?i.branchName:e.branchName,branchBinding:r?e.branchBinding:c?i.branchBinding:e.branchBinding},{initialCommitHash:d,isGitRepository:p,setupAction:u,useWorktree:m,initPolicyUpdates:h}=await this.ensureWorkspace(l,t,i),g={initialized:!0,initializedAt:(new Date).toISOString(),cwd:s,repositorySourceType:l.repositorySourceType,useWorktree:m,userCwd:e.userCwd,forceUserCwd:e.forceUserCwd,gitUrl:e.gitUrl,baseBranch:e.baseBranch,branchName:l.branchName,branchBinding:l.branchBinding,taskRepositoryId:l.taskRepositoryId,initialCommitHash:d,initPolicies:{...i?.initPolicies,...e.initPolicies,...h}};await machine.machine.writeWorkspaceState(n,a,g),this.persistedState=g;const f=await handleGitStateOnWorkerStart(s,n,a,d);return this.state={cwd:s,initialCommitHash:d,isGitRepository:p,setupAction:u,gitStateResult:f,taskRepositoryId:g.taskRepositoryId,branchName:g.branchName,branchBinding:g.branchBinding},p&&!e.taskRepositoryId&&await tryAssociateRepository(s,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 updateBranchBinding(e,t){await this.updateTaskMetadata({branchName:e,branchBinding:t})}async updateTaskMetadata(e){if(!this.state||!this.persistedState)throw new Error("[WORKSPACE] Workspace not initialized");const{userId:t,taskId:n}=this.params.options,a={...this.persistedState};"taskRepositoryId"in e&&(a.taskRepositoryId=e.taskRepositoryId),"branchName"in e&&(a.branchName=e.branchName),"branchBinding"in e&&(a.branchBinding=e.branchBinding),this.persistedState=a,await machine.machine.writeWorkspaceState(t,n,a);const s={...this.state};"taskRepositoryId"in e&&(s.taskRepositoryId=e.taskRepositoryId),"branchName"in e&&(s.branchName=e.branchName),"branchBinding"in e&&(s.branchBinding=e.branchBinding),this.state=s}async prepareResultArtifacts(e={}){const{cwd:t,initialCommitHash:n,isGitRepository:a}=this.getState(),{userId:s,taskId:i}=this.params.options;if(!a||!n)return{};const o=await getWorkspaceArtifactsSnapshot(t,n);if(!o)return{};try{await saveTaskPatchDiff(s,i,o.patch)}catch(t){e.onPatchError?.(t)}const r=await detectPreviewMetadata(t),c=await machine.machine.readLastSentArtifactVersion(s,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 a=e.repositorySourceType;return"git-server"===a?this.ensureGitServerWorkspace(e,t,n):"directory"===a?this.ensureDirectoryWorkspace(e,t,n):this.ensureTemporaryWorkspace(e,t,n)}async ensureGitServerWorkspace(e,t,n){const{cwd:a,gitUrl:s,taskId:i,baseBranch:o,gitServerId:r}=e;if(!s)throw new Error("[WORKSPACE] gitUrl is required for git-server mode");const c=hasStrongBranchBinding(e)?e.branchName:void 0,l=e.forceUserCwd||!1===e.useWorktree,d="git-server"===n?.repositorySourceType&&!0===n.useWorktree,p=await isGitRepository(a),u=isDirectoryEmpty(a);if(l)return this.ensureDirectGitServerWorkspace(e,t,n,p,u);if(Boolean(e.taskRepositoryId&&r)&&(!p||d)){const l=await setupGitServerWorktreeWorkspace(a,i,s,r,o,c);return p?{...await this.tryResolveDirtyRepo(e,t,n),setupAction:"reuse",useWorktree:!0}:{initialCommitHash:this.resolveInitialCommitHash(n?.initialCommitHash,l.initialCommitHash,"none"),isGitRepository:!0,setupAction:"worktree",autoCommitPolicy:"enabled",useWorktree:!0}}if(!p){if(!u)throw new Error(`[WORKSPACE] Directory ${a} exists but is not a git repository.`);const e=await setupGitRepository(a,s,i,o,r,c)||await getCurrentCommitHash(a);return{initialCommitHash:this.resolveInitialCommitHash(n?.initialCommitHash,e,"none"),isGitRepository:!0,setupAction:"clone",autoCommitPolicy:"enabled",useWorktree:!1}}return await updateRemoteUrl(a,"origin",sanitizeGitRemoteUrl(s)),{...await this.tryResolveDirtyRepo(e,t,n),setupAction:"reuse",useWorktree:n?.useWorktree??!1}}async ensureDirectGitServerWorkspace(e,t,n,a,s){const{cwd:i,gitUrl:o,taskId:r,baseBranch:c,gitServerId:l}=e;if(!o)throw new Error("[WORKSPACE] gitUrl is required for git-server direct directory mode");const d=hasStrongBranchBinding(e)?e.branchName:void 0;if(!a){if(!s)throw new Error(`[WORKSPACE] Directory ${i} exists but is not a git repository.`);const e=await setupGitRepository(i,o,r,c,l,d)||await getCurrentCommitHash(i);return{initialCommitHash:this.resolveInitialCommitHash(n?.initialCommitHash,e,"none"),isGitRepository:!0,setupAction:"clone",autoCommitPolicy:"enabled",useWorktree:!1}}return await this.assertDirectGitServerRemoteMatches(i,o),{...await this.tryResolveDirtyRepo(e,t,n,{defaultBranchMismatchAction:"Keep"}),setupAction:"reuse",useWorktree:!1}}async assertDirectGitServerRemoteMatches(e,t){const n=parseRemoteInfoFromUrl(sanitizeGitRemoteUrl(t));if(!n)throw new Error(`[WORKSPACE] Unable to parse selected repository remote URL: ${sanitizeGitRemoteUrl(t)}`);const a=await getRemoteInfo(e);if(!a)throw new Error(`[WORKSPACE] Direct directory ${e} must have an origin remote matching the selected repository.`);const s=n.host.toLowerCase(),i=a.host.toLowerCase(),o=n.owner.toLowerCase(),r=a.owner.toLowerCase(),c=n.repo.toLowerCase(),l=a.repo.toLowerCase();if(s!==i||o!==r||c!==l)throw new Error(`[WORKSPACE] Direct directory ${e} points to ${a.host}/${a.owner}/${a.repo}, but the selected repository is ${n.host}/${n.owner}/${n.repo}.`)}async ensureDirectoryWorkspace(e,t,n){const{cwd:a,taskId:s,userCwd:i}=e;if(await isGitRepository(a))return this.tryResolveDirtyRepo(e,t,n);if(!isDirectoryEmpty(a))return{initialCommitHash:"",isGitRepository:!1,setupAction:"reuse",autoCommitPolicy:"enabled",useWorktree:!1};{if(!i)return{initialCommitHash:"",isGitRepository:!1,setupAction:"reuse",autoCommitPolicy:"enabled",useWorktree:!1};const t=i.replace(/^~/,os.homedir());if(isDirectoryEmpty(t))return{initialCommitHash:"",isGitRepository:!1,setupAction:"reuse",autoCommitPolicy:"enabled",useWorktree:!1};if(!await isGitRepository(t))return{initialCommitHash:"",isGitRepository:!1,setupAction:"reuse",autoCommitPolicy:"enabled",useWorktree:!1};await hasAnyCommits(t)||await initialCommit(t),await setupWorktreeWorkspace(t,a,s,hasStrongBranchBinding(e)?e.branchName:void 0)}return{...await this.tryResolveDirtyRepo(e,t,n),setupAction:"reuse",useWorktree:!0}}async ensureTemporaryWorkspace(e,t,n){const{cwd:a}=e;if(!await isGitRepository(a)){await setupTmpRepoWorkspace(a),hasStrongBranchBinding(e)&&e.branchName&&await ensureTaskBranch(a,e.branchName,e.baseBranch);const t=await getCurrentCommitHash(a);return{initialCommitHash:this.resolveInitialCommitHash(n?.initialCommitHash,t,"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,a={}){let s=null,i="enabled";const o={};if(await checkUncommittedChanges(e.cwd)){const a=this.getPersistedInitPolicy(n,e,"uncommittedChanges",["Ignore","Commit","Stash"]),r=a?{action:a,remember:!0}:isExternalChannelWorkspaceTask(e)?{action:"Ignore",remember:!0}:t?.onUncommittedChanges?await t.onUncommittedChanges():{action:"Ignore",remember:!1},c=r.action;if(await handleUncommittedChanges(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()}!a&&r.remember&&(o.uncommittedChanges=c),s=c,"Ignore"===c&&(i="disabled_by_ignore")}let r;await hasAnyCommits(e.cwd)||await initialCommit(e.cwd),r=hasStrongBranchBinding(e)?"Ignore"===s?await getCurrentBranch(e.cwd)===e.branchName?"none":"kept":await this.tryResolveBranchMismatch(e,t,n,o,a.defaultBranchMismatchAction??"Switch"):"none";const c=await getCurrentCommitHash(e.cwd);return{initialCommitHash:this.resolveInitialCommitHash(n?.initialCommitHash,c,r),isGitRepository:!0,setupAction:"reuse",autoCommitPolicy:i,useWorktree:n?.useWorktree??!1,initPolicyUpdates:o}}getPersistedInitPolicy(e,t,n,a){const s=e?.initPolicies?.[n]??t.initPolicies?.[n];return s&&a.includes(s)?s:null}resolveInitialCommitHash(e,t,n){return e?"kept"===n?t:e:t}async tryResolveBranchMismatch(e,t,n,a,s){if(!hasStrongBranchBinding(e)||!e.branchName)return"none";const i=e.branchName,o=await getCurrentBranch(e.cwd);if(o===i)return"none";const r=this.getPersistedInitPolicy(n,e,"branchMismatch",["Switch","Keep"]),c=r?{action:r,remember:!0}:t?.onBranchMismatch?await t.onBranchMismatch({currentBranch:o,expectedBranch:i,workingDirectory:e.cwd}):{action:s,remember:!1};if("Abort"===c.action)throw new Error("Task aborted by user due to branch mismatch");return!r&&c.remember&&(a.branchMismatch=c.action),"Keep"===c.action?"kept":(await ensureTaskBranch(e.cwd,i,e.baseBranch),"switched")}}const prInfoSchema=zod.z.object({title:zod.z.string().describe("Concise PR title following conventional commits format (feat/fix/docs/refactor/test/chore: description), maximum 50 characters"),description:zod.z.string().describe("Detailed PR description explaining: what changed, why these changes were necessary, any important technical decisions, and impact on existing functionality"),userMessage:zod.z.string().describe("Friendly message to display to the user, summarizing the PR creation. Should be concise and informative.")}),prInfoJsonSchema=zod.toJSONSchema(prInfoSchema,{target:"draft-07"}),prInfoOpenAiSchema=zod.toJSONSchema(prInfoSchema);function parsePrInfoFromResult(e){if("success"!==e.subtype)throw new Error("PR response failed before structured output was returned");const t=e;return t.structured_output?prInfoSchema.parse(t.structured_output):parsePrInfo(t.result??"")}function extractJsonCandidate(e){const t=e.match(/```(?:json)?\s*\n?([\s\S]*?)\n?```/);return t?t[1].trim():e.trim()}function parsePrInfo(e){if(!e.trim())throw new Error("PR response was empty");const t=extractJsonCandidate(e),n=JSON.parse(t);return prInfoSchema.parse(n)}class InProcessQueue{chain=Promise.resolve();run(e){const t=this.chain.then(e,e);return this.chain=t.then(()=>{},()=>{}),t}}const CLI_BUILTIN_COMMANDS=[{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"},{name:"/agentrix-dev-init",sendAs:"![agentrix-dev-init]",description:"Run Agentrix DevOps initialization for this project"}];function normalizeCommandName(e){const t=e.trim();return t?t.startsWith("/")?t:`/${t}`:""}function getBuiltinSlashCommands(){return CLI_BUILTIN_COMMANDS.map(e=>({id:`cli_builtin:${e.name}`,name:e.name,kind:"cli_builtin",sendAs:e.sendAs,description:e.description}))}function buildSlashCommandCatalog(e=[]){const t=[],n=new Set;for(const e of getBuiltinSlashCommands())t.push(e),n.add(e.name);const a=Array.from(new Set(e.map(normalizeCommandName).filter(Boolean)));a.sort((e,t)=>e.localeCompare(t));for(const e of a)n.has(e)||t.push({id:`sdk:${e}`,name:e,kind:"sdk",sendAs:e});return t}const commitMessageSchema=zod.z.object({message:zod.z.string().describe("A git commit message following conventional commits. Return only the commit message text, optionally with a blank line and body.")}),commitMessageClaudeSchema=zod.toJSONSchema(commitMessageSchema,{target:"draft-07"}),commitMessageOpenAiSchema=zod.toJSONSchema(commitMessageSchema),COMMIT_PROMPT="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.";function parseCommitMessageResult(e){if("success"!==e.subtype)throw new Error("Commit message generation failed before structured output was returned");const t=e,n=(t.structured_output?commitMessageSchema.parse(t.structured_output):commitMessageSchema.parse(JSON.parse(extractJsonCandidate(t.result??"")))).message.trim();if(!n)throw new Error("Commit message generation returned an empty message");return n}async function generateCommitMessageForCurrentChanges(e){const t=e.runner.runStreamed(COMMIT_PROMPT,{cwd:e.workingDirectory,model:e.model,abortController:e.abortController,modeConfig:e.modeConfig,env:e.env,disableClaudePlanModeTools:e.disableClaudePlanModeTools,projectAgentrixGuidance:e.projectAgentrixGuidance,structuredOutputSchema:{type:"json_schema",schema:"claude"===e.schemaTarget?commitMessageClaudeSchema:commitMessageOpenAiSchema}});let n=null;for await(const a of t){if("result"===a.type){n=a;break}await(e.onStreamMessage?.(a))}if(!n)throw new Error("Commit message generation did not return a result message");return parseCommitMessageResult(n)}async function commitCurrentChangesWithAgent(e){if(!await hasUncommittedChanges(e.workingDirectory))throw new Error("No uncommitted changes to commit");const t=await getCurrentCommitHash(e.workingDirectory),n=await generateCommitMessageForCurrentChanges(e),a=await commitWithMessage(e.workingDirectory,n);if(await hasUncommittedChanges(e.workingDirectory))throw new Error("Commit completed but working tree is still dirty");if(a===t)throw new Error("Commit completed but HEAD did not change");return{commitHash:a,message:n}}function buildStructuredOutputSchema(e){if(e)return{type:"json_schema",schema:e}}async function copyDirectory(e,t){await fs.promises.mkdir(t,{recursive:!0});const n=await fs.promises.readdir(e,{withFileTypes:!0});for(const a of n){const n=path.join(e,a.name),s=path.join(t,a.name);a.isDirectory()?await copyDirectory(n,s):await fs.promises.copyFile(n,s)}}function getWorkerExecutionMode(e){return e.workerExecutionMode??shared.DEFAULT_WORKER_EXECUTION_MODE}function isOneShotExecution(e){return"oneshot"===getWorkerExecutionMode(e)}async function loadProjectAgentrixGuidance(e){const t=path.join(e,".agentrix"),n=path.join(t,"prompt.md"),a=path.join(t,"plugins"),[s,i]=await Promise.all([readPromptIfPresent(n),loadClaudePlugins(a)]);return{systemPromptAppend:s,claudePlugins:i}}async function readPromptIfPresent(e){try{if(!(await fs.promises.stat(e)).isFile())return;const t=(await fs.promises.readFile(e,"utf8")).trim();return t.length>0?t:void 0}catch(e){if(isMissingPathError(e))return;throw e}}async function loadClaudePlugins(e){let t;try{t=await fs.promises.readdir(e,{withFileTypes:!0})}catch(e){if(isMissingPathError(e))return[];throw e}const n=[];for(const a of t.sort((e,t)=>e.name.localeCompare(t.name))){if(!a.isDirectory())continue;const t=path.join(e,a.name),s=path.join(t,".claude-plugin","plugin.json");try{(await fs.promises.stat(s)).isFile()&&n.push({type:"local",path:t})}catch(e){if(isMissingPathError(e))continue;throw e}}return n}function isMissingPathError(e){return"object"==typeof e&&null!==e&&"code"in e&&"ENOENT"===e.code}function isCloudRuntime(){return Boolean(process.env.CLOUD_AUTH_TOKEN?.trim())}function hasExplicitTaskExecutionTarget(e){const t=e;return Boolean(t.machineId||t.cloudId)}function isTaskPreviewAvailableForWorker(e){const t=e,n=shared.getTaskExecutionMode({machineId:t.machineId??null,cloudId:t.cloudId??null});return hasExplicitTaskExecutionTarget(e)?"local"===n:!isCloudRuntime()&&"cloud"!==n}function isVisionPlanAvailableForWorkspace(e){if(!e)return!1;const t=path.join(e,".agentrix","vision");try{return fs.existsSync(t)&&fs.statSync(t).isDirectory()}catch{return!1}}function normalizeEnvUrl(e){const t=e?.trim();if(t)return t.replace(/\/+$/,"")}function buildGitLabPatEnvironment(e,t,n){return{GITLAB_TOKEN:e,...t?{GITLAB_BASE_URL:t,CI_SERVER_URL:t}:{},...n?{GITLAB_API_URL:n}:{}}}function extractAuthenticatedGithubToken(e){if(!e)return null;try{const t=new URL(e),n=decodeURIComponent(t.username),a=decodeURIComponent(t.password);if(t.host.toLowerCase(),"x-access-token"===n&&a)return a}catch{return null}return null}async function buildGitProviderAgentEnvironment(e){const t=extractAuthenticatedGithubToken(e.gitUrl);if(t)return{GITHUB_TOKEN:t,GH_TOKEN:t};if(!e.gitServerId)return{};const n=await getGitServerEncryptionKey();if(!n)return{};const a=loadPat(e.gitServerId,n);if(!a)return{};const s=loadGitServerConfig(e.gitServerId);return buildGitLabPatEnvironment(a,normalizeEnvUrl(s?.baseUrl),normalizeEnvUrl(s?.apiUrl))}async function applyGitProviderAgentEnvironment(e){const t=await buildGitProviderAgentEnvironment(e);for(const[e,n]of Object.entries(t))process.env[e]=n;return t}function putIfPresent(e,t,n){if(null==n)return;const a=String(n);0!==a.length&&(e[t]=a)}function buildTaskContextEnvironment(e,t){const n={},a=e.machineId??t.machineId;return putIfPresent(n,"AGENTRIX_TASK_ID",e.taskId),putIfPresent(n,"AGENTRIX_USER_ID",e.userId),putIfPresent(n,"AGENTRIX_AGENT_ID",e.agentId),putIfPresent(n,"AGENTRIX_AGENT_TYPE",e.agentType),putIfPresent(n,"AGENTRIX_CHAT_ID",e.chatId),putIfPresent(n,"AGENTRIX_MACHINE_ID",a),putIfPresent(n,"AGENTRIX_CLOUD_ID",e.cloudId),putIfPresent(n,"AGENTRIX_ROOT_TASK_ID",e.rootTaskId),putIfPresent(n,"AGENTRIX_PARENT_TASK_ID",e.parentTaskId),putIfPresent(n,"AGENTRIX_TASK_TYPE",e.taskType),putIfPresent(n,"AGENTRIX_WORKSPACE_ID",e.workspaceId),putIfPresent(n,"AGENTRIX_WORKING_DIR",t.workingDirectory),putIfPresent(n,"AGENTRIX_WORKING_USER",e.userId),putIfPresent(n,"AGENTRIX_WORKING_TASK",e.taskId),n}function applyTaskEnvironmentToProcess(e,t){if(e.environmentVariables)for(const[t,n]of Object.entries(e.environmentVariables))null!=n&&(process.env[t]=String(n));Object.assign(process.env,buildTaskContextEnvironment(e,t))}function buildAgentRunEnvironment(e,t){const n={};if(t.baseEnv)for(const[e,a]of Object.entries(t.baseEnv))"string"==typeof a&&(n[e]=a);return{...n,...buildTaskContextEnvironment(e,t)}}const logger$1=machine.createModuleLogger("undefined"==typeof document?require("url").pathToFileURL(__filename).href:_documentCurrentScript&&"SCRIPT"===_documentCurrentScript.tagName.toUpperCase()&&_documentCurrentScript.src||new URL("index.cjs",document.baseURI).href),COMPANION_HEARTBEAT_CONTEXT=Symbol("companionHeartbeatContext"),COMPANION_MEMORY_ORGANIZATION_CONTEXT=Symbol("companionMemoryOrganizationContext");function getPermissionModeAfterToolUse(e,t){return"EnterPlanMode"===e?"plan":"ExitPlanMode"===e?t:null}class ClaudeWorker{constructor(e,t,n){this.credentials=e,this.options=t,this.workingDirectory=n;const a=this.options.input,{taskId:s,userId:i}=a;this.logger=machine.getLoggerBase(),this.currentAgentSessionId="agentSessionId"in a?a.agentSessionId:void 0;const o=a.taskAgents||[];this.taskAgentsMap=new Map(o.map(e=>[e.id,e]));const r=this.taskAgentsMap.size>1;this.primaryAgentId=r?"planner":a.agentId,this.primaryAgentName=r?"planner":this.taskAgentsMap.get(a.agentId)?.name??"unknown";const c=this.createWorkerClientConfig(i,s,n),l=machine.machine.resolveDataDir(i,s);this.historyDb=getTaskDb({dataDir:l,taskId:s}),this.workClient=new WorkerClient(c.config,{...c.handlers,getPermissionMode:()=>this.getPermissionModeSnapshot(),historyDb:this.historyDb}),this.coordinator=this.createMessageCoordinator(this.workClient,this.options.idleTimeoutSecond),this.agentContext=new AgentContextImpl({logger:this.logger,socketClient:this.workClient.client,taskId:a.taskId,userId:a.userId,chatId:a.chatId,rootTaskId:a.rootTaskId||a.taskId,parentTaskId:a.parentTaskId||null,workingDirectory:this.workingDirectory,agentHomeDir:machine.machine.agentrixAgentsHomeDir,taskAgents:a.taskAgents||[],serverUrl:machine.machine.serverUrl,taskDataKey:this.options.dataEncryptionKey}),this.agentrixTools=this.createAgentrixTools();const d={...buildWorkspaceOptions(this.options.input),cwd:this.workingDirectory};this.workspace=new Workspace({options:d,handlers:this.createWorkspaceHandlers(this.workClient)})}abortController=new AbortController;isStopping=!1;askUserAwaiter=new Map;messageFilter=createMessageFilter();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;loopModelSetter=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";pendingChannelReplies=[];channelMessageInvocationCount=0;projectAgentrixGuidance={claudePlugins:[]};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 isOneShotExecution(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(),a="group_chat"===n||"group_work"===n,s=shared.isAskUserResponseMessage(t);return!!shared.isCompanionHeartbeatMessage(t)||!!shared.isCompanionMemoryOrganizationMessage(t)||!!shared.isCompanionReminderMessage(t)||!(!shared.isSDKMessage(t)&&!s)&&"agent"!==e.senderType&&(a?e.senderId!==this.primaryAgentId:!!s||"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,a=[];for(const t of e.data)if(this.lastProcessedSequence=t.localSequence,this.shouldProcessMessage(t)){if(n&&this.isUnsupportedGroupPlanCommand(t)){logger$1.info("Ignoring unsupported ![plan] command in group mode");continue}a.push(t)}if(a.length>0){this.deduplicateHeartbeats(a);const e=this.mergeConsecutiveHumanMessages(a);n?await this.processMessagesAsGroup(e):await this.processMessagesIndividually(e)}e.hasMore&&await this.processPendingMessages()}isUnsupportedGroupPlanCommand(e){const t=e.message;return!(!shared.isSDKMessage(t)||"user"!==t.type)&&"![plan]"===extractUserMessageText(t).trim()}deduplicateHeartbeats(e){let t=-1;for(let n=e.length-1;n>=0;n--)shared.isCompanionHeartbeatMessage(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 a=e[n];if("human"===a.senderType){const s=[a];for(;n+1<e.length;){const t=e[n+1];if("human"!==t.senderType||t.senderId!==a.senderId)break;s.push(t),n++}1===s.length?t.push(a):t.push(this.createMergedHumanMessage(s))}else t.push(a);n++}return t}createMergedHumanMessage(e){const t=[],n=[];for(const a of e){const e=a.message;if(!shared.isSDKMessage(e)||"user"!==e.type)continue;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)}const a=t.join(""),s=n.length>0?[{type:"text",text:a},...n]:a,i=e[0],o=e[e.length-1];return{localSequence:o.localSequence,eventId:o.eventId,senderType:i.senderType,senderId:i.senderId,senderName:i.senderName,createdAt:o.createdAt,message:{type:"user",message:{role:"user",content:s},parent_tool_use_id:null,session_id:i.message?.session_id||""}}}async processMessagesAsGroup(e){const t=[],n=[];for(const a of e){const e=formatHistoryMessage(a);if(e){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)}}if(0===t.length)return;const a=Math.max(...e.map(e=>e.localSequence)),s=t.join(" "),i={type:"user",message:{role:"user",content:n.length>0?[{type:"text",text:s},...n]:s},parent_tool_use_id:null,session_id:""};this.attachInputMetadata(i,{localSequence:a,isChannelInput:e.some(e=>"channel"===e.senderType),channelReplyTarget:this.extractChannelReplyTarget(e)}),await this.coordinator.enqueue(i)}async processMessagesIndividually(e){for(const t of e){const e=this.formatSingleMessage(t);e&&(this.attachInputMetadata(e,{localSequence:t.localSequence,isChannelInput:"channel"===t.senderType,channelReplyTarget:this.extractChannelReplyTarget([t])}),delete e.__channelReplyTarget,await this.coordinator.enqueue(e))}}attachInputMetadata(e,t){e.__localSequence=t.localSequence,e.__isChannelInput=t.isChannelInput,t.channelReplyTarget&&(e.__channelReplyTarget=t.channelReplyTarget)}clearRuntimeInputMetadata(e){delete e.__localSequence,delete e.__isChannelInput,delete e.__channelReplyTarget}extractChannelReplyTarget(e){for(let t=e.length-1;t>=0;t--){const n=e[t].message.__channelReplyTarget;if(this.isChannelReplyTarget(n))return n}return null}formatSingleMessage(e){const t=e.message;if(shared.isCompanionHeartbeatMessage(t)){const e=t,n={type:"user",message:{role:"user",content:this.buildCompanionHeartbeatPrompt(e)},parent_tool_use_id:null,session_id:""};return n[COMPANION_HEARTBEAT_CONTEXT]=e,n}if(shared.isCompanionReminderMessage(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:""}}if(shared.isCompanionMemoryOrganizationMessage(t)){const e=t,n={type:"user",message:{role:"user",content:this.buildCompanionMemoryOrganizationPrompt(e)},parent_tool_use_id:null,session_id:""};return n[COMPANION_MEMORY_ORGANIZATION_CONTEXT]=e,n}return shared.isSDKMessage(t)&&"user"===t.type?t:null}buildCompanionHeartbeatPrompt(e){const t=this.options.input,n=t.rootTaskId||t.taskId;return["[heartbeat] You are being awakened by a scheduled companion heartbeat.","","Review target:","Always review the recent context of this companion chat and its root chat task before deciding what to do. Do not limit the review to a generic workspace scan.",...[`heartbeat timestamp: ${e.timestamp}`,e.triggerTime?`local trigger time: ${e.triggerTime}`:void 0,e.triggerReasons?.length?`trigger reasons: ${e.triggerReasons.join(", ")}`:void 0,"number"==typeof e.heartbeatTriggerCount?`heartbeat trigger count: ${e.heartbeatTriggerCount}`:void 0,`current worker taskId: ${t.taskId}`,t.chatId?`companion chatId: ${t.chatId}`:void 0,n?`root chat taskId: ${n}`:void 0].filter(e=>Boolean(e)).map(e=>`- ${e}`),"","Use the available conversation-reading tools for the companion chat/root chat task when needed. Follow the current heartbeat mode instructions from your system prompt. If there is nothing actionable after review, respond briefly and exit."].join("\n")}buildCompanionMemoryOrganizationPrompt(e){const t=this.options.input,n=[`trigger: ${e.trigger}`,`timestamp: ${e.timestamp}`,e.triggerTime?`local trigger time: ${e.triggerTime}`:void 0,"number"==typeof e.intervalHours?`configured interval hours: ${e.intervalHours}`:void 0,`current worker taskId: ${t.taskId}`,t.chatId?`companion chatId: ${t.chatId}`:void 0].filter(e=>Boolean(e));return logger$1.info(`Memory organization input received: trigger=${e.trigger}, timestamp=${e.timestamp}, intervalHours=${e.intervalHours??"unset"}, taskId=${t.taskId}`),["[memory organization] You are being awakened for Companion memory organization.",...n.map(e=>`- ${e}`),"","Use the available conversation, task, and history tools to gather the current signals needed for this memory organization run. Follow the memory organization mode instructions from your system prompt and MEMORY_ORGANIZATION.md."].join("\n")}extractCompanionPromptPlaceholders(e){const t=e[COMPANION_MEMORY_ORGANIZATION_CONTEXT];return t?(delete e[COMPANION_MEMORY_ORGANIZATION_CONTEXT],{COMPANION_SHADOW_TASK:"memory_organization",COMPANION_MEMORY_ORGANIZATION_TRIGGER:t.trigger,COMPANION_MEMORY_ORGANIZATION_TIMESTAMP:t.timestamp,COMPANION_MEMORY_ORGANIZATION_INTERVAL_HOURS:"number"==typeof t.intervalHours?String(t.intervalHours):""}):e[COMPANION_HEARTBEAT_CONTEXT]?(delete e[COMPANION_HEARTBEAT_CONTEXT],{COMPANION_SHADOW_TASK:"heartbeat"}):void 0}async prepareMessageForRunner(e){return processAttachments(e,{attachmentsDir:machine.machine.resolveAttachmentsDir(this.options.input.userId,this.taskId)})}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{if(await this.initialize(),!await this.maybeConfirmAgentrixDevOpsInit())return;await this.handleEvent(),await this.runClaude()}catch(t){if(!(t instanceof claudeAgentSdk.AbortError)){e="error",logger$1.warn("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,a=t.agentGitSubDir;if(n)try{logger$1.info(`Auto-installing agent ${e} from git`),await installAgentFromGit({agentId:e,gitUrl:n,subDir:a??void 0})}catch(t){logger$1.warn(`Auto-install failed for agent ${e}: ${t}`)}else logger$1.warn(`Auto-install skipped: no agentGitUrl provided for agent ${e}`)}async applyAgentUpgrade(e,t,n){const a=machine.machine.agentrixAgentsHomeDir,s=path.join(a,`${e}.new`),i=path.join(a,`${e}-bak`);try{logger$1.info(`Applying upgrade for ${e}`),buildAgentPlugins(n),fs.renameSync(n,s),await copyDirectory(t,i),fs.rmSync(t,{recursive:!0,force:!0}),fs.renameSync(s,t),fs$1.existsSync(i)&&fs.rmSync(i,{recursive:!0,force:!0}),logger$1.info(`Upgrade applied for ${e}`)}catch(n){logger$1.warn(`Upgrade failed for ${e}: ${n}`),!fs$1.existsSync(t)&&fs$1.existsSync(i)&&fs.renameSync(i,t),fs$1.existsSync(s)&&fs.rmSync(s,{recursive:!0,force:!0})}}async initialize(){const e=this.options.input,t="filesystem"===e.agentSource;let n=null;const a=e.agentDir??machine.machine.resolveAgentDir(e.agentId,this.workingDirectory);Boolean(t&&"git-server"===e.repositorySourceType&&!e.agentDir&&!fs$1.existsSync(path.join(a,"agent.json")))&&(n=await this.workspace.setup());const s=e.agentDir??machine.machine.resolveAgentDir(e.agentId,this.workingDirectory),i=path.join(s,"upgrade"),o=Boolean(s)&&Boolean(e.agentGitUrl)&&!t,r=Boolean(e.agentId&&"default"!==e.agentId&&!e.agentDir&&o&&!fs$1.existsSync(s)),c=Boolean(e.agentId&&"default"!==e.agentId&&!e.agentDir&&!t&&!r&&fs$1.existsSync(i));if(await this.workClient.connect(),this.workClient.sendWorkerInitializing({deployingAgent:r,upgradingAgent:c}),r&&await this.autoInstallAgent(e.agentId),t&&"default"!==e.agentId&&!fs$1.existsSync(path.join(s,"agent.json")))throw new Error(`Filesystem agent not found: ${e.agentId} (${s})`);c&&await this.applyAgentUpgrade(e.agentId,s,i),logger$1.info(`Resolved agent ${e.agentId}: ${s}`);const l=await AgentRunners.create(e.agentType,e.agentId,{agentDir:s,context:this.agentContext});this.runner=l,this.initializePermissionModeState(),n??=await this.workspace.setup(),this.projectAgentrixGuidance=await loadProjectAgentrixGuidance(this.workingDirectory),await this.registerWithDaemon(this.workingDirectory),logger$1.info(`Prepared ${this.options.input.repositorySourceType} workspace via ${n.setupAction} at ${this.workingDirectory} (${n.initialCommitHash||"none"})`),await this.setEnvironmentVariables(),this.lastProcessedSequence=this.historyDb.getAgentLastSequences().get(this.primaryAgentId)??0,logger$1.info(`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(buildSlashCommandCatalog())}createWorkspaceHandlers(e){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: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)},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 notifyDaemonSessionStarted(t,{cwd:e,machineId:this.credentials.machineId,pid:process.pid,startedBy:this.options.startedBy||"terminal"});n.error?logger$1.warn(`Failed to report session ${t}:`,n.error):logger$1.info(`Session ${t} registered`)}async setEnvironmentVariables(){applyTaskEnvironmentToProcess(this.options.input,{workingDirectory:this.workingDirectory,machineId:this.credentials.machineId}),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),await applyGitProviderAgentEnvironment(this.options.input)}buildClaudeRunEnvironment(){return buildAgentRunEnvironment(this.options.input,{workingDirectory:this.workingDirectory,machineId:this.credentials.machineId,baseEnv:process.env})}createMessageCoordinator(e,t){const n=1e3*Math.max(0,t??0);return this.coordinator=new Coordinator({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()},onAgentrixDevInit:async()=>{await notifyDaemonStartDevOpsInit(this.taskId,this.options.input.userId),this.stopTask("event")},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)},idleTimeoutMs:n,onIdleTimeout:()=>this.stopTask("idle")}),this.coordinator}sendCurrentWorkerStatus(){const{state:e}=this.coordinator.getStatus();"running"===e?this.workClient.sendWorkRunning(this.coordinator.getActiveAgents()):"idle"===e&&this.workClient.sendWorkerReady()}async handleEvent(){const e=this.options.input.event,t=this.options.input.eventData;if("sub-task-result-updated"===e){const e=t,n=buildSubTaskResultMessage(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=buildSubTaskAskUserMessage(e,this.options.dataEncryptionKey);this.historyDb.saveMessage({eventId:e.eventId||`sub-task-ask-${Date.now()}`,message:n,senderType:"system",senderId:"system",senderName:"system"})}if("task-message"===e){const e=t;if(e.message){const t=formatUserContentLogLine(e,e.message,{source:"startup"});t&&logger$1.info(t)}}if(this.isOneShotExecution())await this.processPendingMessages(),this.coordinator.hasAgentMessages()||this.isStopping||this.stopTask("oneshot_complete");else{if("task-message"===e){const n=t,a=n.message;a&&shared.isCompanionMemoryOrganizationMessage(a)&&this.historyDb.saveMessage({eventId:n.eventId,message:a,senderType:n.senderType,senderId:n.senderId,senderName:n.senderName}).inserted&&this.historyDb.saveTaskEvent({eventType:e,eventId:n.eventId,eventData:n,taskId:this.taskId,chatId:n.chatId??this.options.input.chatId,sequence:n.sequence??null})}this.triggerMessageProcessing()}"task-message"===e&&t?.eventId&&this.workClient.sendEventAck(t.eventId)}async executeMergeRequest(){logger$1.info("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 logger$1.warn("No repositoryId found in task input"),void this.workClient.sendSystemErrorMessage(e,{groupId:this.currentGroupId??void 0})}await hasUncommittedChanges(this.workingDirectory)&&await this.commitCurrentChangesWithAgent();const e=await getCurrentCommitHash(this.workingDirectory),n=this.workspace.getInitialCommitHash();if(!n){const e="Cannot create PR: initial commit hash is missing.";return logger$1.error(e),void this.workClient.sendSystemErrorMessage(e,{groupId:this.currentGroupId??void 0})}if(0===(await getDiffStats(this.workingDirectory,n,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 a=this.workspace.getState(),s=a.branchName?{branchName:a.branchName,branchBinding:a.branchBinding}:this.options.input,i=hasStrongBranchBinding(s),o=i?resolvePublishBranchName(this.options.input.taskId,s.branchName):void 0;if(i&&o){const e=await getCurrentBranch(this.workingDirectory);if(e!==o){const t=buildMergeRequestBranchMismatchMessage(e,o);return logger$1.warn(t),void this.workClient.sendSystemErrorMessage(t,{groupId:this.currentGroupId??void 0})}}const r=this.runner?.getAgentConfiguration(),c=buildPRRequestPrompt(n,(r?.customPRPromptTemplate?applyPRPromptTemplate(r.customPRPromptTemplate,{initialCommitHash:n,currentCommitHash:e,branchName:o??"to-be-generated-from-pr-title"}):void 0)??void 0);logger$1.debug(`PR prompt: ${c.substring(0,200)}...`);const l=this.runner;let d=null;const p=l.runStreamed(c,{cwd:this.workingDirectory,model:this.options.input.model,abortController:this.abortController,modeConfig:this.getRunnerModeConfig(),env:this.buildClaudeRunEnvironment(),disableClaudePlanModeTools:this.shouldDisableClaudePlanModeTools(),projectAgentrixGuidance:this.projectAgentrixGuidance,allowAskUser:!this.isOneShotExecution(),supportedFeatures:this.options.input.supportedFeatures,structuredOutputSchema:{type:"json_schema",schema:prInfoJsonSchema}});for await(const e of p){if(this.logger.debug(`sdk message: ${JSON.stringify(e)}`),"result"===e.type){d=e;break}const n=t?e:this.messageFilter.filter(e);null!==n&&this.workClient.sendTaskEvent(this.getChatSenderMeta(),n,{groupId:this.currentGroupId??void 0})}if(!d)throw new Error("Merge-request did not return a result message");if("success"!==d.subtype)throw new Error("Merge-request did not return a successful result message");const u=parsePrInfoFromResult(d),m=resolvePublishBranchName(this.options.input.taskId,o,u.title);i||await checkoutPublishBranchAtHead(this.workingDirectory,m);const h=buildHeadPushRef(m);logger$1.info(`Pushing HEAD to remote branch ${m}`),await pushForTask(this.workingDirectory,h,!1,{gitServerId:this.options.input.gitServerId,gitUrl:this.options.input.gitUrl}),logger$1.info("Successfully pushed branch to remote");const g=await this.workClient.sendMergeRequest(u.title,u.description,m);"explicit"!==s.branchBinding&&await this.workspace.updateBranchBinding(m,"platform-managed");const f=`${u.userMessage}\n\n✅ Pull request created successfully!\nNumber: #${g.pullRequestNumber}\nURL: ${g.pullRequestUrl}`,y={input_tokens:d.usage.input_tokens??0,cached_input_tokens:d.usage.cache_read_input_tokens??0,output_tokens:d.usage.output_tokens??0,reasoning_output_tokens:0};this.workClient.sendTaskMessage(this.getChatSenderMeta(),createSdkResultMessage({sessionId:d.session_id,model:this.options.input.model??"unknown",numTurns:d.num_turns,usage:y,result:f}),{groupId:this.currentGroupId??void 0})}catch(e){const t=e instanceof Error?e.message:String(e);logger$1.error("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})}}async executeBashCommand(e){if(!machine.machine.isDirectBashAllowed())return logger$1.warn("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});logger$1.info(`Executing command: ${e}`);const t={senderType:"agent",senderId:"bash",senderName:"bash"},n=await executeCommandStreaming(e,this.workingDirectory,{onOutput:e=>{this.workClient.sendTaskMessage(t,e,{groupId:this.currentGroupId??void 0})},onComplete:e=>{logger$1.info(`Command completed with exit code: ${e}`)}});logger$1.info(`Worker ready after command execution (exit code: ${n})`)}async executeMergePr(){await executeMergePr({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(){logger$1.info("Generating commit message with agent"),await commitCurrentChangesWithAgent({runner:this.runner,workingDirectory:this.workingDirectory,model:this.options.input.model,abortController:this.abortController,modeConfig:this.getRunnerModeConfig(),env:this.buildClaudeRunEnvironment(),disableClaudePlanModeTools:this.shouldDisableClaudePlanModeTools(),schemaTarget:"claude",projectAgentrixGuidance:this.projectAgentrixGuidance,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})}}),logger$1.info("Committed changes with agent-generated message")}async executeNewSession(){logger$1.info("Executing new-session: clearing agentSessionId"),this.currentAgentSessionId=void 0,this.primarySessionReady=!1,this.workClient.sendResetTaskSession(),logger$1.info("Session reset sent, stopping task for clean restart"),this.stopTask("event")}isAgentrixDevOpsInitWorker(){return"Agentrix-DevOps"===this.options.input.agentId}async maybeConfirmAgentrixDevOpsInit(){if(!this.isAgentrixDevOpsInitWorker())return!0;const e=resolveDevOpsLanguage(this.options.input),t=(await this.askUser([buildPreInitQuestion(e)],{onTimeout:"abort_task"})).answers[0]??"";return("zh-Hans"===e?"先初始化"===t:"Initialize first"===t)||(await notifyDaemonDevOpsInitComplete(this.taskId,this.options.input.userId,"continue"),!1)}getAgentrixExtraTools(){if(this.isAgentrixDevOpsInitWorker())return[claudeAgentSdk.tool("complete_devops_init","Notify the Agentrix platform that Agentrix DevOps initialization is complete or that the user wants to leave the Agentrix-DevOps init session after it has completed. Call this only after project memory, environment guidance, local initialization state, and automated testing readiness are complete, or when the user explicitly asks to exit init/return to the development agent after choosing to stop. Do not call this because a normal response turn is ending.",{summary:zod.z.string().describe("Short user-visible summary of what initialization completed")},async e=>{const t=resolveDevOpsLanguage(this.options.input),n=await this.askUser([buildPostInitQuestion(t)],{onTimeout:"abort_task"}),a=parsePostInitDecision(n.answers[0]??"",t);if(logger$1.info(`Post-init user decision: ${a??"unrecognized"} (answer=${JSON.stringify(n.answers[0]??"")})`),!a)return{content:[{type:"text",text:"The platform could not recognize the user post-init choice. Ask the user again or call complete_devops_init again after confirming the next action. Do not stop this DevOps init session yet."}]};if("modify"===a){const e=n.details?.[0]?.trim();return{content:[{type:"text",text:e?`The user wants additional Agentrix DevOps init changes before completion:\n${e}`:"The user wants additional Agentrix DevOps init changes before completion. Continue the same initialization session."}]}}return await notifyDaemonDevOpsInitComplete(this.taskId,this.options.input.userId,"continue"===a?"continue":"stop"),setImmediate(()=>this.stopTask("event")),{content:[{type:"text",text:"continue"===a?`Agentrix DevOps initialization completed: ${e.summary}. The platform is switching back to the original development agent.`:`Agentrix DevOps initialization completed: ${e.summary}. The task will stop without starting the development agent.`}]}})]}async runClaude(){if(logger$1.info(`Starting Claude agent for task ${this.taskId}`),this.isStopping)return void logger$1.info(`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(),a="group_chat"===n.mode||"group_work"===n.mode,s=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=>{logger$1.debug(e)},modeConfig:n,env:this.buildClaudeRunEnvironment(),disableClaudePlanModeTools:this.shouldDisableClaudePlanModeTools(),agentrixTools:this.agentrixTools,agentrixExtraTools:this.getAgentrixExtraTools(),enableAgentrixComputerUse:this.isComputerUseEnabled(),enableTaskPreviewUrl:isTaskPreviewAvailableForWorker(this.options.input),enableVisionPlan:isVisionPlanAvailableForWorkspace(this.workingDirectory),allowAskUser:!this.isOneShotExecution(),supportedFeatures:this.options.input.supportedFeatures,channelBound:this.isChannelBoundTask(),channelGroupBound:this.isChannelGroupBoundTask(),channelContext:this.getExternalChannelPromptContext(),visionModel:this.options.input.visionModel,canUseTool:s,hooks:i,maxTurns:this.options.input.maxTurns??void 0,projectAgentrixGuidance:this.projectAgentrixGuidance,structuredOutputSchema:this.getStructuredOutputSchema()});this.loopPermissionModeSetter=o.setPermissionMode??null,this.loopModelSetter=o.setModel??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);const t=e.__localSequence;if(void 0!==t&&this.markPrimaryMessageProcessed(t),Boolean(e.__isChannelInput)){const t=e.__channelReplyTarget;this.pendingChannelReplies.push({target:this.isChannelReplyTarget(t)?t:null,channelMessageInvocationCountAtStart:this.channelMessageInvocationCount})}this.clearRuntimeInputMetadata(e),o.push(await this.prepareMessageForRunner(e)),delete e.__isChannelInput,delete e.__channelReplyTarget}}catch(e){logger$1.error("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,a);this.resetPrimaryPermissionState(),logger$1.info(`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,a=this.createPermissionHandler(),s=this.buildSystemHooks({trackBackgroundTasks:!0,trackPrimaryAgentStop:!0});this.loopPermissionModeSetter=null,this.loopModelSetter=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 logger$1.info(`Claude oneshot finished for task ${this.taskId} without runnable message`);const o=i.__localSequence;if(void 0!==o&&this.markPrimaryMessageProcessed(o),Boolean(i.__isChannelInput)){const e=i.__channelReplyTarget;this.pendingChannelReplies.push({target:this.isChannelReplyTarget(e)?e:null,channelMessageInvocationCountAtStart:this.channelMessageInvocationCount})}delete i.__isChannelInput,delete i.__channelReplyTarget,this.updateAgentRunning(!0);try{const o=this.extractCompanionPromptPlaceholders(i),r=await this.prepareMessageForRunner(i),c=e.runStreamed(r,{cwd:this.workingDirectory,model:this.options.input.model,agentSessionId:this.currentAgentSessionId,abortController:this.abortController,initialPermissionMode:this.getPermissionModeSnapshot()??void 0,stderr:e=>{logger$1.debug(e)},modeConfig:t,env:this.buildClaudeRunEnvironment(),disableClaudePlanModeTools:this.shouldDisableClaudePlanModeTools(),agentrixTools:this.agentrixTools,agentrixExtraTools:this.getAgentrixExtraTools(),enableAgentrixComputerUse:this.isComputerUseEnabled(),enableTaskPreviewUrl:isTaskPreviewAvailableForWorker(this.options.input),enableVisionPlan:isVisionPlanAvailableForWorkspace(this.workingDirectory),allowAskUser:!1,supportedFeatures:this.options.input.supportedFeatures,channelBound:this.isChannelBoundTask(),channelGroupBound:this.isChannelGroupBoundTask(),channelContext:this.getExternalChannelPromptContext(),visionModel:this.options.input.visionModel,canUseTool:a,hooks:s,maxTurns:this.options.input.maxTurns??void 0,projectAgentrixGuidance:this.projectAgentrixGuidance,structuredOutputSchema:this.getStructuredOutputSchema(),promptPlaceholders:o});for await(const e of c)this.logger.debug(`sdk message: ${JSON.stringify(e)}`),await this.handlePrimaryRunnerMessage(e,n);this.isStopping||this.stopTask("oneshot_complete")}finally{this.resetPrimaryPermissionState(),logger$1.info(`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(buildSlashCommandCatalog(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.loopModelSetter=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",logger$1.info("One-shot execution completed, stopping task")),"idle"===e?logger$1.info("Idle timeout reached, stopping task"):"ask_user_timeout"===e&&logger$1.info("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 logger$1.warn("AskUserQuestion missing questions"),{behavior:"deny",message:"AskUserQuestion missing questions"};const a=n.map(e=>({...e,options:[...e.options,{label:"Other",description:""}]}));try{const e=await this.askUser(a),s={};for(let t=0;t<n.length;t+=1){const a=n[t]?.question;if(!a)continue;const i=e.answers?.[t];"string"==typeof i&&(s[a]=i)}return{behavior:"allow",updatedInput:{...t,answers:s}}}catch(e){return logger$1.warn(`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 logger$1.info(`Tool "${e}" already granted, skipping`),{behavior:"allow",updatedInput:t};const n=this.pendingPermissions.get(e);if(n)return logger$1.info(`Tool "${e}" has pending request, waiting...`),"allow"===await n?{behavior:"allow",updatedInput:t}:{behavior:"deny",message:"Permission denied by user"};let a;logger$1.info(`Requesting permission for "${e}"`);const s=new Promise(e=>{a=e});this.pendingPermissions.set(e,s);try{const n=await this.requestToolPermission(e);return a(n),"allow"===n?(this.grantedPermissions.add(e),{behavior:"allow",updatedInput:t}):{behavior:"deny",message:"Permission denied by user"}}catch(e){return a("deny"),{behavior:"deny",message:"Permission request failed"}}finally{this.pendingPermissions.delete(e)}}}async handleExitPlanModePermission(e){const t=e.planFilePath??e.filePath;let n,a;if(t){const e=this.workspace.getCwd(),s=e.endsWith("/")?e:e+"/";n=t.startsWith(s)?t.slice(s.length):void 0;try{const e=await fs$1.promises.readFile(t,"utf-8");a=e.length>8e3?e.slice(0,8e3)+"\n\n…(truncated)":e}catch{}}!a&&"string"==typeof e.plan&&e.plan&&(a=e.plan);const s=[{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:a}];try{const t=await this.askUser(s,{onTimeout:"abort_task"}),n=t.answers[0],a=t.details?.[0]?.trim();return"Approve"===n?{behavior:"allow",updatedInput:e}:"Revise"===n?{behavior:"deny",message:a?`The user wants to revise the plan. Revision notes: ${a}. 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 logger$1.warn(`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 askUserWithTimeout(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],a=t.rememberAnswers?.[0]??e[0]?.rememberSelection?.defaultValue??!1;return n.startsWith("other:")?(logger$1.info(`User provided custom input: ${n}, defaulting to Abort`),{action:"Abort",remember:!1}):{action:{Ignore:"Ignore",Commit:"Commit",Stash:"Stash",Abort:"Abort"}[n]||"Abort",remember:a}}catch(e){return logger$1.warn(`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],a=e.rememberAnswers?.[0]??n[0]?.rememberSelection?.defaultValue??!1;return t.startsWith("other:")?(logger$1.info(`User provided custom input: ${t}, defaulting to Abort`),{action:"Abort",remember:!1}):{action:{Switch:"Switch",Keep:"Keep",Abort:"Abort"}[t]||"Abort",remember:a}}catch(e){return logger$1.warn(`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()}}shouldDisableClaudePlanModeTools(){const e=this.options.input.taskType;return"chat"===e||"shadow"===e||this.isChannelBoundTask()||Boolean(this.options.input.parentTaskId)}get supportChangeTitle(){const e=this.options.input.customTitle;return!("string"==typeof e&&e.trim().length>0)}getStructuredOutputSchema(){return buildStructuredOutputSchema(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=machine.machine.resolveDataDir(t,e);this.chatHistoryDb=getTaskDb({dataDir:n,taskId:e})}return createAgentrixMcpTools({agentContext:this.agentContext,workClient:this.workClient,uploadFile:e=>this.agentContext.uploadFile(e),credentials:this.credentials,taskId:this.taskId,chatId:this.options.input.chatId,agentId:this.primaryAgentId,isGroup:e,historyDb:this.historyDb,chatHistoryDb:this.chatHistoryDb??void 0,askUser:e=>this.askUser(e),onChannelMessageInvoked:()=>{this.channelMessageInvocationCount+=1},invokeAgent:(e,t)=>this.invokeAgent(e,t),assign:(e,t,n)=>this.assignWork(e,t,n),setPendingNavigateTaskId:e=>{this.pendingNavigateTaskId=e},getChannelReplyTarget:()=>this.getInjectedChannelReplyTarget(),supportedFeatures:this.options.input.supportedFeatures,visionModel:this.options.input.visionModel,workingDirectory:this.workingDirectory})}isComputerUseEnabled(){try{return ensureComputerUseBridgeConfigured().enabled}catch(e){return logger$1.warn(`Failed to evaluate Agentrix Computer Use enablement: ${e instanceof Error?e.message:String(e)}`),!1}}resolveTaskAgentName(e){return this.taskAgentsMap.get(e)?.name||""}getChatSenderMeta(){return{senderType:"agent",senderId:this.primaryAgentId,senderName:this.primaryAgentName}}sendAgentErrorMessage(e,t,n,a){const s=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${s}: ${n}`}]}};this.workClient.sendTaskMessage({senderType:"agent",senderId:e,senderName:s},i,{groupId:a?.groupId})}async invokeAgent(e,t){const n=this.buildSubAgentHistoryContext(e,t);if(!n)return!1;const a=this.taskAgentsMap.get(e),s=a?.type||"claude";let i=this.agentQueues.get(e);i||(i=new InProcessQueue,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 a=await AgentRunners.create(s,e,{context:this.agentContext}),i=this.getGroupAgents()||[],r={mode:"reply",supportChangeTitle:!1,groupAgents:i},l=this.createPermissionHandler(),d=this.buildSystemHooks({trackBackgroundTasks:!1}),p=createMessageFilter(),u=a.loop({cwd:this.workingDirectory,model:this.options.input.model,agentSessionId:n.sessionId,abortController:this.abortController,modeConfig:r,env:this.buildClaudeRunEnvironment(),disableClaudePlanModeTools:this.shouldDisableClaudePlanModeTools(),agentrixTools:this.agentrixTools,enableTaskPreviewUrl:isTaskPreviewAvailableForWorker(this.options.input),enableVisionPlan:isVisionPlanAvailableForWorkspace(this.workingDirectory),allowAskUser:!this.isOneShotExecution(),supportedFeatures:this.options.input.supportedFeatures,channelBound:this.isChannelBoundTask(),channelGroupBound:this.isChannelGroupBoundTask(),channelContext:this.getExternalChannelPromptContext(),canUseTool:l,hooks:d,maxTurns:this.options.input.maxTurns??void 0,projectAgentrixGuidance:this.projectAgentrixGuidance,structuredOutputSchema:this.getStructuredOutputSchema()});let m=n.message;if("codex"===s&&!n.sessionId){const t=[buildAgentContextPrompt(e,i),"=== CONVERSATION STREAM START FROM HERE ===",extractUserMessageText(n.message)].join("\n\n").trim();t&&(m=t)}"string"==typeof m?u.push(m):u.push(await this.prepareMessageForRunner(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 a=c?n:p.filter(n);a&&this.workClient.sendTaskEvent({senderType:"agent",senderId:e,senderName:o},a,{groupId:t})}}catch(t){logger$1.error(`Invoke failed for ${e}:`,t)}finally{this.coordinator?.setAgentRunning(e,o,!1)}}),!0}async assignWork(e,t,n){const a=this.taskAgentsMap.get(e),s=a?.type||"claude";let i=this.agentQueues.get(e);i||(i=new InProcessQueue,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 a=this.newMessageGroupId();n&&this.workClient.sendTaskMessage({senderType:"agent",senderId:e,senderName:o},createClaudeAssistantMessage(n),{groupId:this.newMessageGroupId()});try{const n=await AgentRunners.create(s,e,{context:this.agentContext}),i={mode:"work",supportChangeTitle:!1},r=this.createPermissionHandler(),l=this.buildSystemHooks({trackBackgroundTasks:!1}),d=createMessageFilter(),p=n.loop({cwd:this.workingDirectory,model:this.options.input.model,abortController:this.abortController,modeConfig:i,env:this.buildClaudeRunEnvironment(),disableClaudePlanModeTools:this.shouldDisableClaudePlanModeTools(),agentrixTools:this.agentrixTools,enableTaskPreviewUrl:isTaskPreviewAvailableForWorker(this.options.input),enableVisionPlan:isVisionPlanAvailableForWorkspace(this.workingDirectory),allowAskUser:!this.isOneShotExecution(),supportedFeatures:this.options.input.supportedFeatures,channelBound:this.isChannelBoundTask(),channelGroupBound:this.isChannelGroupBoundTask(),channelContext:this.getExternalChannelPromptContext(),canUseTool:r,hooks:l,maxTurns:this.options.input.maxTurns??void 0,projectAgentrixGuidance:this.projectAgentrixGuidance,structuredOutputSchema:this.getStructuredOutputSchema()});p.push(t);let u=!1;for await(const t of p.events){if("system"===t.type&&"init"===t.subtype)continue;if("result"===t.type){this.workClient.sendTaskMessage({senderType:"agent",senderId:e,senderName:o},t,{groupId:a}),u=!0;break}const n=c?t:d.filter(t);n&&this.workClient.sendTaskEvent({senderType:"agent",senderId:e,senderName:o},n,{groupId:a})}}catch(t){logger$1.error(`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:a})}finally{this.coordinator?.setAgentRunning(e,o,!1)}})}buildSubAgentHistoryContext(e,t){const n=this.historyDb;if(!n)return logger$1.warn("Task history DB unavailable; delegate cannot build context."),null;const a=n.getAgentSessions().get(e),s=n.getAgentLastSequences().get(e)??0,i=n.pageRecentMessagesAfter(s,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:a,lastSequence:i.data.length>0?i.data[i.data.length-1].localSequence:s}:null}buildHistoryMessages(e,t){const n=[];for(const t of e){const e=formatHistoryMessageXml(t);e&&n.push(e)}if(0===n.length&&!t)return null;let a=n.join("\n");return t&&(a=`<hint>\n${t}\n</hint>\n\n${a}`),{type:"user",message:{role:"user",content:a},parent_tool_use_id:null,session_id:""}}buildSystemHooks(e){const t=e?.trackBackgroundTasks??!0,n=e?.trackPrimaryAgentStop??!1,a={};return t&&(a.PostToolUse=async e=>(this.syncPermissionModeFromPostToolUse(e),this.trackBackgroundTaskFromPostToolUse(e),{})),n&&(a.Stop=async()=>(this.updateAgentRunning(!1),{})),a}trackBackgroundTaskFromPostToolUse(e){if(!e||"object"!=typeof e)return void logger$1.debug("PostToolUse hook input is not an object");const t=e,n=t.tool_input;if(!n||!0!==n.run_in_background)return;const a=this.extractBackgroundTaskId(t.tool_response);if(!a)return logger$1.debug(`PostToolUse(${t.tool_name}) run_in_background=true but no task_id found, using anonymous tracking`),void this.coordinator?.setAnonymousBackgroundTaskRunning(!0);this.coordinator?.setBackgroundTaskRunning(a,!0),logger$1.info(`Background task started: ${a} (tool: ${t.tool_name})`)}syncPermissionModeFromPostToolUse(e){if(!e||"object"!=typeof e)return;const t=getPermissionModeAfterToolUse(e.tool_name,this.configuredPermissionMode);t&&this.confirmPermissionModeApplied(t)}handleBackgroundTaskNotification(e){this.updateAgentRunning(!0),this.coordinator?.setBackgroundTaskRunning(e.task_id,!1),logger$1.info(`Background task ${e.task_id} ${e.status}`)}extractBackgroundTaskId(e){const t=new Set,n=new Set,a=e=>{if("string"!=typeof e)return;const n=e.trim();n&&t.add(n)},s=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));)a(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)s(t);return}const t=e;"string"==typeof t.task_id&&a(t.task_id),"string"==typeof t.taskId&&a(t.taskId),"string"==typeof t.agent_id&&a(t.agent_id),"string"==typeof t.agentId&&a(t.agentId),"string"==typeof t.shell_id&&a(t.shell_id),"string"==typeof t.shellId&&a(t.shellId);for(const e of Object.values(t))s(e)};s(e);const i=[...t];return i.length>1&&logger$1.warn(`Multiple background task ids extracted (${i.join(", ")}), using first id ${i[0]}`),i[0]}createWorkerClientConfig(e,t,n){const a=this.options.input.agentId,s=this.taskAgentsMap.get(a)?.name;return{config:{userId:e,taskId:t,chatId:this.options.input.chatId,machineId:this.credentials.machineId,agentId:a,agentName:s,cwd:n,serverUrl:machine.machine.serverUrl.replace(/^http/,"ws"),path:"/v1/ws",auth:shared.workerAuth(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:shared.createEventId(),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}},handlers:{attachmentsDir:machine.machine.resolveAttachmentsDir(e,t),stopTask:async()=>{this.stopTask("event")},shouldPersistTaskMessage:async e=>!shared.isCompanionHeartbeatMessage(e)||!this.shouldDropHeartbeatWhileBusy()||(logger$1.debug("Dropping heartbeat at WorkerClient receive stage: agent is running"),!1),onTaskMessage:async(e,t)=>{if(shared.isAskUserResponseMessage(e)){const[t,n]=this.askUserAwaiter.entries().next().value||[];t&&n&&(this.askUserAwaiter.delete(t),n(e))}},onTaskInfoUpdate:async e=>{const t=this.options.input.model;await applyTaskInfoUpdate(e,this.options.input,this.workspace),t!==this.options.input.model&&Object.prototype.hasOwnProperty.call(e.updates??{},"model")&&(logger$1.info(`Task model updated from ${t??"default"} to ${this.options.input.model??"default"}; applying to subsequent Claude responses`),await(this.loopModelSetter?.(this.options.input.model)))},onReconnect:async()=>{this.sendCurrentWorkerStatus()},onWorkerStatusRequest:async()=>{this.sendCurrentWorkerStatus()},onSubTaskResultUpdated:async e=>{const t=buildSubTaskResultMessage(e,this.options.dataEncryptionKey);await this.coordinator.enqueue(t)},onSubTaskAskUser:async e=>{const t=buildSubTaskAskUserMessage(e,this.options.dataEncryptionKey);await this.coordinator.enqueue(t)}}}}async exitWorker(e){logger$1.info(`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){await this.workClient.sendTerminalErrorResultAndWait(e,{groupId:this.currentGroupId??void 0})}get taskId(){return this.options.input.taskId}async handleSdkResultMessage(e){let t,n;try{const e=await this.workspace.prepareResultArtifacts({onPatchError:e=>{logger$1.warn("Failed to write patch diff for result:",e)}});t=e.artifacts,n=e.artifactVersion}catch(e){logger$1.warn("Failed to prepare git artifacts for result:",e)}const a=this.getRunnerMode(),s="group_chat"===a||"group_work"===a,i=this.pendingNavigateTaskId;if(this.pendingNavigateTaskId=null,s?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 markArtifactVersionAsSent(this.options.input.userId,this.taskId,n)}catch(e){logger$1.warn("Failed to mark artifact version as sent:",e)}await this.forwardResultToChannelIfNeeded(e)}async forwardResultToChannelIfNeeded(e){if("result"!==e.type)return;const t=this.pendingChannelReplies.shift(),n=void 0===t?this.getInjectedChannelReplyTarget():t.target??this.getInjectedChannelReplyTarget();if(void 0===t&&!n)return;const a="success"===e.subtype,s=t?this.channelMessageInvocationCount>t.channelMessageInvocationCountAtStart:this.channelMessageInvocationCount>0;if(a&&s)return;const i=this.extractResultTextForChannel(e);if(!i)return;const o=await sendTaskChannelMessage(this.taskId,i,n),r=a;this.historyDb.saveTaskEvent({taskId:this.taskId,chatId:this.options.input.chatId,eventType:"channel-message-send",sequence:null,eventData:{status:o?.error?"error":"sent",delivery:r?"fallback":"error-forward",reason:r?"send_channel_message_not_invoked":"task_failed",channelId:n?.channelId,hasContent:!0,attachments:[],...o?.error?{error:o.error}:{}}}),o?.error&&logger$1.debug(`Claude reply was not sent to channel: ${o.error}`)}getInjectedChannelReplyTarget(){const e=process.env.AGENTRIX_CHANNEL_REPLY_TARGET;if(!e)return null;try{const t=JSON.parse(e);if("string"==typeof t.channelId&&"string"==typeof t.chatId)return{channelId:t.channelId,chatId:t.chatId,..."string"==typeof t.platform?{platform:t.platform}:{},..."string"==typeof t.chatType?{chatType:t.chatType}:{},..."string"==typeof t.chatName?{chatName:t.chatName}:{}}}catch(e){logger$1.debug("Ignoring invalid channel reply target:",e)}return null}isChannelBoundTask(){return null!==this.getInjectedChannelReplyTarget()}isChannelGroupBoundTask(){return"group"===this.getInjectedChannelReplyTarget()?.chatType?.toLowerCase()}getExternalChannelPromptContext(){const e=this.getInjectedChannelReplyTarget();if(e)return{platform:e.platform,chatType:e.chatType,chatName:e.chatName,chatId:e.chatId}}isChannelReplyTarget(e){return Boolean(e&&"object"==typeof e&&"string"==typeof e.channelId&&"string"==typeof e.chatId)}extractResultTextForChannel(e){if("success"===e.subtype){const t=e.result;if("string"!=typeof t)return null;const n=t.trim();return n.length>0?n:null}const t=e.errors,n=Array.isArray(t)?t.filter(e=>"string"==typeof e&&e.trim().length>0).join("\n").trim():"",a=e.subtype;return`Task failed: ${n||("string"==typeof a?a:"Unknown error")}`}}class CwdCalculator{static async calculateFinalCwd(e){const{repositorySourceType:t,cwd:n,userCwd:a,userId:s,taskId:i,forceUserCwd:o,useWorktree:r}=e,c=e=>normalizeWorkspacePath(e)||e;if(n)return c(n);const l=machine.machine.resolveProjectDir(s,i);if(("directory"===t||"git-server"===t)&&a){const e=c(a.replace(/^~/,os.homedir()));if(o||!1===r)return await this.assertUsableUserCwd(e),e}if("directory"===t&&a){const e=c(a.replace(/^~/,os.homedir()));return await this.assertUsableUserCwd(e),await this.shouldUseWorktree(e)?c(l):e}return c(l)}static async shouldUseWorktree(e){try{return!isDirectoryEmpty(e)&&await isGitRepository(e)}catch{return!1}}static async assertUsableUserCwd(e){let t;try{t=await promises$1.stat(e)}catch{throw new Error(`Workspace directory is unavailable: ${e}. Restore or relink the workspace before starting a filesystem task.`)}if(!t.isDirectory())throw new Error(`Workspace path is not a directory: ${e}`);try{await promises$1.access(e,fs.constants.R_OK|fs.constants.W_OK)}catch{throw new Error(`Workspace directory is not readable and writable: ${e}. Restore permissions before starting a filesystem task.`)}}}async function runClaude(e,t){const n=buildWorkspaceOptions(t.input),a=await CwdCalculator.calculateFinalCwd(n),s=new ClaudeWorker(e,t,a);await s.start()}const logger=machine.createModuleLogger("undefined"==typeof document?require("url").pathToFileURL(__filename).href:_documentCurrentScript&&"SCRIPT"===_documentCurrentScript.tagName.toUpperCase()&&_documentCurrentScript.src||new URL("index.cjs",document.baseURI).href);class CodexWorker{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;workerStartedAt=null;exitReason="completed";projectAgentrixGuidance={claudePlugins:[]};codexAgentrixEventMcp=null;isOneShotExecution(){return isOneShotExecution(this.options.input)}refreshGroupId(){this.currentGroupId=`group-${node_crypto.randomUUID()}`}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(),logger.warn("Fatal error:",e);const t=e instanceof Error?e.message:String(e);throw await this.exitWorker("error",t),e}logger.info(`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,n=Date.now();this.workerStartedAt=n,this.logger=machine.getLoggerBase(),this.dataEncryptionKey=this.options.dataEncryptionKey??null;const a=buildWorkspaceOptions(this.options.input),s=await CwdCalculator.calculateFinalCwd(a),i={...a,cwd:s};logger.debug(`Phase 1: Working directory: ${s}`);const o=1e3*Math.max(0,this.options.idleTimeoutSecond??0);logger.info([`worker.start taskId=${e}`,"workerType=codex",`agentId=${this.options.input.agentId??"unknown"}`,`cwd=${s}`,`repositorySourceType=${this.options.input.repositorySourceType??"unknown"}`,"sandboxMode=danger-full-access",`idleTimeoutMs=${o}`].join(" "));const r=this.createWorkerClientConfig(t,e,s),c=machine.machine.resolveDataDir(t,e);this.historyDb=getTaskDb({dataDir:c,taskId:e});const l=new WorkerClient(r.config,{...r.handlers,historyDb:this.historyDb});this.workClient=l,logger.debug("Phase 2: WorkerClient created"),this.coordinator=this.createMessageCoordinator(l,o),logger.debug("Phase 3: Coordinator created");const d=Date.now();await l.connect();const p=Date.now()-d;l.sendWorkerInitializing(),logger.debug("Phase 4: Connected to server"),logger.debug("Phase 5: Skipped (no AgentContext for Codex)"),logger.debug("Phase 6: Skipped (no custom resources for Codex)");const u=new Workspace({options:i,handlers:this.createWorkspaceHandlers(l,s)}),m=Date.now(),{initialCommitHash:h,gitStateResult:g,setupAction:f,branchName:y}=await u.setup(),v=Date.now()-m;this.workspace=u,this.projectAgentrixGuidance=await loadProjectAgentrixGuidance(s),logger.debug("Phase 7: Workspace setup complete"),logger.info([`workspace.ready action=${f}`,`cwd=${s}`,`branch=${y??"unknown"}`,`commit=${h||"none"}`,`repositorySourceType=${this.options.input.repositorySourceType??"unknown"}`,`workspaceMs=${v}`,`hadUncommittedChanges=${Boolean(g?.hadUncommittedChanges)}`].join(" ")),l.sendWorkerInitialized(),l.sendTaskSlashCommandsUpdate(buildSlashCommandCatalog()),logger.debug("Phase 8: Initialization finalized");const b=Date.now();await this.registerWithDaemon(s);const k=Date.now()-b;logger.debug("Phase 9: Registered with daemon"),logger.debug(`Prepared ${this.options.input.repositorySourceType} workspace via ${f} at ${s} (${h||"none"})`),logger.info(["worker.init.completed totalMs="+(Date.now()-n),`connectMs=${p}`,`workspaceMs=${v}`,`daemonRegisterMs=${k}`,`cwd=${s}`,"workerType=codex",`model=${this.options.input.model??"auto"}`].join(" ")),this.context={credentials:this.credentials,options:this.options,workClient:l,workingDirectory:s,dataDir:c,initialCommitHash:h,logger:this.logger},applyTaskEnvironmentToProcess(this.options.input,{workingDirectory:s,machineId:this.credentials.machineId}),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),await applyGitProviderAgentEnvironment(this.options.input),"agentSessionId"in this.options.input&&this.options.input.agentSessionId&&(this.threadId=this.options.input.agentSessionId,logger.info(`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 notifyDaemonSessionStarted(t,{cwd:e,machineId:this.credentials.machineId,pid:process.pid,startedBy:this.options.startedBy||"terminal"});n.error?logger.warn(`Failed to report session ${t}:`,n.error):logger.info(`Session ${t} registered`)}createMessageCoordinator(e,t){return this.coordinator=new Coordinator({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()},onAgentrixDevInit:async()=>{await notifyDaemonStartDevOpsInit(this.taskId,this.options.input.userId),this.stopTask("event")}},idleTimeoutMs:t,onIdleTimeout:()=>this.stopTask("idle")}),this.coordinator}sendCurrentWorkerStatus(){const e=this.workClient;if(!e||!this.coordinator)return;const{state:t}=this.coordinator.getStatus();"running"===t?e.sendWorkRunning(this.coordinator.getActiveAgents()):"idle"===t&&e.sendWorkerReady()}async handleEvent(){if("task-message"===this.options.input.event){const e=this.options.input.eventData,t=e.message;if(t){const n=formatUserContentLogLine(e,t,{source:"startup"});n&&logger.info(n)}t&&shared.isSDKMessage(t)&&"user"===t.type&&(await this.coordinator.enqueue(t),e.eventId&&this.workClient?.sendEventAck(e.eventId))}}async executeMergeRequest(){this.refreshGroupId(),logger.info("Executing merge-request command");try{if(!this.options.input.repositoryId){const e="Cannot create PR: task has no git repository configured.";return logger.warn("No repositoryId found in task input"),void this.context.workClient.sendSystemErrorMessage(e,{groupId:this.currentGroupId??void 0})}await hasUncommittedChanges(this.context.workingDirectory)&&await this.commitCurrentChangesWithAgent();const e=await getCurrentCommitHash(this.context.workingDirectory),t=this.context.initialCommitHash,n=this.workspace.getState(),a=n.branchName?{branchName:n.branchName,branchBinding:n.branchBinding}:this.options.input,s=hasStrongBranchBinding(a),i=s?resolvePublishBranchName(this.options.input.taskId,a.branchName):void 0;if(s&&i){const e=await getCurrentBranch(this.context.workingDirectory);if(e!==i){const t=buildMergeRequestBranchMismatchMessage(e,i);return logger.warn(t),void this.context.workClient.sendSystemErrorMessage(t,{groupId:this.currentGroupId??void 0})}}if(!t){const e="Cannot create PR: initial commit hash is missing.";return logger.error(e),void this.context.workClient.sendSystemErrorMessage(e,{groupId:this.currentGroupId??void 0})}if(0===(await getDiffStats(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 o=buildPRRequestPrompt(t);logger.debug(`PR prompt: ${o.substring(0,200)}...`);const r=this.options.input.agentId??"default",c=await AgentRunners.create("codex",r),l={mode:"work",supportChangeTitle:!1},d=c.runStreamed(o,{cwd:this.context.workingDirectory,model:this.currentModel||void 0,abortController:this.abortController,modeConfig:l,env:this.buildCodexRunEnvironment(),projectAgentrixGuidance:this.projectAgentrixGuidance,structuredOutputSchema:{type:"json_schema",schema:prInfoOpenAiSchema}});let p=null;for await(const e of d){if(this.context.logger.debug(`sdk message: ${JSON.stringify(e)}`),"result"===e.type){p=e;break}const t=this.filterMessages(e);null!==t&&this.context.workClient.sendTaskEvent(this.getChatSenderMeta(),t,{groupId:this.currentGroupId??void 0})}if(!p)throw new Error("Merge-request did not return a result message");const u=parsePrInfoFromResult(p),m=resolvePublishBranchName(this.options.input.taskId,i,u.title);s||await checkoutPublishBranchAtHead(this.context.workingDirectory,m);const h=buildHeadPushRef(m);logger.info(`Pushing HEAD to remote branch ${m}`),await pushForTask(this.context.workingDirectory,h,!1,{gitServerId:this.options.input.gitServerId,gitUrl:this.options.input.gitUrl}),logger.info("Successfully pushed branch to remote"),await this.createPullRequest(u.title,u.description,m),"explicit"!==a.branchBinding&&await this.workspace.updateBranchBinding(m,"platform-managed"),this.sendMessage(u.userMessage)}catch(e){const t=e instanceof Error?e.message:String(e);logger.error("Merge-request failed:",e),this.context.workClient.sendSystemErrorMessage(`Merge-request failed: ${t}\n\n`,{groupId:this.currentGroupId??void 0})}}async executeChangeTitle(e){logger.info(`Changing task title to: ${e}`),this.context.workClient.sendChangeTaskTitle(e)}async executeBashCommand(e){if(this.refreshGroupId(),!machine.machine.isDirectBashAllowed())return logger.warn("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});logger.info(`Executing command: ${e}`);const t=await executeCommandStreaming(e,this.context.workingDirectory,{onOutput:e=>{this.context.workClient.sendTaskMessage(this.getChatSenderMeta(),e,{groupId:this.currentGroupId??void 0})},onComplete:e=>{logger.info(`Command completed with exit code: ${e}`)}});logger.info(`Worker ready after command execution (exit code: ${t})`)}async executeMergePr(){this.refreshGroupId(),await executeMergePr({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 AgentRunners.create("codex",t),a=e||this.context?.workingDirectory;if(!a)throw new Error("Working directory is not available for commit generation");logger.info("Generating commit message with agent"),await commitCurrentChangesWithAgent({runner:n,workingDirectory:a,model:this.currentModel||this.options.input.model||void 0,abortController:this.abortController,modeConfig:{mode:"work",supportChangeTitle:!1},env:this.buildCodexRunEnvironment(),schemaTarget:"openai",projectAgentrixGuidance:this.projectAgentrixGuidance,onStreamMessage:async e=>{const t=this.filterMessages(e);null!==t&&this.getActiveWorkClient().sendTaskEvent(this.getChatSenderMeta(),t,{groupId:this.currentGroupId??void 0})}}),logger.info("Committed changes with agent-generated message")}async executeNewSession(){logger.info("Executing new-session: clearing threadId"),this.threadId=null,this.context.workClient.sendResetTaskSession(),logger.info("Session reset sent, stopping task for clean restart"),this.stopTask("event")}getStructuredOutputSchema(){return buildStructuredOutputSchema(this.options.input.outputSchema)}get supportChangeTitle(){const e=this.options.input.customTitle;return!("string"==typeof e&&e.trim().length>0)}async resolveCodexAgentrixEventMcp(){const e=await machine.machine.readDaemonState();if(!e?.port)return logger.debug("Agentrix event MCP broker unavailable: daemon state not found"),null;const t=isTaskPreviewAvailableForWorker(this.options.input),n=isVisionPlanAvailableForWorkspace(this.context?.workingDirectory),a=signAgentrixEventMcpToken(this.credentials,{taskId:this.taskId,userId:this.options.input.userId,taskPreviewEnabled:t,visionPlanEnabled:n});return{serverName:"agentrix_event_broker",url:buildDaemonControlUrl(e,AGENTRIX_EVENT_MCP_ROUTE),tokenEnvVar:"AGENTRIX_EVENT_MCP_TOKEN",titleToolName:"change_title",previewToolName:t?"publish_task_preview_url":void 0,sendVisionArtifactToolName:n?"send_vision_artifact":void 0,token:a}}buildCodexRunEnvironment(){const e=buildAgentRunEnvironment(this.options.input,{workingDirectory:this.context.workingDirectory,machineId:this.credentials.machineId,baseEnv:process.env});return this.codexAgentrixEventMcp&&(e[this.codexAgentrixEventMcp.tokenEnvVar]=this.codexAgentrixEventMcp.token),e}async runCodex(){logger.info(`Starting Codex agent for task ${this.taskId}`),this.currentModel=resolveCodexModel(this.options.input.model),this.currentModel?logger.info(`Using model: ${this.currentModel}`):logger.info("Using default model from Codex config (model name unavailable)");const e=this.options.input.agentId??"default",t=await AgentRunners.create("codex",e),n={mode:"work",supportChangeTitle:this.supportChangeTitle};if(this.codexAgentrixEventMcp=await this.resolveCodexAgentrixEventMcp(),this.isStopping)return void logger.info(`Skipping Codex run for task ${this.taskId} because worker is stopping`);if(this.isOneShotExecution())return void await this.runCodexOneShot(t,n);const a=t.loop({cwd:this.context.workingDirectory,model:this.currentModel||void 0,getModel:()=>this.currentModel||void 0,agentSessionId:this.threadId??void 0,abortController:this.abortController,modeConfig:n,env:this.buildCodexRunEnvironment(),codexAgentrixEventMcp:this.codexAgentrixEventMcp??void 0,taskDataDir:this.context.dataDir,enableTaskPreviewUrl:isTaskPreviewAvailableForWorker(this.options.input),enableVisionPlan:isVisionPlanAvailableForWorkspace(this.context.workingDirectory),projectAgentrixGuidance:this.projectAgentrixGuidance,structuredOutputSchema:this.getStructuredOutputSchema()});(async()=>{try{for(;!this.isStopping;){const e=await this.coordinator.waitForAgentMessage();if(e)this.refreshGroupId(),this.startAgentTurn(e),this.updateAgentRunning(!0),a.push(e);else if(this.isStopping)break}}catch(e){logger.error("Message pump failed:",e),this.stopTask("event")}})();try{for await(const e of a.events)this.context.logger.debug(`sdk message: ${JSON.stringify(e)}`),await this.handlePrimaryRunnerMessage(e)}catch(e){throw this.logAgentTurnFailed(e),e}logger.info(`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 logger.info(`Codex oneshot finished for task ${this.taskId} without runnable message`);this.updateAgentRunning(!0);try{this.refreshGroupId(),this.startAgentTurn(n);const a=e.runStreamed(n,{cwd:this.context.workingDirectory,model:this.currentModel||void 0,agentSessionId:this.threadId??void 0,abortController:this.abortController,modeConfig:t,env:this.buildCodexRunEnvironment(),codexAgentrixEventMcp:this.codexAgentrixEventMcp??void 0,taskDataDir:this.context.dataDir,enableTaskPreviewUrl:isTaskPreviewAvailableForWorker(this.options.input),enableVisionPlan:isVisionPlanAvailableForWorkspace(this.context.workingDirectory),projectAgentrixGuidance:this.projectAgentrixGuidance,structuredOutputSchema:this.getStructuredOutputSchema()});try{for await(const e of a)this.context.logger.debug(`sdk message: ${JSON.stringify(e)}`),await this.handlePrimaryRunnerMessage(e)}catch(e){throw this.logAgentTurnFailed(e),e}this.isStopping||this.stopTask("oneshot_complete")}finally{logger.info(`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(buildSlashCommandCatalog(e.slash_commands??[]),e.session_id),logger.debug(`Thread started: ${e.session_id}`),logger.info(`agent.thread.started sessionId=${e.session_id}`),void this.updateAgentRunning(!0);const t=this.filterMessages(e);null!==t&&("result"===e.type?(this.logAgentTurnCompleted(e),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 a=n.filter(e=>"tool_use"===e.type&&isAgentrixInternalMcpServerName(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===a.length?null:(t.message.content=a,t)}sendMessage(e){const t={type:"assistant",message:{id:node_crypto.randomUUID().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:node_crypto.randomUUID().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 askUserWithTimeout(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}startAgentTurn(e){logger.info([`agent.turn.started groupId=${this.currentGroupId??"none"}`,`model=${this.currentModel??this.options.input.model??"auto"}`,"session="+(this.threadId?"resume":"new"),`inputChars=${e.length}`].join(" "))}logAgentTurnCompleted(e){const t=e.usage;logger.info([`agent.turn.completed sessionId=${e.session_id||this.threadId||"unknown"}`,`subtype=${e.subtype}`,`isError=${e.is_error}`,`durationMs=${e.duration_ms}`,`turns=${e.num_turns}`,`inputTokens=${t?.input_tokens??0}`,`outputTokens=${t?.output_tokens??0}`,`cacheRead=${t?.cache_read_input_tokens??0}`,`resultChars=${"success"===e.subtype?(e.result??"").length:0}`].join(" "))}logAgentTurnFailed(e){const t=e instanceof Error?e.message:String(e);logger.warn([`agent.turn.failed sessionId=${this.threadId??"unknown"}`,`error=${JSON.stringify(t)}`].filter(Boolean).join(" "))}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],a=t.rememberAnswers?.[0]??e[0]?.rememberSelection?.defaultValue??!1;return n.startsWith("other:")?(logger.info(`User provided custom input: ${n}, defaulting to Abort`),{action:"Abort",remember:!1}):{action:{Ignore:"Ignore",Commit:"Commit",Stash:"Stash",Abort:"Abort"}[n]||"Abort",remember:a}}catch(e){return logger.warn(`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],a=e.rememberAnswers?.[0]??n[0]?.rememberSelection?.defaultValue??!1;return t.startsWith("other:")?(logger.info(`User provided custom input: ${t}, defaulting to Abort`),{action:"Abort",remember:!1}):{action:{Switch:"Switch",Keep:"Keep",Abort:"Abort"}[t]||"Abort",remember:a}}catch(e){return logger.warn(`Failed to get user response for branch mismatch: ${e}`),{action:"Abort",remember:!1}}}async createPullRequest(e,t,n){logger.info(`Creating PR: ${e}`);const a=await this.context.workClient.sendMergeRequest(e,t,n);this.sendMessage(`✅ Pull request created successfully!\nNumber: #${a.pullRequestNumber}\nURL: ${a.pullRequestUrl}`)}async convertSDKMessageToCodexInput(e){const t=e.message.content;if("string"==typeof t)return t;if(Array.isArray(t)){const e=[],n=machine.machine.resolveAttachmentsDir(this.options.input.userId,this.taskId);for(const a of t)if("text"===a.type&&a.text)e.push(a.text);else if("image"===a.type&&a.source&&a.source.url){const t=a.source.url;try{const{filePath:a}=await downloadFile(t,n,!1);logger.info(`Downloaded image from ${t} to ${a}`),e.push(`Image: ${a}`)}catch(e){logger.error(`Failed to download image from ${t}:`,e)}}else if("document"===a.type&&a.source&&a.source.url){const t=a.source.url;try{const{filePath:s,mimeType:i,filename:o}=await downloadFile(t,n,!0);logger.info(`Downloaded document from ${t} to ${s}`);const r=a.title||o;e.push(`Document: ${s}\nTitle: ${r}\nType: ${i}`)}catch(e){logger.error(`Failed to download document from ${t}:`,e)}}const a=e.map(e=>e.trim()).filter(Boolean).join("\n\n").trim();if(a)return a}return""}stopTask(e){this.isStopping||(this.isStopping=!0,"oneshot_complete"===e&&(this.exitReason="oneshot_complete",logger.info("One-shot execution completed, stopping task")),"idle"===e?(this.exitReason="idle_timeout",logger.info("worker.stop.requested reason=idle_timeout source=codex_worker")):"ask_user_timeout"===e&&(this.exitReason="ask_user_timeout",logger.info("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 a=this.options.input.agentId,s=this.options.input.taskAgents?.find(e=>e.id===a)?.name;return{config:{userId:e,taskId:t,chatId:this.options.input.chatId,machineId:this.credentials.machineId,agentId:a,agentName:s,cwd:n,serverUrl:machine.machine.serverUrl.replace(/^http/,"ws"),path:"/v1/ws",auth:shared.workerAuth(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:shared.createEventId(),status:n,taskId:t,machineId:this.credentials.machineId,timestamp:Date.now().toString()}}},healthCheckConfig:{enabled:!0,intervalMs:3e4,timeoutMs:5e3}},handlers:{attachmentsDir:machine.machine.resolveAttachmentsDir(e,t),stopTask:async()=>{this.stopTask("event")},onTaskMessage:async e=>{if(shared.isAskUserResponseMessage(e)){const[t,n]=this.askUserAwaiter.entries().next().value||[];return void(t&&n&&(this.askUserAwaiter.delete(t),n(e)))}shared.isSDKMessage(e)&&"user"===e.type&&await this.coordinator.enqueue(e)},onTaskInfoUpdate:async e=>{const t=this.options.input.model;await applyTaskInfoUpdate(e,this.options.input,this.workspace),t!==this.options.input.model&&Object.prototype.hasOwnProperty.call(e.updates??{},"model")&&(this.currentModel=resolveCodexModel(this.options.input.model),logger.info(`Task model updated from ${t??"default"} to ${this.options.input.model??"default"}; applying to subsequent Codex turns`))},onReconnect:async()=>{this.sendCurrentWorkerStatus()},onWorkerStatusRequest:async()=>{this.sendCurrentWorkerStatus()}}}}async exitWorker(e,t){this.coordinator&&this.coordinator.stop(),logger.info(`worker.exit reason=${e} taskId=${this.taskId} totalMs=${this.workerStartedAt?Date.now()-this.workerStartedAt:"unknown"}`);const n=this.context?.workClient??this.workClient;n&&("error"===e&&t?await n.sendErrorMessageAndExit(t):(n.sendWorkerExit(e),await n.disconnect()),this.historyDb&&this.historyDb.close())}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=>{logger.warn("Failed to write patch diff for result:",e)}});t=e.artifacts,n=e.artifactVersion}catch(e){logger.warn("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 markArtifactVersionAsSent(this.options.input.userId,this.taskId,n)}catch(e){logger.warn("Failed to mark artifact version as sent:",e)}}}async function runCodex(e,t){const n=new CodexWorker(e,t);await n.start()}function createWorkerClient$2(e,t,n){const a=machine.machine.serverUrl.replace(/^http/,"ws");return socket_ioClient.io(a,{path:"/v1/ws",transports:["websocket"],auth:{token:e.token,clientType:"worker",machineId:e.machineId,taskId:n}})}async function runDeployment(e,t){const n=t.input,{taskId:a,sourcePath:s,targetAgentId:i,userId:o,name:r,avatar:c,isSystemAgent:l,supportLocal:d}=n;let p=null;try{if(console.log(`[Deployment] Starting deployment worker for task ${a}`),!fs.existsSync(s))throw new Error(`Source path not found: ${s}`);const t=path.join(machine.machine.agentrixAgentsHomeDir,i);if(fs.existsSync(t))throw new Error(`Target agent directory already exists: ${t}`);console.log(`[Deployment] Copying from ${s} to ${t}`),await copyDirectory(s,t),console.log("[Deployment] Deployment completed successfully"),p=createWorkerClient$2(e,o,a),await new Promise((e,t)=>{const n=setTimeout(()=>{t(new Error("WebSocket connection timeout"))},1e4);p.on("connect",()=>{clearTimeout(n),console.log("[Deployment] Connected to server"),p.emit("deploy-agent-complete",{eventId:shared.createEventId(),taskId:a,targetAgentId:i,success:!0,name:r,avatar:c,isSystemAgent:l,supportLocal:d}),console.log("[Deployment] Sent deploy-agent-complete event"),setTimeout(()=>{e()},1e3)}),p.on("connect_error",e=>{clearTimeout(n),t(e)})})}catch(e){throw console.error("[Deployment] Deployment failed:",e),p&&p.connected&&(p.emit("deploy-agent-complete",{eventId:shared.createEventId(),taskId:a,targetAgentId:i,success:!1,error:e instanceof Error?e.message:String(e)}),await new Promise(e=>setTimeout(e,1e3))),e}finally{p&&p.disconnect(),process.exit(0)}}function resolveClaudePath(){const e=process.env.AGENTRIX_CLAUDE_PATH?.trim();if(!e)return;if(e.includes("/")||e.includes("\\")||e.startsWith(".")){const t=path.isAbsolute(e)?e:path.resolve(e);return fs.existsSync(t)?t:void 0}const t="win32"===process.platform?"where":"which",n=node_child_process.spawnSync(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 normalizeReviewTags(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 createReviewTool(e){return claudeAgentSdk.tool("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:zod.z.boolean().describe("true if the code passes security review, false if it must be rejected"),reasons:zod.z.array(zod.z.string()).describe("If rejected: list each specific issue found. If approved: briefly state what was checked."),tags:zod.z.array(zod.z.string()).describe("3-8 concise marketplace discovery tags describing the agent or skill capability. Use lowercase kebab-case.")},async t=>(e({approved:t.approved,reasons:t.reasons,tags:normalizeReviewTags(t.tags)}),{content:[{type:"text",text:"Review decision recorded."}]}))}function collectFileList(e,t=""){const n=fs.readdirSync(e,{withFileTypes:!0}),a=[];for(const s of n){const n=t?`${t}/${s.name}`:s.name;"node_modules"!==s.name&&".git"!==s.name&&(s.isDirectory()?a.push(...collectFileList(path.join(e,s.name),n)):a.push(n))}return a}const REVIEW_SYSTEM_PROMPT='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 real publish-blocking security issues:\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 that appear to be user data or sensitive personal data\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 or instructions that abuse permissions to access sensitive files, steal data, persist malware, or operate outside the intended agent/skill workflow\n\nAgentrix-specific review guidance:\n- Do NOT reject solely because an agent config uses permissionMode "bypassPermissions".\n- Do NOT reject solely because allowedTools includes Bash, WebFetch, Read, Write, Edit, or other normal Agentrix/Claude tools. These tools are part of the Agentrix runtime model.\n- Reject permission usage only when the source contains malicious or clearly unsafe behavior, such as reading secrets from home directories, scanning unrelated user files, silently uploading data, destructive shell commands, persistence, credential theft, or instructions to bypass user intent.\n- Generated/local build metadata such as avatar/upload-avatar.json may contain local file paths or localhost URLs from the creator\'s machine. Treat these as cleanup suggestions, not publish-blocking security issues, unless they contain secrets or sensitive personal data beyond ordinary development paths.\n- Ordinary repository paths, localhost URLs, sample usernames in paths, generated artifact paths, and non-secret build cache metadata are not enough to reject a publish request.\n- If you find non-blocking cleanup suggestions, include them in reasons while still approving.\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 about real security issues, but do not reject normal Agentrix runtime configuration or harmless generated local metadata. Approve when there is no credible exploit, secret, malicious behavior, or sensitive user-data exposure.';async function reviewHivePublish(e,t,n){const a=collectFileList(e).map(e=>` - ${e}`).join("\n");return new Promise((s,i)=>{let o=!1,r=null;const c=e=>{o||(o=!0,clearTimeout(d),s(e))},l=e=>{o||(o=!0,clearTimeout(d),i(e))},d=setTimeout(()=>{c({approved:!1,reasons:["Review timed out after 10 minutes"],tags:[]})},6e5),p=createReviewTool(e=>{r=e,c(e)}),u=claudeAgentSdk.createSdkMcpServer({name:"hive_review",version:"1.0.0",tools:[p]}),m=[`Review the ${n} "${t}" for security issues before publishing to Hive.`,"",`Source directory: ${e}`,"","Files to review:",a,"","Read each file, then call mcp__hive_review__hive_publish_review with your decision."].join("\n"),h=claudeAgentSdk.query({prompt:m,options:{systemPrompt:REVIEW_SYSTEM_PROMPT,permissionMode:"bypassPermissions",settingSources:["user","project","local"],maxTurns:30,cwd:e,mcpServers:{hive_review:u},pathToClaudeCodeExecutable:resolveClaudePath(),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 execFileAsync$1=node_util.promisify(node_child_process.execFile);function createWorkerClient$1(e,t,n){const a=machine.machine.serverUrl.replace(/^http/,"ws");return socket_ioClient.io(a,{path:"/v1/ws",transports:["websocket"],auth:{token:e.token,clientType:"worker",machineId:e.machineId,taskId:n}})}async function git$1(e,...t){const{stdout:n}=await execFileAsync$1("git",t,{cwd:e});return n.trim()}async function hasStagedChanges(e){try{return await execFileAsync$1("git",["diff","--cached","--quiet"],{cwd:e}),!1}catch(e){if("number"==typeof e?.code&&1===e.code)return!0;throw e}}function slugifyName(e){return e.toLowerCase().replace(/[^a-z0-9-]/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,"")||"skill"}function parseSkillMetadata(e){const t=path.join(e,"SKILL.md"),n=fs.readFileSync(t,"utf-8"),a=n.match(/^---\r?\n([\s\S]*?)\r?\n---\r?\n?/);if(!a)throw new Error("SKILL.md must start with YAML frontmatter containing name and description");const s=a[1],i=new Map;for(const e of s.split(/\r?\n/)){const t=e.match(/^([A-Za-z0-9_-]+):\s*(.*)$/);t&&i.set(t[1],t[2].replace(/^["']|["']$/g,"").trim())}const o=i.get("name"),r=i.get("description");if(!o)throw new Error("SKILL.md frontmatter must include name");if(!r)throw new Error("SKILL.md frontmatter must include description");return{name:slugifyName(o),displayName:o,description:r,readme:n,repoDirName:slugifyName(o)}}function validateHivePublishSource(e,t){if(!fs.existsSync(e))throw new Error(`Source directory not found: ${e}`);if(!fs.statSync(e).isDirectory())throw new Error(`Source path is not a directory: ${e}`);if("skill"===t&&!fs.existsSync(path.join(e,"SKILL.md")))throw new Error(`Skill directory must contain SKILL.md: ${e}`)}async function runHivePublish(e,t){const n=t.input,{taskId:a,listingId:s,userId:i,sourceDir:o,gitUrl:r,version:c}=n;let l,d,{repoDir:p,name:u}=n,m=n.displayName,h=n.description,g=n.readme,f=null,y=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 ${a}, name=${u}`),validateHivePublishSource(o,n.type),"skill"===n.type){const e=parseSkillMetadata(o);u=e.name,m=e.displayName,h=e.description,g=e.readme,p=path.posix.join(p,e.repoDirName),console.log(`[HivePublish] Parsed skill metadata name=${u}, displayName=${m}`)}y=path.join(machine.machine.agentrixHomeDir,"tmp","hive-publish",a),fs.mkdirSync(y,{recursive:!0}),console.log("[HivePublish] Cloning hive repo..."),await git$1(y,"clone","--depth","1",r,".");const t=path.join(y,p);if(fs.mkdirSync(path.dirname(t),{recursive:!0}),"skill"===n.type&&fs.existsSync(t))throw new Error(`Skill already exists in Hive repository: ${p}`);fs.existsSync(t)&&fs.rmSync(t,{recursive:!0,force:!0}),console.log(`[HivePublish] Copying ${o} → ${p}`),await copyDirectory(o,t),fs.writeFileSync(path.join(t,"agentrix-hive-id.txt"),`${s}\n`,"utf-8"),await git$1(y,"add",".");const v=await hasStagedChanges(y);if(v){console.log("[HivePublish] Running Claude security review...");const e=await reviewHivePublish(o,u,n.type);if(l=e.reasons,d=e.tags,!e.approved)throw new Error(`Security review rejected: ${e.reasons.join("; ")}`);console.log("[HivePublish] Security review passed");const t=`publish: ${p} v${c}`;await git$1(y,"commit","-m",t),console.log("[HivePublish] Pushing to remote..."),await git$1(y,"push")}else console.log("[HivePublish] No git changes to publish; using existing HEAD");const b=await git$1(y,"rev-parse","HEAD");console.log(`[HivePublish] Push succeeded, commit=${b}`),f=createWorkerClient$1(e,i,a),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:shared.createEventId(),taskId:a,listingId:s,success:!0,gitCommitHash:b,hasChanges:v,tags:d,name:u,displayName:m,description:h,readme:g,repoDir:p}),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??createWorkerClient$1(e,i,a),await new Promise(e=>{const n=setTimeout(e,5e3),i=()=>{f.emit("hive-publish-complete",{eventId:shared.createEventId(),taskId:a,listingId:s,success:!1,error:t instanceof Error?t.message:String(t),reviewReasons:l}),clearTimeout(n),setTimeout(e,1e3)};f.connected?i():(f.on("connect",i),f.on("connect_error",()=>{clearTimeout(n),e()}))})}catch{console.error("[HivePublish] Failed to send error event")}throw t}finally{if(f&&f.disconnect(),y&&fs.existsSync(y))try{fs.rmSync(y,{recursive:!0,force:!0})}catch{}process.exit(0)}}const execFileAsync=node_util.promisify(node_child_process.execFile);function createWorkerClient(e,t,n){const a=machine.machine.serverUrl.replace(/^http/,"ws");return socket_ioClient.io(a,{path:"/v1/ws",transports:["websocket"],auth:{token:e.token,clientType:"worker",machineId:e.machineId,taskId:n}})}async function git(e,...t){const{stdout:n}=await execFileAsync("git",t,{cwd:e});return n.trim()}function resolveInstallDir(e){return e.startsWith("~/")?path.join(process.env.HOME||"",e.slice(2)):path.isAbsolute(e)?e:path.join(machine.machine.agentrixHomeDir,e)}async function runHiveInstall(e,t){const n=t.input,{taskId:a,userId:s,sourceRepoDir:i,gitUrl:o,name:r,sourceType:c}=n,l=n.installDir??n.draftAgentDir;let d=null,p=null;try{console.log(`[HiveInstall] Starting for task ${a}, name=${r}`),p=path.join(machine.machine.agentrixHomeDir,"tmp","hive-install",a),fs.mkdirSync(p,{recursive:!0}),console.log("[HiveInstall] Cloning hive repo..."),await git(p,"clone","--depth","1",o,".");const t=path.join(p,i);if(!fs.existsSync(t))throw new Error(`Source directory not found in hive repo: ${i}`);if("skill"===c&&!fs.existsSync(path.join(t,"SKILL.md")))throw new Error(`Skill directory must contain SKILL.md: ${i}`);const n=resolveInstallDir(l);if(fs.existsSync(n))throw new Error(`Target install directory already exists: ${n}`);if(fs.mkdirSync(n,{recursive:!0}),console.log(`[HiveInstall] Copying ${i} → ${n}`),await copyDirectory(t,n),"agent"===c)try{console.log(`[HiveInstall] Building agent plugins/hooks in ${n}`),buildAgentPlugins(n)}catch(e){try{fs.rmSync(n,{recursive:!0,force:!0})}catch{}throw e}const u=path.join(n,".git");fs.existsSync(u)&&(fs.rmSync(u,{recursive:!0,force:!0}),console.log("[HiveInstall] Removed .git from installed directory")),console.log("[HiveInstall] Install completed successfully"),d=createWorkerClient(e,s,a),await new Promise((e,t)=>{const s=setTimeout(()=>t(new Error("WebSocket connection timeout")),1e4);d.on("connect",()=>{clearTimeout(s),d.emit("hive-install-complete",{eventId:shared.createEventId(),taskId:a,success:!0,agentDir:n}),console.log("[HiveInstall] Sent hive-install-complete (success)"),setTimeout(e,1e3)}),d.on("connect_error",e=>{clearTimeout(s),t(e)})})}catch(t){console.error("[HiveInstall] Failed:",t);try{d=d??createWorkerClient(e,s,a),await new Promise(e=>{const n=setTimeout(e,5e3),s=()=>{d.emit("hive-install-complete",{eventId:shared.createEventId(),taskId:a,success:!1,error:t instanceof Error?t.message:String(t)}),clearTimeout(n),setTimeout(e,1e3)};d.connected?s():(d.on("connect",s),d.on("connect_error",()=>{clearTimeout(n),e()}))})}catch{console.error("[HiveInstall] Failed to send error event")}throw t}finally{if(d&&d.disconnect(),p&&fs.existsSync(p))try{fs.rmSync(p,{recursive:!0,force:!0})}catch{}process.exit(0)}}async function runCompanion(e,t){const{agentDir:n,homeDir:a}=await ensureCompanionAgent();t.input.agentDir=n,process.env.AGENTRIX_COMPANION_HOME=a;const s=buildWorkspaceOptions(t.input),i=await CwdCalculator.calculateFinalCwd(s),o=new ClaudeWorker(e,t,i);await o.start()}const workerTypes=["claude","codex","deployment","companion","hive-publish","hive-install"],workerRegistry={claude:{async run({credentials:e,startedBy:t,userId:n,taskId:a,idleTimeoutSecond:s}){const i=machine.machine.readTaskInput(n,a),o=i.dataEncryptionKey?shared.decodeBase64(i.dataEncryptionKey):null;if(o&&32!==o.length)throw new Error("Invalid dataEncryptionKey: expected decrypted 32-byte key");const r={startedBy:t,idleTimeoutSecond:s,input:i,dataEncryptionKey:o};await runClaude(e,r)}},codex:{async run({credentials:e,startedBy:t,userId:n,taskId:a,idleTimeoutSecond:s}){const i=machine.machine.readTaskInput(n,a),o=i.dataEncryptionKey?shared.decodeBase64(i.dataEncryptionKey):null;if(o&&32!==o.length)throw new Error("Invalid dataEncryptionKey: expected decrypted 32-byte key");const r={startedBy:t,idleTimeoutSecond:s,input:i,dataEncryptionKey:o};await runCodex(e,r)}},deployment:{async run({credentials:e,startedBy:t,userId:n,taskId:a,idleTimeoutSecond:s}){const i={input:machine.machine.readTaskInput(n,a)};await runDeployment(e,i)}},"hive-publish":{async run({credentials:e,startedBy:t,userId:n,taskId:a,idleTimeoutSecond:s}){const i={input:machine.machine.readTaskInput(n,a)};await runHivePublish(e,i)}},"hive-install":{async run({credentials:e,startedBy:t,userId:n,taskId:a,idleTimeoutSecond:s}){const i={input:machine.machine.readTaskInput(n,a)};await runHiveInstall(e,i)}},companion:{async run({credentials:e,startedBy:t,userId:n,taskId:a,idleTimeoutSecond:s}){const i=machine.machine.readTaskInput(n,a),o=i.dataEncryptionKey?shared.decodeBase64(i.dataEncryptionKey):null;if(o&&32!==o.length)throw new Error("Invalid dataEncryptionKey: expected decrypted 32-byte key");const r={startedBy:t,idleTimeoutSecond:s,input:i,dataEncryptionKey:o};await runCompanion(e,r)}}};async function fetchAgentGitUrl(e,t){const n=`${machine.machine.serverUrl}/v1/agents/${encodeURIComponent(e)}/git-url`,a=await fetch(n,{headers:{Authorization:`Bearer ${t.token}`}});return a.ok?a.json():null}function readAgentVersion(e){try{const t=fs.readFileSync(path.join(e,"agent.json"),"utf-8"),n=JSON.parse(t);return"string"==typeof n.version?n.version:null}catch{return null}}function isNewerVersion(e,t){const n=e=>e.split(".").map(e=>parseInt(e,10)||0),a=n(e),s=n(t);for(let e=0;e<Math.max(a.length,s.length);e++){const t=a[e]??0,n=s[e]??0;if(t>n)return!0;if(t<n)return!1}return!1}async function checkAgentUpdates(e){const t=machine.machine.agentrixAgentsHomeDir;if(!fs.existsSync(t))return;let n;try{n=fs.readdirSync(t).filter(e=>fs.statSync(path.join(t,e)).isDirectory())}catch{return}for(const a of n){if("companion"===a||a.startsWith("draftagent-")||a.includes("."))continue;const n=path.join(t,a),s=path.join(n,"upgrade");if(fs.existsSync(s))continue;const i=readAgentVersion(n);machine.logger.info(`[AGENT UPDATE] Checking ${a} (local version: ${i??"unknown"})`);try{const t=await fetchAgentGitUrl(a,e);if(!t||!t.gitUrl){machine.logger.info(`[AGENT UPDATE] No git repo for ${a}, skipping`);continue}const n=`${s}.tmp-${Date.now()}`;try{const e=["git","clone","--depth=1","--branch",t.branch,t.gitUrl,n];node_child_process.execSync(e.join(" "),{stdio:"pipe",timeout:12e4});const o=t.subDir?path.join(n,t.subDir):n;if(t.subDir&&!fs.existsSync(o))throw new Error(`subDir "${t.subDir}" not found in cloned repo`);const r=readAgentVersion(o);if(!r||i&&!isNewerVersion(r,i)){machine.logger.info(`[AGENT UPDATE] ${a} up to date (local: ${i??"unknown"}, remote: ${r??"unknown"})`),fs.rmSync(n,{recursive:!0,force:!0});continue}machine.logger.info(`[AGENT UPDATE] Update available for ${a}: ${i??"unknown"} → ${r}`),t.subDir?(fs.renameSync(o,s),fs.rmSync(n,{recursive:!0,force:!0})):fs.renameSync(n,s),machine.logger.info(`[AGENT UPDATE] Staged upgrade for ${a}`)}catch(e){throw fs.existsSync(n)&&fs.rmSync(n,{recursive:!0,force:!0}),e}}catch(e){machine.logger.warn(`[AGENT UPDATE] Check failed for ${a}: ${e}`)}}}function normalizeUrl(e,t){const n=e.trim();if(!n)throw new Error(`${t} is required`);let a;try{a=new URL(n)}catch{throw new Error(`${t} must be a valid URL`)}if("http:"!==a.protocol&&"https:"!==a.protocol)throw new Error(`${t} must use http or https`);return a.toString().replace(/\/+$/,"")}function defaultGitLabApiUrl(e){return`${normalizeUrl(e,"baseUrl")}/api/v4`}function readSecretInput(e){if("-"===e)return fs.readFileSync(0,"utf8").trim();if(!fs.existsSync(e))throw new Error(`File not found: ${e}`);return fs.readFileSync(e,"utf8").trim()}async function promptText(e,t){if(!node_process.stdin.isTTY){if(void 0!==t)return t;throw new Error(`${e} is required in non-interactive mode`)}const n=promises$3.createInterface({input:node_process.stdin,output:node_process.stdout});try{const a=t?` (${t})`:"";return(await n.question(`${e}${a}: `)).trim()||t||""}finally{n.close()}}async function promptSecret(e){return node_process.stdin.isTTY&&node_process.stdout.isTTY&&"function"==typeof node_process.stdin.setRawMode?new Promise((t,n)=>{let a="";const s=()=>{node_process.stdin.setRawMode(!1),node_process.stdin.pause(),node_process.stdin.off("data",i)},i=e=>{const i=e.toString("utf8");return""===i?(s(),node_process.stdout.write("\n"),void n(new Error("Interrupted"))):"\r"===i||"\n"===i?(s(),node_process.stdout.write("\n"),void t(a.trim())):void(""!==i&&"\b"!==i?a+=i:a=a.slice(0,-1))};node_process.stdout.write(`${e}: `),node_process.stdin.setRawMode(!0),node_process.stdin.resume(),node_process.stdin.on("data",i)}):promptText(e)}async function promptYesNo(e,t){if(!node_process.stdin.isTTY)return t;const n=(await promptText(`${e} (Y/n)`)).toLowerCase();return n?["y","yes"].includes(n):t}async function getEncryptionKey(){const e=await getGitServerEncryptionKey();if(!e)throw new Error("No Agentrix auth secret found. Run `agentrix start` and complete machine binding first.");return e}function parseStringArg(e){return"string"==typeof e&&e.trim()?e.trim():void 0}function parseBooleanArg(e){return"boolean"==typeof e?e:void 0}async function runAddCommand(e){const t=normalizeUrl(parseStringArg(e["base-url"])??await promptText("GitLab base URL"),"baseUrl"),n=normalizeUrl(parseStringArg(e["api-url"])??await promptText("GitLab API URL",defaultGitLabApiUrl(t)),"apiUrl"),a=new URL(t).hostname,s=parseStringArg(e.name)??await promptText("Git server name",a),i=(parseStringArg(e["pat-file"])?readSecretInput(parseStringArg(e["pat-file"])):void 0)??await promptSecret("GitLab PAT");if(!i)throw new Error("GitLab PAT is required");const o=parseBooleanArg(e.proxy)??await promptYesNo("Use this machine as a Git proxy node",!0),r=await bindGitServerViaDaemon({name:s,baseUrl:t,apiUrl:n,pat:i,useAsProxy:o});if(r.error||!r.success||!r.gitServer)throw new Error(`Git server add failed: ${r.error||"Daemon did not return a bound Git server"}`);const c=r.gitServer;console.log(JSON.stringify({id:c.id,type:"gitlab",baseUrl:c.baseUrl,apiUrl:c.apiUrl,webhookEndpointPath:r.webhookEndpointPath??node.buildGitLabWebhookEndpointPath(c.id),webhookUrl:r.webhookUrl??node.buildGitLabWebhookUrl(c.id,await machine.machine.readDaemonState()),backendRegistered:!0,proxyRegistered:r.proxyRegistered??o,patConfigured:!0,patMeta:r.patMeta??loadPatMeta(c.id),webhookSecret:r.webhookSecret},null,2))}function buildListItem(e,t,n){const a=loadGitServerConfig(e.id)??{},s=loadGitLabWebhookBridgeSecrets(e.id,t)??{};return{id:e.id,type:"gitlab",baseUrl:e.baseUrl||a.baseUrl,apiUrl:e.apiUrl||a.apiUrl,webhookEndpointPath:node.buildGitLabWebhookEndpointPath(e.id),webhookUrl:node.buildGitLabWebhookUrl(e.id,n),patConfigured:hasPat(e.id),patMeta:loadPatMeta(e.id),webhookSecret:s.webhookSecret,projectTriggerTokens:s.projectTriggerTokens??{}}}async function runListCommand(){const e=await getEncryptionKey(),t=await machine.machine.readDaemonState(),n=await listGitServersViaDaemon();if(n.error)throw new Error(`Backend Git server list failed: ${n.error}`);const a=(n.gitServers??[]).filter(e=>"gitlab"===e.type&&"local_pat"===e.authModeDefault).map(n=>buildListItem(n,e,t));console.log(JSON.stringify(a,null,2))}function handleCommandError(e){console.error(chalk.red("Error:"),e instanceof Error?e.message:"Unknown error"),process.env.DEBUG&&console.error(e),process.exit(1)}function registerGitServerCommands(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("name",{type:"string",describe:"Git server display name, defaults to the GitLab hostname"}).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("proxy",{type:"boolean",describe:"Register this machine as a Git proxy node (use --no-proxy to save PAT locally only)"}),async e=>{try{await runAddCommand(e),process.exit(0)}catch(e){handleCommandError(e)}}).command("list","List local private GitLab server config",{},async()=>{try{await runListCommand(),process.exit(0)}catch(e){handleCommandError(e)}}).demandCommand(1,"Please specify one of: add, list").strict(),()=>{})}const DEFAULT_CLAUDE_MODELS={primary:"claude-sonnet-4-6",fast:"claude-haiku-4-5",subagent:"claude-sonnet-4-6"},DEFAULT_CODEX_MODEL$1="gpt-5.5";function getFallbackAgentrixApiBaseUrl(){return process.env.OPENAPI_BASE_URL||process.env.AGENTRIX_OPENAPI_BASE_URL||machine.machine.serverUrl}async function fetchAgentrixApiBaseUrl(e){try{return(await axios.get(`${machine.machine.serverUrl}/v1/openapi-config`,{headers:{Authorization:`Bearer ${e.token}`},timeout:1e4})).data.baseUrl||getFallbackAgentrixApiBaseUrl()}catch(e){const t=e instanceof Error?e.message:"unknown error";return console.log(chalk.yellow(`Could not fetch Agentrix API URL from server, using fallback: ${t}`)),getFallbackAgentrixApiBaseUrl()}}function commandExists(e){return(process.env.PATH||"").split(":").filter(Boolean).some(t=>{try{return fs.accessSync(path.join(t,e),fs.constants.X_OK),!0}catch{return!1}})}function detectPackageManager(){return[{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=>commandExists(e.name))||null}function runCommand(e,t,n){return new Promise((a,s)=>{const i=node_child_process.spawn(e,t,{stdio:"inherit",shell:n?.shell||!1,env:process.env});i.on("error",s),i.on("close",t=>{0===t?a():s(new Error(`${e} exited with code ${t}`))})})}async function pathExists(e){try{return await promises$1.access(e),!0}catch{return!1}}function missingInstallableDeps(e){return e.filter(e=>e.required&&!e.installed)}async function installSystemDependencies(e){if(0===e.length)return void console.log(chalk.green("✓ System dependencies are installed"));if("linux"!==process.platform){console.log(chalk.yellow("Automatic dependency installation is currently only supported on Linux."));for(const t of e)console.log(chalk.yellow(`- ${t.name}: ${t.installCommand||"install manually"}`));return}const t=detectPackageManager();if(!t){console.log(chalk.yellow("No supported package manager found. Install these dependencies manually:"));for(const t of e)console.log(chalk.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(chalk.blue(`Installing system dependencies with ${t.name}: ${n.join(", ")}`));const a=t.installCommand(n);"apt-get"===t.name?await runCommand(a.join(" "),[],{shell:!0}):await runCommand(a[0],a.slice(1))}async function installNpmDependency(e,t){commandExists(e)?console.log(chalk.green(`✓ ${e} is installed`)):commandExists("npm")?(console.log(chalk.blue(`Installing ${e} with npm...`)),await runCommand("npm",["install","-g",t])):console.log(chalk.yellow(`npm is not available. Install ${t} manually.`))}async function ensureDependencies(){const e=checkAllDependencies(),t=[...missingInstallableDeps(e.cli.filter(e=>"claude"!==e.name)),...missingInstallableDeps(e.sandbox)];"linux"!==process.platform||commandExists("rg")||t.push({name:"ripgrep",installed:!1,required:!0,description:"Fast code search tool",installCommand:"sudo apt install ripgrep"}),await installSystemDependencies(t),await installNpmDependency("claude","@anthropic-ai/claude-code@latest"),await installNpmDependency("codex","@openai/codex@latest");const n=checkCriticalDependencies();if(!n.ok)throw new Error(`Missing critical dependencies after installation: ${n.missing.join(", ")}`)}async function askWithDefault(e,t,n){const a=n?` (${n})`:"";return(await e.question(`${t}${a}: `)).trim()||n||""}async function askYesNo(e,t,n=!0){const a=n?"Y/n":"y/N",s=(await e.question(`${t} (${a}): `)).trim().toLowerCase();return s?"y"===s||"yes"===s:n}async function askChoice(e,t,n,a){for(console.log(t),n.forEach((e,t)=>{const n=e.value===a?" default":"";console.log(` ${t+1}. ${e.label}${n}`)});;){const t=(await e.question("Select: ")).trim();if(!t)return a;const s=Number.parseInt(t,10);if(!Number.isNaN(s)&&n[s-1])return n[s-1].value;const i=n.find(e=>e.value===t);if(i)return i.value;console.log(chalk.yellow("Invalid selection"))}}async function writeClaudeConfig(e,t,n){const a=path.join(machine.machine.claudeConfigDir,"settings.json");if(!t&&await pathExists(a)&&!await askYesNo(e,`Claude config already exists at ${a}. Overwrite`,!1))return void console.log(chalk.gray("Skipped Claude config"));const s=await askChoice(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"===s)return void console.log(chalk.gray("Skipped Claude config"));const i={};if("official"===s)i.ANTHROPIC_API_KEY=await askWithDefault(e,"Anthropic API key");else if("agentrix"===s)i.ANTHROPIC_BASE_URL=n,i.ANTHROPIC_AUTH_TOKEN=await askWithDefault(e,"Agentrix API key for Claude");else{const t=await askWithDefault(e,"Anthropic-compatible base URL");i.ANTHROPIC_BASE_URL=t,i.ANTHROPIC_AUTH_TOKEN=await askWithDefault(e,"Anthropic auth token")}const o=await askWithDefault(e,"Claude primary model",DEFAULT_CLAUDE_MODELS.primary),r=await askWithDefault(e,"Claude fast model",DEFAULT_CLAUDE_MODELS.fast),c=await askWithDefault(e,"Claude subagent model",o||DEFAULT_CLAUDE_MODELS.subagent);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 promises$1.mkdir(machine.machine.claudeConfigDir,{recursive:!0}),await promises$1.writeFile(a,JSON.stringify({env:i,model:o},null,2),"utf-8"),console.log(chalk.green(`✓ Wrote Claude config: ${a}`))}function tomlString$1(e){return JSON.stringify(e)}function buildCodexToml$1(e){const t=e.provider,n=[`model = ${tomlString$1(e.model)}`,`model_provider = ${tomlString$1(t)}`,"",`[model_providers.${t}]`,`name = ${tomlString$1("agentrix"===t?"Agentrix":"openai"===t?"Openai":"Custom")}`,`wire_api = ${tomlString$1(e.wireApi)}`];if(e.baseUrl){const a="agentrix"===t?e.baseUrl.replace(/\/+$/,"")+"/v1":e.baseUrl;n.push(`base_url = ${tomlString$1(a)}`)}return e.envKey&&n.push(`env_key = ${tomlString$1(e.envKey)}`),`${n.join("\n")}\n`}function writeDaemonEnvVars(e){const t=machine.machine.readOrInitSettings({sandbox:machine.machine.getSandboxSettings(),daemonEnv:{enabled:!1,variables:{}},daemonControl:{allowLanAccess:!1},allowDirectBash:!0}),n=t.daemonEnv||{enabled:!1,variables:{}},a={...n.variables||{},...e};machine.machine.writeSettings({...t,daemonEnv:{...n,enabled:!0,variables:a}});for(const[t,n]of Object.entries(e))process.env[t]=n}async function writeCodexConfig(e,t,n){const a=path.join(machine.machine.codexHomeDir,"config.toml");if(!t&&await pathExists(a)&&!await askYesNo(e,`Codex config already exists at ${a}. Overwrite`,!1))return void console.log(chalk.gray("Skipped Codex config"));const s=await askChoice(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"===s)return void console.log(chalk.gray("Skipped Codex config"));const i=await askWithDefault(e,"Codex model","gpt-5.5"),o=await askChoice(e,"Codex API wire format",[{value:"responses",label:"Responses API"},{value:"chat",label:"Chat Completions API"}],"agentrix"===s?"responses":"chat"),r={};let c,l;"agentrix"===s?(c=n,l="AGENTRIX_API_KEY",r[l]=await askWithDefault(e,"Agentrix API key for Codex")):"openai"===s?(l="OPENAI_API_KEY",r[l]=await askWithDefault(e,"OpenAI API key")):(c=await askWithDefault(e,"Custom OpenAI-compatible base URL"),l="CUSTOM_API_KEY",r[l]=await askWithDefault(e,"Custom API key")),await promises$1.mkdir(machine.machine.codexHomeDir,{recursive:!0}),await promises$1.writeFile(a,buildCodexToml$1({provider:s,baseUrl:c||void 0,envKey:l,model:i,wireApi:o}),"utf-8"),writeDaemonEnvVars(r),console.log(chalk.green(`✓ Wrote Codex config: ${a}`)),console.log(chalk.green(`✓ Wrote Codex env vars to ${machine.machine.getStatePaths().settingsFile}`))}async function configureLlm(e,t){const n=await fetchAgentrixApiBaseUrl(t),a=promises$3.createInterface({input:node_process.stdin,output:node_process.stdout});try{await writeClaudeConfig(a,e,n),await writeCodexConfig(a,e,n)}finally{a.close()}}async function startDaemonIfNeeded(){if(await isLatestDaemonRunning())console.log(chalk.green("✓ Daemon is already running"));else{console.log(chalk.blue("Starting Agentrix daemon...")),spawnAgentrixCLI(["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 checkIfDaemonRunningAndCleanupStaleState())return void console.log(chalk.green("✓ Daemon started successfully"));console.log(chalk.yellow("Daemon may still be starting. Run `agentrix status` to check."))}}async function runInitCommand(e={}){console.log(chalk.bold("\nAgentrix CLI initialization\n")),e.skipDeps||await ensureDependencies();const t=await authAndSetupMachineIfNeeded();await configureLlm(Boolean(e.force),t),e.skipDaemon||await startDaemonIfNeeded(),console.log(chalk.green("\n✓ Agentrix CLI initialization complete"))}function registerInitCommand(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 runInitCommand({skipDeps:e.skipDeps,skipDaemon:e.skipDaemon,force:e.force}),process.exit(0)}catch(e){console.error(chalk.red("Error:"),e instanceof Error?e.message:"Unknown error"),process.env.DEBUG&&console.error(e),process.exit(1)}})}const DEFAULT_LLM_BASE_URL="https://api.xmz.ai",DEFAULT_CODEX_MODEL="gpt-5.5",DEFAULT_CODEX_APPROVAL_POLICY="never",DEFAULT_CODEX_REASONING_EFFORT="high",DEFAULT_CLAUDE_MODEL="claude-sonnet-4-6",DEFAULT_CLAUDE_FAST_MODEL="claude-haiku-4-5",DEFAULT_GEMINI_IMAGE_MODEL="gemini-2.5-flash-image";function readEnv(e,t){const n=e[t]?.trim();return n||void 0}function resolveHomePath(e){return e.replace(/^~(?=\/|$)/,os.homedir())}function normalizeBaseUrl(e){const t=e.trim().replace(/\/+$/,"");try{const e=new URL(t);if("http:"!==e.protocol&&"https:"!==e.protocol)throw new Error("unsupported protocol")}catch{throw new Error("AGENTRIX_BASE_URL must be a valid http(s) URL")}return t}function toOpenAICompatibleBaseUrl(e){return`${e.replace(/\/+$/,"")}/v1`}async function readSecretFile(e){try{return(await promises$1.readFile(resolveHomePath(e),"utf-8")).replace(/[\r\n]/g,"")}catch{throw new Error(`AGENTRIX_API_KEY_FILE is set but is not readable: ${e}`)}}async function resolveApiKey(e){const t=readEnv(e,"AGENTRIX_API_KEY");if(t)return t;const n=readEnv(e,"AGENTRIX_API_KEY_FILE");if(!n)return;return(await readSecretFile(n)).trim()||void 0}async function resolveConfig(e){const t=resolveHomePath(readEnv(e,"AGENTRIX_HOME_DIR")||readEnv(e,"AGENTRIX_DIR")||path.join(os.homedir(),".agentrix")),n=resolveHomePath(readEnv(e,"AGENTRIX_CLAUDE_HOME")||path.join(os.homedir(),".claude")),a=resolveHomePath(readEnv(e,"AGENTRIX_CODEX_HOME")||path.join(os.homedir(),".codex")),s=resolveHomePath(readEnv(e,"AGENTRIX_GEMINI_HOME")||path.join(t,"config","gemini")),i=readEnv(e,"AGENTRIX_CLAUDE_MODEL")||"claude-sonnet-4-6";return{agentrixHomeDir:t,claudeConfigDir:n,codexHomeDir:a,geminiConfigDir:s,baseUrl:normalizeBaseUrl(readEnv(e,"AGENTRIX_BASE_URL")||"https://api.xmz.ai"),apiKey:await resolveApiKey(e),codexModel:readEnv(e,"AGENTRIX_CODEX_MODEL")||"gpt-5.5",claudeModel:i,claudeFastModel:readEnv(e,"AGENTRIX_CLAUDE_FAST_MODEL")||"claude-haiku-4-5",claudeSubagentModel:readEnv(e,"AGENTRIX_CLAUDE_SUBAGENT_MODEL")||i,geminiImageModel:readEnv(e,"AGENTRIX_GEMINI_IMAGE_MODEL")||"gemini-2.5-flash-image"}}function tomlString(e){return JSON.stringify(e)}function buildClaudeSettings(e,t){return`${JSON.stringify({env:{ANTHROPIC_BASE_URL:e.baseUrl,ANTHROPIC_AUTH_TOKEN:t,ANTHROPIC_MODEL:e.claudeModel,CLAUDE_CODE_SUBAGENT_MODEL:e.claudeSubagentModel,ANTHROPIC_SMALL_FAST_MODEL:e.claudeFastModel,ANTHROPIC_DEFAULT_OPUS_MODEL:"claude-opus-4-6",ANTHROPIC_DEFAULT_SONNET_MODEL:"claude-sonnet-4-6",ANTHROPIC_DEFAULT_HAIKU_MODEL:"claude-haiku-4-5"},model:e.claudeModel},null,2)}\n`}function buildCodexToml(e){return`${[`model = ${tomlString(e.codexModel)}`,'model_provider = "agentrix"',`approval_policy = ${tomlString("never")}`,`model_reasoning_effort = ${tomlString("high")}`,"","[model_providers.agentrix]",'name = "Agentrix"','wire_api = "responses"',`base_url = ${tomlString(toOpenAICompatibleBaseUrl(e.baseUrl))}`,'env_key = "AGENTRIX_API_KEY"'].join("\n")}\n`}function buildGeminiSettings(e,t){return`${JSON.stringify({connectionMode:"gemini-compatible",baseUrl:e.baseUrl,apiKey:t,imageModel:e.geminiImageModel},null,2)}\n`}function buildTargetFiles(e,t){return[{kind:"claude",path:path.join(e.claudeConfigDir,"settings.json"),content:buildClaudeSettings(e,t)},{kind:"codex",path:path.join(e.codexHomeDir,"config.toml"),content:buildCodexToml(e)},{kind:"gemini",path:path.join(e.geminiConfigDir,"settings.json"),content:buildGeminiSettings(e,t)}]}function configNeedsApiKey(e,t){return!(!t&&fs.existsSync(path.join(e.claudeConfigDir,"settings.json"))&&fs.existsSync(path.join(e.codexHomeDir,"config.toml"))&&fs.existsSync(path.join(e.geminiConfigDir,"settings.json")))}async function applyLlmAutoConfig(e={}){const t=e.env||process.env,n=!0===e.force,a=!0===e.dryRun,s=await resolveConfig(t);if(configNeedsApiKey(s,n)&&!s.apiKey)throw new Error("AGENTRIX_API_KEY is required to generate missing LLM config files");s.apiKey&&(t.AGENTRIX_API_KEY=s.apiKey);const i=buildTargetFiles(s,s.apiKey||""),o=[];for(const e of i)n||!fs.existsSync(e.path)?(o.push({kind:e.kind,path:e.path,action:"write"}),a||(await promises$1.mkdir(path.dirname(e.path),{recursive:!0}),await promises$1.writeFile(e.path,e.content,"utf-8"))):o.push({kind:e.kind,path:e.path,action:"skip"});return{dryRun:a,files:o,env:s.apiKey?{AGENTRIX_API_KEY:s.apiKey}:{}}}function formatAction(e,t){return"skip"===e?"skip":t?"would write":"write"}function registerLlmConfigCommand(e){e.command("llm-config apply","Generate Claude, Codex, and Gemini config from Agentrix environment variables",e=>e.option("source",{type:"string",choices:["env"],default:"env",describe:"Configuration source"}).option("force",{type:"boolean",default:!1,describe:"Overwrite existing LLM config files"}).option("dry-run",{type:"boolean",default:!1,describe:"Show planned writes without changing files"}).option("verbose",{type:"boolean",default:!1,describe:"Show detailed file actions"}),async e=>{try{const t=await applyLlmAutoConfig({force:!0===e.force,dryRun:!0===e.dryRun,env:process.env}),n=t.files.filter(e=>"write"===e.action).length,a=t.files.filter(e=>"skip"===e.action).length,s=t.dryRun?"LLM config dry run":"LLM config applied";if(console.log(chalk.green(`✓ ${s}: ${n} write(s), ${a} skipped`)),!0===e.verbose||t.dryRun)for(const e of t.files)console.log(`${formatAction(e.action,t.dryRun)} ${e.kind}: ${e.path}`);t.env.AGENTRIX_API_KEY&&console.log(chalk.gray("AGENTRIX_API_KEY prepared for this process.")),process.exit(0)}catch(e){console.error(chalk.red("Error:"),e instanceof Error?e.message:"Unknown error"),process.env.DEBUG&&console.error(e),process.exit(1)}})}async function runStorageCleanWorker(e){const{opCode:t,emit:n}=e,a=new Set(e.activeTaskIds??[]),s={releasedBytes:0,deletedCount:0,skippedCount:0,failedCount:0,dryRunCount:0};n({type:"started",opCode:t,itemCount:e.items.length,startedAt:(new Date).toISOString()});for(const i of e.items){n({type:"item-validating",opCode:t,relativePath:i.relativePath});const o=await planCleanItem(i.relativePath,a);if(o.releasable)if(n({type:"item-cleaning",opCode:t,relativePath:o.relativePath,method:o.method}),e.dryRun)s.dryRunCount+=1,n({type:"item-completed",opCode:t,relativePath:o.relativePath,releasedBytes:0,method:o.method});else try{const e=await executeCleanPlan(o);s.releasedBytes+=e,s.deletedCount+=1,n({type:"item-completed",opCode:t,relativePath:o.relativePath,releasedBytes:e,method:o.method})}catch(e){s.failedCount+=1,n({type:"item-failed",opCode:t,relativePath:o.relativePath,errorCode:"delete_failed",message:e instanceof Error?e.message:"Failed to clean item"})}else s.skippedCount+=1,n({type:"item-skipped",opCode:t,relativePath:o.relativePath,reasonCode:o.reasonCode,message:o.message})}return n({type:"completed",opCode:t,summary:{...s},result:{summary:{...s}},completedAt:(new Date).toISOString()}),s}const CATEGORY_LABELS={workspaces:"Task workspaces",logs:"Logs",tmp:"Temporary files",repos:"Repository store",runtime:"Runtime assets",monitor:"Monitor data",config:"Configuration",other:"Other"},DAY_MS=864e5,TASK_LOG_PATTERN=/^task-(.+)\.log(?:\.\d+)?(?:\.gz)?$/;function category(e){return{kind:e,label:CATEGORY_LABELS[e],bytes:0,reclaimableBytes:0,itemCount:0}}function taskTimestamp(e){const t=e.state?.initializedAt?Date.parse(e.state.initializedAt):Number.NaN;return Number.isFinite(t)?t:fs.statSync(e.taskDir).mtimeMs}function parseTaskIdFromLogName(e){return TASK_LOG_PATTERN.exec(e)?.[1]??null}function completeCategory(e){return{kind:e.kind,label:e.label,bytes:e.bytes,reclaimableBytes:e.reclaimableBytes,itemCount:e.itemCount}}async function addItem(e,t,n,a,s){n.bytes+=s.bytes,n.itemCount+=1,s.reclaimable&&(n.reclaimableBytes+=s.bytes),a.push(s),t({type:"item",opCode:e,item:s})}async function scanWorkspaces(e,t,n,a,s){const i=category("workspaces");t({type:"category-started",opCode:e,kind:i.kind,label:i.label});const o=Date.now()-s*DAY_MS;for(const s of listWorkspaceTasks()){const r=n.has(s.taskId),c=isDirectUserDirectoryWorkspace(s.state),l=!r&&!c&&taskTimestamp(s)<o,d=r?{reasonCode:"active_task",reason:"Task is currently running"}:c?{reasonCode:"user_directory",reason:"Task uses a user-owned directory"}:{},p=fs.existsSync(s.projectDir),u=fs.existsSync(s.dataDir),m=p?await getPathSize(s.projectDir):0,h=u?await getPathSize(s.dataDir):0;if(p){const n=r||c?null:await getRegisteredWorktreeMainRepo(s.projectDir);await addItem(e,t,i,a,makeStorageItem({id:`workspace:${s.userId}:${s.taskId}:project`,kind:"workspace-project",label:s.taskId,absolutePath:s.projectDir,bytes:m,reclaimable:!r&&!c,defaultSelected:l,deleteMode:r||c?"protected":n?"remove-worktree":"rm-stale-directory",childrenSummary:[{label:"project",bytes:m},...u?[{label:"data",bytes:h}]:[]],...d}))}u&&await addItem(e,t,i,a,makeStorageItem({id:`workspace:${s.userId}:${s.taskId}:data`,kind:"workspace-data",label:`${s.taskId} data`,absolutePath:s.dataDir,bytes:h,reclaimable:!r&&!c,defaultSelected:l,deleteMode:r||c?"protected":"rm",childrenSummary:[{label:"data",bytes:h}],...d}))}const r=completeCategory(i);return t({type:"category-completed",opCode:e,category:r}),r}async function scanLogs(e,t,n,a,s){const i=category("logs");t({type:"category-started",opCode:e,kind:i.kind,label:i.label});const o=path.join(machine.machine.agentrixHomeDir,"logs");if(!fs.existsSync(o)){const n=completeCategory(i);return t({type:"category-completed",opCode:e,category:n}),n}const r=new Map(listWorkspaceTasks().map(e=>[e.taskId,e])),c=Date.now()-s*DAY_MS;for(const s of fs.readdirSync(o,{withFileTypes:!0})){const l=path.join(o,s.name);try{const o=await getPathSize(l),d=parseTaskIdFromLogName(s.name),p=d?r.get(d):void 0,u=!!d&&n.has(d),m=p?taskTimestamp(p):fs.statSync(l).mtimeMs,h=Boolean(d)&&m<c;await addItem(e,t,i,a,makeStorageItem({id:`logs:${toProtocolRelative(machine.machine.agentrixHomeDir,l)}`,kind:"logs",label:s.name,absolutePath:l,bytes:o,reclaimable:!u,defaultSelected:!u&&h,deleteMode:u?"protected":"rm",reasonCode:u?"active_task":void 0,reason:u?"Task is currently running":void 0}))}catch(n){t({type:"item-error",opCode:e,kind:"logs",pathDisplay:toProtocolRelative(machine.machine.agentrixHomeDir,l),errorCode:"stat_failed",message:n instanceof Error?n.message:"Failed to scan item"})}}const l=completeCategory(i);return t({type:"category-completed",opCode:e,category:l}),l}async function scanRepos(e,t,n){const a=category("repos");t({type:"category-started",opCode:e,kind:a.kind,label:a.label});const s=path.join(machine.machine.agentrixHomeDir,"repos");if(!fs.existsSync(s)){const n=completeCategory(a);return t({type:"category-completed",opCode:e,category:n}),n}for(const i of fs.readdirSync(s,{withFileTypes:!0})){if(!i.isDirectory())continue;const o=path.join(s,i.name);for(const s of fs.readdirSync(o,{withFileTypes:!0})){if(!s.isDirectory())continue;const i=path.join(o,s.name);for(const o of fs.readdirSync(i,{withFileTypes:!0})){if(!o.isDirectory())continue;const r=path.join(i,o.name);try{const i=await getPathSize(r);await addItem(e,t,a,n,makeStorageItem({id:`repos:${toProtocolRelative(machine.machine.agentrixHomeDir,r)}`,kind:"repos",label:`${s.name}/${o.name}`,absolutePath:r,bytes:i,reclaimable:!0,defaultSelected:!1,deleteMode:"rm"}))}catch(n){t({type:"item-error",opCode:e,kind:"repos",pathDisplay:toProtocolRelative(machine.machine.agentrixHomeDir,r),errorCode:"stat_failed",message:n instanceof Error?n.message:"Failed to scan item"})}}}}const i=completeCategory(a);return t({type:"category-completed",opCode:e,category:i}),i}async function scanTopLevelDirectory(e,t,n,a,s,i){const o=category(a);t({type:"category-started",opCode:e,kind:o.kind,label:o.label});const r=path.join(machine.machine.agentrixHomeDir,s);if(!fs.existsSync(r)){const n=completeCategory(o);return t({type:"category-completed",opCode:e,category:n}),n}for(const s of fs.readdirSync(r,{withFileTypes:!0})){const c=path.join(r,s.name);try{const r=await getPathSize(c);await addItem(e,t,o,n,makeStorageItem({id:`${a}:${toProtocolRelative(machine.machine.agentrixHomeDir,c)}`,kind:a,label:s.name,absolutePath:c,bytes:r,reclaimable:i,deleteMode:i?"rm":"protected",reasonCode:i?void 0:`${a}_protected`,reason:i?void 0:"This area is shown for visibility only"}))}catch(n){t({type:"item-error",opCode:e,kind:a,pathDisplay:toProtocolRelative(machine.machine.agentrixHomeDir,c),errorCode:"stat_failed",message:n instanceof Error?n.message:"Failed to scan item"})}}const c=completeCategory(o);return t({type:"category-completed",opCode:e,category:c}),c}async function runStorageScanWorker(e){const{opCode:t,emit:n}=e,a=new Set(e.activeTaskIds??[]),s=machine.machine.getStorageManagementSettings(),i=[],o=[];n({type:"started",opCode:t,root:machine.machine.agentrixHomeDir,startedAt:(new Date).toISOString()}),o.push(await scanWorkspaces(t,n,a,i,s.autoSelectTaskOlderThanDays)),o.push(await scanLogs(t,n,a,i,s.autoSelectTaskOlderThanDays)),o.push(await scanTopLevelDirectory(t,n,i,"tmp","tmp",!0)),o.push(await scanRepos(t,n,i)),o.push(await scanTopLevelDirectory(t,n,i,"runtime","node-runtime",!1)),o.push(await scanTopLevelDirectory(t,n,i,"monitor","monitor",!1));const r=o.reduce((e,t)=>e+t.bytes,0),c=o.reduce((e,t)=>e+t.reclaimableBytes,0),l={scanId:`scan-${t}`,root:machine.machine.agentrixHomeDir,generatedAt:(new Date).toISOString(),totalBytes:r,reclaimableBytes:c,categories:o,items:i.sort((e,t)=>Number(t.reclaimable)-Number(e.reclaimable)||t.bytes-e.bytes)};return n({type:"completed",opCode:t,result:l,summary:{totalBytes:r,reclaimableBytes:c,itemCount:i.length,skippedCount:i.filter(e=>!e.reclaimable).length},completedAt:l.generatedAt}),l}async function readWorkerRequest(e){if(!e)return{};const t=await promises$1.readFile(e,"utf8");return JSON.parse(t)}function writeJsonLine(e){process.stdout.write(`${JSON.stringify(e)}\n`)}function registerStorageManagementCommands(e){e.command("storage-scan",!1,e=>e.option("op-code",{type:"string",demandOption:!0}).option("request-file",{type:"string"}),async e=>{const t=e["op-code"];try{const n=await readWorkerRequest(e["request-file"]);await runStorageScanWorker({opCode:t,activeTaskIds:n.activeTaskIds,emit:writeJsonLine}),process.exitCode=0}catch(e){writeJsonLine({type:"failed",opCode:t,errorCode:"operation_failed",message:e instanceof Error?e.message:"Storage scan failed"}),process.exitCode=1}}),e.command("storage-clean",!1,e=>e.option("op-code",{type:"string",demandOption:!0}).option("request-file",{type:"string",demandOption:!0}),async e=>{const t=e["op-code"];try{const n=await readWorkerRequest(e["request-file"]);await runStorageCleanWorker({opCode:t,activeTaskIds:n.activeTaskIds,items:n.items??[],dryRun:!0===n.dryRun,emit:writeJsonLine}),process.exitCode=0}catch(e){writeJsonLine({type:"failed",opCode:t,errorCode:"operation_failed",message:e instanceof Error?e.message:"Storage clean failed"}),process.exitCode=1}})}async function readRecentDaemonLog(){const e=path.join(machine.machine.getStatePaths().logsDir,"daemon.log");try{return(await promises$1.readFile(e,"utf8")).trim().split("\n").filter(Boolean).slice(-12).join("\n")||null}catch{return null}}async function reportDaemonStartupFailure(){const e=await readRecentDaemonLog();if(console.log(chalk.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(chalk.yellow(t)):(console.log(chalk.gray("Recent daemon log:")),console.log(e))}const cli=yargs(helpers.hideBin(process.argv)).scriptName("agentrix").version(machine.packageJson.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");function isProcessRunning(e){try{return process.kill(e,0),!0}catch{return!1}}async function waitForDaemonRestart(e,t,n=15e3){const a=Date.now()+n;let s=!e;for(;Date.now()<a;){if(e&&!s){if(isProcessRunning(e.pid)){await new Promise(e=>setTimeout(e,100));continue}s=!0}const n=await machine.machine.readDaemonState();if(n&&n.pid!==e?.pid&&n.cliVersion===t&&isProcessRunning(n.pid))return!0;await new Promise(e=>setTimeout(e,100))}return!1}async function handleRestartCommand(e){let t;if("string"==typeof e["report-json"])try{t=JSON.parse(e["report-json"])}catch{console.error(chalk.red("Error:"),"Invalid restart report JSON"),process.exit(1)}const n="number"==typeof e["old-pid"]?e["old-pid"]:void 0,a="string"==typeof e["expected-version"]?e["expected-version"]:void 0,s=await runDaemonRestart({oldPid:n,expectedCliVersion:a,reason:"string"==typeof e.reason?e.reason:void 0,report:t,stopExistingDaemon:void 0===n});s.success||(console.error(chalk.red("Error:"),s.error??"Daemon restart failed"),process.exit(1))}machine.machine.getStatePaths,cli.command("upgrade","Upgrade CLI to the latest version",{},async e=>{console.log(chalk.dim(`Current version: ${machine.packageJson.version}`));const t=await checkIfDaemonRunningAndCleanupStaleState(),n=t?await machine.machine.readDaemonState():null;await performAutoUpgrade()||process.exit(1);try{const e=await machine.machine.readCredentials();e&&(console.log(chalk.dim("Checking agent updates...")),await checkAgentUpdates(e))}catch{}if(t){console.log(chalk.blue("Preparing daemon restart..."));const e=await prepareDaemonGracefulRestart("CLI upgrade installed");let t=!0;const a=getInstalledCliVersion();e.error?(console.log(chalk.yellow(`⚠️ Could not prepare graceful restart: ${e.error}`)),console.log(chalk.blue("Restarting daemon directly...")),await stopDaemon(),spawnAgentrixCLI(["daemon"],{detached:!0,stdio:"ignore",env:process.env}).unref()):"pending_restart"===e.state&&(console.log(chalk.yellow(`Daemon restart deferred until ${e.activeSessions??0} active session(s) finish.`)),t=!1);let s=!1;t&&(s=await waitForDaemonRestart(n,a),s?console.log(chalk.green("✓ Daemon restarted successfully")):console.log(chalk.yellow("⚠️ Daemon may still be starting. Run 'agentrix status' to check.")))}const a=getInstalledCliVersion();"0.0.0"!==a?console.log(chalk.green(`\n✓ Now running version: ${a}`)):console.log(chalk.dim("\nRun 'agentrix --version' to see the new version")),process.exit(0)}),cli.command("doctor","System diagnostics & troubleshooting",{},async e=>{await runDoctorCommand(),process.exit(0)}),cli.command("logout","Logout from Agentrix",{},async e=>{try{await handleAuthLogout()}catch(e){console.error(chalk.red("Error:"),e instanceof Error?e.message:"Unknown error"),process.env.DEBUG&&console.error(e),process.exit(1)}process.exit(0)}),cli.command("stop","Stop the daemon",{},async e=>{await stopDaemon(),process.exit(0)}),cli.command("restart","Restart the daemon",e=>e.option("old-pid",{type:"number",describe:"PID of the daemon that must exit before replacement starts"}).option("expected-version",{type:"string",describe:"CLI version expected from the replacement daemon"}).option("reason",{type:"string",describe:"Restart reason"}),async e=>{await handleRestartCommand(e),console.log(chalk.green("✓ Daemon restarted successfully")),process.exit(0)}),cli.command("status","Show daemon and authentication status",{},async e=>{await runDoctorCommand("daemon"),console.log(""),await handleAuthStatus(),process.exit(0)}),cli.command("ls","List active sessions",{},async e=>{try{const e=await listDaemonSessions();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)}),cli.command("killall","Clean up all runaway agentrix processes",{},async()=>{const e=await killRunawayAgentrixProcesses();console.log(`Cleaned up ${e.killed} runaway processes`),e.errors.length>0&&console.log("Errors:",e.errors),process.exit(0)}),registerGitServerCommands(cli),registerInitCommand(cli),registerLlmConfigCommand(cli),registerStorageManagementCommands(cli),cli.command("kill <sessionId>","Stop a specific session",e=>e.positional("sessionId",{type:"string",describe:"Session ID to stop"}),async e=>{try{const t=await stopDaemonSession(e.sessionId);console.log(t?chalk.green("✓ Session stopped"):chalk.red("Failed to stop session"))}catch(e){console.log(chalk.red("No daemon running"))}process.exit(0)}),cli.command("daemon",!1,{},async e=>{try{await authAndSetupMachineIfNeeded()}catch(e){console.error(chalk.red("Error:"),e instanceof Error?e.message:"Authentication failed"),process.env.DEBUG&&console.error(e),process.exit(1)}await startDaemon(),process.exit(0)}),cli.command("worker",!1,e=>e.option("type",{type:"string",choices:workerTypes,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=workerRegistry[t];if(!n)throw new Error(`Unsupported worker type: ${String(e.type)}`);const a=e["started-by"],s=e["user-id"],i=e["task-id"],o=e["idle-timeout"];machine.initializeLogger({type:"worker",taskId:i});const r=await authAndSetupMachineIfNeeded();await n.run({credentials:r,startedBy:a,userId:s,taskId:i,idleTimeoutSecond:o})}catch(e){console.error(chalk.red("Error:"),e instanceof Error?e.message:"Unknown error"),process.env.DEBUG&&console.error(e),process.exit(1)}}),cli.command("restart-daemon",!1,e=>e.option("old-pid",{type:"number",describe:"PID of the daemon that must exit before replacement starts"}).option("expected-version",{type:"string",describe:"CLI version expected from the replacement daemon"}).option("reason",{type:"string",describe:"Restart reason"}).option("report-json",{type:"string",describe:"Machine-control restart report context"}),async e=>{await handleRestartCommand(e),process.exit(0)}),cli.command("start","Start daemon (if not running) and show status",{},async e=>{try{await authAndSetupMachineIfNeeded()}catch(e){console.error(chalk.red("Error:"),e instanceof Error?e.message:"Authentication failed"),process.env.DEBUG&&console.error(e),process.exit(1)}const t=checkCriticalDependencies();if(t.ok||(console.log(chalk.bold.red("\n⚠️ Missing Critical Dependencies")),console.log(chalk.yellow(`Cannot start daemon. Missing: ${t.missing.join(", ")}`)),console.log(chalk.blue('\nRun "agentrix doctor" for detailed dependency information and installation instructions.')),process.exit(1)),!await isLatestDaemonRunning()){console.log("Starting Agentrix background service..."),spawnAgentrixCLI(["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 checkIfDaemonRunningAndCleanupStaleState()){e=!0;break}e?(await new Promise(e=>setTimeout(e,1200)),await checkIfDaemonRunningAndCleanupStaleState()?console.log(chalk.green("✓ Daemon started successfully")):await reportDaemonStartupFailure()):console.log(chalk.yellow("⚠️ Daemon may still be starting..."))}await runDoctorCommand("daemon"),process.exit(0)}),cli.demandCommand(1,"Please specify a command. Use --help to see available commands.").parse();
1
+ "use strict";var os=require("node:os"),fs=require("node:fs"),path=require("node:path"),yargs=require("yargs"),helpers=require("yargs/helpers"),chalk=require("chalk"),shared=require("@agentrix/shared"),node_crypto=require("node:crypto"),axios=require("axios"),machine=require("./logger-B5VvgaeC.cjs"),node_readline=require("node:readline"),fs$1=require("fs"),path$1=require("path"),open=require("open"),socket_ioClient=require("socket.io-client"),node_events=require("node:events"),promises=require("node:stream/promises"),node_module=require("node:module"),child_process=require("child_process"),psList=require("ps-list"),spawn=require("cross-spawn"),platform_js=require("@xmz-ai/sandbox-runtime/dist/utils/platform.js"),fastify=require("fastify"),zod=require("zod"),fastifyTypeProviderZod=require("fastify-type-provider-zod"),node_child_process=require("node:child_process"),claudeAgentSdk=require("@anthropic-ai/claude-agent-sdk"),node=require("@agentrix/shared/node"),promises$1=require("node:fs/promises"),node_util=require("node:util"),simpleGit=require("simple-git"),events=require("events"),Database=require("better-sqlite3"),url=require("url"),croner=require("croner"),mcp_js=require("@modelcontextprotocol/sdk/server/mcp.js"),streamableHttp_js=require("@modelcontextprotocol/sdk/server/streamableHttp.js"),crypto$1=require("crypto"),sandboxRuntime=require("@xmz-ai/sandbox-runtime"),lark=require("@larksuiteoapi/node-sdk"),os$1=require("os"),promises$2=require("fs/promises"),codexSdk=require("@openai/codex-sdk"),node_process=require("node:process"),promises$3=require("node:readline/promises");require("winston"),require("node:url");var _documentCurrentScript="undefined"!=typeof document?document.currentScript:null;function _interopNamespaceDefault(e){var t=Object.create(null);return e&&Object.keys(e).forEach(function(n){if("default"!==n){var a=Object.getOwnPropertyDescriptor(e,n);Object.defineProperty(t,n,a.get?a:{enumerable:!0,get:function(){return e[n]}})}}),t.default=e,Object.freeze(t)}var fs__namespace=_interopNamespaceDefault(fs),path__namespace=_interopNamespaceDefault(path),fs__namespace$1=_interopNamespaceDefault(fs$1),path__namespace$1=_interopNamespaceDefault(path$1),lark__namespace=_interopNamespaceDefault(lark);const ALWAYS_ON_ENV_KEYS=new Set(["AGENTRIX_CLAUDE_HOME","AGENTRIX_CODEX_HOME","AGENTRIX_GEMINI_HOME","AGENTRIX_CLAUDE_PATH","AGENTRIX_CODEX_PATH"]);function resolveHomePath$1(e){return e.replace(/^~(?=\/|$)/,os.homedir())}function resolveAgentrixHomeDir(e=process.env){const t=e.AGENTRIX_HOME_DIR||e.AGENTRIX_DIR;return t?resolveHomePath$1(t):path.join(os.homedir(),".agentrix")}function readDaemonEnvSettings(e=process.env){const t=path.join(resolveAgentrixHomeDir(e),"settings.json");if(!fs.existsSync(t))return null;try{const e=fs.readFileSync(t,"utf-8"),n=JSON.parse(e);return n?.daemonEnv||null}catch{return null}}function setProxyAliases(e,t,n){const a=t.toLowerCase();"http_proxy"===a?(e.HTTP_PROXY=n,e.http_proxy=n):"https_proxy"===a?(e.HTTPS_PROXY=n,e.https_proxy=n):"no_proxy"===a?(e.NO_PROXY=n,e.no_proxy=n):"all_proxy"===a?(e.ALL_PROXY=n,e.all_proxy=n):"global_agent_http_proxy"===a&&(e.GLOBAL_AGENT_HTTP_PROXY=n,e.global_agent_http_proxy=n)}function applyAgentHomeAliases(e,t,n){const a=n.trim();a&&("AGENTRIX_CLAUDE_HOME"===t?e.CLAUDE_CONFIG_DIR=resolveHomePath$1(a):"AGENTRIX_CODEX_HOME"===t&&(e.CODEX_HOME=resolveHomePath$1(a)))}function applyDaemonEnvSettings(e=process.env,t){if(!t?.variables)return e;const n=!0===t.enabled;for(const[a,s]of Object.entries(t.variables)){const t=a.trim();if(!t)continue;const i=String(s),o=ALWAYS_ON_ENV_KEYS.has(t);(n||o)&&(e[t]=i,setProxyAliases(e,t,i),applyAgentHomeAliases(e,t,i))}return e}function bootstrapDaemonEnv(e=process.env){return applyDaemonEnvSettings(e,readDaemonEnvSettings(e))}async function delay(e){return new Promise(t=>setTimeout(t,e))}function buildDaemonControlUrl(e,t){return`http://${"::1"===e.host?"[::1]":"127.0.0.1"}:${e.port}${t}`}async function daemonPost(e,t){const n=await machine.machine.readDaemonState();if(!n?.port){const e="No daemon running, no state file found";return machine.logger.debug(`[CONTROL CLIENT] ${e}`),{error:e}}try{const a=process.env.AGENTRIX_DAEMON_HTTP_TIMEOUT?parseInt(process.env.AGENTRIX_DAEMON_HTTP_TIMEOUT):1e4,s=buildDaemonControlUrl(n,e),i=await fetch(s,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t||{}),signal:AbortSignal.timeout(a)});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 machine.logger.debug(`[CONTROL CLIENT] ${n}`),{error:n}}return await i.json()}catch(t){const a=`Request failed: ${e} at ${buildDaemonControlUrl(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 machine.logger.debug(`[CONTROL CLIENT] ${a}`),{error:a}}}async function notifyDaemonSessionStarted(e,t){return await daemonPost("/session-started",{sessionId:e,metadata:t})}async function notifyDaemonDevOpsInitComplete(e,t,n){return await daemonPost("/devops-init-complete",{taskId:e,userId:t,action:n})}async function notifyDaemonStartDevOpsInit(e,t){return await daemonPost("/devops-init-start",{taskId:e,userId:t})}async function sendTaskChannelMessage(e,t,n){const a="string"==typeof t?{content:t}:t;return await daemonPost("/channels/task-message",{taskId:e,...a,...n?{target:n}:{}})}async function getTaskChannelGroupHistory(e,t,n={}){return await daemonPost("/channels/group-history",{taskId:e,target:t,...n})}async function listDaemonSessions(){return(await daemonPost("/list")).children||[]}async function stopDaemonSession(e){return(await daemonPost("/stop-session",{sessionId:e})).success||!1}async function stopDaemonHttp(){await daemonPost("/stop")}async function prepareDaemonGracefulRestart(e){return await daemonPost("/prepare-graceful-restart",{source:"agentrix-cli",reason:e})}async function bindGitServerViaDaemon(e){return await daemonPost("/git-server/bind",e)}async function listGitServersViaDaemon(){return await daemonPost("/git-server/list")}async function checkIfDaemonRunningAndCleanupStaleState(){const e=await machine.machine.readDaemonState();if(!e)return!1;try{return process.kill(e.pid,0),!0}catch{return machine.logger.debug("[DAEMON RUN] Daemon PID not running, cleaning up state"),await cleanupDaemonState(),!1}}async function isLatestDaemonRunning(){if(machine.logger.debug("[DAEMON CONTROL] Checking if daemon is running same version"),!await checkIfDaemonRunningAndCleanupStaleState())return machine.logger.debug("[DAEMON CONTROL] No daemon running, returning false"),!1;const e=await machine.machine.readDaemonState();if(!e)return machine.logger.debug("[DAEMON CONTROL] No daemon state found, returning false"),!1;try{const t=path$1.join(machine.projectPath(),"package.json"),n=JSON.parse(fs$1.readFileSync(t,"utf-8")).version;return machine.logger.debug(`[DAEMON CONTROL] Current CLI version: ${n}, Daemon started with version: ${e.cliVersion}`),n===e.cliVersion}catch(e){return machine.logger.debug("[DAEMON CONTROL] Error checking daemon version",e),!1}}async function cleanupDaemonState(){try{await machine.machine.clearDaemonState(),machine.logger.debug("[DAEMON RUN] Daemon state file removed")}catch(e){machine.logger.debug("[DAEMON RUN] Error cleaning up daemon metadata",e)}}async function stopDaemon(){try{const e=await machine.machine.readDaemonState();if(!e)return void machine.logger.debug("No daemon state found");machine.logger.debug(`Stopping daemon with PID ${e.pid}`);try{return await stopDaemonHttp(),void await waitForProcessDeath(e.pid,2e3)}catch(e){machine.logger.debug("HTTP stop failed, will force kill",e)}process.kill(e.pid,"SIGKILL")}catch(e){machine.logger.debug("Error stopping daemon",e)}}async function waitForProcessDeath(e,t){const n=Date.now();for(;Date.now()-n<t;)try{process.kill(e,0),await new Promise(e=>setTimeout(e,100))}catch{return}throw new Error("Process did not die within timeout")}function generateWebAuthUrl(e,t){const n={key:shared.encodeBase64(e,"base64"),machineId:t},a=JSON.stringify(n),s=shared.encodeBase64((new TextEncoder).encode(a),"base64url");return`${machine.machine.webappUrl}/terminal/connect?auth=${s}`}async function handleAuthLogout(){if(!await machine.machine.readCredentials())return void console.log(chalk.yellow("Not currently authenticated"));console.log(chalk.blue("This will log you out of Agentrix")),console.log(chalk.yellow("⚠️ You will need to re-authenticate to use Agentrix again"));const e=node_readline.createInterface({input:process.stdin,output:process.stdout}),t=await new Promise(t=>{e.question(chalk.yellow("Are you sure you want to log out? (y/N): "),t)});if(e.close(),"y"===t.toLowerCase()||"yes"===t.toLowerCase())try{try{await stopDaemon(),console.log(chalk.gray("Stopped daemon"))}catch{}await machine.machine.clearCredentials(),console.log(chalk.gray("Removed credentials")),console.log(chalk.green("✓ Successfully logged out"))}catch(e){throw new Error(`Failed to logout: ${e instanceof Error?e.message:"Unknown error"}`)}else console.log(chalk.blue("Logout cancelled"))}async function handleAuthStatus(){const e=await machine.machine.readCredentials();if(console.log(chalk.bold("\nAuthentication Status\n")),!e)return void console.log(chalk.red("✗ Not authenticated"));console.log(chalk.green("✓ Authenticated"));const t=e.token.substring(0,30)+"...";console.log(chalk.gray(` Token: ${t}`)),e.machineId?(console.log(chalk.green("✓ Machine registered")),console.log(chalk.gray(` Machine ID: ${e.machineId}`)),console.log(chalk.gray(` Host: ${os.hostname()}`))):console.log(chalk.yellow("⚠️ Machine not registered")),console.log(chalk.gray(`\n Data directory: ${machine.machine.agentrixHomeDir}`));try{await checkIfDaemonRunningAndCleanupStaleState()?console.log(chalk.green("✓ Daemon running")):console.log(chalk.gray("✗ Daemon not running"))}catch{console.log(chalk.gray("✗ Daemon not running"))}}async function openBrowser(e){try{return!process.stdout.isTTY||process.env.CI||process.env.HEADLESS?(machine.logger.debug("[browser] Headless environment detected, skipping browser open"),!1):(machine.logger.debug(`[browser] Attempting to open URL: ${e}`),await open(e),machine.logger.debug("[browser] Browser opened successfully"),!0)}catch(e){return machine.logger.debug("[browser] Failed to open browser:",e),!1}}function withReauthHint(e){return`${e}\nRun \`agentrix logout\` and bind this machine again.`}function formatMachineAuthError(e,t){if(axios.isAxiosError(e)){const n=e.response?.data?.message;return"string"==typeof n&&n.length>0?n.includes("Machine binding revoked")?withReauthHint(n):`${t}: ${n}`:"string"==typeof e.message&&e.message.includes("Machine binding revoked")?withReauthHint(e.message):`${t}: ${e.message}`}return e instanceof Error&&e.message.includes("Machine binding revoked")?withReauthHint(e.message):e instanceof Error?`${t}: ${e.message}`:t}function generateLocalAuthSecret(){return shared.encodeBase64(new Uint8Array(node_crypto.randomBytes(32)))}function readMachineAesKey(e){if(!e.machineAesKey)return null;try{const t=shared.decodeBase64(e.machineAesKey);return 32===t.length?t:null}catch{return null}}function ensureMachineAesKey(e){const t=readMachineAesKey(e);if(t)return t;const n=shared.generateAESKey();return e.machineAesKey=shared.encodeBase64(n),n}async function doAuth(){console.clear();const e=machine.machine.generateMachineId(),t=new Uint8Array(node_crypto.randomBytes(32)),n=await shared.createKeyPairWithUit8Array(t);try{console.log(`[AUTH] Sending auth request to: ${machine.machine.serverUrl}/v1/auth/machine`),console.log(`[AUTH] Public key: ${shared.encodeBase64(n.publicKey).substring(0,20)}...`);const t={machineId:e};await axios.post(`${machine.machine.serverUrl}/v1/auth/machine`,t),console.log("[AUTH] Auth request sent successfully")}catch(e){return console.log(formatMachineAuthError(e,"Failed to create authentication request, please try again later.")),{credentials:null,userPublicKey:null,keypair:n}}const a=await doWebAuth(n,e);return a.token?{credentials:{token:a.token,secret:shared.encodeBase64(t),machineId:e},userPublicKey:a?.userPublicKey,keypair:n}:{credentials:null,userPublicKey:null,keypair:n}}async function doWebAuth(e,t){console.clear(),console.log("\nWeb Authentication\n");const n=generateWebAuthUrl(e.publicKey,t);return console.log("Opening your browser..."),await openBrowser(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 waitForAuthentication(e,t)}async function waitForAuthentication(e,t){process.stdout.write("Waiting for authentication");let n=0,a=!1;const s=()=>{a=!0,console.log("\n\nAuthentication cancelled."),process.exit(0)};process.on("SIGINT",s);try{for(;!a;){try{const n=await axios.get(`${machine.machine.serverUrl}/v1/auth/machine?machineId=${t}`);if("authorized"===n.data.state){const t=n.data.token,a=n.data.content,s=shared.decryptWithEphemeralKey(shared.decodeBase64(a),e.secretKey);return s?{token:t,userPublicKey:JSON.parse((new TextDecoder).decode(s)).publicKey}:(console.log("\n\nFailed to decrypt authentication data. Please try again."),{token:null,userPublicKey:null})}}catch(e){return console.log(`\n\n${formatMachineAuthError(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 delay(1e3)}}finally{process.off("SIGINT",s)}return{token:null,userPublicKey:null}}async function syncMachine(e,t,n,a){try{const s={id:e.machineId,metadata:JSON.stringify(t)};if(a&&n){const t=ensureMachineAesKey(e);s.dataEncryptionKey=shared.encryptMachineEncryptionKey(a.publicKey,t,shared.decodeBase64(n))}await axios.post(`${machine.machine.serverUrl}/v1/machines/sync`,s,{headers:{Authorization:`Bearer ${e.token}`,"Content-Type":"application/json"},timeout:6e4})}catch(e){throw new Error(formatMachineAuthError(e,"Failed to sync machine data"))}}async function validateExistingCredentials(e){try{await axios.get(`${machine.machine.serverUrl}/v1/machines/validate`,{headers:{Authorization:`Bearer ${e.token}`},timeout:15e3})}catch(e){throw new Error(formatMachineAuthError(e,"Stored machine credentials are no longer valid"))}}async function authAndSetupMachineIfNeeded(){const e=await machine.machine.readCredentials();if(e){await validateExistingCredentials(e);let t=e;e.secret||(t={...e,secret:generateLocalAuthSecret()},await machine.machine.writeCredentials(t),machine.logger.info("[AUTH] Generated missing local auth secret"));try{await syncMachine(t,machine.machine.metadata()),machine.logger.info("[AUTH] Machine metadata synced")}catch(e){machine.logger.warn("[AUTH] Failed to sync machine metadata",e)}return machine.logger.info("[AUTH] Using existing credentials"),t}const t=process.env.CLOUD_AUTH_TOKEN;let n,a,s;if(t){const e=machine.machine.generateMachineId();n={token:t,secret:generateLocalAuthSecret(),machineId:e},machine.logger.info(`[AUTH] Cloud mode detected, generated machine ID: ${e}`)}else{const e=await doAuth();if(!e.credentials||!e.userPublicKey)throw new Error("Authentication failed or was cancelled");n=e.credentials,a=e.keypair,s=e.userPublicKey}return await syncMachine(n,machine.machine.metadata(),s,a),await machine.machine.writeCredentials(n),machine.logger.info("[AUTH] Machine setup completed"),n}bootstrapDaemonEnv();const logger$a=machine.createModuleLogger("undefined"==typeof document?require("url").pathToFileURL(__filename).href:_documentCurrentScript&&"SCRIPT"===_documentCurrentScript.tagName.toUpperCase()&&_documentCurrentScript.src||new URL("index.cjs",document.baseURI).href),REDACTED_LOG_VALUE="[REDACTED]",SENSITIVE_LOG_KEYS=new Set(["authorization","apikey","accesstoken","refreshtoken","machineaeskey","key","password","pat","secret","token"]);class KeepAliveManager{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 readSocketErrorData(e){const t=shared.SocketAuthErrorDataSchema.safeParse(e);return t.success?t.data:null}function getSocketErrorDetails(e){if(!e||"object"!=typeof e)return{message:String(e??"unknown error")};const t=e,n=readSocketErrorData(t.data);return n?{message:n.message||t.message||"Socket connection failed",...n.code?{code:n.code}:{},...n.action?{action:n.action}:{}}:{message:t.message||"unknown socket error"}}function formatSocketError(e){if(!e||"object"!=typeof e)return String(e??"unknown error");const t=e,n=getSocketErrorDetails(e);if(n.code||n.action)return[n.code?`[${n.code}]`:void 0,n.message,n.action].filter(Boolean).join(" ");const a=[];return t.message&&a.push(t.message),t.type&&a.push(`type=${t.type}`),void 0!==t.description&&a.push(`description=${stringifyForLog(t.description)}`),void 0!==t.data&&a.push(`data=${stringifyForLog(t.data)}`),void 0!==t.context&&a.push(`context=${stringifyForLog(t.context)}`),a.filter(Boolean).join(" ")||"unknown socket error"}function redactSocketPayloadForLog(e,t=0){if(t>8)return"[MaxDepth]";if(Array.isArray(e))return e.map(e=>redactSocketPayloadForLog(e,t+1));if(!e||"object"!=typeof e)return e;const n={};for(const[a,s]of Object.entries(e)){const e=a.replace(/[-_]/g,"").toLowerCase();n[a]=SENSITIVE_LOG_KEYS.has(e)?"[REDACTED]":redactSocketPayloadForLog(s,t+1)}return n}function stringifyForLog(e){try{return JSON.stringify(redactSocketPayloadForLog(e))}catch{return"[Unserializable]"}}function summarizeSocketPayloadForLog(e){if(!e||"object"!=typeof e||Array.isArray(e))return{};const t=e,n=t.data&&"object"==typeof t.data&&!Array.isArray(t.data)?t.data:void 0,a={},s=["eventId","taskId","chatId","from","senderType","messageType","opCode","sequence","status"];for(const e of s)void 0!==t[e]&&(a[e]=t[e]);void 0!==n?.sequence&&(a.ackSequence=n.sequence),void 0!==t.message&&(a.hasMessage=!0),"string"==typeof t.encryptedMessage&&(a.encrypted=!0,a.encryptedMessageChars=t.encryptedMessage.length);const i=new Set(s),o=Object.keys(t).filter(e=>!i.has(e)&&"message"!==e&&"encryptedMessage"!==e);return o.length>0&&(a.extraKeys=o.sort()),a}class SocketClient{socket=null;config;eventHandlers=new Map;eventEmitter=new node_events.EventEmitter;KeepAliveManager=null;healthCheckInterval=null;connectStartedAt=null;constructor(e){this.config=e,e.keepAliveConfig&&(this.KeepAliveManager=new KeepAliveManager(e.keepAliveConfig))}connect(){if(this.socket)return void this.targetLogger.debug("Already connected or connecting");const{serverUrl:e,path:t,auth:n={},options:a={}}=this.config,s={path:t,auth:n,transports:["websocket"],reconnection:!0,reconnectionDelay:1e3,reconnectionDelayMax:5e3,reconnectionAttempts:1/0,...a};this.connectStartedAt=Date.now(),this.socket=socket_ioClient.io(e,s),this.setupSocketHandlers(),this.targetLogger.debug(`Connecting to ${e}`)}disconnect(){this.socket&&(this.targetLogger.info("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.targetLogger.debug(`received event ${e}, summary: ${stringifyForLog(summarizeSocketPayloadForLog(n))}`),t(n)),a=this.eventHandlers.get(e);this.eventHandlers.set(e,n),this.replaceSocketHandler(e,a,n)}onEventWithAck(e,t){const n=async(n,a)=>(this.targetLogger.debug(`received event with ack ${e}, summary: ${stringifyForLog(summarizeSocketPayloadForLog(n))}`),t(n,a)),a=this.eventHandlers.get(e);this.eventHandlers.set(e,n),this.replaceSocketHandler(e,a,n)}unregisterHandler(e){this.eventHandlers.delete(e),this.socket&&this.socket.off(e)}send(e,t){this.socket?(this.targetLogger.debug(`send event ${e}, summary: ${stringifyForLog(summarizeSocketPayloadForLog(t))}`),void 0!==t?this.socket.emit(e,t):this.socket.emit(e)):this.targetLogger.warn("Cannot send - socket not connected")}async sendWithAck(e,t){if(!this.socket)throw new Error("Cannot send - socket not connected");return this.targetLogger.debug(`send event ${e}, summary: ${stringifyForLog(summarizeSocketPayloadForLog(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",()=>{const e=this.connectStartedAt?Date.now()-this.connectStartedAt:void 0;this.connectStartedAt=null,this.targetLogger.info(`socket.connected host=${this.config.serverUrl}${void 0!==e?` connectMs=${e}`:""}`),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.targetLogger.info(`Disconnected: ${e||"unknown"}`),this.eventEmitter.emit("lifecycle:disconnect",e),this.KeepAliveManager?.stop(),this.stopHealthCheck()}),this.socket.on("connect_error",e=>{this.targetLogger.warn(`Connection error: ${formatSocketError(e)}`),this.eventEmitter.emit("lifecycle:connect_error",e),setTimeout(()=>this.socket?.connect(),5e3)}),this.socket.on("error",e=>{this.targetLogger.warn(`Socket error: ${formatSocketError(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.targetLogger.warn("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)}get targetLogger(){return this.config.logger??logger$a}}const FALLBACK_FILE_NAME="attachment",MIME_EXTENSION_MAP={"image/jpeg":".jpg","image/png":".png","image/gif":".gif","image/webp":".webp","image/heic":".heic","application/pdf":".pdf"};function getChannelFilesDir(){const e=path.join(machine.machine.agentrixHomeDir,"tmp","channel-files");return fs.existsSync(e)||fs.mkdirSync(e,{recursive:!0}),e}function createChannelFilePath(e){const t=sanitizeFileName(e)||"attachment";return path.join(getChannelFilesDir(),`${node_crypto.randomUUID()}-${t}`)}function resolveChannelFilePath(e){const t=path.resolve(getChannelFilesDir()),n=path.resolve(e);if(n!==t&&!n.startsWith(`${t}${path.sep}`))throw new Error("Access denied: channel attachment path is outside channel files directory");return n}async function saveResponseToChannelFile(e,t){if(!e.ok)throw new Error(`HTTP ${e.status}: ${e.statusText}`);if(!e.body)throw new Error("Response body is null");const n=createChannelFilePath(resolveFileName(t||getFileNameFromContentDisposition(e.headers.get("content-disposition")),e.headers.get("content-type"))),a=fs.createWriteStream(n);return await promises.pipeline(e.body,a),n}async function downloadUrlToChannelFile(e,t,n){const a=await fetch(e,n),s=getFileNameFromUrl(e);return saveResponseToChannelFile(a,t||s)}function sanitizeFileName(e){if(e)return path.basename(e).replace(/[<>:"/\\|?*\x00-\x1F]/g,"_").trim()||void 0}function getFileNameFromContentDisposition(e){if(!e)return;const t=e.match(/filename\*=UTF-8''([^;]+)/i);if(t?.[1])return decodeURIComponent(t[1]);const n=e.match(/filename="?([^";]+)"?/i);return n?.[1]}function getFileNameFromUrl(e){try{const t=path.basename(new URL(e).pathname);return path.extname(t)?t:void 0}catch{return}}function resolveFileName(e,t){if(!e){const e=getExtensionFromContentType(t);return e?`attachment${e}`:void 0}if(path.extname(e))return e;const n=getExtensionFromContentType(t);return n?`${e}${n}`:e}function getExtensionFromContentType(e){const t=e?.split(";")[0]?.trim().toLowerCase();return t?MIME_EXTENSION_MAP[t]:void 0}var mimeDb,hasRequiredMimeDb,hasRequiredMimeTypes,mimeTypes={},require$$0={"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}};function requireMimeDb(){return hasRequiredMimeDb?mimeDb:(hasRequiredMimeDb=1,mimeDb=require$$0)}function requireMimeTypes(){return hasRequiredMimeTypes||(hasRequiredMimeTypes=1,function(e){var t,n,a,s=requireMimeDb(),i=path$1.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&&s[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 a=e.charset(n);a&&(n+="; charset="+a.toLowerCase())}return n},e.extension=function(t){if(!t||"string"!=typeof t)return!1;var n=o.exec(t),a=n&&e.extensions[n[1].toLowerCase()];return!(!a||!a.length)&&a[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,a=["nginx","apache",void 0,"iana"],Object.keys(s).forEach(function(e){var i=s[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=a.indexOf(s[n[c]].source),d=a.indexOf(i.source);if("application/octet-stream"!==n[c]&&(l>d||l===d&&"application/"===n[c].substr(0,12)))continue}n[c]=e}}})}(mimeTypes)),mimeTypes}var mimeTypesExports=requireMimeTypes();async function decryptDataEncryptionKey(e){try{const t=await machine.machine.getSecretKey();if(!t)return machine.logger.warn("[WORKSPACE] Machine secret key not available"),null;const n=shared.decodeBase64(e);return shared.decryptWithEphemeralKey(n,t)||(machine.logger.warn("[WORKSPACE] Failed to decrypt dataEncryptionKey"),null)}catch(e){return machine.logger.warn("[WORKSPACE] Error decrypting dataEncryptionKey:",e),null}}function resolveFilePath$1(e,t,n){if(n.startsWith("channel-attachment/")){const e=n.slice(19);return resolveChannelFilePath(decodeURIComponent(e))}return machine.machine.resolveWorkspaceFilePath(e,t,n)}function isWithinWorkspaceBase$1(e,t,n,a){const s=n.replace(/^\/+/,""),i="project"===s||s.startsWith("project/")?"project":"data"===s||s.startsWith("data/")?"data":"",o=path__namespace.normalize(machine.machine.resolveWorkspaceFilePath(e,t,i)),r=path__namespace.normalize(a);return r===o||r.startsWith(o+path__namespace.sep)}function sendResponse(e,t){e?e.send("workspace-file-response",t):machine.logger.error("[WORKSPACE] Cannot send workspace-file-response: client not available")}function sendMutationResponse(e,t){e?e.send("workspace-file-mutation-response",t):machine.logger.error("[WORKSPACE] Cannot send workspace-file-mutation-response: client not available")}function createErrorResponse(e,t,n,a){return{eventId:shared.createEventId(),requestId:e,taskId:t,success:!1,error:{code:n,message:a}}}function createMutationErrorResponse(e,t,n,a){return{eventId:shared.createEventId(),requestId:e,taskId:t,success:!1,error:{code:n,message:a}}}function handleNotModified(e,t,n,a){machine.logger.debug(`[WORKSPACE] File not modified: ${a}`),sendResponse(e,{eventId:shared.createEventId(),requestId:t,taskId:n,success:!0,notModified:!0})}async function handleDirectory(e,t,n,a,s,i){const o=await fs__namespace.promises.readdir(a,{withFileTypes:!0}),r=await Promise.all(o.map(async e=>{const t=path__namespace.join(a,e.name),n=await fs__namespace.promises.stat(t);return{name:e.name,type:e.isDirectory()?"directory":"file",size:n.size,modifiedAt:n.mtime.toISOString(),accessDenied:n.size>i}}));sendResponse(e,{eventId:shared.createEventId(),requestId:t,taskId:n,success:!0,data:{type:"directory",entries:r,metadata:{size:0,modifiedAt:s.mtime.toISOString()}}})}function handleFileTooLarge(e,t,n,a,s,i,o){machine.logger.warn(`[WORKSPACE] File too large (${s.size} bytes > ${o} bytes): ${a}`),sendResponse(e,{eventId:shared.createEventId(),requestId:t,taskId:n,success:!0,data:{type:"file",metadata:{size:s.size,mimeType:i,modifiedAt:s.mtime.toISOString(),accessDenied:!0}}})}async function handleFile(e,t,n,a,s,i){const o=mimeTypesExports.lookup(a)||"application/octet-stream",r=(await fs__namespace.promises.readFile(a)).toString("base64");let c=null;i&&(c=await decryptDataEncryptionKey(i));const l={type:"file",metadata:{size:s.size,mimeType:o,modifiedAt:s.mtime.toISOString()}};c?l.encryptedContent=shared.encryptFileContent(r,c):l.content=r,sendResponse(e,{eventId:shared.createEventId(),requestId:t,taskId:n,success:!0,data:l})}function workspaceFileMutationRequestHandler(e){return async t=>{const{taskId:n,userId:a,relativePath:s,requestId:i,operation:o,content:r,createOnly:c}=t;machine.logger.debug(`[WORKSPACE] File mutation request: taskId=${n}, userId=${a}, relativePath=${s}, operation=${o}, createOnly=${!!c}`);try{if(s.startsWith("channel-attachment/"))return void sendMutationResponse(e.client,createMutationErrorResponse(i,n,"permission_denied","Channel attachments are read-only"));const t=resolveFilePath$1(a,n,s);if(!isWithinWorkspaceBase$1(a,n,s,t))return void sendMutationResponse(e.client,createMutationErrorResponse(i,n,"permission_denied","Path escapes workspace"));if("delete"===o)return await fs__namespace.promises.rm(t,{force:!1}),void sendMutationResponse(e.client,{eventId:shared.createEventId(),requestId:i,taskId:n,success:!0,data:{relativePath:s,operation:o}});if(void 0===r)return void sendMutationResponse(e.client,createMutationErrorResponse(i,n,"bad_request","File content is required"));await fs__namespace.promises.mkdir(path__namespace.dirname(t),{recursive:!0});try{await fs__namespace.promises.writeFile(t,r,c?{flag:"wx"}:void 0)}catch(t){if("EEXIST"===t.code)return void sendMutationResponse(e.client,createMutationErrorResponse(i,n,"file_exists","File already exists"));throw t}const l=await fs__namespace.promises.stat(t);sendMutationResponse(e.client,{eventId:shared.createEventId(),requestId:i,taskId:n,success:!0,data:{relativePath:s,operation:o,modifiedAt:l.mtime.toISOString()}})}catch(t){machine.logger.error(`[WORKSPACE] Failed to handle workspace-file-mutation-request: ${t.message}`,t);const a="ENOENT"===t.code?"file_not_found":"EACCES"===t.code?"permission_denied":"unknown_error";sendMutationResponse(e.client,createMutationErrorResponse(i,n,a,t.message))}}}function workspaceFileRequestHandler(e){return async t=>{const{taskId:n,userId:a,relativePath:s,requestId:i,maxFileSizeMB:o,ifModifiedSince:r,dataEncryptionKey:c}=t;machine.logger.debug(`[WORKSPACE] File request: taskId=${n}, userId=${a}, relativePath=${s}, maxFileSizeMB=${o}, ifModifiedSince=${r}, hasEncryptionKey=${!!c}`);try{const t=1024*(o||10)*1024,l=resolveFilePath$1(a,n,s);if(!fs__namespace.existsSync(l))return machine.logger.warn(`[WORKSPACE] File not found: ${l}`),void sendResponse(e.client,createErrorResponse(i,n,"file_not_found","File or directory not found"));const d=await fs__namespace.promises.stat(l),p=d.mtime.toISOString();if(r&&p===r)return void handleNotModified(e.client,i,n,l);if(d.isDirectory())return void await handleDirectory(e.client,i,n,l,d,t);{const a=mimeTypesExports.lookup(l)||"application/octet-stream";return d.size>t?void handleFileTooLarge(e.client,i,n,l,d,a,t):void await handleFile(e.client,i,n,l,d,c)}}catch(t){machine.logger.error(`[WORKSPACE] Failed to handle workspace-file-request: ${t.message}`,t);const a="ENOENT"===t.code?"file_not_found":"EACCES"===t.code?"permission_denied":"unknown_error";sendResponse(e.client,createErrorResponse(i,n,a,t.message))}}}function failure(e,t){return{eventId:shared.createEventId(),status:"failed",opCode:e,message:t}}function assertSafeIssueId(e){if(!/^[A-Za-z0-9._-]+$/.test(e)||e.includes(".."))throw new Error("Invalid Vision Plan issue id")}function assertInside(e,t){const n=path__namespace.relative(t,e);if(n.startsWith("..")||path__namespace.isAbsolute(n))throw new Error("Vision Plan review path is outside the bound issue directory")}async function nextReviewFile(e){await fs__namespace.promises.mkdir(e,{recursive:!0});let t=(await fs__namespace.promises.readdir(e).catch(()=>[])).reduce((e,t)=>{const n=/^(\d{3})(?:-|\.md$)/.exec(t);return n?Math.max(e,Number(n[1])):e},0)+1;for(;;){const n=`${String(t).padStart(3,"0")}-vision-plan-review.md`,a=path__namespace.join(e,n);try{const e=await fs__namespace.promises.open(a,"wx");return await e.close(),a}catch(e){if("EEXIST"!==e.code)throw e;t+=1}}}function visionPlanReviewWriteHandler(){return async(e,t)=>{const n="string"==typeof e?.eventId?e.eventId:"vision-plan-review-write";try{const a=shared.VisionPlanReviewWriteEventSchema.parse(e);assertSafeIssueId(a.issueId);const s=`project/.agentrix/issues/${a.issueId}/review/user`;if(a.reviewDirRelativePath!==s)return void t(failure(n,"Vision Plan review write path does not match the bound issue"));const i=machine.machine.resolveWorkspaceFilePath(a.userId,a.taskId,s);assertInside(i,machine.machine.resolveWorkspaceFilePath(a.userId,a.taskId,`project/.agentrix/issues/${a.issueId}`));const o=await nextReviewFile(i);assertInside(o,i),await fs__namespace.promises.writeFile(o,a.content.endsWith("\n")?a.content:`${a.content}\n`,"utf8");const r=path__namespace.posix.join(s,path__namespace.basename(o)).replace(/^project\//,"");t({eventId:shared.createEventId(),status:"success",opCode:a.eventId,data:{relativePath:r}})}catch(e){machine.logger.error("[VisionPlanReviewWrite] Failed to write review:",e),t(failure(n,e instanceof Error?e.message:"Failed to write Vision Plan review"))}}}const GITLAB_PER_PAGE=100,GITLAB_PAGE_BATCH_SIZE=4,AGENTRIX_TRIGGER_DESCRIPTION="Agentrix webhook bridge",PROXY_ALLOWLIST=[{method:"GET",pattern:/^\/user$/},{method:"GET",pattern:/^\/projects$/},{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 GitLabExecutor{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}withMetadata(e,t={}){return{data:e,metadata:t}}truncateText(e,t=300){return e.length<=t?e:`${e.slice(0,t)}...`}async requestWithResponse(e,t="GET",n){const a=`${this.apiUrl}${e}`,s={Authorization:`Bearer ${this.pat}`,"Content-Type":"application/json"},i=Date.now();try{const o=await fetch(a,{method:t,headers:s,body:n?JSON.stringify(n):void 0}),r=Date.now()-i;if(!o.ok){const n=await o.text().catch(()=>"Unknown error"),a=this.truncateText(n);throw machine.logger.warn(`${this.logPrefix()} request failed: ${t} ${e}, status=${o.status}, elapsedMs=${r}, detail=${a}`),{status:o.status,message:`GitLab API error: ${o.status} ${o.statusText}`,detail:a}}return{data:await o.json(),headers:o.headers,status:o.status}}catch(n){if("object"==typeof n&&null!==n&&"status"in n)throw n;const a=n instanceof Error?n.message:"Unknown network error";throw machine.logger.error(`${this.logPrefix()} request exception: ${t} ${e}, message=${a}`),{status:0,message:`GitLab request failed: ${a}`}}}async requestForm(e,t){const n=`${this.apiUrl}${e}`,a={Authorization:`Bearer ${this.pat}`,"Content-Type":"application/x-www-form-urlencoded"},s=Date.now();try{const i=await fetch(n,{method:"POST",headers:a,body:t}),o=Date.now()-s;if(!i.ok){const t=await i.text().catch(()=>"Unknown error"),n=this.truncateText(t);throw machine.logger.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 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 machine.logger.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:a}=await this.requestWithResponse(e,t,n);return a}withQueryParams(e,t){const[n,a=""]=e.split("?"),s=new URLSearchParams(a);for(const[e,n]of Object.entries(t))s.set(e,String(n));const i=s.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 a=2;a<=e;a+=4){const s=Math.min(a+4-1,e),i=Array.from({length:s-a+1},(e,t)=>a+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:100,page:1}),n=await this.requestWithResponse(t),a=[...n.data],s=this.parseTotalPages(n.headers);if(s&&s>1){const t=await this.fetchRemainingPagesInBatches(s,async t=>{const n=this.withQueryParams(e,{per_page:100,page:t});return this.request(n)});return a.push(...t),a}if(!s&&100===n.data.length){let t=2;for(;;){const n=this.withQueryParams(e,{per_page:100,page:t}),s=await this.request(n);if(0===s.length)break;if(a.push(...s),s.length<100)break;t+=1}}return a}async executeOperation(e,t,n={}){return(await this.executeOperationWithMetadata(e,t,n)).data}async executeOperationWithMetadata(e,t,n={}){n.silent||machine.logger.info(`${this.logPrefix()} execute operation: op=${e}, payloadKeys=${Object.keys(t||{}).join(",")||"-"}`);try{let a;switch(e){case"listRepos":a=this.withMetadata(await this.listRepos());break;case"listBranches":a=this.withMetadata(await this.listBranches(t.owner,t.name));break;case"createMergeRequest":a=this.withMetadata(await this.createMergeRequest(t));break;case"getMergeRequest":a=this.withMetadata(await this.getMergeRequest(t.owner,t.name,t.iid));break;case"listMergeRequests":a=this.withMetadata(await this.listMergeRequests(t.owner,t.name));break;case"triggerPipeline":a=this.withMetadata(await this.triggerPipeline(t));break;case"ensurePipelineTriggerToken":a=this.withMetadata(await this.ensurePipelineTriggerToken(t));break;case"requestGitlabApi":a=await this.requestGitlabApi(t);break;case"resolveGitAuthContext":a=this.withMetadata({authMode:"local_pat",hasPat:!0});break;default:throw{status:400,message:`Unknown operation: ${e}`}}return n.silent||machine.logger.info(`${this.logPrefix()} operation success: op=${e}, summary=${this.summarizeResult(e,a.data)}`),a}catch(t){const a=t instanceof Error?t.message:"object"==typeof t&&null!==t&&"message"in t?String(t.message):"Unknown error";throw n.silent||machine.logger.error(`${this.logPrefix()} operation failed: op=${e}, message=${a}`),t}}async listRepos(){return(await this.requestPaginated("/projects?membership=true&order_by=updated_at&sort=desc")).map(e=>({id:e.id,owner:e.path_with_namespace.split("/").slice(0,-1).join("/")||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 a=encodeURIComponent(`${e}/${t}`),s=await this.request(`/projects/${a}/merge_requests/${n}`);return{number:s.iid,title:s.title,body:s.description,state:"opened"===s.state?"open":s.state,url:s.web_url,head:s.source_branch,base:s.target_branch,createdAt:s.created_at,updatedAt:s.updated_at}}async listMergeRequests(e,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"),a=this.parseOptionalString(e.repo??e.name,"repo");if(!n||!a)throw{status:400,message:"projectId, projectPath, or owner + repo is required"};return encodeURIComponent(`${n}/${a}`)}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,a]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!=a){if("string"!=typeof a&&"number"!=typeof a&&"boolean"!=typeof a)throw{status:400,message:`Pipeline variable value for "${n}" is invalid`};t[n]=String(a)}}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 a=this.parseOptionalString(t.triggerDescription,"triggerDescription")??"Agentrix webhook bridge",s=(await this.requestPaginated(`/projects/${e}/triggers`)).find(e=>e.description===a&&this.isUsableTriggerToken(e.token));if(s?.token)return s.token;const i=new URLSearchParams;i.set("description",a);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"),a=this.parsePipelineVariables(e.variables),s=await this.resolvePipelineTriggerToken(t,e),i=new URLSearchParams;i.set("token",s),i.set("ref",n);for(const[e,t]of Object.entries(a))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,a]of Object.entries(e))if(null!=a)if(Array.isArray(a))for(const e of a){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 a&&"number"!=typeof a&&"boolean"!=typeof a)throw{status:400,message:`Proxy query value for "${n}" is invalid`};t.append(n,String(a))}return t.toString()}isProxyAllowed(e,t){return PROXY_ALLOWLIST.some(n=>n.method===e&&n.pattern.test(t))}async requestGitlabApi(e){const t=this.parseProxyMethod(e.method),n=this.parseProxyPath(e.path),a=this.buildProxyQueryString(e.query),s=a.length>0?`${n}?${a}`:n;if(!this.isProxyAllowed(t,n))throw{status:403,message:`Proxy path not allowed: ${t} ${n}`};if("GET"===t){const e=await this.requestWithResponse(s,t);return this.withMetadata(e.data,{status:e.status})}const i=await this.requestWithResponse(s,t,e.body);return this.withMetadata(i.data,{status:i.status})}}function normalizeBaseUrl$1(e){return e.replace(/\/+$/,"")}function modelUrl(e){const t=normalizeBaseUrl$1(e);return t.endsWith("/v1")?`${t}/models`:`${t}/v1/models`}function inferProtocol(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}function safeEndpointLabel(e){try{const t=new URL(e);return`${t.protocol}//${t.host}${t.pathname.replace(/\/+$/,"")}`}catch{return e}}function summarizeError(e){return axios.isAxiosError(e)?{message:e.message,status:e.response?.status,code:e.code}:{message:e instanceof Error?e.message:String(e)}}async function fetchModels(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}`},a=await axios.get(modelUrl(e.baseUrl),{headers:n,timeout:1e4});return(a.data?.data||[]).map(e=>e&&"object"==typeof e&&"id"in e?String(e.id):null).filter(e=>Boolean(e))}async function fetchEndpointModels(e){const t=inferProtocol(e.baseUrl),n=t?[t]:["anthropic","openai"];let a;for(const s of n){machine.logger.info(`[MODELS] Requesting models: source=${e.source}, protocol=${s}, url=${safeEndpointLabel(modelUrl(e.baseUrl))}, officialProtocol=${t??"none"}`);try{const t=await fetchModels(e,s);return machine.logger.info(`[MODELS] Models request succeeded: source=${e.source}, protocol=${s}, count=${t.length}`),t}catch(t){a=t;const n=summarizeError(t);machine.logger.warn(`[MODELS] Models request failed: source=${e.source}, protocol=${s}, status=${n.status??"-"}, code=${n.code??"-"}, message=${n.message}`)}}throw a instanceof Error?a:new Error("failed to fetch models")}function readJsonFile(e){if(!fs.existsSync(e))return null;try{return JSON.parse(fs.readFileSync(e,"utf-8"))}catch{return null}}function readCodexProvider(){const e=path.join(machine.machine.codexHomeDir,"config.toml");if(!fs.existsSync(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=fs.readFileSync(e,"utf-8"),n=t.match(/^model_provider\s*=\s*"([^"]+)"/m)?.[1]||"openai",a=t.match(/^model\s*=\s*"([^"]+)"/m)?.[1],s=t.match(new RegExp(`\\[model_providers\\.${n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}\\]([\\s\\S]*?)(?=\\n\\[|$)`)),i=s?.[1]||"",o=i.match(/^\s*base_url\s*=\s*"([^"]+)"/m)?.[1]||process.env.OPENAI_BASE_URL||"https://api.openai.com",r=i.match(/^\s*env_key\s*=\s*"([^"]+)"/m)?.[1]||("agentrix"===n?"AGENTRIX_API_KEY":"OPENAI_API_KEY");return{baseUrl:o,apiKey:process.env[r],source:"codex",defaultModel:a}}function resolveClaudeDefaultModel(e,t){const n=t.ANTHROPIC_MODEL||e?.model||process.env.ANTHROPIC_MODEL;if(!n)return;const a=n.toLowerCase();return"opus"===a?t.ANTHROPIC_DEFAULT_OPUS_MODEL||process.env.ANTHROPIC_DEFAULT_OPUS_MODEL||"claude-opus-4-6":"sonnet"===a?t.ANTHROPIC_DEFAULT_SONNET_MODEL||process.env.ANTHROPIC_DEFAULT_SONNET_MODEL||"claude-sonnet-4-6":"haiku"===a?t.ANTHROPIC_DEFAULT_HAIKU_MODEL||process.env.ANTHROPIC_DEFAULT_HAIKU_MODEL||"claude-haiku-4-5":n}function readClaudeProvider(){const e=readJsonFile(path.join(machine.machine.claudeConfigDir,"settings.json")),t=e?.env||{},n=t.ANTHROPIC_BASE_URL||process.env.ANTHROPIC_BASE_URL||"https://api.anthropic.com",a=t.ANTHROPIC_AUTH_TOKEN||t.ANTHROPIC_API_KEY||process.env.ANTHROPIC_AUTH_TOKEN||process.env.ANTHROPIC_API_KEY;return a?{baseUrl:n,apiKey:a,source:"claude",defaultModel:resolveClaudeDefaultModel(e,t)}:null}async function listAvailableModels(e){const t=[];if(!e||"claude"===e){const e=readClaudeProvider();e&&t.push(e)}if(!e||"codex"===e){const e=readCodexProvider();e&&t.push(e)}machine.logger.info(`[MODELS] Listing available models: agentType=${e??"all"}, endpointCount=${t.length}, endpoints=${t.map(e=>`${e.source}:${safeEndpointLabel(e.baseUrl)}:hasKey=${Boolean(e.apiKey)}:defaultModel=${e.defaultModel??"-"}`).join(",")||"-"}`);const n=new Set,a=[],s=t.find(e=>e.defaultModel)?.defaultModel;for(const e of t)try{for(const t of await fetchEndpointModels(e))n.add(t)}catch(t){const n=summarizeError(t);a.push({source:e.source,baseUrl:safeEndpointLabel(e.baseUrl),message:n.message,status:n.status,code:n.code})}const i=Array.from(n).sort();return 0===i.length?machine.logger.warn(`[MODELS] No models available: endpointCount=${t.length}, failures=${JSON.stringify(a)}`):machine.logger.info(`[MODELS] Listed available models: count=${i.length}`),{models:i,defaultModel:s}}function createImmediateFailureAck(e,t){return{eventId:shared.createEventId(),status:"failed",opCode:e,message:t}}function truncateValue(e,t=300){return e.length<=t?e:`${e.slice(0,t)}...`}function getGitlabProxyLogMethod(e){return("string"==typeof e.method&&e.method.trim().length>0?e.method.trim():"GET").toUpperCase()}function getGitlabProxyLogPath(e){return"string"==typeof e.path&&e.path.length>0?e.path:"-"}function getGitlabProxyErrorStatus(e){return"number"==typeof e.status?e.status:0}function logGitlabProxyRequest(e,t){machine.logger.info(`[GITLAB PROXY] reqId=${e.requestId}, gitServer=${e.gitServerId}, method=${t.method}, path=${t.path}, status=${t.status}, elapsedMs=${t.elapsedMs}`)}function createTaskHandler(e){return async(t,n)=>{if(machine.logger.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 machine.logger.error(`[EVENT HANDLER] create-task expects task-message, got ${t.event} for task ${t.taskId}`),void n(createImmediateFailureAck(t.eventId,`create-task expects task-message, got ${t.event}`));try{const a=await e.workerManager.startWorker(t,"create-task");"success"!==a.status&&machine.logger.error(`[EVENT HANDLER] create-task startup failed for task ${t.taskId}: ${a.message||"unknown error"}`),n(a)}catch(e){machine.logger.error(`[EVENT HANDLER] create-task startup threw for task ${t.taskId}:`,e),n(createImmediateFailureAck(t.eventId,e instanceof Error?e.message:"create-task startup failed"))}}}function resumeTaskHandler(e){return async(t,n)=>{machine.logger.debug(`[EVENT HANDLER] resume-task: ${t.taskId}, agentSessionId=${t.agentSessionId}`),"shadow"!==t.taskType&&e.onCompanionInteraction?.(t.chatId);try{const a=await e.workerManager.startWorker(t,"resume-task");"success"!==a.status&&machine.logger.error(`[EVENT HANDLER] resume-task startup failed for task ${t.taskId}: ${a.message||"unknown error"}`),n(a)}catch(e){machine.logger.error(`[EVENT HANDLER] resume-task startup threw for task ${t.taskId}:`,e),n(createImmediateFailureAck(t.eventId,e instanceof Error?e.message:"resume-task startup failed"))}}}function listModelsHandler(e){return async(t,n)=>{if(machine.logger.info(`[EVENT HANDLER] list-models received: machineId=${t.machineId}, agentType=${t.agentType??"all"}, eventId=${t.eventId}`),t.machineId!==e.machineId)return machine.logger.warn(`[EVENT HANDLER] list-models target mismatch: requested=${t.machineId}, current=${e.machineId}`),void n(createImmediateFailureAck(t.eventId,"list-models target machine mismatch"));try{const{models:e,defaultModel:a}=await listAvailableModels(t.agentType);if(0===e.length&&!a)return machine.logger.warn(`[EVENT HANDLER] list-models found no models and no default model: machineId=${t.machineId}, agentType=${t.agentType??"all"}`),void n(createImmediateFailureAck(t.eventId,"No models available from configured endpoints"));machine.logger.info(`[EVENT HANDLER] list-models success: machineId=${t.machineId}, count=${e.length}, defaultModel=${a??"-"}`),n({eventId:shared.createEventId(),status:"success",opCode:t.eventId,data:{models:e,defaultModel:a}})}catch(e){machine.logger.error(`[EVENT HANDLER] list-models failed: machineId=${t.machineId}, agentType=${t.agentType??"all"}:`,e),n(createImmediateFailureAck(t.eventId,e instanceof Error?e.message:"Failed to list models"))}}}function shutdownMachineHandler(e){return async t=>{machine.logger.info("[EVENT HANDLER] shutdown-machine received",t),e.requestShutdown("agentrix-app",t.reason)}}function deployAgentHandler(e){return async(t,n)=>{machine.logger.info(`[EVENT HANDLER] deploy-agent received: taskId=${t.taskId}, draftAgentId=${t.draftAgentId}, targetAgentId=${t.targetAgentId}, sourcePath=${t.sourcePath}`);try{const a=await e.workerManager.startDeploymentWorker(t);"success"!==a.status&&machine.logger.error(`[EVENT HANDLER] deploy-agent startup failed for task ${t.taskId}: ${a.message||"unknown error"}`),n(a)}catch(e){machine.logger.error(`[EVENT HANDLER] deploy-agent startup threw for task ${t.taskId}:`,e),n(createImmediateFailureAck(t.eventId,e instanceof Error?e.message:"deploy-agent startup failed"))}}}function hivePublishHandler(e){return async(t,n)=>{machine.logger.info(`[EVENT HANDLER] hive-publish received: taskId=${t.taskId}, name=${t.name}, repoDir=${t.repoDir}`);try{const a=await e.workerManager.startHivePublishWorker(t);"success"!==a.status&&machine.logger.error(`[EVENT HANDLER] hive-publish startup failed for task ${t.taskId}: ${a.message||"unknown error"}`),n(a)}catch(e){machine.logger.error(`[EVENT HANDLER] hive-publish startup threw for task ${t.taskId}:`,e),n(createImmediateFailureAck(t.eventId,e instanceof Error?e.message:"hive-publish startup failed"))}}}function hiveInstallHandler(e){return async(t,n)=>{machine.logger.info(`[EVENT HANDLER] hive-install received: taskId=${t.taskId}, name=${t.name}, hiveListingId=${t.hiveListingId}`);try{const a=await e.workerManager.startHiveInstallWorker(t);"success"!==a.status&&machine.logger.error(`[EVENT HANDLER] hive-install startup failed for task ${t.taskId}: ${a.message||"unknown error"}`),n(a)}catch(e){machine.logger.error(`[EVENT HANDLER] hive-install startup threw for task ${t.taskId}:`,e),n(createImmediateFailureAck(t.eventId,e instanceof Error?e.message:"hive-install startup failed"))}}}function stopTaskHandler(e){return async t=>{machine.logger.info(`[EVENT HANDLER] stop-task: ${t.taskId}, reason=${t.reason||"n/a"}`),e.workerManager.stopSession(t.taskId)||machine.logger.warn(`[EVENT HANDLER] stop-task failed, task not found: ${t.taskId}`)}}function daemonGitlabRequestHandler(e){return async t=>{const n=Date.now(),a=getGitlabProxyLogMethod(t.payload),s=getGitlabProxyLogPath(t.payload),i=n=>{const a={eventId:t.requestId,requestId:t.requestId,machineId:e.machineId,...n};e.client?e.client.send("daemon-gitlab-response",a):machine.logger.error(`[GITLAB PROXY] response dropped: reqId=${t.requestId}, op=${t.operation}, reason=socket-client-unavailable`)};try{const e=t.accessToken?.trim();if(!e){const e=Date.now()-n;return machine.logger.warn(`[GITLAB PROXY] access token missing: reqId=${t.requestId}, op=${t.operation}, gitServer=${t.gitServerId}`),logGitlabProxyRequest(t,{method:a,path:s,status:0,elapsedMs:e}),void i({success:!1,errorCode:"PAT_MISSING",errorMessage:`No access token provided for git server ${t.gitServerId}`,executionTimeMs:e})}const o=t.payload.apiUrl;if(!o){const e=Date.now()-n;return machine.logger.warn(`[GITLAB PROXY] apiUrl missing in payload: reqId=${t.requestId}, op=${t.operation}, gitServer=${t.gitServerId}`),logGitlabProxyRequest(t,{method:a,path:s,status:0,elapsedMs:e}),void i({success:!1,errorCode:"PAT_MISSING",errorMessage:"GitLab API URL not provided in request",executionTimeMs:e})}const r=new GitLabExecutor(o,e,{requestId:t.requestId,gitServerId:t.gitServerId}),c=await r.executeOperationWithMetadata(t.operation,t.payload,{silent:!0}),l=Date.now()-n;logGitlabProxyRequest(t,{method:a,path:s,status:c.metadata.status??200,elapsedMs:l}),i({success:!0,data:c.data,executionTimeMs:l})}catch(e){const o=e;let r="GITLAB_CONNECTIVITY_FAILED";401===o.status?r="PAT_INVALID":403===o.status?r="PAT_SCOPE_INSUFFICIENT":404===o.status&&(r="RESOURCE_NOT_FOUND");const c="string"==typeof o.message?o.message:"Unknown error",l="string"==typeof o.detail?truncateValue(o.detail):void 0,d=getGitlabProxyErrorStatus(o),p=Date.now()-n;logGitlabProxyRequest(t,{method:a,path:s,status:d,elapsedMs:p}),machine.logger.error(`[GITLAB PROXY] execution failed: reqId=${t.requestId}, op=${t.operation}, errorCode=${r}, status=${d}, message=${c}${l?`, detail=${l}`:""}`),i({success:!1,errorCode:r,errorMessage:c,executionTimeMs:p})}}}function machineControlCommandHandler(e){return async(t,n)=>{e.machineControl?e.machineControl.handleCommand(t,n):n(createImmediateFailureAck(t.eventId,"Machine control is not available"))}}function workspaceCacheUpdateHandler(e){return async(t,n)=>{if(e.workspaceStatusSync)try{await e.workspaceStatusSync.applyCacheUpdate(t),n({eventId:shared.createEventId(),status:"success",opCode:t.eventId})}catch(e){machine.logger.warn("[WORKSPACE SYNC] Failed to apply workspace cache update",e),n(createImmediateFailureAck(t.eventId,e instanceof Error?e.message:"Failed to apply workspace cache update"))}else n(createImmediateFailureAck(t.eventId,"Workspace sync is not available"))}}function createEventHandlers(e){return{"create-task":createTaskHandler(e),"resume-task":resumeTaskHandler(e),"list-models":listModelsHandler(e),"stop-task":stopTaskHandler(e),"deploy-agent":deployAgentHandler(e),"hive-publish":hivePublishHandler(e),"hive-install":hiveInstallHandler(e),"shutdown-machine":shutdownMachineHandler(e),"workspace-file-request":workspaceFileRequestHandler({client:e.client}),"workspace-file-mutation-request":workspaceFileMutationRequestHandler({client:e.client}),"vision-plan-review-write":visionPlanReviewWriteHandler(),"daemon-gitlab-request":daemonGitlabRequestHandler(e),"machine-control-command":machineControlCommandHandler(e),"workspace-cache-update":workspaceCacheUpdateHandler(e)}}const CHUNK_SIZE=65536,DEFAULT_MAX_FILE_SIZE_MB=parseInt(process.env.MAX_WORKSPACE_FILE_SIZE_MB||"100",10);function getPeerConnectionConstructor(e){return e.RTCPeerConnection||e.PeerConnection||e.RTCConnection||e.PeerConnection}function normalizeIceServers(e){const t=[];return e.forEach(e=>{Array.isArray(e.urls)?t.push(...e.urls):t.push(e.urls)}),t}function sendChannelMessage(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)}function normalizeSignalDescription(e,t){return e&&"object"==typeof e&&"string"==typeof e.sdp?{sdp:e.sdp,type:e.type||t}:{sdp:String(e||""),type:t}}function normalizeCandidate(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}function resolveFilePath(e,t,n){if(n.startsWith("channel-attachment/")){const e=n.slice(19);return resolveChannelFilePath(decodeURIComponent(e))}return machine.machine.resolveWorkspaceFilePath(e,t,n)}function isWithinWorkspaceBase(e,t,n,a){const s=n.replace(/^\/+/,""),i="project"===s||s.startsWith("project/")?"project":"data"===s||s.startsWith("data/")?"data":"",o=path__namespace.normalize(machine.machine.resolveWorkspaceFilePath(e,t,i)),r=path__namespace.normalize(a);return r===o||r.startsWith(o+path__namespace.sep)}function isFileModified(e,t){return!t||e.mtime.toISOString()!==t}class MachineRtcManager{client;machineId;iceServers=[];sessions=new Map;rtcModule={};peerConstructor;constructor(e,t){this.client=e,this.machineId=t;const n=node_module.createRequire("undefined"==typeof document?require("url").pathToFileURL(__filename).href:_documentCurrentScript&&"SCRIPT"===_documentCurrentScript.tagName.toUpperCase()&&_documentCurrentScript.src||new URL("index.cjs",document.baseURI).href);try{this.rtcModule=n("node-datachannel"),this.peerConstructor=getPeerConnectionConstructor(this.rtcModule),this.rtcModule.setDebugLevel?.("warning")}catch(e){const t=e instanceof Error?e.message:String(e);machine.logger.warn(`[RTC] node-datachannel unavailable; RTC support disabled: ${t}`)}}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))):machine.logger.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:shared.createEventId()})}handleIceServersResponse(e){this.iceServers=normalizeIceServers(e.iceServers),machine.logger.info(`[RTC] Loaded ${this.iceServers.length} ICE servers`)}handleRtcRequest(e){if(!this.peerConstructor)return;const t=e.userId;if(!t)return void machine.logger.warn("[RTC] machine-rtc-request missing userId");const n=e.workspaceUserId||t,a=e.taskId;if(this.sessions.has(e.sessionId))return void this.sendMachineRtcResponse(e.sessionId,t,!0);const s=new this.peerConstructor(e.sessionId,{iceServers:this.iceServers}),i={sessionId:e.sessionId,userId:t,workspaceUserId:n,allowedTaskId:a||void 0,peerConnection:s,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,a){this.client.send("machine-rtc-response",{eventId:shared.createEventId(),machineId:this.machineId,sessionId:e,accepted:n,reason:a,userId:t,capabilities:{dataChannel:!0}})}handleRtcSignal(e){if(!this.peerConstructor)return;if("app"!==e.from)return;const t=e.userId;if(!t)return void machine.logger.warn("[RTC] rtc-signal missing userId");const n=e.workspaceUserId||t,a=e.taskId;let s=this.sessions.get(e.sessionId);if(!s){const i=new this.peerConstructor(e.sessionId,{iceServers:this.iceServers});s={sessionId:e.sessionId,userId:t,workspaceUserId:n,allowedTaskId:a||void 0,peerConnection:i,lastActivity:Date.now(),remoteDescriptionSet:!1,pendingCandidates:[]},this.sessions.set(e.sessionId,s),this.registerPeerHandlers(s)}try{this.applyRemoteSignal(s,e.signal)}catch(e){machine.logger.warn("[RTC] Failed to apply remote signal",e)}}registerPeerHandlers(e){const{peerConnection:t}=e;t.onStateChange?.(t=>{machine.logger.info(`[RTC] Peer state (${e.sessionId}): ${t}`)}),t.onGatheringStateChange?.(t=>{machine.logger.info(`[RTC] ICE gathering (${e.sessionId}): ${t}`)}),t.onLocalDescription?.((t,n)=>{const a=normalizeSignalDescription(t,n);this.client.send("rtc-signal",{eventId:shared.createEventId(),machineId:this.machineId,sessionId:e.sessionId,from:"machine",signal:a,userId:e.userId})}),t.onLocalCandidate?.((t,n,a)=>{const s=normalizeCandidate(t,n,a);s&&this.client.send("rtc-signal",{eventId:shared.createEventId(),machineId:this.machineId,sessionId:e.sessionId,from:"machine",signal:{candidate:s},userId:e.userId})}),t.onDataChannel?.(t=>{e.dataChannel=t,this.registerDataChannel(e,t)})}registerDataChannel(e,t){t.onOpen?.(()=>{machine.logger.info(`[RTC] Data channel open (${e.sessionId})`),e.lastActivity=Date.now(),sendChannelMessage(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?.(()=>{machine.logger.warn(`[RTC] Data channel closed (${e.sessionId})`),e.peerConnection.close?.(),this.sessions.delete(e.sessionId)}),t.onError?.(t=>{machine.logger.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{shared.splitRtcChunkFrame(new Uint8Array(t))}catch(e){machine.logger.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 a=null;try{a=JSON.parse(n)}catch(e){return void machine.logger.warn("[RTC] Non-JSON message",n)}a&&"string"==typeof a.type&&("file.request"!==a.type?"file.mutate"===a.type&&this.handleFileMutation(e,a).catch(e=>{machine.logger.error("[RTC] Failed to handle file mutation",e)}):this.handleFileRequest(e,a).catch(e=>{machine.logger.error("[RTC] Failed to handle file request",e)}))}validateFilePayload(e,t){const n=t.payload;return n?n.userId!==e.workspaceUserId?(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"}}),null):e.allowedTaskId&&n.taskId!==e.allowedTaskId?(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"}}),null):n:null}assertWorkspacePath(e,t,n){if(n.startsWith("channel-attachment/"))throw Object.assign(new Error("Channel attachments are read-only"),{code:"permission_denied"});const a=resolveFilePath(e,t,n);if(!isWithinWorkspaceBase(e,t,n,a))throw Object.assign(new Error("Path escapes workspace"),{code:"permission_denied"});return a}async handleFileRequest(e,t){const n=this.validateFilePayload(e,t);if(!n)return;const a=resolveFilePath(n.userId,n.taskId,n.relativePath);if(!fs__namespace.existsSync(a))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 s=await fs__namespace.promises.stat(a);if(!isFileModified(s,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(s.isDirectory()||"directory"===n.entryType){const n=await fs__namespace.promises.readdir(a,{withFileTypes:!0}),i={entries:await Promise.all(n.map(async e=>{const t=path__namespace.join(a,e.name),n=await fs__namespace.promises.stat(t);return{name:e.name,type:e.isDirectory()?"directory":"file",size:n.size,modifiedAt:n.mtime.toISOString()}})),modifiedAt:s.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:i})}const i=1024*(n.maxFileSizeMB??DEFAULT_MAX_FILE_SIZE_MB)*1024;if(s.size>i)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 o=mimeTypesExports.lookup(a)||"application/octet-stream",r={size:s.size,mimeType:"string"==typeof o?o:"application/octet-stream",modifiedAt:s.mtime.toISOString()};this.sendControl(e,{v:1,type:"file.meta",channel:"file",requestId:t.requestId,streamId:t.streamId,timestamp:(new Date).toISOString(),payload:r}),await this.sendFileChunks(e,t.streamId,a),this.sendControl(e,{v:1,type:"file.end",channel:"file",requestId:t.requestId,streamId:t.streamId,timestamp:(new Date).toISOString(),payload:{size:s.size}})}async handleFileMutation(e,t){const n=this.validateFilePayload(e,t);if(n)try{const a=this.assertWorkspacePath(n.userId,n.taskId,n.relativePath);if("delete"===n.operation)return await fs__namespace.promises.rm(a,{force:!1}),void this.sendMutationAck(e,t,{relativePath:n.relativePath,operation:n.operation});if(void 0===n.content)throw Object.assign(new Error("File content is required"),{code:"bad_request"});await fs__namespace.promises.mkdir(path__namespace.dirname(a),{recursive:!0});try{await fs__namespace.promises.writeFile(a,n.content,n.createOnly?{flag:"wx"}:void 0)}catch(e){if("EEXIST"===e.code)throw Object.assign(new Error("File already exists"),{code:"file_exists"});throw e}const s=await fs__namespace.promises.stat(a);this.sendMutationAck(e,t,{relativePath:n.relativePath,operation:n.operation,modifiedAt:s.mtime.toISOString()})}catch(n){this.sendControl(e,{v:1,type:"file.error",channel:"file",requestId:t.requestId,streamId:t.streamId,timestamp:(new Date).toISOString(),error:{code:n.code||"unknown_error",message:n.message||"File mutation failed"}})}}sendMutationAck(e,t,n){this.sendControl(e,{v:1,type:"file.mutation_ack",channel:"file",requestId:t.requestId,streamId:t.streamId,timestamp:(new Date).toISOString(),payload:n})}async sendFileChunks(e,t,n){const a=e.dataChannel;if(!a)return;const s=fs__namespace.createReadStream(n,{highWaterMark:65536});let i=0;await new Promise((e,n)=>{s.on("data",e=>{const n=shared.RtcChunkFlags.Binary|(0===i?shared.RtcChunkFlags.Start:0),s=Buffer.isBuffer(e)?e:Buffer.from(e),o=new Uint8Array(s.buffer,s.byteOffset,s.byteLength),r=shared.buildRtcChunkFrame({streamId:t,seq:i,flags:n,payloadLength:o.length},o);sendChannelMessage(a,r),i+=1}),s.on("end",()=>{if(i>0){const e=shared.buildRtcChunkFrame({streamId:t,seq:i,flags:shared.RtcChunkFlags.End|shared.RtcChunkFlags.Binary,payloadLength:0},new Uint8Array);sendChannelMessage(a,e)}e()}),s.on("error",e=>n(e))})}sendControl(e,t){const n=e.dataChannel;n&&sendChannelMessage(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){machine.logger.warn("[RTC] Failed to add queued candidate",e)}}),void(e.pendingCandidates=[]);if(t&&t.candidate){const a=t.candidate,s="string"==typeof a?a:a&&"string"==typeof a.candidate?a.candidate:null,i=t.sdpMid||a?.sdpMid||a?.mid||"0";if(s){if(!e.remoteDescriptionSet)return void e.pendingCandidates?.push({candidate:s,mid:i});n.addRemoteCandidate?.(s,i)}}}}class MachineClient{client;context;rtcManager;constructor(e,t,n){const{machineId:a,...s}=e;this.client=new SocketClient(s),this.context={machineId:a,workerManager:t,requestShutdown:n.requestShutdown,client:this.client,machineControl:n.machineControl,workspaceStatusSync:n.workspaceStatusSync},this.rtcManager=new MachineRtcManager(this.client,a),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=createEventHandlers(this.context);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.onEventWithAck("machine-control-command",e["machine-control-command"]),this.client.onEventWithAck("workspace-cache-update",e["workspace-cache-update"]),this.client.onEvent("shutdown-machine",e["shutdown-machine"]),this.client.onEvent("workspace-file-request",e["workspace-file-request"]),this.client.onEvent("workspace-file-mutation-request",e["workspace-file-mutation-request"]),this.client.onEventWithAck("vision-plan-review-write",e["vision-plan-review-write"]),this.client.onEvent("daemon-gitlab-request",e["daemon-gitlab-request"])}}let caffeinateProcess=null;function startCaffeinate(){if(machine.machine.disableCaffeinate)return machine.logger.debug("[caffeinate] Caffeinate disabled via AGENTRIX_DISABLE_CAFFEINATE environment variable"),!1;if("darwin"!==process.platform)return machine.logger.debug("[caffeinate] Not on macOS, skipping caffeinate"),!1;if(caffeinateProcess&&!caffeinateProcess.killed)return machine.logger.debug("[caffeinate] Caffeinate already running"),!0;try{return caffeinateProcess=child_process.spawn("caffeinate",["-im"],{stdio:"ignore",detached:!1}),caffeinateProcess.on("error",e=>{machine.logger.debug("[caffeinate] Error starting caffeinate:",e),caffeinateProcess=null}),caffeinateProcess.on("exit",(e,t)=>{machine.logger.debug(`[caffeinate] Process exited with code ${e}, signal ${t}`),caffeinateProcess=null}),machine.logger.info(`[caffeinate] Started with PID ${caffeinateProcess.pid}`),setupCleanupHandlers(),!0}catch(e){return machine.logger.info("[caffeinate] Failed to start caffeinate:",e),!1}}let isStopping=!1;async function stopCaffeinate(){if(isStopping)machine.logger.info("[caffeinate] Already stopping, skipping");else if(caffeinateProcess&&!caffeinateProcess.killed){isStopping=!0,machine.logger.info(`[caffeinate] Stopping caffeinate process PID ${caffeinateProcess.pid}`);try{caffeinateProcess.kill("SIGTERM"),await new Promise(e=>setTimeout(e,1e3)),caffeinateProcess&&!caffeinateProcess.killed&&caffeinateProcess.kill("SIGKILL"),caffeinateProcess=null,isStopping=!1}catch(e){machine.logger.info("[caffeinate] Error stopping caffeinate:",e),isStopping=!1}}}let cleanupHandlersSet=!1;function setupCleanupHandlers(){if(cleanupHandlersSet)return;cleanupHandlersSet=!0;const e=()=>{stopCaffeinate()};process.on("exit",e),process.on("SIGINT",e),process.on("SIGTERM",e),process.on("SIGUSR1",e),process.on("SIGUSR2",e),process.on("uncaughtException",t=>{machine.logger.debug("[caffeinate] Uncaught exception, cleaning up:",t),e()}),process.on("unhandledRejection",(t,n)=>{machine.logger.debug("[caffeinate] Unhandled rejection, cleaning up:",t),e()})}function parseAgentrixProcess(e){const{pid:t,name:n,cmd:a}=e;if(t===process.pid||t===process.ppid)return null;if(!(n.includes("agentrix")||"node"===n&&(a.includes("agentrix-cli")||a.includes("dist/index.mjs")||a.includes("dist\\index.mjs"))||("MainThread"===n||n.includes("MainThread"))&&(a.includes("agentrix-cli")||a.includes("dist/index.mjs")||a.includes("agentrix.mjs"))||a.includes("agentrix.mjs")||a.includes("agentrix-cli")||a.includes("tsx")&&a.includes("src/index.ts")&&a.includes("agentrix-cli")))return null;let s="unknown";const i=a.toLowerCase();return i.includes(" worker")?s="worker":i.includes(" daemon")?s="daemon":i.includes("doctor")&&(s="doctor"),{pid:t,command:a||n,type:s}}async function getWindowsProcessList(){try{const e=child_process.execSync("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 a=n[e];if(!a)continue;const s=a.indexOf(",");if(-1===s)continue;const i=a.substring(s+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[]}}async function findAllAgentrixProcesses(){try{let e;e="win32"===process.platform?await getWindowsProcessList():(await psList()).map(e=>({pid:e.pid,name:e.name||"",cmd:e.cmd||""}));const t=[];for(const n of e){const e=parseAgentrixProcess(n);e&&t.push(e)}return t}catch(e){return[]}}async function findRunawayAgentrixProcesses(){return(await findAllAgentrixProcesses()).filter(e=>e.pid!==process.pid&&("daemon"===e.type||"worker"===e.type)).map(e=>({pid:e.pid,command:e.command}))}async function killRunawayAgentrixProcesses(){const e=await findRunawayAgentrixProcesses(),t=[];let n=0;for(const{pid:a,command:s}of e)try{if(console.log(`Killing runaway process PID ${a}: ${s}`),"win32"===process.platform){const e=spawn.sync("taskkill",["/F","/PID",a.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(a,"SIGTERM"),await new Promise(e=>setTimeout(e,1e3));(await psList()).find(e=>e.pid===a)&&(console.log(`Process PID ${a} ignored SIGTERM, using SIGKILL`),process.kill(a,"SIGKILL"))}console.log(`Successfully killed runaway process PID ${a}`),n++}catch(e){const n=e.message;t.push({pid:a,error:n}),console.log(`Failed to kill process PID ${a}: ${n}`)}return{killed:n,errors:t}}function isCommandAvailable$1(e){try{const t="win32"===process.platform?"where":"which";return{available:!0,path:child_process.execSync(`${t} ${e}`,{encoding:"utf-8",stdio:["pipe","pipe","ignore"]}).trim()}}catch{return{available:!1}}}function getSandboxDependencies(e){if("macos"===e){const e=isCommandAvailable$1("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=isCommandAvailable$1("bwrap"),t=isCommandAvailable$1("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[]}function getCliDependencies(){const e=isCommandAvailable$1("git"),t=isCommandAvailable$1("claude"),n=isCommandAvailable$1("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}]}function checkAllDependencies(){const e=platform_js.getPlatform(),t=getCliDependencies(),n=getSandboxDependencies(e),a=t.filter(e=>e.required&&!e.installed),s=n.filter(e=>e.required&&!e.installed);return{cli:t,sandbox:n,allSatisfied:0===a.length&&0===s.length,missingSandbox:s,missingCli:a}}function displayDependencyStatus(e=!1){const t=checkAllDependencies(),n=platform_js.getPlatform();console.log(chalk.bold("\n🔧 CLI Dependencies"));for(const n of t.cli)if(n.installed)console.log(chalk.green(`✓ ${n.name}`),chalk.gray(`- ${n.description}`)),e&&n.path&&console.log(chalk.gray(` Location: ${n.path}`));else{const e=n.required?chalk.red("❌"):chalk.yellow("⚠️");console.log(`${e} ${n.name}`,chalk.gray(`- ${n.description}`)),n.installCommand&&console.log(chalk.blue(` Install: ${n.installCommand}`))}if(t.sandbox.length>0){console.log(chalk.bold("\n🔒 Sandbox Dependencies")),console.log(chalk.gray(`Platform: ${n}`));for(const n of t.sandbox)n.installed?(console.log(chalk.green(`✓ ${n.name}`),chalk.gray(`- ${n.description}`)),e&&n.path&&console.log(chalk.gray(` Location: ${n.path}`))):(console.log(chalk.red(`❌ ${n.name}`),chalk.gray(`- ${n.description}`)),n.installCommand&&console.log(chalk.blue(` Install: ${n.installCommand}`)))}else console.log(chalk.bold("\n🔒 Sandbox Dependencies")),console.log(chalk.yellow(`⚠️ Platform ${n} not supported - sandbox will be disabled`));if(t.allSatisfied)return console.log(chalk.bold.green("\n✓ All required dependencies are installed")),!0;{console.log(chalk.bold.red("\n⚠️ Missing Required Dependencies"));const e=[...t.missingCli,...t.missingSandbox];for(const t of e)console.log(chalk.red(` • ${t.name}`));return console.log(chalk.yellow("\nPlease install missing dependencies before starting the daemon.")),!1}}function checkCriticalDependencies(){const e=checkAllDependencies(),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 getEnvironmentInfo(){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:machine.machine.agentrixHomeDir,serverUrl:machine.machine.serverUrl,logsDir:machine.machine.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 runDoctorCommand(e){if(e||(e="all"),console.log(chalk.bold.cyan("\n🩺 Agentrix CLI Doctor\n")),"all"===e){console.log(chalk.bold("📋 Basic Information")),console.log(`Agentrix CLI Version: ${chalk.green(machine.packageJson.version)}`),console.log(`Platform: ${chalk.green(process.platform)} ${process.arch}`),console.log(`Node.js Version: ${chalk.green(process.version)}`),console.log(""),console.log(chalk.bold("🔧 Daemon Spawn Diagnostics"));const e=machine.projectPath(),t=path.join(e,"bin","agentrix.mjs"),n=path.join(e,"dist","index.mjs");console.log(`Project Root: ${chalk.blue(e)}`),console.log(`Wrapper Script: ${chalk.blue(t)}`),console.log(`CLI Entrypoint: ${chalk.blue(n)}`),console.log(`Wrapper Exists: ${fs.existsSync(t)?chalk.green("✓ Yes"):chalk.red("❌ No")}`),console.log(`CLI Exists: ${fs.existsSync(n)?chalk.green("✓ Yes"):chalk.red("❌ No")}`),console.log(""),console.log(chalk.bold("⚙️ Configuration")),console.log(`Agentrix Home: ${chalk.blue(machine.machine.agentrixHomeDir)}`),console.log(`Server URL: ${chalk.blue(machine.machine.serverUrl)}`),console.log(`Logs Dir: ${chalk.blue(machine.machine.getStatePaths().logsDir)}`),console.log(chalk.bold("\n🌍 Environment Variables"));const a=getEnvironmentInfo();console.log(`AGENTRIX_HOME_DIR: ${a.AGENTRIX_HOME_DIR?chalk.green(a.AGENTRIX_HOME_DIR):chalk.gray("not set")}`),console.log(`AGENTRIX_SERVER_URL: ${a.AGENTRIX_SERVER_URL?chalk.green(a.AGENTRIX_SERVER_URL):chalk.gray("not set")}`),console.log(`DANGEROUSLY_LOG_TO_SERVER: ${a.DANGEROUSLY_LOG_TO_SERVER_FOR_AI_AUTO_DEBUGGING?chalk.yellow("ENABLED"):chalk.gray("not set")}`),console.log(`DEBUG: ${a.DEBUG?chalk.green(a.DEBUG):chalk.gray("not set")}`),console.log(`NODE_ENV: ${a.NODE_ENV?chalk.green(a.NODE_ENV):chalk.gray("not set")}`),console.log(chalk.bold("\n🔐 Authentication"));try{await machine.machine.readCredentials()?console.log(chalk.green("✓ Authenticated (credentials found)")):console.log(chalk.yellow("⚠️ Not authenticated (no credentials)"))}catch(e){console.log(chalk.red("❌ Error reading credentials"))}displayDependencyStatus(!0)}console.log(chalk.bold("\n🤖 Daemon Status"));try{const t=await checkIfDaemonRunningAndCleanupStaleState(),n=await machine.machine.readDaemonState();if(t&&n?(console.log(chalk.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(chalk.yellow("⚠️ Daemon state exists but process not running (stale)")):console.log(chalk.red("❌ Daemon is not running")),n){console.log(chalk.bold("\n📄 Daemon State:"));const e=machine.machine.getStatePaths();console.log(chalk.blue(`Location: ${e.daemonStateFile}`)),console.log(chalk.gray(JSON.stringify(n,null,2)))}const a=await findAllAgentrixProcesses();if(a.length>0){console.log(chalk.bold("\n🔍 All Agentrix CLI Processes"));const e=a.reduce((e,t)=>(e[t.type]||(e[t.type]=[]),e[t.type].push(t),e),{});Object.entries(e).forEach(([e,t])=>{console.log(chalk.blue(`\n${{daemon:"🤖 Daemon",worker:"🔗 Workers",doctor:"🩺 Doctor",unknown:"❓ Unknown"}[e]||e}:`)),t.forEach(({pid:t,command:n})=>{const a=e.startsWith("dev")?chalk.cyan:e.includes("daemon")?chalk.blue:chalk.gray;console.log(` ${a(`PID ${t}`)}: ${chalk.gray(n)}`)})})}else console.log(chalk.red("❌ No agentrix processes found"));"all"===e&&a.length>1&&(console.log(chalk.bold("\n💡 Process Management")),console.log(chalk.gray("To clean up runaway processes: agentrix killall")))}catch(e){console.log(chalk.red("❌ Error checking daemon status"))}}const CACHE_TTL_MS=6048e5;let cachedOpeners=null;async function listOpeners(){const e=getOpenerOverrides(),t=getOpenerOverridesSignature(e);if(cachedOpeners&&cachedOpeners.expiresAt>Date.now()&&cachedOpeners.overridesSignature===t)return cachedOpeners.openers;const n=getOpenerDefinitions(e),a=[];for(const e of n){const t=e.isSupported();t&&a.push({id:e.id,label:e.label,kind:e.kind,method:e.method,urlTemplate:e.urlTemplate,supported:t})}return cachedOpeners={expiresAt:Date.now()+6048e5,openers:a,overridesSignature:t},a}async function openWithOpener({openerId:e,targetPath:t,userId:n,taskId:a}){const s=getOpenerDefinitions(getOpenerOverrides()).find(t=>t.id===e);if(!s)return{success:!1,error:"Unknown openerId"};if("cli"!==s.method||!s.open)return{success:!1,error:"Opener is not executable by CLI"};if(!s.isSupported())return{success:!1,error:"Opener is not supported on this system"};let i;try{i=resolveTargetPath(t,n,a)}catch(e){return{success:!1,error:e instanceof Error?e.message:"Invalid path"}}try{return s.open(i),{success:!0}}catch(e){const t=e instanceof Error?e.message:"Failed to open path";return machine.logger.warn(`[OPENERS] Failed to open path: ${t}`),{success:!1,error:t}}}function pickDirectory(e){const t=process.platform;if("darwin"===t)return pickDirectoryMac(e);if("win32"===t)return pickDirectoryWindows(e);if("linux"===t)return pickDirectoryLinux(e);throw new Error("Directory picker is not supported on this platform")}function resolveTargetPath(e,t,n){const a=path.resolve(e);if(!path.isAbsolute(a))throw new Error("Path must be absolute");if(!fs.statSync(a).isDirectory())throw new Error("Path must be a directory");if(t&&n){const e=machine.machine.getTaskCwd(t,n);if(e&&!isSubPath(a,path.resolve(e)))throw new Error("Path is outside the task workspace")}return a}function isSubPath(e,t){const n=path.relative(t,e);return""===n||!n.startsWith("..")&&!path.isAbsolute(n)}function getOpenerDefinitions(e){const t=process.platform,n=["Visual Studio Code","Visual Studio Code - Insiders"],a=["Cursor"],s=["IntelliJ IDEA","IntelliJ IDEA CE","IntelliJ IDEA Ultimate"],i=["WebStorm"],o=["PyCharm","PyCharm CE","PyCharm Professional"];return applyOpenerOverrides([{id:"vscode",label:"VS Code",kind:"editor",method:"scheme",urlTemplate:"vscode://file/{path}?windowId=_blank",scheme:"vscode",macAppNames:n,isSupported:()=>isSchemeRegistered("vscode",t,n)},{id:"cursor",label:"Cursor",kind:"editor",method:"scheme",urlTemplate:"cursor://file/{path}?windowId=_blank",scheme:"cursor",macAppNames:a,isSupported:()=>isSchemeRegistered("cursor",t,a)},{id:"idea",label:"IntelliJ IDEA",kind:"ide",method:"scheme",urlTemplate:"idea://open?file={path}&newWindow=true",scheme:"idea",macAppNames:s,isSupported:()=>isSchemeRegistered("idea",t,s)},{id:"pycharm",label:"PyCharm",kind:"ide",method:"scheme",urlTemplate:"pycharm://open?file={path}&newWindow=true",scheme:"pycharm",macAppNames:o,isSupported:()=>isSchemeRegistered("pycharm",t,o)},{id:"webstorm",label:"WebStorm",kind:"ide",method:"scheme",urlTemplate:"webstorm://open?file={path}&newWindow=true",scheme:"webstorm",macAppNames:i,isSupported:()=>isSchemeRegistered("webstorm",t,i)},{id:"terminal",label:"Terminal",kind:"terminal",method:"cli",isSupported:()=>isTerminalSupported(t),open:e=>openInTerminal(e,t)},{id:"file-manager",label:"darwin"===t?"Finder":"win32"===t?"Explorer":"Files",kind:"file-manager",method:"cli",isSupported:()=>isFileManagerSupported(t),open:e=>openInFileManager(e,t)},{id:"open-with",label:"Open With...",kind:"system",method:"cli",isSupported:()=>isOpenWithSupported(t),open:e=>openWithChooser(e,t)}],t,e)}function pickDirectoryMac(e){const t=resolvePickerDefaultPath(e),n=[];if(t){const e=escapeAppleScriptString(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"),normalizePickerOutput(runCommand$1("osascript",n,{captureOutput:!0}))}function pickDirectoryWindows(e){const t=commandExists$1("powershell")?"powershell":commandExists$1("pwsh")?"pwsh":null;if(!t)throw new Error("PowerShell is required to pick a directory");const n=resolvePickerDefaultPath(e),a=["Add-Type -AssemblyName System.Windows.Forms;","$dialog = New-Object System.Windows.Forms.FolderBrowserDialog;",n?`$dialog.SelectedPath = '${escapePowerShellString(n)}';`:"","$null = $dialog.ShowDialog();","$dialog.SelectedPath;"].filter(Boolean).join(" ");return normalizePickerOutput(runCommand$1(t,"powershell"===t?["-NoProfile","-STA","-Command",a]:["-NoProfile","-Sta","-Command",a],{captureOutput:!0}))}function pickDirectoryLinux(e){const t=resolvePickerDefaultPath(e);if(commandExists$1("zenity")){const e=["--file-selection","--directory","--title=Select Folder"];if(t){const n=t.endsWith("/")?t:`${t}/`;e.push(`--filename=${n}`)}return normalizePickerOutput(runCommand$1("zenity",e,{captureOutput:!0}))}if(commandExists$1("kdialog")){const e=["--getexistingdirectory"];return t&&e.push(t),normalizePickerOutput(runCommand$1("kdialog",e,{captureOutput:!0}))}throw new Error("No supported directory picker is available")}function resolvePickerDefaultPath(e){if(!e)return;const t=e.replace(/^~(?=$|[\\/])/,os.homedir());if(fs.existsSync(t)){try{if(!fs.statSync(t).isDirectory())return}catch{return}return t}}function normalizePickerOutput(e){if(!e)return null;return e.trim()||null}function isOpenWithSupported(e){return"darwin"===e?commandExists$1("osascript"):"win32"===e?commandExists$1("powershell")||commandExists$1("pwsh"):"linux"===e&&commandExists$1("gio")}function isFileManagerSupported(e){return"darwin"===e?commandExists$1("open"):"win32"===e||"linux"===e&&(commandExists$1("xdg-open")||commandExists$1("gio"))}function isTerminalSupported(e){return"darwin"===e?commandExists$1("osascript")&&isMacAppInstalled("Terminal"):"win32"===e?commandExists$1("wt")||commandExists$1("powershell")||commandExists$1("pwsh")||commandExists$1("cmd"):"linux"===e&&Boolean(getLinuxTerminalCommand())}function openInTerminal(e,t){if("darwin"!==t){if("win32"===t){if(commandExists$1("wt"))return void launchDetached("wt",["-d",e]);const t=commandExists$1("powershell")?"powershell":commandExists$1("pwsh")?"pwsh":null;return t?void launchDetached(t,["-NoExit","-Command",`Set-Location -LiteralPath '${escapePowerShellString(e)}'`]):void launchDetached("cmd",["/K",`cd /d "${e.replace(/"/g,'""')}"`])}if("linux"===t){const t=getLinuxTerminalCommand();if(!t)throw new Error("No supported terminal is available");return void launchDetached(t.command,t.args(e))}throw new Error("Terminal open is not supported on this platform")}if(!runCommand$1("osascript",["-e",'tell application "Terminal"',"-e",`do script "${escapeAppleScriptString(`cd ${shellQuotePosix(e)}`)}"`,"-e","activate","-e","end tell"]))throw new Error("Failed to open Terminal")}function openWithChooser(e,t){if("darwin"!==t)if("win32"!==t){if("linux"!==t)throw new Error("Open With is not supported on this platform");runCommand$1("gio",["open","--ask",e])}else runCommand$1(commandExists$1("powershell")?"powershell":"pwsh",["-NoProfile","-Command",`Start-Process -Verb OpenAs -FilePath '${escapePowerShellString(e)}'`]);else if(null===runCommand$1("osascript",["-e",`set targetPath to POSIX file "${escapeAppleScriptString(e)}"`,"-e","set appChoice to choose application","-e","tell appChoice to open targetPath"],{captureOutput:!0}))throw new Error("No application selected")}function getLinuxTerminalCommand(){const e=shellQuotePosix(process.env.SHELL||"/bin/sh"),t=process.env.TERMINAL;return t&&isSafeCommandReference(t)&&commandExists$1(t)?{command:t,args:t=>["-e","sh","-lc",`cd ${shellQuotePosix(t)} && exec ${e}`]}:[{command:"gnome-terminal",args:e=>["--working-directory",e]},{command:"kgx",args:e=>["--working-directory",e]},{command:"konsole",args:e=>["--workdir",e]},{command:"xfce4-terminal",args:e=>["--working-directory",e]},{command:"mate-terminal",args:e=>["--working-directory",e]},{command:"lxterminal",args:e=>["--working-directory",e]},{command:"alacritty",args:e=>["--working-directory",e]},{command:"kitty",args:e=>["--directory",e]},{command:"xterm",args:t=>["-e","sh","-lc",`cd ${shellQuotePosix(t)} && exec ${e}`]},{command:"x-terminal-emulator",args:t=>["-e","sh","-lc",`cd ${shellQuotePosix(t)} && exec ${e}`]}].find(e=>commandExists$1(e.command))??null}function openInFileManager(e,t){if("darwin"!==t){if("win32"!==t){if("linux"===t)return commandExists$1("xdg-open")?void runCommand$1("xdg-open",[e]):void runCommand$1("gio",["open",e]);throw new Error("File manager open is not supported on this platform")}runCommand$1("explorer",[e])}else runCommand$1("open",[e])}function applyOpenerOverrides(e,t,n){const a=n??getOpenerOverrides();return e.map(e=>{const n=a[e.id];if(!n)return e;if(!1===n.enabled)return{...e,isSupported:()=>!1};const s={...e,label:n.label??e.label,method:n.method??e.method,urlTemplate:n.urlTemplate??e.urlTemplate};if(n.command){const a=normalizeAppNames(n.appName??e.macAppNames);s.method="cli",s.isSupported=()=>isCommandAvailable(n.command,a,t),s.open=e=>openWithCommand(n.command,n.args,e)}return s})}function getOpenerOverrides(){try{const e=machine.machine.readSettings();if(!e||"object"!=typeof e)return{};const t=e.openersOverrides;return t&&"object"==typeof t?t:{}}catch(e){return machine.logger.warn("[OPENERS] Failed to read opener overrides",e),{}}}function getOpenerOverridesSignature(e){try{return JSON.stringify(e)}catch{return""}}function openWithCommand(e,t,n){if(!runCommand$1(e,(t&&t.length>0?t:["{path}"]).map(e=>e.split("{path}").join(n))))throw new Error(`Command failed: ${e}`)}function isCommandAvailable(e,t,n){return"darwin"===n&&t.length>0?t.some(e=>isMacAppInstalled(e)):path.isAbsolute(e)||e.includes(path.sep)?fs.existsSync(e):commandExists$1(e)}function normalizeAppNames(e){return e?Array.isArray(e)?e:[e]:[]}function isSchemeRegistered(e,t,n){return"darwin"===t?isSchemeRegisteredMac(e,n):"win32"===t?isSchemeRegisteredWindows(e):"linux"===t&&isSchemeRegisteredLinux(e)}function isSchemeRegisteredMac(e,t){if(commandExists$1("mdfind")){const t=runCommand$1("mdfind",[`kMDItemCFBundleURLSchemes == '${e}'`],{captureOutput:!0});if(t&&t.trim())return!0}if(commandExists$1("plutil")){const t=[path.join(os.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(!fs.existsSync(n))continue;const t=runCommand$1("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){machine.logger.debug("[OPENERS] Failed to parse LaunchServices handlers",e)}}}return!!(t&&t.length>0)&&t.some(e=>isMacAppInstalled(e))}function isMacAppInstalled(e){return"darwin"===process.platform&&Boolean(runCommand$1("open",["-Ra",e]))}function isSchemeRegisteredWindows(e){return commandExists$1("reg")&&(Boolean(runCommand$1("reg",["query",`HKCU\\Software\\Classes\\${e}`]))||Boolean(runCommand$1("reg",["query",`HKCR\\${e}`])))}function isSchemeRegisteredLinux(e){if(commandExists$1("xdg-settings")){const t=runCommand$1("xdg-settings",["get","default-url-scheme-handler",e],{captureOutput:!0});if(t&&t.trim()&&"null"!==t.trim())return!0}if(commandExists$1("gio")){const t=runCommand$1("gio",["mime",`x-scheme-handler/${e}`],{captureOutput:!0});if(t&&/Default application/.test(t))return!0}return!1}function commandExists$1(e){return"win32"===process.platform?Boolean(runCommand$1("where",[e])):Boolean(runCommand$1("sh",["-c",`command -v ${e}`]))}function isSafeCommandReference(e){return/^[A-Za-z0-9_./+-]+$/.test(e)}function runCommand$1(e,t,n){const a=node_child_process.spawnSync(e,t,{encoding:n?.captureOutput?"utf8":void 0,stdio:n?.captureOutput?"pipe":"ignore",windowsHide:!0});if(0!==a.status){if(n?.captureOutput){const n="string"==typeof a.stderr?a.stderr.trim():"";n&&machine.logger.warn(`[OPENERS] Command failed: ${e} ${t.join(" ")}: ${n}`)}return null}return n?.captureOutput?a.stdout:"ok"}function launchDetached(e,t){node_child_process.spawn(e,t,{detached:!0,stdio:"ignore",windowsHide:!1}).unref()}function escapePowerShellString(e){return e.replace(/'/g,"''")}function escapeAppleScriptString(e){return e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}function shellQuotePosix(e){return`'${e.replace(/'/g,"'\\''")}'`}function getVersionPath(e,t){if(t){const n=path.relative(t,e),a=!n||n.startsWith("..")||path.isAbsolute(n)?path.basename(e):n;return path.join(t,"versions",a)}let n=path.dirname(e),a=0;for(;a<10;){if(fs.existsSync(path.join(n,"agent.json"))){const t=e.slice(n.length).replace(/^\//,"");return path.join(n,"versions",t)}const t=path.dirname(n);if(t===n)break;n=t,a++}const s=path.dirname(e),i=path.basename(e);return path.join(s,`.${i}.version`)}function readFileVersion(e,t){const n=getVersionPath(e,t);if(!fs.existsSync(n))return"0.0.0";try{return fs.readFileSync(n,"utf-8").trim()}catch(e){return"0.0.0"}}function writeFileVersion(e,t,n){try{const a=getVersionPath(e,n),s=path.dirname(a);fs.existsSync(s)||fs.mkdirSync(s,{recursive:!0}),fs.writeFileSync(a,t,"utf-8")}catch(e){}}function compareVersions$1(e,t){const n=e.split(".").map(Number),a=t.split(".").map(Number);for(let e=0;e<3;e++){const t=n[e]||0,s=a[e]||0;if(t>s)return 1;if(t<s)return-1}return 0}function installTemplateFile(e,t,n){const a=readFileVersion(e,n),s=compareVersions$1(t.metadata.version,a);if(!fs.existsSync(e)){const a=path.dirname(e);return fs.existsSync(a)||fs.mkdirSync(a,{recursive:!0}),fs.writeFileSync(e,t.content,"utf-8"),writeFileVersion(e,t.metadata.version,n),{updated:!0,reason:"created"}}if(s<=0)return{updated:!1,reason:"up-to-date"};switch(t.metadata.updateStrategy){case"overwrite":return fs.writeFileSync(e,t.content,"utf-8"),writeFileVersion(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"}}}function checkPendingUpgrades(e,t,n={}){const a=[],s=[];for(const i of e){if("notify-user"!==i.metadata.updateStrategy)continue;const e=path.join(t,i.relativePath);if(!fs.existsSync(e))continue;const o=readFileVersion(e,t);if(compareVersions$1(i.metadata.version,o)>0){const r={template:i,targetPath:e,upgradePath:`${e}.upgrade`,versionPath:getVersionPath(e,t),currentVersion:o,newVersion:i.metadata.version},c=i.language??"common";if("common"!==c){if(!1===n.languageVerified){s.push({...r,reason:`Cannot safely determine installed Companion template language; refusing to generate ${c} upgrade content for ${i.relativePath}.`});continue}if(n.currentLanguage&&c!==n.currentLanguage){s.push({...r,reason:`Template language ${c} does not match installed Companion language ${n.currentLanguage}.`});continue}}a.push(r)}}return{pendingUpgrades:a,blockedUpgrades:s}}function generateUpgradeNotification(e){const t=e.pendingUpgrades,n=e.blockedUpgrades??[],a=t.length>0?t.map(e=>`### ${e.template.metadata.description||e.template.relativePath}\n\n- Relative path: \`${e.template.relativePath}\`\n- Template language: \`${e.template.language??"common"}\`\n- Current version: \`v${e.currentVersion}\`\n- New version: \`v${e.newVersion}\`\n- Target path: \`${e.targetPath}\`\n- Upgrade file path: \`${e.upgradePath}\`\n- Version marker path: \`${e.versionPath}\``).join("\n\n"):"None.",s=n.length>0?n.map(e=>`### ${e.template.metadata.description||e.template.relativePath}\n\n- Relative path: \`${e.template.relativePath}\`\n- Template language: \`${e.template.language??"common"}\`\n- Current version: \`v${e.currentVersion}\`\n- New version: \`v${e.newVersion}\`\n- Target path: \`${e.targetPath}\`\n- Upgrade file path: \`${e.upgradePath}\`\n- Version marker path: \`${e.versionPath}\`\n- Reason: ${e.reason}`).join("\n\n"):"None.";return`# Upgrades Available\n\nGenerated by Agentrix Companion upgrade detection.\n\n- Agent root: \`${e.agentDir}\`\n- Current Companion template language: \`${e.language}\`\n- Language source: \`${e.languageSource}\`\n\n## Ready Upgrades\n\n${a}\n\n## Blocked Upgrades\n\n${s}\n\n---\n\n**Shadow's Instructions:**\n\nWhen you detect this file:\n1. Read this file to identify available upgrades\n2. For each ready upgrade, read the exact \`Upgrade file path\`\n3. Integrate the new content into the target file while preserving local customizations when possible\n4. Update the exact \`Version marker path\` with the new version number\n5. Delete processed \`.upgrade\` files\n6. Delete this file when all ready upgrades are applied and there are no blocked upgrades\n7. If an upgrade cannot be applied safely, leave the files in place and write the reason under Blocked Upgrades in this file; do not notify the main companion\n`}function generateUpgradeFileContent(e){return`# Upgrade: ${e.template.metadata.description||e.template.relativePath}\n\n**Relative Path**: \`${e.template.relativePath}\`\n**Template Language**: \`${e.template.language??"common"}\`\n**Current Version**: v${e.currentVersion}\n**New Version**: v${e.newVersion}\n**Target Path**: \`${e.targetPath}\`\n**Upgrade File Path**: \`${e.upgradePath}\`\n**Version Marker Path**: \`${e.versionPath}\`\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 the exact target file: \`${e.targetPath}\`\n3. Integrate the new features in the Companion's current voice and language\n4. Keep existing customizations\n5. Use Write tool to update the exact version marker path \`${e.versionPath}\` with content: "${e.newVersion}"\n6. Delete this file when done: \`${e.upgradePath}\`\n`}async function installAgentFromGit(e){const{agentId:t,gitUrl:n,branch:a,subDir:s}=e,i=path.join(machine.machine.agentrixAgentsHomeDir,t);if(fs.existsSync(i))return{agentDir:i};const o=`${i}.tmp-${Date.now()}`;try{const e=["git","clone","--depth=1"];if(a&&e.push("--branch",a),e.push(n,o),node_child_process.execSync(e.join(" "),{stdio:"pipe"}),s){const e=path.join(o,s);if(!fs.existsSync(e))throw new Error(`Sub-directory "${s}" not found in cloned repository`);fs.renameSync(e,i),fs.rmSync(o,{recursive:!0,force:!0})}else fs.renameSync(o,i);return buildAgentPlugins(i),{agentDir:i}}catch(e){throw fs.existsSync(o)&&fs.rmSync(o,{recursive:!0,force:!0}),fs.existsSync(i)&&fs.rmSync(i,{recursive:!0,force:!0}),e}}function buildAgentPlugins(e){const t=[],n=path.join(e,"claude","plugins");if(fs.existsSync(n))for(const e of fs.readdirSync(n)){const a=path.join(n,e);fs.statSync(a).isDirectory()&&fs.existsSync(path.join(a,"package.json"))&&t.push(a)}const a=path.join(e,"claude","hooks");fs.existsSync(a)&&fs.existsSync(path.join(a,"package.json"))&&t.push(a);for(const e of t)node_child_process.execSync("yarn install --frozen-lockfile",{cwd:e,stdio:"pipe"}),node_child_process.execSync("yarn build",{cwd:e,stdio:"pipe"})}function trimIdent(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 CHANGE_TITLE_PROMPT=trimIdent("\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");function buildCodexEventBrokerTitlePrompt(e){return trimIdent(`\n ## Title Setting Protocol:\n - MUST set a descriptive title as your FIRST action when the user makes a request\n - Use the Agentrix event broker MCP tool for this: server "${e.serverName}", tool "${e.toolName}"\n - This is mandatory when the tool is available; do this before any other work\n - Update the title if the conversation direction changes substantially\n `)}function buildCodexEventBrokerPreviewPrompt(e){return trimIdent(`\n ## Task Preview URL Protocol:\n - Important: when a browser-viewable frontend preview URL is available, publishing it is required, not optional.\n - If the user provided a service startup port, relevant startup documentation, or you started/reused a frontend service yourself, publish the preview URL for the current Agentrix task whenever you know the running service port.\n - Use the Agentrix event broker MCP tool for this: server "${e.serverName}", tool "${e.toolName}".\n - Publish only absolute http or https URLs. Local preview URLs such as http://localhost:5173 are valid.\n - Do not publish URLs for backend-only services or endpoints that are not user-facing frontend previews.\n `)}function buildTaskPreviewPrompt(e){return trimIdent(`\n ## Task Preview URL Protocol:\n - Important: when a browser-viewable frontend preview URL is available, publishing it is required, not optional.\n - If the user provided a service startup port, relevant startup documentation, or you started/reused a frontend service yourself, publish the preview URL for the current Agentrix task whenever you know the running service port.\n - Use \`${e}\` to publish the preview URL.\n - Publish only absolute http or https URLs. Local preview URLs such as http://localhost:5173 are valid.\n - Do not publish URLs for backend-only services or endpoints that are not user-facing frontend previews.\n `)}function buildVisionArtifactPrompt(e){return trimIdent(`\n ## Agentrix Vision Artifact Protocol:\n - After you create or materially update the visual plan (\`plan/index.html\`), and again after you create or update the visual test report (\`test/index.html\`), use \`${e}\` to send the issue vision artifacts to the platform so the user can review them.\n - Pass only the repository root and issue id. The platform presents the available plan and test artifacts together.\n - Do not start the local Vision engine just to use this tool.\n - If this tool is unavailable, share the local artifact paths with the user and ask them to review.\n `)}function buildCodexEventBrokerVisionArtifactPrompt(e){return trimIdent(`\n ## Agentrix Vision Artifact Protocol:\n - After you create or materially update the visual plan (\`plan/index.html\`), and again after you create or update the visual test report (\`test/index.html\`), send the issue vision artifacts to the platform for review using the Agentrix event broker MCP tool: server "${e.serverName}", tool "${e.toolName}".\n - Pass only the repository root and issue id. The platform presents the available plan and test artifacts together.\n - Do not start the local Vision engine just to use this tool.\n - If this tool is unavailable, share the local artifact paths with the user and ask them to review.\n `)}function buildAgentrixComputerUsePrompt(e){return trimIdent(`\n ## Agentrix Computer Use Protocol:\n - When the user explicitly asks you to operate this local computer, use \`${e}\`.\n - Use it for desktop apps, Finder, documents, windows, menus, dialogs, and other GUI operations.\n - Pass a concrete natural-language operation instruction. Do not invent low-level click coordinates or try to perform the GUI operation yourself.\n - When the operation references a file, directory, document, download, or save location, include the absolute path in the instruction.\n - Only use this tool for user-requested local computer control.\n `)}const FILE_WRITE_CHUNKING_PROMPT=trimIdent("\n Important: If the content to be written to a file is too long, split it into chunks and write them to the file incrementally. Writing too much content at once can easily cause errors.\n");function formatChannelPlatform(e){const t=e?.trim();return t?{telegram:"Telegram",wechat:"WeChat",lark:"Lark"}[t.toLowerCase()]??t:null}function buildExternalChannelContextIntro(e){const t=formatChannelPlatform(e?.platform),n=[e?.chatType?`chat type: ${e.chatType}`:void 0,e?.chatName?`chat name: ${e.chatName}`:void 0,e?.chatId?`chat id: ${e.chatId}`:void 0].filter(Boolean).join(", ");return trimIdent(t?`\n This task was started from an external messaging channel on ${t}.\n The user is interacting with you through ${t}.\n ${n?`Channel context: ${n}.`:""}\n `:"\n This task was started from an external messaging channel such as Telegram, WeChat, or Lark.\n The user is interacting with you through that external platform.\n ")}function buildExternalChannelPrompt(e){const t="group"===e?.chatType?.toLowerCase();return trimIdent(`\n ## External Channel Context\n\n ${buildExternalChannelContextIntro(e)}\n\n ${t?trimIdent("\n This external channel is a group chat. Recent group history may already be injected into the current input as `<external_group_history>` with `<msg>` entries and sender metadata.\n\n If you need more context from earlier group messages, use `mcp__agentrix__get_channel_group_history` to page older saved group history. That tool is read-only and is only for understanding context/history.\n "):""}\n\n Your normal final result is NOT automatically sent to the external channel. It is stored in Agentrix/task history.\n\n The external user is waiting on the external platform. If you do not call \`mcp__agentrix__send_channel_message\` during this turn, the user will see absolutely nothing from your model-directed channel response. Any runtime fallback is only an emergency safety net; do not rely on it.\n\n You MUST use \`mcp__agentrix__send_channel_message\` to send anything the external user should see: acknowledgements, progress updates, questions, results, and failures.\n\n Before ending the task, you MUST ensure the external user has received an appropriate user-facing message via \`mcp__agentrix__send_channel_message\`.\n\n Do not put user-facing content only in the final internal result; the system will NOT forward the normal success result when you have used the channel message tool.\n\n For multi-step tasks, at minimum call \`mcp__agentrix__send_channel_message\` once before ending with the final conclusion.\n\n If the user receives no message at all, the answer is considered a failure regardless of how complete the internal result is.\n\n ## What to send with send_channel_message\n\n Use \`mcp__agentrix__send_channel_message\` to send user-facing conversational messages to the external channel.\n The purpose is to help the user understand that you are working, what state the work is in, and what the final result is.\n\n You should send:\n - Acknowledgement/progress when the task is long-running, multi-step, or requires waiting, so the user knows work started or is ongoing.\n - Questions/choices/permission requests when user input is needed or you are blocked.\n - User-understandable results when done: conclusion, summary, next steps, and key deliverable notes.\n - Clear failure/limitation messages when the task cannot be completed, a platform does not support something, permission is missing, or an external service fails.\n\n Do not send:\n - Internal reasoning, verbose execution logs, stack traces, debug dumps.\n - Internal summaries that only matter to Agentrix/task history.\n - Excessive implementation detail unless the user is explicitly collaborating technically and needs it.\n - Temporary paths, environment variables, tokens, secrets, or private data.\n\n Style:\n - External channel messages should feel like natural conversation: short, clear, useful.\n - For simple tasks, usually send only the final answer.\n - For long tasks, send a brief start/progress message and a final result message.\n - If attachments are sent, briefly explain what they are and what the user can do next.\n\n ## What attachments to send\n\n Attachments are part of \`send_channel_message\` and are only for deliverables the user should consume, save, view, or forward.\n\n Send attachments for:\n - Files the user explicitly asked to generate, export, package, send, or share.\n - Final deliverables such as images, posters, charts, PDFs, spreadsheets, reports, slides, archives, audio, or video.\n - Artifacts without which the channel answer would be incomplete.\n\n Do not send attachments for:\n - Files that were merely created, edited, read, downloaded, or used while doing the work.\n - Logs, caches, temporary files, build artifacts, intermediate screenshots, debug outputs unless the user explicitly asked for them.\n - Files containing secrets, credentials, private data, or local environment details.\n - Any file that is only part of the work process rather than a user deliverable.\n\n Decision rules:\n - A file generated for the user to use/view/save is usually an attachment deliverable.\n - A file created or modified while completing work is not automatically a deliverable; decide based on user intent.\n - Do not decide based on file location or directory.\n - A file inside the workspace can be a deliverable.\n - A file outside the workspace can still be unsafe or inappropriate.\n - Decide based on semantics and user intent, not path location.\n - When modifying files, do not send them automatically; summarize changes in text unless the user asked to receive, export, package, or forward those files.\n - If uncertain or risky, ask for confirmation via \`send_channel_message\` first.\n\n Do NOT send files just because they were created, edited, read, downloaded, or used during the task.\n After sending the external response, your final result can briefly summarize what you sent for Agentrix history.\n If the platform does not support sending that attachment type, explain that and provide the best available alternative.\n`)}buildExternalChannelPrompt();const GROUP_CHAT_MESSAGE_FORMAT=trimIdent('\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'),ORCHESTRATION_DECISION_FRAMEWORK=trimIdent('\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'),GROUP_CHAT_PLANNER_IDENTITY=trimIdent('\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'),CHAT_MODE_TASK_DELEGATION=trimIdent("\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"),PLANNER_BASE_PROMPT=trimIdent(`\n ${GROUP_CHAT_PLANNER_IDENTITY}\n\n ${GROUP_CHAT_MESSAGE_FORMAT}\n\n ${ORCHESTRATION_DECISION_FRAMEWORK}\n`),GROUP_MEMBER_MESSAGE_FORMAT=trimIdent('\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 buildAgentsListPrompt(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 buildAgentContextPrompt(e,t){const n=t.find(t=>t.id===e);if(!n)return buildAgentsListPrompt(t);const a=t.filter(t=>t.id!==e),s=["# Group Context","",`You are \`${n.name}\`. `,"You are a member of this group chat."];if(n.description&&s.push(`Your role: ${n.description}`),a.length>0){s.push(""),s.push("## Other Agents in This Group"),s.push("");for(const e of a)e.description?s.push(`- **${e.name}**: ${e.description}`):s.push(`- **${e.name}**`)}return s.push(""),s.push(GROUP_MEMBER_MESSAGE_FORMAT),s.join("\n")}function mergeEnvironment(e){const t={};for(const[n,a]of Object.entries(e))"string"==typeof a&&(t[n]=a);return t}function isTextBlock$1(e){if("object"!=typeof e||null===e)return!1;const t=e;return"text"===t.type&&"string"==typeof t.text}function normalizeClaudeUserMessage(e){return{type:"user",message:{role:"user",content:e},parent_tool_use_id:null,session_id:""}}function extractUserMessageText(e){const t=e.message?.content;return"string"==typeof t?t:Array.isArray(t)?t.filter(isTextBlock$1).map(e=>e.text).join("\n").trim():""}function createClaudeAssistantMessage(e){return{type:"assistant",session_id:"",uuid:crypto.randomUUID(),parent_tool_use_id:null,message:{role:"assistant",content:[{type:"text",text:e}]}}}function createSdkResultMessage(e){const t=e.usage.input_tokens-e.usage.cached_input_tokens,n=Math.max(0,Math.trunc(e.durationMs??0)),a={input_tokens:e.usage.input_tokens,output_tokens:e.usage.output_tokens,cache_creation:{ephemeral_1h_input_tokens:0,ephemeral_5m_input_tokens:0},cache_creation_input_tokens:0,cache_read_input_tokens:e.usage.cached_input_tokens,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:n,duration_api_ms:n,is_error:!1,num_turns:e.numTurns,result:e.result??"",stop_reason:null,total_cost_usd:0,usage:a,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 createSdkErrorResultMessage(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:""}}function parseStructuredOutputTextOrThrow(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 HOOK_TIMEOUT_MS=6e4;async function executeHook(e,t,n,a){if(!e)return;const s=e[t];if(!s)return;const i=a||(e=>console.log(e));try{i(`[${t}] Executing hook...`);const e=new AbortController,a=setTimeout(()=>{e.abort()},6e4);try{await s(n,"",{signal:e.signal}),i(`[${t}] Hook executed successfully`)}finally{clearTimeout(a)}}catch(e){console.warn(`[${t}] Hook failed (non-fatal):`,e)}}function buildHooksWithDelegation(e,t){const n={},a=e=>async(t,n,a)=>await e(t,n,a)??{},s=new Set([...Object.keys(e),...t?Object.keys(t):[]]);for(const i of s){const s=[],o=e[i];o&&s.push(a(o));const r=t?.[i];r&&s.push(a(r)),n[i]=[{hooks:s}]}return n}const DEFAULT_SERVER_NAME="agentrix",DEFAULT_SERVER_VERSION="1.0.0",formatToolName=(e,t)=>`mcp__${e}__${t}`;function buildAgentrixMcpServer(e){const{modeConfig:t,tools:n,agentType:a,allowAskUser:s=!0,supportedFeatures:i,channelBound:o,channelGroupBound:r,visionModel:c,enableTaskPreviewUrl:l=!0,enableVisionPlan:d=!1,enableComputerUse:p=!1,extraTools:u=[],serverName:m=DEFAULT_SERVER_NAME,serverVersion:h=DEFAULT_SERVER_VERSION}=e,{mode:g,supportChangeTitle:f}=t,y=[];switch(g){case"work":p&&y.push(n.computerUse),i?.includes("sub-task")&&(y.push(n.createTask),y.push(n.replyToSubTask),y.push(n.listSubTask)),f&&y.push(n.changeTaskTitle),s&&y.push(n.askUser),l&&y.push(n.publishTaskPreviewUrl),d&&y.push(n.sendVisionArtifact),y.push(n.getTaskHistory);break;case"chat":p&&y.push(n.computerUse),y.push(n.createTask),y.push(n.replyToSubTask),s&&y.push(n.askUser),y.push(n.getTaskHistory),y.push(n.listSubTask);break;case"group_chat":y.push(n.invoke),y.push(n.createSoloTask),y.push(n.createGroupTask),y.push(n.replyToSubTask),y.push(n.getTaskAgents),y.push(n.getTaskHistory);break;case"group_work":y.push(n.invoke),y.push(n.assign),f&&y.push(n.changeTaskTitle),l&&y.push(n.publishTaskPreviewUrl),d&&y.push(n.sendVisionArtifact),y.push(n.getTaskAgents),y.push(n.getTaskHistory);break;case"reply":y.push(n.getTaskHistory),s&&y.push(n.askUser);break;case"companion_chat":y.push(n.createTask),y.push(n.replyToSubTask),s&&y.push(n.askUser),y.push(n.getTaskHistory),y.push(n.uploadFile),y.push(n.listAgents),y.push(n.scheduleTask);break;case"companion_shadow":y.push(n.getTaskHistory),y.push(n.readConversation),y.push(n.listAgents),y.push(n.scheduleTask)}return("companion_chat"===g||"companion_shadow"===g)&&(y.push(n.listTasks),y.push(n.sendReminder),y.push(n.recordMemoryChange),y.push(n.prepareHiveRepository),y.push(n.publishToHive),y.push(n.updateHiveListingVersion),y.push(n.recordHiveInstall),y.push(n.createHiveReview),y.push(n.createHiveComment)),"companion"===a&&y.push(n.updateAgentInfo),o&&"companion_shadow"!==g&&y.push(n.sendChannelMessage),r&&"companion_shadow"!==g&&y.push(n.getChannelGroupHistory),c&&"companion_shadow"!==g&&"reply"!==g&&y.push(n.analyzeImage),y.push(...u),{server:claudeAgentSdk.createSdkMcpServer({name:m,version:h,tools:y}),toolNames:y.map(e=>formatToolName(m,e.name))}}const execFileAsync$6=node_util.promisify(node_child_process.execFile),logger$9=machine.createModuleLogger("undefined"==typeof document?require("url").pathToFileURL(__filename).href:_documentCurrentScript&&"SCRIPT"===_documentCurrentScript.tagName.toUpperCase()&&_documentCurrentScript.src||new URL("index.cjs",document.baseURI).href),COMPANION_SELF_EVOLUTION_GITIGNORE=["*","","!.gitignore","","!MEMORY.md","!USER.md","!SOUL.md","!IDENTITY.md","!SKILLS.md","!system_prompt.md","","!HEARTBEAT.md","!MEMORY_ORGANIZATION.md","!UPGRADES.md","!*.upgrade","","!memory/","!memory/**","!memory-changes/","!memory-changes/**","","!plugins/","!plugins/**","!versions/","!versions/**",""].join("\n"),TOP_LEVEL_ALLOWED_FILES=new Set(["MEMORY.md","USER.md","SOUL.md","IDENTITY.md","SKILLS.md","system_prompt.md","HEARTBEAT.md","MEMORY_ORGANIZATION.md","UPGRADES.md"]),ALLOWED_DIRECTORIES=["memory","memory-changes","plugins","versions"],GIT_AUTHOR_ENV={GIT_AUTHOR_NAME:"Agentrix Companion",GIT_AUTHOR_EMAIL:"companion@agentrix.local",GIT_COMMITTER_NAME:"Agentrix Companion",GIT_COMMITTER_EMAIL:"companion@agentrix.local"};function toGitPath(e){return e.split(path.sep).join("/")}function normalizeRelativePath$1(e){return toGitPath(path.normalize(e)).replace(/^\.\//,"")}function logGitError(e,t){logger$9.warn(e,t)}async function runGit(e,t){const{stdout:n}=await execFileAsync$6("git",t,{cwd:e,encoding:"utf-8",windowsHide:!0,env:{...process.env,...GIT_AUTHOR_ENV}});return n}async function ensureGitignore(e){const t=path.join(e,".gitignore");await promises$1.readFile(t,"utf-8").catch(()=>{})!==COMPANION_SELF_EVOLUTION_GITIGNORE&&await promises$1.writeFile(t,COMPANION_SELF_EVOLUTION_GITIGNORE,"utf-8")}async function hasStagedDiff(e){try{return await runGit(e,["diff","--cached","--quiet","--exit-code"]),!1}catch(e){if("number"==typeof e?.code&&1===e.code)return!0;throw e}}async function commitStaged(e,t,n){const a=["commit","-m",t];return n?.trim()&&a.push("-m",n.trim()),await runGit(e,a),(await runGit(e,["rev-parse","HEAD"])).trim()}async function listTrackedAllowedPaths(e){return(await runGit(e,["ls-files"])).split(/\r?\n/).map(e=>e.trim()).filter(e=>e.length>0).filter(isCompanionSelfEvolutionAllowedPath)}async function listExistingAllowlistStagePaths(e){const t=new Set;fs.existsSync(path.join(e,".gitignore"))&&t.add(".gitignore");for(const n of TOP_LEVEL_ALLOWED_FILES)fs.existsSync(path.join(e,n))&&t.add(n);const n=await promises$1.readdir(e).catch(()=>[]);for(const a of n)!a.includes("/")&&a.endsWith(".upgrade")&&fs.existsSync(path.join(e,a))&&t.add(a);for(const n of ALLOWED_DIRECTORIES)fs.existsSync(path.join(e,n))&&t.add(n);for(const n of await listTrackedAllowedPaths(e))t.add(n);return Array.from(t)}function isCompanionSelfEvolutionAllowedPath(e){const t=normalizeRelativePath$1(e);return!(!t||"."===t||t.startsWith("../")||t.includes("/../"))&&(!!TOP_LEVEL_ALLOWED_FILES.has(t)||!(t.includes("/")||!t.endsWith(".upgrade"))||ALLOWED_DIRECTORIES.some(e=>t===e||t.startsWith(`${e}/`)))}function resolveCompanionSelfEvolutionPath(e,t){const n=path.normalize(e),a=path.normalize(t),s=path.isAbsolute(a)?a:path.normalize(path.join(n,a)),i=normalizeRelativePath$1(path.relative(n,s));if(!i.startsWith("../")&&!path.isAbsolute(i)&&isCompanionSelfEvolutionAllowedPath(i))return{absolutePath:s,relativePath:i};if(!path.isAbsolute(a)){const e=path.normalize(path.join(n,"memory",a)),t=normalizeRelativePath$1(path.relative(n,e));if(!t.startsWith("../")&&!path.isAbsolute(t)&&isCompanionSelfEvolutionAllowedPath(t))return{absolutePath:e,relativePath:t}}throw new Error(`Companion self-evolution path is not allowlisted: ${t}`)}async function ensureCompanionSelfEvolutionGitRepo(e){const{companionHome:t}=e;if(!t)return logger$9.warn("Skipping self-evolution git repo ensure: companion home is not set"),!1;if(!fs.existsSync(t))return logger$9.warn(`Skipping self-evolution git repo ensure: companion home does not exist (${t})`),!1;try{await promises$1.mkdir(t,{recursive:!0});const e=fs.existsSync(path.join(t,".git"));return e||await runGit(t,["init"]),await ensureGitignore(t),e||(await stageCompanionSelfEvolutionAllowlist(t),await hasStagedDiff(t)&&await commitStaged(t,"Initialize Companion self-evolution history","Initial snapshot before automatic Companion run checkpoints.")),!0}catch(e){return logGitError("Failed to ensure Companion self-evolution git repo",e),!1}}async function stageCompanionSelfEvolutionAllowlist(e){const t=await listExistingAllowlistStagePaths(e);0!==t.length&&await runGit(e,["add","-A","--",...t])}async function stageCompanionSelfEvolutionPaths(e,t){const n=new Set(await listTrackedAllowedPaths(e)),a=Array.from(new Set(t.map(normalizeRelativePath$1))).filter(isCompanionSelfEvolutionAllowedPath).filter(t=>fs.existsSync(path.join(e,t))||n.has(t));return 0===a.length?[]:(await runGit(e,["add","-A","--",...a]),a)}function buildCheckpointTitle(e,t,n){const a="before_run"===n?"before":"after";return"companion_shadow"===e?"unknown"===t?`checkpoint: ${a} companion_shadow run`:`checkpoint: ${a} companion_shadow ${t} run`:`checkpoint: ${a} companion_chat run`}function buildCheckpointBody(e,t,n){return[`mode: ${e}`,`shadow_task: ${"companion_shadow"===e?t:"unknown"}`,`phase: ${n}`].join("\n")}function resolveCompanionShadowTask(e){return"heartbeat"===e?.COMPANION_SHADOW_TASK?"heartbeat":"memory_organization"===e?.COMPANION_SHADOW_TASK?"memory_organization":"unknown"}async function checkpointCompanionSelfEvolution(e){const{companionHome:t,mode:n,phase:a}=e;if("companion_chat"!==n&&"companion_shadow"!==n)return{committed:!1};try{if(!await ensureCompanionSelfEvolutionGitRepo({companionHome:t})||!t)return{committed:!1};if(await stageCompanionSelfEvolutionAllowlist(t),!await hasStagedDiff(t))return{committed:!1};const s="companion_shadow"===n?e.shadowTask??"unknown":"unknown",i=await commitStaged(t,buildCheckpointTitle(n,s,a),buildCheckpointBody(n,s,a));return logger$9.info(`Created Companion self-evolution ${a} checkpoint ${i}`),{committed:!0,commit:i}}catch(e){return logGitError(`Failed to create Companion self-evolution ${a} checkpoint`,e),{committed:!1}}}function buildMemoryChangeCommitBody(e){const t=["reasons:"];for(const n of e.reasons)t.push(`- ${n}`);return t.push("",`trigger: ${e.trigger}`,`source: ${e.source??"unspecified"}`),e.taskId&&t.push(`taskId: ${e.taskId}`),t.push(`action: ${e.action}`,`file: ${e.file}`),e.deletedFiles?.length&&t.push(`deletedFiles: ${e.deletedFiles.join(", ")}`),t.push(`notifiedCompanion: ${e.notifiedCompanion}`),t.join("\n")}async function commitCompanionMemoryChange(e){const{companionHome:t,title:n,body:a,paths:s}=e;try{return 0===(await stageCompanionSelfEvolutionPaths(t,s)).length?(logger$9.warn("Skipping Companion memory change commit: no allowlisted paths to stage"),null):await hasStagedDiff(t)?await commitStaged(t,n,a):null}catch(e){return logGitError("Failed to create Companion memory change semantic commit",e),null}}async function*oneShotPrompt(e){yield e}let claudePathOverrideCache;function resolveBinaryPath(e){const t="win32"===process.platform?"where":"which",n=node_child_process.spawnSync(t,[e],{encoding:"utf-8"});if(0===n.status)return n.stdout.split(/\r?\n/).map(e=>e.trim()).find(e=>e.length>0)}function normalizeClaudePath(e){const t=e.trim();if(t){if(t.includes("/")||t.includes("\\")||t.startsWith(".")){const e=path.isAbsolute(t)?t:path.resolve(t);return fs.existsSync(e)?e:void 0}return resolveBinaryPath(t)}}function resolveClaudePathOverride(){if(void 0!==claudePathOverrideCache)return claudePathOverrideCache??void 0;const e=process.env.AGENTRIX_CLAUDE_PATH?.trim();if(e){const t=normalizeClaudePath(e);if(t)return claudePathOverrideCache=t,t}claudePathOverrideCache=null}const CHAT_TOOLS=["Bash","Glob","Grep","ExitPlanMode","Read","Skill","SlashCommand","EnterPlanMode"],CLAUDE_PLAN_MODE_TOOLS=["EnterPlanMode","ExitPlanMode"],CLAUDE_PLAN_MODE_TOOL_SET=new Set(CLAUDE_PLAN_MODE_TOOLS),GROUP_REPLY_TOOLS=["Glob","Grep","Read","Skill"],GROUP_CHAT_TOOLS=["Read","Glob","Grep"],GROUP_WORK_TOOLS=["Read","Glob","Grep","TodoWrite"];function buildSdkTools(e){switch(e){case"work":case"companion_shadow":return;case"chat":case"companion_chat":return[...CHAT_TOOLS];case"reply":return[...GROUP_REPLY_TOOLS];case"group_chat":return[...GROUP_CHAT_TOOLS];case"group_work":return[...GROUP_WORK_TOOLS]}}function filterClaudePlanModeTools(e,t){return t&&e?e.filter(e=>!CLAUDE_PLAN_MODE_TOOL_SET.has(e)):e}function getModePrompt(e,t){const{mode:n,supportChangeTitle:a}=e,s=t?.enableTaskPreviewUrl??!0,i=[FILE_WRITE_CHUNKING_PROMPT];switch(n){case"work":a&&i.unshift(CHANGE_TITLE_PROMPT),s&&i.push(buildTaskPreviewPrompt("mcp__agentrix__publish_task_preview_url")),t?.enableVisionPlan&&i.push(buildVisionArtifactPrompt("mcp__agentrix__send_vision_artifact")),t?.enableAgentrixComputerUse&&i.push(buildAgentrixComputerUsePrompt("mcp__agentrix__agentrix_computer_use"));break;case"companion_shadow":case"companion_chat":case"reply":case"group_chat":break;case"chat":i.unshift(CHAT_MODE_TASK_DELEGATION),t?.enableAgentrixComputerUse&&i.push(buildAgentrixComputerUsePrompt("mcp__agentrix__agentrix_computer_use"));break;case"group_work":a&&i.unshift(CHANGE_TITLE_PROMPT),s&&i.push(buildTaskPreviewPrompt("mcp__agentrix__publish_task_preview_url")),t?.enableVisionPlan&&i.push(buildVisionArtifactPrompt("mcp__agentrix__send_vision_artifact"))}return i.join("\n\n")}function loadCompanionShadowRoutine(e,t){if(!e||!t)return;const n="memory_organization"===t?"MEMORY_ORGANIZATION.md":"HEARTBEAT.md",a=path.join(e,n);if(!fs.existsSync(a))return;const s=fs.readFileSync(a,"utf-8").trim();return s?[`## Injected Companion ${"memory_organization"===t?"Memory Organization":"Heartbeat"} Routine`,"",s].join("\n"):void 0}function getCompanionShadowTask(e){return"memory_organization"===e?.COMPANION_SHADOW_TASK?"memory_organization":"heartbeat"}function getAgentrixMonitorPromptValue(){const e=machine.machine.readSettings();if(!e||"object"!=typeof e)return"disable";const t=e["agentrix-monitor"];return t&&"object"==typeof t&&!0===t.enable?"enable":"disable"}function buildSystemPrompt(e){const{agentId:t,modeConfig:n,cwd:a,agentConfig:s,channelBound:i,channelContext:o,projectGuidance:r,promptPlaceholders:c,enableTaskPreviewUrl:l,enableVisionPlan:d,enableAgentrixComputerUse:p}=e,{mode:u,groupAgents:m}=n,h=s.customSystemPrompt,g=s.systemPromptMode??"append",f=getModePrompt(n,{enableTaskPreviewUrl:l,enableVisionPlan:d,enableAgentrixComputerUse:p});if("group_chat"===u||"group_work"===u){const e=[PLANNER_BASE_PROMPT];return m&&m.length>0&&e.push(buildAgentsListPrompt(m)),f&&e.push(f),i&&e.push(buildExternalChannelPrompt(o)),r?.systemPromptAppend&&e.push(r.systemPromptAppend),e.join("\n\n")}const y="reply"===u&&m&&m.length>0?buildAgentContextPrompt(t,m):void 0,v={},b=process.env.AGENTRIX_COMPANION_HOME||process.env.AGENTRIX_COMPANION_WORKSPACE,k="companion_shadow"===u?getCompanionShadowTask(c):void 0;b&&(v.COMPANION_HOME=b,v.COMPANION_MODE="companion_shadow"===u?"shadow":"chat","companion_shadow"===u&&(v.AGENTRIX_MONITOR=getAgentrixMonitorPromptValue(),v.COMPANION_SHADOW_TASK=k??"heartbeat")),Object.assign(v,c);const w=Object.keys(v).length>0?v:void 0,x=h?node.replacePromptPlaceholders(h,a,w):void 0,I="companion_shadow"===u?loadCompanionShadowRoutine(b,k):void 0;if("replace"===g&&x){const e=[x];return y&&e.push(y),f&&e.push(f),i&&e.push(buildExternalChannelPrompt(o)),I&&e.push(I),r?.systemPromptAppend&&e.push(r.systemPromptAppend),e.join("\n\n")}const S=[];return y&&S.push(y),f&&S.push(f),i&&S.push(buildExternalChannelPrompt(o)),x&&S.push(x),I&&S.push(I),r?.systemPromptAppend&&S.push(r.systemPromptAppend),{type:"preset",preset:"claude_code",append:S.length>0?S.join("\n\n"):void 0}}function buildQueryOptions(e,t,n,a,s,i,o,r){const c=buildSystemPrompt({agentId:e,modeConfig:n.modeConfig,cwd:n.cwd,agentConfig:a,channelBound:n.channelBound,channelContext:n.channelContext,projectGuidance:n.projectAgentrixGuidance,promptPlaceholders:n.promptPlaceholders,enableTaskPreviewUrl:n.enableTaskPreviewUrl,enableVisionPlan:n.enableVisionPlan,enableAgentrixComputerUse:n.enableAgentrixComputerUse}),l=filterClaudePlanModeTools(buildSdkTools(n.modeConfig.mode),Boolean(n.disableClaudePlanModeTools)),d=buildHooksWithDelegation(n.hooks??{},s),p=resolveClaudePathOverride(),u=o?buildAgentrixMcpServer({modeConfig:n.modeConfig,tools:o,agentType:t,allowAskUser:n.allowAskUser,supportedFeatures:n.supportedFeatures,channelBound:n.channelBound,channelGroupBound:n.channelGroupBound,visionModel:n.visionModel,enableTaskPreviewUrl:n.enableTaskPreviewUrl,enableVisionPlan:n.enableVisionPlan,enableComputerUse:n.enableAgentrixComputerUse,extraTools:n.agentrixExtraTools}):void 0,m={...u?.server?{agentrix:u.server}:{},...n.mcpServers??{},...i??{}};return{stderr:n.stderr,model:n.model||a.customModel,fallbackModel:a.customFallbackModel,cwd:n.cwd,resume:n.agentSessionId,permissionMode:n.initialPermissionMode??a.customPermissionMode??"bypassPermissions",settingSources:["user","project","local"],systemPrompt:c,tools:l,...n.disableClaudePlanModeTools?{disallowedTools:[...CLAUDE_PLAN_MODE_TOOLS]}:{},mcpServers:m,plugins:[...a.customPlugins,...n.projectAgentrixGuidance?.claudePlugins??[]],abortController:n.abortController,env:n.env?mergeEnvironment(n.env):void 0,pathToClaudeCodeExecutable:p,maxTurns:a.customMaxTurns??n.maxTurns??r,extraArgs:a.customExtraArgs,canUseTool:n.canUseTool,hooks:d,outputFormat:n.structuredOutputSchema}}class ClaudeRunner{constructor(e,t,n,a,s){this.agentId=e,this.agentType=t,this.agentConfig=n,this.agentHooks=a,this.agentMcpServers=s}getAgentConfiguration(){return this.agentConfig}getHooks(){return this.agentHooks}getMcpServers(){return this.agentMcpServers}async executeHook(e,t,n){await executeHook(this.agentHooks,e,t,n)}async run(e,t){const n=this.agentConfig,a="string"==typeof e?normalizeClaudeUserMessage(e):e;let s=null;await this.checkpointCompanionRun(t,"before_run");try{const e=claudeAgentSdk.query({prompt:oneShotPrompt(a),options:buildQueryOptions(this.agentId,this.agentType,t,n,this.agentHooks,this.agentMcpServers,t.agentrixTools)});for await(const t of e)if("result"===t.type){s=t;break}if(!s)throw new Error("ClaudeRunner.run: missing result message");return s}finally{await this.checkpointCompanionRun(t,"after_run")}}async*runStreamed(e,t){const n=this.agentConfig,a="string"==typeof e?normalizeClaudeUserMessage(e):e;await this.checkpointCompanionRun(t,"before_run");try{const e=claudeAgentSdk.query({prompt:oneShotPrompt(a),options:buildQueryOptions(this.agentId,this.agentType,t,n,this.agentHooks,this.agentMcpServers,t.agentrixTools)});for await(const t of e)if(yield t,"result"===t.type)break}finally{await this.checkpointCompanionRun(t,"after_run")}}loop(e){const t=this,n=e.abortController,a=this.agentConfig,s=buildQueryOptions(this.agentId,this.agentType,e,a,this.agentHooks,this.agentMcpServers,e.agentrixTools);let i=!1;const o=[];let r=null,c=null;const l=()=>{if(!i&&(i=!0,r)){const e=r;r=null,e(null)}},d=async function*(){for(;!i&&!n.signal.aborted;){if(o.length>0){yield o.shift();continue}const e=await new Promise(e=>{r=e});if(!e)break;yield e}},p=async function*(){try{await t.checkpointCompanionRun(e,"before_run");const n=claudeAgentSdk.query({prompt:d(),options:s});c=n;for await(const e of n)yield e}finally{c=null,await t.checkpointCompanionRun(e,"after_run"),l()}}();return n.signal.addEventListener("abort",l,{once:!0}),{push:e=>{if(i)return;const t="string"==typeof e?normalizeClaudeUserMessage(e):e;if(r){const e=r;return r=null,void e(t)}o.push(t)},events:p,stop:l,setPermissionMode:async e=>{c&&await c.setPermissionMode(e)},setModel:async e=>{c&&await c.setModel(e)}}}async checkpointCompanionRun(e,t){const n=e.modeConfig.mode;if("companion_chat"!==n&&"companion_shadow"!==n)return;const a=process.env.AGENTRIX_COMPANION_HOME||process.env.AGENTRIX_COMPANION_WORKSPACE;await checkpointCompanionSelfEvolution({companionHome:a,mode:n,shadowTask:"companion_shadow"===n?resolveCompanionShadowTask(e.promptPlaceholders):void 0,phase:t})}}const logger$8=machine.createModuleLogger("undefined"==typeof document?require("url").pathToFileURL(__filename).href:_documentCurrentScript&&"SCRIPT"===_documentCurrentScript.tagName.toUpperCase()&&_documentCurrentScript.src||new URL("index.cjs",document.baseURI).href);function createDefaultClaudeAgentConfiguration(){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}}async function loadClaudeAgentConfiguration(e){const{agentId:t,agentDir:n}=e;if(!t||"default"===t)return createDefaultClaudeAgentConfiguration();try{logger$8.info(`Loading agent: ${t}`);const e=await node.loadAgentConfig({agentId:t,framework:"claude",agentDir:n});if(!e.claude)return logger$8.warn(`No claude configuration found for agent ${t}`),createDefaultClaudeAgentConfiguration();const a=e.claude,s=a.plugins.map(e=>({type:"local",path:e})),i=n||node.getAgentContext().resolveAgentDir(t),o=a.config.sdkMcpTools?.map(e=>path.join(i,"claude",e)),r={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:s,systemPromptMode:a.config.systemPrompt?.mode??"append",customPRPromptTemplate:a.prPromptTemplate,prPromptMode:a.config.pullRequestPrompt?.mode??"append",customSdkMcpTools:o};return logger$8.info(`Agent ${t} loaded successfully (${s.length} plugins)`),r}catch{return logger$8.error(`Failed to load agent: ${t}`),createDefaultClaudeAgentConfiguration()}}const PROBE_TIMEOUT_MS=45e3;function buildProbeTimeoutMessage(){return`Companion probe timed out after ${Math.round(45)}s`}function normalizeProbeError(e){return e instanceof Error&&e.message?e.message:String(e)}function extractProbeFailureMessage(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 probeCompanionChain(){const e=path.join(machine.machine.agentrixHomeDir,"tmp","companion-probe");fs.mkdirSync(e,{recursive:!0});const t=new ClaudeRunner("default","claude",createDefaultClaudeAgentConfiguration()),n=new AbortController;let a=!1;const s=setTimeout(()=>{a=!0,n.abort()},45e3);try{const s=await t.run("hi",{cwd:e,abortController:n,modeConfig:{mode:"chat",supportChangeTitle:!1}});return s.is_error?{success:!1,error:a?buildProbeTimeoutMessage():extractProbeFailureMessage(s)}:{success:!0}}catch(e){return{success:!1,error:a?buildProbeTimeoutMessage():normalizeProbeError(e)}}finally{clearTimeout(s)}}const execFileAsync$5=node_util.promisify(node_child_process.execFile);function createGit(e){const t={baseDir:e,binary:"git",maxConcurrentProcesses:6,trimmed:!1};return"win32"===process.platform&&(t.spawnOptions={windowsHide:!0}),simpleGit(t)}async function isGitRepository(e){try{const t=createGit(e);return await t.checkIsRepo()}catch{return!1}}async function listWorktrees(e){const t=createGit(e),n=(await t.raw(["worktree","list","--porcelain"])).trim().split("\n").filter(Boolean),a=[];let s=null;for(const e of n)if(e.startsWith("worktree "))s&&a.push(s),s={path:e.replace("worktree ","").trim(),branch:null,commit:"",isMain:0===a.length};else if(s)if(e.startsWith("HEAD "))s.commit=e.replace("HEAD ","").trim();else{if(e.startsWith("branch ")){const t=e.replace("branch ","").trim();s.branch=t.replace("refs/heads/","");continue}e.startsWith("detached")&&(s.branch=null)}return s&&a.push(s),a}async function createWorktree(e,t,n,a="HEAD"){const s=path.dirname(t);if(fs.existsSync(s)||fs.mkdirSync(s,{recursive:!0}),fs.existsSync(t)&&!isDirectoryEmpty(t))throw new Error(`Worktree directory already exists at ${t}`);const i=createGit(e);await i.raw(["worktree","add","-b",n,t,a])}async function removeWorktree(e,t,n=!1){const a=createGit(e),s=["worktree","remove"];n&&s.push("--force"),s.push(t),await a.raw(s)}async function setGitConfig(e,t,n){await execFileAsync$5("git",["config","user.name",t],{cwd:e,windowsHide:!0}),await execFileAsync$5("git",["config","user.email",n],{cwd:e,windowsHide:!0})}async function gitInit(e){const t=createGit(e);await t.init()}async function initialCommit(e){const t=createGit(e);await t.add("."),await t.commit("Initial commit",{"--allow-empty":null})}async function gitClone(e,t){const n=path.dirname(t);fs.existsSync(n)||fs.mkdirSync(n,{recursive:!0});const a=createGit();await a.clone(e,t)}async function ensureTaskBranch(e,t,n){const a=createGit(e);(await a.branchLocal()).all.includes(t)?await a.checkout(t):(await listRemoteBranches(e).catch(()=>[])).includes(t)?await execFileAsync$5("git",["checkout","-B",t,`origin/${t}`],{cwd:e,windowsHide:!0}):n?await execFileAsync$5("git",["checkout","-b",t,n],{cwd:e,windowsHide:!0}):await a.checkoutLocalBranch(t)}async function hasUncommittedChanges(e){const t=createGit(e);return!(await t.status()).isClean()}async function gitStash(e,t){const n=createGit(e);await n.stash(["push"])}async function getCurrentCommitHash(e){const t=createGit(e),n=await t.log({maxCount:1});if(!n.latest)throw new Error("No commits found in repository");return n.latest.hash}async function hasAnyCommits(e){try{const t=createGit(e);return null!==(await t.log({maxCount:1})).latest}catch{return!1}}function isDirectoryEmpty(e){if(!fs.existsSync(e))return!0;const t=fs.readdirSync(e);return 0===t.length||1===t.length&&".git"===t[0]}async function commitWithMessage(e,t){const n=t.trim();if(!n)throw new Error("Commit message cannot be empty");const[a,...s]=n.split(/\n\s*\n/).map(e=>e.trim()).filter(Boolean);if(!a)throw new Error("Commit subject cannot be empty");const i=createGit(e);await i.add(["--all"]);const o=["commit","-m",a];for(const e of s)o.push("-m",e);return await i.raw(o),await getCurrentCommitHash(e)}function parseGitRenamePath(e){const t=e.match(/^(.*)?\{([^}]*) => ([^}]*)\}(.*)$/);if(!t)return e;const[,n="",,a,s=""]=t;return`${n}${a}${s}`}async function getDiffStats(e,t,n){const a=createGit(e),s=await a.diffSummary([`${t}..${n}`]);return{totalInsertions:s.insertions,totalDeletions:s.deletions,files:s.files.map(e=>({path:parseGitRenamePath(shared.decodeGitPath(e.file)),insertions:"insertions"in e?e.insertions:0,deletions:"deletions"in e?e.deletions:0}))}}function normalizePatch(e){const t=e.trim();return t?`${t}\n`:""}async function runGitDiffCommand(e,t){try{const{stdout:n}=await execFileAsync$5("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}}async function getUntrackedFiles(e){const{stdout:t}=await execFileAsync$5("git",["ls-files","--others","--exclude-standard","-z"],{cwd:e,maxBuffer:10485760,windowsHide:!0});return t.split("\0").filter(Boolean)}function parseNumstatLine(e){const[t,n,a]=e.split("\t");if(!t||!n||!a)return null;const s="-"===t?0:Number.parseInt(t,10),i="-"===n?0:Number.parseInt(n,10);if(Number.isNaN(s)||Number.isNaN(i))return null;const o=a.startsWith("/dev/null => ")?a.slice(13):a;return{path:parseGitRenamePath(shared.decodeGitPath(o)),insertions:s,deletions:i}}function parseNumstatOutput(e){return e.split("\n").map(e=>e.trim()).filter(Boolean).map(e=>parseNumstatLine(e)).filter(e=>null!==e)}function buildDiffStats(e){return{totalInsertions:e.reduce((e,t)=>e+t.insertions,0),totalDeletions:e.reduce((e,t)=>e+t.deletions,0),files:e}}function createArtifactVersion(e,t){return node_crypto.createHash("sha256").update(`${e}\n${t}`).digest("hex")}async function getWorkspaceArtifactsSnapshot(e,t){const n=await runGitDiffCommand(e,["diff","--binary","--find-renames",t,"--"]),a=parseNumstatOutput(await runGitDiffCommand(e,["diff","--numstat","--find-renames",t,"--"])),s=await getUntrackedFiles(e),i=await Promise.all(s.map(t=>runGitDiffCommand(e,["diff","--no-index","--binary","--","/dev/null",t]))),o=parseNumstatOutput((await Promise.all(s.map(t=>runGitDiffCommand(e,["diff","--no-index","--numstat","--","/dev/null",t])))).join("\n")),r=normalizePatch([n,...i].filter(Boolean).join("\n"));return r?{patch:r,stats:buildDiffStats([...a,...o]),artifactVersion:createArtifactVersion(t,r)}:null}async function getCurrentBranch(e){const t=createGit(e);return(await t.revparse(["--abbrev-ref","HEAD"])).trim()}async function gitPush(e,t,n=!1){const a=createGit(e),s=n?["--force"]:[];await a.push("origin",t,s)}async function hasUnpushedCommits(e,t){const n=createGit(e);try{return(await n.log([`origin/${t}..HEAD`])).total>0}catch{return!0}}async function updateRemoteUrl(e,t,n){const a=createGit(e);await a.remote(["set-url",t,n])}function sanitizeGitRemoteUrl(e){try{const t=new URL(e);return t.username="",t.password="",t.toString()}catch{return e}}async function ensureRemote(e,t,n){const a=createGit(e),s=(await a.getRemotes(!0)).find(e=>e.name===t);s?s.refs.fetch!==n&&await updateRemoteUrl(e,t,n):await a.addRemote(t,n)}async function listRemoteBranches(e,t="origin"){const{stdout:n}=await execFileAsync$5("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)}async function forceRefreshLocalBranchToStartPoint(e,t,n){await execFileAsync$5("git",["checkout","--force","-B",t,n],{cwd:e,windowsHide:!0}),await execFileAsync$5("git",["reset","--hard",n],{cwd:e,windowsHide:!0}),await execFileAsync$5("git",["clean","-fd"],{cwd:e,windowsHide:!0})}function parseRemoteInfoFromUrl(e){const t=e.match(/^git@([^:]+):(.+)\/(.+?)(?:\.git)?$/);if(t){const[,n,a,s]=t;return{url:e,host:n.split("-")[0],owner:a,repo:s}}const n=e.match(/^https?:\/\/([^/]+)\/(.+)\/(.+?)(?:\.git)?$/);if(n){const[,t,a,s]=n;return{url:e,host:t,owner:a,repo:s}}return null}async function getRemoteInfo(e){try{const t=createGit(e),n=(await t.getRemotes(!0)).find(e=>"origin"===e.name);return n?.refs?.fetch?parseRemoteInfoFromUrl(n.refs.fetch):null}catch(e){return console.error("[GIT] Failed to get remote info:",e),null}}const DEFAULT_GIT_HTTP_USERNAME="oauth2",ASKPASS_USERNAME_ENV="AGENTRIX_GIT_USERNAME",ASKPASS_PASSWORD_ENV="AGENTRIX_GIT_PASSWORD";function createAskPassScript(){const e=path.join(os.tmpdir(),`git-askpass-${node_crypto.randomUUID()}.sh`);return fs.writeFileSync(e,`#!/bin/sh\ncase "$1" in\n *Username*|*username*) printf '%s\\n' "\${${ASKPASS_USERNAME_ENV}:-oauth2}" ;;\n *) printf '%s\\n' "\${${ASKPASS_PASSWORD_ENV}:-}" ;;\nesac\n`,{mode:448}),e}function askPassEnv(e,t,n="oauth2"){return{...process.env,GIT_ASKPASS:e,GIT_TERMINAL_PROMPT:"0",[ASKPASS_USERNAME_ENV]:n,[ASKPASS_PASSWORD_ENV]:t}}function nonInteractiveGitEnv(){const e={...process.env};return delete e.GIT_ASKPASS,delete e.SSH_ASKPASS,delete e.VSCODE_GIT_ASKPASS_NODE,delete e.VSCODE_GIT_ASKPASS_MAIN,delete e.VSCODE_GIT_ASKPASS_EXTRA_ARGS,e.GIT_TERMINAL_PROMPT="0",e}async function cloneWithAskPass(e,t,n){const a=path.dirname(n);fs.existsSync(a)||fs.mkdirSync(a,{recursive:!0});const s=createAskPassScript();try{await execFileAsync$5("git",["-c","credential.helper=","clone",t,n],{env:askPassEnv(s,e),windowsHide:!0})}finally{fs.unlinkSync(s)}}async function pushWithAskPass(e,t,n,a=!1){const s=createAskPassScript();try{const i=["-c","credential.helper=","push","origin",n];a&&i.push("--force"),await execFileAsync$5("git",i,{cwd:t,env:askPassEnv(s,e),windowsHide:!0})}finally{fs.unlinkSync(s)}}async function fetchWithAskPass(e,t){const n=createAskPassScript();try{await execFileAsync$5("git",["-c","credential.helper=","fetch","--prune","origin"],{cwd:t,env:askPassEnv(n,e),windowsHide:!0})}finally{fs.unlinkSync(n)}}async function fetchWithRemoteUrl(e,t){await execFileAsync$5("git",["-c","credential.helper=","fetch","--prune",e,"+refs/heads/*:refs/remotes/origin/*","+refs/tags/*:refs/tags/*"],{cwd:t,env:nonInteractiveGitEnv(),windowsHide:!0})}async function pushWithRemoteUrl(e,t,n,a=!1){const s=["-c","credential.helper=","push",e,n];a&&s.push("--force"),await execFileAsync$5("git",s,{cwd:t,env:nonInteractiveGitEnv(),windowsHide:!0})}const execFileAsync$4=node_util.promisify(node_child_process.execFile),COMPANION_GIT_SERVER_ID="github",COMPANION_REPOSITORY_OWNER="xmz-ai",COMPANION_REPOSITORY_NAME="agentrix-agent",COMPANION_TEMPLATE_AGENT_ID="companion",COMPANION_FALLBACK_GIT_URL="https://github.com/xmz-ai/agentrix-agent.git",COMPANION_FALLBACK_BRANCH="main";async function fetchCompanionGitUrl(e){const t=`${machine.machine.serverUrl}/v1/agents/${encodeURIComponent("companion")}/git-url`;try{const n=await fetch(t,{headers:{Authorization:`Bearer ${e}`}});return n.ok?n.json():null}catch{return null}}async function resolveCompanionGitSource(e){if(e?.token){const t=await fetchCompanionGitUrl(e.token);if(t?.gitUrl)return{gitUrl:t.gitUrl,branch:t.branch||"main"}}return{gitUrl:COMPANION_FALLBACK_GIT_URL,branch:"main"}}async function cloneCompanionRepository(e,t,n){await execFileAsync$4("git",["clone","--depth=1","--branch",t,e,n]),await ensureRemote(n,"origin",sanitizeGitRemoteUrl(e))}async function pullCompanionRepository(e,t,n){await execFileAsync$4("git",["fetch","--depth=1",e,t],{cwd:n}),await execFileAsync$4("git",["merge","--ff-only","FETCH_HEAD"],{cwd:n}),await ensureRemote(n,"origin",sanitizeGitRemoteUrl(e))}function isRecoverableCheckoutHistoryError(e){const t=e instanceof Error?e.message:String(e);return t.includes("refusing to merge unrelated histories")||t.includes("Not possible to fast-forward")||t.includes("non-fast-forward")}async function replaceCompanionRepository(e,t,n){const a=path.join(path.dirname(n),`.agentrix-agent.tmp-${process.pid}-${Date.now()}`);try{await cloneCompanionRepository(e,t,a),fs.rmSync(n,{recursive:!0,force:!0}),fs.renameSync(a,n)}catch(e){throw fs.rmSync(a,{recursive:!0,force:!0}),e}}async function prepareCompanionTemplateRepository(e){const t=machine.machine.resolveRepoStoreCheckoutDir("github","xmz-ai","agentrix-agent"),n=path.join(t,"companion"),a=machine.machine.resolveRepoStoreLockPath("github","xmz-ai","agentrix-agent"),s=await machine.machine.acquireFileLock(a);if(!s)throw new Error(`Timed out waiting for Companion template repository lock at ${a}`);try{const{gitUrl:a,branch:s}=await resolveCompanionGitSource(e);if(!await isGitRepository(t)){if(!isDirectoryEmpty(t))return{path:t,companionDir:n,pullSucceeded:!1,error:`Companion template checkout exists but is not a git repository: ${t}`};try{return await cloneCompanionRepository(a,s,t),{path:t,companionDir:n,pullSucceeded:!0}}catch(e){return{path:t,companionDir:n,pullSucceeded:!1,error:e instanceof Error?e.message:String(e)}}}try{return await pullCompanionRepository(a,s,t),{path:t,companionDir:n,pullSucceeded:!0}}catch(e){if(isRecoverableCheckoutHistoryError(e))try{return await replaceCompanionRepository(a,s,t),{path:t,companionDir:n,pullSucceeded:!0}}catch(a){return{path:t,companionDir:n,pullSucceeded:!1,error:`${e instanceof Error?e.message:String(e)}; failed to replace checkout: ${a instanceof Error?a.message:String(a)}`}}return{path:t,companionDir:n,pullSucceeded:!1,error:e instanceof Error?e.message:String(e)}}}finally{await machine.machine.releaseFileLock(a,s)}}const TEMPLATE_LANGUAGE_MARKER_RELATIVE_PATH="versions/.companion-template-language.json";function ensureDir(e){fs.existsSync(e)||fs.mkdirSync(e,{recursive:!0})}function normalizeRelativePath(e){return e.split("\\").join("/")}function readTemplatesInDirectory(e){const t={};if(!fs.existsSync(e))return t;const n=a=>{const s=fs.readdirSync(a).sort();for(const i of s){const s=path.join(a,i);if(fs.statSync(s).isDirectory()){n(s);continue}if("versions.json"===i)continue;const o=normalizeRelativePath(path.relative(e,s));t[o]=fs.readFileSync(s,"utf-8")}};return n(e),t}function readVersionMetadata(e,t){const n=path.join(t,"template","versions",`${e}.json`);if(!fs.existsSync(n))return{};try{const e=fs.readFileSync(n,"utf-8");return JSON.parse(e)}catch(e){return console.warn(`[Companion] Failed to parse ${n}:`,e),{}}}function resolveCompanionTemplateLanguage(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"}function isCompanionTemplateLanguage(e){return"en"===e||"zh-Hans"===e}function getTemplateLanguageMarkerPath(e){return path.join(e,TEMPLATE_LANGUAGE_MARKER_RELATIVE_PATH)}function readTemplateLanguageMarker(e){const t=getTemplateLanguageMarkerPath(e);if(!fs.existsSync(t))return null;try{const e=JSON.parse(fs.readFileSync(t,"utf-8"));return isCompanionTemplateLanguage(e.language)?e.language:null}catch{return null}}function inferTemplateLanguageFromInstalledFiles(e){const t=path.join(e,"claude","HEARTBEAT.md");if(!fs.existsSync(t))return null;const n=fs.readFileSync(t,"utf-8");return/[\u3400-\u9fff]/.test(n)||n.includes("# 心跳")?"zh-Hans":n.includes("# Heartbeat")||n.includes("## Routine")?"en":null}function resolveInstalledTemplateLanguage(e,t,n){if(n)return{language:t,source:"initial-install",verified:!0};const a=readTemplateLanguageMarker(e);if(a)return{language:a,source:"marker",verified:!0};const s=inferTemplateLanguageFromInstalledFiles(e);return s?{language:s,source:"inferred",verified:!0}:{language:t,source:"unverified",verified:!1}}function writeTemplateLanguageMarker(e,t,n){if("unverified"===n)return;const a=getTemplateLanguageMarkerPath(e);ensureDir(path.dirname(a)),fs.writeFileSync(a,JSON.stringify({language:t,source:n,updatedAt:(new Date).toISOString()},null,2),"utf-8")}function getTemplatesForLanguage(e,t,n){const a=resolveCompanionTemplateLanguage(e),s=readVersionMetadata("common",t),i=readVersionMetadata(a,t),o=[],r={version:"1.0.0",updateStrategy:"create-only"};for(const[e,n]of Object.entries(s)){const a=path.join(t,e);fs.existsSync(a)&&o.push({relativePath:e,content:fs.readFileSync(a,"utf-8"),metadata:n,language:"common",sourcePath:a})}const c=path.join(t,"template","languages",a),l=readTemplatesInDirectory(c);for(const[e,t]of Object.entries(l)){const s=i[e]||(n?r:void 0);s&&o.push({relativePath:e,content:t,metadata:s,language:a,sourcePath:path.join(c,e)})}if(0===o.length)throw new Error(`Companion template files are missing in ${t}`);return{language:a,templates:o}}async function ensureCompanionAgent(e){const t=machine.machine.agentrixAgentsHomeDir,n=path.join(t,"companion"),a=path.join(n,"claude"),s=!fs.existsSync(path.join(n,"agent.json")),i=await prepareCompanionTemplateRepository(e?.credentials);let o=fs.existsSync(path.join(i.companionDir,"agent.json"))?i.companionDir:n;if(i.pullSucceeded||console.warn("[Companion] Template repository update failed:",i.error||"unknown error"),s){const e=await probeCompanionChain();if(!e.success)throw new Error(`Companion probe failed: ${e.error||"Unknown error"}`);if(fs.existsSync(path.join(o,"agent.json")))fs.cpSync(o,n,{recursive:!0}),buildAgentPlugins(n),console.log("[Companion] Installed from template repository");else try{await installAgentFromGit({agentId:"companion",gitUrl:COMPANION_FALLBACK_GIT_URL,branch:"main",subDir:"companion"}),console.log("[Companion] Installed from git fallback")}catch(e){console.warn("[Companion] Git install failed, will retry next boot:",e instanceof Error?e.message:e)}fs.existsSync(path.join(n,"agent.json"))||(console.log("[Companion] Falling back to public repo install..."),await installAgentFromGit({agentId:"companion",gitUrl:COMPANION_FALLBACK_GIT_URL,branch:"main",subDir:"companion"})),o=fs.existsSync(path.join(i.companionDir,"agent.json"))?i.companionDir:n}ensureDir(path.join(a,"memory"));const r=resolveCompanionTemplateLanguage(e?.preferredLanguage),c=resolveInstalledTemplateLanguage(n,r,s);"marker"===c.source&&c.language!==r&&console.log(`[Companion] Using installed template language ${c.language}; requested language ${r} ignored for safe upgrades`),c.verified||console.warn(`[Companion] Could not safely determine installed template language; language-specific pending upgrades will be diagnostic-only. Requested language: ${r}`);const{language:l,templates:d}=getTemplatesForLanguage(c.language,o,s);writeTemplateLanguageMarker(n,l,c.source);const p=[];for(const e of d){const t=installTemplateFile(path.join(n,e.relativePath),e,n);if(p.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}`)}}p.some(e=>e.updated&&(e.path.startsWith("claude/plugins/")||e.path.startsWith("claude/hooks/")))&&(buildAgentPlugins(n),console.log("[Companion] Rebuilt plugins after template updates"));const{pendingUpgrades:u,blockedUpgrades:m}=checkPendingUpgrades(d,n,{currentLanguage:l,languageVerified:c.verified});if(u.length>0||m.length>0)try{const e=path.join(a,"UPGRADES.md"),t=generateUpgradeNotification({pendingUpgrades:u,blockedUpgrades:m,agentDir:n,language:l,languageSource:c.source});fs.writeFileSync(e,t,"utf-8");for(const e of u)fs.writeFileSync(e.upgradePath,generateUpgradeFileContent(e),"utf-8");console.log(`[Companion] Created UPGRADES.md with ${u.length} pending upgrade(s) and ${m.length} blocked upgrade(s)`),console.log("[Companion] Shadow will process upgrades 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: ${l}`),{agentDir:n,homeDir:a}}const MIGRATIONS=[{version:1,fileName:"001_init.sql"}];function getTaskDb(e){return createTaskDb(resolveDbPath(e.dataDir),e.taskId)}function resolveDbPath(e){return path$1.join(e,"data.bin")}function createTaskDb(e,t){const n=new Database(e),a=new events.EventEmitter;n.pragma("journal_mode = WAL"),migrateSchema(n);const s=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 * FROM task_event\n WHERE event_type = 'task-message'\n ORDER BY COALESCE(sequence, 0) DESC, rowid DESC\n LIMIT ?\n "),d=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 "),u=n.prepare("\n SELECT * FROM task_message\n WHERE local_sequence > ?\n ORDER BY local_sequence ASC\n LIMIT ?\n "),m=n.prepare("\n SELECT * FROM task_message\n WHERE local_sequence < ?\n ORDER BY local_sequence DESC\n LIMIT ?\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 1 as has_row\n FROM task_message\n WHERE local_sequence > ?\n LIMIT 1\n "),f=n.prepare("\n SELECT * FROM task_message\n WHERE local_sequence > ?\n ORDER BY local_sequence DESC\n LIMIT ?\n "),y=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 "),b=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??shared.createEventId(),o=(new Date).toISOString(),r=s.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&&a.emit("message-saved",{eventId:n}),{eventId:n,localSequence:l,inserted:r}},saveTaskEvent:e=>{const t=e.eventId??shared.createEventId(),n=(new Date).toISOString(),a={...e.eventData,eventId:t};return o.run({eventId:t,taskId:e.taskId,chatId:e.chatId,sequence:e.sequence,eventType:e.eventType,eventData:JSON.stringify(a),createdAt:n}),t},updateTaskEventSequence:(e,t)=>{r.run(t,e,t)},pageTaskEventsAfter:(e,t)=>{const n=c.all(e,t).map(parseTaskEventRow),a=n.at(-1)?.sequence??null;return{data:n,hasMore:null!==a&&Boolean(d.get(a))}},pageRecentTaskEvents:e=>{const t=l.all(e);return{data:t.map(parseTaskEventRow).reverse(),hasMore:t.length>=e}},getLatestTaskEvent:e=>{if(0===e.length)return null;const t=e.map(()=>"?").join(","),a=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 a?parseTaskEventRow(a):null},pageRecentMessages:e=>{const t=p.all(e).map(parseTaskMessageRow).reverse(),n=t[0]?.localSequence??null;return{data:t,hasMore:!!n&&Boolean(h.get(n))}},pageMessagesAfter:(e,t)=>{const n=u.all(e,t).map(parseTaskMessageRow),a=n.at(-1)?.localSequence??null;return{data:n,hasMore:!!a&&Boolean(g.get(a))}},pageMessagesBefore:(e,t)=>{const n=m.all(e,t).map(parseTaskMessageRow).reverse(),a=n[0]?.localSequence??null;return{data:n,hasMore:!!a&&Boolean(h.get(a))}},pageRecentMessagesAfter:(e,t)=>{const n=f.all(e,t).map(parseTaskMessageRow).reverse(),a=n[0]?.localSequence??null;return{data:n,hasMore:!!a&&Boolean(h.get(a))}},getAgentSessions:()=>{const e=y.all(),t=new Map;for(const n of e)t.set(n.agent_id,n.session_id);return t},getAgentLastSequences:()=>{const e=y.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)=>{b.run(e,t,n,(new Date).toISOString())},on:(e,t)=>{a.on(e,t)},off:(e,t)=>{a.off(e,t)},close:()=>{a.removeAllListeners(),n.close()}}}function migrateSchema(e){const t=resolveMigrationsDir(),n=e.pragma("user_version",{simple:!0}),a=loadMigrationSql(t,MIGRATIONS[0].fileName);e.exec(a),n<MIGRATIONS[0].version&&e.pragma(`user_version = ${MIGRATIONS[0].version}`)}function resolveMigrationsDir(){const e=path$1.dirname(url.fileURLToPath("undefined"==typeof document?require("url").pathToFileURL(__filename).href:_documentCurrentScript&&"SCRIPT"===_documentCurrentScript.tagName.toUpperCase()&&_documentCurrentScript.src||new URL("index.cjs",document.baseURI).href)),t=[path$1.join(e,"migrations"),path$1.join(process.cwd(),"dist","migrations"),path$1.join(process.cwd(),"src","worker","history","migrations")];for(const e of t)if(fs$1.existsSync(e))return e;throw new Error(`Task history migrations directory not found at ${t[0]}`)}function loadMigrationSql(e,t){const n=path$1.join(e,t);return fs$1.readFileSync(n,"utf8")}function parseTaskMessageRow(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 parseTaskEventRow(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 DEFAULT_HEARTBEAT_INTERVAL_MS=9e5,DEFAULT_INITIAL_DELAY_MS=6e4,DEFAULT_MEMORY_ORGANIZATION_INTERVAL_HOURS=4,ALLOWED_MEMORY_ORGANIZATION_INTERVAL_HOURS=[1,2,4,6,8,12,24];function isAllowedMemoryOrganizationIntervalHours(e){return"number"==typeof e&&ALLOWED_MEMORY_ORGANIZATION_INTERVAL_HOURS.includes(e)}function normalizeMemoryOrganizationIntervalHours(e){return isAllowedMemoryOrganizationIntervalHours(e)?e:4}class CompanionScheduler{constructor(e,t,n={}){this.client=e,this.machineId=t;const a=machine.machine.agentrixAgentsHomeDir,s=path.join(a,"companion","claude");this.stateFilePath=n.stateFilePath??path.join(s,"state.json"),this.initialDelayMs=n.initialDelayMs??6e4}timer=null;initialDelay=null;intervalMs=9e5;enabled=!1;heartbeatTaskId=null;memoryOrganizationEnabled=!1;memoryOrganizationIntervalHours=4;memoryOrganizationTaskId=null;companionState=null;stateFilePath;initialDelayMs;started=!1;cronJobs=new Map;start(){this.started?this.reloadStateAndReschedule():(this.started=!0,this.loadState(),this.companionState?(machine.logger.info(`[COMPANION SCHEDULER] Ready: agent=${this.companionState.agentId}, chatId=${this.companionState.chatId}`),this.restoreScheduledTasks()):machine.logger.warn("[COMPANION SCHEDULER] No state.json found (companion not registered yet), will keep checking"),machine.logger.info(`[COMPANION SCHEDULER] Starting with interval ${this.intervalMs}ms`),this.initialDelay=setTimeout(()=>{this.initialDelay=null,this.tick(),this.scheduleNext()},this.initialDelayMs))}stop(){this.started=!1,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(),machine.logger.debug(`[COMPANION SCHEDULER] Stopped cron job: ${e}`);this.cronJobs.clear(),machine.logger.info("[COMPANION SCHEDULER] Stopped")}scheduleNext(){this.started&&(this.timer&&(clearTimeout(this.timer),this.timer=null),this.timer=setTimeout(()=>{this.timer=null,this.tick(),this.scheduleNext()},this.intervalMs))}reloadStateAndReschedule(){this.loadState()}reschedulePendingHeartbeatTimer(){this.initialDelay&&(clearTimeout(this.initialDelay),this.initialDelay=null),this.scheduleNext(),machine.logger.info(`[COMPANION SCHEDULER] Rescheduled pending heartbeat timer with interval ${this.intervalMs}ms`)}setHeartbeatTaskId(e){this.heartbeatTaskId=e,this.saveStateField("heartbeatTaskId",e)}clearHeartbeatTaskId(){this.heartbeatTaskId=null,this.saveStateField("heartbeatTaskId",void 0),machine.logger.info("[COMPANION SCHEDULER] Cleared heartbeat task ID")}setMemoryOrganizationTaskId(e){this.memoryOrganizationTaskId=e,this.saveStateField("memoryOrganizationTaskId",e)}clearMemoryOrganizationTaskId(){this.memoryOrganizationTaskId=null,this.saveStateField("memoryOrganizationTaskId",void 0),machine.logger.info("[COMPANION SCHEDULER] Cleared memory organization task ID")}recordInteraction(e){if(!this.companionState?.chatId||e!==this.companionState.chatId)return;const t=(new Date).toISOString();this.saveStateField("lastInteractionTimestamp",t),machine.logger.debug(`[COMPANION SCHEDULER] Recorded interaction at ${t}`)}loadState(){try{if(fs.existsSync(this.stateFilePath)){this.companionState=JSON.parse(fs.readFileSync(this.stateFilePath,"utf-8"));const e=this.intervalMs,t=this.companionState?.heartbeatIntervalMs??9e5;t!==this.intervalMs&&(machine.logger.info(`[COMPANION SCHEDULER] Interval changed: ${this.intervalMs}ms -> ${t}ms`),this.intervalMs=t,this.started&&(this.timer||this.initialDelay)&&e!==this.intervalMs&&this.reschedulePendingHeartbeatTimer()),this.enabled=this.companionState?.heartbeatEnabled??!1,this.heartbeatTaskId=this.companionState?.heartbeatTaskId??null,this.memoryOrganizationEnabled=this.companionState?.memoryOrganizationEnabled??!1,this.memoryOrganizationIntervalHours=normalizeMemoryOrganizationIntervalHours(this.companionState?.memoryOrganizationIntervalHours),this.memoryOrganizationTaskId=this.companionState?.memoryOrganizationTaskId??null,machine.logger.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"}, memoryOrganizationEnabled=${this.memoryOrganizationEnabled}, memoryOrganizationIntervalHours=${this.memoryOrganizationIntervalHours}, memoryOrganizationTaskId=${this.memoryOrganizationTaskId??"none"}`)}}catch(e){machine.logger.warn("[COMPANION SCHEDULER] Failed to load state.json",e)}}saveStateField(e,t){try{let n={};fs.existsSync(this.stateFilePath)&&(n=JSON.parse(fs.readFileSync(this.stateFilePath,"utf-8"))),void 0===t?delete n[e]:n[e]=t;const a=path.dirname(this.stateFilePath);fs.existsSync(a)||fs.mkdirSync(a,{recursive:!0}),fs.writeFileSync(this.stateFilePath,JSON.stringify(n,null,2),"utf-8"),machine.logger.debug(`[COMPANION SCHEDULER] Saved state field: ${e}=${t??"removed"}`)}catch(t){machine.logger.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")}`}isMemoryOrganizationDue(e,t){if(!this.memoryOrganizationEnabled)return!1;if(!(e.agentId&&e.machineId&&e.userId&&e.chatId))return!1;if(!e.lastMemoryOrganizationTimestamp)return!0;const n=new Date(e.lastMemoryOrganizationTimestamp).getTime();if(Number.isNaN(n))return!0;const a=60*this.memoryOrganizationIntervalHours*60*1e3;return t.getTime()-n>=a}triggerMemoryOrganization(e,t){const n=t.toISOString();this.saveStateField("lastMemoryOrganizationTimestamp",n);const a=t.toLocaleString(),s={type:"companion_memory_organization",timestamp:n,trigger:"scheduled",triggerTime:a,intervalHours:this.memoryOrganizationIntervalHours};if(this.memoryOrganizationTaskId)return machine.logger.debug(`[COMPANION SCHEDULER] Sending memory organization to existing task ${this.memoryOrganizationTaskId}`),void this.client.send("task-message",{eventId:shared.createEventId(),taskId:this.memoryOrganizationTaskId,chatId:e.chatId,from:"machine",message:s,senderType:"system",senderId:"system",senderName:"system"});machine.logger.debug("[COMPANION SCHEDULER] Requesting initial memory organization task"),this.client.send("request-companion-memory-organization",{eventId:shared.createEventId(),machineId:e.machineId,agentId:e.agentId,chatId:e.chatId,userId:e.userId,timestamp:n,trigger:"scheduled",triggerTime:a,intervalHours:this.memoryOrganizationIntervalHours})}addScheduledTask(e){const t={id:node_crypto.randomUUID(),...e,createdAt:(new Date).toISOString()};this.loadState();const n=this.companionState?.scheduledTasks??[];return n.push(t),this.saveStateField("scheduledTasks",n),this.startCronJob(t),machine.logger.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 a=this.cronJobs.get(e);return a&&(a.stop(),this.cronJobs.delete(e)),machine.logger.info(`[COMPANION SCHEDULER] Deleted scheduled task: id=${e}`),!0}startCronJob(e){try{const t={},n="utc"===e.timeType;let a;if(e.due){if(n){const n=new Date(e.due);a=`${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 machine.logger.warn(`[COMPANION SCHEDULER] Cannot parse due date: ${e.due}, skipping: ${e.id}`);a=`${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 machine.logger.warn(`[COMPANION SCHEDULER] Invalid task entry, skipping: ${e.id}`);a=e.cron,n?t.timezone="Etc/UTC":e.timezone&&(t.timezone=e.timezone)}const s=new croner.Cron(a,t,()=>{this.onScheduledTaskFired(e)});this.cronJobs.set(e.id,s),machine.logger.debug(`[COMPANION SCHEDULER] Started cron job: id=${e.id}, pattern="${a}"`)}catch(t){machine.logger.warn(`[COMPANION SCHEDULER] Failed to start cron job for task ${e.id}`,t)}}onScheduledTaskFired(e){machine.logger.info(`[COMPANION SCHEDULER] Scheduled task fired: id=${e.id}, task="${e.task}"`),this.loadState();const t=this.companionState;if(!t?.chatId)return;const n=t.chatTaskId??t.chatId;this.client.send("task-message",{eventId:shared.createEventId(),taskId:n,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()?machine.logger.debug(`[COMPANION SCHEDULER] Skipping expired one-time task: ${n.id}`):(this.startCronJob(n),t++);machine.logger.info(`[COMPANION SCHEDULER] Restored ${t}/${e.length} scheduled tasks`)}tick(){if(this.loadState(),!this.companionState)return void machine.logger.debug("[COMPANION SCHEDULER] Still no state.json, skipping heartbeat");const e=this.companionState,t=[],n=new Date;if(this.isMemoryOrganizationDue(e,n)&&(machine.logger.info("[COMPANION SCHEDULER] Memory organization triggered"),this.triggerMemoryOrganization(e,n)),!this.enabled)return void machine.logger.debug("[COMPANION SCHEDULER] Heartbeat disabled, skipping");e.lastInteractionTimestamp&&(!e.lastHeartbeatTimestamp||new Date(e.lastInteractionTimestamp).getTime()>new Date(e.lastHeartbeatTimestamp).getTime())&&t.push("new_interaction");const a=this.getTodayDateString();if(e.lastHeartbeatDate!==a&&t.push("first_today"),0===t.length)return void machine.logger.debug("[COMPANION SCHEDULER] No trigger conditions met, skipping heartbeat");machine.logger.info(`[COMPANION SCHEDULER] Heartbeat triggered: ${t.join(", ")}`);const s=("number"==typeof e.heartbeatTriggerCount?e.heartbeatTriggerCount:0)+1;this.saveStateField("lastHeartbeatTimestamp",n.toISOString()),this.saveStateField("lastHeartbeatDate",a),this.saveStateField("heartbeatTriggerCount",s);const i=n.toLocaleString(),o={type:"companion_heartbeat",timestamp:n.toISOString(),triggerTime:i,triggerReasons:t,heartbeatTriggerCount:s};this.heartbeatTaskId?(machine.logger.debug(`[COMPANION SCHEDULER] Sending heartbeat to existing task ${this.heartbeatTaskId}`),this.client.send("task-message",{eventId:shared.createEventId(),taskId:this.heartbeatTaskId,chatId:e.chatId,from:"machine",message:o,senderType:"system",senderId:"system",senderName:"system"})):(machine.logger.debug("[COMPANION SCHEDULER] Requesting new heartbeat task"),this.client.send("request-companion-heartbeat",{eventId:shared.createEventId(),machineId:e.machineId,agentId:e.agentId,chatId:e.chatId,userId:e.userId,timestamp:n.toISOString(),triggerTime:i,triggerReasons:t,heartbeatTriggerCount:s}))}}const store=new node.GitServerLocalStore({credentialsDir:path.join(machine.machine.agentrixHomeDir,"credentials")});async function getGitServerEncryptionKey(){const e=await machine.machine.readCredentials();return e?.secret?node.deriveLocalGitServerEncryptionKey(e.secret):null}function saveGitServerConfig(e,t){store.saveGitServerConfig(e,t)}function loadGitServerConfig(e){return store.loadGitServerConfig(e)}function loadGitLabWebhookBridgeSecrets(e,t){return store.loadGitLabWebhookBridgeSecrets(e,t)}function saveGitLabWebhookBridgeSecrets(e,t,n){store.saveGitLabWebhookBridgeSecrets(e,t,n)}function ensureGitLabWebhookSecret(e,t){return store.ensureGitLabWebhookSecret(e,t)}function loadPatMeta(e){return store.loadPatMeta(e)}function savePatMeta(e,t){store.savePatMeta(e,t)}function savePat(e,t,n){store.savePat(e,t,n)}function loadPat(e,t){return store.loadPat(e,t)}function hasPat(e){return store.hasPat(e)}const DEFAULT_BASE_URL="https://ilinkai.weixin.qq.com",WECHAT_CDN_BASE_URL="https://novac2c.cdn.weixin.qq.com/c2c",DEFAULT_POLL_TIMEOUT_MS=3e4,DEFAULT_REQUEST_TIMEOUT_MS=4e4,INITIAL_RETRY_DELAY_MS$1=1e3,MAX_RETRY_DELAY_MS$1=3e4,BOT_MESSAGE_TYPE=2,FINISH_MESSAGE_STATE=2,TEXT_ITEM_TYPE=1,IMAGE_ITEM_TYPE=2,FILE_ITEM_TYPE=4,IMAGE_MEDIA_TYPE=1,FILE_MEDIA_TYPE=3,WECHAT_CDN_ENCRYPT_TYPE=1,require$1=node_module.createRequire("undefined"==typeof document?require("url").pathToFileURL(__filename).href:_documentCurrentScript&&"SCRIPT"===_documentCurrentScript.tagName.toUpperCase()&&_documentCurrentScript.src||new URL("index.cjs",document.baseURI).href),qrcodeTerminal=require$1("qrcode-terminal");function requireString$2(e,t){if("string"!=typeof e||0===e.trim().length)throw new Error(`WeChat credential "${t}" is required`);return e.trim()}function optionalString$1(e){return"string"==typeof e&&e.trim().length>0?e.trim():void 0}function optionalNumber(e,t){if("number"==typeof e&&Number.isFinite(e)&&e>0)return e;if("string"==typeof e){const t=Number(e);if(Number.isFinite(t)&&t>0)return t}return t}function parseCredentials$2(e){const t=optionalString$1(e.token)??optionalString$1(e.botToken)??optionalString$1(e.bot_token)??optionalString$1(e.apiKey)??optionalString$1(e.api_key);return{baseUrl:optionalString$1(e.baseUrl)??optionalString$1(e.base_url)??DEFAULT_BASE_URL,token:t||requireString$2(t,"token"),routeTag:optionalString$1(e.routeTag)??optionalString$1(e.route_tag),getUpdatesBuf:optionalString$1(e.getUpdatesBuf)??optionalString$1(e.get_updates_buf)??"",channelVersion:optionalString$1(e.channelVersion)??optionalString$1(e.channel_version)??"1.0.0",pollTimeoutMs:optionalNumber(e.pollTimeoutMs??e.poll_timeout_ms,3e4),requestTimeoutMs:optionalNumber(e.requestTimeoutMs??e.request_timeout_ms,4e4),fileDownloadEndpoint:optionalString$1(e.fileDownloadEndpoint)??optionalString$1(e.file_download_endpoint)??optionalString$1(e.downloadEndpoint)??optionalString$1(e.download_endpoint)??"downloadfile"}}function normalizeTimestamp$1(e){if("number"==typeof e||"string"==typeof e){const t=Number(e);if(Number.isFinite(t))return new Date(t>1e10?t:1e3*t).toISOString();const n=new Date(e);if(!Number.isNaN(n.getTime()))return n.toISOString()}return(new Date).toISOString()}function getStringField(e,t){for(const n of t){const t=e[n];if("string"==typeof t&&t.trim())return t}}function getTextContent$1(e){if("string"==typeof e.text)return e.text;if("string"==typeof e.content)return e.content;if(e.text_item?.text)return e.text_item.text;for(const t of e.item_list??[]){if("string"==typeof t.text)return t.text;if("string"==typeof t.text_item?.text)return t.text_item.text}}function getMessageItems(e){return e.item_list??[]}function inferMessageType$1(e){const t=String(e.message_type??e.msg_type??"").toLowerCase();if(t.includes("image"))return"image";if(t.includes("file"))return"file";if(t.includes("voice")||t.includes("audio"))return"voice";if(e.image_item)return"image";if(e.file_item)return"file";for(const t of getMessageItems(e)){const e=String(t.type??"").toLowerCase();if(t.image_item||e.includes("image"))return"image";if(t.file_item||e.includes("file"))return"file";if(e.includes("voice")||e.includes("audio"))return"voice"}return"text"}function getImageKey$1(e){if(e.image_item?.media?.full_url)return encodeWechatMediaKey(e.image_item.media,e.image_item.aeskey,"image.jpg");if(e.image_item?.url)return e.image_item.url;if(e.image_item?.file_id)return e.image_item.file_id;if(e.image_item?.image_key)return e.image_item.image_key;for(const t of e.item_list??[]){if(t.image_item?.media?.full_url)return encodeWechatMediaKey(t.image_item.media,t.image_item.aeskey,"image.jpg");if(t.image_item?.url)return t.image_item.url;if(t.image_item?.file_id)return t.image_item.file_id;if(t.image_item?.image_key)return t.image_item.image_key}}function getFileData(e){if(e.file_item){const t=e.file_item.file_name??e.file_item.name;return{fileKey:e.file_item.media?.full_url?encodeWechatMediaKey(e.file_item.media,void 0,t):e.file_item.file_id??e.file_item.file_key,fileName:t}}for(const t of e.item_list??[])if(t.file_item){const e=t.file_item.file_name??t.file_item.name;return{fileKey:t.file_item.media?.full_url?encodeWechatMediaKey(t.file_item.media,void 0,e):t.file_item.file_id??t.file_item.file_key,fileName:e}}return{}}function encodeWechatMediaKey(e,t,n){const a={url:e.full_url||"",aesKey:e.aes_key||t,fileName:n};return`wechat-media:${Buffer.from(JSON.stringify(a)).toString("base64url")}`}function decodeWechatMediaKey(e){if(!e.startsWith("wechat-media:"))return null;try{const t=JSON.parse(Buffer.from(e.slice(13),"base64url").toString("utf-8"));return"string"==typeof t?.url&&t.url?{url:t.url,aesKey:"string"==typeof t.aesKey?t.aesKey:void 0,fileName:"string"==typeof t.fileName?t.fileName:void 0}:null}catch{return null}}function collectUpdates(e){return e?Array.isArray(e.updates)?e.updates:Array.isArray(e.msgs)?e.msgs:Array.isArray(e.message_list)?e.message_list:Array.isArray(e.items)?e.items:[]:[]}function getRetCode(e){return e.retcode??e.ret??e.errcode}function formatILinkError(e,t){const n=getRetCode(e);return[void 0===n?void 0:`ret=${n}`,e.errmsg||t].filter(Boolean).join(", ")}function buildApiUrl(e,t){const n=e.replace(/\/+$/,"");return n.endsWith("/ilink/bot")?`${n}/${t}`:`${n}/ilink/bot/${t}`}function renderTerminalQRCode(e){let t="";return qrcodeTerminal.generate(e,{small:!0},e=>{t=e}),t}class WechatAdapter{id;platform="wechat";capabilities={sendText:!0,sendImage:!0,sendFile:!0,sendAudio:!1,sendVideo:!1};messageHandler=null;stateHandler=null;connectionState="disconnected";credentials;polling=!1;pollController=null;pollPromise=null;retryTimer=null;resolveRetrySleep=null;retryDelayMs=1e3;contextTokens=new Map;clientId=node_crypto.randomBytes(8).toString("hex");constructor(e){this.id=e.id,this.credentials=parseCredentials$2(e.credentials)}static async createLoginQRCode(e={}){const t=e.baseUrl?.trim()||DEFAULT_BASE_URL,n={};e.routeTag?.trim()&&(n.SKRouteTag=e.routeTag.trim());const a=await fetch(`${buildApiUrl(t,"get_bot_qrcode")}?bot_type=3`,{method:"GET",headers:n}),s=await a.json().catch(()=>({}));if(!a.ok)throw new Error(`HTTP ${a.status}: ${JSON.stringify(s)}`);const i=getRetCode(s);if(i&&0!==i)throw new Error(formatILinkError(s,"WeChat QR login failed"));if(!s.qrcode||!s.qrcode_img_content)throw new Error("WeChat QR login response is missing qrcode data");return{qrcode:s.qrcode,qrcodeContent:s.qrcode_img_content,qrcodeTerminal:renderTerminalQRCode(s.qrcode_img_content),baseUrl:t}}static async getLoginStatus(e,t={}){const n=t.baseUrl?.trim()||DEFAULT_BASE_URL,a=await fetch(`${buildApiUrl(n,"get_qrcode_status")}?qrcode=${encodeURIComponent(e)}`,{method:"GET",headers:{"iLink-App-ClientVersion":"1"}}),s=await a.json().catch(()=>({}));if(!a.ok)throw new Error(`HTTP ${a.status}: ${JSON.stringify(s)}`);const i=getRetCode(s);if(i&&0!==i)throw new Error(formatILinkError(s,"WeChat QR status failed"));return{status:s.status||"wait",token:s.bot_token,baseUrl:s.baseurl,ilinkBotId:s.ilink_bot_id,ilinkUserId:s.ilink_user_id}}get state(){return this.connectionState}async connect(){"connected"!==this.connectionState&&"connecting"!==this.connectionState&&(this.polling=!0,this.retryDelayMs=1e3,this.setState("connecting"),this.pollPromise=this.pollLoop(),this.setState("connected"),machine.logger.info(`[CHANNEL][WECHAT] Connected: channel=${this.id}`))}async disconnect(){this.polling=!1,this.retryTimer&&(clearTimeout(this.retryTimer),this.retryTimer=null,this.resolveRetrySleep?.()),this.resolveRetrySleep=null,this.pollController?.abort(),this.pollController=null,await(this.pollPromise?.catch(()=>{})),this.pollPromise=null,this.setState("disconnected")}async sendMessage(e,t){const n=this.contextTokens.get(e);if(!n)throw new Error(`WeChat sendMessage requires an iLink context_token for chat ${e}; wait for this contact to send a message first`);const a=await this.request("sendmessage",{msg:{from_user_id:"",to_user_id:e,client_id:`agentrix-wechat:${Date.now()}-${node_crypto.randomBytes(4).toString("hex")}`,message_type:2,message_state:2,context_token:n,item_list:[{type:1,text_item:{text:t}}]}},{timeoutMs:this.credentials.requestTimeoutMs}),s=getRetCode(a);if(s&&0!==s)throw new Error(formatILinkError(a,"WeChat sendMessage failed"))}async sendChannelMessage(e,t){const n=t.content?.trim();n&&await this.sendMessage(e,n);for(const n of t.attachments??[])await this.sendAttachment(e,n)}async sendAttachment(e,t){const n=this.contextTokens.get(e);if(!n)throw new Error(`WeChat send attachment requires an iLink context_token for chat ${e}; wait for this contact to send a message first`);const a=t.fileName?.trim()||path.basename(t.filePath),s=await promises$1.readFile(t.filePath),i=this.resolveOutgoingKind(t),o="image"===i?1:3,r="image"===i?2:4,c=await this.uploadWechatMedia(e,s,a,o),l={full_url:c.fullUrl,aes_key:c.aesKey,encrypt_query_param:c.encryptQueryParam,encrypt_type:1},d="image"===i?{type:r,image_item:{media:l,aeskey:c.aesKeyHex,mid_size:c.encryptedSize}}:{type:r,file_item:{file_name:a,name:a,md5:c.md5,media:l,len:String(s.length)}},p=await this.request("sendmessage",{msg:{from_user_id:"",to_user_id:e,client_id:`agentrix-wechat:${Date.now()}-${node_crypto.randomBytes(4).toString("hex")}`,message_type:2,message_state:2,context_token:n,item_list:[d]}},{timeoutMs:this.credentials.requestTimeoutMs}),u=getRetCode(p);if(u&&0!==u)throw new Error(formatILinkError(p,"WeChat send attachment failed"))}resolveOutgoingKind(e){return"image"===e.kind?"image":e.kind&&"auto"!==e.kind&&"file"!==e.kind?"file":e.mimeType?.startsWith("image/")?"image":"file"}async uploadWechatMedia(e,t,n,a){const s=node_crypto.randomBytes(16).toString("hex"),i=node_crypto.randomBytes(16).toString("hex"),o=this.encryptWechatMedia(t,i),r=node_crypto.createHash("md5").update(t).digest("hex"),c=await this.request("getuploadurl",{media_type:a,to_user_id:e,filekey:s,rawsize:t.length,rawfilemd5:r,filesize:o.length,no_need_thumb:!0,aeskey:i},{timeoutMs:this.credentials.requestTimeoutMs}),l=getRetCode(c);if(l&&0!==l)throw new Error(formatILinkError(c,"WeChat getuploadurl failed"));const d=this.extractUploadParam(c),p=await fetch(`${WECHAT_CDN_BASE_URL}/upload?encrypted_query_param=${encodeURIComponent(d)}&filekey=${encodeURIComponent(s)}`,{method:"POST",headers:{"Content-Type":"application/octet-stream","Content-Length":String(o.length)},body:o});if(!p.ok){const e=await p.text().catch(()=>"");throw new Error(`WeChat CDN upload failed: HTTP ${p.status}: ${e||p.statusText}`)}const u=p.headers.get("x-encrypted-param");if(!u)throw new Error("WeChat CDN upload response missing x-encrypted-param");return{fullUrl:`${WECHAT_CDN_BASE_URL}/download?encrypted_query_param=${encodeURIComponent(u)}`,aesKey:Buffer.from(i,"utf-8").toString("base64"),aesKeyHex:i,encryptQueryParam:u,md5:r,encryptedSize:o.length}}extractUploadParam(e){const t=e.upload_param;if("string"==typeof t&&t.trim())return t.trim();const n=e.data;if(n&&"object"==typeof n){const e=n.upload_param;if("string"==typeof e&&e.trim())return e.trim()}throw new Error("WeChat getuploadurl response missing upload_param")}async getContacts(){return[]}async downloadFile(e,t={}){try{const n=decodeWechatMediaKey(e);if(n)return await this.downloadEncryptedMedia(n,t.fileName);if(/^https?:\/\//i.test(e))return await downloadUrlToChannelFile(e,t.fileName);const a=await this.requestDownloadFile(e);return await saveResponseToChannelFile(a,t.fileName||e)}catch(t){return machine.logger.warn(`[CHANNEL][WECHAT] Failed to download file: channel=${this.id}, fileKey=${e}`,t),null}}async getChatName(e){return e}async getUserName(e){return e}onMessage(e){this.messageHandler=e}onStateChange(e){this.stateHandler=e}setState(e,t){this.connectionState=e,this.stateHandler?.(e,t)}async pollLoop(){for(;this.polling;)try{const e=await this.request("getupdates",{get_updates_buf:this.credentials.getUpdatesBuf},{timeoutMs:Math.max(this.credentials.requestTimeoutMs,this.credentials.pollTimeoutMs+5e3)}),t=getRetCode(e);if(t&&0!==t)throw new Error(formatILinkError(e,"WeChat getupdates failed"));const n=e.data??e;this.credentials.getUpdatesBuf=n.get_updates_buf??this.credentials.getUpdatesBuf,this.retryDelayMs=1e3,"connected"!==this.connectionState&&this.setState("connected");for(const e of collectUpdates(n)){const t=this.normalizeMessage(e);t&&await(this.messageHandler?.(t))}}catch(e){if(!this.polling)break;if(this.isAbortError(e))continue;const t=e instanceof Error?e:new Error(String(e));machine.logger.warn(`[CHANNEL][WECHAT] Poll failed: channel=${this.id}, message=${t.message}`),this.setState("error",t),await this.sleepWithCancel(this.retryDelayMs),this.retryDelayMs=Math.min(2*this.retryDelayMs,3e4),this.polling&&this.setState("connecting")}}async request(e,t,n){const a=new AbortController;"getupdates"===e&&(this.pollController=a);const s=setTimeout(()=>a.abort(),n.timeoutMs);try{const n=this.buildHeaders(),s=await fetch(this.apiUrl(e),{method:"POST",headers:n,body:JSON.stringify({base_info:{channel_version:this.credentials.channelVersion},client_id:this.clientId,...t}),signal:a.signal}),i=await s.json().catch(()=>({}));if(!s.ok)throw new Error(`HTTP ${s.status}: ${JSON.stringify(i)}`);return i}finally{clearTimeout(s),"getupdates"===e&&this.pollController===a&&(this.pollController=null)}}async requestDownloadFile(e){const t=new AbortController,n=setTimeout(()=>t.abort(),this.credentials.requestTimeoutMs);try{const n=this.buildHeaders(),a=await fetch(this.apiUrl(this.credentials.fileDownloadEndpoint),{method:"POST",headers:n,body:JSON.stringify({base_info:{channel_version:this.credentials.channelVersion},client_id:this.clientId,file_id:e,file_key:e,image_key:e}),signal:t.signal});if(!a.ok){const e=await a.text().catch(()=>"");throw new Error(`HTTP ${a.status}: ${e||a.statusText}`)}return a}finally{clearTimeout(n)}}async downloadEncryptedMedia(e,t){const n=await fetch(e.url);if(!n.ok)throw new Error(`HTTP ${n.status}: ${n.statusText}`);const a=Buffer.from(await n.arrayBuffer()),s=e.aesKey?this.decryptWechatMedia(a,e.aesKey):a,i=createChannelFilePath(t||e.fileName||"attachment");return await promises$1.writeFile(i,s),i}decryptWechatMedia(e,t){const n=this.decodeWechatAesKey(t);try{const t=node_crypto.createDecipheriv("aes-128-ecb",n,null);return Buffer.concat([t.update(e),t.final()])}catch{const t=node_crypto.createDecipheriv("aes-128-ecb",n,null);return t.setAutoPadding(!1),Buffer.concat([t.update(e),t.final()])}}encryptWechatMedia(e,t){const n=Buffer.from(t,"hex");if(16!==n.length)throw new Error(`Invalid WeChat upload AES key length: ${n.length}`);const a=node_crypto.createCipheriv("aes-128-ecb",n,null);return Buffer.concat([a.update(e),a.final()])}decodeWechatAesKey(e){const t=Buffer.from(e,"base64").toString("utf-8"),n=/^[0-9a-f]{32}$/i.test(t)?t:e,a=/^[0-9a-f]{32}$/i.test(n)?Buffer.from(n,"hex"):Buffer.from(n,"utf-8");if(16!==a.length)throw new Error(`Invalid WeChat media AES key length: ${a.length}`);return a}buildHeaders(){const e={"Content-Type":"application/json",AuthorizationType:"ilink_bot_token",Authorization:`Bearer ${this.credentials.token}`,"X-WECHAT-UIN":this.generateWechatUin()};return this.credentials.routeTag&&(e.SKRouteTag=this.credentials.routeTag),e}apiUrl(e){return buildApiUrl(this.credentials.baseUrl,e)}generateWechatUin(){const e=node_crypto.randomBytes(4).readUInt32BE(0).toString();return Buffer.from(e).toString("base64")}sleepWithCancel(e){return new Promise(t=>{this.resolveRetrySleep=t,this.retryTimer=setTimeout(()=>{this.retryTimer=null,this.resolveRetrySleep=null,t()},e)})}isAbortError(e){return e instanceof Error&&"AbortError"===e.name}normalizeMessage(e){const t=e.chat_id??e.room_id??e.talker??e.from_user_id;if(!t)return machine.logger.warn(`[CHANNEL][WECHAT] Ignoring malformed message event: channel=${this.id}`),null;e.context_token&&this.contextTokens.set(t,e.context_token);const n=e,a=getFileData(e),s=e.from_user_id??e.sender??t,i=!0===n.is_at||!0===n.mentioned_bot||!0===n.at_bot,o=!0===n.reply_to_bot||!0===n.is_reply_to_bot;return{id:e.message_id??e.msg_id??String(e.id??e.seq??node_crypto.randomUUID()),channelId:this.id,platform:"wechat",chatId:t,chatType:e.room_id||String(t).endsWith("@chatroom")?"group":"p2p",senderId:s,senderName:getStringField(n,["sender_name","nickname","user_name"]),type:inferMessageType$1(e),text:getTextContent$1(e),fileKey:a.fileKey,fileName:a.fileName,imageKey:getImageKey$1(e),mentionedBot:i,replyToBot:o,triggered:i||o,rawContent:e.content??e.item_list,timestamp:normalizeTimestamp$1(e.timestamp??e.create_time),raw:e}}}const ChannelPlatforms=["telegram","wechat","lark"],ChannelPlatformSchema=zod.z.enum(ChannelPlatforms),ChannelConnectionStateSchema=zod.z.enum(["connecting","connected","disconnected","error"]),ChannelMessageTypeSchema=zod.z.enum(["text","image","file","voice"]),ChannelCredentialsSchema=zod.z.record(zod.z.string(),zod.z.unknown()),ChannelConfigSchema=zod.z.object({id:zod.z.string(),platform:ChannelPlatformSchema,name:zod.z.string().optional(),credentials:ChannelCredentialsSchema,enabled:zod.z.boolean(),connectionState:ChannelConnectionStateSchema,lastConnectedAt:zod.z.string().optional(),lastDisconnectedAt:zod.z.string().optional(),lastError:zod.z.string().optional(),createdAt:zod.z.string(),updatedAt:zod.z.string()}),AddChannelConfigSchema=zod.z.object({platform:ChannelPlatformSchema,name:zod.z.string().optional(),credentials:ChannelCredentialsSchema,enabled:zod.z.boolean().optional()}),ChannelBindingSchema=zod.z.object({id:zod.z.string(),channelId:zod.z.string(),chatId:zod.z.string(),taskId:zod.z.string(),chatName:zod.z.string().optional(),createdAt:zod.z.string(),updatedAt:zod.z.string()});zod.z.object({id:zod.z.string(),channelId:zod.z.string(),platform:ChannelPlatformSchema,chatId:zod.z.string(),chatType:zod.z.string().optional(),senderId:zod.z.string().optional(),senderType:zod.z.string().optional(),senderName:zod.z.string().optional(),type:ChannelMessageTypeSchema,text:zod.z.string().optional(),fileKey:zod.z.string().optional(),fileName:zod.z.string().optional(),imageKey:zod.z.string().optional(),attachmentPaths:zod.z.array(zod.z.string()).optional(),mentionedBot:zod.z.boolean().optional(),replyToBot:zod.z.boolean().optional(),triggered:zod.z.boolean().optional(),rawContent:zod.z.unknown().optional(),timestamp:zod.z.string(),raw:zod.z.unknown().optional()});const ChannelContactSchema=zod.z.object({id:zod.z.string(),name:zod.z.string(),avatar:zod.z.string().optional(),description:zod.z.string().optional(),chatStatus:zod.z.string().optional(),external:zod.z.boolean().optional()}),ChannelOutgoingAttachmentKindSchema=zod.z.enum(["auto","image","file","audio","video"]),ChannelOutgoingAttachmentSchema=zod.z.object({filePath:zod.z.string(),fileName:zod.z.string().optional(),mimeType:zod.z.string().optional(),kind:ChannelOutgoingAttachmentKindSchema.optional()});zod.z.object({content:zod.z.string().optional(),attachments:zod.z.array(ChannelOutgoingAttachmentSchema).optional()});const ChannelStoreSchema=zod.z.object({version:zod.z.literal(1),channels:zod.z.array(ChannelConfigSchema),bindings:zod.z.array(ChannelBindingSchema)}),GITLAB_WEBHOOK_TRIGGER_DEDUPE_TTL_MS=18e5,processedGitLabWebhookTriggerEvents=new Map;function asRecord(e){return!e||"object"!=typeof e||Array.isArray(e)?null:e}function getString(e){return"string"==typeof e&&e.trim().length>0?e.trim():void 0}function getNumber(e){return"number"==typeof e&&Number.isFinite(e)?e:void 0}function getBoolean(e){if("boolean"==typeof e)return e;if("string"!=typeof e)return;const t=e.trim().toLowerCase();return"true"===t||"1"===t||"yes"===t||"false"!==t&&"0"!==t&&"no"!==t&&void 0}function splitProjectPath(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}}function parseProject(e){const t=asRecord(e.project);return t?{id:getNumber(t.id),path:getString(t.path),path_with_namespace:getString(t.path_with_namespace),default_branch:getString(t.default_branch),web_url:getString(t.web_url)}:null}function getGitLabWebhookProjectKey(e){const t=parseProject(e);return t?.id?String(t.id):t?.path_with_namespace??null}function getGitLabWebhookProjectLocator(e){const t=parseProject(e);return t?.path_with_namespace?t.id?{projectId:t.id}:{projectPath:t.path_with_namespace}:null}function parseIssue(e){const t=asRecord(e.object_attributes);return t?{iid:getNumber(t.iid),title:getString(t.title),url:getString(t.url),action:getString(t.action),state:getString(t.state)}:null}function parseMergeRequest(e){const t=asRecord(e.object_attributes);if(!t)return null;const n=asRecord(t.last_commit),a=getLabelKeys(t.labels);return{iid:getNumber(t.iid),title:getString(t.title),description:getString(t.description),url:getString(t.url),action:getString(t.action),state:getString(t.state),source_branch:getString(t.source_branch),target_branch:getString(t.target_branch),oldrev:getString(t.oldrev)??getString(e.oldrev),last_commit_sha:getString(n?.id)??getString(n?.sha),labels:a.length>0?a:getLabelKeys(t.label_names)}}function parseNote(e){const t=asRecord(e.object_attributes);return t?{id:getNumber(t.id),note:getString(t.note),noteable_type:getString(t.noteable_type),url:getString(t.url),action:getString(t.action),system:getBoolean(t.system),isDiffNote:Boolean(t.position||t.diff_refs||t.line_code)}:null}function parsePipeline(e){const t=asRecord(e.object_attributes);return t?{id:getNumber(t.id),iid:getNumber(t.iid),status:getString(t.status),source:getString(t.source),ref:getString(t.ref),sha:getString(t.sha),url:getString(t.url)}:null}function resolveIssueUrl(e,t){return t.url?t.url:e.web_url&&"number"==typeof t.iid?`${e.web_url}/-/issues/${t.iid}`:void 0}function resolveMergeRequestUrl(e,t){return t.url?t.url:e.web_url&&"number"==typeof t.iid?`${e.web_url}/-/merge_requests/${t.iid}`:void 0}function resolvePipelineUrl(e,t){return t.url?t.url:e.web_url&&"number"==typeof t.id?`${e.web_url}/-/pipelines/${t.id}`:void 0}function parseEventType(e){return getString(e.event_type)||getString(e.object_kind)||"unknown"}function normalizeTriggerError(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}}function getTriggerDedupeKey(e,t){return`gitlab-webhook-trigger:${e}:${t}:pipeline`}function pruneProcessedGitLabWebhookTriggerEvents(e){for(const[t,n]of processedGitLabWebhookTriggerEvents.entries())n<=e&&processedGitLabWebhookTriggerEvents.delete(t)}function hasProcessedGitLabWebhookTriggerEvent(e,t,n){pruneProcessedGitLabWebhookTriggerEvents(n);const a=getTriggerDedupeKey(e,t),s=processedGitLabWebhookTriggerEvents.get(a);return"number"==typeof s&&s>n}function markGitLabWebhookTriggerEventProcessed(e,t,n){const a=getTriggerDedupeKey(e,t);processedGitLabWebhookTriggerEvents.set(a,n+18e5)}function hasAgentrixCommand(e){return!!e&&/(?:^|[^A-Za-z0-9._-])(?:@agentrix|\/agentrix)(?=$|[^A-Za-z0-9._-])/i.test(e)}function normalizeNoteableType(e){const t=e?.trim().toLowerCase();return"issue"===t?"issue":"mergerequest"===t||"merge_request"===t?"merge_request":void 0}function getChanges(e){return asRecord(e.changes)??{}}function readChangePair(e,t){if(!(t in e))return null;const n=e[t];if(Array.isArray(n)&&n.length>=2)return{previous:n[0],current:n[1]};const a=asRecord(n);return a?{previous:a.previous,current:a.current}:null}function readFirstChangePair(e,t){for(const n of t){const t=readChangePair(e,n);if(t)return t}return null}function asArray(e){return Array.isArray(e)?e:[]}function unique(e){return Array.from(new Set(e))}function getLabelKey(e){if("string"==typeof e)return getString(e);const t=asRecord(e);return getString(t?.title)??getString(t?.name)}function getLabelKeys(e){return unique(asArray(e).map(getLabelKey).filter(e=>Boolean(e)))}function getUserKey(e){const t=asRecord(e);return getString(t?.username)??getString(t?.name)??("number"==typeof t?.id?String(t.id):void 0)}function getCommitSha(e){if("string"==typeof e)return getString(e);const t=asRecord(e);return getString(t?.id)??getString(t?.sha)}function diffByKey(e,t,n){const a=unique(asArray(e).map(n).filter(e=>Boolean(e))),s=unique(asArray(t).map(n).filter(e=>Boolean(e)));return{added:s.filter(e=>!a.includes(e)),removed:a.filter(e=>!s.includes(e)),current:s,previous:a}}function isEmptyValue(e){return null==e||""===e}function booleanPair(e){if(!e)return null;const t=getBoolean(e.previous),n=getBoolean(e.current);return void 0===t||void 0===n||t===n?null:{previous:t,current:n}}function hasAnyChange(e,t){return t.some(t=>t in e)}function readHeadShaChange(e){const t=readFirstChangePair(e,["last_commit","head_sha","source_branch_sha","sha"]);if(!t)return null;const n=getCommitSha(t.previous),a=getCommitSha(t.current);return n||a?n===a?null:{previous:n,current:a}:null}function stableJsonStringify(e){if(Array.isArray(e))return`[${e.map(stableJsonStringify).join(",")}]`;const t=asRecord(e);return t?`{${Object.keys(t).sort().map(e=>`${JSON.stringify(e)}:${stableJsonStringify(t[e])}`).join(",")}}`:JSON.stringify(e)}function getGitLabWebhookDeliveryKey(e,t){const n=getString(t);return n||`payload-${node_crypto.createHash("sha256").update(stableJsonStringify(e)).digest("hex")}`}function encodeEventIdPart(e){return encodeURIComponent(String(e??"unknown"))}function buildNormalizedEventId(e,t){return[e,...t].map(encodeEventIdPart).join(":")}function setVariable(e,t,n){null!=n&&(e[t]=String(n))}function setJsonVariable(e,t,n){e[t]=JSON.stringify(n)}function setLabelListVariables(e,t){0!==t.length&&(setVariable(e,"AGENTRIX_LABELS",t.join(",")),setJsonVariable(e,"AGENTRIX_LABELS_JSON",t))}function buildBaseVariables(e){const{owner:t,name:n}=splitProjectPath(e.project.path_with_namespace??""),a={AGENTRIX_EVENT_NAME:e.eventName,AGENTRIX_EVENT_ACTION:e.eventAction,AGENTRIX_GIT_SERVER_ID:e.gitServerId,AGENTRIX_PROVIDER:"gitlab",AGENTRIX_REPOSITORY_OWNER:t,AGENTRIX_REPOSITORY_NAME:n,AGENTRIX_TRIGGER_SOURCE:"agentrix_daemon_webhook",AGENTRIX_COMPAT_KIND:e.compatKind,AGENTRIX_PROVIDER_EVENT_NAME:e.providerEventName,AGENTRIX_GITLAB_EVENT_NAME:e.providerEventName,AGENTRIX_GITLAB_CHANGED_KEYS:e.changedKeys.join(",")};return setVariable(a,"AGENTRIX_PROVIDER_EVENT_ACTION",e.providerEventAction),setVariable(a,"AGENTRIX_GITLAB_EVENT_ACTION",e.providerEventAction),setVariable(a,"AGENTRIX_SUBJECT_KIND",e.subjectKind),a}function addIssueVariables(e,t,n){setVariable(e,"AGENTRIX_ISSUE_NUMBER",n.iid),setVariable(e,"AGENTRIX_ISSUE_TITLE",n.title),setVariable(e,"AGENTRIX_ISSUE_URL",resolveIssueUrl(t,n))}function addMergeRequestVariables(e,t,n){setVariable(e,"AGENTRIX_PR_NUMBER",n.iid),setVariable(e,"AGENTRIX_HEAD_REF",n.source_branch),setVariable(e,"AGENTRIX_BASE_REF",n.target_branch),setVariable(e,"AGENTRIX_MR_TITLE",n.title),setVariable(e,"AGENTRIX_PR_BODY",n.description),setVariable(e,"AGENTRIX_MR_DESCRIPTION",n.description),setVariable(e,"AGENTRIX_MR_URL",resolveMergeRequestUrl(t,n)),setLabelListVariables(e,n.labels)}function buildOperationPayload(e,t,n,a){const s={ref:t,variables:n};return e.id?s.projectId=e.id:e.path_with_namespace&&(s.projectPath=e.path_with_namespace),a.triggerToken&&(s.triggerToken=a.triggerToken),void 0!==a.createTriggerIfMissing&&(s.createTriggerIfMissing=a.createTriggerIfMissing),s}function createDraft(e){const t={...buildBaseVariables(e),...e.variables??{}};return{project:e.project,ref:e.ref,normalizedEventIdParts:e.normalizedEventIdParts,eventName:e.eventName,eventAction:e.eventAction,providerEventName:e.providerEventName,providerEventAction:e.providerEventAction,compatKind:e.compatKind,subjectKind:e.subjectKind,changedKeys:e.changedKeys,variables:t}}function finalizeDrafts(e,t,n){return e.map((a,s)=>{const i=buildNormalizedEventId(n,a.normalizedEventIdParts),o={...a.variables,AGENTRIX_NORMALIZED_EVENT_ID:i,AGENTRIX_NORMALIZED_EVENT_INDEX:String(s),AGENTRIX_NORMALIZED_EVENT_COUNT:String(e.length)};return{normalizedEventId:i,eventName:a.eventName,eventAction:a.eventAction,providerEventName:a.providerEventName,providerEventAction:a.providerEventAction,compatKind:a.compatKind,operationPayload:buildOperationPayload(a.project,a.ref,o,t),action:a.eventAction}})}function buildIssueDrafts(e,t,n){const a=parseProject(t),s=parseIssue(t);if(!a?.path_with_namespace||!s?.iid)return[];const i=n.ref||a.default_branch;if(!i)throw{status:400,message:"Pipeline ref is required; pass ref or ensure GitLab payload includes project.default_branch"};const o=s.action,r=Object.keys(getChanges(t)),c={gitServerId:e,project:a,ref:i,providerEventName:"issue",providerEventAction:o,subjectKind:"issue",changedKeys:r},l=()=>{const e={};return addIssueVariables(e,a,s),e};if("open"===o||"opened"===o||!o&&"opened"===s.state)return[createDraft({...c,eventName:"issues",eventAction:"opened",compatKind:"exact",normalizedEventIdParts:["issues","opened",`issue-${s.iid}`],variables:l()})];if("close"===o||"closed"===o||!o&&"closed"===s.state)return[createDraft({...c,eventName:"issues",eventAction:"closed",compatKind:"exact",normalizedEventIdParts:["issues","closed",`issue-${s.iid}`],variables:l()})];if("reopen"===o||"reopened"===o)return[createDraft({...c,eventName:"issues",eventAction:"reopened",compatKind:"exact",normalizedEventIdParts:["issues","reopened",`issue-${s.iid}`],variables:l()})];const d=getChanges(t),p=[],u=readChangePair(d,"labels");if(u){const e=diffByKey(u.previous,u.current,getLabelKey);for(const t of e.added){const n=l();n.AGENTRIX_LABEL_NAME=t,setLabelListVariables(n,e.current),setJsonVariable(n,"AGENTRIX_LABEL_CHANGES_JSON",e),p.push(createDraft({...c,eventName:"issues",eventAction:"labeled",compatKind:"exact",normalizedEventIdParts:["issues","labeled",`issue-${s.iid}`,`label-${t}`],variables:n}))}for(const t of e.removed){const n=l();n.AGENTRIX_LABEL_NAME=t,setLabelListVariables(n,e.current),setJsonVariable(n,"AGENTRIX_LABEL_CHANGES_JSON",e),p.push(createDraft({...c,eventName:"issues",eventAction:"unlabeled",compatKind:"exact",normalizedEventIdParts:["issues","unlabeled",`issue-${s.iid}`,`label-${t}`],variables:n}))}}const m=readChangePair(d,"assignees");if(m){const e=diffByKey(m.previous,m.current,getUserKey);for(const t of e.added){const n=l();n.AGENTRIX_ASSIGNEE_LOGIN=t,setJsonVariable(n,"AGENTRIX_ASSIGNEE_CHANGES_JSON",e),p.push(createDraft({...c,eventName:"issues",eventAction:"assigned",compatKind:"exact",normalizedEventIdParts:["issues","assigned",`issue-${s.iid}`,`assignee-${t}`],variables:n}))}for(const t of e.removed){const n=l();n.AGENTRIX_ASSIGNEE_LOGIN=t,setJsonVariable(n,"AGENTRIX_ASSIGNEE_CHANGES_JSON",e),p.push(createDraft({...c,eventName:"issues",eventAction:"unassigned",compatKind:"exact",normalizedEventIdParts:["issues","unassigned",`issue-${s.iid}`,`assignee-${t}`],variables:n}))}}const h=readFirstChangePair(d,["milestone","milestone_id"]);if(h&&isEmptyValue(h.previous)!==isEmptyValue(h.current)){const e=isEmptyValue(h.previous)?"milestoned":"demilestoned",t=l();p.push(createDraft({...c,eventName:"issues",eventAction:e,compatKind:"exact",normalizedEventIdParts:["issues",e,`issue-${s.iid}`],variables:t}))}const g=booleanPair(readChangePair(d,"discussion_locked"));if(g){const e=g.current?"locked":"unlocked",t=l();p.push(createDraft({...c,eventName:"issues",eventAction:e,compatKind:"exact",normalizedEventIdParts:["issues",e,`issue-${s.iid}`],variables:t}))}return hasAnyChange(d,["title","description"])&&p.push(createDraft({...c,eventName:"issues",eventAction:"edited",compatKind:"exact",normalizedEventIdParts:["issues","edited",`issue-${s.iid}`],variables:l()})),p}function buildMergeRequestDrafts(e,t,n){const a=parseProject(t),s=parseMergeRequest(t);if(!a?.path_with_namespace||!s?.iid)return[];const i=n.ref||s.target_branch||a.default_branch||s.source_branch;if(!i)throw{status:400,message:"Pipeline ref is required; pass ref or ensure GitLab payload includes target_branch or project.default_branch"};const o=s.action,r=Object.keys(getChanges(t)),c={gitServerId:e,project:a,ref:i,providerEventName:"merge_request",providerEventAction:o,subjectKind:"pull_request",changedKeys:r},l=()=>{const e={};return addMergeRequestVariables(e,a,s),e};if("open"===o||"opened"===o)return[createDraft({...c,eventName:"pull_request",eventAction:"opened",compatKind:"exact",normalizedEventIdParts:["pull_request","opened",`mr-${s.iid}`],variables:l()})];if("reopen"===o||"reopened"===o)return[createDraft({...c,eventName:"pull_request",eventAction:"reopened",compatKind:"exact",normalizedEventIdParts:["pull_request","reopened",`mr-${s.iid}`],variables:l()})];if("merge"===o||"merged"===o||"merged"===s.state){const e=l();return e.AGENTRIX_PULL_REQUEST_MERGED="true",[createDraft({...c,eventName:"pull_request",eventAction:"closed",compatKind:"derived",normalizedEventIdParts:["pull_request","closed",`mr-${s.iid}`,"merged"],variables:e})]}if("close"===o||"closed"===o){const e=l();return e.AGENTRIX_PULL_REQUEST_MERGED="false",[createDraft({...c,eventName:"pull_request",eventAction:"closed",compatKind:"exact",normalizedEventIdParts:["pull_request","closed",`mr-${s.iid}`],variables:e})]}if("approved"===o||"approval"===o){const e=l();return e.AGENTRIX_REVIEW_STATE="approved",[createDraft({...c,eventName:"pull_request_review",eventAction:"submitted",compatKind:"derived",normalizedEventIdParts:["pull_request_review","submitted",`mr-${s.iid}`,"approved"],variables:e})]}if("unapproved"===o||"unapproval"===o){const e=l();return e.AGENTRIX_REVIEW_STATE="approved_removed",[createDraft({...c,eventName:"pull_request_review",eventAction:"dismissed",compatKind:"derived",normalizedEventIdParts:["pull_request_review","dismissed",`mr-${s.iid}`,"approved_removed"],variables:e})]}const d=getChanges(t),p=[],u=readHeadShaChange(d),m=s.oldrev??u?.current??s.last_commit_sha??"unknown";if(s.oldrev||u){const e=l();setVariable(e,"AGENTRIX_GITLAB_OLDREV",s.oldrev??u?.previous),setVariable(e,"AGENTRIX_HEAD_SHA",u?.current??s.last_commit_sha),p.push(createDraft({...c,eventName:"pull_request",eventAction:"synchronize",compatKind:"derived",normalizedEventIdParts:["pull_request","synchronize",`mr-${s.iid}`,m],variables:e}))}const h=readChangePair(d,"labels");if(h){const e=diffByKey(h.previous,h.current,getLabelKey);for(const t of e.added){const n=l();n.AGENTRIX_LABEL_NAME=t,setLabelListVariables(n,e.current),setJsonVariable(n,"AGENTRIX_LABEL_CHANGES_JSON",e),p.push(createDraft({...c,eventName:"pull_request",eventAction:"labeled",compatKind:"exact",normalizedEventIdParts:["pull_request","labeled",`mr-${s.iid}`,`label-${t}`],variables:n}))}for(const t of e.removed){const n=l();n.AGENTRIX_LABEL_NAME=t,setLabelListVariables(n,e.current),setJsonVariable(n,"AGENTRIX_LABEL_CHANGES_JSON",e),p.push(createDraft({...c,eventName:"pull_request",eventAction:"unlabeled",compatKind:"exact",normalizedEventIdParts:["pull_request","unlabeled",`mr-${s.iid}`,`label-${t}`],variables:n}))}}const g=readChangePair(d,"assignees");if(g){const e=diffByKey(g.previous,g.current,getUserKey);for(const t of e.added){const n=l();n.AGENTRIX_ASSIGNEE_LOGIN=t,setJsonVariable(n,"AGENTRIX_ASSIGNEE_CHANGES_JSON",e),p.push(createDraft({...c,eventName:"pull_request",eventAction:"assigned",compatKind:"exact",normalizedEventIdParts:["pull_request","assigned",`mr-${s.iid}`,`assignee-${t}`],variables:n}))}for(const t of e.removed){const n=l();n.AGENTRIX_ASSIGNEE_LOGIN=t,setJsonVariable(n,"AGENTRIX_ASSIGNEE_CHANGES_JSON",e),p.push(createDraft({...c,eventName:"pull_request",eventAction:"unassigned",compatKind:"exact",normalizedEventIdParts:["pull_request","unassigned",`mr-${s.iid}`,`assignee-${t}`],variables:n}))}}const f=readChangePair(d,"reviewers");if(f){const e=diffByKey(f.previous,f.current,getUserKey);for(const t of e.added){const n=l();n.AGENTRIX_REQUESTED_REVIEWER_LOGIN=t,setJsonVariable(n,"AGENTRIX_REVIEWER_CHANGES_JSON",e),p.push(createDraft({...c,eventName:"pull_request",eventAction:"review_requested",compatKind:"exact",normalizedEventIdParts:["pull_request","review_requested",`mr-${s.iid}`,`reviewer-${t}`],variables:n}))}for(const t of e.removed){const n=l();n.AGENTRIX_REQUESTED_REVIEWER_LOGIN=t,setJsonVariable(n,"AGENTRIX_REVIEWER_CHANGES_JSON",e),p.push(createDraft({...c,eventName:"pull_request",eventAction:"review_request_removed",compatKind:"exact",normalizedEventIdParts:["pull_request","review_request_removed",`mr-${s.iid}`,`reviewer-${t}`],variables:n}))}}const y=booleanPair(readFirstChangePair(d,["draft","work_in_progress"]));if(y){const e=y.current?"converted_to_draft":"ready_for_review";p.push(createDraft({...c,eventName:"pull_request",eventAction:e,compatKind:"derived",normalizedEventIdParts:["pull_request",e,`mr-${s.iid}`],variables:l()}))}return hasAnyChange(d,["title","description","target_branch"])&&p.push(createDraft({...c,eventName:"pull_request",eventAction:"edited",compatKind:"exact",normalizedEventIdParts:["pull_request","edited",`mr-${s.iid}`],variables:l()})),p}function buildNoteDrafts(e,t,n){const a=parseProject(t),s=parseNote(t);if(!a?.path_with_namespace||!s||!0===s.system)return[];const i=normalizeNoteableType(s.noteable_type);if(!i)return[];const o=asRecord("issue"===i?t.issue:t.merge_request),r=getNumber(o?.iid);if(!r)return[];const c=(()=>{switch(s.action){case void 0:case"create":case"created":return"created";case"update":case"updated":return"edited";case"delete":case"deleted":return"deleted";default:return null}})();if(!c)return[];const l="merge_request"===i?getString(o?.source_branch):void 0,d="merge_request"===i?getString(o?.target_branch):void 0,p=n.ref||d||a.default_branch||l;if(!p)throw{status:400,message:"Pipeline ref is required; pass ref or ensure GitLab payload includes a usable ref"};const u="merge_request"===i&&s.isDiffNote?"pull_request_review_comment":"issue_comment",m="merge_request"===i?"pull_request":"issue",h=Object.keys(getChanges(t)),g={AGENTRIX_COMMENT_COMMAND:hasAgentrixCommand(s.note)?"true":"false",AGENTRIX_GITLAB_NOTEABLE_TYPE:s.noteable_type??i};return setVariable(g,"AGENTRIX_COMMENT_BODY",s.note),setVariable(g,"AGENTRIX_COMMENT_ID",s.id),setVariable(g,"AGENTRIX_COMMENT_URL",s.url),"issue"===i?setVariable(g,"AGENTRIX_ISSUE_NUMBER",r):(setVariable(g,"AGENTRIX_PR_NUMBER",r),setVariable(g,"AGENTRIX_HEAD_REF",l),setVariable(g,"AGENTRIX_BASE_REF",d)),[createDraft({gitServerId:e,project:a,ref:p,eventName:u,eventAction:c,providerEventName:"note",providerEventAction:s.action,compatKind:"issue"===i?"exact":"derived",subjectKind:m,changedKeys:h,normalizedEventIdParts:[u,c,`${m}-${r}`,`comment-${s.id??"unknown"}`],variables:g})]}function getPipelineMergeRequestIid(e){const t=asRecord(e.merge_request);return getNumber(t?.iid)}function mapPipelineStatus(e){switch(e){case"created":case"pending":return{eventAction:"requested",workflowStatus:"pending"};case"running":return{eventAction:"in_progress",workflowStatus:e};case"success":return{eventAction:"completed",workflowStatus:"completed",conclusion:"success"};case"failed":return{eventAction:"completed",workflowStatus:"completed",conclusion:"failure"};case"canceled":case"cancelled":return{eventAction:"completed",workflowStatus:"completed",conclusion:"cancelled"};case"skipped":return{eventAction:"completed",workflowStatus:"completed",conclusion:"skipped"};default:return null}}function buildPipelineDrafts(e,t,n){const a=parseProject(t),s=parsePipeline(t);if(!a?.path_with_namespace||!s?.status)return[];const i=mapPipelineStatus(s.status);if(!i)return[];const o=n.ref||s.ref||a.default_branch;if(!o)throw{status:400,message:"Pipeline ref is required; pass ref or ensure GitLab payload includes object_attributes.ref or project.default_branch"};const r={AGENTRIX_WORKFLOW_RUN_STATUS:i.workflowStatus,AGENTRIX_PIPELINE_STATUS:s.status,AGENTRIX_REF:o};return setVariable(r,"AGENTRIX_WORKFLOW_RUN_CONCLUSION",i.conclusion),setVariable(r,"AGENTRIX_PIPELINE_SOURCE",s.source),setVariable(r,"AGENTRIX_PIPELINE_ID",s.id),setVariable(r,"AGENTRIX_PIPELINE_IID",s.iid),setVariable(r,"AGENTRIX_SHA",s.sha),setVariable(r,"AGENTRIX_PIPELINE_URL",resolvePipelineUrl(a,s)),setVariable(r,"AGENTRIX_PR_NUMBER",getPipelineMergeRequestIid(t)),[createDraft({gitServerId:e,project:a,ref:o,eventName:"workflow_run",eventAction:i.eventAction,providerEventName:"pipeline",providerEventAction:s.status,compatKind:"derived",subjectKind:"workflow_run",changedKeys:[],normalizedEventIdParts:["workflow_run",i.eventAction,`pipeline-${s.id??s.iid??"unknown"}`],variables:r})]}function buildGitLabWebhookPipelineTriggerPayloads(e,t,n){const a=getGitLabWebhookDeliveryKey(t,n.deliveryId),s=parseEventType(t);return finalizeDrafts((()=>{switch(s){case"issue":return buildIssueDrafts(e,t,n);case"note":return buildNoteDrafts(e,t,n);case"merge_request":return buildMergeRequestDrafts(e,t,n);case"pipeline":return buildPipelineDrafts(e,t,n);default:return[]}})(),n,a)}function getIgnoredReason(e){const t=parseEventType(e);if("note"===t){const t=parseNote(e);return!0===t?.system?"system_note":t?"unsupported_provider_specific_event":"missing_required_payload"}if("pipeline"===t)return"unsupported_provider_specific_event";if("issue"===t||"merge_request"===t){const n=parseProject(e),a="issue"===t?parseIssue(e):parseMergeRequest(e);return n?.path_with_namespace&&a?.iid?"unsupported_provider_specific_event":"missing_required_payload"}return"unsupported_provider_specific_event"}function getGitLabWebhookPipelineProjectKey(e){const t=getGitLabWebhookProjectKey(e);if(!t)return null;try{return buildGitLabWebhookPipelineTriggerPayloads("__probe__",e,{ref:"__probe__"}).length>0?t:null}catch{return t}}async function triggerPipelineFromGitLabWebhook({gitServerId:e,payload:t,config:n,pat:a}){const s=parseEventType(t),i=buildGitLabWebhookPipelineTriggerPayloads(e,t,n);if(0===i.length)return{status:"ignored",eventType:s,reason:getIgnoredReason(t),triggeredCount:0,failedCount:0,events:[]};if(!n.apiUrl)throw{status:400,message:"GitLab API URL is required"};const o=new GitLabExecutor(n.apiUrl,a,{gitServerId:e}),r=[];for(const t of i){const n=Date.now();if(hasProcessedGitLabWebhookTriggerEvent(e,t.normalizedEventId,n))r.push({status:"ignored",normalizedEventId:t.normalizedEventId,eventName:t.eventName,eventAction:t.eventAction,action:t.action,reason:"duplicate_delivery_event"});else try{const n=await o.executeOperation("triggerPipeline",t.operationPayload);markGitLabWebhookTriggerEventProcessed(e,t.normalizedEventId,Date.now()),r.push({status:"triggered",normalizedEventId:t.normalizedEventId,eventName:t.eventName,eventAction:t.eventAction,action:t.action,pipeline:n})}catch(e){const n=normalizeTriggerError(e);r.push({status:"failed",normalizedEventId:t.normalizedEventId,eventName:t.eventName,eventAction:t.eventAction,action:t.action,reason:"pipeline_trigger_failed",errorMessage:n.message,errorDetail:n.detail,upstreamStatus:n.upstreamStatus})}}const c=r.filter(e=>"failed"===e.status),l=r.filter(e=>"triggered"===e.status),d=r.filter(e=>"ignored"===e.status),p=r[0],u=c[0];return u?{status:"failed",eventType:s,eventName:p?.eventName,eventAction:p?.eventAction,action:p?.action,reason:u.reason,errorMessage:u.errorMessage,errorDetail:u.errorDetail,upstreamStatus:u.upstreamStatus,triggeredCount:l.length,failedCount:c.length,events:r}:0===l.length&&d.length>0?{status:"ignored",eventType:s,eventName:p?.eventName,eventAction:p?.eventAction,action:p?.action,reason:p?.reason,triggeredCount:0,failedCount:0,events:r}:{status:"triggered",eventType:s,eventName:p?.eventName,eventAction:p?.eventAction,action:p?.action,pipeline:1===r.length?p?.pipeline:void 0,triggeredCount:l.length,failedCount:0,events:r}}function getSigningSecret(e){return e.secret||e.token}function encodeBase64Url(e){return Buffer.from(e,"utf8").toString("base64url")}function decodeBase64Url(e){return Buffer.from(e,"base64url").toString("utf8")}function signPayload(e,t){return node_crypto.createHmac("sha256",t).update(e).digest("base64url")}function safeEqualString(e,t){const n=Buffer.from(e),a=Buffer.from(t);return n.length===a.length&&node_crypto.timingSafeEqual(n,a)}function signAgentrixEventMcpToken(e,t){const n={taskId:t.taskId,userId:t.userId,machineId:t.machineId??e.machineId,nonce:node_crypto.randomBytes(16).toString("base64url"),taskPreviewEnabled:t.taskPreviewEnabled,visionPlanEnabled:t.visionPlanEnabled},a=encodeBase64Url(JSON.stringify(n));return`${a}.${signPayload(a,getSigningSecret(e))}`}function verifyAgentrixEventMcpToken(e,t){const[n,a,s]=t.split(".");if(!n||!a||void 0!==s)throw new Error("Invalid Agentrix event MCP token format");if(!safeEqualString(a,signPayload(n,getSigningSecret(e))))throw new Error("Invalid Agentrix event MCP token signature");let i;try{i=JSON.parse(decodeBase64Url(n))}catch{throw new Error("Invalid Agentrix event MCP token payload")}if(!(i.taskId&&i.userId&&i.machineId&&i.nonce))throw new Error("Incomplete Agentrix event MCP token payload");if(i.machineId!==e.machineId)throw new Error("Agentrix event MCP token machine mismatch");return i}const SendVisionArtifactRequestSchema=zod.z.object({repoRoot:zod.z.string().min(1).describe("Absolute repository root containing .agentrix/issues"),issueId:zod.z.string().min(1).max(160).regex(/^[A-Za-z0-9._-]+$/).describe("Agentrix issue directory id, for example 478-vision-plan-agentrix-platform-bridge")});async function normalizeSendVisionArtifactRequest(e,t){return{issueId:SendVisionArtifactRequestSchema.parse(e).issueId}}const AGENTRIX_EVENT_MCP_SERVER_NAME="agentrix_event_broker",AGENTRIX_EVENT_MCP_ROUTE="/mcp/agentrix-event-broker",AGENTRIX_EVENT_MCP_TOKEN_ENV="AGENTRIX_EVENT_MCP_TOKEN",AGENTRIX_CHANGE_TITLE_EVENT_TOOL="change_title",AGENTRIX_PUBLISH_TASK_PREVIEW_URL_EVENT_TOOL="publish_task_preview_url",AGENTRIX_SEND_VISION_ARTIFACT_EVENT_TOOL="send_vision_artifact";function isAgentrixInternalMcpServerName(e){return"agentrix"===e||"agentrix_event_broker"===e}function extractBearerToken(e){const t=e.headers.authorization;if(!t)throw new Error("Missing Agentrix event MCP bearer token");const n=/^Bearer\s+(.+)$/i.exec(t);if(!n?.[1])throw new Error("Invalid Agentrix event MCP authorization header");return n[1]}async function sendChangeTitleMachineEvent(e,t,n){const a=e?.();if(!a?.connected)throw new Error("Agentrix daemon machine socket is not connected");const s={eventId:shared.createEventId(),taskId:t.taskId,title:n},i=await a.sendWithAck("change-task-title",s);if("success"!==i.status)throw new Error(i.message||"Failed to change task title")}async function sendTaskPreviewUrlUpdate(e,t,n){const a=await fetch(`${machine.machine.serverUrl}/v1/tasks/${encodeURIComponent(t.taskId)}/preview-url`,{method:"PUT",headers:{Authorization:`Bearer ${e.token}`,"Content-Type":"application/json","X-Agentrix-Task":t.taskId},body:JSON.stringify({previewUrl:n})});if(!a.ok){const e=await a.text().catch(()=>"");throw new Error(`Failed to publish task preview URL (${a.status}): ${e||a.statusText}`)}}function createDefaultAgentrixEventBrokerDispatcher(e,t){return{changeTitle:(e,n)=>sendChangeTitleMachineEvent(t,e,n),publishTaskPreviewUrl:(t,n)=>sendTaskPreviewUrlUpdate(e,t,n),sendVisionArtifact:async(e,n)=>{const a=await normalizeSendVisionArtifactRequest(n,{taskId:e.taskId}),s=t?.();if(!s?.connected)throw new Error("Agentrix daemon machine socket is not connected");const i=await s.sendWithAck("vision-plan-card",{eventId:shared.createEventId(),taskId:e.taskId,issueId:a.issueId,repoRoot:n.repoRoot,createdAt:(new Date).toISOString()});if("success"!==i.status)throw new Error(i.message||"Failed to send Vision Plan card");return{issueId:a.issueId}}}}async function dispatchAgentrixChangeTitleEventTool(e,t,n){const a=n.trim();if(!a)throw new Error("Title must not be empty");return await e.changeTitle(t,a),`Agentrix title change event emitted for task ${t.taskId}: ${a}`}async function dispatchAgentrixPublishTaskPreviewUrlEventTool(e,t,n){const a=shared.UpdateTaskPreviewUrlRequestSchema.parse({previewUrl:n});return await e.publishTaskPreviewUrl(t,a.previewUrl),`Agentrix preview URL updated for task ${t.taskId}: ${a.previewUrl}`}async function dispatchAgentrixSendVisionArtifactEventTool(e,t,n){const a=SendVisionArtifactRequestSchema.parse(n);return`Agentrix vision artifacts sent for issue ${(await e.sendVisionArtifact(t,a)).issueId}.`}function createAgentrixEventMcpServer(e){const t=new mcp_js.McpServer({name:"agentrix-event-broker",version:"1.0.0"});return t.registerTool("change_title",{title:"Change session title",description:["Emit an Agentrix event that changes the current session title.","Use this early in a task when the conversation has no user-provided title."].join(" "),inputSchema:{title:zod.z.string().min(1).max(200).describe("New title for the current Agentrix task")}},async({title:t})=>({content:[{type:"text",text:await dispatchAgentrixChangeTitleEventTool(e.dispatcher,e.context,t)}]})),!1!==e.context.taskPreviewEnabled&&t.registerTool("publish_task_preview_url",{title:"Publish task preview URL",description:["Record the frontend preview URL for the current Agentrix task.","Use this on a local machine when a browser-viewable frontend URL exists after starting or reusing the local environment.","The URL must be absolute http(s); localhost URLs are allowed."].join(" "),inputSchema:{previewUrl:zod.z.string().min(1).max(2048).describe("Absolute http(s) URL for the current task preview")}},async({previewUrl:t})=>({content:[{type:"text",text:await dispatchAgentrixPublishTaskPreviewUrlEventTool(e.dispatcher,e.context,t)}]})),!0===e.context.visionPlanEnabled&&t.registerTool("send_vision_artifact",{title:"Send Agentrix vision artifacts",description:["Send the issue vision artifacts (visual plan and test report) to the Agentrix platform so the user can review them.","Use this after generating or materially updating the visual plan, and again after generating the visual test report.","Pass only the repository root and issue id."].join(" "),inputSchema:{repoRoot:zod.z.string().min(1).describe("Absolute repository root containing .agentrix/issues"),issueId:zod.z.string().min(1).max(160).describe("Agentrix issue directory id")}},async({repoRoot:t,issueId:n})=>({content:[{type:"text",text:await dispatchAgentrixSendVisionArtifactEventTool(e.dispatcher,e.context,{repoRoot:t,issueId:n})}]})),t}async function handleMcpRequest(e,t,n){const a=extractBearerToken(e),s=createAgentrixEventMcpServer({context:verifyAgentrixEventMcpToken(n.credentials,a),dispatcher:n.dispatcher}),i=new streamableHttp_js.StreamableHTTPServerTransport({sessionIdGenerator:void 0});try{await s.connect(i),t.hijack(),await i.handleRequest(e.raw,t.raw,e.body)}catch(e){machine.logger.warn("[EVENT MCP] Failed to handle MCP request:",e),t.raw.headersSent||(t.raw.writeHead(500,{"Content-Type":"application/json"}),t.raw.end(JSON.stringify({jsonrpc:"2.0",error:{code:-32603,message:"Internal server error"},id:null})))}finally{await i.close().catch(()=>{}),await s.close().catch(()=>{})}}function registerAgentrixEventMcpBrokerRoutes(e,t){const n=t.getSocketClient??(()=>{}),a={credentials:t.credentials,getSocketClient:n,dispatcher:t.dispatcher??createDefaultAgentrixEventBrokerDispatcher(t.credentials,n)};e.post(AGENTRIX_EVENT_MCP_ROUTE,async(e,t)=>{try{await handleMcpRequest(e,t,a)}catch(e){const n=e instanceof Error?e.message:"Unauthorized Agentrix event MCP request";return machine.logger.warn(`[EVENT MCP] ${n}`),t.status(401).send({jsonrpc:"2.0",error:{code:-32001,message:n},id:null})}}),e.get(AGENTRIX_EVENT_MCP_ROUTE,async(e,t)=>t.status(405).send({jsonrpc:"2.0",error:{code:-32e3,message:"Method not allowed."},id:null})),e.delete(AGENTRIX_EVENT_MCP_ROUTE,async(e,t)=>t.status(405).send({jsonrpc:"2.0",error:{code:-32e3,message:"Method not allowed."},id:null}))}class MachineAesKeyUpdateError extends Error{constructor(e,t){super(e),this.statusCode=t,this.name="MachineAesKeyUpdateError"}}function decodeValidMachineAesKey(e){if(!e)return null;try{const t=shared.decodeBase64(e);return 32===t.length?t:null}catch{return null}}function hasValidMachineAesKey(e){return!!decodeValidMachineAesKey(e.machineAesKey)}async function storeRecoveredMachineAesKey(e,t,n=machine.machine){if(t.machineId!==e.machineId)throw new MachineAesKeyUpdateError("machineId does not match daemon credentials",409);if(!decodeValidMachineAesKey(t.machineAesKey))throw new MachineAesKeyUpdateError("machineAesKey must decode to a 32-byte key",400);const a=await n.readCredentials()??e;if(a.machineId!==e.machineId)throw new MachineAesKeyUpdateError("stored credentials machineId does not match daemon credentials",409);if(hasValidMachineAesKey(a))return e.machineAesKey=a.machineAesKey,{success:!0,updated:!1,hasMachineAesKey:!0};const s={...a,machineAesKey:t.machineAesKey};return await n.writeCredentials(s),e.machineAesKey=t.machineAesKey,{success:!0,updated:!0,hasMachineAesKey:!0}}const logger$7=machine.createModuleLogger("undefined"==typeof document?require("url").pathToFileURL(__filename).href:_documentCurrentScript&&"SCRIPT"===_documentCurrentScript.tagName.toUpperCase()&&_documentCurrentScript.src||new URL("index.cjs",document.baseURI).href),COMPUTER_USE_AGENT_ID="codex",COMPUTER_USE_TASK_STATE_AGENT_ID="agentrix-computer-use";function isTruthy(e){return["1","true","yes","on"].includes((e??"").trim().toLowerCase())}function resolveCodexHome(){const e=process.env.AGENTRIX_COMPUTER_USE_CODEX_HOME||process.env.AGENTRIX_CODEX_HOME_FOR_COMPUTER_USE;return e?.trim()?e.trim().replace(/^~(?=\/|$)/,os.homedir()):path.join(os.homedir(),".codex")}function resolveCodexPath(){const e=process.env.AGENTRIX_CODEX_PATH?.trim();if(e)return fs.existsSync(e)?{available:!0,path:e}:{available:!1,path:e};const t=node_child_process.spawnSync("win32"===process.platform?"where":"which",["codex"],{encoding:"utf8"}).stdout.split(/\r?\n/).map(e=>e.trim()).find(Boolean);return t?{available:!0,path:t}:{available:!1}}function resolveCommandPath(e,t){const n=t?.trim();if(n)return fs.existsSync(n)?{available:!0,path:n}:{available:!1,path:n};const a=node_child_process.spawnSync("win32"===process.platform?"where":"which",[e],{encoding:"utf8"}).stdout.split(/\r?\n/).map(e=>e.trim()).find(Boolean);if(a)return{available:!0,path:a};for(const e of[path.join(os.homedir(),".local","bin","cua-driver"),"/usr/local/bin/cua-driver","/Applications/CuaDriver.app/Contents/MacOS/cua-driver"])if(fs.existsSync(e))return{available:!0,path:e};return{available:!1}}function isDirectory(e){try{return fs.statSync(e).isDirectory()}catch{return!1}}function readTextIfExists(e){try{return fs.readFileSync(e,"utf8")}catch{return""}}function parseOptionalBoolean(e){return"boolean"==typeof e?e:void 0}function getCuaDriverPermissionStatus(e){if(!e||"darwin"!==process.platform)return{};const t=node_child_process.spawnSync(e,["doctor","--json"],{encoding:"utf8",timeout:1e4});try{const e=JSON.parse(t.stdout);return{accessibilityGranted:parseOptionalBoolean(e.ax_granted),screenRecordingGranted:parseOptionalBoolean(e.screen_recording_granted)}}catch(e){return 0!==t.status?{error:[t.stderr,t.stdout].map(e=>e?.trim()).filter(Boolean).join("\n")||"Failed to check Cua Driver permission status."}:{error:`Failed to parse Cua Driver permission status: ${e instanceof Error?e.message:String(e)}`}}}function normalizeHomePath(e){return e.replace(/^~(?=\/|$)/,os.homedir())}function getCodexSkillDirs(e){return[path.join(e,"skills","cua-driver"),path.join(os.homedir(),".agents","skills","cua-driver")]}function findPresentSkillDir(e){for(const t of getCodexSkillDirs(e))if(isDirectory(t)&&fs.existsSync(path.join(t,"SKILL.md")))return t;return null}function resolveCuaDriverSkillSource(){const e=process.env.AGENTRIX_CUA_DRIVER_SKILL_SOURCE?.trim();if(e){const t=normalizeHomePath(e);return fs.existsSync(path.join(t,"SKILL.md"))?t:null}const t=[path.join(os.homedir(),".agents","skills","cua-driver"),path.join(os.homedir(),".claude","skills","cua-driver"),path.join(os.homedir(),".openclaw","skills","cua-driver")].filter(e=>Boolean(e));for(const e of t){const t=path.resolve(normalizeHomePath(e));if(fs.existsSync(path.join(t,"SKILL.md")))return t}return null}function getEnablement(e,t){if(isTruthy(process.env.AGENTRIX_COMPUTER_USE_ENABLED))return"env";const n=e;return!1===n?.agentrixComputerUse?.enabled?null:!0===n?.agentrixComputerUse?.enabled?"settings":fs.existsSync(t)?"marker":null}function getComputerUseBridgeStatus(e=machine.machine.readSettings()){const t=resolveCodexHome(),n=path.join(machine.machine.agentrixHomeDir,"computer-use","enabled"),a=getEnablement(e,n),s=resolveCodexPath(),i=resolveCommandPath("cua-driver",process.env.AGENTRIX_CUA_DRIVER_PATH),o=path.join(t,"config.toml"),r=readTextIfExists(o),c=r.length>0,l=/\[mcp_servers\.(["']?cua-driver["']?|cua_driver)\]/.test(r)||/cua-driver/.test(r);path.join(t,"skills","cua-driver");const d=null!==findPresentSkillDir(t),p=resolveCuaDriverSkillSource()??void 0,u=getCuaDriverPermissionStatus(i.path),m=[];return s.available||m.push("Codex CLI is not available. Install Codex or set AGENTRIX_CODEX_PATH to the codex executable."),i.available||m.push("Cua Driver CLI is not available. Install Cua Driver or set AGENTRIX_CUA_DRIVER_PATH to the cua-driver executable."),u.error&&m.push(`Cua Driver permission status could not be checked: ${u.error}`),!1===u.accessibilityGranted&&m.push("Cua Driver Accessibility permission is not granted. Install Agentrix Computer Use to open the macOS permission prompt, then grant Accessibility access."),!1===u.screenRecordingGranted&&m.push("Cua Driver Screen Recording permission is not granted. Install Agentrix Computer Use to open the macOS permission prompt, then grant Screen Recording access."),c&&l||m.push(`Cua Driver MCP is not configured in ${o}. Run: cua-driver mcp-config --client codex`),d||m.push(`Cua Driver Codex skill is missing. Checked ${getCodexSkillDirs(t).join(" and ")}.`),{platform:process.platform,enabled:null!==a,enabledBy:a,codexHome:t,codexAvailable:s.available,codexPath:s.path,codexConfigPresent:c,cuaDriverAvailable:i.available,cuaDriverPath:i.path,cuaDriverAccessibilityGranted:u.accessibilityGranted,cuaDriverScreenRecordingGranted:u.screenRecordingGranted,cuaDriverMcpConfigured:l,cuaDriverSkillPresent:d,cuaDriverSkillSource:p,markerPath:n,missing:m}}function runCuaDriverMcpConfig(e){const t=resolveCommandPath("cua-driver",process.env.AGENTRIX_CUA_DRIVER_PATH);if(!t.available||!t.path)return"cua-driver command is not available. Install Cua Driver CLI or set AGENTRIX_CUA_DRIVER_PATH.";const n=resolveCodexPath();if(!n.available||!n.path)return"Codex CLI is not available. Install Codex or set AGENTRIX_CODEX_PATH to the codex executable.";fs.mkdirSync(e,{recursive:!0});const a=node_child_process.spawnSync(t.path,["mcp-config","--client","codex"],{encoding:"utf8",env:{...process.env,CODEX_HOME:e,AGENTRIX_CODEX_HOME:e}});if(0!==a.status){const e=[a.stderr,a.stdout].map(e=>e?.trim()).filter(Boolean).join("\n");return"Failed to run `cua-driver mcp-config --client codex`"+(e?`:\n${e}`:".")}const s=node_child_process.spawnSync(n.path,["mcp","add","cua-driver","--",t.path,"mcp"],{encoding:"utf8",env:{...process.env,CODEX_HOME:e}});if(0===s.status)return null;const i=[s.stderr,s.stdout].map(e=>e?.trim()).filter(Boolean).join("\n");return`Failed to run \`codex mcp add cua-driver -- ${t.path} mcp\`${i?`:\n${i}`:"."}`}function ensureCuaDriverSkillSymlink(e){const t=resolveCuaDriverSkillSource(),n=path.join(e,"skills","cua-driver");if(!t)return["Cua Driver skill source was not found.","Install or update Cua Driver so its installer auto-wires agent skills, or set AGENTRIX_CUA_DRIVER_SKILL_SOURCE to a directory containing SKILL.md."].join(" ");if(fs.existsSync(n)){if(fs.existsSync(path.join(n,"SKILL.md")))return null;try{return fs.lstatSync(n).isSymbolicLink()?`Existing Cua Driver skill symlink at ${n} does not resolve to a valid skill.`:`Existing path ${n} is not a valid Cua Driver skill directory.`}catch(e){return`Failed to inspect existing Cua Driver skill path ${n}: ${e instanceof Error?e.message:String(e)}`}}try{return fs.mkdirSync(path.dirname(n),{recursive:!0}),fs.symlinkSync(t,n,"dir"),null}catch(e){return`Failed to create Cua Driver skill symlink ${n} -> ${t}: ${e instanceof Error?e.message:String(e)}`}}function requestCuaDriverPermissions(e){const t=node_child_process.spawnSync(e,["call","check_permissions",'{"prompt":true}',"--raw","--compact"],{encoding:"utf8",timeout:3e4});if(0===t.status)return null;const n=[t.stderr,t.stdout].map(e=>e?.trim()).filter(Boolean).join("\n");return"Failed to open Cua Driver permission prompt"+(n?`:\n${n}`:".")}function enableComputerUseBridgeMarker(e){try{return fs.mkdirSync(path.dirname(e),{recursive:!0}),fs.writeFileSync(e,`${(new Date).toISOString()}\n`,"utf8"),null}catch(t){return`Failed to enable Agentrix Computer Use at ${e}: ${t instanceof Error?t.message:String(t)}`}}function enableComputerUseBridgeSettings(){try{const e=machine.machine.readSettings()??{};return machine.machine.writeSettings({...e,agentrixComputerUse:{...e.agentrixComputerUse??{},enabled:!0}}),null}catch(e){return`Failed to enable Agentrix Computer Use in settings: ${e instanceof Error?e.message:String(e)}`}}function disableComputerUseBridgeSettings(){try{const e=machine.machine.readSettings()??{};return machine.machine.writeSettings({...e,agentrixComputerUse:{...e.agentrixComputerUse??{},enabled:!1}}),null}catch(e){return`Failed to disable Agentrix Computer Use in settings: ${e instanceof Error?e.message:String(e)}`}}function removeComputerUseBridgeMarker(e){try{return fs.existsSync(e)&&fs.unlinkSync(e),null}catch(t){return`Failed to remove Agentrix Computer Use marker at ${e}: ${t instanceof Error?t.message:String(t)}`}}function installAgentrixComputerUse(){let e=getComputerUseBridgeStatus();const t=[],n=[];if("darwin"!==process.platform)return{success:!1,status:e,actions:t,error:"Agentrix Computer Use currently requires macOS because Cua Driver is macOS-only."};if(!e.cuaDriverAvailable)return{success:!1,status:e,actions:t,error:"Cua Driver is not installed or not available. Install Cua Driver from Desktop first, or set AGENTRIX_CUA_DRIVER_PATH."};if(e.cuaDriverAvailable&&t.push(`Detected Cua Driver at ${e.cuaDriverPath??"PATH"}`),e.cuaDriverPath){const a=requestCuaDriverPermissions(e.cuaDriverPath);a?n.push(a):t.push("Checked Cua Driver permissions and opened macOS permission prompts for any missing grants.")}if(e.cuaDriverMcpConfigured)t.push("Cua Driver MCP is already configured for Agentrix Computer Use.");else{const a=runCuaDriverMcpConfig(e.codexHome);a?n.push(a):t.push("Configured Cua Driver MCP for Agentrix Computer Use.")}if(e=getComputerUseBridgeStatus(),e.cuaDriverSkillPresent)t.push("Cua Driver skill is already available to Agentrix Computer Use.");else{const a=ensureCuaDriverSkillSymlink(e.codexHome);a?n.push(a):t.push("Linked Cua Driver skill for Agentrix Computer Use.")}const a=enableComputerUseBridgeMarker(e.markerPath);a?n.push(a):e.enabled?t.push("Agentrix Computer Use was already enabled."):t.push("Enabled Agentrix Computer Use.");const s=enableComputerUseBridgeSettings();s&&n.push(s);const i=getComputerUseBridgeStatus(),o=0===n.length&&i.enabled&&0===i.missing.length;return{success:o,status:0===n.length?i:{...i,missing:[...i.missing,...n.map(e=>`Agentrix Computer Use install failed: ${e}`)]},actions:t,error:o?void 0:[...n,...i.missing].join("\n")||"Agentrix Computer Use is not ready."}}function removePathIfExists(e){try{return(fs.existsSync(e)||fs.lstatSync(e).isSymbolicLink())&&fs.rmSync(e,{recursive:!0,force:!0}),null}catch(t){return"ENOENT"===t.code?null:`Failed to remove ${e}: ${t instanceof Error?t.message:String(t)}`}}function removeSymlinkIfExists(e){try{return fs.lstatSync(e).isSymbolicLink()?(fs.unlinkSync(e),null):null}catch(t){return"ENOENT"===t.code?null:`Failed to remove symlink ${e}: ${t instanceof Error?t.message:String(t)}`}}function removeSkillSymlinkIfExists(e){try{if(!fs.lstatSync(e).isSymbolicLink())return null;const t=fs.readlinkSync(e);return t.includes("CuaDriver.app")||t.includes("cua-driver")?(fs.unlinkSync(e),null):null}catch(t){return"ENOENT"===t.code?null:`Failed to remove Cua Driver skill symlink ${e}: ${t instanceof Error?t.message:String(t)}`}}function removeCodexCuaDriverMcpConfig(e){const t=path.join(e,"config.toml");try{const n=resolveCodexPath();if(n.available&&n.path&&node_child_process.spawnSync(n.path,["mcp","remove","cua-driver"],{encoding:"utf8",env:{...process.env,CODEX_HOME:e}}),!fs.existsSync(t))return null;const a=fs.readFileSync(t,"utf8"),s=a.replace(/\n?\[mcp_servers\.(?:"cua-driver"|'cua-driver'|cua-driver|cua_driver)\][\s\S]*?(?=\n\[[^\]]+\]|\s*$)/g,"").replace(/\n{3,}/g,"\n\n").trimEnd()+"\n";return s!==a&&fs.writeFileSync(t,s,"utf8"),null}catch(e){return`Failed to remove Cua Driver MCP config from ${t}: ${e instanceof Error?e.message:String(e)}`}}function uninstallCuaDriver(e){const t=[],n=[],a=e.cuaDriverPath;a&&(node_child_process.spawnSync(a,["stop"],{encoding:"utf8",timeout:1e4}),t.push("Stopped Cua Driver daemon if it was running."));const s=["/Applications/CuaDriver.app","/Applications/CuaDriverRs.app",path.join(os.homedir(),"Library","LaunchAgents","com.trycua.cua_driver_updater.plist"),path.join(os.homedir(),"Library","LaunchAgents","com.trycua.cua_driver_daemon.plist"),path.join(os.homedir(),"Library","LaunchAgents","com.trycua.cua-driver-rs.plist"),path.join(os.homedir(),"Library","Application Support","Cua Driver"),path.join(os.homedir(),"Library","Caches","cua-driver"),path.join(os.homedir(),".cua-driver-rs")];for(const e of s){const a=removePathIfExists(e);a?n.push(a):t.push(`Removed ${e}.`)}for(const e of[path.join(os.homedir(),".local","bin","cua-driver"),"/usr/local/bin/cua-driver"]){const a=removeSymlinkIfExists(e);a?n.push(a):t.push(`Removed ${e}.`)}for(const a of[path.join(e.codexHome,"skills","cua-driver"),path.join(os.homedir(),".agents","skills","cua-driver")]){const e=removeSkillSymlinkIfExists(a);e?n.push(e):t.push(`Removed ${a}.`)}const i=removeCodexCuaDriverMcpConfig(e.codexHome);return i?n.push(i):t.push("Removed Cua Driver MCP config from Codex when present."),{actions:t,errors:n}}function uninstallAgentrixComputerUse(){const e=getComputerUseBridgeStatus(),t=[],n=[],a=removeComputerUseBridgeMarker(e.markerPath);a?n.push(a):"marker"===e.enabledBy?t.push("Removed Agentrix Computer Use enablement marker."):t.push("Agentrix Computer Use enablement marker is already absent or not the active source.");const s=disableComputerUseBridgeSettings();s?n.push(s):t.push("Disabled Agentrix Computer Use in settings.");const i=uninstallCuaDriver(e);t.push(...i.actions),n.push(...i.errors);const o=getComputerUseBridgeStatus();"env"===o.enabledBy&&n.push("Agentrix Computer Use is still enabled by AGENTRIX_COMPUTER_USE_ENABLED. Remove that environment variable and restart the daemon to complete uninstall.");const r=0===n.length&&!o.enabled;return{success:r,status:o,actions:t,error:r?void 0:n.join("\n")||"Agentrix Computer Use is still enabled."}}function ensureComputerUseBridgeConfigured(e=machine.machine.readSettings()){const t=getComputerUseBridgeStatus(e);if(!t.enabled)return t;const n=[];if(!t.cuaDriverMcpConfigured){logger$7.info("computer_use.configure_mcp");const e=runCuaDriverMcpConfig(t.codexHome);e&&n.push(e)}if(!t.cuaDriverSkillPresent){logger$7.info("computer_use.configure_skill");const e=ensureCuaDriverSkillSymlink(t.codexHome);e&&n.push(e)}const a=getComputerUseBridgeStatus(e);return 0===n.length?a:{...a,missing:[...a.missing,...n.map(e=>`Automatic Cua Driver configuration failed: ${e}`)]}}function buildComputerUseSetupMessage(e){const t=["Agentrix Computer Use execution bridge is not ready.","","Enablement: "+(e.enabled?`enabled by ${e.enabledBy}`:"disabled"),`Codex home checked: ${e.codexHome}`,""];return e.enabled||t.push("Enable it with one of:","- set AGENTRIX_COMPUTER_USE_ENABLED=true for the worker/daemon environment;","- set settings.json field agentrixComputerUse.enabled=true;",`- create marker file ${e.markerPath}.`,""),e.missing.length>0&&t.push("Missing configuration:",...e.missing.map(e=>`- ${e}`),""),t.push("Agentrix tries to configure Codex automatically after this bridge is enabled:","1. cua-driver mcp-config --client codex","2. link the Cua Driver SKILL.md pack into Codex when a valid local skill source can be discovered","If automatic configuration fails, run the official Cua Driver installer/update flow or set AGENTRIX_CUA_DRIVER_PATH / AGENTRIX_CUA_DRIVER_SKILL_SOURCE.","Grant macOS Accessibility and Screen Recording permissions to Cua Driver when prompted."),t.join("\n")}function buildComputerUseCodexPrompt(e){const t=e.expectedResult?.trim();return["You are the Agentrix Computer Use execution worker for the current Agentrix task.","","Use the configured Cua Driver skill and MCP tools in this Codex environment to operate the local computer. Do not implement or modify Agentrix code unless the desktop operation explicitly requires editing a file. Prefer Cua Driver app-control tools over shell commands for GUI work. If the request needs a permission grant or user login that you cannot complete, stop and explain exactly what the user must do.","","Desktop operation instruction:",e.instruction.trim(),"",t?`Expected result:\n${t}`:void 0,"","Return a concise report of what you did, what result you observed, and any blocker or follow-up required."].filter(e=>Boolean(e)).join("\n")}async function executeComputerUseBridge(e,t){if(!e.instruction.trim())throw new Error("instruction is required.");const n=t.status??ensureComputerUseBridgeConfigured();if(!n.enabled||n.missing.length>0)throw new Error(buildComputerUseSetupMessage(n));const a=buildComputerUseCodexPrompt(e),s=e.title?.trim()||"Computer use",i=t.historyDb.getAgentSessions().get("agentrix-computer-use");if(i)return logger$7.info(`Emitting computer-use instruction to existing sub-task ${i} for task ${t.taskId}`),await t.sendMessage({taskId:i,target:"agent",message:{type:"user",message:{role:"user",content:a},parent_tool_use_id:null,session_id:""}}),{taskId:i,title:s,action:"emitted"};logger$7.info(`Starting computer-use sub-task for task ${t.taskId}`);const o=await t.startSubTask({agentId:"codex",message:{type:"user",message:{role:"user",content:a},parent_tool_use_id:null,session_id:"new"},title:s,cwd:t.cwd,forceUserCwd:!0,initPolicies:{uncommittedChanges:"Ignore",branchMismatch:"Keep"}});return t.historyDb.upsertAgentSession("agentrix-computer-use",o.taskId),{taskId:o.taskId,title:s,action:"created"}}function formatGitLabPatValidationError(e,t){if(e.valid)return"";switch(e.status){case"insufficient_scope":{const t=e.missingScopes?.filter(Boolean).join(", ");return t?`GitLab PAT is missing required scopes: ${t}. Update or recreate the PAT with these scopes, then run the command again.`:"GitLab PAT is missing required scopes. Update or recreate the PAT with the required GitLab scopes, then run the command again."}case"expired":return"GitLab rejected this PAT because it is expired, revoked, or no longer accepted. Create a new GitLab PAT and run the command again.";case"network_error":return`Cannot reach the GitLab API at ${t}. Check the GitLab URL, network, VPN, or intranet access, then run the command again.`;case"invalid":return"Token is empty"===e.error?"GitLab PAT is required. Provide a token with --pat-file, stdin, or the interactive prompt.":"GitLab rejected this PAT. Check that you copied the full token, or create a new GitLab PAT and run the command again.";default:return e.error||`GitLab PAT validation failed for ${t}/user`}}function normalizeUrl$1(e,t){const n=e.trim();if(!n)throw new Error(`${t} is required`);let a;try{a=new URL(n)}catch{throw new Error(`${t} must be a valid URL`)}if("http:"!==a.protocol&&"https:"!==a.protocol)throw new Error(`${t} must use http or https`);return a.toString().replace(/\/+$/,"")}function parseBooleanEnv(e,t){if(void 0===e||""===e.trim())return t;const n=e.trim().toLowerCase();if(["true","1","yes"].includes(n))return!0;if(["false","0","no"].includes(n))return!1;throw new Error(`Invalid boolean value: ${e}`)}function readPatFromEnv(e){const t=e.GITLAB_TOKEN?.trim();if(t)return t;const n=e.GITLAB_TOKEN_FILE?.trim();if(!n)return null;if(!fs.existsSync(n))throw new Error(`GITLAB_TOKEN_FILE is not readable: ${n}`);return fs.readFileSync(n,"utf8").trim()}function readGitServerAutoConfigFromEnv(e=process.env){if(!parseBooleanEnv(e.AGENTRIX_GITLAB_AUTO_CONFIG,!0))return null;const t=e.GITLAB_BASE_URL?.trim(),n=readPatFromEnv(e);if(!t&&!n)return null;if(!t)throw new Error("GITLAB_BASE_URL is required when GITLAB_TOKEN is configured");if(!n)throw new Error("GITLAB_TOKEN or GITLAB_TOKEN_FILE is required when GITLAB_BASE_URL is configured");const a=normalizeUrl$1(t,"GITLAB_BASE_URL"),s=normalizeUrl$1(e.GITLAB_API_URL?.trim()||`${a}/api/v4`,"GITLAB_API_URL");return{name:e.AGENTRIX_GITLAB_NAME?.trim()||new URL(a).hostname,baseUrl:a,apiUrl:s,pat:n,useAsProxy:parseBooleanEnv(e.AGENTRIX_GITLAB_USE_AS_PROXY,!0)}}function withTimeout$1(e,t,n){let a;const s=new Promise((e,s)=>{a=setTimeout(()=>s(new Error(n)),t)});return Promise.race([e,s]).finally(()=>{a&&clearTimeout(a)})}async function machineRpc$1(e,t,n,a,s=15e3){if(!e.connected)throw new Error("Machine WebSocket is not connected");const i={eventId:shared.createEventId(),method:t,path:n,body:a},o=await withTimeout$1(e.sendWithAck("machine-rpc-call",i),s,`Timed out waiting for machine RPC ${t} ${n}`);if(!o.success)throw new Error(o.error?.message||`Machine RPC failed: ${t} ${n}`);return o.data}async function bindGitServerWithLocalPat(e,t,n){const a=await node.validateGitLabPatToken(n.apiUrl,n.pat,{log:{warn:(e,t)=>machine.logger.warn(e,t),error:(e,t)=>machine.logger.warn(e,t)}});if(!a.result.valid||!a.user)throw new Error(formatGitLabPatValidationError(a.result,n.apiUrl));const s=await getGitServerEncryptionKey();if(!s)throw new Error("No Agentrix auth secret found for GitLab configuration");const i=await machineRpc$1(e,"POST","/v1/git-servers/machine-bind",{name:n.name,baseUrl:n.baseUrl,apiUrl:n.apiUrl,machineId:t.machineId,pat:n.pat,useAsProxy:n.useAsProxy});if(!i.success||!i.gitServer)throw new Error("Backend Git server bind failed");const o=i.gitServer,r={username:a.user.username,email:a.user.email||"",lastValidatedAt:(new Date).toISOString(),expiresAt:a.result.expiresAt};saveGitServerConfig(o.id,{baseUrl:o.baseUrl,apiUrl:o.apiUrl}),savePat(o.id,n.pat,s),savePatMeta(o.id,r);const c=ensureGitLabWebhookSecret(o.id,s);return{success:!0,gitServer:o,machineId:i.machineId,proxyRegistered:i.proxyRegistered,webhookEndpointPath:node.buildGitLabWebhookEndpointPath(o.id),webhookUrl:node.buildGitLabWebhookUrl(o.id,await machine.machine.readDaemonState()),patConfigured:!0,patMeta:r,webhookSecret:c}}async function configureGitServerFromEnvironment(e,t){const n=readGitServerAutoConfigFromEnv();if(!n)return null;const a=await bindGitServerWithLocalPat(e,t,n),s=a.gitServer,i={gitServerId:s.id,baseUrl:s.baseUrl,apiUrl:s.apiUrl,webhookEndpointPath:a.webhookEndpointPath,webhookUrl:a.webhookUrl,proxyRegistered:a.proxyRegistered};return machine.logger.info(`[GIT SERVER] auto-configured from environment: gitServer=${i.gitServerId}, proxyRegistered=${i.proxyRegistered}`),i}async function configureGitServerFromEnvironmentSafely(e,t){try{return await configureGitServerFromEnvironment(e,t)}catch(e){return machine.logger.warn("[GIT SERVER] environment auto-config failed; daemon startup will continue",e),null}}function listWorkspaceFiles(e,t){const n=[],a=fs.readdirSync(e,{withFileTypes:!0});for(const s of a){if(".gitkeep"===s.name)continue;const a=path.join(e,s.name),i=fs.statSync(a),o=path.relative(t,a);n.push({name:s.name,path:o,size:i.size,modifiedAt:i.mtimeMs,isDirectory:s.isDirectory()}),s.isDirectory()&&n.push(...listWorkspaceFiles(a,t))}return n}function resolveCompanionHomeDir(){return path.join(machine.machine.agentrixAgentsHomeDir,"companion","claude")}function safeCompanionPath(e,t){const n=path.normalize(path.join(e,t));return n.startsWith(e)?{absolutePath:n,relativePath:path.relative(e,n)}:null}function parseAfterDate(e){const t=new Date(e);return Number.isNaN(t.getTime())?null:t}function previousUtcDayKey(e){const t=parseAfterDate(e);if(!t)return null;const n=new Date(Date.UTC(t.getUTCFullYear(),t.getUTCMonth(),t.getUTCDate()));n.setUTCDate(n.getUTCDate()-1);const a=n.toISOString();return{key:n.toISOString().slice(0,10),nextAfter:a}}function dateDayKey(e){if(!/^\d{4}-\d{2}-\d{2}$/.test(e))return null;const t=new Date(`${e}T00:00:00.000Z`);return Number.isNaN(t.getTime())?null:{key:e,nextAfter:t.toISOString()}}function normalizeMemoryEventRecord(e,t,n){const a=Array.isArray(e?.changes)?e.changes:[e],s=a.map(e=>e?.summary).filter(Boolean),i=a.flatMap(e=>Array.isArray(e?.reasons)?e.reasons:[]).filter(Boolean),o=a.map(e=>e?.file).filter(Boolean),r=a.map(e=>e?.action).filter(Boolean);return{id:n,createdAt:e?.time||e?.timestamp||e?.createdAt||t,title:e?.title||s[0]||"记忆已更新",summary:i.length?i.join("\n"):"",files:o,actions:r,source:e?.source,trigger:e?.trigger,commit:e?.commit}}function readCompanionMemoryEventsForDay(e,t,n){const a=path.join(e,"memory-changes"),s=path.join(a,`${t.key}.jsonl`),i=`${t.key}T00:00:00.000Z`,o=fs.existsSync(s)?fs.readFileSync(s,"utf-8").split("\n").map((e,n)=>{const a=e.trim();if(!a)return null;try{return normalizeMemoryEventRecord(JSON.parse(a),i,`${t.key}-${n}`)}catch{return null}}).filter(Boolean):[],r=fs.existsSync(a)&&fs.readdirSync(a).some(e=>/^\d{4}-\d{2}-\d{2}\.jsonl$/.test(e)&&e.slice(0,10)<t.key);return{...n,nextAfter:t.nextAfter,events:o.sort((e,t)=>new Date(t.createdAt).getTime()-new Date(e.createdAt).getTime()),hasMore:r}}function readCompanionMemoryEventsForQuery(e,t){if(t.date){const n=dateDayKey(t.date);return n?readCompanionMemoryEventsForDay(e,n,{date:t.date}):null}if(t.after){const n=previousUtcDayKey(t.after);return n?readCompanionMemoryEventsForDay(e,n,{after:t.after}):null}return null}function runCompanionGit(e,t){if(!fs.existsSync(path.join(e,".git")))return"";try{return node_child_process.execFileSync("git",["-C",e,...t],{encoding:"utf8",timeout:1e4,stdio:["ignore","pipe","ignore"]})}catch{return""}}function listCompanionFileVersions(e,t,n={}){const a=Math.min(Math.max(n.limit??10,1),50),s=Math.max(n.skip??0,0),i=runCompanionGit(e,["log",`--max-count=${a+1}`,`--skip=${s}`,"--date=iso-strict","--pretty=format:%H%x1f%h%x1f%aI%x1f%s%x1f%b%x1e","--",t]).split("").map(e=>e.trim()).filter(Boolean).map(e=>{const[t,n,a,s,i]=e.split("");return{commit:t||"",shortCommit:n||"",authoredAt:a||"",subject:s||"没有详细变更说明",body:i?.trim()||""}}).filter(e=>e.commit.length>0);return{versions:i.slice(0,a),hasMore:i.length>a,nextSkip:s+Math.min(i.length,a)}}function readCompanionFileDiff(e,t,n){const a=n.replace(/[^0-9a-f]/gi,"");return a?runCompanionGit(e,["show","--format=","--no-ext-diff",a,"--",t]):""}function summarizeStructuredCompanionValue(e){if(!e||"object"!=typeof e)return"";const t=e,n=(Array.isArray(t.changes)?t.changes:[]).map(e=>e&&"object"==typeof e?e.summary:null).filter(e=>"string"==typeof e&&e.trim().length>0);if(n.length)return n.join(";");const a=t.input;if(a&&"object"==typeof a){const e=summarizeStructuredCompanionValue(a);if(e)return e}for(const e of["result","summary","title","content","text","message"]){const n=t[e];if("string"==typeof n&&n.trim())return n;if(n&&"object"==typeof n){const e=summarizeStructuredCompanionValue(n);if(e)return e}}return""}function stringifyMessageForConsole(e){if("string"==typeof e){const t=e.trim();if(t.startsWith("{")&&t.endsWith("}")||t.startsWith("[")&&t.endsWith("]"))try{const e=summarizeStructuredCompanionValue(JSON.parse(t));if(e)return e}catch{}return e}if(!e||"object"!=typeof e)return"";const t=summarizeStructuredCompanionValue(e);if(t)return t;const n=e.content;return"string"==typeof n?stringifyMessageForConsole(n):Array.isArray(n)?n.map(e=>stringifyMessageForConsole(e)).filter(Boolean).join("\n"):""}function companionDisplayText(e,t){return stringifyMessageForConsole(e).trim()||t}function companionRecordHasUpdate(e){return!/(no\s+(memory\s+)?changes?\s+(needed|required|found|detected)|no\s+updates?\s+(needed|required|found|detected)|无需.*(更新|变更|修改|创建|新增|删除)|不需要.*(更新|变更|修改|创建|新增|删除)|没有.*(更新|变更|修改|创建|新增|删除)|无.*(更新|变更|修改|创建|新增|删除)|未.*(发现|检测到).*(更新|变更|修改|创建|新增|删除))/i.test(e)&&/更新|updated|created|deleted|修改|创建|新增|删除|memory change|memory changes/i.test(e)}function isCompanionMemoryOrganizationTrigger(e){return!!e&&"object"==typeof e&&"companion_memory_organization"===e.type}function isRecordMemoryChangeToolUse(e){if(!e)return!1;if(Array.isArray(e))return e.some(isRecordMemoryChangeToolUse);if("object"!=typeof e)return!1;const t=e;return"tool_use"===t.type&&("mcp__agentrix__record_memory_change"===t.name||"record_memory_change"===t.name)||Object.values(t).some(isRecordMemoryChangeToolUse)}function extractResultText(e){if(!e||"object"!=typeof e)return"";const t=e;return"result"===t.type&&"string"==typeof t.result?t.result:""}function readRecentLocalTaskMessages(e,t,n=1){if(!e||!t)return[];try{const a=getTaskDb({dataDir:machine.machine.resolveDataDir(e,t),taskId:t});try{return[...a.pageRecentMessages(50).data].reverse().filter(e=>"system"!==e.senderType&&stringifyMessageForConsole(e.message).trim()).slice(0,n).map(e=>({summary:companionDisplayText(stringifyMessageForConsole(e.message),""),time:e.createdAt}))}finally{a.close()}}catch{return[]}}function readRecentCompanionChatActivity(e,t=1){return readRecentLocalTaskMessages("string"==typeof e.userId?e.userId:null,"string"==typeof e.chatTaskId?e.chatTaskId:null,t).map(e=>({type:"chat",title:"Companion Chat",summary:e.summary,time:e.time}))}async function readRecentCompanionTaskActivity(e,t,n=1){const a="string"==typeof e.chatId?e.chatId:null;if(!a)return[];try{const s=new URLSearchParams({chatId:a,limit:String(Math.min(Math.max(3*n,10),50))}),i=await machineRpc(t,"GET",`/v1/tasks/recent?${s.toString()}`,void 0,1e4);return Array.isArray(i.tasks)?i.tasks.filter(e=>!["completed","cancelled","error"].includes(String(e.state))).slice(0,n).map(t=>{const n="string"==typeof t.taskId?t.taskId:"",a="string"==typeof t.title&&t.title.trim()?t.title.trim():"Task",s=readRecentLocalTaskMessages("string"==typeof e.userId?e.userId:null,n,1)[0];return{type:"task",title:a,summary:s?.summary||"",time:s?.time||t.updatedAt||t.createdAt||(new Date).toISOString()}}):[]}catch{return[]}}function readRecentCompanionMemoryActivity(e,t=1){const n=path.join(e,"memory-changes");if(!fs.existsSync(n))return[];const a=fs.readdirSync(n).filter(e=>/^\d{4}-\d{2}-\d{2}\.jsonl$/.test(e)).sort().reverse(),s=[];for(const n of a){const a=n.slice(0,10),i=readCompanionMemoryEventsForDay(e,{key:a,nextAfter:`${a}T00:00:00.000Z`},{date:a});for(const e of i.events){const n=companionDisplayText(e.summary||e.files.join(", ")||e.title,"记忆已更新");if(s.push({type:"memory",title:e.title||"记忆已更新",summary:n,time:String(e.createdAt)}),s.length>=t)return s}}return s}function readCompanionMemoryOrganizationRecentRecords(e,t){const n=[],a=getTaskDb({dataDir:machine.machine.resolveDataDir(e,t),taskId:t});try{let e=!1,t=!1;for(const s of a.pageRecentTaskEvents(1e3).data){const a=s.eventData,i=a.message;if(isCompanionMemoryOrganizationTrigger(i)){e=!0,t=!1;continue}if(!e)continue;isRecordMemoryChangeToolUse(i)&&(t=!0);const o="agent"===a.senderType?extractResultText(i):"";o&&(n.push({time:s.createdAt,summary:companionDisplayText(o,"记忆整理已运行"),updated:t}),e=!1,t=!1)}}finally{a.close()}return n}function readCompanionRecentRecords(e,t,n=1){const a="string"==typeof e.userId?e.userId:null,s="string"==typeof e.chatTaskId?e.chatTaskId:null;if(!a||!s)return[];const i=("heartbeat"===t?[e.heartbeatTaskId,e.heartbeatShadowTaskId]:[e.memoryOrganizationTaskId,e.memoryOrganizationShadowTaskId]).filter(e=>"string"==typeof e&&e.length>0),o=[s,...i],r="heartbeat"===t?["heartbeat","心跳","reminder","待处理事项"]:["memory organization","memory-organization","记忆整理","companion_memory_organization","memory review","memory changes","记忆更新"],c=[];if("memory-organization"===t){for(const e of[...new Set(i)])try{c.push(...readCompanionMemoryOrganizationRecentRecords(a,e))}catch{}if(c.length>0)return normalizeCompanionRecentRecords(c,n)}for(const e of[...new Set(o)]){const n=i.includes(e);try{const s=getTaskDb({dataDir:machine.machine.resolveDataDir(a,e),taskId:e});try{for(const e of s.pageRecentMessages(160).data){if("agent"!==e.senderType)continue;const a=stringifyMessageForConsole(e.message);if(!a.trim())continue;if(!n&&!r.some(e=>a.toLowerCase().includes(e.toLowerCase())))continue;const s=companionDisplayText(a,"heartbeat"===t?"Heartbeat 已运行":"记忆整理已运行");c.push({time:e.createdAt,summary:s,updated:companionRecordHasUpdate(a)})}}finally{s.close()}}catch{}}return normalizeCompanionRecentRecords(c,n)}function normalizeCompanionRecentRecords(e,t=1){const n=new Set;return e.sort((e,t)=>new Date(t.time).getTime()-new Date(e.time).getTime()).filter(e=>{const t=`${e.time}:${e.summary}`;return!n.has(t)&&(n.add(t),!0)}).slice(0,t)}function secureTokenEquals(e,t){if("string"!=typeof e)return!1;const n=Buffer.from(e),a=Buffer.from(t);return n.length===a.length&&node_crypto.timingSafeEqual(n,a)}function isLoopbackAddress(e){return"127.0.0.1"===e||"::1"===e||"::ffff:127.0.0.1"===e}function getGitLabEventType(e){const t=e.event_type??e.object_kind;return"string"==typeof t?t:"unknown"}function summarizeGitLabWebhookPipeline(e){if(!e||"object"!=typeof e)return"-";const t=e,n=t.id??t.iid??"-",a=t.status??"-",s=t.ref??"-",i=t.web_url??t.webUrl??"-";return`id=${String(n)}, status=${String(a)}, ref=${String(s)}, webUrl=${String(i)}`}function summarizeGitLabWebhookResponse(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??"-"),a=String(t.eventType??"-"),s=String(t.eventName??"-"),i=String(t.action??"-"),o=String(t.reason??"-"),r=String(t.upstreamStatus??"-"),c=String(t.errorMessage??"-");return`status=${n}, eventType=${a}, eventName=${s}, action=${i}, reason=${o}, triggeredCount=${String(t.triggeredCount??"-")}, failedCount=${String(t.failedCount??"-")}, upstreamStatus=${r}, errorMessage=${c}, pipeline=${summarizeGitLabWebhookPipeline(t.pipeline)}`}const GitServerResponseSchema=zod.z.object({id:zod.z.string(),type:zod.z.string(),name:zod.z.string(),baseUrl:zod.z.string(),apiUrl:zod.z.string(),oauthServerId:zod.z.string().nullable().optional(),ownerId:zod.z.string().nullable().optional(),authModeDefault:zod.z.string().optional(),executionMode:zod.z.string().optional(),syncMode:zod.z.string().optional(),networkMode:zod.z.string().optional(),githubAppName:zod.z.string().nullable().optional(),enabled:zod.z.boolean().optional(),createdAt:zod.z.string().optional(),updatedAt:zod.z.string().optional()}).passthrough(),ComputerUseBridgeStatusSchema=zod.z.object({platform:zod.z.string(),enabled:zod.z.boolean(),enabledBy:zod.z.enum(["env","settings","marker"]).nullable(),codexHome:zod.z.string(),codexAvailable:zod.z.boolean(),codexPath:zod.z.string().optional(),codexConfigPresent:zod.z.boolean(),cuaDriverAvailable:zod.z.boolean(),cuaDriverPath:zod.z.string().optional(),cuaDriverAccessibilityGranted:zod.z.boolean().optional(),cuaDriverScreenRecordingGranted:zod.z.boolean().optional(),cuaDriverMcpConfigured:zod.z.boolean(),cuaDriverSkillPresent:zod.z.boolean(),cuaDriverSkillSource:zod.z.string().optional(),markerPath:zod.z.string(),missing:zod.z.array(zod.z.string())}),REPOSITORY_INBOX_WEBHOOK_ACK_TIMEOUT_MS=5e3;async function withTimeout(e,t,n){let a;try{return await Promise.race([e,new Promise((e,s)=>{a=setTimeout(()=>s(new Error(n)),t)})])}finally{a&&clearTimeout(a)}}function getHeaderString(e){return Array.isArray(e)?e[0]:e}function getGitLabWebhookDeliveryHeader(e){return getHeaderString(e["webhook-id"])??getHeaderString(e["idempotency-key"])??getHeaderString(e["x-gitlab-webhook-uuid"])??getHeaderString(e["x-gitlab-event-uuid"])??getHeaderString(e["x-gitlab-delivery"])}function formatApiError(e){return e instanceof Error?e.message:"Unknown error"}async function reportRepositoryInboxWebhook(e,t,n,a,s){if(!s?.connected)throw new Error("Machine WebSocket is not connected");const i={eventId:shared.createEventId(),provider:"gitlab",gitServerId:e,deliveryId:n,eventType:a,payload:t},o=await withTimeout(s.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")}async function machineRpc(e,t,n,a,s=15e3){if(!e?.connected)throw new Error("Machine WebSocket is not connected");const i={eventId:shared.createEventId(),method:t,path:n,body:a},o=await withTimeout(e.sendWithAck("machine-rpc-call",i),s,`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 startDaemonControlServer(e){const{getChildren:t,stopSession:n,startDevOpsInit:a,completeDevOpsInit:s,requestShutdown:i,registerSession:o,credentials:r,getSocketClient:c,prepareGracefulRestart:l,clearGracefulRestartGate:d}=e;return new Promise(p=>{const u=machine.machine.getDaemonControlHost(),m=machine.machine.getDaemonWebhookHost(),h=fastify({logger:!1});h.removeContentTypeParser("application/json"),h.addContentTypeParser("application/json",{parseAs:"string"},(e,t,n)=>{const a="string"==typeof t?t:t.toString("utf8");if(0!==a.trim().length)try{n(null,JSON.parse(a))}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(fastifyTypeProviderZod.validatorCompiler),h.setSerializerCompiler(fastifyTypeProviderZod.serializerCompiler);const g=h.withTypeProvider();registerAgentrixEventMcpBrokerRoutes(h,{credentials:r,getSocketClient:c});const f=e=>{e.header("Access-Control-Allow-Origin","*"),e.header("Access-Control-Allow-Methods","GET, POST, PUT, DELETE, OPTIONS"),e.header("Access-Control-Allow-Headers","Content-Type"),e.header("Access-Control-Allow-Private-Network","true")};g.post("/session-started",{schema:{body:zod.z.object({sessionId:zod.z.string(),metadata:zod.z.any()}),response:{200:zod.z.object({status:zod.z.literal("ok")})}}},async e=>{const{sessionId:t,metadata:n}=e.body;return machine.logger.debug(`[CONTROL SERVER] Session started: ${t}`),o(t,n),{status:"ok"}}),g.post("/devops-init-complete",{schema:{body:zod.z.object({taskId:zod.z.string(),userId:zod.z.string(),action:zod.z.enum(["continue","stop"])}),response:{200:zod.z.object({status:zod.z.literal("ok")})}}},async e=>{const{taskId:t,userId:n,action:a}=e.body;return machine.logger.info(`[CONTROL SERVER] Agentrix DevOps init complete for task ${t}, action=${a}`),s?.({taskId:t,userId:n,action:a}),{status:"ok"}}),g.post("/devops-init-start",{schema:{body:zod.z.object({taskId:zod.z.string(),userId:zod.z.string()}),response:{200:zod.z.object({status:zod.z.literal("ok")})}}},async e=>{const{taskId:t,userId:n}=e.body;return machine.logger.info(`[CONTROL SERVER] Starting Agentrix DevOps init for existing task ${t}`),a?.({taskId:t,userId:n}),{status:"ok"}}),g.post("/prepare-graceful-restart",{schema:{body:zod.z.object({source:zod.z.string().optional(),reason:zod.z.string().optional()}).optional(),response:{200:zod.z.object({state:zod.z.enum(["pending_restart","restarting"]),activeSessions:zod.z.number()}),503:zod.z.object({error:zod.z.string()}),403:zod.z.object({error:zod.z.string()})}}},async(e,t)=>isLoopbackAddress(e.ip)?l?l({source:e.body?.source??"control-server",reason:e.body?.reason}):t.code(503).send({error:"Graceful restart gate is not available"}):t.code(403).send({error:"Graceful restart control is only allowed from loopback"})),g.post("/clear-graceful-restart-gate",{schema:{response:{200:zod.z.object({success:zod.z.literal(!0)}),403:zod.z.object({error:zod.z.string()})}}},async(e,t)=>isLoopbackAddress(e.ip)?(d?.(),{success:!0}):t.code(403).send({error:"Graceful restart control is only allowed from loopback"})),g.options("/ping",async(e,t)=>(f(t),t.send())),g.get("/ping",{schema:{response:{200:zod.z.object({status:zod.z.literal("ok"),machineId:zod.z.string(),timestamp:zod.z.string(),controlHost:zod.z.string(),webhookHost:zod.z.string(),hasMachineAesKey:zod.z.boolean()})}}},async(e,t)=>(f(t),{status:"ok",machineId:r.machineId,timestamp:(new Date).toISOString(),controlHost:u,webhookHost:m,hasMachineAesKey:hasValidMachineAesKey(r)})),g.get("/computer-use/status",{schema:{response:{200:zod.z.object({status:ComputerUseBridgeStatusSchema}),403:zod.z.object({error:zod.z.string()})}}},async(e,t)=>isLoopbackAddress(e.ip)?{status:getComputerUseBridgeStatus()}:t.code(403).send({error:"Computer Use status is only allowed from loopback"})),g.post("/computer-use/install",{schema:{response:{200:zod.z.object({success:zod.z.boolean(),status:ComputerUseBridgeStatusSchema,actions:zod.z.array(zod.z.string()),error:zod.z.string().optional()}),403:zod.z.object({error:zod.z.string()})}}},async(e,t)=>{if(!isLoopbackAddress(e.ip))return t.code(403).send({error:"Computer Use installation is only allowed from loopback"});try{return installAgentrixComputerUse()}catch(e){return{success:!1,status:getComputerUseBridgeStatus(),actions:[],error:formatApiError(e)}}}),g.post("/computer-use/uninstall",{schema:{response:{200:zod.z.object({success:zod.z.boolean(),status:ComputerUseBridgeStatusSchema,actions:zod.z.array(zod.z.string()),error:zod.z.string().optional()}),403:zod.z.object({error:zod.z.string()})}}},async(e,t)=>{if(!isLoopbackAddress(e.ip))return t.code(403).send({error:"Computer Use uninstall is only allowed from loopback"});try{return uninstallAgentrixComputerUse()}catch(e){return{success:!1,status:getComputerUseBridgeStatus(),actions:[],error:formatApiError(e)}}}),g.post("/machine/aes-key",{schema:{body:zod.z.object({machineId:zod.z.string(),machineAesKey:zod.z.string()}),response:{200:zod.z.object({success:zod.z.literal(!0),updated:zod.z.boolean(),hasMachineAesKey:zod.z.literal(!0)}),400:zod.z.object({error:zod.z.string()}),403:zod.z.object({error:zod.z.string()}),409:zod.z.object({error:zod.z.string()}),500:zod.z.object({error:zod.z.string()})}}},async(e,t)=>{if(!isLoopbackAddress(e.ip))return t.code(403).send({error:"machine AES key recovery is only allowed from loopback"});try{const t=await storeRecoveredMachineAesKey(r,e.body);return machine.logger.info(t.updated?`[CONTROL SERVER] Recovered machine AES key stored for ${r.machineId}`:`[CONTROL SERVER] Machine AES key already present for ${r.machineId}`),t}catch(e){const n=e instanceof MachineAesKeyUpdateError?e.statusCode:500,a=400===n||409===n?n:500,s=e instanceof Error?e.message:"Failed to store machine AES key";return machine.logger.warn(`[CONTROL SERVER] Failed to store recovered machine AES key: ${s}`),t.code(a).send({error:s})}}),g.options("/openers",async(e,t)=>(f(t),t.send())),g.get("/openers",{schema:{response:{200:zod.z.object({openers:zod.z.array(zod.z.object({id:zod.z.string(),label:zod.z.string(),kind:zod.z.enum(["system","file-manager","terminal","editor","ide"]),method:zod.z.enum(["scheme","cli"]),urlTemplate:zod.z.string().optional(),supported:zod.z.boolean()}))})}}},async(e,t)=>(f(t),{openers:await listOpeners()})),g.options("/open",async(e,t)=>(f(t),t.send())),g.options("/pick-directory",async(e,t)=>(f(t),t.send())),g.options("/validate-directory",async(e,t)=>(f(t),t.send())),g.post("/open",{schema:{body:zod.z.object({path:zod.z.string(),openerId:zod.z.string(),userId:zod.z.string().optional(),taskId:zod.z.string().optional()}),response:{200:zod.z.object({success:zod.z.boolean(),error:zod.z.string().optional()})}}},async(e,t)=>{f(t);const{path:n,openerId:a,userId:s,taskId:i}=e.body;return await openWithOpener({openerId:a,targetPath:n,userId:s,taskId:i})}),g.post("/pick-directory",{schema:{body:zod.z.object({defaultPath:zod.z.string().optional()}),response:{200:zod.z.object({path:zod.z.string().nullable(),error:zod.z.string().optional()})}}},async(e,t)=>{f(t);try{return{path:pickDirectory(e.body.defaultPath)??null}}catch(e){return{path:null,error:e instanceof Error?e.message:"Failed to pick directory"}}}),g.post("/validate-directory",{schema:{body:zod.z.object({path:zod.z.string()}),response:{200:zod.z.object({ok:zod.z.boolean(),status:zod.z.enum(["active","missing","permission_lost"]),error:zod.z.string().optional()})}}},async(e,t)=>{f(t);try{if(!fs.statSync(e.body.path).isDirectory())return{ok:!1,status:"missing",error:"Path is not a directory"};try{fs.accessSync(e.body.path,fs.constants.R_OK|fs.constants.W_OK)}catch{return{ok:!1,status:"permission_lost",error:"Directory is not readable and writable"}}return{ok:!0,status:"active"}}catch(e){return{ok:!1,status:"missing",error:e instanceof Error?e.message:"Directory is unavailable"}}}),g.post("/companion/ensure",{schema:{body:zod.z.object({preferredLanguage:zod.z.enum(["en","zh-Hans"]).nullable().optional()}).optional(),response:{200:zod.z.object({agentDir:zod.z.string()})}}},async e=>await ensureCompanionAgent({preferredLanguage:e.body?.preferredLanguage,credentials:r})),g.post("/companion/probe",{schema:{response:{200:zod.z.object({success:zod.z.boolean(),error:zod.z.string().optional()})}}},async()=>await probeCompanionChain()),g.get("/companion/workspace/status",{schema:{response:{200:zod.z.object({exists:zod.z.boolean()})}}},async()=>{const e=resolveCompanionHomeDir();return{exists:fs.existsSync(e)}}),g.get("/companion/workspace",{schema:{response:{200:zod.z.object({files:zod.z.array(zod.z.object({name:zod.z.string(),path:zod.z.string(),size:zod.z.number(),modifiedAt:zod.z.number(),isDirectory:zod.z.boolean()}))})}}},async()=>{const e=resolveCompanionHomeDir();return fs.existsSync(e)?{files:listWorkspaceFiles(e,e)}:{files:[]}}),g.get("/companion/file",{schema:{querystring:zod.z.object({path:zod.z.string()}),response:{200:zod.z.object({content:zod.z.string()}),404:zod.z.object({error:zod.z.string()})}}},async(e,t)=>{const n=resolveCompanionHomeDir(),a=path.normalize(path.join(n,e.query.path));return a.startsWith(n)&&fs.existsSync(a)?{content:fs.readFileSync(a,"utf-8")}:t.code(404).send({error:"File not found"})}),g.put("/companion/file",{schema:{body:zod.z.object({path:zod.z.string(),content:zod.z.string()}),response:{200:zod.z.object({success:zod.z.boolean()}),400:zod.z.object({error:zod.z.string()})}}},async(e,t)=>{const n=resolveCompanionHomeDir(),a=path.normalize(path.join(n,e.body.path));return a.startsWith(n)?(fs.mkdirSync(path.dirname(a),{recursive:!0}),fs.writeFileSync(a,e.body.content,"utf-8"),{success:!0}):t.code(400).send({error:"Invalid path"})}),g.get("/companion/file/versions",{schema:{querystring:zod.z.object({path:zod.z.string(),limit:zod.z.coerce.number().int().positive().max(50).optional(),skip:zod.z.coerce.number().int().min(0).optional()}),response:{200:zod.z.object({versions:zod.z.array(zod.z.object({commit:zod.z.string(),shortCommit:zod.z.string(),subject:zod.z.string(),body:zod.z.string(),authoredAt:zod.z.string()})),hasMore:zod.z.boolean(),nextSkip:zod.z.number()}),404:zod.z.object({error:zod.z.string()})}}},async(e,t)=>{const n=resolveCompanionHomeDir(),a=safeCompanionPath(n,e.query.path);return a&&fs.existsSync(a.absolutePath)?listCompanionFileVersions(n,a.relativePath,{limit:e.query.limit??10,skip:e.query.skip??0}):t.code(404).send({error:"File not found"})}),g.get("/companion/file/diff",{schema:{querystring:zod.z.object({path:zod.z.string(),commit:zod.z.string()}),response:{200:zod.z.object({commit:zod.z.string(),path:zod.z.string(),diff:zod.z.string()}),404:zod.z.object({error:zod.z.string()})}}},async(e,t)=>{const n=resolveCompanionHomeDir(),a=safeCompanionPath(n,e.query.path);return a&&fs.existsSync(a.absolutePath)?{commit:e.query.commit,path:a.relativePath,diff:readCompanionFileDiff(n,a.relativePath,e.query.commit)}:t.code(404).send({error:"File not found"})}),g.get("/companion/memory-events",{schema:{querystring:zod.z.object({after:zod.z.string().optional(),date:zod.z.string().optional()}),response:{200:zod.z.object({after:zod.z.string().optional(),date:zod.z.string().optional(),nextAfter:zod.z.string(),events:zod.z.array(zod.z.object({id:zod.z.string(),createdAt:zod.z.union([zod.z.string(),zod.z.number()]),title:zod.z.string(),summary:zod.z.string(),files:zod.z.array(zod.z.string()),actions:zod.z.array(zod.z.string()).optional(),source:zod.z.string().optional(),trigger:zod.z.string().optional(),commit:zod.z.string().optional()})),hasMore:zod.z.boolean()}),400:zod.z.object({error:zod.z.string()})}}},async(e,t)=>{const n=resolveCompanionHomeDir();if(!e.query.after&&!e.query.date)return t.code(400).send({error:"Use after or date"});return readCompanionMemoryEventsForQuery(n,e.query)||t.code(400).send({error:"Invalid after or date"})}),g.get("/companion/recent-activity",{schema:{querystring:zod.z.object({limit:zod.z.coerce.number().int().positive().max(50).optional()}),response:{200:zod.z.object({chats:zod.z.array(zod.z.object({type:zod.z.literal("chat"),title:zod.z.string(),summary:zod.z.string(),time:zod.z.string(),status:zod.z.string().optional()})),tasks:zod.z.array(zod.z.object({type:zod.z.literal("task"),title:zod.z.string(),summary:zod.z.string(),time:zod.z.string(),status:zod.z.string().optional()})),memories:zod.z.array(zod.z.object({type:zod.z.literal("memory"),title:zod.z.string(),summary:zod.z.string(),time:zod.z.string(),status:zod.z.string().optional()}))})}}},async e=>{const t=resolveCompanionHomeDir(),n=e.query.limit??1,a=path.join(t,"state.json");let s={};if(fs.existsSync(a))try{s=JSON.parse(fs.readFileSync(a,"utf-8"))}catch{s={}}const[i,o,r]=await Promise.all([readRecentCompanionTaskActivity(s,c?.(),n),Promise.resolve(readRecentCompanionChatActivity(s,n)),Promise.resolve(readRecentCompanionMemoryActivity(t,n))]);return{chats:o,tasks:i,memories:r}}),g.get("/companion/config",{schema:{querystring:zod.z.object({recentLimit:zod.z.coerce.number().int().positive().max(50).optional()}),response:{200:zod.z.object({heartbeatIntervalMs:zod.z.number(),heartbeatEnabled:zod.z.boolean(),lastHeartbeatTimestamp:zod.z.string().nullable(),lastHeartbeatDate:zod.z.string().nullable(),lastMaintenanceHeartbeatTimestamp:zod.z.string().nullable(),heartbeatTriggerCount:zod.z.number(),lastInteractionTimestamp:zod.z.string().nullable(),memoryOrganizationEnabled:zod.z.boolean(),memoryOrganizationIntervalHours:zod.z.number(),allowedMemoryOrganizationIntervalHours:zod.z.array(zod.z.number()),lastMemoryOrganizationTimestamp:zod.z.string().nullable(),memoryOrganizationTaskId:zod.z.string().nullable(),heartbeatRecentRecords:zod.z.array(zod.z.object({time:zod.z.string(),summary:zod.z.string(),updated:zod.z.boolean()})),memoryOrganizationRecentRecords:zod.z.array(zod.z.object({time:zod.z.string(),summary:zod.z.string(),updated:zod.z.boolean()}))})}}},async e=>{const t=resolveCompanionHomeDir(),n=e.query.recentLimit??1,a=path.join(t,"state.json");let s=9e5,i=!1,o=null,r=null,c=null,l=0,d=null,p=!1,u=4,m=null,h=null,g={};if(fs.existsSync(a))try{g=JSON.parse(fs.readFileSync(a,"utf-8")),"number"==typeof g.heartbeatIntervalMs&&(s=g.heartbeatIntervalMs),"boolean"==typeof g.heartbeatEnabled&&(i=g.heartbeatEnabled),"string"==typeof g.lastHeartbeatTimestamp&&(o=g.lastHeartbeatTimestamp),"string"==typeof g.lastHeartbeatDate&&(r=g.lastHeartbeatDate),"string"==typeof g.lastMaintenanceHeartbeatTimestamp&&(c=g.lastMaintenanceHeartbeatTimestamp),"number"==typeof g.heartbeatTriggerCount&&(l=g.heartbeatTriggerCount),"string"==typeof g.lastInteractionTimestamp&&(d=g.lastInteractionTimestamp),"boolean"==typeof g.memoryOrganizationEnabled&&(p=g.memoryOrganizationEnabled),u=normalizeMemoryOrganizationIntervalHours(g.memoryOrganizationIntervalHours),"string"==typeof g.lastMemoryOrganizationTimestamp&&(m=g.lastMemoryOrganizationTimestamp),"string"==typeof g.memoryOrganizationTaskId&&(h=g.memoryOrganizationTaskId)}catch{}const f=readCompanionRecentRecords(g,"heartbeat",n),y=readCompanionRecentRecords(g,"memory-organization",n);return{heartbeatIntervalMs:s,heartbeatEnabled:i,lastHeartbeatTimestamp:o,lastHeartbeatDate:r,lastMaintenanceHeartbeatTimestamp:c,heartbeatTriggerCount:l,lastInteractionTimestamp:d,memoryOrganizationEnabled:p,memoryOrganizationIntervalHours:u,allowedMemoryOrganizationIntervalHours:[...ALLOWED_MEMORY_ORGANIZATION_INTERVAL_HOURS],lastMemoryOrganizationTimestamp:m,memoryOrganizationTaskId:h,heartbeatRecentRecords:f,memoryOrganizationRecentRecords:y}}),g.put("/companion/config",{schema:{body:zod.z.object({heartbeatIntervalMs:zod.z.number().optional(),heartbeatEnabled:zod.z.boolean().optional(),memoryOrganizationEnabled:zod.z.boolean().optional(),memoryOrganizationIntervalHours:zod.z.number().optional()}),response:{200:zod.z.object({success:zod.z.boolean()}),400:zod.z.object({error:zod.z.string()})}}},async(t,n)=>{const a=resolveCompanionHomeDir(),s=path.join(a,"state.json");let i={};if(fs.existsSync(s))try{i=JSON.parse(fs.readFileSync(s,"utf-8"))}catch{}const{heartbeatIntervalMs:o,heartbeatEnabled:r,memoryOrganizationEnabled:c,memoryOrganizationIntervalHours:l}=t.body;if(void 0!==o&&(i.heartbeatIntervalMs=o),void 0!==r&&(i.heartbeatEnabled=r),void 0!==c&&(i.memoryOrganizationEnabled=c),void 0!==l){if(!isAllowedMemoryOrganizationIntervalHours(l))return n.code(400).send({error:`memoryOrganizationIntervalHours must be one of: ${ALLOWED_MEMORY_ORGANIZATION_INTERVAL_HOURS.join(", ")}`});i.memoryOrganizationIntervalHours=l}return fs.mkdirSync(path.dirname(s),{recursive:!0}),fs.writeFileSync(s,JSON.stringify(i,null,2),"utf-8"),e.companionScheduler?.reloadStateAndReschedule(),{success:!0}}),g.post("/agent/install",{schema:{body:zod.z.object({agentId:zod.z.string(),gitUrl:zod.z.string(),branch:zod.z.string().optional(),subDir:zod.z.string().optional()}),response:{200:zod.z.object({agentDir:zod.z.string()}),500:zod.z.object({error:zod.z.string()})}}},async(e,t)=>{try{return await installAgentFromGit(e.body)}catch(e){const n=e instanceof Error?e.message:String(e);return t.code(500).send({error:n})}}),g.post("/git-server/bind",{schema:{body:zod.z.object({name:zod.z.string().min(1),baseUrl:zod.z.string().url(),apiUrl:zod.z.string().url(),pat:zod.z.string().min(1),useAsProxy:zod.z.boolean().optional().default(!0)}),response:{200:zod.z.object({success:zod.z.literal(!0),gitServer:GitServerResponseSchema,machineId:zod.z.string(),proxyRegistered:zod.z.boolean(),webhookEndpointPath:zod.z.string(),webhookUrl:zod.z.string().optional(),patConfigured:zod.z.literal(!0),patMeta:zod.z.object({username:zod.z.string(),email:zod.z.string(),lastValidatedAt:zod.z.string(),expiresAt:zod.z.string().nullable().optional()}),webhookSecret:zod.z.string()}),502:zod.z.object({error:zod.z.string()})}}},async(e,t)=>{try{const n=c?.();if(!n)throw new Error("Machine WebSocket is not connected");const a=await bindGitServerWithLocalPat(n,r,{name:e.body.name,baseUrl:e.body.baseUrl,apiUrl:e.body.apiUrl,pat:e.body.pat,useAsProxy:e.body.useAsProxy});return t.send(a)}catch(n){const a=formatApiError(n);return machine.logger.warn(`[GIT SERVER] bind failed: baseUrl=${e.body.baseUrl}, message=${a}`),t.code(502).send({error:a})}}),g.post("/git-server/list",{schema:{response:{200:zod.z.object({gitServers:zod.z.array(GitServerResponseSchema)}),502:zod.z.object({error:zod.z.string()})}}},async(e,t)=>{try{const e=await machineRpc(c?.(),"POST","/v1/git-servers/machine-list",{machineId:r.machineId});return t.send({gitServers:Array.isArray(e)?e:[]})}catch(e){const n=formatApiError(e);return machine.logger.warn(`[GIT SERVER] list failed: message=${n}`),t.code(502).send({error:n})}}),g.post("/git-server/delete",{schema:{body:zod.z.object({gitServerId:zod.z.string().min(1)}),response:{200:zod.z.object({success:zod.z.boolean(),machineId:zod.z.string()}),502:zod.z.object({error:zod.z.string()})}}},async(e,t)=>{try{const n=await machineRpc(c?.(),"POST",`/v1/git-servers/${encodeURIComponent(e.body.gitServerId)}/machine-unlink`,{machineId:r.machineId});return t.send({success:!0,machineId:r.machineId,...n&&"object"==typeof n?n:{}})}catch(n){const a=formatApiError(n);return machine.logger.warn(`[GIT SERVER] delete failed: gitServerId=${e.body.gitServerId}, message=${a}`),t.code(502).send({error:a})}}),g.post("/webhooks/gitlab/:gitServerId",{schema:{params:zod.z.object({gitServerId:zod.z.string()}),body:zod.z.record(zod.z.string(),zod.z.unknown()),response:{200:zod.z.object({status:zod.z.enum(["triggered","ignored","failed"]),eventType:zod.z.string(),eventName:zod.z.string().optional(),eventAction:zod.z.string().optional(),action:zod.z.string().optional(),pipeline:zod.z.unknown().optional(),reason:zod.z.string().optional(),errorMessage:zod.z.string().optional(),errorDetail:zod.z.string().optional(),upstreamStatus:zod.z.number().optional(),triggeredCount:zod.z.number().optional(),failedCount:zod.z.number().optional(),events:zod.z.array(zod.z.object({status:zod.z.enum(["triggered","failed","ignored"]),normalizedEventId:zod.z.string(),eventName:zod.z.string(),eventAction:zod.z.string(),action:zod.z.string(),pipeline:zod.z.unknown().optional(),reason:zod.z.string().optional(),errorMessage:zod.z.string().optional(),errorDetail:zod.z.string().optional(),upstreamStatus:zod.z.number().optional()})).optional()}),400:zod.z.object({error:zod.z.string()}),401:zod.z.object({error:zod.z.string()}),403:zod.z.object({error:zod.z.string()}),404:zod.z.object({error:zod.z.string()}),502:zod.z.object({error:zod.z.string()}),500:zod.z.object({error:zod.z.string()})}}},async(e,t)=>{const n=node_crypto.randomUUID(),a=Date.now(),s=getGitLabEventType(e.body),i=getGitLabWebhookPipelineProjectKey(e.body),o=e.ip||"-",r="string"==typeof e.headers["user-agent"]?e.headers["user-agent"]:"-",l=(s,i)=>{const o=Date.now()-a,r=summarizeGitLabWebhookResponse(i),c=s>=400?"warn":"info";return machine.logger[c](`[GITLAB WEBHOOK] response: hookId=${n}, gitServer=${e.params.gitServerId}, statusCode=${s}, elapsedMs=${o}, ${r}`),t.code(s).send(i)};machine.logger.info(`[GITLAB WEBHOOK] request received: hookId=${n}, gitServer=${e.params.gitServerId}, eventType=${s}, projectKey=${i??"-"}, remote=${o}, userAgent=${r}`);const d=await getGitServerEncryptionKey();if(!d)return l(500,{error:"Git server encryption key not available"});const p=loadGitLabWebhookBridgeSecrets(e.params.gitServerId,d),u=p?.webhookSecret;if(!u)return l(403,{error:`GitLab webhook bridge is not configured for git server ${e.params.gitServerId}`});if(!secureTokenEquals(e.headers["x-gitlab-token"],u))return l(401,{error:"Invalid GitLab webhook token"});const m=getGitLabWebhookDeliveryKey(e.body,getGitLabWebhookDeliveryHeader(e.headers)),h=s;if(reportRepositoryInboxWebhook(e.params.gitServerId,e.body,m,h,c?.()).catch(t=>{const a=t instanceof Error?t.message:String(t);machine.logger.warn(`[GITLAB WEBHOOK] inbox side-channel failed: hookId=${n}, gitServer=${e.params.gitServerId}, message=${a}`)}),!i)return l(200,await triggerPipelineFromGitLabWebhook({gitServerId:e.params.gitServerId,payload:e.body,pat:"",config:{deliveryId:m}}));const g=loadPat(e.params.gitServerId,d);if(!g)return l(403,{error:`No PAT configured for git server ${e.params.gitServerId}`});try{const t=loadGitServerConfig(e.params.gitServerId),a=t?.apiUrl;if(!a)return l(400,{error:`GitLab API URL is not configured for git server ${e.params.gitServerId}`});let o;if(i)if(o=p.projectTriggerTokens?.[i],o)machine.logger.info(`[GITLAB WEBHOOK] pipeline trigger token reused: hookId=${n}, gitServer=${e.params.gitServerId}, projectKey=${i}`);else{const t=getGitLabWebhookProjectLocator(e.body);if(!t)return l(400,{error:"GitLab webhook payload is missing project information"});machine.logger.info(`[GITLAB WEBHOOK] ensuring pipeline trigger token: hookId=${n}, gitServer=${e.params.gitServerId}, projectKey=${i}, mode=create_or_reuse`);const s=new GitLabExecutor(a,g,{gitServerId:e.params.gitServerId}),r=await s.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,saveGitLabWebhookBridgeSecrets(e.params.gitServerId,{webhookSecret:u,projectTriggerTokens:{...p.projectTriggerTokens??{},[i]:o}},d),machine.logger.info(`[GITLAB WEBHOOK] pipeline trigger token stored: hookId=${n}, gitServer=${e.params.gitServerId}, projectKey=${i}`)}return machine.logger.info(`[GITLAB WEBHOOK] triggering pipeline: hookId=${n}, gitServer=${e.params.gitServerId}, eventType=${s}, projectKey=${i??"-"}`),l(200,await triggerPipelineFromGitLabWebhook({gitServerId:e.params.gitServerId,payload:e.body,pat:g,config:{apiUrl:a,triggerToken:o,deliveryId:m}}))}catch(t){const a=t,s="number"==typeof a.status&&a.status>=400&&a.status<600?a.status:500,i="string"==typeof a.message?a.message:t instanceof Error?t.message:"Failed to process GitLab webhook";return machine.logger.warn(`[GITLAB WEBHOOK] failed: hookId=${n}, gitServer=${e.params.gitServerId}, statusCode=${s}, message=${i}`),l(s,{error:i})}}),g.post("/schedule",{schema:{body:zod.z.object({task:zod.z.string(),type:zod.z.enum(["once","recurring"]),due:zod.z.string().optional(),cron:zod.z.string().optional(),timezone:zod.z.string().optional(),timeType:zod.z.enum(["utc","local"]).optional()}),response:{200:zod.z.object({id:zod.z.string(),task:zod.z.string(),type:zod.z.enum(["once","recurring"]),due:zod.z.string().optional(),cron:zod.z.string().optional(),timezone:zod.z.string().optional(),timeType:zod.z.enum(["utc","local"]).optional(),createdAt:zod.z.string()}),400:zod.z.object({error:zod.z.string()}),503:zod.z.object({error:zod.z.string()})}}},async(t,n)=>{const a=e.companionScheduler;if(!a)return n.code(503).send({error:"Companion scheduler not available"});const{task:s,type:i,due:o,cron:r,timezone:c,timeType:l}=t.body;return"once"!==i||o?"recurring"!==i||r?a.addScheduledTask({task:s,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'})}),g.get("/schedule",{schema:{response:{200:zod.z.object({tasks:zod.z.array(zod.z.object({id:zod.z.string(),task:zod.z.string(),type:zod.z.enum(["once","recurring"]),due:zod.z.string().optional(),cron:zod.z.string().optional(),timezone:zod.z.string().optional(),timeType:zod.z.enum(["utc","local"]).optional(),createdAt:zod.z.string()}))}),503:zod.z.object({error:zod.z.string()})}}},async(t,n)=>{const a=e.companionScheduler;return a?{tasks:a.listScheduledTasks()}:n.code(503).send({error:"Companion scheduler not available"})}),g.delete("/schedule/:id",{schema:{params:zod.z.object({id:zod.z.string()}),response:{200:zod.z.object({success:zod.z.boolean()}),404:zod.z.object({error:zod.z.string()}),503:zod.z.object({error:zod.z.string()})}}},async(t,n)=>{const a=e.companionScheduler;return a?a.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"})});const y=t=>e.channelManager||(t.code(503).send({error:"Channel manager not available"}),null);g.options("/channels",async(e,t)=>(f(t),t.send())),g.options("/channels/platforms",async(e,t)=>(f(t),t.send())),g.options("/channels/wechat/login/qrcode",async(e,t)=>(f(t),t.send())),g.options("/channels/wechat/login/qrcode/:qrcode/status",async(e,t)=>(f(t),t.send())),g.options("/channels/:id",async(e,t)=>(f(t),t.send())),g.options("/channels/:id/connect",async(e,t)=>(f(t),t.send())),g.options("/channels/:id/disconnect",async(e,t)=>(f(t),t.send())),g.options("/channels/:id/contacts",async(e,t)=>(f(t),t.send())),g.options("/channels/:id/bindings",async(e,t)=>(f(t),t.send())),g.options("/channels/:id/bindings/:bindingId",async(e,t)=>(f(t),t.send())),g.options("/channels/task-message",async(e,t)=>(f(t),t.send())),g.options("/channels/group-history",async(e,t)=>(f(t),t.send())),g.get("/channels",{schema:{response:{200:zod.z.object({channels:zod.z.array(ChannelConfigSchema)}),503:zod.z.object({error:zod.z.string()})}}},async(e,t)=>{f(t);const n=y(t);if(n)return{channels:n.getChannels()}}),g.get("/channels/platforms",{schema:{response:{200:zod.z.object({platforms:zod.z.array(zod.z.enum(ChannelPlatforms))})}}},async(e,t)=>(f(t),{platforms:[...ChannelPlatforms]})),g.get("/channels/wechat/login/qrcode",{schema:{response:{200:zod.z.object({qrcode:zod.z.string(),qrcodeContent:zod.z.string(),qrcodeTerminal:zod.z.string(),baseUrl:zod.z.string()}),502:zod.z.object({error:zod.z.string()})}}},async(e,t)=>{f(t);try{return await WechatAdapter.createLoginQRCode()}catch(e){const n=e instanceof Error?e.message:String(e);return machine.logger.warn(`[CHANNEL][WECHAT] Failed to create login QR code: ${n}`),t.code(502).send({error:n})}}),g.get("/channels/wechat/login/qrcode/:qrcode/status",{schema:{params:zod.z.object({qrcode:zod.z.string()}),response:{200:zod.z.object({status:zod.z.string(),token:zod.z.string().optional(),baseUrl:zod.z.string().optional(),ilinkBotId:zod.z.string().optional(),ilinkUserId:zod.z.string().optional()}),502:zod.z.object({error:zod.z.string()})}}},async(e,t)=>{f(t);try{return await WechatAdapter.getLoginStatus(e.params.qrcode)}catch(e){const n=e instanceof Error?e.message:String(e);return machine.logger.warn(`[CHANNEL][WECHAT] Failed to get login QR status: ${n}`),t.code(502).send({error:n})}}),g.post("/channels",{schema:{body:AddChannelConfigSchema,response:{200:ChannelConfigSchema,503:zod.z.object({error:zod.z.string()})}}},async(e,t)=>{f(t);const n=y(t);if(n)return n.addChannel(e.body)}),g.delete("/channels/:id",{schema:{params:zod.z.object({id:zod.z.string()}),response:{200:zod.z.object({success:zod.z.boolean()}),404:zod.z.object({error:zod.z.string()}),503:zod.z.object({error:zod.z.string()})}}},async(e,t)=>{f(t);const n=y(t);if(n)return await n.removeChannel(e.params.id)?{success:!0}:t.code(404).send({error:`Channel ${e.params.id} not found`})}),g.post("/channels/:id/connect",{schema:{params:zod.z.object({id:zod.z.string()}),response:{200:ChannelConfigSchema,404:zod.z.object({error:zod.z.string()}),500:zod.z.object({error:zod.z.string()}),503:zod.z.object({error:zod.z.string()})}}},async(e,t)=>{f(t);const n=y(t);if(n)try{return await n.connectChannel(e.params.id)}catch(e){const n=e instanceof Error?e.message:String(e),a=n.includes("not found")?404:500;return t.code(a).send({error:n})}}),g.post("/channels/:id/disconnect",{schema:{params:zod.z.object({id:zod.z.string()}),response:{200:ChannelConfigSchema,404:zod.z.object({error:zod.z.string()}),500:zod.z.object({error:zod.z.string()}),503:zod.z.object({error:zod.z.string()})}}},async(e,t)=>{f(t);const n=y(t);if(n)try{return await n.disconnectChannel(e.params.id,{disable:!0})}catch(e){const n=e instanceof Error?e.message:String(e),a=n.includes("not found")?404:500;return t.code(a).send({error:n})}}),g.get("/channels/:id/contacts",{schema:{params:zod.z.object({id:zod.z.string()}),response:{200:zod.z.object({contacts:zod.z.array(ChannelContactSchema)}),404:zod.z.object({error:zod.z.string()}),500:zod.z.object({error:zod.z.string()}),503:zod.z.object({error:zod.z.string()})}}},async(e,t)=>{f(t);const n=y(t);if(n)try{return{contacts:await n.getContacts(e.params.id)}}catch(e){const n=e instanceof Error?e.message:String(e),a=n.includes("not found")?404:500;return t.code(a).send({error:n})}}),g.get("/channels/:id/bindings",{schema:{params:zod.z.object({id:zod.z.string()}),response:{200:zod.z.object({bindings:zod.z.array(ChannelBindingSchema)}),404:zod.z.object({error:zod.z.string()}),503:zod.z.object({error:zod.z.string()})}}},async(e,t)=>{f(t);const n=y(t);if(n)try{return{bindings:n.getBindings(e.params.id)}}catch(e){const n=e instanceof Error?e.message:String(e);return t.code(404).send({error:n})}}),g.post("/channels/task-message",{schema:{body:zod.z.object({taskId:zod.z.string(),content:zod.z.string().optional(),attachments:zod.z.array(zod.z.object({filePath:zod.z.string(),fileName:zod.z.string().optional(),mimeType:zod.z.string().optional(),kind:zod.z.enum(["auto","image","file","audio","video"]).optional()})).optional(),target:zod.z.object({channelId:zod.z.string(),chatId:zod.z.string()}).optional()}),response:{200:zod.z.object({success:zod.z.boolean()}),404:zod.z.object({error:zod.z.string()}),503:zod.z.object({error:zod.z.string()}),500:zod.z.object({error:zod.z.string()})}}},async(e,t)=>{f(t);const n=y(t);if(n)try{const a={content:e.body.content,attachments:e.body.attachments};return e.body.target?(await n.sendMessageToChannel(e.body.target,a),{success:!0}):await n.sendMessageToTaskChannel(e.body.taskId,a)?{success:!0}:t.code(404).send({error:`No channel binding for task ${e.body.taskId}`})}catch(e){const n=e instanceof Error?e.message:String(e);return t.code(500).send({error:n})}}),g.post("/channels/group-history",{schema:{body:zod.z.object({taskId:zod.z.string(),limit:zod.z.number().int().positive().max(100).optional(),beforeSeq:zod.z.number().int().positive().optional(),afterSeq:zod.z.number().int().nonnegative().optional(),target:zod.z.object({channelId:zod.z.string(),chatId:zod.z.string(),platform:zod.z.string().optional(),chatType:zod.z.string().optional(),chatName:zod.z.string().optional()})}),response:{200:zod.z.object({historyXml:zod.z.string(),hasMoreBefore:zod.z.boolean(),hasMoreAfter:zod.z.boolean()}),400:zod.z.object({error:zod.z.string()}),503:zod.z.object({error:zod.z.string()}),500:zod.z.object({error:zod.z.string()})}}},async(e,t)=>{f(t);const n=y(t);if(n)try{return void 0!==e.body.beforeSeq&&void 0!==e.body.afterSeq?t.code(400).send({error:"Use beforeSeq or afterSeq, not both"}):n.getChannelGroupHistory(e.body.target,{limit:e.body.limit,beforeSeq:e.body.beforeSeq,afterSeq:e.body.afterSeq})}catch(e){const n=e instanceof Error?e.message:String(e),a=n.includes("only available")?400:500;return t.code(a).send({error:n})}}),g.delete("/channels/:id/bindings/:bindingId",{schema:{params:zod.z.object({id:zod.z.string(),bindingId:zod.z.string()}),response:{200:zod.z.object({success:zod.z.boolean()}),404:zod.z.object({error:zod.z.string()}),503:zod.z.object({error:zod.z.string()})}}},async(e,t)=>{f(t);const n=y(t);if(n)try{return n.removeBinding(e.params.id,e.params.bindingId)?{success:!0}:t.code(404).send({error:`Binding ${e.params.bindingId} not found`})}catch(e){const n=e instanceof Error?e.message:String(e);return t.code(404).send({error:n})}}),g.post("/list",{schema:{response:{200:zod.z.object({children:zod.z.array(zod.z.object({startedBy:zod.z.string(),taskId:zod.z.string(),pid:zod.z.number()}))})}}},async()=>({children:t().filter(e=>void 0!==e.taskId).map(e=>({startedBy:e.startedBy,taskId:e.taskId,pid:e.pid}))})),g.post("/stop-session",{schema:{body:zod.z.object({sessionId:zod.z.string()}),response:{200:zod.z.object({success:zod.z.boolean()})}}},async e=>{const{sessionId:t}=e.body;return machine.logger.debug(`[CONTROL SERVER] Stop session request: ${t}`),{success:n(t)}}),g.post("/stop",{schema:{response:{200:zod.z.object({status:zod.z.string()})}}},async()=>(machine.logger.debug("[CONTROL SERVER] Stop daemon request received"),setTimeout(()=>{machine.logger.debug("[CONTROL SERVER] Triggering daemon shutdown"),i()},50),{status:"stopping"})),"127.0.0.1"!==u&&machine.logger.warn(`[CONTROL SERVER] Listening on ${u}; ensure daemon control endpoints are protected by network policy`);const v=e=>new Promise((t,n)=>{h.listen({port:e,host:u},(e,a)=>{e?n(e):t(a)})});(async()=>{let e;try{e=await v(30624)}catch(t){const n=t?.code;if("EADDRINUSE"!==n&&"EACCES"!==n)throw machine.logger.info("[CONTROL SERVER] Failed to start:",t),t;machine.logger.info(`[CONTROL SERVER] Port 30624 unavailable (${n??"error"}), falling back to dynamic port`),e=await v(0)}const t=parseInt(e.split(":").pop());machine.logger.info(`[CONTROL SERVER] Started on port ${t}`),p({port:t,host:u,webhookHost:m,stop:async()=>{await h.close(),machine.logger.info("[CONTROL SERVER] Server stopped")}})})().catch(e=>{throw machine.logger.info("[CONTROL SERVER] Failed to start:",e),e})})}function spawnAgentrixCLI(e,t={}){const n=machine.projectPath(),a=path.join(n,"dist","index.mjs"),s=["--no-warnings","--no-deprecation",a,...e];if(!fs.existsSync(a)){const e=`Entrypoint ${a} does not exist`;throw machine.logger.debug(`[SPAWN Agentrix CLI] ${e}`),new Error(e)}return child_process.spawn(process.execPath,s,t)}const MIME_TYPE_MAP={".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"};function detectMimeType(e){const t=e.toLowerCase();return MIME_TYPE_MAP[t]||"application/octet-stream"}const MIME_TO_EXT={"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"};function extensionFromMimeType(e){return MIME_TO_EXT[e]||""}function extractExtension(e){try{const t=new URL(e),n=path.extname(t.pathname);if(n)return n;const a=t.searchParams.get("filename")||t.searchParams.get("name")||t.searchParams.get("file");if(a){const e=path.extname(a);if(e)return e}return""}catch{return""}}async function downloadFile(e,t,n=!1){try{const a=await fetch(e);if(!a.ok)throw new Error(`Failed to download file: ${a.status} ${a.statusText}`);if(!a.body)throw new Error("Response body is null");const s=extractExtension(e),i=a.headers.get("content-type"),o=i?.split(";")[0].trim()||detectMimeType(s),r=s||extensionFromMimeType(o);let c;if(n)try{const t=new URL(e).pathname,n=path.basename(t);c=n&&path.extname(n)?n:`${node_crypto.randomUUID()}${r||".dat"}`}catch{c=`${node_crypto.randomUUID()}${r||".dat"}`}else c=`${node_crypto.randomUUID()}${r||".dat"}`;const l=path.join(t,c),d=a.body,p=fs.createWriteStream(l);return await promises.pipeline(d,p),{filePath:l,mimeType:o,filename:c}}catch(t){throw new Error(`Failed to download file from ${e}: ${t instanceof Error?t.message:String(t)}`)}}const logger$6=machine.createModuleLogger("undefined"==typeof document?require("url").pathToFileURL(__filename).href:_documentCurrentScript&&"SCRIPT"===_documentCurrentScript.tagName.toUpperCase()&&_documentCurrentScript.src||new URL("index.cjs",document.baseURI).href);async function processAttachments(e,t){const{attachmentsDir:n}=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?processImageBlock(e,n):"document"===e.type&&"url"===e.source?.type&&e.source?.url?processDocumentBlock(e,n):e));return{...e,message:{...e.message,content:a}}}async function processImageBlock(e,t){try{const n=e.source.url;logger$6.info(`image.download.started url=${n}`);const{filePath:a,mimeType:s}=await downloadFile(n,t,!0);return logger$6.info(`image.download.completed filePath=${a}`),{type:"text",text:`Image file: ${a}\nType: ${s}`}}catch(t){return logger$6.error(`image.download.failed error=${t}`),{type:"text",text:`[Image unavailable: failed to download from ${e.source.url}]`}}}async function processDocumentBlock(e,t){try{const n=e.source.url;logger$6.info(`document.download.started url=${n}`);const{filePath:a,mimeType:s,filename:i}=await downloadFile(n,t,!0);return logger$6.info(`document.download.completed filePath=${a}`),{type:"text",text:`Document: ${a}\nTitle: ${e.title||i}\nType: ${s}`}}catch(t){return logger$6.error(`document.download.failed error=${t}`),{type:"text",text:`[Document unavailable: failed to download from ${e.source?.url}]`}}}const AGENTRIX_DEVOPS_AGENT_ID="Agentrix-DevOps",AGENTRIX_DEVOPS_GIT_URL="https://github.com/xmz-ai/agentrix-agent.git",AGENTRIX_DEVOPS_GIT_SUBDIR="agentrix-dev-init",AGENTRIX_DEVOPS_GIT_BRANCH="main";function isAgentrixDevInitEnabled(e){return(e.supportedFeatures??[]).includes(shared.AGENTRIX_DEV_INIT_FEATURE)}function resolveDevOpsLanguage(e){return"zh-Hans"===e.preferredLanguage||`${process.env.AGENTRIX_LANG??""} ${process.env.LANG??""}`.toLowerCase().includes("zh")?"zh-Hans":"en"}function detectAgentrixInitState(e,t={}){const n=t.checkLocalState??!0,a=path.join(e,".agentrix"),s=path.join(a,"env"),i=path.join(s,"init"),o=path.join(i,"state","local"),r=!fs.existsSync(a),c=!fs.existsSync(path.join(s,"README.md")),l=!fs.existsSync(path.join(i,"README.md")),d=!(!n||fs.existsSync(o)&&0!==safeReadDir(o).length);return{needsInit:r||c||l||d,missingAgentrixDir:r,missingEnvReadme:c,missingEnvModeDocs:l,missingLocalInitState:d}}function safeReadDir(e){try{return fs.readdirSync(e)}catch{return[]}}async function ensureAgentrixDevOpsAgent(){const e=path.join(machine.machine.agentrixAgentsHomeDir,"Agentrix-DevOps"),t=path.join(machine.machine.agentrixHomeDir,"tmp","agentrix-agent-devops-init"),n=`${e}.tmp-${Date.now()}`,a=`${e}.backup-${Date.now()}`;fs.mkdirSync(path.join(machine.machine.agentrixHomeDir,"tmp"),{recursive:!0}),fs.existsSync(path.join(t,".git"))?(node_child_process.execFileSync("git",["fetch","--depth=1","origin","main:refs/remotes/origin/main"],{cwd:t,stdio:"pipe"}),node_child_process.execFileSync("git",["checkout","main"],{cwd:t,stdio:"pipe"}),node_child_process.execFileSync("git",["reset","--hard","origin/main"],{cwd:t,stdio:"pipe"})):(fs.rmSync(t,{recursive:!0,force:!0}),node_child_process.execFileSync("git",["clone","--depth=1","--branch","main",AGENTRIX_DEVOPS_GIT_URL,t],{stdio:"pipe"}));const s=path.join(t,"agentrix-dev-init");if(!fs.existsSync(path.join(s,"agent.json")))throw new Error(`Agentrix DevOps agent definition not found at ${s}`);fs.rmSync(n,{recursive:!0,force:!0}),fs.cpSync(s,n,{recursive:!0}),buildAgentPlugins(n);try{fs.existsSync(e)&&fs.renameSync(e,a),fs.renameSync(n,e),fs.rmSync(a,{recursive:!0,force:!0})}catch(t){throw fs.rmSync(e,{recursive:!0,force:!0}),fs.existsSync(a)&&fs.renameSync(a,e),fs.rmSync(n,{recursive:!0,force:!0}),t}return{agentDir:e}}function buildPreInitQuestion(e){return"zh-Hans"===e?{header:"初始化",question:"检测到当前项目尚未完成 Agentrix DevOps 初始化,或缺少本地初始化状态。是否先运行 Agentrix DevOps init,以便后续开发任务可以读取项目环境、启动方式和本地状态?",multiSelect:!1,options:[{label:"先初始化",description:"先运行 Agentrix DevOps init,再继续开发需求"},{label:"跳过,直接继续",description:"不运行初始化,直接开始当前开发任务"}]}:{header:"Init",question:"This project is missing Agentrix DevOps initialization or local init state. Run Agentrix DevOps init first so the development task can read project environment, startup, and local state guidance?",multiSelect:!1,options:[{label:"Initialize first",description:"Run Agentrix DevOps init before the development request"},{label:"Skip and continue",description:"Start the current development task without initialization"}]}}function buildPostInitQuestion(e){return"zh-Hans"===e?{header:"下一步",question:"初始化已经完成,是否继续实现您的需求?如果需要修改,请告诉我。",multiSelect:!1,options:[{label:"继续实现需求",description:"启动新的开发 session 并继续原需求"},{label:"停止任务",description:"停留在当前初始化结果,不启动开发 session"},{label:"输入修改建议",description:"把你的修改建议发送给 Agentrix DevOps init session",additionalInput:{enabled:!0,required:!0,placeholder:"请输入需要 Agentrix DevOps 调整的内容"}}]}:{header:"Next",question:"Initialization is complete. Continue implementing your request, stop, or provide modification suggestions?",multiSelect:!1,options:[{label:"Continue request",description:"Start a fresh development session and continue the original request"},{label:"Stop task",description:"Stay in the initialization result without starting implementation"},{label:"Provide changes",description:"Send modification suggestions to the Agentrix DevOps init session",additionalInput:{enabled:!0,required:!0,placeholder:"Describe what Agentrix DevOps should adjust"}}]}}function parsePostInitDecision(e,t){const n=e.trim();return"zh-Hans"===t?"继续实现需求"===n||"继续"===n?"continue":"输入修改建议"===n||"修改建议"===n?"modify":"停止任务"===n||"停止"===n?"stop":null:"Continue request"===n||"Continue"===n?"continue":"Provide changes"===n||"Modify"===n?"modify":"Stop task"===n||"Stop"===n?"stop":null}function computeOriginalWorkerHistoryStartAfter(e){return null===e?null:Math.max(0,e-1)}function buildDevOpsInitPrompt(e){return["Run Agentrix DevOps initialization for the current project.","You are running as the Agentrix-DevOps agent in a platform-managed pre-initialization worker before the user development request starts.",`User preferred language / ask-user language: ${"zh-Hans"===e?"Chinese (Simplified, zh-Hans)":"English (en)"}. When you need to ask the user questions or produce user-visible completion/status text, use this language preference.`,"The Agentrix platform has already asked the user whether to run this initialization before this prompt was delivered to you.","Check whether `.agentrix` and `.agentrix/env` are already initialized; if initialization already exists, do not overwrite it, only fill missing or stale environment guidance and local initialization state.","Focus on the local development/validation mode, commands, environment variables, authentication state, and safety constraints needed by future development tasks.","Ask the user with the normal Agentrix `ask_user` tool whenever user-answerable information is required.","Maintain project iteration memory and automated testing guidance so future Agentrix development workers can continue with concrete commands and known local constraints.","This is a pre-development initialization flow. Do not assume the platform treats a normal response or turn result as completion.","A normal assistant response, result message, or end of turn is not completion.","When, and only when, you have confirmed initialization is complete, call the `complete_devops_init` Agentrix tool. The platform will ask the user what to do next only after that tool is called.","If the user chooses to stop after initialization, remain available in this Agentrix-DevOps init session.","If the user later says they want to exit init, return to the development agent, continue the original request, or stop staying in the init session, call `complete_devops_init` again so the platform can ask and switch state."].join(" ")}function devOpsStateDir(e,t){return path.join(machine.machine.resolveDataDir(e,t),"devops-init")}function devOpsOriginalInputPath(e,t){return path.join(devOpsStateDir(e,t),"original-input.json")}function devOpsHandoffPath(e,t){return path.join(devOpsStateDir(e,t),"handoff.json")}function saveDevOpsOriginalInput(e){const t=devOpsStateDir(e.userId,e.taskId);fs.mkdirSync(t,{recursive:!0}),fs.writeFileSync(devOpsOriginalInputPath(e.userId,e.taskId),JSON.stringify(e,null,2))}function readDevOpsOriginalInput(e,t){const n=devOpsOriginalInputPath(e,t);return fs.existsSync(n)?JSON.parse(fs.readFileSync(n,"utf-8")):null}function writeDevOpsHandoff(e,t,n){const a=devOpsStateDir(e,t);fs.mkdirSync(a,{recursive:!0}),fs.writeFileSync(devOpsHandoffPath(e,t),JSON.stringify({action:n,createdAt:(new Date).toISOString()},null,2))}function consumeDevOpsHandoff(e,t){const n=devOpsHandoffPath(e,t);if(!fs.existsSync(n))return null;const a=JSON.parse(fs.readFileSync(n,"utf-8"));return fs.unlinkSync(n),a}class TaskWorkerManager{pidToTrackedSession;taskToStartPromise;sandboxPool;channelManager=null;socketClientProvider=null;acceptingNewWorkers=!0;workerStartGateCode=null;workerStartGateMessage=null;drainCallback=null;constructor(e){this.pidToTrackedSession=new Map,this.taskToStartPromise=new Map,this.sandboxPool=e||null}setChannelManager(e){this.channelManager=e}setSocketClientProvider(e){this.socketClientProvider=e}setWorkerStartGate(e,t,n){this.acceptingNewWorkers=e,this.workerStartGateCode=e?null:t??"daemon_control_busy",this.workerStartGateMessage=e?null:n??"Daemon is not accepting new workers"}isAcceptingNewWorkers(){return this.acceptingNewWorkers}setDrainCallback(e){this.drainCallback=e}createWorkerGateAck(e){return this.acceptingNewWorkers?null:{eventId:shared.createEventId(),status:"failed",opCode:e,message:this.workerStartGateMessage??"Daemon is not accepting new workers",data:{errorCode:this.workerStartGateCode??"daemon_control_busy"}}}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 machine.logger.warn(`[SESSION] Missing PID for task ${e}`);machine.logger.info(`[SESSION] Registered task ${e}, PID: ${n}`);const a=this.pidToTrackedSession.get(n);if(!(a&&a.taskId===e||a)){const t={startedBy:"cli",taskId:e,pid:n};this.pidToTrackedSession.set(n,t)}}async decryptTaskMessage(e){if(!e.dataEncryptionKey)return;const t=await machine.machine.getSecretKey();if(!t)return;const n=shared.decryptWithEphemeralKey(shared.decodeBase64(e.dataEncryptionKey),t);if(!n)return void machine.logger.warn("[SESSION] Failed to decrypt data encryption key");if(e.dataEncryptionKey=shared.encodeBase64(n),"task-message"!==e.event)return;const a=e.eventData;if(!a.encryptedMessage)return;const s=shared.decryptSdkMessage(a.encryptedMessage,n);s?e.eventData={...a,message:s,encryptedMessage:void 0}:machine.logger.warn("[SESSION] Failed to decrypt task message")}async persistCreateTaskStart(e){const t=machine.machine.resolveDataDir(e.userId,e.taskId),n=machine.machine.resolveAttachmentsDir(e.userId,e.taskId),a=getTaskDb({dataDir:t,taskId:e.taskId});try{const t=e.eventData;a.saveTaskEvent({eventType:e.event,eventId:t.eventId,eventData:t,taskId:e.taskId,chatId:e.chatId,sequence:t.sequence??0});let s=null;if(t.message){let e=t.message;shared.isSDKUserMessage(e)&&(e=await processAttachments(e,{attachmentsDir:n})),s=a.saveMessage({eventId:t.eventId,message:e,senderType:t.senderType,senderId:t.senderId,senderName:t.senderName}).localSequence}return s}finally{a.close()}}async persistResumeTaskStart(e){const t=machine.machine.resolveDataDir(e.userId,e.taskId),n=machine.machine.resolveAttachmentsDir(e.userId,e.taskId),a=getTaskDb({dataDir:t,taskId:e.taskId}),s=e.eventData.sequence;if(null==s)throw new Error(`Missing resume sequence for task ${e.taskId}`);try{const t=e.eventData;a.saveTaskEvent({eventType:e.event,eventId:t.eventId,eventData:t,taskId:e.taskId,chatId:e.chatId,sequence:s});let i=null;if(t.message){let e=t.message;shared.isSDKUserMessage(e)&&(e=await processAttachments(e,{attachmentsDir:n})),i=a.saveMessage({eventId:t.eventId,message:e,senderType:t.senderType,senderId:t.senderId,senderName:t.senderName}).localSequence}return i}finally{a.close()}}async processTaskMessageAttachments(e){if("task-message"!==e.event)return;const t=e.eventData;if(!t.message||!shared.isSDKUserMessage(t.message))return;const n=machine.machine.resolveAttachmentsDir(e.userId,e.taskId),a=await processAttachments(t.message,{attachmentsDir:n});e.eventData={...t,message:a}}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,a)=>{this.pidToTrackedSession.delete(t.pid),this.sandboxPool&&this.sandboxPool.disposeWorkerSandbox(e.taskId),this.maybeContinueAfterDevOpsInit(e).catch(t=>{machine.logger.error(`[DEVOPS_INIT] Failed to continue original worker for task ${e.taskId} after DevOps worker exit:`,t)}),0===this.pidToTrackedSession.size&&this.drainCallback?.()}),t.on("error",n=>{this.pidToTrackedSession.delete(t.pid),this.sandboxPool&&this.sandboxPool.disposeWorkerSandbox(e.taskId),0===this.pidToTrackedSession.size&&this.drainCallback?.()})}async maybeContinueAfterDevOpsInit(e){const t=consumeDevOpsHandoff(e.userId,e.taskId);t&&(machine.logger.info(`[DEVOPS_INIT] Consumed handoff for task ${e.taskId}, action=${t.action}`),"continue"===t.action&&await this.startOriginalWorkerAfterDevOpsInit(e.userId,e.taskId))}async startOriginalWorkerAfterDevOpsInit(e,t){const n=readDevOpsOriginalInput(e,t);if(!n)return void machine.logger.warn(`[DEVOPS_INIT] Missing original task input for ${t}; cannot continue original worker`);if(machine.logger.info(`[DEVOPS_INIT] Starting original worker for task ${t} after Agentrix DevOps init`),this.syncOriginalWorkerAgentSession(n),"agentSessionId"in n)return void this.restoreOriginalWorkerAfterSlashDevOpsInit(n);let a=null;a=await this.persistCreateTaskStart(n),this.positionOriginalWorkerHistoryCursor(n,a),machine.machine.writeTaskInput(n);const s={eventId:shared.createEventId(),status:"success",opCode:n.eventId};await this.startWorkerInternal(n,"create-task",s)}restoreOriginalWorkerAfterSlashDevOpsInit(e){const t=getTaskDb({dataDir:machine.machine.resolveDataDir(e.userId,e.taskId),taskId:e.taskId});try{const n=t.pageRecentMessages(1).data[0]?.localSequence??0;t.updateAgentLastSequence(e.agentId,n),machine.logger.info(`[DEVOPS_INIT] Restored original worker ${e.agentId} for task ${e.taskId} at sequence ${n}; waiting for the next user message`)}finally{t.close()}machine.machine.writeTaskInput(e)}positionOriginalWorkerHistoryCursor(e,t){if(null===t)return void machine.logger.warn(`[DEVOPS_INIT] Original worker message for task ${e.taskId} has no local sequence; cannot isolate DevOps init history`);const n=getTaskDb({dataDir:machine.machine.resolveDataDir(e.userId,e.taskId),taskId:e.taskId});try{const a=computeOriginalWorkerHistoryStartAfter(t);if(null===a)return;n.updateAgentLastSequence(e.agentId,a),machine.logger.info(`[DEVOPS_INIT] Positioned original worker ${e.agentId} at sequence ${a} for task ${e.taskId}`)}finally{n.close()}}syncOriginalWorkerAgentSession(e){const t=this.socketClientProvider?.();if(t){if("agentSessionId"in e&&e.agentSessionId)return t.send("update-task-agent-session-id",{eventId:shared.createEventId(),taskId:e.taskId,agentSessionId:e.agentSessionId,cwd:e.cwd??e.userCwd}),void machine.logger.info(`[DEVOPS_INIT] Restored original agent session for task ${e.taskId}`);t.send("reset-task-session",{eventId:shared.createEventId(),taskId:e.taskId}),machine.logger.info(`[DEVOPS_INIT] Cleared DevOps init agent session for task ${e.taskId}`)}else machine.logger.warn(`[DEVOPS_INIT] No daemon socket client available to sync task session for ${e.taskId}`)}completeDevOpsInit(e){machine.logger.info(`[DEVOPS_INIT] Completion received for task ${e.taskId}, action=${e.action}`),writeDevOpsHandoff(e.userId,e.taskId,e.action);const t=this.getAliveSessionByTaskId(e.taskId)?.pid;setTimeout(()=>{const n=this.getAliveSessionByTaskId(e.taskId);n&&n.pid===t&&this.stopSession(e.taskId),"continue"===e.action&&this.continueDevOpsInitWhenStopped(e.userId,e.taskId,t).catch(t=>{machine.logger.error(`[DEVOPS_INIT] Failed to continue original worker for task ${e.taskId} after completion signal:`,t)})},100)}startDevOpsInit(e){this.startDevOpsInitAsync(e).catch(t=>{machine.logger.error(`[DEVOPS_INIT] Failed to start slash-command DevOps init for task ${e.taskId}:`,t)})}async startDevOpsInitAsync(e){const t=machine.machine.readTaskInput(e.userId,e.taskId);saveDevOpsOriginalInput(t);const n=await this.buildDevOpsWorkerInput(t,!0);machine.machine.writeTaskInput(n),await this.persistCreateTaskStart(n),this.stopSession(e.taskId),this.startWorkerWhenPreviousStops(n,"create-task")}async startWorkerWhenPreviousStops(e,t){for(let n=0;n<20;n+=1){if(await new Promise(e=>setTimeout(e,250)),this.getAliveSessionByTaskId(e.taskId))continue;const n={eventId:shared.createEventId(),status:"success",opCode:e.eventId};return void await this.startWorkerInternal(e,t,n)}machine.logger.warn(`[DEVOPS_INIT] Timed out waiting to start switched worker for task ${e.taskId}`)}async continueDevOpsInitWhenStopped(e,t,n){for(let a=0;a<20;a+=1){await new Promise(e=>setTimeout(e,250));const a=this.getAliveSessionByTaskId(t);if(a&&a.pid!==n)return void machine.logger.info(`[DEVOPS_INIT] Original worker for task ${t} is already running with PID ${a.pid}`);if(a)continue;const s=consumeDevOpsHandoff(e,t);if(!s)return void machine.logger.info(`[DEVOPS_INIT] Handoff for task ${t} was already consumed`);if(machine.logger.info(`[DEVOPS_INIT] Consumed handoff for task ${t} from completion path, action=${s.action}`),"continue"!==s.action)return;return void await this.startOriginalWorkerAfterDevOpsInit(e,t)}machine.logger.warn(`[DEVOPS_INIT] Timed out waiting to continue original worker for task ${t}`)}shouldLookupChannelReplyTarget(e){const t="task-message"===e.event?e.eventData:null;return"channel"===t?.senderType||"companion"===e.agentType&&"work"===e.taskType&&!e.parentTaskId}resolveChannelReplyTarget(e){return e.channelReplyTarget?e.channelReplyTarget:this.shouldLookupChannelReplyTarget(e)?this.channelManager?.getReplyTargetForTask(e.taskId)??null:null}buildWorkerEnv(e){return{...process.env,...e?{AGENTRIX_CHANNEL_REPLY_TARGET:JSON.stringify(e)}:{}}}async startWorker(e,t){const n={eventId:shared.createEventId(),status:"success",opCode:e.eventId},a=this.createWorkerGateAck(e.eventId);if(a)return machine.logger.warn(`[SESSION] Rejecting ${t} for task ${e.taskId}: ${a.message}`),a;await this.decryptTaskMessage(e),await this.processTaskMessageAttachments(e),"create-task"===t?e=await this.resolveDevOpsInitCreateInput(e):"resume-task"===t&&(e=this.stripStaleDevOpsAgentSession(e)),machine.machine.writeTaskInput(e),"create-task"===t?await this.persistCreateTaskStart(e):await this.persistResumeTaskStart(e);const s=this.taskToStartPromise.get(e.taskId);if(s)return machine.logger.info(`[SESSION] Task ${e.taskId} is already starting, skip duplicate ${t}`),s;const i=this.startWorkerInternal(e,t,n).finally(()=>{this.taskToStartPromise.get(e.taskId)===i&&this.taskToStartPromise.delete(e.taskId)});return this.taskToStartPromise.set(e.taskId,i),i}stripStaleDevOpsAgentSession(e){if("Agentrix-DevOps"===e.agentId||!isAgentrixDevInitEnabled(e))return e;const t=readDevOpsOriginalInput(e.userId,e.taskId);if(!t||"agentSessionId"in t)return e;machine.logger.warn(`[DEVOPS_INIT] Clearing stale DevOps init agentSessionId for resumed original worker on task ${e.taskId}`);const{agentSessionId:n,...a}=e;return this.syncOriginalWorkerAgentSession(a),a}async resolveDevOpsInitCreateInput(e){if(!isAgentrixDevInitEnabled(e)||"Agentrix-DevOps"===e.agentId)return e;if(this.isLocalDirectoryDevOpsTarget(e)){if(!detectAgentrixInitState(machine.machine.resolveProjectCWD(e.userCwd,e.userId,e.taskId),{checkLocalState:!0}).needsInit)return machine.logger.info(`[DEVOPS_INIT] Local project init state complete for task ${e.taskId}; starting original worker`),e}else{if(!this.isCodeRepositoryDevOpsTarget(e))return machine.logger.info(`[DEVOPS_INIT] No project directory or code repository selected for task ${e.taskId}; skipping Agentrix DevOps init`),e;machine.logger.info(`[DEVOPS_INIT] Code repository target selected for task ${e.taskId}; starting Agentrix-DevOps without local init-state precheck`)}saveDevOpsOriginalInput(e);const t=await this.buildDevOpsWorkerInput(e,!1);return machine.logger.info(`[DEVOPS_INIT] Starting Agentrix-DevOps worker before original ${e.agentType}/${e.agentId} worker for task ${e.taskId}`),t}isLocalDirectoryDevOpsTarget(e){return"directory"===e.repositorySourceType&&Boolean(e.userCwd)}isCodeRepositoryDevOpsTarget(e){return"git-server"===e.repositorySourceType&&Boolean(e.repositoryId||e.gitUrl)}async buildDevOpsWorkerInput(e,t){const{agentDir:n}=await ensureAgentrixDevOpsAgent(),a=buildDevOpsInitPrompt(resolveDevOpsLanguage(e)),s=e.eventData,i=this.toCreateTaskInput(e);return{...i,eventId:t?shared.createEventId():i.eventId,agentId:"Agentrix-DevOps",agentType:"claude",agentDir:n,eventData:{...s,eventId:shared.createEventId(),senderType:"system",senderId:"agentrix-devops-init",senderName:"Agentrix DevOps init",message:{uuid:crypto$1.randomUUID(),type:"user",message:{role:"user",content:a},parent_tool_use_id:null,session_id:"new"},encryptedMessage:void 0}}}toCreateTaskInput(e){if(!("agentSessionId"in e))return e;const{agentSessionId:t,...n}=e;return n}async startWorkerInternal(e,t,n){const a=this.createWorkerGateAck(e.eventId);if(a)return machine.logger.warn(`[SESSION] Rejecting ${t} for task ${e.taskId}: ${a.message}`),a;const s=this.getAliveSessionByTaskId(e.taskId);if(s)return machine.logger.info(`[SESSION] Task ${e.taskId} already has worker PID ${s.pid}, skip duplicate ${t}`),n.message=`Worker already running (PID ${s.pid})`,n;const i=machine.machine.resolveProjectCWD(e.userCwd,e.userId,e.taskId),o=["worker","--type",e.agentType||"claude","--started-by","daemon","--task-id",e.taskId,"--user-id",e.userId,"--idle-timeout","120"],r=this.resolveChannelReplyTarget(e),c=this.buildWorkerEnv(r);let l;if(this.sandboxPool?.isEnabled())try{if(!await this.sandboxPool.createWorkerSandbox(e.taskId,e.userId,i))throw new Error("Failed to create sandbox instance");const{projectPath:t}=await Promise.resolve().then(function(){return require("./logger-B5VvgaeC.cjs")}).then(function(e){return e.machine$1}),{join:n}=await import("path"),a=["--no-warnings","--no-deprecation",n(t(),"dist","index.mjs"),...o],s=`"${process.execPath}" ${a.map(e=>`"${e}"`).join(" ")}`,r=await this.sandboxPool.wrapWorkerCommand(e.taskId,s);machine.logger.debug(`[SESSION] Sandboxed command for task ${e.taskId}: ${r}`),l=child_process.spawn(r,{shell:!0,cwd:i,detached:!0,stdio:["ignore","pipe","pipe"],env:c}),machine.logger.info(`[SESSION] Worker started with sandbox, PID: ${l.pid}`)}catch(t){return machine.logger.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 l=spawnAgentrixCLI(o,{cwd:i,detached:!0,stdio:["ignore","pipe","pipe"],env:c}),machine.logger.info(`[SESSION] Worker started without sandbox, PID: ${l.pid}`);return process.env.DEBUG&&(l.stdout?.on("data",e=>{machine.logger.debug(`[Daemon] worker stdout: ${e.toString()}`)}),l.stderr?.on("data",e=>{machine.logger.debug(`[Daemon] worker stderr: ${e.toString()}`)})),l.pid?(this.trackWorkerProcess(e,l),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"),machine.logger.info(`[SESSION] Task ${e} stopped`);const a=setTimeout(()=>{const n=this.pidToTrackedSession.get(t);if(n&&n.taskId===e&&this.isProcessAlive(t))try{process.kill(t,"SIGKILL"),machine.logger.warn(`[SESSION] Task ${e} did not exit after SIGTERM, sent SIGKILL to PID ${t}`)}catch(n){machine.logger.warn(`[SESSION] Failed to force kill task ${e} (PID ${t}):`,n)}},3e3);a.unref?.()}catch(n){machine.logger.warn(`[SESSION] Failed to stop task ${e}:`,n),this.isProcessAlive(t)||this.pidToTrackedSession.delete(t)}return!0}return machine.logger.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(){machine.logger.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){machine.logger.warn(`[SESSION] Failed to stop PID ${e}:`,t)}this.pidToTrackedSession.clear()}async startHivePublishWorker(e){const t={eventId:shared.createEventId(),status:"success",opCode:e.eventId},n=this.createWorkerGateAck(e.eventId);if(n)return machine.logger.warn(`[SESSION] Rejecting hive-publish for task ${e.taskId}: ${n.message}`),n;machine.machine.writeTaskInput(e);try{const n=spawnAgentrixCLI(["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=>{machine.logger.debug(`[HivePublish] worker stdout: ${e.toString()}`)}),n.stderr?.on("data",e=>{machine.logger.debug(`[HivePublish] worker stderr: ${e.toString()}`)})),!n.pid)return t.status="failed",t.message="Failed to start hive-publish worker - no PID",t;machine.logger.info(`[SESSION] Hive publish worker started, PID: ${n.pid}`);const a={taskId:e.taskId,userId:e.userId};return this.trackWorkerProcess(a,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:shared.createEventId(),status:"success",opCode:e.eventId},n=this.createWorkerGateAck(e.eventId);if(n)return machine.logger.warn(`[SESSION] Rejecting hive-install for task ${e.taskId}: ${n.message}`),n;machine.machine.writeTaskInput(e);try{const n=spawnAgentrixCLI(["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=>{machine.logger.debug(`[HiveInstall] worker stdout: ${e.toString()}`)}),n.stderr?.on("data",e=>{machine.logger.debug(`[HiveInstall] worker stderr: ${e.toString()}`)})),!n.pid)return t.status="failed",t.message="Failed to start hive-install worker - no PID",t;machine.logger.info(`[SESSION] Hive install worker started, PID: ${n.pid}`);const a={taskId:e.taskId,userId:e.userId};return this.trackWorkerProcess(a,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:shared.createEventId(),status:"success",opCode:e.eventId},n=this.createWorkerGateAck(e.eventId);if(n)return machine.logger.warn(`[SESSION] Rejecting deployment for task ${e.taskId}: ${n.message}`),n;machine.machine.writeTaskInput(e);try{const n=spawnAgentrixCLI(["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=>{machine.logger.debug(`[Deployment] worker stdout: ${e.toString()}`)}),n.stderr?.on("data",e=>{machine.logger.debug(`[Deployment] worker stderr: ${e.toString()}`)})),!n.pid)return t.status="failed",t.message="Failed to start deployment worker - no PID",t;machine.logger.info(`[SESSION] Deployment worker started, PID: ${n.pid}`);const a={taskId:e.taskId,userId:e.userId};return this.trackWorkerProcess(a,n),t}catch(e){return t.status="failed",t.message=`Failed to start deployment worker: ${e instanceof Error?e.message:String(e)}`,t}}}function setupGracefulShutdown(e){const{processType:t,onShutdownRequest:n,forceExitTimeoutMs:a=3e4}=e,s=`[${t.toUpperCase()}]`;let i,o=!1;const r=new Promise(e=>{i=(t,i)=>{o?machine.logger.debug(`${s} Shutdown already requested; ignoring duplicate request from ${t}`):(o=!0,machine.logger.info(`${s} Requesting shutdown (source: ${t}, errorMessage: ${i})`),n&&n(t,i),setTimeout(()=>process.exit(1),a).unref?.(),e({source:t,errorMessage:i}))}}),c=e=>{process.on(e,()=>{i("os-signal")})};return c("SIGINT"),c("SIGTERM"),process.on("uncaughtException",e=>{machine.logger.info(`${s} FATAL: Uncaught exception`,e),machine.logger.info(`${s} Stack trace: ${e.stack}`),i("exception",e.message)}),process.on("unhandledRejection",e=>{machine.logger.info(`${s} FATAL: Unhandled promise rejection`,e);const t=e instanceof Error?e:new Error(`Unhandled promise rejection: ${e}`);machine.logger.info(`${s} Stack trace: ${t.stack}`),i("exception",t.message)}),process.on("exit",e=>{machine.logger.info(`${s} Process exiting with code: ${e}`)}),{requestShutdown:i,shutdownPromise:r}}class SandboxPool{networkManager=null;workerSandboxes=new Map;settings=null;platform;constructor(){this.platform=platform_js.getPlatform()}async initialize(e){if(this.settings=e,!e.enabled)return machine.logger.info("[SANDBOX] Sandbox disabled via settings"),!1;if(!sandboxRuntime.isSupportedPlatform(this.platform))return machine.logger.warn("[SANDBOX] Platform not supported, sandbox disabled"),!1;try{const t={allowedDomains:[new URL(machine.machine.serverUrl).hostname,...e.network.allowedDomains],deniedDomains:e.network.deniedDomains,allowLocalBinding:!1};return this.networkManager=new sandboxRuntime.NetworkManager,await this.networkManager.initialize(t),machine.logger.info("[SANDBOX] Sandbox pool initialized successfully"),!0}catch(e){throw machine.logger.error("[SANDBOX] Failed to initialize:",e),e}}async createWorkerSandbox(e,t,n){if(!this.networkManager||!this.settings?.enabled)return null;try{const a=machine.machine.resolveUserWorkSpaceDir(t),s=machine.machine.getStatePaths().logsDir,i=this.settings.filesystem||{},o=this.settings.env||{},r={...i,allowWrite:[...i.allowWrite||[],a,n,s]};if("linux"===this.platform&&i.allowRead){const e=path$1.dirname(process.execPath);r.allowRead=[...i.allowRead,e]}const c={filesystem:r,env:o},l=new sandboxRuntime.SandboxManager(this.networkManager,c);return this.workerSandboxes.set(e,l),machine.logger.info(`[SANDBOX] Created sandbox for task ${e}`),l}catch(t){return machine.logger.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 a=await n.wrapWithSandbox(t);return machine.logger.debug(`[SANDBOX] Wrapped command for task ${e}`),a}disposeWorkerSandbox(e){const t=this.workerSandboxes.get(e);t&&(t.dispose(),this.workerSandboxes.delete(e),machine.logger.debug(`[SANDBOX] Disposed sandbox for task ${e}`))}async shutdown(){machine.logger.info("[SANDBOX] Shutting down sandbox pool");for(const[e,t]of this.workerSandboxes.entries())t.dispose(),machine.logger.debug(`[SANDBOX] Disposed sandbox for task ${e}`);this.workerSandboxes.clear(),this.networkManager&&(await this.networkManager.shutdown(),this.networkManager=null,machine.logger.info("[SANDBOX] Network manager shutdown complete"))}isEnabled(){return!0===this.settings?.enabled}}class CompanionBootstrapWatcher{constructor(e,t){this.client=e,this.machineId=t;const n=machine.machine.agentrixAgentsHomeDir,a=path.join(n,"companion"),s=path.join(a,"claude");this.bootstrapPath=path.join(s,"BOOTSTRAP.md"),this.countPath=path.join(a,"BOOTSTRAP.count"),this.stateFilePath=path.join(s,"state.json")}timer=null;intervalMs=18e4;maxAttempts=10;bootstrapPath;countPath;stateFilePath;start(){fs.existsSync(this.bootstrapPath)?this.readCount()>=this.maxAttempts?machine.logger.warn(`[COMPANION BOOTSTRAP] Already reached max attempts (${this.maxAttempts}), not starting watcher`):(machine.logger.info("[COMPANION BOOTSTRAP] BOOTSTRAP.md exists, starting watcher"),this.scheduleNext()):machine.logger.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(!fs.existsSync(this.bootstrapPath))return void machine.logger.info("[COMPANION BOOTSTRAP] BOOTSTRAP.md removed, companion init complete");const e=this.readCount();if(e>=this.maxAttempts)return void machine.logger.warn(`[COMPANION BOOTSTRAP] Max attempts (${this.maxAttempts}) reached, giving up`);const t=this.loadState();if(!t)return machine.logger.warn("[COMPANION BOOTSTRAP] No state.json available, will retry next interval"),void this.scheduleNext();this.writeCount(e+1),machine.logger.info(`[COMPANION BOOTSTRAP] Sending init request (attempt ${e+1}/${this.maxAttempts})`),this.client.send("request-companion-init",{eventId:shared.createEventId(),machineId:t.machineId,agentId:t.agentId,chatId:t.chatId,chatTaskId:t.chatTaskId,userId:t.userId}),this.scheduleNext()}readCount(){try{if(fs.existsSync(this.countPath)){const e=parseInt(fs.readFileSync(this.countPath,"utf-8").trim(),10);return isNaN(e)?0:e}}catch{}return 0}writeCount(e){try{fs.writeFileSync(this.countPath,String(e),"utf-8")}catch(e){machine.logger.warn("[COMPANION BOOTSTRAP] Failed to write BOOTSTRAP.count:",e)}}loadState(){try{if(fs.existsSync(this.stateFilePath)){const e=JSON.parse(fs.readFileSync(this.stateFilePath,"utf-8"));if(e?.agentId&&e?.machineId&&e?.userId&&e?.chatId)return e}}catch{}return null}}function requireString$1(e,t){if("string"!=typeof e||0===e.trim().length)throw new Error(`Lark credential "${t}" is required`);return e}function parseCredentials$1(e){return{appId:requireString$1(e.appId,"appId"),appSecret:requireString$1(e.appSecret,"appSecret")}}function safeJsonParse(e){try{return JSON.parse(e)}catch{return e}}function getTextContent(e){if("string"==typeof e)return e;if(!e||"object"!=typeof e)return;const t=e;return"string"==typeof t.text?t.text:void 0}function normalizeTimestamp(e){if(!e)return(new Date).toISOString();const t=Number(e);if(Number.isFinite(t))return new Date(t>1e10?t:1e3*t).toISOString();const n=new Date(e);return Number.isNaN(n.getTime())?(new Date).toISOString():n.toISOString()}function getLarkUserIdType(e){return e.startsWith("on_")?"union_id":e.startsWith("ou_")?"open_id":"user_id"}function extractSenderName(e){if(!e||"object"!=typeof e)return;const t=e;for(const e of["name","sender_name","user_name","nickname"]){const n=t[e];if("string"==typeof n&&n.trim())return n}}function larkMentionsBot(e,t,n){return!!Array.isArray(e)&&e.some(e=>{if(!e||"object"!=typeof e)return!1;const a=e;if("bot"===("string"==typeof a.mentioned_type?a.mentioned_type.toLowerCase():void 0))return!0;const s=a.id;if(s&&"object"==typeof s){const e=s;return e.open_id===n||e.app_id===t||e.open_id===t||e.user_id===t}return a.app_id===t||a.open_id===t||a.user_id===t})}function formatLarkError(e){const t=e?.response?.status,n=e?.response?.data,a=e?.response?.headers?.["x-tt-logid"]||e?.response?.headers?.["x-request-id"];return[t?`status=${t}`:void 0,n?`data=${JSON.stringify(n)}`:void 0,a?`logId=${a}`:void 0,e?.message||e?.msg||String(e)].filter(Boolean).join(", ")}function encodeLarkResourceKey(e,t,n){return[e,t,n].map(encodeURIComponent).join(":")}function decodeLarkResourceKey(e){const[t,n,a]=e.split(":").map(decodeURIComponent);if(!t||!n||!a)throw new Error("Invalid Lark resource key");return{messageId:t,resourceType:n,fileKey:a}}class LarkAdapter{id;platform="lark";capabilities={sendText:!0,sendImage:!0,sendFile:!0,sendAudio:!1,sendVideo:!1};client;wsClient=null;messageHandler=null;stateHandler=null;connectionState="disconnected";credentials;botOpenId;constructor(e){this.id=e.id,this.credentials=parseCredentials$1(e.credentials),this.client=new lark__namespace.Client({appId:this.credentials.appId,appSecret:this.credentials.appSecret,appType:lark__namespace.AppType.SelfBuild,domain:lark__namespace.Domain.Feishu})}get state(){return this.connectionState}async connect(){if("connected"===this.connectionState||"connecting"===this.connectionState)return;this.setState("connecting"),await this.fetchBotIdentity(),this.wsClient=new lark__namespace.WSClient({appId:this.credentials.appId,appSecret:this.credentials.appSecret,domain:lark__namespace.Domain.Feishu,loggerLevel:lark__namespace.LoggerLevel.info,onReady:()=>{machine.logger.info(`[CHANNEL][LARK] Connected: channel=${this.id}`),this.setState("connected")},onError:e=>{machine.logger.warn(`[CHANNEL][LARK] Connection error: channel=${this.id}, message=${e.message}`),this.setState("error",e)},onReconnecting:()=>{machine.logger.warn(`[CHANNEL][LARK] Reconnecting: channel=${this.id}`),this.setState("connecting")},onReconnected:()=>{machine.logger.info(`[CHANNEL][LARK] Reconnected: channel=${this.id}`),this.setState("connected")}});const e=new lark__namespace.EventDispatcher({}).register({"im.message.receive_v1":async e=>{const t=this.normalizeMessage(e);t&&await(this.messageHandler?.(t))}});try{await this.wsClient.start({eventDispatcher:e})}catch(e){const t=e instanceof Error?e:new Error(String(e));throw this.setState("error",t),t}}async disconnect(){this.wsClient&&(this.wsClient.close({force:!0}),this.wsClient=null),this.setState("disconnected")}async sendMessage(e,t){const n=await this.client.im.message.create({params:{receive_id_type:"chat_id"},data:{receive_id:e,msg_type:"text",content:JSON.stringify({text:t})}});if(n.code&&0!==n.code)throw new Error(n.msg||`Lark sendMessage failed with code ${n.code}`)}async sendChannelMessage(e,t){try{const n=t.content?.trim();n&&await this.sendMessage(e,n);for(const n of t.attachments??[])await this.sendAttachment(e,n)}catch(e){throw new Error(`Lark sendChannelMessage failed: ${formatLarkError(e)}`)}}async sendAttachment(e,t){if("image"===this.resolveOutgoingKind(t)){const n=await this.client.im.image.create({data:{image_type:"message",image:fs.createReadStream(t.filePath)}});if(!n?.image_key)throw new Error("Lark image upload did not return image_key");return void await this.sendRawMessage(e,"image",{image_key:n.image_key})}const n=t.fileName||path.basename(t.filePath),a=await this.client.im.file.create({data:{file_type:this.resolveLarkFileType(n,t.mimeType),file_name:n,file:fs.createReadStream(t.filePath)}});if(!a?.file_key)throw new Error("Lark file upload did not return file_key");await this.sendRawMessage(e,"file",{file_key:a.file_key})}async getChatName(e){try{const t=await this.client.im.chat.get({path:{chat_id:e}});return t.code&&0!==t.code?(machine.logger.warn(`[CHANNEL][LARK] getChatName failed: code=${t.code}, msg=${t.msg}`),e):t.data?.name?t.data.name:e}catch(t){return machine.logger.warn(`[CHANNEL][LARK] Failed to get chat name for ${e}`,t),e}}async getUserName(e){const t=getLarkUserIdType(e);try{const n=await this.client.request({url:"/open-apis/contact/v3/users/basic_batch",method:"POST",params:{user_id_type:t},data:{user_ids:[e]}});if(n.code&&0!==n.code)return machine.logger.warn(`[CHANNEL][LARK] contact.user.basic_batch failed: code=${n.code}, msg=${n.msg}`),e;const a=n.data?.users?.[0];return a?.name||a?.i18n_name?.zh_cn||a?.i18n_name?.en_us||a?.i18n_name?.ja_jp||e}catch(t){return machine.logger.warn(`[CHANNEL][LARK] contact.user.basic_batch failed for ${e}: ${formatLarkError(t)}`),e}}async getContacts(){const e=[];for await(const t of await this.client.im.chat.listWithIterator({params:{page_size:50,sort_type:"ByActiveTimeDesc"}}))for(const n of t?.items??[])n.chat_id&&e.push({id:n.chat_id,name:n.name||n.chat_id,avatar:n.avatar,description:n.description,chatStatus:n.chat_status,external:n.external});return e}async downloadFile(e,t={}){try{const n=decodeLarkResourceKey(e),a=createChannelFilePath(t.fileName||n.fileKey),s=await this.client.im.messageResource.get({path:{message_id:n.messageId,file_key:n.fileKey},params:{type:n.resourceType}});return await s.writeFile(a),a}catch(e){return machine.logger.warn(`[CHANNEL][LARK] Failed to download file: channel=${this.id}, ${formatLarkError(e)}`),null}}onMessage(e){this.messageHandler=e}onStateChange(e){this.stateHandler=e}setState(e,t){this.connectionState=e,this.stateHandler?.(e,t)}async sendRawMessage(e,t,n){const a=await this.client.im.message.create({params:{receive_id_type:"chat_id"},data:{receive_id:e,msg_type:t,content:JSON.stringify(n)}});if(a.code&&0!==a.code)throw new Error(a.msg||`Lark send ${t} failed with code ${a.code}`)}async fetchBotIdentity(){try{const e=await this.client.request({url:"/open-apis/bot/v3/info",method:"GET"});if(e.code&&0!==e.code)return void machine.logger.warn(`[CHANNEL][LARK] bot identity lookup failed: code=${e.code}, msg=${e.msg}`);this.botOpenId=e.bot?.open_id}catch(e){machine.logger.warn(`[CHANNEL][LARK] bot identity lookup failed: ${formatLarkError(e)}`)}}resolveOutgoingKind(e){return"image"===e.kind?"image":"auto"!==e.kind&&e.kind?"file":e.mimeType?.startsWith("image/")?"image":"file"}resolveLarkFileType(e,t){const n=path.extname(e).toLowerCase().replace(/^\./,"");return"pdf"===n||"application/pdf"===t?"pdf":["doc","docx"].includes(n)?"doc":["xls","xlsx","csv"].includes(n)?"xls":["ppt","pptx"].includes(n)?"ppt":"mp4"===n||"video/mp4"===t?"mp4":"opus"===n||"audio/opus"===t?"opus":"stream"}normalizeMessage(e){const t=e?.message;if(!t?.message_id||!t?.chat_id)return machine.logger.warn(`[CHANNEL][LARK] Ignoring malformed message event: channel=${this.id}`),null;const n=safeJsonParse(t.content??""),a=n&&"object"==typeof n?n:{},s=t.message_type,i="string"==typeof a.file_key?a.file_key:void 0,o="string"==typeof a.image_key?a.image_key:void 0,r=larkMentionsBot(t.mentions,this.credentials.appId,this.botOpenId);return{id:t.message_id,channelId:this.id,platform:"lark",chatId:t.chat_id,chatType:t.chat_type,senderId:e?.sender?.sender_id?.open_id??e?.sender?.sender_id?.user_id??e?.sender?.sender_id?.union_id,senderType:e?.sender?.sender_type,senderName:extractSenderName(e?.sender),type:"image"===s?"image":"file"===s?"file":"audio"===s?"voice":"text",text:getTextContent(n),fileKey:i?encodeLarkResourceKey(t.message_id,"audio"===s?"audio":"file",i):void 0,fileName:"string"==typeof a.file_name?a.file_name:void 0,imageKey:o?encodeLarkResourceKey(t.message_id,"image",o):void 0,mentionedBot:r,replyToBot:!1,triggered:r,rawContent:n,timestamp:normalizeTimestamp(t.create_time??e?.create_time??e?.ts),raw:e}}}const API_BASE_URL="https://api.telegram.org",POLL_TIMEOUT_SECONDS=30,REQUEST_TIMEOUT_MS=4e4,INITIAL_RETRY_DELAY_MS=1e3,MAX_RETRY_DELAY_MS=3e4;function requireString(e,t){if("string"!=typeof e||0===e.trim().length)throw new Error(`Telegram credential "${t}" is required`);return e.trim()}function optionalString(e){return"string"==typeof e&&e.trim().length>0?e.trim():void 0}function parseCredentials(e){const t=optionalString(e.token)??optionalString(e.botToken)??optionalString(e.bot_token);return{token:t||requireString(t,"token")}}function formatTelegramName(e){return[e.first_name,e.last_name].filter(Boolean).join(" ").trim()||(e.username?`@${e.username}`:void 0)}function normalizeChatType(e){return"private"===e?"p2p":"group"===e||"supergroup"===e?"group":e}function inferMessageType(e){return e.photo?.length?"image":e.document?"file":e.voice?"voice":"text"}function getImageKey(e){return e.photo?.[e.photo.length-1]?.file_id}class TelegramAdapter{id;platform="telegram";capabilities={sendText:!0,sendImage:!0,sendFile:!0,sendAudio:!1,sendVideo:!1};messageHandler=null;stateHandler=null;connectionState="disconnected";credentials;polling=!1;pollController=null;pollPromise=null;retryTimer=null;resolveRetrySleep=null;retryDelayMs=1e3;offset;botUser=null;constructor(e){this.id=e.id,this.credentials=parseCredentials(e.credentials)}get state(){return this.connectionState}async connect(){"connected"!==this.connectionState&&"connecting"!==this.connectionState&&(this.setState("connecting"),this.botUser=await this.request("getMe",{},{timeoutMs:4e4}),this.polling=!0,this.retryDelayMs=1e3,this.pollPromise=this.pollLoop(),this.setState("connected"),machine.logger.info(`[CHANNEL][TELEGRAM] Connected: channel=${this.id}`))}async disconnect(){this.polling=!1,this.retryTimer&&(clearTimeout(this.retryTimer),this.retryTimer=null,this.resolveRetrySleep?.()),this.resolveRetrySleep=null,this.pollController?.abort(),this.pollController=null,await(this.pollPromise?.catch(()=>{})),this.pollPromise=null,this.setState("disconnected")}async sendMessage(e,t){await this.request("sendMessage",{chat_id:e,text:t},{timeoutMs:4e4})}async sendChannelMessage(e,t){const n=t.attachments??[],a=t.content?.trim();if(0===n.length)return void(a&&await this.sendMessage(e,a));const s=1===n.length?a:void 0;a&&!s&&await this.sendMessage(e,a);for(let t=0;t<n.length;t+=1)await this.sendAttachment(e,n[t],0===t?s:void 0)}async sendAttachment(e,t,n){const a=this.resolveOutgoingKind(t),s="image"===a?"sendPhoto":"sendDocument",i="image"===a?"photo":"document",o=t.fileName||path.basename(t.filePath),r=await promises$1.readFile(t.filePath),c=new FormData;c.append("chat_id",e),c.append(i,new Blob([r],{type:t.mimeType||"application/octet-stream"}),o),n&&c.append("caption",n),await this.requestForm(s,c,{timeoutMs:4e4})}async getContacts(){return[]}async downloadFile(e,t={}){try{const n=await this.request("getFile",{file_id:e},{timeoutMs:4e4});if(!n.file_path)throw new Error("Telegram getFile response is missing file_path");const a=t.fileName||path.basename(n.file_path);return await downloadUrlToChannelFile(`${API_BASE_URL}/file/bot${this.credentials.token}/${n.file_path}`,a)}catch(t){return machine.logger.warn(`[CHANNEL][TELEGRAM] Failed to download file: channel=${this.id}, fileKey=${e}`,t),null}}async getChatName(e){try{const t=await this.request("getChat",{chat_id:e},{timeoutMs:4e4});return t.title||formatTelegramName(t)||t.username||e}catch(t){return machine.logger.warn(`[CHANNEL][TELEGRAM] Failed to get chat name for ${e}`,t),e}}async getUserName(e){try{const t=await this.request("getChat",{chat_id:e},{timeoutMs:4e4});return formatTelegramName(t)||t.username||e}catch(t){return machine.logger.warn(`[CHANNEL][TELEGRAM] Failed to get user name for ${e}`,t),e}}onMessage(e){this.messageHandler=e}onStateChange(e){this.stateHandler=e}setState(e,t){this.connectionState=e,this.stateHandler?.(e,t)}async pollLoop(){for(;this.polling;)try{const e=await this.request("getUpdates",{offset:this.offset,timeout:30,allowed_updates:["message"]},{timeoutMs:4e4,isPoll:!0});this.retryDelayMs=1e3,"connected"!==this.connectionState&&this.setState("connected");for(const t of e){this.offset=Math.max(this.offset??0,t.update_id+1);const e=this.normalizeMessage(t);e&&await(this.messageHandler?.(e))}}catch(e){if(!this.polling)break;if(this.isAbortError(e))continue;const t=e instanceof Error?e:new Error(String(e));machine.logger.warn(`[CHANNEL][TELEGRAM] Poll failed: channel=${this.id}, message=${t.message}`),this.setState("error",t),await this.sleepWithCancel(this.retryDelayMs),this.retryDelayMs=Math.min(2*this.retryDelayMs,3e4),this.polling&&this.setState("connecting")}}async request(e,t,n){const a=new AbortController;n.isPoll&&(this.pollController=a);const s=setTimeout(()=>a.abort(),n.timeoutMs);try{const n=await fetch(`${API_BASE_URL}/bot${this.credentials.token}/${e}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t),signal:a.signal}),s=await n.json().catch(()=>({}));if(!n.ok||!s.ok){const e=s.error_code?`code=${s.error_code}`:void 0,t=s.description||`HTTP ${n.status}`;throw new Error([e,t].filter(Boolean).join(", "))}if(void 0===s.result)throw new Error(`Telegram ${e} response is missing result`);return s.result}finally{clearTimeout(s),n.isPoll&&this.pollController===a&&(this.pollController=null)}}async requestForm(e,t,n){const a=new AbortController,s=setTimeout(()=>a.abort(),n.timeoutMs);try{const n=await fetch(`${API_BASE_URL}/bot${this.credentials.token}/${e}`,{method:"POST",body:t,signal:a.signal}),s=await n.json().catch(()=>({}));if(!n.ok||!s.ok){const e=s.error_code?`code=${s.error_code}`:void 0,t=s.description||`HTTP ${n.status}`;throw new Error([e,t].filter(Boolean).join(", "))}if(void 0===s.result)throw new Error(`Telegram ${e} response is missing result`);return s.result}finally{clearTimeout(s)}}resolveOutgoingKind(e){return"image"===e.kind?"image":"auto"!==e.kind&&e.kind?"file":e.mimeType?.startsWith("image/")?"image":"file"}sleepWithCancel(e){return new Promise(t=>{this.resolveRetrySleep=t,this.retryTimer=setTimeout(()=>{this.retryTimer=null,this.resolveRetrySleep=null,t()},e)})}isAbortError(e){return e instanceof Error&&"AbortError"===e.name}isTriggeredMessage(e){const t=this.botUser?.id,n=this.botUser?.username?.toLowerCase(),a=e.text??e.caption??"",s=e.text?e.entities:e.caption_entities,i=Boolean(void 0!==t&&e.reply_to_message?.from?.id===t);let o=!1;if(n){o=a.toLowerCase().includes(`@${n}`);for(const e of s??[]){if("mention"!==e.type&&"bot_command"!==e.type)continue;const t=a.slice(e.offset,e.offset+e.length).toLowerCase();if(t===`@${n}`||t.endsWith(`@${n}`)){o=!0;break}}}return{mentionedBot:o,replyToBot:i,triggered:o||i}}normalizeMessage(e){const t=e.message;if(!t?.chat?.id||!t.message_id)return machine.logger.warn(`[CHANNEL][TELEGRAM] Ignoring malformed message event: channel=${this.id}`),null;const n=String(t.chat.id),a=void 0===t.from?.id?void 0:String(t.from.id),s=this.isTriggeredMessage(t);return{id:String(t.message_id||e.update_id||node_crypto.randomUUID()),channelId:this.id,platform:"telegram",chatId:n,chatType:normalizeChatType(t.chat.type),senderId:a,senderName:t.from?formatTelegramName(t.from):void 0,type:inferMessageType(t),text:t.text??t.caption,fileKey:t.document?.file_id??t.voice?.file_id,fileName:t.document?.file_name,imageKey:getImageKey(t),mentionedBot:s.mentionedBot,replyToBot:s.replyToBot,triggered:s.triggered,rawContent:t.text??t.caption??t.photo??t.document??t.voice,timestamp:new Date(1e3*t.date).toISOString(),raw:e}}}function formatHistoryMessage(e){const t=buildHistoryMessageParts(e);return t?{type:"user",message:{role:"user",content:[{type:"text",text:`<msg ${buildAttributes({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 formatHistoryMessageXml(e){const t=buildHistoryMessageParts(e);return t?`<msg ${buildAttributes({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 buildAttributes(e){return Object.entries(e).filter(([,e])=>void 0!==e&&""!==e).map(([e,t])=>`${e}="${escapeXmlAttr(t)}"`).join(" ")}function escapeXmlAttr(e){return e.replaceAll("&","&amp;").replaceAll('"',"&quot;").replaceAll("<","&lt;").replaceAll(">","&gt;")}function formatHistoryXml(e){const t=[];for(const n of e){const e=formatHistoryMessageXml(n);e&&t.push(e)}return t.join("\n")}function formatAskUserMessage(e){return`Ask user: ${e.questions.map((e,t)=>{const n=e.options?.map(e=>e.label).filter(Boolean),a=n&&n.length>0?` options: ${n.join(", ")}`:"";return`Q${t+1}[${e.header}] ${e.question}${a}`}).join(" | ")}`}function formatAskUserResponse(e){const t=e.status?` status=${e.status}`:"",n=e.reason?` reason=${e.reason}`:"",a=e.answers?.length?e.answers.join(", "):"no answers",s=e.details?.filter(Boolean).join(" | ");return`Ask user response:${t}${n} answers: ${a}${s?` details: ${s}`:""}`}function buildHistoryMessageParts(e){const{text:t,nonTextBlocks:n}=formatMessageParts(e.message);return t?{seq:e.localSequence,at:e.createdAt,senderType:e.senderType,senderId:e.senderId,senderName:e.senderName,text:t,nonTextBlocks:n}:null}function formatMessageParts(e){return shared.isAskUserMessage(e)?{text:formatAskUserMessage(e),nonTextBlocks:[]}:shared.isAskUserResponseMessage(e)?{text:formatAskUserResponse(e),nonTextBlocks:[]}:shared.isSDKMessage(e)?formatSdkMessageParts(e):{text:"",nonTextBlocks:[]}}function formatSdkMessageParts(e){switch(e.type){case"user":case"assistant":return splitContentBlocks(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:[]}}function splitContentBlocks(e){if("string"==typeof e)return{text:e,nonTextBlocks:[]};if(Array.isArray(e)){const t=[],n=[];for(const a of e)"text"!==a.type||"string"!=typeof a.text?n.push(a):t.push(a.text);return{text:t.join("\n"),nonTextBlocks:n}}return{text:"",nonTextBlocks:[]}}function decodeMachineAesKey(e){if(!e.machineAesKey)return null;try{const t=shared.decodeBase64(e.machineAesKey);return 32===t.length?t:null}catch{return null}}async function createChannelTaskEncryptionPayload(e){if(!e.secret)return null;const t=decodeMachineAesKey(e);if(!t)return null;const n=await shared.createKeyPair(e.secret),a=shared.generateAESKey();return{taskDataKey:a,dataEncryptionKey:shared.encodeBase64(shared.encryptWithEphemeralKey(a,n.publicKey)),ownerEncryptedDataKey:shared.encodeBase64(shared.encryptAES(shared.encodeBase64(a),t))}}const RECONNECT_DELAY_MS=3e4,ATTACHMENT_BUFFER_TIMEOUT_MS=5e3,GROUP_HISTORY_CONTEXT_LIMIT=30,GROUP_HISTORY_TOOL_DEFAULT_LIMIT=30,GROUP_HISTORY_TOOL_MAX_LIMIT=100,GROUP_HISTORY_TRIGGER_SCAN_LIMIT=500;class ChannelManager{constructor(e,t){this.client=e,this.machineId=t,this.stateFilePath=path.join(machine.machine.agentrixHomeDir,"channels","state.json"),this.groupHistoryFilePath=path.join(machine.machine.agentrixHomeDir,"channels","group-history"),this.loadState()}stateFilePath;groupHistoryFilePath;adapters=new Map;reconnectTimers=new Map;pendingMessages=new Map;store={version:1,channels:[],bindings:[]};taskDataKeyCache=new Map;stopping=!1;createTaskLocks=new Map;async start(){this.loadState();const e=this.store.channels.filter(e=>e.enabled);for(const t of e)try{await this.connectChannel(t.id)}catch(e){machine.logger.warn(`[CHANNEL] Failed to auto-connect channel ${t.id}`,e)}machine.logger.info(`[CHANNEL] Manager started: machineId=${this.machineId}, channels=${this.store.channels.length}, enabled=${e.length}`)}async stop(){this.stopping=!0;for(const e of this.reconnectTimers.values())clearTimeout(e);this.reconnectTimers.clear();for(const e of this.pendingMessages.values())clearTimeout(e.timer);this.pendingMessages.clear();for(const e of this.adapters.values())await e.disconnect().catch(t=>{machine.logger.warn(`[CHANNEL] Failed to disconnect channel ${e.id}`,t)});this.adapters.clear(),machine.logger.info("[CHANNEL] Manager stopped")}getChannels(){return this.loadState(),this.store.channels.map(e=>({...e,credentials:this.redactCredentials(e.credentials)}))}addChannel(e){this.loadState();const t=(new Date).toISOString(),n={id:node_crypto.randomUUID(),platform:e.platform,name:e.name,credentials:e.credentials,enabled:e.enabled??!1,connectionState:"disconnected",createdAt:t,updatedAt:t};return this.store.channels.push(n),this.saveState(),machine.logger.info(`[CHANNEL] Added channel: id=${n.id}, platform=${n.platform}`),{...n,credentials:this.redactCredentials(n.credentials)}}async removeChannel(e){this.loadState();const t=this.store.channels.findIndex(t=>t.id===e);return-1!==t&&(await this.disconnectChannel(e,{disable:!0}).catch(()=>{}),this.store.channels.splice(t,1),this.store.bindings=this.store.bindings.filter(t=>t.channelId!==e),this.saveState(),machine.logger.info(`[CHANNEL] Removed channel: id=${e}`),!0)}async connectChannel(e){this.loadState();const t=this.requireChannel(e);let n;this.clearReconnect(e),this.updateChannel(e,{enabled:!0,connectionState:"connecting",lastError:void 0});try{const a=this.adapters.get(e);a&&"disconnected"!==a.state&&(await a.disconnect().catch(t=>{machine.logger.warn(`[CHANNEL] Failed to reset adapter before reconnect: channel=${e}`,t)}),this.adapters.delete(e),this.clearReconnect(e)),n=this.getOrCreateAdapter(t),await n.connect()}catch(t){const n=t instanceof Error?t.message:String(t);throw this.updateChannel(e,{connectionState:"error",lastError:n}),t}return this.updateChannel(e,{enabled:!0,connectionState:n.state,lastConnectedAt:"connected"===n.state?(new Date).toISOString():t.lastConnectedAt,lastError:"error"===n.state?"Connection failed":void 0}),this.getChannel(e)}async disconnectChannel(e,t={}){this.loadState(),this.requireChannel(e),this.clearReconnect(e),t.disable&&this.updateChannel(e,{enabled:!1});const n=this.adapters.get(e);return n&&(await n.disconnect(),this.adapters.delete(e)),this.updateChannel(e,{enabled:!t.disable&&this.requireChannel(e).enabled,connectionState:"disconnected",lastDisconnectedAt:(new Date).toISOString()}),this.getChannel(e)}async getContacts(e){this.loadState();const t=this.requireChannel(e);return this.getOrCreateAdapter(t).getContacts()}getBindings(e){return this.loadState(),this.requireChannel(e),this.store.bindings.filter(t=>t.channelId===e)}async sendMessageToTaskChannel(e,t){this.loadState();const n=this.getReplyTargetForTask(e);return n?(await this.sendMessageToChannel(n,t),machine.logger.info(`[CHANNEL] Sent task ${e} reply to ${n.channelId}/${n.chatId}`),!0):(machine.logger.debug(`[CHANNEL] No channel binding for task ${e}`),!1)}getReplyTargetForTask(e){this.loadState();const t=this.store.bindings.find(t=>t.taskId===e);if(!t)return null;const n=this.store.channels.find(e=>e.id===t.channelId);return{channelId:t.channelId,chatId:t.chatId,...n?.platform?{platform:n.platform}:{},...t.chatName?{chatName:t.chatName}:{}}}async sendMessageToChannel(e,t){const n=this.getOrCreateAdapter(this.requireChannel(e.channelId));"connected"!==n.state&&await this.connectChannel(e.channelId);const a="string"==typeof t?{content:t}:t,s=a.content?.trim(),i=a.attachments??[];if(!s&&0===i.length)throw new Error("Channel message requires content or attachments");const o=i.map(e=>({...e,kind:this.resolveAttachmentKind(e)}));for(const e of o)if(!this.isAttachmentKindSupported(n,e.kind))throw new Error(`Channel platform ${n.platform} does not support sending ${e.kind} attachments`);if(o.length>0){if(!n.sendChannelMessage)throw new Error(`Channel platform ${n.platform} does not support outgoing attachment messages`);await n.sendChannelMessage(e.chatId,{content:a.content,attachments:o})}else n.sendChannelMessage?await n.sendChannelMessage(e.chatId,{content:a.content}):await n.sendMessage(e.chatId,a.content??"")}getChannelGroupHistory(e,t={}){if("group"!==e.chatType?.toLowerCase())throw new Error("Channel group history is only available for external group chats");const n=Math.max(1,Math.min(t.limit??30,100)),a=this.buildGroupHistoryRef(e),s=this.openGroupHistoryDb(a);try{const i="number"==typeof t.beforeSeq?s.pageMessagesBefore(t.beforeSeq,n):"number"==typeof t.afterSeq?s.pageMessagesAfter(t.afterSeq,n):s.pageRecentMessages(n);return{historyXml:this.formatExternalGroupHistoryXml(a,i.data,e.chatName||e.chatId,{markTriggered:!1}),hasMoreBefore:"number"!=typeof t.afterSeq&&i.hasMore,hasMoreAfter:"number"==typeof t.afterSeq&&i.hasMore}}finally{s.close()}}removeBinding(e,t){this.loadState(),this.requireChannel(e);const n=this.store.bindings.findIndex(n=>n.channelId===e&&n.id===t);return-1!==n&&(this.store.bindings.splice(n,1),this.saveState(),machine.logger.info(`[CHANNEL] Removed binding: channel=${e}, binding=${t}`),!0)}getChannel(e){const t=this.requireChannel(e);return{...t,credentials:this.redactCredentials(t.credentials)}}getOrCreateAdapter(e){const t=this.adapters.get(e.id);if(t)return t;const n=this.createAdapter(e);return n.onMessage(e=>this.routeMessage(e)),n.onStateChange?.((t,n)=>this.handleAdapterState(e.id,t,n)),this.adapters.set(e.id,n),n}createAdapter(e){if("lark"===e.platform)return new LarkAdapter({id:e.id,credentials:e.credentials});if("wechat"===e.platform)return new WechatAdapter({id:e.id,credentials:e.credentials});if("telegram"===e.platform)return new TelegramAdapter({id:e.id,credentials:e.credentials});throw new Error(`Unsupported channel platform: ${e.platform}`)}resolveAttachmentKind(e){return e.kind&&"auto"!==e.kind?e.kind:e.mimeType?.startsWith("image/")?"image":e.mimeType?.startsWith("audio/")?"audio":e.mimeType?.startsWith("video/")?"video":"file"}isAttachmentKindSupported(e,t){const n=e.capabilities;return!n||("image"===t?!0===n.sendImage||!0===n.sendFile:"audio"===t?!0===n.sendAudio||!0===n.sendFile:"video"===t&&!0===n.sendVideo||!0===n.sendFile)}async routeMessage(e){machine.logger.info(`[CHANNEL] routeMessage raw: ${JSON.stringify(e)}`);const t=await this.downloadMessageAttachments(e),n=this.getPendingMessageKey(t);if(this.isAttachmentOnlyMessage(t))return void this.bufferPendingMessage(n,t);const a=this.takePendingMessages(n),s=a.length>0?this.mergePendingMessages(a,t):t;await this.routeRoutableMessage(s)}async routeRoutableMessage(e){this.loadState();let t=e;if(this.isGroupMessage(e)){if(await this.saveGroupHistoryMessage(e),!this.isGroupMessageTriggered(e))return void machine.logger.info(`[CHANNEL] Stored passive group message only: channel=${e.channelId}, chat=${e.chatId}, message=${e.id}`);const n=await this.resolveChatName(e),a=this.loadRecentGroupHistory(e,30);t=this.injectExternalGroupHistory(e,a,n)}const{binding:n,isNew:a}=await this.getOrCreateBindingForMessage(t);machine.logger.info(`[CHANNEL] routeMessage: isNew=${a}, taskId=${n.taskId}`),a||await this.forwardMessageToTask(t,n)}async flushPendingMessages(e){const t=this.takePendingMessages(e);for(const e of t)await this.routeRoutableMessage(e)}bufferPendingMessage(e,t){const n=this.pendingMessages.get(e);n&&clearTimeout(n.timer);const a=setTimeout(()=>{this.flushPendingMessages(e).catch(t=>{machine.logger.warn(`[CHANNEL] Failed to flush pending attachment messages: key=${e}`,t)})},5e3);this.pendingMessages.set(e,{messages:[...n?.messages??[],t],timer:a}),machine.logger.info(`[CHANNEL] Buffered attachment-only message: key=${e}, count=${(n?.messages.length??0)+1}`)}takePendingMessages(e){const t=this.pendingMessages.get(e);return t?(clearTimeout(t.timer),this.pendingMessages.delete(e),t.messages):[]}mergePendingMessages(e,t){const n=[...e.flatMap(e=>e.attachmentPaths??[]),...t.attachmentPaths??[]];return{...t,attachmentPaths:n,mentionedBot:t.mentionedBot||e.some(e=>e.mentionedBot),replyToBot:t.replyToBot||e.some(e=>e.replyToBot),triggered:t.triggered||e.some(e=>e.triggered),rawContent:{pendingMessages:e,textMessage:t.rawContent}}}isGroupMessage(e){return"group"===e.chatType?.toLowerCase()}isGroupMessageTriggered(e){return!0===e.mentionedBot||!0===e.replyToBot||!0===e.triggered}async saveGroupHistoryMessage(e){const t=this.openGroupHistoryDb(e);try{const n=await this.resolveGroupMessageSenderName(e);t.saveMessage({eventId:this.getGroupHistoryEventId(e),message:this.buildGroupHistorySdkMessage(e),senderType:"channel",senderId:e.senderId||"channel-user",senderName:n})}finally{t.close()}}loadRecentGroupHistory(e,t){const n=this.openGroupHistoryDb(e);try{const a=this.getGroupHistoryEventId(e),s=n.pageRecentMessages(500).data,i=s.findIndex(e=>e.eventId===a),o=i>=0?s.slice(0,i+1):s,r=this.findPreviousTriggerIndex(o,a),c=r>=0?r+1:0;return o.slice(c).slice(-t)}finally{n.close()}}injectExternalGroupHistory(e,t,n){return{...e,text:this.formatExternalGroupHistoryXml(e,t,n)}}formatExternalGroupHistoryXml(e,t,n,a={markTriggered:!0}){const s=[`<external_group_history ${[`platform="${this.escapeXmlAttribute(e.platform)}"`,`chatName="${this.escapeXmlAttribute(n)}"`,`chatId="${this.escapeXmlAttribute(e.chatId)}"`].join(" ")}>`];return t.forEach((t,n)=>{const i=buildAttributes({seq:t.localSequence.toString(),id:t.eventId,at:t.createdAt,senderType:t.senderType,senderId:t.senderId,senderName:t.senderName,mentionedBot:this.getHistoryEntryTriggerFlags(t).mentionedBot?"true":void 0,replyToBot:this.getHistoryEntryTriggerFlags(t).replyToBot?"true":void 0,triggered:!1===a.markTriggered?void 0:t.eventId===this.getGroupHistoryEventId(e)?"true":void 0});s.push(` <msg ${i}>`),s.push(` ${this.escapeXmlText(this.formatHistoryMessageContent(t))}`),s.push(" </msg>")}),s.push("</external_group_history>"),s.join("\n")}formatHistoryMessageContent(e){const t=e.message;if(!t||"object"!=typeof t||"user"!==t.type)return"[non-text message]";const n=t.message.content;return"string"==typeof n?n.trim()||"[non-text message]":Array.isArray(n)&&n.filter(e=>e&&"object"==typeof e&&"text"===e.type&&"string"==typeof e.text).map(e=>e.text).join("\n\n").trim()||"[non-text message]"}buildGroupHistorySdkMessage(e){const t=e.attachmentPaths?.length?`[attachments: ${e.attachmentPaths.join(", ")}]`:void 0;return{type:"user",message:{role:"user",content:[e.text?.trim(),t,e.text?.trim()||t?void 0:`[${e.type}]`].filter(Boolean).join("\n\n")},parent_tool_use_id:null,session_id:"",__channelGroupHistory:{mentionedBot:!0===e.mentionedBot,replyToBot:!0===e.replyToBot,triggered:this.isGroupMessageTriggered(e)}}}async resolveGroupMessageSenderName(e){if(e.senderName?.trim())return e.senderName.trim();const t=e.senderId?.trim(),n=this.adapters.get(e.channelId);if(t&&n?.getUserName)try{const e=await n.getUserName(t);if(e&&e!==t)return e}catch(n){machine.logger.debug(`[CHANNEL] Failed to resolve group sender name: channel=${e.channelId}, sender=${t}`,n)}return t||`${e.platform}:${e.chatId}`}getHistoryEntryTriggerFlags(e){const t=e.message.__channelGroupHistory;if(!t||"object"!=typeof t)return{mentionedBot:!1,replyToBot:!1,triggered:!1};const n=t;return{mentionedBot:!0===n.mentionedBot,replyToBot:!0===n.replyToBot,triggered:!0===n.triggered}}isTriggeredHistoryEntry(e){const t=this.getHistoryEntryTriggerFlags(e);return t.triggered||t.mentionedBot||t.replyToBot}findPreviousTriggerIndex(e,t){for(let n=e.length-1;n>=0;n-=1){const a=e[n];if(a.eventId!==t&&this.isTriggeredHistoryEntry(a))return n}return-1}openGroupHistoryDb(e){const t=this.getGroupHistoryDataDir(e);return fs.existsSync(t)||fs.mkdirSync(t,{recursive:!0}),getTaskDb({dataDir:t,taskId:this.getGroupHistoryTaskId(e)})}getGroupHistoryDataDir(e){return path.join(this.groupHistoryFilePath,this.encodePathPart(e.channelId),this.encodePathPart(e.chatId))}getGroupHistoryTaskId(e){return`channel-group:${e.channelId}:${e.chatId}`}getGroupHistoryEventId(e){return`channel-group:${e.channelId}:${e.chatId}:${e.id}`}buildGroupHistoryRef(e){const t="telegram"===e.platform||"wechat"===e.platform||"lark"===e.platform?e.platform:"lark";return{id:"__history_page__",channelId:e.channelId,platform:t,chatId:e.chatId,chatType:e.chatType,type:"text",timestamp:(new Date).toISOString()}}encodePathPart(e){return Buffer.from(e).toString("base64url")}escapeXmlText(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}escapeXmlAttribute(e){return this.escapeXmlText(e).replace(/"/g,"&quot;").replace(/'/g,"&apos;")}getPendingMessageKey(e){return`${e.channelId}:${e.chatId}`}isAttachmentOnlyMessage(e){const t="string"==typeof e.text&&e.text.trim().length>0,n=Boolean(e.fileKey||e.imageKey||e.attachmentPaths?.length);return!t&&n&&("image"===e.type||"file"===e.type)}async downloadMessageAttachments(e){const t=this.adapters.get(e.channelId);if(!t?.downloadFile)return e;const n=[e.imageKey,e.fileKey].filter(e=>Boolean(e)),a=[...new Set(n)];if(0===a.length)return e;const s=[];for(const n of a){const a=await t.downloadFile(n,{fileName:e.fileName});a&&(machine.logger.info(`[CHANNEL] Downloaded attachment: channel=${e.channelId}, chat=${e.chatId}, path=${a}`),s.push(a))}return s.length>0?{...e,attachmentPaths:[...e.attachmentPaths??[],...s]}:e}async forwardMessageToTask(e,t){if(machine.logger.info(`[CHANNEL] Message from ${e.platform} chat ${e.chatId} → task ${t.taskId}`),!this.client.connected)return void machine.logger.debug(`[CHANNEL] Socket not connected, cannot forward message to task ${t.taskId}`);if(t.taskId.startsWith("pending-"))return void machine.logger.warn(`[CHANNEL] Task ${t.taskId} is pending, skipping message forward`);const n=this.readCompanionState(),a=n?.chatId||t.taskId,s=await this.getTaskDataKeyForTask(t.taskId);if(!s)return void machine.logger.warn(`[CHANNEL] Missing task data key, skipping encrypted channel message forward: task=${t.taskId}`);const{plainMessage:i,encryptedMessage:o}=await this.buildEncryptedMessage(e,s);this.client.send("task-message",{eventId:shared.createEventId(),taskId:t.taskId,chatId:a,from:"machine",message:i,encryptedMessage:o,messageType:"text",senderType:"channel",senderId:e.senderId||"channel-user",senderName:e.senderName||`${e.platform}:${e.chatId}`,channelReplyTarget:{channelId:e.channelId,chatId:e.chatId,platform:e.platform,chatType:e.chatType,chatName:t.chatName}}),machine.logger.info(`[CHANNEL] Forwarded message to task ${t.taskId}`)}async buildEncryptedMessage(e,t){const n=e.attachmentPaths??[],a=n.length>0?`[User sent the following attachments: ${n.join(", ")}]`:void 0,s={type:"user",message:{role:"user",content:[a,e.text||(a?void 0:`[${e.type}]`)].filter(Boolean).join("\n\n")}};let i,o=s;if(t)try{i=shared.encryptSdkMessage(s,t),o=void 0}catch(e){machine.logger.warn("[CHANNEL] Failed to encrypt message, sending plaintext",e)}return{plainMessage:o,encryptedMessage:i}}async getOrCreateBindingForMessage(e){const t=this.store.bindings.find(t=>t.channelId===e.channelId&&t.chatId===e.chatId);if(t&&!this.isPendingTaskId(t.taskId))return{binding:t,isNew:!1};t&&(this.store.bindings=this.store.bindings.filter(e=>e.id!==t.id),this.saveState(),machine.logger.warn(`[CHANNEL] Removed pending binding before retry: channel=${t.channelId}, chat=${t.chatId}, task=${t.taskId}`));const n=await this.resolveChatName(e),a=await this.createTaskForChat(e,n),s=(new Date).toISOString(),i={id:node_crypto.randomUUID(),channelId:e.channelId,chatId:e.chatId,taskId:a,chatName:n,createdAt:s,updatedAt:s};return this.isPendingTaskId(a)?(machine.logger.warn(`[CHANNEL] Task creation did not complete; not persisting pending binding: channel=${e.channelId}, chat=${e.chatId}, task=${a}`),{binding:i,isNew:!0}):(this.store.bindings.push(i),this.saveState(),machine.logger.info(`[CHANNEL] Auto-created binding: channel=${e.channelId}, chat=${e.chatId}, task=${a}`),{binding:i,isNew:!0})}isPendingTaskId(e){return e.startsWith("pending-")}async createTaskForChat(e,t){const n=this.createTaskLocks.get(e.chatId);if(n)return n;const a=this.doCreateTaskForChat(e,t);this.createTaskLocks.set(e.chatId,a);try{return await a}finally{this.createTaskLocks.delete(e.chatId)}}async doCreateTaskForChat(e,t){const n=this.readCompanionState();if(!n)return machine.logger.error("[CHANNEL] Cannot create task: companion not registered"),`pending-no-companion-${node_crypto.randomUUID()}`;if(!this.client.connected)return machine.logger.warn("[CHANNEL] Socket not connected, cannot create task via API"),`pending-offline-${node_crypto.randomUUID()}`;const a=await this.createChannelTaskEncryptionPayload();if(!a)return machine.logger.error("[CHANNEL] Cannot create encrypted channel task: missing local machine encryption credentials"),`pending-encryption-unavailable-${node_crypto.randomUUID()}`;const{plainMessage:s,encryptedMessage:i}=await this.buildEncryptedMessage(e,a.taskDataKey);try{const o=await this.client.sendWithAck("channel-task-create",{eventId:shared.createEventId(),userId:n.userId,chatId:n.chatId,agentId:n.agentId,machineId:n.machineId,customTitle:"wechat"===e.platform?"wechat bot":`${e.platform}/${t}`,taskType:"work",supportedFeatures:["sub-task"],taskAgentIds:[n.agentId],dataEncryptionKey:a.dataEncryptionKey,ownerEncryptedDataKey:a.ownerEncryptedDataKey,message:s,encryptedMessage:i,senderType:"channel",senderId:e.senderId||"channel-user",senderName:e.senderName||`${e.platform}:${e.chatId}`,channelReplyTarget:{channelId:e.channelId,chatId:e.chatId,platform:e.platform,chatType:e.chatType,chatName:t}});return"success"===o?.status&&o.taskId?(this.taskDataKeyCache.set(o.taskId,a.taskDataKey),machine.logger.info(`[CHANNEL] Created task ${o.taskId} for chat ${e.chatId}`),o.taskId):(machine.logger.error(`[CHANNEL] API task creation failed: ${o?.message||"unknown"}`),`pending-api-error-${node_crypto.randomUUID()}`)}catch(e){return machine.logger.error("[CHANNEL] Failed to create task via API",e),`pending-error-${node_crypto.randomUUID()}`}}async resolveChatName(e){try{machine.logger.info(`[CHANNEL] resolveChatName: chatType=${e.chatType}, senderId=${e.senderId}, channelId=${e.channelId}`);const t=this.adapters.get(e.channelId),n="p2p"===e.chatType?.toLowerCase();if(n){if(e.senderName)return e.senderName;if(e.senderId&&t?.getUserName){const n=await t.getUserName(e.senderId);if(machine.logger.info(`[CHANNEL] resolveChatName: getUserName returned "${n}"`),n&&n!==e.senderId)return n}}if(t?.getChatName){const n=await t.getChatName(e.chatId);if(machine.logger.info(`[CHANNEL] resolveChatName: getChatName returned "${n}"`),n&&n!==e.chatId)return n}return!n&&e.senderName?e.senderName:e.senderId||e.chatId}catch(t){return machine.logger.warn(`[CHANNEL] Failed to resolve chat name for ${e.chatId}: ${t?.message||String(t)}`),e.senderName||e.senderId||e.chatId}}async createChannelTaskEncryptionPayload(){const e=await machine.machine.readCredentials();if(!e?.secret)return machine.logger.warn("[CHANNEL] Missing machine secret; cannot create encrypted channel task key"),null;return await createChannelTaskEncryptionPayload(e)||(machine.logger.warn("[CHANNEL] Missing machineAesKey in credentials; rebind this machine before creating encrypted channel tasks"),null)}async getTaskDataKeyForTask(e){const t=this.taskDataKeyCache.get(e);if(t)return t;if(!this.client.connected)return machine.logger.debug(`[CHANNEL] Socket not connected, cannot fetch encryption key for task ${e}`),null;try{const t=await this.client.sendWithAck("get-task-encryption-keys",{eventId:shared.createEventId(),taskId:e});if("success"===t?.status&&t.dataEncryptionKey){const n=await machine.machine.getSecretKey();if(!n)return machine.logger.warn(`[CHANNEL] Missing machine secret key while decrypting task key: task=${e}`),null;const a=shared.decryptWithEphemeralKey(shared.decodeBase64(t.dataEncryptionKey),n);return a&&32===a.length?(this.taskDataKeyCache.set(e,a),a):(machine.logger.warn(`[CHANNEL] Failed to decrypt valid task data key: task=${e}`),null)}machine.logger.warn(`[CHANNEL] Failed to fetch encryption keys for task ${e}: ${t?.message||"unknown"}`)}catch(t){machine.logger.warn(`[CHANNEL] Error fetching encryption keys for task ${e}`,t)}return null}readCompanionState(){const e=path.join(machine.machine.agentrixAgentsHomeDir,"companion","claude","state.json");if(!fs.existsSync(e))return machine.logger.warn("[CHANNEL] Companion state.json not found"),null;try{const t=JSON.parse(fs.readFileSync(e,"utf-8"));return t.userId&&t.agentId&&t.chatId&&t.machineId?{userId:t.userId,agentId:t.agentId,chatId:t.chatId,machineId:t.machineId}:(machine.logger.warn("[CHANNEL] Companion state.json missing required fields"),null)}catch(e){return machine.logger.warn("[CHANNEL] Failed to read companion state.json",e),null}}handleAdapterState(e,t,n){this.loadState();const a=this.store.channels.find(t=>t.id===e);a&&(this.updateChannel(e,{connectionState:t,lastConnectedAt:"connected"===t?(new Date).toISOString():a.lastConnectedAt,lastDisconnectedAt:"disconnected"===t?(new Date).toISOString():a.lastDisconnectedAt,lastError:n?.message}),this.stopping||"disconnected"!==t&&"error"!==t||!a.enabled||this.scheduleReconnect(e))}scheduleReconnect(e){if(this.reconnectTimers.has(e))return;const t=setTimeout(()=>{this.reconnectTimers.delete(e),this.connectChannel(e).catch(t=>{machine.logger.warn(`[CHANNEL] Reconnect failed: channel=${e}`,t),this.scheduleReconnect(e)})},3e4);this.reconnectTimers.set(e,t),machine.logger.info(`[CHANNEL] Scheduled reconnect: channel=${e}, delayMs=30000`)}clearReconnect(e){const t=this.reconnectTimers.get(e);t&&(clearTimeout(t),this.reconnectTimers.delete(e))}requireChannel(e){const t=this.store.channels.find(t=>t.id===e);if(!t)throw new Error(`Channel ${e} not found`);return t}updateChannel(e,t){const n=this.requireChannel(e);Object.assign(n,t,{updatedAt:(new Date).toISOString()}),this.saveState()}loadState(){try{if(!fs.existsSync(this.stateFilePath))return void(this.store={version:1,channels:[],bindings:[]});const e=JSON.parse(fs.readFileSync(this.stateFilePath,"utf-8"));this.store=ChannelStoreSchema.parse(e),(e.companionDataEncryptionKey||e.companionOwnerEncryptedDataKey||e.companionKeyMachineId||e.companionKeyChatId)&&this.saveState()}catch(e){machine.logger.warn("[CHANNEL] Failed to load channel state; using empty state",e),this.store={version:1,channels:[],bindings:[]}}}saveState(){const e=path.dirname(this.stateFilePath);fs.existsSync(e)||fs.mkdirSync(e,{recursive:!0}),fs.writeFileSync(this.stateFilePath,JSON.stringify(this.store,null,2),"utf-8")}redactCredentials(e){return Object.fromEntries(Object.entries(e).map(([e,t])=>[e,"string"==typeof t&&t.length>0?"********":t]))}}function getInstalledCliVersion(){try{const e=path$1.join(machine.projectPath(),"package.json"),t=JSON.parse(fs$1.readFileSync(e,"utf-8"));if("string"==typeof t.version&&t.version.trim().length>0)return t.version}catch{}return"0.0.0"}function getUpgradeLockPath(){return path$1.join(path$1.dirname(machine.machine.getStatePaths().daemonStateFile),"upgrade.lock")}function isProcessRunning$2(e){try{return process.kill(e,0),!0}catch{return!1}}function tryAcquireUpgradeLock(){const e=getUpgradeLockPath();if(fs$1.existsSync(e))try{const t=fs$1.readFileSync(e,"utf-8"),n=JSON.parse(t);"number"!=typeof n.pid||isProcessRunning$2(n.pid)||fs$1.unlinkSync(e)}catch{fs$1.unlinkSync(e)}try{const t=fs$1.openSync(e,"wx");fs$1.writeFileSync(t,JSON.stringify({pid:process.pid,createdAt:(new Date).toISOString()})),fs$1.closeSync(t)}catch{return null}return{release:()=>{try{const t=fs$1.readFileSync(e,"utf-8");JSON.parse(t).pid===process.pid&&fs$1.unlinkSync(e)}catch{}}}}async function checkForUpgrades(){const e=getInstalledCliVersion();try{const t=child_process.execSync("npm view @agentrix/cli version",{encoding:"utf-8",stdio:["pipe","pipe","pipe"],timeout:5e3}).trim();return{hasUpgrade:compareVersions(t,e)>0,currentVersion:e,latestVersion:t}}catch(t){return{hasUpgrade:!1,currentVersion:e,latestVersion:null}}}async function installLatestCli(e){await new Promise((t,n)=>{const a=child_process.spawn("npm",["install","-g","@agentrix/cli@latest"],{stdio:e,env:process.env});a.on("error",n),a.on("exit",e=>{0!==e?n(new Error(`npm install exited with code ${e??"unknown"}`)):t()})})}async function executeCliUpgrade(e,t={}){const n=tryAcquireUpgradeLock();if(!n)return{status:"busy",message:"CLI upgrade already in progress"};try{const n=e??await checkForUpgrades();if(!n.hasUpgrade)return{status:"already_latest",currentVersion:n.currentVersion,latestVersion:n.latestVersion};try{return await installLatestCli(t.stdio??"inherit"),{status:"upgraded",fromVersion:n.currentVersion,toVersion:n.latestVersion??"latest"}}catch(e){return{status:"failed",currentVersion:n.currentVersion,latestVersion:n.latestVersion,error:e instanceof Error?e.message:String(e)}}}finally{n.release()}}function compareVersions(e,t){const n=e.split(".").map(Number),a=t.split(".").map(Number);for(let e=0;e<Math.max(n.length,a.length);e++){const t=n[e]||0,s=a[e]||0;if(t>s)return 1;if(t<s)return-1}return 0}async function performAutoUpgrade(e){try{if(console.log(""),e||(console.log(chalk.blue("🔄 Checking for upgrades...")),e=await checkForUpgrades()),!e.hasUpgrade)return console.log(chalk.green("✓ Already on latest version")),console.log(""),!0;console.log(chalk.blue(`🔄 Upgrading from ${e.currentVersion} to ${e.latestVersion}...`));const t=await executeCliUpgrade(e,{stdio:"inherit"});if("busy"===t.status)return console.log(chalk.yellow(`⚠️ ${t.message}`)),!1;if("failed"===t.status)throw new Error(t.error);return console.log(chalk.green("✓ Upgrade complete")),console.log(""),!0}catch(e){return console.log(""),console.log(chalk.yellow("⚠️ CLI upgrade failed")),console.log(chalk.dim(" You can upgrade manually with: npm install -g @agentrix/cli@latest")),console.log(""),!1}}const execFileAsync$3=node_util.promisify(node_child_process.execFile),TASK_LOG_PATTERN$1=/^task-(.+)\.log(?:\.\d+)?(?:\.gz)?$/;function toProtocolRelative(e,t){return path.relative(e,t).split(path.sep).join("/")}function normalizeProtocolRelative(e){const t=e.trim().replace(/\\/g,"/");if(!t||t.includes("\0")||t.startsWith("/"))return null;const n=t.split("/").filter(Boolean);return 0===n.length||n.some(e=>"."===e||".."===e)?null:n.join("/")}async function resolveSafeRelativePath(e,t){const n=normalizeProtocolRelative(t);if(!n)return null;const a=await promises$1.realpath(e),s=path.resolve(a,...n.split("/"));if(s!==a&&!s.startsWith(a+path.sep))return null;if(!fs.existsSync(s))return{relativePath:n,absolutePath:s};const i=await promises$1.realpath(s);return i===a||i.startsWith(a+path.sep)?{relativePath:n,absolutePath:s}:null}async function getPathSize(e){let t=0;const n=[e];for(;n.length>0;){const e=n.pop();let a,s;try{a=await promises$1.lstat(e)}catch{continue}if(t+=a.size,a.isDirectory()&&!a.isSymbolicLink())try{s=await promises$1.opendir(e);for await(const t of s)n.push(path.join(e,t.name))}catch{continue}}return t}function readWorkspaceStateForTask(e,t){const n=path.join(machine.machine.agentrixWorkspaceHomeDir,"users",e,t,"data"),a=path.join(n,"workspace.json");if(fs.existsSync(a))try{return JSON.parse(fs.readFileSync(a,"utf-8"))}catch{return null}const s=path.join(n,"cwd.txt");if(!fs.existsSync(s))return null;try{const e=fs.readFileSync(s,"utf-8").trim();return e?{initialized:!0,initializedAt:new Date(fs.statSync(s).mtimeMs).toISOString(),cwd:e}:null}catch{return null}}function listWorkspaceTasks(){const e=machine.machine.agentrixWorkspaceHomeDir,t=path.join(e,"users");if(!fs.existsSync(t))return[];const n=[];for(const e of fs.readdirSync(t,{withFileTypes:!0})){if(!e.isDirectory())continue;const a=e.name,s=path.join(t,a);for(const e of fs.readdirSync(s,{withFileTypes:!0})){if(!e.isDirectory())continue;const t=e.name,i=path.join(s,t);n.push({userId:a,taskId:t,taskDir:i,projectDir:path.join(i,"project"),dataDir:path.join(i,"data"),state:readWorkspaceStateForTask(a,t)})}}return n}function isDirectUserDirectoryWorkspace(e){return"directory"===e?.repositorySourceType&&(!0===e.forceUserCwd||!1===e.useWorktree)}function makeStorageItem(e){const t=e.relativePath??toProtocolRelative(machine.machine.agentrixHomeDir,e.absolutePath);return{id:e.id,kind:e.kind,label:e.label,relativePath:t,pathDisplay:t,bytes:e.bytes,reclaimable:e.reclaimable,defaultSelected:e.defaultSelected??e.reclaimable,deleteMode:e.deleteMode,reasonCode:e.reasonCode,reason:e.reason,childrenSummary:e.childrenSummary}}async function findGitCommonDir(e){try{const{stdout:t}=await execFileAsync$3("git",["-C",e,"rev-parse","--path-format=absolute","--git-common-dir"],{windowsHide:!0}),n=t.trim();return n?n.endsWith(`${path.sep}.git`)?path.dirname(n):n:null}catch{return null}}async function getRegisteredWorktreeMainRepo(e){const t=await findGitCommonDir(e);if(!t)return null;try{const n=await listWorktrees(t),a=fs.realpathSync(e);return n.some(e=>{try{return fs.realpathSync(e.path)===a&&!e.isMain}catch{return!1}})?t:null}catch{return null}}function findWorkspaceForRelativePath(e){const t=e.split("/");if(t.length<4||"workspaces"!==t[0]||"users"!==t[1])return null;const[,,n,a]=t,s=path.join(machine.machine.agentrixWorkspaceHomeDir,"users",n,a);return{userId:n,taskId:a,taskDir:s,projectDir:path.join(s,"project"),dataDir:path.join(s,"data"),state:readWorkspaceStateForTask(n,a)}}function parseTaskIdFromLogRelativePath(e){const t=e.split("/");return"logs"!==t[0]?null:TASK_LOG_PATTERN$1.exec(t[t.length-1])?.[1]??null}async function planCleanItem(e,t){const n=await resolveSafeRelativePath(machine.machine.agentrixHomeDir,e);if(!n)return{relativePath:e,releasable:!1,reasonCode:"invalid_path",message:"Path must stay inside the Agentrix home directory"};const{relativePath:a,absolutePath:s}=n;if(!fs.existsSync(s))return{relativePath:a,absolutePath:s,releasable:!1,reasonCode:"missing",message:"Path no longer exists"};const i=a.split("/")[0];if("logs"===i){const e=parseTaskIdFromLogRelativePath(a);return e&&t.has(e)?{relativePath:a,absolutePath:s,releasable:!1,reasonCode:"active_task",message:"Task is currently running"}:{relativePath:a,absolutePath:s,kind:"logs",method:"rm",releasable:!0}}if("tmp"===i)return{relativePath:a,absolutePath:s,kind:"tmp",method:"rm",releasable:!0};if("repos"===i)return 4===a.split("/").length?{relativePath:a,absolutePath:s,kind:"repos",method:"rm",releasable:!0}:{relativePath:a,absolutePath:s,releasable:!1,reasonCode:"unsupported_repo_path",message:"Only repository-level paths are cleanable"};if("workspaces"!==i)return{relativePath:a,absolutePath:s,releasable:!1,reasonCode:"protected_area",message:"This Agentrix area is not cleanable"};const o=findWorkspaceForRelativePath(a);if(!o)return{relativePath:a,absolutePath:s,releasable:!1,reasonCode:"unsupported_workspace_path",message:"Only task project and task data paths are cleanable"};if(t.has(o.taskId))return{relativePath:a,absolutePath:s,releasable:!1,reasonCode:"active_task",message:"Task is currently running"};if(isDirectUserDirectoryWorkspace(o.state))return{relativePath:a,absolutePath:s,releasable:!1,reasonCode:"user_directory",message:"This task uses a user-owned directory"};const r=a.split("/").slice(4).join("/");if("project"===r){const e=await getRegisteredWorktreeMainRepo(s);return e?{relativePath:a,absolutePath:s,kind:"workspaces",method:"remove-worktree",releasable:!0,workspace:o,mainRepoDir:e}:{relativePath:a,absolutePath:s,kind:"workspaces",method:"rm-stale-directory",releasable:!0,workspace:o}}return"data"===r?{relativePath:a,absolutePath:s,kind:"workspaces",method:"rm",releasable:!0,workspace:o}:{relativePath:a,absolutePath:s,releasable:!1,reasonCode:"unsupported_workspace_path",message:"Only task project and task data paths are cleanable"}}async function executeCleanPlan(e){const t=await getPathSize(e.absolutePath);if("remove-worktree"===e.method){if(!e.mainRepoDir)throw new Error("Missing main repository for worktree removal");await removeWorktree(e.mainRepoDir,e.absolutePath,!0)}else{const t=fs.lstatSync(e.absolutePath);t.isDirectory()&&!t.isSymbolicLink()?await promises$1.rm(e.absolutePath,{recursive:!0,force:!1}):await promises$1.unlink(e.absolutePath)}return t}function removePathBestEffort(e){try{fs.statSync(e).isDirectory()?fs.rmSync(e,{recursive:!0,force:!0}):fs.unlinkSync(e)}catch{}}function validateDirectory(e){try{if(!fs$1.statSync(e).isDirectory())return{ok:!1,status:"missing",error:"Path is not a directory"};try{fs$1.accessSync(e,fs$1.constants.R_OK|fs$1.constants.W_OK)}catch{return{ok:!1,status:"permission_lost",error:"Directory is not readable and writable"}}return{ok:!0,status:"active"}}catch(e){return{ok:!1,status:"missing",error:e instanceof Error?e.message:"Directory is unavailable"}}}function directoryEntry(e,t,n){const a=fs$1.statSync(e);return{name:t,path:e,type:n,size:a.size,modifiedAt:a.mtime.toISOString()}}function listDirectory(e){const t=path$1.resolve(e?.trim()||os$1.homedir()),n=validateDirectory(t);if("active"!==n.status)return{ok:!1,status:n.status,path:t,parentPath:null,entries:[],error:n.error};const a=path$1.parse(t).root,s=t===a?null:path$1.dirname(t),i=fs$1.readdirSync(t,{withFileTypes:!0}).map(e=>{const n=path$1.join(t,e.name);try{if(e.isDirectory())return directoryEntry(n,e.name,"directory");if(e.isFile())return directoryEntry(n,e.name,"file")}catch{return null}return null}).filter(e=>Boolean(e)).sort((e,t)=>e.type!==t.type?"directory"===e.type?-1:1:e.name.localeCompare(t.name));return{ok:!0,status:"active",path:t,parentPath:s,entries:i}}function createDirectory(e,t){const n=t.trim();if(!n||"."===n||".."===n||n.includes("/")||n.includes("\\"))throw new Error("Directory name is invalid");const a=path$1.resolve(e),s=validateDirectory(a);if("active"!==s.status)throw new Error(s.error||"Parent directory is unavailable");const i=path$1.resolve(a,n);if(i!==a&&!i.startsWith(a.endsWith(path$1.sep)?a:a+path$1.sep))throw new Error("Directory path is invalid");return fs$1.mkdirSync(i),{path:i,validation:validateDirectory(i)}}class MachineControlCoordinator{state="ready";machineId;workerManager;getSocketClient;requestRestartCallback;restartRequested=!1;pendingRestartReport=null;activeStorageOperations={};constructor(e){this.machineId=e.machineId,this.workerManager=e.workerManager,this.getSocketClient=e.getSocketClient,this.requestRestartCallback=e.requestRestart,this.workerManager.setDrainCallback(()=>this.handleSessionDrain())}getState(){return this.state}isAcceptingNewWorkers(){return this.workerManager.isAcceptingNewWorkers()}clearGracefulRestartGate(){"pending_restart"===this.state&&(this.state="ready"),this.restartRequested=!1,this.pendingRestartReport=null,this.workerManager.setWorkerStartGate(!0)}rollbackGracefulRestart(){"pending_restart"!==this.state&&"restarting"!==this.state||(this.state="ready"),this.restartRequested=!1,this.pendingRestartReport=null,this.workerManager.setWorkerStartGate(!0)}prepareGracefulRestart(e,t,n){this.workerManager.setWorkerStartGate(!1,"daemon_pending_restart",t??"Daemon restart is pending"),this.workerManager.pruneStaleSessions();const a=this.workerManager.getCurrentSessions().length;if(0===a){this.state="restarting";const s=n??this.pendingRestartReport??void 0;return this.pendingRestartReport=null,this.requestRestart(e,t,s),{state:"restarting",activeSessions:a}}return this.state="pending_restart",this.pendingRestartReport=n??this.pendingRestartReport,{state:"pending_restart",activeSessions:a}}buildPingResult(){this.workerManager.pruneStaleSessions();const e="pending_restart"===this.state||"restarting"===this.state;return{machineId:this.machineId,runningCliVersion:machine.packageJson.version,installedCliVersion:getInstalledCliVersion(),restartRequired:e,restartPending:e,platform:process.platform,uptimeMs:Math.max(0,Math.floor(1e3*process.uptime())),activeSessions:this.workerManager.getCurrentSessions().length,capabilities:["ping","upgrade-cli","storage-scan","storage-clean","pick-directory","validate-directory","list-directory","create-directory"]}}handleCommand(e,t){if(this.matchesTarget(e))if("ping"!==e.action){if("validate-directory"===e.action){const n="string"==typeof e.params?.path?e.params.path:"";return n.trim()?void t({eventId:shared.createEventId(),status:"success",opCode:e.eventId,data:{result:validateDirectory(n)}}):void t(this.failedAck(e.eventId,"operation_failed","Directory path is required"))}if("pick-directory"!==e.action){if("list-directory"===e.action){const n="string"==typeof e.params?.path?e.params.path:void 0;return void t({eventId:shared.createEventId(),status:"success",opCode:e.eventId,data:{result:listDirectory(n)}})}if("create-directory"!==e.action)"upgrade-cli"!==e.action?"storage-scan"!==e.action&&"storage-clean"!==e.action?t(this.failedAck(e.eventId,"unsupported_operation","Unsupported machine control operation")):this.handleStorageManagement(e,t):this.handleUpgradeCli(e,t);else try{const n=createDirectory("string"==typeof e.params?.parentPath?e.params.parentPath:"","string"==typeof e.params?.name?e.params.name:"");t({eventId:shared.createEventId(),status:"success",opCode:e.eventId,data:{result:n}})}catch(n){const a=n instanceof Error?n.message:"Failed to create directory";t(this.failedAck(e.eventId,"operation_failed",a))}}else try{const n=pickDirectory("string"==typeof e.params?.defaultPath?e.params.defaultPath:void 0);t({eventId:shared.createEventId(),status:"success",opCode:e.eventId,data:{result:{path:n??null,...n?{validation:validateDirectory(n)}:{}}}})}catch(n){const a=n instanceof Error?n.message:"Failed to pick directory";t(this.failedAck(e.eventId,"operation_failed",a))}}else t({eventId:shared.createEventId(),status:"success",opCode:e.eventId,data:{result:this.buildPingResult()}});else t(this.failedAck(e.eventId,"machine_not_found","Machine control target does not match this daemon"))}handleUpgradeCli(e,t){"ready"===this.state?(this.state="upgrading",t({eventId:shared.createEventId(),status:"success",opCode:e.eventId}),this.runUpgrade(e).catch(t=>{machine.logger.error("[MACHINE CONTROL] upgrade-cli failed unexpectedly:",t),this.state="ready",this.sendProgress({eventId:shared.createEventId(),opCode:e.eventId,status:"failed",errorCode:"operation_failed",errorMessage:t instanceof Error?t.message:"CLI upgrade failed"})})):t(this.failedAck(e.eventId,"pending_restart"===this.state?"daemon_pending_restart":"daemon_control_busy","Daemon is not ready for CLI upgrade"))}async runUpgrade(e){this.sendProgress({eventId:shared.createEventId(),opCode:e.eventId,status:"running",message:"Checking and installing CLI upgrade"});const t=await executeCliUpgrade(void 0,{stdio:"ignore"});if("busy"===t.status)return this.state="ready",void this.sendProgress({eventId:shared.createEventId(),opCode:e.eventId,status:"failed",errorCode:"operation_busy",errorMessage:t.message});if("already_latest"===t.status)return this.state="ready",void this.sendProgress({eventId:shared.createEventId(),opCode:e.eventId,status:"succeeded",message:"CLI is already up to date",result:{alreadyLatest:!0,currentVersion:t.currentVersion,latestVersion:t.latestVersion,restartRequired:!1,restartDeferred:!1,activeSessions:this.workerManager.getCurrentSessions().length}});if("failed"===t.status)return this.state="ready",void this.sendProgress({eventId:shared.createEventId(),opCode:e.eventId,status:"failed",errorCode:"operation_failed",errorMessage:t.error});const n={opCode:e.eventId,target:e.target,fromVersion:t.fromVersion,toVersion:t.toVersion},a=this.prepareGracefulRestart("machine-control","CLI upgrade installed",n);this.sendProgress({eventId:shared.createEventId(),opCode:e.eventId,status:"running",message:"pending_restart"===a.state?"CLI upgrade installed; restart deferred until active sessions finish":"CLI upgrade installed; restarting daemon",result:{fromVersion:t.fromVersion,toVersion:t.toVersion,restartRequired:!0,restartDeferred:"pending_restart"===a.state,activeSessions:a.activeSessions}})}handleStorageManagement(e,t){if("ready"!==this.state)return void t(this.failedAck(e.eventId,"daemon_control_busy","Daemon is not ready for storage management"));const n="storage-scan"===e.action||"storage-clean"===e.action?e.action:null;if(!n)return void t(this.failedAck(e.eventId,"unsupported_operation","Unsupported storage operation"));if(this.activeStorageOperations[n])return void t(this.failedAck(e.eventId,"operation_busy",`Another ${n} operation is already running`));const a=this.buildStorageWorkerRequest(e);"storage-clean"!==e.action||a.items&&0!==a.items.length?(this.activeStorageOperations[n]=e.eventId,t({eventId:shared.createEventId(),status:"success",opCode:e.eventId}),this.runStorageManagementWorker(e,a).catch(t=>{machine.logger.error("[MACHINE CONTROL] storage management failed unexpectedly:",t),this.sendProgress({eventId:shared.createEventId(),opCode:e.eventId,status:"failed",errorCode:"operation_failed",errorMessage:t instanceof Error?t.message:"Storage operation failed"})}).finally(()=>{this.activeStorageOperations[n]===e.eventId&&delete this.activeStorageOperations[n]})):t(this.failedAck(e.eventId,"operation_failed","No storage items selected"))}buildStorageWorkerRequest(e){const t={activeTaskIds:this.workerManager.getCurrentSessions().map(e=>e.taskId)};if("storage-clean"===e.action){t.dryRun=!0===e.params?.dryRun;const n=Array.isArray(e.params?.items)?e.params.items:[];t.items=n.map(e=>e&&"object"==typeof e&&"string"==typeof e.relativePath?{relativePath:e.relativePath}:null).filter(e=>Boolean(e))}return t}async runStorageManagementWorker(e,t){let n=null;try{n=fs$1.mkdtempSync(path$1.join(os$1.tmpdir(),`agentrix-${e.action}-`));const a=path$1.join(n,"request.json");fs$1.writeFileSync(a,JSON.stringify(t));const s=e.action,i=spawnAgentrixCLI([s,"--op-code",e.eventId,"--request-file",a],{stdio:["ignore","pipe","pipe"],env:process.env});this.sendProgress({eventId:shared.createEventId(),opCode:e.eventId,status:"running",message:"storage-scan"===e.action?"Scanning Agentrix storage":"Cleaning Agentrix storage"}),await new Promise(t=>{let n="",a=!1;const o=t=>{"completed"!==t.type&&"failed"!==t.type||(a=!0),this.sendProgress(this.mapStorageWorkerEventToProgress(e,t))};i.stdout?.setEncoding("utf8"),i.stdout?.on("data",e=>{n+=e;const t=n.split(/\r?\n/);n=t.pop()??"";for(const e of t){const t=e.trim();if(t)try{o(JSON.parse(t))}catch(e){machine.logger.warn(`[MACHINE CONTROL] Ignoring malformed storage worker event: ${t}`,e)}}}),i.stderr?.setEncoding("utf8"),i.stderr?.on("data",e=>{machine.logger.warn(`[MACHINE CONTROL] ${s} stderr: ${e.trim()}`)}),i.on("error",t=>{a||(a=!0,this.sendProgress({eventId:shared.createEventId(),opCode:e.eventId,status:"failed",errorCode:"operation_failed",errorMessage:t.message}))}),i.on("close",s=>{if(n.trim())try{o(JSON.parse(n.trim()))}catch(e){machine.logger.warn(`[MACHINE CONTROL] Ignoring malformed trailing storage worker event: ${n.trim()}`,e)}a||this.sendProgress({eventId:shared.createEventId(),opCode:e.eventId,status:"failed",errorCode:"operation_failed",errorMessage:0===s?"Storage operation ended before reporting completion; please retry":`Storage worker exited with code ${s}`}),t()})})}finally{n&&removePathBestEffort(n)}}mapStorageWorkerEventToProgress(e,t){return"failed"===t.type?{eventId:shared.createEventId(),opCode:e.eventId,status:"failed",message:t.message,errorCode:"operation_failed",errorMessage:t.message,result:{phase:t.type,...t}}:"completed"===t.type?{eventId:shared.createEventId(),opCode:e.eventId,status:"succeeded",message:"storage-scan"===e.action?"Storage scan completed":"Storage clean completed",result:t.result??{summary:t.summary}}:{eventId:shared.createEventId(),opCode:e.eventId,status:"running",message:this.describeStorageWorkerEvent(e.action,t),result:{phase:t.type,...t}}}describeStorageWorkerEvent(e,t){return"category-started"===t.type?`Scanning ${t.label}`:"item"===t.type?`Scanned ${t.item.pathDisplay??t.item.relativePath}`:"item-validating"===t.type?`Validating ${t.relativePath}`:"item-cleaning"===t.type?`Cleaning ${t.relativePath}`:"item-completed"===t.type?`Cleaned ${t.relativePath}`:"item-skipped"===t.type?`Skipped ${t.relativePath}`:"item-failed"===t.type?`Failed ${t.relativePath}`:"storage-scan"===e?"Scanning Agentrix storage":"Cleaning Agentrix storage"}handleSessionDrain(){if("pending_restart"!==this.state)return;const e=this.pendingRestartReport??void 0,t=this.prepareGracefulRestart("machine-control","Active sessions drained after CLI upgrade",e);e&&this.sendProgress({eventId:shared.createEventId(),opCode:e.opCode,status:"running",message:"Active sessions drained; restarting daemon",result:{fromVersion:e.fromVersion,toVersion:e.toVersion,restartRequired:!0,restartDeferred:!1,activeSessions:t.activeSessions}})}requestRestart(e,t,n){this.restartRequested||(this.restartRequested=!0,this.requestRestartCallback(e,t,n))}sendProgress(e){const t=this.getSocketClient();t?.connected?t.send("machine-control-progress",e):machine.logger.warn(`[MACHINE CONTROL] Dropping progress ${e.opCode}; socket not connected`)}matchesTarget(e){return e.target.machineId===this.machineId}failedAck(e,t,n){return{eventId:shared.createEventId(),status:"failed",opCode:e,message:n,data:{errorCode:t}}}}const DEFAULT_OLD_DAEMON_EXIT_TIMEOUT_MS=12e4,DEFAULT_NEW_DAEMON_START_TIMEOUT_MS=3e4,POLL_INTERVAL_MS=100;function getPendingReportPath(){return path.join(path.dirname(machine.machine.getStatePaths().daemonStateFile),"daemon-restart-report.json")}function sleep(e){return new Promise(t=>setTimeout(t,e))}function isProcessRunning$1(e){try{return process.kill(e,0),!0}catch{return!1}}function readPendingReport(){const e=getPendingReportPath();if(!fs.existsSync(e))return null;try{const t=JSON.parse(fs.readFileSync(e,"utf-8"));return t.opCode&&t.target?.machineId?t:null}catch{return null}}function writePendingReport(e){fs.writeFileSync(getPendingReportPath(),JSON.stringify(e,null,2),"utf-8")}function clearPendingReport(){try{const e=getPendingReportPath();fs.existsSync(e)&&fs.unlinkSync(e)}catch{}}function buildDaemonRestartArgs(e){const t=["restart-daemon"];return void 0!==e.oldPid&&t.push("--old-pid",String(e.oldPid)),e.expectedCliVersion&&t.push("--expected-version",e.expectedCliVersion),e.reason&&t.push("--reason",e.reason),e.report&&t.push("--report-json",JSON.stringify(e.report)),t}function launchDaemonRestart(e){try{const t=spawnAgentrixCLI(buildDaemonRestartArgs(e),{detached:!0,stdio:"ignore",env:process.env});return t.unref(),t}catch(e){return machine.logger.error("[DAEMON RESTART] Failed to launch restart command",e),null}}async function waitForOldDaemonExit(e,t){const n=Date.now()+t;for(;Date.now()<n;){if(!isProcessRunning$1(e))return!0;await sleep(100)}return!isProcessRunning$1(e)}async function waitForReplacementDaemon(e,t,n){const a=Date.now()+n;for(;Date.now()<a;){const n=await machine.machine.readDaemonState();if(n&&n.pid!==e&&n.cliVersion===t&&isProcessRunning$1(n.pid))return n;await sleep(100)}return null}async function runDaemonRestart(e){const t=void 0===e.oldPid?await machine.machine.readDaemonState():null,n=e.oldPid??(t&&isProcessRunning$1(t.pid)?t.pid:void 0),a=e.expectedCliVersion??getInstalledCliVersion();if(e.report&&writePendingReport({...e.report,oldPid:n,expectedCliVersion:a,reason:e.reason,createdAt:(new Date).toISOString()}),e.stopExistingDaemon&&void 0!==n&&isProcessRunning$1(n)&&await stopDaemon(),void 0!==n&&!await waitForOldDaemonExit(n,e.oldDaemonExitTimeoutMs??12e4))return{success:!1,error:`Old daemon PID ${n} did not exit before timeout`};try{spawnAgentrixCLI(["daemon"],{detached:!0,stdio:"ignore",env:process.env}).unref()}catch(e){return{success:!1,error:e instanceof Error?e.message:String(e)}}return await waitForReplacementDaemon(n,a,e.newDaemonStartTimeoutMs??3e4)?{success:!0}:{success:!1,error:`Replacement daemon did not report version ${a} before timeout`}}async function flushPendingDaemonRestartReport(e){const t=readPendingReport();if(!t)return!1;const n=machine.packageJson.version,a={eventId:shared.createEventId(),opCode:t.opCode,status:"succeeded",message:"CLI upgrade installed; daemon restarted",result:{fromVersion:t.fromVersion,toVersion:t.toVersion??t.expectedCliVersion,currentVersion:n,runningCliVersion:n,installedCliVersion:n,restartRequired:!1,restartDeferred:!1,activeSessions:0}};return e.send("machine-control-progress",a),await e.flush(3e3).catch(e=>{machine.logger.warn("[DAEMON RESTART] Could not confirm restart report flush",e)}),clearPendingReport(),machine.logger.info(`[DAEMON RESTART] Flushed pending restart report for ${t.opCode}`),!0}const DEFAULT_WORKSPACE_SYNC_INTERVAL_MS=3e5,WORKSPACE_SYNC_STATE_VERSION=1;function workspaceStatus(e){return validateDirectory(e).status}function defaultWorkspaceSyncStateFile(){return path.join(machine.machine.agentrixHomeDir,"workspace-mode.state.json")}async function requestJson(e,t){const n=await fetch(e,t);if(!n.ok){const e=await n.text().catch(()=>"");throw new Error(`HTTP ${n.status}${e?`: ${e}`:""}`)}return n.json()}class WorkspaceStatusSync{constructor(e,t={}){this.credentials=e,this.intervalMs=t.intervalMs??3e5,this.stateFilePath=t.stateFilePath??defaultWorkspaceSyncStateFile()}timer=null;running=!1;intervalMs;stateFilePath;start(){this.timer||(this.syncOnce(),this.timer=setInterval(()=>{this.syncOnce()},this.intervalMs),this.timer.unref?.())}stop(){this.timer&&(clearInterval(this.timer),this.timer=null)}async syncOnce(){if(!this.running){this.running=!0;try{const e=await this.loadState(),t=this.buildStatusReports(e);if(0===t.length)return;const n=this.markStatusesObserved(e,t);await this.saveState(n);const a={statuses:t};await requestJson(`${machine.machine.serverUrl}/v1/workspaces/machine/path-statuses`,{method:"POST",headers:{Authorization:`Bearer ${this.credentials.token}`,"Content-Type":"application/json"},body:JSON.stringify(a)}),await this.saveState(this.markStatusesSynced(n,t))}catch(e){machine.logger.warn("[WORKSPACE SYNC] Failed to sync workspace path statuses",e)}finally{this.running=!1}}}async applyCacheUpdate(e){if(e.machineId!==this.credentials.machineId)return;const t=await this.loadState(),n=(new Date).toISOString(),a={...t.workspaces};if("replace"===e.action){const t={};for(const a of e.workspaces??[])t[a.id]=this.entryFromWorkspace(a,n);return void await this.saveState({version:1,machineId:this.credentials.machineId,workspaces:t})}if("upsert"===e.action&&e.workspace)return a[e.workspace.id]=this.entryFromWorkspace(e.workspace,n),void await this.saveState({...t,workspaces:a});"remove"===e.action&&e.workspaceId&&(delete a[e.workspaceId],await this.saveState({...t,workspaces:a}))}async loadState(){const e={version:1,machineId:this.credentials.machineId,workspaces:{}};if(!fs.existsSync(this.stateFilePath))return e;try{const t=JSON.parse(await promises$1.readFile(this.stateFilePath,"utf-8"));return 1===t.version&&t.machineId===this.credentials.machineId&&t.workspaces&&"object"==typeof t.workspaces?t:e}catch(t){return machine.logger.warn("[WORKSPACE SYNC] Failed to read workspace sync state; rebuilding cache",t),e}}async saveState(e){await promises$1.mkdir(path.dirname(this.stateFilePath),{recursive:!0}),await promises$1.writeFile(this.stateFilePath,JSON.stringify(e,null,2),"utf-8")}buildStatusReports(e){const t=[];for(const n of Object.values(e.workspaces)){const e=workspaceStatus(n.path);e!==n.lastSyncedStatus&&t.push({workspaceId:n.workspaceId,pathStatus:e})}return t}markStatusesSynced(e,t){const n={...e.workspaces};for(const e of t){const t=n[e.workspaceId];t&&(n[e.workspaceId]={...t,lastKnownStatus:e.pathStatus,lastSyncedStatus:e.pathStatus,updatedAt:(new Date).toISOString()})}return{...e,workspaces:n}}markStatusesObserved(e,t){const n={...e.workspaces};for(const e of t){const t=n[e.workspaceId];t&&(n[e.workspaceId]={...t,lastKnownStatus:e.pathStatus,updatedAt:(new Date).toISOString()})}return{...e,workspaces:n}}entryFromWorkspace(e,t){return{workspaceId:e.id,path:e.path,lastKnownStatus:e.pathStatus,lastSyncedStatus:e.pathStatus,updatedAt:t}}}function isReauthRequiredError(e){const t=getSocketErrorDetails(e);return"machine_binding_revoked"===t.code||t.message.includes("Machine binding revoked")}function getActionableSocketError(e){const t=getSocketErrorDetails(e);return t.code||t.action?t:null}function isGitlabProxySocketLog(e){return e.includes("daemon-gitlab-request")||e.includes("daemon-gitlab-response")}async function startDaemon(){machine.initializeLogger({type:"daemon"});const{requestShutdown:e,shutdownPromise:t}=setupGracefulShutdown({processType:"daemon"});console.log("[DAEMON RUN] Starting daemon process..."),machine.logger.debug("[DAEMON RUN] Environment",getEnvironmentInfo()),await isLatestDaemonRunning()&&(console.log("Daemon already running..."),process.exit(0));let n=await machine.machine.acquireDaemonLock(5,200);for(;!n;)await stopDaemon(),n=await machine.machine.acquireDaemonLock(5,200),n||(machine.logger.debug("[DAEMON RUN] cannot acquire daemon lock..."),process.exit(1));try{startCaffeinate()&&machine.logger.debug("[DAEMON RUN] Sleep prevention enabled");const a=await authAndSetupMachineIfNeeded();machine.logger.debug("[DAEMON RUN] Auth and machine setup complete");const s=new SandboxPool;await s.initialize(machine.machine.getSandboxSettings());const i=new TaskWorkerManager(s);let o,r,c,l,d=!1;i.setSocketClientProvider(()=>o?.client),l=new MachineControlCoordinator({machineId:a.machineId,workerManager:i,getSocketClient:()=>o?.client,requestRestart:(t,n,a)=>{launchDaemonRestart({oldPid:process.pid,expectedCliVersion:a?.toVersion??getInstalledCliVersion(),reason:n,report:a})?(d=!0,e("agentrix-cli",n)):l.rollbackGracefulRestart()}});const{port:p,host:u,webhookHost:m,stop:h}=await startDaemonControlServer({getChildren:()=>i.getCurrentSessions(),stopSession:e=>i.stopSession(e),startDevOpsInit:e=>i.startDevOpsInit(e),completeDevOpsInit:e=>i.completeDevOpsInit(e),requestShutdown:()=>e("agentrix-cli"),registerSession:(e,t)=>i.registerTaskWorker(e,t),prepareGracefulRestart:e=>l.prepareGracefulRestart(e.source,e.reason),clearGracefulRestartGate:()=>l.clearGracefulRestartGate(),getSocketClient:()=>o?.client,credentials:a,get companionScheduler(){return r},get channelManager(){return c}});try{await listOpeners(),machine.logger.debug("[DAEMON RUN] Openers detected")}catch(e){machine.logger.warn("[DAEMON RUN] Failed to detect openers",e)}const g={pid:process.pid,port:p,host:u,webhookHost:m,startTime:(new Date).toLocaleString(),cliVersion:machine.packageJson.version,logPath:machine.getLogPath({type:"daemon"})};machine.machine.writeDaemonState(g),machine.logger.debug("[DAEMON RUN] Daemon state written");const f=new WorkspaceStatusSync(a),y=new MachineClient({machineId:a.machineId,serverUrl:machine.machine.serverUrl.replace(/^http/,"ws"),path:"/v1/ws",auth:shared.machineAuth(a.token,a.machineId),keepAliveConfig:{intervalMs:2e4,event:"machine-alive",payloadGenerator:()=>({eventId:shared.createEventId(),machineId:a.machineId,timestamp:Date.now().toString(),controlPort:p})},healthCheckConfig:{enabled:!0,intervalMs:3e4,timeoutMs:5e3},logger:machine.createModuleLogger("undefined"==typeof document?require("url").pathToFileURL(__filename).href:_documentCurrentScript&&"SCRIPT"===_documentCurrentScript.tagName.toUpperCase()&&_documentCurrentScript.src||new URL("index.cjs",document.baseURI).href,void 0,{filter:e=>!isGitlabProxySocketLog(e)})},i,{requestShutdown:e,machineControl:l,workspaceStatusSync:f}),v=new ChannelManager(y.client,a.machineId);c=v,i.setChannelManager(v),await y.connect(),o=y,machine.logger.info("[DAEMON RUN] Machine client connected to server"),await flushPendingDaemonRestartReport(y.client).catch(e=>{machine.logger.warn("[DAEMON RUN] Failed to flush pending restart report",e)}),await configureGitServerFromEnvironmentSafely(y.client,a),f.start();const b=new CompanionScheduler(y.client,a.machineId);r=b,b.start(),await v.start(),y.setCompanionInteractionCallback(e=>{b.recordInteraction(e)});const k=new CompanionBootstrapWatcher(y.client,a.machineId);k.start(),y.client.onEvent("companion-heartbeat-response",e=>{e?.taskId&&b.setHeartbeatTaskId(e.taskId)}),y.client.onEvent("companion-memory-organization-response",e=>{e?.taskId&&b.setMemoryOrganizationTaskId(e.taskId)});const w=async(e,t)=>{await v.stop(),f.stop(),b.stop(),k.stop(),await y.disconnect(),await h(),await s.shutdown(),await cleanupDaemonState(),await stopCaffeinate(),await machine.machine.releaseDaemonLock(n),d&&machine.logger.info("[DAEMON RUN] Restart command owns replacement daemon startup"),machine.logger.info("[DAEMON RUN] Cleanup completed, exiting process"),process.exit(0)};machine.logger.info("[DAEMON RUN] Daemon started successfully, waiting for shutdown request");const x=await t;await w(x.source,x.errorMessage)}catch(e){const t=getActionableSocketError(e);t?(console.error(t.message),t.action&&console.error(t.action)):isReauthRequiredError(e)&&(console.error("Machine binding is no longer valid."),console.error("Run `agentrix logout` and bind this machine again.")),machine.logger.info("[DAEMON RUN][FATAL] Failed somewhere unexpectedly - exiting with code 1",e),process.exit(1)}}const TOOL_RESULT_CONTENT_LIMIT_BYTES=1024,TOOL_RESULT_TRUNCATION_MARKER="\n\n[Tool result truncated to 1024 bytes]";function truncateToolResultContent(e,t=1024){if(Buffer.byteLength(e,"utf8")<=t)return e;const n=Buffer.byteLength(TOOL_RESULT_TRUNCATION_MARKER,"utf8");return n>t?sliceUtf8Bytes(TOOL_RESULT_TRUNCATION_MARKER,t):`${sliceUtf8Bytes(e,t-n)}${TOOL_RESULT_TRUNCATION_MARKER}`}function truncateToolResultPayload(e,t=1024){if("string"==typeof e)return truncateToolResultContent(e,t);const n=safeStringify(e);return Buffer.byteLength(n,"utf8")<=t?e:Array.isArray(e)?truncateToolResultContent(e.map(e=>isTextBlock(e)?e.text:safeStringify(e)).join("\n"),t):truncateToolResultContent(n,t)}function truncateToolResultMessage(e,t=1024){const n=e,a=n?.message?.content;if(!Array.isArray(a))return e;let s=!1;const i=a.map(e=>{if("tool_result"!==e?.type||!("content"in e))return e;const n=truncateToolResultPayload(e.content,t);return n===e.content?e:(s=!0,{...e,content:n})});return s?{...n,message:{...n.message,content:i}}:e}function isTextBlock(e){return"object"==typeof e&&null!==e&&"text"in e&&"string"==typeof e.text}function safeStringify(e){try{return JSON.stringify(e)??String(e)}catch{return String(e)}}function sliceUtf8Bytes(e,t){let n="",a=0;for(const s of e){const e=Buffer.byteLength(s,"utf8");if(a+e>t)break;n+=s,a+=e}return n}function formatTaskMessageLogMeta(e,t){return[`eventId=${e.eventId}`,void 0!==e.sequence?`sequence=${e.sequence}`:void 0,e.opCode?`opCode=${e.opCode}`:void 0,`senderType=${e.senderType}`,`messageType=${t?.type??e.messageType??"unknown"}`,`encrypted=${Boolean(e.encryptedMessage)}`].filter(Boolean).join(" ")}function extractUserContentForLog(e){return shared.isSDKUserMessage(e)?extractUserMessageText(e):shared.isAskUserResponseMessage(e)?{answers:e.answers,...e.details?{details:e.details}:{},...e.status?{status:e.status}:{},...e.reason?{reason:e.reason}:{}}:null}function formatUserContentLogLine(e,t,n={}){const a=extractUserContentForLog(t);if(null===a)return null;const s="string"==typeof a?a:JSON.stringify(a);return["message.user_content",n.source?`source=${n.source}`:void 0,formatTaskMessageLogMeta(e,t),`chars=${s.length}`,`content=${JSON.stringify(a)}`].filter(Boolean).join(" ")}const logger$5=machine.createModuleLogger("undefined"==typeof document?require("url").pathToFileURL(__filename).href:_documentCurrentScript&&"SCRIPT"===_documentCurrentScript.tagName.toUpperCase()&&_documentCurrentScript.src||new URL("index.cjs",document.baseURI).href),system_sender={senderType:"system",senderId:"system",senderName:"system"};function createWorkerEventHandlers(e,t,n){return{"cancel-task":async t=>{t.taskId===e.taskId&&(logger$5.info(`worker.cancelled taskId=${e.taskId}`),await e.stopTask())},"stop-task":async t=>{t.taskId===e.taskId&&(logger$5.info(`worker.stopped taskId=${e.taskId} reason=${t.reason||"no reason"}`),await e.stopTask())},"task-message":async a=>{if(a.taskId!==e.taskId)return;logger$5.debug(`message.received ${formatTaskMessageLogMeta(a)}`);let s=a.message??null;if(!s&&a.encryptedMessage&&e.dataEncryptionKey&&(s=shared.decryptSdkMessage(a.encryptedMessage,e.dataEncryptionKey)??null),!s&&a.encryptedMessage&&!e.dataEncryptionKey)return void logger$5.warn(`message.decrypt_failed ${formatTaskMessageLogMeta(a)} reason=missing_data_encryption_key`);if(!s&&a.encryptedMessage)return void logger$5.warn(`message.decrypt_failed ${formatTaskMessageLogMeta(a)} reason=invalid_encrypted_payload`);if(!s)return void logger$5.warn(`message.empty ${formatTaskMessageLogMeta(a)} reason=missing_message_payload`);a.channelReplyTarget&&"object"==typeof s&&(s.__channelReplyTarget=a.channelReplyTarget);const i={senderType:a.senderType,senderId:a.senderId,senderName:a.senderName};if(e.attachmentsDir&&shared.isSDKUserMessage(s)&&(s=await processAttachments(s,{attachmentsDir:e.attachmentsDir})),e.shouldPersistTaskMessage&&!await e.shouldPersistTaskMessage(s,i))return void logger$5.debug(`message.dropped ${formatTaskMessageLogMeta(a,s)} reason=should_not_persist`);if(!t.saveMessage({eventId:a.eventId,message:s,senderType:a.senderType,senderId:a.senderId,senderName:a.senderName}).inserted)return n(a.eventId),void logger$5.debug(`message.duplicate ${formatTaskMessageLogMeta(a,s)} acked=true`);const o=formatUserContentLogLine(a,s,{source:"runtime"});o&&logger$5.info(o);const r={...a,message:s,encryptedMessage:void 0,chatId:a.chatId??e.chatId};t.saveTaskEvent({eventType:"task-message",eventId:a.eventId,eventData:r,taskId:e.taskId,chatId:a.chatId??e.chatId,sequence:a.sequence??null}),n(a.eventId),e.onTaskMessage&&await e.onTaskMessage(s,i),logger$5.info(`message.accepted ${formatTaskMessageLogMeta(a,s)} persisted=true duplicate=false acked=true dispatched=${Boolean(e.onTaskMessage)}`)},"task-info-update":async t=>{t.taskId===e.taskId&&e.onTaskInfoUpdate&&await e.onTaskInfoUpdate(t)},"worker-status-request":async t=>{t.taskId===e.taskId&&e.onWorkerStatusRequest&&await e.onWorkerStatusRequest(t)},"sub-task-result-updated":async t=>{t.parentTaskId===e.taskId&&e.onSubTaskResultUpdated&&await e.onSubTaskResultUpdated(t)},"sub-task-ask-user":async t=>{t.parentTaskId===e.taskId&&e.onSubTaskAskUser&&await e.onSubTaskAskUser(t)}}}class WorkerClient{client;context;historyDb;getPermissionMode;outbox=new Map;ackWaiters=new Map;hasConnectedOnce=!1;constructor(e,t){const{taskId:n,userId:a,machineId:s,cwd:i,chatId:o,...r}=e,c=i.endsWith("/")?i:`${i}/`;this.client=new SocketClient(r),this.context={taskId:n,chatId:o,userId:a,machineId:s,cwd:c,stopTask:t.stopTask,shouldPersistTaskMessage:t.shouldPersistTaskMessage,onTaskMessage:t.onTaskMessage,onReconnect:t.onReconnect,onTaskInfoUpdate:t.onTaskInfoUpdate,onWorkerStatusRequest:t.onWorkerStatusRequest,onSubTaskResultUpdated:t.onSubTaskResultUpdated,onSubTaskAskUser:t.onSubTaskAskUser,onGitPush:t.onGitPush,dataEncryptionKey:e.dataEncryptionKey,attachmentsDir:t.attachmentsDir},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 a=shared.createEventId();return this.historyDb.saveMessage({eventId:a,message:t,senderType:e.senderType,senderId:e.senderId,senderName:e.senderName}),this.sendTaskEvent(e,t,n),a}sendWorkerInitializing(e){const t={eventId:shared.createEventId(),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:shared.createEventId(),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:shared.createEventId(),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),logger$5.info([`worker.ready taskId=${this.context.taskId}`,void 0!==e?`activeMs=${e}`:void 0,null!==t?`permissionMode=${t}`:void 0].filter(Boolean).join(" "))}sendWorkRunning(e){const t=this.getPermissionModeSnapshot(),n={eventId:shared.createEventId(),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:shared.createEventId(),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:shared.createEventId(),taskId:this.context.taskId,machineId:this.context.machineId,timestamp:(new Date).toISOString(),reason:e};this.client.send("worker-exit",t)}async sendErrorMessageAndExit(e){await this.sendTerminalErrorResultAndWait(e),this.sendWorkerExit("error"),await this.disconnect()}async sendTerminalErrorResultAndWait(e,t){const n=this.sendTerminalErrorResult(e,t);await this.waitForEventAcks(n,2e3)}sendTerminalErrorResult(e,t){return[this.sendSystemErrorMessage(e,t),this.sendTaskEvent(system_sender,createSdkErrorResultMessage(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"}}]}};return this.sendTaskEvent(system_sender,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(system_sender,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(system_sender,t,{opCode:e})}sendTaskEvent(e,t,n){const a=truncateToolResultMessage(t),{eventId:s,opCode:i,artifacts:o,navigateToTaskId:r}=n||{},c=s??shared.createEventId(),l={eventId:c,taskId:this.context.taskId,chatId:this.context.chatId,from:"worker",messageType:a.type,message:a,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 d=this.buildTaskUsageReport(a,c);if(this.context.dataEncryptionKey){const e=shared.encryptSdkMessage(a,this.context.dataEncryptionKey);l.message=void 0,l.encryptedMessage=e}return this.outbox.set(c,{payload:l,usageReport:d??void 0,sentAt:Date.now(),messageType:l.messageType,isResult:"result"===a.type}),d&&this.client.send("task-usage-report",d),this.client.send("task-message",l),"result"===a.type&&logger$5.info([`outbound.result.sent eventId=${c}`,d?.eventId?`usageEventId=${d.eventId}`:"usageEventId=none",`encrypted=${Boolean(l.encryptedMessage)}`,`artifacts=${Boolean(o)}`,`outboxSize=${this.outbox.size}`].join(" ")),c}waitForEventAcks(e,t){const n=new Set(e.filter(e=>this.outbox.has(e)));return 0===n.size?Promise.resolve():new Promise(e=>{const a=t=>{this.ackWaiters.delete(t),n.delete(t),0===n.size&&(clearTimeout(s),e())},s=setTimeout(()=>{for(const e of n){const n=this.outbox.get(e),a=n?Date.now()-n.sentAt:t;logger$5.warn(`${n?.isResult?"outbound.result.ack_timeout":"outbound.event.ack_timeout"} eventId=${e} pendingMs=${a} outboxSize=${this.outbox.size}`),this.ackWaiters.delete(e)}e()},t);for(const e of n)this.ackWaiters.set(e,()=>a(e))})}buildTaskUsageReport(e,t){if("result"!==e.type)return null;const n=e.modelUsage;if(!n||"object"!=typeof n)return null;const a={};for(const[e,t]of Object.entries(n)){if(!e||!t||"object"!=typeof t)continue;const n=t,s={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(s).some(e=>e>0)&&(a[e]=s)}return 0===Object.keys(a).length?null:{eventId:shared.createEventId(),taskId:this.context.taskId,resultEventId:t,modelUsage:a}}normalizeUsageCount(e){return"number"!=typeof e||!Number.isFinite(e)||e<=0?0:Math.trunc(e)}sendUpdateTaskAgentSessionId(e){const t={eventId:shared.createEventId(),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:shared.createEventId(),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:shared.createEventId(),taskId:this.context.taskId,title:e};this.client.send("change-task-title",t),logger$5.info(`task.title_changed title=${e}`)}sendUpdateAgentInfo(e,t){const n={eventId:shared.createEventId(),taskId:this.context.taskId,agentId:e,...t};this.client.send("update-agent-info",n),logger$5.info(`agent.info_updated updates=${JSON.stringify(t)}`)}async sendVisionPlanCard(e){const t={eventId:shared.createEventId(),taskId:this.context.taskId,issueId:e.issueId,repoRoot:e.repoRoot,createdAt:(new Date).toISOString()},n=await this.client.sendWithAck("vision-plan-card",t);if("success"!==n.status)throw new Error(n.message||"Failed to send Vision Plan card");return logger$5.info(`vision_plan_card.sent issueId=${e.issueId}`),n}sendResetTaskSession(){const e={eventId:shared.createEventId(),taskId:this.context.taskId};this.client.send("reset-task-session",e),logger$5.info(`session.reset_requested taskId=${this.context.taskId}`)}async sendMergeRequest(e,t,n){const a={eventId:shared.createEventId(),taskId:this.context.taskId,summary:e,description:t,sourceBranch:n};logger$5.info(`merge_request.sent taskId=${this.context.taskId}`);const s=await this.client.sendWithAck("merge-request",a);if(!s.success)throw new Error(`Failed to create pull request: ${s.error||"Unknown error"}`);return logger$5.info(`merge_request.created pullRequestNumber=${s.data.pullRequestNumber}`),{pullRequestNumber:s.data.pullRequestNumber,pullRequestUrl:s.data.pullRequestUrl}}async sendMergePr(){const e={eventId:shared.createEventId(),taskId:this.context.taskId,mergeMethod:"squash"};return logger$5.info(`merge_pr.sent taskId=${this.context.taskId}`),await this.client.sendWithAck("merge-pr",e)}associateRepository(e,t,n,a){const s={eventId:shared.createEventId(),taskId:this.context.taskId,gitServerHost:e,owner:t,repo:n,remoteUrl:a};logger$5.info(`repo.association.sent repository=${e}/${t}/${n}`),this.client.send("associate-repo",s)}async dispatchTaskMessage(e){await this.context.onTaskMessage(e)}sendEventAck(e){this.client.send("event-ack",{eventId:shared.createEventId(),status:"success",opCode:e})}initHandlers(){const e=createWorkerEventHandlers(this.context,this.historyDb,e=>{this.sendEventAck(e)});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;if(void 0!==e.opCode){const n=this.outbox.get(e.opCode),a=n?Date.now()-n.sentAt:void 0;this.outbox.delete(e.opCode),this.ackWaiters.get(e.opCode)?.(),n?.isResult?logger$5.info([`outbound.result.acked eventId=${e.opCode}`,"number"==typeof t?`sequence=${t}`:"sequence=unknown",void 0!==a?`ackMs=${a}`:void 0].filter(Boolean).join(" ")):logger$5.debug([`outbound.event.acked eventId=${e.opCode}`,n?.messageType?`messageType=${n.messageType}`:void 0,"number"==typeof t?`sequence=${t}`:void 0,void 0!==a?`ackMs=${a}`:void 0].filter(Boolean).join(" "))}void 0!==e.opCode&&"number"==typeof t&&this.historyDb.updateTaskEventSequence(e.opCode,t)}),this.client.onLifecycle("connect",()=>{if(this.hasConnectedOnce){if(Promise.resolve(this.context.onReconnect?.()).catch(e=>{logger$5.warn(`reconnect.handler_failed error=${e instanceof Error?e.message:String(e)}`)}),this.outbox.size>0){logger$5.info(`reconnect.outbox_flush count=${this.outbox.size}`);for(const[e,t]of this.outbox.entries())t.usageReport&&this.client.send("task-usage-report",t.usageReport),this.outbox.set(e,{...t,sentAt:Date.now()}),this.client.send("task-message",t.payload)}}else this.hasConnectedOnce=!0})}}const execFileAsync$2=node_util.promisify(node_child_process.execFile),HIVE_REPOSITORY_OWNER="xmz-ai",HIVE_REPOSITORY_NAME="agentrix-hive",HIVE_REPOSITORY_URL="https://github.com/xmz-ai/agentrix-hive.git",HIVE_GIT_SERVER_ID="github";async function prepareHiveRepository(){const e=machine.machine.resolveRepoStoreCheckoutDir("github","xmz-ai","agentrix-hive"),t=machine.machine.resolveRepoStoreLockPath("github","xmz-ai","agentrix-hive"),n=await machine.machine.acquireFileLock(t);if(!n)throw new Error(`Timed out waiting for Hive repository lock at ${t}`);try{if(!await isGitRepository(e)){if(!isDirectoryEmpty(e))return{path:e,pullSucceeded:!1,error:`Hive repository checkout exists but is not a git repository: ${e}`};try{await gitClone(HIVE_REPOSITORY_URL,e)}catch(t){return{path:e,pullSucceeded:!1,error:t instanceof Error?t.message:String(t)}}return{path:e,pullSucceeded:!0}}await ensureRemote(e,"origin",sanitizeGitRemoteUrl(HIVE_REPOSITORY_URL));try{return await execFileAsync$2("git",["pull","--ff-only"],{cwd:e}),{path:e,pullSucceeded:!0}}catch(t){return{path:e,pullSucceeded:!1,error:t instanceof Error?t.message:String(t)}}}finally{await machine.machine.releaseFileLock(t,n)}}class AgentContextImpl{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 a=shared.createEventId();try{const s=await this.socketClient.sendWithAck("rpc-call",{eventId:a,taskId:this.taskId,method:e,path:t,query:n?.query,body:n?.body});if(!s.success){const n=s.error||{code:"unknown",message:"Unknown error"};throw new Error(`RPC ${e} ${t} failed: ${n.message} (${n.code})`)}return s.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,initPolicies:e.initPolicies};return this.taskDataKey?t.encryptedMessage=shared.encryptSdkMessage(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=shared.encryptSdkMessage(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,initPolicies:e.initPolicies};return this.taskDataKey?t.encryptedMessage=shared.encryptSdkMessage(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 prepareHiveRepository(){const e=await prepareHiveRepository();return e.pullSucceeded||this.logger.warn(`[Agent-Context] Hive repository update failed; continuing when local copy is usable: ${e.error}`),e}async recordHiveInstall(e,t){return this.call("POST",`/v1/hive/listings/${e}/record-install`,{body:t})}async installHiveListing(e,t){return this.call("POST",`/v1/hive/listings/${e}/install`,{body:t})}async publishToHive(e){return this.call("POST","/v1/hive/publish",{body:e})}async updateHiveListingVersion(e,t){return this.call("POST",`/v1/hive/listings/${e}/update-version`,{body:t})}async createHiveReview(e,t){return this.call("POST",`/v1/hive/listings/${e}/reviews`,{body:t})}async createHiveComment(e,t){return this.call("POST",`/v1/hive/listings/${e}/comments`,{body:t})}async listAgents(){return this.call("GET","/v1/user-agents")}async uploadFile(e){this.logger.info("[Agent-Context] Uploading file...");const t=await fs__namespace$1.promises.stat(e.path);this.logger.info("[Agent-Context] file stats");const n=t.size,a=e.contentType||mimeTypesExports.lookup(e.name)||"application/octet-stream",s=(await this.call("POST","/v1/files/upload-urls",{body:{count:1}})).files[0],i=s.url;this.logger.info(`[Agent-Context] FileUploadUrl: ${i}`);const o=await fs__namespace$1.promises.readFile(e.path),r=await fetch(i,{method:"PUT",headers:{"Content-Type":a},body:o});if(!r.ok)throw new Error(`Failed to upload file to S3: ${r.status} ${r.statusText}`);let c;return await this.call("POST","/v1/files/confirm-upload",{body:{fileId:s.id,name:e.name,size:n,contentType:a,visibility:e.visibility||"private"}}),c="public"===e.visibility?`${this.serverUrl}/v1/files/public/${s.id}`:i.split("?")[0],{fileId:s.id,name:e.name,size:n,contentType:a,url:c}}}function buildSubTaskResultMessage(e,t){let n=e.resultMessage;if(0===n.result.trim().length&&e.encryptedResultMessage&&t){const a=shared.decryptSdkMessage(e.encryptedResultMessage,t);a&&"result"===a.type&&(n={type:"result",result:"result"in a?a.result:"",is_error:a.is_error})}const a={...e,resultMessage:n};let s=`<sub-task-result-updated>\n${JSON.stringify(a,null,2)}\n</sub-task-result-updated>`;return s+=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:s}}}function buildSubTaskAskUserMessage(e,t){let n=e.message;if(!n&&e.encryptedMessage&&t){const a=shared.decryptSdkMessage(e.encryptedMessage,t);a&&"ask_user"===a.type&&(n=a)}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 createMessageFilter(){const e=new Set;return{filter(t){const n=t;if(!n.message||!n.message.content||"string"==typeof n.message.content)return t;const a=n.message.content.filter(t=>!("tool_result"===t.type&&e.has(t.tool_use_id)||"user"===n.type&&"tool_result"!==t.type));return 0===a.length?null:(n.message.content=a,n)},clear(){e.clear()}}}const logger$4=machine.createModuleLogger("undefined"==typeof document?require("url").pathToFileURL(__filename).href:_documentCurrentScript&&"SCRIPT"===_documentCurrentScript.tagName.toUpperCase()&&_documentCurrentScript.src||new URL("index.cjs",document.baseURI).href);function createAgentrixMcpTools(e){return{createTask:createTaskTool(e),createSoloTask:createSoloTaskTool(e),createGroupTask:createGroupTaskTool(e),replyToSubTask:createReplyToSubTaskTool(e),changeTaskTitle:createChangeTaskTitleTool(e),publishTaskPreviewUrl:createPublishTaskPreviewUrlTool(e),sendVisionArtifact:createSendVisionArtifactTool(e),askUser:createAskUserTool(e),getTaskHistory:createGetTaskHistoryTool(e),getTaskAgents:createGetTaskAgentsTool(e),listSubTask:createListSubTaskTool(e),invoke:createInvokeTool(e),assign:createAssignTool(e),updateAgentInfo:createUpdateAgentInfoTool(e),sendReminder:createSendReminderTool(e),recordMemoryChange:createRecordMemoryChangeTool(e),listTasks:createListTasksTool(e),readConversation:createReadConversationTool(e),uploadFile:createUploadFileTool(e),sendChannelMessage:createSendChannelMessageTool(e),getChannelGroupHistory:createGetChannelGroupHistoryTool(e),listAgents:createListAgentsTool(e),analyzeImage:createAnalyzeImageTool(e),scheduleTask:createScheduleTaskTool(),prepareHiveRepository:createPrepareHiveRepositoryTool(e),publishToHive:createPublishToHiveTool(e),updateHiveListingVersion:createUpdateHiveListingVersionTool(e),recordHiveInstall:createRecordHiveInstallTool(e),createHiveReview:createHiveReviewTool(e),createHiveComment:createHiveCommentTool(e),computerUse:createComputerUseTool(e)}}function createComputerUseTool(e){return claudeAgentSdk.tool("agentrix_computer_use","Execute a concrete operation on the user's local computer through Agentrix Computer Use.\n\nUse this tool when the user asks you to operate local desktop apps, windows, documents, menus, dialogs, browsers, Finder, or other GUI surfaces on this machine. Provide the requested operation as a natural-language instruction. Do not decompose the task into low-level click coordinates; Agentrix Computer Use will operate the GUI through its configured desktop-control tools.\n\nThis tool can control the local computer. Call it only for explicit user-requested computer operation.",{instruction:zod.z.string().describe("Concrete natural-language desktop operation to perform, including the app/document/target and desired outcome."),expectedResult:zod.z.string().optional().describe("Optional concise success condition the computer-use sub-task should verify before returning."),title:zod.z.string().optional().describe('Optional title for the computer-use sub-task. Defaults to "Computer use".')},async t=>{try{const n=await executeComputerUseBridge({instruction:t.instruction,expectedResult:t.expectedResult,title:t.title},{taskId:e.taskId,cwd:e.workingDirectory,historyDb:e.historyDb,startSubTask:t=>e.agentContext.startSubTask(t),sendMessage:t=>e.agentContext.sendMessage(t)});return{content:[{type:"text",text:"created"===n.action?[`computer-use sub-task created: ${n.taskId}`,`Title: ${n.title}`,"","The computer operation is now running asynchronously in that sub-task. Use this same agentrix_computer_use tool again for follow-up instructions or corrections; it will route them to the same computer-use sub-task."].join("\n"):[`computer-use instruction sent to existing sub-task: ${n.taskId}`,"","The computer-use sub-task will continue from its existing context."].join("\n")}]}}catch(e){return{content:[{type:"text",text:e instanceof Error?e.message:String(e)}],isError:!0}}})}function createChangeTaskTitleTool({workClient:e}){return claudeAgentSdk.tool("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:zod.z.string().describe("New title for the task")},async t=>(e.sendChangeTaskTitle(t.title),{content:[{type:"text",text:`Task title updated to: ${t.title}`}]}))}async function publishTaskPreviewUrl(e,t){const n=shared.UpdateTaskPreviewUrlRequestSchema.parse({previewUrl:t}),a=await fetch(`${machine.machine.serverUrl}/v1/tasks/${encodeURIComponent(e.taskId)}/preview-url`,{method:"PUT",headers:{Authorization:`Bearer ${e.credentials.token}`,"Content-Type":"application/json","X-Agentrix-Task":e.taskId},body:JSON.stringify(n)});if(!a.ok){const e=await a.text().catch(()=>"");throw new Error(`Failed to publish task preview URL (${a.status}): ${e||a.statusText}`)}}function createPublishTaskPreviewUrlTool(e){return claudeAgentSdk.tool("publish_task_preview_url","Publish the frontend preview URL for the current Agentrix task.\n\nUse this on a local machine when the user provided a service startup port or relevant startup documentation for a frontend app, and you have started or reused the local environment after completing the task.\nThe URL is recorded on the current task only. It must be an absolute http or https URL; localhost URLs are allowed.",{previewUrl:zod.z.string().describe("Absolute http(s) URL for the current task preview, such as http://localhost:5173")},async t=>(await publishTaskPreviewUrl(e,t.previewUrl),{content:[{type:"text",text:`Task preview URL published: ${t.previewUrl.trim()}`}]}))}function createSendVisionArtifactTool(e){return claudeAgentSdk.tool("send_vision_artifact","Send the issue vision artifacts (visual plan and test report) to the Agentrix platform so the user can review them.\n\nUse this after generating or materially updating the visual plan, and again after generating the visual test report. Pass only the repository root and issue id; Agentrix derives the current task routing from platform context.",{repoRoot:SendVisionArtifactRequestSchema.shape.repoRoot,issueId:SendVisionArtifactRequestSchema.shape.issueId},async t=>{const n=await normalizeSendVisionArtifactRequest(t);if(!e.workClient.sendVisionPlanCard)throw new Error("Vision artifact publishing is not available in this worker");return await e.workClient.sendVisionPlanCard({issueId:n.issueId,repoRoot:t.repoRoot}),{content:[{type:"text",text:`Agentrix vision artifacts sent for issue ${n.issueId}.`}]}})}function createReplyToSubTaskTool({agentContext:e}){return claudeAgentSdk.tool("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:zod.z.string().describe("Sub-task ID to send the message to"),instructions:zod.z.string().optional().describe("Follow-up instructions for the sub-task (used when not answering ask_user)"),answers:zod.z.array(zod.z.string()).optional().describe("Answers to the sub-task ask_user questions, one per question. When provided, sends as ask_user_response.")},async t=>{try{let n;return n=t.answers&&t.answers.length>0?{type:"ask_user_response",answers:t.answers}:{type:"user",message:{role:"user",content:t.instructions??""}},await e.sendMessage({taskId:t.taskId,message:n,target:"agent"}),{content:[{type:"text",text:`${t.answers?"Sent ask_user response":"Sent follow-up instructions"} to sub-task ${t.taskId}.`}]}}catch(e){return logger$4.error(`Failed to send message to sub-task ${t.taskId}:`,e),{content:[{type:"text",text:`Failed to send message to sub-task: ${e instanceof Error?e.message:"Unknown error"}`}],isError:!0}}})}function createGetTaskHistoryTool({historyDb:e}){return claudeAgentSdk.tool("get_task_history","Retrieve task history stored locally. Omit sequence to read the latest messages; only pass sequence when paginating to older messages.",{sequence:zod.z.number().int().min(0).optional().describe("Pagination cursor for older history. Omit this field, or pass 0, to read the latest messages. Only pass a positive sequence value that was returned by the previous result as “Use sequence=N to load earlier messages”; it means return messages before that local sequence, not start at that position."),limit:zod.z.number().int().min(1).max(50).default(20).describe("Maximum number of messages to return.")},async t=>{const n=t.limit??20,a=null!=t.sequence&&t.sequence>0,s=a?e.pageMessagesBefore(t.sequence,n):e.pageRecentMessages(n);if(0===s.data.length)return{content:[{type:"text",text:a?"No earlier messages found.":"No task history messages found."}]};let i=formatHistoryXml(s.data);return s.hasMore&&(i+=`\n\nMore messages available. Use sequence=${Math.min(...s.data.map(e=>e.localSequence))} to load earlier messages.`),{content:[{type:"text",text:i}]}})}function createGetTaskAgentsTool({agentContext:e}){return claudeAgentSdk.tool("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 createListSubTaskTool({agentContext:e}){return claudeAgentSdk.tool("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 logger$4.error("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 createTaskTool({agentContext:e,agentId:t,setPendingNavigateTaskId:n}){return claudeAgentSdk.tool("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:zod.z.string().optional().describe('Target agent ID (e.g., "agent-poster-generator"). If not provided, uses current agent.'),title:zod.z.string().min(1).max(200).describe("Task title for the agent to use (required)"),instructions:zod.z.string().describe("Detailed instructions for the agent. Be specific about what needs to be done."),briefSummary:zod.z.string().describe('One-line summary shown to user immediately (e.g., "Creating login page")'),cwd:zod.z.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:zod.z.boolean().optional().describe("Whether to create a git worktree for isolation. Defaults to false (work in-place)."),independent:zod.z.boolean().optional().describe("Create as independent top-level task (no parent). Defaults to false (sub-task mode)."),autoNavigate:zod.z.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 s=a.agentId||t;let i;return a.independent?(i=await e.startIndependentTask({agentId:s,message:{type:"user",message:{role:"user",content:a.instructions}},title:a.title,cwd:a.cwd,forceUserCwd:!a.useWorktree,autoNavigate:a.autoNavigate}),a.autoNavigate&&n(i.taskId),logger$4.info(`Created independent task ${i.taskId} for agent ${s} (autoNavigate: ${a.autoNavigate??!1})`)):(i=await e.startSubTask({agentId:s,message:{type:"user",message:{role:"user",content:a.instructions}},title:a.title,cwd:a.cwd,forceUserCwd:!a.useWorktree,initPolicies:{uncommittedChanges:"Ignore",branchMismatch:"Keep"}}),logger$4.info(`Created sub-task ${i.taskId} for agent ${s}`)),{content:[{type:"text",text:`🚀 Task created: ${i.taskId}\n${a.agentId?`Agent: ${s}\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 logger$4.error("Failed to create task:",e),{content:[{type:"text",text:`Failed to create task: ${e instanceof Error?e.message:"Unknown error"}`}],isError:!0}}})}function createSoloTaskTool({agentContext:e}){return claudeAgentSdk.tool("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:zod.z.string().min(1).max(200).describe("Task title"),instructions:zod.z.string().describe("Instructions for the owner agent"),briefSummary:zod.z.string().optional().describe("One-line summary shown to user immediately"),agentId:zod.z.string().describe("Target agent ID"),cwd:zod.z.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:zod.z.boolean().optional().describe("Whether to create a git worktree for isolation. Defaults to false (work in-place).")},async t=>{try{return{content:[{type:"text",text:`🚀 Task created: ${(await e.startSubTask({agentId:t.agentId,message:{type:"user",message:{role:"user",content:t.instructions}},title:t.title,cwd:t.cwd,forceUserCwd:!t.useWorktree,initPolicies:{uncommittedChanges:"Ignore",branchMismatch:"Keep"}})).taskId}\n${t.briefSummary?`Summary: ${t.briefSummary}\n`:""}\nYou'll receive a <sub-task-result-updated> notification when the task completes. Continue responding to the user.`}]}}catch(e){return logger$4.error("Create solo task failed:",e),{content:[{type:"text",text:`Create solo task failed: ${e instanceof Error?e.message:"Unknown error"}`}],isError:!0}}})}function createGroupTaskTool({agentContext:e}){return claudeAgentSdk.tool("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:zod.z.string().min(1).max(200).describe("Task title"),requirement:zod.z.string().describe("Overall requirement"),briefSummary:zod.z.string().optional().describe("One-line summary shown to user immediately"),todos:zod.z.array(zod.z.object({agentId:zod.z.string().describe("Agent ID responsible for the todo"),title:zod.z.string().min(1).max(200).describe("Todo title"),instructions:zod.z.string().describe("Detailed instructions for this todo")})).min(1).describe("Todo list for agents")},async t=>{try{return{content:[{type:"text",text:`🚀 Task created: ${(await e.startGroupTask({title:t.title,todos:t.todos,initPolicies:{uncommittedChanges:"Ignore",branchMismatch:"Keep"},message:{type:"user",message:{role:"user",content:t.requirement}}})).taskId}\n${t.briefSummary?`Summary: ${t.briefSummary}\n`:""}\nYou'll receive a <sub-task-result-updated> notification when the task completes. Continue responding to the user.`}]}}catch(e){return logger$4.error("Dispatch failed:",e),{content:[{type:"text",text:`Dispatch failed: ${e instanceof Error?e.message:"Unknown error"}`}],isError:!0}}})}function createAskUserTool({askUser:e}){return claudeAgentSdk.tool("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:zod.z.array(zod.z.object({question:zod.z.string().describe("The complete question to ask the user"),header:zod.z.string().max(12).describe("Short label displayed as a chip/tag (max 12 chars)"),multiSelect:zod.z.boolean().describe("Set to true to allow multiple option selections"),options:zod.z.array(zod.z.object({label:zod.z.string().describe("Option label (1-5 words)"),description:zod.z.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 t=>{try{const n=t.questions.map(e=>({...e,options:[...e.options,{label:"Other",description:""}]})),a=await e(n);return"answered"!==(a.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${a.answers.map(e=>e.startsWith("other:")?`Other: "${e.slice(6)}"`:e).join("\n")}`}]}}catch(e){return logger$4.error("Failed to get user response:",e),{content:[{type:"text",text:`Failed to get user response: ${e instanceof Error?e.message:"Unknown error"}`}]}}})}function createInvokeTool({invokeAgent:e}){return claudeAgentSdk.tool("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:zod.z.string().describe("Target agent ID"),hint:zod.z.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 createUpdateAgentInfoTool({workClient:e,agentId:t,uploadFile:n}){return claudeAgentSdk.tool("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:zod.z.string().optional().describe("Your display name"),avatarPath:zod.z.string().optional().describe("Local path to avatar image file (png/jpg/svg)"),signature:zod.z.string().optional().describe("Short status line or tagline shown under your name")},async a=>{let s;if(a.avatarPath)try{s=(await n({name:"avatar.png",path:a.avatarPath,visibility:"public"})).fileId}catch(e){return logger$4.error("Avatar upload failed:",e),{content:[{type:"text",text:`Avatar upload failed: ${e}`}],isError:!0}}e.sendUpdateAgentInfo(t,{displayName:a.displayName,avatar:s,signature:a.signature});const i=[];return a.displayName&&i.push(`name → ${a.displayName}`),s&&i.push("avatar → uploaded"),a.signature&&i.push(`signature → ${a.signature}`),{content:[{type:"text",text:`Profile updated: ${i.join(", ")}`}]}})}function createAssignTool({assign:e}){return claudeAgentSdk.tool("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:zod.z.string().describe("Target agent ID"),instruction:zod.z.string().describe("Task instruction for the agent"),acknowledgment:zod.z.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 createListTasksTool({agentContext:e}){return claudeAgentSdk.tool("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:zod.z.number().int().min(1).max(50).default(10).optional().describe("Maximum number of tasks to return (default 10)."),status:zod.z.enum(["all","active","completed"]).default("all").optional().describe("Filter by task status: all, active, or completed.")},async t=>{try{const n=await e.listTasks({limit:t.limit??10,status:t.status??"all"});return n.length?{content:[{type:"text",text:JSON.stringify(n,null,2)}]}:{content:[{type:"text",text:"No tasks found."}]}}catch(e){return logger$4.error("Failed to list tasks:",e),{content:[{type:"text",text:`Failed to list tasks: ${e instanceof Error?e.message:"Unknown error"}`}],isError:!0}}})}function createReadConversationTool({chatHistoryDb:e}){return claudeAgentSdk.tool("read_conversation","Read messages from the main conversation between you and the user. Omit before to read the latest messages; only pass before when paginating to older messages.",{limit:zod.z.number().int().min(1).max(200).default(50).optional().describe("Number of recent messages to return (default 50)."),before:zod.z.number().int().min(0).optional().describe("Pagination cursor for older conversation history. Omit this field, or pass 0, to read the latest messages. Only pass a positive before value that was returned by the previous result as “Use before=N to load earlier messages”; it means return messages before that sequence, not start at that position.")},async t=>{if(!e)return{content:[{type:"text",text:"Chat history not available in this mode."}],isError:!0};const n=t.limit??50,a=null!=t.before&&t.before>0?e.pageMessagesBefore(t.before,n):e.pageRecentMessages(n);if(0===a.data.length)return{content:[{type:"text",text:"No conversation messages found."}]};let s=formatHistoryXml(a.data);return a.hasMore&&(s+=`\n\nMore messages available. Use before=${Math.min(...a.data.map(e=>e.localSequence))} to load earlier messages.`),{content:[{type:"text",text:s}]}})}function createSendReminderTool({agentContext:e}){return claudeAgentSdk.tool("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:zod.z.string().describe('Brief reminder message (one sentence, e.g., "Heartbeat architecture discussion pending for 2 days, consider following up")'),filePath:zod.z.string().optional().describe("Path to detailed analysis file in workspace, if any")},async t=>{try{const n=e.getChatId();return await e.sendMessage({taskId:n,message:{type:"companion_reminder",content:t.content,filePath:t.filePath,timestamp:(new Date).toISOString()},target:"agent"}),{content:[{type:"text",text:"Reminder sent to main companion."}]}}catch(e){return logger$4.error("Failed to send reminder:",e),{content:[{type:"text",text:`Failed to send reminder: ${e instanceof Error?e.message:"Unknown error"}`}],isError:!0}}})}const MemoryChangeActionSchema=zod.z.enum(["created","updated","deleted"]);function createRecordMemoryChangeTool({taskId:e}){return claudeAgentSdk.tool("record_memory_change","Append a structured JSONL record for an actual Companion memory change.\nUse this from Companion chat, heartbeat shadow, or memory-organization shadow after memory files were really created, updated, deleted, merged, compressed, or cleaned.\nDo not call this tool when the memory review found nothing to change.\nAfter recording an actual change, use send_reminder separately if the main Companion should be awakened.",{title:zod.z.string().optional().describe("Deprecated compatibility field; each change.summary is used for the JSONL record and semantic git commit title."),trigger:zod.z.enum(["scheduled","user_request"]).describe("What triggered this memory change."),source:zod.z.string().optional().describe("Where the changed memory fact came from, such as user correction, recent conversation, task history, reminder, existing memory consolidation, or verified project evidence. This is the memory evidence source, not the Companion execution path."),notifiedCompanion:zod.z.boolean().describe("Whether a reminder has already been sent or will be sent immediately after this record."),changes:zod.z.array(zod.z.object({file:zod.z.string().describe("Current primary self-evolution file path, relative to Companion claude home, such as memory/agentrix-companion-memory/memory.md or MEMORY.md. Legacy memory/-relative paths are accepted and normalized."),action:MemoryChangeActionSchema,summary:zod.z.string().describe("One-sentence summary of what changed."),reasons:zod.z.array(zod.z.string()).min(1).describe("Short reasons for this change."),deletedFiles:zod.z.array(zod.z.string()).optional().describe("Optional old allowlisted files removed while consolidating into file.")})).min(1).describe("One or more concrete file-bound memory changes for this topic.")},async t=>{try{const n=process.env.AGENTRIX_COMPANION_HOME;if(!n)throw new Error("AGENTRIX_COMPANION_HOME is not set; memory changes can only be recorded by Companion workers.");const a=new Date,s=a.toISOString().slice(0,10),i=path.join(n,"memory-changes"),o=path.join(i,`${s}.jsonl`),r=t.changes.map(e=>({file:resolveCompanionSelfEvolutionPath(n,e.file).relativePath,action:e.action,summary:e.summary,reasons:e.reasons,deletedFiles:e.deletedFiles?.map(e=>resolveCompanionSelfEvolutionPath(n,e).relativePath)??[]}));await ensureCompanionSelfEvolutionGitRepo({companionHome:n});const c=new Map;for(const e of r){const t=c.get(e.file);t?t.push(e):c.set(e.file,[e])}const l=[];for(const s of c.values()){const i=s[0],o=Array.from(new Set(s.flatMap(e=>e.deletedFiles))),r=await commitCompanionMemoryChange({companionHome:n,title:i.summary,body:buildMemoryChangeCommitBody({trigger:t.trigger,source:t.source,action:i.action,file:i.file,reasons:s.flatMap(e=>e.reasons),deletedFiles:o,notifiedCompanion:t.notifiedCompanion,taskId:e}),paths:[i.file,...o]});if(r)for(const n of s)l.push(JSON.stringify({time:a.toISOString(),trigger:t.trigger,source:t.source,taskId:e,file:n.file,action:n.action,summary:n.summary,reasons:n.reasons,deletedFiles:n.deletedFiles,notifiedCompanion:t.notifiedCompanion,commit:r}));else logger$4.warn(`Skipping memory change JSONL record because no semantic git commit was created: file=${i.file}`)}return l.length>0&&(await promises$2.mkdir(i,{recursive:!0}),await promises$2.appendFile(o,`${l.join("\n")}\n`,"utf-8")),logger$4.info(`Memory changes recorded: path=${o}, source=${t.source??"unspecified"}, trigger=${t.trigger}, records=${l.length}, requestedChanges=${r.length}, taskId=${e}`),{content:[{type:"text",text:l.length>0?`Memory changes recorded: ${l.length} JSONL record(s) at ${o}`:"No memory change JSONL records were written because no semantic git commit was created."}]}}catch(e){return logger$4.error("Failed to record memory change:",e),{content:[{type:"text",text:`Failed to record memory change: ${e instanceof Error?e.message:"Unknown error"}`}],isError:!0}}})}function createUploadFileTool({uploadFile:e}){return claudeAgentSdk.tool("upload_file","Upload a local file to the platform and get a public URL.\nUse this to share images, documents, or other files with the user.\nReturns a public URL that can be embedded in markdown (e.g., ![screenshot](url)).",{filePath:zod.z.string().describe("Absolute path to the local file to upload"),name:zod.z.string().optional().describe("Display name for the file (defaults to filename)")},async t=>{try{const n=require("path"),a=t.name||n.basename(t.filePath);return{content:[{type:"text",text:(await e({name:a,path:t.filePath,visibility:"public"})).url}]}}catch(e){return logger$4.error("File upload failed:",e),{content:[{type:"text",text:`File upload failed: ${e}`}],isError:!0}}})}const MAX_CHANNEL_ATTACHMENT_BYTES=2147483648,SENSITIVE_ATTACHMENT_NAME_RE=/(^\.env($|\.)|\.pem$|\.key$|\.p12$|\.pfx$|^id_rsa$|^id_dsa$|^id_ecdsa$|^id_ed25519$|credential|credentials|secret|secrets|token)/i;function createSendChannelMessageTool({taskId:e,chatId:t,historyDb:n,getChannelReplyTarget:a,onChannelMessageInvoked:s}){return claudeAgentSdk.tool("send_channel_message","Send a user-facing message back to the external channel that started this task.\n\nFor channel-bound tasks, normal successful final results are NOT automatically forwarded to the external channel after this tool has been used. You MUST call this tool for anything the external user should see. Before ending the task, ensure the external user has received an appropriate message through this tool. If you end without calling it, the user may see no model-directed response; that is considered a failed channel interaction even if the internal task result is complete.\n\nUse this for user-facing conversational output: acknowledgements, progress updates for long work, questions/choices/permission requests, clear failures or limitations, final answers, and user-facing deliverable notes.\n\nMessages should feel like natural conversation: short, clear, useful. Do not send internal reasoning, verbose logs, stack traces, debug dumps, internal-only summaries, temporary paths, environment variables, tokens, secrets, or private data. Avoid excessive implementation detail unless the user is explicitly collaborating technically and needs it.\n\nAttachments are part of this channel message. Attach only deliverables the user is meant to consume, save, view, or forward: generated images, PDFs, spreadsheets, reports, slide decks, archives, audio/video, or requested exports/packages.\n\nDo NOT send files merely because they were created, edited, read, downloaded, or used. A file created or modified while completing work is not automatically a deliverable; decide based on user intent. Do not decide based on file location or directory: a file inside the workspace can be a deliverable, and a file outside the workspace can still be unsafe or inappropriate. Logs, caches, temporary files, build artifacts, intermediate screenshots, debug outputs, and internal workflow files should not be sent unless the user explicitly asked for them. When modifying files, summarize changes in text unless the user asked to receive, export, package, or forward those files. Never send files containing secrets, credentials, tokens, private data, or local environment details. If the deliverable status is uncertain or sending might expose unintended content, ask for confirmation with this tool first.\n\nThe tool automatically sends to the original channel/chat for this task. Do not provide channel IDs or chat IDs.",{content:zod.z.string().optional().describe("Text to send to the external user. Required when attachments are omitted."),attachments:zod.z.array(zod.z.object({filePath:zod.z.string().describe("Absolute path to an existing user-facing deliverable file. Relative paths are rejected."),fileName:zod.z.string().optional().describe("Optional display filename shown to the external user. Defaults to the local basename."),kind:zod.z.enum(["auto","image","file","audio","video"]).optional().describe("Attachment kind. Use auto unless you know the exact type.")})).optional().describe("Optional user-facing deliverable files to send with the message.")},async i=>{const o=a?.()??null;if(!o)return{content:[{type:"text",text:"Unsupported: this task is not bound to an external channel, so no channel message can be sent."}],isError:!0};s?.();try{const a=i.content?.trim(),s=await validateChannelAttachments(i.attachments??[]);if(!a&&0===s.length)throw new Error("send_channel_message requires content or attachments");const r=await sendTaskChannelMessage(e,{content:a||void 0,attachments:s.length>0?s:void 0},o);return r?.error?(n.saveTaskEvent({taskId:e,chatId:t,eventType:"channel-message-send",sequence:null,eventData:{status:"error",channelId:o.channelId,hasContent:Boolean(a),attachments:s.map(e=>({filePath:e.filePath,fileName:e.fileName,kind:e.kind})),error:r.error}}),{content:[{type:"text",text:`Failed to send channel message: ${r.error}`}],isError:!0}):(n.saveTaskEvent({taskId:e,chatId:t,eventType:"channel-message-send",sequence:null,eventData:{status:"sent",channelId:o.channelId,hasContent:Boolean(a),attachments:s.map(e=>({filePath:e.filePath,fileName:e.fileName,mimeType:e.mimeType,kind:e.kind}))}}),{content:[{type:"text",text:s.length>0?`Sent channel message with ${s.length} attachment(s).`:"Sent channel message."}]})}catch(e){return logger$4.warn("Channel message send rejected or failed:",e),{content:[{type:"text",text:`Failed to send channel message: ${e instanceof Error?e.message:String(e)}`}],isError:!0}}})}function createGetChannelGroupHistoryTool({taskId:e,getChannelReplyTarget:t}){return claudeAgentSdk.tool("get_channel_group_history","Read older saved history for the external group chat bound to this task.\n\nUse this only when the automatically injected recent group history is not enough to understand context. This tool is read-only and automatically reads the current external channel group; do not provide channel IDs or chat IDs.\n\nThe result is XML-style history with sender metadata. Use it to understand context/history.",{limit:zod.z.number().int().positive().max(100).optional().describe("Maximum messages to return. Defaults to 30; capped at 100."),beforeSeq:zod.z.number().int().positive().optional().describe("Return messages before this local sequence number for older pages."),afterSeq:zod.z.number().int().nonnegative().optional().describe("Return messages after this local sequence number for newer pages. Do not combine with beforeSeq.")},async n=>{const a=t?.()??null;if(!a||"group"!==a.chatType?.toLowerCase())return{content:[{type:"text",text:"Unsupported: this task is not bound to an external channel group chat."}],isError:!0};if(void 0!==n.beforeSeq&&void 0!==n.afterSeq)return{content:[{type:"text",text:"Use beforeSeq or afterSeq, not both."}],isError:!0};const s=await getTaskChannelGroupHistory(e,a,{limit:n.limit,beforeSeq:n.beforeSeq,afterSeq:n.afterSeq});return s?.error?{content:[{type:"text",text:`Failed to read channel group history: ${s.error}`}],isError:!0}:{content:[{type:"text",text:`${[`hasMoreBefore=${Boolean(s.hasMoreBefore)}`,`hasMoreAfter=${Boolean(s.hasMoreAfter)}`].join(" ")}\n\n${s.historyXml??"<external_group_history />"}`}]}})}async function validateChannelAttachments(e){const t=[];for(const n of e)t.push(await validateChannelAttachment(n));return t}async function validateChannelAttachment(e){if(!path.isAbsolute(e.filePath))throw new Error("filePath must be absolute");const t=await promises$2.stat(e.filePath).catch(e=>{throw new Error(`filePath does not exist or cannot be read: ${e instanceof Error?e.message:String(e)}`)});if(!t.isFile())throw new Error("filePath must point to a regular file");if(t.size<=0)throw new Error("file is empty");if(t.size>2147483648)throw new Error(`file is too large for channel delivery (${t.size} bytes; max 2147483648 bytes)`);const n=e.fileName||path.basename(e.filePath),a=path.basename(e.filePath);if(SENSITIVE_ATTACHMENT_NAME_RE.test(a)||SENSITIVE_ATTACHMENT_NAME_RE.test(n))throw new Error("refusing to send an attachment with a sensitive-looking filename");const s=mimeTypesExports.lookup(n)||mimeTypesExports.lookup(e.filePath)||"application/octet-stream",i="string"==typeof s?s:"application/octet-stream",o=e.kind||"auto";return{filePath:e.filePath,fileName:e.fileName,kind:o,mimeType:i}}function createListAgentsTool({agentContext:e}){return claudeAgentSdk.tool("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(),a=e=>`- **${e.displayName||e.name}** (${e.id})\n Type: ${e.type}\n`+(e.developerName?` Developer: ${e.developerName}\n`:"")+` ${e.description||"No description"}\n`;let s="# Available Agents\n\n";return t.length>0&&(s+="## Published Agents\n\n",s+=t.map(a).join("\n")),n.length>0&&(s+="\n## Draft Agents\n\n",s+=n.map(a).join("\n")),0===t.length&&0===n.length&&(s+="No agents available."),{content:[{type:"text",text:s}]}}catch(e){return logger$4.error("Failed to list agents:",e),{content:[{type:"text",text:`Failed to list agents: ${e instanceof Error?e.message:"Unknown error"}`}],isError:!0}}})}async function*singleVisionMessage(e){yield e}function createAnalyzeImageTool({visionModel:e}){return claudeAgentSdk.tool("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:zod.z.string().describe("Absolute path to the image file to analyze"),prompt:zod.z.string().optional().describe("Optional specific question or instruction about the image (default: describe the image)")},async t=>{if(!e)return{content:[{type:"text",text:"Vision analysis is not available (missing configuration)."}],isError:!0};try{const n=(await promises$2.readFile(t.imagePath)).toString("base64"),a={type:"user",message:{role:"user",content:[{type:"image",source:{type:"base64",media_type:{jpg:"image/jpeg",jpeg:"image/jpeg",png:"image/png",gif:"image/gif",webp:"image/webp"}[t.imagePath.split(".").pop()?.toLowerCase()??"jpeg"]??"image/jpeg",data:n}},{type:"text",text:t.prompt||"Describe this image in detail."}]},parent_tool_use_id:null,session_id:""},s=claudeAgentSdk.query({prompt:singleVisionMessage(a),options:{model:e,permissionMode:"bypassPermissions",maxTurns:1,tools:[]}});let i="";for await(const e of s)if("result"===e.type){i=e.result??"";break}return{content:[{type:"text",text:i||"No description returned."}]}}catch(e){return logger$4.error("Failed to analyze image:",e),{content:[{type:"text",text:`Failed to analyze image: ${e instanceof Error?e.message:"Unknown error"}`}],isError:!0}}})}function createScheduleTaskTool(e){return claudeAgentSdk.tool("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:zod.z.enum(["create","list","delete"]).describe("Operation to perform"),task:zod.z.string().optional().describe("Task description (required for create)"),type:zod.z.enum(["once","recurring"]).optional().describe("Task type (required for create)"),due:zod.z.string().optional().describe("ISO 8601 timestamp for one-time tasks"),cron:zod.z.string().optional().describe('Cron expression for recurring tasks (e.g., "0 18 * * *")'),timezone:zod.z.string().optional().describe('IANA timezone (e.g., Asia/Shanghai). Required when timeType is "local"'),timeType:zod.z.enum(["utc","local"]).optional().describe('How to interpret time — "utc" for absolute UTC, "local" (default) for user timezone'),id:zod.z.string().optional().describe("Task ID (required for delete)")},async e=>{try{const t=await machine.machine.readDaemonState();if(!t?.port)return{content:[{type:"text",text:"Daemon not running."}],isError:!0};const n=`http://127.0.0.1:${t.port}`;if("list"===e.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 a=t.tasks??[];return 0===a.length?{content:[{type:"text",text:"No scheduled tasks."}]}:{content:[{type:"text",text:a.map(e=>`- [${e.id}] ${"once"===e.type?`once at ${e.due}`:`recurring: ${e.cron}`} — "${e.task}"`).join("\n")}]}}if("create"===e.action){if(!e.task||!e.type)return{content:[{type:"text",text:"Missing required fields: task, type"}],isError:!0};const t=await fetch(`${n}/schedule`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({task:e.task,type:e.type,due:e.due,cron:e.cron,timezone:e.timezone,timeType:e.timeType})}),a=await t.json();if(!t.ok)return{content:[{type:"text",text:`Error: ${a.error}`}],isError:!0};const s="once"===a.type?`due=${a.due}`:`cron=${a.cron}`;return{content:[{type:"text",text:`Scheduled: id=${a.id}, ${s}`}]}}if("delete"===e.action){if(!e.id)return{content:[{type:"text",text:"Missing required field: id"}],isError:!0};const t=await fetch(`${n}/schedule/${e.id}`,{method:"DELETE"}),a=await t.json();return t.ok?{content:[{type:"text",text:`Deleted: ${e.id}`}]}:{content:[{type:"text",text:`Error: ${a.error}`}],isError:!0}}return{content:[{type:"text",text:`Unknown action: ${e.action}`}],isError:!0}}catch(e){return logger$4.error("Schedule task failed:",e),{content:[{type:"text",text:`Failed: ${e instanceof Error?e.message:String(e)}`}],isError:!0}}})}function createPrepareHiveRepositoryTool({agentContext:e}){return claudeAgentSdk.tool("hive_prepare_repository","Prepare the Agentrix Hive source repository in the local global repo store.\n\nUse this before discovering community agents or skills. This tool only clones/pulls\nthe repository and returns the absolute checkout path. It does not search and does\nnot define the repository layout. After calling it, use Explore with a\ntask-specific goal to find relevant candidates; do not catalog the whole repo\nunless the user explicitly asks for a catalog. If pullSucceeded is false, inspect\nerror and continue with the existing local checkout when it is usable.",{},async()=>{try{const t=await e.prepareHiveRepository();return{content:[{type:"text",text:JSON.stringify(t,null,2)}]}}catch(e){return logger$4.error("Failed to prepare Hive repository:",e),{content:[{type:"text",text:`Failed to prepare Hive repository: ${e instanceof Error?e.message:String(e)}`}],isError:!0}}})}function createPublishToHiveTool({agentContext:e}){return claudeAgentSdk.tool("hive_publish","Publish a newly created agent or skill to Agentrix Hive after the user explicitly agrees.\n\nUse this for content created by this agent/user. Do not use it to republish\nsomeone else's Hive content that was installed locally. To change an owned\nexisting listing, use hive_update. To suggest changes for someone else's listing,\nmodify locally if needed and leave a hive_comment.",{type:zod.z.enum(["agent","skill"]),draftAgentId:zod.z.string().optional().describe("DraftAgent ID for agent publishing"),sourceDir:zod.z.string().optional().describe("Absolute local skill directory for skill publishing"),name:zod.z.string().optional().describe("Listing name, lowercase kebab-case"),displayName:zod.z.string().optional().describe("Human-readable listing name"),description:zod.z.string().optional(),readme:zod.z.string().optional(),category:zod.z.string().optional(),tags:zod.z.array(zod.z.string()).optional(),authorType:zod.z.enum(["user","agent"]).default("user"),authorId:zod.z.string(),machineId:zod.z.string().optional(),cloudId:zod.z.string().optional()},async t=>{try{const n=await e.publishToHive(t);return{content:[{type:"text",text:JSON.stringify(n,null,2)}]}}catch(e){return logger$4.error("Hive publish failed:",e),{content:[{type:"text",text:`Hive publish failed: ${e instanceof Error?e.message:String(e)}`}],isError:!0}}})}function createUpdateHiveListingVersionTool({agentContext:e}){return claudeAgentSdk.tool("hive_update","Publish a new version for an owned Hive listing after the user explicitly agrees.\n\nUse this only when the listing belongs to the user/agent. Do not use it for\nsomeone else's installed Hive content; for those, keep changes local and leave a\nhive_comment with concrete suggestions.",{listingId:zod.z.string().describe("Owned HiveListing ID to update"),version:zod.z.string().optional().describe("Optional new version; defaults to next patch version"),changelog:zod.z.string().optional(),sourceDir:zod.z.string().optional().describe("Absolute local skill directory for skill listing updates"),machineId:zod.z.string().optional(),cloudId:zod.z.string().optional()},async t=>{try{const{listingId:n,...a}=t,s=await e.updateHiveListingVersion(n,a);return{content:[{type:"text",text:JSON.stringify(s,null,2)}]}}catch(e){return logger$4.error("Hive update failed:",e),{content:[{type:"text",text:`Hive update failed: ${e instanceof Error?e.message:String(e)}`}],isError:!0}}})}function createRecordHiveInstallTool({agentContext:e}){return claudeAgentSdk.tool("hive_record_install","Record a Hive agent or skill after installing it locally.\n\nDo not use this tool to install. First prepare the Hive repository, inspect the\nsource for safety and relevance, ask the user if needed, and perform the local\nagent/skill install yourself. Then read the HiveListing ID from\nagentrix-hive-id.txt in the Hive source directory and pass it as listingId.",{listingId:zod.z.string().describe("HiveListing ID read from agentrix-hive-id.txt in the Hive source directory"),agentDir:zod.z.string().describe("Absolute local directory where the agent or skill was installed"),name:zod.z.string().optional().describe("Optional local name for installed agent"),machineId:zod.z.string().optional(),cloudId:zod.z.string().optional(),installedVersion:zod.z.string().optional()},async t=>{try{const{listingId:n,...a}=t,s=await e.recordHiveInstall(n,a);return{content:[{type:"text",text:JSON.stringify(s,null,2)}]}}catch(e){return logger$4.error("Hive install record failed:",e),{content:[{type:"text",text:`Hive install record failed: ${e instanceof Error?e.message:String(e)}`}],isError:!0}}})}function createHiveReviewTool({agentContext:e}){return claudeAgentSdk.tool("hive_review","Leave or update structured feedback for a Hive listing after using it or evaluating user/Syn feedback.",{listingId:zod.z.string().describe("HiveListing ID"),rating:zod.z.number().int().min(1).max(5),comment:zod.z.string().optional().describe("Markdown review text")},async t=>{try{const n=await e.createHiveReview(t.listingId,{rating:t.rating,comment:t.comment??null});return{content:[{type:"text",text:JSON.stringify(n,null,2)}]}}catch(e){return logger$4.error("Hive review failed:",e),{content:[{type:"text",text:`Hive review failed: ${e instanceof Error?e.message:String(e)}`}],isError:!0}}})}function createHiveCommentTool({agentContext:e}){return claudeAgentSdk.tool("hive_comment","Leave a discussion comment, bug report, usage suggestion, or reply for a Hive listing.",{listingId:zod.z.string().describe("HiveListing ID"),content:zod.z.string().min(1).describe("Markdown comment content"),parentId:zod.z.string().optional().describe("Parent comment ID for replies")},async t=>{try{const n=await e.createHiveComment(t.listingId,{content:t.content,parentId:t.parentId});return{content:[{type:"text",text:JSON.stringify(n,null,2)}]}}catch(e){return logger$4.error("Hive comment failed:",e),{content:[{type:"text",text:`Hive comment failed: ${e instanceof Error?e.message:String(e)}`}],isError:!0}}})}function normalizeWorkspacePath(e){if(e)return e.replace(/\/+$/g,"")||"/"}async function checkUncommittedChanges(e){return!!await isGitRepository(e)&&await hasUncommittedChanges(e)}async function handleUncommittedChanges(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 gitStash(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")}}function buildWorkspaceOptions(e){return{eventData:e.eventData,gitUrl:e.gitUrl,baseBranch:e.baseBranch,branchName:e.branchName,branchBinding:e.branchBinding,cwd:normalizeWorkspacePath(e.cwd)||"",userCwd:normalizeWorkspacePath(e.userCwd),forceUserCwd:e.forceUserCwd,useWorktree:e.useWorktree,initPolicies:e.initPolicies,userId:e.userId,taskId:e.taskId,repositorySourceType:e.repositorySourceType,taskRepositoryId:e.repositoryId,workspaceId:e.workspaceId,gitServerId:e.gitServerId,channelReplyTarget:e.channelReplyTarget}}function isExternalChannelWorkspaceTask(e){if(e.channelReplyTarget)return!0;const t=e.eventData;return"object"==typeof t&&null!==t&&"senderType"in t&&"channel"===t.senderType}function hasStrongBranchBinding(e){return!!e.branchName&&"none"!==e.branchBinding&&"external-observed"!==e.branchBinding}function buildShortTaskId(e){return e.replace(/^task-/,"").replace(/[^a-zA-Z0-9]/g,"").toLowerCase().slice(0,8)||"task"}function buildSemanticBranchSlug(e){return e.replace(/^[a-z]+(?:\([^)]+\))?!?:\s*/i,"").normalize("NFKD").replace(/[\u0300-\u036f]/g,"").toLowerCase().replace(/['’]/g,"").replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,48).replace(/-+$/g,"")||"task"}function resolvePublishBranchName(e,t,n){return t||(n?.trim()?`agentrix/${buildSemanticBranchSlug(n)}-${buildShortTaskId(e)}`:`agentrix/${e}`)}async function checkoutPublishBranchAtHead(e,t){const n=simpleGit(e);await n.raw(["checkout","-B",t,"HEAD"])}function buildHeadPushRef(e){return`HEAD:refs/heads/${e}`}function buildMergeRequestBranchMismatchMessage(e,t){return`Cannot create PR: current branch is ${e}, but this task is bound to ${t}. Switch to ${t} or choose Keep during branch mismatch handling before creating the PR.`}async function tryLoadPat(e){if(!e)return null;const t=await getGitServerEncryptionKey();return t?loadPat(e,t):null}async function configureGitIdentity(e,t){const n=loadPatMeta(t);if(!n)return void console.warn("[GIT] No PAT user metadata found, skipping git config");const a=n.username,s=n.email||`${n.username}@gitlab.local`;await setGitConfig(e,a,s),console.log(`[GIT] Set local git config user.name=${a} user.email=${s}`)}async function fetchTaskRemote(e,t,n){const a=await tryLoadPat(n);a?await fetchWithAskPass(a,e):await fetchWithRemoteUrl(t,e)}function resolveManagedBaseBranch(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.")}async function ensureRepoStoreReady(e,t,n,a){const s=sanitizeGitRemoteUrl(t);if(!await isGitRepository(e)){if(!isDirectoryEmpty(e))throw new Error(`Repo store directory ${e} exists but is not a git repository`);await gitInit(e)}await ensureRemote(e,"origin",s),await fetchTaskRemote(e,t,n);const i=resolveManagedBaseBranch(await listRemoteBranches(e),a);return await forceRefreshLocalBranchToStartPoint(e,i,`origin/${i}`),{baseBranch:i}}async function setupGitRepository(e,t,n,a,s,i){const o=sanitizeGitRemoteUrl(t),r=await isGitRepository(e);if(!isDirectoryEmpty(e)&&!r)throw new Error(`Directory ${e} exists but is not a git repository`);const c=await tryLoadPat(s);return isDirectoryEmpty(e)?(c?(console.log("[GIT] Using GIT_ASKPASS credential injection for clone"),await cloneWithAskPass(c,o,e),s&&await configureGitIdentity(e,s)):await gitClone(t,e),await updateRemoteUrl(e,"origin",o),i&&await ensureTaskBranch(e,i,a),await getCurrentCommitHash(e)):(await ensureRemote(e,"origin",o),await fetchTaskRemote(e,t,s),s&&await configureGitIdentity(e,s),i&&await ensureTaskBranch(e,i,a),await getCurrentCommitHash(e))}async function pushForTask(e,t,n,a={}){const s=await tryLoadPat(a.gitServerId);s?await pushWithAskPass(s,e,t,n):a.gitUrl?await pushWithRemoteUrl(a.gitUrl,e,t,n):await gitPush(e,t,n)}async function setupGitServerWorktreeWorkspace(e,t,n,a,s,i){const o=normalizeWorkspacePath(e)||e,r=sanitizeGitRemoteUrl(n),c=parseRemoteInfoFromUrl(r);if(!c)throw new Error(`Unable to resolve repository owner/name from git URL: ${r}`);const l=machine.machine.resolveRepoStoreCheckoutDir(a,c.owner,c.repo),d=machine.machine.resolveRepoStoreLockPath(a,c.owner,c.repo),p=await machine.machine.acquireFileLock(d);if(!p)throw new Error(`Timed out waiting for repo store lock at ${d}`);try{await ensureRepoStoreReady(l,n,a,s);const e=i,t=await listWorktrees(l);if(t.find(e=>normalizeWorkspacePath(e.path)===o))return a&&await configureGitIdentity(o,a),{initialCommitHash:await getCurrentCommitHash(o)};const r=e?t.find(t=>t.branch===e&&normalizeWorkspacePath(t.path)!==o):void 0;if(e&&r)throw new Error(`Branch ${e} is already attached to worktree ${r.path}. Remove it before retrying.`);const c=simpleGit(l),d=await c.branchLocal(),p=!!e&&d.all.includes(e);if(fs.existsSync(o)&&!isDirectoryEmpty(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{e?p?await c.raw(["worktree","add",o,e]):await createWorktree(l,o,e,"HEAD"):await c.raw(["worktree","add",o,"HEAD"])}catch(e){try{await removeWorktree(l,o,!0)}catch{}throw e}return await configureGitIdentity(o,a),{initialCommitHash:await getCurrentCommitHash(o)}}finally{await machine.machine.releaseFileLock(d,p)}}async function initializeGitRepository(e){return await gitInit(e),await initialCommit(e),await getCurrentCommitHash(e)}async function tryAssociateRepository(e,t){try{const n=await getRemoteInfo(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)}}async function setupTmpRepoWorkspace(e){return{initialCommitHash:await initializeGitRepository(e)}}async function setupWorktreeWorkspace(e,t,n,a){const s=e.replace(/^~/,os.homedir()),i=normalizeWorkspacePath(t)||t;if(!await isGitRepository(s))throw new Error(`Directory ${s} is not a git repository. Worktrees can only be created from existing git repositories.`);if(!await hasAnyCommits(s))throw new Error(`Cannot create worktree: repository at ${s} has no commits. Please create an initial commit first: cd ${s} && git add . && git commit -m 'Initial commit'`);const o=a;if((await listWorktrees(s)).find(e=>normalizeWorkspacePath(e.path)===i))return{initialCommitHash:await getCurrentCommitHash(i)};const r=simpleGit(s),c=await r.branchLocal(),l=!!o&&c.all.includes(o);if(fs.existsSync(i)&&!isDirectoryEmpty(i))throw new Error(`Worktree directory already exists at ${i}. This may be from a previous task. To clean up: git worktree remove ${i} OR rm -rf ${i}`);try{o?l?await r.raw(["worktree","add",i,o]):await createWorktree(s,i,o,"HEAD"):await r.raw(["worktree","add",i,"HEAD"])}catch(e){try{await removeWorktree(s,i,!0)}catch{}throw e}return{initialCommitHash:await getCurrentCommitHash(i)}}async function saveTaskPatchDiff(e,t,n){const a=n.trim();if(!a)return;const s=machine.machine.resolveDataDir(e,t),i=path.join(s,"patch.diff");return await promises$1.mkdir(s,{recursive:!0}),await promises$1.writeFile(i,`${a}\n`),i}async function handleGitState(e,t,n,a){if(!await isGitRepository(e))return{currentCommitHash:"",hadUncommittedChanges:!1,hasNewArtifacts:!1,lastSentArtifactVersion:void 0,patchPath:"",diffStats:void 0};const s=await hasUncommittedChanges(e),i=await getCurrentCommitHash(e),o=a||machine.machine.getWorkspaceState(t,n)?.initialCommitHash;if(!o)throw new Error(`Initial commit hash not found for task ${n}`);const r=await getWorkspaceArtifactsSnapshot(e,o),c=r?await saveTaskPatchDiff(t,n,r.patch):void 0,l=await machine.machine.readLastSentArtifactVersion(t,n),d=!!r&&r.artifactVersion!==l;return{currentCommitHash:i,currentArtifactVersion:r?.artifactVersion,hadUncommittedChanges:s,hasNewArtifacts:d,lastSentArtifactVersion:l??void 0,patchPath:c,diffStats:r?.stats}}async function handleGitStateOnWorkerStart(e,t,n,a){return handleGitState(e,t,n,a)}async function markArtifactVersionAsSent(e,t,n){await machine.machine.writeLastSentArtifactVersion(e,t,n)}function applyTemplateVariables(e,t){return e.replace(/\{\{initialCommitHash\}\}/g,t.initialCommitHash).replace(/\{\{currentCommitHash\}\}/g,t.currentCommitHash).replace(/\{\{branchName\}\}/g,t.branchName)}function applyPRPromptTemplate(e,t){return applyTemplateVariables(e,t)}function buildPRRequestPrompt(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 createCommandResultMessage(e,t,n){return{type:"result",subtype:n?"error_during_execution":"success",duration_ms:0,duration_api_ms:0,is_error:n,num_turns:0,result:e,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:[],terminal_reason:n?`exit_code_${t}`:"completed",session_id:"",uuid:crypto$1.randomUUID()}}function createCommandAssistantMessage(e){return{type:"assistant",message:{role:"assistant",content:[{type:"text",text:e}]},parent_tool_use_id:null,session_id:"",uuid:crypto$1.randomUUID()}}function formatCommandOutput(e){const t="```sh\n",n="\n```";return`${t}${truncateToolResultContent(e.trim()?e:"[Command completed with no output]",1024-Buffer.byteLength(t,"utf8")-Buffer.byteLength(n,"utf8"))}${n}`}function executeCommandStreaming(e,t,n,a=6e4){return new Promise(s=>{const i=child_process.spawn("/bin/bash",["-c",e],{cwd:t,env:process.env,shell:!1});let o=null,r=!1;a>0&&(o=setTimeout(()=>{r=!0,i.kill("SIGTERM"),setTimeout(()=>{i.killed||i.kill("SIGKILL")},1e3)},a));let c="";i.stdout?.on("data",e=>{c+=e.toString()}),i.stderr?.on("data",e=>{c+=e.toString()}),i.on("close",(e,t)=>{let i,l,d;if(o&&clearTimeout(o),r){i=124,d=!0;const e=`\n[Command timed out after ${a/1e3} seconds]`;l=c?`${c}${e}`:e.trim()}else i=null!==e?e:"SIGTERM"===t?143:1,d=0!==i,l=c;const p=formatCommandOutput(l);n.onOutput(createCommandAssistantMessage(p)),n.onOutput(createCommandResultMessage(p,i,d)),n.onComplete(i),s(i)}),i.on("error",e=>{o&&clearTimeout(o);const t=formatCommandOutput(`[Error] ${e.message||"Command execution failed"}`);n.onOutput(createCommandAssistantMessage(t)),n.onOutput(createCommandResultMessage(t,1,!0)),n.onComplete(1),s(1)})})}const logger$3=machine.createModuleLogger("undefined"==typeof document?require("url").pathToFileURL(__filename).href:_documentCurrentScript&&"SCRIPT"===_documentCurrentScript.tagName.toUpperCase()&&_documentCurrentScript.src||new URL("index.cjs",document.baseURI).href);class Coordinator{config;messageQueue=[];agentMessageQueue=[];agentMessageResolver=null;workerState="idle";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}:"![agentrix-dev-init]"===t?{type:"agentrix-dev-init",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 logger$3.warn("Ignoring message - coordinator is stopped");if(!("user"!==e.type||e.message&&"object"==typeof e.message&&"content"in e.message))return void logger$3.warn("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),logger$3.debug(`message.enqueued id=${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();logger$3.debug(`message.processing id=${e.id} type=${e.type}`),await this.processMessage(e),logger$3.debug(`message.dispatched id=${e.id} type=${e.type}`)}catch(e){logger$3.error(`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"agentrix-dev-init":await this.processAgentrixDevInit(e);break;case"plan-mode":await this.processPlanMode(e);break;default:logger$3.warn(`Unknown message type: ${e.type}`)}}async processNormalMessage(e){logger$3.debug("message.dispatching_to_agent_queue type=normal");const t=await this.config.handlers.onNormalMessage(e.originalMessage);this.enqueueAgentMessage(t)}async processBashCommand(e){logger$3.info(`Processing bash command: ${e.content}`),await this.processCommand(async()=>{await this.config.handlers.onBashCommand(e.content,e.originalMessage)},e)}async processMergeRequest(e){logger$3.info("Processing merge-request command"),await this.processCommand(async()=>{await this.config.handlers.onMergeRequest(e.originalMessage)},e)}async processMergePr(e){logger$3.info("Processing merge-pr command"),await this.processCommand(async()=>{await this.config.handlers.onMergePr()},e)}async processNewSession(e){logger$3.info("Processing new-session command"),await this.processCommand(async()=>{await(this.config.handlers.onNewSession?.())},e)}async processAgentrixDevInit(e){logger$3.info("Processing agentrix-dev-init command"),await this.processCommand(async()=>{await(this.config.handlers.onAgentrixDevInit?.(e.originalMessage))},e)}async processPlanMode(e){logger$3.info("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");logger$3.debug("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.workerState=e,logger$3.info(`worker.state.changed from=${t} to=${e} activeAgents=${this.agentRunningMap.size} backgroundTasks=${this.backgroundTaskMap.size+this.anonymousBackgroundTaskCount}`),"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 a="running"===this.workerState,s=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(),a&&"running"===this.workerState&&i!==s&&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,logger$3.debug(`Background task ${e} completed via anonymous fallback (remaining: ${this.anonymousBackgroundTaskCount})`)),this.tryUpdateWorkerState())}setAnonymousBackgroundTaskRunning(e){e?(this.anonymousBackgroundTaskCount+=1,logger$3.debug(`Anonymous background task started (count: ${this.anonymousBackgroundTaskCount})`)):this.anonymousBackgroundTaskCount>0&&(this.anonymousBackgroundTaskCount-=1,logger$3.debug(`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)logger$3.warn("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||(logger$3.info(`worker.idle_timer.started timeoutMs=${this.idleTimeoutMs}`),this.idleTimeoutHandle=setTimeout(()=>{this.idleTimeoutHandle=null,this.isStopped||(logger$3.info(`worker.stop.requested reason=idle_timeout source=coordinator timeoutMs=${this.idleTimeoutMs}`),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.isStopped?logger$3.debug("coordinator.stop.ignored alreadyStopped=true"):(logger$3.info("coordinator.stop requested=true"),this.isStopped=!0,this.clearIdleTimer(),this.messageQueue=[],this.agentMessageQueue=[],this.backgroundTaskMap.clear(),this.anonymousBackgroundTaskCount=0,this.cancelAgentWait())}}function sendMessage(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(system_sender,n)}async function executeMergePr(e){const{workingDirectory:t,workClient:n,repositoryId:a,gitServerId:s,gitUrl:i,logger:o,allowInteractive:r=!0,askUser:c,commitChanges:l}=e;if(o.info("[MERGE-PR] Executing merge-pr command"),a){try{const e=await getCurrentBranch(t),a=await hasUncommittedChanges(t),d=await hasUnpushedCommits(t,e);if(a||d){if(!r)throw new Error("merge-pr requires user input to resolve git state, which is not supported in oneshot execution mode");const p=await askMergePrAction(a,d,c,o);if("Pause"===p)return void sendMessage(n,"Operation paused. Please handle git state and run merge again.");if(("Push"===p||"PushAndMerge"===p)&&(a&&(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 pushForTask(t,e,!1,{gitServerId:s,gitUrl:i}),"Push"===p))return void sendMessage(n,"✅ All changes pushed to remote. You can now review and run merge again if everything looks good.")}const p=await n.sendMergePr();if(p.success)sendMessage(n,`✅ PR merged successfully! Branch ${e} has been merged into the target branch.`);else{let e;switch(p.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: ${p.error||"Unknown error"}`;break;default:e=`Failed to merge PR: ${p.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.")}async function askMergePrAction(e,t,n,a){let s="";s=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:s,header:"Git Status",multiSelect:!1,options:[{label:"Pause",description:"Stop operation, handle git state manually"},{label:"Push",description:"Push changes and review before merging"},{label:"Push and Merge",description:"Push changes and merge PR immediately"}]}];try{const e=(await n(i)).answers[0];return e.startsWith("other:")?(a.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 a.error("[MERGE-PR] Ask user failed:",e),"Pause"}}async function applyTaskInfoUpdate(e,t,n){let a=!1;const s=e.updates??{};if(Object.prototype.hasOwnProperty.call(s,"model")){const e=s.model,n="string"==typeof e&&e.trim().length>0?e.trim():null===e?void 0:t.model;t.model!==n&&(n?t.model=n:delete t.model,a=!0)}const i={},o=s.repositoryId;"string"==typeof o&&o.length>0&&t.repositoryId!==o&&(t.repositoryId=o,i.taskRepositoryId=o,a=!0);const r=s.branchName;"string"==typeof r&&r.length>0&&t.branchName!==r&&(t.branchName=r,i.branchName=r,a=!0);const c=s.branchBinding;return"none"!==c&&"explicit"!==c&&"platform-managed"!==c&&"external-observed"!==c||t.branchBinding===c||(t.branchBinding=c,i.branchBinding=c,a=!0),Object.keys(i).length>0&&n&&await n.updateTaskMetadata(i),a}function normalizeAskUserResponse(e){const t=e.status??"answered";return e.status&&e.reason?e:{...e,status:t,reason:e.reason??("timeout"===t?"timeout":"user")}}function askUserWithTimeout(e,t,n,a={}){const s=n.sendAskUser(e),i=a.timeoutMs??18e5,o=a.onTimeout;return new Promise((e,a)=>{const r=setTimeout(()=>{t.delete(s);const i={type:"ask_user_response",answers:[],status:"timeout",reason:"timeout"};n.sendAskUserResponse(s,i),"abort_task"===o?(n.onTimeoutMessage?.("ask_user timed out. Task cancelled."),n.stopTask?.("ask_user_timeout"),a(new Error("Ask user request timed out"))):e(i)},i);t.set(s,t=>{clearTimeout(r),e(normalizeAskUserResponse(t))})})}function createSyntheticInitMessage(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:node_crypto.randomUUID(),session_id:e.sessionId}}function generateAndMapToolId(e,t){const n=node_crypto.randomUUID();return t.set(e,n),n}function getMappedToolId(e,t){return t.get(e)||e}function convertThreadEventToSDKMessage(e,t,n={}){return"thread.started"===e.type||"turn.started"===e.type||"turn.completed"===e.type||"turn.failed"===e.type?null:"error"===e.type?convertStreamError(e.message):"item.started"===e.type?convertItemStarted(e.item,t):"item.completed"===e.type?convertItemCompleted(e.item,t,n):null}function convertStreamError(e){return{type:"system",subtype:"temporary",content:e}}function convertItemStarted(e,t){switch(e.type){case"command_execution":return convertCommandExecutionStarted(e,t);case"file_change":return convertFileChangeStarted(e,t);case"mcp_tool_call":return convertMcpToolCallStarted(e,t);case"web_search":return convertWebSearchStarted(e,t);default:return null}}function convertItemCompleted(e,t,n){switch(e.type){case"agent_message":return convertAgentMessage(e);case"reasoning":default:return null;case"command_execution":return convertCommandExecutionCompleted(e,t);case"file_change":return convertFileChangeCompleted(e,t);case"mcp_tool_call":return convertMcpToolCallCompleted(e,t,n);case"web_search":return convertWebSearchCompleted(e,t);case"todo_list":return convertTodoList(e);case"error":return convertError(e)}}function convertAgentMessage(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:node_crypto.randomUUID().toString()}}function convertCommandExecutionStarted(e,t){return{type:"assistant",message:{role:"assistant",content:[{type:"tool_use",id:generateAndMapToolId(e.id,t),name:"Bash",input:{command:e.command}}]},parent_tool_use_id:null,session_id:""}}function convertCommandExecutionCompleted(e,t){return{type:"user",message:{role:"user",content:[{type:"tool_result",tool_use_id:getMappedToolId(e.id,t),content:"failed"===e.status?"Command execution failed":e.aggregated_output||""}]},parent_tool_use_id:null,session_id:""}}function convertFileChangeStarted(e,t){return{type:"assistant",message:{role:"assistant",content:[{type:"tool_use",id:generateAndMapToolId(e.id,t),name:"Edit",input:{changes:e.changes.map(e=>({kind:e.kind,path:e.path}))}}]},parent_tool_use_id:null,session_id:""}}function convertFileChangeCompleted(e,t){const n=t.get(e.id),a=n??generateAndMapToolId(e.id,t),s=!n;(e.changes||[]).map(e=>`${e.kind}: ${e.path}`);const i={type:"assistant",message:{role:"assistant",content:[{type:"tool_use",id:a,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:a,content:"failed"===e.status?"File changes failed":"File changes completed"}]},parent_tool_use_id:null,session_id:""};return s?[i,o]:o}function convertMcpToolCallStarted(e,t){return{type:"assistant",message:{role:"assistant",content:[{type:"tool_use",id:generateAndMapToolId(e.id,t),server_name:e.server,name:e.tool,input:e.arguments}]},parent_tool_use_id:null,session_id:""}}function convertMcpToolCallCompleted(e,t,n){const a=getMappedToolId(e.id,t),s="failed"===e.status&&e.error;return{type:"user",message:{role:"user",content:[{type:"tool_result",tool_use_id:a,is_error:s,content:s?e.error.message:normalizeMcpToolResultContent(e,n)}]},parent_tool_use_id:null,session_id:""}}function normalizeMcpToolResultContent(e,t){const n=e.result?.content||"";if(!t.taskDataDir||!isComputerUseImageTool(e.tool))return n;if(!Array.isArray(n)){const a=convertImageBlockToTaskDataReference(n,t.taskDataDir);if(a!==n)return[a];const s=convertScreenshotOutFileToTaskDataReference(e,t.taskDataDir);return s?[n,s]:n}const a=n.map(e=>convertImageBlockToTaskDataReference(e,t.taskDataDir)),s=convertScreenshotOutFileToTaskDataReference(e,t.taskDataDir);return s?[...a,s]:a}function isComputerUseImageTool(e){return"get_window_state"===e||"screenshot"===e||e.endsWith("__get_window_state")||e.endsWith("__screenshot")}function convertImageBlockToTaskDataReference(e,t){const n=extractImageData(e);if(!n)return e;try{const e=path.join(t,"attachments");fs.mkdirSync(e,{recursive:!0});const a=extensionForMimeType(n.mimeType),s=path.join(e,`${node_crypto.randomUUID()}${a}`);return fs.writeFileSync(s,Buffer.from(n.base64,"base64")),{type:"text",text:`Image file: ${s}\nType: ${n.mimeType}`}}catch(e){return{type:"text",text:`[Image unavailable: failed to save tool result image: ${e instanceof Error?e.message:String(e)}]`}}}function convertScreenshotOutFileToTaskDataReference(e,t){const n=getScreenshotOutFilePath(e);if(!n||!fs.existsSync(n))return null;try{const e=path.join(t,"attachments");fs.mkdirSync(e,{recursive:!0});const a=imageExtensionFromPath(n),s=mimeTypeForExtension(a),i=path.join(e,`${node_crypto.randomUUID()}${a}`);return fs.copyFileSync(n,i),{type:"text",text:`Image file: ${i}\nType: ${s}`}}catch(e){return{type:"text",text:`[Image unavailable: failed to copy screenshot_out_file: ${e instanceof Error?e.message:String(e)}]`}}}function getScreenshotOutFilePath(e){const t=e.arguments,n=t?.screenshot_out_file;return"string"==typeof n&&n.trim()?n.trim():null}function extractImageData(e){if("object"!=typeof e||null===e)return null;const t=e,n=t.data,a=n&&"object"==typeof n?n:void 0,s="string"==typeof t.mimeType?t.mimeType:"string"==typeof t.mime_type?t.mime_type:"string"==typeof a?.mimeType?a.mimeType:"string"==typeof a?.mime_type?a.mime_type:"image/png";if(!s.startsWith("image/"))return null;const i="string"==typeof t.base64String?t.base64String:"string"==typeof t.base64_string?t.base64_string:"string"==typeof a?.base64String?a.base64String:"string"==typeof a?.base64_string?a.base64_string:"string"==typeof n?n:void 0;return i?{base64:stripDataUrlPrefix(i),mimeType:s}:null}function stripDataUrlPrefix(e){const t=e.match(/^data:[^;]+;base64,(.*)$/s);return t?t[1]:e}function extensionForMimeType(e){switch(e.toLowerCase()){case"image/jpeg":case"image/jpg":return".jpg";case"image/webp":return".webp";case"image/gif":return".gif";default:return".png"}}function imageExtensionFromPath(e){const t=path.extname(e).toLowerCase();return[".png",".jpg",".jpeg",".webp",".gif"].includes(t)?".jpeg"===t?".jpg":t:".png"}function mimeTypeForExtension(e){switch(e.toLowerCase()){case".jpg":case".jpeg":return"image/jpeg";case".webp":return"image/webp";case".gif":return"image/gif";default:return"image/png"}}function convertWebSearchStarted(e,t){return{type:"assistant",message:{role:"assistant",content:[{type:"tool_use",id:generateAndMapToolId(e.id,t),name:"web_search",input:{query:e.query}}]},parent_tool_use_id:null,session_id:""}}function convertWebSearchCompleted(e,t){return{type:"user",message:{role:"user",content:[{type:"tool_result",tool_use_id:getMappedToolId(e.id,t),content:{type:"web_search_result",results:[]}}]},parent_tool_use_id:null,session_id:""}}function convertTodoList(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:""}}function convertError(e){return{type:"assistant",message:{role:"assistant",content:`❌ Error: ${e.message}`},parent_tool_use_id:null,session_id:""}}let cachedConfigModel,cachedConfigPath,codexPathOverrideCache;function stripInlineComment(e){let t=null,n=!1;for(let a=0;a<e.length;a+=1){const s=e[a];if(n)n=!1;else if("\\"!==s||'"'!==t)if('"'!==s&&"'"!==s||null!==t)if(s!==t){if("#"===s&&null===t)return e.slice(0,a)}else t=null;else t=s;else n=!0}return e}function parseTomlString(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 getCodexConfigPath(){const e=process.env.CODEX_HOME||process.env.AGENTRIX_CODEX_HOME||path.join(os.homedir(),".codex");return path.join(e.replace(/^~(?=\/|$)/,os.homedir()),"config.toml")}function readCodexDefaultModel(){const e=getCodexConfigPath();if(cachedConfigPath===e&&void 0!==cachedConfigModel)return cachedConfigModel;if(cachedConfigPath=e,cachedConfigModel=null,!fs.existsSync(e))return cachedConfigModel;let t;try{t=fs.readFileSync(e,"utf8")}catch{return cachedConfigModel}for(const e of t.split(/\r?\n/)){const t=stripInlineComment(e).trim();if(!t)continue;if(t.startsWith("["))break;const n=t.match(/^model\s*=\s*(.+)$/);if(!n)continue;const a=parseTomlString(n[1])?.trim();return cachedConfigModel=a||null,cachedConfigModel}return cachedConfigModel}function resolveCodexModel(e){const t=e?.trim();return t||readCodexDefaultModel()}function resolveCodexPathOverride(){if(void 0!==codexPathOverrideCache)return codexPathOverrideCache??void 0;const e=process.env.AGENTRIX_CODEX_PATH?.trim();if(e)return codexPathOverrideCache=e,e;codexPathOverrideCache=null}function buildDeveloperInstructions(e){const t=[];e.modeConfig.supportChangeTitle&&e.codexAgentrixEventMcp&&("work"===e.modeConfig.mode||"group_work"===e.modeConfig.mode)&&t.push(buildCodexEventBrokerTitlePrompt({serverName:e.codexAgentrixEventMcp.serverName,toolName:e.codexAgentrixEventMcp.titleToolName})),e.codexAgentrixEventMcp&&e.codexAgentrixEventMcp.previewToolName&&("work"===e.modeConfig.mode||"group_work"===e.modeConfig.mode)&&t.push(buildCodexEventBrokerPreviewPrompt({serverName:e.codexAgentrixEventMcp.serverName,toolName:e.codexAgentrixEventMcp.previewToolName})),e.codexAgentrixEventMcp&&e.codexAgentrixEventMcp.sendVisionArtifactToolName&&("work"===e.modeConfig.mode||"group_work"===e.modeConfig.mode)&&t.push(buildCodexEventBrokerVisionArtifactPrompt({serverName:e.codexAgentrixEventMcp.serverName,toolName:e.codexAgentrixEventMcp.sendVisionArtifactToolName}));const n=e.projectAgentrixGuidance?.systemPromptAppend?.trim();return n&&t.push(n),t.length>0?t.join("\n\n"):void 0}function applyCodexAgentrixEventMcpConfig(e,t){const n=t.codexAgentrixEventMcp;if(!n)return;const a=e.config??{},s=a.mcp_servers&&"object"==typeof a.mcp_servers&&!Array.isArray(a.mcp_servers)?a.mcp_servers:{};e.config={...a,mcp_servers:{...s,[n.serverName]:{url:n.url,bearer_token_env_var:n.tokenEnvVar}}}}class CodexRunner{createCodex(e){const t={},n=resolveCodexPathOverride();n&&(t.codexPathOverride=n),e.env&&(t.env=mergeEnvironment(e.env));const a=buildDeveloperInstructions(e);return a&&(t.config={...t.config??{},developer_instructions:a}),applyCodexAgentrixEventMcpConfig(t,e),new codexSdk.Codex(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,a=this.createCodex(t),s=resolveCodexModel(t.model),i={workingDirectory:t.cwd,model:s??void 0,sandboxMode:"danger-full-access",approvalPolicy:"never",skipGitRepoCheck:!0},o=t.agentSessionId?a.resumeThread(t.agentSessionId,i):a.startThread(i),r=Date.now(),c=await o.run("string"==typeof e?e:extractUserMessageText(e),{signal:n.signal,outputSchema:t.structuredOutputSchema?.schema||void 0}),l=Date.now()-r;return createSdkResultMessage({sessionId:o.id??t.agentSessionId??"unknown",model:s??"unknown",numTurns:1,usage:c.usage??{input_tokens:0,cached_input_tokens:0,output_tokens:0,reasoning_output_tokens:0},result:c.finalResponse??"",structuredOutput:parseStructuredOutputTextOrThrow(c.finalResponse??"",Boolean(t.structuredOutputSchema)),durationMs:l})}async*runStreamed(e,t){const n=t.abortController,a=this.createCodex(t),s=resolveCodexModel(t.model),i={workingDirectory:t.cwd,model:s??void 0,sandboxMode:"danger-full-access",approvalPolicy:"never",skipGitRepoCheck:!0},o=t.agentSessionId?a.resumeThread(t.agentSessionId,i):a.startThread(i),r=Date.now(),{events:c}=await o.runStreamed("string"==typeof e?e:extractUserMessageText(e),{signal:n.signal,outputSchema:t.structuredOutputSchema?.schema||void 0});let l=t.agentSessionId||"",d="",p={input_tokens:0,cached_input_tokens:0,output_tokens:0,reasoning_output_tokens:0};const u=new Map,m={get:e=>u.get(e),set:(e,t)=>{u.set(e,t)}};for await(const e of c){if("thread.started"===e.type&&(l=e.thread_id,yield createSyntheticInitMessage({sessionId:l,cwd:t.cwd,model:s??void 0})),"turn.completed"===e.type){e.usage&&(p=e.usage);break}if("turn.failed"===e.type)throw new Error(e.error.message);if("item.completed"===e.type&&"agent_message"===e.item.type&&e.item.text&&(d=e.item.text),"error"===e.type||"item.started"===e.type||"item.completed"===e.type){const n=convertThreadEventToSDKMessage(e,m,{taskDataDir:t.taskDataDir});if(!n)continue;const a=Array.isArray(n)?n:[n];for(const e of a)yield e}}const h=createSdkResultMessage({sessionId:l,model:s??"unknown",numTurns:1,usage:p,result:d,structuredOutput:parseStructuredOutputTextOrThrow(d,Boolean(t.structuredOutputSchema)),durationMs:Date.now()-r});yield h}loop(e){const t=e.abortController,n=this.createCodex(e),a={workingDirectory:e.cwd,sandboxMode:"danger-full-access",approvalPolicy:"never",skipGitRepoCheck:!0};let s=e.model;const i=()=>resolveCodexModel(e.getModel?e.getModel():s)??void 0;let o=i(),r=e.agentSessionId?n.resumeThread(e.agentSessionId,{...a,model:o??void 0}):n.startThread({...a,model:o??void 0}),c=!1;const l=[];let d=null,p=e.agentSessionId??null,u=0;const m=()=>{if(!c&&(c=!0,d)){const e=d;d=null,e(null)}},h=e=>"string"==typeof e?e:extractUserMessageText(e),g=async function*(){try{for(;!c&&!t.signal.aborted;){const s=l.length>0?l.shift():await new Promise(e=>{d=e});if(!s)break;let m="";const g=i();g!==o&&(o=g),p&&(r=n.resumeThread(p,{...a,model:o??void 0}));const f=new Map,y={get:e=>f.get(e),set:(e,t)=>{f.set(e,t)}},v=Date.now(),{events:b}=await r.runStreamed(h(s),{signal:t.signal,outputSchema:e.structuredOutputSchema?.schema||void 0});for await(const t of b){if(c)break;if("thread.started"!==t.type){if("turn.completed"===t.type){p&&(yield createSdkResultMessage({sessionId:p,model:o??"unknown",numTurns:u+1,usage:t.usage??{input_tokens:0,cached_input_tokens:0,output_tokens:0},result:m,structuredOutput:parseStructuredOutputTextOrThrow(m,Boolean(e.structuredOutputSchema)),durationMs:Date.now()-v}));break}if("turn.failed"===t.type)throw new Error(t.error.message);if("error"===t.type||"item.started"===t.type||"item.completed"===t.type){"item.completed"===t.type&&"agent_message"===t.item.type&&t.item.text&&(m=t.item.text);const n=convertThreadEventToSDKMessage(t,y,{taskDataDir:e.taskDataDir});if(!n)continue;const a=Array.isArray(n)?n:[n];for(const e of a)yield e}}else p=t.thread_id,yield createSyntheticInitMessage({sessionId:p,cwd:e.cwd,model:o??void 0})}u+=1}}finally{m()}}();return t.signal.addEventListener("abort",m,{once:!0}),{push:e=>{if(!c){if(d){const t=d;return d=null,void t(e)}l.push(e)}},events:g,stop:m,setModel:async e=>{s=e,o=resolveCodexModel(e)??void 0}}}}const runtimeImport=new Function("specifier","return import(specifier)");function importRuntimeModule(e){return runtimeImport(e)}const VALID_HOOK_NAMES=["PreToolUse","PostToolUse","SessionStart","SessionEnd","UserPromptSubmit","Stop","SubagentStop","PreCompact","Notification"];async function loadHooks(e,t){const n=path$1.join(e,"hooks");if(!fs$1.existsSync(n))return{};const a=[path$1.join(n,"dist","index.mjs"),path$1.join(n,"dist","index.js"),path$1.join(n,"index.mjs"),path$1.join(n,"index.js")];let s=null;for(const e of a)if(fs$1.existsSync(e)){s=e;break}if(!s)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] ${path$1.join(n,"index.js")} or ${path$1.join(n,"index.mjs")}`),{};try{console.log(`[Hook Loader] Loading hooks: ${s}`);const e=`${url.pathToFileURL(s).href}?t=${Date.now()}`,n=await importRuntimeModule(e);if("function"==typeof n.default){if(t)return console.log("[Hook Loader] Using factory pattern with AgentrixContext"),extractHooks(n.default(t));console.warn("[Hook Loader] Factory function found but no context provided, skipping factory")}return extractHooks(n)}catch(e){throw console.error(`[Hook Loader] Failed to load hooks from ${s}:`,e),new Error(`Hook loading failed: ${e instanceof Error?e.message:String(e)}`)}}function extractHooks(e){const t={};for(const n of VALID_HOOK_NAMES){const a=e[n];"function"==typeof a&&(t[n]=a,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}const logger$2=machine.createModuleLogger("undefined"==typeof document?require("url").pathToFileURL(__filename).href:_documentCurrentScript&&"SCRIPT"===_documentCurrentScript.tagName.toUpperCase()&&_documentCurrentScript.src||new URL("index.cjs",document.baseURI).href);async function loadAgentHooks(e,t,n){if(e&&"default"!==e)try{const a=shared.getAgentContext(),s=t||a.resolveAgentDir(e),i=path.join(s,"claude");return await loadHooks(i,n)}catch(e){return void console.warn("[AgentRunners] Failed to load hooks:",e)}}async function loadSdkMcpTools(e,t){const n={};for(const a of e)try{logger$2.info(`Loading SDK MCP tools from: ${a}`);const e=await importRuntimeModule(a),s=e.default||e;if(!s){logger$2.warn(`No default export found in ${a}`);continue}const i="function"==typeof s?s(t):s,o=i.name;n[o]=i,logger$2.info(`Loaded MCP server: ${o}`)}catch(e){const t=e instanceof Error?e.message:String(e);logger$2.error(`Failed to load SDK MCP tools from ${a}: ${t}`)}return n}class AgentRunners{static pool=new Map;static async create(e,t,n){const a=this.pool.get(t);if(a)return a;let s;if("claude"===e||"companion"===e){const a=await loadClaudeAgentConfiguration({agentId:t,agentDir:n?.agentDir});let i,o;n?.context&&t&&"default"!==t&&(i=await loadAgentHooks(t,n.agentDir,n.context)),n?.context&&a.customSdkMcpTools&&a.customSdkMcpTools.length>0&&(o=await loadSdkMcpTools(a.customSdkMcpTools,n.context)),s=new ClaudeRunner(t,e,a,i,o)}else s=new CodexRunner;return this.pool.set(t,s),s}static release(e){this.pool.delete(e)}static releaseAll(){this.pool.clear()}}class NodeFileSystemAdapter{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=path__namespace$1.join(this.workingDirectory,e);return fs__namespace$1.existsSync(t)?fs__namespace$1.readFileSync(t,"utf-8"):null}catch{return null}}async fileExists(e){const t=path__namespace$1.join(this.workingDirectory,e);return fs__namespace$1.existsSync(t)}listFilesRecursively(e,t,n,a,s){if(!(s>a))try{const i=fs__namespace$1.readdirSync(e,{withFileTypes:!0});for(const o of i){const i=n?`${n}/${o.name}`:o.name;o.isDirectory()?shared.IGNORED_DIRECTORIES.includes(o.name)||this.listFilesRecursively(path__namespace$1.join(e,o.name),t,i,a,s+1):o.isFile()&&t.push(i)}}catch(e){}}}async function detectPreviewMetadata(e){const t=new NodeFileSystemAdapter(e);return shared.detectPreview(t)}class Workspace{constructor(e){this.params=e}state=null;persistedState=null;async setup(){const{options:e,handlers:t}=this.params,{userId:n,taskId:a,cwd:s}=e;if(!s)throw new Error("[WORKSPACE] Missing cwd for workspace setup");const i=machine.machine.getWorkspaceState(n,a),o=e.repositorySourceType,r="string"==typeof e.branchName&&e.branchName.length>0,c="string"==typeof i?.branchName&&i.branchName.length>0,l={...e,repositorySourceType:o,taskRepositoryId:e.taskRepositoryId??i?.taskRepositoryId,branchName:r?e.branchName:c?i.branchName:e.branchName,branchBinding:r?e.branchBinding:c?i.branchBinding:e.branchBinding},{initialCommitHash:d,isGitRepository:p,setupAction:u,useWorktree:m,initPolicyUpdates:h}=await this.ensureWorkspace(l,t,i),g={initialized:!0,initializedAt:(new Date).toISOString(),cwd:s,repositorySourceType:l.repositorySourceType,useWorktree:m,userCwd:e.userCwd,forceUserCwd:e.forceUserCwd,gitUrl:e.gitUrl,baseBranch:e.baseBranch,branchName:l.branchName,branchBinding:l.branchBinding,taskRepositoryId:l.taskRepositoryId,initialCommitHash:d,initPolicies:{...i?.initPolicies,...e.initPolicies,...h}};await machine.machine.writeWorkspaceState(n,a,g),this.persistedState=g;const f=await handleGitStateOnWorkerStart(s,n,a,d);return this.state={cwd:s,initialCommitHash:d,isGitRepository:p,setupAction:u,gitStateResult:f,taskRepositoryId:g.taskRepositoryId,branchName:g.branchName,branchBinding:g.branchBinding},p&&!e.taskRepositoryId&&await tryAssociateRepository(s,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 updateBranchBinding(e,t){await this.updateTaskMetadata({branchName:e,branchBinding:t})}async updateTaskMetadata(e){if(!this.state||!this.persistedState)throw new Error("[WORKSPACE] Workspace not initialized");const{userId:t,taskId:n}=this.params.options,a={...this.persistedState};"taskRepositoryId"in e&&(a.taskRepositoryId=e.taskRepositoryId),"branchName"in e&&(a.branchName=e.branchName),"branchBinding"in e&&(a.branchBinding=e.branchBinding),this.persistedState=a,await machine.machine.writeWorkspaceState(t,n,a);const s={...this.state};"taskRepositoryId"in e&&(s.taskRepositoryId=e.taskRepositoryId),"branchName"in e&&(s.branchName=e.branchName),"branchBinding"in e&&(s.branchBinding=e.branchBinding),this.state=s}async prepareResultArtifacts(e={}){const{cwd:t,initialCommitHash:n,isGitRepository:a}=this.getState(),{userId:s,taskId:i}=this.params.options;if(!a||!n)return{};const o=await getWorkspaceArtifactsSnapshot(t,n);if(!o)return{};try{await saveTaskPatchDiff(s,i,o.patch)}catch(t){e.onPatchError?.(t)}const r=await detectPreviewMetadata(t),c=await machine.machine.readLastSentArtifactVersion(s,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 a=e.repositorySourceType;return"git-server"===a?this.ensureGitServerWorkspace(e,t,n):"directory"===a?this.ensureDirectoryWorkspace(e,t,n):this.ensureTemporaryWorkspace(e,t,n)}async ensureGitServerWorkspace(e,t,n){const{cwd:a,gitUrl:s,taskId:i,baseBranch:o,gitServerId:r}=e;if(!s)throw new Error("[WORKSPACE] gitUrl is required for git-server mode");const c=hasStrongBranchBinding(e)?e.branchName:void 0,l=e.forceUserCwd||!1===e.useWorktree,d="git-server"===n?.repositorySourceType&&!0===n.useWorktree,p=await isGitRepository(a),u=isDirectoryEmpty(a);if(l)return this.ensureDirectGitServerWorkspace(e,t,n,p,u);if(Boolean(e.taskRepositoryId&&r)&&(!p||d)){const l=await setupGitServerWorktreeWorkspace(a,i,s,r,o,c);return p?{...await this.tryResolveDirtyRepo(e,t,n),setupAction:"reuse",useWorktree:!0}:{initialCommitHash:this.resolveInitialCommitHash(n?.initialCommitHash,l.initialCommitHash,"none"),isGitRepository:!0,setupAction:"worktree",autoCommitPolicy:"enabled",useWorktree:!0}}if(!p){if(!u)throw new Error(`[WORKSPACE] Directory ${a} exists but is not a git repository.`);const e=await setupGitRepository(a,s,i,o,r,c)||await getCurrentCommitHash(a);return{initialCommitHash:this.resolveInitialCommitHash(n?.initialCommitHash,e,"none"),isGitRepository:!0,setupAction:"clone",autoCommitPolicy:"enabled",useWorktree:!1}}return await updateRemoteUrl(a,"origin",sanitizeGitRemoteUrl(s)),{...await this.tryResolveDirtyRepo(e,t,n),setupAction:"reuse",useWorktree:n?.useWorktree??!1}}async ensureDirectGitServerWorkspace(e,t,n,a,s){const{cwd:i,gitUrl:o,taskId:r,baseBranch:c,gitServerId:l}=e;if(!o)throw new Error("[WORKSPACE] gitUrl is required for git-server direct directory mode");const d=hasStrongBranchBinding(e)?e.branchName:void 0;if(!a){if(!s)throw new Error(`[WORKSPACE] Directory ${i} exists but is not a git repository.`);const e=await setupGitRepository(i,o,r,c,l,d)||await getCurrentCommitHash(i);return{initialCommitHash:this.resolveInitialCommitHash(n?.initialCommitHash,e,"none"),isGitRepository:!0,setupAction:"clone",autoCommitPolicy:"enabled",useWorktree:!1}}return await this.assertDirectGitServerRemoteMatches(i,o),{...await this.tryResolveDirtyRepo(e,t,n,{defaultBranchMismatchAction:"Keep"}),setupAction:"reuse",useWorktree:!1}}async assertDirectGitServerRemoteMatches(e,t){const n=parseRemoteInfoFromUrl(sanitizeGitRemoteUrl(t));if(!n)throw new Error(`[WORKSPACE] Unable to parse selected repository remote URL: ${sanitizeGitRemoteUrl(t)}`);const a=await getRemoteInfo(e);if(!a)throw new Error(`[WORKSPACE] Direct directory ${e} must have an origin remote matching the selected repository.`);const s=n.host.toLowerCase(),i=a.host.toLowerCase(),o=n.owner.toLowerCase(),r=a.owner.toLowerCase(),c=n.repo.toLowerCase(),l=a.repo.toLowerCase();if(s!==i||o!==r||c!==l)throw new Error(`[WORKSPACE] Direct directory ${e} points to ${a.host}/${a.owner}/${a.repo}, but the selected repository is ${n.host}/${n.owner}/${n.repo}.`)}async ensureDirectoryWorkspace(e,t,n){const{cwd:a,taskId:s,userCwd:i}=e;if(await isGitRepository(a))return this.tryResolveDirtyRepo(e,t,n);if(!isDirectoryEmpty(a))return{initialCommitHash:"",isGitRepository:!1,setupAction:"reuse",autoCommitPolicy:"enabled",useWorktree:!1};{if(!i)return{initialCommitHash:"",isGitRepository:!1,setupAction:"reuse",autoCommitPolicy:"enabled",useWorktree:!1};const t=i.replace(/^~/,os.homedir());if(isDirectoryEmpty(t))return{initialCommitHash:"",isGitRepository:!1,setupAction:"reuse",autoCommitPolicy:"enabled",useWorktree:!1};if(!await isGitRepository(t))return{initialCommitHash:"",isGitRepository:!1,setupAction:"reuse",autoCommitPolicy:"enabled",useWorktree:!1};await hasAnyCommits(t)||await initialCommit(t),await setupWorktreeWorkspace(t,a,s,hasStrongBranchBinding(e)?e.branchName:void 0)}return{...await this.tryResolveDirtyRepo(e,t,n),setupAction:"reuse",useWorktree:!0}}async ensureTemporaryWorkspace(e,t,n){const{cwd:a}=e;if(!await isGitRepository(a)){await setupTmpRepoWorkspace(a),hasStrongBranchBinding(e)&&e.branchName&&await ensureTaskBranch(a,e.branchName,e.baseBranch);const t=await getCurrentCommitHash(a);return{initialCommitHash:this.resolveInitialCommitHash(n?.initialCommitHash,t,"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,a={}){let s=null,i="enabled";const o={};if(await checkUncommittedChanges(e.cwd)){const a=this.getPersistedInitPolicy(n,e,"uncommittedChanges",["Ignore","Commit","Stash"]),r=a?{action:a,remember:!0}:isExternalChannelWorkspaceTask(e)?{action:"Ignore",remember:!0}:t?.onUncommittedChanges?await t.onUncommittedChanges():{action:"Ignore",remember:!1},c=r.action;if(await handleUncommittedChanges(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()}!a&&r.remember&&(o.uncommittedChanges=c),s=c,"Ignore"===c&&(i="disabled_by_ignore")}let r;await hasAnyCommits(e.cwd)||await initialCommit(e.cwd),r=hasStrongBranchBinding(e)?"Ignore"===s?await getCurrentBranch(e.cwd)===e.branchName?"none":"kept":await this.tryResolveBranchMismatch(e,t,n,o,a.defaultBranchMismatchAction??"Switch"):"none";const c=await getCurrentCommitHash(e.cwd);return{initialCommitHash:this.resolveInitialCommitHash(n?.initialCommitHash,c,r),isGitRepository:!0,setupAction:"reuse",autoCommitPolicy:i,useWorktree:n?.useWorktree??!1,initPolicyUpdates:o}}getPersistedInitPolicy(e,t,n,a){const s=e?.initPolicies?.[n]??t.initPolicies?.[n];return s&&a.includes(s)?s:null}resolveInitialCommitHash(e,t,n){return e?"kept"===n?t:e:t}async tryResolveBranchMismatch(e,t,n,a,s){if(!hasStrongBranchBinding(e)||!e.branchName)return"none";const i=e.branchName,o=await getCurrentBranch(e.cwd);if(o===i)return"none";const r=this.getPersistedInitPolicy(n,e,"branchMismatch",["Switch","Keep"]),c=r?{action:r,remember:!0}:t?.onBranchMismatch?await t.onBranchMismatch({currentBranch:o,expectedBranch:i,workingDirectory:e.cwd}):{action:s,remember:!1};if("Abort"===c.action)throw new Error("Task aborted by user due to branch mismatch");return!r&&c.remember&&(a.branchMismatch=c.action),"Keep"===c.action?"kept":(await ensureTaskBranch(e.cwd,i,e.baseBranch),"switched")}}const prInfoSchema=zod.z.object({title:zod.z.string().describe("Concise PR title following conventional commits format (feat/fix/docs/refactor/test/chore: description), maximum 50 characters"),description:zod.z.string().describe("Detailed PR description explaining: what changed, why these changes were necessary, any important technical decisions, and impact on existing functionality"),userMessage:zod.z.string().describe("Friendly message to display to the user, summarizing the PR creation. Should be concise and informative.")}),prInfoJsonSchema=zod.toJSONSchema(prInfoSchema,{target:"draft-07"}),prInfoOpenAiSchema=zod.toJSONSchema(prInfoSchema);function parsePrInfoFromResult(e){if("success"!==e.subtype)throw new Error("PR response failed before structured output was returned");const t=e;return t.structured_output?prInfoSchema.parse(t.structured_output):parsePrInfo(t.result??"")}function extractJsonCandidate(e){const t=e.match(/```(?:json)?\s*\n?([\s\S]*?)\n?```/);return t?t[1].trim():e.trim()}function parsePrInfo(e){if(!e.trim())throw new Error("PR response was empty");const t=extractJsonCandidate(e),n=JSON.parse(t);return prInfoSchema.parse(n)}class InProcessQueue{chain=Promise.resolve();run(e){const t=this.chain.then(e,e);return this.chain=t.then(()=>{},()=>{}),t}}const CLI_BUILTIN_COMMANDS=[{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"},{name:"/agentrix-dev-init",sendAs:"![agentrix-dev-init]",description:"Run Agentrix DevOps initialization for this project"}];function normalizeCommandName(e){const t=e.trim();return t?t.startsWith("/")?t:`/${t}`:""}function getBuiltinSlashCommands(){return CLI_BUILTIN_COMMANDS.map(e=>({id:`cli_builtin:${e.name}`,name:e.name,kind:"cli_builtin",sendAs:e.sendAs,description:e.description}))}function buildSlashCommandCatalog(e=[]){const t=[],n=new Set;for(const e of getBuiltinSlashCommands())t.push(e),n.add(e.name);const a=Array.from(new Set(e.map(normalizeCommandName).filter(Boolean)));a.sort((e,t)=>e.localeCompare(t));for(const e of a)n.has(e)||t.push({id:`sdk:${e}`,name:e,kind:"sdk",sendAs:e});return t}const commitMessageSchema=zod.z.object({message:zod.z.string().describe("A git commit message following conventional commits. Return only the commit message text, optionally with a blank line and body.")}),commitMessageClaudeSchema=zod.toJSONSchema(commitMessageSchema,{target:"draft-07"}),commitMessageOpenAiSchema=zod.toJSONSchema(commitMessageSchema),COMMIT_PROMPT="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.";function parseCommitMessageResult(e){if("success"!==e.subtype)throw new Error("Commit message generation failed before structured output was returned");const t=e,n=(t.structured_output?commitMessageSchema.parse(t.structured_output):commitMessageSchema.parse(JSON.parse(extractJsonCandidate(t.result??"")))).message.trim();if(!n)throw new Error("Commit message generation returned an empty message");return n}async function generateCommitMessageForCurrentChanges(e){const t=e.runner.runStreamed(COMMIT_PROMPT,{cwd:e.workingDirectory,model:e.model,abortController:e.abortController,modeConfig:e.modeConfig,env:e.env,disableClaudePlanModeTools:e.disableClaudePlanModeTools,projectAgentrixGuidance:e.projectAgentrixGuidance,structuredOutputSchema:{type:"json_schema",schema:"claude"===e.schemaTarget?commitMessageClaudeSchema:commitMessageOpenAiSchema}});let n=null;for await(const a of t){if("result"===a.type){n=a;break}await(e.onStreamMessage?.(a))}if(!n)throw new Error("Commit message generation did not return a result message");return parseCommitMessageResult(n)}async function commitCurrentChangesWithAgent(e){if(!await hasUncommittedChanges(e.workingDirectory))throw new Error("No uncommitted changes to commit");const t=await getCurrentCommitHash(e.workingDirectory),n=await generateCommitMessageForCurrentChanges(e),a=await commitWithMessage(e.workingDirectory,n);if(await hasUncommittedChanges(e.workingDirectory))throw new Error("Commit completed but working tree is still dirty");if(a===t)throw new Error("Commit completed but HEAD did not change");return{commitHash:a,message:n}}function buildStructuredOutputSchema(e){if(e)return{type:"json_schema",schema:e}}async function copyDirectory(e,t){await fs.promises.mkdir(t,{recursive:!0});const n=await fs.promises.readdir(e,{withFileTypes:!0});for(const a of n){const n=path.join(e,a.name),s=path.join(t,a.name);a.isDirectory()?await copyDirectory(n,s):await fs.promises.copyFile(n,s)}}function getWorkerExecutionMode(e){return e.workerExecutionMode??shared.DEFAULT_WORKER_EXECUTION_MODE}function isOneShotExecution(e){return"oneshot"===getWorkerExecutionMode(e)}async function loadProjectAgentrixGuidance(e){const t=path.join(e,".agentrix"),n=path.join(t,"prompt.md"),a=path.join(t,"plugins"),[s,i]=await Promise.all([readPromptIfPresent(n),loadClaudePlugins(a)]);return{systemPromptAppend:s,claudePlugins:i}}async function readPromptIfPresent(e){try{if(!(await fs.promises.stat(e)).isFile())return;const t=(await fs.promises.readFile(e,"utf8")).trim();return t.length>0?t:void 0}catch(e){if(isMissingPathError(e))return;throw e}}async function loadClaudePlugins(e){let t;try{t=await fs.promises.readdir(e,{withFileTypes:!0})}catch(e){if(isMissingPathError(e))return[];throw e}const n=[];for(const a of t.sort((e,t)=>e.name.localeCompare(t.name))){if(!a.isDirectory())continue;const t=path.join(e,a.name),s=path.join(t,".claude-plugin","plugin.json");try{(await fs.promises.stat(s)).isFile()&&n.push({type:"local",path:t})}catch(e){if(isMissingPathError(e))continue;throw e}}return n}function isMissingPathError(e){return"object"==typeof e&&null!==e&&"code"in e&&"ENOENT"===e.code}function isCloudRuntime(){return Boolean(process.env.CLOUD_AUTH_TOKEN?.trim())}function hasExplicitTaskExecutionTarget(e){const t=e;return Boolean(t.machineId||t.cloudId)}function isTaskPreviewAvailableForWorker(e){const t=e,n=shared.getTaskExecutionMode({machineId:t.machineId??null,cloudId:t.cloudId??null});return hasExplicitTaskExecutionTarget(e)?"local"===n:!isCloudRuntime()&&"cloud"!==n}function isVisionPlanAvailableForWorkspace(e){if(!e)return!1;const t=path.join(e,".agentrix","vision");try{return fs.existsSync(t)&&fs.statSync(t).isDirectory()}catch{return!1}}function normalizeEnvUrl(e){const t=e?.trim();if(t)return t.replace(/\/+$/,"")}function buildGitLabPatEnvironment(e,t,n){return{GITLAB_TOKEN:e,...t?{GITLAB_BASE_URL:t,CI_SERVER_URL:t}:{},...n?{GITLAB_API_URL:n}:{}}}function extractAuthenticatedGithubToken(e){if(!e)return null;try{const t=new URL(e),n=decodeURIComponent(t.username),a=decodeURIComponent(t.password);if(t.host.toLowerCase(),"x-access-token"===n&&a)return a}catch{return null}return null}async function buildGitProviderAgentEnvironment(e){const t=extractAuthenticatedGithubToken(e.gitUrl);if(t)return{GITHUB_TOKEN:t,GH_TOKEN:t};if(!e.gitServerId)return{};const n=await getGitServerEncryptionKey();if(!n)return{};const a=loadPat(e.gitServerId,n);if(!a)return{};const s=loadGitServerConfig(e.gitServerId);return buildGitLabPatEnvironment(a,normalizeEnvUrl(s?.baseUrl),normalizeEnvUrl(s?.apiUrl))}async function applyGitProviderAgentEnvironment(e){const t=await buildGitProviderAgentEnvironment(e);for(const[e,n]of Object.entries(t))process.env[e]=n;return t}function putIfPresent(e,t,n){if(null==n)return;const a=String(n);0!==a.length&&(e[t]=a)}function buildTaskContextEnvironment(e,t){const n={},a=e.machineId??t.machineId;return putIfPresent(n,"AGENTRIX_TASK_ID",e.taskId),putIfPresent(n,"AGENTRIX_USER_ID",e.userId),putIfPresent(n,"AGENTRIX_AGENT_ID",e.agentId),putIfPresent(n,"AGENTRIX_AGENT_TYPE",e.agentType),putIfPresent(n,"AGENTRIX_CHAT_ID",e.chatId),putIfPresent(n,"AGENTRIX_MACHINE_ID",a),putIfPresent(n,"AGENTRIX_CLOUD_ID",e.cloudId),putIfPresent(n,"AGENTRIX_ROOT_TASK_ID",e.rootTaskId),putIfPresent(n,"AGENTRIX_PARENT_TASK_ID",e.parentTaskId),putIfPresent(n,"AGENTRIX_TASK_TYPE",e.taskType),putIfPresent(n,"AGENTRIX_WORKSPACE_ID",e.workspaceId),putIfPresent(n,"AGENTRIX_WORKING_DIR",t.workingDirectory),putIfPresent(n,"AGENTRIX_WORKING_USER",e.userId),putIfPresent(n,"AGENTRIX_WORKING_TASK",e.taskId),n}function applyTaskEnvironmentToProcess(e,t){if(e.environmentVariables)for(const[t,n]of Object.entries(e.environmentVariables))null!=n&&(process.env[t]=String(n));Object.assign(process.env,buildTaskContextEnvironment(e,t))}function buildAgentRunEnvironment(e,t){const n={};if(t.baseEnv)for(const[e,a]of Object.entries(t.baseEnv))"string"==typeof a&&(n[e]=a);return{...n,...buildTaskContextEnvironment(e,t)}}const logger$1=machine.createModuleLogger("undefined"==typeof document?require("url").pathToFileURL(__filename).href:_documentCurrentScript&&"SCRIPT"===_documentCurrentScript.tagName.toUpperCase()&&_documentCurrentScript.src||new URL("index.cjs",document.baseURI).href),COMPANION_HEARTBEAT_CONTEXT=Symbol("companionHeartbeatContext"),COMPANION_MEMORY_ORGANIZATION_CONTEXT=Symbol("companionMemoryOrganizationContext");function getPermissionModeAfterToolUse(e,t){return"EnterPlanMode"===e?"plan":"ExitPlanMode"===e?t:null}class ClaudeWorker{constructor(e,t,n){this.credentials=e,this.options=t,this.workingDirectory=n;const a=this.options.input,{taskId:s,userId:i}=a;this.logger=machine.getLoggerBase(),this.currentAgentSessionId="agentSessionId"in a?a.agentSessionId:void 0;const o=a.taskAgents||[];this.taskAgentsMap=new Map(o.map(e=>[e.id,e]));const r=this.taskAgentsMap.size>1;this.primaryAgentId=r?"planner":a.agentId,this.primaryAgentName=r?"planner":this.taskAgentsMap.get(a.agentId)?.name??"unknown";const c=this.createWorkerClientConfig(i,s,n),l=machine.machine.resolveDataDir(i,s);this.historyDb=getTaskDb({dataDir:l,taskId:s}),this.workClient=new WorkerClient(c.config,{...c.handlers,getPermissionMode:()=>this.getPermissionModeSnapshot(),historyDb:this.historyDb}),this.coordinator=this.createMessageCoordinator(this.workClient,this.options.idleTimeoutSecond),this.agentContext=new AgentContextImpl({logger:this.logger,socketClient:this.workClient.client,taskId:a.taskId,userId:a.userId,chatId:a.chatId,rootTaskId:a.rootTaskId||a.taskId,parentTaskId:a.parentTaskId||null,workingDirectory:this.workingDirectory,agentHomeDir:machine.machine.agentrixAgentsHomeDir,taskAgents:a.taskAgents||[],serverUrl:machine.machine.serverUrl,taskDataKey:this.options.dataEncryptionKey}),this.agentrixTools=this.createAgentrixTools();const d={...buildWorkspaceOptions(this.options.input),cwd:this.workingDirectory};this.workspace=new Workspace({options:d,handlers:this.createWorkspaceHandlers(this.workClient)})}abortController=new AbortController;isStopping=!1;askUserAwaiter=new Map;messageFilter=createMessageFilter();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;loopModelSetter=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";pendingChannelReplies=[];channelMessageInvocationCount=0;projectAgentrixGuidance={claudePlugins:[]};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 isOneShotExecution(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(),a="group_chat"===n||"group_work"===n,s=shared.isAskUserResponseMessage(t);return!!shared.isCompanionHeartbeatMessage(t)||!!shared.isCompanionMemoryOrganizationMessage(t)||!!shared.isCompanionReminderMessage(t)||!(!shared.isSDKMessage(t)&&!s)&&"agent"!==e.senderType&&(a?e.senderId!==this.primaryAgentId:!!s||"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,a=[];for(const t of e.data)if(this.lastProcessedSequence=t.localSequence,this.shouldProcessMessage(t)){if(n&&this.isUnsupportedGroupPlanCommand(t)){logger$1.info("Ignoring unsupported ![plan] command in group mode");continue}a.push(t)}if(a.length>0){this.deduplicateHeartbeats(a);const e=this.mergeConsecutiveHumanMessages(a);n?await this.processMessagesAsGroup(e):await this.processMessagesIndividually(e)}e.hasMore&&await this.processPendingMessages()}isUnsupportedGroupPlanCommand(e){const t=e.message;return!(!shared.isSDKMessage(t)||"user"!==t.type)&&"![plan]"===extractUserMessageText(t).trim()}deduplicateHeartbeats(e){let t=-1;for(let n=e.length-1;n>=0;n--)shared.isCompanionHeartbeatMessage(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 a=e[n];if("human"===a.senderType){const s=[a];for(;n+1<e.length;){const t=e[n+1];if("human"!==t.senderType||t.senderId!==a.senderId)break;s.push(t),n++}1===s.length?t.push(a):t.push(this.createMergedHumanMessage(s))}else t.push(a);n++}return t}createMergedHumanMessage(e){const t=[],n=[];for(const a of e){const e=a.message;if(!shared.isSDKMessage(e)||"user"!==e.type)continue;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)}const a=t.join(""),s=n.length>0?[{type:"text",text:a},...n]:a,i=e[0],o=e[e.length-1];return{localSequence:o.localSequence,eventId:o.eventId,senderType:i.senderType,senderId:i.senderId,senderName:i.senderName,createdAt:o.createdAt,message:{type:"user",message:{role:"user",content:s},parent_tool_use_id:null,session_id:i.message?.session_id||""}}}async processMessagesAsGroup(e){const t=[],n=[];for(const a of e){const e=formatHistoryMessage(a);if(e){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)}}if(0===t.length)return;const a=Math.max(...e.map(e=>e.localSequence)),s=t.join(" "),i={type:"user",message:{role:"user",content:n.length>0?[{type:"text",text:s},...n]:s},parent_tool_use_id:null,session_id:""};this.attachInputMetadata(i,{localSequence:a,isChannelInput:e.some(e=>"channel"===e.senderType),channelReplyTarget:this.extractChannelReplyTarget(e)}),await this.coordinator.enqueue(i)}async processMessagesIndividually(e){for(const t of e){const e=this.formatSingleMessage(t);e&&(this.attachInputMetadata(e,{localSequence:t.localSequence,isChannelInput:"channel"===t.senderType,channelReplyTarget:this.extractChannelReplyTarget([t])}),delete e.__channelReplyTarget,await this.coordinator.enqueue(e))}}attachInputMetadata(e,t){e.__localSequence=t.localSequence,e.__isChannelInput=t.isChannelInput,t.channelReplyTarget&&(e.__channelReplyTarget=t.channelReplyTarget)}clearRuntimeInputMetadata(e){delete e.__localSequence,delete e.__isChannelInput,delete e.__channelReplyTarget}extractChannelReplyTarget(e){for(let t=e.length-1;t>=0;t--){const n=e[t].message.__channelReplyTarget;if(this.isChannelReplyTarget(n))return n}return null}formatSingleMessage(e){const t=e.message;if(shared.isCompanionHeartbeatMessage(t)){const e=t,n={type:"user",message:{role:"user",content:this.buildCompanionHeartbeatPrompt(e)},parent_tool_use_id:null,session_id:""};return n[COMPANION_HEARTBEAT_CONTEXT]=e,n}if(shared.isCompanionReminderMessage(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:""}}if(shared.isCompanionMemoryOrganizationMessage(t)){const e=t,n={type:"user",message:{role:"user",content:this.buildCompanionMemoryOrganizationPrompt(e)},parent_tool_use_id:null,session_id:""};return n[COMPANION_MEMORY_ORGANIZATION_CONTEXT]=e,n}return shared.isSDKMessage(t)&&"user"===t.type?t:null}buildCompanionHeartbeatPrompt(e){const t=this.options.input,n=t.rootTaskId||t.taskId;return["[heartbeat] You are being awakened by a scheduled companion heartbeat.","","Review target:","Always review the recent context of this companion chat and its root chat task before deciding what to do. Do not limit the review to a generic workspace scan.",...[`heartbeat timestamp: ${e.timestamp}`,e.triggerTime?`local trigger time: ${e.triggerTime}`:void 0,e.triggerReasons?.length?`trigger reasons: ${e.triggerReasons.join(", ")}`:void 0,"number"==typeof e.heartbeatTriggerCount?`heartbeat trigger count: ${e.heartbeatTriggerCount}`:void 0,`current worker taskId: ${t.taskId}`,t.chatId?`companion chatId: ${t.chatId}`:void 0,n?`root chat taskId: ${n}`:void 0].filter(e=>Boolean(e)).map(e=>`- ${e}`),"","Use the available conversation-reading tools for the companion chat/root chat task when needed. Follow the current heartbeat mode instructions from your system prompt. If there is nothing actionable after review, respond briefly and exit."].join("\n")}buildCompanionMemoryOrganizationPrompt(e){const t=this.options.input,n=[`trigger: ${e.trigger}`,`timestamp: ${e.timestamp}`,e.triggerTime?`local trigger time: ${e.triggerTime}`:void 0,"number"==typeof e.intervalHours?`configured interval hours: ${e.intervalHours}`:void 0,`current worker taskId: ${t.taskId}`,t.chatId?`companion chatId: ${t.chatId}`:void 0].filter(e=>Boolean(e));return logger$1.info(`Memory organization input received: trigger=${e.trigger}, timestamp=${e.timestamp}, intervalHours=${e.intervalHours??"unset"}, taskId=${t.taskId}`),["[memory organization] You are being awakened for Companion memory organization.",...n.map(e=>`- ${e}`),"","Use the available conversation, task, and history tools to gather the current signals needed for this memory organization run. Follow the memory organization mode instructions from your system prompt and MEMORY_ORGANIZATION.md."].join("\n")}extractCompanionPromptPlaceholders(e){const t=e[COMPANION_MEMORY_ORGANIZATION_CONTEXT];return t?(delete e[COMPANION_MEMORY_ORGANIZATION_CONTEXT],{COMPANION_SHADOW_TASK:"memory_organization",COMPANION_MEMORY_ORGANIZATION_TRIGGER:t.trigger,COMPANION_MEMORY_ORGANIZATION_TIMESTAMP:t.timestamp,COMPANION_MEMORY_ORGANIZATION_INTERVAL_HOURS:"number"==typeof t.intervalHours?String(t.intervalHours):""}):e[COMPANION_HEARTBEAT_CONTEXT]?(delete e[COMPANION_HEARTBEAT_CONTEXT],{COMPANION_SHADOW_TASK:"heartbeat"}):void 0}async prepareMessageForRunner(e){return processAttachments(e,{attachmentsDir:machine.machine.resolveAttachmentsDir(this.options.input.userId,this.taskId)})}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{if(await this.initialize(),!await this.maybeConfirmAgentrixDevOpsInit())return;await this.handleEvent(),await this.runClaude()}catch(t){if(!(t instanceof claudeAgentSdk.AbortError)){e="error",logger$1.warn("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,a=t.agentGitSubDir;if(n)try{logger$1.info(`Auto-installing agent ${e} from git`),await installAgentFromGit({agentId:e,gitUrl:n,subDir:a??void 0})}catch(t){logger$1.warn(`Auto-install failed for agent ${e}: ${t}`)}else logger$1.warn(`Auto-install skipped: no agentGitUrl provided for agent ${e}`)}async applyAgentUpgrade(e,t,n){const a=machine.machine.agentrixAgentsHomeDir,s=path.join(a,`${e}.new`),i=path.join(a,`${e}-bak`);try{logger$1.info(`Applying upgrade for ${e}`),buildAgentPlugins(n),fs.renameSync(n,s),await copyDirectory(t,i),fs.rmSync(t,{recursive:!0,force:!0}),fs.renameSync(s,t),fs$1.existsSync(i)&&fs.rmSync(i,{recursive:!0,force:!0}),logger$1.info(`Upgrade applied for ${e}`)}catch(n){logger$1.warn(`Upgrade failed for ${e}: ${n}`),!fs$1.existsSync(t)&&fs$1.existsSync(i)&&fs.renameSync(i,t),fs$1.existsSync(s)&&fs.rmSync(s,{recursive:!0,force:!0})}}async initialize(){const e=this.options.input,t="filesystem"===e.agentSource;let n=null;const a=e.agentDir??machine.machine.resolveAgentDir(e.agentId,this.workingDirectory);Boolean(t&&"git-server"===e.repositorySourceType&&!e.agentDir&&!fs$1.existsSync(path.join(a,"agent.json")))&&(n=await this.workspace.setup());const s=e.agentDir??machine.machine.resolveAgentDir(e.agentId,this.workingDirectory),i=path.join(s,"upgrade"),o=Boolean(s)&&Boolean(e.agentGitUrl)&&!t,r=Boolean(e.agentId&&"default"!==e.agentId&&!e.agentDir&&o&&!fs$1.existsSync(s)),c=Boolean(e.agentId&&"default"!==e.agentId&&!e.agentDir&&!t&&!r&&fs$1.existsSync(i));if(await this.workClient.connect(),this.workClient.sendWorkerInitializing({deployingAgent:r,upgradingAgent:c}),r&&await this.autoInstallAgent(e.agentId),t&&"default"!==e.agentId&&!fs$1.existsSync(path.join(s,"agent.json")))throw new Error(`Filesystem agent not found: ${e.agentId} (${s})`);c&&await this.applyAgentUpgrade(e.agentId,s,i),logger$1.info(`Resolved agent ${e.agentId}: ${s}`);const l=await AgentRunners.create(e.agentType,e.agentId,{agentDir:s,context:this.agentContext});this.runner=l,this.initializePermissionModeState(),n??=await this.workspace.setup(),this.projectAgentrixGuidance=await loadProjectAgentrixGuidance(this.workingDirectory),await this.registerWithDaemon(this.workingDirectory),logger$1.info(`Prepared ${this.options.input.repositorySourceType} workspace via ${n.setupAction} at ${this.workingDirectory} (${n.initialCommitHash||"none"})`),await this.setEnvironmentVariables(),this.lastProcessedSequence=this.historyDb.getAgentLastSequences().get(this.primaryAgentId)??0,logger$1.info(`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(buildSlashCommandCatalog())}createWorkspaceHandlers(e){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: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)},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 notifyDaemonSessionStarted(t,{cwd:e,machineId:this.credentials.machineId,pid:process.pid,startedBy:this.options.startedBy||"terminal"});n.error?logger$1.warn(`Failed to report session ${t}:`,n.error):logger$1.info(`Session ${t} registered`)}async setEnvironmentVariables(){applyTaskEnvironmentToProcess(this.options.input,{workingDirectory:this.workingDirectory,machineId:this.credentials.machineId}),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),await applyGitProviderAgentEnvironment(this.options.input)}buildClaudeRunEnvironment(){return buildAgentRunEnvironment(this.options.input,{workingDirectory:this.workingDirectory,machineId:this.credentials.machineId,baseEnv:process.env})}createMessageCoordinator(e,t){const n=1e3*Math.max(0,t??0);return this.coordinator=new Coordinator({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()},onAgentrixDevInit:async()=>{await notifyDaemonStartDevOpsInit(this.taskId,this.options.input.userId),this.stopTask("event")},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)},idleTimeoutMs:n,onIdleTimeout:()=>this.stopTask("idle")}),this.coordinator}sendCurrentWorkerStatus(){const{state:e}=this.coordinator.getStatus();"running"===e?this.workClient.sendWorkRunning(this.coordinator.getActiveAgents()):"idle"===e&&this.workClient.sendWorkerReady()}async handleEvent(){const e=this.options.input.event,t=this.options.input.eventData;if("sub-task-result-updated"===e){const e=t,n=buildSubTaskResultMessage(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=buildSubTaskAskUserMessage(e,this.options.dataEncryptionKey);this.historyDb.saveMessage({eventId:e.eventId||`sub-task-ask-${Date.now()}`,message:n,senderType:"system",senderId:"system",senderName:"system"})}if("task-message"===e){const e=t;if(e.message){const t=formatUserContentLogLine(e,e.message,{source:"startup"});t&&logger$1.info(t)}}if(this.isOneShotExecution())await this.processPendingMessages(),this.coordinator.hasAgentMessages()||this.isStopping||this.stopTask("oneshot_complete");else{if("task-message"===e){const n=t,a=n.message;a&&shared.isCompanionMemoryOrganizationMessage(a)&&this.historyDb.saveMessage({eventId:n.eventId,message:a,senderType:n.senderType,senderId:n.senderId,senderName:n.senderName}).inserted&&this.historyDb.saveTaskEvent({eventType:e,eventId:n.eventId,eventData:n,taskId:this.taskId,chatId:n.chatId??this.options.input.chatId,sequence:n.sequence??null})}this.triggerMessageProcessing()}"task-message"===e&&t?.eventId&&this.workClient.sendEventAck(t.eventId)}async executeMergeRequest(){logger$1.info("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 logger$1.warn("No repositoryId found in task input"),void this.workClient.sendSystemErrorMessage(e,{groupId:this.currentGroupId??void 0})}await hasUncommittedChanges(this.workingDirectory)&&await this.commitCurrentChangesWithAgent();const e=await getCurrentCommitHash(this.workingDirectory),n=this.workspace.getInitialCommitHash();if(!n){const e="Cannot create PR: initial commit hash is missing.";return logger$1.error(e),void this.workClient.sendSystemErrorMessage(e,{groupId:this.currentGroupId??void 0})}if(0===(await getDiffStats(this.workingDirectory,n,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 a=this.workspace.getState(),s=a.branchName?{branchName:a.branchName,branchBinding:a.branchBinding}:this.options.input,i=hasStrongBranchBinding(s),o=i?resolvePublishBranchName(this.options.input.taskId,s.branchName):void 0;if(i&&o){const e=await getCurrentBranch(this.workingDirectory);if(e!==o){const t=buildMergeRequestBranchMismatchMessage(e,o);return logger$1.warn(t),void this.workClient.sendSystemErrorMessage(t,{groupId:this.currentGroupId??void 0})}}const r=this.runner?.getAgentConfiguration(),c=buildPRRequestPrompt(n,(r?.customPRPromptTemplate?applyPRPromptTemplate(r.customPRPromptTemplate,{initialCommitHash:n,currentCommitHash:e,branchName:o??"to-be-generated-from-pr-title"}):void 0)??void 0);logger$1.debug(`PR prompt: ${c.substring(0,200)}...`);const l=this.runner;let d=null;const p=l.runStreamed(c,{cwd:this.workingDirectory,model:this.options.input.model,abortController:this.abortController,modeConfig:this.getRunnerModeConfig(),env:this.buildClaudeRunEnvironment(),disableClaudePlanModeTools:this.shouldDisableClaudePlanModeTools(),projectAgentrixGuidance:this.projectAgentrixGuidance,allowAskUser:!this.isOneShotExecution(),supportedFeatures:this.options.input.supportedFeatures,structuredOutputSchema:{type:"json_schema",schema:prInfoJsonSchema}});for await(const e of p){if(this.logger.debug(`sdk message: ${JSON.stringify(e)}`),"result"===e.type){d=e;break}const n=t?e:this.messageFilter.filter(e);null!==n&&this.workClient.sendTaskEvent(this.getChatSenderMeta(),n,{groupId:this.currentGroupId??void 0})}if(!d)throw new Error("Merge-request did not return a result message");if("success"!==d.subtype)throw new Error("Merge-request did not return a successful result message");const u=parsePrInfoFromResult(d),m=resolvePublishBranchName(this.options.input.taskId,o,u.title);i||await checkoutPublishBranchAtHead(this.workingDirectory,m);const h=buildHeadPushRef(m);logger$1.info(`Pushing HEAD to remote branch ${m}`),await pushForTask(this.workingDirectory,h,!1,{gitServerId:this.options.input.gitServerId,gitUrl:this.options.input.gitUrl}),logger$1.info("Successfully pushed branch to remote");const g=await this.workClient.sendMergeRequest(u.title,u.description,m);"explicit"!==s.branchBinding&&await this.workspace.updateBranchBinding(m,"platform-managed");const f=`${u.userMessage}\n\n✅ Pull request created successfully!\nNumber: #${g.pullRequestNumber}\nURL: ${g.pullRequestUrl}`,y={input_tokens:d.usage.input_tokens??0,cached_input_tokens:d.usage.cache_read_input_tokens??0,output_tokens:d.usage.output_tokens??0,reasoning_output_tokens:0};this.workClient.sendTaskMessage(this.getChatSenderMeta(),createSdkResultMessage({sessionId:d.session_id,model:this.options.input.model??"unknown",numTurns:d.num_turns,usage:y,result:f}),{groupId:this.currentGroupId??void 0})}catch(e){const t=e instanceof Error?e.message:String(e);logger$1.error("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})}}async executeBashCommand(e){if(!machine.machine.isDirectBashAllowed())return logger$1.warn("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});logger$1.info(`Executing command: ${e}`);const t={senderType:"agent",senderId:"bash",senderName:"bash"},n=await executeCommandStreaming(e,this.workingDirectory,{onOutput:e=>{this.workClient.sendTaskMessage(t,e,{groupId:this.currentGroupId??void 0})},onComplete:e=>{logger$1.info(`Command completed with exit code: ${e}`)}});logger$1.info(`Worker ready after command execution (exit code: ${n})`)}async executeMergePr(){await executeMergePr({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(){logger$1.info("Generating commit message with agent"),await commitCurrentChangesWithAgent({runner:this.runner,workingDirectory:this.workingDirectory,model:this.options.input.model,abortController:this.abortController,modeConfig:this.getRunnerModeConfig(),env:this.buildClaudeRunEnvironment(),disableClaudePlanModeTools:this.shouldDisableClaudePlanModeTools(),schemaTarget:"claude",projectAgentrixGuidance:this.projectAgentrixGuidance,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})}}),logger$1.info("Committed changes with agent-generated message")}async executeNewSession(){logger$1.info("Executing new-session: clearing agentSessionId"),this.currentAgentSessionId=void 0,this.primarySessionReady=!1,this.workClient.sendResetTaskSession(),logger$1.info("Session reset sent, stopping task for clean restart"),this.stopTask("event")}isAgentrixDevOpsInitWorker(){return"Agentrix-DevOps"===this.options.input.agentId}async maybeConfirmAgentrixDevOpsInit(){if(!this.isAgentrixDevOpsInitWorker())return!0;const e=resolveDevOpsLanguage(this.options.input),t=(await this.askUser([buildPreInitQuestion(e)],{onTimeout:"abort_task"})).answers[0]??"";return("zh-Hans"===e?"先初始化"===t:"Initialize first"===t)||(await notifyDaemonDevOpsInitComplete(this.taskId,this.options.input.userId,"continue"),!1)}getAgentrixExtraTools(){if(this.isAgentrixDevOpsInitWorker())return[claudeAgentSdk.tool("complete_devops_init","Notify the Agentrix platform that Agentrix DevOps initialization is complete or that the user wants to leave the Agentrix-DevOps init session after it has completed. Call this only after project memory, environment guidance, local initialization state, and automated testing readiness are complete, or when the user explicitly asks to exit init/return to the development agent after choosing to stop. Do not call this because a normal response turn is ending.",{summary:zod.z.string().describe("Short user-visible summary of what initialization completed")},async e=>{const t=resolveDevOpsLanguage(this.options.input),n=await this.askUser([buildPostInitQuestion(t)],{onTimeout:"abort_task"}),a=parsePostInitDecision(n.answers[0]??"",t);if(logger$1.info(`Post-init user decision: ${a??"unrecognized"} (answer=${JSON.stringify(n.answers[0]??"")})`),!a)return{content:[{type:"text",text:"The platform could not recognize the user post-init choice. Ask the user again or call complete_devops_init again after confirming the next action. Do not stop this DevOps init session yet."}]};if("modify"===a){const e=n.details?.[0]?.trim();return{content:[{type:"text",text:e?`The user wants additional Agentrix DevOps init changes before completion:\n${e}`:"The user wants additional Agentrix DevOps init changes before completion. Continue the same initialization session."}]}}return await notifyDaemonDevOpsInitComplete(this.taskId,this.options.input.userId,"continue"===a?"continue":"stop"),setImmediate(()=>this.stopTask("event")),{content:[{type:"text",text:"continue"===a?`Agentrix DevOps initialization completed: ${e.summary}. The platform is switching back to the original development agent.`:`Agentrix DevOps initialization completed: ${e.summary}. The task will stop without starting the development agent.`}]}})]}async runClaude(){if(logger$1.info(`Starting Claude agent for task ${this.taskId}`),this.isStopping)return void logger$1.info(`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(),a="group_chat"===n.mode||"group_work"===n.mode,s=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=>{logger$1.debug(e)},modeConfig:n,env:this.buildClaudeRunEnvironment(),disableClaudePlanModeTools:this.shouldDisableClaudePlanModeTools(),agentrixTools:this.agentrixTools,agentrixExtraTools:this.getAgentrixExtraTools(),enableAgentrixComputerUse:this.isComputerUseEnabled(),enableTaskPreviewUrl:isTaskPreviewAvailableForWorker(this.options.input),enableVisionPlan:isVisionPlanAvailableForWorkspace(this.workingDirectory),allowAskUser:!this.isOneShotExecution(),supportedFeatures:this.options.input.supportedFeatures,channelBound:this.isChannelBoundTask(),channelGroupBound:this.isChannelGroupBoundTask(),channelContext:this.getExternalChannelPromptContext(),visionModel:this.options.input.visionModel,canUseTool:s,hooks:i,maxTurns:this.options.input.maxTurns??void 0,projectAgentrixGuidance:this.projectAgentrixGuidance,structuredOutputSchema:this.getStructuredOutputSchema()});this.loopPermissionModeSetter=o.setPermissionMode??null,this.loopModelSetter=o.setModel??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);const t=e.__localSequence;if(void 0!==t&&this.markPrimaryMessageProcessed(t),Boolean(e.__isChannelInput)){const t=e.__channelReplyTarget;this.pendingChannelReplies.push({target:this.isChannelReplyTarget(t)?t:null,channelMessageInvocationCountAtStart:this.channelMessageInvocationCount})}this.clearRuntimeInputMetadata(e),o.push(await this.prepareMessageForRunner(e)),delete e.__isChannelInput,delete e.__channelReplyTarget}}catch(e){logger$1.error("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,a);this.resetPrimaryPermissionState(),logger$1.info(`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,a=this.createPermissionHandler(),s=this.buildSystemHooks({trackBackgroundTasks:!0,trackPrimaryAgentStop:!0});this.loopPermissionModeSetter=null,this.loopModelSetter=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 logger$1.info(`Claude oneshot finished for task ${this.taskId} without runnable message`);const o=i.__localSequence;if(void 0!==o&&this.markPrimaryMessageProcessed(o),Boolean(i.__isChannelInput)){const e=i.__channelReplyTarget;this.pendingChannelReplies.push({target:this.isChannelReplyTarget(e)?e:null,channelMessageInvocationCountAtStart:this.channelMessageInvocationCount})}delete i.__isChannelInput,delete i.__channelReplyTarget,this.updateAgentRunning(!0);try{const o=this.extractCompanionPromptPlaceholders(i),r=await this.prepareMessageForRunner(i),c=e.runStreamed(r,{cwd:this.workingDirectory,model:this.options.input.model,agentSessionId:this.currentAgentSessionId,abortController:this.abortController,initialPermissionMode:this.getPermissionModeSnapshot()??void 0,stderr:e=>{logger$1.debug(e)},modeConfig:t,env:this.buildClaudeRunEnvironment(),disableClaudePlanModeTools:this.shouldDisableClaudePlanModeTools(),agentrixTools:this.agentrixTools,agentrixExtraTools:this.getAgentrixExtraTools(),enableAgentrixComputerUse:this.isComputerUseEnabled(),enableTaskPreviewUrl:isTaskPreviewAvailableForWorker(this.options.input),enableVisionPlan:isVisionPlanAvailableForWorkspace(this.workingDirectory),allowAskUser:!1,supportedFeatures:this.options.input.supportedFeatures,channelBound:this.isChannelBoundTask(),channelGroupBound:this.isChannelGroupBoundTask(),channelContext:this.getExternalChannelPromptContext(),visionModel:this.options.input.visionModel,canUseTool:a,hooks:s,maxTurns:this.options.input.maxTurns??void 0,projectAgentrixGuidance:this.projectAgentrixGuidance,structuredOutputSchema:this.getStructuredOutputSchema(),promptPlaceholders:o});for await(const e of c)this.logger.debug(`sdk message: ${JSON.stringify(e)}`),await this.handlePrimaryRunnerMessage(e,n);this.isStopping||this.stopTask("oneshot_complete")}finally{this.resetPrimaryPermissionState(),logger$1.info(`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(buildSlashCommandCatalog(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.loopModelSetter=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",logger$1.info("One-shot execution completed, stopping task")),"idle"===e?logger$1.info("Idle timeout reached, stopping task"):"ask_user_timeout"===e&&logger$1.info("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 logger$1.warn("AskUserQuestion missing questions"),{behavior:"deny",message:"AskUserQuestion missing questions"};const a=n.map(e=>({...e,options:[...e.options,{label:"Other",description:""}]}));try{const e=await this.askUser(a),s={};for(let t=0;t<n.length;t+=1){const a=n[t]?.question;if(!a)continue;const i=e.answers?.[t];"string"==typeof i&&(s[a]=i)}return{behavior:"allow",updatedInput:{...t,answers:s}}}catch(e){return logger$1.warn(`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 logger$1.info(`Tool "${e}" already granted, skipping`),{behavior:"allow",updatedInput:t};const n=this.pendingPermissions.get(e);if(n)return logger$1.info(`Tool "${e}" has pending request, waiting...`),"allow"===await n?{behavior:"allow",updatedInput:t}:{behavior:"deny",message:"Permission denied by user"};let a;logger$1.info(`Requesting permission for "${e}"`);const s=new Promise(e=>{a=e});this.pendingPermissions.set(e,s);try{const n=await this.requestToolPermission(e);return a(n),"allow"===n?(this.grantedPermissions.add(e),{behavior:"allow",updatedInput:t}):{behavior:"deny",message:"Permission denied by user"}}catch(e){return a("deny"),{behavior:"deny",message:"Permission request failed"}}finally{this.pendingPermissions.delete(e)}}}async handleExitPlanModePermission(e){const t=e.planFilePath??e.filePath;let n,a;if(t){const e=this.workspace.getCwd(),s=e.endsWith("/")?e:e+"/";n=t.startsWith(s)?t.slice(s.length):void 0;try{const e=await fs$1.promises.readFile(t,"utf-8");a=e.length>8e3?e.slice(0,8e3)+"\n\n…(truncated)":e}catch{}}!a&&"string"==typeof e.plan&&e.plan&&(a=e.plan);const s=[{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:a}];try{const t=await this.askUser(s,{onTimeout:"abort_task"}),n=t.answers[0],a=t.details?.[0]?.trim();return"Approve"===n?{behavior:"allow",updatedInput:e}:"Revise"===n?{behavior:"deny",message:a?`The user wants to revise the plan. Revision notes: ${a}. 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 logger$1.warn(`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 askUserWithTimeout(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],a=t.rememberAnswers?.[0]??e[0]?.rememberSelection?.defaultValue??!1;return n.startsWith("other:")?(logger$1.info(`User provided custom input: ${n}, defaulting to Abort`),{action:"Abort",remember:!1}):{action:{Ignore:"Ignore",Commit:"Commit",Stash:"Stash",Abort:"Abort"}[n]||"Abort",remember:a}}catch(e){return logger$1.warn(`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],a=e.rememberAnswers?.[0]??n[0]?.rememberSelection?.defaultValue??!1;return t.startsWith("other:")?(logger$1.info(`User provided custom input: ${t}, defaulting to Abort`),{action:"Abort",remember:!1}):{action:{Switch:"Switch",Keep:"Keep",Abort:"Abort"}[t]||"Abort",remember:a}}catch(e){return logger$1.warn(`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()}}shouldDisableClaudePlanModeTools(){const e=this.options.input.taskType;return"chat"===e||"shadow"===e||this.isChannelBoundTask()||Boolean(this.options.input.parentTaskId)}get supportChangeTitle(){const e=this.options.input.customTitle;return!("string"==typeof e&&e.trim().length>0)}getStructuredOutputSchema(){return buildStructuredOutputSchema(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=machine.machine.resolveDataDir(t,e);this.chatHistoryDb=getTaskDb({dataDir:n,taskId:e})}return createAgentrixMcpTools({agentContext:this.agentContext,workClient:this.workClient,uploadFile:e=>this.agentContext.uploadFile(e),credentials:this.credentials,taskId:this.taskId,chatId:this.options.input.chatId,agentId:this.primaryAgentId,isGroup:e,historyDb:this.historyDb,chatHistoryDb:this.chatHistoryDb??void 0,askUser:e=>this.askUser(e),onChannelMessageInvoked:()=>{this.channelMessageInvocationCount+=1},invokeAgent:(e,t)=>this.invokeAgent(e,t),assign:(e,t,n)=>this.assignWork(e,t,n),setPendingNavigateTaskId:e=>{this.pendingNavigateTaskId=e},getChannelReplyTarget:()=>this.getInjectedChannelReplyTarget(),supportedFeatures:this.options.input.supportedFeatures,visionModel:this.options.input.visionModel,workingDirectory:this.workingDirectory})}isComputerUseEnabled(){try{return ensureComputerUseBridgeConfigured().enabled}catch(e){return logger$1.warn(`Failed to evaluate Agentrix Computer Use enablement: ${e instanceof Error?e.message:String(e)}`),!1}}resolveTaskAgentName(e){return this.taskAgentsMap.get(e)?.name||""}getChatSenderMeta(){return{senderType:"agent",senderId:this.primaryAgentId,senderName:this.primaryAgentName}}sendAgentErrorMessage(e,t,n,a){const s=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${s}: ${n}`}]}};this.workClient.sendTaskMessage({senderType:"agent",senderId:e,senderName:s},i,{groupId:a?.groupId})}async invokeAgent(e,t){const n=this.buildSubAgentHistoryContext(e,t);if(!n)return!1;const a=this.taskAgentsMap.get(e),s=a?.type||"claude";let i=this.agentQueues.get(e);i||(i=new InProcessQueue,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 a=await AgentRunners.create(s,e,{context:this.agentContext}),i=this.getGroupAgents()||[],r={mode:"reply",supportChangeTitle:!1,groupAgents:i},l=this.createPermissionHandler(),d=this.buildSystemHooks({trackBackgroundTasks:!1}),p=createMessageFilter(),u=a.loop({cwd:this.workingDirectory,model:this.options.input.model,agentSessionId:n.sessionId,abortController:this.abortController,modeConfig:r,env:this.buildClaudeRunEnvironment(),disableClaudePlanModeTools:this.shouldDisableClaudePlanModeTools(),agentrixTools:this.agentrixTools,enableTaskPreviewUrl:isTaskPreviewAvailableForWorker(this.options.input),enableVisionPlan:isVisionPlanAvailableForWorkspace(this.workingDirectory),allowAskUser:!this.isOneShotExecution(),supportedFeatures:this.options.input.supportedFeatures,channelBound:this.isChannelBoundTask(),channelGroupBound:this.isChannelGroupBoundTask(),channelContext:this.getExternalChannelPromptContext(),canUseTool:l,hooks:d,maxTurns:this.options.input.maxTurns??void 0,projectAgentrixGuidance:this.projectAgentrixGuidance,structuredOutputSchema:this.getStructuredOutputSchema()});let m=n.message;if("codex"===s&&!n.sessionId){const t=[buildAgentContextPrompt(e,i),"=== CONVERSATION STREAM START FROM HERE ===",extractUserMessageText(n.message)].join("\n\n").trim();t&&(m=t)}"string"==typeof m?u.push(m):u.push(await this.prepareMessageForRunner(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 a=c?n:p.filter(n);a&&this.workClient.sendTaskEvent({senderType:"agent",senderId:e,senderName:o},a,{groupId:t})}}catch(t){logger$1.error(`Invoke failed for ${e}:`,t)}finally{this.coordinator?.setAgentRunning(e,o,!1)}}),!0}async assignWork(e,t,n){const a=this.taskAgentsMap.get(e),s=a?.type||"claude";let i=this.agentQueues.get(e);i||(i=new InProcessQueue,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 a=this.newMessageGroupId();n&&this.workClient.sendTaskMessage({senderType:"agent",senderId:e,senderName:o},createClaudeAssistantMessage(n),{groupId:this.newMessageGroupId()});try{const n=await AgentRunners.create(s,e,{context:this.agentContext}),i={mode:"work",supportChangeTitle:!1},r=this.createPermissionHandler(),l=this.buildSystemHooks({trackBackgroundTasks:!1}),d=createMessageFilter(),p=n.loop({cwd:this.workingDirectory,model:this.options.input.model,abortController:this.abortController,modeConfig:i,env:this.buildClaudeRunEnvironment(),disableClaudePlanModeTools:this.shouldDisableClaudePlanModeTools(),agentrixTools:this.agentrixTools,enableTaskPreviewUrl:isTaskPreviewAvailableForWorker(this.options.input),enableVisionPlan:isVisionPlanAvailableForWorkspace(this.workingDirectory),allowAskUser:!this.isOneShotExecution(),supportedFeatures:this.options.input.supportedFeatures,channelBound:this.isChannelBoundTask(),channelGroupBound:this.isChannelGroupBoundTask(),channelContext:this.getExternalChannelPromptContext(),canUseTool:r,hooks:l,maxTurns:this.options.input.maxTurns??void 0,projectAgentrixGuidance:this.projectAgentrixGuidance,structuredOutputSchema:this.getStructuredOutputSchema()});p.push(t);let u=!1;for await(const t of p.events){if("system"===t.type&&"init"===t.subtype)continue;if("result"===t.type){this.workClient.sendTaskMessage({senderType:"agent",senderId:e,senderName:o},t,{groupId:a}),u=!0;break}const n=c?t:d.filter(t);n&&this.workClient.sendTaskEvent({senderType:"agent",senderId:e,senderName:o},n,{groupId:a})}}catch(t){logger$1.error(`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:a})}finally{this.coordinator?.setAgentRunning(e,o,!1)}})}buildSubAgentHistoryContext(e,t){const n=this.historyDb;if(!n)return logger$1.warn("Task history DB unavailable; delegate cannot build context."),null;const a=n.getAgentSessions().get(e),s=n.getAgentLastSequences().get(e)??0,i=n.pageRecentMessagesAfter(s,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:a,lastSequence:i.data.length>0?i.data[i.data.length-1].localSequence:s}:null}buildHistoryMessages(e,t){const n=[];for(const t of e){const e=formatHistoryMessageXml(t);e&&n.push(e)}if(0===n.length&&!t)return null;let a=n.join("\n");return t&&(a=`<hint>\n${t}\n</hint>\n\n${a}`),{type:"user",message:{role:"user",content:a},parent_tool_use_id:null,session_id:""}}buildSystemHooks(e){const t=e?.trackBackgroundTasks??!0,n=e?.trackPrimaryAgentStop??!1,a={};return t&&(a.PostToolUse=async e=>(this.syncPermissionModeFromPostToolUse(e),this.trackBackgroundTaskFromPostToolUse(e),{})),n&&(a.Stop=async()=>(this.updateAgentRunning(!1),{})),a}trackBackgroundTaskFromPostToolUse(e){if(!e||"object"!=typeof e)return void logger$1.debug("PostToolUse hook input is not an object");const t=e,n=t.tool_input;if(!n||!0!==n.run_in_background)return;const a=this.extractBackgroundTaskId(t.tool_response);if(!a)return logger$1.debug(`PostToolUse(${t.tool_name}) run_in_background=true but no task_id found, using anonymous tracking`),void this.coordinator?.setAnonymousBackgroundTaskRunning(!0);this.coordinator?.setBackgroundTaskRunning(a,!0),logger$1.info(`Background task started: ${a} (tool: ${t.tool_name})`)}syncPermissionModeFromPostToolUse(e){if(!e||"object"!=typeof e)return;const t=getPermissionModeAfterToolUse(e.tool_name,this.configuredPermissionMode);t&&this.confirmPermissionModeApplied(t)}handleBackgroundTaskNotification(e){this.updateAgentRunning(!0),this.coordinator?.setBackgroundTaskRunning(e.task_id,!1),logger$1.info(`Background task ${e.task_id} ${e.status}`)}extractBackgroundTaskId(e){const t=new Set,n=new Set,a=e=>{if("string"!=typeof e)return;const n=e.trim();n&&t.add(n)},s=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));)a(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)s(t);return}const t=e;"string"==typeof t.task_id&&a(t.task_id),"string"==typeof t.taskId&&a(t.taskId),"string"==typeof t.agent_id&&a(t.agent_id),"string"==typeof t.agentId&&a(t.agentId),"string"==typeof t.shell_id&&a(t.shell_id),"string"==typeof t.shellId&&a(t.shellId);for(const e of Object.values(t))s(e)};s(e);const i=[...t];return i.length>1&&logger$1.warn(`Multiple background task ids extracted (${i.join(", ")}), using first id ${i[0]}`),i[0]}createWorkerClientConfig(e,t,n){const a=this.options.input.agentId,s=this.taskAgentsMap.get(a)?.name;return{config:{userId:e,taskId:t,chatId:this.options.input.chatId,machineId:this.credentials.machineId,agentId:a,agentName:s,cwd:n,serverUrl:machine.machine.serverUrl.replace(/^http/,"ws"),path:"/v1/ws",auth:shared.workerAuth(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:shared.createEventId(),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}},handlers:{attachmentsDir:machine.machine.resolveAttachmentsDir(e,t),stopTask:async()=>{this.stopTask("event")},shouldPersistTaskMessage:async e=>!shared.isCompanionHeartbeatMessage(e)||!this.shouldDropHeartbeatWhileBusy()||(logger$1.debug("Dropping heartbeat at WorkerClient receive stage: agent is running"),!1),onTaskMessage:async(e,t)=>{if(shared.isAskUserResponseMessage(e)){const[t,n]=this.askUserAwaiter.entries().next().value||[];t&&n&&(this.askUserAwaiter.delete(t),n(e))}},onTaskInfoUpdate:async e=>{const t=this.options.input.model;await applyTaskInfoUpdate(e,this.options.input,this.workspace),t!==this.options.input.model&&Object.prototype.hasOwnProperty.call(e.updates??{},"model")&&(logger$1.info(`Task model updated from ${t??"default"} to ${this.options.input.model??"default"}; applying to subsequent Claude responses`),await(this.loopModelSetter?.(this.options.input.model)))},onReconnect:async()=>{this.sendCurrentWorkerStatus()},onWorkerStatusRequest:async()=>{this.sendCurrentWorkerStatus()},onSubTaskResultUpdated:async e=>{const t=buildSubTaskResultMessage(e,this.options.dataEncryptionKey);await this.coordinator.enqueue(t)},onSubTaskAskUser:async e=>{const t=buildSubTaskAskUserMessage(e,this.options.dataEncryptionKey);await this.coordinator.enqueue(t)}}}}async exitWorker(e){logger$1.info(`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){await this.workClient.sendTerminalErrorResultAndWait(e,{groupId:this.currentGroupId??void 0})}get taskId(){return this.options.input.taskId}async handleSdkResultMessage(e){let t,n;try{const e=await this.workspace.prepareResultArtifacts({onPatchError:e=>{logger$1.warn("Failed to write patch diff for result:",e)}});t=e.artifacts,n=e.artifactVersion}catch(e){logger$1.warn("Failed to prepare git artifacts for result:",e)}const a=this.getRunnerMode(),s="group_chat"===a||"group_work"===a,i=this.pendingNavigateTaskId;if(this.pendingNavigateTaskId=null,s?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 markArtifactVersionAsSent(this.options.input.userId,this.taskId,n)}catch(e){logger$1.warn("Failed to mark artifact version as sent:",e)}await this.forwardResultToChannelIfNeeded(e)}async forwardResultToChannelIfNeeded(e){if("result"!==e.type)return;const t=this.pendingChannelReplies.shift(),n=void 0===t?this.getInjectedChannelReplyTarget():t.target??this.getInjectedChannelReplyTarget();if(void 0===t&&!n)return;const a="success"===e.subtype,s=t?this.channelMessageInvocationCount>t.channelMessageInvocationCountAtStart:this.channelMessageInvocationCount>0;if(a&&s)return;const i=this.extractResultTextForChannel(e);if(!i)return;const o=await sendTaskChannelMessage(this.taskId,i,n),r=a;this.historyDb.saveTaskEvent({taskId:this.taskId,chatId:this.options.input.chatId,eventType:"channel-message-send",sequence:null,eventData:{status:o?.error?"error":"sent",delivery:r?"fallback":"error-forward",reason:r?"send_channel_message_not_invoked":"task_failed",channelId:n?.channelId,hasContent:!0,attachments:[],...o?.error?{error:o.error}:{}}}),o?.error&&logger$1.debug(`Claude reply was not sent to channel: ${o.error}`)}getInjectedChannelReplyTarget(){const e=process.env.AGENTRIX_CHANNEL_REPLY_TARGET;if(!e)return null;try{const t=JSON.parse(e);if("string"==typeof t.channelId&&"string"==typeof t.chatId)return{channelId:t.channelId,chatId:t.chatId,..."string"==typeof t.platform?{platform:t.platform}:{},..."string"==typeof t.chatType?{chatType:t.chatType}:{},..."string"==typeof t.chatName?{chatName:t.chatName}:{}}}catch(e){logger$1.debug("Ignoring invalid channel reply target:",e)}return null}isChannelBoundTask(){return null!==this.getInjectedChannelReplyTarget()}isChannelGroupBoundTask(){return"group"===this.getInjectedChannelReplyTarget()?.chatType?.toLowerCase()}getExternalChannelPromptContext(){const e=this.getInjectedChannelReplyTarget();if(e)return{platform:e.platform,chatType:e.chatType,chatName:e.chatName,chatId:e.chatId}}isChannelReplyTarget(e){return Boolean(e&&"object"==typeof e&&"string"==typeof e.channelId&&"string"==typeof e.chatId)}extractResultTextForChannel(e){if("success"===e.subtype){const t=e.result;if("string"!=typeof t)return null;const n=t.trim();return n.length>0?n:null}const t=e.errors,n=Array.isArray(t)?t.filter(e=>"string"==typeof e&&e.trim().length>0).join("\n").trim():"",a=e.subtype;return`Task failed: ${n||("string"==typeof a?a:"Unknown error")}`}}class CwdCalculator{static async calculateFinalCwd(e){const{repositorySourceType:t,cwd:n,userCwd:a,userId:s,taskId:i,forceUserCwd:o,useWorktree:r}=e,c=e=>normalizeWorkspacePath(e)||e;if(n)return c(n);const l=machine.machine.resolveProjectDir(s,i);if(("directory"===t||"git-server"===t)&&a){const e=c(a.replace(/^~/,os.homedir()));if(o||!1===r)return await this.assertUsableUserCwd(e),e}if("directory"===t&&a){const e=c(a.replace(/^~/,os.homedir()));return await this.assertUsableUserCwd(e),await this.shouldUseWorktree(e)?c(l):e}return c(l)}static async shouldUseWorktree(e){try{return!isDirectoryEmpty(e)&&await isGitRepository(e)}catch{return!1}}static async assertUsableUserCwd(e){let t;try{t=await promises$1.stat(e)}catch{throw new Error(`Workspace directory is unavailable: ${e}. Restore or relink the workspace before starting a filesystem task.`)}if(!t.isDirectory())throw new Error(`Workspace path is not a directory: ${e}`);try{await promises$1.access(e,fs.constants.R_OK|fs.constants.W_OK)}catch{throw new Error(`Workspace directory is not readable and writable: ${e}. Restore permissions before starting a filesystem task.`)}}}async function runClaude(e,t){const n=buildWorkspaceOptions(t.input),a=await CwdCalculator.calculateFinalCwd(n),s=new ClaudeWorker(e,t,a);await s.start()}const logger=machine.createModuleLogger("undefined"==typeof document?require("url").pathToFileURL(__filename).href:_documentCurrentScript&&"SCRIPT"===_documentCurrentScript.tagName.toUpperCase()&&_documentCurrentScript.src||new URL("index.cjs",document.baseURI).href);class CodexWorker{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;workerStartedAt=null;exitReason="completed";projectAgentrixGuidance={claudePlugins:[]};codexAgentrixEventMcp=null;isOneShotExecution(){return isOneShotExecution(this.options.input)}refreshGroupId(){this.currentGroupId=`group-${node_crypto.randomUUID()}`}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(),logger.warn("Fatal error:",e);const t=e instanceof Error?e.message:String(e);throw await this.exitWorker("error",t),e}logger.info(`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,n=Date.now();this.workerStartedAt=n,this.logger=machine.getLoggerBase(),this.dataEncryptionKey=this.options.dataEncryptionKey??null;const a=buildWorkspaceOptions(this.options.input),s=await CwdCalculator.calculateFinalCwd(a),i={...a,cwd:s};logger.debug(`Phase 1: Working directory: ${s}`);const o=1e3*Math.max(0,this.options.idleTimeoutSecond??0);logger.info([`worker.start taskId=${e}`,"workerType=codex",`agentId=${this.options.input.agentId??"unknown"}`,`cwd=${s}`,`repositorySourceType=${this.options.input.repositorySourceType??"unknown"}`,"sandboxMode=danger-full-access",`idleTimeoutMs=${o}`].join(" "));const r=this.createWorkerClientConfig(t,e,s),c=machine.machine.resolveDataDir(t,e);this.historyDb=getTaskDb({dataDir:c,taskId:e});const l=new WorkerClient(r.config,{...r.handlers,historyDb:this.historyDb});this.workClient=l,logger.debug("Phase 2: WorkerClient created"),this.coordinator=this.createMessageCoordinator(l,o),logger.debug("Phase 3: Coordinator created");const d=Date.now();await l.connect();const p=Date.now()-d;l.sendWorkerInitializing(),logger.debug("Phase 4: Connected to server"),logger.debug("Phase 5: Skipped (no AgentContext for Codex)"),logger.debug("Phase 6: Skipped (no custom resources for Codex)");const u=new Workspace({options:i,handlers:this.createWorkspaceHandlers(l,s)}),m=Date.now(),{initialCommitHash:h,gitStateResult:g,setupAction:f,branchName:y}=await u.setup(),v=Date.now()-m;this.workspace=u,this.projectAgentrixGuidance=await loadProjectAgentrixGuidance(s),logger.debug("Phase 7: Workspace setup complete"),logger.info([`workspace.ready action=${f}`,`cwd=${s}`,`branch=${y??"unknown"}`,`commit=${h||"none"}`,`repositorySourceType=${this.options.input.repositorySourceType??"unknown"}`,`workspaceMs=${v}`,`hadUncommittedChanges=${Boolean(g?.hadUncommittedChanges)}`].join(" ")),l.sendWorkerInitialized(),l.sendTaskSlashCommandsUpdate(buildSlashCommandCatalog()),logger.debug("Phase 8: Initialization finalized");const b=Date.now();await this.registerWithDaemon(s);const k=Date.now()-b;logger.debug("Phase 9: Registered with daemon"),logger.debug(`Prepared ${this.options.input.repositorySourceType} workspace via ${f} at ${s} (${h||"none"})`),logger.info(["worker.init.completed totalMs="+(Date.now()-n),`connectMs=${p}`,`workspaceMs=${v}`,`daemonRegisterMs=${k}`,`cwd=${s}`,"workerType=codex",`model=${this.options.input.model??"auto"}`].join(" ")),this.context={credentials:this.credentials,options:this.options,workClient:l,workingDirectory:s,dataDir:c,initialCommitHash:h,logger:this.logger},applyTaskEnvironmentToProcess(this.options.input,{workingDirectory:s,machineId:this.credentials.machineId}),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),await applyGitProviderAgentEnvironment(this.options.input),"agentSessionId"in this.options.input&&this.options.input.agentSessionId&&(this.threadId=this.options.input.agentSessionId,logger.info(`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 notifyDaemonSessionStarted(t,{cwd:e,machineId:this.credentials.machineId,pid:process.pid,startedBy:this.options.startedBy||"terminal"});n.error?logger.warn(`Failed to report session ${t}:`,n.error):logger.info(`Session ${t} registered`)}createMessageCoordinator(e,t){return this.coordinator=new Coordinator({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()},onAgentrixDevInit:async()=>{await notifyDaemonStartDevOpsInit(this.taskId,this.options.input.userId),this.stopTask("event")}},idleTimeoutMs:t,onIdleTimeout:()=>this.stopTask("idle")}),this.coordinator}sendCurrentWorkerStatus(){const e=this.workClient;if(!e||!this.coordinator)return;const{state:t}=this.coordinator.getStatus();"running"===t?e.sendWorkRunning(this.coordinator.getActiveAgents()):"idle"===t&&e.sendWorkerReady()}async handleEvent(){if("task-message"===this.options.input.event){const e=this.options.input.eventData,t=e.message;if(t){const n=formatUserContentLogLine(e,t,{source:"startup"});n&&logger.info(n)}t&&shared.isSDKMessage(t)&&"user"===t.type&&(await this.coordinator.enqueue(t),e.eventId&&this.workClient?.sendEventAck(e.eventId))}}async executeMergeRequest(){this.refreshGroupId(),logger.info("Executing merge-request command");try{if(!this.options.input.repositoryId){const e="Cannot create PR: task has no git repository configured.";return logger.warn("No repositoryId found in task input"),void this.context.workClient.sendSystemErrorMessage(e,{groupId:this.currentGroupId??void 0})}await hasUncommittedChanges(this.context.workingDirectory)&&await this.commitCurrentChangesWithAgent();const e=await getCurrentCommitHash(this.context.workingDirectory),t=this.context.initialCommitHash,n=this.workspace.getState(),a=n.branchName?{branchName:n.branchName,branchBinding:n.branchBinding}:this.options.input,s=hasStrongBranchBinding(a),i=s?resolvePublishBranchName(this.options.input.taskId,a.branchName):void 0;if(s&&i){const e=await getCurrentBranch(this.context.workingDirectory);if(e!==i){const t=buildMergeRequestBranchMismatchMessage(e,i);return logger.warn(t),void this.context.workClient.sendSystemErrorMessage(t,{groupId:this.currentGroupId??void 0})}}if(!t){const e="Cannot create PR: initial commit hash is missing.";return logger.error(e),void this.context.workClient.sendSystemErrorMessage(e,{groupId:this.currentGroupId??void 0})}if(0===(await getDiffStats(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 o=buildPRRequestPrompt(t);logger.debug(`PR prompt: ${o.substring(0,200)}...`);const r=this.options.input.agentId??"default",c=await AgentRunners.create("codex",r),l={mode:"work",supportChangeTitle:!1},d=c.runStreamed(o,{cwd:this.context.workingDirectory,model:this.currentModel||void 0,abortController:this.abortController,modeConfig:l,env:this.buildCodexRunEnvironment(),projectAgentrixGuidance:this.projectAgentrixGuidance,structuredOutputSchema:{type:"json_schema",schema:prInfoOpenAiSchema}});let p=null;for await(const e of d){if(this.context.logger.debug(`sdk message: ${JSON.stringify(e)}`),"result"===e.type){p=e;break}const t=this.filterMessages(e);null!==t&&this.context.workClient.sendTaskEvent(this.getChatSenderMeta(),t,{groupId:this.currentGroupId??void 0})}if(!p)throw new Error("Merge-request did not return a result message");const u=parsePrInfoFromResult(p),m=resolvePublishBranchName(this.options.input.taskId,i,u.title);s||await checkoutPublishBranchAtHead(this.context.workingDirectory,m);const h=buildHeadPushRef(m);logger.info(`Pushing HEAD to remote branch ${m}`),await pushForTask(this.context.workingDirectory,h,!1,{gitServerId:this.options.input.gitServerId,gitUrl:this.options.input.gitUrl}),logger.info("Successfully pushed branch to remote"),await this.createPullRequest(u.title,u.description,m),"explicit"!==a.branchBinding&&await this.workspace.updateBranchBinding(m,"platform-managed"),this.sendMessage(u.userMessage)}catch(e){const t=e instanceof Error?e.message:String(e);logger.error("Merge-request failed:",e),this.context.workClient.sendSystemErrorMessage(`Merge-request failed: ${t}\n\n`,{groupId:this.currentGroupId??void 0})}}async executeChangeTitle(e){logger.info(`Changing task title to: ${e}`),this.context.workClient.sendChangeTaskTitle(e)}async executeBashCommand(e){if(this.refreshGroupId(),!machine.machine.isDirectBashAllowed())return logger.warn("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});logger.info(`Executing command: ${e}`);const t=await executeCommandStreaming(e,this.context.workingDirectory,{onOutput:e=>{this.context.workClient.sendTaskMessage(this.getChatSenderMeta(),e,{groupId:this.currentGroupId??void 0})},onComplete:e=>{logger.info(`Command completed with exit code: ${e}`)}});logger.info(`Worker ready after command execution (exit code: ${t})`)}async executeMergePr(){this.refreshGroupId(),await executeMergePr({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 AgentRunners.create("codex",t),a=e||this.context?.workingDirectory;if(!a)throw new Error("Working directory is not available for commit generation");logger.info("Generating commit message with agent"),await commitCurrentChangesWithAgent({runner:n,workingDirectory:a,model:this.currentModel||this.options.input.model||void 0,abortController:this.abortController,modeConfig:{mode:"work",supportChangeTitle:!1},env:this.buildCodexRunEnvironment(),schemaTarget:"openai",projectAgentrixGuidance:this.projectAgentrixGuidance,onStreamMessage:async e=>{const t=this.filterMessages(e);null!==t&&this.getActiveWorkClient().sendTaskEvent(this.getChatSenderMeta(),t,{groupId:this.currentGroupId??void 0})}}),logger.info("Committed changes with agent-generated message")}async executeNewSession(){logger.info("Executing new-session: clearing threadId"),this.threadId=null,this.context.workClient.sendResetTaskSession(),logger.info("Session reset sent, stopping task for clean restart"),this.stopTask("event")}getStructuredOutputSchema(){return buildStructuredOutputSchema(this.options.input.outputSchema)}get supportChangeTitle(){const e=this.options.input.customTitle;return!("string"==typeof e&&e.trim().length>0)}async resolveCodexAgentrixEventMcp(){const e=await machine.machine.readDaemonState();if(!e?.port)return logger.debug("Agentrix event MCP broker unavailable: daemon state not found"),null;const t=isTaskPreviewAvailableForWorker(this.options.input),n=isVisionPlanAvailableForWorkspace(this.context?.workingDirectory),a=signAgentrixEventMcpToken(this.credentials,{taskId:this.taskId,userId:this.options.input.userId,taskPreviewEnabled:t,visionPlanEnabled:n});return{serverName:"agentrix_event_broker",url:buildDaemonControlUrl(e,AGENTRIX_EVENT_MCP_ROUTE),tokenEnvVar:"AGENTRIX_EVENT_MCP_TOKEN",titleToolName:"change_title",previewToolName:t?"publish_task_preview_url":void 0,sendVisionArtifactToolName:n?"send_vision_artifact":void 0,token:a}}buildCodexRunEnvironment(){const e=buildAgentRunEnvironment(this.options.input,{workingDirectory:this.context.workingDirectory,machineId:this.credentials.machineId,baseEnv:process.env});return this.codexAgentrixEventMcp&&(e[this.codexAgentrixEventMcp.tokenEnvVar]=this.codexAgentrixEventMcp.token),e}async runCodex(){logger.info(`Starting Codex agent for task ${this.taskId}`),this.currentModel=resolveCodexModel(this.options.input.model),this.currentModel?logger.info(`Using model: ${this.currentModel}`):logger.info("Using default model from Codex config (model name unavailable)");const e=this.options.input.agentId??"default",t=await AgentRunners.create("codex",e),n={mode:"work",supportChangeTitle:this.supportChangeTitle};if(this.codexAgentrixEventMcp=await this.resolveCodexAgentrixEventMcp(),this.isStopping)return void logger.info(`Skipping Codex run for task ${this.taskId} because worker is stopping`);if(this.isOneShotExecution())return void await this.runCodexOneShot(t,n);const a=t.loop({cwd:this.context.workingDirectory,model:this.currentModel||void 0,getModel:()=>this.currentModel||void 0,agentSessionId:this.threadId??void 0,abortController:this.abortController,modeConfig:n,env:this.buildCodexRunEnvironment(),codexAgentrixEventMcp:this.codexAgentrixEventMcp??void 0,taskDataDir:this.context.dataDir,enableTaskPreviewUrl:isTaskPreviewAvailableForWorker(this.options.input),enableVisionPlan:isVisionPlanAvailableForWorkspace(this.context.workingDirectory),projectAgentrixGuidance:this.projectAgentrixGuidance,structuredOutputSchema:this.getStructuredOutputSchema()});(async()=>{try{for(;!this.isStopping;){const e=await this.coordinator.waitForAgentMessage();if(e)this.refreshGroupId(),this.startAgentTurn(e),this.updateAgentRunning(!0),a.push(e);else if(this.isStopping)break}}catch(e){logger.error("Message pump failed:",e),this.stopTask("event")}})();try{for await(const e of a.events)this.context.logger.debug(`sdk message: ${JSON.stringify(e)}`),await this.handlePrimaryRunnerMessage(e)}catch(e){throw this.logAgentTurnFailed(e),e}logger.info(`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 logger.info(`Codex oneshot finished for task ${this.taskId} without runnable message`);this.updateAgentRunning(!0);try{this.refreshGroupId(),this.startAgentTurn(n);const a=e.runStreamed(n,{cwd:this.context.workingDirectory,model:this.currentModel||void 0,agentSessionId:this.threadId??void 0,abortController:this.abortController,modeConfig:t,env:this.buildCodexRunEnvironment(),codexAgentrixEventMcp:this.codexAgentrixEventMcp??void 0,taskDataDir:this.context.dataDir,enableTaskPreviewUrl:isTaskPreviewAvailableForWorker(this.options.input),enableVisionPlan:isVisionPlanAvailableForWorkspace(this.context.workingDirectory),projectAgentrixGuidance:this.projectAgentrixGuidance,structuredOutputSchema:this.getStructuredOutputSchema()});try{for await(const e of a)this.context.logger.debug(`sdk message: ${JSON.stringify(e)}`),await this.handlePrimaryRunnerMessage(e)}catch(e){throw this.logAgentTurnFailed(e),e}this.isStopping||this.stopTask("oneshot_complete")}finally{logger.info(`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(buildSlashCommandCatalog(e.slash_commands??[]),e.session_id),logger.debug(`Thread started: ${e.session_id}`),logger.info(`agent.thread.started sessionId=${e.session_id}`),void this.updateAgentRunning(!0);const t=this.filterMessages(e);null!==t&&("result"===e.type?(this.logAgentTurnCompleted(e),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 a=n.filter(e=>"tool_use"===e.type&&isAgentrixInternalMcpServerName(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===a.length?null:(t.message.content=a,t)}sendMessage(e){const t={type:"assistant",message:{id:node_crypto.randomUUID().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:node_crypto.randomUUID().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 askUserWithTimeout(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}startAgentTurn(e){logger.info([`agent.turn.started groupId=${this.currentGroupId??"none"}`,`model=${this.currentModel??this.options.input.model??"auto"}`,"session="+(this.threadId?"resume":"new"),`inputChars=${e.length}`].join(" "))}logAgentTurnCompleted(e){const t=e.usage;logger.info([`agent.turn.completed sessionId=${e.session_id||this.threadId||"unknown"}`,`subtype=${e.subtype}`,`isError=${e.is_error}`,`durationMs=${e.duration_ms}`,`turns=${e.num_turns}`,`inputTokens=${t?.input_tokens??0}`,`outputTokens=${t?.output_tokens??0}`,`cacheRead=${t?.cache_read_input_tokens??0}`,`resultChars=${"success"===e.subtype?(e.result??"").length:0}`].join(" "))}logAgentTurnFailed(e){const t=e instanceof Error?e.message:String(e);logger.warn([`agent.turn.failed sessionId=${this.threadId??"unknown"}`,`error=${JSON.stringify(t)}`].filter(Boolean).join(" "))}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],a=t.rememberAnswers?.[0]??e[0]?.rememberSelection?.defaultValue??!1;return n.startsWith("other:")?(logger.info(`User provided custom input: ${n}, defaulting to Abort`),{action:"Abort",remember:!1}):{action:{Ignore:"Ignore",Commit:"Commit",Stash:"Stash",Abort:"Abort"}[n]||"Abort",remember:a}}catch(e){return logger.warn(`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],a=e.rememberAnswers?.[0]??n[0]?.rememberSelection?.defaultValue??!1;return t.startsWith("other:")?(logger.info(`User provided custom input: ${t}, defaulting to Abort`),{action:"Abort",remember:!1}):{action:{Switch:"Switch",Keep:"Keep",Abort:"Abort"}[t]||"Abort",remember:a}}catch(e){return logger.warn(`Failed to get user response for branch mismatch: ${e}`),{action:"Abort",remember:!1}}}async createPullRequest(e,t,n){logger.info(`Creating PR: ${e}`);const a=await this.context.workClient.sendMergeRequest(e,t,n);this.sendMessage(`✅ Pull request created successfully!\nNumber: #${a.pullRequestNumber}\nURL: ${a.pullRequestUrl}`)}async convertSDKMessageToCodexInput(e){const t=e.message.content;if("string"==typeof t)return t;if(Array.isArray(t)){const e=[],n=machine.machine.resolveAttachmentsDir(this.options.input.userId,this.taskId);for(const a of t)if("text"===a.type&&a.text)e.push(a.text);else if("image"===a.type&&a.source&&a.source.url){const t=a.source.url;try{const{filePath:a}=await downloadFile(t,n,!1);logger.info(`Downloaded image from ${t} to ${a}`),e.push(`Image: ${a}`)}catch(e){logger.error(`Failed to download image from ${t}:`,e)}}else if("document"===a.type&&a.source&&a.source.url){const t=a.source.url;try{const{filePath:s,mimeType:i,filename:o}=await downloadFile(t,n,!0);logger.info(`Downloaded document from ${t} to ${s}`);const r=a.title||o;e.push(`Document: ${s}\nTitle: ${r}\nType: ${i}`)}catch(e){logger.error(`Failed to download document from ${t}:`,e)}}const a=e.map(e=>e.trim()).filter(Boolean).join("\n\n").trim();if(a)return a}return""}stopTask(e){this.isStopping||(this.isStopping=!0,"oneshot_complete"===e&&(this.exitReason="oneshot_complete",logger.info("One-shot execution completed, stopping task")),"idle"===e?(this.exitReason="idle_timeout",logger.info("worker.stop.requested reason=idle_timeout source=codex_worker")):"ask_user_timeout"===e&&(this.exitReason="ask_user_timeout",logger.info("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 a=this.options.input.agentId,s=this.options.input.taskAgents?.find(e=>e.id===a)?.name;return{config:{userId:e,taskId:t,chatId:this.options.input.chatId,machineId:this.credentials.machineId,agentId:a,agentName:s,cwd:n,serverUrl:machine.machine.serverUrl.replace(/^http/,"ws"),path:"/v1/ws",auth:shared.workerAuth(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:shared.createEventId(),status:n,taskId:t,machineId:this.credentials.machineId,timestamp:Date.now().toString()}}},healthCheckConfig:{enabled:!0,intervalMs:3e4,timeoutMs:5e3}},handlers:{attachmentsDir:machine.machine.resolveAttachmentsDir(e,t),stopTask:async()=>{this.stopTask("event")},onTaskMessage:async e=>{if(shared.isAskUserResponseMessage(e)){const[t,n]=this.askUserAwaiter.entries().next().value||[];return void(t&&n&&(this.askUserAwaiter.delete(t),n(e)))}shared.isSDKMessage(e)&&"user"===e.type&&await this.coordinator.enqueue(e)},onTaskInfoUpdate:async e=>{const t=this.options.input.model;await applyTaskInfoUpdate(e,this.options.input,this.workspace),t!==this.options.input.model&&Object.prototype.hasOwnProperty.call(e.updates??{},"model")&&(this.currentModel=resolveCodexModel(this.options.input.model),logger.info(`Task model updated from ${t??"default"} to ${this.options.input.model??"default"}; applying to subsequent Codex turns`))},onReconnect:async()=>{this.sendCurrentWorkerStatus()},onWorkerStatusRequest:async()=>{this.sendCurrentWorkerStatus()}}}}async exitWorker(e,t){this.coordinator&&this.coordinator.stop(),logger.info(`worker.exit reason=${e} taskId=${this.taskId} totalMs=${this.workerStartedAt?Date.now()-this.workerStartedAt:"unknown"}`);const n=this.context?.workClient??this.workClient;n&&("error"===e&&t?await n.sendErrorMessageAndExit(t):(n.sendWorkerExit(e),await n.disconnect()),this.historyDb&&this.historyDb.close())}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=>{logger.warn("Failed to write patch diff for result:",e)}});t=e.artifacts,n=e.artifactVersion}catch(e){logger.warn("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 markArtifactVersionAsSent(this.options.input.userId,this.taskId,n)}catch(e){logger.warn("Failed to mark artifact version as sent:",e)}}}async function runCodex(e,t){const n=new CodexWorker(e,t);await n.start()}function createWorkerClient$2(e,t,n){const a=machine.machine.serverUrl.replace(/^http/,"ws");return socket_ioClient.io(a,{path:"/v1/ws",transports:["websocket"],auth:{token:e.token,clientType:"worker",machineId:e.machineId,taskId:n}})}async function runDeployment(e,t){const n=t.input,{taskId:a,sourcePath:s,targetAgentId:i,userId:o,name:r,avatar:c,isSystemAgent:l,supportLocal:d}=n;let p=null;try{if(console.log(`[Deployment] Starting deployment worker for task ${a}`),!fs.existsSync(s))throw new Error(`Source path not found: ${s}`);const t=path.join(machine.machine.agentrixAgentsHomeDir,i);if(fs.existsSync(t))throw new Error(`Target agent directory already exists: ${t}`);console.log(`[Deployment] Copying from ${s} to ${t}`),await copyDirectory(s,t),console.log("[Deployment] Deployment completed successfully"),p=createWorkerClient$2(e,o,a),await new Promise((e,t)=>{const n=setTimeout(()=>{t(new Error("WebSocket connection timeout"))},1e4);p.on("connect",()=>{clearTimeout(n),console.log("[Deployment] Connected to server"),p.emit("deploy-agent-complete",{eventId:shared.createEventId(),taskId:a,targetAgentId:i,success:!0,name:r,avatar:c,isSystemAgent:l,supportLocal:d}),console.log("[Deployment] Sent deploy-agent-complete event"),setTimeout(()=>{e()},1e3)}),p.on("connect_error",e=>{clearTimeout(n),t(e)})})}catch(e){throw console.error("[Deployment] Deployment failed:",e),p&&p.connected&&(p.emit("deploy-agent-complete",{eventId:shared.createEventId(),taskId:a,targetAgentId:i,success:!1,error:e instanceof Error?e.message:String(e)}),await new Promise(e=>setTimeout(e,1e3))),e}finally{p&&p.disconnect(),process.exit(0)}}function resolveClaudePath(){const e=process.env.AGENTRIX_CLAUDE_PATH?.trim();if(!e)return;if(e.includes("/")||e.includes("\\")||e.startsWith(".")){const t=path.isAbsolute(e)?e:path.resolve(e);return fs.existsSync(t)?t:void 0}const t="win32"===process.platform?"where":"which",n=node_child_process.spawnSync(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 normalizeReviewTags(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 createReviewTool(e){return claudeAgentSdk.tool("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:zod.z.boolean().describe("true if the code passes security review, false if it must be rejected"),reasons:zod.z.array(zod.z.string()).describe("If rejected: list each specific issue found. If approved: briefly state what was checked."),tags:zod.z.array(zod.z.string()).describe("3-8 concise marketplace discovery tags describing the agent or skill capability. Use lowercase kebab-case.")},async t=>(e({approved:t.approved,reasons:t.reasons,tags:normalizeReviewTags(t.tags)}),{content:[{type:"text",text:"Review decision recorded."}]}))}function collectFileList(e,t=""){const n=fs.readdirSync(e,{withFileTypes:!0}),a=[];for(const s of n){const n=t?`${t}/${s.name}`:s.name;"node_modules"!==s.name&&".git"!==s.name&&(s.isDirectory()?a.push(...collectFileList(path.join(e,s.name),n)):a.push(n))}return a}const REVIEW_SYSTEM_PROMPT='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 real publish-blocking security issues:\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 that appear to be user data or sensitive personal data\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 or instructions that abuse permissions to access sensitive files, steal data, persist malware, or operate outside the intended agent/skill workflow\n\nAgentrix-specific review guidance:\n- Do NOT reject solely because an agent config uses permissionMode "bypassPermissions".\n- Do NOT reject solely because allowedTools includes Bash, WebFetch, Read, Write, Edit, or other normal Agentrix/Claude tools. These tools are part of the Agentrix runtime model.\n- Reject permission usage only when the source contains malicious or clearly unsafe behavior, such as reading secrets from home directories, scanning unrelated user files, silently uploading data, destructive shell commands, persistence, credential theft, or instructions to bypass user intent.\n- Generated/local build metadata such as avatar/upload-avatar.json may contain local file paths or localhost URLs from the creator\'s machine. Treat these as cleanup suggestions, not publish-blocking security issues, unless they contain secrets or sensitive personal data beyond ordinary development paths.\n- Ordinary repository paths, localhost URLs, sample usernames in paths, generated artifact paths, and non-secret build cache metadata are not enough to reject a publish request.\n- If you find non-blocking cleanup suggestions, include them in reasons while still approving.\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 about real security issues, but do not reject normal Agentrix runtime configuration or harmless generated local metadata. Approve when there is no credible exploit, secret, malicious behavior, or sensitive user-data exposure.';async function reviewHivePublish(e,t,n){const a=collectFileList(e).map(e=>` - ${e}`).join("\n");return new Promise((s,i)=>{let o=!1,r=null;const c=e=>{o||(o=!0,clearTimeout(d),s(e))},l=e=>{o||(o=!0,clearTimeout(d),i(e))},d=setTimeout(()=>{c({approved:!1,reasons:["Review timed out after 10 minutes"],tags:[]})},6e5),p=createReviewTool(e=>{r=e,c(e)}),u=claudeAgentSdk.createSdkMcpServer({name:"hive_review",version:"1.0.0",tools:[p]}),m=[`Review the ${n} "${t}" for security issues before publishing to Hive.`,"",`Source directory: ${e}`,"","Files to review:",a,"","Read each file, then call mcp__hive_review__hive_publish_review with your decision."].join("\n"),h=claudeAgentSdk.query({prompt:m,options:{systemPrompt:REVIEW_SYSTEM_PROMPT,permissionMode:"bypassPermissions",settingSources:["user","project","local"],maxTurns:30,cwd:e,mcpServers:{hive_review:u},pathToClaudeCodeExecutable:resolveClaudePath(),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 execFileAsync$1=node_util.promisify(node_child_process.execFile);function createWorkerClient$1(e,t,n){const a=machine.machine.serverUrl.replace(/^http/,"ws");return socket_ioClient.io(a,{path:"/v1/ws",transports:["websocket"],auth:{token:e.token,clientType:"worker",machineId:e.machineId,taskId:n}})}async function git$1(e,...t){const{stdout:n}=await execFileAsync$1("git",t,{cwd:e});return n.trim()}async function hasStagedChanges(e){try{return await execFileAsync$1("git",["diff","--cached","--quiet"],{cwd:e}),!1}catch(e){if("number"==typeof e?.code&&1===e.code)return!0;throw e}}function slugifyName(e){return e.toLowerCase().replace(/[^a-z0-9-]/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,"")||"skill"}function parseSkillMetadata(e){const t=path.join(e,"SKILL.md"),n=fs.readFileSync(t,"utf-8"),a=n.match(/^---\r?\n([\s\S]*?)\r?\n---\r?\n?/);if(!a)throw new Error("SKILL.md must start with YAML frontmatter containing name and description");const s=a[1],i=new Map;for(const e of s.split(/\r?\n/)){const t=e.match(/^([A-Za-z0-9_-]+):\s*(.*)$/);t&&i.set(t[1],t[2].replace(/^["']|["']$/g,"").trim())}const o=i.get("name"),r=i.get("description");if(!o)throw new Error("SKILL.md frontmatter must include name");if(!r)throw new Error("SKILL.md frontmatter must include description");return{name:slugifyName(o),displayName:o,description:r,readme:n,repoDirName:slugifyName(o)}}function validateHivePublishSource(e,t){if(!fs.existsSync(e))throw new Error(`Source directory not found: ${e}`);if(!fs.statSync(e).isDirectory())throw new Error(`Source path is not a directory: ${e}`);if("skill"===t&&!fs.existsSync(path.join(e,"SKILL.md")))throw new Error(`Skill directory must contain SKILL.md: ${e}`)}async function runHivePublish(e,t){const n=t.input,{taskId:a,listingId:s,userId:i,sourceDir:o,gitUrl:r,version:c}=n;let l,d,{repoDir:p,name:u}=n,m=n.displayName,h=n.description,g=n.readme,f=null,y=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 ${a}, name=${u}`),validateHivePublishSource(o,n.type),"skill"===n.type){const e=parseSkillMetadata(o);u=e.name,m=e.displayName,h=e.description,g=e.readme,p=path.posix.join(p,e.repoDirName),console.log(`[HivePublish] Parsed skill metadata name=${u}, displayName=${m}`)}y=path.join(machine.machine.agentrixHomeDir,"tmp","hive-publish",a),fs.mkdirSync(y,{recursive:!0}),console.log("[HivePublish] Cloning hive repo..."),await git$1(y,"clone","--depth","1",r,".");const t=path.join(y,p);if(fs.mkdirSync(path.dirname(t),{recursive:!0}),"skill"===n.type&&fs.existsSync(t))throw new Error(`Skill already exists in Hive repository: ${p}`);fs.existsSync(t)&&fs.rmSync(t,{recursive:!0,force:!0}),console.log(`[HivePublish] Copying ${o} → ${p}`),await copyDirectory(o,t),fs.writeFileSync(path.join(t,"agentrix-hive-id.txt"),`${s}\n`,"utf-8"),await git$1(y,"add",".");const v=await hasStagedChanges(y);if(v){console.log("[HivePublish] Running Claude security review...");const e=await reviewHivePublish(o,u,n.type);if(l=e.reasons,d=e.tags,!e.approved)throw new Error(`Security review rejected: ${e.reasons.join("; ")}`);console.log("[HivePublish] Security review passed");const t=`publish: ${p} v${c}`;await git$1(y,"commit","-m",t),console.log("[HivePublish] Pushing to remote..."),await git$1(y,"push")}else console.log("[HivePublish] No git changes to publish; using existing HEAD");const b=await git$1(y,"rev-parse","HEAD");console.log(`[HivePublish] Push succeeded, commit=${b}`),f=createWorkerClient$1(e,i,a),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:shared.createEventId(),taskId:a,listingId:s,success:!0,gitCommitHash:b,hasChanges:v,tags:d,name:u,displayName:m,description:h,readme:g,repoDir:p}),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??createWorkerClient$1(e,i,a),await new Promise(e=>{const n=setTimeout(e,5e3),i=()=>{f.emit("hive-publish-complete",{eventId:shared.createEventId(),taskId:a,listingId:s,success:!1,error:t instanceof Error?t.message:String(t),reviewReasons:l}),clearTimeout(n),setTimeout(e,1e3)};f.connected?i():(f.on("connect",i),f.on("connect_error",()=>{clearTimeout(n),e()}))})}catch{console.error("[HivePublish] Failed to send error event")}throw t}finally{if(f&&f.disconnect(),y&&fs.existsSync(y))try{fs.rmSync(y,{recursive:!0,force:!0})}catch{}process.exit(0)}}const execFileAsync=node_util.promisify(node_child_process.execFile);function createWorkerClient(e,t,n){const a=machine.machine.serverUrl.replace(/^http/,"ws");return socket_ioClient.io(a,{path:"/v1/ws",transports:["websocket"],auth:{token:e.token,clientType:"worker",machineId:e.machineId,taskId:n}})}async function git(e,...t){const{stdout:n}=await execFileAsync("git",t,{cwd:e});return n.trim()}function resolveInstallDir(e){return e.startsWith("~/")?path.join(process.env.HOME||"",e.slice(2)):path.isAbsolute(e)?e:path.join(machine.machine.agentrixHomeDir,e)}async function runHiveInstall(e,t){const n=t.input,{taskId:a,userId:s,sourceRepoDir:i,gitUrl:o,name:r,sourceType:c}=n,l=n.installDir??n.draftAgentDir;let d=null,p=null;try{console.log(`[HiveInstall] Starting for task ${a}, name=${r}`),p=path.join(machine.machine.agentrixHomeDir,"tmp","hive-install",a),fs.mkdirSync(p,{recursive:!0}),console.log("[HiveInstall] Cloning hive repo..."),await git(p,"clone","--depth","1",o,".");const t=path.join(p,i);if(!fs.existsSync(t))throw new Error(`Source directory not found in hive repo: ${i}`);if("skill"===c&&!fs.existsSync(path.join(t,"SKILL.md")))throw new Error(`Skill directory must contain SKILL.md: ${i}`);const n=resolveInstallDir(l);if(fs.existsSync(n))throw new Error(`Target install directory already exists: ${n}`);if(fs.mkdirSync(n,{recursive:!0}),console.log(`[HiveInstall] Copying ${i} → ${n}`),await copyDirectory(t,n),"agent"===c)try{console.log(`[HiveInstall] Building agent plugins/hooks in ${n}`),buildAgentPlugins(n)}catch(e){try{fs.rmSync(n,{recursive:!0,force:!0})}catch{}throw e}const u=path.join(n,".git");fs.existsSync(u)&&(fs.rmSync(u,{recursive:!0,force:!0}),console.log("[HiveInstall] Removed .git from installed directory")),console.log("[HiveInstall] Install completed successfully"),d=createWorkerClient(e,s,a),await new Promise((e,t)=>{const s=setTimeout(()=>t(new Error("WebSocket connection timeout")),1e4);d.on("connect",()=>{clearTimeout(s),d.emit("hive-install-complete",{eventId:shared.createEventId(),taskId:a,success:!0,agentDir:n}),console.log("[HiveInstall] Sent hive-install-complete (success)"),setTimeout(e,1e3)}),d.on("connect_error",e=>{clearTimeout(s),t(e)})})}catch(t){console.error("[HiveInstall] Failed:",t);try{d=d??createWorkerClient(e,s,a),await new Promise(e=>{const n=setTimeout(e,5e3),s=()=>{d.emit("hive-install-complete",{eventId:shared.createEventId(),taskId:a,success:!1,error:t instanceof Error?t.message:String(t)}),clearTimeout(n),setTimeout(e,1e3)};d.connected?s():(d.on("connect",s),d.on("connect_error",()=>{clearTimeout(n),e()}))})}catch{console.error("[HiveInstall] Failed to send error event")}throw t}finally{if(d&&d.disconnect(),p&&fs.existsSync(p))try{fs.rmSync(p,{recursive:!0,force:!0})}catch{}process.exit(0)}}async function runCompanion(e,t){const{agentDir:n,homeDir:a}=await ensureCompanionAgent();t.input.agentDir=n,process.env.AGENTRIX_COMPANION_HOME=a;const s=buildWorkspaceOptions(t.input),i=await CwdCalculator.calculateFinalCwd(s),o=new ClaudeWorker(e,t,i);await o.start()}const workerTypes=["claude","codex","deployment","companion","hive-publish","hive-install"],workerRegistry={claude:{async run({credentials:e,startedBy:t,userId:n,taskId:a,idleTimeoutSecond:s}){const i=machine.machine.readTaskInput(n,a),o=i.dataEncryptionKey?shared.decodeBase64(i.dataEncryptionKey):null;if(o&&32!==o.length)throw new Error("Invalid dataEncryptionKey: expected decrypted 32-byte key");const r={startedBy:t,idleTimeoutSecond:s,input:i,dataEncryptionKey:o};await runClaude(e,r)}},codex:{async run({credentials:e,startedBy:t,userId:n,taskId:a,idleTimeoutSecond:s}){const i=machine.machine.readTaskInput(n,a),o=i.dataEncryptionKey?shared.decodeBase64(i.dataEncryptionKey):null;if(o&&32!==o.length)throw new Error("Invalid dataEncryptionKey: expected decrypted 32-byte key");const r={startedBy:t,idleTimeoutSecond:s,input:i,dataEncryptionKey:o};await runCodex(e,r)}},deployment:{async run({credentials:e,startedBy:t,userId:n,taskId:a,idleTimeoutSecond:s}){const i={input:machine.machine.readTaskInput(n,a)};await runDeployment(e,i)}},"hive-publish":{async run({credentials:e,startedBy:t,userId:n,taskId:a,idleTimeoutSecond:s}){const i={input:machine.machine.readTaskInput(n,a)};await runHivePublish(e,i)}},"hive-install":{async run({credentials:e,startedBy:t,userId:n,taskId:a,idleTimeoutSecond:s}){const i={input:machine.machine.readTaskInput(n,a)};await runHiveInstall(e,i)}},companion:{async run({credentials:e,startedBy:t,userId:n,taskId:a,idleTimeoutSecond:s}){const i=machine.machine.readTaskInput(n,a),o=i.dataEncryptionKey?shared.decodeBase64(i.dataEncryptionKey):null;if(o&&32!==o.length)throw new Error("Invalid dataEncryptionKey: expected decrypted 32-byte key");const r={startedBy:t,idleTimeoutSecond:s,input:i,dataEncryptionKey:o};await runCompanion(e,r)}}};async function fetchAgentGitUrl(e,t){const n=`${machine.machine.serverUrl}/v1/agents/${encodeURIComponent(e)}/git-url`,a=await fetch(n,{headers:{Authorization:`Bearer ${t.token}`}});return a.ok?a.json():null}function readAgentVersion(e){try{const t=fs.readFileSync(path.join(e,"agent.json"),"utf-8"),n=JSON.parse(t);return"string"==typeof n.version?n.version:null}catch{return null}}function isNewerVersion(e,t){const n=e=>e.split(".").map(e=>parseInt(e,10)||0),a=n(e),s=n(t);for(let e=0;e<Math.max(a.length,s.length);e++){const t=a[e]??0,n=s[e]??0;if(t>n)return!0;if(t<n)return!1}return!1}async function checkAgentUpdates(e){const t=machine.machine.agentrixAgentsHomeDir;if(!fs.existsSync(t))return;let n;try{n=fs.readdirSync(t).filter(e=>fs.statSync(path.join(t,e)).isDirectory())}catch{return}for(const a of n){if("companion"===a||a.startsWith("draftagent-")||a.includes("."))continue;const n=path.join(t,a),s=path.join(n,"upgrade");if(fs.existsSync(s))continue;const i=readAgentVersion(n);machine.logger.info(`[AGENT UPDATE] Checking ${a} (local version: ${i??"unknown"})`);try{const t=await fetchAgentGitUrl(a,e);if(!t||!t.gitUrl){machine.logger.info(`[AGENT UPDATE] No git repo for ${a}, skipping`);continue}const n=`${s}.tmp-${Date.now()}`;try{const e=["git","clone","--depth=1","--branch",t.branch,t.gitUrl,n];node_child_process.execSync(e.join(" "),{stdio:"pipe",timeout:12e4});const o=t.subDir?path.join(n,t.subDir):n;if(t.subDir&&!fs.existsSync(o))throw new Error(`subDir "${t.subDir}" not found in cloned repo`);const r=readAgentVersion(o);if(!r||i&&!isNewerVersion(r,i)){machine.logger.info(`[AGENT UPDATE] ${a} up to date (local: ${i??"unknown"}, remote: ${r??"unknown"})`),fs.rmSync(n,{recursive:!0,force:!0});continue}machine.logger.info(`[AGENT UPDATE] Update available for ${a}: ${i??"unknown"} → ${r}`),t.subDir?(fs.renameSync(o,s),fs.rmSync(n,{recursive:!0,force:!0})):fs.renameSync(n,s),machine.logger.info(`[AGENT UPDATE] Staged upgrade for ${a}`)}catch(e){throw fs.existsSync(n)&&fs.rmSync(n,{recursive:!0,force:!0}),e}}catch(e){machine.logger.warn(`[AGENT UPDATE] Check failed for ${a}: ${e}`)}}}function normalizeUrl(e,t){const n=e.trim();if(!n)throw new Error(`${t} is required`);let a;try{a=new URL(n)}catch{throw new Error(`${t} must be a valid URL`)}if("http:"!==a.protocol&&"https:"!==a.protocol)throw new Error(`${t} must use http or https`);return a.toString().replace(/\/+$/,"")}function defaultGitLabApiUrl(e){return`${normalizeUrl(e,"baseUrl")}/api/v4`}function readSecretInput(e){if("-"===e)return fs.readFileSync(0,"utf8").trim();if(!fs.existsSync(e))throw new Error(`File not found: ${e}`);return fs.readFileSync(e,"utf8").trim()}async function promptText(e,t){if(!node_process.stdin.isTTY){if(void 0!==t)return t;throw new Error(`${e} is required in non-interactive mode`)}const n=promises$3.createInterface({input:node_process.stdin,output:node_process.stdout});try{const a=t?` (${t})`:"";return(await n.question(`${e}${a}: `)).trim()||t||""}finally{n.close()}}async function promptSecret(e){return node_process.stdin.isTTY&&node_process.stdout.isTTY&&"function"==typeof node_process.stdin.setRawMode?new Promise((t,n)=>{let a="";const s=()=>{node_process.stdin.setRawMode(!1),node_process.stdin.pause(),node_process.stdin.off("data",i)},i=e=>{const i=e.toString("utf8");return""===i?(s(),node_process.stdout.write("\n"),void n(new Error("Interrupted"))):"\r"===i||"\n"===i?(s(),node_process.stdout.write("\n"),void t(a.trim())):void(""!==i&&"\b"!==i?a+=i:a=a.slice(0,-1))};node_process.stdout.write(`${e}: `),node_process.stdin.setRawMode(!0),node_process.stdin.resume(),node_process.stdin.on("data",i)}):promptText(e)}async function promptYesNo(e,t){if(!node_process.stdin.isTTY)return t;const n=(await promptText(`${e} (Y/n)`)).toLowerCase();return n?["y","yes"].includes(n):t}async function getEncryptionKey(){const e=await getGitServerEncryptionKey();if(!e)throw new Error("No Agentrix auth secret found. Run `agentrix start` and complete machine binding first.");return e}function parseStringArg(e){return"string"==typeof e&&e.trim()?e.trim():void 0}function parseBooleanArg(e){return"boolean"==typeof e?e:void 0}async function runAddCommand(e){const t=normalizeUrl(parseStringArg(e["base-url"])??await promptText("GitLab base URL"),"baseUrl"),n=normalizeUrl(parseStringArg(e["api-url"])??await promptText("GitLab API URL",defaultGitLabApiUrl(t)),"apiUrl"),a=new URL(t).hostname,s=parseStringArg(e.name)??await promptText("Git server name",a),i=(parseStringArg(e["pat-file"])?readSecretInput(parseStringArg(e["pat-file"])):void 0)??await promptSecret("GitLab PAT");if(!i)throw new Error("GitLab PAT is required");const o=parseBooleanArg(e.proxy)??await promptYesNo("Use this machine as a Git proxy node",!0),r=await bindGitServerViaDaemon({name:s,baseUrl:t,apiUrl:n,pat:i,useAsProxy:o});if(r.error||!r.success||!r.gitServer)throw new Error(`Git server add failed: ${r.error||"Daemon did not return a bound Git server"}`);const c=r.gitServer;console.log(JSON.stringify({id:c.id,type:"gitlab",baseUrl:c.baseUrl,apiUrl:c.apiUrl,webhookEndpointPath:r.webhookEndpointPath??node.buildGitLabWebhookEndpointPath(c.id),webhookUrl:r.webhookUrl??node.buildGitLabWebhookUrl(c.id,await machine.machine.readDaemonState()),backendRegistered:!0,proxyRegistered:r.proxyRegistered??o,patConfigured:!0,patMeta:r.patMeta??loadPatMeta(c.id),webhookSecret:r.webhookSecret},null,2))}function buildListItem(e,t,n){const a=loadGitServerConfig(e.id)??{},s=loadGitLabWebhookBridgeSecrets(e.id,t)??{};return{id:e.id,type:"gitlab",baseUrl:e.baseUrl||a.baseUrl,apiUrl:e.apiUrl||a.apiUrl,webhookEndpointPath:node.buildGitLabWebhookEndpointPath(e.id),webhookUrl:node.buildGitLabWebhookUrl(e.id,n),patConfigured:hasPat(e.id),patMeta:loadPatMeta(e.id),webhookSecret:s.webhookSecret,projectTriggerTokens:s.projectTriggerTokens??{}}}async function runListCommand(){const e=await getEncryptionKey(),t=await machine.machine.readDaemonState(),n=await listGitServersViaDaemon();if(n.error)throw new Error(`Backend Git server list failed: ${n.error}`);const a=(n.gitServers??[]).filter(e=>"gitlab"===e.type&&"local_pat"===e.authModeDefault).map(n=>buildListItem(n,e,t));console.log(JSON.stringify(a,null,2))}function handleCommandError(e){console.error(chalk.red("Error:"),e instanceof Error?e.message:"Unknown error"),process.env.DEBUG&&console.error(e),process.exit(1)}function registerGitServerCommands(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("name",{type:"string",describe:"Git server display name, defaults to the GitLab hostname"}).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("proxy",{type:"boolean",describe:"Register this machine as a Git proxy node (use --no-proxy to save PAT locally only)"}),async e=>{try{await runAddCommand(e),process.exit(0)}catch(e){handleCommandError(e)}}).command("list","List local private GitLab server config",{},async()=>{try{await runListCommand(),process.exit(0)}catch(e){handleCommandError(e)}}).demandCommand(1,"Please specify one of: add, list").strict(),()=>{})}const DEFAULT_CLAUDE_MODELS={primary:"claude-sonnet-4-6",fast:"claude-haiku-4-5",subagent:"claude-sonnet-4-6"},DEFAULT_CODEX_MODEL$1="gpt-5.5";function getFallbackAgentrixApiBaseUrl(){return process.env.OPENAPI_BASE_URL||process.env.AGENTRIX_OPENAPI_BASE_URL||machine.machine.serverUrl}async function fetchAgentrixApiBaseUrl(e){try{return(await axios.get(`${machine.machine.serverUrl}/v1/openapi-config`,{headers:{Authorization:`Bearer ${e.token}`},timeout:1e4})).data.baseUrl||getFallbackAgentrixApiBaseUrl()}catch(e){const t=e instanceof Error?e.message:"unknown error";return console.log(chalk.yellow(`Could not fetch Agentrix API URL from server, using fallback: ${t}`)),getFallbackAgentrixApiBaseUrl()}}function commandExists(e){return(process.env.PATH||"").split(":").filter(Boolean).some(t=>{try{return fs.accessSync(path.join(t,e),fs.constants.X_OK),!0}catch{return!1}})}function detectPackageManager(){return[{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=>commandExists(e.name))||null}function runCommand(e,t,n){return new Promise((a,s)=>{const i=node_child_process.spawn(e,t,{stdio:"inherit",shell:n?.shell||!1,env:process.env});i.on("error",s),i.on("close",t=>{0===t?a():s(new Error(`${e} exited with code ${t}`))})})}async function pathExists(e){try{return await promises$1.access(e),!0}catch{return!1}}function missingInstallableDeps(e){return e.filter(e=>e.required&&!e.installed)}async function installSystemDependencies(e){if(0===e.length)return void console.log(chalk.green("✓ System dependencies are installed"));if("linux"!==process.platform){console.log(chalk.yellow("Automatic dependency installation is currently only supported on Linux."));for(const t of e)console.log(chalk.yellow(`- ${t.name}: ${t.installCommand||"install manually"}`));return}const t=detectPackageManager();if(!t){console.log(chalk.yellow("No supported package manager found. Install these dependencies manually:"));for(const t of e)console.log(chalk.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(chalk.blue(`Installing system dependencies with ${t.name}: ${n.join(", ")}`));const a=t.installCommand(n);"apt-get"===t.name?await runCommand(a.join(" "),[],{shell:!0}):await runCommand(a[0],a.slice(1))}async function installNpmDependency(e,t){commandExists(e)?console.log(chalk.green(`✓ ${e} is installed`)):commandExists("npm")?(console.log(chalk.blue(`Installing ${e} with npm...`)),await runCommand("npm",["install","-g",t])):console.log(chalk.yellow(`npm is not available. Install ${t} manually.`))}async function ensureDependencies(){const e=checkAllDependencies(),t=[...missingInstallableDeps(e.cli.filter(e=>"claude"!==e.name)),...missingInstallableDeps(e.sandbox)];"linux"!==process.platform||commandExists("rg")||t.push({name:"ripgrep",installed:!1,required:!0,description:"Fast code search tool",installCommand:"sudo apt install ripgrep"}),await installSystemDependencies(t),await installNpmDependency("claude","@anthropic-ai/claude-code@latest"),await installNpmDependency("codex","@openai/codex@latest");const n=checkCriticalDependencies();if(!n.ok)throw new Error(`Missing critical dependencies after installation: ${n.missing.join(", ")}`)}async function askWithDefault(e,t,n){const a=n?` (${n})`:"";return(await e.question(`${t}${a}: `)).trim()||n||""}async function askYesNo(e,t,n=!0){const a=n?"Y/n":"y/N",s=(await e.question(`${t} (${a}): `)).trim().toLowerCase();return s?"y"===s||"yes"===s:n}async function askChoice(e,t,n,a){for(console.log(t),n.forEach((e,t)=>{const n=e.value===a?" default":"";console.log(` ${t+1}. ${e.label}${n}`)});;){const t=(await e.question("Select: ")).trim();if(!t)return a;const s=Number.parseInt(t,10);if(!Number.isNaN(s)&&n[s-1])return n[s-1].value;const i=n.find(e=>e.value===t);if(i)return i.value;console.log(chalk.yellow("Invalid selection"))}}async function writeClaudeConfig(e,t,n){const a=path.join(machine.machine.claudeConfigDir,"settings.json");if(!t&&await pathExists(a)&&!await askYesNo(e,`Claude config already exists at ${a}. Overwrite`,!1))return void console.log(chalk.gray("Skipped Claude config"));const s=await askChoice(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"===s)return void console.log(chalk.gray("Skipped Claude config"));const i={};if("official"===s)i.ANTHROPIC_API_KEY=await askWithDefault(e,"Anthropic API key");else if("agentrix"===s)i.ANTHROPIC_BASE_URL=n,i.ANTHROPIC_AUTH_TOKEN=await askWithDefault(e,"Agentrix API key for Claude");else{const t=await askWithDefault(e,"Anthropic-compatible base URL");i.ANTHROPIC_BASE_URL=t,i.ANTHROPIC_AUTH_TOKEN=await askWithDefault(e,"Anthropic auth token")}const o=await askWithDefault(e,"Claude primary model",DEFAULT_CLAUDE_MODELS.primary),r=await askWithDefault(e,"Claude fast model",DEFAULT_CLAUDE_MODELS.fast),c=await askWithDefault(e,"Claude subagent model",o||DEFAULT_CLAUDE_MODELS.subagent);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 promises$1.mkdir(machine.machine.claudeConfigDir,{recursive:!0}),await promises$1.writeFile(a,JSON.stringify({env:i,model:o},null,2),"utf-8"),console.log(chalk.green(`✓ Wrote Claude config: ${a}`))}function tomlString$1(e){return JSON.stringify(e)}function buildCodexToml$1(e){const t=e.provider,n=[`model = ${tomlString$1(e.model)}`,`model_provider = ${tomlString$1(t)}`,"",`[model_providers.${t}]`,`name = ${tomlString$1("agentrix"===t?"Agentrix":"openai"===t?"Openai":"Custom")}`,`wire_api = ${tomlString$1(e.wireApi)}`];if(e.baseUrl){const a="agentrix"===t?e.baseUrl.replace(/\/+$/,"")+"/v1":e.baseUrl;n.push(`base_url = ${tomlString$1(a)}`)}return e.envKey&&n.push(`env_key = ${tomlString$1(e.envKey)}`),`${n.join("\n")}\n`}function writeDaemonEnvVars(e){const t=machine.machine.readOrInitSettings({sandbox:machine.machine.getSandboxSettings(),daemonEnv:{enabled:!1,variables:{}},daemonControl:{allowLanAccess:!1},allowDirectBash:!0}),n=t.daemonEnv||{enabled:!1,variables:{}},a={...n.variables||{},...e};machine.machine.writeSettings({...t,daemonEnv:{...n,enabled:!0,variables:a}});for(const[t,n]of Object.entries(e))process.env[t]=n}async function writeCodexConfig(e,t,n){const a=path.join(machine.machine.codexHomeDir,"config.toml");if(!t&&await pathExists(a)&&!await askYesNo(e,`Codex config already exists at ${a}. Overwrite`,!1))return void console.log(chalk.gray("Skipped Codex config"));const s=await askChoice(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"===s)return void console.log(chalk.gray("Skipped Codex config"));const i=await askWithDefault(e,"Codex model","gpt-5.5"),o=await askChoice(e,"Codex API wire format",[{value:"responses",label:"Responses API"},{value:"chat",label:"Chat Completions API"}],"agentrix"===s?"responses":"chat"),r={};let c,l;"agentrix"===s?(c=n,l="AGENTRIX_API_KEY",r[l]=await askWithDefault(e,"Agentrix API key for Codex")):"openai"===s?(l="OPENAI_API_KEY",r[l]=await askWithDefault(e,"OpenAI API key")):(c=await askWithDefault(e,"Custom OpenAI-compatible base URL"),l="CUSTOM_API_KEY",r[l]=await askWithDefault(e,"Custom API key")),await promises$1.mkdir(machine.machine.codexHomeDir,{recursive:!0}),await promises$1.writeFile(a,buildCodexToml$1({provider:s,baseUrl:c||void 0,envKey:l,model:i,wireApi:o}),"utf-8"),writeDaemonEnvVars(r),console.log(chalk.green(`✓ Wrote Codex config: ${a}`)),console.log(chalk.green(`✓ Wrote Codex env vars to ${machine.machine.getStatePaths().settingsFile}`))}async function configureLlm(e,t){const n=await fetchAgentrixApiBaseUrl(t),a=promises$3.createInterface({input:node_process.stdin,output:node_process.stdout});try{await writeClaudeConfig(a,e,n),await writeCodexConfig(a,e,n)}finally{a.close()}}async function startDaemonIfNeeded(){if(await isLatestDaemonRunning())console.log(chalk.green("✓ Daemon is already running"));else{console.log(chalk.blue("Starting Agentrix daemon...")),spawnAgentrixCLI(["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 checkIfDaemonRunningAndCleanupStaleState())return void console.log(chalk.green("✓ Daemon started successfully"));console.log(chalk.yellow("Daemon may still be starting. Run `agentrix status` to check."))}}async function runInitCommand(e={}){console.log(chalk.bold("\nAgentrix CLI initialization\n")),e.skipDeps||await ensureDependencies();const t=await authAndSetupMachineIfNeeded();await configureLlm(Boolean(e.force),t),e.skipDaemon||await startDaemonIfNeeded(),console.log(chalk.green("\n✓ Agentrix CLI initialization complete"))}function registerInitCommand(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 runInitCommand({skipDeps:e.skipDeps,skipDaemon:e.skipDaemon,force:e.force}),process.exit(0)}catch(e){console.error(chalk.red("Error:"),e instanceof Error?e.message:"Unknown error"),process.env.DEBUG&&console.error(e),process.exit(1)}})}const DEFAULT_LLM_BASE_URL="https://api.xmz.ai",DEFAULT_CODEX_MODEL="gpt-5.5",DEFAULT_CODEX_APPROVAL_POLICY="never",DEFAULT_CODEX_REASONING_EFFORT="high",DEFAULT_CLAUDE_MODEL="claude-sonnet-4-6",DEFAULT_CLAUDE_FAST_MODEL="claude-haiku-4-5",DEFAULT_GEMINI_IMAGE_MODEL="gemini-2.5-flash-image";function readEnv(e,t){const n=e[t]?.trim();return n||void 0}function resolveHomePath(e){return e.replace(/^~(?=\/|$)/,os.homedir())}function normalizeBaseUrl(e){const t=e.trim().replace(/\/+$/,"");try{const e=new URL(t);if("http:"!==e.protocol&&"https:"!==e.protocol)throw new Error("unsupported protocol")}catch{throw new Error("AGENTRIX_BASE_URL must be a valid http(s) URL")}return t}function toOpenAICompatibleBaseUrl(e){return`${e.replace(/\/+$/,"")}/v1`}async function readSecretFile(e){try{return(await promises$1.readFile(resolveHomePath(e),"utf-8")).replace(/[\r\n]/g,"")}catch{throw new Error(`AGENTRIX_API_KEY_FILE is set but is not readable: ${e}`)}}async function resolveApiKey(e){const t=readEnv(e,"AGENTRIX_API_KEY");if(t)return t;const n=readEnv(e,"AGENTRIX_API_KEY_FILE");if(!n)return;return(await readSecretFile(n)).trim()||void 0}async function resolveConfig(e){const t=resolveHomePath(readEnv(e,"AGENTRIX_HOME_DIR")||readEnv(e,"AGENTRIX_DIR")||path.join(os.homedir(),".agentrix")),n=resolveHomePath(readEnv(e,"AGENTRIX_CLAUDE_HOME")||path.join(os.homedir(),".claude")),a=resolveHomePath(readEnv(e,"AGENTRIX_CODEX_HOME")||path.join(os.homedir(),".codex")),s=resolveHomePath(readEnv(e,"AGENTRIX_GEMINI_HOME")||path.join(t,"config","gemini")),i=readEnv(e,"AGENTRIX_CLAUDE_MODEL")||"claude-sonnet-4-6";return{agentrixHomeDir:t,claudeConfigDir:n,codexHomeDir:a,geminiConfigDir:s,baseUrl:normalizeBaseUrl(readEnv(e,"AGENTRIX_BASE_URL")||"https://api.xmz.ai"),apiKey:await resolveApiKey(e),codexModel:readEnv(e,"AGENTRIX_CODEX_MODEL")||"gpt-5.5",claudeModel:i,claudeFastModel:readEnv(e,"AGENTRIX_CLAUDE_FAST_MODEL")||"claude-haiku-4-5",claudeSubagentModel:readEnv(e,"AGENTRIX_CLAUDE_SUBAGENT_MODEL")||i,geminiImageModel:readEnv(e,"AGENTRIX_GEMINI_IMAGE_MODEL")||"gemini-2.5-flash-image"}}function tomlString(e){return JSON.stringify(e)}function buildClaudeSettings(e,t){return`${JSON.stringify({env:{ANTHROPIC_BASE_URL:e.baseUrl,ANTHROPIC_AUTH_TOKEN:t,ANTHROPIC_MODEL:e.claudeModel,CLAUDE_CODE_SUBAGENT_MODEL:e.claudeSubagentModel,ANTHROPIC_SMALL_FAST_MODEL:e.claudeFastModel,ANTHROPIC_DEFAULT_OPUS_MODEL:"claude-opus-4-6",ANTHROPIC_DEFAULT_SONNET_MODEL:"claude-sonnet-4-6",ANTHROPIC_DEFAULT_HAIKU_MODEL:"claude-haiku-4-5"},model:e.claudeModel},null,2)}\n`}function buildCodexToml(e){return`${[`model = ${tomlString(e.codexModel)}`,'model_provider = "agentrix"',`approval_policy = ${tomlString("never")}`,`model_reasoning_effort = ${tomlString("high")}`,"","[model_providers.agentrix]",'name = "Agentrix"','wire_api = "responses"',`base_url = ${tomlString(toOpenAICompatibleBaseUrl(e.baseUrl))}`,'env_key = "AGENTRIX_API_KEY"'].join("\n")}\n`}function buildGeminiSettings(e,t){return`${JSON.stringify({connectionMode:"gemini-compatible",baseUrl:e.baseUrl,apiKey:t,imageModel:e.geminiImageModel},null,2)}\n`}function buildTargetFiles(e,t){return[{kind:"claude",path:path.join(e.claudeConfigDir,"settings.json"),content:buildClaudeSettings(e,t)},{kind:"codex",path:path.join(e.codexHomeDir,"config.toml"),content:buildCodexToml(e)},{kind:"gemini",path:path.join(e.geminiConfigDir,"settings.json"),content:buildGeminiSettings(e,t)}]}function configNeedsApiKey(e,t){return!(!t&&fs.existsSync(path.join(e.claudeConfigDir,"settings.json"))&&fs.existsSync(path.join(e.codexHomeDir,"config.toml"))&&fs.existsSync(path.join(e.geminiConfigDir,"settings.json")))}async function applyLlmAutoConfig(e={}){const t=e.env||process.env,n=!0===e.force,a=!0===e.dryRun,s=await resolveConfig(t);if(configNeedsApiKey(s,n)&&!s.apiKey)throw new Error("AGENTRIX_API_KEY is required to generate missing LLM config files");s.apiKey&&(t.AGENTRIX_API_KEY=s.apiKey);const i=buildTargetFiles(s,s.apiKey||""),o=[];for(const e of i)n||!fs.existsSync(e.path)?(o.push({kind:e.kind,path:e.path,action:"write"}),a||(await promises$1.mkdir(path.dirname(e.path),{recursive:!0}),await promises$1.writeFile(e.path,e.content,"utf-8"))):o.push({kind:e.kind,path:e.path,action:"skip"});return{dryRun:a,files:o,env:s.apiKey?{AGENTRIX_API_KEY:s.apiKey}:{}}}function formatAction(e,t){return"skip"===e?"skip":t?"would write":"write"}function registerLlmConfigCommand(e){e.command("llm-config apply","Generate Claude, Codex, and Gemini config from Agentrix environment variables",e=>e.option("source",{type:"string",choices:["env"],default:"env",describe:"Configuration source"}).option("force",{type:"boolean",default:!1,describe:"Overwrite existing LLM config files"}).option("dry-run",{type:"boolean",default:!1,describe:"Show planned writes without changing files"}).option("verbose",{type:"boolean",default:!1,describe:"Show detailed file actions"}),async e=>{try{const t=await applyLlmAutoConfig({force:!0===e.force,dryRun:!0===e.dryRun,env:process.env}),n=t.files.filter(e=>"write"===e.action).length,a=t.files.filter(e=>"skip"===e.action).length,s=t.dryRun?"LLM config dry run":"LLM config applied";if(console.log(chalk.green(`✓ ${s}: ${n} write(s), ${a} skipped`)),!0===e.verbose||t.dryRun)for(const e of t.files)console.log(`${formatAction(e.action,t.dryRun)} ${e.kind}: ${e.path}`);t.env.AGENTRIX_API_KEY&&console.log(chalk.gray("AGENTRIX_API_KEY prepared for this process.")),process.exit(0)}catch(e){console.error(chalk.red("Error:"),e instanceof Error?e.message:"Unknown error"),process.env.DEBUG&&console.error(e),process.exit(1)}})}async function runStorageCleanWorker(e){const{opCode:t,emit:n}=e,a=new Set(e.activeTaskIds??[]),s={releasedBytes:0,deletedCount:0,skippedCount:0,failedCount:0,dryRunCount:0};n({type:"started",opCode:t,itemCount:e.items.length,startedAt:(new Date).toISOString()});for(const i of e.items){n({type:"item-validating",opCode:t,relativePath:i.relativePath});const o=await planCleanItem(i.relativePath,a);if(o.releasable)if(n({type:"item-cleaning",opCode:t,relativePath:o.relativePath,method:o.method}),e.dryRun)s.dryRunCount+=1,n({type:"item-completed",opCode:t,relativePath:o.relativePath,releasedBytes:0,method:o.method});else try{const e=await executeCleanPlan(o);s.releasedBytes+=e,s.deletedCount+=1,n({type:"item-completed",opCode:t,relativePath:o.relativePath,releasedBytes:e,method:o.method})}catch(e){s.failedCount+=1,n({type:"item-failed",opCode:t,relativePath:o.relativePath,errorCode:"delete_failed",message:e instanceof Error?e.message:"Failed to clean item"})}else s.skippedCount+=1,n({type:"item-skipped",opCode:t,relativePath:o.relativePath,reasonCode:o.reasonCode,message:o.message})}return n({type:"completed",opCode:t,summary:{...s},result:{summary:{...s}},completedAt:(new Date).toISOString()}),s}const CATEGORY_LABELS={workspaces:"Task workspaces",logs:"Logs",tmp:"Temporary files",repos:"Repository store",runtime:"Runtime assets",monitor:"Monitor data",config:"Configuration",other:"Other"},DAY_MS=864e5,TASK_LOG_PATTERN=/^task-(.+)\.log(?:\.\d+)?(?:\.gz)?$/;function category(e){return{kind:e,label:CATEGORY_LABELS[e],bytes:0,reclaimableBytes:0,itemCount:0}}function taskTimestamp(e){const t=e.state?.initializedAt?Date.parse(e.state.initializedAt):Number.NaN;return Number.isFinite(t)?t:fs.statSync(e.taskDir).mtimeMs}function parseTaskIdFromLogName(e){return TASK_LOG_PATTERN.exec(e)?.[1]??null}function completeCategory(e){return{kind:e.kind,label:e.label,bytes:e.bytes,reclaimableBytes:e.reclaimableBytes,itemCount:e.itemCount}}async function addItem(e,t,n,a,s){n.bytes+=s.bytes,n.itemCount+=1,s.reclaimable&&(n.reclaimableBytes+=s.bytes),a.push(s),t({type:"item",opCode:e,item:s})}async function scanWorkspaces(e,t,n,a,s){const i=category("workspaces");t({type:"category-started",opCode:e,kind:i.kind,label:i.label});const o=Date.now()-s*DAY_MS;for(const s of listWorkspaceTasks()){const r=n.has(s.taskId),c=isDirectUserDirectoryWorkspace(s.state),l=!r&&!c&&taskTimestamp(s)<o,d=r?{reasonCode:"active_task",reason:"Task is currently running"}:c?{reasonCode:"user_directory",reason:"Task uses a user-owned directory"}:{},p=fs.existsSync(s.projectDir),u=fs.existsSync(s.dataDir),m=p?await getPathSize(s.projectDir):0,h=u?await getPathSize(s.dataDir):0;if(p){const n=r||c?null:await getRegisteredWorktreeMainRepo(s.projectDir);await addItem(e,t,i,a,makeStorageItem({id:`workspace:${s.userId}:${s.taskId}:project`,kind:"workspace-project",label:s.taskId,absolutePath:s.projectDir,bytes:m,reclaimable:!r&&!c,defaultSelected:l,deleteMode:r||c?"protected":n?"remove-worktree":"rm-stale-directory",childrenSummary:[{label:"project",bytes:m},...u?[{label:"data",bytes:h}]:[]],...d}))}u&&await addItem(e,t,i,a,makeStorageItem({id:`workspace:${s.userId}:${s.taskId}:data`,kind:"workspace-data",label:`${s.taskId} data`,absolutePath:s.dataDir,bytes:h,reclaimable:!r&&!c,defaultSelected:l,deleteMode:r||c?"protected":"rm",childrenSummary:[{label:"data",bytes:h}],...d}))}const r=completeCategory(i);return t({type:"category-completed",opCode:e,category:r}),r}async function scanLogs(e,t,n,a,s){const i=category("logs");t({type:"category-started",opCode:e,kind:i.kind,label:i.label});const o=path.join(machine.machine.agentrixHomeDir,"logs");if(!fs.existsSync(o)){const n=completeCategory(i);return t({type:"category-completed",opCode:e,category:n}),n}const r=new Map(listWorkspaceTasks().map(e=>[e.taskId,e])),c=Date.now()-s*DAY_MS;for(const s of fs.readdirSync(o,{withFileTypes:!0})){const l=path.join(o,s.name);try{const o=await getPathSize(l),d=parseTaskIdFromLogName(s.name),p=d?r.get(d):void 0,u=!!d&&n.has(d),m=p?taskTimestamp(p):fs.statSync(l).mtimeMs,h=Boolean(d)&&m<c;await addItem(e,t,i,a,makeStorageItem({id:`logs:${toProtocolRelative(machine.machine.agentrixHomeDir,l)}`,kind:"logs",label:s.name,absolutePath:l,bytes:o,reclaimable:!u,defaultSelected:!u&&h,deleteMode:u?"protected":"rm",reasonCode:u?"active_task":void 0,reason:u?"Task is currently running":void 0}))}catch(n){t({type:"item-error",opCode:e,kind:"logs",pathDisplay:toProtocolRelative(machine.machine.agentrixHomeDir,l),errorCode:"stat_failed",message:n instanceof Error?n.message:"Failed to scan item"})}}const l=completeCategory(i);return t({type:"category-completed",opCode:e,category:l}),l}async function scanRepos(e,t,n){const a=category("repos");t({type:"category-started",opCode:e,kind:a.kind,label:a.label});const s=path.join(machine.machine.agentrixHomeDir,"repos");if(!fs.existsSync(s)){const n=completeCategory(a);return t({type:"category-completed",opCode:e,category:n}),n}for(const i of fs.readdirSync(s,{withFileTypes:!0})){if(!i.isDirectory())continue;const o=path.join(s,i.name);for(const s of fs.readdirSync(o,{withFileTypes:!0})){if(!s.isDirectory())continue;const i=path.join(o,s.name);for(const o of fs.readdirSync(i,{withFileTypes:!0})){if(!o.isDirectory())continue;const r=path.join(i,o.name);try{const i=await getPathSize(r);await addItem(e,t,a,n,makeStorageItem({id:`repos:${toProtocolRelative(machine.machine.agentrixHomeDir,r)}`,kind:"repos",label:`${s.name}/${o.name}`,absolutePath:r,bytes:i,reclaimable:!0,defaultSelected:!1,deleteMode:"rm"}))}catch(n){t({type:"item-error",opCode:e,kind:"repos",pathDisplay:toProtocolRelative(machine.machine.agentrixHomeDir,r),errorCode:"stat_failed",message:n instanceof Error?n.message:"Failed to scan item"})}}}}const i=completeCategory(a);return t({type:"category-completed",opCode:e,category:i}),i}async function scanTopLevelDirectory(e,t,n,a,s,i){const o=category(a);t({type:"category-started",opCode:e,kind:o.kind,label:o.label});const r=path.join(machine.machine.agentrixHomeDir,s);if(!fs.existsSync(r)){const n=completeCategory(o);return t({type:"category-completed",opCode:e,category:n}),n}for(const s of fs.readdirSync(r,{withFileTypes:!0})){const c=path.join(r,s.name);try{const r=await getPathSize(c);await addItem(e,t,o,n,makeStorageItem({id:`${a}:${toProtocolRelative(machine.machine.agentrixHomeDir,c)}`,kind:a,label:s.name,absolutePath:c,bytes:r,reclaimable:i,deleteMode:i?"rm":"protected",reasonCode:i?void 0:`${a}_protected`,reason:i?void 0:"This area is shown for visibility only"}))}catch(n){t({type:"item-error",opCode:e,kind:a,pathDisplay:toProtocolRelative(machine.machine.agentrixHomeDir,c),errorCode:"stat_failed",message:n instanceof Error?n.message:"Failed to scan item"})}}const c=completeCategory(o);return t({type:"category-completed",opCode:e,category:c}),c}async function runStorageScanWorker(e){const{opCode:t,emit:n}=e,a=new Set(e.activeTaskIds??[]),s=machine.machine.getStorageManagementSettings(),i=[],o=[];n({type:"started",opCode:t,root:machine.machine.agentrixHomeDir,startedAt:(new Date).toISOString()}),o.push(await scanWorkspaces(t,n,a,i,s.autoSelectTaskOlderThanDays)),o.push(await scanLogs(t,n,a,i,s.autoSelectTaskOlderThanDays)),o.push(await scanTopLevelDirectory(t,n,i,"tmp","tmp",!0)),o.push(await scanRepos(t,n,i)),o.push(await scanTopLevelDirectory(t,n,i,"runtime","node-runtime",!1)),o.push(await scanTopLevelDirectory(t,n,i,"monitor","monitor",!1));const r=o.reduce((e,t)=>e+t.bytes,0),c=o.reduce((e,t)=>e+t.reclaimableBytes,0),l={scanId:`scan-${t}`,root:machine.machine.agentrixHomeDir,generatedAt:(new Date).toISOString(),totalBytes:r,reclaimableBytes:c,categories:o,items:i.sort((e,t)=>Number(t.reclaimable)-Number(e.reclaimable)||t.bytes-e.bytes)};return n({type:"completed",opCode:t,result:l,summary:{totalBytes:r,reclaimableBytes:c,itemCount:i.length,skippedCount:i.filter(e=>!e.reclaimable).length},completedAt:l.generatedAt}),l}async function readWorkerRequest(e){if(!e)return{};const t=await promises$1.readFile(e,"utf8");return JSON.parse(t)}function writeJsonLine(e){process.stdout.write(`${JSON.stringify(e)}\n`)}function registerStorageManagementCommands(e){e.command("storage-scan",!1,e=>e.option("op-code",{type:"string",demandOption:!0}).option("request-file",{type:"string"}),async e=>{const t=e["op-code"];try{const n=await readWorkerRequest(e["request-file"]);await runStorageScanWorker({opCode:t,activeTaskIds:n.activeTaskIds,emit:writeJsonLine}),process.exitCode=0}catch(e){writeJsonLine({type:"failed",opCode:t,errorCode:"operation_failed",message:e instanceof Error?e.message:"Storage scan failed"}),process.exitCode=1}}),e.command("storage-clean",!1,e=>e.option("op-code",{type:"string",demandOption:!0}).option("request-file",{type:"string",demandOption:!0}),async e=>{const t=e["op-code"];try{const n=await readWorkerRequest(e["request-file"]);await runStorageCleanWorker({opCode:t,activeTaskIds:n.activeTaskIds,items:n.items??[],dryRun:!0===n.dryRun,emit:writeJsonLine}),process.exitCode=0}catch(e){writeJsonLine({type:"failed",opCode:t,errorCode:"operation_failed",message:e instanceof Error?e.message:"Storage clean failed"}),process.exitCode=1}})}async function readRecentDaemonLog(){const e=path.join(machine.machine.getStatePaths().logsDir,"daemon.log");try{return(await promises$1.readFile(e,"utf8")).trim().split("\n").filter(Boolean).slice(-12).join("\n")||null}catch{return null}}async function reportDaemonStartupFailure(){const e=await readRecentDaemonLog();if(console.log(chalk.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(chalk.yellow(t)):(console.log(chalk.gray("Recent daemon log:")),console.log(e))}const cli=yargs(helpers.hideBin(process.argv)).scriptName("agentrix").version(machine.packageJson.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");function isProcessRunning(e){try{return process.kill(e,0),!0}catch{return!1}}async function waitForDaemonRestart(e,t,n=15e3){const a=Date.now()+n;let s=!e;for(;Date.now()<a;){if(e&&!s){if(isProcessRunning(e.pid)){await new Promise(e=>setTimeout(e,100));continue}s=!0}const n=await machine.machine.readDaemonState();if(n&&n.pid!==e?.pid&&n.cliVersion===t&&isProcessRunning(n.pid))return!0;await new Promise(e=>setTimeout(e,100))}return!1}async function handleRestartCommand(e){let t;if("string"==typeof e["report-json"])try{t=JSON.parse(e["report-json"])}catch{console.error(chalk.red("Error:"),"Invalid restart report JSON"),process.exit(1)}const n="number"==typeof e["old-pid"]?e["old-pid"]:void 0,a="string"==typeof e["expected-version"]?e["expected-version"]:void 0,s=await runDaemonRestart({oldPid:n,expectedCliVersion:a,reason:"string"==typeof e.reason?e.reason:void 0,report:t,stopExistingDaemon:void 0===n});s.success||(console.error(chalk.red("Error:"),s.error??"Daemon restart failed"),process.exit(1))}machine.machine.getStatePaths,cli.command("upgrade","Upgrade CLI to the latest version",{},async e=>{console.log(chalk.dim(`Current version: ${machine.packageJson.version}`));const t=await checkIfDaemonRunningAndCleanupStaleState(),n=t?await machine.machine.readDaemonState():null;await performAutoUpgrade()||process.exit(1);try{const e=await machine.machine.readCredentials();e&&(console.log(chalk.dim("Checking agent updates...")),await checkAgentUpdates(e))}catch{}if(t){console.log(chalk.blue("Preparing daemon restart..."));const e=await prepareDaemonGracefulRestart("CLI upgrade installed");let t=!0;const a=getInstalledCliVersion();e.error?(console.log(chalk.yellow(`⚠️ Could not prepare graceful restart: ${e.error}`)),console.log(chalk.blue("Restarting daemon directly...")),await stopDaemon(),spawnAgentrixCLI(["daemon"],{detached:!0,stdio:"ignore",env:process.env}).unref()):"pending_restart"===e.state&&(console.log(chalk.yellow(`Daemon restart deferred until ${e.activeSessions??0} active session(s) finish.`)),t=!1);let s=!1;t&&(s=await waitForDaemonRestart(n,a),s?console.log(chalk.green("✓ Daemon restarted successfully")):console.log(chalk.yellow("⚠️ Daemon may still be starting. Run 'agentrix status' to check.")))}const a=getInstalledCliVersion();"0.0.0"!==a?console.log(chalk.green(`\n✓ Now running version: ${a}`)):console.log(chalk.dim("\nRun 'agentrix --version' to see the new version")),process.exit(0)}),cli.command("doctor","System diagnostics & troubleshooting",{},async e=>{await runDoctorCommand(),process.exit(0)}),cli.command("logout","Logout from Agentrix",{},async e=>{try{await handleAuthLogout()}catch(e){console.error(chalk.red("Error:"),e instanceof Error?e.message:"Unknown error"),process.env.DEBUG&&console.error(e),process.exit(1)}process.exit(0)}),cli.command("stop","Stop the daemon",{},async e=>{await stopDaemon(),process.exit(0)}),cli.command("restart","Restart the daemon",e=>e.option("old-pid",{type:"number",describe:"PID of the daemon that must exit before replacement starts"}).option("expected-version",{type:"string",describe:"CLI version expected from the replacement daemon"}).option("reason",{type:"string",describe:"Restart reason"}),async e=>{await handleRestartCommand(e),console.log(chalk.green("✓ Daemon restarted successfully")),process.exit(0)}),cli.command("status","Show daemon and authentication status",{},async e=>{await runDoctorCommand("daemon"),console.log(""),await handleAuthStatus(),process.exit(0)}),cli.command("ls","List active sessions",{},async e=>{try{const e=await listDaemonSessions();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)}),cli.command("killall","Clean up all runaway agentrix processes",{},async()=>{const e=await killRunawayAgentrixProcesses();console.log(`Cleaned up ${e.killed} runaway processes`),e.errors.length>0&&console.log("Errors:",e.errors),process.exit(0)}),registerGitServerCommands(cli),registerInitCommand(cli),registerLlmConfigCommand(cli),registerStorageManagementCommands(cli),cli.command("kill <sessionId>","Stop a specific session",e=>e.positional("sessionId",{type:"string",describe:"Session ID to stop"}),async e=>{try{const t=await stopDaemonSession(e.sessionId);console.log(t?chalk.green("✓ Session stopped"):chalk.red("Failed to stop session"))}catch(e){console.log(chalk.red("No daemon running"))}process.exit(0)}),cli.command("daemon",!1,{},async e=>{try{await authAndSetupMachineIfNeeded()}catch(e){console.error(chalk.red("Error:"),e instanceof Error?e.message:"Authentication failed"),process.env.DEBUG&&console.error(e),process.exit(1)}await startDaemon(),process.exit(0)}),cli.command("worker",!1,e=>e.option("type",{type:"string",choices:workerTypes,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=workerRegistry[t];if(!n)throw new Error(`Unsupported worker type: ${String(e.type)}`);const a=e["started-by"],s=e["user-id"],i=e["task-id"],o=e["idle-timeout"];machine.initializeLogger({type:"worker",taskId:i});const r=await authAndSetupMachineIfNeeded();await n.run({credentials:r,startedBy:a,userId:s,taskId:i,idleTimeoutSecond:o})}catch(e){console.error(chalk.red("Error:"),e instanceof Error?e.message:"Unknown error"),process.env.DEBUG&&console.error(e),process.exit(1)}}),cli.command("restart-daemon",!1,e=>e.option("old-pid",{type:"number",describe:"PID of the daemon that must exit before replacement starts"}).option("expected-version",{type:"string",describe:"CLI version expected from the replacement daemon"}).option("reason",{type:"string",describe:"Restart reason"}).option("report-json",{type:"string",describe:"Machine-control restart report context"}),async e=>{await handleRestartCommand(e),process.exit(0)}),cli.command("start","Start daemon (if not running) and show status",{},async e=>{try{await authAndSetupMachineIfNeeded()}catch(e){console.error(chalk.red("Error:"),e instanceof Error?e.message:"Authentication failed"),process.env.DEBUG&&console.error(e),process.exit(1)}const t=checkCriticalDependencies();if(t.ok||(console.log(chalk.bold.red("\n⚠️ Missing Critical Dependencies")),console.log(chalk.yellow(`Cannot start daemon. Missing: ${t.missing.join(", ")}`)),console.log(chalk.blue('\nRun "agentrix doctor" for detailed dependency information and installation instructions.')),process.exit(1)),!await isLatestDaemonRunning()){console.log("Starting Agentrix background service..."),spawnAgentrixCLI(["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 checkIfDaemonRunningAndCleanupStaleState()){e=!0;break}e?(await new Promise(e=>setTimeout(e,1200)),await checkIfDaemonRunningAndCleanupStaleState()?console.log(chalk.green("✓ Daemon started successfully")):await reportDaemonStartupFailure()):console.log(chalk.yellow("⚠️ Daemon may still be starting..."))}await runDoctorCommand("daemon"),process.exit(0)}),cli.demandCommand(1,"Please specify a command. Use --help to see available commands.").parse();