@agenthippo-ai/agenthippo 1.110.19 → 1.110.20

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.
Files changed (2) hide show
  1. package/out/cli/index.js +120 -119
  2. package/package.json +10 -6
package/out/cli/index.js CHANGED
@@ -1,7 +1,7 @@
1
1
  /*! Copyright (c) 2026 AgentHippo.ai. All rights reserved. Proprietary; see LICENSE. */
2
- "use strict";var Qw=Object.create;var Np=Object.defineProperty;var Zw=Object.getOwnPropertyDescriptor;var eA=Object.getOwnPropertyNames;var tA=Object.getPrototypeOf,nA=Object.prototype.hasOwnProperty;var S=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports);var rA=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of eA(e))!nA.call(t,s)&&s!==n&&Np(t,s,{get:()=>e[s],enumerable:!(r=Zw(e,s))||r.enumerable});return t};var wn=(t,e,n)=>(n=t!=null?Qw(tA(t)):{},rA(e||!t||!t.__esModule?Np(n,"default",{value:t,enumerable:!0}):n,t));var Ke=S(ve=>{"use strict";Object.defineProperty(ve,"__esModule",{value:!0});ve.SETTINGS_DISPLAY_PREFIX=ve.SETTINGS_KEY_PREFIX=ve.AGENTIDE_DEPS_PACKAGE_NAME=ve.AGENTIDE_DEPS_DIR_NAME=ve.AGENTIDE_CLI_NAME=ve.AGENTIDE_DIR_NAME=ve.AGENTIDE_EXTENSION_NAME=ve.AGENTIDE_BRAND_NAME=void 0;ve.toSettingsDisplayKey=Rp;ve.describeSettingKey=sA;ve.applyBrandingTokens=Cp;ve.brandify=iA;ve.AGENTIDE_BRAND_NAME="Agent Hippo";ve.AGENTIDE_EXTENSION_NAME=`${ve.AGENTIDE_BRAND_NAME} Extension`;ve.AGENTIDE_DIR_NAME=".agent-hippo";ve.AGENTIDE_CLI_NAME="agenthippo";ve.AGENTIDE_DEPS_DIR_NAME=`.${ve.AGENTIDE_CLI_NAME}-deps`;ve.AGENTIDE_DEPS_PACKAGE_NAME=`${ve.AGENTIDE_CLI_NAME}-deps`;ve.SETTINGS_KEY_PREFIX="agentide.";ve.SETTINGS_DISPLAY_PREFIX="agenthippoai.";function Rp(t){return t.startsWith(ve.SETTINGS_KEY_PREFIX)?ve.SETTINGS_DISPLAY_PREFIX+t.slice(ve.SETTINGS_KEY_PREFIX.length):t}function sA(t){let e=Rp(t);return e===t?t:`${t} (shown in Settings as ${e})`}function Cp(t){return t.replace(/\{\{AGENT_BRAND\}\}|\{\{AGENTIDE_BRAND\}\}/g,ve.AGENTIDE_BRAND_NAME).replace(/\{\{BRAND_FOLDER\}\}/g,ve.AGENTIDE_DIR_NAME)}function iA(t){return Cp(t).replace(/\bAgentIDE\b/g,ve.AGENTIDE_BRAND_NAME)}});var Un=S(x=>{"use strict";var oA=x&&x.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,s)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),aA=x&&x.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),Il=x&&x.__importStar||(function(){var t=function(e){return t=Object.getOwnPropertyNames||function(n){var r=[];for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(r[r.length]=s);return r},t(e)};return function(e){if(e&&e.__esModule)return e;var n={};if(e!=null)for(var r=t(e),s=0;s<r.length;s++)r[s]!=="default"&&oA(n,e,r[s]);return aA(n,e),n}})();Object.defineProperty(x,"__esModule",{value:!0});x.AGENT_CONSTANTS=void 0;x.getAgentideHome=ca;x.getUserAgentsDir=kp;x.getUserSkillsDir=$p;x.getUserSkillDir=dA;x.getUserMcpDir=Dp;x.getUserMcpServerDir=fA;x.getUserAgentRoot=Pl;x.getUserAgentVersionDir=pA;x.getUserAgentCurrentPath=gA;x.getAgentideDir=Nl;x.getAgentsDir=Lp;x.getAgentRoot=Os;x.resolveAgentRuntimePaths=Mp;x.resolveRuntimePaths=hA;x.userScopedEngineHome=mA;x.engineHomeUserKey=Gp;x.userScopedEngineHomeFromKey=Up;x.isDefaultAgent=EA;x.getAgentManifestPath=_A;x.getAgentAgentsMdPath=yA;x.getAgentContextPath=wA;x.getAgentSkillsDir=AA;x.getAgentRulesDir=SA;x.getAgentMcpDir=TA;x.getSessionsDir=bA;x.parseAgentIdFromPath=vA;x.isValidPackName=OA;x.normalizePackName=IA;x.getPackNameError=PA;x.packNameToTitle=Rl;x.stripModelProviderPrefix=aa;x.generateDefaultAgentYaml=NA;x.generateAgentYaml=RA;x.generateAgentsMd=CA;var Re=Il(require("path")),cA=Il(require("os")),lA=Il(require("crypto")),uA=Ke();x.AGENT_CONSTANTS={DEFAULT_AGENT_ID:"default",AGENTIDE_DIR_NAME:uA.AGENTIDE_DIR_NAME,AGENTS_DIR:"agents",RULES_DIR:"rules",SKILLS_DIR:"skills",MCP_DIR:"mcp",SESSIONS_DIR:"sessions",MANIFEST_FILE:"agent.yaml",AGENTS_MD:"AGENTS.md",GHOST_TEXT_FILE:"GHOST_TEXT.md",TERMINAL_ASSIST_FILE:"TERMINAL_ASSIST.md",CLAUDE_MD:"CLAUDE.md",CONTEXT_MD:"context.md",SOURCE_FILE:".agentide-source.json",CURRENT_VERSION_FILE:"current.txt"};function ca(){return process.env.AGENTHIPPO_HOME||Re.join(cA.homedir(),x.AGENT_CONSTANTS.AGENTIDE_DIR_NAME)}function kp(){return process.env.AGENTIDE_USER_AGENTS_DIR||Re.join(ca(),x.AGENT_CONSTANTS.AGENTS_DIR)}function $p(){return Re.join(ca(),x.AGENT_CONSTANTS.SKILLS_DIR)}function dA(t){return Re.join($p(),t)}function Dp(){return Re.join(ca(),x.AGENT_CONSTANTS.MCP_DIR)}function fA(t){return Re.join(Dp(),t)}function Pl(t){return Re.join(kp(),t)}function pA(t,e){return Re.join(Pl(t),e)}function gA(t){return Re.join(Pl(t),x.AGENT_CONSTANTS.CURRENT_VERSION_FILE)}function Nl(t){return Re.join(t,x.AGENT_CONSTANTS.AGENTIDE_DIR_NAME)}function Lp(t){return Re.join(Nl(t),x.AGENT_CONSTANTS.AGENTS_DIR)}function Os(t,e){return Re.join(Lp(t),e)}function Mp(t,e,n,r="0.0.0"){let s=Os(t,n);return{agentId:n,agentVersion:r,agentRoot:s,rulesDir:Re.join(s,x.AGENT_CONSTANTS.RULES_DIR),skillsDir:Re.join(s,x.AGENT_CONSTANTS.SKILLS_DIR),mcpDir:Re.join(s,x.AGENT_CONSTANTS.MCP_DIR),codexDerivedDir:Re.join(t,".codex"),claudeDerivedDir:Re.join(t,".claude"),codexHome:Re.join(e,x.AGENT_CONSTANTS.AGENTS_DIR,n,"codex"),claudeConfigDir:Re.join(e,x.AGENT_CONSTANTS.AGENTS_DIR,n,"claude")}}function hA(t,e,n,r){let s=n??x.AGENT_CONSTANTS.DEFAULT_AGENT_ID;return Mp(t,e,s,r)}function mA(t,e){return Up(t,Gp(e))}function Gp(t){let e=t?.trim();if(e)return lA.createHash("sha256").update(e).digest("hex").slice(0,16)}function Up(t,e){return!e||!/^[0-9a-f]{16}$/.test(e)?t:Re.join(t,"users",e)}function EA(t){return t===x.AGENT_CONSTANTS.DEFAULT_AGENT_ID}function _A(t,e){return Re.join(Os(t,e),x.AGENT_CONSTANTS.MANIFEST_FILE)}function yA(t,e){return Re.join(Os(t,e),x.AGENT_CONSTANTS.AGENTS_MD)}function wA(t,e){return Re.join(Os(t,e),x.AGENT_CONSTANTS.CONTEXT_MD)}function AA(t,e){return Re.join(Os(t,e),x.AGENT_CONSTANTS.SKILLS_DIR)}function SA(t,e){return Re.join(Os(t,e),x.AGENT_CONSTANTS.RULES_DIR)}function TA(t,e){return Re.join(Os(t,e),x.AGENT_CONSTANTS.MCP_DIR)}function bA(t){return Re.join(Nl(t),x.AGENT_CONSTANTS.SESSIONS_DIR)}function vA(t){let e=t.split(Re.sep),n=e.lastIndexOf(x.AGENT_CONSTANTS.AGENTS_DIR);if(n!==-1&&e.length>n+1)return e[n+1]}var Hp=/[/\\:*?"<>|]/;function OA(t){return!(!t||t.trim().length===0||Hp.test(t)||t.startsWith("."))}function IA(t){return t.trim().toLowerCase().replace(/[\s_]+/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,"")}function PA(t){if(!t||t.trim().length===0)return"Pack name is required";if(Hp.test(t))return'Pack name cannot contain path separators or special characters (/ \\ : * ? " < > |)';if(t.startsWith("."))return"Pack name cannot start with a dot"}function Rl(t){return t.split(/[-_\s]+/).map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(" ")}function aa(t){let e=t.match(/^[a-z0-9-]+::/i);return e?t.slice(e[0].length):t}function NA(t={}){let{engine:e="claude",model:n,includeHeaderComments:r=!0,includeModelHintComment:s=!1}=t,i=n?aa(n):void 0;return[...r?["# Agent Hippo Pack Configuration","# This is the default agent pack for agenthippo.","# Edit this file to customize the agent's behavior.",""]:[],"apiVersion: agenthippo.ai/v1","kind: Agent","metadata:"," name: default",' version: "1.0.0"',' description: "agent hippo"',"spec:"," # Preferred engine (claude or codex)",` engine: ${e}`,...i?[` model: ${i}`]:s?[" # Model to use (optional - uses engine default if not specified)"," # model: claude-sonnet-4-20250514"]:[]," permissions:"," # File access scope for this agent:"," # - read-only: no file writes"," # - workspace-write: writes limited to workspace folders"," # - full: full filesystem access (yolo)"," fileAccess: full"," visibility: internal",""].join(`
3
- `)}function RA(t,e={}){let{description:n=`A specialized agent for ${Rl(t).toLowerCase()} tasks`,engine:r="claude",author:s=process.env.USER||"unknown"}=e,i=e.model??(r==="claude"?"claude-sonnet-4":"codex"),o=aa(i),a=e.cheapModel?aa(e.cheapModel):void 0;return[`# ${t} Agent Manifest`,"apiVersion: agenthippo.ai/v1","kind: Agent","metadata:",` name: ${t}`," version: 0.1.0",` author: ${s}`,` description: ${n}`,"","spec:",` engine: ${r}`,` model: ${o}`,...a?[` cheapModel: ${a}`]:[],""," skills: []"," # Uncomment to add skills:"," # - path: ./skills/my-skill",""," # Optional: seed pack data into workspace on first use (target missing/empty)"," # Remove this block if your pack has no data files."," # data:"," # sourcePath: ./data",` # workspacePath: ${x.AGENT_CONSTANTS.AGENTIDE_DIR_NAME}/data/${t}`,""," permissions:"," # File access scope for this pack:"," # - read-only: no file writes"," # - workspace-write: writes limited to workspace folders"," # - full: full filesystem access (yolo)"," fileAccess: full",""," visibility: internal",""].join(`
4
- `)}function CA(t,e={}){let n=Rl(t),r=e.description||`A specialized agent for ${n.toLowerCase()} tasks.`;return`# ${n} Agent
2
+ "use strict";var nA=Object.create;var Rp=Object.defineProperty;var rA=Object.getOwnPropertyDescriptor;var sA=Object.getOwnPropertyNames;var iA=Object.getPrototypeOf,oA=Object.prototype.hasOwnProperty;var S=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports);var aA=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of sA(e))!oA.call(t,s)&&s!==n&&Rp(t,s,{get:()=>e[s],enumerable:!(r=rA(e,s))||r.enumerable});return t};var wn=(t,e,n)=>(n=t!=null?nA(iA(t)):{},aA(e||!t||!t.__esModule?Rp(n,"default",{value:t,enumerable:!0}):n,t));var Ke=S(ve=>{"use strict";Object.defineProperty(ve,"__esModule",{value:!0});ve.SETTINGS_DISPLAY_PREFIX=ve.SETTINGS_KEY_PREFIX=ve.AGENTIDE_DEPS_PACKAGE_NAME=ve.AGENTIDE_DEPS_DIR_NAME=ve.AGENTIDE_CLI_NAME=ve.AGENTIDE_DIR_NAME=ve.AGENTIDE_EXTENSION_NAME=ve.AGENTIDE_BRAND_NAME=void 0;ve.toSettingsDisplayKey=Cp;ve.describeSettingKey=cA;ve.applyBrandingTokens=kp;ve.brandify=lA;ve.AGENTIDE_BRAND_NAME="Agent Hippo";ve.AGENTIDE_EXTENSION_NAME=`${ve.AGENTIDE_BRAND_NAME} Extension`;ve.AGENTIDE_DIR_NAME=".agent-hippo";ve.AGENTIDE_CLI_NAME="agenthippo";ve.AGENTIDE_DEPS_DIR_NAME=`.${ve.AGENTIDE_CLI_NAME}-deps`;ve.AGENTIDE_DEPS_PACKAGE_NAME=`${ve.AGENTIDE_CLI_NAME}-deps`;ve.SETTINGS_KEY_PREFIX="agentide.";ve.SETTINGS_DISPLAY_PREFIX="agenthippoai.";function Cp(t){return t.startsWith(ve.SETTINGS_KEY_PREFIX)?ve.SETTINGS_DISPLAY_PREFIX+t.slice(ve.SETTINGS_KEY_PREFIX.length):t}function cA(t){let e=Cp(t);return e===t?t:`${t} (shown in Settings as ${e})`}function kp(t){return t.replace(/\{\{AGENT_BRAND\}\}|\{\{AGENTIDE_BRAND\}\}/g,ve.AGENTIDE_BRAND_NAME).replace(/\{\{BRAND_FOLDER\}\}/g,ve.AGENTIDE_DIR_NAME)}function lA(t){return kp(t).replace(/\bAgentIDE\b/g,ve.AGENTIDE_BRAND_NAME)}});var Un=S(x=>{"use strict";var uA=x&&x.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,s)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),dA=x&&x.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),Pl=x&&x.__importStar||(function(){var t=function(e){return t=Object.getOwnPropertyNames||function(n){var r=[];for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(r[r.length]=s);return r},t(e)};return function(e){if(e&&e.__esModule)return e;var n={};if(e!=null)for(var r=t(e),s=0;s<r.length;s++)r[s]!=="default"&&uA(n,e,r[s]);return dA(n,e),n}})();Object.defineProperty(x,"__esModule",{value:!0});x.AGENT_CONSTANTS=void 0;x.getAgentideHome=la;x.getUserAgentsDir=$p;x.getUserSkillsDir=Dp;x.getUserSkillDir=hA;x.getUserMcpDir=Lp;x.getUserMcpServerDir=mA;x.getUserAgentRoot=Nl;x.getUserAgentVersionDir=EA;x.getUserAgentCurrentPath=_A;x.getAgentideDir=Rl;x.getAgentsDir=Mp;x.getAgentRoot=Os;x.resolveAgentRuntimePaths=Gp;x.resolveRuntimePaths=yA;x.userScopedEngineHome=wA;x.engineHomeUserKey=Up;x.userScopedEngineHomeFromKey=Hp;x.isDefaultAgent=AA;x.getAgentManifestPath=SA;x.getAgentAgentsMdPath=TA;x.getAgentContextPath=bA;x.getAgentSkillsDir=vA;x.getAgentRulesDir=OA;x.getAgentMcpDir=IA;x.getSessionsDir=PA;x.parseAgentIdFromPath=NA;x.isValidPackName=RA;x.normalizePackName=CA;x.getPackNameError=kA;x.packNameToTitle=Cl;x.stripModelProviderPrefix=ca;x.generateDefaultAgentYaml=$A;x.generateAgentYaml=DA;x.generateAgentsMd=LA;var Re=Pl(require("path")),fA=Pl(require("os")),pA=Pl(require("crypto")),gA=Ke();x.AGENT_CONSTANTS={DEFAULT_AGENT_ID:"default",AGENTIDE_DIR_NAME:gA.AGENTIDE_DIR_NAME,AGENTS_DIR:"agents",RULES_DIR:"rules",SKILLS_DIR:"skills",MCP_DIR:"mcp",SESSIONS_DIR:"sessions",MANIFEST_FILE:"agent.yaml",AGENTS_MD:"AGENTS.md",GHOST_TEXT_FILE:"GHOST_TEXT.md",TERMINAL_ASSIST_FILE:"TERMINAL_ASSIST.md",CLAUDE_MD:"CLAUDE.md",CONTEXT_MD:"context.md",SOURCE_FILE:".agentide-source.json",CURRENT_VERSION_FILE:"current.txt"};function la(){return process.env.AGENTHIPPO_HOME||Re.join(fA.homedir(),x.AGENT_CONSTANTS.AGENTIDE_DIR_NAME)}function $p(){return process.env.AGENTIDE_USER_AGENTS_DIR||Re.join(la(),x.AGENT_CONSTANTS.AGENTS_DIR)}function Dp(){return Re.join(la(),x.AGENT_CONSTANTS.SKILLS_DIR)}function hA(t){return Re.join(Dp(),t)}function Lp(){return Re.join(la(),x.AGENT_CONSTANTS.MCP_DIR)}function mA(t){return Re.join(Lp(),t)}function Nl(t){return Re.join($p(),t)}function EA(t,e){return Re.join(Nl(t),e)}function _A(t){return Re.join(Nl(t),x.AGENT_CONSTANTS.CURRENT_VERSION_FILE)}function Rl(t){return Re.join(t,x.AGENT_CONSTANTS.AGENTIDE_DIR_NAME)}function Mp(t){return Re.join(Rl(t),x.AGENT_CONSTANTS.AGENTS_DIR)}function Os(t,e){return Re.join(Mp(t),e)}function Gp(t,e,n,r="0.0.0"){let s=Os(t,n);return{agentId:n,agentVersion:r,agentRoot:s,rulesDir:Re.join(s,x.AGENT_CONSTANTS.RULES_DIR),skillsDir:Re.join(s,x.AGENT_CONSTANTS.SKILLS_DIR),mcpDir:Re.join(s,x.AGENT_CONSTANTS.MCP_DIR),codexDerivedDir:Re.join(t,".codex"),claudeDerivedDir:Re.join(t,".claude"),codexHome:Re.join(e,x.AGENT_CONSTANTS.AGENTS_DIR,n,"codex"),claudeConfigDir:Re.join(e,x.AGENT_CONSTANTS.AGENTS_DIR,n,"claude")}}function yA(t,e,n,r){let s=n??x.AGENT_CONSTANTS.DEFAULT_AGENT_ID;return Gp(t,e,s,r)}function wA(t,e){return Hp(t,Up(e))}function Up(t){let e=t?.trim();if(e)return pA.createHash("sha256").update(e).digest("hex").slice(0,16)}function Hp(t,e){return!e||!/^[0-9a-f]{16}$/.test(e)?t:Re.join(t,"users",e)}function AA(t){return t===x.AGENT_CONSTANTS.DEFAULT_AGENT_ID}function SA(t,e){return Re.join(Os(t,e),x.AGENT_CONSTANTS.MANIFEST_FILE)}function TA(t,e){return Re.join(Os(t,e),x.AGENT_CONSTANTS.AGENTS_MD)}function bA(t,e){return Re.join(Os(t,e),x.AGENT_CONSTANTS.CONTEXT_MD)}function vA(t,e){return Re.join(Os(t,e),x.AGENT_CONSTANTS.SKILLS_DIR)}function OA(t,e){return Re.join(Os(t,e),x.AGENT_CONSTANTS.RULES_DIR)}function IA(t,e){return Re.join(Os(t,e),x.AGENT_CONSTANTS.MCP_DIR)}function PA(t){return Re.join(Rl(t),x.AGENT_CONSTANTS.SESSIONS_DIR)}function NA(t){let e=t.split(Re.sep),n=e.lastIndexOf(x.AGENT_CONSTANTS.AGENTS_DIR);if(n!==-1&&e.length>n+1)return e[n+1]}var jp=/[/\\:*?"<>|]/;function RA(t){return!(!t||t.trim().length===0||jp.test(t)||t.startsWith("."))}function CA(t){return t.trim().toLowerCase().replace(/[\s_]+/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,"")}function kA(t){if(!t||t.trim().length===0)return"Pack name is required";if(jp.test(t))return'Pack name cannot contain path separators or special characters (/ \\ : * ? " < > |)';if(t.startsWith("."))return"Pack name cannot start with a dot"}function Cl(t){return t.split(/[-_\s]+/).map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(" ")}function ca(t){let e=t.match(/^[a-z0-9-]+::/i);return e?t.slice(e[0].length):t}function $A(t={}){let{engine:e="claude",model:n,includeHeaderComments:r=!0,includeModelHintComment:s=!1}=t,i=n?ca(n):void 0;return[...r?["# Agent Hippo Pack Configuration","# This is the default agent pack for agenthippo.","# Edit this file to customize the agent's behavior.",""]:[],"apiVersion: agenthippo.ai/v1","kind: Agent","metadata:"," name: default",' version: "1.0.0"',' description: "agent hippo"',"spec:"," # Preferred engine (claude or codex)",` engine: ${e}`,...i?[` model: ${i}`]:s?[" # Model to use (optional - uses engine default if not specified)"," # model: claude-sonnet-4-20250514"]:[]," permissions:"," # File access scope for this agent:"," # - read-only: no file writes"," # - workspace-write: writes limited to workspace folders"," # - full: full filesystem access (yolo)"," fileAccess: full"," visibility: internal",""].join(`
3
+ `)}function DA(t,e={}){let{description:n=`A specialized agent for ${Cl(t).toLowerCase()} tasks`,engine:r="claude",author:s=process.env.USER||"unknown"}=e,i=e.model??(r==="claude"?"claude-sonnet-4":"codex"),o=ca(i),a=e.cheapModel?ca(e.cheapModel):void 0;return[`# ${t} Agent Manifest`,"apiVersion: agenthippo.ai/v1","kind: Agent","metadata:",` name: ${t}`," version: 0.1.0",` author: ${s}`,` description: ${n}`,"","spec:",` engine: ${r}`,` model: ${o}`,...a?[` cheapModel: ${a}`]:[],""," skills: []"," # Uncomment to add skills:"," # - path: ./skills/my-skill",""," # Optional: seed pack data into workspace on first use (target missing/empty)"," # Remove this block if your pack has no data files."," # data:"," # sourcePath: ./data",` # workspacePath: ${x.AGENT_CONSTANTS.AGENTIDE_DIR_NAME}/data/${t}`,""," permissions:"," # File access scope for this pack:"," # - read-only: no file writes"," # - workspace-write: writes limited to workspace folders"," # - full: full filesystem access (yolo)"," fileAccess: full",""," visibility: internal",""].join(`
4
+ `)}function LA(t,e={}){let n=Cl(t),r=e.description||`A specialized agent for ${n.toLowerCase()} tasks.`;return`# ${n} Agent
5
5
 
6
6
  ${r}
7
7
 
@@ -20,15 +20,15 @@ ${r}
20
20
  ## Output Format
21
21
 
22
22
  Provide clear, actionable responses with code examples when relevant.
23
- `}});var Is=S(an=>{"use strict";Object.defineProperty(an,"__esModule",{value:!0});an.ON_DENIED_TIMEOUT_MS=an.WARRANT_DENIED_REASON=void 0;an.runWithCredential=MA;an.currentCredential=GA;an.resolveEngineHomeUserKey=UA;an.requireUserId=HA;var kA=require("async_hooks"),$A=Un();an.WARRANT_DENIED_REASON="token_without_verified_user";an.ON_DENIED_TIMEOUT_MS=2e3;var la=new kA.AsyncLocalStorage;async function DA(t,e,n){if(!t)return;let r=Number.isFinite(n)&&n>0?n:an.ON_DENIED_TIMEOUT_MS,s;try{await Promise.race([Promise.resolve().then(()=>t(e)),new Promise(i=>{s=setTimeout(i,r),s.unref?.()})])}catch{}finally{s&&clearTimeout(s)}}async function LA(t,e){if(t.dataToken?.trim()&&!t.userId?.trim())throw await DA(e?.onDenied,an.WARRANT_DENIED_REASON,e?.onDeniedTimeoutMs??an.ON_DENIED_TIMEOUT_MS),new Error(`OBO data token present without a verified user in request scope (fail-closed: ${an.WARRANT_DENIED_REASON})`)}async function MA(t,e,n){return await LA(t,n),la.run(t,async()=>e())}function GA(){return la.getStore()}function UA(t){return(0,$A.engineHomeUserKey)(la.getStore()?.userId)??t?.trim()??void 0}function HA(){let t=la.getStore()?.userId?.trim();if(!t)throw new Error("No authenticated user in request scope (fail-closed)");return t}});var Ys=S(Qt=>{"use strict";var jA=Qt&&Qt.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,s)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),xA=Qt&&Qt.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),jp=Qt&&Qt.__importStar||(function(){var t=function(e){return t=Object.getOwnPropertyNames||function(n){var r=[];for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(r[r.length]=s);return r},t(e)};return function(e){if(e&&e.__esModule)return e;var n={};if(e!=null)for(var r=t(e),s=0;s<r.length;s++)r[s]!=="default"&&jA(n,e,r[s]);return xA(n,e),n}})();Object.defineProperty(Qt,"__esModule",{value:!0});Qt.DIRS=Qt.PID_FILES=void 0;Qt.getAgentideHome=xp;Qt.getAgentidePath=qs;Qt.getAnalyticsScriptsDir=VA;var ua=jp(require("path")),BA=jp(require("os")),FA=Ke();function xp(){let t=process.env.AGENT_HOME_DIR||process.env.AGENTHIPPO_HOME;return t?.trim()?t.trim():ua.join(BA.homedir(),FA.AGENTIDE_DIR_NAME)}function qs(...t){return ua.join(xp(),...t)}Qt.PID_FILES={gateway:()=>qs("gateway.pid"),litellm:()=>qs("litellm.pid"),otelcol:()=>qs("analytics","otelcol.pid")};Qt.DIRS={analytics:()=>qs("analytics"),credentials:()=>qs("credentials"),sessions:()=>qs("sessions")};function VA(t){let e=require("fs"),n=ua.join(t,"out","scripts","analytics"),r=ua.join(t,"scripts","analytics");try{return e.accessSync(n),n}catch{}try{return e.accessSync(r),r}catch{}return n}});var fa=S(Hn=>{"use strict";Object.defineProperty(Hn,"__esModule",{value:!0});Hn.GATEWAY_SECRET_ENV_KEYS=void 0;Hn.getAgentHomeEnvFilePath=da;Hn.parseEnvContent=Bp;Hn.readAgentHomeEnvFile=Cl;Hn.mergeEnvIntoProcessEnv=Fp;Hn.mergeAgentHomeEnvIntoProcessEnv=qA;Hn.buildGatewayChildProcessEnv=Vp;Hn.readGatewayChildProcessEnv=YA;var WA=require("fs"),KA=Ys();function da(){return(0,KA.getAgentidePath)(".env")}function Bp(t){let e={},n=t.split(/\r?\n/);for(let r of n){let s=r.trim();if(!s||s.startsWith("#"))continue;let i=s.indexOf("=");if(i===-1)continue;let o=s.slice(0,i).trim(),a=s.slice(i+1).trim(),c=a.length>=2&&a.startsWith('"')&&a.endsWith('"'),l=a.length>=2&&a.startsWith("'")&&a.endsWith("'");(c||l)&&(a=a.slice(1,-1)),c&&(a=a.replace(/\\n/g,`
24
- `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\\\/g,"\\")),o&&(e[o]=a)}return e}async function Cl(t=da()){try{let e=await WA.promises.readFile(t,"utf-8");return Bp(e)}catch{return{}}}function Fp(t,e=process.env){let n=[],r=[];for(let[s,i]of Object.entries(t))if(s){if(Object.prototype.hasOwnProperty.call(e,s)){r.push(s);continue}e[s]=i,n.push(s)}return{applied:n,skipped:r}}async function qA(t=da()){let e=await Cl(t);return{...Fp(e),envFilePath:t}}Hn.GATEWAY_SECRET_ENV_KEYS=["SLACK_BOT_TOKEN","SLACK_APP_TOKEN","OPENCLAW_GATEWAY_TOKEN"];function Vp(t,e,n=Hn.GATEWAY_SECRET_ENV_KEYS){let r={...t},s=new Set(n);for(let[i,o]of Object.entries(e)){if(!i||!o.trim())continue;let a=r[i];(s.has(i)||a===void 0||a==="")&&(r[i]=o)}return r}async function YA(t=da()){let e=await Cl(t);return Vp(process.env,e)}});var lo=S(xe=>{"use strict";var XA=xe&&xe.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,s)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),JA=xe&&xe.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),zA=xe&&xe.__importStar||(function(){var t=function(e){return t=Object.getOwnPropertyNames||function(n){var r=[];for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(r[r.length]=s);return r},t(e)};return function(e){if(e&&e.__esModule)return e;var n={};if(e!=null)for(var r=t(e),s=0;s<r.length;s++)r[s]!=="default"&&XA(n,e,r[s]);return JA(n,e),n}})();Object.defineProperty(xe,"__esModule",{value:!0});xe.AGENTHIPPO_MCP_SERVERS_ENV=xe.ALLOW_INLINE_DATA_TOKEN_ENV=void 0;xe.loadMcpServers=nS;xe.resolveMcpEnvVar=Yp;xe.resolveMcpServerEnv=cS;xe.generateCodexMcpConfig=fS;xe.getDefaultMcpConfig=pS;xe.loadBundledMcpServers=gS;xe.resolveHttpMcpHeaders=Gl;xe.referenceHttpMcpHeaders=mS;xe.formatInlineMcpServers=ES;xe.serializeInlineMcpServers=_S;xe.parseInlineMcpServers=yS;var Oi=require("fs"),kr=zA(require("path")),kl=Is(),Wp=Un(),QA=fa(),ZA="enable-bundled",eS="disable-bundled",Kp=".mcp.json",Dl="mcp-servers";xe.ALLOW_INLINE_DATA_TOKEN_ENV="AGENTHIPPO_ALLOW_INLINE_DATA_TOKEN";function $l(){return/^(1|true)$/i.test(process.env[xe.ALLOW_INLINE_DATA_TOKEN_ENV]?.trim()??"")}var Ll=/\$\{env:(\w+)\}/g,tS=/\$\{credential:(\w+)\}/g;async function nS(t,e,n){let r=(0,Wp.getAgentMcpDir)(e,t||Wp.AGENT_CONSTANTS.DEFAULT_AGENT_ID),s=kr.join(r,Kp);if(!await ga(s))return[];let i=n?kr.join(n,Dl):"";return rS(s,r,e,i)}async function rS(t,e,n,r){let s;try{let a=await Oi.promises.readFile(t,"utf-8");s=JSON.parse(a)}catch(a){return console.warn(`[AgentIDE] Failed to load MCP config from ${t}:`,a),[]}if(!s.mcpServers)return[];let i=await uS(n,e),o=[];for(let[a,c]of Object.entries(s.mcpServers))try{let l=await sS(a,c,e,r,i);l&&o.push(l)}catch(l){console.warn(`[AgentIDE] Failed to resolve MCP server '${a}':`,l)}return o}async function sS(t,e,n,r,s){if(e.command===eS)return null;if(e.command===ZA)return iS(t,e,r,s);if(e.url){let i=e.url.replace(Ll,(o,a)=>Xp(a,s)).trim();return i?{name:t,label:e.label??t,description:e.description,command:"",args:[],url:i,headers:lS(e.headers,s),bearerTokenEnv:e.bearerTokenEnv?.trim()||void 0}:null}return{name:t,label:e.label??t,description:e.description,command:e.command??"",args:Ml(e.args,n),env:pa(e.env,s)}}async function iS(t,e,n,r){let s=await qp(t,n);if(!s)return null;let i=kr.join(n,t),o={...s.env??{}};if(e.env)for(let[a,c]of Object.entries(e.env))o[a]=c;return{name:t,label:e.label??s.label??t,description:e.description??s.description,command:s.command,args:Ml(s.args,i),env:pa(o,r)}}async function qp(t,e){if(!e)return console.warn(`[AgentIDE] Bundled MCP directory unavailable; cannot resolve '${t}'`),null;let n=kr.join(e,t,"mcp.json");if(!await ga(n))return console.warn(`[AgentIDE] Bundled server '${t}' not found at ${n}`),null;try{let r=await Oi.promises.readFile(n,"utf-8"),s=JSON.parse(r);return!s.command||typeof s.command!="string"?(console.warn(`[AgentIDE] Invalid bundled server config at ${n}: missing command`),null):s}catch(r){return console.warn(`[AgentIDE] Failed to load bundled server config from ${n}:`,r),null}}function Ml(t,e){return t?t.map(n=>{let r=n;return r=r.replace(/\$\{serverDir\}/g,e),(r.startsWith("./")||r.startsWith("../"))&&(r=kr.resolve(e,r)),r}):[]}function Yp(t,e={}){let n=oS();if(t==="dataToken"){let r=(0,kl.currentCredential)()?.dataToken?.trim();return r&&$l()?r:""}if(n.includes(t)){let r=(0,kl.currentCredential)()?.dataToken?.trim();if(r&&$l())return r}return process.env[t]??e[t]??""}function oS(){let t=process.env.AGENTHIPPO_DATA_TOKEN_ENV_VARS;return t!==void 0?t.split(",").map(e=>e.trim()).filter(Boolean):[]}function aS(t){return/\$\{credential:dataToken\}/.test(t)}function pa(t,e={}){if(!t)return;let n={};for(let[r,s]of Object.entries(t)){if(tS.lastIndex=0,aS(s)){let i=(0,kl.currentCredential)()?.dataToken?.trim();if(i)$l()&&(n[r]=i);else{let o=process.env[r]??e[r]??"";o&&(n[r]=o)}continue}n[r]=s.replace(Ll,(i,o)=>Yp(o,e))}return n}function cS(t,e={}){return pa(t,e)}function lS(t,e={}){if(!t)return;let n={};for(let[r,s]of Object.entries(t)){let i=s.replace(Ll,(o,a)=>Xp(a,e));i&&(n[r]=i)}return Object.keys(n).length>0?n:void 0}function Xp(t,e){return process.env[t]??e[t]??""}async function uS(t,e){let n={},r=[kr.join(e,".env"),kr.join(t,".env")];for(let s of r){let i=await dS(s);Object.assign(n,i)}return n}async function dS(t){try{let e=await Oi.promises.readFile(t,"utf-8");return(0,QA.parseEnvContent)(e)}catch{return{}}}function fS(t,e){if(t.length===0)return"";let n=e?.autoApprove?'default_tools_approval_mode = "approve"':void 0;return`
23
+ `}});var Is=S(an=>{"use strict";Object.defineProperty(an,"__esModule",{value:!0});an.ON_DENIED_TIMEOUT_MS=an.WARRANT_DENIED_REASON=void 0;an.runWithCredential=jA;an.currentCredential=xA;an.resolveEngineHomeUserKey=BA;an.requireUserId=FA;var MA=require("async_hooks"),GA=Un();an.WARRANT_DENIED_REASON="token_without_verified_user";an.ON_DENIED_TIMEOUT_MS=2e3;var ua=new MA.AsyncLocalStorage;async function UA(t,e,n){if(!t)return;let r=Number.isFinite(n)&&n>0?n:an.ON_DENIED_TIMEOUT_MS,s;try{await Promise.race([Promise.resolve().then(()=>t(e)),new Promise(i=>{s=setTimeout(i,r),s.unref?.()})])}catch{}finally{s&&clearTimeout(s)}}async function HA(t,e){if(t.dataToken?.trim()&&!t.userId?.trim())throw await UA(e?.onDenied,an.WARRANT_DENIED_REASON,e?.onDeniedTimeoutMs??an.ON_DENIED_TIMEOUT_MS),new Error(`OBO data token present without a verified user in request scope (fail-closed: ${an.WARRANT_DENIED_REASON})`)}async function jA(t,e,n){return await HA(t,n),ua.run(t,async()=>e())}function xA(){return ua.getStore()}function BA(t){return(0,GA.engineHomeUserKey)(ua.getStore()?.userId)??t?.trim()??void 0}function FA(){let t=ua.getStore()?.userId?.trim();if(!t)throw new Error("No authenticated user in request scope (fail-closed)");return t}});var Ys=S(Qt=>{"use strict";var VA=Qt&&Qt.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,s)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),WA=Qt&&Qt.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),xp=Qt&&Qt.__importStar||(function(){var t=function(e){return t=Object.getOwnPropertyNames||function(n){var r=[];for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(r[r.length]=s);return r},t(e)};return function(e){if(e&&e.__esModule)return e;var n={};if(e!=null)for(var r=t(e),s=0;s<r.length;s++)r[s]!=="default"&&VA(n,e,r[s]);return WA(n,e),n}})();Object.defineProperty(Qt,"__esModule",{value:!0});Qt.DIRS=Qt.PID_FILES=void 0;Qt.getAgentideHome=Bp;Qt.getAgentidePath=qs;Qt.getAnalyticsScriptsDir=YA;var da=xp(require("path")),KA=xp(require("os")),qA=Ke();function Bp(){let t=process.env.AGENT_HOME_DIR||process.env.AGENTHIPPO_HOME;return t?.trim()?t.trim():da.join(KA.homedir(),qA.AGENTIDE_DIR_NAME)}function qs(...t){return da.join(Bp(),...t)}Qt.PID_FILES={gateway:()=>qs("gateway.pid"),litellm:()=>qs("litellm.pid"),otelcol:()=>qs("analytics","otelcol.pid")};Qt.DIRS={analytics:()=>qs("analytics"),credentials:()=>qs("credentials"),sessions:()=>qs("sessions")};function YA(t){let e=require("fs"),n=da.join(t,"out","scripts","analytics"),r=da.join(t,"scripts","analytics");try{return e.accessSync(n),n}catch{}try{return e.accessSync(r),r}catch{}return n}});var pa=S(Hn=>{"use strict";Object.defineProperty(Hn,"__esModule",{value:!0});Hn.GATEWAY_SECRET_ENV_KEYS=void 0;Hn.getAgentHomeEnvFilePath=fa;Hn.parseEnvContent=Fp;Hn.readAgentHomeEnvFile=kl;Hn.mergeEnvIntoProcessEnv=Vp;Hn.mergeAgentHomeEnvIntoProcessEnv=zA;Hn.buildGatewayChildProcessEnv=Wp;Hn.readGatewayChildProcessEnv=QA;var XA=require("fs"),JA=Ys();function fa(){return(0,JA.getAgentidePath)(".env")}function Fp(t){let e={},n=t.split(/\r?\n/);for(let r of n){let s=r.trim();if(!s||s.startsWith("#"))continue;let i=s.indexOf("=");if(i===-1)continue;let o=s.slice(0,i).trim(),a=s.slice(i+1).trim(),c=a.length>=2&&a.startsWith('"')&&a.endsWith('"'),l=a.length>=2&&a.startsWith("'")&&a.endsWith("'");(c||l)&&(a=a.slice(1,-1)),c&&(a=a.replace(/\\n/g,`
24
+ `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\\\/g,"\\")),o&&(e[o]=a)}return e}async function kl(t=fa()){try{let e=await XA.promises.readFile(t,"utf-8");return Fp(e)}catch{return{}}}function Vp(t,e=process.env){let n=[],r=[];for(let[s,i]of Object.entries(t))if(s){if(Object.prototype.hasOwnProperty.call(e,s)){r.push(s);continue}e[s]=i,n.push(s)}return{applied:n,skipped:r}}async function zA(t=fa()){let e=await kl(t);return{...Vp(e),envFilePath:t}}Hn.GATEWAY_SECRET_ENV_KEYS=["SLACK_BOT_TOKEN","SLACK_APP_TOKEN","OPENCLAW_GATEWAY_TOKEN"];function Wp(t,e,n=Hn.GATEWAY_SECRET_ENV_KEYS){let r={...t},s=new Set(n);for(let[i,o]of Object.entries(e)){if(!i||!o.trim())continue;let a=r[i];(s.has(i)||a===void 0||a==="")&&(r[i]=o)}return r}async function QA(t=fa()){let e=await kl(t);return Wp(process.env,e)}});var fo=S(xe=>{"use strict";var ZA=xe&&xe.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,s)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),eS=xe&&xe.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),tS=xe&&xe.__importStar||(function(){var t=function(e){return t=Object.getOwnPropertyNames||function(n){var r=[];for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(r[r.length]=s);return r},t(e)};return function(e){if(e&&e.__esModule)return e;var n={};if(e!=null)for(var r=t(e),s=0;s<r.length;s++)r[s]!=="default"&&ZA(n,e,r[s]);return eS(n,e),n}})();Object.defineProperty(xe,"__esModule",{value:!0});xe.AGENTHIPPO_MCP_SERVERS_ENV=xe.ALLOW_INLINE_DATA_TOKEN_ENV=void 0;xe.loadMcpServers=oS;xe.resolveMcpEnvVar=Xp;xe.resolveMcpServerEnv=fS;xe.generateCodexMcpConfig=mS;xe.getDefaultMcpConfig=ES;xe.loadBundledMcpServers=_S;xe.resolveHttpMcpHeaders=Ul;xe.referenceHttpMcpHeaders=wS;xe.formatInlineMcpServers=AS;xe.serializeInlineMcpServers=SS;xe.parseInlineMcpServers=TS;var Oi=require("fs"),kr=tS(require("path")),$l=Is(),Kp=Un(),nS=pa(),rS="enable-bundled",sS="disable-bundled",qp=".mcp.json",Ll="mcp-servers";xe.ALLOW_INLINE_DATA_TOKEN_ENV="AGENTHIPPO_ALLOW_INLINE_DATA_TOKEN";function Dl(){return/^(1|true)$/i.test(process.env[xe.ALLOW_INLINE_DATA_TOKEN_ENV]?.trim()??"")}var Ml=/\$\{env:(\w+)\}/g,iS=/\$\{credential:(\w+)\}/g;async function oS(t,e,n){let r=(0,Kp.getAgentMcpDir)(e,t||Kp.AGENT_CONSTANTS.DEFAULT_AGENT_ID),s=kr.join(r,qp);if(!await ha(s))return[];let i=n?kr.join(n,Ll):"";return aS(s,r,e,i)}async function aS(t,e,n,r){let s;try{let a=await Oi.promises.readFile(t,"utf-8");s=JSON.parse(a)}catch(a){return console.warn(`[AgentIDE] Failed to load MCP config from ${t}:`,a),[]}if(!s.mcpServers)return[];let i=await gS(n,e),o=[];for(let[a,c]of Object.entries(s.mcpServers))try{let l=await cS(a,c,e,r,i);l&&o.push(l)}catch(l){console.warn(`[AgentIDE] Failed to resolve MCP server '${a}':`,l)}return o}async function cS(t,e,n,r,s){if(e.command===sS)return null;if(e.command===rS)return lS(t,e,r,s);if(e.url){let i=e.url.replace(Ml,(o,a)=>Jp(a,s)).trim();return i?{name:t,label:e.label??t,description:e.description,command:"",args:[],url:i,headers:pS(e.headers,s),bearerTokenEnv:e.bearerTokenEnv?.trim()||void 0}:null}return{name:t,label:e.label??t,description:e.description,command:e.command??"",args:Gl(e.args,n),env:ga(e.env,s)}}async function lS(t,e,n,r){let s=await Yp(t,n);if(!s)return null;let i=kr.join(n,t),o={...s.env??{}};if(e.env)for(let[a,c]of Object.entries(e.env))o[a]=c;return{name:t,label:e.label??s.label??t,description:e.description??s.description,command:s.command,args:Gl(s.args,i),env:ga(o,r)}}async function Yp(t,e){if(!e)return console.warn(`[AgentIDE] Bundled MCP directory unavailable; cannot resolve '${t}'`),null;let n=kr.join(e,t,"mcp.json");if(!await ha(n))return console.warn(`[AgentIDE] Bundled server '${t}' not found at ${n}`),null;try{let r=await Oi.promises.readFile(n,"utf-8"),s=JSON.parse(r);return!s.command||typeof s.command!="string"?(console.warn(`[AgentIDE] Invalid bundled server config at ${n}: missing command`),null):s}catch(r){return console.warn(`[AgentIDE] Failed to load bundled server config from ${n}:`,r),null}}function Gl(t,e){return t?t.map(n=>{let r=n;return r=r.replace(/\$\{serverDir\}/g,e),(r.startsWith("./")||r.startsWith("../"))&&(r=kr.resolve(e,r)),r}):[]}function Xp(t,e={}){let n=uS();if(t==="dataToken"){let r=(0,$l.currentCredential)()?.dataToken?.trim();return r&&Dl()?r:""}if(n.includes(t)){let r=(0,$l.currentCredential)()?.dataToken?.trim();if(r&&Dl())return r}return process.env[t]??e[t]??""}function uS(){let t=process.env.AGENTHIPPO_DATA_TOKEN_ENV_VARS;return t!==void 0?t.split(",").map(e=>e.trim()).filter(Boolean):[]}function dS(t){return/\$\{credential:dataToken\}/.test(t)}function ga(t,e={}){if(!t)return;let n={};for(let[r,s]of Object.entries(t)){if(iS.lastIndex=0,dS(s)){let i=(0,$l.currentCredential)()?.dataToken?.trim();if(i)Dl()&&(n[r]=i);else{let o=process.env[r]??e[r]??"";o&&(n[r]=o)}continue}n[r]=s.replace(Ml,(i,o)=>Xp(o,e))}return n}function fS(t,e={}){return ga(t,e)}function pS(t,e={}){if(!t)return;let n={};for(let[r,s]of Object.entries(t)){let i=s.replace(Ml,(o,a)=>Jp(a,e));i&&(n[r]=i)}return Object.keys(n).length>0?n:void 0}function Jp(t,e){return process.env[t]??e[t]??""}async function gS(t,e){let n={},r=[kr.join(e,".env"),kr.join(t,".env")];for(let s of r){let i=await hS(s);Object.assign(n,i)}return n}async function hS(t){try{let e=await Oi.promises.readFile(t,"utf-8");return(0,nS.parseEnvContent)(e)}catch{return{}}}function mS(t,e){if(t.length===0)return"";let n=e?.autoApprove?'default_tools_approval_mode = "approve"':void 0;return`
25
25
  # MCP Servers (AgentIDE)
26
26
  `+t.map(s=>{if(s.url){let o=[`[mcp_servers.${s.name}]`,`url = ${JSON.stringify(s.url)}`];if(s.bearerTokenEnv&&o.push(`bearer_token_env_var = ${JSON.stringify(s.bearerTokenEnv)}`),s.headers&&Object.keys(s.headers).length>0){let a=Object.entries(s.headers).map(([c,l])=>`${JSON.stringify(c)} = ${JSON.stringify(l)}`).join(", ");o.push(`http_headers = { ${a} }`)}return n&&o.push(n),o.join(`
27
27
  `)}let i=[`[mcp_servers.${s.name}]`,`command = ${JSON.stringify(s.command)}`,`args = ${JSON.stringify(s.args)}`];if(n&&i.push(n),s.env&&Object.keys(s.env).length>0){i.push("",`[mcp_servers.${s.name}.env]`);for(let[o,a]of Object.entries(s.env))i.push(`${JSON.stringify(o)} = ${JSON.stringify(a)}`)}return i.join(`
28
28
  `)}).join(`
29
29
 
30
- `)}async function pS(t){let e=kr.join(t,Dl,Kp);if(!await ga(e))return null;try{return await Oi.promises.readFile(e,"utf-8")}catch{return null}}async function gS(t){let e=kr.join(t,Dl);if(!await ga(e))return[];let n=[],r;try{r=await Oi.promises.readdir(e,{withFileTypes:!0})}catch{return[]}for(let s of r){if(!s.isDirectory())continue;let i=s.name,o=await qp(i,e);if(!o)continue;let a=kr.join(e,i);n.push({name:o.name??i,label:o.label??i,description:o.description,command:o.command,args:Ml(o.args,a),env:pa(o.env)})}return n}xe.AGENTHIPPO_MCP_SERVERS_ENV="AGENTHIPPO_MCP_SERVERS";function Gl(t,e){let n={...t.headers??{}};if(t.bearerTokenEnv){let r=e[t.bearerTokenEnv]?.trim();r&&(n.Authorization=`Bearer ${r}`)}return Object.keys(n).length>0?n:void 0}var hS=/^[A-Za-z_][A-Za-z0-9_]*$/;function mS(t,e){let n=t.bearerTokenEnv;if(n&&!hS.test(n))return Gl(t,e);let r={...t.headers??{}};return n&&(r.Authorization=`Bearer \${${n}}`),Object.keys(r).length>0?r:void 0}function ES(t,e){let n={};for(let r of t){if(r.url){let s=Gl(r,e??process.env);n[r.name]={type:"http",url:r.url,...s?{headers:s}:{}};continue}n[r.name]={command:r.command,args:r.args,...r.env&&Object.keys(r.env).length>0?{env:r.env}:{}}}return n}function _S(t){if(Object.keys(t).length!==0)return JSON.stringify(t)}function yS(t){if(t?.trim())try{let e=JSON.parse(t);return!e||typeof e!="object"||Array.isArray(e)?void 0:e}catch{return}}async function ga(t){try{return await Oi.promises.access(t),!0}catch{return!1}}});var Jp=S(Ii=>{"use strict";Object.defineProperty(Ii,"__esModule",{value:!0});Ii.NoOpLogger=Ii.ConsoleLogger=void 0;var Ul=class{prefix;constructor(e="[AgentIDE]"){this.prefix=e}debug(e){console.debug(`${this.prefix} ${e}`)}info(e){console.log(`${this.prefix} ${e}`)}warn(e){console.warn(`${this.prefix} Warning: ${e}`)}error(e,n){console.error(`${this.prefix} Error: ${e}${n?`: ${n.message}`:""}`)}};Ii.ConsoleLogger=Ul;var Hl=class{debug(e){}info(e){}warn(e){}error(e,n){}};Ii.NoOpLogger=Hl});var zp=S(Ps=>{"use strict";Object.defineProperty(Ps,"__esModule",{value:!0});Ps.CLIPermissionHandler=Ps.AutoDenyPermissionHandler=Ps.AutoApprovePermissionHandler=void 0;var jl=class{async requestPermission(e){return{behavior:"allow"}}};Ps.AutoApprovePermissionHandler=jl;var xl=class{message;constructor(e="All tool requests are denied"){this.message=e}async requestPermission(e){return{behavior:"deny",message:this.message}}};Ps.AutoDenyPermissionHandler=xl;var Bl=class{readline;async requestPermission(e){return this.readline||(this.readline=require("readline")),new Promise(n=>{let r=this.readline.createInterface({input:process.stdin,output:process.stdout}),s=e.toolInput?`${e.toolName}: ${JSON.stringify(e.toolInput).slice(0,100)}`:e.toolName;console.log(`
31
- \u26A0\uFE0F Tool permission requested: ${s}`),r.question("Allow? (y/n): ",i=>{r.close();let o=i.toLowerCase().startsWith("y");n(o?{behavior:"allow"}:{behavior:"deny",message:"User denied permission"})})})}};Ps.CLIPermissionHandler=Bl});var Qp=S(ha=>{"use strict";Object.defineProperty(ha,"__esModule",{value:!0});ha.NoOpEditTracker=void 0;var Fl=class{appliesEdits=!1;async startTracking(e,n){}async stopTracking(e,n){}async applyEdit(e,n,r,s){}};ha.NoOpEditTracker=Fl});var Zp=S(cn=>{"use strict";var wS=cn&&cn.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,s)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),AS=cn&&cn.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),SS=cn&&cn.__importStar||(function(){var t=function(e){return t=Object.getOwnPropertyNames||function(n){var r=[];for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(r[r.length]=s);return r},t(e)};return function(e){if(e&&e.__esModule)return e;var n={};if(e!=null)for(var r=t(e),s=0;s<r.length;s++)r[s]!=="default"&&wS(n,e,r[s]);return AS(n,e),n}})();Object.defineProperty(cn,"__esModule",{value:!0});cn.DirectorySessionStore=cn.FileSessionStore=cn.MemorySessionStore=void 0;var Zt=require("fs"),ma=SS(require("path")),TS=require("crypto"),Vl=class{store=new Map;get(e){return this.store.get(e)}async set(e,n){this.store.set(e,n)}clear(){this.store.clear()}};cn.MemorySessionStore=Vl;var Wl=class{store={};loaded=!1;filePath;constructor(e){this.filePath=e}async load(){if(!this.loaded){try{let e=await Zt.promises.readFile(this.filePath,"utf-8");this.store=JSON.parse(e)}catch(e){e.code!=="ENOENT"&&console.warn(`[FileSessionStore] Failed to load ${this.filePath}: ${e}`),this.store={}}this.loaded=!0}}get(e){return this.loaded||this.loadSync(),this.store[e]}async set(e,n){this.store[e]=n,await this.flush()}async clear(){this.store={},await this.flush()}async flush(){let e=ma.dirname(this.filePath);await Zt.promises.mkdir(e,{recursive:!0});let n=`${this.filePath}.tmp.${Date.now()}`,r=JSON.stringify(this.store,null,2);try{await Zt.promises.writeFile(n,r,"utf-8"),await Zt.promises.rename(n,this.filePath)}catch(s){try{await Zt.promises.unlink(n)}catch{}throw s}}loadSync(){if(!this.loaded){try{let e=(0,Zt.readFileSync)(this.filePath,"utf-8");this.store=JSON.parse(e)}catch(e){e.code!=="ENOENT"&&console.warn(`[FileSessionStore] Failed to load ${this.filePath}: ${e}`),this.store={}}this.loaded=!0}}};cn.FileSessionStore=Wl;var Kl=class{dir;entries={};serialized=new Map;files=new Map;loaded=!1;constructor(e){this.dir=e}get(e){return this.loaded||this.loadSync(),this.entries}async set(e,n){this.loaded||this.loadSync();let r=n&&typeof n=="object"?n:{};await Zt.promises.mkdir(this.dir,{recursive:!0});for(let[s,i]of Object.entries(r)){let o=JSON.stringify(i);if(this.serialized.get(s)===o)continue;let a=this.files.get(s)??`${this.fileNameFor(s)}.json`;await this.writeAtomic(a,JSON.stringify({key:s,value:i},null,2)),this.files.set(s,a),this.serialized.set(s,o)}for(let s of[...this.serialized.keys()]){if(Object.prototype.hasOwnProperty.call(r,s))continue;let i=this.files.get(s);if(i)try{await Zt.promises.unlink(ma.join(this.dir,i))}catch{}this.files.delete(s),this.serialized.delete(s)}this.entries={...r}}fileNameFor(e){return(0,TS.createHash)("sha256").update(e).digest("hex").slice(0,40)}async writeAtomic(e,n){let r=ma.join(this.dir,e),s=`${r}.tmp.${process.pid}.${Date.now()}`;try{await Zt.promises.writeFile(s,n,"utf-8"),await Zt.promises.rename(s,r)}catch(i){try{await Zt.promises.unlink(s)}catch{}throw i}}loadSync(){if(this.loaded)return;this.loaded=!0,this.migrateLegacySingleFileSync();let e;try{e=(0,Zt.readdirSync)(this.dir).filter(n=>n.endsWith(".json"))}catch(n){n.code!=="ENOENT"&&console.warn(`[DirectorySessionStore] Failed to list ${this.dir}: ${n}`);return}for(let n of e)try{let r=(0,Zt.readFileSync)(ma.join(this.dir,n),"utf-8"),s=JSON.parse(r);s&&typeof s.key=="string"&&(this.entries[s.key]=s.value,this.serialized.set(s.key,JSON.stringify(s.value)),this.files.set(s.key,n))}catch(r){console.warn(`[DirectorySessionStore] Skipping unreadable ${n}: ${r}`)}}migrateLegacySingleFileSync(){let e=!0;try{(0,Zt.readdirSync)(this.dir)}catch{e=!1}if(e)return;let n=`${this.dir}.json`,r;try{r=JSON.parse((0,Zt.readFileSync)(n,"utf-8"))}catch{return}for(let s of Object.values(r))if(s&&typeof s=="object")for(let[i,o]of Object.entries(s))this.entries[i]=o}};cn.DirectorySessionStore=Kl});var eg=S(Ea=>{"use strict";Object.defineProperty(Ea,"__esModule",{value:!0});Ea.StaticConfigProvider=void 0;var ql=class{config;customProviders;engineSettings;constructor(e={},n={},r={}){this.config=e,this.customProviders=n,this.engineSettings=r}get(e,n,r){let s=`${e}.${n}`,i=this.config[s];return i!==void 0?i:r}getCustomProviders(){return this.customProviders}getEngineSettings(){return this.engineSettings}};Ea.StaticConfigProvider=ql});var Jl=S(Je=>{"use strict";Object.defineProperty(Je,"__esModule",{value:!0});Je.StaticConfigProvider=Je.DirectorySessionStore=Je.FileSessionStore=Je.MemorySessionStore=Je.NoOpEditTracker=Je.CLIPermissionHandler=Je.AutoDenyPermissionHandler=Je.AutoApprovePermissionHandler=Je.NoOpLogger=Je.ConsoleLogger=void 0;var tg=Jp();Object.defineProperty(Je,"ConsoleLogger",{enumerable:!0,get:function(){return tg.ConsoleLogger}});Object.defineProperty(Je,"NoOpLogger",{enumerable:!0,get:function(){return tg.NoOpLogger}});var Yl=zp();Object.defineProperty(Je,"AutoApprovePermissionHandler",{enumerable:!0,get:function(){return Yl.AutoApprovePermissionHandler}});Object.defineProperty(Je,"AutoDenyPermissionHandler",{enumerable:!0,get:function(){return Yl.AutoDenyPermissionHandler}});Object.defineProperty(Je,"CLIPermissionHandler",{enumerable:!0,get:function(){return Yl.CLIPermissionHandler}});var bS=Qp();Object.defineProperty(Je,"NoOpEditTracker",{enumerable:!0,get:function(){return bS.NoOpEditTracker}});var Xl=Zp();Object.defineProperty(Je,"MemorySessionStore",{enumerable:!0,get:function(){return Xl.MemorySessionStore}});Object.defineProperty(Je,"FileSessionStore",{enumerable:!0,get:function(){return Xl.FileSessionStore}});Object.defineProperty(Je,"DirectorySessionStore",{enumerable:!0,get:function(){return Xl.DirectorySessionStore}});var vS=eg();Object.defineProperty(Je,"StaticConfigProvider",{enumerable:!0,get:function(){return vS.StaticConfigProvider}})});var Pi=S(ft=>{"use strict";Object.defineProperty(ft,"__esModule",{value:!0});ft.RAW_IDS_ENV=ft.ID_SALT_ENV=ft.CONTENT_CAPTURE_ENV=void 0;ft.isContentCaptureEnabled=sg;ft.resetPrivacyAnnouncementsForTest=PS;ft.hashIdentity=RS;ft.digestContent=ig;ft.describeContent=CS;var ng=require("crypto");ft.CONTENT_CAPTURE_ENV="AGENTHIPPO_EVIDENCE_CONTENT_CAPTURE";ft.ID_SALT_ENV="AGENTHIPPO_EVIDENCE_ID_SALT";ft.RAW_IDS_ENV="AGENTHIPPO_EVIDENCE_RAW_IDS";var OS="agenthippo-evidence-unsalted",IS=new Set(["1","true","yes","on"]);function rg(t){return IS.has((t??"").trim().toLowerCase())}var zl=!1,Ql=!1;function sg(t=process.env){let e=rg(t[ft.CONTENT_CAPTURE_ENV]);return zl||(zl=!0,console.warn(e?`[evidence] CONTENT CAPTURE IS ON \u2014 prompts, completions and tool I/O are recorded in evidence (${ft.CONTENT_CAPTURE_ENV} is set). Unset it for metadata-only evidence.`:`[evidence] content capture off \u2014 tool I/O is recorded as sha256 + length only. Set ${ft.CONTENT_CAPTURE_ENV}=1 to restore full previews.`)),e}function PS(){zl=!1,Ql=!1}function NS(t){let e=t[ft.ID_SALT_ENV]?.trim();return e||(Ql||(Ql=!0,console.warn(`[evidence] ${ft.ID_SALT_ENV} is not set \u2014 identity hashes use a public constant salt. They pseudonymise, but a known address can still be confirmed by hashing it. Set the same secret on every instance whose evidence is joined.`)),OS)}function RS(t,e=process.env){let n=t?.trim();return n?rg(e[ft.RAW_IDS_ENV])?n:`anon_${(0,ng.createHash)("sha256").update(`${NS(e)}\0${n}`).digest("hex").slice(0,32)}`:void 0}function ig(t){return{sha256:(0,ng.createHash)("sha256").update(t,"utf8").digest("hex"),length:Buffer.byteLength(t,"utf8")}}function CS(t,e,n=500,r=process.env){if(e===void 0)return{};let s=ig(e),i={[`${t}_sha256`]:s.sha256,[`${t}_length`]:s.length};return sg(r)&&(i[`${t}Preview`]=e.slice(0,n)),i}});var _a=S(Se=>{"use strict";Object.defineProperty(Se,"__esModule",{value:!0});Se.ANTHROPIC_SETUP_TOKEN_PREFIX=Se.PROVIDERS=void 0;Se.getProvider=kS;Se.requiresApiKey=$S;Se.isLocalProvider=DS;Se.getAllProviderIds=LS;Se.getCloudProviders=MS;Se.getLocalProviders=GS;Se.getApiKeyProviders=US;Se.requiresBaseUrl=HS;Se.getGatewayProviders=jS;Se.isGatewayProvider=xS;Se.isAnthropicProviderFamily=BS;Se.normalizeAnthropicSetupToken=FS;Se.isAnthropicSetupToken=VS;Se.providerNotSupportAnthropicApi=WS;Se.PROVIDERS={openai:{id:"openai",displayName:"OpenAI",defaultEndpoint:"https://api.openai.com/v1",requiresApiKey:!0,showInAddApiKeyUI:!0,notSupportAnthropicApi:!0},"openai-codex":{id:"openai-codex",displayName:"OpenAI Codex (ChatGPT OAuth)",defaultEndpoint:"https://chatgpt.com/backend-api/codex",requiresApiKey:!0,description:"Use your ChatGPT/Codex subscription via native OAuth",showInAddApiKeyUI:!0,notSupportAnthropicApi:!0},anthropic:{id:"anthropic",displayName:"Anthropic",defaultEndpoint:"https://api.anthropic.com/v1",endpointSettingKey:"agentide.providers.anthropic.baseUrl",requiresApiKey:!0,apiKeyHeader:"x-api-key",staticHeaders:{"anthropic-version":"2023-06-01"},headerSettingKeys:{"anthropic-version":"agentide.providers.anthropic.version"},showInAddApiKeyUI:!0},"anthropic-setup-token":{id:"anthropic-setup-token",displayName:"Anthropic (Claude Subscription)",defaultEndpoint:"https://api.anthropic.com/v1",endpointSettingKey:"agentide.providers.anthropic.baseUrl",requiresApiKey:!0,apiKeyHeader:"x-api-key",staticHeaders:{"anthropic-version":"2023-06-01"},headerSettingKeys:{"anthropic-version":"agentide.providers.anthropic.version"},description:'Use Claude subscription setup-token from "claude setup-token"',showInAddApiKeyUI:!0},openrouter:{id:"openrouter",displayName:"OpenRouter",defaultEndpoint:"https://openrouter.ai/api/v1",requiresApiKey:!0,description:"Fast model proxy via openrouter.ai that works with all agents",showInAddApiKeyUI:!0,isGateway:!0},litellm:{id:"litellm",displayName:"LiteLLM",endpointSettingKey:"agentide.providers.litellm.baseUrl",requiresApiKey:!0,description:"local adapter for agents to work with Spotlight and all models from OpenAI, Anthropic, Ollama etc.",showInAddApiKeyUI:!0,isGateway:!0,deferMissingApiKey:!0},ollama:{id:"ollama",displayName:"Ollama",defaultEndpoint:"http://localhost:11434/v1",requiresApiKey:!1,enabledSettingKey:"agentide.local.ollama.enabled",defaultEnabled:!0,placeholderApiKey:"ollama",description:"Local LLM server",showInAddApiKeyUI:!1,notSupportAnthropicApi:!0},agenthippo:{id:"agenthippo",displayName:"AgentHippo Gateway",defaultEndpoint:"https://gateway.agenthippo.ai/v1",endpointSettingKey:"agentide.AgentHippoModelGateway.url",requiresApiKey:!0,description:"AgentHippo managed gateway \u2014 uses account JWT, picks model automatically",showInAddApiKeyUI:!1,isGateway:!0,staticHeaders:{"x-agenthippo-source":"chat-ui"},credentialRefreshCommand:"agentide.auth.refreshToken",deferMissingApiKey:!0}};function kS(t){return Se.PROVIDERS[t]}function $S(t){return Se.PROVIDERS[t]?.requiresApiKey??!0}function DS(t){let e=Se.PROVIDERS[t];return e?!e.requiresApiKey:!1}function LS(){return Object.keys(Se.PROVIDERS)}function MS(){return Object.values(Se.PROVIDERS).filter(t=>t.requiresApiKey)}function GS(){return Object.values(Se.PROVIDERS).filter(t=>!t.requiresApiKey)}function US(){return Object.values(Se.PROVIDERS).filter(t=>t.showInAddApiKeyUI===!0)}function HS(t){let e=Se.PROVIDERS[t];return e?!!e.endpointSettingKey&&!e.defaultEndpoint:!1}function jS(){return Object.values(Se.PROVIDERS).filter(t=>t.isGateway)}function xS(t){return Se.PROVIDERS[t]?.isGateway??!1}function BS(t){return t==="anthropic"||t==="anthropic-setup-token"}Se.ANTHROPIC_SETUP_TOKEN_PREFIX="sk-ant-oat01-";function FS(t){return t.replace(/\s+/g,"").trim()}function VS(t){return typeof t=="string"&&t.trim().startsWith(Se.ANTHROPIC_SETUP_TOKEN_PREFIX)}function WS(t,e){let n=Se.PROVIDERS[t];return n?n.notSupportAnthropicApi??!1:e?.[t]?.notSupportAnthropicApi===!0}});var ya=S($e=>{"use strict";Object.defineProperty($e,"__esModule",{value:!0});$e.REGISTRY_KEY_SEPARATOR=$e.BUILTIN_MODELS=void 0;$e.getRegistryKey=og;$e.parseRegistryKey=KS;$e.isCompositeKey=qS;$e.getModel=YS;$e.getModelByRegistryKey=XS;$e.getModelsForProvider=JS;$e.getRecommendedModels=zS;$e.getModelsWithCapability=QS;$e.getActiveModels=ZS;$e.resolveModelAlias=eT;$e.BUILTIN_MODELS=[{id:"ah-auto",name:"Auto",provider:"agenthippo",contextWindow:2e5,maxOutputTokens:8192,capabilities:["chat","vision","function-calling","code"],description:"Managed gateway \u2014 routed through AgentHippo using your account, not your own API keys",recommended:!0}];$e.REGISTRY_KEY_SEPARATOR="::";function og(t,e){return`${t}${$e.REGISTRY_KEY_SEPARATOR}${e}`}function KS(t){let e=t.indexOf($e.REGISTRY_KEY_SEPARATOR);if(e!==-1)return{providerId:t.substring(0,e),modelId:t.substring(e+$e.REGISTRY_KEY_SEPARATOR.length)}}function qS(t){return t.includes($e.REGISTRY_KEY_SEPARATOR)}function YS(t){return $e.BUILTIN_MODELS.find(e=>e.id===t)}function XS(t){return $e.BUILTIN_MODELS.find(e=>og(e.provider,e.id)===t)}function JS(t){return $e.BUILTIN_MODELS.filter(e=>e.provider===t)}function zS(){return $e.BUILTIN_MODELS.filter(t=>t.recommended===!0)}function QS(t){return $e.BUILTIN_MODELS.filter(e=>e.capabilities.includes(t))}function ZS(){return $e.BUILTIN_MODELS.filter(t=>!t.deprecated)}function eT(t){if(!t)return t;let e=t.toLowerCase().trim();return $e.BUILTIN_MODELS.find(r=>r.id.toLowerCase()===e)?.id??t}});var Zl=S(rt=>{"use strict";Object.defineProperty(rt,"__esModule",{value:!0});rt.AGENT_ENGINES=void 0;rt.getAgentEngine=tT;rt.getAllAgentEngines=nT;rt.getAllAgentEngineIds=rT;rt.getCompatibleProviders=sT;rt.getEnginesCompatibleWithProvider=iT;rt.isEngineCompatibleWithProvider=oT;rt.getEngineRulesFile=aT;rt.getEngineWorkspaceDir=cT;var as=_a();rt.AGENT_ENGINES={codex:{id:"codex",displayName:"Codex",description:"OpenAI Codex - code generation agent",icon:"sparkle",nativeProvider:"openai",workspaceDir:".codex",rulesFile:"AGENTS.md",configEnvVar:"CODEX_HOME",managedPaths:["skills","config.toml","agentide.runtime.md"]},claude:{id:"claude",displayName:"Claude",description:"Anthropic Claude - agentic coding assistant",icon:"beaker",nativeProvider:"anthropic",workspaceDir:".claude",rulesFile:"CLAUDE.md",configEnvVar:"CLAUDE_CONFIG_DIR"}};function tT(t){return rt.AGENT_ENGINES[t]}function nT(){return Object.values(rt.AGENT_ENGINES)}function rT(){return Object.keys(rt.AGENT_ENGINES)}function sT(t){let e=rt.AGENT_ENGINES[t];if(!e)return[];let n=[e.nativeProvider];for(let[r,s]of Object.entries(as.PROVIDERS))if(!n.includes(r)){if(s.isGateway){n.push(r);continue}e.nativeProvider==="openai"&&!(0,as.isAnthropicProviderFamily)(r)&&n.push(r),e.nativeProvider==="anthropic"&&(0,as.isAnthropicProviderFamily)(r)&&n.push(r)}return n}function iT(t){let e=as.PROVIDERS[t];return e?e.isGateway?Object.values(rt.AGENT_ENGINES):Object.values(rt.AGENT_ENGINES).filter(n=>!!(n.nativeProvider===t||n.nativeProvider==="openai"&&!(0,as.isAnthropicProviderFamily)(t)||n.nativeProvider==="anthropic"&&(0,as.isAnthropicProviderFamily)(t))):[]}function oT(t,e){let n=rt.AGENT_ENGINES[t];return n?!!(n.nativeProvider===e||(0,as.isGatewayProvider)(e)||n.nativeProvider==="openai"&&!(0,as.isAnthropicProviderFamily)(e)||n.nativeProvider==="anthropic"&&(0,as.isAnthropicProviderFamily)(e)):!1}function aT(t){return rt.AGENT_ENGINES[t]?.rulesFile}function cT(t){return rt.AGENT_ENGINES[t]?.workspaceDir}});var Sa=S(U=>{"use strict";Object.defineProperty(U,"__esModule",{value:!0});U.getEngineWorkspaceDir=U.getEngineRulesFile=U.isEngineCompatibleWithProvider=U.getEnginesCompatibleWithProvider=U.getCompatibleProviders=U.getAllAgentEngineIds=U.getAllAgentEngines=U.getAgentEngine=U.AGENT_ENGINES=U.getActiveModels=U.getModelsWithCapability=U.getRecommendedModels=U.getModelsForProvider=U.getModel=U.getModelByRegistryKey=U.isCompositeKey=U.parseRegistryKey=U.getRegistryKey=U.REGISTRY_KEY_SEPARATOR=U.BUILTIN_MODELS=U.providerNotSupportAnthropicApi=U.isAnthropicSetupToken=U.normalizeAnthropicSetupToken=U.ANTHROPIC_SETUP_TOKEN_PREFIX=U.isAnthropicProviderFamily=U.requiresBaseUrl=U.getApiKeyProviders=U.getLocalProviders=U.getCloudProviders=U.getAllProviderIds=U.isLocalProvider=U.requiresApiKey=U.getProvider=U.PROVIDERS=void 0;U.getProviderForModel=uT;U.getEngineForModel=dT;U.getModelsForEngine=fT;U.isModelFromProvider=pT;var ln=_a();Object.defineProperty(U,"PROVIDERS",{enumerable:!0,get:function(){return ln.PROVIDERS}});Object.defineProperty(U,"getProvider",{enumerable:!0,get:function(){return ln.getProvider}});Object.defineProperty(U,"requiresApiKey",{enumerable:!0,get:function(){return ln.requiresApiKey}});Object.defineProperty(U,"isLocalProvider",{enumerable:!0,get:function(){return ln.isLocalProvider}});Object.defineProperty(U,"getAllProviderIds",{enumerable:!0,get:function(){return ln.getAllProviderIds}});Object.defineProperty(U,"getCloudProviders",{enumerable:!0,get:function(){return ln.getCloudProviders}});Object.defineProperty(U,"getLocalProviders",{enumerable:!0,get:function(){return ln.getLocalProviders}});Object.defineProperty(U,"getApiKeyProviders",{enumerable:!0,get:function(){return ln.getApiKeyProviders}});Object.defineProperty(U,"requiresBaseUrl",{enumerable:!0,get:function(){return ln.requiresBaseUrl}});Object.defineProperty(U,"isAnthropicProviderFamily",{enumerable:!0,get:function(){return ln.isAnthropicProviderFamily}});Object.defineProperty(U,"ANTHROPIC_SETUP_TOKEN_PREFIX",{enumerable:!0,get:function(){return ln.ANTHROPIC_SETUP_TOKEN_PREFIX}});Object.defineProperty(U,"normalizeAnthropicSetupToken",{enumerable:!0,get:function(){return ln.normalizeAnthropicSetupToken}});Object.defineProperty(U,"isAnthropicSetupToken",{enumerable:!0,get:function(){return ln.isAnthropicSetupToken}});Object.defineProperty(U,"providerNotSupportAnthropicApi",{enumerable:!0,get:function(){return ln.providerNotSupportAnthropicApi}});var dr=ya();Object.defineProperty(U,"BUILTIN_MODELS",{enumerable:!0,get:function(){return dr.BUILTIN_MODELS}});Object.defineProperty(U,"REGISTRY_KEY_SEPARATOR",{enumerable:!0,get:function(){return dr.REGISTRY_KEY_SEPARATOR}});Object.defineProperty(U,"getRegistryKey",{enumerable:!0,get:function(){return dr.getRegistryKey}});Object.defineProperty(U,"parseRegistryKey",{enumerable:!0,get:function(){return dr.parseRegistryKey}});Object.defineProperty(U,"isCompositeKey",{enumerable:!0,get:function(){return dr.isCompositeKey}});Object.defineProperty(U,"getModelByRegistryKey",{enumerable:!0,get:function(){return dr.getModelByRegistryKey}});Object.defineProperty(U,"getModel",{enumerable:!0,get:function(){return dr.getModel}});Object.defineProperty(U,"getModelsForProvider",{enumerable:!0,get:function(){return dr.getModelsForProvider}});Object.defineProperty(U,"getRecommendedModels",{enumerable:!0,get:function(){return dr.getRecommendedModels}});Object.defineProperty(U,"getModelsWithCapability",{enumerable:!0,get:function(){return dr.getModelsWithCapability}});Object.defineProperty(U,"getActiveModels",{enumerable:!0,get:function(){return dr.getActiveModels}});var cs=Zl();Object.defineProperty(U,"AGENT_ENGINES",{enumerable:!0,get:function(){return cs.AGENT_ENGINES}});Object.defineProperty(U,"getAgentEngine",{enumerable:!0,get:function(){return cs.getAgentEngine}});Object.defineProperty(U,"getAllAgentEngines",{enumerable:!0,get:function(){return cs.getAllAgentEngines}});Object.defineProperty(U,"getAllAgentEngineIds",{enumerable:!0,get:function(){return cs.getAllAgentEngineIds}});Object.defineProperty(U,"getCompatibleProviders",{enumerable:!0,get:function(){return cs.getCompatibleProviders}});Object.defineProperty(U,"getEnginesCompatibleWithProvider",{enumerable:!0,get:function(){return cs.getEnginesCompatibleWithProvider}});Object.defineProperty(U,"isEngineCompatibleWithProvider",{enumerable:!0,get:function(){return cs.isEngineCompatibleWithProvider}});Object.defineProperty(U,"getEngineRulesFile",{enumerable:!0,get:function(){return cs.getEngineRulesFile}});Object.defineProperty(U,"getEngineWorkspaceDir",{enumerable:!0,get:function(){return cs.getEngineWorkspaceDir}});var lT=_a(),Aa=ya(),wa=Zl();function uT(t){let e=Aa.BUILTIN_MODELS.find(n=>n.id===t);return e?lT.PROVIDERS[e.provider]:void 0}function dT(t){let e=Aa.BUILTIN_MODELS.find(n=>n.id===t);if(e)return Object.values(wa.AGENT_ENGINES).find(n=>(0,wa.isEngineCompatibleWithProvider)(n.id,e.provider))}function fT(t){let e=wa.AGENT_ENGINES[t];return e?Aa.BUILTIN_MODELS.filter(n=>(0,wa.isEngineCompatibleWithProvider)(e.id,n.provider)):[]}function pT(t,e){return Aa.BUILTIN_MODELS.find(r=>r.id===t)?.provider===e}});var Pa=S(jn=>{"use strict";var gT=jn&&jn.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,s)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),hT=jn&&jn.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),ag=jn&&jn.__importStar||(function(){var t=function(e){return t=Object.getOwnPropertyNames||function(n){var r=[];for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(r[r.length]=s);return r},t(e)};return function(e){if(e&&e.__esModule)return e;var n={};if(e!=null)for(var r=t(e),s=0;s<r.length;s++)r[s]!=="default"&&gT(n,e,r[s]);return hT(n,e),n}})();Object.defineProperty(jn,"__esModule",{value:!0});jn.getDefaultCustomEnginesInstallRoot=Ia;jn.installCustomEngineFromFiles=IT;jn.listInstalledCustomEngines=PT;jn.uninstallCustomEngine=NT;var mT=require("child_process"),st=require("fs"),ET=ag(require("os")),Pe=ag(require("path")),_T=require("util"),yT=Ke(),Oa=en(),wT=(0,_T.promisify)(mT.execFile),An="engine.manifest.json";function Ia(){return Pe.join(process.env.AGENT_HOME_DIR||process.env.AGENTHIPPO_HOME||Pe.join(ET.homedir(),yT.AGENTIDE_DIR_NAME),"engines")}function cg(t){let e=t.replace(/\\/g,"/").trim().replace(/^\.\//,"");if(!e||e.includes("\0"))throw new Error(`Invalid engine package path: ${t}`);if(e.startsWith("/")||/^[A-Za-z]:/.test(e))throw new Error(`Engine package path must be relative: ${t}`);let n=e.split("/").filter(Boolean);if(n.length===0||n.some(r=>r==="."||r===".."))throw new Error(`Engine package path must not contain "." or "..": ${t}`);return n.join("/")}function Ta(t,e){try{return cg(t).replace(/\//g,Pe.sep)}catch(n){let r=n instanceof Error?n.message:String(n);throw new Error(`${e}: ${r}`)}}function Xs(t,e,n){let r=Pe.resolve(t),s=Pe.resolve(e),i=Pe.relative(r,s);if(i&&(i.startsWith("..")||Pe.isAbsolute(i)))throw new Error(`${n} must stay inside ${t}: ${e}`)}async function ba(t){try{return await st.promises.access(t),!0}catch{return!1}}function eu(t,e){let n=JSON.parse(t);if(!n||typeof n!="object"||Array.isArray(n))throw new Error(`${e} must be a JSON object`);return n}function va(t,e,n){let r=t[e];if(typeof r!="string"||r.trim().length===0)throw new Error(`${n} missing required string field "${e}"`);return r.trim()}function lg(t){let e=t.trim().toLowerCase();if(!/^[a-z0-9][a-z0-9._-]*$/.test(e))throw new Error(`Custom engine id must contain only lowercase letters, numbers, ".", "_", or "-": ${t}`);return e}function AT(t,e){if(!t)return;if(typeof t!="object"||Array.isArray(t))throw new Error(`${e} workspaceSync must be an object`);let n=t;if(n.enabled!==!0)return;let r=va(n,"dir",`${e} workspaceSync`),s=va(n,"rulesFile",`${e} workspaceSync`);Ta(r,"workspaceSync.dir"),Ta(s,"workspaceSync.rulesFile")}async function ST(t){let e=Pe.join(t,An),n;try{n=await st.promises.readFile(e,"utf8")}catch{throw new Error(`Custom engine package is missing ${An}`)}let r=eu(n,An),s=va(r,"id",An),i={version:r.version,id:s,displayName:typeof r.displayName=="string"&&r.displayName.trim()?r.displayName.trim():void 0,description:typeof r.description=="string"&&r.description.trim()?r.description.trim():void 0,entry:va(r,"entry",An),workspaceSync:r.workspaceSync};if(i.version!==2)throw new Error(`${An} must declare version 2`);if(i.id!==i.id.toLowerCase()||!/^[a-z0-9][a-z0-9._-]*$/.test(i.id))throw new Error(`${An} id must contain only lowercase letters, numbers, ".", "_", or "-"`);AT(i.workspaceSync,An);let o=Ta(i.entry,"entry"),a=Pe.join(t,o);if(Xs(t,a,"Engine entry"),!await ba(a))throw new Error(`${An} entry not found: ${i.entry}`);return i}async function TT(t,e){let n=new Set;for(let r of e){let s=cg(r.path);if(n.has(s))throw new Error(`Duplicate engine package path: ${r.path}`);n.add(s);let i=Pe.join(t,...s.split("/"));Xs(t,i,"Engine package file"),await st.promises.mkdir(Pe.dirname(i),{recursive:!0}),await st.promises.writeFile(i,r.content)}}async function ug(t,e,n){try{await wT(t,e,{cwd:n,maxBuffer:10*1024*1024,windowsHide:!0,shell:process.platform==="win32"&&/\.(?:cmd|bat)$/i.test(t)})}catch(r){let s=typeof r.stderr=="string"?r.stderr.trim():"",i=typeof r.stdout=="string"?r.stdout.trim():"",o=s||i||(r instanceof Error?r.message:String(r));throw new Error(`${t} ${e.join(" ")} failed: ${o}`)}}async function bT(t,e,n){let r=Pe.join(t,"package.json");if(!await ba(r))return!1;let s=Pe.join(t,"package-lock.json");if(!await ba(s))throw new Error("Custom engine packages with package.json must include package-lock.json");if(!e)return!1;let i=process.platform==="win32"?"npm.cmd":"npm";return n&&(0,Oa.logInfo)(n,"[Store] Running npm ci --omit=dev for custom engine"),await ug(i,["ci","--omit=dev"],t),!0}async function vT(t,e,n){let r=Ta(e.entry,"entry"),s=Pe.join(t,r);return n&&(0,Oa.logInfo)(n,`[Store] Validating custom engine entry: ${e.entry}`),await ug("node",["--check",s],t),s}async function OT(t,e,n,r){await st.promises.mkdir(e,{recursive:!0});let s=Pe.join(e,n);Xs(e,s,"Custom engine install target");let i=await ba(s);if(i&&!r)throw new Error(`Custom engine "${n}" already exists at ${s}`);if(!i)return await st.promises.rename(t,s),s;let o=Pe.join(e,".tmp");await st.promises.mkdir(o,{recursive:!0});let a=Pe.join(o,`${n}.previous-${Date.now()}`);Xs(e,a,"Custom engine backup target"),await st.promises.rm(a,{recursive:!0,force:!0}),await st.promises.rename(s,a);try{return await st.promises.rename(t,s),await st.promises.rm(a,{recursive:!0,force:!0}),s}catch(c){throw await st.promises.rm(s,{recursive:!0,force:!0}).catch(()=>{}),await st.promises.rename(a,s).catch(()=>{}),c}}async function IT(t,e={}){if(t.length===0)throw new Error("Custom engine package is empty");let n=Pe.resolve(e.installRoot??Ia()),r=e.runNpmCi!==!1,s=e.overwrite!==!1,i=Pe.join(n,".tmp");await st.promises.mkdir(i,{recursive:!0});let o=await st.promises.mkdtemp(Pe.join(i,`${e.slug||"engine"}-`));Xs(i,o,"Custom engine staging directory");let a=!0;try{await TT(o,t);let c=await ST(o),l=await bT(o,r,e.logger),f=await vT(o,c,e.logger),u=await OT(o,n,c.id,s);a=!1;let d=Pe.join(u,Pe.relative(o,f)),p={id:c.id,displayName:c.displayName||c.id,version:c.version,manifestPath:Pe.join(u,An),installDir:u,entryPath:d,npmInstalled:l};if(e.logger){let g=e.sourceUrl?` from ${e.sourceUrl}`:"";(0,Oa.logInfo)(e.logger,`[Store] Installed custom engine ${p.id}${g} to ${u}`)}return p}finally{a&&await st.promises.rm(o,{recursive:!0,force:!0}).catch(()=>{})}}async function PT(t={}){let e=Pe.resolve(t.installRoot??Ia()),n;try{n=await st.promises.readdir(e,{withFileTypes:!0})}catch{return[]}let r=[];for(let s of n){if(!s.isDirectory()||s.name.startsWith("."))continue;let i=Pe.join(e,s.name);Xs(e,i,"Custom engine install target");let o=Pe.join(i,An),a=s.name,c=s.name;try{let l=eu(await st.promises.readFile(o,"utf8"),o);typeof l.id=="string"&&l.id.trim()&&(a=lg(l.id)),typeof l.displayName=="string"&&l.displayName.trim()?c=l.displayName.trim():c=a}catch{}r.push({id:a,displayName:c,manifestPath:o,installDir:i})}return r.sort((s,i)=>s.id.localeCompare(i.id))}async function NT(t,e={}){let n=lg(t),r=Pe.resolve(e.installRoot??Ia()),s=Pe.join(r,n);Xs(r,s,"Custom engine uninstall target");let i;try{let o=await st.promises.lstat(s);if(!o.isDirectory()||o.isSymbolicLink())throw new Error(`Custom engine install target is not a normal directory: ${s}`);try{let a=eu(await st.promises.readFile(Pe.join(s,An),"utf8"),An);i=typeof a.displayName=="string"&&a.displayName.trim()?a.displayName.trim():void 0}catch{}}catch(o){if(o?.code==="ENOENT")return{id:n,installDir:s,removed:!1};throw o}return await st.promises.rm(s,{recursive:!0,force:!0}),e.logger&&(0,Oa.logInfo)(e.logger,`[Store] Uninstalled custom engine ${n} from ${s}`),{id:n,displayName:i,installDir:s,removed:!0}}});var Ns=S(Tn=>{"use strict";var RT=Tn&&Tn.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,s)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),CT=Tn&&Tn.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),tu=Tn&&Tn.__importStar||(function(){var t=function(e){return t=Object.getOwnPropertyNames||function(n){var r=[];for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(r[r.length]=s);return r},t(e)};return function(e){if(e&&e.__esModule)return e;var n={};if(e!=null)for(var r=t(e),s=0;s<r.length;s++)r[s]!=="default"&&RT(n,e,r[s]);return CT(n,e),n}})();Object.defineProperty(Tn,"__esModule",{value:!0});Tn.parseCustomEngineSearchPath=Ca;Tn.getCustomEngineSearchRoots=gg;Tn.discoverCustomEngineManifests=hg;Tn.resolveCustomEngineManifest=mg;Tn.tryResolveCustomEngineManifest=HT;var Na=tu(require("fs")),kT=tu(require("os")),fr=tu(require("path")),Ra=Ke(),$T=Pa(),dg="engines",fg="engine.manifest.json";function pg(t){return t.trim().toLowerCase()}function Sn(t){return typeof t=="string"&&t.trim().length>0}function Ca(t){return Array.isArray(t)?t.flatMap(e=>Ca(e)):t?.trim()?t.split(fr.delimiter).map(e=>e.trim()).filter(Boolean):[]}function DT(t){let e=new Set,n=[];for(let r of t){let s=fr.resolve(r);e.has(s)||(e.add(s),n.push(s))}return n}function LT(t,e){if(!t)return;if(typeof t!="object")throw new Error(`Invalid model config in ${e}: expected object`);let n=t;if(!Sn(n.defaultModel))throw new Error(`Invalid model config in ${e}: "defaultModel" is required`);return{defaultModel:n.defaultModel.trim(),apiKeyEnvVar:Sn(n.apiKeyEnvVar)?n.apiKeyEnvVar.trim():void 0,baseUrlEnvVar:Sn(n.baseUrlEnvVar)?n.baseUrlEnvVar.trim():void 0,openaiBaseUrlEnvVar:Sn(n.openaiBaseUrlEnvVar)?n.openaiBaseUrlEnvVar.trim():void 0}}function MT(t,e){if(!t)return{mode:"env-only"};if(typeof t!="object")throw new Error(`Invalid promptInjection config in ${e}: expected object`);let n=t,s=Sn(n.mode)?n.mode.trim():"env-only";if(s!=="none"&&s!=="env-only"&&s!=="message-suffix")throw new Error(`Invalid promptInjection config in ${e}: "mode" must be none, env-only, or message-suffix`);return{mode:s}}function GT(t,e){if(!t)return;if(typeof t!="object")throw new Error(`Invalid workspaceSync config in ${e}: expected object`);let n=t;if(!(n.enabled===!0))return{enabled:!1,dir:"",rulesFile:"",includeSkills:!1,includeRules:!1};if(!Sn(n.dir))throw new Error(`Invalid workspaceSync config in ${e}: "dir" is required when enabled`);if(!Sn(n.rulesFile))throw new Error(`Invalid workspaceSync config in ${e}: "rulesFile" is required when enabled`);let s=n.dir.trim();if(fr.isAbsolute(s)||s.includes(".."))throw new Error(`Invalid workspaceSync config in ${e}: "dir" must be a relative workspace directory`);let i=n.rulesFile.trim();if(fr.isAbsolute(i)||i.includes(".."))throw new Error(`Invalid workspaceSync config in ${e}: "rulesFile" must be a relative path`);return{enabled:!0,dir:s,rulesFile:i,includeSkills:n.includeSkills!==!1,includeRules:n.includeRules!==!1}}function UT(t,e){let n=Na.readFileSync(t,"utf8"),r=JSON.parse(n);if(!Sn(r.id))throw new Error(`Invalid custom engine manifest ${t}: "id" is required`);if(r.version!==2)throw new Error(`Invalid custom engine manifest ${t}: "version" must be 2`);if(!Sn(r.entry))throw new Error(`Invalid custom engine manifest ${t}: "entry" is required`);let s=pg(r.id),i=fr.dirname(t),o=r.entry.trim(),a=fr.isAbsolute(o)?o:fr.resolve(i,o);return{version:2,id:s,displayName:Sn(r.displayName)?r.displayName.trim():void 0,description:Sn(r.description)?r.description.trim():void 0,entry:o,entryPath:a,engineExport:Sn(r.engineExport)?r.engineExport.trim():void 0,homeEnvVar:Sn(r.homeEnvVar)?r.homeEnvVar.trim():void 0,workspaceSync:GT(r.workspaceSync,t),promptInjection:MT(r.promptInjection,t),model:LT(r.model,t),manifestPath:t,manifestDir:i,searchRoot:e}}function gg(t,e){let n=t?fr.resolve(t):void 0,r=Ca(e),s=Ca(process.env.AGENTHIPPO_CUSTOM_ENGINES_DIR??process.env.AGENTIDE_CUSTOM_ENGINES_DIR);return DT([...n?[fr.join(n,Ra.AGENTIDE_DIR_NAME,dg)]:[],...r,...s,(0,$T.getDefaultCustomEnginesInstallRoot)(),fr.join(kT.homedir(),Ra.AGENTIDE_DIR_NAME,dg)])}function hg(t,e,n){let r=[],s=new Set;for(let i of gg(t,e)){if(!Na.existsSync(i))continue;let o;try{o=Na.readdirSync(i,{withFileTypes:!0})}catch{continue}for(let a of o){if(!a.isDirectory())continue;let c=fr.join(i,a.name,fg);if(!Na.existsSync(c))continue;let l;try{l=UT(c,i)}catch(f){n?.(c,f);continue}s.has(l.id)||(s.add(l.id),r.push(l))}}return r}function mg(t,e,n,r){let s=hg(t,n,r),i=e?pg(e):void 0;if(i){let o=s.find(a=>a.id===i);if(!o){let a=s.map(c=>c.id).sort();throw new Error(a.length>0?`Custom engine "${i}" not found. Available: ${a.join(", ")}`:`Custom engine "${i}" not found. No manifests discovered under ${Ra.AGENTIDE_DIR_NAME}/engines.`)}return o}if(s.length===0)throw new Error(`No custom engines found. Add ${fg} under ${Ra.AGENTIDE_DIR_NAME}/engines/<engine-id>/`);if(s.length>1){let o=s.map(a=>a.id).sort();throw new Error(`Multiple custom engines found (${o.join(", ")}). Specify one with --engine <id>.`)}return s[0]}function HT(t,e,n,r){try{return mg(t,e,n,r)}catch{return}}});var en=S((exports,module)=>{"use strict";var __createBinding=exports&&exports.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,s)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),__setModuleDefault=exports&&exports.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),__importStar=exports&&exports.__importStar||(function(){var t=function(e){return t=Object.getOwnPropertyNames||function(n){var r=[];for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(r[r.length]=s);return r},t(e)};return function(e){if(e&&e.__esModule)return e;var n={};if(e!=null)for(var r=t(e),s=0;s<r.length;s++)r[s]!=="default"&&__createBinding(n,e,r[s]);return __setModuleDefault(n,e),n}})();Object.defineProperty(exports,"__esModule",{value:!0});exports.getAnalyticsScriptsDir=void 0;exports.logInfo=logInfo;exports.getErrorCode=getErrorCode;exports.pathExists=pathExists;exports.isDirOrSymlink=isDirOrSymlink;exports.ensureRealDirectory=ensureRealDirectory;exports.writeFileIfChanged=writeFileIfChanged;exports.copyDirRecursive=copyDirRecursive;exports.copyDirRecursiveWithTransform=copyDirRecursiveWithTransform;exports.symlinkOrCopyFile=symlinkOrCopyFile;exports.syncDirByFileLinks=syncDirByFileLinks;exports.ensureWorkspaceGitAndGitignore=ensureWorkspaceGitAndGitignore;exports.readFileSha256=readFileSha256;exports.getFileStats=getFileStats;exports.isCachedHashValid=isCachedHashValid;exports.shortSig=shortSig;exports.isLocalHttps=isLocalHttps;exports.applyLocalTlsBypass=applyLocalTlsBypass;exports.getOverrideOpenAIBaseUrl=getOverrideOpenAIBaseUrl;exports.inferModelProvider=inferModelProvider;exports.resolveApiRouting=resolveApiRouting;exports.getExplicitConfigValue=getExplicitConfigValue;exports.getAgentideEngineSettings=getAgentideEngineSettings;exports.emitStreamEvent=emitStreamEvent;exports.createIPCStreamEmitter=createIPCStreamEmitter;exports.computeTextDelta=computeTextDelta;exports.createDeferred=createDeferred;exports.stableAdditionalDirs=stableAdditionalDirs;exports.extractFilePaths=extractFilePaths;exports.isCreateCommand=isCreateCommand;exports.normalizeFileChangeKind=normalizeFileChangeKind;exports.isBinaryFile=isBinaryFile;var fs_1=require("fs"),child_process_1=require("child_process"),promises_1=require("stream/promises"),util_1=require("util"),path=__importStar(require("path")),crypto=__importStar(require("crypto")),shared_1=Sa(),branding_1=Ke(),customRegistry_1=Ns(),execFileAsync=(0,util_1.promisify)(child_process_1.execFile),_vscode;function getVscode(){if(!_vscode)try{_vscode=eval("require")("vscode")}catch{throw new Error("vscode module not available. Use ConfigProvider instead of vscode.workspace.getConfiguration")}return _vscode}function logInfo(t,e){t.appendLine?t.appendLine(e):t.info&&t.info(e)}function getErrorCode(t){return t&&typeof t=="object"?t.code:void 0}async function pathExists(t){try{return await fs_1.promises.lstat(t),!0}catch(e){if(getErrorCode(e)==="ENOENT")return!1;throw e}}async function isDirOrSymlink(t){try{let e=await fs_1.promises.lstat(t);return e.isDirectory()||e.isSymbolicLink()}catch(e){if(getErrorCode(e)==="ENOENT")return!1;throw e}}async function ensureRealDirectory(t){try{let e=await fs_1.promises.lstat(t);(e.isSymbolicLink()||!e.isDirectory())&&(await fs_1.promises.rm(t,{recursive:!0,force:!0}),await fs_1.promises.mkdir(t,{recursive:!0}))}catch(e){if(getErrorCode(e)==="ENOENT"){await fs_1.promises.mkdir(t,{recursive:!0});return}throw e}}async function writeFileIfChanged(t,e){try{if(await fs_1.promises.readFile(t,"utf8")===e)return!1}catch(n){if(getErrorCode(n)!=="ENOENT")throw n}return await fs_1.promises.mkdir(path.dirname(t),{recursive:!0}),await fs_1.promises.writeFile(t,e,"utf8"),!0}async function copyDirRecursive(t,e){await fs_1.promises.mkdir(e,{recursive:!0});let n=await fs_1.promises.readdir(t,{withFileTypes:!0});for(let r of n){let s=path.join(t,r.name),i=path.join(e,r.name);if(r.isDirectory())await copyDirRecursive(s,i);else if(r.isFile())await fs_1.promises.copyFile(s,i);else if(r.isSymbolicLink()){let o=await fs_1.promises.readlink(s),a=path.isAbsolute(o)?o:path.resolve(path.dirname(s),o);(await fs_1.promises.stat(a)).isDirectory()?await copyDirRecursive(a,i):await fs_1.promises.copyFile(a,i)}}}async function copyDirRecursiveWithTransform(t,e,n){await fs_1.promises.mkdir(e,{recursive:!0});let r=await fs_1.promises.readdir(t,{withFileTypes:!0});for(let s of r){let i=path.join(t,s.name),o=path.join(e,s.name);if(s.isDirectory())await copyDirRecursiveWithTransform(i,o,n);else if(s.isFile())if(s.name.toLowerCase().endsWith(".md")){let c=await fs_1.promises.readFile(i,"utf8");await fs_1.promises.writeFile(o,n(c),"utf8")}else await fs_1.promises.copyFile(i,o);else if(s.isSymbolicLink()){let a=await fs_1.promises.readlink(i),c=path.isAbsolute(a)?a:path.resolve(path.dirname(i),a);if((await fs_1.promises.stat(c)).isDirectory())await copyDirRecursiveWithTransform(c,o,n);else if(s.name.toLowerCase().endsWith(".md")){let u=await fs_1.promises.readFile(c,"utf8");await fs_1.promises.writeFile(o,n(u),"utf8")}else await fs_1.promises.copyFile(c,o)}}}async function symlinkOrCopyFile(t,e,n,r,s){let i=s?.force??!1;try{if((await fs_1.promises.lstat(e)).isSymbolicLink()){try{let a=await fs_1.promises.readlink(e),c=path.isAbsolute(a)?a:path.resolve(path.dirname(e),a);if(path.resolve(c)===path.resolve(t))return}catch{}await fs_1.promises.unlink(e)}else if(i)await fs_1.promises.rm(e,{recursive:!0,force:!0});else return}catch(o){if(getErrorCode(o)!=="ENOENT")throw o}if(await fs_1.promises.mkdir(path.dirname(e),{recursive:!0}),path.resolve(t)!==path.resolve(e))try{await fs_1.promises.symlink(t,e,"file"),logInfo(n,`[AgentIDE] Linked ${r} (symlink): ${e} -> ${t}`)}catch{await fs_1.promises.copyFile(t,e),logInfo(n,`[AgentIDE] Linked ${r} (copy fallback): ${e}`)}}async function syncDirByFileLinks(t,e,n,r){await ensureRealDirectory(e);let s=new Set,i=new Map,o=async(u,d)=>{let p;try{p=await fs_1.promises.readdir(u,{withFileTypes:!0})}catch(g){if(getErrorCode(g)==="ENOENT")return;throw g}for(let g of p){if(g.name.startsWith("."))continue;let m=path.join(u,g.name),h=d?path.join(d,g.name):g.name;if(g.isDirectory())s.add(h),await o(m,h);else if(g.isFile())i.set(h,m);else if(g.isSymbolicLink())try{let E=await fs_1.promises.readlink(m),_=path.isAbsolute(E)?E:path.resolve(path.dirname(m),E);(await fs_1.promises.stat(_)).isDirectory()?(s.add(h),await o(_,h)):i.set(h,_)}catch(E){let _=getErrorCode(E);if(_==="ENOENT"||_==="ELOOP")continue;throw E}}};await o(t,"");let a=Array.from(s).sort((u,d)=>u.split(path.sep).length-d.split(path.sep).length);for(let u of a)await ensureRealDirectory(path.join(e,u));for(let[u,d]of i.entries())await symlinkOrCopyFile(d,path.join(e,u),n,`${r}/${u}`.replace(/\\/g,"/"),{force:!0});let c=new Set(i.keys()),l=async(u,d)=>{let p;try{p=await fs_1.promises.readdir(u,{withFileTypes:!0})}catch(g){if(getErrorCode(g)==="ENOENT")return;throw g}for(let g of p){if(g.name.startsWith("."))continue;let m=path.join(u,g.name),h=d?path.join(d,g.name):g.name,E=path.join(t,h);if(g.isDirectory())await l(m,h);else if(g.isFile()&&!g.isSymbolicLink()&&!c.has(h))try{await fs_1.promises.mkdir(path.dirname(E),{recursive:!0}),await fs_1.promises.copyFile(m,E),logInfo(n,`[AgentIDE] Copied new file to source: ${r}/${h}`.replace(/\\/g,"/")),i.set(h,E)}catch(_){logInfo(n,`[AgentIDE] Warning: failed to copy back ${h}: ${_ instanceof Error?_.message:String(_)}`)}}};await l(e,"");for(let[u,d]of i.entries()){let p=path.join(e,u);try{let g=await fs_1.promises.lstat(p);g.isFile()&&!g.isSymbolicLink()&&(await fs_1.promises.rm(p,{force:!0}),await symlinkOrCopyFile(d,p,n,`${r}/${u}`.replace(/\\/g,"/"),{force:!0}))}catch{}}let f=async(u,d)=>{let p;try{p=await fs_1.promises.readdir(u,{withFileTypes:!0})}catch(g){if(getErrorCode(g)==="ENOENT")return;throw g}for(let g of p){if(g.name.startsWith("."))continue;let m=path.join(u,g.name),h=d?path.join(d,g.name):g.name;g.isDirectory()?await f(m,h):g.isSymbolicLink()&&(c.has(h)||await fs_1.promises.rm(m,{force:!0}))}};await f(e,"")}function getManagedWorkspaceDirs(t,e){let n=Object.values(shared_1.AGENT_ENGINES).map(s=>s.workspaceDir),r=(0,customRegistry_1.discoverCustomEngineManifests)(t,e).filter(s=>s.workspaceSync?.enabled).map(s=>s.workspaceSync.dir);return[...new Set([...n,...r])]}async function ensureWorkspaceGitAndGitignore(t,e,n){let r=path.join(t,".git");if(!await pathExists(r))try{await execFileAsync("git",["init"],{cwd:t}),logInfo(e,`[AgentIDE] Initialized git repository in ${t}`)}catch(m){logInfo(e,`[AgentIDE] Note: Could not initialize git in ${t}: ${m instanceof Error?m.message:String(m)}`)}let i=path.join(t,".gitignore"),o=getManagedWorkspaceDirs(t,n?.extraSearchPath),a=[`# ${branding_1.AGENTIDE_BRAND_NAME} (managed)`,`# These directories are managed by ${branding_1.AGENTIDE_BRAND_NAME} and should not be committed.`,...o],c="";try{c=await fs_1.promises.readFile(i,"utf8")}catch(m){if(getErrorCode(m)!=="ENOENT"){logInfo(e,`[AgentIDE] Warning: failed to read root .gitignore: ${m instanceof Error?m.message:String(m)}`);return}}let l=c.split(`
30
+ `)}async function ES(t){let e=kr.join(t,Ll,qp);if(!await ha(e))return null;try{return await Oi.promises.readFile(e,"utf-8")}catch{return null}}async function _S(t){let e=kr.join(t,Ll);if(!await ha(e))return[];let n=[],r;try{r=await Oi.promises.readdir(e,{withFileTypes:!0})}catch{return[]}for(let s of r){if(!s.isDirectory())continue;let i=s.name,o=await Yp(i,e);if(!o)continue;let a=kr.join(e,i);n.push({name:o.name??i,label:o.label??i,description:o.description,command:o.command,args:Gl(o.args,a),env:ga(o.env)})}return n}xe.AGENTHIPPO_MCP_SERVERS_ENV="AGENTHIPPO_MCP_SERVERS";function Ul(t,e){let n={...t.headers??{}};if(t.bearerTokenEnv){let r=e[t.bearerTokenEnv]?.trim();r&&(n.Authorization=`Bearer ${r}`)}return Object.keys(n).length>0?n:void 0}var yS=/^[A-Za-z_][A-Za-z0-9_]*$/;function wS(t,e){let n=t.bearerTokenEnv;if(n&&!yS.test(n))return Ul(t,e);let r={...t.headers??{}};return n&&(r.Authorization=`Bearer \${${n}}`),Object.keys(r).length>0?r:void 0}function AS(t,e){let n={};for(let r of t){if(r.url){let s=Ul(r,e??process.env);n[r.name]={type:"http",url:r.url,...s?{headers:s}:{}};continue}n[r.name]={command:r.command,args:r.args,...r.env&&Object.keys(r.env).length>0?{env:r.env}:{}}}return n}function SS(t){if(Object.keys(t).length!==0)return JSON.stringify(t)}function TS(t){if(t?.trim())try{let e=JSON.parse(t);return!e||typeof e!="object"||Array.isArray(e)?void 0:e}catch{return}}async function ha(t){try{return await Oi.promises.access(t),!0}catch{return!1}}});var zp=S(Ii=>{"use strict";Object.defineProperty(Ii,"__esModule",{value:!0});Ii.NoOpLogger=Ii.ConsoleLogger=void 0;var Hl=class{prefix;constructor(e="[AgentIDE]"){this.prefix=e}debug(e){console.debug(`${this.prefix} ${e}`)}info(e){console.log(`${this.prefix} ${e}`)}warn(e){console.warn(`${this.prefix} Warning: ${e}`)}error(e,n){console.error(`${this.prefix} Error: ${e}${n?`: ${n.message}`:""}`)}};Ii.ConsoleLogger=Hl;var jl=class{debug(e){}info(e){}warn(e){}error(e,n){}};Ii.NoOpLogger=jl});var Qp=S(Ps=>{"use strict";Object.defineProperty(Ps,"__esModule",{value:!0});Ps.CLIPermissionHandler=Ps.AutoDenyPermissionHandler=Ps.AutoApprovePermissionHandler=void 0;var xl=class{async requestPermission(e){return{behavior:"allow"}}};Ps.AutoApprovePermissionHandler=xl;var Bl=class{message;constructor(e="All tool requests are denied"){this.message=e}async requestPermission(e){return{behavior:"deny",message:this.message}}};Ps.AutoDenyPermissionHandler=Bl;var Fl=class{readline;async requestPermission(e){return this.readline||(this.readline=require("readline")),new Promise(n=>{let r=this.readline.createInterface({input:process.stdin,output:process.stdout}),s=e.toolInput?`${e.toolName}: ${JSON.stringify(e.toolInput).slice(0,100)}`:e.toolName;console.log(`
31
+ \u26A0\uFE0F Tool permission requested: ${s}`),r.question("Allow? (y/n): ",i=>{r.close();let o=i.toLowerCase().startsWith("y");n(o?{behavior:"allow"}:{behavior:"deny",message:"User denied permission"})})})}};Ps.CLIPermissionHandler=Fl});var Zp=S(ma=>{"use strict";Object.defineProperty(ma,"__esModule",{value:!0});ma.NoOpEditTracker=void 0;var Vl=class{appliesEdits=!1;async startTracking(e,n){}async stopTracking(e,n){}async applyEdit(e,n,r,s){}};ma.NoOpEditTracker=Vl});var eg=S(cn=>{"use strict";var bS=cn&&cn.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,s)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),vS=cn&&cn.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),OS=cn&&cn.__importStar||(function(){var t=function(e){return t=Object.getOwnPropertyNames||function(n){var r=[];for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(r[r.length]=s);return r},t(e)};return function(e){if(e&&e.__esModule)return e;var n={};if(e!=null)for(var r=t(e),s=0;s<r.length;s++)r[s]!=="default"&&bS(n,e,r[s]);return vS(n,e),n}})();Object.defineProperty(cn,"__esModule",{value:!0});cn.DirectorySessionStore=cn.FileSessionStore=cn.MemorySessionStore=void 0;var Zt=require("fs"),Ea=OS(require("path")),IS=require("crypto"),Wl=class{store=new Map;get(e){return this.store.get(e)}async set(e,n){this.store.set(e,n)}clear(){this.store.clear()}};cn.MemorySessionStore=Wl;var Kl=class{store={};loaded=!1;filePath;constructor(e){this.filePath=e}async load(){if(!this.loaded){try{let e=await Zt.promises.readFile(this.filePath,"utf-8");this.store=JSON.parse(e)}catch(e){e.code!=="ENOENT"&&console.warn(`[FileSessionStore] Failed to load ${this.filePath}: ${e}`),this.store={}}this.loaded=!0}}get(e){return this.loaded||this.loadSync(),this.store[e]}async set(e,n){this.store[e]=n,await this.flush()}async clear(){this.store={},await this.flush()}async flush(){let e=Ea.dirname(this.filePath);await Zt.promises.mkdir(e,{recursive:!0});let n=`${this.filePath}.tmp.${Date.now()}`,r=JSON.stringify(this.store,null,2);try{await Zt.promises.writeFile(n,r,"utf-8"),await Zt.promises.rename(n,this.filePath)}catch(s){try{await Zt.promises.unlink(n)}catch{}throw s}}loadSync(){if(!this.loaded){try{let e=(0,Zt.readFileSync)(this.filePath,"utf-8");this.store=JSON.parse(e)}catch(e){e.code!=="ENOENT"&&console.warn(`[FileSessionStore] Failed to load ${this.filePath}: ${e}`),this.store={}}this.loaded=!0}}};cn.FileSessionStore=Kl;var ql=class{dir;entries={};serialized=new Map;files=new Map;loaded=!1;constructor(e){this.dir=e}get(e){return this.loaded||this.loadSync(),this.entries}async set(e,n){this.loaded||this.loadSync();let r=n&&typeof n=="object"?n:{};await Zt.promises.mkdir(this.dir,{recursive:!0});for(let[s,i]of Object.entries(r)){let o=JSON.stringify(i);if(this.serialized.get(s)===o)continue;let a=this.files.get(s)??`${this.fileNameFor(s)}.json`;await this.writeAtomic(a,JSON.stringify({key:s,value:i},null,2)),this.files.set(s,a),this.serialized.set(s,o)}for(let s of[...this.serialized.keys()]){if(Object.prototype.hasOwnProperty.call(r,s))continue;let i=this.files.get(s);if(i)try{await Zt.promises.unlink(Ea.join(this.dir,i))}catch{}this.files.delete(s),this.serialized.delete(s)}this.entries={...r}}fileNameFor(e){return(0,IS.createHash)("sha256").update(e).digest("hex").slice(0,40)}async writeAtomic(e,n){let r=Ea.join(this.dir,e),s=`${r}.tmp.${process.pid}.${Date.now()}`;try{await Zt.promises.writeFile(s,n,"utf-8"),await Zt.promises.rename(s,r)}catch(i){try{await Zt.promises.unlink(s)}catch{}throw i}}loadSync(){if(this.loaded)return;this.loaded=!0,this.migrateLegacySingleFileSync();let e;try{e=(0,Zt.readdirSync)(this.dir).filter(n=>n.endsWith(".json"))}catch(n){n.code!=="ENOENT"&&console.warn(`[DirectorySessionStore] Failed to list ${this.dir}: ${n}`);return}for(let n of e)try{let r=(0,Zt.readFileSync)(Ea.join(this.dir,n),"utf-8"),s=JSON.parse(r);s&&typeof s.key=="string"&&(this.entries[s.key]=s.value,this.serialized.set(s.key,JSON.stringify(s.value)),this.files.set(s.key,n))}catch(r){console.warn(`[DirectorySessionStore] Skipping unreadable ${n}: ${r}`)}}migrateLegacySingleFileSync(){let e=!0;try{(0,Zt.readdirSync)(this.dir)}catch{e=!1}if(e)return;let n=`${this.dir}.json`,r;try{r=JSON.parse((0,Zt.readFileSync)(n,"utf-8"))}catch{return}for(let s of Object.values(r))if(s&&typeof s=="object")for(let[i,o]of Object.entries(s))this.entries[i]=o}};cn.DirectorySessionStore=ql});var tg=S(_a=>{"use strict";Object.defineProperty(_a,"__esModule",{value:!0});_a.StaticConfigProvider=void 0;var Yl=class{config;customProviders;engineSettings;constructor(e={},n={},r={}){this.config=e,this.customProviders=n,this.engineSettings=r}get(e,n,r){let s=`${e}.${n}`,i=this.config[s];return i!==void 0?i:r}getCustomProviders(){return this.customProviders}getEngineSettings(){return this.engineSettings}};_a.StaticConfigProvider=Yl});var zl=S(Je=>{"use strict";Object.defineProperty(Je,"__esModule",{value:!0});Je.StaticConfigProvider=Je.DirectorySessionStore=Je.FileSessionStore=Je.MemorySessionStore=Je.NoOpEditTracker=Je.CLIPermissionHandler=Je.AutoDenyPermissionHandler=Je.AutoApprovePermissionHandler=Je.NoOpLogger=Je.ConsoleLogger=void 0;var ng=zp();Object.defineProperty(Je,"ConsoleLogger",{enumerable:!0,get:function(){return ng.ConsoleLogger}});Object.defineProperty(Je,"NoOpLogger",{enumerable:!0,get:function(){return ng.NoOpLogger}});var Xl=Qp();Object.defineProperty(Je,"AutoApprovePermissionHandler",{enumerable:!0,get:function(){return Xl.AutoApprovePermissionHandler}});Object.defineProperty(Je,"AutoDenyPermissionHandler",{enumerable:!0,get:function(){return Xl.AutoDenyPermissionHandler}});Object.defineProperty(Je,"CLIPermissionHandler",{enumerable:!0,get:function(){return Xl.CLIPermissionHandler}});var PS=Zp();Object.defineProperty(Je,"NoOpEditTracker",{enumerable:!0,get:function(){return PS.NoOpEditTracker}});var Jl=eg();Object.defineProperty(Je,"MemorySessionStore",{enumerable:!0,get:function(){return Jl.MemorySessionStore}});Object.defineProperty(Je,"FileSessionStore",{enumerable:!0,get:function(){return Jl.FileSessionStore}});Object.defineProperty(Je,"DirectorySessionStore",{enumerable:!0,get:function(){return Jl.DirectorySessionStore}});var NS=tg();Object.defineProperty(Je,"StaticConfigProvider",{enumerable:!0,get:function(){return NS.StaticConfigProvider}})});var Pi=S(ft=>{"use strict";Object.defineProperty(ft,"__esModule",{value:!0});ft.RAW_IDS_ENV=ft.ID_SALT_ENV=ft.CONTENT_CAPTURE_ENV=void 0;ft.isContentCaptureEnabled=ig;ft.resetPrivacyAnnouncementsForTest=kS;ft.hashIdentity=DS;ft.digestContent=og;ft.describeContent=LS;var rg=require("crypto");ft.CONTENT_CAPTURE_ENV="AGENTHIPPO_EVIDENCE_CONTENT_CAPTURE";ft.ID_SALT_ENV="AGENTHIPPO_EVIDENCE_ID_SALT";ft.RAW_IDS_ENV="AGENTHIPPO_EVIDENCE_RAW_IDS";var RS="agenthippo-evidence-unsalted",CS=new Set(["1","true","yes","on"]);function sg(t){return CS.has((t??"").trim().toLowerCase())}var Ql=!1,Zl=!1;function ig(t=process.env){let e=sg(t[ft.CONTENT_CAPTURE_ENV]);return Ql||(Ql=!0,console.warn(e?`[evidence] CONTENT CAPTURE IS ON \u2014 prompts, completions and tool I/O are recorded in evidence (${ft.CONTENT_CAPTURE_ENV} is set). Unset it for metadata-only evidence.`:`[evidence] content capture off \u2014 tool I/O is recorded as sha256 + length only. Set ${ft.CONTENT_CAPTURE_ENV}=1 to restore full previews.`)),e}function kS(){Ql=!1,Zl=!1}function $S(t){let e=t[ft.ID_SALT_ENV]?.trim();return e||(Zl||(Zl=!0,console.warn(`[evidence] ${ft.ID_SALT_ENV} is not set \u2014 identity hashes use a public constant salt. They pseudonymise, but a known address can still be confirmed by hashing it. Set the same secret on every instance whose evidence is joined.`)),RS)}function DS(t,e=process.env){let n=t?.trim();return n?sg(e[ft.RAW_IDS_ENV])?n:`anon_${(0,rg.createHash)("sha256").update(`${$S(e)}\0${n}`).digest("hex").slice(0,32)}`:void 0}function og(t){return{sha256:(0,rg.createHash)("sha256").update(t,"utf8").digest("hex"),length:Buffer.byteLength(t,"utf8")}}function LS(t,e,n=500,r=process.env){if(e===void 0)return{};let s=og(e),i={[`${t}_sha256`]:s.sha256,[`${t}_length`]:s.length};return ig(r)&&(i[`${t}Preview`]=e.slice(0,n)),i}});var ya=S(Se=>{"use strict";Object.defineProperty(Se,"__esModule",{value:!0});Se.ANTHROPIC_SETUP_TOKEN_PREFIX=Se.PROVIDERS=void 0;Se.getProvider=MS;Se.requiresApiKey=GS;Se.isLocalProvider=US;Se.getAllProviderIds=HS;Se.getCloudProviders=jS;Se.getLocalProviders=xS;Se.getApiKeyProviders=BS;Se.requiresBaseUrl=FS;Se.getGatewayProviders=VS;Se.isGatewayProvider=WS;Se.isAnthropicProviderFamily=KS;Se.normalizeAnthropicSetupToken=qS;Se.isAnthropicSetupToken=YS;Se.providerNotSupportAnthropicApi=XS;Se.PROVIDERS={openai:{id:"openai",displayName:"OpenAI",defaultEndpoint:"https://api.openai.com/v1",requiresApiKey:!0,showInAddApiKeyUI:!0,notSupportAnthropicApi:!0},"openai-codex":{id:"openai-codex",displayName:"OpenAI Codex (ChatGPT OAuth)",defaultEndpoint:"https://chatgpt.com/backend-api/codex",requiresApiKey:!0,description:"Use your ChatGPT/Codex subscription via native OAuth",showInAddApiKeyUI:!0,notSupportAnthropicApi:!0},anthropic:{id:"anthropic",displayName:"Anthropic",defaultEndpoint:"https://api.anthropic.com/v1",endpointSettingKey:"agentide.providers.anthropic.baseUrl",requiresApiKey:!0,apiKeyHeader:"x-api-key",staticHeaders:{"anthropic-version":"2023-06-01"},headerSettingKeys:{"anthropic-version":"agentide.providers.anthropic.version"},showInAddApiKeyUI:!0},"anthropic-setup-token":{id:"anthropic-setup-token",displayName:"Anthropic (Claude Subscription)",defaultEndpoint:"https://api.anthropic.com/v1",endpointSettingKey:"agentide.providers.anthropic.baseUrl",requiresApiKey:!0,apiKeyHeader:"x-api-key",staticHeaders:{"anthropic-version":"2023-06-01"},headerSettingKeys:{"anthropic-version":"agentide.providers.anthropic.version"},description:'Use Claude subscription setup-token from "claude setup-token"',showInAddApiKeyUI:!0},openrouter:{id:"openrouter",displayName:"OpenRouter",defaultEndpoint:"https://openrouter.ai/api/v1",requiresApiKey:!0,description:"Fast model proxy via openrouter.ai that works with all agents",showInAddApiKeyUI:!0,isGateway:!0},litellm:{id:"litellm",displayName:"LiteLLM",endpointSettingKey:"agentide.providers.litellm.baseUrl",requiresApiKey:!0,description:"local adapter for agents to work with Spotlight and all models from OpenAI, Anthropic, Ollama etc.",showInAddApiKeyUI:!0,isGateway:!0,deferMissingApiKey:!0},ollama:{id:"ollama",displayName:"Ollama",defaultEndpoint:"http://localhost:11434/v1",requiresApiKey:!1,enabledSettingKey:"agentide.local.ollama.enabled",defaultEnabled:!0,placeholderApiKey:"ollama",description:"Local LLM server",showInAddApiKeyUI:!1,notSupportAnthropicApi:!0},agenthippo:{id:"agenthippo",displayName:"AgentHippo Gateway",defaultEndpoint:"https://gateway.agenthippo.ai/v1",endpointSettingKey:"agentide.AgentHippoModelGateway.url",requiresApiKey:!0,description:"AgentHippo managed gateway \u2014 uses account JWT, picks model automatically",showInAddApiKeyUI:!1,isGateway:!0,staticHeaders:{"x-agenthippo-source":"chat-ui"},credentialRefreshCommand:"agentide.auth.refreshToken",deferMissingApiKey:!0}};function MS(t){return Se.PROVIDERS[t]}function GS(t){return Se.PROVIDERS[t]?.requiresApiKey??!0}function US(t){let e=Se.PROVIDERS[t];return e?!e.requiresApiKey:!1}function HS(){return Object.keys(Se.PROVIDERS)}function jS(){return Object.values(Se.PROVIDERS).filter(t=>t.requiresApiKey)}function xS(){return Object.values(Se.PROVIDERS).filter(t=>!t.requiresApiKey)}function BS(){return Object.values(Se.PROVIDERS).filter(t=>t.showInAddApiKeyUI===!0)}function FS(t){let e=Se.PROVIDERS[t];return e?!!e.endpointSettingKey&&!e.defaultEndpoint:!1}function VS(){return Object.values(Se.PROVIDERS).filter(t=>t.isGateway)}function WS(t){return Se.PROVIDERS[t]?.isGateway??!1}function KS(t){return t==="anthropic"||t==="anthropic-setup-token"}Se.ANTHROPIC_SETUP_TOKEN_PREFIX="sk-ant-oat01-";function qS(t){return t.replace(/\s+/g,"").trim()}function YS(t){return typeof t=="string"&&t.trim().startsWith(Se.ANTHROPIC_SETUP_TOKEN_PREFIX)}function XS(t,e){let n=Se.PROVIDERS[t];return n?n.notSupportAnthropicApi??!1:e?.[t]?.notSupportAnthropicApi===!0}});var wa=S($e=>{"use strict";Object.defineProperty($e,"__esModule",{value:!0});$e.REGISTRY_KEY_SEPARATOR=$e.BUILTIN_MODELS=void 0;$e.getRegistryKey=ag;$e.parseRegistryKey=JS;$e.isCompositeKey=zS;$e.getModel=QS;$e.getModelByRegistryKey=ZS;$e.getModelsForProvider=eT;$e.getRecommendedModels=tT;$e.getModelsWithCapability=nT;$e.getActiveModels=rT;$e.resolveModelAlias=sT;$e.BUILTIN_MODELS=[{id:"ah-auto",name:"Auto",provider:"agenthippo",contextWindow:2e5,maxOutputTokens:8192,capabilities:["chat","vision","function-calling","code"],description:"Managed gateway \u2014 routed through AgentHippo using your account, not your own API keys",recommended:!0}];$e.REGISTRY_KEY_SEPARATOR="::";function ag(t,e){return`${t}${$e.REGISTRY_KEY_SEPARATOR}${e}`}function JS(t){let e=t.indexOf($e.REGISTRY_KEY_SEPARATOR);if(e!==-1)return{providerId:t.substring(0,e),modelId:t.substring(e+$e.REGISTRY_KEY_SEPARATOR.length)}}function zS(t){return t.includes($e.REGISTRY_KEY_SEPARATOR)}function QS(t){return $e.BUILTIN_MODELS.find(e=>e.id===t)}function ZS(t){return $e.BUILTIN_MODELS.find(e=>ag(e.provider,e.id)===t)}function eT(t){return $e.BUILTIN_MODELS.filter(e=>e.provider===t)}function tT(){return $e.BUILTIN_MODELS.filter(t=>t.recommended===!0)}function nT(t){return $e.BUILTIN_MODELS.filter(e=>e.capabilities.includes(t))}function rT(){return $e.BUILTIN_MODELS.filter(t=>!t.deprecated)}function sT(t){if(!t)return t;let e=t.toLowerCase().trim();return $e.BUILTIN_MODELS.find(r=>r.id.toLowerCase()===e)?.id??t}});var eu=S(rt=>{"use strict";Object.defineProperty(rt,"__esModule",{value:!0});rt.AGENT_ENGINES=void 0;rt.getAgentEngine=iT;rt.getAllAgentEngines=oT;rt.getAllAgentEngineIds=aT;rt.getCompatibleProviders=cT;rt.getEnginesCompatibleWithProvider=lT;rt.isEngineCompatibleWithProvider=uT;rt.getEngineRulesFile=dT;rt.getEngineWorkspaceDir=fT;var os=ya();rt.AGENT_ENGINES={codex:{id:"codex",displayName:"Codex",description:"OpenAI Codex - code generation agent",icon:"sparkle",nativeProvider:"openai",workspaceDir:".codex",rulesFile:"AGENTS.md",configEnvVar:"CODEX_HOME",managedPaths:["skills","config.toml","agentide.runtime.md"]},claude:{id:"claude",displayName:"Claude",description:"Anthropic Claude - agentic coding assistant",icon:"beaker",nativeProvider:"anthropic",workspaceDir:".claude",rulesFile:"CLAUDE.md",configEnvVar:"CLAUDE_CONFIG_DIR"}};function iT(t){return rt.AGENT_ENGINES[t]}function oT(){return Object.values(rt.AGENT_ENGINES)}function aT(){return Object.keys(rt.AGENT_ENGINES)}function cT(t){let e=rt.AGENT_ENGINES[t];if(!e)return[];let n=[e.nativeProvider];for(let[r,s]of Object.entries(os.PROVIDERS))if(!n.includes(r)){if(s.isGateway){n.push(r);continue}e.nativeProvider==="openai"&&!(0,os.isAnthropicProviderFamily)(r)&&n.push(r),e.nativeProvider==="anthropic"&&(0,os.isAnthropicProviderFamily)(r)&&n.push(r)}return n}function lT(t){let e=os.PROVIDERS[t];return e?e.isGateway?Object.values(rt.AGENT_ENGINES):Object.values(rt.AGENT_ENGINES).filter(n=>!!(n.nativeProvider===t||n.nativeProvider==="openai"&&!(0,os.isAnthropicProviderFamily)(t)||n.nativeProvider==="anthropic"&&(0,os.isAnthropicProviderFamily)(t))):[]}function uT(t,e){let n=rt.AGENT_ENGINES[t];return n?!!(n.nativeProvider===e||(0,os.isGatewayProvider)(e)||n.nativeProvider==="openai"&&!(0,os.isAnthropicProviderFamily)(e)||n.nativeProvider==="anthropic"&&(0,os.isAnthropicProviderFamily)(e)):!1}function dT(t){return rt.AGENT_ENGINES[t]?.rulesFile}function fT(t){return rt.AGENT_ENGINES[t]?.workspaceDir}});var Ta=S(U=>{"use strict";Object.defineProperty(U,"__esModule",{value:!0});U.getEngineWorkspaceDir=U.getEngineRulesFile=U.isEngineCompatibleWithProvider=U.getEnginesCompatibleWithProvider=U.getCompatibleProviders=U.getAllAgentEngineIds=U.getAllAgentEngines=U.getAgentEngine=U.AGENT_ENGINES=U.getActiveModels=U.getModelsWithCapability=U.getRecommendedModels=U.getModelsForProvider=U.getModel=U.getModelByRegistryKey=U.isCompositeKey=U.parseRegistryKey=U.getRegistryKey=U.REGISTRY_KEY_SEPARATOR=U.BUILTIN_MODELS=U.providerNotSupportAnthropicApi=U.isAnthropicSetupToken=U.normalizeAnthropicSetupToken=U.ANTHROPIC_SETUP_TOKEN_PREFIX=U.isAnthropicProviderFamily=U.requiresBaseUrl=U.getApiKeyProviders=U.getLocalProviders=U.getCloudProviders=U.getAllProviderIds=U.isLocalProvider=U.requiresApiKey=U.getProvider=U.PROVIDERS=void 0;U.getProviderForModel=gT;U.getEngineForModel=hT;U.getModelsForEngine=mT;U.isModelFromProvider=ET;var ln=ya();Object.defineProperty(U,"PROVIDERS",{enumerable:!0,get:function(){return ln.PROVIDERS}});Object.defineProperty(U,"getProvider",{enumerable:!0,get:function(){return ln.getProvider}});Object.defineProperty(U,"requiresApiKey",{enumerable:!0,get:function(){return ln.requiresApiKey}});Object.defineProperty(U,"isLocalProvider",{enumerable:!0,get:function(){return ln.isLocalProvider}});Object.defineProperty(U,"getAllProviderIds",{enumerable:!0,get:function(){return ln.getAllProviderIds}});Object.defineProperty(U,"getCloudProviders",{enumerable:!0,get:function(){return ln.getCloudProviders}});Object.defineProperty(U,"getLocalProviders",{enumerable:!0,get:function(){return ln.getLocalProviders}});Object.defineProperty(U,"getApiKeyProviders",{enumerable:!0,get:function(){return ln.getApiKeyProviders}});Object.defineProperty(U,"requiresBaseUrl",{enumerable:!0,get:function(){return ln.requiresBaseUrl}});Object.defineProperty(U,"isAnthropicProviderFamily",{enumerable:!0,get:function(){return ln.isAnthropicProviderFamily}});Object.defineProperty(U,"ANTHROPIC_SETUP_TOKEN_PREFIX",{enumerable:!0,get:function(){return ln.ANTHROPIC_SETUP_TOKEN_PREFIX}});Object.defineProperty(U,"normalizeAnthropicSetupToken",{enumerable:!0,get:function(){return ln.normalizeAnthropicSetupToken}});Object.defineProperty(U,"isAnthropicSetupToken",{enumerable:!0,get:function(){return ln.isAnthropicSetupToken}});Object.defineProperty(U,"providerNotSupportAnthropicApi",{enumerable:!0,get:function(){return ln.providerNotSupportAnthropicApi}});var dr=wa();Object.defineProperty(U,"BUILTIN_MODELS",{enumerable:!0,get:function(){return dr.BUILTIN_MODELS}});Object.defineProperty(U,"REGISTRY_KEY_SEPARATOR",{enumerable:!0,get:function(){return dr.REGISTRY_KEY_SEPARATOR}});Object.defineProperty(U,"getRegistryKey",{enumerable:!0,get:function(){return dr.getRegistryKey}});Object.defineProperty(U,"parseRegistryKey",{enumerable:!0,get:function(){return dr.parseRegistryKey}});Object.defineProperty(U,"isCompositeKey",{enumerable:!0,get:function(){return dr.isCompositeKey}});Object.defineProperty(U,"getModelByRegistryKey",{enumerable:!0,get:function(){return dr.getModelByRegistryKey}});Object.defineProperty(U,"getModel",{enumerable:!0,get:function(){return dr.getModel}});Object.defineProperty(U,"getModelsForProvider",{enumerable:!0,get:function(){return dr.getModelsForProvider}});Object.defineProperty(U,"getRecommendedModels",{enumerable:!0,get:function(){return dr.getRecommendedModels}});Object.defineProperty(U,"getModelsWithCapability",{enumerable:!0,get:function(){return dr.getModelsWithCapability}});Object.defineProperty(U,"getActiveModels",{enumerable:!0,get:function(){return dr.getActiveModels}});var as=eu();Object.defineProperty(U,"AGENT_ENGINES",{enumerable:!0,get:function(){return as.AGENT_ENGINES}});Object.defineProperty(U,"getAgentEngine",{enumerable:!0,get:function(){return as.getAgentEngine}});Object.defineProperty(U,"getAllAgentEngines",{enumerable:!0,get:function(){return as.getAllAgentEngines}});Object.defineProperty(U,"getAllAgentEngineIds",{enumerable:!0,get:function(){return as.getAllAgentEngineIds}});Object.defineProperty(U,"getCompatibleProviders",{enumerable:!0,get:function(){return as.getCompatibleProviders}});Object.defineProperty(U,"getEnginesCompatibleWithProvider",{enumerable:!0,get:function(){return as.getEnginesCompatibleWithProvider}});Object.defineProperty(U,"isEngineCompatibleWithProvider",{enumerable:!0,get:function(){return as.isEngineCompatibleWithProvider}});Object.defineProperty(U,"getEngineRulesFile",{enumerable:!0,get:function(){return as.getEngineRulesFile}});Object.defineProperty(U,"getEngineWorkspaceDir",{enumerable:!0,get:function(){return as.getEngineWorkspaceDir}});var pT=ya(),Sa=wa(),Aa=eu();function gT(t){let e=Sa.BUILTIN_MODELS.find(n=>n.id===t);return e?pT.PROVIDERS[e.provider]:void 0}function hT(t){let e=Sa.BUILTIN_MODELS.find(n=>n.id===t);if(e)return Object.values(Aa.AGENT_ENGINES).find(n=>(0,Aa.isEngineCompatibleWithProvider)(n.id,e.provider))}function mT(t){let e=Aa.AGENT_ENGINES[t];return e?Sa.BUILTIN_MODELS.filter(n=>(0,Aa.isEngineCompatibleWithProvider)(e.id,n.provider)):[]}function ET(t,e){return Sa.BUILTIN_MODELS.find(r=>r.id===t)?.provider===e}});var Na=S(jn=>{"use strict";var _T=jn&&jn.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,s)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),yT=jn&&jn.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),cg=jn&&jn.__importStar||(function(){var t=function(e){return t=Object.getOwnPropertyNames||function(n){var r=[];for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(r[r.length]=s);return r},t(e)};return function(e){if(e&&e.__esModule)return e;var n={};if(e!=null)for(var r=t(e),s=0;s<r.length;s++)r[s]!=="default"&&_T(n,e,r[s]);return yT(n,e),n}})();Object.defineProperty(jn,"__esModule",{value:!0});jn.getDefaultCustomEnginesInstallRoot=Pa;jn.installCustomEngineFromFiles=CT;jn.listInstalledCustomEngines=kT;jn.uninstallCustomEngine=$T;var wT=require("child_process"),st=require("fs"),AT=cg(require("os")),Pe=cg(require("path")),ST=require("util"),TT=Ke(),Ia=en(),bT=(0,ST.promisify)(wT.execFile),An="engine.manifest.json";function Pa(){return Pe.join(process.env.AGENT_HOME_DIR||process.env.AGENTHIPPO_HOME||Pe.join(AT.homedir(),TT.AGENTIDE_DIR_NAME),"engines")}function lg(t){let e=t.replace(/\\/g,"/").trim().replace(/^\.\//,"");if(!e||e.includes("\0"))throw new Error(`Invalid engine package path: ${t}`);if(e.startsWith("/")||/^[A-Za-z]:/.test(e))throw new Error(`Engine package path must be relative: ${t}`);let n=e.split("/").filter(Boolean);if(n.length===0||n.some(r=>r==="."||r===".."))throw new Error(`Engine package path must not contain "." or "..": ${t}`);return n.join("/")}function ba(t,e){try{return lg(t).replace(/\//g,Pe.sep)}catch(n){let r=n instanceof Error?n.message:String(n);throw new Error(`${e}: ${r}`)}}function Xs(t,e,n){let r=Pe.resolve(t),s=Pe.resolve(e),i=Pe.relative(r,s);if(i&&(i.startsWith("..")||Pe.isAbsolute(i)))throw new Error(`${n} must stay inside ${t}: ${e}`)}async function va(t){try{return await st.promises.access(t),!0}catch{return!1}}function tu(t,e){let n=JSON.parse(t);if(!n||typeof n!="object"||Array.isArray(n))throw new Error(`${e} must be a JSON object`);return n}function Oa(t,e,n){let r=t[e];if(typeof r!="string"||r.trim().length===0)throw new Error(`${n} missing required string field "${e}"`);return r.trim()}function ug(t){let e=t.trim().toLowerCase();if(!/^[a-z0-9][a-z0-9._-]*$/.test(e))throw new Error(`Custom engine id must contain only lowercase letters, numbers, ".", "_", or "-": ${t}`);return e}function vT(t,e){if(!t)return;if(typeof t!="object"||Array.isArray(t))throw new Error(`${e} workspaceSync must be an object`);let n=t;if(n.enabled!==!0)return;let r=Oa(n,"dir",`${e} workspaceSync`),s=Oa(n,"rulesFile",`${e} workspaceSync`);ba(r,"workspaceSync.dir"),ba(s,"workspaceSync.rulesFile")}async function OT(t){let e=Pe.join(t,An),n;try{n=await st.promises.readFile(e,"utf8")}catch{throw new Error(`Custom engine package is missing ${An}`)}let r=tu(n,An),s=Oa(r,"id",An),i={version:r.version,id:s,displayName:typeof r.displayName=="string"&&r.displayName.trim()?r.displayName.trim():void 0,description:typeof r.description=="string"&&r.description.trim()?r.description.trim():void 0,entry:Oa(r,"entry",An),workspaceSync:r.workspaceSync};if(i.version!==2)throw new Error(`${An} must declare version 2`);if(i.id!==i.id.toLowerCase()||!/^[a-z0-9][a-z0-9._-]*$/.test(i.id))throw new Error(`${An} id must contain only lowercase letters, numbers, ".", "_", or "-"`);vT(i.workspaceSync,An);let o=ba(i.entry,"entry"),a=Pe.join(t,o);if(Xs(t,a,"Engine entry"),!await va(a))throw new Error(`${An} entry not found: ${i.entry}`);return i}async function IT(t,e){let n=new Set;for(let r of e){let s=lg(r.path);if(n.has(s))throw new Error(`Duplicate engine package path: ${r.path}`);n.add(s);let i=Pe.join(t,...s.split("/"));Xs(t,i,"Engine package file"),await st.promises.mkdir(Pe.dirname(i),{recursive:!0}),await st.promises.writeFile(i,r.content)}}async function dg(t,e,n){try{await bT(t,e,{cwd:n,maxBuffer:10*1024*1024,windowsHide:!0,shell:process.platform==="win32"&&/\.(?:cmd|bat)$/i.test(t)})}catch(r){let s=typeof r.stderr=="string"?r.stderr.trim():"",i=typeof r.stdout=="string"?r.stdout.trim():"",o=s||i||(r instanceof Error?r.message:String(r));throw new Error(`${t} ${e.join(" ")} failed: ${o}`)}}async function PT(t,e,n){let r=Pe.join(t,"package.json");if(!await va(r))return!1;let s=Pe.join(t,"package-lock.json");if(!await va(s))throw new Error("Custom engine packages with package.json must include package-lock.json");if(!e)return!1;let i=process.platform==="win32"?"npm.cmd":"npm";return n&&(0,Ia.logInfo)(n,"[Store] Running npm ci --omit=dev for custom engine"),await dg(i,["ci","--omit=dev"],t),!0}async function NT(t,e,n){let r=ba(e.entry,"entry"),s=Pe.join(t,r);return n&&(0,Ia.logInfo)(n,`[Store] Validating custom engine entry: ${e.entry}`),await dg("node",["--check",s],t),s}async function RT(t,e,n,r){await st.promises.mkdir(e,{recursive:!0});let s=Pe.join(e,n);Xs(e,s,"Custom engine install target");let i=await va(s);if(i&&!r)throw new Error(`Custom engine "${n}" already exists at ${s}`);if(!i)return await st.promises.rename(t,s),s;let o=Pe.join(e,".tmp");await st.promises.mkdir(o,{recursive:!0});let a=Pe.join(o,`${n}.previous-${Date.now()}`);Xs(e,a,"Custom engine backup target"),await st.promises.rm(a,{recursive:!0,force:!0}),await st.promises.rename(s,a);try{return await st.promises.rename(t,s),await st.promises.rm(a,{recursive:!0,force:!0}),s}catch(c){throw await st.promises.rm(s,{recursive:!0,force:!0}).catch(()=>{}),await st.promises.rename(a,s).catch(()=>{}),c}}async function CT(t,e={}){if(t.length===0)throw new Error("Custom engine package is empty");let n=Pe.resolve(e.installRoot??Pa()),r=e.runNpmCi!==!1,s=e.overwrite!==!1,i=Pe.join(n,".tmp");await st.promises.mkdir(i,{recursive:!0});let o=await st.promises.mkdtemp(Pe.join(i,`${e.slug||"engine"}-`));Xs(i,o,"Custom engine staging directory");let a=!0;try{await IT(o,t);let c=await OT(o),l=await PT(o,r,e.logger),f=await NT(o,c,e.logger),u=await RT(o,n,c.id,s);a=!1;let d=Pe.join(u,Pe.relative(o,f)),p={id:c.id,displayName:c.displayName||c.id,version:c.version,manifestPath:Pe.join(u,An),installDir:u,entryPath:d,npmInstalled:l};if(e.logger){let g=e.sourceUrl?` from ${e.sourceUrl}`:"";(0,Ia.logInfo)(e.logger,`[Store] Installed custom engine ${p.id}${g} to ${u}`)}return p}finally{a&&await st.promises.rm(o,{recursive:!0,force:!0}).catch(()=>{})}}async function kT(t={}){let e=Pe.resolve(t.installRoot??Pa()),n;try{n=await st.promises.readdir(e,{withFileTypes:!0})}catch{return[]}let r=[];for(let s of n){if(!s.isDirectory()||s.name.startsWith("."))continue;let i=Pe.join(e,s.name);Xs(e,i,"Custom engine install target");let o=Pe.join(i,An),a=s.name,c=s.name;try{let l=tu(await st.promises.readFile(o,"utf8"),o);typeof l.id=="string"&&l.id.trim()&&(a=ug(l.id)),typeof l.displayName=="string"&&l.displayName.trim()?c=l.displayName.trim():c=a}catch{}r.push({id:a,displayName:c,manifestPath:o,installDir:i})}return r.sort((s,i)=>s.id.localeCompare(i.id))}async function $T(t,e={}){let n=ug(t),r=Pe.resolve(e.installRoot??Pa()),s=Pe.join(r,n);Xs(r,s,"Custom engine uninstall target");let i;try{let o=await st.promises.lstat(s);if(!o.isDirectory()||o.isSymbolicLink())throw new Error(`Custom engine install target is not a normal directory: ${s}`);try{let a=tu(await st.promises.readFile(Pe.join(s,An),"utf8"),An);i=typeof a.displayName=="string"&&a.displayName.trim()?a.displayName.trim():void 0}catch{}}catch(o){if(o?.code==="ENOENT")return{id:n,installDir:s,removed:!1};throw o}return await st.promises.rm(s,{recursive:!0,force:!0}),e.logger&&(0,Ia.logInfo)(e.logger,`[Store] Uninstalled custom engine ${n} from ${s}`),{id:n,displayName:i,installDir:s,removed:!0}}});var Ns=S(Tn=>{"use strict";var DT=Tn&&Tn.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,s)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),LT=Tn&&Tn.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),nu=Tn&&Tn.__importStar||(function(){var t=function(e){return t=Object.getOwnPropertyNames||function(n){var r=[];for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(r[r.length]=s);return r},t(e)};return function(e){if(e&&e.__esModule)return e;var n={};if(e!=null)for(var r=t(e),s=0;s<r.length;s++)r[s]!=="default"&&DT(n,e,r[s]);return LT(n,e),n}})();Object.defineProperty(Tn,"__esModule",{value:!0});Tn.parseCustomEngineSearchPath=ka;Tn.getCustomEngineSearchRoots=hg;Tn.discoverCustomEngineManifests=mg;Tn.resolveCustomEngineManifest=Eg;Tn.tryResolveCustomEngineManifest=FT;var Ra=nu(require("fs")),MT=nu(require("os")),fr=nu(require("path")),Ca=Ke(),GT=Na(),fg="engines",pg="engine.manifest.json";function gg(t){return t.trim().toLowerCase()}function Sn(t){return typeof t=="string"&&t.trim().length>0}function ka(t){return Array.isArray(t)?t.flatMap(e=>ka(e)):t?.trim()?t.split(fr.delimiter).map(e=>e.trim()).filter(Boolean):[]}function UT(t){let e=new Set,n=[];for(let r of t){let s=fr.resolve(r);e.has(s)||(e.add(s),n.push(s))}return n}function HT(t,e){if(!t)return;if(typeof t!="object")throw new Error(`Invalid model config in ${e}: expected object`);let n=t;if(!Sn(n.defaultModel))throw new Error(`Invalid model config in ${e}: "defaultModel" is required`);return{defaultModel:n.defaultModel.trim(),apiKeyEnvVar:Sn(n.apiKeyEnvVar)?n.apiKeyEnvVar.trim():void 0,baseUrlEnvVar:Sn(n.baseUrlEnvVar)?n.baseUrlEnvVar.trim():void 0,openaiBaseUrlEnvVar:Sn(n.openaiBaseUrlEnvVar)?n.openaiBaseUrlEnvVar.trim():void 0}}function jT(t,e){if(!t)return{mode:"env-only"};if(typeof t!="object")throw new Error(`Invalid promptInjection config in ${e}: expected object`);let n=t,s=Sn(n.mode)?n.mode.trim():"env-only";if(s!=="none"&&s!=="env-only"&&s!=="message-suffix")throw new Error(`Invalid promptInjection config in ${e}: "mode" must be none, env-only, or message-suffix`);return{mode:s}}function xT(t,e){if(!t)return;if(typeof t!="object")throw new Error(`Invalid workspaceSync config in ${e}: expected object`);let n=t;if(!(n.enabled===!0))return{enabled:!1,dir:"",rulesFile:"",includeSkills:!1,includeRules:!1};if(!Sn(n.dir))throw new Error(`Invalid workspaceSync config in ${e}: "dir" is required when enabled`);if(!Sn(n.rulesFile))throw new Error(`Invalid workspaceSync config in ${e}: "rulesFile" is required when enabled`);let s=n.dir.trim();if(fr.isAbsolute(s)||s.includes(".."))throw new Error(`Invalid workspaceSync config in ${e}: "dir" must be a relative workspace directory`);let i=n.rulesFile.trim();if(fr.isAbsolute(i)||i.includes(".."))throw new Error(`Invalid workspaceSync config in ${e}: "rulesFile" must be a relative path`);return{enabled:!0,dir:s,rulesFile:i,includeSkills:n.includeSkills!==!1,includeRules:n.includeRules!==!1}}function BT(t,e){let n=Ra.readFileSync(t,"utf8"),r=JSON.parse(n);if(!Sn(r.id))throw new Error(`Invalid custom engine manifest ${t}: "id" is required`);if(r.version!==2)throw new Error(`Invalid custom engine manifest ${t}: "version" must be 2`);if(!Sn(r.entry))throw new Error(`Invalid custom engine manifest ${t}: "entry" is required`);let s=gg(r.id),i=fr.dirname(t),o=r.entry.trim(),a=fr.isAbsolute(o)?o:fr.resolve(i,o);return{version:2,id:s,displayName:Sn(r.displayName)?r.displayName.trim():void 0,description:Sn(r.description)?r.description.trim():void 0,entry:o,entryPath:a,engineExport:Sn(r.engineExport)?r.engineExport.trim():void 0,homeEnvVar:Sn(r.homeEnvVar)?r.homeEnvVar.trim():void 0,workspaceSync:xT(r.workspaceSync,t),promptInjection:jT(r.promptInjection,t),model:HT(r.model,t),manifestPath:t,manifestDir:i,searchRoot:e}}function hg(t,e){let n=t?fr.resolve(t):void 0,r=ka(e),s=ka(process.env.AGENTHIPPO_CUSTOM_ENGINES_DIR??process.env.AGENTIDE_CUSTOM_ENGINES_DIR);return UT([...n?[fr.join(n,Ca.AGENTIDE_DIR_NAME,fg)]:[],...r,...s,(0,GT.getDefaultCustomEnginesInstallRoot)(),fr.join(MT.homedir(),Ca.AGENTIDE_DIR_NAME,fg)])}function mg(t,e,n){let r=[],s=new Set;for(let i of hg(t,e)){if(!Ra.existsSync(i))continue;let o;try{o=Ra.readdirSync(i,{withFileTypes:!0})}catch{continue}for(let a of o){if(!a.isDirectory())continue;let c=fr.join(i,a.name,pg);if(!Ra.existsSync(c))continue;let l;try{l=BT(c,i)}catch(f){n?.(c,f);continue}s.has(l.id)||(s.add(l.id),r.push(l))}}return r}function Eg(t,e,n,r){let s=mg(t,n,r),i=e?gg(e):void 0;if(i){let o=s.find(a=>a.id===i);if(!o){let a=s.map(c=>c.id).sort();throw new Error(a.length>0?`Custom engine "${i}" not found. Available: ${a.join(", ")}`:`Custom engine "${i}" not found. No manifests discovered under ${Ca.AGENTIDE_DIR_NAME}/engines.`)}return o}if(s.length===0)throw new Error(`No custom engines found. Add ${pg} under ${Ca.AGENTIDE_DIR_NAME}/engines/<engine-id>/`);if(s.length>1){let o=s.map(a=>a.id).sort();throw new Error(`Multiple custom engines found (${o.join(", ")}). Specify one with --engine <id>.`)}return s[0]}function FT(t,e,n,r){try{return Eg(t,e,n,r)}catch{return}}});var en=S((exports,module)=>{"use strict";var __createBinding=exports&&exports.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,s)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),__setModuleDefault=exports&&exports.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),__importStar=exports&&exports.__importStar||(function(){var t=function(e){return t=Object.getOwnPropertyNames||function(n){var r=[];for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(r[r.length]=s);return r},t(e)};return function(e){if(e&&e.__esModule)return e;var n={};if(e!=null)for(var r=t(e),s=0;s<r.length;s++)r[s]!=="default"&&__createBinding(n,e,r[s]);return __setModuleDefault(n,e),n}})();Object.defineProperty(exports,"__esModule",{value:!0});exports.getAnalyticsScriptsDir=void 0;exports.logInfo=logInfo;exports.getErrorCode=getErrorCode;exports.pathExists=pathExists;exports.isDirOrSymlink=isDirOrSymlink;exports.ensureRealDirectory=ensureRealDirectory;exports.writeFileIfChanged=writeFileIfChanged;exports.copyDirRecursive=copyDirRecursive;exports.copyDirRecursiveWithTransform=copyDirRecursiveWithTransform;exports.symlinkOrCopyFile=symlinkOrCopyFile;exports.syncDirByFileLinks=syncDirByFileLinks;exports.ensureWorkspaceGitAndGitignore=ensureWorkspaceGitAndGitignore;exports.readFileSha256=readFileSha256;exports.getFileStats=getFileStats;exports.isCachedHashValid=isCachedHashValid;exports.shortSig=shortSig;exports.isLocalHttps=isLocalHttps;exports.applyLocalTlsBypass=applyLocalTlsBypass;exports.getOverrideOpenAIBaseUrl=getOverrideOpenAIBaseUrl;exports.inferModelProvider=inferModelProvider;exports.resolveApiRouting=resolveApiRouting;exports.getExplicitConfigValue=getExplicitConfigValue;exports.getAgentideEngineSettings=getAgentideEngineSettings;exports.emitStreamEvent=emitStreamEvent;exports.createIPCStreamEmitter=createIPCStreamEmitter;exports.computeTextDelta=computeTextDelta;exports.createDeferred=createDeferred;exports.stableAdditionalDirs=stableAdditionalDirs;exports.extractFilePaths=extractFilePaths;exports.isCreateCommand=isCreateCommand;exports.normalizeFileChangeKind=normalizeFileChangeKind;exports.isBinaryFile=isBinaryFile;var fs_1=require("fs"),child_process_1=require("child_process"),promises_1=require("stream/promises"),util_1=require("util"),path=__importStar(require("path")),crypto=__importStar(require("crypto")),shared_1=Ta(),branding_1=Ke(),customRegistry_1=Ns(),execFileAsync=(0,util_1.promisify)(child_process_1.execFile),_vscode;function getVscode(){if(!_vscode)try{_vscode=eval("require")("vscode")}catch{throw new Error("vscode module not available. Use ConfigProvider instead of vscode.workspace.getConfiguration")}return _vscode}function logInfo(t,e){t.appendLine?t.appendLine(e):t.info&&t.info(e)}function getErrorCode(t){return t&&typeof t=="object"?t.code:void 0}async function pathExists(t){try{return await fs_1.promises.lstat(t),!0}catch(e){if(getErrorCode(e)==="ENOENT")return!1;throw e}}async function isDirOrSymlink(t){try{let e=await fs_1.promises.lstat(t);return e.isDirectory()||e.isSymbolicLink()}catch(e){if(getErrorCode(e)==="ENOENT")return!1;throw e}}async function ensureRealDirectory(t){try{let e=await fs_1.promises.lstat(t);(e.isSymbolicLink()||!e.isDirectory())&&(await fs_1.promises.rm(t,{recursive:!0,force:!0}),await fs_1.promises.mkdir(t,{recursive:!0}))}catch(e){if(getErrorCode(e)==="ENOENT"){await fs_1.promises.mkdir(t,{recursive:!0});return}throw e}}async function writeFileIfChanged(t,e){try{if(await fs_1.promises.readFile(t,"utf8")===e)return!1}catch(n){if(getErrorCode(n)!=="ENOENT")throw n}return await fs_1.promises.mkdir(path.dirname(t),{recursive:!0}),await fs_1.promises.writeFile(t,e,"utf8"),!0}async function copyDirRecursive(t,e){await fs_1.promises.mkdir(e,{recursive:!0});let n=await fs_1.promises.readdir(t,{withFileTypes:!0});for(let r of n){let s=path.join(t,r.name),i=path.join(e,r.name);if(r.isDirectory())await copyDirRecursive(s,i);else if(r.isFile())await fs_1.promises.copyFile(s,i);else if(r.isSymbolicLink()){let o=await fs_1.promises.readlink(s),a=path.isAbsolute(o)?o:path.resolve(path.dirname(s),o);(await fs_1.promises.stat(a)).isDirectory()?await copyDirRecursive(a,i):await fs_1.promises.copyFile(a,i)}}}async function copyDirRecursiveWithTransform(t,e,n){await fs_1.promises.mkdir(e,{recursive:!0});let r=await fs_1.promises.readdir(t,{withFileTypes:!0});for(let s of r){let i=path.join(t,s.name),o=path.join(e,s.name);if(s.isDirectory())await copyDirRecursiveWithTransform(i,o,n);else if(s.isFile())if(s.name.toLowerCase().endsWith(".md")){let c=await fs_1.promises.readFile(i,"utf8");await fs_1.promises.writeFile(o,n(c),"utf8")}else await fs_1.promises.copyFile(i,o);else if(s.isSymbolicLink()){let a=await fs_1.promises.readlink(i),c=path.isAbsolute(a)?a:path.resolve(path.dirname(i),a);if((await fs_1.promises.stat(c)).isDirectory())await copyDirRecursiveWithTransform(c,o,n);else if(s.name.toLowerCase().endsWith(".md")){let u=await fs_1.promises.readFile(c,"utf8");await fs_1.promises.writeFile(o,n(u),"utf8")}else await fs_1.promises.copyFile(c,o)}}}async function symlinkOrCopyFile(t,e,n,r,s){let i=s?.force??!1;try{if((await fs_1.promises.lstat(e)).isSymbolicLink()){try{let a=await fs_1.promises.readlink(e),c=path.isAbsolute(a)?a:path.resolve(path.dirname(e),a);if(path.resolve(c)===path.resolve(t))return}catch{}await fs_1.promises.unlink(e)}else if(i)await fs_1.promises.rm(e,{recursive:!0,force:!0});else return}catch(o){if(getErrorCode(o)!=="ENOENT")throw o}if(await fs_1.promises.mkdir(path.dirname(e),{recursive:!0}),path.resolve(t)!==path.resolve(e))try{await fs_1.promises.symlink(t,e,"file"),logInfo(n,`[AgentIDE] Linked ${r} (symlink): ${e} -> ${t}`)}catch{await fs_1.promises.copyFile(t,e),logInfo(n,`[AgentIDE] Linked ${r} (copy fallback): ${e}`)}}async function syncDirByFileLinks(t,e,n,r){await ensureRealDirectory(e);let s=new Set,i=new Map,o=async(u,d)=>{let p;try{p=await fs_1.promises.readdir(u,{withFileTypes:!0})}catch(g){if(getErrorCode(g)==="ENOENT")return;throw g}for(let g of p){if(g.name.startsWith("."))continue;let m=path.join(u,g.name),h=d?path.join(d,g.name):g.name;if(g.isDirectory())s.add(h),await o(m,h);else if(g.isFile())i.set(h,m);else if(g.isSymbolicLink())try{let E=await fs_1.promises.readlink(m),_=path.isAbsolute(E)?E:path.resolve(path.dirname(m),E);(await fs_1.promises.stat(_)).isDirectory()?(s.add(h),await o(_,h)):i.set(h,_)}catch(E){let _=getErrorCode(E);if(_==="ENOENT"||_==="ELOOP")continue;throw E}}};await o(t,"");let a=Array.from(s).sort((u,d)=>u.split(path.sep).length-d.split(path.sep).length);for(let u of a)await ensureRealDirectory(path.join(e,u));for(let[u,d]of i.entries())await symlinkOrCopyFile(d,path.join(e,u),n,`${r}/${u}`.replace(/\\/g,"/"),{force:!0});let c=new Set(i.keys()),l=async(u,d)=>{let p;try{p=await fs_1.promises.readdir(u,{withFileTypes:!0})}catch(g){if(getErrorCode(g)==="ENOENT")return;throw g}for(let g of p){if(g.name.startsWith("."))continue;let m=path.join(u,g.name),h=d?path.join(d,g.name):g.name,E=path.join(t,h);if(g.isDirectory())await l(m,h);else if(g.isFile()&&!g.isSymbolicLink()&&!c.has(h))try{await fs_1.promises.mkdir(path.dirname(E),{recursive:!0}),await fs_1.promises.copyFile(m,E),logInfo(n,`[AgentIDE] Copied new file to source: ${r}/${h}`.replace(/\\/g,"/")),i.set(h,E)}catch(_){logInfo(n,`[AgentIDE] Warning: failed to copy back ${h}: ${_ instanceof Error?_.message:String(_)}`)}}};await l(e,"");for(let[u,d]of i.entries()){let p=path.join(e,u);try{let g=await fs_1.promises.lstat(p);g.isFile()&&!g.isSymbolicLink()&&(await fs_1.promises.rm(p,{force:!0}),await symlinkOrCopyFile(d,p,n,`${r}/${u}`.replace(/\\/g,"/"),{force:!0}))}catch{}}let f=async(u,d)=>{let p;try{p=await fs_1.promises.readdir(u,{withFileTypes:!0})}catch(g){if(getErrorCode(g)==="ENOENT")return;throw g}for(let g of p){if(g.name.startsWith("."))continue;let m=path.join(u,g.name),h=d?path.join(d,g.name):g.name;g.isDirectory()?await f(m,h):g.isSymbolicLink()&&(c.has(h)||await fs_1.promises.rm(m,{force:!0}))}};await f(e,"")}function getManagedWorkspaceDirs(t,e){let n=Object.values(shared_1.AGENT_ENGINES).map(s=>s.workspaceDir),r=(0,customRegistry_1.discoverCustomEngineManifests)(t,e).filter(s=>s.workspaceSync?.enabled).map(s=>s.workspaceSync.dir);return[...new Set([...n,...r])]}async function ensureWorkspaceGitAndGitignore(t,e,n){let r=path.join(t,".git");if(!await pathExists(r))try{await execFileAsync("git",["init"],{cwd:t}),logInfo(e,`[AgentIDE] Initialized git repository in ${t}`)}catch(m){logInfo(e,`[AgentIDE] Note: Could not initialize git in ${t}: ${m instanceof Error?m.message:String(m)}`)}let i=path.join(t,".gitignore"),o=getManagedWorkspaceDirs(t,n?.extraSearchPath),a=[`# ${branding_1.AGENTIDE_BRAND_NAME} (managed)`,`# These directories are managed by ${branding_1.AGENTIDE_BRAND_NAME} and should not be committed.`,...o],c="";try{c=await fs_1.promises.readFile(i,"utf8")}catch(m){if(getErrorCode(m)!=="ENOENT"){logInfo(e,`[AgentIDE] Warning: failed to read root .gitignore: ${m instanceof Error?m.message:String(m)}`);return}}let l=c.split(`
32
32
  `).map(m=>m.trim());if(o.filter(m=>!l.includes(m)).length===0)return;let u=`# ${branding_1.AGENTIDE_BRAND_NAME} (managed)`,d="# AgentIDE (managed)",p=c.includes(u)||c.includes(d),g;if(p){let m=c.split(`
33
33
  `),h=[],E=!1;for(let _ of m){if(_.trim()===u||_.trim()===d){E=!0,h.push(...a);continue}if(E){if(_.trim().startsWith("#")||o.includes(_.trim())||_.trim()==="")continue;E=!1}h.push(_)}g=h.join(`
34
34
  `).replace(/\n{3,}/g,`
@@ -36,22 +36,22 @@ Provide clear, actionable responses with code examples when relevant.
36
36
  `).trimEnd()+`
37
37
  `}else g=[c.trimEnd(),"",a.join(`
38
38
  `),""].join(`
39
- `).replace(/^\n+/,"");try{await writeFileIfChanged(i,g)&&logInfo(e,`[AgentIDE] Updated ${i} to ignore ${branding_1.AGENTIDE_BRAND_NAME} directories`)}catch(m){logInfo(e,`[AgentIDE] Warning: failed to write root .gitignore: ${m instanceof Error?m.message:String(m)}`)}}async function readFileSha256(t){let e=await fs_1.promises.stat(t),n=crypto.createHash("sha256");return await(0,promises_1.pipeline)((0,fs_1.createReadStream)(t),n),{sha256:n.digest("hex"),size:e.size,mtimeMs:e.mtimeMs}}async function getFileStats(t){try{let e=await fs_1.promises.stat(t);return{size:e.size,mtimeMs:e.mtimeMs}}catch(e){if(getErrorCode(e)==="ENOENT")return;throw e}}function isCachedHashValid(t,e){if(!(!t||!e)&&t.mtimeMs===e.mtimeMs&&t.size===e.size)return t}function shortSig(t){return crypto.createHash("sha256").update(t).digest("hex").slice(0,16)}var LOCAL_TLS_HOSTNAMES=new Set(["localhost","127.0.0.1","0.0.0.0","::1","[::1]"]);function isLocalHttps(t){if(!t)return!1;try{let e=new URL(t);return e.protocol==="https:"&&LOCAL_TLS_HOSTNAMES.has(e.hostname.toLowerCase())}catch{return!1}}function applyLocalTlsBypass(t,e){return isLocalHttps(e)?(t.NODE_TLS_REJECT_UNAUTHORIZED="0",!0):!1}function getOverrideOpenAIBaseUrl(t,e){if(!e)return;let n=e.getCustomProviders(),r=t.replace(/\/$/,"");for(let s of Object.values(n))if(s.baseUrl){let i=s.baseUrl.replace(/\/$/,"");if(r===i&&s.overrideOpenAIBaseUrl)return s.overrideOpenAIBaseUrl.trim()}}function inferModelProvider(t){return t&&/claude|anthropic/i.test(t)?"anthropic":"openai"}function resolveApiRouting(t,e,n,r){let s=t.useLiteLLM===!0,i=t.baseUrl||(s?e.litellmBaseUrl:void 0),o=n==="anthropic"?e.anthropicApiKey:e.openaiApiKey,a=s?t.apiKey||e.litellmApiKey||"sk-dummy":t.apiKey||o||"",c=i;if(i){let l=getOverrideOpenAIBaseUrl(i,r);l&&(c=l)}return{apiKey:a,baseUrl:i,openaiBaseUrl:c,useLiteLLM:s}}function getExplicitConfigValue(t,e){let n=t.inspect(e);if(n)return n.workspaceFolderValue??n.workspaceValue??n.globalValue}function getAgentideEngineSettings(t){return t?t.getEngineSettings():{claudeMaxThinkingTokens:0}}async function emitStreamEvent(t){try{await getVscode().commands.executeCommand("agentide.streamCallback",t)}catch(e){console.error("[AgentIDE Extension] Failed to emit stream event:",e)}}var STREAM_COALESCE_WINDOW_MS=40,STREAM_COALESCE_MIN_CHARS=120;function flushCoalescedBuffers(t,e){let n=[];return e.markdownBuffer&&(n.push(emitStreamEvent({streamId:t,type:"markdown",data:e.markdownBuffer})),e.markdownBuffer=""),e.thinkingBuffer&&(n.push(emitStreamEvent({streamId:t,type:"thinking",data:e.thinkingBuffer})),e.thinkingBuffer=""),e.flushTimer&&(clearTimeout(e.flushTimer),e.flushTimer=void 0),Promise.all(n).then(()=>{})}function ensureFlushTimer(t,e){e.flushTimer||(e.flushTimer=setTimeout(()=>{flushCoalescedBuffers(t,e)},STREAM_COALESCE_WINDOW_MS))}function createIPCStreamEmitter(t){let e={markdownBuffer:"",thinkingBuffer:"",flushTimer:void 0};return{async thinking(n){if(n){if(e.thinkingBuffer+=n,e.thinkingBuffer.length>=STREAM_COALESCE_MIN_CHARS){await flushCoalescedBuffers(t,e);return}ensureFlushTimer(t,e)}},async text(n){if(n){if(e.markdownBuffer+=n,e.markdownBuffer.length>=STREAM_COALESCE_MIN_CHARS){await flushCoalescedBuffers(t,e);return}ensureFlushTimer(t,e)}},async toolStart(n,r,s,i){await flushCoalescedBuffers(t,e),await emitStreamEvent({streamId:t,type:"tool_use",toolName:n,toolCallId:s,data:r||"",metadata:i})},async toolEnd(n,r,s,i,o){await flushCoalescedBuffers(t,e),await emitStreamEvent({streamId:t,type:"tool_end",toolName:n,toolCallId:r,data:s||"",metadata:{...o&&typeof o=="object"?o:{},isError:i}})},async progress(n){await flushCoalescedBuffers(t,e),await emitStreamEvent({streamId:t,type:"progress",data:n})},async question(n){return await flushCoalescedBuffers(t,e),await emitStreamEvent({streamId:t,type:"question",metadata:n}),{selected:[],freeText:null,declined:!0}},async error(n){await flushCoalescedBuffers(t,e),await emitStreamEvent({streamId:t,type:"error",data:n})},async done(){await flushCoalescedBuffers(t,e),await emitStreamEvent({streamId:t,type:"done"})}}}function computeTextDelta(t,e,n){let r=n.get(t)??"",s=e.startsWith(r)?e.slice(r.length):e;return n.set(t,e),s}function createDeferred(){let t,e;return{promise:new Promise((r,s)=>{t=r,e=s}),resolve:t,reject:e}}function stableAdditionalDirs(t){return(t??[]).slice().filter(Boolean).sort()}var paths_1=Ys();Object.defineProperty(exports,"getAnalyticsScriptsDir",{enumerable:!0,get:function(){return paths_1.getAnalyticsScriptsDir}});var CREATE_CMD_PATTERN=/(?:cat\s*>[^>]|echo\s*>[^>]|touch\s+|>\s*[^>]|<<\s*['"]?EOF)/,EXCLUDED_PREFIXES=["/tmp/","/var/","/dev/"],EXCLUDED_SUFFIXES=[".tmp",".bak"];function extractFilePaths(t,e){let n=t.matchAll(/(?:^|[\s'"`;|&()=><])([./]*(?:[\w.\-]+\/)*[\w.\-]+\.[\w]+)(?=[\s'"`;|&()=><]|$)/g),r=new Set;for(let s of n){let i=s[1].replace(/['"]/g,"").trim();!i||i.startsWith("-")||i.includes("..")||EXCLUDED_PREFIXES.some(o=>i.startsWith(o))||EXCLUDED_SUFFIXES.some(o=>i.endsWith(o))||r.add(i.startsWith("/")?i:`${e}/${i.replace(/^\.\//,"")}`)}return[...r]}function isCreateCommand(t){return CREATE_CMD_PATTERN.test(t)}function normalizeFileChangeKind(t){switch(t){case"add":case"create":return"create";case"update":case"modify":return"modify";case"delete":return"delete";default:return}}var BINARY_EXTENSIONS=new Set([".pdf",".doc",".docx",".xls",".xlsx",".ppt",".pptx",".zip",".tar",".gz",".rar",".7z",".png",".jpg",".jpeg",".gif",".bmp",".ico",".webp",".svg",".mp3",".mp4",".wav",".avi",".mov",".mkv",".exe",".dll",".so",".dylib",".bin",".woff",".woff2",".ttf",".otf",".eot",".pyc",".class",".o",".a"]);function isBinaryFile(t){let e=t.lastIndexOf(".");return e===-1?!1:BINARY_EXTENSIONS.has(t.slice(e))}});var Eg=S(ka=>{"use strict";Object.defineProperty(ka,"__esModule",{value:!0});ka.VSCodeSessionStore=void 0;var nu=class{globalState;constructor(e){this.globalState=e}get(e){return this.globalState.get(e)}async set(e,n){await this.globalState.update(e,n)}};ka.VSCodeSessionStore=nu});var Js=S(at=>{"use strict";var jT=at&&at.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,s)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),xT=at&&at.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),BT=at&&at.__importStar||(function(){var t=function(e){return t=Object.getOwnPropertyNames||function(n){var r=[];for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(r[r.length]=s);return r},t(e)};return function(e){if(e&&e.__esModule)return e;var n={};if(e!=null)for(var r=t(e),s=0;s<r.length;s++)r[s]!=="default"&&jT(n,e,r[s]);return xT(n,e),n}})();Object.defineProperty(at,"__esModule",{value:!0});at.DEFAULT_CONVERSATION_LOCK_TIMEOUT_MS=void 0;at.initSessionStore=qT;at.initSessionStoreWithStore=wg;at._getSessionStore=YT;at._resetSessionStore=XT;at.upsertPersistedSession=JT;at.touchPersistedSession=zT;at.getPersistedSession=QT;at.runSessionMaintenance=ZT;at.buildConversationKey=tb;at.withConversationLock=nb;var FT=BT(require("crypto")),VT=en(),WT=Eg(),yg="agentide.providerSessions.v1",_g=200,KT=1e3*60*60*24*14,xn={},uo;function qT(t){wg(new WT.VSCodeSessionStore(t.globalState))}function wg(t){uo=t,xn=t.get(yg)??{},Da(Date.now()),La()}function YT(){return uo}function XT(){uo=void 0,xn={}}function Da(t){for(let[n,r]of Object.entries(xn))t-r.lastUsedAt>KT&&delete xn[n];let e=Object.keys(xn);if(!(e.length<=_g)){e.sort((n,r)=>xn[n].lastUsedAt-xn[r].lastUsedAt);for(let n=0;n<e.length-_g;n++)delete xn[e[n]]}}async function La(){if(uo)try{await uo.set(yg,xn)}catch{}}async function JT(t,e){xn[t]=e,Da(Date.now()),await La()}async function zT(t){let e=xn[t];e&&(e.lastUsedAt=Date.now(),Da(e.lastUsedAt),await La())}function QT(t){return xn[t]}function ZT(){Da(Date.now()),La()}function eb(t){return JSON.stringify({workspaceRoot:t.workspaceRoot,additionalDirectories:(0,VT.stableAdditionalDirs)(t.additionalDirectories),agentPackId:t.agentPackId??"default"})}function tb(t,e){let n=e.sessionId?.trim(),r=e.contextSessionId?.trim()||n,s=!r,i=r||`ephemeral-${Date.now()}-${Math.random().toString(36).slice(2)}`,o=n||i,a=e.agentPackId??"default",c=eb(e),l=FT.createHash("sha256").update(c).digest("hex").slice(0,16);return{key:`${t}:${i}:${a}:${l}`,chatSessionId:o,isEphemeral:s,signatureHash:l,signatureRaw:c,agentPackId:a}}at.DEFAULT_CONVERSATION_LOCK_TIMEOUT_MS=1e3*60*60*48;var $a=new Map;function nb(t,e,n){let r=$a.get(t)??Promise.resolve(),s,i=new Promise(E=>{s=E}),o=r.then(()=>i);$a.set(t,o);let a=n?.label?` (${n.label})`:"",c=typeof n?.timeoutMs=="number"?n.timeoutMs:void 0,l=n?.signal,f,u,d=!1,p=l?new Promise((E,_)=>{if(l.aborted){_(new Error(`[AgentIDE] Cancelled while waiting for conversation lock${a}`));return}f=()=>_(new Error(`[AgentIDE] Cancelled while waiting for conversation lock${a}`)),l.addEventListener("abort",f,{once:!0})}):void 0,g=c&&c>0?new Promise((E,_)=>{u=setTimeout(()=>{d=!0,n?.onTimeout?.(),_(new Error(`[AgentIDE] Conversation lock timed out after ${c}ms${a}`))},c)}):void 0,m=[r,p,g].filter(Boolean);return Promise.race(m).then(async()=>{if(l?.aborted)throw new Error(`[AgentIDE] Cancelled before running conversation work${a}`);if(d)throw new Error(`[AgentIDE] Conversation lock timed out after ${c}ms${a}`);let _=[e(),g].filter(Boolean);return await Promise.race(_)}).finally(()=>{try{u&&clearTimeout(u),l&&f&&l.removeEventListener("abort",f)}finally{s(),$a.get(t)===o&&$a.delete(t)}})}});var zs=S(un=>{"use strict";var rb=un&&un.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,s)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),sb=un&&un.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),ib=un&&un.__importStar||(function(){var t=function(e){return t=Object.getOwnPropertyNames||function(n){var r=[];for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(r[r.length]=s);return r},t(e)};return function(e){if(e&&e.__esModule)return e;var n={};if(e!=null)for(var r=t(e),s=0;s<r.length;s++)r[s]!=="default"&&rb(n,e,r[s]);return sb(n,e),n}})();Object.defineProperty(un,"__esModule",{value:!0});un.buildLiteLLMMetadataHeaders=cb;un.resolveAnalyticsProjectId=lb;un.generateRequestId=ub;un.persistSessionIfNeeded=db;un.touchSessionIfNeeded=fb;un.getPersistedSessionId=pb;var ob=Pi(),Ma=Js(),ab=ib(require("path"));function cb(t,e){if(!t)return[];let n=[],r=(0,ob.hashIdentity)(e.analyticsUserId);return r&&(n.push(`x-litellm-metadata-user-id: ${r}`),n.push(`langfuse_trace_user_id: ${r}`)),e.sessionId?.trim()&&(n.push(`x-litellm-metadata-session-id: ${e.sessionId.trim()}`),n.push(`langfuse_session_id: ${e.sessionId.trim()}`)),e.analyticsProjectId?.trim()&&n.push(`x-litellm-metadata-project-id: ${e.analyticsProjectId.trim()}`),e.agentId?.trim()&&n.push(`x-litellm-metadata-agent-id: ${e.agentId.trim()}`),e.agentVersion?.trim()&&n.push(`x-litellm-metadata-agent-version: ${e.agentVersion.trim()}`),e.source?.trim()&&n.push(`x-litellm-metadata-source: ${e.source.trim()}`),e.engine?.trim()&&n.push(`x-litellm-metadata-engine: ${e.engine.trim()}`),e.requestId?.trim()&&n.push(`x-litellm-metadata-request-id: ${e.requestId.trim()}`),e.policyVersion?.trim()&&n.push(`x-litellm-metadata-policy-version: ${e.policyVersion.trim()}`),e.packDigest?.trim()&&n.push(`x-litellm-metadata-pack-digest: ${e.packDigest.trim()}`),e.engineVersion?.trim()&&n.push(`x-litellm-metadata-engine-version: ${e.engineVersion.trim()}`),e.tier!==void 0&&n.push(`x-litellm-metadata-tier: ${e.tier}`),e.instanceId?.trim()&&n.push(`x-litellm-metadata-instance-id: ${e.instanceId.trim()}`),n}function lb(t,e){let n=t?.trim();if(n)return n;if(!e)return;let r=e.replace(/[\\/]+$/,"").trim();return r&&ab.basename(r).trim()||void 0}function ub(){return`req-${Math.random().toString(16).slice(2,10)}`}async function db(t,e,n,r){if(e.isEphemeral)return;let s=Date.now(),i=(0,Ma.getPersistedSession)(e.key);await(0,Ma.upsertPersistedSession)(e.key,{provider:t,id:n,chatSessionId:e.chatSessionId,signatureHash:e.signatureHash,signatureRaw:e.signatureRaw,agentPackId:r?.agentPackId??e.agentPackId,agentPackVersion:r?.agentPackVersion,createdAt:i?.createdAt??s,lastUsedAt:s})}function fb(t){t.isEphemeral||(0,Ma.touchPersistedSession)(t.key)}function pb(t,e){let n=(0,Ma.getPersistedSession)(e);return n?.provider===t?n.id:void 0}});var ru=S(pr=>{"use strict";Object.defineProperty(pr,"__esModule",{value:!0});pr.DEFAULT_PERMISSIONS=void 0;pr.getDefaultPermissions=Ag;pr._resetMappingConfigCache=gb;pr.parsePermissions=Sg;pr.parseManifestPermissions=hb;pr.enforcePermissions=mb;pr.toClaudeOptions=Eb;pr.toCodexOptions=_b;pr.DEFAULT_PERMISSIONS={fileAccess:"full"};var Rs={defaults:{fileAccess:"full"},claude:{readOnly:{permissionMode:"plan",allowDangerouslySkipPermissions:!1},workspaceWrite:{permissionMode:"acceptEdits",allowDangerouslySkipPermissions:!1},fullAccess:{permissionMode:"bypassPermissions",allowDangerouslySkipPermissions:!0}},codex:{approvalPolicy:"never",readOnly:{sandboxMode:"read-only"},workspaceWrite:{sandboxMode:"workspace-write"},fullAccess:{sandboxMode:"danger-full-access"}}};function Ag(){return{...Rs.defaults}}function gb(){}function Sg(t){let e=t?.spec?.permissions,n=Ag();return{fileAccess:e?.fileAccess??n.fileAccess}}function hb(t){return Sg(t)}function mb(t,e){return{fileAccess:e.fileAccess}}function Eb(t,e){return{...t.fileAccess==="read-only"?Rs.claude.readOnly:t.fileAccess==="workspace-write"?Rs.claude.workspaceWrite:Rs.claude.fullAccess,additionalDirectories:t.fileAccess==="full"?void 0:e}}function _b(t,e){let n=t.fileAccess==="read-only"?Rs.codex.readOnly:t.fileAccess==="workspace-write"?Rs.codex.workspaceWrite:Rs.codex.fullAccess;return{approvalPolicy:Rs.codex.approvalPolicy,...n,additionalDirectories:e}}});var Qs=S(bn=>{"use strict";var yb=bn&&bn.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,s)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),wb=bn&&bn.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),Ab=bn&&bn.__importStar||(function(){var t=function(e){return t=Object.getOwnPropertyNames||function(n){var r=[];for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(r[r.length]=s);return r},t(e)};return function(e){if(e&&e.__esModule)return e;var n={};if(e!=null)for(var r=t(e),s=0;s<r.length;s++)r[s]!=="default"&&yb(n,e,r[s]);return wb(n,e),n}})();Object.defineProperty(bn,"__esModule",{value:!0});bn.parseYaml=iu;bn.stringifyYaml=bg;bn.updateManifestName=Tb;bn.loadAgentManifest=bb;bn.parseAgentManifest=vg;var su=require("fs"),Tg=Ab(require("path")),Sb=Ke();function iu(t){return require("js-yaml").load(t)}function bg(t){return require("js-yaml").dump(t,{indent:2,lineWidth:-1,quotingType:'"',forceQuotes:!1})}async function Tb(t,e){let n=await su.promises.readFile(t,"utf8"),r=iu(n);r&&typeof r=="object"&&r.metadata&&(r.metadata.name=e);let s=bg(r);await su.promises.writeFile(t,s,"utf8")}async function bb(t){let e=await su.promises.readFile(t,"utf8");return vg(e,t)}function vg(t,e){let n=iu(t),r=e?` (${e})`:"";if(!n?.metadata?.name)throw new Error(`Manifest missing metadata.name${r}`);if(!n.metadata.version)throw new Error(`Manifest missing metadata.version${r}`);if(!n.spec?.engine)throw new Error(`Manifest missing spec.engine${r}`);return vb(n,r),n}function vb(t,e){let n=t.spec?.data;if(!n)return;let r=(s,i,o)=>{let c=(s??o).trim();if(!c)throw new Error(`Manifest spec.data.${i} cannot be empty${e}`);if(Tg.isAbsolute(c))throw new Error(`Manifest spec.data.${i} must be relative (not absolute)${e}`);if(/^(https?:\/\/|git@|ssh:\/\/)/i.test(c))throw new Error(`Manifest spec.data.${i} must be a local relative path${e}`);let l=Tg.posix.normalize(c.replace(/\\/g,"/"));if(l===".."||l.startsWith("../"))throw new Error(`Manifest spec.data.${i} cannot escape parent directories${e}`)};r(n.sourcePath,"sourcePath","./data"),r(n.workspacePath,"workspacePath",`${Sb.AGENTIDE_DIR_NAME}/data/${t.metadata.name}`)}});var cu=S(St=>{"use strict";var Ob=St&&St.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,s)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),Ib=St&&St.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),Pb=St&&St.__importStar||(function(){var t=function(e){return t=Object.getOwnPropertyNames||function(n){var r=[];for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(r[r.length]=s);return r},t(e)};return function(e){if(e&&e.__esModule)return e;var n={};if(e!=null)for(var r=t(e),s=0;s<r.length;s++)r[s]!=="default"&&Ob(n,e,r[s]);return Ib(n,e),n}})();Object.defineProperty(St,"__esModule",{value:!0});St.listUserLibraryAgents=Cb;St.isWorkspaceAgentAvailable=kb;St.isAgentInUserLibrary=$b;St.hydrateFromUserLibrary=Ig;St.promoteToUserLibrary=Db;St.readAgentSource=Pg;St.checkForUpdate=Lb;St.updateFromUserLibrary=Mb;St.duplicateAgent=Ub;St.resetDefaultAgent=Hb;var qe=require("fs"),Be=Pb(require("path")),te=en(),ae=Un(),Ni=Qs(),Og=Ke();function Nb(t,e){let n=o=>o.split(".").map(a=>{let c=parseInt(a,10);return isNaN(c)?0:c}),r=n(t),s=n(e),i=Math.max(r.length,s.length);for(let o=0;o<i;o++){let a=r[o]??0,c=s[o]??0;if(a!==c)return a-c}return 0}function Rb(t){return[...t].sort(Nb)}async function ou(t,e){await qe.promises.mkdir(e,{recursive:!0});let n=await qe.promises.readdir(t,{withFileTypes:!0});for(let r of n){let s=Be.join(t,r.name),i=Be.join(e,r.name);if(r.isDirectory()){if(r.name.startsWith("."))continue;await ou(s,i)}else await qe.promises.copyFile(s,i)}}async function Cb(){let t=(0,ae.getUserAgentsDir)();if(!await(0,te.pathExists)(t))return[];let e=await qe.promises.readdir(t,{withFileTypes:!0}),n=[];for(let r of e){if(!r.isDirectory()||r.name.startsWith("."))continue;let s=r.name,i=(0,ae.getUserAgentRoot)(s),o=await au(i);if(o.length===0)continue;let a=await Ga(s),c=a||o[o.length-1],l=(0,ae.getUserAgentVersionDir)(s,c),f=Be.join(l,ae.AGENT_CONSTANTS.MANIFEST_FILE),u,d;try{let p=await(0,Ni.loadAgentManifest)(f);u=p.metadata.description,d=p.spec.engine}catch{}n.push({id:s,versions:o,currentVersion:a,description:u,preferredEngine:d})}return n}async function au(t){try{let e=await qe.promises.readdir(t,{withFileTypes:!0}),n=[];for(let r of e){if(!r.isDirectory()||r.name.startsWith("."))continue;let s=Be.join(t,r.name,ae.AGENT_CONSTANTS.MANIFEST_FILE);if(await(0,te.pathExists)(s))try{await(0,Ni.loadAgentManifest)(s),n.push(r.name)}catch{}}return Rb(n)}catch{return[]}}async function Ga(t){let e=(0,ae.getUserAgentCurrentPath)(t);try{let n=(await qe.promises.readFile(e,"utf8")).trim();if(!n)return;let r=(0,ae.getUserAgentVersionDir)(t,n),s=Be.join(r,ae.AGENT_CONSTANTS.MANIFEST_FILE);if(!await(0,te.pathExists)(s))return;try{return await(0,Ni.loadAgentManifest)(s),n}catch{return}}catch{}}async function kb(t,e){let n=(0,ae.getAgentManifestPath)(t,e);if(!await(0,te.pathExists)(n))return!1;try{return(await(0,Ni.loadAgentManifest)(n)).metadata.name===e}catch{return!1}}async function $b(t){if(await Ga(t))return!0;let n=(0,ae.getUserAgentRoot)(t);return(await au(n)).length>0}async function Ig(t,e,n,r){let s=n,i=n??"current";if(!s&&(s=await Ga(e),!s)){let d=(0,ae.getUserAgentRoot)(e),p=await au(d);if(p.length===0){(0,te.logInfo)(r,`[AgentStores] Agent not in User Library: ${e}`);return}s=p[p.length-1],i=s}let o=(0,ae.getUserAgentVersionDir)(e,s);if(!await(0,te.pathExists)(o)){(0,te.logInfo)(r,`[AgentStores] Version not found in User Library: ${e}@${s}`);return}let a=(0,ae.getAgentRoot)(t,e);(0,te.logInfo)(r,`[AgentStores] Hydrating ${e}@${s} from User Library`),await(0,te.pathExists)(a)&&((0,te.logInfo)(r,`[AgentStores] Clearing existing directory: ${a}`),await qe.promises.rm(a,{recursive:!0,force:!0})),await(0,te.copyDirRecursive)(o,a);let c=Be.join(a,ae.AGENT_CONSTANTS.MANIFEST_FILE),{sha256:l}=await(0,te.readFileSha256)(c),f={source:"user-library",agentId:e,version:s,resolvedFrom:i,sha256:l,hydratedAt:new Date().toISOString()},u=Be.join(a,ae.AGENT_CONSTANTS.SOURCE_FILE);return await qe.promises.writeFile(u,JSON.stringify(f,null,2),"utf8"),(0,te.logInfo)(r,`[AgentStores] Hydrated ${e}@${s} to ${a}`),s}async function Db(t,e,n){if(e===ae.AGENT_CONSTANTS.DEFAULT_AGENT_ID)throw new Error("Cannot promote the default agent to User Library");let r=(0,ae.getAgentRoot)(t,e),s=(0,ae.getAgentManifestPath)(t,e);if(!await(0,te.pathExists)(s))throw new Error(`Agent not found: ${e}`);let o=(await(0,Ni.loadAgentManifest)(s)).metadata.version,a=(0,ae.getUserAgentVersionDir)(e,o),c=Be.join(a,ae.AGENT_CONSTANTS.MANIFEST_FILE);if(await(0,te.pathExists)(c)){let f=await(0,te.readFileSha256)(s),u=await(0,te.readFileSha256)(c);if(f.sha256===u.sha256)return(0,te.logInfo)(n,`[AgentStores] ${e}@${o} already in User Library (identical)`),o;throw new Error(`Version conflict: ${e}@${o} already exists in User Library with different content. Bump the version in agent.yaml and try again.`)}(0,te.logInfo)(n,`[AgentStores] Promoting ${e}@${o} to User Library`),await qe.promises.mkdir(a,{recursive:!0}),await ou(r,a);let l=(0,ae.getUserAgentCurrentPath)(e);return await qe.promises.writeFile(l,o,"utf8"),(0,te.logInfo)(n,`[AgentStores] Promoted ${e}@${o} to ${a}`),o}async function Pg(t,e){let n=Be.join((0,ae.getAgentRoot)(t,e),ae.AGENT_CONSTANTS.SOURCE_FILE);try{let r=await qe.promises.readFile(n,"utf8");return JSON.parse(r)}catch{return}}async function Lb(t,e){let n=await Pg(t,e);if(!n||n.source!=="user-library")return;let r=await Ga(e);if(r&&r!==n.version)return r}async function Mb(t,e,n,r){let s=(0,ae.getAgentRoot)(t,e),i=new Date().toISOString().replace(/[:.]/g,"-"),o=Be.join(Be.dirname(s),`.${e}.backup-${i}`);await(0,te.pathExists)(s)&&((0,te.logInfo)(r,`[AgentStores] Backing up ${e} to ${o}`),await(0,te.copyDirRecursive)(s,o),await qe.promises.rm(s,{recursive:!0,force:!0}));let a=await Ig(t,e,n,r);if(!a)throw await(0,te.pathExists)(o)&&((0,te.logInfo)(r,"[AgentStores] Restoring backup after failed update"),await(0,te.copyDirRecursive)(o,s)),new Error(`Failed to update ${e} from User Library`);return(0,te.logInfo)(r,`[AgentStores] Updated ${e} to ${a}`),a}async function Gb(t,e){let n=`${e}-copy`;if(!await(0,te.pathExists)((0,ae.getAgentRoot)(t,n)))return n;for(let r=2;r<100;r++){let s=`${e}-${r}`;if(!await(0,te.pathExists)((0,ae.getAgentRoot)(t,s)))return s}return`${e}-${Date.now()}`}async function Ub(t,e,n){let r=(0,ae.getAgentRoot)(t,e),s=(0,ae.getAgentManifestPath)(t,e);if(!await(0,te.pathExists)(s))throw new Error(`Agent not found: ${e}`);let i=await Gb(t,e),o=(0,ae.getAgentRoot)(t,i);(0,te.logInfo)(n,`[AgentStores] Duplicating ${e} to ${i}`),await ou(r,o);let a=(0,ae.getAgentManifestPath)(t,i);await(0,Ni.updateManifestName)(a,i);let c=Be.join(o,ae.AGENT_CONSTANTS.SOURCE_FILE);try{await qe.promises.rm(c,{force:!0})}catch{}return(0,te.logInfo)(n,`[AgentStores] Duplicated ${e} to ${i}`),i}async function Hb(t,e,n){let r=(0,ae.getAgentRoot)(t,ae.AGENT_CONSTANTS.DEFAULT_AGENT_ID),s=new Date().toISOString().replace(/[:.]/g,"-"),i=Be.join(Be.dirname(r),`.default.backup-${s}`);if(await(0,te.pathExists)(r)&&((0,te.logInfo)(n,`[AgentStores] Backing up default agent to ${i}`),await(0,te.copyDirRecursive)(r,i),await qe.promises.rm(r,{recursive:!0,force:!0})),await qe.promises.mkdir(r,{recursive:!0}),await qe.promises.mkdir(Be.join(r,ae.AGENT_CONSTANTS.RULES_DIR),{recursive:!0}),await qe.promises.mkdir(Be.join(r,ae.AGENT_CONSTANTS.SKILLS_DIR),{recursive:!0}),e){let c=Be.join(e,"rules","AGENTS.md"),l=Be.join(r,ae.AGENT_CONSTANTS.AGENTS_MD);if(await(0,te.pathExists)(c)){let p=await qe.promises.readFile(c,"utf8");await qe.promises.writeFile(l,(0,Og.applyBrandingTokens)(p),"utf8"),(0,te.logInfo)(n,"[AgentStores] Restored AGENTS.md from bundled templates")}let f=Be.join(e,ae.AGENT_CONSTANTS.GHOST_TEXT_FILE),u=Be.join(r,ae.AGENT_CONSTANTS.GHOST_TEXT_FILE);if(await(0,te.pathExists)(f)&&!await(0,te.pathExists)(u)){let p=await qe.promises.readFile(f,"utf8");await qe.promises.writeFile(u,p,"utf8"),(0,te.logInfo)(n,"[AgentStores] Restored GHOST_TEXT.md from bundled templates")}let d=Be.join(e,"skills");if(await(0,te.pathExists)(d)){let p=await qe.promises.readdir(d,{withFileTypes:!0});for(let g of p){if(!g.isDirectory())continue;let m=Be.join(d,g.name),h=Be.join(r,ae.AGENT_CONSTANTS.SKILLS_DIR,g.name);await(0,te.copyDirRecursiveWithTransform)(m,h,Og.applyBrandingTokens),(0,te.logInfo)(n,`[AgentStores] Restored skill: ${g.name}`)}}}let o=(0,ae.generateDefaultAgentYaml)({model:"claude"}),a=Be.join(r,ae.AGENT_CONSTANTS.MANIFEST_FILE);await qe.promises.writeFile(a,o,"utf8"),(0,te.logInfo)(n,"[AgentStores] Reset default agent complete")}});var Ng=S((exports,module)=>{"use strict";var __createBinding=exports&&exports.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,s)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),__setModuleDefault=exports&&exports.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),__importStar=exports&&exports.__importStar||(function(){var t=function(e){return t=Object.getOwnPropertyNames||function(n){var r=[];for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(r[r.length]=s);return r},t(e)};return function(e){if(e&&e.__esModule)return e;var n={};if(e!=null)for(var r=t(e),s=0;s<r.length;s++)r[s]!=="default"&&__createBinding(n,e,r[s]);return __setModuleDefault(n,e),n}})();Object.defineProperty(exports,"__esModule",{value:!0});exports.AgentPackManager=void 0;var fs_1=require("fs"),path=__importStar(require("path")),_vscode;function getVscode(){return _vscode||(_vscode=eval("require")("vscode")),_vscode}var paths_1=Un(),manifest_1=Qs(),utils_1=en(),stores_1=cu(),AgentPackManager=class{syncService;getWorkspaceRoot;getStorageUri;outputChannel;constructor(e,n,r,s){this.syncService=e,this.getWorkspaceRoot=n,this.getStorageUri=r,this.outputChannel=s}async installFromLocal(e){let n=this.getWorkspaceRoot(),r=this.getStorageUri(),s=path.join(e,paths_1.AGENT_CONSTANTS.MANIFEST_FILE);if(!await(0,utils_1.pathExists)(s))throw new Error(`No agent.yaml found at ${e}`);let i=await(0,manifest_1.loadAgentManifest)(s),o=i.metadata.name,a=i.metadata.version;if((0,paths_1.isDefaultAgent)(o))throw new Error('Cannot install an agent with reserved ID "default"');(0,utils_1.logInfo)(this.outputChannel,`[Agent] Installing: ${o}@${a} from ${e}`);let c=(0,paths_1.resolveAgentRuntimePaths)(n,r,o,a);await this.createAgentDirectories(c);let l=c.agentRoot;path.resolve(e)!==path.resolve(l)&&((0,utils_1.logInfo)(this.outputChannel,`[Agent] Copying ${e} to ${l}`),await(0,utils_1.copyDirRecursive)(e,l));let f=await this.registerAgent(o,{source:"local"});return await this.syncService.seedAgentDataIfNeeded(n,o,this.outputChannel),(0,utils_1.logInfo)(this.outputChannel,`[Agent] Successfully installed: ${o}@${a}`),f}async uninstall(e){let n=this.getWorkspaceRoot(),r=this.getStorageUri();if((0,paths_1.isDefaultAgent)(e))throw new Error("Cannot uninstall the default agent");(0,utils_1.logInfo)(this.outputChannel,`[Agent] Uninstalling: ${e}`);let s=(0,paths_1.resolveAgentRuntimePaths)(n,r,e);await(0,utils_1.pathExists)(s.agentRoot)&&(await fs_1.promises.rm(s.agentRoot,{recursive:!0,force:!0}),(0,utils_1.logInfo)(this.outputChannel,`[Agent] Removed directory: ${s.agentRoot}`)),await(0,utils_1.pathExists)(s.codexHome)&&await fs_1.promises.rm(s.codexHome,{recursive:!0,force:!0}),await(0,utils_1.pathExists)(s.claudeConfigDir)&&await fs_1.promises.rm(s.claudeConfigDir,{recursive:!0,force:!0}),await this.syncService.removeInstalledAgent(n,e,this.outputChannel);try{await getVscode().commands.executeCommand("agentide.packsChanged")}catch{}(0,utils_1.logInfo)(this.outputChannel,`[Agent] Successfully uninstalled: ${e}`)}async listInstalled(){let e=this.getWorkspaceRoot();return this.syncService.loadInstalledAgents(e)}async getInstalledAgent(e){return(await this.listInstalled()).find(r=>r.id===e)}async isInstalled(e){return await this.getInstalledAgent(e)!==void 0}async cleanupStaleAgents(){let e=this.getWorkspaceRoot(),n=await this.listInstalled(),r=[];for(let s of n){let i=(0,paths_1.getAgentManifestPath)(e,s.id);await(0,utils_1.pathExists)(i)||r.push(s.id)}for(let s of r)(0,utils_1.logInfo)(this.outputChannel,`[Agent] Removing stale entry: ${s} (folder missing)`),await this.syncService.removeInstalledAgent(e,s,this.outputChannel);if(r.length>0){(0,utils_1.logInfo)(this.outputChannel,`[Agent] Cleaned up ${r.length} stale agent(s)`);try{await getVscode().commands.executeCommand("agentide.packsChanged")}catch{}}return r}async listInstalledWithCleanup(e=!0){return e&&await this.cleanupStaleAgents(),this.listInstalled()}getAgentRuntimePaths(e,n){let r=this.getWorkspaceRoot(),s=this.getStorageUri();return(0,paths_1.resolveAgentRuntimePaths)(r,s,e,n)}async createAgentDirectories(e){await fs_1.promises.mkdir(e.agentRoot,{recursive:!0}),await fs_1.promises.mkdir(e.rulesDir,{recursive:!0}),await fs_1.promises.mkdir(e.skillsDir,{recursive:!0}),await fs_1.promises.mkdir(e.mcpDir,{recursive:!0}),await fs_1.promises.mkdir(e.codexHome,{recursive:!0}),await fs_1.promises.mkdir(e.claudeConfigDir,{recursive:!0})}async buildInstalledAgent(e,n,r){let s=(0,paths_1.getAgentManifestPath)(e,n),i=await(0,manifest_1.loadAgentManifest)(s),o=await(0,utils_1.readFileSha256)(s),a=r?.source??((0,paths_1.isDefaultAgent)(n)?"builtin":"local"),c=r?.agentRootOverride??`${paths_1.AGENT_CONSTANTS.AGENTS_DIR}/${n}`;return{id:n,version:i.metadata.version,source:a,installedAt:new Date().toISOString(),manifestHash:o.sha256,featureSetHash:o.sha256,skillsSignature:o.sha256,promptsSignature:o.sha256,agentRoot:c,preferredEngine:i.spec.engine,preferredModel:i.spec.model,preferredCheapModel:i.spec.cheapModel,status:"active"}}async registerAgent(e,n){let r=this.getWorkspaceRoot(),s=await this.buildInstalledAgent(r,e,n);await this.syncService.updateInstalledAgent(r,s,this.outputChannel);try{await getVscode().commands.executeCommand("agentide.packsChanged")}catch{}return s}async discoverAgents(){let e=this.getWorkspaceRoot(),n=(0,paths_1.getAgentsDir)(e);if(!await(0,utils_1.pathExists)(n))return[];let r=await fs_1.promises.readdir(n,{withFileTypes:!0}),s=[];for(let i of r){if(!i.isDirectory()||i.name.startsWith("."))continue;let o=(0,paths_1.getAgentManifestPath)(e,i.name);await(0,utils_1.pathExists)(o)&&s.push(i.name)}return s}async repairUnregisteredAgents(){let e=this.getWorkspaceRoot(),n=(0,paths_1.getAgentsDir)(e);if(!await(0,utils_1.pathExists)(n))return{registered:[],alreadyRegistered:[]};let r=await this.listInstalled(),s=new Set(r.map(c=>c.id)),i=await this.discoverAgents(),o=[],a=[];for(let c of i){if(s.has(c)){a.push(c);continue}try{await this.registerAgent(c),o.push(c),(0,utils_1.logInfo)(this.outputChannel,`[Agent] Repaired: registered untracked agent "${c}"`)}catch(l){(0,utils_1.logInfo)(this.outputChannel,`[Agent] Failed to repair agent "${c}": ${l instanceof Error?l.message:String(l)}`)}}return o.length>0&&(0,utils_1.logInfo)(this.outputChannel,`[Agent] Repair complete: ${o.length} agent(s) registered`),{registered:o,alreadyRegistered:a}}async installAgentToWorkspace(e){let n=this.getWorkspaceRoot();if(await(0,stores_1.isWorkspaceAgentAvailable)(n,e))return(0,utils_1.logInfo)(this.outputChannel,`[Agent] Agent available in workspace: ${e}`),await this.getInstalledAgent(e)||((0,utils_1.logInfo)(this.outputChannel,`[Agent] Registering untracked agent: ${e}`),await this.registerAgent(e)),await this.syncService.seedAgentDataIfNeeded(n,e,this.outputChannel),{installed:!0,hydrated:!1};if(await(0,stores_1.isAgentInUserLibrary)(e)){(0,utils_1.logInfo)(this.outputChannel,`[Agent] Hydrating from User Library: ${e}`);let r=await(0,stores_1.hydrateFromUserLibrary)(n,e,void 0,this.outputChannel);if(r)return await this.registerAgent(e,{source:"local"}),{installed:!0,hydrated:!0,version:r}}return(0,utils_1.logInfo)(this.outputChannel,`[Agent] Agent not found: ${e}`),{installed:!1,hydrated:!1}}async shareToUserLibrary(e){let n=this.getWorkspaceRoot();return(0,stores_1.promoteToUserLibrary)(n,e,this.outputChannel)}async updateFromLibrary(e,n){let r=this.getWorkspaceRoot();return(0,stores_1.updateFromUserLibrary)(r,e,n,this.outputChannel)}async duplicate(e){let n=this.getWorkspaceRoot(),r=await(0,stores_1.duplicateAgent)(n,e,this.outputChannel);return await this.registerAgent(r,{source:"local"}),r}async resetDefault(e){let n=this.getWorkspaceRoot();await(0,stores_1.resetDefaultAgent)(n,e,this.outputChannel);let r=(0,paths_1.getAgentManifestPath)(n,paths_1.AGENT_CONSTANTS.DEFAULT_AGENT_ID);await(0,utils_1.pathExists)(r)&&await this.registerAgent(paths_1.AGENT_CONSTANTS.DEFAULT_AGENT_ID,{source:"builtin"})}async listUserLibrary(){return(0,stores_1.listUserLibraryAgents)()}async checkAgentUpdate(e){let n=this.getWorkspaceRoot();return(0,stores_1.checkForUpdate)(n,e)}async getAgentSource(e){let n=this.getWorkspaceRoot();return(0,stores_1.readAgentSource)(n,e)}};exports.AgentPackManager=AgentPackManager});var fo=S((exports,module)=>{"use strict";Object.defineProperty(exports,"__esModule",{value:!0});exports.getGitHubToken=getGitHubToken;exports.isGitHubAuthenticated=isGitHubAuthenticated;exports.getGitHubUser=getGitHubUser;exports.getRepo=getRepo;exports.createRepo=createRepo;exports.getReleaseByTag=getReleaseByTag;exports.getLatestRelease=getLatestRelease;exports.createRelease=createRelease;exports.downloadTarball=downloadTarball;exports.getFileContent=getFileContent;exports.putFileContent=putFileContent;exports.getDefaultBranch=getDefaultBranch;exports.getBranchSha=getBranchSha;exports.createBranch=createBranch;exports.createPullRequest=createPullRequest;exports.commitMultipleFiles=commitMultipleFiles;exports.parseGitHubSource=parseGitHubSource;exports.formatGitHubSource=formatGitHubSource;var _vscode;function getVscode(){return _vscode||(_vscode=eval("require")("vscode")),_vscode}async function getGitHubToken(t=!0,e=["repo","user"]){let n=process.env.GITHUB_TOKEN||process.env.GH_TOKEN||process.env.AGENTHIPPO_GITHUB_TOKEN;if(n?.trim())return n.trim();let s=await getVscode().authentication.getSession("github",e,{createIfNone:t});if(!s)throw new Error("GitHub authentication required. Please sign in.");return s.accessToken}async function isGitHubAuthenticated(){try{return await getGitHubToken(!1),!0}catch{return!1}}async function getGitHubUser(){let t=await getGitHubToken(),e=await fetch("https://api.github.com/user",{headers:{Authorization:`Bearer ${t}`,Accept:"application/vnd.github.v3+json","User-Agent":"AgentIDE"}});if(!e.ok)throw new Error(`Failed to get GitHub user: ${e.statusText}`);return e.json()}async function getRepo(t,e){let n=await getGitHubToken(),r=await fetch(`https://api.github.com/repos/${t}/${e}`,{headers:{Authorization:`Bearer ${n}`,Accept:"application/vnd.github.v3+json","User-Agent":"AgentIDE"}});if(r.status===404)return null;if(!r.ok)throw new Error(`Failed to get repo: ${r.statusText}`);return r.json()}async function createRepo(t,e,n){let r=await getGitHubToken(),s=await fetch("https://api.github.com/user/repos",{method:"POST",headers:{Authorization:`Bearer ${r}`,Accept:"application/vnd.github.v3+json","User-Agent":"AgentIDE","Content-Type":"application/json"},body:JSON.stringify({name:t,description:e,private:n,auto_init:!1})});if(!s.ok){let i=await s.text();throw new Error(`Failed to create repo: ${i}`)}return s.json()}async function getReleaseByTag(t,e,n){let r=await getGitHubToken(),s=await fetch(`https://api.github.com/repos/${t}/${e}/releases/tags/${n}`,{headers:{Authorization:`Bearer ${r}`,Accept:"application/vnd.github.v3+json","User-Agent":"AgentIDE"}});if(s.status===404)return null;if(!s.ok)throw new Error(`Failed to get release: ${s.statusText}`);return s.json()}async function getLatestRelease(t,e){let n=await getGitHubToken(),r=await fetch(`https://api.github.com/repos/${t}/${e}/releases/latest`,{headers:{Authorization:`Bearer ${n}`,Accept:"application/vnd.github.v3+json","User-Agent":"AgentIDE"}});if(r.status===404)return null;if(!r.ok)throw new Error(`Failed to get latest release: ${r.statusText}`);return r.json()}async function createRelease(t,e,n,r,s,i){let o=await getGitHubToken(),a=await fetch(`https://api.github.com/repos/${t}/${e}/releases`,{method:"POST",headers:{Authorization:`Bearer ${o}`,Accept:"application/vnd.github.v3+json","User-Agent":"AgentIDE","Content-Type":"application/json"},body:JSON.stringify({tag_name:n,name:r,body:s,target_commitish:i})});if(!a.ok){let c=await a.text();throw new Error(`Failed to create release: ${c}`)}return a.json()}async function downloadTarball(t,e,n){let r=await getGitHubToken(),s=await fetch(`https://api.github.com/repos/${t}/${e}/tarball/${n}`,{headers:{Authorization:`Bearer ${r}`,Accept:"application/vnd.github.v3+json","User-Agent":"AgentIDE"},redirect:"follow"});if(!s.ok)throw new Error(`Failed to download tarball: ${s.statusText}`);return s.arrayBuffer()}async function getFileContent(t,e,n,r){let s=await getGitHubToken(),i=new URL(`https://api.github.com/repos/${t}/${e}/contents/${n}`);r&&i.searchParams.set("ref",r);let o=await fetch(i.toString(),{headers:{Authorization:`Bearer ${s}`,Accept:"application/vnd.github.v3+json","User-Agent":"AgentIDE"}});if(o.status===404)return null;if(!o.ok)throw new Error(`Failed to get file content: ${o.statusText}`);let a=await o.json();return{content:Buffer.from(a.content,"base64").toString("utf-8"),sha:a.sha}}async function putFileContent(t,e,n,r,s,i,o){let a=await getGitHubToken(),c=await fetch(`https://api.github.com/repos/${t}/${e}/contents/${n}`,{method:"PUT",headers:{Authorization:`Bearer ${a}`,Accept:"application/vnd.github.v3+json","User-Agent":"AgentIDE","Content-Type":"application/json"},body:JSON.stringify({message:s,content:Buffer.from(r).toString("base64"),sha:i,branch:o})});if(!c.ok){let l=await c.text();throw new Error(`Failed to put file content: ${l}`)}}async function getDefaultBranch(t,e){let n=await getRepo(t,e);if(!n)throw new Error(`Repository ${t}/${e} not found`);return n.default_branch}async function getBranchSha(t,e,n){let r=await getGitHubToken(),s=await fetch(`https://api.github.com/repos/${t}/${e}/git/refs/heads/${n}`,{headers:{Authorization:`Bearer ${r}`,Accept:"application/vnd.github.v3+json","User-Agent":"AgentHippo"}});if(!s.ok)throw new Error(`Failed to get branch ${n}: ${s.status}`);return(await s.json()).object.sha}async function createBranch(t,e,n,r){let s=await getGitHubToken(),i=await getBranchSha(t,e,r),o=await fetch(`https://api.github.com/repos/${t}/${e}/git/refs`,{method:"POST",headers:{Authorization:`Bearer ${s}`,Accept:"application/vnd.github.v3+json","User-Agent":"AgentHippo","Content-Type":"application/json"},body:JSON.stringify({ref:`refs/heads/${n}`,sha:i})});if(!o.ok){let a=await o.text();throw new Error(`Failed to create branch ${n}: ${o.status} ${a}`)}}async function createPullRequest(t,e,n){let r=await getGitHubToken(),s=await fetch(`https://api.github.com/repos/${t}/${e}/pulls`,{method:"POST",headers:{Authorization:`Bearer ${r}`,Accept:"application/vnd.github.v3+json","User-Agent":"AgentHippo","Content-Type":"application/json"},body:JSON.stringify({title:n.title,body:n.body,head:n.head,base:n.base})});if(!s.ok){let i=await s.text();throw new Error(`Failed to create pull request: ${s.status} ${i}`)}return await s.json()}async function commitMultipleFiles(t,e,n,r,s,i){let a={Authorization:`Bearer ${await getGitHubToken(!0,i?.scopes)}`,Accept:"application/vnd.github.v3+json","User-Agent":"AgentHippo","Content-Type":"application/json"};await new Promise(b=>setTimeout(b,500));let c=await fetch(`https://api.github.com/repos/${t}/${e}/git/refs/heads/${n}`,{headers:a});if(!c.ok){let b=await c.text();throw new Error(`Failed to get branch ref for ${n}: ${c.status} - ${b}`)}let f=(await c.json()).object.sha,u=await fetch(`https://api.github.com/repos/${t}/${e}/git/commits/${f}`,{headers:a});if(!u.ok){let b=await u.text();throw new Error(`Failed to get commit ${f}: ${u.status} - ${b}`)}let p=(await u.json()).tree.sha,g=[];for(let b of r){let T=b.encoding??"utf-8",O=await fetch(`https://api.github.com/repos/${t}/${e}/git/blobs`,{method:"POST",headers:a,body:JSON.stringify({content:b.content,encoding:T})});if(!O.ok){let v=await O.text();throw new Error(`Failed to create blob for ${b.path}: ${O.status} - ${v}`)}let A=await O.json();g.push({path:b.path,mode:"100644",type:"blob",sha:A.sha})}console.log("[AgentHippo] Repo:",`${t}/${e}`),console.log("[AgentHippo] Branch:",n),console.log("[AgentHippo] Creating tree with base:",p),console.log("[AgentHippo] Tree items:",JSON.stringify(g,null,2));let m=await fetch(`https://api.github.com/repos/${t}/${e}/git/trees`,{method:"POST",headers:a,body:JSON.stringify({base_tree:p,tree:g})});if(m.status===404&&(console.log("[AgentHippo] Retrying tree creation without base_tree..."),m=await fetch(`https://api.github.com/repos/${t}/${e}/git/trees`,{method:"POST",headers:a,body:JSON.stringify({tree:g})})),!m.ok)return console.log("[AgentHippo] Git Data API failed, falling back to Contents API..."),await commitMultipleFilesViaContentsApi(t,e,n,r,s,a);let h=await m.json(),E=await fetch(`https://api.github.com/repos/${t}/${e}/git/commits`,{method:"POST",headers:a,body:JSON.stringify({message:s,tree:h.sha,parents:[f]})});if(!E.ok)throw new Error(`Failed to create commit: ${E.status}`);let _=await E.json(),y=await fetch(`https://api.github.com/repos/${t}/${e}/git/refs/heads/${n}`,{method:"PATCH",headers:a,body:JSON.stringify({sha:_.sha})});if(!y.ok)throw new Error(`Failed to update ref: ${y.status}`);return{sha:_.sha}}async function commitMultipleFilesViaContentsApi(t,e,n,r,s,i){let o="";for(let a of r){let c=encodeURIComponent(n),l=await fetch(`https://api.github.com/repos/${t}/${e}/contents/${a.path}?ref=${c}`,{headers:i}),f=l.ok?(await l.json()).sha:void 0,u=await fetch(`https://api.github.com/repos/${t}/${e}/contents/${a.path}`,{method:"PUT",headers:i,body:JSON.stringify({message:`${s} - ${a.path}`,content:a.encoding==="base64"?a.content:Buffer.from(a.content,"utf-8").toString("base64"),branch:n,sha:f})});if(!u.ok){let p=await u.text();throw new Error(`Failed to create file ${a.path}: ${u.status} - ${p}`)}o=(await u.json()).commit.sha,console.log(`[AgentHippo] Created ${a.path}`)}return{sha:o}}function parseGitHubSource(t){let e=t.trim();e=e.replace(/^github:\/\//,""),e=e.replace(/^https?:\/\/github\.com\//,""),e=e.replace(/\.git$/,"");let n;if(e.includes("@")){let i=e.split("@");e=i[0],n=i[1]}let[r,s]=e.split("/");if(!r||!s)throw new Error(`Invalid GitHub source: ${t}. Expected format: owner/repo[@version]`);return{owner:r,repo:s,version:n}}function formatGitHubSource(t){let e=`github://${t.owner}/${t.repo}`;return t.version&&(e+=`@${t.version}`),e}});var Lg=S($r=>{"use strict";var jb=$r&&$r.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,s)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),xb=$r&&$r.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),Bb=$r&&$r.__importStar||(function(){var t=function(e){return t=Object.getOwnPropertyNames||function(n){var r=[];for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(r[r.length]=s);return r},t(e)};return function(e){if(e&&e.__esModule)return e;var n={};if(e!=null)for(var r=t(e),s=0;s<r.length;s++)r[s]!=="default"&&jb(n,e,r[s]);return xb(n,e),n}})();Object.defineProperty($r,"__esModule",{value:!0});$r.validateForPublish=$g;$r.publishToGitHub=Vb;var lu=require("fs"),Cg=Bb(require("path")),dn=en(),kg=Qs(),Ha=Un(),Zs=fo(),Fb=[".","..",".git",".claude",".codex",".agentide","node_modules","*.log","current.txt"],Rg=1024*1024,Ua=10*1024*1024;async function $g(t,e){let n=[],r=[],s=(0,Ha.getAgentRoot)(t,e);if(!await(0,dn.pathExists)(s))return n.push(`Agent directory not found: ${s}`),{valid:!1,errors:n,warnings:r};let i=["agent.yaml","AGENTS.md"];for(let l of i){let f=Cg.join(s,l);await(0,dn.pathExists)(f)||n.push(`Missing required file: ${l}`)}let o=(0,Ha.getAgentManifestPath)(t,e);if(await(0,dn.pathExists)(o))try{let l=await(0,kg.loadAgentManifest)(o);l.metadata.name||n.push("agent.yaml missing metadata.name"),l.metadata.version?/^\d+\.\d+\.\d+/.test(l.metadata.version)||n.push(`Invalid version format: ${l.metadata.version}. Use semver (e.g., 1.0.0)`):n.push("agent.yaml missing metadata.version"),l.metadata.description||r.push("Consider adding a description to agent.yaml"),l.metadata.author||r.push("Consider adding an author to agent.yaml")}catch(l){n.push(`Invalid agent.yaml: ${l instanceof Error?l.message:String(l)}`)}let a=await Dg(s),c=a.reduce((l,f)=>l+f.size,0);c>Ua?n.push(`Bundle too large: ${Ri(c)} (max ${Ri(Ua)})`):c>Ua*.8&&r.push(`Bundle is ${Ri(c)}, approaching limit of ${Ri(Ua)}`);for(let l of a)l.size>Rg&&n.push(`File too large: ${l.relativePath} (${Ri(l.size)}, max ${Ri(Rg)})`);return{valid:n.length===0,errors:n,warnings:r}}async function Dg(t){let e=[];async function n(r,s){let i;try{i=await lu.promises.readdir(r)}catch{return}for(let o of i){if(Fb.some(f=>o===f||o.startsWith(".")))continue;let a=Cg.join(r,o),c=s?`${s}/${o}`:o,l=await lu.promises.stat(a);l.isDirectory()?await n(a,c):l.isFile()&&e.push({relativePath:c,absolutePath:a,size:l.size})}}return await n(t,""),e}async function Vb(t,e,n){let{agentId:r,visibility:s,changelog:i}=e;(0,dn.logInfo)(n,`[Publish] Starting publish for ${r}...`);let o=await $g(t,r);if(!o.valid)throw new Error(`Validation failed:
39
+ `).replace(/^\n+/,"");try{await writeFileIfChanged(i,g)&&logInfo(e,`[AgentIDE] Updated ${i} to ignore ${branding_1.AGENTIDE_BRAND_NAME} directories`)}catch(m){logInfo(e,`[AgentIDE] Warning: failed to write root .gitignore: ${m instanceof Error?m.message:String(m)}`)}}async function readFileSha256(t){let e=await fs_1.promises.stat(t),n=crypto.createHash("sha256");return await(0,promises_1.pipeline)((0,fs_1.createReadStream)(t),n),{sha256:n.digest("hex"),size:e.size,mtimeMs:e.mtimeMs}}async function getFileStats(t){try{let e=await fs_1.promises.stat(t);return{size:e.size,mtimeMs:e.mtimeMs}}catch(e){if(getErrorCode(e)==="ENOENT")return;throw e}}function isCachedHashValid(t,e){if(!(!t||!e)&&t.mtimeMs===e.mtimeMs&&t.size===e.size)return t}function shortSig(t){return crypto.createHash("sha256").update(t).digest("hex").slice(0,16)}var LOCAL_TLS_HOSTNAMES=new Set(["localhost","127.0.0.1","0.0.0.0","::1","[::1]"]);function isLocalHttps(t){if(!t)return!1;try{let e=new URL(t);return e.protocol==="https:"&&LOCAL_TLS_HOSTNAMES.has(e.hostname.toLowerCase())}catch{return!1}}function applyLocalTlsBypass(t,e){return isLocalHttps(e)?(t.NODE_TLS_REJECT_UNAUTHORIZED="0",!0):!1}function getOverrideOpenAIBaseUrl(t,e){if(!e)return;let n=e.getCustomProviders(),r=t.replace(/\/$/,"");for(let s of Object.values(n))if(s.baseUrl){let i=s.baseUrl.replace(/\/$/,"");if(r===i&&s.overrideOpenAIBaseUrl)return s.overrideOpenAIBaseUrl.trim()}}function inferModelProvider(t){return t&&/claude|anthropic/i.test(t)?"anthropic":"openai"}function resolveApiRouting(t,e,n,r){let s=t.useLiteLLM===!0,i=t.baseUrl||(s?e.litellmBaseUrl:void 0),o=n==="anthropic"?e.anthropicApiKey:e.openaiApiKey,a=s?t.apiKey||e.litellmApiKey||"sk-dummy":t.apiKey||o||"",c=i;if(i){let l=getOverrideOpenAIBaseUrl(i,r);l&&(c=l)}return{apiKey:a,baseUrl:i,openaiBaseUrl:c,useLiteLLM:s}}function getExplicitConfigValue(t,e){let n=t.inspect(e);if(n)return n.workspaceFolderValue??n.workspaceValue??n.globalValue}function getAgentideEngineSettings(t){return t?t.getEngineSettings():{claudeMaxThinkingTokens:0}}async function emitStreamEvent(t){try{await getVscode().commands.executeCommand("agentide.streamCallback",t)}catch(e){console.error("[AgentIDE Extension] Failed to emit stream event:",e)}}var STREAM_COALESCE_WINDOW_MS=40,STREAM_COALESCE_MIN_CHARS=120;function flushCoalescedBuffers(t,e){let n=[];return e.markdownBuffer&&(n.push(emitStreamEvent({streamId:t,type:"markdown",data:e.markdownBuffer})),e.markdownBuffer=""),e.thinkingBuffer&&(n.push(emitStreamEvent({streamId:t,type:"thinking",data:e.thinkingBuffer})),e.thinkingBuffer=""),e.flushTimer&&(clearTimeout(e.flushTimer),e.flushTimer=void 0),Promise.all(n).then(()=>{})}function ensureFlushTimer(t,e){e.flushTimer||(e.flushTimer=setTimeout(()=>{flushCoalescedBuffers(t,e)},STREAM_COALESCE_WINDOW_MS))}function createIPCStreamEmitter(t){let e={markdownBuffer:"",thinkingBuffer:"",flushTimer:void 0};return{async thinking(n){if(n){if(e.thinkingBuffer+=n,e.thinkingBuffer.length>=STREAM_COALESCE_MIN_CHARS){await flushCoalescedBuffers(t,e);return}ensureFlushTimer(t,e)}},async text(n){if(n){if(e.markdownBuffer+=n,e.markdownBuffer.length>=STREAM_COALESCE_MIN_CHARS){await flushCoalescedBuffers(t,e);return}ensureFlushTimer(t,e)}},async toolStart(n,r,s,i){await flushCoalescedBuffers(t,e),await emitStreamEvent({streamId:t,type:"tool_use",toolName:n,toolCallId:s,data:r||"",metadata:i})},async toolEnd(n,r,s,i,o){await flushCoalescedBuffers(t,e),await emitStreamEvent({streamId:t,type:"tool_end",toolName:n,toolCallId:r,data:s||"",metadata:{...o&&typeof o=="object"?o:{},isError:i}})},async progress(n){await flushCoalescedBuffers(t,e),await emitStreamEvent({streamId:t,type:"progress",data:n})},async question(n){return await flushCoalescedBuffers(t,e),await emitStreamEvent({streamId:t,type:"question",metadata:n}),{selected:[],freeText:null,declined:!0}},async error(n){await flushCoalescedBuffers(t,e),await emitStreamEvent({streamId:t,type:"error",data:n})},async done(){await flushCoalescedBuffers(t,e),await emitStreamEvent({streamId:t,type:"done"})}}}function computeTextDelta(t,e,n){let r=n.get(t)??"",s=e.startsWith(r)?e.slice(r.length):e;return n.set(t,e),s}function createDeferred(){let t,e;return{promise:new Promise((r,s)=>{t=r,e=s}),resolve:t,reject:e}}function stableAdditionalDirs(t){return(t??[]).slice().filter(Boolean).sort()}var paths_1=Ys();Object.defineProperty(exports,"getAnalyticsScriptsDir",{enumerable:!0,get:function(){return paths_1.getAnalyticsScriptsDir}});var CREATE_CMD_PATTERN=/(?:cat\s*>[^>]|echo\s*>[^>]|touch\s+|>\s*[^>]|<<\s*['"]?EOF)/,EXCLUDED_PREFIXES=["/tmp/","/var/","/dev/"],EXCLUDED_SUFFIXES=[".tmp",".bak"];function extractFilePaths(t,e){let n=t.matchAll(/(?:^|[\s'"`;|&()=><])([./]*(?:[\w.\-]+\/)*[\w.\-]+\.[\w]+)(?=[\s'"`;|&()=><]|$)/g),r=new Set;for(let s of n){let i=s[1].replace(/['"]/g,"").trim();!i||i.startsWith("-")||i.includes("..")||EXCLUDED_PREFIXES.some(o=>i.startsWith(o))||EXCLUDED_SUFFIXES.some(o=>i.endsWith(o))||r.add(i.startsWith("/")?i:`${e}/${i.replace(/^\.\//,"")}`)}return[...r]}function isCreateCommand(t){return CREATE_CMD_PATTERN.test(t)}function normalizeFileChangeKind(t){switch(t){case"add":case"create":return"create";case"update":case"modify":return"modify";case"delete":return"delete";default:return}}var BINARY_EXTENSIONS=new Set([".pdf",".doc",".docx",".xls",".xlsx",".ppt",".pptx",".zip",".tar",".gz",".rar",".7z",".png",".jpg",".jpeg",".gif",".bmp",".ico",".webp",".svg",".mp3",".mp4",".wav",".avi",".mov",".mkv",".exe",".dll",".so",".dylib",".bin",".woff",".woff2",".ttf",".otf",".eot",".pyc",".class",".o",".a"]);function isBinaryFile(t){let e=t.lastIndexOf(".");return e===-1?!1:BINARY_EXTENSIONS.has(t.slice(e))}});var _g=S($a=>{"use strict";Object.defineProperty($a,"__esModule",{value:!0});$a.VSCodeSessionStore=void 0;var ru=class{globalState;constructor(e){this.globalState=e}get(e){return this.globalState.get(e)}async set(e,n){await this.globalState.update(e,n)}};$a.VSCodeSessionStore=ru});var Js=S(at=>{"use strict";var VT=at&&at.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,s)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),WT=at&&at.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),KT=at&&at.__importStar||(function(){var t=function(e){return t=Object.getOwnPropertyNames||function(n){var r=[];for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(r[r.length]=s);return r},t(e)};return function(e){if(e&&e.__esModule)return e;var n={};if(e!=null)for(var r=t(e),s=0;s<r.length;s++)r[s]!=="default"&&VT(n,e,r[s]);return WT(n,e),n}})();Object.defineProperty(at,"__esModule",{value:!0});at.DEFAULT_CONVERSATION_LOCK_TIMEOUT_MS=void 0;at.initSessionStore=zT;at.initSessionStoreWithStore=Ag;at._getSessionStore=QT;at._resetSessionStore=ZT;at.upsertPersistedSession=eb;at.touchPersistedSession=tb;at.getPersistedSession=nb;at.runSessionMaintenance=rb;at.buildConversationKey=ib;at.withConversationLock=ob;var qT=KT(require("crypto")),YT=en(),XT=_g(),wg="agentide.providerSessions.v1",yg=200,JT=1e3*60*60*24*14,xn={},po;function zT(t){Ag(new XT.VSCodeSessionStore(t.globalState))}function Ag(t){po=t,xn=t.get(wg)??{},La(Date.now()),Ma()}function QT(){return po}function ZT(){po=void 0,xn={}}function La(t){for(let[n,r]of Object.entries(xn))t-r.lastUsedAt>JT&&delete xn[n];let e=Object.keys(xn);if(!(e.length<=yg)){e.sort((n,r)=>xn[n].lastUsedAt-xn[r].lastUsedAt);for(let n=0;n<e.length-yg;n++)delete xn[e[n]]}}async function Ma(){if(po)try{await po.set(wg,xn)}catch{}}async function eb(t,e){xn[t]=e,La(Date.now()),await Ma()}async function tb(t){let e=xn[t];e&&(e.lastUsedAt=Date.now(),La(e.lastUsedAt),await Ma())}function nb(t){return xn[t]}function rb(){La(Date.now()),Ma()}function sb(t){return JSON.stringify({workspaceRoot:t.workspaceRoot,additionalDirectories:(0,YT.stableAdditionalDirs)(t.additionalDirectories),agentPackId:t.agentPackId??"default"})}function ib(t,e){let n=e.sessionId?.trim(),r=e.contextSessionId?.trim()||n,s=!r,i=r||`ephemeral-${Date.now()}-${Math.random().toString(36).slice(2)}`,o=n||i,a=e.agentPackId??"default",c=sb(e),l=qT.createHash("sha256").update(c).digest("hex").slice(0,16);return{key:`${t}:${i}:${a}:${l}`,chatSessionId:o,isEphemeral:s,signatureHash:l,signatureRaw:c,agentPackId:a}}at.DEFAULT_CONVERSATION_LOCK_TIMEOUT_MS=1e3*60*60*48;var Da=new Map;function ob(t,e,n){let r=Da.get(t)??Promise.resolve(),s,i=new Promise(E=>{s=E}),o=r.then(()=>i);Da.set(t,o);let a=n?.label?` (${n.label})`:"",c=typeof n?.timeoutMs=="number"?n.timeoutMs:void 0,l=n?.signal,f,u,d=!1,p=l?new Promise((E,_)=>{if(l.aborted){_(new Error(`[AgentIDE] Cancelled while waiting for conversation lock${a}`));return}f=()=>_(new Error(`[AgentIDE] Cancelled while waiting for conversation lock${a}`)),l.addEventListener("abort",f,{once:!0})}):void 0,g=c&&c>0?new Promise((E,_)=>{u=setTimeout(()=>{d=!0,n?.onTimeout?.(),_(new Error(`[AgentIDE] Conversation lock timed out after ${c}ms${a}`))},c)}):void 0,m=[r,p,g].filter(Boolean);return Promise.race(m).then(async()=>{if(l?.aborted)throw new Error(`[AgentIDE] Cancelled before running conversation work${a}`);if(d)throw new Error(`[AgentIDE] Conversation lock timed out after ${c}ms${a}`);let _=[e(),g].filter(Boolean);return await Promise.race(_)}).finally(()=>{try{u&&clearTimeout(u),l&&f&&l.removeEventListener("abort",f)}finally{s(),Da.get(t)===o&&Da.delete(t)}})}});var zs=S(un=>{"use strict";var ab=un&&un.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,s)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),cb=un&&un.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),lb=un&&un.__importStar||(function(){var t=function(e){return t=Object.getOwnPropertyNames||function(n){var r=[];for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(r[r.length]=s);return r},t(e)};return function(e){if(e&&e.__esModule)return e;var n={};if(e!=null)for(var r=t(e),s=0;s<r.length;s++)r[s]!=="default"&&ab(n,e,r[s]);return cb(n,e),n}})();Object.defineProperty(un,"__esModule",{value:!0});un.buildLiteLLMMetadataHeaders=fb;un.resolveAnalyticsProjectId=pb;un.generateRequestId=gb;un.persistSessionIfNeeded=hb;un.touchSessionIfNeeded=mb;un.getPersistedSessionId=Eb;var ub=Pi(),Ga=Js(),db=lb(require("path"));function fb(t,e){if(!t)return[];let n=[],r=(0,ub.hashIdentity)(e.analyticsUserId);return r&&(n.push(`x-litellm-metadata-user-id: ${r}`),n.push(`langfuse_trace_user_id: ${r}`)),e.sessionId?.trim()&&(n.push(`x-litellm-metadata-session-id: ${e.sessionId.trim()}`),n.push(`langfuse_session_id: ${e.sessionId.trim()}`)),e.analyticsProjectId?.trim()&&n.push(`x-litellm-metadata-project-id: ${e.analyticsProjectId.trim()}`),e.agentId?.trim()&&n.push(`x-litellm-metadata-agent-id: ${e.agentId.trim()}`),e.agentVersion?.trim()&&n.push(`x-litellm-metadata-agent-version: ${e.agentVersion.trim()}`),e.source?.trim()&&n.push(`x-litellm-metadata-source: ${e.source.trim()}`),e.engine?.trim()&&n.push(`x-litellm-metadata-engine: ${e.engine.trim()}`),e.requestId?.trim()&&n.push(`x-litellm-metadata-request-id: ${e.requestId.trim()}`),e.policyVersion?.trim()&&n.push(`x-litellm-metadata-policy-version: ${e.policyVersion.trim()}`),e.packDigest?.trim()&&n.push(`x-litellm-metadata-pack-digest: ${e.packDigest.trim()}`),e.engineVersion?.trim()&&n.push(`x-litellm-metadata-engine-version: ${e.engineVersion.trim()}`),e.tier!==void 0&&n.push(`x-litellm-metadata-tier: ${e.tier}`),e.instanceId?.trim()&&n.push(`x-litellm-metadata-instance-id: ${e.instanceId.trim()}`),n}function pb(t,e){let n=t?.trim();if(n)return n;if(!e)return;let r=e.replace(/[\\/]+$/,"").trim();return r&&db.basename(r).trim()||void 0}function gb(){return`req-${Math.random().toString(16).slice(2,10)}`}async function hb(t,e,n,r){if(e.isEphemeral)return;let s=Date.now(),i=(0,Ga.getPersistedSession)(e.key);await(0,Ga.upsertPersistedSession)(e.key,{provider:t,id:n,chatSessionId:e.chatSessionId,signatureHash:e.signatureHash,signatureRaw:e.signatureRaw,agentPackId:r?.agentPackId??e.agentPackId,agentPackVersion:r?.agentPackVersion,createdAt:i?.createdAt??s,lastUsedAt:s})}function mb(t){t.isEphemeral||(0,Ga.touchPersistedSession)(t.key)}function Eb(t,e){let n=(0,Ga.getPersistedSession)(e);return n?.provider===t?n.id:void 0}});var su=S(pr=>{"use strict";Object.defineProperty(pr,"__esModule",{value:!0});pr.DEFAULT_PERMISSIONS=void 0;pr.getDefaultPermissions=Sg;pr._resetMappingConfigCache=_b;pr.parsePermissions=Tg;pr.parseManifestPermissions=yb;pr.enforcePermissions=wb;pr.toClaudeOptions=Ab;pr.toCodexOptions=Sb;pr.DEFAULT_PERMISSIONS={fileAccess:"full"};var Rs={defaults:{fileAccess:"full"},claude:{readOnly:{permissionMode:"plan",allowDangerouslySkipPermissions:!1},workspaceWrite:{permissionMode:"acceptEdits",allowDangerouslySkipPermissions:!1},fullAccess:{permissionMode:"bypassPermissions",allowDangerouslySkipPermissions:!0}},codex:{approvalPolicy:"never",readOnly:{sandboxMode:"read-only"},workspaceWrite:{sandboxMode:"workspace-write"},fullAccess:{sandboxMode:"danger-full-access"}}};function Sg(){return{...Rs.defaults}}function _b(){}function Tg(t){let e=t?.spec?.permissions,n=Sg();return{fileAccess:e?.fileAccess??n.fileAccess}}function yb(t){return Tg(t)}function wb(t,e){return{fileAccess:e.fileAccess}}function Ab(t,e){return{...t.fileAccess==="read-only"?Rs.claude.readOnly:t.fileAccess==="workspace-write"?Rs.claude.workspaceWrite:Rs.claude.fullAccess,additionalDirectories:t.fileAccess==="full"?void 0:e}}function Sb(t,e){let n=t.fileAccess==="read-only"?Rs.codex.readOnly:t.fileAccess==="workspace-write"?Rs.codex.workspaceWrite:Rs.codex.fullAccess;return{approvalPolicy:Rs.codex.approvalPolicy,...n,additionalDirectories:e}}});var Qs=S(bn=>{"use strict";var Tb=bn&&bn.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,s)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),bb=bn&&bn.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),vb=bn&&bn.__importStar||(function(){var t=function(e){return t=Object.getOwnPropertyNames||function(n){var r=[];for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(r[r.length]=s);return r},t(e)};return function(e){if(e&&e.__esModule)return e;var n={};if(e!=null)for(var r=t(e),s=0;s<r.length;s++)r[s]!=="default"&&Tb(n,e,r[s]);return bb(n,e),n}})();Object.defineProperty(bn,"__esModule",{value:!0});bn.parseYaml=ou;bn.stringifyYaml=vg;bn.updateManifestName=Ib;bn.loadAgentManifest=Pb;bn.parseAgentManifest=Og;var iu=require("fs"),bg=vb(require("path")),Ob=Ke();function ou(t){return require("js-yaml").load(t)}function vg(t){return require("js-yaml").dump(t,{indent:2,lineWidth:-1,quotingType:'"',forceQuotes:!1})}async function Ib(t,e){let n=await iu.promises.readFile(t,"utf8"),r=ou(n);r&&typeof r=="object"&&r.metadata&&(r.metadata.name=e);let s=vg(r);await iu.promises.writeFile(t,s,"utf8")}async function Pb(t){let e=await iu.promises.readFile(t,"utf8");return Og(e,t)}function Og(t,e){let n=ou(t),r=e?` (${e})`:"";if(!n?.metadata?.name)throw new Error(`Manifest missing metadata.name${r}`);if(!n.metadata.version)throw new Error(`Manifest missing metadata.version${r}`);if(!n.spec?.engine)throw new Error(`Manifest missing spec.engine${r}`);return Nb(n,r),n}function Nb(t,e){let n=t.spec?.data;if(!n)return;let r=(s,i,o)=>{let c=(s??o).trim();if(!c)throw new Error(`Manifest spec.data.${i} cannot be empty${e}`);if(bg.isAbsolute(c))throw new Error(`Manifest spec.data.${i} must be relative (not absolute)${e}`);if(/^(https?:\/\/|git@|ssh:\/\/)/i.test(c))throw new Error(`Manifest spec.data.${i} must be a local relative path${e}`);let l=bg.posix.normalize(c.replace(/\\/g,"/"));if(l===".."||l.startsWith("../"))throw new Error(`Manifest spec.data.${i} cannot escape parent directories${e}`)};r(n.sourcePath,"sourcePath","./data"),r(n.workspacePath,"workspacePath",`${Ob.AGENTIDE_DIR_NAME}/data/${t.metadata.name}`)}});var lu=S(St=>{"use strict";var Rb=St&&St.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,s)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),Cb=St&&St.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),kb=St&&St.__importStar||(function(){var t=function(e){return t=Object.getOwnPropertyNames||function(n){var r=[];for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(r[r.length]=s);return r},t(e)};return function(e){if(e&&e.__esModule)return e;var n={};if(e!=null)for(var r=t(e),s=0;s<r.length;s++)r[s]!=="default"&&Rb(n,e,r[s]);return Cb(n,e),n}})();Object.defineProperty(St,"__esModule",{value:!0});St.listUserLibraryAgents=Lb;St.isWorkspaceAgentAvailable=Mb;St.isAgentInUserLibrary=Gb;St.hydrateFromUserLibrary=Pg;St.promoteToUserLibrary=Ub;St.readAgentSource=Ng;St.checkForUpdate=Hb;St.updateFromUserLibrary=jb;St.duplicateAgent=Bb;St.resetDefaultAgent=Fb;var qe=require("fs"),Be=kb(require("path")),te=en(),ae=Un(),Ni=Qs(),Ig=Ke();function $b(t,e){let n=o=>o.split(".").map(a=>{let c=parseInt(a,10);return isNaN(c)?0:c}),r=n(t),s=n(e),i=Math.max(r.length,s.length);for(let o=0;o<i;o++){let a=r[o]??0,c=s[o]??0;if(a!==c)return a-c}return 0}function Db(t){return[...t].sort($b)}async function au(t,e){await qe.promises.mkdir(e,{recursive:!0});let n=await qe.promises.readdir(t,{withFileTypes:!0});for(let r of n){let s=Be.join(t,r.name),i=Be.join(e,r.name);if(r.isDirectory()){if(r.name.startsWith("."))continue;await au(s,i)}else await qe.promises.copyFile(s,i)}}async function Lb(){let t=(0,ae.getUserAgentsDir)();if(!await(0,te.pathExists)(t))return[];let e=await qe.promises.readdir(t,{withFileTypes:!0}),n=[];for(let r of e){if(!r.isDirectory()||r.name.startsWith("."))continue;let s=r.name,i=(0,ae.getUserAgentRoot)(s),o=await cu(i);if(o.length===0)continue;let a=await Ua(s),c=a||o[o.length-1],l=(0,ae.getUserAgentVersionDir)(s,c),f=Be.join(l,ae.AGENT_CONSTANTS.MANIFEST_FILE),u,d;try{let p=await(0,Ni.loadAgentManifest)(f);u=p.metadata.description,d=p.spec.engine}catch{}n.push({id:s,versions:o,currentVersion:a,description:u,preferredEngine:d})}return n}async function cu(t){try{let e=await qe.promises.readdir(t,{withFileTypes:!0}),n=[];for(let r of e){if(!r.isDirectory()||r.name.startsWith("."))continue;let s=Be.join(t,r.name,ae.AGENT_CONSTANTS.MANIFEST_FILE);if(await(0,te.pathExists)(s))try{await(0,Ni.loadAgentManifest)(s),n.push(r.name)}catch{}}return Db(n)}catch{return[]}}async function Ua(t){let e=(0,ae.getUserAgentCurrentPath)(t);try{let n=(await qe.promises.readFile(e,"utf8")).trim();if(!n)return;let r=(0,ae.getUserAgentVersionDir)(t,n),s=Be.join(r,ae.AGENT_CONSTANTS.MANIFEST_FILE);if(!await(0,te.pathExists)(s))return;try{return await(0,Ni.loadAgentManifest)(s),n}catch{return}}catch{}}async function Mb(t,e){let n=(0,ae.getAgentManifestPath)(t,e);if(!await(0,te.pathExists)(n))return!1;try{return(await(0,Ni.loadAgentManifest)(n)).metadata.name===e}catch{return!1}}async function Gb(t){if(await Ua(t))return!0;let n=(0,ae.getUserAgentRoot)(t);return(await cu(n)).length>0}async function Pg(t,e,n,r){let s=n,i=n??"current";if(!s&&(s=await Ua(e),!s)){let d=(0,ae.getUserAgentRoot)(e),p=await cu(d);if(p.length===0){(0,te.logInfo)(r,`[AgentStores] Agent not in User Library: ${e}`);return}s=p[p.length-1],i=s}let o=(0,ae.getUserAgentVersionDir)(e,s);if(!await(0,te.pathExists)(o)){(0,te.logInfo)(r,`[AgentStores] Version not found in User Library: ${e}@${s}`);return}let a=(0,ae.getAgentRoot)(t,e);(0,te.logInfo)(r,`[AgentStores] Hydrating ${e}@${s} from User Library`),await(0,te.pathExists)(a)&&((0,te.logInfo)(r,`[AgentStores] Clearing existing directory: ${a}`),await qe.promises.rm(a,{recursive:!0,force:!0})),await(0,te.copyDirRecursive)(o,a);let c=Be.join(a,ae.AGENT_CONSTANTS.MANIFEST_FILE),{sha256:l}=await(0,te.readFileSha256)(c),f={source:"user-library",agentId:e,version:s,resolvedFrom:i,sha256:l,hydratedAt:new Date().toISOString()},u=Be.join(a,ae.AGENT_CONSTANTS.SOURCE_FILE);return await qe.promises.writeFile(u,JSON.stringify(f,null,2),"utf8"),(0,te.logInfo)(r,`[AgentStores] Hydrated ${e}@${s} to ${a}`),s}async function Ub(t,e,n){if(e===ae.AGENT_CONSTANTS.DEFAULT_AGENT_ID)throw new Error("Cannot promote the default agent to User Library");let r=(0,ae.getAgentRoot)(t,e),s=(0,ae.getAgentManifestPath)(t,e);if(!await(0,te.pathExists)(s))throw new Error(`Agent not found: ${e}`);let o=(await(0,Ni.loadAgentManifest)(s)).metadata.version,a=(0,ae.getUserAgentVersionDir)(e,o),c=Be.join(a,ae.AGENT_CONSTANTS.MANIFEST_FILE);if(await(0,te.pathExists)(c)){let f=await(0,te.readFileSha256)(s),u=await(0,te.readFileSha256)(c);if(f.sha256===u.sha256)return(0,te.logInfo)(n,`[AgentStores] ${e}@${o} already in User Library (identical)`),o;throw new Error(`Version conflict: ${e}@${o} already exists in User Library with different content. Bump the version in agent.yaml and try again.`)}(0,te.logInfo)(n,`[AgentStores] Promoting ${e}@${o} to User Library`),await qe.promises.mkdir(a,{recursive:!0}),await au(r,a);let l=(0,ae.getUserAgentCurrentPath)(e);return await qe.promises.writeFile(l,o,"utf8"),(0,te.logInfo)(n,`[AgentStores] Promoted ${e}@${o} to ${a}`),o}async function Ng(t,e){let n=Be.join((0,ae.getAgentRoot)(t,e),ae.AGENT_CONSTANTS.SOURCE_FILE);try{let r=await qe.promises.readFile(n,"utf8");return JSON.parse(r)}catch{return}}async function Hb(t,e){let n=await Ng(t,e);if(!n||n.source!=="user-library")return;let r=await Ua(e);if(r&&r!==n.version)return r}async function jb(t,e,n,r){let s=(0,ae.getAgentRoot)(t,e),i=new Date().toISOString().replace(/[:.]/g,"-"),o=Be.join(Be.dirname(s),`.${e}.backup-${i}`);await(0,te.pathExists)(s)&&((0,te.logInfo)(r,`[AgentStores] Backing up ${e} to ${o}`),await(0,te.copyDirRecursive)(s,o),await qe.promises.rm(s,{recursive:!0,force:!0}));let a=await Pg(t,e,n,r);if(!a)throw await(0,te.pathExists)(o)&&((0,te.logInfo)(r,"[AgentStores] Restoring backup after failed update"),await(0,te.copyDirRecursive)(o,s)),new Error(`Failed to update ${e} from User Library`);return(0,te.logInfo)(r,`[AgentStores] Updated ${e} to ${a}`),a}async function xb(t,e){let n=`${e}-copy`;if(!await(0,te.pathExists)((0,ae.getAgentRoot)(t,n)))return n;for(let r=2;r<100;r++){let s=`${e}-${r}`;if(!await(0,te.pathExists)((0,ae.getAgentRoot)(t,s)))return s}return`${e}-${Date.now()}`}async function Bb(t,e,n){let r=(0,ae.getAgentRoot)(t,e),s=(0,ae.getAgentManifestPath)(t,e);if(!await(0,te.pathExists)(s))throw new Error(`Agent not found: ${e}`);let i=await xb(t,e),o=(0,ae.getAgentRoot)(t,i);(0,te.logInfo)(n,`[AgentStores] Duplicating ${e} to ${i}`),await au(r,o);let a=(0,ae.getAgentManifestPath)(t,i);await(0,Ni.updateManifestName)(a,i);let c=Be.join(o,ae.AGENT_CONSTANTS.SOURCE_FILE);try{await qe.promises.rm(c,{force:!0})}catch{}return(0,te.logInfo)(n,`[AgentStores] Duplicated ${e} to ${i}`),i}async function Fb(t,e,n){let r=(0,ae.getAgentRoot)(t,ae.AGENT_CONSTANTS.DEFAULT_AGENT_ID),s=new Date().toISOString().replace(/[:.]/g,"-"),i=Be.join(Be.dirname(r),`.default.backup-${s}`);if(await(0,te.pathExists)(r)&&((0,te.logInfo)(n,`[AgentStores] Backing up default agent to ${i}`),await(0,te.copyDirRecursive)(r,i),await qe.promises.rm(r,{recursive:!0,force:!0})),await qe.promises.mkdir(r,{recursive:!0}),await qe.promises.mkdir(Be.join(r,ae.AGENT_CONSTANTS.RULES_DIR),{recursive:!0}),await qe.promises.mkdir(Be.join(r,ae.AGENT_CONSTANTS.SKILLS_DIR),{recursive:!0}),e){let c=Be.join(e,"rules","AGENTS.md"),l=Be.join(r,ae.AGENT_CONSTANTS.AGENTS_MD);if(await(0,te.pathExists)(c)){let p=await qe.promises.readFile(c,"utf8");await qe.promises.writeFile(l,(0,Ig.applyBrandingTokens)(p),"utf8"),(0,te.logInfo)(n,"[AgentStores] Restored AGENTS.md from bundled templates")}let f=Be.join(e,ae.AGENT_CONSTANTS.GHOST_TEXT_FILE),u=Be.join(r,ae.AGENT_CONSTANTS.GHOST_TEXT_FILE);if(await(0,te.pathExists)(f)&&!await(0,te.pathExists)(u)){let p=await qe.promises.readFile(f,"utf8");await qe.promises.writeFile(u,p,"utf8"),(0,te.logInfo)(n,"[AgentStores] Restored GHOST_TEXT.md from bundled templates")}let d=Be.join(e,"skills");if(await(0,te.pathExists)(d)){let p=await qe.promises.readdir(d,{withFileTypes:!0});for(let g of p){if(!g.isDirectory())continue;let m=Be.join(d,g.name),h=Be.join(r,ae.AGENT_CONSTANTS.SKILLS_DIR,g.name);await(0,te.copyDirRecursiveWithTransform)(m,h,Ig.applyBrandingTokens),(0,te.logInfo)(n,`[AgentStores] Restored skill: ${g.name}`)}}}let o=(0,ae.generateDefaultAgentYaml)({model:"claude"}),a=Be.join(r,ae.AGENT_CONSTANTS.MANIFEST_FILE);await qe.promises.writeFile(a,o,"utf8"),(0,te.logInfo)(n,"[AgentStores] Reset default agent complete")}});var Rg=S((exports,module)=>{"use strict";var __createBinding=exports&&exports.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,s)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),__setModuleDefault=exports&&exports.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),__importStar=exports&&exports.__importStar||(function(){var t=function(e){return t=Object.getOwnPropertyNames||function(n){var r=[];for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(r[r.length]=s);return r},t(e)};return function(e){if(e&&e.__esModule)return e;var n={};if(e!=null)for(var r=t(e),s=0;s<r.length;s++)r[s]!=="default"&&__createBinding(n,e,r[s]);return __setModuleDefault(n,e),n}})();Object.defineProperty(exports,"__esModule",{value:!0});exports.AgentPackManager=void 0;var fs_1=require("fs"),path=__importStar(require("path")),_vscode;function getVscode(){return _vscode||(_vscode=eval("require")("vscode")),_vscode}var paths_1=Un(),manifest_1=Qs(),utils_1=en(),stores_1=lu(),AgentPackManager=class{syncService;getWorkspaceRoot;getStorageUri;outputChannel;constructor(e,n,r,s){this.syncService=e,this.getWorkspaceRoot=n,this.getStorageUri=r,this.outputChannel=s}async installFromLocal(e){let n=this.getWorkspaceRoot(),r=this.getStorageUri(),s=path.join(e,paths_1.AGENT_CONSTANTS.MANIFEST_FILE);if(!await(0,utils_1.pathExists)(s))throw new Error(`No agent.yaml found at ${e}`);let i=await(0,manifest_1.loadAgentManifest)(s),o=i.metadata.name,a=i.metadata.version;if((0,paths_1.isDefaultAgent)(o))throw new Error('Cannot install an agent with reserved ID "default"');(0,utils_1.logInfo)(this.outputChannel,`[Agent] Installing: ${o}@${a} from ${e}`);let c=(0,paths_1.resolveAgentRuntimePaths)(n,r,o,a);await this.createAgentDirectories(c);let l=c.agentRoot;path.resolve(e)!==path.resolve(l)&&((0,utils_1.logInfo)(this.outputChannel,`[Agent] Copying ${e} to ${l}`),await(0,utils_1.copyDirRecursive)(e,l));let f=await this.registerAgent(o,{source:"local"});return await this.syncService.seedAgentDataIfNeeded(n,o,this.outputChannel),(0,utils_1.logInfo)(this.outputChannel,`[Agent] Successfully installed: ${o}@${a}`),f}async uninstall(e){let n=this.getWorkspaceRoot(),r=this.getStorageUri();if((0,paths_1.isDefaultAgent)(e))throw new Error("Cannot uninstall the default agent");(0,utils_1.logInfo)(this.outputChannel,`[Agent] Uninstalling: ${e}`);let s=(0,paths_1.resolveAgentRuntimePaths)(n,r,e);await(0,utils_1.pathExists)(s.agentRoot)&&(await fs_1.promises.rm(s.agentRoot,{recursive:!0,force:!0}),(0,utils_1.logInfo)(this.outputChannel,`[Agent] Removed directory: ${s.agentRoot}`)),await(0,utils_1.pathExists)(s.codexHome)&&await fs_1.promises.rm(s.codexHome,{recursive:!0,force:!0}),await(0,utils_1.pathExists)(s.claudeConfigDir)&&await fs_1.promises.rm(s.claudeConfigDir,{recursive:!0,force:!0}),await this.syncService.removeInstalledAgent(n,e,this.outputChannel);try{await getVscode().commands.executeCommand("agentide.packsChanged")}catch{}(0,utils_1.logInfo)(this.outputChannel,`[Agent] Successfully uninstalled: ${e}`)}async listInstalled(){let e=this.getWorkspaceRoot();return this.syncService.loadInstalledAgents(e)}async getInstalledAgent(e){return(await this.listInstalled()).find(r=>r.id===e)}async isInstalled(e){return await this.getInstalledAgent(e)!==void 0}async cleanupStaleAgents(){let e=this.getWorkspaceRoot(),n=await this.listInstalled(),r=[];for(let s of n){let i=(0,paths_1.getAgentManifestPath)(e,s.id);await(0,utils_1.pathExists)(i)||r.push(s.id)}for(let s of r)(0,utils_1.logInfo)(this.outputChannel,`[Agent] Removing stale entry: ${s} (folder missing)`),await this.syncService.removeInstalledAgent(e,s,this.outputChannel);if(r.length>0){(0,utils_1.logInfo)(this.outputChannel,`[Agent] Cleaned up ${r.length} stale agent(s)`);try{await getVscode().commands.executeCommand("agentide.packsChanged")}catch{}}return r}async listInstalledWithCleanup(e=!0){return e&&await this.cleanupStaleAgents(),this.listInstalled()}getAgentRuntimePaths(e,n){let r=this.getWorkspaceRoot(),s=this.getStorageUri();return(0,paths_1.resolveAgentRuntimePaths)(r,s,e,n)}async createAgentDirectories(e){await fs_1.promises.mkdir(e.agentRoot,{recursive:!0}),await fs_1.promises.mkdir(e.rulesDir,{recursive:!0}),await fs_1.promises.mkdir(e.skillsDir,{recursive:!0}),await fs_1.promises.mkdir(e.mcpDir,{recursive:!0}),await fs_1.promises.mkdir(e.codexHome,{recursive:!0}),await fs_1.promises.mkdir(e.claudeConfigDir,{recursive:!0})}async buildInstalledAgent(e,n,r){let s=(0,paths_1.getAgentManifestPath)(e,n),i=await(0,manifest_1.loadAgentManifest)(s),o=await(0,utils_1.readFileSha256)(s),a=r?.source??((0,paths_1.isDefaultAgent)(n)?"builtin":"local"),c=r?.agentRootOverride??`${paths_1.AGENT_CONSTANTS.AGENTS_DIR}/${n}`;return{id:n,version:i.metadata.version,source:a,installedAt:new Date().toISOString(),manifestHash:o.sha256,featureSetHash:o.sha256,skillsSignature:o.sha256,promptsSignature:o.sha256,agentRoot:c,preferredEngine:i.spec.engine,preferredModel:i.spec.model,preferredCheapModel:i.spec.cheapModel,status:"active"}}async registerAgent(e,n){let r=this.getWorkspaceRoot(),s=await this.buildInstalledAgent(r,e,n);await this.syncService.updateInstalledAgent(r,s,this.outputChannel);try{await getVscode().commands.executeCommand("agentide.packsChanged")}catch{}return s}async discoverAgents(){let e=this.getWorkspaceRoot(),n=(0,paths_1.getAgentsDir)(e);if(!await(0,utils_1.pathExists)(n))return[];let r=await fs_1.promises.readdir(n,{withFileTypes:!0}),s=[];for(let i of r){if(!i.isDirectory()||i.name.startsWith("."))continue;let o=(0,paths_1.getAgentManifestPath)(e,i.name);await(0,utils_1.pathExists)(o)&&s.push(i.name)}return s}async repairUnregisteredAgents(){let e=this.getWorkspaceRoot(),n=(0,paths_1.getAgentsDir)(e);if(!await(0,utils_1.pathExists)(n))return{registered:[],alreadyRegistered:[]};let r=await this.listInstalled(),s=new Set(r.map(c=>c.id)),i=await this.discoverAgents(),o=[],a=[];for(let c of i){if(s.has(c)){a.push(c);continue}try{await this.registerAgent(c),o.push(c),(0,utils_1.logInfo)(this.outputChannel,`[Agent] Repaired: registered untracked agent "${c}"`)}catch(l){(0,utils_1.logInfo)(this.outputChannel,`[Agent] Failed to repair agent "${c}": ${l instanceof Error?l.message:String(l)}`)}}return o.length>0&&(0,utils_1.logInfo)(this.outputChannel,`[Agent] Repair complete: ${o.length} agent(s) registered`),{registered:o,alreadyRegistered:a}}async installAgentToWorkspace(e){let n=this.getWorkspaceRoot();if(await(0,stores_1.isWorkspaceAgentAvailable)(n,e))return(0,utils_1.logInfo)(this.outputChannel,`[Agent] Agent available in workspace: ${e}`),await this.getInstalledAgent(e)||((0,utils_1.logInfo)(this.outputChannel,`[Agent] Registering untracked agent: ${e}`),await this.registerAgent(e)),await this.syncService.seedAgentDataIfNeeded(n,e,this.outputChannel),{installed:!0,hydrated:!1};if(await(0,stores_1.isAgentInUserLibrary)(e)){(0,utils_1.logInfo)(this.outputChannel,`[Agent] Hydrating from User Library: ${e}`);let r=await(0,stores_1.hydrateFromUserLibrary)(n,e,void 0,this.outputChannel);if(r)return await this.registerAgent(e,{source:"local"}),{installed:!0,hydrated:!0,version:r}}return(0,utils_1.logInfo)(this.outputChannel,`[Agent] Agent not found: ${e}`),{installed:!1,hydrated:!1}}async shareToUserLibrary(e){let n=this.getWorkspaceRoot();return(0,stores_1.promoteToUserLibrary)(n,e,this.outputChannel)}async updateFromLibrary(e,n){let r=this.getWorkspaceRoot();return(0,stores_1.updateFromUserLibrary)(r,e,n,this.outputChannel)}async duplicate(e){let n=this.getWorkspaceRoot(),r=await(0,stores_1.duplicateAgent)(n,e,this.outputChannel);return await this.registerAgent(r,{source:"local"}),r}async resetDefault(e){let n=this.getWorkspaceRoot();await(0,stores_1.resetDefaultAgent)(n,e,this.outputChannel);let r=(0,paths_1.getAgentManifestPath)(n,paths_1.AGENT_CONSTANTS.DEFAULT_AGENT_ID);await(0,utils_1.pathExists)(r)&&await this.registerAgent(paths_1.AGENT_CONSTANTS.DEFAULT_AGENT_ID,{source:"builtin"})}async listUserLibrary(){return(0,stores_1.listUserLibraryAgents)()}async checkAgentUpdate(e){let n=this.getWorkspaceRoot();return(0,stores_1.checkForUpdate)(n,e)}async getAgentSource(e){let n=this.getWorkspaceRoot();return(0,stores_1.readAgentSource)(n,e)}};exports.AgentPackManager=AgentPackManager});var go=S((exports,module)=>{"use strict";Object.defineProperty(exports,"__esModule",{value:!0});exports.getGitHubToken=getGitHubToken;exports.isGitHubAuthenticated=isGitHubAuthenticated;exports.getGitHubUser=getGitHubUser;exports.getRepo=getRepo;exports.createRepo=createRepo;exports.getReleaseByTag=getReleaseByTag;exports.getLatestRelease=getLatestRelease;exports.createRelease=createRelease;exports.downloadTarball=downloadTarball;exports.getFileContent=getFileContent;exports.putFileContent=putFileContent;exports.getDefaultBranch=getDefaultBranch;exports.getBranchSha=getBranchSha;exports.createBranch=createBranch;exports.createPullRequest=createPullRequest;exports.commitMultipleFiles=commitMultipleFiles;exports.parseGitHubSource=parseGitHubSource;exports.formatGitHubSource=formatGitHubSource;var _vscode;function getVscode(){return _vscode||(_vscode=eval("require")("vscode")),_vscode}async function getGitHubToken(t=!0,e=["repo","user"]){let n=process.env.GITHUB_TOKEN||process.env.GH_TOKEN||process.env.AGENTHIPPO_GITHUB_TOKEN;if(n?.trim())return n.trim();let s=await getVscode().authentication.getSession("github",e,{createIfNone:t});if(!s)throw new Error("GitHub authentication required. Please sign in.");return s.accessToken}async function isGitHubAuthenticated(){try{return await getGitHubToken(!1),!0}catch{return!1}}async function getGitHubUser(){let t=await getGitHubToken(),e=await fetch("https://api.github.com/user",{headers:{Authorization:`Bearer ${t}`,Accept:"application/vnd.github.v3+json","User-Agent":"AgentIDE"}});if(!e.ok)throw new Error(`Failed to get GitHub user: ${e.statusText}`);return e.json()}async function getRepo(t,e){let n=await getGitHubToken(),r=await fetch(`https://api.github.com/repos/${t}/${e}`,{headers:{Authorization:`Bearer ${n}`,Accept:"application/vnd.github.v3+json","User-Agent":"AgentIDE"}});if(r.status===404)return null;if(!r.ok)throw new Error(`Failed to get repo: ${r.statusText}`);return r.json()}async function createRepo(t,e,n){let r=await getGitHubToken(),s=await fetch("https://api.github.com/user/repos",{method:"POST",headers:{Authorization:`Bearer ${r}`,Accept:"application/vnd.github.v3+json","User-Agent":"AgentIDE","Content-Type":"application/json"},body:JSON.stringify({name:t,description:e,private:n,auto_init:!1})});if(!s.ok){let i=await s.text();throw new Error(`Failed to create repo: ${i}`)}return s.json()}async function getReleaseByTag(t,e,n){let r=await getGitHubToken(),s=await fetch(`https://api.github.com/repos/${t}/${e}/releases/tags/${n}`,{headers:{Authorization:`Bearer ${r}`,Accept:"application/vnd.github.v3+json","User-Agent":"AgentIDE"}});if(s.status===404)return null;if(!s.ok)throw new Error(`Failed to get release: ${s.statusText}`);return s.json()}async function getLatestRelease(t,e){let n=await getGitHubToken(),r=await fetch(`https://api.github.com/repos/${t}/${e}/releases/latest`,{headers:{Authorization:`Bearer ${n}`,Accept:"application/vnd.github.v3+json","User-Agent":"AgentIDE"}});if(r.status===404)return null;if(!r.ok)throw new Error(`Failed to get latest release: ${r.statusText}`);return r.json()}async function createRelease(t,e,n,r,s,i){let o=await getGitHubToken(),a=await fetch(`https://api.github.com/repos/${t}/${e}/releases`,{method:"POST",headers:{Authorization:`Bearer ${o}`,Accept:"application/vnd.github.v3+json","User-Agent":"AgentIDE","Content-Type":"application/json"},body:JSON.stringify({tag_name:n,name:r,body:s,target_commitish:i})});if(!a.ok){let c=await a.text();throw new Error(`Failed to create release: ${c}`)}return a.json()}async function downloadTarball(t,e,n){let r=await getGitHubToken(),s=await fetch(`https://api.github.com/repos/${t}/${e}/tarball/${n}`,{headers:{Authorization:`Bearer ${r}`,Accept:"application/vnd.github.v3+json","User-Agent":"AgentIDE"},redirect:"follow"});if(!s.ok)throw new Error(`Failed to download tarball: ${s.statusText}`);return s.arrayBuffer()}async function getFileContent(t,e,n,r){let s=await getGitHubToken(),i=new URL(`https://api.github.com/repos/${t}/${e}/contents/${n}`);r&&i.searchParams.set("ref",r);let o=await fetch(i.toString(),{headers:{Authorization:`Bearer ${s}`,Accept:"application/vnd.github.v3+json","User-Agent":"AgentIDE"}});if(o.status===404)return null;if(!o.ok)throw new Error(`Failed to get file content: ${o.statusText}`);let a=await o.json();return{content:Buffer.from(a.content,"base64").toString("utf-8"),sha:a.sha}}async function putFileContent(t,e,n,r,s,i,o){let a=await getGitHubToken(),c=await fetch(`https://api.github.com/repos/${t}/${e}/contents/${n}`,{method:"PUT",headers:{Authorization:`Bearer ${a}`,Accept:"application/vnd.github.v3+json","User-Agent":"AgentIDE","Content-Type":"application/json"},body:JSON.stringify({message:s,content:Buffer.from(r).toString("base64"),sha:i,branch:o})});if(!c.ok){let l=await c.text();throw new Error(`Failed to put file content: ${l}`)}}async function getDefaultBranch(t,e){let n=await getRepo(t,e);if(!n)throw new Error(`Repository ${t}/${e} not found`);return n.default_branch}async function getBranchSha(t,e,n){let r=await getGitHubToken(),s=await fetch(`https://api.github.com/repos/${t}/${e}/git/refs/heads/${n}`,{headers:{Authorization:`Bearer ${r}`,Accept:"application/vnd.github.v3+json","User-Agent":"AgentHippo"}});if(!s.ok)throw new Error(`Failed to get branch ${n}: ${s.status}`);return(await s.json()).object.sha}async function createBranch(t,e,n,r){let s=await getGitHubToken(),i=await getBranchSha(t,e,r),o=await fetch(`https://api.github.com/repos/${t}/${e}/git/refs`,{method:"POST",headers:{Authorization:`Bearer ${s}`,Accept:"application/vnd.github.v3+json","User-Agent":"AgentHippo","Content-Type":"application/json"},body:JSON.stringify({ref:`refs/heads/${n}`,sha:i})});if(!o.ok){let a=await o.text();throw new Error(`Failed to create branch ${n}: ${o.status} ${a}`)}}async function createPullRequest(t,e,n){let r=await getGitHubToken(),s=await fetch(`https://api.github.com/repos/${t}/${e}/pulls`,{method:"POST",headers:{Authorization:`Bearer ${r}`,Accept:"application/vnd.github.v3+json","User-Agent":"AgentHippo","Content-Type":"application/json"},body:JSON.stringify({title:n.title,body:n.body,head:n.head,base:n.base})});if(!s.ok){let i=await s.text();throw new Error(`Failed to create pull request: ${s.status} ${i}`)}return await s.json()}async function commitMultipleFiles(t,e,n,r,s,i){let a={Authorization:`Bearer ${await getGitHubToken(!0,i?.scopes)}`,Accept:"application/vnd.github.v3+json","User-Agent":"AgentHippo","Content-Type":"application/json"};await new Promise(b=>setTimeout(b,500));let c=await fetch(`https://api.github.com/repos/${t}/${e}/git/refs/heads/${n}`,{headers:a});if(!c.ok){let b=await c.text();throw new Error(`Failed to get branch ref for ${n}: ${c.status} - ${b}`)}let f=(await c.json()).object.sha,u=await fetch(`https://api.github.com/repos/${t}/${e}/git/commits/${f}`,{headers:a});if(!u.ok){let b=await u.text();throw new Error(`Failed to get commit ${f}: ${u.status} - ${b}`)}let p=(await u.json()).tree.sha,g=[];for(let b of r){let T=b.encoding??"utf-8",O=await fetch(`https://api.github.com/repos/${t}/${e}/git/blobs`,{method:"POST",headers:a,body:JSON.stringify({content:b.content,encoding:T})});if(!O.ok){let v=await O.text();throw new Error(`Failed to create blob for ${b.path}: ${O.status} - ${v}`)}let A=await O.json();g.push({path:b.path,mode:"100644",type:"blob",sha:A.sha})}console.log("[AgentHippo] Repo:",`${t}/${e}`),console.log("[AgentHippo] Branch:",n),console.log("[AgentHippo] Creating tree with base:",p),console.log("[AgentHippo] Tree items:",JSON.stringify(g,null,2));let m=await fetch(`https://api.github.com/repos/${t}/${e}/git/trees`,{method:"POST",headers:a,body:JSON.stringify({base_tree:p,tree:g})});if(m.status===404&&(console.log("[AgentHippo] Retrying tree creation without base_tree..."),m=await fetch(`https://api.github.com/repos/${t}/${e}/git/trees`,{method:"POST",headers:a,body:JSON.stringify({tree:g})})),!m.ok)return console.log("[AgentHippo] Git Data API failed, falling back to Contents API..."),await commitMultipleFilesViaContentsApi(t,e,n,r,s,a);let h=await m.json(),E=await fetch(`https://api.github.com/repos/${t}/${e}/git/commits`,{method:"POST",headers:a,body:JSON.stringify({message:s,tree:h.sha,parents:[f]})});if(!E.ok)throw new Error(`Failed to create commit: ${E.status}`);let _=await E.json(),y=await fetch(`https://api.github.com/repos/${t}/${e}/git/refs/heads/${n}`,{method:"PATCH",headers:a,body:JSON.stringify({sha:_.sha})});if(!y.ok)throw new Error(`Failed to update ref: ${y.status}`);return{sha:_.sha}}async function commitMultipleFilesViaContentsApi(t,e,n,r,s,i){let o="";for(let a of r){let c=encodeURIComponent(n),l=await fetch(`https://api.github.com/repos/${t}/${e}/contents/${a.path}?ref=${c}`,{headers:i}),f=l.ok?(await l.json()).sha:void 0,u=await fetch(`https://api.github.com/repos/${t}/${e}/contents/${a.path}`,{method:"PUT",headers:i,body:JSON.stringify({message:`${s} - ${a.path}`,content:a.encoding==="base64"?a.content:Buffer.from(a.content,"utf-8").toString("base64"),branch:n,sha:f})});if(!u.ok){let p=await u.text();throw new Error(`Failed to create file ${a.path}: ${u.status} - ${p}`)}o=(await u.json()).commit.sha,console.log(`[AgentHippo] Created ${a.path}`)}return{sha:o}}function parseGitHubSource(t){let e=t.trim();e=e.replace(/^github:\/\//,""),e=e.replace(/^https?:\/\/github\.com\//,""),e=e.replace(/\.git$/,"");let n;if(e.includes("@")){let i=e.split("@");e=i[0],n=i[1]}let[r,s]=e.split("/");if(!r||!s)throw new Error(`Invalid GitHub source: ${t}. Expected format: owner/repo[@version]`);return{owner:r,repo:s,version:n}}function formatGitHubSource(t){let e=`github://${t.owner}/${t.repo}`;return t.version&&(e+=`@${t.version}`),e}});var Mg=S($r=>{"use strict";var Vb=$r&&$r.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,s)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),Wb=$r&&$r.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),Kb=$r&&$r.__importStar||(function(){var t=function(e){return t=Object.getOwnPropertyNames||function(n){var r=[];for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(r[r.length]=s);return r},t(e)};return function(e){if(e&&e.__esModule)return e;var n={};if(e!=null)for(var r=t(e),s=0;s<r.length;s++)r[s]!=="default"&&Vb(n,e,r[s]);return Wb(n,e),n}})();Object.defineProperty($r,"__esModule",{value:!0});$r.validateForPublish=Dg;$r.publishToGitHub=Yb;var uu=require("fs"),kg=Kb(require("path")),dn=en(),$g=Qs(),ja=Un(),Zs=go(),qb=[".","..",".git",".claude",".codex",".agentide","node_modules","*.log","current.txt"],Cg=1024*1024,Ha=10*1024*1024;async function Dg(t,e){let n=[],r=[],s=(0,ja.getAgentRoot)(t,e);if(!await(0,dn.pathExists)(s))return n.push(`Agent directory not found: ${s}`),{valid:!1,errors:n,warnings:r};let i=["agent.yaml","AGENTS.md"];for(let l of i){let f=kg.join(s,l);await(0,dn.pathExists)(f)||n.push(`Missing required file: ${l}`)}let o=(0,ja.getAgentManifestPath)(t,e);if(await(0,dn.pathExists)(o))try{let l=await(0,$g.loadAgentManifest)(o);l.metadata.name||n.push("agent.yaml missing metadata.name"),l.metadata.version?/^\d+\.\d+\.\d+/.test(l.metadata.version)||n.push(`Invalid version format: ${l.metadata.version}. Use semver (e.g., 1.0.0)`):n.push("agent.yaml missing metadata.version"),l.metadata.description||r.push("Consider adding a description to agent.yaml"),l.metadata.author||r.push("Consider adding an author to agent.yaml")}catch(l){n.push(`Invalid agent.yaml: ${l instanceof Error?l.message:String(l)}`)}let a=await Lg(s),c=a.reduce((l,f)=>l+f.size,0);c>Ha?n.push(`Bundle too large: ${Ri(c)} (max ${Ri(Ha)})`):c>Ha*.8&&r.push(`Bundle is ${Ri(c)}, approaching limit of ${Ri(Ha)}`);for(let l of a)l.size>Cg&&n.push(`File too large: ${l.relativePath} (${Ri(l.size)}, max ${Ri(Cg)})`);return{valid:n.length===0,errors:n,warnings:r}}async function Lg(t){let e=[];async function n(r,s){let i;try{i=await uu.promises.readdir(r)}catch{return}for(let o of i){if(qb.some(f=>o===f||o.startsWith(".")))continue;let a=kg.join(r,o),c=s?`${s}/${o}`:o,l=await uu.promises.stat(a);l.isDirectory()?await n(a,c):l.isFile()&&e.push({relativePath:c,absolutePath:a,size:l.size})}}return await n(t,""),e}async function Yb(t,e,n){let{agentId:r,visibility:s,changelog:i}=e;(0,dn.logInfo)(n,`[Publish] Starting publish for ${r}...`);let o=await Dg(t,r);if(!o.valid)throw new Error(`Validation failed:
40
40
  ${o.errors.join(`
41
41
  `)}`);o.warnings.length>0&&(0,dn.logInfo)(n,`[Publish] Warnings:
42
42
  ${o.warnings.join(`
43
- `)}`);let a=(0,Ha.getAgentManifestPath)(t,r),c=await(0,kg.loadAgentManifest)(a),l=c.metadata.version,f=`v${l}`,u=await(0,Zs.getGitHubUser)();(0,dn.logInfo)(n,`[Publish] Authenticated as ${u.login}`);let d=e.repoName||r,p=await(0,Zs.getRepo)(u.login,d);if(p?(0,dn.logInfo)(n,`[Publish] Using existing repository: ${p.full_name}`):((0,dn.logInfo)(n,`[Publish] Creating new repository: ${u.login}/${d}`),p=await(0,Zs.createRepo)(d,c.metadata.description||`AgentIDE pack: ${r}`,s==="private")),await(0,Zs.getReleaseByTag)(u.login,d,f))throw new Error(`Version ${l} already published. Bump version in agent.yaml and try again.`);let m=(0,Ha.getAgentRoot)(t,r),h=await Dg(m);(0,dn.logInfo)(n,`[Publish] Pushing ${h.length} files to ${p.full_name}...`);for(let _ of h){let y=await lu.promises.readFile(_.absolutePath,"utf-8"),b=await(0,Zs.getFileContent)(u.login,d,_.relativePath);await(0,Zs.putFileContent)(u.login,d,_.relativePath,y,`Publish ${r} v${l}`,b?.sha,p.default_branch),(0,dn.logInfo)(n,`[Publish] \u2713 ${_.relativePath}`)}(0,dn.logInfo)(n,`[Publish] Creating release ${f}...`);let E=await(0,Zs.createRelease)(u.login,d,f,`${r} v${l}`,i||`Release ${l}`,p.default_branch);return(0,dn.logInfo)(n,`[Publish] OK Published ${r} v${l}`),(0,dn.logInfo)(n,`[Publish] Repo: ${p.html_url}`),(0,dn.logInfo)(n,`[Publish] Release: ${E.html_url}`),{owner:u.login,repo:d,version:l,repoUrl:p.html_url,releaseUrl:E.html_url}}function Ri(t){return t<1024?`${t} B`:t<1024*1024?`${(t/1024).toFixed(1)} KB`:`${(t/(1024*1024)).toFixed(1)} MB`}});var Hg=S(gr=>{"use strict";var Wb=gr&&gr.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,s)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),Kb=gr&&gr.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),qb=gr&&gr.__importStar||(function(){var t=function(e){return t=Object.getOwnPropertyNames||function(n){var r=[];for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(r[r.length]=s);return r},t(e)};return function(e){if(e&&e.__esModule)return e;var n={};if(e!=null)for(var r=t(e),s=0;s<r.length;s++)r[s]!=="default"&&Wb(n,e,r[s]);return Kb(n,e),n}})();Object.defineProperty(gr,"__esModule",{value:!0});gr.downloadTarball=Gg;gr.installFromGitHub=Qb;gr.checkGitHubUpdate=Zb;var ja=require("fs"),Mg=qb(require("path")),Yb=require("zlib"),jt=en(),xa=Un(),Xb=Qs(),Ba=fo();async function Gg(t,e,n,r){let s=`https://github.com/${t}/${e}/archive/refs/tags/${n}.tar.gz`,i=await fetch(s,{headers:{"User-Agent":"AgentIDE"},redirect:"follow"});if(!i.ok){if(i.status===401||i.status===403||i.status===404||i.status===429){r&&(0,jt.logInfo)(r,"[Install] Requires authentication, signing in...");let c=await(0,Ba.getGitHubToken)();i=await fetch(s,{headers:{"User-Agent":"AgentIDE",Authorization:`Bearer ${c}`},redirect:"follow"})}if(!i.ok)throw new Error(`Failed to download: ${i.status} ${i.statusText}`)}let o=Buffer.from(await i.arrayBuffer()),a=(0,Yb.gunzipSync)(o);return Jb(a)}function Jb(t){let e=new Map,n=0;for(;n<t.length-512;){let r=t.subarray(n,n+512);if(r.every(c=>c===0))break;let s=r.subarray(0,100).toString("utf-8").replace(/\0/g,"").trim(),i=r.subarray(124,136).toString("utf-8").replace(/\0/g,"").trim(),o=r[156];if(!s){n+=512;continue}let a=parseInt(i,8)||0;if(n+=512,o===0||o===48){let c=t.subarray(n,n+a);e.set(s,Buffer.from(c))}n+=Math.ceil(a/512)*512}return e}function zb(t){let e=new Map;for(let[n,r]of t){let s=n.indexOf("/");if(s!==-1){let i=n.slice(s+1);i&&e.set(i,r)}}return e}async function Qb(t,e,n){let{source:r,force:s=!1}=e;(0,jt.logInfo)(n,`[Install] Installing from ${r}...`);let i=(0,Ba.parseGitHubSource)(r);(0,jt.logInfo)(n,`[Install] Repository: ${i.owner}/${i.repo}`);let o;if(i.version)o=i.version;else{(0,jt.logInfo)(n,"[Install] Resolving latest version...");let d=await Ug(i.owner,i.repo,n);if(!d)throw new Error(`No releases found for ${i.owner}/${i.repo}. The repository may not have any published versions.`);o=d,(0,jt.logInfo)(n,`[Install] Latest version: ${o}`)}let a=i.repo,c=(0,xa.getAgentRoot)(t,a);if(await(0,jt.pathExists)(c)){if(!s)throw new Error(`Agent "${a}" already exists. Use force option to overwrite.`);(0,jt.logInfo)(n,"[Install] Removing existing installation..."),await ja.promises.rm(c,{recursive:!0,force:!0})}(0,jt.logInfo)(n,`[Install] Downloading ${o}...`);let l=await Gg(i.owner,i.repo,o,n),f=zb(l);if((0,jt.logInfo)(n,`[Install] Found ${f.size} files`),!f.has(xa.AGENT_CONSTANTS.MANIFEST_FILE))throw new Error(`Invalid agent pack: missing ${xa.AGENT_CONSTANTS.MANIFEST_FILE}. Ensure the repository contains a valid agent pack.`);await ja.promises.mkdir(c,{recursive:!0});let u=0;for(let[d,p]of f){(0,jt.logInfo)(n,`[Install] \u2193 ${d}`);let g=Mg.join(c,d);await ja.promises.mkdir(Mg.dirname(g),{recursive:!0}),await ja.promises.writeFile(g,p),u+=p.length}return(0,jt.logInfo)(n,`[Install] OK Installed ${a} ${o}`),(0,jt.logInfo)(n,`[Install] Location: ${c}`),(0,jt.logInfo)(n,`[Install] Downloaded: ${ev(u)}`),{agentId:a,version:o,source:`github://${i.owner}/${i.repo}@${o}`,installed:!0}}async function Ug(t,e,n){let r=`https://api.github.com/repos/${t}/${e}/releases/latest`,s=await fetch(r,{headers:{"User-Agent":"AgentIDE",Accept:"application/vnd.github.v3+json"}});if(!s.ok&&(s.status===401||s.status===403||s.status===429)){n&&(0,jt.logInfo)(n,"[Install] Requires authentication...");let o=await(0,Ba.getGitHubToken)();s=await fetch(r,{headers:{"User-Agent":"AgentIDE",Accept:"application/vnd.github.v3+json",Authorization:`Bearer ${o}`}})}return s.ok?(await s.json()).tag_name:null}async function Zb(t,e,n,r){try{let s=(0,xa.getAgentManifestPath)(t,e);if(!await(0,jt.pathExists)(s))return{hasUpdate:!1};let o=(await(0,Xb.loadAgentManifest)(s)).metadata.version,a=(0,Ba.parseGitHubSource)(n),c=await Ug(a.owner,a.repo,r);if(!c)return{hasUpdate:!1,currentVersion:o};let l=c.replace(/^v/,"");return{hasUpdate:l!==o,currentVersion:o,latestVersion:l}}catch(s){return(0,jt.logInfo)(r,`[Install] Update check failed: ${s}`),{hasUpdate:!1}}}function ev(t){return t<1024?`${t} B`:t<1024*1024?`${(t/1024).toFixed(1)} KB`:`${(t/(1024*1024)).toFixed(1)} MB`}});var uu=S(P=>{"use strict";Object.defineProperty(P,"__esModule",{value:!0});P.checkGitHubUpdate=P.installFromGitHub=P.validateForPublish=P.publishToGitHub=P.getGitHubUser=P.isGitHubAuthenticated=P.getGitHubToken=P.formatGitHubSource=P.parseGitHubSource=P.resetDefaultAgent=P.duplicateAgent=P.updateFromUserLibrary=P.checkForUpdate=P.readAgentSource=P.promoteToUserLibrary=P.hydrateFromUserLibrary=P.isAgentInUserLibrary=P.isWorkspaceAgentAvailable=P.listUserLibraryAgents=P.updateManifestName=P.parseAgentManifest=P.loadAgentManifest=P.stringifyYaml=P.parseYaml=P.AgentPackManager=P.getUserAgentCurrentPath=P.getUserAgentVersionDir=P.getUserAgentRoot=P.getUserAgentsDir=P.getAgentideHome=P.parseAgentIdFromPath=P.getSessionsDir=P.getAgentMcpDir=P.getAgentRulesDir=P.getAgentSkillsDir=P.getAgentContextPath=P.getAgentAgentsMdPath=P.getAgentManifestPath=P.isDefaultAgent=P.engineHomeUserKey=P.userScopedEngineHomeFromKey=P.userScopedEngineHome=P.resolveRuntimePaths=P.resolveAgentRuntimePaths=P.getAgentRoot=P.getAgentsDir=P.getAgentideDir=P.AGENT_CONSTANTS=void 0;var Ye=Un();Object.defineProperty(P,"AGENT_CONSTANTS",{enumerable:!0,get:function(){return Ye.AGENT_CONSTANTS}});Object.defineProperty(P,"getAgentideDir",{enumerable:!0,get:function(){return Ye.getAgentideDir}});Object.defineProperty(P,"getAgentsDir",{enumerable:!0,get:function(){return Ye.getAgentsDir}});Object.defineProperty(P,"getAgentRoot",{enumerable:!0,get:function(){return Ye.getAgentRoot}});Object.defineProperty(P,"resolveAgentRuntimePaths",{enumerable:!0,get:function(){return Ye.resolveAgentRuntimePaths}});Object.defineProperty(P,"resolveRuntimePaths",{enumerable:!0,get:function(){return Ye.resolveRuntimePaths}});Object.defineProperty(P,"userScopedEngineHome",{enumerable:!0,get:function(){return Ye.userScopedEngineHome}});Object.defineProperty(P,"userScopedEngineHomeFromKey",{enumerable:!0,get:function(){return Ye.userScopedEngineHomeFromKey}});Object.defineProperty(P,"engineHomeUserKey",{enumerable:!0,get:function(){return Ye.engineHomeUserKey}});Object.defineProperty(P,"isDefaultAgent",{enumerable:!0,get:function(){return Ye.isDefaultAgent}});Object.defineProperty(P,"getAgentManifestPath",{enumerable:!0,get:function(){return Ye.getAgentManifestPath}});Object.defineProperty(P,"getAgentAgentsMdPath",{enumerable:!0,get:function(){return Ye.getAgentAgentsMdPath}});Object.defineProperty(P,"getAgentContextPath",{enumerable:!0,get:function(){return Ye.getAgentContextPath}});Object.defineProperty(P,"getAgentSkillsDir",{enumerable:!0,get:function(){return Ye.getAgentSkillsDir}});Object.defineProperty(P,"getAgentRulesDir",{enumerable:!0,get:function(){return Ye.getAgentRulesDir}});Object.defineProperty(P,"getAgentMcpDir",{enumerable:!0,get:function(){return Ye.getAgentMcpDir}});Object.defineProperty(P,"getSessionsDir",{enumerable:!0,get:function(){return Ye.getSessionsDir}});Object.defineProperty(P,"parseAgentIdFromPath",{enumerable:!0,get:function(){return Ye.parseAgentIdFromPath}});Object.defineProperty(P,"getAgentideHome",{enumerable:!0,get:function(){return Ye.getAgentideHome}});Object.defineProperty(P,"getUserAgentsDir",{enumerable:!0,get:function(){return Ye.getUserAgentsDir}});Object.defineProperty(P,"getUserAgentRoot",{enumerable:!0,get:function(){return Ye.getUserAgentRoot}});Object.defineProperty(P,"getUserAgentVersionDir",{enumerable:!0,get:function(){return Ye.getUserAgentVersionDir}});Object.defineProperty(P,"getUserAgentCurrentPath",{enumerable:!0,get:function(){return Ye.getUserAgentCurrentPath}});var tv=Ng();Object.defineProperty(P,"AgentPackManager",{enumerable:!0,get:function(){return tv.AgentPackManager}});var po=Qs();Object.defineProperty(P,"parseYaml",{enumerable:!0,get:function(){return po.parseYaml}});Object.defineProperty(P,"stringifyYaml",{enumerable:!0,get:function(){return po.stringifyYaml}});Object.defineProperty(P,"loadAgentManifest",{enumerable:!0,get:function(){return po.loadAgentManifest}});Object.defineProperty(P,"parseAgentManifest",{enumerable:!0,get:function(){return po.parseAgentManifest}});Object.defineProperty(P,"updateManifestName",{enumerable:!0,get:function(){return po.updateManifestName}});var Dr=cu();Object.defineProperty(P,"listUserLibraryAgents",{enumerable:!0,get:function(){return Dr.listUserLibraryAgents}});Object.defineProperty(P,"isWorkspaceAgentAvailable",{enumerable:!0,get:function(){return Dr.isWorkspaceAgentAvailable}});Object.defineProperty(P,"isAgentInUserLibrary",{enumerable:!0,get:function(){return Dr.isAgentInUserLibrary}});Object.defineProperty(P,"hydrateFromUserLibrary",{enumerable:!0,get:function(){return Dr.hydrateFromUserLibrary}});Object.defineProperty(P,"promoteToUserLibrary",{enumerable:!0,get:function(){return Dr.promoteToUserLibrary}});Object.defineProperty(P,"readAgentSource",{enumerable:!0,get:function(){return Dr.readAgentSource}});Object.defineProperty(P,"checkForUpdate",{enumerable:!0,get:function(){return Dr.checkForUpdate}});Object.defineProperty(P,"updateFromUserLibrary",{enumerable:!0,get:function(){return Dr.updateFromUserLibrary}});Object.defineProperty(P,"duplicateAgent",{enumerable:!0,get:function(){return Dr.duplicateAgent}});Object.defineProperty(P,"resetDefaultAgent",{enumerable:!0,get:function(){return Dr.resetDefaultAgent}});var go=fo();Object.defineProperty(P,"parseGitHubSource",{enumerable:!0,get:function(){return go.parseGitHubSource}});Object.defineProperty(P,"formatGitHubSource",{enumerable:!0,get:function(){return go.formatGitHubSource}});Object.defineProperty(P,"getGitHubToken",{enumerable:!0,get:function(){return go.getGitHubToken}});Object.defineProperty(P,"isGitHubAuthenticated",{enumerable:!0,get:function(){return go.isGitHubAuthenticated}});Object.defineProperty(P,"getGitHubUser",{enumerable:!0,get:function(){return go.getGitHubUser}});var jg=Lg();Object.defineProperty(P,"publishToGitHub",{enumerable:!0,get:function(){return jg.publishToGitHub}});Object.defineProperty(P,"validateForPublish",{enumerable:!0,get:function(){return jg.validateForPublish}});var xg=Hg();Object.defineProperty(P,"installFromGitHub",{enumerable:!0,get:function(){return xg.installFromGitHub}});Object.defineProperty(P,"checkGitHubUpdate",{enumerable:!0,get:function(){return xg.checkGitHubUpdate}})});var Fa=S(Nt=>{"use strict";var nv=Nt&&Nt.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,s)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),rv=Nt&&Nt.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),sv=Nt&&Nt.__importStar||(function(){var t=function(e){return t=Object.getOwnPropertyNames||function(n){var r=[];for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(r[r.length]=s);return r},t(e)};return function(e){if(e&&e.__esModule)return e;var n={};if(e!=null)for(var r=t(e),s=0;s<r.length;s++)r[s]!=="default"&&nv(n,e,r[s]);return rv(n,e),n}})();Object.defineProperty(Nt,"__esModule",{value:!0});Nt.AGENTHIPPO_GATEWAY_OUTBOUND_FILE_ENV=Nt.GATEWAY_OUTBOUND_FILENAME=void 0;Nt.safeGatewaySessionDirId=du;Nt.getGatewayOutboundFilePath=Bg;Nt.resolveGatewaySessionDirId=Fg;Nt.resolveGatewayOutboundFilePath=av;var iv=sv(require("path")),ov=Ke();Nt.GATEWAY_OUTBOUND_FILENAME="gateway-outbound.json";Nt.AGENTHIPPO_GATEWAY_OUTBOUND_FILE_ENV="AGENTHIPPO_GATEWAY_OUTBOUND_FILE";function du(t){return t.replace(/[<>:"/\\|?*\x00-\x1F]/g,"_").slice(0,160).replace(/^\.+$/,n=>"_".repeat(n.length))||"session"}function Bg(t,e){return iv.join(t,ov.AGENTIDE_DIR_NAME,"sessions",e,Nt.GATEWAY_OUTBOUND_FILENAME)}function Fg(t){let e=t.chatSessionId?.trim();if(e)return du(e);let n=t.gatewaySessionKey?.trim();if(n)return du(n)}function av(t){let e=Fg(t);if(e)return Bg(t.workspaceRoot,e)}});var Kg=S(tn=>{"use strict";var cv=tn&&tn.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,s)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),lv=tn&&tn.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),uv=tn&&tn.__importStar||(function(){var t=function(e){return t=Object.getOwnPropertyNames||function(n){var r=[];for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(r[r.length]=s);return r},t(e)};return function(e){if(e&&e.__esModule)return e;var n={};if(e!=null)for(var r=t(e),s=0;s<r.length;s++)r[s]!=="default"&&cv(n,e,r[s]);return lv(n,e),n}})();Object.defineProperty(tn,"__esModule",{value:!0});tn.isProcessRunning=Va;tn.isProcessRunningAsync=fv;tn.isPidFileProcessRunning=pv;tn.readPidFile=Vg;tn.writePidFile=gv;tn.removePidFile=Wg;tn.checkPidFileWithCleanup=hv;var ho=require("fs"),dv=uv(require("path"));function Va(t){try{return process.kill(t,0),!0}catch(e){return e?.code==="EPERM"}}async function fv(t){return Va(t)}async function pv(t){try{let e=await ho.promises.readFile(t,"utf8").catch(()=>null);if(!e)return!1;let n=parseInt(e.trim().split(`
44
- `)[0],10);return isNaN(n)?!1:Va(n)}catch{return!1}}async function Vg(t){try{let n=(await ho.promises.readFile(t,"utf8")).trim().split(`
45
- `),r=parseInt(n[0],10);return isNaN(r)?null:{pid:r,metadata:n.slice(1)}}catch{return null}}async function gv(t,e,...n){try{let r=dv.dirname(t);await ho.promises.mkdir(r,{recursive:!0});let s=[e,...n].join(`
43
+ `)}`);let a=(0,ja.getAgentManifestPath)(t,r),c=await(0,$g.loadAgentManifest)(a),l=c.metadata.version,f=`v${l}`,u=await(0,Zs.getGitHubUser)();(0,dn.logInfo)(n,`[Publish] Authenticated as ${u.login}`);let d=e.repoName||r,p=await(0,Zs.getRepo)(u.login,d);if(p?(0,dn.logInfo)(n,`[Publish] Using existing repository: ${p.full_name}`):((0,dn.logInfo)(n,`[Publish] Creating new repository: ${u.login}/${d}`),p=await(0,Zs.createRepo)(d,c.metadata.description||`AgentIDE pack: ${r}`,s==="private")),await(0,Zs.getReleaseByTag)(u.login,d,f))throw new Error(`Version ${l} already published. Bump version in agent.yaml and try again.`);let m=(0,ja.getAgentRoot)(t,r),h=await Lg(m);(0,dn.logInfo)(n,`[Publish] Pushing ${h.length} files to ${p.full_name}...`);for(let _ of h){let y=await uu.promises.readFile(_.absolutePath,"utf-8"),b=await(0,Zs.getFileContent)(u.login,d,_.relativePath);await(0,Zs.putFileContent)(u.login,d,_.relativePath,y,`Publish ${r} v${l}`,b?.sha,p.default_branch),(0,dn.logInfo)(n,`[Publish] \u2713 ${_.relativePath}`)}(0,dn.logInfo)(n,`[Publish] Creating release ${f}...`);let E=await(0,Zs.createRelease)(u.login,d,f,`${r} v${l}`,i||`Release ${l}`,p.default_branch);return(0,dn.logInfo)(n,`[Publish] OK Published ${r} v${l}`),(0,dn.logInfo)(n,`[Publish] Repo: ${p.html_url}`),(0,dn.logInfo)(n,`[Publish] Release: ${E.html_url}`),{owner:u.login,repo:d,version:l,repoUrl:p.html_url,releaseUrl:E.html_url}}function Ri(t){return t<1024?`${t} B`:t<1024*1024?`${(t/1024).toFixed(1)} KB`:`${(t/(1024*1024)).toFixed(1)} MB`}});var jg=S(gr=>{"use strict";var Xb=gr&&gr.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,s)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),Jb=gr&&gr.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),zb=gr&&gr.__importStar||(function(){var t=function(e){return t=Object.getOwnPropertyNames||function(n){var r=[];for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(r[r.length]=s);return r},t(e)};return function(e){if(e&&e.__esModule)return e;var n={};if(e!=null)for(var r=t(e),s=0;s<r.length;s++)r[s]!=="default"&&Xb(n,e,r[s]);return Jb(n,e),n}})();Object.defineProperty(gr,"__esModule",{value:!0});gr.downloadTarball=Ug;gr.installFromGitHub=nv;gr.checkGitHubUpdate=rv;var xa=require("fs"),Gg=zb(require("path")),Qb=require("zlib"),jt=en(),Ba=Un(),Zb=Qs(),Fa=go();async function Ug(t,e,n,r){let s=`https://github.com/${t}/${e}/archive/refs/tags/${n}.tar.gz`,i=await fetch(s,{headers:{"User-Agent":"AgentIDE"},redirect:"follow"});if(!i.ok){if(i.status===401||i.status===403||i.status===404||i.status===429){r&&(0,jt.logInfo)(r,"[Install] Requires authentication, signing in...");let c=await(0,Fa.getGitHubToken)();i=await fetch(s,{headers:{"User-Agent":"AgentIDE",Authorization:`Bearer ${c}`},redirect:"follow"})}if(!i.ok)throw new Error(`Failed to download: ${i.status} ${i.statusText}`)}let o=Buffer.from(await i.arrayBuffer()),a=(0,Qb.gunzipSync)(o);return ev(a)}function ev(t){let e=new Map,n=0;for(;n<t.length-512;){let r=t.subarray(n,n+512);if(r.every(c=>c===0))break;let s=r.subarray(0,100).toString("utf-8").replace(/\0/g,"").trim(),i=r.subarray(124,136).toString("utf-8").replace(/\0/g,"").trim(),o=r[156];if(!s){n+=512;continue}let a=parseInt(i,8)||0;if(n+=512,o===0||o===48){let c=t.subarray(n,n+a);e.set(s,Buffer.from(c))}n+=Math.ceil(a/512)*512}return e}function tv(t){let e=new Map;for(let[n,r]of t){let s=n.indexOf("/");if(s!==-1){let i=n.slice(s+1);i&&e.set(i,r)}}return e}async function nv(t,e,n){let{source:r,force:s=!1}=e;(0,jt.logInfo)(n,`[Install] Installing from ${r}...`);let i=(0,Fa.parseGitHubSource)(r);(0,jt.logInfo)(n,`[Install] Repository: ${i.owner}/${i.repo}`);let o;if(i.version)o=i.version;else{(0,jt.logInfo)(n,"[Install] Resolving latest version...");let d=await Hg(i.owner,i.repo,n);if(!d)throw new Error(`No releases found for ${i.owner}/${i.repo}. The repository may not have any published versions.`);o=d,(0,jt.logInfo)(n,`[Install] Latest version: ${o}`)}let a=i.repo,c=(0,Ba.getAgentRoot)(t,a);if(await(0,jt.pathExists)(c)){if(!s)throw new Error(`Agent "${a}" already exists. Use force option to overwrite.`);(0,jt.logInfo)(n,"[Install] Removing existing installation..."),await xa.promises.rm(c,{recursive:!0,force:!0})}(0,jt.logInfo)(n,`[Install] Downloading ${o}...`);let l=await Ug(i.owner,i.repo,o,n),f=tv(l);if((0,jt.logInfo)(n,`[Install] Found ${f.size} files`),!f.has(Ba.AGENT_CONSTANTS.MANIFEST_FILE))throw new Error(`Invalid agent pack: missing ${Ba.AGENT_CONSTANTS.MANIFEST_FILE}. Ensure the repository contains a valid agent pack.`);await xa.promises.mkdir(c,{recursive:!0});let u=0;for(let[d,p]of f){(0,jt.logInfo)(n,`[Install] \u2193 ${d}`);let g=Gg.join(c,d);await xa.promises.mkdir(Gg.dirname(g),{recursive:!0}),await xa.promises.writeFile(g,p),u+=p.length}return(0,jt.logInfo)(n,`[Install] OK Installed ${a} ${o}`),(0,jt.logInfo)(n,`[Install] Location: ${c}`),(0,jt.logInfo)(n,`[Install] Downloaded: ${sv(u)}`),{agentId:a,version:o,source:`github://${i.owner}/${i.repo}@${o}`,installed:!0}}async function Hg(t,e,n){let r=`https://api.github.com/repos/${t}/${e}/releases/latest`,s=await fetch(r,{headers:{"User-Agent":"AgentIDE",Accept:"application/vnd.github.v3+json"}});if(!s.ok&&(s.status===401||s.status===403||s.status===429)){n&&(0,jt.logInfo)(n,"[Install] Requires authentication...");let o=await(0,Fa.getGitHubToken)();s=await fetch(r,{headers:{"User-Agent":"AgentIDE",Accept:"application/vnd.github.v3+json",Authorization:`Bearer ${o}`}})}return s.ok?(await s.json()).tag_name:null}async function rv(t,e,n,r){try{let s=(0,Ba.getAgentManifestPath)(t,e);if(!await(0,jt.pathExists)(s))return{hasUpdate:!1};let o=(await(0,Zb.loadAgentManifest)(s)).metadata.version,a=(0,Fa.parseGitHubSource)(n),c=await Hg(a.owner,a.repo,r);if(!c)return{hasUpdate:!1,currentVersion:o};let l=c.replace(/^v/,"");return{hasUpdate:l!==o,currentVersion:o,latestVersion:l}}catch(s){return(0,jt.logInfo)(r,`[Install] Update check failed: ${s}`),{hasUpdate:!1}}}function sv(t){return t<1024?`${t} B`:t<1024*1024?`${(t/1024).toFixed(1)} KB`:`${(t/(1024*1024)).toFixed(1)} MB`}});var du=S(P=>{"use strict";Object.defineProperty(P,"__esModule",{value:!0});P.checkGitHubUpdate=P.installFromGitHub=P.validateForPublish=P.publishToGitHub=P.getGitHubUser=P.isGitHubAuthenticated=P.getGitHubToken=P.formatGitHubSource=P.parseGitHubSource=P.resetDefaultAgent=P.duplicateAgent=P.updateFromUserLibrary=P.checkForUpdate=P.readAgentSource=P.promoteToUserLibrary=P.hydrateFromUserLibrary=P.isAgentInUserLibrary=P.isWorkspaceAgentAvailable=P.listUserLibraryAgents=P.updateManifestName=P.parseAgentManifest=P.loadAgentManifest=P.stringifyYaml=P.parseYaml=P.AgentPackManager=P.getUserAgentCurrentPath=P.getUserAgentVersionDir=P.getUserAgentRoot=P.getUserAgentsDir=P.getAgentideHome=P.parseAgentIdFromPath=P.getSessionsDir=P.getAgentMcpDir=P.getAgentRulesDir=P.getAgentSkillsDir=P.getAgentContextPath=P.getAgentAgentsMdPath=P.getAgentManifestPath=P.isDefaultAgent=P.engineHomeUserKey=P.userScopedEngineHomeFromKey=P.userScopedEngineHome=P.resolveRuntimePaths=P.resolveAgentRuntimePaths=P.getAgentRoot=P.getAgentsDir=P.getAgentideDir=P.AGENT_CONSTANTS=void 0;var Ye=Un();Object.defineProperty(P,"AGENT_CONSTANTS",{enumerable:!0,get:function(){return Ye.AGENT_CONSTANTS}});Object.defineProperty(P,"getAgentideDir",{enumerable:!0,get:function(){return Ye.getAgentideDir}});Object.defineProperty(P,"getAgentsDir",{enumerable:!0,get:function(){return Ye.getAgentsDir}});Object.defineProperty(P,"getAgentRoot",{enumerable:!0,get:function(){return Ye.getAgentRoot}});Object.defineProperty(P,"resolveAgentRuntimePaths",{enumerable:!0,get:function(){return Ye.resolveAgentRuntimePaths}});Object.defineProperty(P,"resolveRuntimePaths",{enumerable:!0,get:function(){return Ye.resolveRuntimePaths}});Object.defineProperty(P,"userScopedEngineHome",{enumerable:!0,get:function(){return Ye.userScopedEngineHome}});Object.defineProperty(P,"userScopedEngineHomeFromKey",{enumerable:!0,get:function(){return Ye.userScopedEngineHomeFromKey}});Object.defineProperty(P,"engineHomeUserKey",{enumerable:!0,get:function(){return Ye.engineHomeUserKey}});Object.defineProperty(P,"isDefaultAgent",{enumerable:!0,get:function(){return Ye.isDefaultAgent}});Object.defineProperty(P,"getAgentManifestPath",{enumerable:!0,get:function(){return Ye.getAgentManifestPath}});Object.defineProperty(P,"getAgentAgentsMdPath",{enumerable:!0,get:function(){return Ye.getAgentAgentsMdPath}});Object.defineProperty(P,"getAgentContextPath",{enumerable:!0,get:function(){return Ye.getAgentContextPath}});Object.defineProperty(P,"getAgentSkillsDir",{enumerable:!0,get:function(){return Ye.getAgentSkillsDir}});Object.defineProperty(P,"getAgentRulesDir",{enumerable:!0,get:function(){return Ye.getAgentRulesDir}});Object.defineProperty(P,"getAgentMcpDir",{enumerable:!0,get:function(){return Ye.getAgentMcpDir}});Object.defineProperty(P,"getSessionsDir",{enumerable:!0,get:function(){return Ye.getSessionsDir}});Object.defineProperty(P,"parseAgentIdFromPath",{enumerable:!0,get:function(){return Ye.parseAgentIdFromPath}});Object.defineProperty(P,"getAgentideHome",{enumerable:!0,get:function(){return Ye.getAgentideHome}});Object.defineProperty(P,"getUserAgentsDir",{enumerable:!0,get:function(){return Ye.getUserAgentsDir}});Object.defineProperty(P,"getUserAgentRoot",{enumerable:!0,get:function(){return Ye.getUserAgentRoot}});Object.defineProperty(P,"getUserAgentVersionDir",{enumerable:!0,get:function(){return Ye.getUserAgentVersionDir}});Object.defineProperty(P,"getUserAgentCurrentPath",{enumerable:!0,get:function(){return Ye.getUserAgentCurrentPath}});var iv=Rg();Object.defineProperty(P,"AgentPackManager",{enumerable:!0,get:function(){return iv.AgentPackManager}});var ho=Qs();Object.defineProperty(P,"parseYaml",{enumerable:!0,get:function(){return ho.parseYaml}});Object.defineProperty(P,"stringifyYaml",{enumerable:!0,get:function(){return ho.stringifyYaml}});Object.defineProperty(P,"loadAgentManifest",{enumerable:!0,get:function(){return ho.loadAgentManifest}});Object.defineProperty(P,"parseAgentManifest",{enumerable:!0,get:function(){return ho.parseAgentManifest}});Object.defineProperty(P,"updateManifestName",{enumerable:!0,get:function(){return ho.updateManifestName}});var Dr=lu();Object.defineProperty(P,"listUserLibraryAgents",{enumerable:!0,get:function(){return Dr.listUserLibraryAgents}});Object.defineProperty(P,"isWorkspaceAgentAvailable",{enumerable:!0,get:function(){return Dr.isWorkspaceAgentAvailable}});Object.defineProperty(P,"isAgentInUserLibrary",{enumerable:!0,get:function(){return Dr.isAgentInUserLibrary}});Object.defineProperty(P,"hydrateFromUserLibrary",{enumerable:!0,get:function(){return Dr.hydrateFromUserLibrary}});Object.defineProperty(P,"promoteToUserLibrary",{enumerable:!0,get:function(){return Dr.promoteToUserLibrary}});Object.defineProperty(P,"readAgentSource",{enumerable:!0,get:function(){return Dr.readAgentSource}});Object.defineProperty(P,"checkForUpdate",{enumerable:!0,get:function(){return Dr.checkForUpdate}});Object.defineProperty(P,"updateFromUserLibrary",{enumerable:!0,get:function(){return Dr.updateFromUserLibrary}});Object.defineProperty(P,"duplicateAgent",{enumerable:!0,get:function(){return Dr.duplicateAgent}});Object.defineProperty(P,"resetDefaultAgent",{enumerable:!0,get:function(){return Dr.resetDefaultAgent}});var mo=go();Object.defineProperty(P,"parseGitHubSource",{enumerable:!0,get:function(){return mo.parseGitHubSource}});Object.defineProperty(P,"formatGitHubSource",{enumerable:!0,get:function(){return mo.formatGitHubSource}});Object.defineProperty(P,"getGitHubToken",{enumerable:!0,get:function(){return mo.getGitHubToken}});Object.defineProperty(P,"isGitHubAuthenticated",{enumerable:!0,get:function(){return mo.isGitHubAuthenticated}});Object.defineProperty(P,"getGitHubUser",{enumerable:!0,get:function(){return mo.getGitHubUser}});var xg=Mg();Object.defineProperty(P,"publishToGitHub",{enumerable:!0,get:function(){return xg.publishToGitHub}});Object.defineProperty(P,"validateForPublish",{enumerable:!0,get:function(){return xg.validateForPublish}});var Bg=jg();Object.defineProperty(P,"installFromGitHub",{enumerable:!0,get:function(){return Bg.installFromGitHub}});Object.defineProperty(P,"checkGitHubUpdate",{enumerable:!0,get:function(){return Bg.checkGitHubUpdate}})});var Va=S(Nt=>{"use strict";var ov=Nt&&Nt.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,s)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),av=Nt&&Nt.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),cv=Nt&&Nt.__importStar||(function(){var t=function(e){return t=Object.getOwnPropertyNames||function(n){var r=[];for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(r[r.length]=s);return r},t(e)};return function(e){if(e&&e.__esModule)return e;var n={};if(e!=null)for(var r=t(e),s=0;s<r.length;s++)r[s]!=="default"&&ov(n,e,r[s]);return av(n,e),n}})();Object.defineProperty(Nt,"__esModule",{value:!0});Nt.AGENTHIPPO_GATEWAY_OUTBOUND_FILE_ENV=Nt.GATEWAY_OUTBOUND_FILENAME=void 0;Nt.safeGatewaySessionDirId=fu;Nt.getGatewayOutboundFilePath=Fg;Nt.resolveGatewaySessionDirId=Vg;Nt.resolveGatewayOutboundFilePath=dv;var lv=cv(require("path")),uv=Ke();Nt.GATEWAY_OUTBOUND_FILENAME="gateway-outbound.json";Nt.AGENTHIPPO_GATEWAY_OUTBOUND_FILE_ENV="AGENTHIPPO_GATEWAY_OUTBOUND_FILE";function fu(t){return t.replace(/[<>:"/\\|?*\x00-\x1F]/g,"_").slice(0,160).replace(/^\.+$/,n=>"_".repeat(n.length))||"session"}function Fg(t,e){return lv.join(t,uv.AGENTIDE_DIR_NAME,"sessions",e,Nt.GATEWAY_OUTBOUND_FILENAME)}function Vg(t){let e=t.chatSessionId?.trim();if(e)return fu(e);let n=t.gatewaySessionKey?.trim();if(n)return fu(n)}function dv(t){let e=Vg(t);if(e)return Fg(t.workspaceRoot,e)}});var qg=S(tn=>{"use strict";var fv=tn&&tn.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,s)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),pv=tn&&tn.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),gv=tn&&tn.__importStar||(function(){var t=function(e){return t=Object.getOwnPropertyNames||function(n){var r=[];for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(r[r.length]=s);return r},t(e)};return function(e){if(e&&e.__esModule)return e;var n={};if(e!=null)for(var r=t(e),s=0;s<r.length;s++)r[s]!=="default"&&fv(n,e,r[s]);return pv(n,e),n}})();Object.defineProperty(tn,"__esModule",{value:!0});tn.isProcessRunning=Wa;tn.isProcessRunningAsync=mv;tn.isPidFileProcessRunning=Ev;tn.readPidFile=Wg;tn.writePidFile=_v;tn.removePidFile=Kg;tn.checkPidFileWithCleanup=yv;var Eo=require("fs"),hv=gv(require("path"));function Wa(t){try{return process.kill(t,0),!0}catch(e){return e?.code==="EPERM"}}async function mv(t){return Wa(t)}async function Ev(t){try{let e=await Eo.promises.readFile(t,"utf8").catch(()=>null);if(!e)return!1;let n=parseInt(e.trim().split(`
44
+ `)[0],10);return isNaN(n)?!1:Wa(n)}catch{return!1}}async function Wg(t){try{let n=(await Eo.promises.readFile(t,"utf8")).trim().split(`
45
+ `),r=parseInt(n[0],10);return isNaN(r)?null:{pid:r,metadata:n.slice(1)}}catch{return null}}async function _v(t,e,...n){try{let r=hv.dirname(t);await Eo.promises.mkdir(r,{recursive:!0});let s=[e,...n].join(`
46
46
  `)+`
47
- `;await ho.promises.writeFile(t,s,"utf8")}catch{}}async function Wg(t){try{await ho.promises.unlink(t)}catch{}}async function hv(t){let e=await Vg(t);return e?Va(e.pid)?e:(await Wg(t),null):null}});var qg=S(ls=>{"use strict";var mv=ls&&ls.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,s)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),Ev=ls&&ls.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),_v=ls&&ls.__importStar||(function(){var t=function(e){return t=Object.getOwnPropertyNames||function(n){var r=[];for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(r[r.length]=s);return r},t(e)};return function(e){if(e&&e.__esModule)return e;var n={};if(e!=null)for(var r=t(e),s=0;s<r.length;s++)r[s]!=="default"&&mv(n,e,r[s]);return Ev(n,e),n}})();Object.defineProperty(ls,"__esModule",{value:!0});ls.probePort=wv;var yv=_v(require("net"));function wv(t,e="127.0.0.1",n=2e3){return new Promise(r=>{let s=new yv.Socket;s.setTimeout(n),s.once("connect",()=>{s.destroy(),r(!0)}),s.once("timeout",()=>{s.destroy(),r(!1)}),s.once("error",()=>{s.destroy(),r(!1)}),s.connect(t,e)})}});var pu=S(Bn=>{"use strict";var Av=Bn&&Bn.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,s)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),Sv=Bn&&Bn.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),fu=Bn&&Bn.__importStar||(function(){var t=function(e){return t=Object.getOwnPropertyNames||function(n){var r=[];for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(r[r.length]=s);return r},t(e)};return function(e){if(e&&e.__esModule)return e;var n={};if(e!=null)for(var r=t(e),s=0;s<r.length;s++)r[s]!=="default"&&Av(n,e,r[s]);return Sv(n,e),n}})();Object.defineProperty(Bn,"__esModule",{value:!0});Bn.findBinary=Yg;Bn.findBinaryCached=Nv;Bn.getCommonBinaryPaths=Rv;Bn.clearBinaryCache=Cv;var Tv=require("child_process"),bv=require("util"),vv=require("fs"),Wa=fu(require("fs")),vn=fu(require("path")),Ov=fu(require("os")),Iv=(0,bv.promisify)(Tv.exec),Ka=process.platform==="win32",Pv=6e4,qa=new Map;async function Yg(t,e=5e3){try{let n=Ka?`where ${t}`:`which ${t}`,{stdout:r}=await Iv(n,{timeout:e});return r.trim().split(`
48
- `)[0]||void 0}catch{return}}async function Nv(t,e=[],n=Pv){let r=Date.now(),s=qa.get(t);if(s&&r-s.timestamp<n)return s.path;let i=await Yg(t);if(!i)for(let o of e)try{await vv.promises.access(o,Ka?Wa.constants.F_OK:Wa.constants.X_OK),i=o;break}catch{}return qa.set(t,{path:i,timestamp:r}),i}function Rv(t){let e=Ov.homedir(),n=Ka?`${t}.cmd`:t;if(Ka){let o=process.env.LOCALAPPDATA||vn.join(e,"AppData","Local");return[vn.join(o,"AgentHippo","bin",n),vn.join(e,"AppData","Local","Programs",t,`${t}.exe`),vn.join(e,"AppData","Roaming","npm",n),vn.join(e,"AppData","Local","pnpm",n),vn.join(e,".npm-global",n)]}let r=[vn.join(e,".local","bin",t),vn.join(e,"Library","pnpm",t),vn.join(e,".local","share","pnpm",t),vn.join(e,".npm-global","bin",t),"/opt/homebrew/bin/"+t,"/usr/local/bin/"+t,"/usr/bin/"+t],s=process.env.NVM_DIR||vn.join(e,".nvm"),i=vn.join(s,"versions","node");if(Wa.existsSync(i))try{let o=Wa.readdirSync(i,{withFileTypes:!0}).filter(a=>a.isDirectory()).map(a=>a.name).sort().reverse();for(let a of o)r.push(vn.join(i,a,"bin",t))}catch{}return r}function Cv(t){t?qa.delete(t):qa.clear()}});var Ya=S(hr=>{"use strict";var kv=hr&&hr.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,s)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),$v=hr&&hr.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),gu=hr&&hr.__importStar||(function(){var t=function(e){return t=Object.getOwnPropertyNames||function(n){var r=[];for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(r[r.length]=s);return r},t(e)};return function(e){if(e&&e.__esModule)return e;var n={};if(e!=null)for(var r=t(e),s=0;s<r.length;s++)r[s]!=="default"&&kv(n,e,r[s]);return $v(n,e),n}})();Object.defineProperty(hr,"__esModule",{value:!0});hr.getNodeBinaryCandidates=th;hr.resolveNodeBinary=Uv;hr.prependPathDir=Hv;var ei=gu(require("fs")),Qg=gu(require("os")),Ci=gu(require("path")),Xg=pu(),Zg=process.platform==="win32",Dv=Zg?"node.exe":"node",Jg=Ci.join(Qg.homedir(),".agenthippo","gateway","install.json"),zg=Ci.join(Qg.homedir(),".agenthippo","tools","node");function eh(t){try{let e=Zg?ei.constants.F_OK:ei.constants.X_OK;return ei.accessSync(t,e),!0}catch{return!1}}function Lv(){try{if(!ei.existsSync(Jg))return;let t=ei.readFileSync(Jg,"utf8").replace(/^\uFEFF/,""),n=JSON.parse(t).nodePath?.trim();return n&&eh(n)?n:void 0}catch{return}}function Mv(){if(!ei.existsSync(zg))return[];let t=[],e=(n,r)=>{if(r>4)return;let s;try{s=ei.readdirSync(n,{withFileTypes:!0})}catch{return}for(let i of s){let o=Ci.join(n,i.name);i.isDirectory()?e(o,r+1):i.isFile()&&i.name===Dv&&n.endsWith(`${Ci.sep}bin`)&&t.push(o)}};return e(zg,0),t.sort().reverse()}function Gv(t){let e=new Set,n=[];for(let r of t){let s=Ci.resolve(r);e.has(s)||!eh(s)||(e.add(s),n.push(s))}return n}function th(){let t=[];process.env.NODE_BIN?.trim()&&t.push(process.env.NODE_BIN.trim());let e=Lv();return e&&t.push(e),t.push(...Mv()),process.env.npm_node_execpath?.trim()&&t.push(process.env.npm_node_execpath.trim()),Gv(t)}async function Uv(){let t=th();if(t.length>0)return t[0];let e=await(0,Xg.findBinaryCached)("node",(0,Xg.getCommonBinaryPaths)("node"));return e||"node"}function Hv(t,e){if(!e?.trim())return;let n=e.trim(),r=t.PATH?.trim();t.PATH=r?`${n}${Ci.delimiter}${r}`:n}});var Eo=S(ie=>{"use strict";Object.defineProperty(ie,"__esModule",{value:!0});ie.prependPathDir=ie.getNodeBinaryCandidates=ie.resolveNodeBinary=ie.clearBinaryCache=ie.getCommonBinaryPaths=ie.findBinaryCached=ie.findBinary=ie.probePort=ie.DIRS=ie.PID_FILES=ie.getAnalyticsScriptsDir=ie.getAgentidePath=ie.getAgentideHome=ie.checkPidFileWithCleanup=ie.removePidFile=ie.writePidFile=ie.readPidFile=ie.isPidFileProcessRunning=ie.isProcessRunningAsync=ie.isProcessRunning=void 0;var ti=Kg();Object.defineProperty(ie,"isProcessRunning",{enumerable:!0,get:function(){return ti.isProcessRunning}});Object.defineProperty(ie,"isProcessRunningAsync",{enumerable:!0,get:function(){return ti.isProcessRunningAsync}});Object.defineProperty(ie,"isPidFileProcessRunning",{enumerable:!0,get:function(){return ti.isPidFileProcessRunning}});Object.defineProperty(ie,"readPidFile",{enumerable:!0,get:function(){return ti.readPidFile}});Object.defineProperty(ie,"writePidFile",{enumerable:!0,get:function(){return ti.writePidFile}});Object.defineProperty(ie,"removePidFile",{enumerable:!0,get:function(){return ti.removePidFile}});Object.defineProperty(ie,"checkPidFileWithCleanup",{enumerable:!0,get:function(){return ti.checkPidFileWithCleanup}});var mo=Ys();Object.defineProperty(ie,"getAgentideHome",{enumerable:!0,get:function(){return mo.getAgentideHome}});Object.defineProperty(ie,"getAgentidePath",{enumerable:!0,get:function(){return mo.getAgentidePath}});Object.defineProperty(ie,"getAnalyticsScriptsDir",{enumerable:!0,get:function(){return mo.getAnalyticsScriptsDir}});Object.defineProperty(ie,"PID_FILES",{enumerable:!0,get:function(){return mo.PID_FILES}});Object.defineProperty(ie,"DIRS",{enumerable:!0,get:function(){return mo.DIRS}});var jv=qg();Object.defineProperty(ie,"probePort",{enumerable:!0,get:function(){return jv.probePort}});var Xa=pu();Object.defineProperty(ie,"findBinary",{enumerable:!0,get:function(){return Xa.findBinary}});Object.defineProperty(ie,"findBinaryCached",{enumerable:!0,get:function(){return Xa.findBinaryCached}});Object.defineProperty(ie,"getCommonBinaryPaths",{enumerable:!0,get:function(){return Xa.getCommonBinaryPaths}});Object.defineProperty(ie,"clearBinaryCache",{enumerable:!0,get:function(){return Xa.clearBinaryCache}});var hu=Ya();Object.defineProperty(ie,"resolveNodeBinary",{enumerable:!0,get:function(){return hu.resolveNodeBinary}});Object.defineProperty(ie,"getNodeBinaryCandidates",{enumerable:!0,get:function(){return hu.getNodeBinaryCandidates}});Object.defineProperty(ie,"prependPathDir",{enumerable:!0,get:function(){return hu.prependPathDir}})});var Er=S(Ge=>{"use strict";var xv=Ge&&Ge.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,s)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),Bv=Ge&&Ge.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),Eu=Ge&&Ge.__importStar||(function(){var t=function(e){return t=Object.getOwnPropertyNames||function(n){var r=[];for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(r[r.length]=s);return r},t(e)};return function(e){if(e&&e.__esModule)return e;var n={};if(e!=null)for(var r=t(e),s=0;s<r.length;s++)r[s]!=="default"&&xv(n,e,r[s]);return Bv(n,e),n}})();Object.defineProperty(Ge,"__esModule",{value:!0});Ge.OPENCLAW_GATEWAY_TOKEN_ENV=Ge.AGENTHIPPO_CHAT_SESSION_ID_ENV=Ge.AGENTIDE_CHAT_SESSION_ID_ENV=void 0;Ge.readOpenClawGatewayToken=sh;Ge.getBundledToolsHealth=Kv;Ge.getCliHealth=Qv;Ge.buildSessionEnvPatch=dh;Ge.buildCliEnvPatch=Zv;Ge.readProvenanceEnvFromProcess=eO;Ge.buildProvenanceEnv=tO;Ge.runCli=fh;var Lr=Eu(require("fs")),Fv=Eu(require("os")),mr=Eu(require("path")),Vv=require("child_process"),Ja=Ke(),nh=Fa(),mu=Eo();Ge.AGENTIDE_CHAT_SESSION_ID_ENV="AGENTIDE_CHAT_SESSION_ID";Ge.AGENTHIPPO_CHAT_SESSION_ID_ENV="AGENTHIPPO_CHAT_SESSION_ID";Ge.OPENCLAW_GATEWAY_TOKEN_ENV="OPENCLAW_GATEWAY_TOKEN";function sh(t){let e=t?.OPENCLAW_GATEWAY_TOKEN?.trim()||process.env.OPENCLAW_GATEWAY_TOKEN?.trim();if(e)return e;try{let n=mr.join(Fv.homedir(),".openclaw","openclaw.json"),r=Lr.readFileSync(n,"utf-8"),i=JSON.parse(r).gateway?.auth?.token;return typeof i=="string"?i.trim():void 0}catch{return}}var ih=["rg","sg","tree-sitter"];function oh(t=process.platform,e=process.arch){if(t==="darwin"&&e==="arm64")return"darwin-arm64";if(t==="darwin"&&e==="x64")return"darwin-x64";if(t==="linux"&&e==="x64")return"linux-x64";if(t==="linux"&&e==="arm64")return"linux-arm64";if(t==="win32"&&e==="x64")return"win32-x64";if(t==="win32"&&e==="arm64")return"win32-arm64"}function ah(t){return process.platform!=="win32"?t:`${t}.exe`}function ch(t){for(let e of ih){let n=mr.join(t,ah(e));try{let r=process.platform==="win32"?Lr.constants.F_OK:Lr.constants.X_OK;return Lr.accessSync(n,r),!0}catch{}}return!1}function lh(t,e){let n=oh();if(!n)return[];let r=[],s=process.env.AGENTHIPPO_TOOLS_DIR||process.env.AGENTIDE_TOOLS_DIR;return s?.trim()&&r.push(uh(s)),t?.trim()&&r.push(mr.join(t,"tools",n)),e?.trim()&&r.push(mr.join(e,"tools",n)),r}function Wv(t,e){let n=lh(t,e);for(let r of n)if(ch(r))return r}function Kv(t={}){let e=oh(),n=lh(t.extensionPath,t.binaryDirHint),r=n.find(o=>ch(o)),s=r??n[0],i=ih.map(o=>{let a=s??"",c=mr.join(a,ah(o)),l=!1;if(s)try{let f=process.platform==="win32"?Lr.constants.F_OK:Lr.constants.X_OK;Lr.accessSync(c,f),l=!0}catch{l=!1}return{name:o,path:c,available:l}});return{platformKey:e,toolsDir:r,tools:i}}function qv(t,e){let n=e.map(o=>o.trim()).filter(Boolean),r=t.split(mr.delimiter).map(o=>o.trim()).filter(Boolean),s=new Set,i=[];for(let o of[...n,...r]){let a=process.platform==="win32"?o.toLowerCase():o;s.has(a)||(s.add(a),i.push(o))}return i.join(mr.delimiter)}function Yv(t){return process.platform!=="win32"?"PATH":t&&Object.prototype.hasOwnProperty.call(t,"Path")?"Path":"PATH"}var Xv=3e4,ni;async function rh(t){try{let e=process.platform==="win32"?Lr.constants.F_OK:Lr.constants.X_OK;return await Lr.promises.access(t,e),!0}catch{return!1}}function uh(t){return t.trim().replace(/^"|"$/g,"")}async function Jv(t){let e=t.configuredPath?.trim();if(e){let r=uh(e);if(await rh(r))return{path:r,source:"setting"}}if(t.extensionPath){let r=[Ja.AGENTIDE_CLI_NAME,"agentide"],s=process.platform==="win32"?[".cmd",".exe",".bat",""]:[""],i=[];for(let o of r)for(let a of s)i.push(mr.join(t.extensionPath,"dist",`${o}${a}`));for(let o of i)if(await rh(o))return{path:o,source:"bundled"}}t.forceRefresh&&(0,mu.clearBinaryCache)(Ja.AGENTIDE_CLI_NAME);let n=await(0,mu.findBinaryCached)(Ja.AGENTIDE_CLI_NAME,(0,mu.getCommonBinaryPaths)(Ja.AGENTIDE_CLI_NAME));return n?{path:n,source:"path"}:{source:"not_found"}}async function zv(t){try{let e=await fh(t,["--version"],{timeoutMs:5e3});return e.code!==0?void 0:e.stdout.trim().split(/\r?\n/)[0]||void 0}catch{return}}async function Qv(t={}){let e=Date.now();if(!t.forceRefresh&&ni&&e-ni.lastCheckedAt<Xv)return ni;let n=await Jv(t);if(!n.path)return ni={installed:!1,source:"not_found",lastCheckedAt:e,error:t.configuredPath?`Configured path not found: ${t.configuredPath}`:void 0},ni;let r=await zv(n.path);return ni={installed:!0,path:n.path,version:r,source:n.source,lastCheckedAt:e},ni}function dh(t){let e=t.chatSessionId?.trim(),n=t.gatewaySessionKey?.trim();if(!e&&!n)return{};let r={};e&&(r[Ge.AGENTIDE_CHAT_SESSION_ID_ENV]=e,r[Ge.AGENTHIPPO_CHAT_SESSION_ID_ENV]=e);let s=(0,nh.resolveGatewayOutboundFilePath)({workspaceRoot:t.workspaceRoot,gatewaySessionKey:n,chatSessionId:n?void 0:e});return s&&(r[nh.AGENTHIPPO_GATEWAY_OUTBOUND_FILE_ENV]=s),r}function Zv(t){let e={AGENTHIPPO_WORKSPACE_ROOT:t.workspaceRoot,AGENTHIPPO_ACTIVE_AGENT:t.agentId,...dh({workspaceRoot:t.workspaceRoot,chatSessionId:t.chatSessionId})};if(!t.omitGatewayToken&&!process.env.AGENTHIPPO_EGRESS_URL?.trim()){let i=sh(t.baseEnv);i&&(e[Ge.OPENCLAW_GATEWAY_TOKEN_ENV]=i)}e.CLAUDECODE="";let n=[];t.userInstalledToolsDir?.trim()&&(n.push(t.userInstalledToolsDir.trim()),e.AGENTHIPPO_TOOLS_DIR=t.userInstalledToolsDir.trim(),e.AGENTIDE_TOOLS_DIR=t.userInstalledToolsDir.trim());try{let i=require("@vscode/ripgrep");i?.rgPath&&typeof i.rgPath=="string"&&n.push(mr.dirname(i.rgPath))}catch{}if(t.cliPath?.trim()){let i=t.cliPath.trim();e.AGENTHIPPO_CLI_PATH=i,n.push(mr.dirname(i))}let r=t.cliPath?.trim()?mr.dirname(t.cliPath.trim()):void 0,s=Wv(t.extensionPath,r);if(s&&!t.userInstalledToolsDir?.trim()?(e.AGENTHIPPO_TOOLS_DIR=s,e.AGENTIDE_TOOLS_DIR=s,n.push(s)):s&&n.push(s),n.length>0){let i=Yv(t.baseEnv),o=t.baseEnv?.[i]??t.baseEnv?.PATH??t.baseEnv?.Path??"";e[i]=qv(o,n)}return e}function eO(){let t=r=>process.env[r]?.trim()||void 0,e=t("AGENTIDE_ANALYTICS_TIER"),n=e!==void 0?Number(e):void 0;return{policyVersion:t("AGENTIDE_ANALYTICS_POLICY_VERSION"),packDigest:t("AGENTIDE_ANALYTICS_PACK_DIGEST"),engineVersion:t("AGENTIDE_ANALYTICS_ENGINE_VERSION"),tier:n!==void 0&&Number.isFinite(n)?n:void 0,instanceId:t("AGENTIDE_ANALYTICS_INSTANCE_ID")}}function tO(t){let e={};return t.policyVersion?.trim()&&(e.AGENTIDE_ANALYTICS_POLICY_VERSION=t.policyVersion.trim()),t.packDigest?.trim()&&(e.AGENTIDE_ANALYTICS_PACK_DIGEST=t.packDigest.trim()),t.engineVersion?.trim()&&(e.AGENTIDE_ANALYTICS_ENGINE_VERSION=t.engineVersion.trim()),t.tier!==void 0&&(e.AGENTIDE_ANALYTICS_TIER=String(t.tier)),t.instanceId?.trim()&&(e.AGENTIDE_ANALYTICS_INSTANCE_ID=t.instanceId.trim()),e}async function fh(t,e,n){return await new Promise((r,s)=>{let i=(0,Vv.spawn)(t,e,{cwd:n?.cwd,env:{...process.env,...n?.env??{}},shell:!1}),o="",a="",c=!1,l=n?.timeoutMs??6e4,f=setTimeout(()=>{c||(i.kill(),s(new Error(`CLI command timed out after ${l}ms`)))},l);i.stdout.on("data",u=>{o+=u.toString()}),i.stderr.on("data",u=>{a+=u.toString()}),i.on("error",u=>{c||(c=!0,clearTimeout(f),s(u))}),i.on("close",u=>{c||(c=!0,clearTimeout(f),r({code:u??1,stdout:o,stderr:a}))})})}});var za=S(Fn=>{"use strict";Object.defineProperty(Fn,"__esModule",{value:!0});Fn.RevocationUnsupportedError=Fn.SANDBOX_PROVIDER_KEY_ENV=Fn.SANDBOX_TIER_ENV=void 0;Fn.sandboxHoldsProviderKey=nO;Fn.isContainerSandbox=rO;Fn.SANDBOX_TIER_ENV="AGENTHIPPO_SANDBOX_TIER";Fn.SANDBOX_PROVIDER_KEY_ENV="AGENTHIPPO_SANDBOX_PROVIDER_KEY";function nO(t=process.env){return t[Fn.SANDBOX_PROVIDER_KEY_ENV]==="1"}function rO(t=process.env){return Number(t[Fn.SANDBOX_TIER_ENV])>=2}var _u=class extends Error{constructor(e,n){super(`${e} driver cannot revoke '${n}' \u2014 no enforcement boundary at this tier (use 'all', which kills the sandbox)`),this.name="RevocationUnsupportedError"}};Fn.RevocationUnsupportedError=_u});var Nh=S(_r=>{"use strict";var sO=_r&&_r.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,s)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),iO=_r&&_r.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),oO=_r&&_r.__importStar||(function(){var t=function(e){return t=Object.getOwnPropertyNames||function(n){var r=[];for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(r[r.length]=s);return r},t(e)};return function(e){if(e&&e.__esModule)return e;var n={};if(e!=null)for(var r=t(e),s=0;s<r.length;s++)r[s]!=="default"&&sO(n,e,r[s]);return iO(n,e),n}})();Object.defineProperty(_r,"__esModule",{value:!0});_r.CodexEngine=void 0;_r.registerNewFilesWithTracker=Ph;var Vn=require("fs"),fn=oO(require("path")),ph=lo(),aO=Jl(),Qa=zs(),ze=en(),gh=ru(),yu=Js(),ri=uu(),cO=Is(),lO=Er(),hh=za(),uO="agentide-litellm",dO="agentide-custom",wu="AGENTIDE_ANALYTICS_SESSION_ID",Au="AGENTIDE_ANALYTICS_USER_ID",mh="AGENTIDE_ANALYTICS_PROJECT_ID",Eh="AGENTIDE_ANALYTICS_AGENT_ID",_h="AGENTIDE_ANALYTICS_AGENT_VERSION",yh="AGENTIDE_ANALYTICS_SOURCE",wh="AGENTIDE_ANALYTICS_ENGINE",Ah="AGENTIDE_ANALYTICS_REQUEST_ID",Sh="AGENTIDE_ANALYTICS_POLICY_VERSION",Th="AGENTIDE_ANALYTICS_PACK_DIGEST",bh="AGENTIDE_ANALYTICS_ENGINE_VERSION",vh="AGENTIDE_ANALYTICS_TIER",Oh="AGENTIDE_ANALYTICS_INSTANCE_ID",fO=21,pO="AGENTIDE_CONTEXT_EXPORT_PATH",gO="AGENTIDE_TERMINAL_LOG_PATH";async function Ph(t,e,n){if(e.appliesEdits!==!1)for(let r of t)try{if((0,ze.isBinaryFile)(r)||!await(0,ze.pathExists)(r))continue;let s=await Vn.promises.readFile(r,"utf-8");try{await Vn.promises.unlink(r),await e.applyEdit(n,r,s,!0)}finally{await(0,ze.pathExists)(r)||await Vn.promises.writeFile(r,s,"utf-8")}}catch{}}function Ih(t){return t.type==="item.started"||t.type==="item.updated"||t.type==="item.completed"}var Su=class{config;getSkillsSignature;getBundledBasePromptsDir;id="codex";displayName="Codex";lastWrittenConfigSignature;lastCodexSkillsSignatureByWorkspaceRoot=new Map;constructor(e,n,r){this.config=e,this.getSkillsSignature=n,this.getBundledBasePromptsDir=r}async stream(e,n,r,s,i){let o=s.logger,a=s.editTracker,{Codex:c}=await import("@openai/codex-sdk");if(!n.modelId)throw new Error("Codex modelId not provided for streaming request");let l=n.modelId,f=(0,ze.resolveApiRouting)(n,this.config,"openai"),u=f.apiKey,d=f.openaiBaseUrl,p=f.useLiteLLM,g=n.sessionId,m=n.analyticsUserId,h=(0,Qa.resolveAnalyticsProjectId)(n.analyticsProjectId,n.workspaceRoot),_=d&&d!=="https://api.openai.com/v1",y=p?"LiteLLM proxy":_?"custom provider":"direct OpenAI";o.info(`[AgentIDE] Codex routing: ${y}, baseUrl=${d||"default"}, workspaceRoot=${n.workspaceRoot}`);let b=l.toLowerCase().includes("claude");o.info(`[AgentIDE] Codex wire_api=responses (model=${l})`),b&&(p||_)&&o.info("[AgentIDE] Codex note: selected model appears to be Claude via proxy; reasoning summaries depend on provider support over the Responses API.");let O={...process.env,...s.cliEnvPatch??{},OPENAI_LOG:"debug"};delete O[lO.OPENCLAW_GATEWAY_TOKEN_ENV],delete O.AGENTHIPPO_DATA_PLANE_TOKEN;let A=g?.trim(),v=n.contextSessionId?.trim()||A;v&&(O[pO]=fn.join(n.workspaceRoot,ri.AGENT_CONSTANTS.AGENTIDE_DIR_NAME,"sessions",v,"context.md"),O[gO]=fn.join(n.workspaceRoot,ri.AGENT_CONSTANTS.AGENTIDE_DIR_NAME,"sessions",v,"terminal.md"));let C=n.agentPackId??"default",B=(0,ri.resolveRuntimePaths)(n.workspaceRoot,this.config.storagePath,C,n.agentPackVersion),R=(0,ri.userScopedEngineHomeFromKey)(B.codexHome,(0,cO.resolveEngineHomeUserKey)(n.engineHomeUserKey));O.CODEX_HOME=R,await Vn.promises.mkdir(R,{recursive:!0}),O.AGENT_ID=C,n.agentPackVersion&&(O.AGENTIDE_AGENT_VERSION=n.agentPackVersion),C!=="default"?o.info(`[AgentIDE] Codex using agent: ${C}, CODEX_HOME=${R} (agent-isolated)`):o.info(`[AgentIDE] Codex using default agent, CODEX_HOME=${R}`);let F=_?d:void 0;await this.ensureCodexConfig(p,F,l,n.workspaceRoot,n.additionalDirectories??[],o,R,C,s.permissionHandler instanceof aO.AutoApprovePermissionHandler),p&&R&&(m?.trim()&&(O[Au]=m.trim()),g?.trim()&&(O[wu]=g.trim()),h?.trim()&&(O[mh]=h.trim()),O[Eh]=C,O[_h]=n.agentPackVersion??"workspace",O[yh]="agenthippo",O[wh]="codex",n.requestId&&(O[Ah]=n.requestId),n.policyVersion?.trim()&&(O[Sh]=n.policyVersion.trim()),n.packDigest?.trim()&&(O[Th]=n.packDigest.trim()),n.engineVersion?.trim()&&(O[bh]=n.engineVersion.trim()),n.tier!==void 0&&(O[vh]=String(n.tier)),n.instanceId?.trim()&&(O[Oh]=n.instanceId.trim())),_&&u&&(O.CODEX_API_KEY=u),_&&(O.OPENAI_BASE_URL=d,o.info(`[AgentIDE] Using custom OpenAI base URL: ${d}`),(0,ze.applyLocalTlsBypass)(O,d)&&o.info("[AgentIDE] Disabling TLS verification for local HTTPS (Codex)"));let re=(0,yu.buildConversationKey)("codex",n);o.info(`[AgentIDE] Codex conversationKey=${re.key} (chatSessionId=${re.chatSessionId}, signature=${re.signatureHash}${re.isEphemeral?", ephemeral":""})`),await(0,yu.withConversationLock)(re.key,async()=>{await r.progress("Thinking...");let W=n.permissions??gh.DEFAULT_PERMISSIONS;o.info(`[AgentIDE] Codex permissions: fileAccess=${W.fileAccess}`);let de=[n.workspaceRoot,...n.additionalDirectories??[]],he=(0,gh.toCodexOptions)(W,de);(0,hh.isContainerSandbox)()&&(he.sandboxMode="danger-full-access"),o.info(`[AgentIDE] Codex mapped: sandboxMode=${he.sandboxMode}, approvalPolicy=${he.approvalPolicy}`);let z=n.workspaceRoot,Ne={model:l,sandboxMode:he.sandboxMode,approvalPolicy:he.approvalPolicy,additionalDirectories:he.additionalDirectories,workingDirectory:z,skipGitRepoCheck:!0,modelReasoningEffort:"medium"};o.info(`[AgentIDE] Codex modelReasoningEffort=${Ne.modelReasoningEffort??"default"}`);let We=_?void 0:u,Me=new c({apiKey:We,env:O,...this.config.codexExecutablePath?{codexPathOverride:this.config.codexExecutablePath}:{}}),on=(0,Qa.getPersistedSessionId)("codex",re.key),ye;if(on)try{ye=Me.resumeThread(on,Ne),o.info(`[AgentIDE] Codex resuming thread: ${on} (model: ${l})`)}catch(K){o.warn(`[AgentIDE] Failed to resume Codex thread (${on}): ${K instanceof Error?K.message:String(K)}. Starting new thread.`),ye=Me.startThread(Ne)}else ye=Me.startThread(Ne),o.info(`[AgentIDE] Codex starting new thread (model: ${l})`);if(i?.aborted){o.info("[AgentIDE] Codex stream cancelled before starting turn");return}let cr;try{({events:cr}=await ye.runStreamed(e,{signal:i}))}catch(K){if(i?.aborted){o.info("[AgentIDE] Codex stream aborted while starting turn");return}throw K}let ut=new Map,qt=new Map,En=new Map,Dn=0,Et=0,It=0,Pt=!1,vs=K=>K.replace(/\r/g,"").replace(/\n/g,"\\n").slice(0,160);try{for await(let K of cr){if(i?.aborted){o.info("[AgentIDE] Codex stream aborted; stopping event loop");return}let Ut=Ih(K)?K.item.type:void 0;if(o.debug(`[AgentIDE] Codex event: ${K.type}${Ut?` (item: ${Ut})`:""}`),K.type==="thread.started"){let Z=K.thread_id;o.info(`[AgentIDE] Codex thread started: ${Z}`),await(0,Qa.persistSessionIfNeeded)("codex",re,Z,n);continue}if(K.type==="turn.failed")throw await r.error(K.error?.message||"Codex turn failed"),new Error(K.error?.message||"Codex turn failed");if(K.type==="error")throw await r.error(K.message||"Codex stream error"),new Error(K.message||"Codex stream error");if(K.type==="turn.completed"){o.info(`[AgentIDE] Codex usage: input=${K.usage.input_tokens}, cached=${K.usage.cached_input_tokens}, output=${K.usage.output_tokens}`);continue}if(Ih(K)){let{item:I}=K;if(I.type==="reasoning"){It++;let Z=I.text??"",j=(0,ze.computeTextDelta)(I.id,I.text??"",ut);j?(Dn++,Et+=j.length,Dn<=3&&o.debug(`[AgentIDE] Codex reasoning delta #${Dn} (${j.length} chars): ${vs(j)}`),await r.thinking(j)):!Pt&&Z.length===0&&(Pt=!0,o.debug("[AgentIDE] Codex reasoning item observed but text is empty so far."))}else if(I.type==="agent_message"){let Z=(0,ze.computeTextDelta)(I.id,I.text??"",ut);Z&&await r.text(Z)}else if(I.type==="command_execution"){if(K.type==="item.started"&&(await r.thinking(`**Running command**
47
+ `;await Eo.promises.writeFile(t,s,"utf8")}catch{}}async function Kg(t){try{await Eo.promises.unlink(t)}catch{}}async function yv(t){let e=await Wg(t);return e?Wa(e.pid)?e:(await Kg(t),null):null}});var Yg=S(cs=>{"use strict";var wv=cs&&cs.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,s)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),Av=cs&&cs.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),Sv=cs&&cs.__importStar||(function(){var t=function(e){return t=Object.getOwnPropertyNames||function(n){var r=[];for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(r[r.length]=s);return r},t(e)};return function(e){if(e&&e.__esModule)return e;var n={};if(e!=null)for(var r=t(e),s=0;s<r.length;s++)r[s]!=="default"&&wv(n,e,r[s]);return Av(n,e),n}})();Object.defineProperty(cs,"__esModule",{value:!0});cs.probePort=bv;var Tv=Sv(require("net"));function bv(t,e="127.0.0.1",n=2e3){return new Promise(r=>{let s=new Tv.Socket;s.setTimeout(n),s.once("connect",()=>{s.destroy(),r(!0)}),s.once("timeout",()=>{s.destroy(),r(!1)}),s.once("error",()=>{s.destroy(),r(!1)}),s.connect(t,e)})}});var gu=S(Bn=>{"use strict";var vv=Bn&&Bn.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,s)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),Ov=Bn&&Bn.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),pu=Bn&&Bn.__importStar||(function(){var t=function(e){return t=Object.getOwnPropertyNames||function(n){var r=[];for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(r[r.length]=s);return r},t(e)};return function(e){if(e&&e.__esModule)return e;var n={};if(e!=null)for(var r=t(e),s=0;s<r.length;s++)r[s]!=="default"&&vv(n,e,r[s]);return Ov(n,e),n}})();Object.defineProperty(Bn,"__esModule",{value:!0});Bn.findBinary=Xg;Bn.findBinaryCached=$v;Bn.getCommonBinaryPaths=Dv;Bn.clearBinaryCache=Lv;var Iv=require("child_process"),Pv=require("util"),Nv=require("fs"),Ka=pu(require("fs")),vn=pu(require("path")),Rv=pu(require("os")),Cv=(0,Pv.promisify)(Iv.exec),qa=process.platform==="win32",kv=6e4,Ya=new Map;async function Xg(t,e=5e3){try{let n=qa?`where ${t}`:`which ${t}`,{stdout:r}=await Cv(n,{timeout:e});return r.trim().split(`
48
+ `)[0]||void 0}catch{return}}async function $v(t,e=[],n=kv){let r=Date.now(),s=Ya.get(t);if(s&&r-s.timestamp<n)return s.path;let i=await Xg(t);if(!i)for(let o of e)try{await Nv.promises.access(o,qa?Ka.constants.F_OK:Ka.constants.X_OK),i=o;break}catch{}return Ya.set(t,{path:i,timestamp:r}),i}function Dv(t){let e=Rv.homedir(),n=qa?`${t}.cmd`:t;if(qa){let o=process.env.LOCALAPPDATA||vn.join(e,"AppData","Local");return[vn.join(o,"AgentHippo","bin",n),vn.join(e,"AppData","Local","Programs",t,`${t}.exe`),vn.join(e,"AppData","Roaming","npm",n),vn.join(e,"AppData","Local","pnpm",n),vn.join(e,".npm-global",n)]}let r=[vn.join(e,".local","bin",t),vn.join(e,"Library","pnpm",t),vn.join(e,".local","share","pnpm",t),vn.join(e,".npm-global","bin",t),"/opt/homebrew/bin/"+t,"/usr/local/bin/"+t,"/usr/bin/"+t],s=process.env.NVM_DIR||vn.join(e,".nvm"),i=vn.join(s,"versions","node");if(Ka.existsSync(i))try{let o=Ka.readdirSync(i,{withFileTypes:!0}).filter(a=>a.isDirectory()).map(a=>a.name).sort().reverse();for(let a of o)r.push(vn.join(i,a,"bin",t))}catch{}return r}function Lv(t){t?Ya.delete(t):Ya.clear()}});var Xa=S(hr=>{"use strict";var Mv=hr&&hr.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,s)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),Gv=hr&&hr.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),hu=hr&&hr.__importStar||(function(){var t=function(e){return t=Object.getOwnPropertyNames||function(n){var r=[];for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(r[r.length]=s);return r},t(e)};return function(e){if(e&&e.__esModule)return e;var n={};if(e!=null)for(var r=t(e),s=0;s<r.length;s++)r[s]!=="default"&&Mv(n,e,r[s]);return Gv(n,e),n}})();Object.defineProperty(hr,"__esModule",{value:!0});hr.getNodeBinaryCandidates=nh;hr.resolveNodeBinary=Bv;hr.prependPathDir=Fv;var ei=hu(require("fs")),Zg=hu(require("os")),Ci=hu(require("path")),Jg=gu(),eh=process.platform==="win32",Uv=eh?"node.exe":"node",zg=Ci.join(Zg.homedir(),".agenthippo","gateway","install.json"),Qg=Ci.join(Zg.homedir(),".agenthippo","tools","node");function th(t){try{let e=eh?ei.constants.F_OK:ei.constants.X_OK;return ei.accessSync(t,e),!0}catch{return!1}}function Hv(){try{if(!ei.existsSync(zg))return;let t=ei.readFileSync(zg,"utf8").replace(/^\uFEFF/,""),n=JSON.parse(t).nodePath?.trim();return n&&th(n)?n:void 0}catch{return}}function jv(){if(!ei.existsSync(Qg))return[];let t=[],e=(n,r)=>{if(r>4)return;let s;try{s=ei.readdirSync(n,{withFileTypes:!0})}catch{return}for(let i of s){let o=Ci.join(n,i.name);i.isDirectory()?e(o,r+1):i.isFile()&&i.name===Uv&&n.endsWith(`${Ci.sep}bin`)&&t.push(o)}};return e(Qg,0),t.sort().reverse()}function xv(t){let e=new Set,n=[];for(let r of t){let s=Ci.resolve(r);e.has(s)||!th(s)||(e.add(s),n.push(s))}return n}function nh(){let t=[];process.env.NODE_BIN?.trim()&&t.push(process.env.NODE_BIN.trim());let e=Hv();return e&&t.push(e),t.push(...jv()),process.env.npm_node_execpath?.trim()&&t.push(process.env.npm_node_execpath.trim()),xv(t)}async function Bv(){let t=nh();if(t.length>0)return t[0];let e=await(0,Jg.findBinaryCached)("node",(0,Jg.getCommonBinaryPaths)("node"));return e||"node"}function Fv(t,e){if(!e?.trim())return;let n=e.trim(),r=t.PATH?.trim();t.PATH=r?`${n}${Ci.delimiter}${r}`:n}});var yo=S(ie=>{"use strict";Object.defineProperty(ie,"__esModule",{value:!0});ie.prependPathDir=ie.getNodeBinaryCandidates=ie.resolveNodeBinary=ie.clearBinaryCache=ie.getCommonBinaryPaths=ie.findBinaryCached=ie.findBinary=ie.probePort=ie.DIRS=ie.PID_FILES=ie.getAnalyticsScriptsDir=ie.getAgentidePath=ie.getAgentideHome=ie.checkPidFileWithCleanup=ie.removePidFile=ie.writePidFile=ie.readPidFile=ie.isPidFileProcessRunning=ie.isProcessRunningAsync=ie.isProcessRunning=void 0;var ti=qg();Object.defineProperty(ie,"isProcessRunning",{enumerable:!0,get:function(){return ti.isProcessRunning}});Object.defineProperty(ie,"isProcessRunningAsync",{enumerable:!0,get:function(){return ti.isProcessRunningAsync}});Object.defineProperty(ie,"isPidFileProcessRunning",{enumerable:!0,get:function(){return ti.isPidFileProcessRunning}});Object.defineProperty(ie,"readPidFile",{enumerable:!0,get:function(){return ti.readPidFile}});Object.defineProperty(ie,"writePidFile",{enumerable:!0,get:function(){return ti.writePidFile}});Object.defineProperty(ie,"removePidFile",{enumerable:!0,get:function(){return ti.removePidFile}});Object.defineProperty(ie,"checkPidFileWithCleanup",{enumerable:!0,get:function(){return ti.checkPidFileWithCleanup}});var _o=Ys();Object.defineProperty(ie,"getAgentideHome",{enumerable:!0,get:function(){return _o.getAgentideHome}});Object.defineProperty(ie,"getAgentidePath",{enumerable:!0,get:function(){return _o.getAgentidePath}});Object.defineProperty(ie,"getAnalyticsScriptsDir",{enumerable:!0,get:function(){return _o.getAnalyticsScriptsDir}});Object.defineProperty(ie,"PID_FILES",{enumerable:!0,get:function(){return _o.PID_FILES}});Object.defineProperty(ie,"DIRS",{enumerable:!0,get:function(){return _o.DIRS}});var Vv=Yg();Object.defineProperty(ie,"probePort",{enumerable:!0,get:function(){return Vv.probePort}});var Ja=gu();Object.defineProperty(ie,"findBinary",{enumerable:!0,get:function(){return Ja.findBinary}});Object.defineProperty(ie,"findBinaryCached",{enumerable:!0,get:function(){return Ja.findBinaryCached}});Object.defineProperty(ie,"getCommonBinaryPaths",{enumerable:!0,get:function(){return Ja.getCommonBinaryPaths}});Object.defineProperty(ie,"clearBinaryCache",{enumerable:!0,get:function(){return Ja.clearBinaryCache}});var mu=Xa();Object.defineProperty(ie,"resolveNodeBinary",{enumerable:!0,get:function(){return mu.resolveNodeBinary}});Object.defineProperty(ie,"getNodeBinaryCandidates",{enumerable:!0,get:function(){return mu.getNodeBinaryCandidates}});Object.defineProperty(ie,"prependPathDir",{enumerable:!0,get:function(){return mu.prependPathDir}})});var Er=S(Ge=>{"use strict";var Wv=Ge&&Ge.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,s)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),Kv=Ge&&Ge.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),_u=Ge&&Ge.__importStar||(function(){var t=function(e){return t=Object.getOwnPropertyNames||function(n){var r=[];for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(r[r.length]=s);return r},t(e)};return function(e){if(e&&e.__esModule)return e;var n={};if(e!=null)for(var r=t(e),s=0;s<r.length;s++)r[s]!=="default"&&Wv(n,e,r[s]);return Kv(n,e),n}})();Object.defineProperty(Ge,"__esModule",{value:!0});Ge.OPENCLAW_GATEWAY_TOKEN_ENV=Ge.AGENTHIPPO_CHAT_SESSION_ID_ENV=Ge.AGENTIDE_CHAT_SESSION_ID_ENV=void 0;Ge.readOpenClawGatewayToken=ih;Ge.getBundledToolsHealth=Jv;Ge.getCliHealth=nO;Ge.buildSessionEnvPatch=fh;Ge.buildCliEnvPatch=rO;Ge.readProvenanceEnvFromProcess=sO;Ge.buildProvenanceEnv=iO;Ge.runCli=ph;var Lr=_u(require("fs")),qv=_u(require("os")),mr=_u(require("path")),Yv=require("child_process"),za=Ke(),rh=Va(),Eu=yo();Ge.AGENTIDE_CHAT_SESSION_ID_ENV="AGENTIDE_CHAT_SESSION_ID";Ge.AGENTHIPPO_CHAT_SESSION_ID_ENV="AGENTHIPPO_CHAT_SESSION_ID";Ge.OPENCLAW_GATEWAY_TOKEN_ENV="OPENCLAW_GATEWAY_TOKEN";function ih(t){let e=t?.OPENCLAW_GATEWAY_TOKEN?.trim()||process.env.OPENCLAW_GATEWAY_TOKEN?.trim();if(e)return e;try{let n=mr.join(qv.homedir(),".openclaw","openclaw.json"),r=Lr.readFileSync(n,"utf-8"),i=JSON.parse(r).gateway?.auth?.token;return typeof i=="string"?i.trim():void 0}catch{return}}var oh=["rg","sg","tree-sitter"];function ah(t=process.platform,e=process.arch){if(t==="darwin"&&e==="arm64")return"darwin-arm64";if(t==="darwin"&&e==="x64")return"darwin-x64";if(t==="linux"&&e==="x64")return"linux-x64";if(t==="linux"&&e==="arm64")return"linux-arm64";if(t==="win32"&&e==="x64")return"win32-x64";if(t==="win32"&&e==="arm64")return"win32-arm64"}function ch(t){return process.platform!=="win32"?t:`${t}.exe`}function lh(t){for(let e of oh){let n=mr.join(t,ch(e));try{let r=process.platform==="win32"?Lr.constants.F_OK:Lr.constants.X_OK;return Lr.accessSync(n,r),!0}catch{}}return!1}function uh(t,e){let n=ah();if(!n)return[];let r=[],s=process.env.AGENTHIPPO_TOOLS_DIR||process.env.AGENTIDE_TOOLS_DIR;return s?.trim()&&r.push(dh(s)),t?.trim()&&r.push(mr.join(t,"tools",n)),e?.trim()&&r.push(mr.join(e,"tools",n)),r}function Xv(t,e){let n=uh(t,e);for(let r of n)if(lh(r))return r}function Jv(t={}){let e=ah(),n=uh(t.extensionPath,t.binaryDirHint),r=n.find(o=>lh(o)),s=r??n[0],i=oh.map(o=>{let a=s??"",c=mr.join(a,ch(o)),l=!1;if(s)try{let f=process.platform==="win32"?Lr.constants.F_OK:Lr.constants.X_OK;Lr.accessSync(c,f),l=!0}catch{l=!1}return{name:o,path:c,available:l}});return{platformKey:e,toolsDir:r,tools:i}}function zv(t,e){let n=e.map(o=>o.trim()).filter(Boolean),r=t.split(mr.delimiter).map(o=>o.trim()).filter(Boolean),s=new Set,i=[];for(let o of[...n,...r]){let a=process.platform==="win32"?o.toLowerCase():o;s.has(a)||(s.add(a),i.push(o))}return i.join(mr.delimiter)}function Qv(t){return process.platform!=="win32"?"PATH":t&&Object.prototype.hasOwnProperty.call(t,"Path")?"Path":"PATH"}var Zv=3e4,ni;async function sh(t){try{let e=process.platform==="win32"?Lr.constants.F_OK:Lr.constants.X_OK;return await Lr.promises.access(t,e),!0}catch{return!1}}function dh(t){return t.trim().replace(/^"|"$/g,"")}async function eO(t){let e=t.configuredPath?.trim();if(e){let r=dh(e);if(await sh(r))return{path:r,source:"setting"}}if(t.extensionPath){let r=[za.AGENTIDE_CLI_NAME,"agentide"],s=process.platform==="win32"?[".cmd",".exe",".bat",""]:[""],i=[];for(let o of r)for(let a of s)i.push(mr.join(t.extensionPath,"dist",`${o}${a}`));for(let o of i)if(await sh(o))return{path:o,source:"bundled"}}t.forceRefresh&&(0,Eu.clearBinaryCache)(za.AGENTIDE_CLI_NAME);let n=await(0,Eu.findBinaryCached)(za.AGENTIDE_CLI_NAME,(0,Eu.getCommonBinaryPaths)(za.AGENTIDE_CLI_NAME));return n?{path:n,source:"path"}:{source:"not_found"}}async function tO(t){try{let e=await ph(t,["--version"],{timeoutMs:5e3});return e.code!==0?void 0:e.stdout.trim().split(/\r?\n/)[0]||void 0}catch{return}}async function nO(t={}){let e=Date.now();if(!t.forceRefresh&&ni&&e-ni.lastCheckedAt<Zv)return ni;let n=await eO(t);if(!n.path)return ni={installed:!1,source:"not_found",lastCheckedAt:e,error:t.configuredPath?`Configured path not found: ${t.configuredPath}`:void 0},ni;let r=await tO(n.path);return ni={installed:!0,path:n.path,version:r,source:n.source,lastCheckedAt:e},ni}function fh(t){let e=t.chatSessionId?.trim(),n=t.gatewaySessionKey?.trim();if(!e&&!n)return{};let r={};e&&(r[Ge.AGENTIDE_CHAT_SESSION_ID_ENV]=e,r[Ge.AGENTHIPPO_CHAT_SESSION_ID_ENV]=e);let s=(0,rh.resolveGatewayOutboundFilePath)({workspaceRoot:t.workspaceRoot,gatewaySessionKey:n,chatSessionId:n?void 0:e});return s&&(r[rh.AGENTHIPPO_GATEWAY_OUTBOUND_FILE_ENV]=s),r}function rO(t){let e={AGENTHIPPO_WORKSPACE_ROOT:t.workspaceRoot,AGENTHIPPO_ACTIVE_AGENT:t.agentId,...fh({workspaceRoot:t.workspaceRoot,chatSessionId:t.chatSessionId})};if(!t.omitGatewayToken&&!process.env.AGENTHIPPO_EGRESS_URL?.trim()){let i=ih(t.baseEnv);i&&(e[Ge.OPENCLAW_GATEWAY_TOKEN_ENV]=i)}e.CLAUDECODE="";let n=[];t.userInstalledToolsDir?.trim()&&(n.push(t.userInstalledToolsDir.trim()),e.AGENTHIPPO_TOOLS_DIR=t.userInstalledToolsDir.trim(),e.AGENTIDE_TOOLS_DIR=t.userInstalledToolsDir.trim());try{let i=require("@vscode/ripgrep");i?.rgPath&&typeof i.rgPath=="string"&&n.push(mr.dirname(i.rgPath))}catch{}if(t.cliPath?.trim()){let i=t.cliPath.trim();e.AGENTHIPPO_CLI_PATH=i,n.push(mr.dirname(i))}let r=t.cliPath?.trim()?mr.dirname(t.cliPath.trim()):void 0,s=Xv(t.extensionPath,r);if(s&&!t.userInstalledToolsDir?.trim()?(e.AGENTHIPPO_TOOLS_DIR=s,e.AGENTIDE_TOOLS_DIR=s,n.push(s)):s&&n.push(s),n.length>0){let i=Qv(t.baseEnv),o=t.baseEnv?.[i]??t.baseEnv?.PATH??t.baseEnv?.Path??"";e[i]=zv(o,n)}return e}function sO(){let t=r=>process.env[r]?.trim()||void 0,e=t("AGENTIDE_ANALYTICS_TIER"),n=e!==void 0?Number(e):void 0;return{policyVersion:t("AGENTIDE_ANALYTICS_POLICY_VERSION"),packDigest:t("AGENTIDE_ANALYTICS_PACK_DIGEST"),engineVersion:t("AGENTIDE_ANALYTICS_ENGINE_VERSION"),tier:n!==void 0&&Number.isFinite(n)?n:void 0,instanceId:t("AGENTIDE_ANALYTICS_INSTANCE_ID")}}function iO(t){let e={};return t.policyVersion?.trim()&&(e.AGENTIDE_ANALYTICS_POLICY_VERSION=t.policyVersion.trim()),t.packDigest?.trim()&&(e.AGENTIDE_ANALYTICS_PACK_DIGEST=t.packDigest.trim()),t.engineVersion?.trim()&&(e.AGENTIDE_ANALYTICS_ENGINE_VERSION=t.engineVersion.trim()),t.tier!==void 0&&(e.AGENTIDE_ANALYTICS_TIER=String(t.tier)),t.instanceId?.trim()&&(e.AGENTIDE_ANALYTICS_INSTANCE_ID=t.instanceId.trim()),e}async function ph(t,e,n){return await new Promise((r,s)=>{let i=(0,Yv.spawn)(t,e,{cwd:n?.cwd,env:{...process.env,...n?.env??{}},shell:!1}),o="",a="",c=!1,l=n?.timeoutMs??6e4,f=setTimeout(()=>{c||(i.kill(),s(new Error(`CLI command timed out after ${l}ms`)))},l);i.stdout.on("data",u=>{o+=u.toString()}),i.stderr.on("data",u=>{a+=u.toString()}),i.on("error",u=>{c||(c=!0,clearTimeout(f),s(u))}),i.on("close",u=>{c||(c=!0,clearTimeout(f),r({code:u??1,stdout:o,stderr:a}))})})}});var Qa=S(Fn=>{"use strict";Object.defineProperty(Fn,"__esModule",{value:!0});Fn.RevocationUnsupportedError=Fn.SANDBOX_PROVIDER_KEY_ENV=Fn.SANDBOX_TIER_ENV=void 0;Fn.sandboxHoldsProviderKey=oO;Fn.isContainerSandbox=aO;Fn.SANDBOX_TIER_ENV="AGENTHIPPO_SANDBOX_TIER";Fn.SANDBOX_PROVIDER_KEY_ENV="AGENTHIPPO_SANDBOX_PROVIDER_KEY";function oO(t=process.env){return t[Fn.SANDBOX_PROVIDER_KEY_ENV]==="1"}function aO(t=process.env){return Number(t[Fn.SANDBOX_TIER_ENV])>=2}var yu=class extends Error{constructor(e,n){super(`${e} driver cannot revoke '${n}' \u2014 no enforcement boundary at this tier (use 'all', which kills the sandbox)`),this.name="RevocationUnsupportedError"}};Fn.RevocationUnsupportedError=yu});var Rh=S(_r=>{"use strict";var cO=_r&&_r.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,s)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),lO=_r&&_r.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),uO=_r&&_r.__importStar||(function(){var t=function(e){return t=Object.getOwnPropertyNames||function(n){var r=[];for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(r[r.length]=s);return r},t(e)};return function(e){if(e&&e.__esModule)return e;var n={};if(e!=null)for(var r=t(e),s=0;s<r.length;s++)r[s]!=="default"&&cO(n,e,r[s]);return lO(n,e),n}})();Object.defineProperty(_r,"__esModule",{value:!0});_r.CodexEngine=void 0;_r.registerNewFilesWithTracker=Nh;var Vn=require("fs"),fn=uO(require("path")),gh=fo(),dO=zl(),Za=zs(),ze=en(),hh=su(),wu=Js(),ri=du(),fO=Is(),pO=Er(),mh=Qa(),gO="agentide-litellm",hO="agentide-custom",Au="AGENTIDE_ANALYTICS_SESSION_ID",Su="AGENTIDE_ANALYTICS_USER_ID",Eh="AGENTIDE_ANALYTICS_PROJECT_ID",_h="AGENTIDE_ANALYTICS_AGENT_ID",yh="AGENTIDE_ANALYTICS_AGENT_VERSION",wh="AGENTIDE_ANALYTICS_SOURCE",Ah="AGENTIDE_ANALYTICS_ENGINE",Sh="AGENTIDE_ANALYTICS_REQUEST_ID",Th="AGENTIDE_ANALYTICS_POLICY_VERSION",bh="AGENTIDE_ANALYTICS_PACK_DIGEST",vh="AGENTIDE_ANALYTICS_ENGINE_VERSION",Oh="AGENTIDE_ANALYTICS_TIER",Ih="AGENTIDE_ANALYTICS_INSTANCE_ID",mO=21,EO="AGENTIDE_CONTEXT_EXPORT_PATH",_O="AGENTIDE_TERMINAL_LOG_PATH";async function Nh(t,e,n){if(e.appliesEdits!==!1)for(let r of t)try{if((0,ze.isBinaryFile)(r)||!await(0,ze.pathExists)(r))continue;let s=await Vn.promises.readFile(r,"utf-8");try{await Vn.promises.unlink(r),await e.applyEdit(n,r,s,!0)}finally{await(0,ze.pathExists)(r)||await Vn.promises.writeFile(r,s,"utf-8")}}catch{}}function Ph(t){return t.type==="item.started"||t.type==="item.updated"||t.type==="item.completed"}var Tu=class{config;getSkillsSignature;getBundledBasePromptsDir;id="codex";displayName="Codex";lastWrittenConfigSignature;lastCodexSkillsSignatureByWorkspaceRoot=new Map;constructor(e,n,r){this.config=e,this.getSkillsSignature=n,this.getBundledBasePromptsDir=r}async stream(e,n,r,s,i){let o=s.logger,a=s.editTracker,{Codex:c}=await import("@openai/codex-sdk");if(!n.modelId)throw new Error("Codex modelId not provided for streaming request");let l=n.modelId,f=(0,ze.resolveApiRouting)(n,this.config,"openai"),u=f.apiKey,d=f.openaiBaseUrl,p=f.useLiteLLM,g=n.sessionId,m=n.analyticsUserId,h=(0,Za.resolveAnalyticsProjectId)(n.analyticsProjectId,n.workspaceRoot),_=d&&d!=="https://api.openai.com/v1",y=p?"LiteLLM proxy":_?"custom provider":"direct OpenAI";o.info(`[AgentIDE] Codex routing: ${y}, baseUrl=${d||"default"}, workspaceRoot=${n.workspaceRoot}`);let b=l.toLowerCase().includes("claude");o.info(`[AgentIDE] Codex wire_api=responses (model=${l})`),b&&(p||_)&&o.info("[AgentIDE] Codex note: selected model appears to be Claude via proxy; reasoning summaries depend on provider support over the Responses API.");let O={...process.env,...s.cliEnvPatch??{},OPENAI_LOG:"debug"};delete O[pO.OPENCLAW_GATEWAY_TOKEN_ENV],delete O.AGENTHIPPO_DATA_PLANE_TOKEN;let A=g?.trim(),v=n.contextSessionId?.trim()||A;v&&(O[EO]=fn.join(n.workspaceRoot,ri.AGENT_CONSTANTS.AGENTIDE_DIR_NAME,"sessions",v,"context.md"),O[_O]=fn.join(n.workspaceRoot,ri.AGENT_CONSTANTS.AGENTIDE_DIR_NAME,"sessions",v,"terminal.md"));let C=n.agentPackId??"default",B=(0,ri.resolveRuntimePaths)(n.workspaceRoot,this.config.storagePath,C,n.agentPackVersion),R=(0,ri.userScopedEngineHomeFromKey)(B.codexHome,(0,fO.resolveEngineHomeUserKey)(n.engineHomeUserKey));O.CODEX_HOME=R,await Vn.promises.mkdir(R,{recursive:!0}),O.AGENT_ID=C,n.agentPackVersion&&(O.AGENTIDE_AGENT_VERSION=n.agentPackVersion),C!=="default"?o.info(`[AgentIDE] Codex using agent: ${C}, CODEX_HOME=${R} (agent-isolated)`):o.info(`[AgentIDE] Codex using default agent, CODEX_HOME=${R}`);let F=_?d:void 0;await this.ensureCodexConfig(p,F,l,n.workspaceRoot,n.additionalDirectories??[],o,R,C,s.permissionHandler instanceof dO.AutoApprovePermissionHandler),p&&R&&(m?.trim()&&(O[Su]=m.trim()),g?.trim()&&(O[Au]=g.trim()),h?.trim()&&(O[Eh]=h.trim()),O[_h]=C,O[yh]=n.agentPackVersion??"workspace",O[wh]="agenthippo",O[Ah]="codex",n.requestId&&(O[Sh]=n.requestId),n.policyVersion?.trim()&&(O[Th]=n.policyVersion.trim()),n.packDigest?.trim()&&(O[bh]=n.packDigest.trim()),n.engineVersion?.trim()&&(O[vh]=n.engineVersion.trim()),n.tier!==void 0&&(O[Oh]=String(n.tier)),n.instanceId?.trim()&&(O[Ih]=n.instanceId.trim())),_&&u&&(O.CODEX_API_KEY=u),_&&(O.OPENAI_BASE_URL=d,o.info(`[AgentIDE] Using custom OpenAI base URL: ${d}`),(0,ze.applyLocalTlsBypass)(O,d)&&o.info("[AgentIDE] Disabling TLS verification for local HTTPS (Codex)"));let re=(0,wu.buildConversationKey)("codex",n);o.info(`[AgentIDE] Codex conversationKey=${re.key} (chatSessionId=${re.chatSessionId}, signature=${re.signatureHash}${re.isEphemeral?", ephemeral":""})`),await(0,wu.withConversationLock)(re.key,async()=>{await r.progress("Thinking...");let W=n.permissions??hh.DEFAULT_PERMISSIONS;o.info(`[AgentIDE] Codex permissions: fileAccess=${W.fileAccess}`);let de=[n.workspaceRoot,...n.additionalDirectories??[]],he=(0,hh.toCodexOptions)(W,de);(0,mh.isContainerSandbox)()&&(he.sandboxMode="danger-full-access"),o.info(`[AgentIDE] Codex mapped: sandboxMode=${he.sandboxMode}, approvalPolicy=${he.approvalPolicy}`);let Q=n.workspaceRoot,Ne={model:l,sandboxMode:he.sandboxMode,approvalPolicy:he.approvalPolicy,additionalDirectories:he.additionalDirectories,workingDirectory:Q,skipGitRepoCheck:!0,modelReasoningEffort:"medium"};o.info(`[AgentIDE] Codex modelReasoningEffort=${Ne.modelReasoningEffort??"default"}`);let We=_?void 0:u,Me=new c({apiKey:We,env:O,...this.config.codexExecutablePath?{codexPathOverride:this.config.codexExecutablePath}:{}}),on=(0,Za.getPersistedSessionId)("codex",re.key),ye;if(on)try{ye=Me.resumeThread(on,Ne),o.info(`[AgentIDE] Codex resuming thread: ${on} (model: ${l})`)}catch(K){o.warn(`[AgentIDE] Failed to resume Codex thread (${on}): ${K instanceof Error?K.message:String(K)}. Starting new thread.`),ye=Me.startThread(Ne)}else ye=Me.startThread(Ne),o.info(`[AgentIDE] Codex starting new thread (model: ${l})`);if(i?.aborted){o.info("[AgentIDE] Codex stream cancelled before starting turn");return}let cr;try{({events:cr}=await ye.runStreamed(e,{signal:i}))}catch(K){if(i?.aborted){o.info("[AgentIDE] Codex stream aborted while starting turn");return}throw K}let ut=new Map,qt=new Map,En=new Map,Dn=0,Et=0,It=0,Pt=!1,vs=K=>K.replace(/\r/g,"").replace(/\n/g,"\\n").slice(0,160);try{for await(let K of cr){if(i?.aborted){o.info("[AgentIDE] Codex stream aborted; stopping event loop");return}let Ut=Ph(K)?K.item.type:void 0;if(o.debug(`[AgentIDE] Codex event: ${K.type}${Ut?` (item: ${Ut})`:""}`),K.type==="thread.started"){let Z=K.thread_id;o.info(`[AgentIDE] Codex thread started: ${Z}`),await(0,Za.persistSessionIfNeeded)("codex",re,Z,n);continue}if(K.type==="turn.failed")throw await r.error(K.error?.message||"Codex turn failed"),new Error(K.error?.message||"Codex turn failed");if(K.type==="error")throw await r.error(K.message||"Codex stream error"),new Error(K.message||"Codex stream error");if(K.type==="turn.completed"){o.info(`[AgentIDE] Codex usage: input=${K.usage.input_tokens}, cached=${K.usage.cached_input_tokens}, output=${K.usage.output_tokens}`);continue}if(Ph(K)){let{item:I}=K;if(I.type==="reasoning"){It++;let Z=I.text??"",j=(0,ze.computeTextDelta)(I.id,I.text??"",ut);j?(Dn++,Et+=j.length,Dn<=3&&o.debug(`[AgentIDE] Codex reasoning delta #${Dn} (${j.length} chars): ${vs(j)}`),await r.thinking(j)):!Pt&&Z.length===0&&(Pt=!0,o.debug("[AgentIDE] Codex reasoning item observed but text is empty so far."))}else if(I.type==="agent_message"){let Z=(0,ze.computeTextDelta)(I.id,I.text??"",ut);Z&&await r.text(Z)}else if(I.type==="command_execution"){if(K.type==="item.started"&&(await r.thinking(`**Running command**
49
49
  \`\`\`bash
50
50
  ${I.command}
51
51
  \`\`\`
52
52
  `),await r.toolStart("terminal",I.command,I.id,{kind:"terminal",language:"bash"}),A&&I.command&&a)){let Z=(0,ze.extractFilePaths)(I.command,n.workspaceRoot).filter(j=>!(0,ze.isBinaryFile)(j));if(Z.length>0)if((0,ze.isCreateCommand)(I.command))En.set(I.id,Z);else{let j=await Promise.all(Z.map(async oe=>[oe,await(0,ze.pathExists)(oe)])),pe=j.filter(([,oe])=>oe).map(([oe])=>oe),dt=j.filter(([,oe])=>!oe).map(([oe])=>oe);if(dt.length>0&&En.set(I.id,dt),pe.length>0)try{let oe=await a.startTracking(A,pe);oe?.operationId!==void 0&&qt.set(I.id,oe.operationId)}catch{}}}if(K.type==="item.updated"||K.type==="item.completed"){let Z=(0,ze.computeTextDelta)(`${I.id}-output`,I.aggregated_output??"",ut);Z&&await r.thinking(Z)}if(K.type==="item.completed"){let Z=I.exit_code!==void 0?I.exit_code===0?"\u2713 Command completed":`\u2717 Exited with code ${I.exit_code}`:"\u2713 Command completed";if(await r.thinking(`
53
53
  ${Z}
54
- `),await r.toolEnd("terminal",I.id,I.exit_code!==void 0?`Exited with code ${I.exit_code}`:"Completed",I.exit_code!==void 0?I.exit_code!==0:!1,{exitCode:I.exit_code}),A&&a){let j=qt.get(I.id);if(j!==void 0){try{await a.stopTracking(A,j)}catch{}qt.delete(I.id)}await Ph(En.get(I.id)??[],a,A),En.delete(I.id)}}}else if(I.type==="mcp_tool_call"){if(K.type==="item.started"){let Z=I.arguments?`
54
+ `),await r.toolEnd("terminal",I.id,I.exit_code!==void 0?`Exited with code ${I.exit_code}`:"Completed",I.exit_code!==void 0?I.exit_code!==0:!1,{exitCode:I.exit_code}),A&&a){let j=qt.get(I.id);if(j!==void 0){try{await a.stopTracking(A,j)}catch{}qt.delete(I.id)}await Nh(En.get(I.id)??[],a,A),En.delete(I.id)}}}else if(I.type==="mcp_tool_call"){if(K.type==="item.started"){let Z=I.arguments?`
55
55
  \`\`\`json
56
56
  ${JSON.stringify(I.arguments,null,2)}
57
57
  \`\`\``:"";await r.thinking(`**Calling MCP tool** \`${I.server}.${I.tool}\`${Z}
@@ -72,26 +72,26 @@ ${Z.join(`
72
72
  ${Z.join(`
73
73
  `)}
74
74
  `)}if(K.type==="item.started"||K.type==="item.completed"){let Z=I.items.filter(j=>j.completed).length;await r.progress(`[Plan] ${Z}/${I.items.length} steps complete`)}}else if(I.type==="error"){let Z=I.message||"Codex warning";o.warn(`[AgentIDE] Codex warning: ${Z}`),await r.thinking(`**Warning:** ${Z}
75
- `)}}}}catch(K){if(i?.aborted){o.info(`[AgentIDE] Codex stream aborted: ${K instanceof Error?K.message:String(K)}`);return}throw K}o.info(`[AgentIDE] Codex reasoning summary: items=${It}, deltas=${Dn}, chars=${Et}`),It===0&&o.debug("[AgentIDE] Codex emitted no reasoning items. This SDK only exposes a reasoning *summary* when available; many runs may have none."),(0,Qa.touchSessionIfNeeded)(re)},{signal:i,timeoutMs:yu.DEFAULT_CONVERSATION_LOCK_TIMEOUT_MS,label:"codex.stream"}),await r.done(),o.info("[AgentIDE] Codex streaming complete")}dispose(){this.lastWrittenConfigSignature=void 0,this.lastCodexSkillsSignatureByWorkspaceRoot.clear()}onMaintenance(e){}async ensureCodexConfig(e,n,r,s,i,o,a,c="default",l=!1){let f=a??this.config.codexHome;if(!f)return;try{let b=this.getSkillsSignature(s);await this.syncCodexSkillsToCodexHome(f,s,c,o,b)}catch(b){o.warn(`[AgentIDE] Warning: failed to sync skills into $CODEX_HOME: ${b instanceof Error?b.message:String(b)}`)}let u=await this.updateCodexRuntimeInstructionsFile(f,s,i,c,o),d="responses",p=e?"litellm":n?"custom":"openai",g=`${fO}:${p}:${n??""}:${d}:${c}:${u??""}`;if(this.lastWrittenConfigSignature===g)return;await Vn.promises.mkdir(f,{recursive:!0});let m=[`# AgentIDE Codex config (generated) - ${p} mode`,'model_reasoning_summary = "detailed"',"hide_agent_reasoning = false",u?`model_instructions_file = ${JSON.stringify(u)}`:void 0,...(0,hh.isContainerSandbox)()?['sandbox_mode = "danger-full-access"']:[]];if(n){let b=e?uO:dO,T=e?"AgentIDE LiteLLM":"AgentIDE Custom Provider";m.push("",`model_provider = "${b}"`,"",`[model_providers.${b}]`,`name = "${T}"`,`base_url = ${JSON.stringify(n)}`,'env_key = "CODEX_API_KEY"',`wire_api = "${d}"`,"query_params = {}"),e&&m.push(`env_http_headers = { "x-litellm-metadata-session-id" = "${wu}", "x-litellm-metadata-user-id" = "${Au}", "x-litellm-metadata-project-id" = "${mh}", "langfuse_session_id" = "${wu}", "langfuse_trace_user_id" = "${Au}", "x-litellm-metadata-agent-id" = "${Eh}", "x-litellm-metadata-agent-version" = "${_h}", "x-litellm-metadata-source" = "${yh}", "x-litellm-metadata-engine" = "${wh}", "x-litellm-metadata-request-id" = "${Ah}", "x-litellm-metadata-policy-version" = "${Sh}", "x-litellm-metadata-pack-digest" = "${Th}", "x-litellm-metadata-engine-version" = "${bh}", "x-litellm-metadata-tier" = "${vh}", "x-litellm-metadata-instance-id" = "${Oh}" }`)}let h=this.getBundledBasePromptsDir(),E=await(0,ph.loadMcpServers)(c,s,h),_=(0,ph.generateCodexMcpConfig)(E,{autoApprove:l});if(E.length>0){let b=c==="default"?"bundled":`pack:${c}`;o.debug(`[AgentIDE] Codex MCP config (${b}): ${E.length} server(s)`)}let y=m.filter(Boolean).join(`
75
+ `)}}}}catch(K){if(i?.aborted){o.info(`[AgentIDE] Codex stream aborted: ${K instanceof Error?K.message:String(K)}`);return}throw K}o.info(`[AgentIDE] Codex reasoning summary: items=${It}, deltas=${Dn}, chars=${Et}`),It===0&&o.debug("[AgentIDE] Codex emitted no reasoning items. This SDK only exposes a reasoning *summary* when available; many runs may have none."),(0,Za.touchSessionIfNeeded)(re)},{signal:i,timeoutMs:wu.DEFAULT_CONVERSATION_LOCK_TIMEOUT_MS,label:"codex.stream"}),await r.done(),o.info("[AgentIDE] Codex streaming complete")}dispose(){this.lastWrittenConfigSignature=void 0,this.lastCodexSkillsSignatureByWorkspaceRoot.clear()}onMaintenance(e){}async ensureCodexConfig(e,n,r,s,i,o,a,c="default",l=!1){let f=a??this.config.codexHome;if(!f)return;try{let b=this.getSkillsSignature(s);await this.syncCodexSkillsToCodexHome(f,s,c,o,b)}catch(b){o.warn(`[AgentIDE] Warning: failed to sync skills into $CODEX_HOME: ${b instanceof Error?b.message:String(b)}`)}let u=await this.updateCodexRuntimeInstructionsFile(f,s,i,c,o),d="responses",p=e?"litellm":n?"custom":"openai",g=`${mO}:${p}:${n??""}:${d}:${c}:${u??""}`;if(this.lastWrittenConfigSignature===g)return;await Vn.promises.mkdir(f,{recursive:!0});let m=[`# AgentIDE Codex config (generated) - ${p} mode`,'model_reasoning_summary = "detailed"',"hide_agent_reasoning = false",u?`model_instructions_file = ${JSON.stringify(u)}`:void 0,...(0,mh.isContainerSandbox)()?['sandbox_mode = "danger-full-access"']:[]];if(n){let b=e?gO:hO,T=e?"AgentIDE LiteLLM":"AgentIDE Custom Provider";m.push("",`model_provider = "${b}"`,"",`[model_providers.${b}]`,`name = "${T}"`,`base_url = ${JSON.stringify(n)}`,'env_key = "CODEX_API_KEY"',`wire_api = "${d}"`,"query_params = {}"),e&&m.push(`env_http_headers = { "x-litellm-metadata-session-id" = "${Au}", "x-litellm-metadata-user-id" = "${Su}", "x-litellm-metadata-project-id" = "${Eh}", "langfuse_session_id" = "${Au}", "langfuse_trace_user_id" = "${Su}", "x-litellm-metadata-agent-id" = "${_h}", "x-litellm-metadata-agent-version" = "${yh}", "x-litellm-metadata-source" = "${wh}", "x-litellm-metadata-engine" = "${Ah}", "x-litellm-metadata-request-id" = "${Sh}", "x-litellm-metadata-policy-version" = "${Th}", "x-litellm-metadata-pack-digest" = "${bh}", "x-litellm-metadata-engine-version" = "${vh}", "x-litellm-metadata-tier" = "${Oh}", "x-litellm-metadata-instance-id" = "${Ih}" }`)}let h=this.getBundledBasePromptsDir(),E=await(0,gh.loadMcpServers)(c,s,h),_=(0,gh.generateCodexMcpConfig)(E,{autoApprove:l});if(E.length>0){let b=c==="default"?"bundled":`pack:${c}`;o.debug(`[AgentIDE] Codex MCP config (${b}): ${E.length} server(s)`)}let y=m.filter(Boolean).join(`
76
76
  `)+_;await Vn.promises.writeFile(fn.join(f,"config.toml"),y,"utf8"),this.lastWrittenConfigSignature=g,o.info(`[AgentIDE] Codex configured (${p}) at ${f}${n?`, baseUrl=${n}, wire_api=${d}`:""}, model=${r??"unknown"}`)}async updateCodexRuntimeInstructionsFile(e,n,r,s,i){let o=fn.join(n,ri.AGENT_CONSTANTS.AGENTIDE_DIR_NAME,"agents",s,"AGENTS.md"),a="";if(await(0,ze.pathExists)(o))a=await Vn.promises.readFile(o,"utf8"),i.debug(`[AgentIDE] Codex instructions from pack: ${s}/AGENTS.md`);else{let h=this.getBundledBasePromptsDir();if(h){let E=fn.join(h,"rules","AGENTS.md");await(0,ze.pathExists)(E)&&(a=await Vn.promises.readFile(E,"utf8"),i.debug(`[AgentIDE] Codex instructions from bundled templates (pack ${s} has no AGENTS.md)`))}a||i.warn(`[AgentIDE] Warning: no AGENTS.md found for agent ${s} and no bundled fallback`)}let c=fn.join(n,ri.AGENT_CONSTANTS.AGENTIDE_DIR_NAME,"agents",s,"context.md"),l="";await(0,ze.pathExists)(c)&&(l=await Vn.promises.readFile(c,"utf8"));let f=r.slice().filter(Boolean).sort(),d=["## AgentIDE Runtime Context (managed)","","### Workspace Information","","```json",JSON.stringify({workspaceRoot:n,additionalDirectories:f},null,2),"```"].join(`
77
77
  `),p=[a.trimEnd()];l.trim()&&p.push(l.trimEnd()),p.push(d.trimEnd());let g=p.filter(Boolean).join(`
78
78
 
79
79
  ---
80
80
 
81
81
  `).trimEnd().concat(`
82
- `),m=fn.join(e,"agentide.runtime.md");return await(0,ze.writeFileIfChanged)(m,g),m}async syncCodexSkillsToCodexHome(e,n,r,s,i){let o=fn.join(n,ri.AGENT_CONSTANTS.AGENTIDE_DIR_NAME,"agents",r,"skills"),a=fn.join(e,"skills");if(i){let f=this.lastCodexSkillsSignatureByWorkspaceRoot.get(n),u=await(0,ze.pathExists)(a);if(f===i&&u){s.debug(`[AgentIDE] Codex skills unchanged (sig=${i}), skipping $CODEX_HOME sync`);return}}try{await Vn.promises.rm(a,{recursive:!0,force:!0})}catch{}if(!await(0,ze.pathExists)(o))return;await Vn.promises.mkdir(a,{recursive:!0});let c=0,l=await Vn.promises.readdir(o,{withFileTypes:!0});for(let f of l){if(!f.isDirectory()||f.name.startsWith("."))continue;let u=fn.join(o,f.name),d=fn.join(u,"SKILL.md");await(0,ze.pathExists)(d)&&(await(0,ze.copyDirRecursive)(u,fn.join(a,f.name)),c++)}i&&this.lastCodexSkillsSignatureByWorkspaceRoot.set(n,i),s.info(`[AgentIDE] Codex skills synced to $CODEX_HOME: ${c} skill(s)`)}};_r.CodexEngine=Su});var $h=S(Mr=>{"use strict";var hO=Mr&&Mr.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,s)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),mO=Mr&&Mr.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),EO=Mr&&Mr.__importStar||(function(){var t=function(e){return t=Object.getOwnPropertyNames||function(n){var r=[];for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(r[r.length]=s);return r},t(e)};return function(e){if(e&&e.__esModule)return e;var n={};if(e!=null)for(var r=t(e),s=0;s<r.length;s++)r[s]!=="default"&&hO(n,e,r[s]);return mO(n,e),n}})();Object.defineProperty(Mr,"__esModule",{value:!0});Mr.ClaudeEngine=void 0;var _O=require("fs"),Za=EO(require("path")),yO=Ke(),_o=zs(),si=en(),Rh=ru(),Ch=lo(),wO=Er(),ec=Js(),tc=uu(),AO=Is(),kh=Sa(),SO=new Set(["Write","Edit","FileEdit","FileWrite","MultiEdit","str_replace_editor","Str_replace_editor","TextEditor","text_editor","Bash","bash","shell","Shell"]),TO=1e3*60*30;function bO(t,e){return async(n,r)=>{if(n==="AskUserQuestion"){let s=r,i=s?.questions??[];if(i.length===0)return e.warn("[AgentIDE] AskUserQuestion with no questions"),{behavior:"allow",updatedInput:{...s,answers:{}}};let o={};for(let a of i){let c={questionId:`ask-${Date.now()}-${Math.random().toString(36).slice(2,9)}`,prompt:a.question,options:a.options?.map(u=>({label:u.label,description:u.description})),multiSelect:a.multiSelect},l=await t.question(c);if(l.declined||l.cancelled)return{behavior:"deny",message:"User declined or cancelled the question."};let f=l.freeText??l.selected.join(", ");o[a.question]=f}return{behavior:"allow",updatedInput:{questions:s.questions,answers:o}}}return{behavior:"allow",updatedInput:r}}}var vO="AGENTIDE_CONTEXT_EXPORT_PATH",OO="AGENTIDE_TERMINAL_LOG_PATH";function IO(){let t=!1,e=[],n=[];return{enqueue(r){if(t)throw new Error("Cannot enqueue into a closed queue");let s=n.shift();if(s){s({value:r,done:!1});return}e.push(r)},close(){for(t=!0;n.length;)n.shift()?.({value:void 0,done:!0})},[Symbol.asyncIterator](){return{next(){if(e.length){let r=e.shift();return Promise.resolve({value:r,done:!1})}return t?Promise.resolve({value:void 0,done:!0}):new Promise(r=>n.push(r))}}}}}function PO(t){let e=IO(),n=new AbortController,r=t.queryFn({prompt:e,options:{...t.options,abortController:n,resume:t.resumeSessionId}}),s=r[Symbol.asyncIterator](),i=!1,o=t.resumeSessionId??null;return{get sessionId(){return o},async setMaxThinkingTokens(a){if(i)throw new Error("Cannot setMaxThinkingTokens on closed Claude session");await r.setMaxThinkingTokens(a)},async interrupt(){if(!i)try{await r.interrupt()}catch{}},async send(a){if(i)throw new Error("Cannot send to closed Claude session");let c;typeof a=="string"?c={type:"user",session_id:"",message:{role:"user",content:[{type:"text",text:a}]},parent_tool_use_id:null}:c=a,e.enqueue(c)},async*receive(){for(;;){let{value:a,done:c}=await s.next();if(c)return;let l=a;if(l.type==="system"&&l.subtype==="init"&&(o=l.session_id),yield l,l.type==="result")return}},close(){i||(i=!0,e.close(),n.abort())}}}var Tu=class{config;computeAgentideSignature;getBundledBasePromptsDir;id="claude";displayName="Claude";activeSessions=new Map;constructor(e,n,r){this.config=e,this.computeAgentideSignature=n,this.getBundledBasePromptsDir=r}async stream(e,n,r,s,i){let o=s.logger,a=s.editTracker,{apiKey:c,baseUrl:l,useLiteLLM:f}=(0,si.resolveApiRouting)(n,this.config,"anthropic");if(!c)throw new Error("Claude API key not provided");o.info(`[AgentIDE] Claude using ${f?"LiteLLM proxy":"direct Anthropic"}, baseUrl: ${l||"default"}, workspaceRoot=${n.workspaceRoot}, additionalDirs=${n.additionalDirectories?.length??0}`),await r.progress("Thinking...");let u=(0,_o.buildLiteLLMMetadataHeaders)(f,{sessionId:n.sessionId,analyticsUserId:n.analyticsUserId,analyticsProjectId:(0,_o.resolveAnalyticsProjectId)(n.analyticsProjectId,n.workspaceRoot),agentId:n.agentPackId??"default",agentVersion:n.agentPackVersion??"workspace",source:"agenthippo",engine:"claude",requestId:n.requestId,policyVersion:n.policyVersion,packDigest:n.packDigest,instanceId:n.instanceId,engineVersion:n.engineVersion,tier:n.tier}),d={...process.env,...s.cliEnvPatch??{},DEBUG_CLAUDE_AGENT_SDK:"1",CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC:"1"};if(delete d[wO.OPENCLAW_GATEWAY_TOKEN_ENV],delete d.AGENTHIPPO_DATA_PLANE_TOKEN,(0,kh.isAnthropicSetupToken)(c)){let C=(0,kh.normalizeAnthropicSetupToken)(c);d.CLAUDE_CODE_OAUTH_TOKEN=C,delete d.ANTHROPIC_AUTH_TOKEN,delete d.ANTHROPIC_API_KEY,o.info("[AgentIDE] Claude using setup-token auth (CLAUDE_CODE_OAUTH_TOKEN)")}else d.ANTHROPIC_API_KEY=c,d.ANTHROPIC_AUTH_TOKEN=c,delete d.CLAUDE_CODE_OAUTH_TOKEN;let g=n.sessionId?.trim(),m=n.contextSessionId?.trim()||g;m&&(d[vO]=Za.join(n.workspaceRoot,tc.AGENT_CONSTANTS.AGENTIDE_DIR_NAME,"sessions",m,"context.md"),d[OO]=Za.join(n.workspaceRoot,tc.AGENT_CONSTANTS.AGENTIDE_DIR_NAME,"sessions",m,"terminal.md"));let h=n.agentPackId??"default",E=(0,tc.resolveRuntimePaths)(n.workspaceRoot,this.config.storagePath,h,n.agentPackVersion),_=(0,tc.userScopedEngineHomeFromKey)(E.claudeConfigDir,(0,AO.resolveEngineHomeUserKey)(n.engineHomeUserKey));if(d.CLAUDE_CONFIG_DIR=_,await _O.promises.mkdir(_,{recursive:!0}),d.AGENT_ID=h,n.agentPackVersion&&(d.AGENTIDE_AGENT_VERSION=n.agentPackVersion),h!=="default"?o.info(`[AgentIDE] Claude using agent: ${h}, CLAUDE_CONFIG_DIR=${_} (agent-isolated)`):o.info(`[AgentIDE] Claude using default agent, CLAUDE_CONFIG_DIR=${_}`),u.length>0&&(d.ANTHROPIC_CUSTOM_HEADERS=u.join(`
83
- `)),l&&l!=="https://api.anthropic.com/v1"){let C=l.endsWith("/v1")?l.slice(0,-3):l;d.ANTHROPIC_BASE_URL=C,o.info(`[AgentIDE] Using custom Anthropic base URL: ${C}`),(0,si.applyLocalTlsBypass)(d,C)&&o.info("[AgentIDE] Disabling TLS verification for local HTTPS")}let T=n.modelId;if(!T)throw new Error("Claude modelId not provided for streaming request");o.info(`[AgentIDE] Using Claude model: ${T}`);let O="",A=async C=>{if(!C)return;let B=O.length,R=C.length;if(B===0){O=C,await r.text(C);return}if(R===B){if(C===O){o.debug("[AgentIDE] Claude: exact duplicate, skipping");return}}else if(R>B){if(C.startsWith(O)){let F=C.slice(B);O=C,o.debug(`[AgentIDE] Claude: emitting remainder (${F.length} chars)`),await r.text(F);return}}else if(O.endsWith(C)){o.debug("[AgentIDE] Claude: suffix already streamed, skipping");return}O=C,await r.text(C)},v=(0,ec.buildConversationKey)("claude",n);o.info(`[AgentIDE] Claude conversationKey=${v.key} (chatSessionId=${v.chatSessionId}, signature=${v.signatureHash}${v.isEphemeral?", ephemeral":""})`),await(0,ec.withConversationLock)(v.key,async()=>{let C=(0,si.getAgentideEngineSettings)(s?.configProvider),B=typeof C.claudeMaxThinkingTokens=="number"&&C.claudeMaxThinkingTokens>0?Math.floor(C.claudeMaxThinkingTokens):null;o.debug(`[AgentIDE] Claude maxThinkingTokens=${B??"default/disabled"}`);let R=(C.claudeCheapModel||"").trim();R&&(d.ANTHROPIC_DEFAULT_HAIKU_MODEL=R,d.CLAUDE_CODE_SUBAGENT_MODEL=R,o.debug(`[AgentIDE] Claude cheapModel=${R}`));let F=n.permissions??Rh.DEFAULT_PERMISSIONS;o.debug(`[AgentIDE] Claude permissions: fileAccess=${F.fileAccess}`);let re=(0,si.stableAdditionalDirs)([n.workspaceRoot,...n.additionalDirectories??[]]),W=(0,Rh.toClaudeOptions)(F,re);o.debug(`[AgentIDE] Claude mapped: permissionMode=${W.permissionMode}, allowDangerouslySkipPermissions=${W.allowDangerouslySkipPermissions}, dirs=${W.additionalDirectories?.length??"undefined"}`);let de=(0,si.stableAdditionalDirs)([...W.additionalDirectories??[],_]),he=await this.computeAgentideSignature(n.workspaceRoot,n.additionalDirectories),z=n.sessionId,Ne=n.workspaceRoot,We={current:null},Me=j=>{let pe=j.trim();return/(?:^|&&|\||;)\s*git\s+/.test(pe)},on=(j,pe)=>{let dt=pe;if(!dt)return[];if(j==="Bash"){let Yt=dt.command;return Yt?Me(Yt)?[]:(0,si.extractFilePaths)(Yt,Ne):[]}let oe=dt.file_path??dt.path;return oe?[Za.isAbsolute(oe)?oe:Za.join(Ne,oe)]:[]},ye={continue:!0},cr=async(j,pe,dt)=>{try{o.debug(`[AgentIDE] PreToolUse hook called: toolUseID=${pe}, event=${j.hook_event_name}`);let oe=We.current;if(!oe)return o.debug("[AgentIDE] PreToolUse: no edit state"),ye;if(oe.aborted)return o.debug("[AgentIDE] PreToolUse: aborted"),ye;if(j.hook_event_name!=="PreToolUse")return o.debug(`[AgentIDE] PreToolUse: wrong event ${j.hook_event_name}`),ye;if(!z)return o.debug("[AgentIDE] PreToolUse: no rawChatSessionId"),ye;if(!a)return o.debug("[AgentIDE] PreToolUse: no edit tracker available"),ye;let _t=j.tool_name;if(!SO.has(_t))return o.debug(`[AgentIDE] PreToolUse: tool ${_t} not tracked (not in FILE_TOOLS)`),ye;let Yt=j.tool_use_id,Xt=on(_t,j.tool_input).filter(Jt=>!(0,si.isBinaryFile)(Jt));if(o.debug(`[AgentIDE] PreToolUse: ${_t} files=${Xt.length}: ${Xt.join(", ")}`),Xt.length===0)return ye;o.debug(`[AgentIDE] PreToolUse: calling startTracking for ${Xt.length} files`);try{let Jt=await a.startTracking(z,Xt);Jt?.operationId!==void 0&&oe&&!oe.aborted&&(o.debug(`[AgentIDE] PreToolUse: startTracking returned opId=${Jt.operationId}`),oe.pendingOperations.set(Yt,Jt.operationId))}catch(Jt){o.warn(`[AgentIDE] PreToolUse: startTracking failed: ${Jt}`)}return ye}catch(oe){return o.error("[AgentIDE] PreToolUse hook EXCEPTION",oe instanceof Error?oe:void 0),ye}},ut=async(j,pe,dt)=>{try{o.debug(`[AgentIDE] PostToolUse hook called: toolUseID=${pe}, event=${j.hook_event_name}`);let oe=We.current;if(!oe||oe.aborted||j.hook_event_name!=="PostToolUse"||!z||!a)return ye;let _t=j.tool_use_id;if(!_t)return ye;let Yt=oe.pendingOperations.get(_t);if(o.debug(`[AgentIDE] PostToolUse: toolUseId=${_t} opId=${Yt}`),Yt!==void 0){oe.pendingOperations.delete(_t);try{await a.stopTracking(z,Yt),o.debug("[AgentIDE] PostToolUse: stopTracking done")}catch(Xt){o.warn(`[AgentIDE] PostToolUse: stopTracking failed: ${Xt}`)}}return ye}catch(oe){return o.error("[AgentIDE] PostToolUse hook EXCEPTION",oe instanceof Error?oe:void 0),ye}};o.debug(`[AgentIDE] Setting up Claude hooks for session ${z}`);let qt=async(j,pe,dt)=>(o.debug(`[AgentIDE] SessionStart hook called! event=${j.hook_event_name}`),ye),En=await this.loadMcpServersForClaude(o,n.workspaceRoot,h,d),Dn=n.workspaceRoot,Et=h!=="default"?["project"]:["user","project"],It=W.allowDangerouslySkipPermissions===!0?!0:void 0,Pt={model:T,cwd:Dn,additionalDirectories:de,settingSources:Et,env:d,permissionMode:W.permissionMode,allowDangerouslySkipPermissions:It,includePartialMessages:!0,persistSession:!0,...B?{maxThinkingTokens:B}:{},...Object.keys(En).length>0?{mcpServers:En}:{},...this.config.claudeCodeExecutablePath?{pathToClaudeCodeExecutable:this.config.claudeCodeExecutablePath}:{},canUseTool:bO(r,o),hooks:{SessionStart:[{hooks:[qt]}],PreToolUse:[{hooks:[cr]}],PostToolUse:[{hooks:[ut]}]},stderr:j=>{o.debug(`[AgentIDE] Claude CLI stderr: ${j}`)}},vs=await this.getOrCreateSession({conversationKey:v.key,chatSessionId:v.chatSessionId,signatureHash:v.signatureHash,signatureRaw:v.signatureRaw,agentideSignature:he,isEphemeral:v.isEphemeral,modelId:T,cheapModel:R||void 0,queryOptions:Pt,logger:o}),K=vs.session,Ut=vs.editTrackingState;We.current=Ut;let I=!1,Z=()=>{I=!0,Ut.aborted=!0;let j=Array.from(Ut.pendingOperations.values());if(Ut.pendingOperations.clear(),z&&j.length>0&&a)for(let pe of j)a.stopTracking(z,pe).catch(()=>{});o.info("[AgentIDE] Claude cancel requested; interrupting session..."),K.interrupt().catch(()=>{try{K.close()}catch{}})};if(i?.aborted){Z();return}i?.addEventListener("abort",Z,{once:!0});try{try{await K.setMaxThinkingTokens(B),o.debug(`[AgentIDE] Claude setMaxThinkingTokens(${B??"null"}) ok`)}catch(J){o.warn(`[AgentIDE] Claude setMaxThinkingTokens(${B??"null"}) failed: ${J instanceof Error?J.message:String(J)}`)}await K.send(e);let j=0,pe=0,dt=0,oe=0,_t=0,Yt=0,Xt=0,Jt=0,ss=new Set,Ti=new Set,to=new Set,lr=new Map,sa=new Map,no=new Map,ia=new Map,ro=J=>J.replace(/\r/g,"").replace(/\n/g,"\\n").slice(0,160),Cr=(J,M)=>{if(typeof M=="string")return M.trim()?M:void 0;if(!M||typeof M!="object")return;let we=M,ke=we.command;if(typeof ke=="string"&&ke.trim())return ke.trim();let Xe=we.args;if(Array.isArray(Xe)&&Xe.every(fe=>typeof fe=="string"))return Xe.join(" ");let me=we.location,Ie=me&&typeof me=="object"?me.path:void 0,yt=we.path??we.file_path??we.file??we.filename??Ie,et=[];typeof yt=="string"&&yt.trim()&&et.push(yt.trim());let tt=we.content;typeof tt=="string"&&et.push(`contentBytes=${Buffer.byteLength(tt,"utf8")}`);let Ae=we.patch??we.diff;if(typeof Ae=="string"&&et.push(`patchBytes=${Buffer.byteLength(Ae,"utf8")}`),et.length>0)return et.join(" ");let je=300,Ht=30,vi=4,Ln=(fe,_n)=>{if(typeof fe=="string")return fe.length>je?`${fe.slice(0,je)}\u2026 (${fe.length} chars)`:fe;if(typeof fe=="number"||typeof fe=="boolean"||fe===null)return fe;if(Array.isArray(fe)){if(_n>=vi)return`[Array(${fe.length})]`;let Mn=fe.slice(0,Ht).map(yn=>Ln(yn,_n+1));return fe.length>Ht?[...Mn,`\u2026 (${fe.length-Ht} more)`]:Mn}if(typeof fe=="object"&&fe){if(_n>=vi)return"[Object]";let Mn={};for(let[yn,os]of Object.entries(fe)){if(typeof os=="string"&&/content|text|data|body|patch|diff/i.test(yn)&&os.length>je){Mn[yn]=`<${Buffer.byteLength(os,"utf8")} bytes>`;continue}Mn[yn]=Ln(os,_n+1)}return Mn}};try{let fe=JSON.stringify(Ln(M,0),null,2),_n=fe.trim();return _n==="{}"||_n==="[]"?void 0:fe}catch{return}},so=J=>{if(!J||typeof J!="object")return;let M=J,we=M.type;if(we==="tool_use"||we==="server_tool_use"){let ke=M.id,Xe=M.name,me=M.input;return typeof ke=="string"&&typeof Xe=="string"?{id:ke,name:Xe,input:me}:void 0}if(we==="mcp_tool_use"){let ke=M.id,Xe=M.name,me=M.server_name,Ie=M.input;if(typeof ke=="string"&&typeof Xe=="string"&&typeof me=="string")return{id:ke,name:`${me}.${Xe}`,input:Ie}}},is=J=>{if(typeof J=="string")return J;if(J!=null)try{return JSON.stringify(J,null,2)}catch{return String(J)}},ur=J=>{if(typeof J=="string")return J;if(Array.isArray(J)){let M=[];for(let ke of J){if(typeof ke=="string"){M.push(ke);continue}if(!ke||typeof ke!="object")continue;let Xe=ke;if(typeof Xe.text=="string"){M.push(Xe.text);continue}let me=is(ke);me&&M.push(me)}return M.join(`
84
- `).trim()||void 0}if(J&&typeof J=="object"){let M=J;if(typeof M.text=="string")return M.text}return is(J)},bi=J=>{if(!J||typeof J!="object")return;let M=J,we=M.type;if(we!=="tool_result"&&we!=="server_tool_result"&&we!=="mcp_tool_result")return;let ke=M.tool_use_id;if(typeof ke!="string"||!ke)return;let Xe=ur(M.content??M.result??M.output??M.data??M.text),me=typeof M.is_error=="boolean"?M.is_error:typeof M.isError=="boolean"?M.isError:void 0;return{toolUseId:ke,resultText:Xe,isError:me}},Ws=async(J,M,we)=>{if(!(!ss.has(M)||!!we&&!Ti.has(M))){lr.set(M,J);return}Yt++,ss.add(M),we&&Ti.add(M),lr.set(M,J),I||await r.toolStart(J,we,M)},zt=async(J,M,we,ke)=>{if(to.has(J))return;let Xe=lr.get(J)??ke??"tool";ss.has(J)||await Ws(Xe,J),to.add(J),lr.delete(J),I||await r.toolEnd(Xe,J,M,we)},oa=!1,io=0;for await(let J of K.receive()){io++;let M=J,we=M.session_id;!oa&&we&&(oa=!0,await(0,_o.persistSessionIfNeeded)("claude",v,we,n));let ke=M.type==="result"||M.type==="system"?M.subtype:void 0;if(o.debug(`[AgentIDE] Claude msg #${io}: type=${M.type}, subtype=${ke||"none"}`),I&&M.type!=="result")continue;if(M.type==="stream_event"){let me=M.event,Ie=me.type;if(Ie==="content_block_start"){let yt=me.content_block,et=yt?.type,tt=me.index;if(et==="thinking"){let Ae=yt?.thinking;dt++,typeof Ae=="string"&&Ae?(pe+=Ae.length,o.debug(`[AgentIDE] Claude thinking block start (${Ae.length} chars): ${ro(Ae)}`),I||await r.thinking(Ae)):o.debug("[AgentIDE] Claude thinking block start (no initial thinking text)")}else if(et==="redacted_thinking"){oe++;let Ae=yt?.data;o.debug(`[AgentIDE] Claude redacted_thinking block start (dataType=${typeof Ae})`)}else{let Ae=bi(me.content_block);if(Ae){await zt(Ae.toolUseId,Ae.resultText,Ae.isError);continue}let je=so(me.content_block);if(je&&(_t++,typeof tt=="number"&&(sa.set(tt,je.id),no.set(tt,je.name)),!ss.has(je.id))){let Ht=Cr(je.name,je.input);o.debug(`[AgentIDE] Claude tool_use start: ${je.name} (id=${je.id}, input=${Ht?"yes":"no"})`),await Ws(je.name,je.id,Ht)}}}else if(Ie==="content_block_delta"){let yt=me.delta,et=yt.type,tt=yt.thinking,Ae=yt.text;if(et==="thinking_delta"&&typeof tt=="string"&&tt)j++,pe+=tt.length,j<=3&&o.debug(`[AgentIDE] Claude thinking delta #${j} (${tt.length} chars): ${ro(tt)}`),I||await r.thinking(tt);else if(et==="input_json_delta"){let je=me.index,Ht=yt.partial_json;if(typeof je=="number"&&typeof Ht=="string"&&Ht){Jt++;let Ln=(ia.get(je)??"")+Ht;ia.set(je,Ln);let fe=sa.get(je);if(fe&&!Ti.has(fe))try{let _n=JSON.parse(Ln),Mn=no.get(je)??"tool",yn=Cr(Mn,_n);yn&&(o.debug(`[AgentIDE] Claude tool_use input_json parsed: ${Mn} (id=${fe})`),await Ws(Mn,fe,yn))}catch{}}}else et==="text_delta"&&typeof Ae=="string"&&Ae&&(O+=Ae,I||await r.text(Ae))}}else if(M.type==="assistant"){let me=M.message.content;if(Array.isArray(me))for(let Ie of me){let yt=Ie.type,et=Ie.text,tt=bi(Ie);if(tt){await zt(tt.toolUseId,tt.resultText,tt.isError);continue}let Ae=so(Ie);if(Ae&&!ss.has(Ae.id)){_t++;let je=Cr(Ae.name,Ae.input);o.debug(`[AgentIDE] Claude tool_use (assistant msg): ${Ae.name} (id=${Ae.id}, input=${je?"yes":"no"})`),await Ws(Ae.name,Ae.id,je);continue}yt==="text"&&typeof et=="string"&&et&&(I||await A(et))}}else if(M.type==="tool_progress"){Xt++;let me=M.tool_use_id,Ie=M.tool_name||"tool";me&&!ss.has(me)&&(o.debug(`[AgentIDE] Claude tool_progress: ${Ie} (tool_use_id=${me})`),await Ws(Ie,me))}else if(M.type==="system")M.subtype==="status"&&M.status==="compacting"&&(I||await r.progress("Compacting context\u2026"));else if(M.type==="result"){if(M.subtype==="success")I||await A(M.result);else if(!I)throw new Error(M.errors?.join(`
85
- `)||M.subtype)}let Xe=M.message?.content;if(M.type!=="assistant"&&Array.isArray(Xe))for(let me of Xe){let Ie=bi(me);Ie&&await zt(Ie.toolUseId,Ie.resultText,Ie.isError)}}for(let[J,M]of Array.from(lr.entries()))await zt(J,"Completed",!1,M);o.info(`[AgentIDE] Claude thinking summary: startBlocks=${dt}, redactedBlocks=${oe}, deltas=${j}, chars=${pe}`),o.info(`[AgentIDE] Claude tool summary: toolBlocks=${_t}, toolEmits=${Yt}, toolProgressMsgs=${Xt}, inputJsonDeltas=${Jt}`),dt===0&&j===0&&oe===0&&o.debug(`[AgentIDE] Claude emitted no thinking blocks/deltas. Ensure model supports extended thinking and set ${(0,yO.toSettingsDisplayKey)("agentide.claude.maxThinkingTokens")} >= 1024.`),_t===0&&Xt===0&&o.debug("[AgentIDE] Claude emitted no tool usage events. If tools were used, ensure includePartialMessages=true and parse tool_use blocks."),(0,_o.touchSessionIfNeeded)(v)}catch(j){if(!I)throw j;o.info(`[AgentIDE] Claude stream aborted: ${j instanceof Error?j.message:String(j)}`)}finally{i?.removeEventListener("abort",Z)}},{signal:i,timeoutMs:ec.DEFAULT_CONVERSATION_LOCK_TIMEOUT_MS,label:"claude.stream"}),await r.done(),o.info("[AgentIDE] Claude streaming complete")}dispose(){for(let e of this.activeSessions.values())try{e.session.close()}catch{}this.activeSessions.clear()}onMaintenance(e){this.sweepIdleSessions(e)}sweepIdleSessions(e){let n=Date.now();for(let[r,s]of this.activeSessions.entries())if(n-s.lastUsedAt>TO){try{s.session.close(),e?.info(`[AgentIDE] Closed idle Claude session (key=${r}, idleMs=${n-s.lastUsedAt})`)}catch{}this.activeSessions.delete(r)}}async getOrCreateSession(e){let n=this.activeSessions.get(e.conversationKey);if(n&&n.signatureHash===e.signatureHash&&n.modelId===e.modelId&&n.cheapModel===e.cheapModel&&n.agentideSignature===e.agentideSignature)return n.lastUsedAt=Date.now(),n.editTrackingState.aborted=!1,n.editTrackingState.pendingOperations.clear(),(0,ec.touchPersistedSession)(e.conversationKey),e.logger.debug(`[AgentIDE] REUSING existing Claude session (key=${e.conversationKey}) - NOTE: hooks from original session creation are used, not new ones`),n;let r;if(n){n.signatureHash===e.signatureHash&&n.agentideSignature!==e.agentideSignature&&(e.logger.info(`[AgentIDE] AgentIDE manifest changed (${n.agentideSignature} \u2192 ${e.agentideSignature}), restarting Claude session with resume`),r=n.session.sessionId??void 0),n.modelId!==e.modelId&&(e.logger.info(`[AgentIDE] Model changed (${n.modelId} \u2192 ${e.modelId}), will resume session with new model`),r=n.session.sessionId??void 0),n.cheapModel!==e.cheapModel&&(e.logger.info(`[AgentIDE] Cheap model changed (${n.cheapModel??"unset"} \u2192 ${e.cheapModel??"unset"}), will resume session with updated env`),r=n.session.sessionId??void 0);try{n.session.close()}catch{}this.activeSessions.delete(e.conversationKey)}!r&&!e.isEphemeral&&(r=(0,_o.getPersistedSessionId)("claude",e.conversationKey)),r?e.logger.info(`[AgentIDE] Claude session will resume: ${r} (model: ${e.modelId})`):e.logger.info(`[AgentIDE] Claude session starting new (model: ${e.modelId})`);let s=await import("@anthropic-ai/claude-agent-sdk"),o={session:PO({resumeSessionId:r,queryFn:s.query,options:e.queryOptions}),chatSessionId:e.chatSessionId,signatureHash:e.signatureHash,agentideSignature:e.agentideSignature,modelId:e.modelId,cheapModel:e.cheapModel,lastUsedAt:Date.now(),editTrackingState:{aborted:!1,pendingOperations:new Map}};return this.activeSessions.set(e.conversationKey,o),o}async loadMcpServersForClaude(e,n,r="default",s){let i=this.getBundledBasePromptsDir(),o=await(0,Ch.loadMcpServers)(r,n,i);if(o.length===0)return{};let a={};for(let l of o){if(l.url){let f=(0,Ch.referenceHttpMcpHeaders)(l,s??process.env);a[l.name]={type:"http",url:l.url,...f?{headers:f}:{}};continue}a[l.name]={command:l.command,args:l.args,...l.env&&Object.keys(l.env).length>0?{env:l.env}:{}}}let c=r==="default"?"bundled":`pack:${r}`;return e.debug(`[AgentIDE] Claude MCP servers loaded (${c}): ${o.map(l=>l.name).join(", ")}`),a}};Mr.ClaudeEngine=Tu});var vu=S(pn=>{"use strict";var NO=pn&&pn.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,s)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),RO=pn&&pn.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),CO=pn&&pn.__importStar||(function(){var t=function(e){return t=Object.getOwnPropertyNames||function(n){var r=[];for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(r[r.length]=s);return r},t(e)};return function(e){if(e&&e.__esModule)return e;var n={};if(e!=null)for(var r=t(e),s=0;s<r.length;s++)r[s]!=="default"&&NO(n,e,r[s]);return RO(n,e),n}})();Object.defineProperty(pn,"__esModule",{value:!0});pn.syncPackMcpToWorkspace=Gh;pn.syncPackToWorkspace=HO;pn.computeSkillsSignature=Uh;pn.createSkillsSignatureGetter=jO;pn.createSessionDir=xO;pn.getSessionDir=BO;var Fe=require("fs"),q=CO(require("path")),Lh=require("crypto"),Ee=en(),kO=Sa(),Ce=Un(),Mh=Qs(),$O=lo(),DO=Ns();async function Gh(t,e,n,r){let s=q.join(t,Ce.AGENT_CONSTANTS.MANIFEST_FILE);if(!await(0,Ee.pathExists)(s))return;let i;try{i=await(0,Mh.loadAgentManifest)(s)}catch(u){Rt(r,`[AgentIDE] Skipping pack MCP sync for ${n}: ${u instanceof Error?u.message:String(u)}`);return}let o=i.spec?.mcp;if(!o?.length)return;let a=q.join(e,Ce.AGENT_CONSTANTS.AGENTIDE_DIR_NAME,Ce.AGENT_CONSTANTS.AGENTS_DIR,n,Ce.AGENT_CONSTANTS.MCP_DIR);await Fe.promises.mkdir(a,{recursive:!0});let c={mcpServers:{}},l=q.join(a,".mcp.json");for(let u of o){let d=u.config?.trim();if(!d)continue;let p=q.resolve(t,d);if(!bu(t,p)){Rt(r,`[AgentIDE] Skipping MCP config ${d}: path escapes pack root`);continue}if(!await(0,Ee.pathExists)(p)){Rt(r,`[AgentIDE] Skipping MCP config ${d}: file not found`);continue}try{let m=JSON.parse(await Fe.promises.readFile(p,"utf8")).mcpServers;m&&typeof m=="object"&&Object.assign(c.mcpServers,m)}catch(g){Rt(r,`[AgentIDE] Skipping MCP config ${d}: ${g instanceof Error?g.message:String(g)}`)}}let f=q.join(t,Ce.AGENT_CONSTANTS.MCP_DIR);if(await(0,Ee.pathExists)(f)){let u=await Fe.promises.readdir(f,{withFileTypes:!0});for(let d of u){if(!d.isDirectory()||d.name.startsWith("."))continue;let p=q.join(f,d.name),g=q.join(a,d.name);await(0,Ee.pathExists)(g)||await(0,Ee.copyDirRecursive)(p,g)}}!c.mcpServers||Object.keys(c.mcpServers).length===0||(await(0,Ee.writeFileIfChanged)(l,`${JSON.stringify(c,null,2)}
86
- `),Rt(r,`[AgentIDE] Synced pack MCP config: ${l}`))}function Dh(t){return!(!t||!t.trim()||q.isAbsolute(t)||/^(https?:\/\/|git@|ssh:\/\/)/i.test(t))}function bu(t,e){let n=q.relative(t,e);return n!==".."&&!n.startsWith(`..${q.sep}`)&&!q.isAbsolute(n)}async function LO(t){return(await Fe.promises.readdir(t)).length===0}async function MO(t,e,n,r){let s=q.join(e,Ce.AGENT_CONSTANTS.MANIFEST_FILE);if(await(0,Ee.pathExists)(s))try{let o=(await(0,Mh.loadAgentManifest)(s)).spec?.data;if(!o)return;let a=o.sourcePath?.trim()||"./data",c=(o.workspacePath?.trim()||`.${q.sep}${Ce.AGENT_CONSTANTS.AGENTIDE_DIR_NAME}${q.sep}data${q.sep}${n}`).replace(/^(?:\.\/|\.\\)/,"");if(!Dh(a)||!Dh(c)){Rt(r,`[AgentIDE] Skipping data sync for ${n}: invalid spec.data paths`);return}let l=q.resolve(e,a),f=q.resolve(t,c);if(!bu(e,l)||!bu(t,f)){Rt(r,`[AgentIDE] Skipping data sync for ${n}: path escapes allowed root`);return}if(!await(0,Ee.pathExists)(l))return;if(!await(0,Ee.pathExists)(f)){await(0,Ee.copyDirRecursive)(l,f),Rt(r,`[AgentIDE] Seeded pack data for ${n}: ${f}`);return}(await Fe.promises.stat(f)).isDirectory()&&await LO(f)&&(await(0,Ee.copyDirRecursive)(l,f),Rt(r,`[AgentIDE] Seeded pack data for ${n}: ${f}`))}catch(i){Rt(r,`[AgentIDE] Skipping data sync for ${n}: ${i instanceof Error?i.message:String(i)}`)}}async function GO(t){let e=q.join(t,"SKILL.md");try{if((await Fe.promises.lstat(e)).isSymbolicLink()){let r=await Fe.promises.readlink(e),s=q.isAbsolute(r)?r:q.resolve(q.dirname(e),r);if(q.resolve(s)===q.resolve(e))return!1}return await Fe.promises.access(e),!0}catch{return!1}}async function UO(t,e,n){let r=q.join(t,"skills");if(!await(0,Ee.pathExists)(r))return;await Fe.promises.mkdir(e,{recursive:!0});let s=await Fe.promises.readdir(r,{withFileTypes:!0});for(let i of s){if(!i.isDirectory())continue;let o=q.join(e,i.name);await(0,Ee.pathExists)(o)&&await GO(o)||(await(0,Ee.pathExists)(o)&&await Fe.promises.rm(o,{recursive:!0,force:!0}),await(0,Ee.copyDirRecursive)(q.join(r,i.name),o),Rt(n,`[AgentIDE] Bootstrapped bundled skill: ${i.name}`))}}async function HO(t,e,n,r,s,i){let o=kO.AGENT_ENGINES[r],a=o?{workspaceDir:o.workspaceDir,rulesFile:o.rulesFile,includeSkills:!0,includeRules:!0}:(()=>{let A=(0,DO.tryResolveCustomEngineManifest)(t,r);if(!A)throw new Error(`Unknown engine: ${r}`);if(A.workspaceSync?.enabled)return{workspaceDir:A.workspaceSync.dir,rulesFile:A.workspaceSync.rulesFile,includeSkills:A.workspaceSync.includeSkills,includeRules:A.workspaceSync.includeRules}})(),c=q.join(e,"AGENTS.md"),l=q.join(e,"context.md"),f=q.join(e,"skills"),u=q.join(e,"rules");await(0,Ee.ensureWorkspaceGitAndGitignore)(t,s);let d=q.join(t,Ce.AGENT_CONSTANTS.AGENTIDE_DIR_NAME,Ce.AGENT_CONSTANTS.AGENTS_DIR,n);if(await Fe.promises.mkdir(d,{recursive:!0}),await(0,Ee.pathExists)(c)){let A=await Fe.promises.readFile(c,"utf8");await(0,Ee.writeFileIfChanged)(q.join(d,Ce.AGENT_CONSTANTS.AGENTS_MD),A)}if(await(0,Ee.pathExists)(l)){let A=await Fe.promises.readFile(l,"utf8");await(0,Ee.writeFileIfChanged)(q.join(d,Ce.AGENT_CONSTANTS.CONTEXT_MD),A)}let p=q.join(e,Ce.AGENT_CONSTANTS.GHOST_TEXT_FILE);if(await(0,Ee.pathExists)(p)){let A=await Fe.promises.readFile(p,"utf8");await(0,Ee.writeFileIfChanged)(q.join(d,Ce.AGENT_CONSTANTS.GHOST_TEXT_FILE),A),Rt(s,`[AgentIDE] Synced GHOST_TEXT.md to ${Ce.AGENT_CONSTANTS.AGENTIDE_DIR_NAME}`)}let g=q.join(d,Ce.AGENT_CONSTANTS.SKILLS_DIR),m=q.resolve(f),h=q.resolve(g);await(0,Ee.pathExists)(f)&&(m===h?Rt(s,`[AgentIDE] Skipping skills self-sync (pack already under ${Ce.AGENT_CONSTANTS.AGENTIDE_DIR_NAME}/agents/${n})`):(await(0,Ee.syncDirByFileLinks)(f,g,s,`${Ce.AGENT_CONSTANTS.AGENTIDE_DIR_NAME}/agents/${n}/skills`),Rt(s,`[AgentIDE] Synced skills to ${Ce.AGENT_CONSTANTS.AGENTIDE_DIR_NAME}: ${g}`))),i&&await UO(i,g,s);let E=q.join(d,Ce.AGENT_CONSTANTS.RULES_DIR);if(await(0,Ee.pathExists)(u)){await Fe.promises.mkdir(E,{recursive:!0});let A=await Fe.promises.readdir(u,{withFileTypes:!0});for(let v of A){if(!v.isFile()||!v.name.toLowerCase().endsWith(".md"))continue;let C=q.join(u,v.name),B=q.join(E,v.name);await(0,Ee.symlinkOrCopyFile)(C,B,s,`rules/${v.name}`,{force:!0})}}if(n===Ce.AGENT_CONSTANTS.DEFAULT_AGENT_ID&&i){let A=await(0,$O.getDefaultMcpConfig)(i);if(A){let v=q.join(d,Ce.AGENT_CONSTANTS.MCP_DIR);await Fe.promises.mkdir(v,{recursive:!0});let C=q.join(v,".mcp.json");await(0,Ee.writeFileIfChanged)(C,A),Rt(s,`[AgentIDE] Synced MCP config: ${C}`)}}if(await Gh(e,t,n,s),await MO(t,e,n,s),!a)return;let _=q.join(t,a.workspaceDir);await Fe.promises.mkdir(_,{recursive:!0});let y="";if(await(0,Ee.pathExists)(c)&&(y=await Fe.promises.readFile(c,"utf8")),await(0,Ee.pathExists)(l)){let A=await Fe.promises.readFile(l,"utf8");y=y.trimEnd()+`
82
+ `),m=fn.join(e,"agentide.runtime.md");return await(0,ze.writeFileIfChanged)(m,g),m}async syncCodexSkillsToCodexHome(e,n,r,s,i){let o=fn.join(n,ri.AGENT_CONSTANTS.AGENTIDE_DIR_NAME,"agents",r,"skills"),a=fn.join(e,"skills");if(i){let f=this.lastCodexSkillsSignatureByWorkspaceRoot.get(n),u=await(0,ze.pathExists)(a);if(f===i&&u){s.debug(`[AgentIDE] Codex skills unchanged (sig=${i}), skipping $CODEX_HOME sync`);return}}try{await Vn.promises.rm(a,{recursive:!0,force:!0})}catch{}if(!await(0,ze.pathExists)(o))return;await Vn.promises.mkdir(a,{recursive:!0});let c=0,l=await Vn.promises.readdir(o,{withFileTypes:!0});for(let f of l){if(!f.isDirectory()||f.name.startsWith("."))continue;let u=fn.join(o,f.name),d=fn.join(u,"SKILL.md");await(0,ze.pathExists)(d)&&(await(0,ze.copyDirRecursive)(u,fn.join(a,f.name)),c++)}i&&this.lastCodexSkillsSignatureByWorkspaceRoot.set(n,i),s.info(`[AgentIDE] Codex skills synced to $CODEX_HOME: ${c} skill(s)`)}};_r.CodexEngine=Tu});var Dh=S(Mr=>{"use strict";var yO=Mr&&Mr.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,s)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),wO=Mr&&Mr.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),AO=Mr&&Mr.__importStar||(function(){var t=function(e){return t=Object.getOwnPropertyNames||function(n){var r=[];for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(r[r.length]=s);return r},t(e)};return function(e){if(e&&e.__esModule)return e;var n={};if(e!=null)for(var r=t(e),s=0;s<r.length;s++)r[s]!=="default"&&yO(n,e,r[s]);return wO(n,e),n}})();Object.defineProperty(Mr,"__esModule",{value:!0});Mr.ClaudeEngine=void 0;var SO=require("fs"),ec=AO(require("path")),TO=Ke(),wo=zs(),si=en(),Ch=su(),kh=fo(),bO=Er(),tc=Js(),nc=du(),vO=Is(),$h=Ta(),OO=new Set(["Write","Edit","FileEdit","FileWrite","MultiEdit","str_replace_editor","Str_replace_editor","TextEditor","text_editor","Bash","bash","shell","Shell"]),IO=1e3*60*30;function PO(t,e){return async(n,r)=>{if(n==="AskUserQuestion"){let s=r,i=s?.questions??[];if(i.length===0)return e.warn("[AgentIDE] AskUserQuestion with no questions"),{behavior:"allow",updatedInput:{...s,answers:{}}};let o={};for(let a of i){let c={questionId:`ask-${Date.now()}-${Math.random().toString(36).slice(2,9)}`,prompt:a.question,options:a.options?.map(u=>({label:u.label,description:u.description})),multiSelect:a.multiSelect},l=await t.question(c);if(l.declined||l.cancelled)return{behavior:"deny",message:"User declined or cancelled the question."};let f=l.freeText??l.selected.join(", ");o[a.question]=f}return{behavior:"allow",updatedInput:{questions:s.questions,answers:o}}}return{behavior:"allow",updatedInput:r}}}var NO="AGENTIDE_CONTEXT_EXPORT_PATH",RO="AGENTIDE_TERMINAL_LOG_PATH";function CO(){let t=!1,e=[],n=[];return{enqueue(r){if(t)throw new Error("Cannot enqueue into a closed queue");let s=n.shift();if(s){s({value:r,done:!1});return}e.push(r)},close(){for(t=!0;n.length;)n.shift()?.({value:void 0,done:!0})},[Symbol.asyncIterator](){return{next(){if(e.length){let r=e.shift();return Promise.resolve({value:r,done:!1})}return t?Promise.resolve({value:void 0,done:!0}):new Promise(r=>n.push(r))}}}}}function kO(t){let e=CO(),n=new AbortController,r=t.queryFn({prompt:e,options:{...t.options,abortController:n,resume:t.resumeSessionId}}),s=r[Symbol.asyncIterator](),i=!1,o=t.resumeSessionId??null;return{get sessionId(){return o},async setMaxThinkingTokens(a){if(i)throw new Error("Cannot setMaxThinkingTokens on closed Claude session");await r.setMaxThinkingTokens(a)},async interrupt(){if(!i)try{await r.interrupt()}catch{}},async send(a){if(i)throw new Error("Cannot send to closed Claude session");let c;typeof a=="string"?c={type:"user",session_id:"",message:{role:"user",content:[{type:"text",text:a}]},parent_tool_use_id:null}:c=a,e.enqueue(c)},async*receive(){for(;;){let{value:a,done:c}=await s.next();if(c)return;let l=a;if(l.type==="system"&&l.subtype==="init"&&(o=l.session_id),yield l,l.type==="result")return}},close(){i||(i=!0,e.close(),n.abort())}}}var bu=class{config;computeAgentideSignature;getBundledBasePromptsDir;id="claude";displayName="Claude";activeSessions=new Map;constructor(e,n,r){this.config=e,this.computeAgentideSignature=n,this.getBundledBasePromptsDir=r}async stream(e,n,r,s,i){let o=s.logger,a=s.editTracker,{apiKey:c,baseUrl:l,useLiteLLM:f}=(0,si.resolveApiRouting)(n,this.config,"anthropic");if(!c)throw new Error("Claude API key not provided");o.info(`[AgentIDE] Claude using ${f?"LiteLLM proxy":"direct Anthropic"}, baseUrl: ${l||"default"}, workspaceRoot=${n.workspaceRoot}, additionalDirs=${n.additionalDirectories?.length??0}`),await r.progress("Thinking...");let u=(0,wo.buildLiteLLMMetadataHeaders)(f,{sessionId:n.sessionId,analyticsUserId:n.analyticsUserId,analyticsProjectId:(0,wo.resolveAnalyticsProjectId)(n.analyticsProjectId,n.workspaceRoot),agentId:n.agentPackId??"default",agentVersion:n.agentPackVersion??"workspace",source:"agenthippo",engine:"claude",requestId:n.requestId,policyVersion:n.policyVersion,packDigest:n.packDigest,instanceId:n.instanceId,engineVersion:n.engineVersion,tier:n.tier}),d={...process.env,...s.cliEnvPatch??{},DEBUG_CLAUDE_AGENT_SDK:"1",CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC:"1"};if(delete d[bO.OPENCLAW_GATEWAY_TOKEN_ENV],delete d.AGENTHIPPO_DATA_PLANE_TOKEN,(0,$h.isAnthropicSetupToken)(c)){let C=(0,$h.normalizeAnthropicSetupToken)(c);d.CLAUDE_CODE_OAUTH_TOKEN=C,delete d.ANTHROPIC_AUTH_TOKEN,delete d.ANTHROPIC_API_KEY,o.info("[AgentIDE] Claude using setup-token auth (CLAUDE_CODE_OAUTH_TOKEN)")}else d.ANTHROPIC_API_KEY=c,d.ANTHROPIC_AUTH_TOKEN=c,delete d.CLAUDE_CODE_OAUTH_TOKEN;let g=n.sessionId?.trim(),m=n.contextSessionId?.trim()||g;m&&(d[NO]=ec.join(n.workspaceRoot,nc.AGENT_CONSTANTS.AGENTIDE_DIR_NAME,"sessions",m,"context.md"),d[RO]=ec.join(n.workspaceRoot,nc.AGENT_CONSTANTS.AGENTIDE_DIR_NAME,"sessions",m,"terminal.md"));let h=n.agentPackId??"default",E=(0,nc.resolveRuntimePaths)(n.workspaceRoot,this.config.storagePath,h,n.agentPackVersion),_=(0,nc.userScopedEngineHomeFromKey)(E.claudeConfigDir,(0,vO.resolveEngineHomeUserKey)(n.engineHomeUserKey));if(d.CLAUDE_CONFIG_DIR=_,await SO.promises.mkdir(_,{recursive:!0}),d.AGENT_ID=h,n.agentPackVersion&&(d.AGENTIDE_AGENT_VERSION=n.agentPackVersion),h!=="default"?o.info(`[AgentIDE] Claude using agent: ${h}, CLAUDE_CONFIG_DIR=${_} (agent-isolated)`):o.info(`[AgentIDE] Claude using default agent, CLAUDE_CONFIG_DIR=${_}`),u.length>0&&(d.ANTHROPIC_CUSTOM_HEADERS=u.join(`
83
+ `)),l&&l!=="https://api.anthropic.com/v1"){let C=l.endsWith("/v1")?l.slice(0,-3):l;d.ANTHROPIC_BASE_URL=C,o.info(`[AgentIDE] Using custom Anthropic base URL: ${C}`),(0,si.applyLocalTlsBypass)(d,C)&&o.info("[AgentIDE] Disabling TLS verification for local HTTPS")}let T=n.modelId;if(!T)throw new Error("Claude modelId not provided for streaming request");o.info(`[AgentIDE] Using Claude model: ${T}`);let O="",A=async C=>{if(!C)return;let B=O.length,R=C.length;if(B===0){O=C,await r.text(C);return}if(R===B){if(C===O){o.debug("[AgentIDE] Claude: exact duplicate, skipping");return}}else if(R>B){if(C.startsWith(O)){let F=C.slice(B);O=C,o.debug(`[AgentIDE] Claude: emitting remainder (${F.length} chars)`),await r.text(F);return}}else if(O.endsWith(C)){o.debug("[AgentIDE] Claude: suffix already streamed, skipping");return}O=C,await r.text(C)},v=(0,tc.buildConversationKey)("claude",n);o.info(`[AgentIDE] Claude conversationKey=${v.key} (chatSessionId=${v.chatSessionId}, signature=${v.signatureHash}${v.isEphemeral?", ephemeral":""})`),await(0,tc.withConversationLock)(v.key,async()=>{let C=(0,si.getAgentideEngineSettings)(s?.configProvider),B=typeof C.claudeMaxThinkingTokens=="number"&&C.claudeMaxThinkingTokens>0?Math.floor(C.claudeMaxThinkingTokens):null;o.debug(`[AgentIDE] Claude maxThinkingTokens=${B??"default/disabled"}`);let R=(C.claudeCheapModel||"").trim();R&&(d.ANTHROPIC_DEFAULT_HAIKU_MODEL=R,d.CLAUDE_CODE_SUBAGENT_MODEL=R,o.debug(`[AgentIDE] Claude cheapModel=${R}`));let F=n.permissions??Ch.DEFAULT_PERMISSIONS;o.debug(`[AgentIDE] Claude permissions: fileAccess=${F.fileAccess}`);let re=(0,si.stableAdditionalDirs)([n.workspaceRoot,...n.additionalDirectories??[]]),W=(0,Ch.toClaudeOptions)(F,re);o.debug(`[AgentIDE] Claude mapped: permissionMode=${W.permissionMode}, allowDangerouslySkipPermissions=${W.allowDangerouslySkipPermissions}, dirs=${W.additionalDirectories?.length??"undefined"}`);let de=(0,si.stableAdditionalDirs)([...W.additionalDirectories??[],_]),he=await this.computeAgentideSignature(n.workspaceRoot,n.additionalDirectories),Q=n.sessionId,Ne=n.workspaceRoot,We={current:null},Me=j=>{let pe=j.trim();return/(?:^|&&|\||;)\s*git\s+/.test(pe)},on=(j,pe)=>{let dt=pe;if(!dt)return[];if(j==="Bash"){let Yt=dt.command;return Yt?Me(Yt)?[]:(0,si.extractFilePaths)(Yt,Ne):[]}let oe=dt.file_path??dt.path;return oe?[ec.isAbsolute(oe)?oe:ec.join(Ne,oe)]:[]},ye={continue:!0},cr=async(j,pe,dt)=>{try{o.debug(`[AgentIDE] PreToolUse hook called: toolUseID=${pe}, event=${j.hook_event_name}`);let oe=We.current;if(!oe)return o.debug("[AgentIDE] PreToolUse: no edit state"),ye;if(oe.aborted)return o.debug("[AgentIDE] PreToolUse: aborted"),ye;if(j.hook_event_name!=="PreToolUse")return o.debug(`[AgentIDE] PreToolUse: wrong event ${j.hook_event_name}`),ye;if(!Q)return o.debug("[AgentIDE] PreToolUse: no rawChatSessionId"),ye;if(!a)return o.debug("[AgentIDE] PreToolUse: no edit tracker available"),ye;let _t=j.tool_name;if(!OO.has(_t))return o.debug(`[AgentIDE] PreToolUse: tool ${_t} not tracked (not in FILE_TOOLS)`),ye;let Yt=j.tool_use_id,Xt=on(_t,j.tool_input).filter(Jt=>!(0,si.isBinaryFile)(Jt));if(o.debug(`[AgentIDE] PreToolUse: ${_t} files=${Xt.length}: ${Xt.join(", ")}`),Xt.length===0)return ye;o.debug(`[AgentIDE] PreToolUse: calling startTracking for ${Xt.length} files`);try{let Jt=await a.startTracking(Q,Xt);Jt?.operationId!==void 0&&oe&&!oe.aborted&&(o.debug(`[AgentIDE] PreToolUse: startTracking returned opId=${Jt.operationId}`),oe.pendingOperations.set(Yt,Jt.operationId))}catch(Jt){o.warn(`[AgentIDE] PreToolUse: startTracking failed: ${Jt}`)}return ye}catch(oe){return o.error("[AgentIDE] PreToolUse hook EXCEPTION",oe instanceof Error?oe:void 0),ye}},ut=async(j,pe,dt)=>{try{o.debug(`[AgentIDE] PostToolUse hook called: toolUseID=${pe}, event=${j.hook_event_name}`);let oe=We.current;if(!oe||oe.aborted||j.hook_event_name!=="PostToolUse"||!Q||!a)return ye;let _t=j.tool_use_id;if(!_t)return ye;let Yt=oe.pendingOperations.get(_t);if(o.debug(`[AgentIDE] PostToolUse: toolUseId=${_t} opId=${Yt}`),Yt!==void 0){oe.pendingOperations.delete(_t);try{await a.stopTracking(Q,Yt),o.debug("[AgentIDE] PostToolUse: stopTracking done")}catch(Xt){o.warn(`[AgentIDE] PostToolUse: stopTracking failed: ${Xt}`)}}return ye}catch(oe){return o.error("[AgentIDE] PostToolUse hook EXCEPTION",oe instanceof Error?oe:void 0),ye}};o.debug(`[AgentIDE] Setting up Claude hooks for session ${Q}`);let qt=async(j,pe,dt)=>(o.debug(`[AgentIDE] SessionStart hook called! event=${j.hook_event_name}`),ye),En=await this.loadMcpServersForClaude(o,n.workspaceRoot,h,d),Dn=n.workspaceRoot,Et=h!=="default"?["project"]:["user","project"],It=W.allowDangerouslySkipPermissions===!0?!0:void 0,Pt={model:T,cwd:Dn,additionalDirectories:de,settingSources:Et,env:d,permissionMode:W.permissionMode,allowDangerouslySkipPermissions:It,includePartialMessages:!0,persistSession:!0,...B?{maxThinkingTokens:B}:{},...Object.keys(En).length>0?{mcpServers:En}:{},...this.config.claudeCodeExecutablePath?{pathToClaudeCodeExecutable:this.config.claudeCodeExecutablePath}:{},canUseTool:PO(r,o),hooks:{SessionStart:[{hooks:[qt]}],PreToolUse:[{hooks:[cr]}],PostToolUse:[{hooks:[ut]}]},stderr:j=>{o.debug(`[AgentIDE] Claude CLI stderr: ${j}`)}},vs=await this.getOrCreateSession({conversationKey:v.key,chatSessionId:v.chatSessionId,signatureHash:v.signatureHash,signatureRaw:v.signatureRaw,agentideSignature:he,isEphemeral:v.isEphemeral,modelId:T,cheapModel:R||void 0,queryOptions:Pt,logger:o}),K=vs.session,Ut=vs.editTrackingState;We.current=Ut;let I=!1,Z=()=>{I=!0,Ut.aborted=!0;let j=Array.from(Ut.pendingOperations.values());if(Ut.pendingOperations.clear(),Q&&j.length>0&&a)for(let pe of j)a.stopTracking(Q,pe).catch(()=>{});o.info("[AgentIDE] Claude cancel requested; interrupting session..."),K.interrupt().catch(()=>{try{K.close()}catch{}})};if(i?.aborted){Z();return}i?.addEventListener("abort",Z,{once:!0});try{try{await K.setMaxThinkingTokens(B),o.debug(`[AgentIDE] Claude setMaxThinkingTokens(${B??"null"}) ok`)}catch(z){o.warn(`[AgentIDE] Claude setMaxThinkingTokens(${B??"null"}) failed: ${z instanceof Error?z.message:String(z)}`)}await K.send(e);let j=0,pe=0,dt=0,oe=0,_t=0,Yt=0,Xt=0,Jt=0,rs=new Set,Ti=new Set,ro=new Set,lr=new Map,ia=new Map,so=new Map,oa=new Map,io=z=>z.replace(/\r/g,"").replace(/\n/g,"\\n").slice(0,160),Cr=(z,M)=>{if(typeof M=="string")return M.trim()?M:void 0;if(!M||typeof M!="object")return;let we=M,ke=we.command;if(typeof ke=="string"&&ke.trim())return ke.trim();let Xe=we.args;if(Array.isArray(Xe)&&Xe.every(fe=>typeof fe=="string"))return Xe.join(" ");let me=we.location,Ie=me&&typeof me=="object"?me.path:void 0,yt=we.path??we.file_path??we.file??we.filename??Ie,et=[];typeof yt=="string"&&yt.trim()&&et.push(yt.trim());let tt=we.content;typeof tt=="string"&&et.push(`contentBytes=${Buffer.byteLength(tt,"utf8")}`);let Ae=we.patch??we.diff;if(typeof Ae=="string"&&et.push(`patchBytes=${Buffer.byteLength(Ae,"utf8")}`),et.length>0)return et.join(" ");let je=300,Ht=30,vi=4,Ln=(fe,_n)=>{if(typeof fe=="string")return fe.length>je?`${fe.slice(0,je)}\u2026 (${fe.length} chars)`:fe;if(typeof fe=="number"||typeof fe=="boolean"||fe===null)return fe;if(Array.isArray(fe)){if(_n>=vi)return`[Array(${fe.length})]`;let Mn=fe.slice(0,Ht).map(yn=>Ln(yn,_n+1));return fe.length>Ht?[...Mn,`\u2026 (${fe.length-Ht} more)`]:Mn}if(typeof fe=="object"&&fe){if(_n>=vi)return"[Object]";let Mn={};for(let[yn,is]of Object.entries(fe)){if(typeof is=="string"&&/content|text|data|body|patch|diff/i.test(yn)&&is.length>je){Mn[yn]=`<${Buffer.byteLength(is,"utf8")} bytes>`;continue}Mn[yn]=Ln(is,_n+1)}return Mn}};try{let fe=JSON.stringify(Ln(M,0),null,2),_n=fe.trim();return _n==="{}"||_n==="[]"?void 0:fe}catch{return}},oo=z=>{if(!z||typeof z!="object")return;let M=z,we=M.type;if(we==="tool_use"||we==="server_tool_use"){let ke=M.id,Xe=M.name,me=M.input;return typeof ke=="string"&&typeof Xe=="string"?{id:ke,name:Xe,input:me}:void 0}if(we==="mcp_tool_use"){let ke=M.id,Xe=M.name,me=M.server_name,Ie=M.input;if(typeof ke=="string"&&typeof Xe=="string"&&typeof me=="string")return{id:ke,name:`${me}.${Xe}`,input:Ie}}},ss=z=>{if(typeof z=="string")return z;if(z!=null)try{return JSON.stringify(z,null,2)}catch{return String(z)}},ur=z=>{if(typeof z=="string")return z;if(Array.isArray(z)){let M=[];for(let ke of z){if(typeof ke=="string"){M.push(ke);continue}if(!ke||typeof ke!="object")continue;let Xe=ke;if(typeof Xe.text=="string"){M.push(Xe.text);continue}let me=ss(ke);me&&M.push(me)}return M.join(`
84
+ `).trim()||void 0}if(z&&typeof z=="object"){let M=z;if(typeof M.text=="string")return M.text}return ss(z)},bi=z=>{if(!z||typeof z!="object")return;let M=z,we=M.type;if(we!=="tool_result"&&we!=="server_tool_result"&&we!=="mcp_tool_result")return;let ke=M.tool_use_id;if(typeof ke!="string"||!ke)return;let Xe=ur(M.content??M.result??M.output??M.data??M.text),me=typeof M.is_error=="boolean"?M.is_error:typeof M.isError=="boolean"?M.isError:void 0;return{toolUseId:ke,resultText:Xe,isError:me}},Ws=async(z,M,we)=>{if(!(!rs.has(M)||!!we&&!Ti.has(M))){lr.set(M,z);return}Yt++,rs.add(M),we&&Ti.add(M),lr.set(M,z),I||await r.toolStart(z,we,M)},zt=async(z,M,we,ke)=>{if(ro.has(z))return;let Xe=lr.get(z)??ke??"tool";rs.has(z)||await Ws(Xe,z),ro.add(z),lr.delete(z),I||await r.toolEnd(Xe,z,M,we)},aa=!1,ao=0;for await(let z of K.receive()){ao++;let M=z,we=M.session_id;!aa&&we&&(aa=!0,await(0,wo.persistSessionIfNeeded)("claude",v,we,n));let ke=M.type==="result"||M.type==="system"?M.subtype:void 0;if(o.debug(`[AgentIDE] Claude msg #${ao}: type=${M.type}, subtype=${ke||"none"}`),I&&M.type!=="result")continue;if(M.type==="stream_event"){let me=M.event,Ie=me.type;if(Ie==="content_block_start"){let yt=me.content_block,et=yt?.type,tt=me.index;if(et==="thinking"){let Ae=yt?.thinking;dt++,typeof Ae=="string"&&Ae?(pe+=Ae.length,o.debug(`[AgentIDE] Claude thinking block start (${Ae.length} chars): ${io(Ae)}`),I||await r.thinking(Ae)):o.debug("[AgentIDE] Claude thinking block start (no initial thinking text)")}else if(et==="redacted_thinking"){oe++;let Ae=yt?.data;o.debug(`[AgentIDE] Claude redacted_thinking block start (dataType=${typeof Ae})`)}else{let Ae=bi(me.content_block);if(Ae){await zt(Ae.toolUseId,Ae.resultText,Ae.isError);continue}let je=oo(me.content_block);if(je&&(_t++,typeof tt=="number"&&(ia.set(tt,je.id),so.set(tt,je.name)),!rs.has(je.id))){let Ht=Cr(je.name,je.input);o.debug(`[AgentIDE] Claude tool_use start: ${je.name} (id=${je.id}, input=${Ht?"yes":"no"})`),await Ws(je.name,je.id,Ht)}}}else if(Ie==="content_block_delta"){let yt=me.delta,et=yt.type,tt=yt.thinking,Ae=yt.text;if(et==="thinking_delta"&&typeof tt=="string"&&tt)j++,pe+=tt.length,j<=3&&o.debug(`[AgentIDE] Claude thinking delta #${j} (${tt.length} chars): ${io(tt)}`),I||await r.thinking(tt);else if(et==="input_json_delta"){let je=me.index,Ht=yt.partial_json;if(typeof je=="number"&&typeof Ht=="string"&&Ht){Jt++;let Ln=(oa.get(je)??"")+Ht;oa.set(je,Ln);let fe=ia.get(je);if(fe&&!Ti.has(fe))try{let _n=JSON.parse(Ln),Mn=so.get(je)??"tool",yn=Cr(Mn,_n);yn&&(o.debug(`[AgentIDE] Claude tool_use input_json parsed: ${Mn} (id=${fe})`),await Ws(Mn,fe,yn))}catch{}}}else et==="text_delta"&&typeof Ae=="string"&&Ae&&(O+=Ae,I||await r.text(Ae))}}else if(M.type==="assistant"){let me=M.message.content;if(Array.isArray(me))for(let Ie of me){let yt=Ie.type,et=Ie.text,tt=bi(Ie);if(tt){await zt(tt.toolUseId,tt.resultText,tt.isError);continue}let Ae=oo(Ie);if(Ae&&!rs.has(Ae.id)){_t++;let je=Cr(Ae.name,Ae.input);o.debug(`[AgentIDE] Claude tool_use (assistant msg): ${Ae.name} (id=${Ae.id}, input=${je?"yes":"no"})`),await Ws(Ae.name,Ae.id,je);continue}yt==="text"&&typeof et=="string"&&et&&(I||await A(et))}}else if(M.type==="tool_progress"){Xt++;let me=M.tool_use_id,Ie=M.tool_name||"tool";me&&!rs.has(me)&&(o.debug(`[AgentIDE] Claude tool_progress: ${Ie} (tool_use_id=${me})`),await Ws(Ie,me))}else if(M.type==="system")M.subtype==="status"&&M.status==="compacting"&&(I||await r.progress("Compacting context\u2026"));else if(M.type==="result"){if(M.subtype==="success")I||await A(M.result);else if(!I)throw new Error(M.errors?.join(`
85
+ `)||M.subtype)}let Xe=M.message?.content;if(M.type!=="assistant"&&Array.isArray(Xe))for(let me of Xe){let Ie=bi(me);Ie&&await zt(Ie.toolUseId,Ie.resultText,Ie.isError)}}for(let[z,M]of Array.from(lr.entries()))await zt(z,"Completed",!1,M);o.info(`[AgentIDE] Claude thinking summary: startBlocks=${dt}, redactedBlocks=${oe}, deltas=${j}, chars=${pe}`),o.info(`[AgentIDE] Claude tool summary: toolBlocks=${_t}, toolEmits=${Yt}, toolProgressMsgs=${Xt}, inputJsonDeltas=${Jt}`),dt===0&&j===0&&oe===0&&o.debug(`[AgentIDE] Claude emitted no thinking blocks/deltas. Ensure model supports extended thinking and set ${(0,TO.toSettingsDisplayKey)("agentide.claude.maxThinkingTokens")} >= 1024.`),_t===0&&Xt===0&&o.debug("[AgentIDE] Claude emitted no tool usage events. If tools were used, ensure includePartialMessages=true and parse tool_use blocks."),(0,wo.touchSessionIfNeeded)(v)}catch(j){if(!I)throw j;o.info(`[AgentIDE] Claude stream aborted: ${j instanceof Error?j.message:String(j)}`)}finally{i?.removeEventListener("abort",Z)}},{signal:i,timeoutMs:tc.DEFAULT_CONVERSATION_LOCK_TIMEOUT_MS,label:"claude.stream"}),await r.done(),o.info("[AgentIDE] Claude streaming complete")}dispose(){for(let e of this.activeSessions.values())try{e.session.close()}catch{}this.activeSessions.clear()}onMaintenance(e){this.sweepIdleSessions(e)}sweepIdleSessions(e){let n=Date.now();for(let[r,s]of this.activeSessions.entries())if(n-s.lastUsedAt>IO){try{s.session.close(),e?.info(`[AgentIDE] Closed idle Claude session (key=${r}, idleMs=${n-s.lastUsedAt})`)}catch{}this.activeSessions.delete(r)}}async getOrCreateSession(e){let n=this.activeSessions.get(e.conversationKey);if(n&&n.signatureHash===e.signatureHash&&n.modelId===e.modelId&&n.cheapModel===e.cheapModel&&n.agentideSignature===e.agentideSignature)return n.lastUsedAt=Date.now(),n.editTrackingState.aborted=!1,n.editTrackingState.pendingOperations.clear(),(0,tc.touchPersistedSession)(e.conversationKey),e.logger.debug(`[AgentIDE] REUSING existing Claude session (key=${e.conversationKey}) - NOTE: hooks from original session creation are used, not new ones`),n;let r;if(n){n.signatureHash===e.signatureHash&&n.agentideSignature!==e.agentideSignature&&(e.logger.info(`[AgentIDE] AgentIDE manifest changed (${n.agentideSignature} \u2192 ${e.agentideSignature}), restarting Claude session with resume`),r=n.session.sessionId??void 0),n.modelId!==e.modelId&&(e.logger.info(`[AgentIDE] Model changed (${n.modelId} \u2192 ${e.modelId}), will resume session with new model`),r=n.session.sessionId??void 0),n.cheapModel!==e.cheapModel&&(e.logger.info(`[AgentIDE] Cheap model changed (${n.cheapModel??"unset"} \u2192 ${e.cheapModel??"unset"}), will resume session with updated env`),r=n.session.sessionId??void 0);try{n.session.close()}catch{}this.activeSessions.delete(e.conversationKey)}!r&&!e.isEphemeral&&(r=(0,wo.getPersistedSessionId)("claude",e.conversationKey)),r?e.logger.info(`[AgentIDE] Claude session will resume: ${r} (model: ${e.modelId})`):e.logger.info(`[AgentIDE] Claude session starting new (model: ${e.modelId})`);let s=await import("@anthropic-ai/claude-agent-sdk"),o={session:kO({resumeSessionId:r,queryFn:s.query,options:e.queryOptions}),chatSessionId:e.chatSessionId,signatureHash:e.signatureHash,agentideSignature:e.agentideSignature,modelId:e.modelId,cheapModel:e.cheapModel,lastUsedAt:Date.now(),editTrackingState:{aborted:!1,pendingOperations:new Map}};return this.activeSessions.set(e.conversationKey,o),o}async loadMcpServersForClaude(e,n,r="default",s){let i=this.getBundledBasePromptsDir(),o=await(0,kh.loadMcpServers)(r,n,i);if(o.length===0)return{};let a={};for(let l of o){if(l.url){let f=(0,kh.referenceHttpMcpHeaders)(l,s??process.env);a[l.name]={type:"http",url:l.url,...f?{headers:f}:{}};continue}a[l.name]={command:l.command,args:l.args,...l.env&&Object.keys(l.env).length>0?{env:l.env}:{}}}let c=r==="default"?"bundled":`pack:${r}`;return e.debug(`[AgentIDE] Claude MCP servers loaded (${c}): ${o.map(l=>l.name).join(", ")}`),a}};Mr.ClaudeEngine=bu});var Ou=S(pn=>{"use strict";var $O=pn&&pn.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,s)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),DO=pn&&pn.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),LO=pn&&pn.__importStar||(function(){var t=function(e){return t=Object.getOwnPropertyNames||function(n){var r=[];for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(r[r.length]=s);return r},t(e)};return function(e){if(e&&e.__esModule)return e;var n={};if(e!=null)for(var r=t(e),s=0;s<r.length;s++)r[s]!=="default"&&$O(n,e,r[s]);return DO(n,e),n}})();Object.defineProperty(pn,"__esModule",{value:!0});pn.syncPackMcpToWorkspace=Uh;pn.syncPackToWorkspace=FO;pn.computeSkillsSignature=Hh;pn.createSkillsSignatureGetter=VO;pn.createSessionDir=WO;pn.getSessionDir=KO;var Fe=require("fs"),Y=LO(require("path")),Mh=require("crypto"),Ee=en(),MO=Ta(),Ce=Un(),Gh=Qs(),GO=fo(),UO=Ns();async function Uh(t,e,n,r){let s=Y.join(t,Ce.AGENT_CONSTANTS.MANIFEST_FILE);if(!await(0,Ee.pathExists)(s))return;let i;try{i=await(0,Gh.loadAgentManifest)(s)}catch(u){Rt(r,`[AgentIDE] Skipping pack MCP sync for ${n}: ${u instanceof Error?u.message:String(u)}`);return}let o=i.spec?.mcp;if(!o?.length)return;let a=Y.join(e,Ce.AGENT_CONSTANTS.AGENTIDE_DIR_NAME,Ce.AGENT_CONSTANTS.AGENTS_DIR,n,Ce.AGENT_CONSTANTS.MCP_DIR);await Fe.promises.mkdir(a,{recursive:!0});let c={mcpServers:{}},l=Y.join(a,".mcp.json");for(let u of o){let d=u.config?.trim();if(!d)continue;let p=Y.resolve(t,d);if(!vu(t,p)){Rt(r,`[AgentIDE] Skipping MCP config ${d}: path escapes pack root`);continue}if(!await(0,Ee.pathExists)(p)){Rt(r,`[AgentIDE] Skipping MCP config ${d}: file not found`);continue}try{let m=JSON.parse(await Fe.promises.readFile(p,"utf8")).mcpServers;m&&typeof m=="object"&&Object.assign(c.mcpServers,m)}catch(g){Rt(r,`[AgentIDE] Skipping MCP config ${d}: ${g instanceof Error?g.message:String(g)}`)}}let f=Y.join(t,Ce.AGENT_CONSTANTS.MCP_DIR);if(await(0,Ee.pathExists)(f)){let u=await Fe.promises.readdir(f,{withFileTypes:!0});for(let d of u){if(!d.isDirectory()||d.name.startsWith("."))continue;let p=Y.join(f,d.name),g=Y.join(a,d.name);await(0,Ee.pathExists)(g)||await(0,Ee.copyDirRecursive)(p,g)}}!c.mcpServers||Object.keys(c.mcpServers).length===0||(await(0,Ee.writeFileIfChanged)(l,`${JSON.stringify(c,null,2)}
86
+ `),Rt(r,`[AgentIDE] Synced pack MCP config: ${l}`))}function Lh(t){return!(!t||!t.trim()||Y.isAbsolute(t)||/^(https?:\/\/|git@|ssh:\/\/)/i.test(t))}function vu(t,e){let n=Y.relative(t,e);return n!==".."&&!n.startsWith(`..${Y.sep}`)&&!Y.isAbsolute(n)}async function HO(t){return(await Fe.promises.readdir(t)).length===0}async function jO(t,e,n,r){let s=Y.join(e,Ce.AGENT_CONSTANTS.MANIFEST_FILE);if(await(0,Ee.pathExists)(s))try{let o=(await(0,Gh.loadAgentManifest)(s)).spec?.data;if(!o)return;let a=o.sourcePath?.trim()||"./data",c=(o.workspacePath?.trim()||`.${Y.sep}${Ce.AGENT_CONSTANTS.AGENTIDE_DIR_NAME}${Y.sep}data${Y.sep}${n}`).replace(/^(?:\.\/|\.\\)/,"");if(!Lh(a)||!Lh(c)){Rt(r,`[AgentIDE] Skipping data sync for ${n}: invalid spec.data paths`);return}let l=Y.resolve(e,a),f=Y.resolve(t,c);if(!vu(e,l)||!vu(t,f)){Rt(r,`[AgentIDE] Skipping data sync for ${n}: path escapes allowed root`);return}if(!await(0,Ee.pathExists)(l))return;if(!await(0,Ee.pathExists)(f)){await(0,Ee.copyDirRecursive)(l,f),Rt(r,`[AgentIDE] Seeded pack data for ${n}: ${f}`);return}(await Fe.promises.stat(f)).isDirectory()&&await HO(f)&&(await(0,Ee.copyDirRecursive)(l,f),Rt(r,`[AgentIDE] Seeded pack data for ${n}: ${f}`))}catch(i){Rt(r,`[AgentIDE] Skipping data sync for ${n}: ${i instanceof Error?i.message:String(i)}`)}}async function xO(t){let e=Y.join(t,"SKILL.md");try{if((await Fe.promises.lstat(e)).isSymbolicLink()){let r=await Fe.promises.readlink(e),s=Y.isAbsolute(r)?r:Y.resolve(Y.dirname(e),r);if(Y.resolve(s)===Y.resolve(e))return!1}return await Fe.promises.access(e),!0}catch{return!1}}async function BO(t,e,n){let r=Y.join(t,"skills");if(!await(0,Ee.pathExists)(r))return;await Fe.promises.mkdir(e,{recursive:!0});let s=await Fe.promises.readdir(r,{withFileTypes:!0});for(let i of s){if(!i.isDirectory())continue;let o=Y.join(e,i.name);await(0,Ee.pathExists)(o)&&await xO(o)||(await(0,Ee.pathExists)(o)&&await Fe.promises.rm(o,{recursive:!0,force:!0}),await(0,Ee.copyDirRecursive)(Y.join(r,i.name),o),Rt(n,`[AgentIDE] Bootstrapped bundled skill: ${i.name}`))}}async function FO(t,e,n,r,s,i){let o=MO.AGENT_ENGINES[r],a=o?{workspaceDir:o.workspaceDir,rulesFile:o.rulesFile,includeSkills:!0,includeRules:!0}:(()=>{let A=(0,UO.tryResolveCustomEngineManifest)(t,r);if(!A)throw new Error(`Unknown engine: ${r}`);if(A.workspaceSync?.enabled)return{workspaceDir:A.workspaceSync.dir,rulesFile:A.workspaceSync.rulesFile,includeSkills:A.workspaceSync.includeSkills,includeRules:A.workspaceSync.includeRules}})(),c=Y.join(e,"AGENTS.md"),l=Y.join(e,"context.md"),f=Y.join(e,"skills"),u=Y.join(e,"rules");await(0,Ee.ensureWorkspaceGitAndGitignore)(t,s);let d=Y.join(t,Ce.AGENT_CONSTANTS.AGENTIDE_DIR_NAME,Ce.AGENT_CONSTANTS.AGENTS_DIR,n);if(await Fe.promises.mkdir(d,{recursive:!0}),await(0,Ee.pathExists)(c)){let A=await Fe.promises.readFile(c,"utf8");await(0,Ee.writeFileIfChanged)(Y.join(d,Ce.AGENT_CONSTANTS.AGENTS_MD),A)}if(await(0,Ee.pathExists)(l)){let A=await Fe.promises.readFile(l,"utf8");await(0,Ee.writeFileIfChanged)(Y.join(d,Ce.AGENT_CONSTANTS.CONTEXT_MD),A)}let p=Y.join(e,Ce.AGENT_CONSTANTS.GHOST_TEXT_FILE);if(await(0,Ee.pathExists)(p)){let A=await Fe.promises.readFile(p,"utf8");await(0,Ee.writeFileIfChanged)(Y.join(d,Ce.AGENT_CONSTANTS.GHOST_TEXT_FILE),A),Rt(s,`[AgentIDE] Synced GHOST_TEXT.md to ${Ce.AGENT_CONSTANTS.AGENTIDE_DIR_NAME}`)}let g=Y.join(d,Ce.AGENT_CONSTANTS.SKILLS_DIR),m=Y.resolve(f),h=Y.resolve(g);await(0,Ee.pathExists)(f)&&(m===h?Rt(s,`[AgentIDE] Skipping skills self-sync (pack already under ${Ce.AGENT_CONSTANTS.AGENTIDE_DIR_NAME}/agents/${n})`):(await(0,Ee.syncDirByFileLinks)(f,g,s,`${Ce.AGENT_CONSTANTS.AGENTIDE_DIR_NAME}/agents/${n}/skills`),Rt(s,`[AgentIDE] Synced skills to ${Ce.AGENT_CONSTANTS.AGENTIDE_DIR_NAME}: ${g}`))),i&&await BO(i,g,s);let E=Y.join(d,Ce.AGENT_CONSTANTS.RULES_DIR);if(await(0,Ee.pathExists)(u)){await Fe.promises.mkdir(E,{recursive:!0});let A=await Fe.promises.readdir(u,{withFileTypes:!0});for(let v of A){if(!v.isFile()||!v.name.toLowerCase().endsWith(".md"))continue;let C=Y.join(u,v.name),B=Y.join(E,v.name);await(0,Ee.symlinkOrCopyFile)(C,B,s,`rules/${v.name}`,{force:!0})}}if(n===Ce.AGENT_CONSTANTS.DEFAULT_AGENT_ID&&i){let A=await(0,GO.getDefaultMcpConfig)(i);if(A){let v=Y.join(d,Ce.AGENT_CONSTANTS.MCP_DIR);await Fe.promises.mkdir(v,{recursive:!0});let C=Y.join(v,".mcp.json");await(0,Ee.writeFileIfChanged)(C,A),Rt(s,`[AgentIDE] Synced MCP config: ${C}`)}}if(await Uh(e,t,n,s),await jO(t,e,n,s),!a)return;let _=Y.join(t,a.workspaceDir);await Fe.promises.mkdir(_,{recursive:!0});let y="";if(await(0,Ee.pathExists)(c)&&(y=await Fe.promises.readFile(c,"utf8")),await(0,Ee.pathExists)(l)){let A=await Fe.promises.readFile(l,"utf8");y=y.trimEnd()+`
87
87
 
88
88
  ---
89
89
 
90
90
  `+A.trimEnd()+`
91
- `}let b=q.join(_,a.rulesFile);y&&(await(0,Ee.writeFileIfChanged)(b,y),Rt(s,`[AgentIDE] Synced rules: ${b}`));let T=q.join(_,"skills");a.includeSkills&&await(0,Ee.pathExists)(g)&&await(0,Ee.syncDirByFileLinks)(g,T,s,`${a.workspaceDir}/skills`);let O=q.join(_,"rules");if(a.includeRules&&await(0,Ee.pathExists)(u)){await Fe.promises.mkdir(O,{recursive:!0});let A=await Fe.promises.readdir(u,{withFileTypes:!0});for(let v of A){if(!v.isFile()||!v.name.toLowerCase().endsWith(".md"))continue;let C=q.join(u,v.name),B=q.join(O,v.name);await(0,Ee.symlinkOrCopyFile)(C,B,s,`rules/${v.name}`,{force:!0})}}Rt(s,`[AgentIDE] Pack '${n}' synced to workspace: ${t}`)}function Uh(t,e){let n=q.join(t,Ce.AGENT_CONSTANTS.AGENTIDE_DIR_NAME,Ce.AGENT_CONSTANTS.AGENTS_DIR,e,Ce.AGENT_CONSTANTS.SKILLS_DIR);try{let r=require("fs");if(!r.existsSync(n))return;let s=(0,Lh.createHash)("sha256"),i=r.readdirSync(n,{withFileTypes:!0});for(let o of i){if(!o.isDirectory()||o.name.startsWith("."))continue;let a=q.join(n,o.name,"SKILL.md");if(r.existsSync(a)){let c=r.statSync(a);s.update(`${o.name}:${c.mtimeMs}`)}}return s.digest("hex").slice(0,16)}catch{return}}function jO(t){return e=>Uh(e,t)}async function xO(t){let e=(0,Lh.randomUUID)(),n=q.join(t,Ce.AGENT_CONSTANTS.AGENTIDE_DIR_NAME,Ce.AGENT_CONSTANTS.SESSIONS_DIR,e);return await Fe.promises.mkdir(n,{recursive:!0}),e}function BO(t,e){return q.join(t,Ce.AGENT_CONSTANTS.AGENTIDE_DIR_NAME,Ce.AGENT_CONSTANTS.SESSIONS_DIR,e)}function Rt(t,e){t.appendLine?t.appendLine(e):t.info&&t.info(e)}});var yo=S(pt=>{"use strict";var FO=pt&&pt.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,s)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),VO=pt&&pt.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),xh=pt&&pt.__importStar||(function(){var t=function(e){return t=Object.getOwnPropertyNames||function(n){var r=[];for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(r[r.length]=s);return r},t(e)};return function(e){if(e&&e.__esModule)return e;var n={};if(e!=null)for(var r=t(e),s=0;s<r.length;s++)r[s]!=="default"&&FO(n,e,r[s]);return VO(n,e),n}})();Object.defineProperty(pt,"__esModule",{value:!0});pt.ObservableStreamEmitter=pt.SessionEventWriter=pt.EVIDENCE_REQUIRED_ENV=void 0;pt.getSessionEventWriterStats=qO;pt.resetSessionEventWriterStatsForTest=YO;pt.evidenceRequired=Bh;pt.wrapEmitterWithObservability=XO;var Hh=xh(require("path")),jh=require("fs"),WO=Ke(),KO=xh(require("os")),Ou=Pi(),Gr={written:0,failed:0};function qO(){return{written:Gr.written,failed:Gr.failed,lastError:Gr.lastError}}function YO(){Gr.written=0,Gr.failed=0,Gr.lastError=void 0}pt.EVIDENCE_REQUIRED_ENV="AGENTHIPPO_EVIDENCE_REQUIRED";function Bh(t=process.env){let e=(t[pt.EVIDENCE_REQUIRED_ENV]??"").trim().toLowerCase();return e==="1"||e==="true"||e==="yes"||e==="on"}var Iu=class{baseDir;ensuredDirs=new Set;written=0;failed=0;lastError;sanitizeSessionId(e){let n=e.trim();return n?n.replace(/[\\/]/g,"_").replace(/\.\./g,"_"):`session-${Date.now()}`}constructor(e){this.baseDir=e??Hh.join(KO.homedir(),WO.AGENTIDE_DIR_NAME,"analytics","sessions")}async append(e,n,r,s){try{let i=this.sanitizeSessionId(e);this.ensuredDirs.has(i)||(await jh.promises.mkdir(this.baseDir,{recursive:!0}),this.ensuredDirs.add(i));let o={session_id:e,request_id:n,timestamp:Date.now(),event_type:r,payload:s},a=Hh.join(this.baseDir,`${i}.jsonl`),c=JSON.stringify(o)+`
92
- `;await jh.promises.appendFile(a,c),this.written++,Gr.written++}catch(i){let o=i instanceof Error?i.message:String(i);this.failed++,Gr.failed++;let a={at:Date.now(),message:o,eventType:r};if(this.lastError=a,Gr.lastError=a,console.error(`[evidence] LOST session event ${r} (session=${e} request=${n}): ${o} \u2014 ${Gr.failed} evidence write(s) lost since start`),Bh())throw new Error(`evidence write failed for ${r}: ${o}`)}}getStats(){return{written:this.written,failed:this.failed,lastError:this.lastError}}getSessionsDir(){return this.baseDir}};pt.SessionEventWriter=Iu;var nc=class{inner;writer;sessionId;requestId;stamp;missingCallIdCounter=0;pendingSyntheticCallIds=new Map;actorId;constructor(e,n,r,s,i,o){this.inner=e,this.writer=n,this.sessionId=r,this.requestId=s,this.stamp=o,this.actorId=(0,Ou.hashIdentity)(i)}makeCallIdKey(e){return`${this.sessionId}:${this.requestId}:${e}`}enqueueSyntheticCallId(e){let n=this.makeCallIdKey(e),r=`synthetic-${e}-${++this.missingCallIdCounter}`,s=this.pendingSyntheticCallIds.get(n)??[];return s.push(r),this.pendingSyntheticCallIds.set(n,s),r}dequeueSyntheticCallId(e){let n=this.makeCallIdKey(e),r=this.pendingSyntheticCallIds.get(n);if(!r||r.length===0)return;let s=r.shift();return r.length===0?this.pendingSyntheticCallIds.delete(n):this.pendingSyntheticCallIds.set(n,r),s}async thinking(e){return this.inner.thinking(e)}async text(e){return this.inner.text(e)}async toolStart(e,n,r,s){let i=r?.trim()?r:this.enqueueSyntheticCallId(e);return await this.writer.append(this.sessionId,this.requestId,"tool_start",{toolName:e,callId:i,...(0,Ou.describeContent)("input",n),userId:this.actorId}),this.inner.toolStart(e,n,r,s)}async toolEnd(e,n,r,s,i){let o=n?.trim()?n:this.dequeueSyntheticCallId(e)??"";return await this.writer.append(this.sessionId,this.requestId,"tool_end",{toolName:e,callId:o,isError:s??!1,...(0,Ou.describeContent)("result",r),userId:this.actorId}),this.inner.toolEnd(e,n,r,s,i)}async progress(e){return this.inner.progress(e)}async question(e){return this.inner.question(e)}async error(e){return await this.writer.append(this.sessionId,this.requestId,"error",{message:e,userId:this.actorId}),this.inner.error(e)}async done(){return this.inner.done()}async emitTurnStart(){await this.writer.append(this.sessionId,this.requestId,"turn_start",{userId:this.actorId,...this.stamp})}async emitTurnEnd(e){await this.writer.append(this.sessionId,this.requestId,"turn_end",{success:e,userId:this.actorId})}};pt.ObservableStreamEmitter=nc;function XO(t,e,n,r,s,i){return new nc(t,e,n,r,s,i)}});var rc=S(ii=>{"use strict";Object.defineProperty(ii,"__esModule",{value:!0});ii.encodeRunnerEvent=JO;ii.encodeWorkerRequest=zO;ii.parseWorkerOutbound=QO;ii.applyRunnerEvent=ZO;ii.applyParsedRunnerEvent=Fh;function JO(t){return`${JSON.stringify(t)}
93
- `}function zO(t){return`${JSON.stringify(t)}
94
- `}function QO(t){let e;try{e=JSON.parse(t)}catch{return}if(!e||typeof e!="object")return;let n=e;if(n.type==="ready")return{type:"ready"};if(n.type==="result"&&typeof n.id=="string")return{type:"result",id:n.id,nativeSessionId:typeof n.nativeSessionId=="string"?n.nativeSessionId:void 0};if(n.type==="failed"&&typeof n.id=="string")return{type:"failed",id:n.id,message:typeof n.message=="string"?n.message:"Custom engine turn failed"};if(typeof n.id=="string"&&n.event&&typeof n.event=="object")return{id:n.id,event:n.event}}async function ZO(t,e){let n;try{n=JSON.parse(e)}catch{return}return Fh(t,n)}async function Fh(t,e){switch(e.type){case"text":await t.text(e.delta);break;case"thinking":await t.thinking(e.delta);break;case"toolStart":await t.toolStart(e.toolName,e.input,e.toolCallId);break;case"toolEnd":await t.toolEnd(e.toolName,e.toolCallId,e.result,e.isError);break;case"progress":await t.progress(e.message);break;case"error":await t.error(e.message);break;case"done":await t.done();break;case"nativeSessionId":return e.nativeSessionId;case"probe":if(!e.ok)throw new Error(e.message??"Custom engine import probe failed");break;default:break}}});var Vh=S(sc=>{"use strict";Object.defineProperty(sc,"__esModule",{value:!0});sc.PersistentEngineWorkerPool=void 0;var eI=require("node:child_process"),tI=require("node:readline"),Pu=rc(),nI=1e3*60*30,rI=1e3*60,sI=1e3*30,iI=1e3*10,Nu=class{opts;child;readyPromise;readyResolve;readyReject;pending=new Map;lineChains=new Map;seq=0;stderr="";retired=!1;retireTimer;readyTimer;lastUsedAt=Date.now();constructor(e){this.opts=e}isUsable(){return!this.retired&&this.child!==void 0&&this.child.exitCode===null&&!this.child.killed}ensureStarted(){if(this.readyPromise)return this.readyPromise;this.readyPromise=new Promise((s,i)=>{this.readyResolve=s,this.readyReject=i});let e=(0,eI.spawn)(this.opts.nodeBin,[this.opts.runnerPath],{cwd:this.opts.cwd,env:this.opts.spawnEnv,stdio:["pipe","pipe","pipe"]});this.child=e,this.opts.logger.info(`[AgentIDE] Persistent engine worker started (${this.opts.label}, pid=${e.pid})`);let n=this.opts.startupTimeoutMs??sI;this.readyTimer=setTimeout(()=>{this.opts.logger.warn(`[AgentIDE] Persistent engine worker (${this.opts.label}) did not signal ready within ${n}ms; terminating`),this.handleExit(`worker did not become ready within ${n}ms`)},n),this.readyTimer.unref?.();let r=(0,tI.createInterface)({input:e.stdout});return r.on("line",s=>this.routeLine(s)),e.stderr?.on("data",s=>{this.stderr+=String(s),this.stderr.length>16384&&(this.stderr=this.stderr.slice(-16384))}),e.on("error",s=>this.handleExit(s.message)),e.on("close",s=>{r.close(),this.handleExit(this.stderr.trim()||`worker exited with code ${s}`)}),this.readyPromise}routeLine(e){let n=(0,Pu.parseWorkerOutbound)(e);if(!n)return;if("type"in n&&n.type==="ready"){this.markReady();return}let r="id"in n?n.id:void 0;if(r===void 0)return;let i=(this.lineChains.get(r)??Promise.resolve()).then(()=>this.handleMessage(n)).catch(()=>{});this.lineChains.set(r,i),i.then(()=>{this.lineChains.get(r)===i&&this.lineChains.delete(r)})}async handleMessage(e){if("type"in e){if(e.type==="ready")return;let r=this.pending.get(e.id);if(!r)return;e.type==="result"?(this.finishRun(e.id,r),r.resolve({nativeSessionId:e.nativeSessionId})):(this.finishRun(e.id,r),r.reject(new Error(e.message)),r.aborted||this.retire("turn error"));return}let n=this.pending.get(e.id);n&&await(0,Pu.applyParsedRunnerEvent)(n.emitter,e.event)}markReady(){this.readyTimer&&(clearTimeout(this.readyTimer),this.readyTimer=void 0),this.readyResolve?.()}cleanupRun(e){e.abortTimer&&(clearTimeout(e.abortTimer),e.abortTimer=void 0),e.signal&&e.onAbort&&(e.signal.removeEventListener("abort",e.onAbort),e.onAbort=void 0)}finishRun(e,n){this.cleanupRun(n),this.pending.delete(e),this.retired&&this.pending.size===0&&this.kill()}handleExit(e){this.retireTimer&&(clearTimeout(this.retireTimer),this.retireTimer=void 0),this.readyTimer&&(clearTimeout(this.readyTimer),this.readyTimer=void 0);let n=this.child;if(this.child=void 0,this.retired=!0,n&&n.exitCode===null&&!n.killed)try{n.kill("SIGKILL")}catch{}this.readyReject?.(new Error(`Persistent engine worker failed to start (${this.opts.label}): ${e}`));let r=[...this.pending.entries()];this.pending.clear();for(let[,s]of r)this.cleanupRun(s),s.reject(new Error(`Custom engine worker exited (${this.opts.label}): ${e}`))}retire(e){this.retired||(this.retired=!0,this.opts.logger.info(`[AgentIDE] Retiring persistent engine worker (${this.opts.label}): ${e}`),this.pending.size===0?this.kill():(this.retireTimer=setTimeout(()=>this.kill(),rI),this.retireTimer.unref?.()))}kill(){this.retireTimer&&(clearTimeout(this.retireTimer),this.retireTimer=void 0),this.readyTimer&&(clearTimeout(this.readyTimer),this.readyTimer=void 0);let e=this.child;this.child=void 0,this.retired=!0,!(!e||e.exitCode!==null||e.killed)&&e.kill("SIGTERM")}send(e){this.child?.stdin?.write((0,Pu.encodeWorkerRequest)(e))}async run(e,n,r){await this.ensureStarted(),this.lastUsedAt=Date.now();let s=String(++this.seq);return new Promise((i,o)=>{let a={emitter:n,resolve:i,reject:o,aborted:!1,signal:r},c=()=>{a.aborted=!0,this.send({type:"abort",id:s}),a.abortTimer=setTimeout(()=>{let l=this.pending.get(s);l&&(this.finishRun(s,l),l.reject(new Error("Custom engine turn aborted")))},this.opts.abortSettleTimeoutMs??iI),a.abortTimer.unref?.()};r&&(a.onAbort=c,r.aborted?c():r.addEventListener("abort",c,{once:!0})),this.pending.set(s,a),this.send({type:"run",id:s,env:e})})}isIdle(e){return this.pending.size===0&&e-this.lastUsedAt>(this.opts.idleTtlMs??nI)}},Ru=class{workers=new Map;async run(e,n,r,s){let i=this.workers.get(e.cacheKey);(!i||!i.isUsable())&&(i?.retire("stale or dead"),i=new Nu(e),this.workers.set(e.cacheKey,i));try{return await i.run(n,r,s)}catch(o){throw this.workers.get(e.cacheKey)===i&&!i.isUsable()&&this.workers.delete(e.cacheKey),o}}onMaintenance(){let e=Date.now();for(let[n,r]of this.workers.entries())r.isIdle(e)&&(r.kill(),this.workers.delete(n))}disposeAll(){for(let e of this.workers.values())e.kill();this.workers.clear()}_workerCountForTest(){return this.workers.size}};sc.PersistentEngineWorkerPool=Ru});var Wh=S(ki=>{"use strict";Object.defineProperty(ki,"__esModule",{value:!0});ki.EMBEDDED_CUSTOM_ENGINE_RUNNER_SOURCE=ki.EMBEDDED_CUSTOM_ENGINE_RUNNER_HASH=void 0;ki.EMBEDDED_CUSTOM_ENGINE_RUNNER_HASH="fe3840b3a767b36e";ki.EMBEDDED_CUSTOM_ENGINE_RUNNER_SOURCE=`"use strict";
91
+ `}let b=Y.join(_,a.rulesFile);y&&(await(0,Ee.writeFileIfChanged)(b,y),Rt(s,`[AgentIDE] Synced rules: ${b}`));let T=Y.join(_,"skills");a.includeSkills&&await(0,Ee.pathExists)(g)&&await(0,Ee.syncDirByFileLinks)(g,T,s,`${a.workspaceDir}/skills`);let O=Y.join(_,"rules");if(a.includeRules&&await(0,Ee.pathExists)(u)){await Fe.promises.mkdir(O,{recursive:!0});let A=await Fe.promises.readdir(u,{withFileTypes:!0});for(let v of A){if(!v.isFile()||!v.name.toLowerCase().endsWith(".md"))continue;let C=Y.join(u,v.name),B=Y.join(O,v.name);await(0,Ee.symlinkOrCopyFile)(C,B,s,`rules/${v.name}`,{force:!0})}}Rt(s,`[AgentIDE] Pack '${n}' synced to workspace: ${t}`)}function Hh(t,e){let n=Y.join(t,Ce.AGENT_CONSTANTS.AGENTIDE_DIR_NAME,Ce.AGENT_CONSTANTS.AGENTS_DIR,e,Ce.AGENT_CONSTANTS.SKILLS_DIR);try{let r=require("fs");if(!r.existsSync(n))return;let s=(0,Mh.createHash)("sha256"),i=r.readdirSync(n,{withFileTypes:!0});for(let o of i){if(!o.isDirectory()||o.name.startsWith("."))continue;let a=Y.join(n,o.name,"SKILL.md");if(r.existsSync(a)){let c=r.statSync(a);s.update(`${o.name}:${c.mtimeMs}`)}}return s.digest("hex").slice(0,16)}catch{return}}function VO(t){return e=>Hh(e,t)}async function WO(t){let e=(0,Mh.randomUUID)(),n=Y.join(t,Ce.AGENT_CONSTANTS.AGENTIDE_DIR_NAME,Ce.AGENT_CONSTANTS.SESSIONS_DIR,e);return await Fe.promises.mkdir(n,{recursive:!0}),e}function KO(t,e){return Y.join(t,Ce.AGENT_CONSTANTS.AGENTIDE_DIR_NAME,Ce.AGENT_CONSTANTS.SESSIONS_DIR,e)}function Rt(t,e){t.appendLine?t.appendLine(e):t.info&&t.info(e)}});var Ao=S(pt=>{"use strict";var qO=pt&&pt.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,s)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),YO=pt&&pt.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),Bh=pt&&pt.__importStar||(function(){var t=function(e){return t=Object.getOwnPropertyNames||function(n){var r=[];for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(r[r.length]=s);return r},t(e)};return function(e){if(e&&e.__esModule)return e;var n={};if(e!=null)for(var r=t(e),s=0;s<r.length;s++)r[s]!=="default"&&qO(n,e,r[s]);return YO(n,e),n}})();Object.defineProperty(pt,"__esModule",{value:!0});pt.ObservableStreamEmitter=pt.SessionEventWriter=pt.EVIDENCE_REQUIRED_ENV=void 0;pt.getSessionEventWriterStats=zO;pt.resetSessionEventWriterStatsForTest=QO;pt.evidenceRequired=Fh;pt.wrapEmitterWithObservability=ZO;var jh=Bh(require("path")),xh=require("fs"),XO=Ke(),JO=Bh(require("os")),Iu=Pi(),Gr={written:0,failed:0};function zO(){return{written:Gr.written,failed:Gr.failed,lastError:Gr.lastError}}function QO(){Gr.written=0,Gr.failed=0,Gr.lastError=void 0}pt.EVIDENCE_REQUIRED_ENV="AGENTHIPPO_EVIDENCE_REQUIRED";function Fh(t=process.env){let e=(t[pt.EVIDENCE_REQUIRED_ENV]??"").trim().toLowerCase();return e==="1"||e==="true"||e==="yes"||e==="on"}var Pu=class{baseDir;ensuredDirs=new Set;written=0;failed=0;lastError;sanitizeSessionId(e){let n=e.trim();return n?n.replace(/[\\/]/g,"_").replace(/\.\./g,"_"):`session-${Date.now()}`}constructor(e){this.baseDir=e??jh.join(JO.homedir(),XO.AGENTIDE_DIR_NAME,"analytics","sessions")}async append(e,n,r,s){try{let i=this.sanitizeSessionId(e);this.ensuredDirs.has(i)||(await xh.promises.mkdir(this.baseDir,{recursive:!0}),this.ensuredDirs.add(i));let o={session_id:e,request_id:n,timestamp:Date.now(),event_type:r,payload:s},a=jh.join(this.baseDir,`${i}.jsonl`),c=JSON.stringify(o)+`
92
+ `;await xh.promises.appendFile(a,c),this.written++,Gr.written++}catch(i){let o=i instanceof Error?i.message:String(i);this.failed++,Gr.failed++;let a={at:Date.now(),message:o,eventType:r};if(this.lastError=a,Gr.lastError=a,console.error(`[evidence] LOST session event ${r} (session=${e} request=${n}): ${o} \u2014 ${Gr.failed} evidence write(s) lost since start`),Fh())throw new Error(`evidence write failed for ${r}: ${o}`)}}getStats(){return{written:this.written,failed:this.failed,lastError:this.lastError}}getSessionsDir(){return this.baseDir}};pt.SessionEventWriter=Pu;var rc=class{inner;writer;sessionId;requestId;stamp;missingCallIdCounter=0;pendingSyntheticCallIds=new Map;actorId;constructor(e,n,r,s,i,o){this.inner=e,this.writer=n,this.sessionId=r,this.requestId=s,this.stamp=o,this.actorId=(0,Iu.hashIdentity)(i)}makeCallIdKey(e){return`${this.sessionId}:${this.requestId}:${e}`}enqueueSyntheticCallId(e){let n=this.makeCallIdKey(e),r=`synthetic-${e}-${++this.missingCallIdCounter}`,s=this.pendingSyntheticCallIds.get(n)??[];return s.push(r),this.pendingSyntheticCallIds.set(n,s),r}dequeueSyntheticCallId(e){let n=this.makeCallIdKey(e),r=this.pendingSyntheticCallIds.get(n);if(!r||r.length===0)return;let s=r.shift();return r.length===0?this.pendingSyntheticCallIds.delete(n):this.pendingSyntheticCallIds.set(n,r),s}async thinking(e){return this.inner.thinking(e)}async text(e){return this.inner.text(e)}async toolStart(e,n,r,s){let i=r?.trim()?r:this.enqueueSyntheticCallId(e);return await this.writer.append(this.sessionId,this.requestId,"tool_start",{toolName:e,callId:i,...(0,Iu.describeContent)("input",n),userId:this.actorId}),this.inner.toolStart(e,n,r,s)}async toolEnd(e,n,r,s,i){let o=n?.trim()?n:this.dequeueSyntheticCallId(e)??"";return await this.writer.append(this.sessionId,this.requestId,"tool_end",{toolName:e,callId:o,isError:s??!1,...(0,Iu.describeContent)("result",r),userId:this.actorId}),this.inner.toolEnd(e,n,r,s,i)}async progress(e){return this.inner.progress(e)}async question(e){return this.inner.question(e)}async error(e){return await this.writer.append(this.sessionId,this.requestId,"error",{message:e,userId:this.actorId}),this.inner.error(e)}async done(){return this.inner.done()}async emitTurnStart(){await this.writer.append(this.sessionId,this.requestId,"turn_start",{userId:this.actorId,...this.stamp})}async emitTurnEnd(e){await this.writer.append(this.sessionId,this.requestId,"turn_end",{success:e,userId:this.actorId})}};pt.ObservableStreamEmitter=rc;function ZO(t,e,n,r,s,i){return new rc(t,e,n,r,s,i)}});var sc=S(ii=>{"use strict";Object.defineProperty(ii,"__esModule",{value:!0});ii.encodeRunnerEvent=eI;ii.encodeWorkerRequest=tI;ii.parseWorkerOutbound=nI;ii.applyRunnerEvent=rI;ii.applyParsedRunnerEvent=Vh;function eI(t){return`${JSON.stringify(t)}
93
+ `}function tI(t){return`${JSON.stringify(t)}
94
+ `}function nI(t){let e;try{e=JSON.parse(t)}catch{return}if(!e||typeof e!="object")return;let n=e;if(n.type==="ready")return{type:"ready"};if(n.type==="result"&&typeof n.id=="string")return{type:"result",id:n.id,nativeSessionId:typeof n.nativeSessionId=="string"?n.nativeSessionId:void 0};if(n.type==="failed"&&typeof n.id=="string")return{type:"failed",id:n.id,message:typeof n.message=="string"?n.message:"Custom engine turn failed"};if(typeof n.id=="string"&&n.event&&typeof n.event=="object")return{id:n.id,event:n.event}}async function rI(t,e){let n;try{n=JSON.parse(e)}catch{return}return Vh(t,n)}async function Vh(t,e){switch(e.type){case"text":await t.text(e.delta);break;case"thinking":await t.thinking(e.delta);break;case"toolStart":await t.toolStart(e.toolName,e.input,e.toolCallId);break;case"toolEnd":await t.toolEnd(e.toolName,e.toolCallId,e.result,e.isError);break;case"progress":await t.progress(e.message);break;case"error":await t.error(e.message);break;case"done":await t.done();break;case"nativeSessionId":return e.nativeSessionId;case"probe":if(!e.ok)throw new Error(e.message??"Custom engine import probe failed");break;default:break}}});var Wh=S(ic=>{"use strict";Object.defineProperty(ic,"__esModule",{value:!0});ic.PersistentEngineWorkerPool=void 0;var sI=require("node:child_process"),iI=require("node:readline"),Nu=sc(),oI=1e3*60*30,aI=1e3*60,cI=1e3*30,lI=1e3*10,Ru=class{opts;child;readyPromise;readyResolve;readyReject;pending=new Map;lineChains=new Map;seq=0;stderr="";retired=!1;retireTimer;readyTimer;lastUsedAt=Date.now();constructor(e){this.opts=e}isUsable(){return!this.retired&&this.child!==void 0&&this.child.exitCode===null&&!this.child.killed}ensureStarted(){if(this.readyPromise)return this.readyPromise;this.readyPromise=new Promise((s,i)=>{this.readyResolve=s,this.readyReject=i});let e=(0,sI.spawn)(this.opts.nodeBin,[this.opts.runnerPath],{cwd:this.opts.cwd,env:this.opts.spawnEnv,stdio:["pipe","pipe","pipe"]});this.child=e,this.opts.logger.info(`[AgentIDE] Persistent engine worker started (${this.opts.label}, pid=${e.pid})`);let n=this.opts.startupTimeoutMs??cI;this.readyTimer=setTimeout(()=>{this.opts.logger.warn(`[AgentIDE] Persistent engine worker (${this.opts.label}) did not signal ready within ${n}ms; terminating`),this.handleExit(`worker did not become ready within ${n}ms`)},n),this.readyTimer.unref?.();let r=(0,iI.createInterface)({input:e.stdout});return r.on("line",s=>this.routeLine(s)),e.stderr?.on("data",s=>{this.stderr+=String(s),this.stderr.length>16384&&(this.stderr=this.stderr.slice(-16384))}),e.on("error",s=>this.handleExit(s.message)),e.on("close",s=>{r.close(),this.handleExit(this.stderr.trim()||`worker exited with code ${s}`)}),this.readyPromise}routeLine(e){let n=(0,Nu.parseWorkerOutbound)(e);if(!n)return;if("type"in n&&n.type==="ready"){this.markReady();return}let r="id"in n?n.id:void 0;if(r===void 0)return;let i=(this.lineChains.get(r)??Promise.resolve()).then(()=>this.handleMessage(n)).catch(()=>{});this.lineChains.set(r,i),i.then(()=>{this.lineChains.get(r)===i&&this.lineChains.delete(r)})}async handleMessage(e){if("type"in e){if(e.type==="ready")return;let r=this.pending.get(e.id);if(!r)return;e.type==="result"?(this.finishRun(e.id,r),r.resolve({nativeSessionId:e.nativeSessionId})):(this.finishRun(e.id,r),r.reject(new Error(e.message)),r.aborted||this.retire("turn error"));return}let n=this.pending.get(e.id);n&&await(0,Nu.applyParsedRunnerEvent)(n.emitter,e.event)}markReady(){this.readyTimer&&(clearTimeout(this.readyTimer),this.readyTimer=void 0),this.readyResolve?.()}cleanupRun(e){e.abortTimer&&(clearTimeout(e.abortTimer),e.abortTimer=void 0),e.signal&&e.onAbort&&(e.signal.removeEventListener("abort",e.onAbort),e.onAbort=void 0)}finishRun(e,n){this.cleanupRun(n),this.pending.delete(e),this.retired&&this.pending.size===0&&this.kill()}handleExit(e){this.retireTimer&&(clearTimeout(this.retireTimer),this.retireTimer=void 0),this.readyTimer&&(clearTimeout(this.readyTimer),this.readyTimer=void 0);let n=this.child;if(this.child=void 0,this.retired=!0,n&&n.exitCode===null&&!n.killed)try{n.kill("SIGKILL")}catch{}this.readyReject?.(new Error(`Persistent engine worker failed to start (${this.opts.label}): ${e}`));let r=[...this.pending.entries()];this.pending.clear();for(let[,s]of r)this.cleanupRun(s),s.reject(new Error(`Custom engine worker exited (${this.opts.label}): ${e}`))}retire(e){this.retired||(this.retired=!0,this.opts.logger.info(`[AgentIDE] Retiring persistent engine worker (${this.opts.label}): ${e}`),this.pending.size===0?this.kill():(this.retireTimer=setTimeout(()=>this.kill(),aI),this.retireTimer.unref?.()))}kill(){this.retireTimer&&(clearTimeout(this.retireTimer),this.retireTimer=void 0),this.readyTimer&&(clearTimeout(this.readyTimer),this.readyTimer=void 0);let e=this.child;this.child=void 0,this.retired=!0,!(!e||e.exitCode!==null||e.killed)&&e.kill("SIGTERM")}send(e){this.child?.stdin?.write((0,Nu.encodeWorkerRequest)(e))}async run(e,n,r){await this.ensureStarted(),this.lastUsedAt=Date.now();let s=String(++this.seq);return new Promise((i,o)=>{let a={emitter:n,resolve:i,reject:o,aborted:!1,signal:r},c=()=>{a.aborted=!0,this.send({type:"abort",id:s}),a.abortTimer=setTimeout(()=>{let l=this.pending.get(s);l&&(this.finishRun(s,l),l.reject(new Error("Custom engine turn aborted")))},this.opts.abortSettleTimeoutMs??lI),a.abortTimer.unref?.()};r&&(a.onAbort=c,r.aborted?c():r.addEventListener("abort",c,{once:!0})),this.pending.set(s,a),this.send({type:"run",id:s,env:e})})}isIdle(e){return this.pending.size===0&&e-this.lastUsedAt>(this.opts.idleTtlMs??oI)}},Cu=class{workers=new Map;async run(e,n,r,s){let i=this.workers.get(e.cacheKey);(!i||!i.isUsable())&&(i?.retire("stale or dead"),i=new Ru(e),this.workers.set(e.cacheKey,i));try{return await i.run(n,r,s)}catch(o){throw this.workers.get(e.cacheKey)===i&&!i.isUsable()&&this.workers.delete(e.cacheKey),o}}onMaintenance(){let e=Date.now();for(let[n,r]of this.workers.entries())r.isIdle(e)&&(r.kill(),this.workers.delete(n))}disposeAll(){for(let e of this.workers.values())e.kill();this.workers.clear()}_workerCountForTest(){return this.workers.size}};ic.PersistentEngineWorkerPool=Cu});var Kh=S(ki=>{"use strict";Object.defineProperty(ki,"__esModule",{value:!0});ki.EMBEDDED_CUSTOM_ENGINE_RUNNER_SOURCE=ki.EMBEDDED_CUSTOM_ENGINE_RUNNER_HASH=void 0;ki.EMBEDDED_CUSTOM_ENGINE_RUNNER_HASH="fe3840b3a767b36e";ki.EMBEDDED_CUSTOM_ENGINE_RUNNER_SOURCE=`"use strict";
95
95
  /*---------------------------------------------------------------------------------------------
96
96
  * Copyright (c) AgentHippo.ai. All rights reserved.
97
97
  *--------------------------------------------------------------------------------------------*/
@@ -409,14 +409,14 @@ else {
409
409
  process.exit(1);
410
410
  });
411
411
  }
412
- `});var Cu=S(xt=>{"use strict";var oI=xt&&xt.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,s)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),aI=xt&&xt.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),cI=xt&&xt.__importStar||(function(){var t=function(e){return t=Object.getOwnPropertyNames||function(n){var r=[];for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(r[r.length]=s);return r},t(e)};return function(e){if(e&&e.__esModule)return e;var n={};if(e!=null)for(var r=t(e),s=0;s<r.length;s++)r[s]!=="default"&&oI(n,e,r[s]);return aI(n,e),n}})();Object.defineProperty(xt,"__esModule",{value:!0});xt.NODE_RUNNER_FILENAME=void 0;xt.ensureNodeRunnerScriptPath=dI;xt.embeddedRunnerContentHash=fI;var lI=require("node:crypto"),$i=require("node:fs"),Cs=cI(require("node:path")),uI=Ys();xt.NODE_RUNNER_FILENAME="run-custom-engine-runner.js";async function Kh(){return Promise.resolve().then(()=>wn(Wh()))}async function dI(){let t=[],e=process.argv[1];e&&t.push(Cs.join(Cs.dirname(e),xt.NODE_RUNNER_FILENAME)),t.push(Cs.join(Cs.dirname(process.execPath),xt.NODE_RUNNER_FILENAME));for(let o of t)try{return await $i.promises.access(o),o}catch{}let{EMBEDDED_CUSTOM_ENGINE_RUNNER_HASH:n,EMBEDDED_CUSTOM_ENGINE_RUNNER_SOURCE:r}=await Kh(),s=Cs.join((0,uI.getAgentideHome)(),"cache","cli"),i=Cs.join(s,`${xt.NODE_RUNNER_FILENAME.replace(/\.js$/,"")}-${n}.js`);try{if(await $i.promises.readFile(i,"utf8")===r)return i}catch{}await $i.promises.mkdir(s,{recursive:!0}),await $i.promises.writeFile(i,r,"utf8");try{let o=`${xt.NODE_RUNNER_FILENAME.replace(/\.js$/,"")}-`;for(let a of await $i.promises.readdir(s))a.startsWith(o)&&a.endsWith(".js")&&Cs.join(s,a)!==i&&await $i.promises.unlink(Cs.join(s,a)).catch(()=>{})}catch{}return i}async function fI(){let{EMBEDDED_CUSTOM_ENGINE_RUNNER_SOURCE:t}=await Kh();return(0,lI.createHash)("sha256").update(t).digest("hex")}});var Lu=S(gn=>{"use strict";var pI=gn&&gn.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,s)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),gI=gn&&gn.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),hI=gn&&gn.__importStar||(function(){var t=function(e){return t=Object.getOwnPropertyNames||function(n){var r=[];for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(r[r.length]=s);return r},t(e)};return function(e){if(e&&e.__esModule)return e;var n={};if(e!=null)for(var r=t(e),s=0;s<r.length;s++)r[s]!=="default"&&pI(n,e,r[s]);return gI(n,e),n}})();Object.defineProperty(gn,"__esModule",{value:!0});gn.CustomEngine=void 0;gn.resolveCustomEngineLoadStrategy=qh;gn.deliverModelRoutingEnv=Yh;gn.buildRunnerChildEnv=Du;gn.probeCustomEngineImport=II;var mI=require("node:child_process"),EI=require("node:readline"),Ao=require("fs"),Tt=hI(require("path")),_I=require("url"),wo=zs(),yI=Er(),wI=Ns(),us=Un(),AI=Is(),ic=en(),oc=Ya(),SI=rc(),TI=Vh(),ku=Js(),ac=lo(),bI=1e3*60*30;function qh(){let t=process.env.AGENTHIPPO_CUSTOM_ENGINE_LOAD?.trim().toLowerCase();return t==="a"||t==="in-process"||t==="inprocess"?"in-process":t==="c"||t==="node-subprocess"||t==="node"||t==="b"||t==="bun-subprocess"||t==="bun"?"node-subprocess":"persistent-worker"}function vI(t){let e=t.engineId?.trim();if(e&&e!=="claude"&&e!=="codex")return e}function OI(t){return t.configProvider?.get("agentide","additionalEngineDir")}function cc(t,e){let n=Tt.join(e,"node_modules"),r=t.NODE_PATH?.trim();t.NODE_PATH=r?`${n}${Tt.delimiter}${r}`:n}function Yh(t,e,n,r,s){let i=(o,a,c)=>{if(!(!o||!a)){if(r[o]?.trim()){s?.info(`[AgentIDE] Custom engine "${e.id}": ${o} already set in ambient env \u2014 keeping the operator's value, skipping per-turn ${c} delivery`);return}t[o]=a}};i(e.model?.apiKeyEnvVar,n.apiKey,"API key"),i(e.model?.baseUrlEnvVar,n.baseUrl,"base URL"),i(e.model?.openaiBaseUrlEnvVar,n.openaiBaseUrl,"OpenAI base URL")}function Du(t,e,n){let r={...process.env,...e.env,AGENTHIPPO_ENGINE_ENTRY:t.entryPath,AGENTHIPPO_MESSAGE:e.message,AGENTHIPPO_WORKSPACE_ROOT:e.workspaceRoot,AGENTHIPPO_MODEL_ID:e.modelId,AGENTHIPPO_CONVERSATION_KEY:e.session.key,AGENTHIPPO_IS_EPHEMERAL:e.session.isEphemeral?"true":"false"};n&&(r.AGENTHIPPO_CUSTOM_ENGINE_PROBE="import"),e.session.nativeSessionId?.trim()&&(r.AGENTHIPPO_NATIVE_SESSION_ID=e.session.nativeSessionId.trim()),t.engineExport&&(r.AGENTHIPPO_ENGINE_EXPORT=t.engineExport);let s=e.mcpServers?(0,ac.serializeInlineMcpServers)(e.mcpServers):void 0;return s&&(r[ac.AGENTHIPPO_MCP_SERVERS_ENV]=s),cc(r,t.manifestDir),r}async function Xh(t,e,n,r,s){let i;try{let{ensureNodeRunnerScriptPath:c}=await Promise.resolve().then(()=>wn(Cu()));i=await c()}catch(c){throw new Error(`Custom engine Node runner not available: ${c instanceof Error?c.message:String(c)}. Rebuild the agenthippo CLI.`)}let o=await(0,oc.resolveNodeBinary)();e.runtime.logger.info(`[AgentIDE] Custom engine Node runner: ${o}`);let a=Du(t,e,r);return process.platform==="win32"&&o===process.execPath&&!o.toLowerCase().endsWith("\\node.exe")&&(a.ELECTRON_RUN_AS_NODE="1"),(0,oc.prependPathDir)(a,Tt.dirname(o)),new Promise((c,l)=>{let f=(0,mI.spawn)(o,[i],{cwd:t.manifestDir,env:a,stdio:["ignore","pipe","pipe"]}),u="",d,p=Promise.resolve(),g=(0,EI.createInterface)({input:f.stdout});g.on("line",h=>{p=p.then(async()=>{let E=await(0,SI.applyRunnerEvent)(n,h);E&&(d=E)}).catch(E=>{g.close(),f.kill(),l(E)})}),f.stderr?.on("data",h=>{u+=String(h)});let m=()=>{f.kill("SIGTERM")};s?.addEventListener("abort",m,{once:!0}),f.on("error",l),f.on("close",h=>{s?.removeEventListener("abort",m),g.close(),p.finally(()=>{if(h===0)c(d?{nativeSessionId:d}:void 0);else{let E=u.trim()||`Custom engine Node runner exited with code ${h}`;l(new Error(E))}})})})}async function II(t,e){try{if(e==="in-process")return await Jh(t),{strategy:e,ok:!0};let n={text:async()=>{},thinking:async()=>{},toolStart:async()=>{},toolEnd:async()=>{},progress:async()=>{},question:async()=>({selected:[],freeText:null}),error:async()=>{},done:async()=>{}},r={message:"",modelId:t.model?.defaultModel??"auto",workspaceRoot:t.searchRoot,additionalDirectories:[],permissions:{fileAccess:"full"},env:{...process.env},routing:{useLiteLLM:!1},session:{key:"probe",chatSessionId:"probe",contextSessionId:"probe",isEphemeral:!0,engineHomeDir:t.manifestDir,engineSessionDir:t.manifestDir},agent:{id:"probe"},emitter:n,runtime:{logger:{info:()=>{},warn:()=>{},error:()=>{},debug:()=>{}}}};return await Xh(t,r,n,!0),{strategy:e,ok:!0}}catch(n){return{strategy:e,ok:!1,error:n instanceof Error?n.message:String(n)}}}async function Jh(t){let{entryPath:e,id:n,engineExport:r}=t;try{await Ao.promises.access(e)}catch{throw new Error(`Custom engine "${n}" entry not found: ${e}`)}let s=process.cwd(),i=process.env.NODE_PATH;try{process.chdir(t.manifestDir),cc(process.env,t.manifestDir);let o=await Ao.promises.stat(e).catch(()=>{}),a=`${(0,_I.pathToFileURL)(e).href}?mtime=${o?.mtimeMs??Date.now()}`,c=await new Function("u","return import(u)")(a),l=(r?c[r]??c.default?.[r]:void 0)??c.default;if(!l){let u=r?`"${r}"`:"default export";throw new Error(`Custom engine "${n}": ${u} not found in ${e}. Export a class or object with a run(turn) method.`)}let f=typeof l=="function"?new l:l;return PI(n,f),f}finally{process.chdir(s),i===void 0?delete process.env.NODE_PATH:process.env.NODE_PATH=i}}function PI(t,e){if(typeof e!="object"||e===null||typeof e.run!="function")throw new Error(`Custom engine "${t}" export must be a class or object with a run(turn) method.`)}function NI(t){return t.replace(/[<>:"/\\|?*\x00-\x1F]/g,"_").slice(0,160)||"session"}function RI(t){let e=[];t.session.contextFilePath&&e.push(`context_file: ${Tt.relative(t.workspaceRoot,t.session.contextFilePath)}`),t.session.terminalLogPath&&e.push(`terminal_log: ${Tt.relative(t.workspaceRoot,t.session.terminalLogPath)}`),t.session.attachmentsDir&&e.push(`attachments_dir: ${Tt.relative(t.workspaceRoot,t.session.attachmentsDir)}`);let n=t.env.AGENTHIPPO_GATEWAY_OUTBOUND_FILE?.trim();n&&e.push(`gateway_outbound_file: ${n}`);let r=t.env.AGENTHIPPO_ACTIVE_AGENT?.trim();return r&&e.push(`active_agent: ${r}`),e.length===0?"":["<agenthippo_runtime_context>",...e,"</agenthippo_runtime_context>"].join(`
413
- `)}var CI=5e3,$u=class{config;getBundledBasePromptsDir;id="custom";displayName="Custom Engine";instances=new Map;activeSessions=new Map;mtimeCache=new Map;workerPool=new TI.PersistentEngineWorkerPool;constructor(e,n=()=>{}){this.config=e,this.getBundledBasePromptsDir=n}async getCachedMtime(e){let n=Date.now(),r=this.mtimeCache.get(e);if(r&&n-r.fetchedAt<CI)return r.mtime;let s=(await Ao.promises.stat(e).catch(()=>{}))?.mtimeMs??0;return this.mtimeCache.set(e,{mtime:s,fetchedAt:n}),s}async buildCacheKey(e){let[n,r]=await Promise.all([this.getCachedMtime(e.manifestPath),this.getCachedMtime(e.entryPath)]);return[e.id,e.manifestPath,n,e.entryPath,r].join("\0")}async stream(e,n,r,s,i){let o=vI(n),a=(0,wI.resolveCustomEngineManifest)(n.workspaceRoot,o,OI(s),(f,u)=>s.logger.warn(`[AgentIDE] Skipping malformed custom engine manifest ${f}: ${u instanceof Error?u.message:String(u)}`)),c=`custom:${a.id}`,l=(0,ku.buildConversationKey)(c,n);await(0,ku.withConversationLock)(l.key,async()=>{let f=qh(),u=await this.buildTurn(a,e,n,r,s,l.key,l.chatSessionId,l.isEphemeral,i);s.logger.info(`[AgentIDE] Custom engine "${a.id}" strategy=${f} entry=${a.entryPath}`);let d;if(f==="in-process"){let{engine:m}=await this.getOrLoadInstance(a,s),h=process.cwd(),E=process.env.NODE_PATH;try{process.chdir(a.manifestDir),cc(process.env,a.manifestDir),d=await m.run(u)}finally{process.chdir(h),E===void 0?delete process.env.NODE_PATH:process.env.NODE_PATH=E}}else f==="persistent-worker"?d=await this.runViaPersistentWorker(a,u,r,i):d=await Xh(a,u,r,!1,i);let p=d?.nativeSessionId?.trim(),g=p||u.session.nativeSessionId;this.activeSessions.set(l.key,{nativeSessionId:g,lastUsedAt:Date.now()}),p?await(0,wo.persistSessionIfNeeded)(c,l,p,n):(0,wo.touchSessionIfNeeded)(l)},{signal:i,timeoutMs:ku.DEFAULT_CONVERSATION_LOCK_TIMEOUT_MS,label:`custom.${a.id}.run`})}async getOrLoadInstance(e,n){let r=await this.buildCacheKey(e),s=this.instances.get(r);if(s)return s;for(let[a,c]of this.instances.entries())if(c.manifest.id===e.id){try{c.engine.dispose?.()}catch{}this.instances.delete(a)}n.logger.info(`[AgentIDE] Loading custom engine "${e.id}" from ${e.entryPath}`);let o={engine:await Jh(e),manifest:e,cacheKey:r};return this.instances.set(r,o),o}async runViaPersistentWorker(e,n,r,s){let{ensureNodeRunnerScriptPath:i}=await Promise.resolve().then(()=>wn(Cu())),o=await i(),a=await(0,oc.resolveNodeBinary)();n.runtime.logger.info(`[AgentIDE] Custom engine persistent worker: ${a}`);let c=Du(e,n,!1),l={...c,AGENTHIPPO_RUNNER_MODE:"persistent"};process.platform==="win32"&&a===process.execPath&&!a.toLowerCase().endsWith("\\node.exe")&&(l.ELECTRON_RUN_AS_NODE="1"),(0,oc.prependPathDir)(l,Tt.dirname(a));let f=await this.buildCacheKey(e);return this.workerPool.run({cacheKey:f,runnerPath:o,nodeBin:a,cwd:e.manifestDir,spawnEnv:l,logger:n.runtime.logger,label:`custom.${e.id}`},c,r,s)}clearInstances(e){for(let[n,{engine:r,manifest:s}]of this.instances.entries())if(!(e&&s.id!==e)){try{r.dispose?.()}catch{}this.instances.delete(n)}}async buildTurn(e,n,r,s,i,o,a,c,l){let f=r.modelId?.trim()||e.model?.defaultModel?.trim();if(!f)throw new Error(`Custom engine "${e.id}" requires a model selection. Add a "model.defaultModel" to the engine manifest or select a model explicitly.`);let u=r.agentPackId??us.AGENT_CONSTANTS.DEFAULT_AGENT_ID,d=r.contextSessionId?.trim()||r.sessionId?.trim()||a,p=NI(d),g=this.config.customEnginesStoragePath??Tt.join(this.config.storagePath,us.AGENT_CONSTANTS.AGENTS_DIR,u,"custom"),m=Tt.join(g,e.id),h=(0,us.userScopedEngineHomeFromKey)(Tt.join(m,"home"),(0,AI.resolveEngineHomeUserKey)(r.engineHomeUserKey)),E=Tt.join(m,us.AGENT_CONSTANTS.SESSIONS_DIR,p);await Ao.promises.mkdir(h,{recursive:!0}),await Ao.promises.mkdir(E,{recursive:!0});let _=Tt.join(r.workspaceRoot,us.AGENT_CONSTANTS.AGENTIDE_DIR_NAME,us.AGENT_CONSTANTS.SESSIONS_DIR,d),y=Tt.join(_,us.AGENT_CONSTANTS.CONTEXT_MD),b=Tt.join(_,"terminal.md"),T=Tt.join(_,"attachments"),O=this.activeSessions.get(o)?.nativeSessionId??(0,wo.getPersistedSessionId)(`custom:${e.id}`,o),A=(0,ic.resolveApiRouting)(r,this.config,(0,ic.inferModelProvider)(r.modelId),i.configProvider),v=A.apiKey?.trim()||void 0,C=A.baseUrl?.trim()||void 0,B=A.openaiBaseUrl?.trim()||void 0,R=e.workspaceSync?.enabled?Tt.join(r.workspaceRoot,e.workspaceSync.dir,e.workspaceSync.rulesFile):void 0,F=e.workspaceSync?.enabled&&e.workspaceSync.includeSkills?Tt.join(r.workspaceRoot,e.workspaceSync.dir,us.AGENT_CONSTANTS.SKILLS_DIR):void 0,re=e.workspaceSync?.enabled&&e.workspaceSync.includeRules?Tt.join(r.workspaceRoot,e.workspaceSync.dir,us.AGENT_CONSTANTS.RULES_DIR):void 0,W={...process.env,...i.cliEnvPatch??{},AGENTHIPPO_ENGINE_ID:e.id,AGENTHIPPO_ENGINE_HOME:h,AGENTHIPPO_ENGINE_SESSION_DIR:E,AGENTHIPPO_CONTEXT_SESSION_ID:d,AGENTHIPPO_CONTEXT_EXPORT_PATH:y,AGENTHIPPO_TERMINAL_LOG_PATH:b,AGENTHIPPO_ATTACHMENTS_DIR:T,AGENTHIPPO_ACTIVE_AGENT:u,AGENT_ID:u,AGENTHIPPO_MODEL_ID:f,AGENTHIPPO_USE_LITELLM:A.useLiteLLM?"true":"false"};if(delete W[yI.OPENCLAW_GATEWAY_TOKEN_ENV],delete W.AGENTHIPPO_DATA_PLANE_TOKEN,cc(W,e.manifestDir),v&&(W.AGENTHIPPO_API_KEY=v),C&&(W.AGENTHIPPO_BASE_URL=C),B&&(W.AGENTHIPPO_OPENAI_BASE_URL=B),A.useLiteLLM){W.AGENTHIPPO_LITELLM_API_KEY=v??"sk-dummy",W.AGENTIDE_LITELLM_API_KEY=v??"sk-dummy",C&&(W.AGENTHIPPO_LITELLM_BASE_URL=C,W.AGENTIDE_LITELLM_BASE_URL=C);let Me=(0,wo.buildLiteLLMMetadataHeaders)(!0,{sessionId:r.sessionId,analyticsUserId:r.analyticsUserId,analyticsProjectId:(0,wo.resolveAnalyticsProjectId)(r.analyticsProjectId,r.workspaceRoot),agentId:u,agentVersion:r.agentPackVersion??"workspace",source:"agenthippo",engine:`custom:${e.id}`,requestId:r.requestId,policyVersion:r.policyVersion,packDigest:r.packDigest,instanceId:r.instanceId,engineVersion:r.engineVersion,tier:r.tier});Me.length>0&&(W.AGENTHIPPO_LITELLM_METADATA_HEADERS=Me.join(`
414
- `))}r.agentPackVersion&&(W.AGENTHIPPO_AGENT_VERSION=r.agentPackVersion,W.AGENTIDE_AGENT_VERSION=r.agentPackVersion),e.homeEnvVar&&(W[e.homeEnvVar]=h),Yh(W,e,{apiKey:v,baseUrl:C,openaiBaseUrl:B},process.env,i.logger),(C&&(0,ic.applyLocalTlsBypass)(W,C)||B&&B!==C&&(0,ic.applyLocalTlsBypass)(W,B))&&i.logger.info(`[AgentIDE] Disabling TLS verification for local HTTPS (${e.id})`);let de=A.useLiteLLM?"LiteLLM proxy":C?"custom provider":"native provider";i.logger.info(`[AgentIDE] Custom engine "${e.id}" routing: ${de}, baseUrl=${C||"default"}, model=${f}`);let he=await(0,ac.loadMcpServers)(u,r.workspaceRoot,this.getBundledBasePromptsDir()),z=(0,ac.formatInlineMcpServers)(he,W);he.length>0&&i.logger.debug(`[AgentIDE] Custom engine "${e.id}" MCP (${u}): ${he.map(Me=>Me.name).join(", ")}`);let Ne=n,We={message:Ne,modelId:f,workspaceRoot:r.workspaceRoot,additionalDirectories:r.additionalDirectories??[],permissions:r.permissions??{fileAccess:"workspace-write"},env:W,routing:{useLiteLLM:A.useLiteLLM,...v?{apiKey:v}:{},...C?{baseUrl:C}:{},...B?{openaiBaseUrl:B}:{}},session:{key:o,chatSessionId:a,contextSessionId:d,isEphemeral:c,engineHomeDir:h,engineSessionDir:E,nativeSessionId:O,contextFilePath:y,terminalLogPath:b,attachmentsDir:T},agent:{id:u,version:r.agentPackVersion,rulesFilePath:R,skillsDir:F,rulesDir:re},...Object.keys(z).length>0?{mcpServers:z}:{},emitter:s,runtime:{...i,invalidateEngineInstance:()=>this.clearInstances(e.id)},signal:l};if(e.promptInjection.mode==="message-suffix"){let Me=RI(We);Me&&(Ne=`${n}
412
+ `});var ku=S(xt=>{"use strict";var uI=xt&&xt.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,s)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),dI=xt&&xt.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),fI=xt&&xt.__importStar||(function(){var t=function(e){return t=Object.getOwnPropertyNames||function(n){var r=[];for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(r[r.length]=s);return r},t(e)};return function(e){if(e&&e.__esModule)return e;var n={};if(e!=null)for(var r=t(e),s=0;s<r.length;s++)r[s]!=="default"&&uI(n,e,r[s]);return dI(n,e),n}})();Object.defineProperty(xt,"__esModule",{value:!0});xt.NODE_RUNNER_FILENAME=void 0;xt.ensureNodeRunnerScriptPath=hI;xt.embeddedRunnerContentHash=mI;var pI=require("node:crypto"),$i=require("node:fs"),Cs=fI(require("node:path")),gI=Ys();xt.NODE_RUNNER_FILENAME="run-custom-engine-runner.js";async function qh(){return Promise.resolve().then(()=>wn(Kh()))}async function hI(){let t=[],e=process.argv[1];e&&t.push(Cs.join(Cs.dirname(e),xt.NODE_RUNNER_FILENAME)),t.push(Cs.join(Cs.dirname(process.execPath),xt.NODE_RUNNER_FILENAME));for(let o of t)try{return await $i.promises.access(o),o}catch{}let{EMBEDDED_CUSTOM_ENGINE_RUNNER_HASH:n,EMBEDDED_CUSTOM_ENGINE_RUNNER_SOURCE:r}=await qh(),s=Cs.join((0,gI.getAgentideHome)(),"cache","cli"),i=Cs.join(s,`${xt.NODE_RUNNER_FILENAME.replace(/\.js$/,"")}-${n}.js`);try{if(await $i.promises.readFile(i,"utf8")===r)return i}catch{}await $i.promises.mkdir(s,{recursive:!0}),await $i.promises.writeFile(i,r,"utf8");try{let o=`${xt.NODE_RUNNER_FILENAME.replace(/\.js$/,"")}-`;for(let a of await $i.promises.readdir(s))a.startsWith(o)&&a.endsWith(".js")&&Cs.join(s,a)!==i&&await $i.promises.unlink(Cs.join(s,a)).catch(()=>{})}catch{}return i}async function mI(){let{EMBEDDED_CUSTOM_ENGINE_RUNNER_SOURCE:t}=await qh();return(0,pI.createHash)("sha256").update(t).digest("hex")}});var Mu=S(gn=>{"use strict";var EI=gn&&gn.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,s)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),_I=gn&&gn.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),yI=gn&&gn.__importStar||(function(){var t=function(e){return t=Object.getOwnPropertyNames||function(n){var r=[];for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(r[r.length]=s);return r},t(e)};return function(e){if(e&&e.__esModule)return e;var n={};if(e!=null)for(var r=t(e),s=0;s<r.length;s++)r[s]!=="default"&&EI(n,e,r[s]);return _I(n,e),n}})();Object.defineProperty(gn,"__esModule",{value:!0});gn.CustomEngine=void 0;gn.resolveCustomEngineLoadStrategy=Yh;gn.deliverModelRoutingEnv=Xh;gn.buildRunnerChildEnv=Lu;gn.probeCustomEngineImport=CI;var wI=require("node:child_process"),AI=require("node:readline"),To=require("fs"),Tt=yI(require("path")),SI=require("url"),So=zs(),TI=Er(),bI=Ns(),ls=Un(),vI=Is(),oc=en(),ac=Xa(),OI=sc(),II=Wh(),$u=Js(),cc=fo(),PI=1e3*60*30;function Yh(){let t=process.env.AGENTHIPPO_CUSTOM_ENGINE_LOAD?.trim().toLowerCase();return t==="a"||t==="in-process"||t==="inprocess"?"in-process":t==="c"||t==="node-subprocess"||t==="node"||t==="b"||t==="bun-subprocess"||t==="bun"?"node-subprocess":"persistent-worker"}function NI(t){let e=t.engineId?.trim();if(e&&e!=="claude"&&e!=="codex")return e}function RI(t){return t.configProvider?.get("agentide","additionalEngineDir")}function lc(t,e){let n=Tt.join(e,"node_modules"),r=t.NODE_PATH?.trim();t.NODE_PATH=r?`${n}${Tt.delimiter}${r}`:n}function Xh(t,e,n,r,s){let i=(o,a,c)=>{if(!(!o||!a)){if(r[o]?.trim()){s?.info(`[AgentIDE] Custom engine "${e.id}": ${o} already set in ambient env \u2014 keeping the operator's value, skipping per-turn ${c} delivery`);return}t[o]=a}};i(e.model?.apiKeyEnvVar,n.apiKey,"API key"),i(e.model?.baseUrlEnvVar,n.baseUrl,"base URL"),i(e.model?.openaiBaseUrlEnvVar,n.openaiBaseUrl,"OpenAI base URL")}function Lu(t,e,n){let r={...process.env,...e.env,AGENTHIPPO_ENGINE_ENTRY:t.entryPath,AGENTHIPPO_MESSAGE:e.message,AGENTHIPPO_WORKSPACE_ROOT:e.workspaceRoot,AGENTHIPPO_MODEL_ID:e.modelId,AGENTHIPPO_CONVERSATION_KEY:e.session.key,AGENTHIPPO_IS_EPHEMERAL:e.session.isEphemeral?"true":"false"};n&&(r.AGENTHIPPO_CUSTOM_ENGINE_PROBE="import"),e.session.nativeSessionId?.trim()&&(r.AGENTHIPPO_NATIVE_SESSION_ID=e.session.nativeSessionId.trim()),t.engineExport&&(r.AGENTHIPPO_ENGINE_EXPORT=t.engineExport);let s=e.mcpServers?(0,cc.serializeInlineMcpServers)(e.mcpServers):void 0;return s&&(r[cc.AGENTHIPPO_MCP_SERVERS_ENV]=s),lc(r,t.manifestDir),r}async function Jh(t,e,n,r,s){let i;try{let{ensureNodeRunnerScriptPath:c}=await Promise.resolve().then(()=>wn(ku()));i=await c()}catch(c){throw new Error(`Custom engine Node runner not available: ${c instanceof Error?c.message:String(c)}. Rebuild the agenthippo CLI.`)}let o=await(0,ac.resolveNodeBinary)();e.runtime.logger.info(`[AgentIDE] Custom engine Node runner: ${o}`);let a=Lu(t,e,r);return process.platform==="win32"&&o===process.execPath&&!o.toLowerCase().endsWith("\\node.exe")&&(a.ELECTRON_RUN_AS_NODE="1"),(0,ac.prependPathDir)(a,Tt.dirname(o)),new Promise((c,l)=>{let f=(0,wI.spawn)(o,[i],{cwd:t.manifestDir,env:a,stdio:["ignore","pipe","pipe"]}),u="",d,p=Promise.resolve(),g=(0,AI.createInterface)({input:f.stdout});g.on("line",h=>{p=p.then(async()=>{let E=await(0,OI.applyRunnerEvent)(n,h);E&&(d=E)}).catch(E=>{g.close(),f.kill(),l(E)})}),f.stderr?.on("data",h=>{u+=String(h)});let m=()=>{f.kill("SIGTERM")};s?.addEventListener("abort",m,{once:!0}),f.on("error",l),f.on("close",h=>{s?.removeEventListener("abort",m),g.close(),p.finally(()=>{if(h===0)c(d?{nativeSessionId:d}:void 0);else{let E=u.trim()||`Custom engine Node runner exited with code ${h}`;l(new Error(E))}})})})}async function CI(t,e){try{if(e==="in-process")return await zh(t),{strategy:e,ok:!0};let n={text:async()=>{},thinking:async()=>{},toolStart:async()=>{},toolEnd:async()=>{},progress:async()=>{},question:async()=>({selected:[],freeText:null}),error:async()=>{},done:async()=>{}},r={message:"",modelId:t.model?.defaultModel??"auto",workspaceRoot:t.searchRoot,additionalDirectories:[],permissions:{fileAccess:"full"},env:{...process.env},routing:{useLiteLLM:!1},session:{key:"probe",chatSessionId:"probe",contextSessionId:"probe",isEphemeral:!0,engineHomeDir:t.manifestDir,engineSessionDir:t.manifestDir},agent:{id:"probe"},emitter:n,runtime:{logger:{info:()=>{},warn:()=>{},error:()=>{},debug:()=>{}}}};return await Jh(t,r,n,!0),{strategy:e,ok:!0}}catch(n){return{strategy:e,ok:!1,error:n instanceof Error?n.message:String(n)}}}async function zh(t){let{entryPath:e,id:n,engineExport:r}=t;try{await To.promises.access(e)}catch{throw new Error(`Custom engine "${n}" entry not found: ${e}`)}let s=process.cwd(),i=process.env.NODE_PATH;try{process.chdir(t.manifestDir),lc(process.env,t.manifestDir);let o=await To.promises.stat(e).catch(()=>{}),a=`${(0,SI.pathToFileURL)(e).href}?mtime=${o?.mtimeMs??Date.now()}`,c=await new Function("u","return import(u)")(a),l=(r?c[r]??c.default?.[r]:void 0)??c.default;if(!l){let u=r?`"${r}"`:"default export";throw new Error(`Custom engine "${n}": ${u} not found in ${e}. Export a class or object with a run(turn) method.`)}let f=typeof l=="function"?new l:l;return kI(n,f),f}finally{process.chdir(s),i===void 0?delete process.env.NODE_PATH:process.env.NODE_PATH=i}}function kI(t,e){if(typeof e!="object"||e===null||typeof e.run!="function")throw new Error(`Custom engine "${t}" export must be a class or object with a run(turn) method.`)}function $I(t){return t.replace(/[<>:"/\\|?*\x00-\x1F]/g,"_").slice(0,160)||"session"}function DI(t){let e=[];t.session.contextFilePath&&e.push(`context_file: ${Tt.relative(t.workspaceRoot,t.session.contextFilePath)}`),t.session.terminalLogPath&&e.push(`terminal_log: ${Tt.relative(t.workspaceRoot,t.session.terminalLogPath)}`),t.session.attachmentsDir&&e.push(`attachments_dir: ${Tt.relative(t.workspaceRoot,t.session.attachmentsDir)}`);let n=t.env.AGENTHIPPO_GATEWAY_OUTBOUND_FILE?.trim();n&&e.push(`gateway_outbound_file: ${n}`);let r=t.env.AGENTHIPPO_ACTIVE_AGENT?.trim();return r&&e.push(`active_agent: ${r}`),e.length===0?"":["<agenthippo_runtime_context>",...e,"</agenthippo_runtime_context>"].join(`
413
+ `)}var LI=5e3,Du=class{config;getBundledBasePromptsDir;id="custom";displayName="Custom Engine";instances=new Map;activeSessions=new Map;mtimeCache=new Map;workerPool=new II.PersistentEngineWorkerPool;constructor(e,n=()=>{}){this.config=e,this.getBundledBasePromptsDir=n}async getCachedMtime(e){let n=Date.now(),r=this.mtimeCache.get(e);if(r&&n-r.fetchedAt<LI)return r.mtime;let s=(await To.promises.stat(e).catch(()=>{}))?.mtimeMs??0;return this.mtimeCache.set(e,{mtime:s,fetchedAt:n}),s}async buildCacheKey(e){let[n,r]=await Promise.all([this.getCachedMtime(e.manifestPath),this.getCachedMtime(e.entryPath)]);return[e.id,e.manifestPath,n,e.entryPath,r].join("\0")}async stream(e,n,r,s,i){let o=NI(n),a=(0,bI.resolveCustomEngineManifest)(n.workspaceRoot,o,RI(s),(f,u)=>s.logger.warn(`[AgentIDE] Skipping malformed custom engine manifest ${f}: ${u instanceof Error?u.message:String(u)}`)),c=`custom:${a.id}`,l=(0,$u.buildConversationKey)(c,n);await(0,$u.withConversationLock)(l.key,async()=>{let f=Yh(),u=await this.buildTurn(a,e,n,r,s,l.key,l.chatSessionId,l.isEphemeral,i);s.logger.info(`[AgentIDE] Custom engine "${a.id}" strategy=${f} entry=${a.entryPath}`);let d;if(f==="in-process"){let{engine:m}=await this.getOrLoadInstance(a,s),h=process.cwd(),E=process.env.NODE_PATH;try{process.chdir(a.manifestDir),lc(process.env,a.manifestDir),d=await m.run(u)}finally{process.chdir(h),E===void 0?delete process.env.NODE_PATH:process.env.NODE_PATH=E}}else f==="persistent-worker"?d=await this.runViaPersistentWorker(a,u,r,i):d=await Jh(a,u,r,!1,i);let p=d?.nativeSessionId?.trim(),g=p||u.session.nativeSessionId;this.activeSessions.set(l.key,{nativeSessionId:g,lastUsedAt:Date.now()}),p?await(0,So.persistSessionIfNeeded)(c,l,p,n):(0,So.touchSessionIfNeeded)(l)},{signal:i,timeoutMs:$u.DEFAULT_CONVERSATION_LOCK_TIMEOUT_MS,label:`custom.${a.id}.run`})}async getOrLoadInstance(e,n){let r=await this.buildCacheKey(e),s=this.instances.get(r);if(s)return s;for(let[a,c]of this.instances.entries())if(c.manifest.id===e.id){try{c.engine.dispose?.()}catch{}this.instances.delete(a)}n.logger.info(`[AgentIDE] Loading custom engine "${e.id}" from ${e.entryPath}`);let o={engine:await zh(e),manifest:e,cacheKey:r};return this.instances.set(r,o),o}async runViaPersistentWorker(e,n,r,s){let{ensureNodeRunnerScriptPath:i}=await Promise.resolve().then(()=>wn(ku())),o=await i(),a=await(0,ac.resolveNodeBinary)();n.runtime.logger.info(`[AgentIDE] Custom engine persistent worker: ${a}`);let c=Lu(e,n,!1),l={...c,AGENTHIPPO_RUNNER_MODE:"persistent"};process.platform==="win32"&&a===process.execPath&&!a.toLowerCase().endsWith("\\node.exe")&&(l.ELECTRON_RUN_AS_NODE="1"),(0,ac.prependPathDir)(l,Tt.dirname(a));let f=await this.buildCacheKey(e);return this.workerPool.run({cacheKey:f,runnerPath:o,nodeBin:a,cwd:e.manifestDir,spawnEnv:l,logger:n.runtime.logger,label:`custom.${e.id}`},c,r,s)}clearInstances(e){for(let[n,{engine:r,manifest:s}]of this.instances.entries())if(!(e&&s.id!==e)){try{r.dispose?.()}catch{}this.instances.delete(n)}}async buildTurn(e,n,r,s,i,o,a,c,l){let f=r.modelId?.trim()||e.model?.defaultModel?.trim();if(!f)throw new Error(`Custom engine "${e.id}" requires a model selection. Add a "model.defaultModel" to the engine manifest or select a model explicitly.`);let u=r.agentPackId??ls.AGENT_CONSTANTS.DEFAULT_AGENT_ID,d=r.contextSessionId?.trim()||r.sessionId?.trim()||a,p=$I(d),g=this.config.customEnginesStoragePath??Tt.join(this.config.storagePath,ls.AGENT_CONSTANTS.AGENTS_DIR,u,"custom"),m=Tt.join(g,e.id),h=(0,ls.userScopedEngineHomeFromKey)(Tt.join(m,"home"),(0,vI.resolveEngineHomeUserKey)(r.engineHomeUserKey)),E=Tt.join(m,ls.AGENT_CONSTANTS.SESSIONS_DIR,p);await To.promises.mkdir(h,{recursive:!0}),await To.promises.mkdir(E,{recursive:!0});let _=Tt.join(r.workspaceRoot,ls.AGENT_CONSTANTS.AGENTIDE_DIR_NAME,ls.AGENT_CONSTANTS.SESSIONS_DIR,d),y=Tt.join(_,ls.AGENT_CONSTANTS.CONTEXT_MD),b=Tt.join(_,"terminal.md"),T=Tt.join(_,"attachments"),O=this.activeSessions.get(o)?.nativeSessionId??(0,So.getPersistedSessionId)(`custom:${e.id}`,o),A=(0,oc.resolveApiRouting)(r,this.config,(0,oc.inferModelProvider)(r.modelId),i.configProvider),v=A.apiKey?.trim()||void 0,C=A.baseUrl?.trim()||void 0,B=A.openaiBaseUrl?.trim()||void 0,R=e.workspaceSync?.enabled?Tt.join(r.workspaceRoot,e.workspaceSync.dir,e.workspaceSync.rulesFile):void 0,F=e.workspaceSync?.enabled&&e.workspaceSync.includeSkills?Tt.join(r.workspaceRoot,e.workspaceSync.dir,ls.AGENT_CONSTANTS.SKILLS_DIR):void 0,re=e.workspaceSync?.enabled&&e.workspaceSync.includeRules?Tt.join(r.workspaceRoot,e.workspaceSync.dir,ls.AGENT_CONSTANTS.RULES_DIR):void 0,W={...process.env,...i.cliEnvPatch??{},AGENTHIPPO_ENGINE_ID:e.id,AGENTHIPPO_ENGINE_HOME:h,AGENTHIPPO_ENGINE_SESSION_DIR:E,AGENTHIPPO_CONTEXT_SESSION_ID:d,AGENTHIPPO_CONTEXT_EXPORT_PATH:y,AGENTHIPPO_TERMINAL_LOG_PATH:b,AGENTHIPPO_ATTACHMENTS_DIR:T,AGENTHIPPO_ACTIVE_AGENT:u,AGENT_ID:u,AGENTHIPPO_MODEL_ID:f,AGENTHIPPO_USE_LITELLM:A.useLiteLLM?"true":"false"};if(delete W[TI.OPENCLAW_GATEWAY_TOKEN_ENV],delete W.AGENTHIPPO_DATA_PLANE_TOKEN,lc(W,e.manifestDir),v&&(W.AGENTHIPPO_API_KEY=v),C&&(W.AGENTHIPPO_BASE_URL=C),B&&(W.AGENTHIPPO_OPENAI_BASE_URL=B),A.useLiteLLM){W.AGENTHIPPO_LITELLM_API_KEY=v??"sk-dummy",W.AGENTIDE_LITELLM_API_KEY=v??"sk-dummy",C&&(W.AGENTHIPPO_LITELLM_BASE_URL=C,W.AGENTIDE_LITELLM_BASE_URL=C);let Me=(0,So.buildLiteLLMMetadataHeaders)(!0,{sessionId:r.sessionId,analyticsUserId:r.analyticsUserId,analyticsProjectId:(0,So.resolveAnalyticsProjectId)(r.analyticsProjectId,r.workspaceRoot),agentId:u,agentVersion:r.agentPackVersion??"workspace",source:"agenthippo",engine:`custom:${e.id}`,requestId:r.requestId,policyVersion:r.policyVersion,packDigest:r.packDigest,instanceId:r.instanceId,engineVersion:r.engineVersion,tier:r.tier});Me.length>0&&(W.AGENTHIPPO_LITELLM_METADATA_HEADERS=Me.join(`
414
+ `))}r.agentPackVersion&&(W.AGENTHIPPO_AGENT_VERSION=r.agentPackVersion,W.AGENTIDE_AGENT_VERSION=r.agentPackVersion),e.homeEnvVar&&(W[e.homeEnvVar]=h),Xh(W,e,{apiKey:v,baseUrl:C,openaiBaseUrl:B},process.env,i.logger),(C&&(0,oc.applyLocalTlsBypass)(W,C)||B&&B!==C&&(0,oc.applyLocalTlsBypass)(W,B))&&i.logger.info(`[AgentIDE] Disabling TLS verification for local HTTPS (${e.id})`);let de=A.useLiteLLM?"LiteLLM proxy":C?"custom provider":"native provider";i.logger.info(`[AgentIDE] Custom engine "${e.id}" routing: ${de}, baseUrl=${C||"default"}, model=${f}`);let he=await(0,cc.loadMcpServers)(u,r.workspaceRoot,this.getBundledBasePromptsDir()),Q=(0,cc.formatInlineMcpServers)(he,W);he.length>0&&i.logger.debug(`[AgentIDE] Custom engine "${e.id}" MCP (${u}): ${he.map(Me=>Me.name).join(", ")}`);let Ne=n,We={message:Ne,modelId:f,workspaceRoot:r.workspaceRoot,additionalDirectories:r.additionalDirectories??[],permissions:r.permissions??{fileAccess:"workspace-write"},env:W,routing:{useLiteLLM:A.useLiteLLM,...v?{apiKey:v}:{},...C?{baseUrl:C}:{},...B?{openaiBaseUrl:B}:{}},session:{key:o,chatSessionId:a,contextSessionId:d,isEphemeral:c,engineHomeDir:h,engineSessionDir:E,nativeSessionId:O,contextFilePath:y,terminalLogPath:b,attachmentsDir:T},agent:{id:u,version:r.agentPackVersion,rulesFilePath:R,skillsDir:F,rulesDir:re},...Object.keys(Q).length>0?{mcpServers:Q}:{},emitter:s,runtime:{...i,invalidateEngineInstance:()=>this.clearInstances(e.id)},signal:l};if(e.promptInjection.mode==="message-suffix"){let Me=DI(We);Me&&(Ne=`${n}
415
415
 
416
- ${Me}`,We.message=Ne)}return We}onMaintenance(e){let n=Date.now();for(let[r,s]of this.activeSessions.entries())n-s.lastUsedAt>bI&&(this.activeSessions.delete(r),e.info(`[AgentIDE] Closed idle custom engine session (key=${r}, idleMs=${n-s.lastUsedAt})`));for(let{engine:r,manifest:s}of this.instances.values())try{r.onMaintenance?.(e)}catch(i){e.warn(`[AgentIDE] Custom engine "${s.id}" onMaintenance error: ${i}`)}this.workerPool.onMaintenance()}dispose(){this.clearInstances(),this.workerPool.disposeAll(),this.activeSessions.clear(),this.mtimeCache.clear()}};gn.CustomEngine=$u});var oi=S(ce=>{"use strict";var kI=ce&&ce.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,s)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),$I=ce&&ce.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),DI=ce&&ce.__importStar||(function(){var t=function(e){return t=Object.getOwnPropertyNames||function(n){var r=[];for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(r[r.length]=s);return r},t(e)};return function(e){if(e&&e.__esModule)return e;var n={};if(e!=null)for(var r=t(e),s=0;s<r.length;s++)r[s]!=="default"&&kI(n,e,r[s]);return $I(n,e),n}})();Object.defineProperty(ce,"__esModule",{value:!0});ce.resolveModelAlias=ce.getSessionDir=ce.createSessionDir=ce.computeSkillsSignature=ce.syncPackToWorkspace=ce.initSessionStoreWithStore=ce.CLIPermissionHandler=ce.AutoApprovePermissionHandler=ce.DirectorySessionStore=ce.FileSessionStore=ce.MemorySessionStore=ce.StaticConfigProvider=ce.NoOpEditTracker=ce.NoOpLogger=ce.ConsoleLogger=void 0;ce.createHeadlessRunner=Mu;ce.createEvalRunner=WI;ce.createCLIRunner=KI;var zh=DI(require("path")),LI=Nh(),MI=$h(),GI=zs(),Ct=Jl();Object.defineProperty(ce,"ConsoleLogger",{enumerable:!0,get:function(){return Ct.ConsoleLogger}});Object.defineProperty(ce,"NoOpLogger",{enumerable:!0,get:function(){return Ct.NoOpLogger}});Object.defineProperty(ce,"NoOpEditTracker",{enumerable:!0,get:function(){return Ct.NoOpEditTracker}});Object.defineProperty(ce,"StaticConfigProvider",{enumerable:!0,get:function(){return Ct.StaticConfigProvider}});Object.defineProperty(ce,"MemorySessionStore",{enumerable:!0,get:function(){return Ct.MemorySessionStore}});Object.defineProperty(ce,"FileSessionStore",{enumerable:!0,get:function(){return Ct.FileSessionStore}});Object.defineProperty(ce,"DirectorySessionStore",{enumerable:!0,get:function(){return Ct.DirectorySessionStore}});Object.defineProperty(ce,"AutoApprovePermissionHandler",{enumerable:!0,get:function(){return Ct.AutoApprovePermissionHandler}});Object.defineProperty(ce,"CLIPermissionHandler",{enumerable:!0,get:function(){return Ct.CLIPermissionHandler}});var Qh=Js(),UI=vu(),Zh=yo(),HI=Er(),jI=Is(),xI=Ys();function BI(t,e){let n=t?.trim();if(n)return n;let r=e?.trim();if(r)return r;let s=process.env.AGENTHIPPO_ANALYTICS_USER_ID?.trim()||process.env.AGENTIDE_ANALYTICS_USER_ID?.trim();if(s)return s;let i=process.env.LOGNAME?.trim()||process.env.USER?.trim()||process.env.LNAME?.trim()||process.env.USERNAME?.trim();return i||"anonymous"}function Mu(t){if(t.freshState){let _=new Ct.MemorySessionStore;(0,Qh.initSessionStoreWithStore)(_)}else(0,Qh.initSessionStoreWithStore)(new Ct.DirectorySessionStore(zh.join(t.storagePath,"provider-sessions")));let e=!!(t.litellmApiKey||t.openaiApiKey||t.anthropicApiKey),n={storagePath:t.storagePath,codexHome:void 0,claudeConfigDir:void 0,litellmApiKey:t.litellmApiKey??(e?void 0:t.apiKey),litellmBaseUrl:t.baseUrl,openaiApiKey:t.openaiApiKey,anthropicApiKey:t.anthropicApiKey,claudeCodeExecutablePath:t.claudeCodeExecutablePath,codexExecutablePath:t.codexExecutablePath},r=t.logger??new Ct.ConsoleLogger("[AgentIDE]"),s=t.editTracker??new Ct.NoOpEditTracker,i=new Ct.StaticConfigProvider({},t.customProviders??{},t.engineSettings??{}),o=t.permissionHandler??new Ct.AutoApprovePermissionHandler,a={logger:r,editTracker:s,configProvider:i,permissionHandler:o,cliEnvPatch:t.cliEnvPatch},c=t.packId??"default",l=_=>(0,UI.computeSkillsSignature)(_,c),f=()=>t.bundledPromptsDir,u,d,p,g=()=>(u||(u=new MI.ClaudeEngine(n,async(_,y)=>l(_)??`headless-${c}`,f)),u),m=()=>(d||(d=new LI.CodexEngine(n,l,f)),d),h=async()=>{if(!p){let{CustomEngine:_}=await Promise.resolve().then(()=>wn(Lu()));p=new _(n,f)}return p},E=new Zh.SessionEventWriter(t.analyticsSessionsDir??zh.join((0,xI.getAgentideHome)(),"analytics","sessions"));return{async run(_){let y={success:!1,text:"",thinking:"",toolCalls:[]},b=_.emitter??{async thinking(R){y.thinking+=R},async text(R){y.text+=R},async toolStart(R,F,re){y.toolCalls.push({name:R,input:F})},async toolEnd(R,F,re,W){let de=y.toolCalls.find(he=>he.name===R&&!he.result);de&&(de.result=re,de.isError=W)},async progress(R){r.debug(`[Progress] ${R}`)},async question(R){return r.debug(`[Question] ${R.prompt}`),{selected:[],freeText:null,declined:!0}},async error(R){y.error=R},async done(){y.error||(y.success=!0)}},T=(0,GI.generateRequestId)(),O=_.sessionId??`headless-${Date.now()}`,A=t.provenance?.(),v=(0,Zh.wrapEmitterWithObservability)(b,E,O,T,(0,jI.currentCredential)()?.userId,A&&{policy_version:A.policyVersion,pack_digest:A.packDigest,engine_version:A.engineVersion,tier:A.tier,instance_id:A.instanceId}),C={modelId:_.modelId,engineId:_.engineId,workspaceRoot:_.workspaceRoot,additionalDirectories:_.additionalDirectories,sessionId:O,analyticsUserId:BI(_.analyticsUserId,t.analyticsUserId),apiKey:_.modelToken??(e?void 0:t.apiKey),baseUrl:t.baseUrl,useLiteLLM:t.useLiteLLM,agentPackId:c,agentPackVersion:t.packVersion,policyVersion:A?.policyVersion,packDigest:A?.packDigest,engineVersion:A?.engineVersion,tier:A?.tier,instanceId:A?.instanceId,permissions:_.permissions,engineHomeUserKey:_.engineHomeUserKey,requestId:T};await v.emitTurnStart();let B={...a,cliEnvPatch:{...a.cliEnvPatch??{},...(0,HI.buildSessionEnvPatch)({workspaceRoot:_.workspaceRoot,chatSessionId:O,gatewaySessionKey:_.gatewaySessionKey}),..._.turnEnv??{}}};try{let R=_.engineId.trim().toLowerCase();R==="claude"?await g().stream(_.message,C,v,B,_.signal):R==="codex"?await m().stream(_.message,C,v,B,_.signal):await(await h()).stream(_.message,C,v,B,_.signal)}catch(R){y.error=R instanceof Error?R.message:String(R),y.success=!1,await v.error(y.error)}return await v.emitTurnEnd(y.success),y},dispose(){u?.dispose(),d?.dispose(),p?.dispose()}}}var FI=Js();Object.defineProperty(ce,"initSessionStoreWithStore",{enumerable:!0,get:function(){return FI.initSessionStoreWithStore}});var lc=vu();Object.defineProperty(ce,"syncPackToWorkspace",{enumerable:!0,get:function(){return lc.syncPackToWorkspace}});Object.defineProperty(ce,"computeSkillsSignature",{enumerable:!0,get:function(){return lc.computeSkillsSignature}});Object.defineProperty(ce,"createSessionDir",{enumerable:!0,get:function(){return lc.createSessionDir}});Object.defineProperty(ce,"getSessionDir",{enumerable:!0,get:function(){return lc.getSessionDir}});var VI=ya();Object.defineProperty(ce,"resolveModelAlias",{enumerable:!0,get:function(){return VI.resolveModelAlias}});function WI(t,e,n){return Mu({storagePath:t,apiKey:e,baseUrl:n,freshState:!0,logger:new Ct.NoOpLogger})}function KI(t,e,n){return Mu({storagePath:t,apiKey:e,baseUrl:n,logger:new Ct.ConsoleLogger("[Agent]")})}});var ai=S(Bt=>{"use strict";var qI=Bt&&Bt.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,s)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),YI=Bt&&Bt.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),uc=Bt&&Bt.__importStar||(function(){var t=function(e){return t=Object.getOwnPropertyNames||function(n){var r=[];for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(r[r.length]=s);return r},t(e)};return function(e){if(e&&e.__esModule)return e;var n={};if(e!=null)for(var r=t(e),s=0;s<r.length;s++)r[s]!=="default"&&qI(n,e,r[s]);return YI(n,e),n}})();Object.defineProperty(Bt,"__esModule",{value:!0});Bt.resolvePackPath=tm;Bt.listAvailablePacks=QI;Bt.loadAgentPack=ZI;Bt.getDefaultConfig=nP;Bt.getEnvDefaultModel=rP;Bt.getApiConfig=nm;Bt.hasCredentialForEngine=sP;Bt.getFileAccess=iP;var nn=uc(require("fs")),it=uc(require("path")),XI=uc(require("os")),JI=uc(require("js-yaml")),dc=Ke();function So(t,e){return process.env[t]??(e?process.env[e]:void 0)}var zI=process.env.AGENTHIPPO_HOME||it.join(XI.homedir(),dc.AGENTIDE_DIR_NAME),Uu=it.join(zI,"agents"),Gu="agents";function Di(t){if(!nn.existsSync(t))return;let e=it.join(t,"current.txt");if(nn.existsSync(e)){let r=nn.readFileSync(e,"utf-8").trim(),s=it.join(t,r);if(nn.existsSync(s))return s}let n=it.join(t,"agent.yaml");if(nn.existsSync(n))return t;try{let s=nn.readdirSync(t,{withFileTypes:!0}).filter(i=>i.isDirectory()&&/^\d+\.\d+\.\d+/.test(i.name)).map(i=>i.name).sort((i,o)=>{let[a,c,l]=i.split(".").map(p=>parseInt(p,10)||0),[f,u,d]=o.split(".").map(p=>parseInt(p,10)||0);return f!==a?f-a:u!==c?u-c:d-l});for(let i of s){let o=it.join(t,i),a=it.join(o,"agent.yaml");if(nn.existsSync(a))return o}}catch{}}function tm(t,e){if(it.isAbsolute(t)||t.startsWith("./")||t.startsWith("../")){let c=it.isAbsolute(t)?t:it.resolve(process.cwd(),t);if(nn.existsSync(c)){try{if(nn.statSync(c).isDirectory())return Di(c)??c}catch{}return c}return}let n=it.join(process.cwd(),t),r=Di(n);if(r)return r;let s=it.join(process.cwd(),Gu,t),i=Di(s);if(i)return i;if(e){let c=it.join(e,dc.AGENTIDE_DIR_NAME,Gu,t),l=Di(c);if(l)return l}let o=it.join(Uu,t),a=Di(o);if(a)return a}function em(t,e){let n=[];if(!nn.existsSync(t))return n;let r=nn.readdirSync(t,{withFileTypes:!0});for(let s of r){if(!s.isDirectory()||s.name.startsWith("."))continue;let i=it.join(t,s.name),o=Di(i);if(!o)continue;let a;o!==i&&(a=it.basename(o)),n.push({name:s.name,path:o,version:a,source:e})}return n}function QI(t){let e=[],n=new Set;if(t){let s=it.join(t,dc.AGENTIDE_DIR_NAME,Gu),i=em(s,"workspace");for(let o of i)e.push(o),n.add(o.name)}let r=em(Uu,"user-library");for(let s of r)n.has(s.name)||e.push(s);return e}async function ZI(t,e){let n=tm(t,e);if(!n){let u=it.isAbsolute(t)||t.startsWith("./")||t.startsWith("../")?[it.resolve(process.cwd(),t)]:[`${process.cwd()}/${t}`,`${process.cwd()}/agents/${t}`,e?`${e}/${dc.AGENTIDE_DIR_NAME}/agents/${t}`:null,`${Uu}/${t}`].filter(Boolean);throw new Error(`Agent pack not found: ${t}
417
- Searched: ${u.join(", ")}`)}let r=it.join(n,"agent.yaml");if(!nn.existsSync(r))throw new Error(`Missing agent.yaml in pack: ${n}`);let s=nn.readFileSync(r,"utf-8"),i=JI.load(s);tP(i,r);let o=eP(i),a="",c=it.join(n,"AGENTS.md");return nn.existsSync(c)&&(a=nn.readFileSync(c,"utf-8")),{manifest:o,packPath:n,systemPrompt:a,rules:[]}}function eP(t){let e=t.spec.engine?.trim()??"",n=e.toLowerCase();return e!==n?{...t,spec:{...t.spec,engine:n}}:t}function tP(t,e){let n=[];if(t.metadata?.name||n.push("Missing metadata.name"),t.metadata?.version||n.push("Missing metadata.version"),t.spec?.engine?.trim()||n.push("Missing spec.engine"),t.spec?.engine?.trim().toLowerCase()==="custom"&&n.push('Invalid spec.engine: use the concrete custom engine id (for example, openclaw), not "custom"'),t.spec?.cheapModel!==void 0&&typeof t.spec.cheapModel!="string"&&n.push("Invalid spec.cheapModel: must be a string when provided"),t.spec?.dataPlane!==void 0&&((typeof t.spec.dataPlane!="object"||!t.spec.dataPlane.connector?.trim())&&n.push("Invalid spec.dataPlane: requires a `connector` path (stdio MCP module run broker-side)"),t.spec.dataPlane?.provider!==void 0&&typeof t.spec.dataPlane.provider!="string"&&n.push("Invalid spec.dataPlane.provider: must be a string when provided")),n.length>0)throw new Error(`Invalid agent manifest at ${e}:
416
+ ${Me}`,We.message=Ne)}return We}onMaintenance(e){let n=Date.now();for(let[r,s]of this.activeSessions.entries())n-s.lastUsedAt>PI&&(this.activeSessions.delete(r),e.info(`[AgentIDE] Closed idle custom engine session (key=${r}, idleMs=${n-s.lastUsedAt})`));for(let{engine:r,manifest:s}of this.instances.values())try{r.onMaintenance?.(e)}catch(i){e.warn(`[AgentIDE] Custom engine "${s.id}" onMaintenance error: ${i}`)}this.workerPool.onMaintenance()}dispose(){this.clearInstances(),this.workerPool.disposeAll(),this.activeSessions.clear(),this.mtimeCache.clear()}};gn.CustomEngine=Du});var oi=S(ce=>{"use strict";var MI=ce&&ce.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,s)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),GI=ce&&ce.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),UI=ce&&ce.__importStar||(function(){var t=function(e){return t=Object.getOwnPropertyNames||function(n){var r=[];for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(r[r.length]=s);return r},t(e)};return function(e){if(e&&e.__esModule)return e;var n={};if(e!=null)for(var r=t(e),s=0;s<r.length;s++)r[s]!=="default"&&MI(n,e,r[s]);return GI(n,e),n}})();Object.defineProperty(ce,"__esModule",{value:!0});ce.resolveModelAlias=ce.getSessionDir=ce.createSessionDir=ce.computeSkillsSignature=ce.syncPackToWorkspace=ce.initSessionStoreWithStore=ce.CLIPermissionHandler=ce.AutoApprovePermissionHandler=ce.DirectorySessionStore=ce.FileSessionStore=ce.MemorySessionStore=ce.StaticConfigProvider=ce.NoOpEditTracker=ce.NoOpLogger=ce.ConsoleLogger=void 0;ce.createHeadlessRunner=Gu;ce.createEvalRunner=XI;ce.createCLIRunner=JI;var Qh=UI(require("path")),HI=Rh(),jI=Dh(),xI=zs(),Ct=zl();Object.defineProperty(ce,"ConsoleLogger",{enumerable:!0,get:function(){return Ct.ConsoleLogger}});Object.defineProperty(ce,"NoOpLogger",{enumerable:!0,get:function(){return Ct.NoOpLogger}});Object.defineProperty(ce,"NoOpEditTracker",{enumerable:!0,get:function(){return Ct.NoOpEditTracker}});Object.defineProperty(ce,"StaticConfigProvider",{enumerable:!0,get:function(){return Ct.StaticConfigProvider}});Object.defineProperty(ce,"MemorySessionStore",{enumerable:!0,get:function(){return Ct.MemorySessionStore}});Object.defineProperty(ce,"FileSessionStore",{enumerable:!0,get:function(){return Ct.FileSessionStore}});Object.defineProperty(ce,"DirectorySessionStore",{enumerable:!0,get:function(){return Ct.DirectorySessionStore}});Object.defineProperty(ce,"AutoApprovePermissionHandler",{enumerable:!0,get:function(){return Ct.AutoApprovePermissionHandler}});Object.defineProperty(ce,"CLIPermissionHandler",{enumerable:!0,get:function(){return Ct.CLIPermissionHandler}});var Zh=Js(),BI=Ou(),em=Ao(),FI=Er(),VI=Is(),WI=Ys();function KI(t,e){let n=t?.trim();if(n)return n;let r=e?.trim();if(r)return r;let s=process.env.AGENTHIPPO_ANALYTICS_USER_ID?.trim()||process.env.AGENTIDE_ANALYTICS_USER_ID?.trim();if(s)return s;let i=process.env.LOGNAME?.trim()||process.env.USER?.trim()||process.env.LNAME?.trim()||process.env.USERNAME?.trim();return i||"anonymous"}function Gu(t){if(t.freshState){let _=new Ct.MemorySessionStore;(0,Zh.initSessionStoreWithStore)(_)}else(0,Zh.initSessionStoreWithStore)(new Ct.DirectorySessionStore(Qh.join(t.storagePath,"provider-sessions")));let e=!!(t.litellmApiKey||t.openaiApiKey||t.anthropicApiKey),n={storagePath:t.storagePath,codexHome:void 0,claudeConfigDir:void 0,litellmApiKey:t.litellmApiKey??(e?void 0:t.apiKey),litellmBaseUrl:t.baseUrl,openaiApiKey:t.openaiApiKey,anthropicApiKey:t.anthropicApiKey,claudeCodeExecutablePath:t.claudeCodeExecutablePath,codexExecutablePath:t.codexExecutablePath},r=t.logger??new Ct.ConsoleLogger("[AgentIDE]"),s=t.editTracker??new Ct.NoOpEditTracker,i=new Ct.StaticConfigProvider({},t.customProviders??{},t.engineSettings??{}),o=t.permissionHandler??new Ct.AutoApprovePermissionHandler,a={logger:r,editTracker:s,configProvider:i,permissionHandler:o,cliEnvPatch:t.cliEnvPatch},c=t.packId??"default",l=_=>(0,BI.computeSkillsSignature)(_,c),f=()=>t.bundledPromptsDir,u,d,p,g=()=>(u||(u=new jI.ClaudeEngine(n,async(_,y)=>l(_)??`headless-${c}`,f)),u),m=()=>(d||(d=new HI.CodexEngine(n,l,f)),d),h=async()=>{if(!p){let{CustomEngine:_}=await Promise.resolve().then(()=>wn(Mu()));p=new _(n,f)}return p},E=new em.SessionEventWriter(t.analyticsSessionsDir??Qh.join((0,WI.getAgentideHome)(),"analytics","sessions"));return{async run(_){let y={success:!1,text:"",thinking:"",toolCalls:[]},b=_.emitter??{async thinking(R){y.thinking+=R},async text(R){y.text+=R},async toolStart(R,F,re){y.toolCalls.push({name:R,input:F})},async toolEnd(R,F,re,W){let de=y.toolCalls.find(he=>he.name===R&&!he.result);de&&(de.result=re,de.isError=W)},async progress(R){r.debug(`[Progress] ${R}`)},async question(R){return r.debug(`[Question] ${R.prompt}`),{selected:[],freeText:null,declined:!0}},async error(R){y.error=R},async done(){y.error||(y.success=!0)}},T=(0,xI.generateRequestId)(),O=_.sessionId??`headless-${Date.now()}`,A=t.provenance?.(),v=(0,em.wrapEmitterWithObservability)(b,E,O,T,(0,VI.currentCredential)()?.userId,A&&{policy_version:A.policyVersion,pack_digest:A.packDigest,engine_version:A.engineVersion,tier:A.tier,instance_id:A.instanceId}),C={modelId:_.modelId,engineId:_.engineId,workspaceRoot:_.workspaceRoot,additionalDirectories:_.additionalDirectories,sessionId:O,analyticsUserId:KI(_.analyticsUserId,t.analyticsUserId),apiKey:_.modelToken??(e?void 0:t.apiKey),baseUrl:t.baseUrl,useLiteLLM:t.useLiteLLM,agentPackId:c,agentPackVersion:t.packVersion,policyVersion:A?.policyVersion,packDigest:A?.packDigest,engineVersion:A?.engineVersion,tier:A?.tier,instanceId:A?.instanceId,permissions:_.permissions,engineHomeUserKey:_.engineHomeUserKey,requestId:T};await v.emitTurnStart();let B={...a,cliEnvPatch:{...a.cliEnvPatch??{},...(0,FI.buildSessionEnvPatch)({workspaceRoot:_.workspaceRoot,chatSessionId:O,gatewaySessionKey:_.gatewaySessionKey}),..._.turnEnv??{}}};try{let R=_.engineId.trim().toLowerCase();R==="claude"?await g().stream(_.message,C,v,B,_.signal):R==="codex"?await m().stream(_.message,C,v,B,_.signal):await(await h()).stream(_.message,C,v,B,_.signal)}catch(R){y.error=R instanceof Error?R.message:String(R),y.success=!1,await v.error(y.error)}return await v.emitTurnEnd(y.success),y},dispose(){u?.dispose(),d?.dispose(),p?.dispose()}}}var qI=Js();Object.defineProperty(ce,"initSessionStoreWithStore",{enumerable:!0,get:function(){return qI.initSessionStoreWithStore}});var uc=Ou();Object.defineProperty(ce,"syncPackToWorkspace",{enumerable:!0,get:function(){return uc.syncPackToWorkspace}});Object.defineProperty(ce,"computeSkillsSignature",{enumerable:!0,get:function(){return uc.computeSkillsSignature}});Object.defineProperty(ce,"createSessionDir",{enumerable:!0,get:function(){return uc.createSessionDir}});Object.defineProperty(ce,"getSessionDir",{enumerable:!0,get:function(){return uc.getSessionDir}});var YI=wa();Object.defineProperty(ce,"resolveModelAlias",{enumerable:!0,get:function(){return YI.resolveModelAlias}});function XI(t,e,n){return Gu({storagePath:t,apiKey:e,baseUrl:n,freshState:!0,logger:new Ct.NoOpLogger})}function JI(t,e,n){return Gu({storagePath:t,apiKey:e,baseUrl:n,logger:new Ct.ConsoleLogger("[Agent]")})}});var ai=S(Bt=>{"use strict";var zI=Bt&&Bt.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,s)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),QI=Bt&&Bt.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),dc=Bt&&Bt.__importStar||(function(){var t=function(e){return t=Object.getOwnPropertyNames||function(n){var r=[];for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(r[r.length]=s);return r},t(e)};return function(e){if(e&&e.__esModule)return e;var n={};if(e!=null)for(var r=t(e),s=0;s<r.length;s++)r[s]!=="default"&&zI(n,e,r[s]);return QI(n,e),n}})();Object.defineProperty(Bt,"__esModule",{value:!0});Bt.resolvePackPath=nm;Bt.listAvailablePacks=nP;Bt.loadAgentPack=rP;Bt.getDefaultConfig=oP;Bt.getEnvDefaultModel=aP;Bt.getApiConfig=rm;Bt.hasCredentialForEngine=cP;Bt.getFileAccess=lP;var nn=dc(require("fs")),it=dc(require("path")),ZI=dc(require("os")),eP=dc(require("js-yaml")),fc=Ke();function bo(t,e){return process.env[t]??(e?process.env[e]:void 0)}var tP=process.env.AGENTHIPPO_HOME||it.join(ZI.homedir(),fc.AGENTIDE_DIR_NAME),Hu=it.join(tP,"agents"),Uu="agents";function Di(t){if(!nn.existsSync(t))return;let e=it.join(t,"current.txt");if(nn.existsSync(e)){let r=nn.readFileSync(e,"utf-8").trim(),s=it.join(t,r);if(nn.existsSync(s))return s}let n=it.join(t,"agent.yaml");if(nn.existsSync(n))return t;try{let s=nn.readdirSync(t,{withFileTypes:!0}).filter(i=>i.isDirectory()&&/^\d+\.\d+\.\d+/.test(i.name)).map(i=>i.name).sort((i,o)=>{let[a,c,l]=i.split(".").map(p=>parseInt(p,10)||0),[f,u,d]=o.split(".").map(p=>parseInt(p,10)||0);return f!==a?f-a:u!==c?u-c:d-l});for(let i of s){let o=it.join(t,i),a=it.join(o,"agent.yaml");if(nn.existsSync(a))return o}}catch{}}function nm(t,e){if(it.isAbsolute(t)||t.startsWith("./")||t.startsWith("../")){let c=it.isAbsolute(t)?t:it.resolve(process.cwd(),t);if(nn.existsSync(c)){try{if(nn.statSync(c).isDirectory())return Di(c)??c}catch{}return c}return}let n=it.join(process.cwd(),t),r=Di(n);if(r)return r;let s=it.join(process.cwd(),Uu,t),i=Di(s);if(i)return i;if(e){let c=it.join(e,fc.AGENTIDE_DIR_NAME,Uu,t),l=Di(c);if(l)return l}let o=it.join(Hu,t),a=Di(o);if(a)return a}function tm(t,e){let n=[];if(!nn.existsSync(t))return n;let r=nn.readdirSync(t,{withFileTypes:!0});for(let s of r){if(!s.isDirectory()||s.name.startsWith("."))continue;let i=it.join(t,s.name),o=Di(i);if(!o)continue;let a;o!==i&&(a=it.basename(o)),n.push({name:s.name,path:o,version:a,source:e})}return n}function nP(t){let e=[],n=new Set;if(t){let s=it.join(t,fc.AGENTIDE_DIR_NAME,Uu),i=tm(s,"workspace");for(let o of i)e.push(o),n.add(o.name)}let r=tm(Hu,"user-library");for(let s of r)n.has(s.name)||e.push(s);return e}async function rP(t,e){let n=nm(t,e);if(!n){let u=it.isAbsolute(t)||t.startsWith("./")||t.startsWith("../")?[it.resolve(process.cwd(),t)]:[`${process.cwd()}/${t}`,`${process.cwd()}/agents/${t}`,e?`${e}/${fc.AGENTIDE_DIR_NAME}/agents/${t}`:null,`${Hu}/${t}`].filter(Boolean);throw new Error(`Agent pack not found: ${t}
417
+ Searched: ${u.join(", ")}`)}let r=it.join(n,"agent.yaml");if(!nn.existsSync(r))throw new Error(`Missing agent.yaml in pack: ${n}`);let s=nn.readFileSync(r,"utf-8"),i=eP.load(s);iP(i,r);let o=sP(i),a="",c=it.join(n,"AGENTS.md");return nn.existsSync(c)&&(a=nn.readFileSync(c,"utf-8")),{manifest:o,packPath:n,systemPrompt:a,rules:[]}}function sP(t){let e=t.spec.engine?.trim()??"",n=e.toLowerCase();return e!==n?{...t,spec:{...t.spec,engine:n}}:t}function iP(t,e){let n=[];if(t.metadata?.name||n.push("Missing metadata.name"),t.metadata?.version||n.push("Missing metadata.version"),t.spec?.engine?.trim()||n.push("Missing spec.engine"),t.spec?.engine?.trim().toLowerCase()==="custom"&&n.push('Invalid spec.engine: use the concrete custom engine id (for example, openclaw), not "custom"'),t.spec?.cheapModel!==void 0&&typeof t.spec.cheapModel!="string"&&n.push("Invalid spec.cheapModel: must be a string when provided"),t.spec?.dataPlane!==void 0&&((typeof t.spec.dataPlane!="object"||!t.spec.dataPlane.connector?.trim())&&n.push("Invalid spec.dataPlane: requires a `connector` path (stdio MCP module run broker-side)"),t.spec.dataPlane?.provider!==void 0&&typeof t.spec.dataPlane.provider!="string"&&n.push("Invalid spec.dataPlane.provider: must be a string when provided")),n.length>0)throw new Error(`Invalid agent manifest at ${e}:
418
418
  - ${n.join(`
419
- - `)}`)}function nP(){return{engine:(So("AGENTHIPPO_DEFAULT_ENGINE","AGENTIDE_DEFAULT_ENGINE")||"claude").trim().toLowerCase(),model:So("AGENTHIPPO_DEFAULT_MODEL","AGENTIDE_DEFAULT_MODEL")||"claude-sonnet-4-5-20250929"}}function rP(){return So("AGENTHIPPO_DEFAULT_MODEL","AGENTIDE_DEFAULT_MODEL")?.trim()||void 0}function nm(){let t=So("AGENTHIPPO_LITELLM_API_KEY","AGENTIDE_LITELLM_API_KEY"),e=So("AGENTHIPPO_LITELLM_BASE_URL","AGENTIDE_LITELLM_BASE_URL"),n=process.env.ANTHROPIC_API_KEY||process.env.CLAUDE_API_KEY,r=process.env.OPENAI_API_KEY;return{apiKey:t||n||r,baseUrl:e,useLiteLLM:!!e,litellmApiKey:t,openaiApiKey:r,anthropicApiKey:n}}function sP(t,e=nm()){if(e.useLiteLLM)return!0;let n=t.trim().toLowerCase();return n==="claude"?!!e.anthropicApiKey:n==="codex"?!!e.openaiApiKey:!0}function iP(t){return t?.manifest.spec.permissions?.fileAccess??"workspace-write"}});var Hu=S((iH,oP)=>{oP.exports={name:"agenthippo",displayName:"Agent Hippo",description:"Agent Hippo - The easiest way to build and test your AI agents",version:"1.110.19",publisher:"agenthippo",private:!0,engines:{vscode:"^1.93.0"},enabledApiProposals:["chatParticipantAdditions","chatParticipantPrivate","languageModelThinkingPart"],activationEvents:["onStartupFinished","onCommand:agentide.customEngine.list","onCommand:agentide.engine.install","onCommand:agentide.engine.uninstall","onChatParticipant:agentide.claude","onChatParticipant:agentide.codex"],main:"./out/extension.js",contributes:{authentication:[{id:"agenthippo",label:"AgentHippo"}],chatParticipants:[{id:"agentide.claude",name:"claude",fullName:"Claude Agent",description:"AI coding agent powered by Anthropic's Claude Agent SDK",isSticky:!1},{id:"agentide.codex",name:"codex",fullName:"Codex Agent",description:"AI coding agent powered by OpenAI's Codex SDK",isSticky:!1}],mcpServerDefinitionProviders:[{id:"bundled-mcp-servers",label:"Agent Hippo Bundled MCP Servers"}],commands:[{command:"agentide.skills.syncRemote",title:"Sync Remote Skills",category:"Agent Hippo"},{command:"agentide.clearManagedResources",title:"Clear Managed Resources",category:"Agent Hippo"},{command:"agentide.showManagedResources",title:"Show Managed Resources",category:"Agent Hippo"},{command:"agentide.cleanupSessionLogs",title:"Cleanup Old Session Logs",category:"Agent Hippo"},{command:"agentide.pack.install",title:"Install Agent Pack",category:"Agent Hippo"},{command:"agentide.pack.list",title:"List Installed Packs",category:"Agent Hippo"},{command:"agentide.customEngine.list",title:"List Custom Engines",category:"Agent Hippo"},{command:"agentide.pack.uninstall",title:"Uninstall Agent Pack",category:"Agent Hippo"},{command:"agentide.pack.getActive",title:"Get Active Agent Pack",category:"Agent Hippo"},{command:"agentide.pack.create",title:"Create Agent Pack",category:"Agent Hippo"},{command:"agentide.pack.share",title:"Share Agent to User Library",category:"Agent Hippo"},{command:"agentide.pack.publish",title:"Publish Agent to Store",category:"Agent Hippo"},{command:"agentide.skill.share",title:"Save Skill to User Library",category:"Agent Hippo"},{command:"agentide.skill.publish",title:"Publish Skill to Store",category:"Agent Hippo"},{command:"agentide.mcp.share",title:"Save MCP Server to User Library",category:"Agent Hippo"},{command:"agentide.mcp.publish",title:"Publish MCP Server to Store",category:"Agent Hippo"},{command:"agenthippo.signIn",title:"Sign In to AgentHippo",category:"Agent Hippo"},{command:"agenthippo.signOut",title:"Sign Out of AgentHippo",category:"Agent Hippo"},{command:"agentide.store.find",title:"Install Packs, Skills, MCP Tools, Engines, Spotlight Views",category:"Agent Hippo"},{command:"agentide.engine.install",title:"Install Custom Engine",category:"Agent Hippo"},{command:"agentide.engine.uninstall",title:"Uninstall Custom Engine",category:"Agent Hippo"},{command:"agentide.engine.publish",title:"Publish Engine to Store",category:"Agent Hippo"},{command:"agentide.spotlight.publish",title:"Publish Spotlight View to Store (Full Bundle)",category:"Agent Hippo"},{command:"agentide.view.install",title:"Install Spotlight View",category:"Agent Hippo"},{command:"agentide.store.sync",title:"Sync Store Index",category:"Agent Hippo"},{command:"agentide.store.setup",title:"Setup Store Index Automation",category:"Agent Hippo"},{command:"agentide.pack.browseLibrary",title:"Browse User Library",category:"Agent Hippo"},{command:"agentide.pack.update",title:"Update Agent from User Library",category:"Agent Hippo"},{command:"agentide.pack.duplicate",title:"Duplicate Agent",category:"Agent Hippo"},{command:"agentide.pack.refresh",title:"Refresh Agent Packs",category:"Agent Hippo"},{command:"agentide.pack.resetDefault",title:"Reset Default Agent",category:"Agent Hippo"},{command:"agentide.gateway.connect",title:"Connect to Gateway",category:"Agent Hippo"},{command:"agentide.gateway.disconnect",title:"Disconnect from Gateway",category:"Agent Hippo"},{command:"agentide.gateway.toggle",title:"Toggle Gateway Connection",category:"Agent Hippo"},{command:"agentide.gateway.status",title:"Show Gateway Status",category:"Agent Hippo"},{command:"agentide.gateway.connectSession",title:"Connect Chat to Gateway",category:"Agent Hippo"},{command:"agentide.gateway.listSessions",title:"Show Connected Gateway Sessions",category:"Agent Hippo"},{command:"agentide.gateway.resetMappings",title:"Reset Agent Mappings (Gateway)",category:"Agent Hippo"},{command:"agentide.anywhere.toggle",title:"Agent Anywhere",category:"Agent Hippo"},{command:"agentide.anywhere.install",title:"Install Agent Anywhere (Gateway)",category:"Agent Hippo"},{command:"agentide.anywhere.uninstall",title:"Uninstall Agent Anywhere (OpenClaw CLI)",category:"Agent Hippo"},{command:"agentide.anywhere.start",title:"Start Agent Anywhere",category:"Agent Hippo"},{command:"agentide.anywhere.stop",title:"Stop Agent Anywhere",category:"Agent Hippo"},{command:"agentide.anywhere.status",title:"Agent Anywhere Status",category:"Agent Hippo"},{command:"agentide.anywhere.connect",title:"Connect Agent Anywhere",category:"Agent Hippo"},{command:"agentide.anywhere.disconnect",title:"Disconnect Agent Anywhere",category:"Agent Hippo"},{command:"agentide.anywhere.openConfig",title:"Open Agent Anywhere Config",category:"Agent Hippo"},{command:"agentide.anywhere.openWebUI",title:"Open Agent Anywhere Web UI",category:"Agent Hippo"},{command:"agentide.anywhere.detect",title:"Detect Agent Anywhere Gateway",category:"Agent Hippo"},{command:"agentide.anywhere.meetAgent",title:"Meet Agent Anywhere...",category:"Agent Hippo"},{command:"agentide.setupCli",title:"Setup AgentHippo CLI",category:"Agent Hippo"},{command:"agentide.cli.status",title:"AgentHippo CLI Status",category:"Agent Hippo"},{command:"agentide.installBundledTools",title:"Install Bundled Tools (rg, sg, tree-sitter)",category:"Agent Hippo"},{command:"agentide.setupAnalytics",title:"Install Spotlight (OTEL + DuckDB)",category:"Agent Hippo"},{command:"agentide.analytics.toggle",title:"Manage Spotlight",category:"Agent Hippo"},{command:"agentide.analytics.start",title:"Start Spotlight (OTEL + LiteLLM)",category:"Agent Hippo"},{command:"agentide.analytics.stop",title:"Stop Spotlight (OTEL + LiteLLM)",category:"Agent Hippo"},{command:"agentide.analytics.status",title:"Show Spotlight Status",category:"Agent Hippo"},{command:"agentide.analytics.query",title:"Query Spotlight (Cost, Sessions)",category:"Agent Hippo"},{command:"agentide.analytics.openDashboard",title:"Open Spotlight Dashboard",category:"Agent Hippo"},{command:"agentide.fleet.open",title:"Open Agent Team",category:"Agent Hippo"},{command:"agentide.analytics.clearArtifacts",title:"Clear Spotlight Artifacts",category:"Agent Hippo"},{command:"agentide.analytics.regenerateDefaults",title:"Regenerate Default Charts",category:"Agent Hippo"}],menus:{ChatModePicker:[{command:"agentide.anywhere.meetAgent",group:"navigation@30",when:"agentide.anywhere.enabled && !agentide.anywhere.hidden",icon:"$(broadcast)"}]},viewsContainers:{activitybar:[{id:"agentide-analytics",title:"Agent Hippo",icon:"$(graph)"},{id:"agentide-team",title:"Agent Team",icon:"$(organization)"}]},views:{"agentide-analytics":[{type:"webview",id:"agentide.analyticsView",name:"Spotlight"}],"agentide-team":[{type:"webview",id:"agentide.teamView",name:"Agent Team"}]},configuration:{title:"Agent Hippo",properties:{"agentide.permissions.fileAccess":{type:"string",scope:"application",enum:["read-only","workspace-write","full"],default:"full",markdownDescription:"Filesystem access scope (applies to all engines).\n- `read-only`: Read/search only (no file writes)\n- `workspace-write`: Read/write within workspace folders only\n- `full`: Full filesystem access (yolo, default)\n\n**Security**: Agent manifest permissions take precedence - user cannot override stricter pack permissions."},"agentide.claude.maxThinkingTokens":{type:"number",default:1024,description:"Claude extended thinking budget (tokens). Set to 0 to disable. Requires a compatible model; Anthropic requires >=1024 for extended thinking."},"agentide.claude.cheapModel":{type:"string",default:"",description:"Optional cheap Claude model for subagents/background routing (for example, claude-haiku-4-5-20251001). Main model selection still comes from the model picker."},"agentide.sessions.retentionDays":{type:"number",default:7,minimum:1,maximum:365,description:"Number of days to retain session logs before cleanup. Cleanup runs on startup (best-effort) and via the 'Agent Hippo: Cleanup Old Session Logs' command."},"agentide.fallbackDirectory":{type:"string",scope:"machine",default:".agent-hippo",description:"Directory name (relative to home) used as workspace when no folder is open. Default: ~/.agent-hippo"},"agentide.additionalEngineDir":{type:"string",scope:"machine",default:"",description:"Additional directories to scan for custom engines. Machine-scoped: engines discovered here are executed, so a workspace must not be able to point this at attacker-controlled code."},"agentide.auth.baseUrl":{type:"string",scope:"application",default:"https://auth.agenthippo.ai",markdownDescription:"AgentHippo auth broker base URL for team sign-in and bootstrap (`agenthippo.signIn`).\n\n**Application-scoped on purpose**: this endpoint receives your PKCE authorization code and your AgentHippo access token, and its `/api/ide/bootstrap` response is written into your model-routing settings. A workspace must never be able to redirect it. Must be `https://` (plain `http://` is accepted only for loopback dev hosts)."},"agentide.cli.path":{type:"string",scope:"machine",default:"",description:"Optional absolute path to the AgentHippo CLI binary. If unset, Agent Hippo auto-detects a bundled binary or falls back to PATH. Machine-scoped: this path is executed."},"agentide.cli.installSource":{type:"string",scope:"machine",default:"",description:"Optional setup source for AgentHippo CLI. Supports HTTPS URL to a prebuilt binary, or local file path. If empty, setup builds from the local repository. Machine-scoped: this source is downloaded and executed."},"agentide.storeRepo":{type:"string",scope:"application",default:"agenthippoai/agenthippo-store",markdownDescription:"GitHub repository for pack store (owner/repo format).\n\nDefault: `agenthippoai/agenthippo-store` ([github.com/agenthippoai/agenthippo-store](https://github.com/agenthippoai/agenthippo-store))\n\nSet to your own repo (e.g., `mycompany/our-packs`) to use a private or custom store."},"agentide.store.indexUrl":{type:"string",scope:"application",default:"https://agenthippoai.github.io/agenthippo-store",markdownDescription:`Base URL for the store index (Orama + metadata are loaded from paths under this URL).
419
+ - `)}`)}function oP(){return{engine:(bo("AGENTHIPPO_DEFAULT_ENGINE","AGENTIDE_DEFAULT_ENGINE")||"claude").trim().toLowerCase(),model:bo("AGENTHIPPO_DEFAULT_MODEL","AGENTIDE_DEFAULT_MODEL")||"claude-sonnet-4-5-20250929"}}function aP(){return bo("AGENTHIPPO_DEFAULT_MODEL","AGENTIDE_DEFAULT_MODEL")?.trim()||void 0}function rm(){let t=bo("AGENTHIPPO_LITELLM_API_KEY","AGENTIDE_LITELLM_API_KEY"),e=bo("AGENTHIPPO_LITELLM_BASE_URL","AGENTIDE_LITELLM_BASE_URL"),n=process.env.ANTHROPIC_API_KEY||process.env.CLAUDE_API_KEY,r=process.env.OPENAI_API_KEY;return{apiKey:t||n||r,baseUrl:e,useLiteLLM:!!e,litellmApiKey:t,openaiApiKey:r,anthropicApiKey:n}}function cP(t,e=rm()){if(e.useLiteLLM)return!0;let n=t.trim().toLowerCase();return n==="claude"?!!e.anthropicApiKey:n==="codex"?!!e.openaiApiKey:!0}function lP(t){return t?.manifest.spec.permissions?.fileAccess??"workspace-write"}});var pc=S((lH,uP)=>{uP.exports={name:"agenthippo",displayName:"Agent Hippo",description:"Agent Hippo - The easiest way to build and test your AI agents",version:"1.110.20",agenthippo:{litellmImageTag:"0.2.8",hippoclawNpm:"@agenthippo-ai/hippoclaw@2026.7.28"},publisher:"agenthippo",private:!0,engines:{vscode:"^1.93.0"},enabledApiProposals:["chatParticipantAdditions","chatParticipantPrivate","languageModelThinkingPart"],activationEvents:["onStartupFinished","onCommand:agentide.customEngine.list","onCommand:agentide.engine.install","onCommand:agentide.engine.uninstall","onChatParticipant:agentide.claude","onChatParticipant:agentide.codex"],main:"./out/extension.js",contributes:{authentication:[{id:"agenthippo",label:"AgentHippo"}],chatParticipants:[{id:"agentide.claude",name:"claude",fullName:"Claude Agent",description:"AI coding agent powered by Anthropic's Claude Agent SDK",isSticky:!1},{id:"agentide.codex",name:"codex",fullName:"Codex Agent",description:"AI coding agent powered by OpenAI's Codex SDK",isSticky:!1}],mcpServerDefinitionProviders:[{id:"bundled-mcp-servers",label:"Agent Hippo Bundled MCP Servers"}],commands:[{command:"agentide.skills.syncRemote",title:"Sync Remote Skills",category:"Agent Hippo"},{command:"agentide.clearManagedResources",title:"Clear Managed Resources",category:"Agent Hippo"},{command:"agentide.showManagedResources",title:"Show Managed Resources",category:"Agent Hippo"},{command:"agentide.cleanupSessionLogs",title:"Cleanup Old Session Logs",category:"Agent Hippo"},{command:"agentide.pack.install",title:"Install Agent Pack",category:"Agent Hippo"},{command:"agentide.pack.list",title:"List Installed Packs",category:"Agent Hippo"},{command:"agentide.customEngine.list",title:"List Custom Engines",category:"Agent Hippo"},{command:"agentide.pack.uninstall",title:"Uninstall Agent Pack",category:"Agent Hippo"},{command:"agentide.pack.getActive",title:"Get Active Agent Pack",category:"Agent Hippo"},{command:"agentide.pack.create",title:"Create Agent Pack",category:"Agent Hippo"},{command:"agentide.pack.share",title:"Share Agent to User Library",category:"Agent Hippo"},{command:"agentide.pack.publish",title:"Publish Agent to Store",category:"Agent Hippo"},{command:"agentide.skill.share",title:"Save Skill to User Library",category:"Agent Hippo"},{command:"agentide.skill.publish",title:"Publish Skill to Store",category:"Agent Hippo"},{command:"agentide.mcp.share",title:"Save MCP Server to User Library",category:"Agent Hippo"},{command:"agentide.mcp.publish",title:"Publish MCP Server to Store",category:"Agent Hippo"},{command:"agenthippo.signIn",title:"Sign In to AgentHippo",category:"Agent Hippo"},{command:"agenthippo.signOut",title:"Sign Out of AgentHippo",category:"Agent Hippo"},{command:"agentide.store.find",title:"Install Packs, Skills, MCP Tools, Engines, Spotlight Views",category:"Agent Hippo"},{command:"agentide.engine.install",title:"Install Custom Engine",category:"Agent Hippo"},{command:"agentide.engine.uninstall",title:"Uninstall Custom Engine",category:"Agent Hippo"},{command:"agentide.engine.publish",title:"Publish Engine to Store",category:"Agent Hippo"},{command:"agentide.spotlight.publish",title:"Publish Spotlight View to Store (Full Bundle)",category:"Agent Hippo"},{command:"agentide.view.install",title:"Install Spotlight View",category:"Agent Hippo"},{command:"agentide.store.sync",title:"Sync Store Index",category:"Agent Hippo"},{command:"agentide.store.setup",title:"Setup Store Index Automation",category:"Agent Hippo"},{command:"agentide.pack.browseLibrary",title:"Browse User Library",category:"Agent Hippo"},{command:"agentide.pack.update",title:"Update Agent from User Library",category:"Agent Hippo"},{command:"agentide.pack.duplicate",title:"Duplicate Agent",category:"Agent Hippo"},{command:"agentide.pack.refresh",title:"Refresh Agent Packs",category:"Agent Hippo"},{command:"agentide.pack.resetDefault",title:"Reset Default Agent",category:"Agent Hippo"},{command:"agentide.gateway.connect",title:"Connect to Gateway",category:"Agent Hippo"},{command:"agentide.gateway.disconnect",title:"Disconnect from Gateway",category:"Agent Hippo"},{command:"agentide.gateway.toggle",title:"Toggle Gateway Connection",category:"Agent Hippo"},{command:"agentide.gateway.status",title:"Show Gateway Status",category:"Agent Hippo"},{command:"agentide.gateway.connectSession",title:"Connect Chat to Gateway",category:"Agent Hippo"},{command:"agentide.gateway.listSessions",title:"Show Connected Gateway Sessions",category:"Agent Hippo"},{command:"agentide.gateway.resetMappings",title:"Reset Agent Mappings (Gateway)",category:"Agent Hippo"},{command:"agentide.anywhere.toggle",title:"Agent Anywhere",category:"Agent Hippo"},{command:"agentide.anywhere.install",title:"Install Agent Anywhere (Gateway)",category:"Agent Hippo"},{command:"agentide.anywhere.uninstall",title:"Uninstall Agent Anywhere (OpenClaw CLI)",category:"Agent Hippo"},{command:"agentide.anywhere.start",title:"Start Agent Anywhere",category:"Agent Hippo"},{command:"agentide.anywhere.stop",title:"Stop Agent Anywhere",category:"Agent Hippo"},{command:"agentide.anywhere.status",title:"Agent Anywhere Status",category:"Agent Hippo"},{command:"agentide.anywhere.connect",title:"Connect Agent Anywhere",category:"Agent Hippo"},{command:"agentide.anywhere.disconnect",title:"Disconnect Agent Anywhere",category:"Agent Hippo"},{command:"agentide.anywhere.openConfig",title:"Open Agent Anywhere Config",category:"Agent Hippo"},{command:"agentide.anywhere.openWebUI",title:"Open Agent Anywhere Web UI",category:"Agent Hippo"},{command:"agentide.anywhere.detect",title:"Detect Agent Anywhere Gateway",category:"Agent Hippo"},{command:"agentide.anywhere.meetAgent",title:"Meet Agent Anywhere...",category:"Agent Hippo"},{command:"agentide.setupCli",title:"Setup AgentHippo CLI",category:"Agent Hippo"},{command:"agentide.cli.status",title:"AgentHippo CLI Status",category:"Agent Hippo"},{command:"agentide.installBundledTools",title:"Install Bundled Tools (rg, sg, tree-sitter)",category:"Agent Hippo"},{command:"agentide.setupAnalytics",title:"Install Spotlight (OTEL + DuckDB)",category:"Agent Hippo"},{command:"agentide.analytics.toggle",title:"Manage Spotlight",category:"Agent Hippo"},{command:"agentide.analytics.start",title:"Start Spotlight (OTEL + LiteLLM)",category:"Agent Hippo"},{command:"agentide.analytics.stop",title:"Stop Spotlight (OTEL + LiteLLM)",category:"Agent Hippo"},{command:"agentide.analytics.status",title:"Show Spotlight Status",category:"Agent Hippo"},{command:"agentide.analytics.query",title:"Query Spotlight (Cost, Sessions)",category:"Agent Hippo"},{command:"agentide.analytics.openDashboard",title:"Open Spotlight Dashboard",category:"Agent Hippo"},{command:"agentide.fleet.open",title:"Open Agent Team",category:"Agent Hippo"},{command:"agentide.analytics.clearArtifacts",title:"Clear Spotlight Artifacts",category:"Agent Hippo"},{command:"agentide.analytics.regenerateDefaults",title:"Regenerate Default Charts",category:"Agent Hippo"}],menus:{ChatModePicker:[{command:"agentide.anywhere.meetAgent",group:"navigation@30",when:"agentide.anywhere.enabled && !agentide.anywhere.hidden",icon:"$(broadcast)"}]},viewsContainers:{activitybar:[{id:"agentide-analytics",title:"Agent Hippo",icon:"$(graph)"},{id:"agentide-team",title:"Agent Team",icon:"$(organization)"}]},views:{"agentide-analytics":[{type:"webview",id:"agentide.analyticsView",name:"Spotlight"}],"agentide-team":[{type:"webview",id:"agentide.teamView",name:"Agent Team"}]},configuration:{title:"Agent Hippo",properties:{"agentide.permissions.fileAccess":{type:"string",scope:"application",enum:["read-only","workspace-write","full"],default:"full",markdownDescription:"Filesystem access scope (applies to all engines).\n- `read-only`: Read/search only (no file writes)\n- `workspace-write`: Read/write within workspace folders only\n- `full`: Full filesystem access (yolo, default)\n\n**Security**: Agent manifest permissions take precedence - user cannot override stricter pack permissions."},"agentide.claude.maxThinkingTokens":{type:"number",default:1024,description:"Claude extended thinking budget (tokens). Set to 0 to disable. Requires a compatible model; Anthropic requires >=1024 for extended thinking."},"agentide.claude.cheapModel":{type:"string",default:"",description:"Optional cheap Claude model for subagents/background routing (for example, claude-haiku-4-5-20251001). Main model selection still comes from the model picker."},"agentide.sessions.retentionDays":{type:"number",default:7,minimum:1,maximum:365,description:"Number of days to retain session logs before cleanup. Cleanup runs on startup (best-effort) and via the 'Agent Hippo: Cleanup Old Session Logs' command."},"agentide.fallbackDirectory":{type:"string",scope:"machine",default:".agent-hippo",description:"Directory name (relative to home) used as workspace when no folder is open. Default: ~/.agent-hippo"},"agentide.additionalEngineDir":{type:"string",scope:"machine",default:"",description:"Additional directories to scan for custom engines. Machine-scoped: engines discovered here are executed, so a workspace must not be able to point this at attacker-controlled code."},"agentide.auth.baseUrl":{type:"string",scope:"application",default:"https://auth.agenthippo.ai",markdownDescription:"AgentHippo auth broker base URL for team sign-in and bootstrap (`agenthippo.signIn`).\n\n**Application-scoped on purpose**: this endpoint receives your PKCE authorization code and your AgentHippo access token, and its `/api/ide/bootstrap` response is written into your model-routing settings. A workspace must never be able to redirect it. Must be `https://` (plain `http://` is accepted only for loopback dev hosts)."},"agentide.cli.path":{type:"string",scope:"machine",default:"",description:"Optional absolute path to the AgentHippo CLI binary. If unset, Agent Hippo auto-detects a bundled binary or falls back to PATH. Machine-scoped: this path is executed."},"agentide.cli.installSource":{type:"string",scope:"machine",default:"",description:"Optional setup source for AgentHippo CLI. Supports HTTPS URL to a prebuilt binary, or local file path. If empty, setup builds from the local repository. Machine-scoped: this source is downloaded and executed."},"agentide.storeRepo":{type:"string",scope:"application",default:"agenthippoai/agenthippo-store",markdownDescription:"GitHub repository for pack store (owner/repo format).\n\nDefault: `agenthippoai/agenthippo-store` ([github.com/agenthippoai/agenthippo-store](https://github.com/agenthippoai/agenthippo-store))\n\nSet to your own repo (e.g., `mycompany/our-packs`) to use a private or custom store."},"agentide.store.indexUrl":{type:"string",scope:"application",default:"https://agenthippoai.github.io/agenthippo-store",markdownDescription:`Base URL for the store index (Orama + metadata are loaded from paths under this URL).
420
420
 
421
421
  Default: \`https://agenthippoai.github.io/agenthippo-store\`
422
422
 
@@ -450,38 +450,38 @@ When enabled, JSONL trace files are incrementally converted to an indexed DuckDB
450
450
 
451
451
  **Application-scoped on purpose**: this host receives your Anthropic key and your prompts.`},"agentide.AgentHippoModelGateway.url":{type:"string",scope:"application",default:"",markdownDescription:"AgentHippo managed model gateway base URL (default `https://gateway.agenthippo.ai/v1`).\n\n**Application-scoped on purpose**: this host receives your AgentHippo sign-in JWT and your prompts."},"agentide.skills.remote.enabled":{type:"boolean",scope:"application",default:!1,description:"Sync skills from a remote skill registry into the default agent."},"agentide.skills.remote.registryUrl":{type:"string",scope:"application",default:"",markdownDescription:`Remote skill registry base URL.
452
452
 
453
- **Application-scoped on purpose**: skills fetched from here become agent instructions and tool definitions on this machine, so this is an install source.`},"agentide.skills.remote.syncOnStartup":{type:"boolean",scope:"application",default:!0,description:"Sync remote skills on extension startup (requires agentide.skills.remote.enabled)."},"agentide.skills.remote.allowOverwriteLocal":{type:"boolean",scope:"application",default:!1,description:"Allow remote skills to overwrite locally-authored skill files of the same name."},"agentide.skills.remote.timeoutMs":{type:"number",scope:"application",default:8e3,minimum:500,maximum:12e4,description:"Timeout (milliseconds) for remote skill registry requests."}}}},capabilities:{untrustedWorkspaces:{supported:"limited",description:"Agent Hippo runs AI agents that read your code, spawn processes, and send prompts to remote model endpoints. In an untrusted workspace the security-relevant settings below are ignored in favour of your user/application values, and remote agent packs (`spec.remote.url`) will not receive your AgentHippo access token without an explicit per-host approval.",restrictedConfigurations:["agentide.auth.baseUrl","agentide.storeRepo","agentide.store.indexUrl","agentide.anywhere.installSource","agentide.anywhere.enabled","agentide.anywhere.autoStart","agentide.anywhere.autoConnect","agentide.anywhere.port","agentide.anywhere.hidden","agentide.cli.path","agentide.cli.installSource","agentide.additionalEngineDir","agentide.fallbackDirectory","agentide.permissions.fileAccess","agentide.gateway.url","agentide.gateway.token","agentide.gateway.autoConnect","agentide.gateway.autoRegister","agentide.gateway.agents","agentide.providers.litellm.baseUrl","agentide.providers.anthropic.baseUrl","agentide.AgentHippoModelGateway.url","agentide.skills.remote.enabled","agentide.skills.remote.registryUrl","agentide.skills.remote.syncOnStartup","agentide.skills.remote.allowOverwriteLocal","agentide.analytics.fleetSources","agentide.analytics.fleetScriptSources","agentide.analytics.defaultDashboardPrompt","agentide.analytics.duckdb.tempDirectory"]}},dependencies:{"@agenthippo-ai/evidence-ship":"0.2.4","@anthropic-ai/claude-agent-sdk":"0.2.71","@anthropic-ai/sdk":"0.78.0","@cfworker/json-schema":"^4.1.1","@mariozechner/pi-ai":"0.54.0","@modelcontextprotocol/sdk":"^1.25.3","@openai/codex":"^0.131.0","@openai/codex-sdk":"^0.131.0","@orama/orama":"^3.1.6",commander:"^14.0.2",hono:"^4.11.5","js-yaml":"^4.1.1",zod:"^4.3.6"},devDependencies:{"@types/js-yaml":"^4.0.9","@types/mocha":"^10.0.10","@types/node":"^25.x"},scripts:{postinstall:"node ./scripts/vendor-tools.mjs --skip-if-present || true",compile:"node ../../node_modules/typescript/bin/tsc -p ./ && node ./scripts/generate-embedded-custom-engine-runner.mjs && node ./scripts/copy-compile-assets.mjs",watch:"node ../../node_modules/typescript/bin/tsc -watch -p ./",test:"node ../../node_modules/mocha/bin/mocha","test:serve-load":"bash ../../scripts/load/run-serve-load.sh","test:serve-load:full":"bash ../../scripts/load/run-serve-load.sh --full",cli:"node out/cli/index.js","build:tools":"node ./scripts/vendor-tools.mjs --clean","build:cli":"./scripts/build-cli.sh","build:cli:macos-arm64":"./scripts/build-cli.sh --target bun-darwin-arm64 --outfile dist/agenthippo-macos-arm64","build:cli:macos-x64":"./scripts/build-cli.sh --target bun-darwin-x64 --outfile dist/agenthippo-macos-x64","build:cli:linux-x64":"./scripts/build-cli.sh --target bun-linux-x64 --outfile dist/agenthippo-linux-x64","build:cli:linux-arm64":"./scripts/build-cli.sh --target bun-linux-arm64 --outfile dist/agenthippo-linux-arm64"}}});var To=S(kt=>{"use strict";var aP=kt&&kt.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,s)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),cP=kt&&kt.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),xu=kt&&kt.__importStar||(function(){var t=function(e){return t=Object.getOwnPropertyNames||function(n){var r=[];for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(r[r.length]=s);return r},t(e)};return function(e){if(e&&e.__esModule)return e;var n={};if(e!=null)for(var r=t(e),s=0;s<r.length;s++)r[s]!=="default"&&aP(n,e,r[s]);return cP(n,e),n}})();Object.defineProperty(kt,"__esModule",{value:!0});kt.getDepsDir=Li;kt.resolveFromOwnDeps=ju;kt.areDepsInstalled=sm;kt.installDeps=im;kt.isAutoInstallDisabled=om;kt.ensureDeps=fP;kt.getClaudeSdkCliPath=pP;kt.getCodexSdkBinaryPath=gP;kt.installedEngineVersion=mP;var Ft=xu(require("fs")),lP=xu(require("os")),ct=xu(require("path")),uP=require("child_process"),Ur=Wn(),fc=Ke();function dP(){let e=(()=>{try{return Hu()}catch{return}})()?.dependencies??{};return{"@anthropic-ai/claude-agent-sdk":e["@anthropic-ai/claude-agent-sdk"]??"^0.2.19","@openai/codex":e["@openai/codex"]??"^0.131.0","@openai/codex-sdk":e["@openai/codex-sdk"]??"^0.131.0"}}var rm=dP();function Li(){let t=ct.dirname(process.execPath),e=ct.join(t,fc.AGENTIDE_DEPS_DIR_NAME);if(Ft.existsSync(e))return e;try{return Ft.accessSync(t,Ft.constants.W_OK),e}catch{return ct.join(lP.homedir(),fc.AGENTIDE_DIR_NAME,fc.AGENTIDE_DEPS_DIR_NAME)}}function ju(t,e){let n=__dirname;for(let r=0;r<8;r++){let s=ct.join(n,"node_modules",...t.split("/"),...e.split("/"));try{if(Ft.existsSync(s))return s}catch{}let i=ct.dirname(n);if(i===n)break;n=i}}function sm(){let t=Li(),e=ct.join(t,"node_modules"),n=ct.join(t,"package.json");try{if(!Ft.existsSync(n))return!1;let o=Ft.readFileSync(n,"utf8"),c=JSON.parse(o).dependencies??{};for(let[l,f]of Object.entries(rm))if(c[l]!==f)return!1}catch{return!1}let r=ct.join(e,"@anthropic-ai","claude-agent-sdk","cli.js"),s=ct.join(e,"@openai","codex","bin","codex.js"),i=ct.join(e,"@openai","codex-sdk","package.json");return Ft.existsSync(r)&&Ft.existsSync(s)&&Ft.existsSync(i)}async function im(t=!1){let e=Li();console.log(`${Ur.COLORS.cyan}Installing engine dependencies...${Ur.COLORS.reset}`),t&&console.log(` Directory: ${e}`),Ft.mkdirSync(e,{recursive:!0});let n={name:fc.AGENTIDE_DEPS_PACKAGE_NAME,version:"1.0.0",private:!0,dependencies:rm};Ft.writeFileSync(ct.join(e,"package.json"),JSON.stringify(n,null,2)+`
454
- `);try{let r=process.platform==="win32"?"npm.cmd":"npm";(0,uP.execSync)(`${r} install --production --no-audit --no-fund`,{cwd:e,stdio:t?"inherit":"pipe"}),console.log(`${Ur.COLORS.green}Dependencies installed${Ur.COLORS.reset}`)}catch(r){throw console.error(`${Ur.COLORS.red}Error: Failed to install dependencies${Ur.COLORS.reset}`),r instanceof Error&&console.error(` ${r.message}`),r}}function om(){let t=(process.env.AGENTHIPPO_NO_AUTO_INSTALL??process.env.AGENTIDE_NO_AUTO_INSTALL??"").trim().toLowerCase();return t==="1"||t==="true"||t==="yes"||t==="on"}async function fP(t=!1){if(!sm()){if(ju("@anthropic-ai/claude-agent-sdk","cli.js")&&ju("@openai/codex","bin/codex.js")){t&&console.error(`${Ur.COLORS.dim}Engine SDKs resolved from the CLI's own node_modules \u2014 skipping install.${Ur.COLORS.reset}`);return}if(om()){t&&console.error(`${Ur.COLORS.dim}AGENTHIPPO_NO_AUTO_INSTALL set \u2014 skipping engine dependency install (expecting a self-contained image).${Ur.COLORS.reset}`);return}await im(t)}}function pP(){let t=Li(),e=ct.join(t,"node_modules","@anthropic-ai","claude-agent-sdk","cli.js");return Ft.existsSync(e)?e:void 0}function gP(){let t=Li(),e=ct.join(t,"node_modules","@openai","codex","bin","codex.js");if(Ft.existsSync(e))return e;let n=ct.join(t,"node_modules","@openai","codex-sdk"),r=hP();if(!r)return;let s=process.platform==="win32"?"codex.exe":"codex",i=ct.join(n,"vendor",r,"codex",s);return Ft.existsSync(i)?i:void 0}function hP(){let t=process.arch,e=process.platform;if(e==="darwin")return t==="arm64"?"aarch64-apple-darwin":"x86_64-apple-darwin";if(e==="linux")return t==="arm64"?"aarch64-unknown-linux-musl":"x86_64-unknown-linux-musl";if(e==="win32")return t==="arm64"?"aarch64-pc-windows-msvc":"x86_64-pc-windows-msvc"}function mP(t){let e=t==="codex"?ct.join("@openai","codex"):t==="claude"?ct.join("@anthropic-ai","claude-agent-sdk"):void 0;if(!e)return;let n=[ct.join(Li(),"node_modules",e,"package.json"),ct.join("/usr/local/lib/node_modules",e,"package.json"),ct.join("/usr/lib/node_modules",e,"package.json")];for(let r of n)try{if(!Ft.existsSync(r))continue;let s=JSON.parse(Ft.readFileSync(r,"utf8"));if(s.version)return s.version}catch{}}});var Wn=S(bt=>{"use strict";var EP=bt&&bt.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,s)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),_P=bt&&bt.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),Bu=bt&&bt.__importStar||(function(){var t=function(e){return t=Object.getOwnPropertyNames||function(n){var r=[];for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(r[r.length]=s);return r},t(e)};return function(e){if(e&&e.__esModule)return e;var n={};if(e!=null)for(var r=t(e),s=0;s<r.length;s++)r[s]!=="default"&&EP(n,e,r[s]);return _P(n,e),n}})();Object.defineProperty(bt,"__esModule",{value:!0});bt.SUGGESTED_LITELLM_SMOKE_TEST_COMMAND=bt.COLORS=void 0;bt.getBinaryDir=gc;bt.findClaudeCodePath=wP;bt.findCodexPath=AP;bt.findBundledBasePromptsDir=SP;bt.getLiteLLMQuickstartHintLines=TP;var yP=Bu(require("os")),ci=Bu(require("path")),Kn=Bu(require("fs")),am=require("child_process"),pc=To();function gc(){return ci.dirname(process.execPath)}function wP(){if(process.env.CLAUDE_CODE_PATH)return process.env.CLAUDE_CODE_PATH;let t=(0,pc.getClaudeSdkCliPath)();if(t)return t;let e=(0,pc.resolveFromOwnDeps)("@anthropic-ai/claude-agent-sdk","cli.js");if(e)return e;let n=gc(),r=ci.join(n,"claude-sdk","cli.js");try{return Kn.accessSync(r,Kn.constants.R_OK),r}catch{}try{let o=process.platform==="win32"?"where claude":"which claude",a=(0,am.execSync)(o,{encoding:"utf8",stdio:["pipe","pipe","ignore"]}).trim();if(a)return a.split(`
455
- `)[0]}catch{}let s=yP.homedir(),i=[ci.join(s,".npm-global","bin","claude"),ci.join(s,".local","bin","claude"),"/usr/local/bin/claude","/opt/homebrew/bin/claude"];for(let o of i)try{return Kn.accessSync(o,Kn.constants.X_OK),o}catch{}}function AP(){if(process.env.CODEX_PATH)return process.env.CODEX_PATH;let t=(0,pc.resolveFromOwnDeps)("@openai/codex","bin/codex.js");if(t)return t;let e=(0,pc.getCodexSdkBinaryPath)();if(e)return e;let n=gc(),r=process.platform==="win32"?"codex.exe":"codex",s=ci.join(n,"codex-sdk",r);try{return Kn.accessSync(s,Kn.constants.X_OK),s}catch{}try{let i=process.platform==="win32"?"where codex":"which codex",o=(0,am.execSync)(i,{encoding:"utf8",stdio:["pipe","pipe","ignore"]}).trim();if(o)return o.split(`
456
- `)[0]}catch{}}function SP(){let t=process.env.AGENTHIPPO_BASE_PROMPTS_DIR||process.env.AGENTIDE_BASE_PROMPTS_DIR;if(t)try{return Kn.accessSync(t,Kn.constants.R_OK),t}catch{}let e=gc(),n=ci.join(e,"base-prompts");try{return Kn.accessSync(n,Kn.constants.R_OK),n}catch{}let r=ci.resolve(__dirname,"..","base-prompts");try{return Kn.accessSync(r,Kn.constants.R_OK),r}catch{}}bt.COLORS={reset:"\x1B[0m",cyan:"\x1B[36m",gray:"\x1B[90m",dim:"\x1B[2m",blue:"\x1B[34m",green:"\x1B[32m",red:"\x1B[31m",yellow:"\x1B[33m"};bt.SUGGESTED_LITELLM_SMOKE_TEST_COMMAND='AGENTHIPPO_LITELLM_BASE_URL="http://localhost:4000" AGENTHIPPO_LITELLM_API_KEY="dummy" AGENTHIPPO_DEFAULT_MODEL="litellm/gpt-5.5" AGENTHIPPO_DEFAULT_ENGINE="codex" agenthippo ask "Reply with exactly: CLI_TEST_OK"';function TP(){return["Try local LiteLLM quickstart:",` ${bt.SUGGESTED_LITELLM_SMOKE_TEST_COMMAND}`]}});var um=S(ds=>{"use strict";var bP=ds&&ds.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,s)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),vP=ds&&ds.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),Vu=ds&&ds.__importStar||(function(){var t=function(e){return t=Object.getOwnPropertyNames||function(n){var r=[];for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(r[r.length]=s);return r},t(e)};return function(e){if(e&&e.__esModule)return e;var n={};if(e!=null)for(var r=t(e),s=0;s<r.length;s++)r[s]!=="default"&&bP(n,e,r[s]);return vP(n,e),n}})();Object.defineProperty(ds,"__esModule",{value:!0});ds.chatCommand=RP;var OP=Vu(require("readline")),IP=Vu(require("path")),PP=Vu(require("os")),yr=oi(),li=ai(),ue=Wn(),cm=Ke(),NP=Er(),lm=Ns(),Fu="-".repeat(62);async function RP(t){let e=(0,li.getApiConfig)(),n,r="default",s,i,o,a=t.verbose?new yr.ConsoleLogger("[Sync]"):new yr.NoOpLogger;if(t.agent)try{n=await(0,li.loadAgentPack)(t.agent,t.workspace),r=n.manifest.metadata.name,s=t.engine||n.manifest.spec.engine;let O=["claude","codex"].includes(s)?void 0:(0,lm.tryResolveCustomEngineManifest)(t.workspace,s)?.model?.defaultModel,A=t.model||n.manifest.spec.model||O||(0,li.getEnvDefaultModel)()||(0,li.getDefaultConfig)().model;i=(0,yr.resolveModelAlias)(A);let v=n.manifest.spec.cheapModel?.trim();o=v?(0,yr.resolveModelAlias)(v):void 0,await(0,yr.syncPackToWorkspace)(t.workspace,n.packPath,r,s,a,(0,ue.findBundledBasePromptsDir)()),console.log(`${ue.COLORS.green}OK:${ue.COLORS.reset} Loaded agent: ${n.manifest.metadata.name} v${n.manifest.metadata.version}`),A!==i&&console.log(`${ue.COLORS.dim} Model: ${A} -> ${i}${ue.COLORS.reset}`),v&&v!==o&&console.log(`${ue.COLORS.dim} Cheap model: ${v} -> ${o}${ue.COLORS.reset}`)}catch(T){console.error(`${ue.COLORS.red}Error: ${T instanceof Error?T.message:T}${ue.COLORS.reset}`),process.exit(1)}else{let T=(0,li.getDefaultConfig)();s=t.engine||T.engine;let O=["claude","codex"].includes(s)?void 0:(0,lm.tryResolveCustomEngineManifest)(t.workspace,s)?.model?.defaultModel,A=t.model||O||(0,li.getEnvDefaultModel)()||T.model;i=(0,yr.resolveModelAlias)(A),A!==i&&console.log(`${ue.COLORS.dim}Model: ${A} -> ${i}${ue.COLORS.reset}`)}if(!e.apiKey&&(s==="claude"||s==="codex")){let T=(0,ue.getLiteLLMQuickstartHintLines)();console.log(["To start a chat, set an API key and re-run the command. Example:",` ${T[1]}`,"","Other options:"," AGENTHIPPO_LITELLM_API_KEY=your_key AGENTHIPPO_LITELLM_BASE_URL=https://... dist/agenthippo chat"," LITELLM_API_KEY=your_key LITELLM_BASE_URL=https://... dist/agenthippo chat"," ANTHROPIC_API_KEY=your_key dist/agenthippo chat"," OPENAI_API_KEY=your_key dist/agenthippo chat"].join(`
457
- `)),process.exit(1)}let c=IP.join(PP.tmpdir(),`${cm.AGENTIDE_CLI_NAME}-cli`),l=t.verbose?new yr.ConsoleLogger("[Agent]"):new yr.NoOpLogger,f=(0,ue.findClaudeCodePath)(),u=(0,ue.findCodexPath)(),d=(0,ue.findBundledBasePromptsDir)();s==="claude"&&!f&&(console.error(`${ue.COLORS.red}Error: Claude Code CLI not found.${ue.COLORS.reset}`),console.error(" Install it: npm install -g @anthropic-ai/claude-code"),console.error(" Or set CLAUDE_CODE_PATH environment variable"),console.error(" Or use --engine codex instead"),process.exit(1)),s==="codex"&&!u&&(console.error(`${ue.COLORS.red}Error: Codex CLI not found.${ue.COLORS.reset}`),console.error(" Install it: npm install -g @openai/codex"),console.error(" Or set CODEX_PATH environment variable"),console.error(" Or use --engine claude instead"),process.exit(1));let p=new yr.AutoApprovePermissionHandler,g={fileAccess:(0,li.getFileAccess)(n)},m=`cli-${Date.now()}`,h=()=>(0,yr.createHeadlessRunner)({storagePath:c,packId:r,packVersion:n?.manifest.metadata.version,bundledPromptsDir:d,apiKey:e.apiKey,baseUrl:e.baseUrl,useLiteLLM:e.useLiteLLM,litellmApiKey:e.litellmApiKey,openaiApiKey:e.openaiApiKey,anthropicApiKey:e.anthropicApiKey,logger:l,freshState:!1,claudeCodeExecutablePath:f,codexExecutablePath:u,permissionHandler:p,cliEnvPatch:(0,NP.buildCliEnvPatch)({cliPath:process.execPath,workspaceRoot:t.workspace,agentId:r,chatSessionId:m,baseEnv:process.env}),...o?{engineSettings:{claudeCheapModel:o}}:{}}),E={runner:h(),sessionId:m,engine:s,model:i},_=()=>({async thinking(T){process.stdout.write(`${ue.COLORS.gray}${T}${ue.COLORS.reset}`)},async text(T){process.stdout.write(T)},async toolStart(T,O){console.log(`
453
+ **Application-scoped on purpose**: skills fetched from here become agent instructions and tool definitions on this machine, so this is an install source.`},"agentide.skills.remote.syncOnStartup":{type:"boolean",scope:"application",default:!0,description:"Sync remote skills on extension startup (requires agentide.skills.remote.enabled)."},"agentide.skills.remote.allowOverwriteLocal":{type:"boolean",scope:"application",default:!1,description:"Allow remote skills to overwrite locally-authored skill files of the same name."},"agentide.skills.remote.timeoutMs":{type:"number",scope:"application",default:8e3,minimum:500,maximum:12e4,description:"Timeout (milliseconds) for remote skill registry requests."}}}},capabilities:{untrustedWorkspaces:{supported:"limited",description:"Agent Hippo runs AI agents that read your code, spawn processes, and send prompts to remote model endpoints. In an untrusted workspace the security-relevant settings below are ignored in favour of your user/application values, and remote agent packs (`spec.remote.url`) will not receive your AgentHippo access token without an explicit per-host approval.",restrictedConfigurations:["agentide.auth.baseUrl","agentide.storeRepo","agentide.store.indexUrl","agentide.anywhere.installSource","agentide.anywhere.enabled","agentide.anywhere.autoStart","agentide.anywhere.autoConnect","agentide.anywhere.port","agentide.anywhere.hidden","agentide.cli.path","agentide.cli.installSource","agentide.additionalEngineDir","agentide.fallbackDirectory","agentide.permissions.fileAccess","agentide.gateway.url","agentide.gateway.token","agentide.gateway.autoConnect","agentide.gateway.autoRegister","agentide.gateway.agents","agentide.providers.litellm.baseUrl","agentide.providers.anthropic.baseUrl","agentide.AgentHippoModelGateway.url","agentide.skills.remote.enabled","agentide.skills.remote.registryUrl","agentide.skills.remote.syncOnStartup","agentide.skills.remote.allowOverwriteLocal","agentide.analytics.fleetSources","agentide.analytics.fleetScriptSources","agentide.analytics.defaultDashboardPrompt","agentide.analytics.duckdb.tempDirectory"]}},dependencies:{"@agenthippo-ai/evidence-ship":"0.2.4","@anthropic-ai/claude-agent-sdk":"0.3.227","@anthropic-ai/sdk":"0.116.0","@cfworker/json-schema":"^4.1.1","@mariozechner/pi-ai":"0.54.0","@modelcontextprotocol/sdk":"^1.30.0","@openai/codex":"0.147.0","@openai/codex-sdk":"0.147.0","@orama/orama":"^3.1.6",commander:"^14.0.2",hono:"^4.11.5","js-yaml":"^4.1.1",zod:"^4.3.6"},devDependencies:{"@types/js-yaml":"^4.0.9","@types/mocha":"^10.0.10","@types/node":"^25.x"},scripts:{postinstall:"node ./scripts/vendor-tools.mjs --skip-if-present || true",compile:"node ../../node_modules/typescript/bin/tsc -p ./ && node ./scripts/generate-embedded-custom-engine-runner.mjs && node ./scripts/copy-compile-assets.mjs",watch:"node ../../node_modules/typescript/bin/tsc -watch -p ./",test:"node ../../node_modules/mocha/bin/mocha","test:serve-load":"bash ../../scripts/load/run-serve-load.sh","test:serve-load:full":"bash ../../scripts/load/run-serve-load.sh --full",cli:"node out/cli/index.js","build:tools":"node ./scripts/vendor-tools.mjs --clean","build:cli":"./scripts/build-cli.sh","build:cli:macos-arm64":"./scripts/build-cli.sh --target bun-darwin-arm64 --outfile dist/agenthippo-macos-arm64","build:cli:macos-x64":"./scripts/build-cli.sh --target bun-darwin-x64 --outfile dist/agenthippo-macos-x64","build:cli:linux-x64":"./scripts/build-cli.sh --target bun-linux-x64 --outfile dist/agenthippo-linux-x64","build:cli:linux-arm64":"./scripts/build-cli.sh --target bun-linux-arm64 --outfile dist/agenthippo-linux-arm64"}}});var vo=S(kt=>{"use strict";var dP=kt&&kt.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,s)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),fP=kt&&kt.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),xu=kt&&kt.__importStar||(function(){var t=function(e){return t=Object.getOwnPropertyNames||function(n){var r=[];for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(r[r.length]=s);return r},t(e)};return function(e){if(e&&e.__esModule)return e;var n={};if(e!=null)for(var r=t(e),s=0;s<r.length;s++)r[s]!=="default"&&dP(n,e,r[s]);return fP(n,e),n}})();Object.defineProperty(kt,"__esModule",{value:!0});kt.getDepsDir=Li;kt.resolveFromOwnDeps=ju;kt.areDepsInstalled=im;kt.installDeps=om;kt.isAutoInstallDisabled=am;kt.ensureDeps=mP;kt.getClaudeSdkCliPath=EP;kt.getCodexSdkBinaryPath=_P;kt.installedEngineVersion=wP;var Ft=xu(require("fs")),pP=xu(require("os")),ct=xu(require("path")),gP=require("child_process"),Ur=Wn(),gc=Ke();function hP(){let e=(()=>{try{return pc()}catch{return}})()?.dependencies??{};return{"@anthropic-ai/claude-agent-sdk":e["@anthropic-ai/claude-agent-sdk"]??"0.3.227","@openai/codex":e["@openai/codex"]??"0.147.0","@openai/codex-sdk":e["@openai/codex-sdk"]??"0.147.0"}}var sm=hP();function Li(){let t=ct.dirname(process.execPath),e=ct.join(t,gc.AGENTIDE_DEPS_DIR_NAME);if(Ft.existsSync(e))return e;try{return Ft.accessSync(t,Ft.constants.W_OK),e}catch{return ct.join(pP.homedir(),gc.AGENTIDE_DIR_NAME,gc.AGENTIDE_DEPS_DIR_NAME)}}function ju(t,e){let n=__dirname;for(let r=0;r<8;r++){let s=ct.join(n,"node_modules",...t.split("/"),...e.split("/"));try{if(Ft.existsSync(s))return s}catch{}let i=ct.dirname(n);if(i===n)break;n=i}}function im(){let t=Li(),e=ct.join(t,"node_modules"),n=ct.join(t,"package.json");try{if(!Ft.existsSync(n))return!1;let o=Ft.readFileSync(n,"utf8"),c=JSON.parse(o).dependencies??{};for(let[l,f]of Object.entries(sm))if(c[l]!==f)return!1}catch{return!1}let r=ct.join(e,"@anthropic-ai","claude-agent-sdk","cli.js"),s=ct.join(e,"@openai","codex","bin","codex.js"),i=ct.join(e,"@openai","codex-sdk","package.json");return Ft.existsSync(r)&&Ft.existsSync(s)&&Ft.existsSync(i)}async function om(t=!1){let e=Li();console.log(`${Ur.COLORS.cyan}Installing engine dependencies...${Ur.COLORS.reset}`),t&&console.log(` Directory: ${e}`),Ft.mkdirSync(e,{recursive:!0});let n={name:gc.AGENTIDE_DEPS_PACKAGE_NAME,version:"1.0.0",private:!0,dependencies:sm};Ft.writeFileSync(ct.join(e,"package.json"),JSON.stringify(n,null,2)+`
454
+ `);try{let r=process.platform==="win32"?"npm.cmd":"npm";(0,gP.execSync)(`${r} install --production --no-audit --no-fund`,{cwd:e,stdio:t?"inherit":"pipe"}),console.log(`${Ur.COLORS.green}Dependencies installed${Ur.COLORS.reset}`)}catch(r){throw console.error(`${Ur.COLORS.red}Error: Failed to install dependencies${Ur.COLORS.reset}`),r instanceof Error&&console.error(` ${r.message}`),r}}function am(){let t=(process.env.AGENTHIPPO_NO_AUTO_INSTALL??process.env.AGENTIDE_NO_AUTO_INSTALL??"").trim().toLowerCase();return t==="1"||t==="true"||t==="yes"||t==="on"}async function mP(t=!1){if(!im()){if(ju("@anthropic-ai/claude-agent-sdk","cli.js")&&ju("@openai/codex","bin/codex.js")){t&&console.error(`${Ur.COLORS.dim}Engine SDKs resolved from the CLI's own node_modules \u2014 skipping install.${Ur.COLORS.reset}`);return}if(am()){t&&console.error(`${Ur.COLORS.dim}AGENTHIPPO_NO_AUTO_INSTALL set \u2014 skipping engine dependency install (expecting a self-contained image).${Ur.COLORS.reset}`);return}await om(t)}}function EP(){let t=Li(),e=ct.join(t,"node_modules","@anthropic-ai","claude-agent-sdk","cli.js");return Ft.existsSync(e)?e:void 0}function _P(){let t=Li(),e=ct.join(t,"node_modules","@openai","codex","bin","codex.js");if(Ft.existsSync(e))return e;let n=ct.join(t,"node_modules","@openai","codex-sdk"),r=yP();if(!r)return;let s=process.platform==="win32"?"codex.exe":"codex",i=ct.join(n,"vendor",r,"codex",s);return Ft.existsSync(i)?i:void 0}function yP(){let t=process.arch,e=process.platform;if(e==="darwin")return t==="arm64"?"aarch64-apple-darwin":"x86_64-apple-darwin";if(e==="linux")return t==="arm64"?"aarch64-unknown-linux-musl":"x86_64-unknown-linux-musl";if(e==="win32")return t==="arm64"?"aarch64-pc-windows-msvc":"x86_64-pc-windows-msvc"}function wP(t){let e=t==="codex"?ct.join("@openai","codex"):t==="claude"?ct.join("@anthropic-ai","claude-agent-sdk"):void 0;if(!e)return;let n=[ct.join(Li(),"node_modules",e,"package.json"),ct.join("/usr/local/lib/node_modules",e,"package.json"),ct.join("/usr/lib/node_modules",e,"package.json")];for(let r of n)try{if(!Ft.existsSync(r))continue;let s=JSON.parse(Ft.readFileSync(r,"utf8"));if(s.version)return s.version}catch{}}});var Wn=S(bt=>{"use strict";var AP=bt&&bt.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,s)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),SP=bt&&bt.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),Bu=bt&&bt.__importStar||(function(){var t=function(e){return t=Object.getOwnPropertyNames||function(n){var r=[];for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(r[r.length]=s);return r},t(e)};return function(e){if(e&&e.__esModule)return e;var n={};if(e!=null)for(var r=t(e),s=0;s<r.length;s++)r[s]!=="default"&&AP(n,e,r[s]);return SP(n,e),n}})();Object.defineProperty(bt,"__esModule",{value:!0});bt.SUGGESTED_LITELLM_SMOKE_TEST_COMMAND=bt.COLORS=void 0;bt.getBinaryDir=mc;bt.findClaudeCodePath=bP;bt.findCodexPath=vP;bt.findBundledBasePromptsDir=OP;bt.getLiteLLMQuickstartHintLines=IP;var TP=Bu(require("os")),ci=Bu(require("path")),Kn=Bu(require("fs")),cm=require("child_process"),hc=vo();function mc(){return ci.dirname(process.execPath)}function bP(){if(process.env.CLAUDE_CODE_PATH)return process.env.CLAUDE_CODE_PATH;let t=(0,hc.getClaudeSdkCliPath)();if(t)return t;let e=(0,hc.resolveFromOwnDeps)("@anthropic-ai/claude-agent-sdk","cli.js");if(e)return e;let n=mc(),r=ci.join(n,"claude-sdk","cli.js");try{return Kn.accessSync(r,Kn.constants.R_OK),r}catch{}try{let o=process.platform==="win32"?"where claude":"which claude",a=(0,cm.execSync)(o,{encoding:"utf8",stdio:["pipe","pipe","ignore"]}).trim();if(a)return a.split(`
455
+ `)[0]}catch{}let s=TP.homedir(),i=[ci.join(s,".npm-global","bin","claude"),ci.join(s,".local","bin","claude"),"/usr/local/bin/claude","/opt/homebrew/bin/claude"];for(let o of i)try{return Kn.accessSync(o,Kn.constants.X_OK),o}catch{}}function vP(){if(process.env.CODEX_PATH)return process.env.CODEX_PATH;let t=(0,hc.resolveFromOwnDeps)("@openai/codex","bin/codex.js");if(t)return t;let e=(0,hc.getCodexSdkBinaryPath)();if(e)return e;let n=mc(),r=process.platform==="win32"?"codex.exe":"codex",s=ci.join(n,"codex-sdk",r);try{return Kn.accessSync(s,Kn.constants.X_OK),s}catch{}try{let i=process.platform==="win32"?"where codex":"which codex",o=(0,cm.execSync)(i,{encoding:"utf8",stdio:["pipe","pipe","ignore"]}).trim();if(o)return o.split(`
456
+ `)[0]}catch{}}function OP(){let t=process.env.AGENTHIPPO_BASE_PROMPTS_DIR||process.env.AGENTIDE_BASE_PROMPTS_DIR;if(t)try{return Kn.accessSync(t,Kn.constants.R_OK),t}catch{}let e=mc(),n=ci.join(e,"base-prompts");try{return Kn.accessSync(n,Kn.constants.R_OK),n}catch{}let r=ci.resolve(__dirname,"..","base-prompts");try{return Kn.accessSync(r,Kn.constants.R_OK),r}catch{}}bt.COLORS={reset:"\x1B[0m",cyan:"\x1B[36m",gray:"\x1B[90m",dim:"\x1B[2m",blue:"\x1B[34m",green:"\x1B[32m",red:"\x1B[31m",yellow:"\x1B[33m"};bt.SUGGESTED_LITELLM_SMOKE_TEST_COMMAND='AGENTHIPPO_LITELLM_BASE_URL="http://localhost:4000" AGENTHIPPO_LITELLM_API_KEY="dummy" AGENTHIPPO_DEFAULT_MODEL="litellm/gpt-5.5" AGENTHIPPO_DEFAULT_ENGINE="codex" agenthippo ask "Reply with exactly: CLI_TEST_OK"';function IP(){return["Try local LiteLLM quickstart:",` ${bt.SUGGESTED_LITELLM_SMOKE_TEST_COMMAND}`]}});var dm=S(us=>{"use strict";var PP=us&&us.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,s)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),NP=us&&us.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),Vu=us&&us.__importStar||(function(){var t=function(e){return t=Object.getOwnPropertyNames||function(n){var r=[];for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(r[r.length]=s);return r},t(e)};return function(e){if(e&&e.__esModule)return e;var n={};if(e!=null)for(var r=t(e),s=0;s<r.length;s++)r[s]!=="default"&&PP(n,e,r[s]);return NP(n,e),n}})();Object.defineProperty(us,"__esModule",{value:!0});us.chatCommand=DP;var RP=Vu(require("readline")),CP=Vu(require("path")),kP=Vu(require("os")),yr=oi(),li=ai(),ue=Wn(),lm=Ke(),$P=Er(),um=Ns(),Fu="-".repeat(62);async function DP(t){let e=(0,li.getApiConfig)(),n,r="default",s,i,o,a=t.verbose?new yr.ConsoleLogger("[Sync]"):new yr.NoOpLogger;if(t.agent)try{n=await(0,li.loadAgentPack)(t.agent,t.workspace),r=n.manifest.metadata.name,s=t.engine||n.manifest.spec.engine;let O=["claude","codex"].includes(s)?void 0:(0,um.tryResolveCustomEngineManifest)(t.workspace,s)?.model?.defaultModel,A=t.model||n.manifest.spec.model||O||(0,li.getEnvDefaultModel)()||(0,li.getDefaultConfig)().model;i=(0,yr.resolveModelAlias)(A);let v=n.manifest.spec.cheapModel?.trim();o=v?(0,yr.resolveModelAlias)(v):void 0,await(0,yr.syncPackToWorkspace)(t.workspace,n.packPath,r,s,a,(0,ue.findBundledBasePromptsDir)()),console.log(`${ue.COLORS.green}OK:${ue.COLORS.reset} Loaded agent: ${n.manifest.metadata.name} v${n.manifest.metadata.version}`),A!==i&&console.log(`${ue.COLORS.dim} Model: ${A} -> ${i}${ue.COLORS.reset}`),v&&v!==o&&console.log(`${ue.COLORS.dim} Cheap model: ${v} -> ${o}${ue.COLORS.reset}`)}catch(T){console.error(`${ue.COLORS.red}Error: ${T instanceof Error?T.message:T}${ue.COLORS.reset}`),process.exit(1)}else{let T=(0,li.getDefaultConfig)();s=t.engine||T.engine;let O=["claude","codex"].includes(s)?void 0:(0,um.tryResolveCustomEngineManifest)(t.workspace,s)?.model?.defaultModel,A=t.model||O||(0,li.getEnvDefaultModel)()||T.model;i=(0,yr.resolveModelAlias)(A),A!==i&&console.log(`${ue.COLORS.dim}Model: ${A} -> ${i}${ue.COLORS.reset}`)}if(!e.apiKey&&(s==="claude"||s==="codex")){let T=(0,ue.getLiteLLMQuickstartHintLines)();console.log(["To start a chat, set an API key and re-run the command. Example:",` ${T[1]}`,"","Other options:"," AGENTHIPPO_LITELLM_API_KEY=your_key AGENTHIPPO_LITELLM_BASE_URL=https://... dist/agenthippo chat"," LITELLM_API_KEY=your_key LITELLM_BASE_URL=https://... dist/agenthippo chat"," ANTHROPIC_API_KEY=your_key dist/agenthippo chat"," OPENAI_API_KEY=your_key dist/agenthippo chat"].join(`
457
+ `)),process.exit(1)}let c=CP.join(kP.tmpdir(),`${lm.AGENTIDE_CLI_NAME}-cli`),l=t.verbose?new yr.ConsoleLogger("[Agent]"):new yr.NoOpLogger,f=(0,ue.findClaudeCodePath)(),u=(0,ue.findCodexPath)(),d=(0,ue.findBundledBasePromptsDir)();s==="claude"&&!f&&(console.error(`${ue.COLORS.red}Error: Claude Code CLI not found.${ue.COLORS.reset}`),console.error(" Install it: npm install -g @anthropic-ai/claude-code"),console.error(" Or set CLAUDE_CODE_PATH environment variable"),console.error(" Or use --engine codex instead"),process.exit(1)),s==="codex"&&!u&&(console.error(`${ue.COLORS.red}Error: Codex CLI not found.${ue.COLORS.reset}`),console.error(" Install it: npm install -g @openai/codex"),console.error(" Or set CODEX_PATH environment variable"),console.error(" Or use --engine claude instead"),process.exit(1));let p=new yr.AutoApprovePermissionHandler,g={fileAccess:(0,li.getFileAccess)(n)},m=`cli-${Date.now()}`,h=()=>(0,yr.createHeadlessRunner)({storagePath:c,packId:r,packVersion:n?.manifest.metadata.version,bundledPromptsDir:d,apiKey:e.apiKey,baseUrl:e.baseUrl,useLiteLLM:e.useLiteLLM,litellmApiKey:e.litellmApiKey,openaiApiKey:e.openaiApiKey,anthropicApiKey:e.anthropicApiKey,logger:l,freshState:!1,claudeCodeExecutablePath:f,codexExecutablePath:u,permissionHandler:p,cliEnvPatch:(0,$P.buildCliEnvPatch)({cliPath:process.execPath,workspaceRoot:t.workspace,agentId:r,chatSessionId:m,baseEnv:process.env}),...o?{engineSettings:{claudeCheapModel:o}}:{}}),E={runner:h(),sessionId:m,engine:s,model:i},_=()=>({async thinking(T){process.stdout.write(`${ue.COLORS.gray}${T}${ue.COLORS.reset}`)},async text(T){process.stdout.write(T)},async toolStart(T,O){console.log(`
458
458
  ${ue.COLORS.blue}Tool: ${T}${ue.COLORS.reset}`),O&&O.length<200&&t.verbose&&console.log(` ${ue.COLORS.gray}${O}${ue.COLORS.reset}`)},async toolEnd(T,O,A,v){console.log(v?` ${ue.COLORS.red}Error: ${A?.slice(0,100)}${ue.COLORS.reset}`:` ${ue.COLORS.green}OK${ue.COLORS.reset}`)},async progress(T){t.verbose&&console.log(`${ue.COLORS.yellow}Progress: ${T}${ue.COLORS.reset}`)},async error(T){console.error(`${ue.COLORS.red}Error: ${T}${ue.COLORS.reset}`)},async question(T){return{selected:[],freeText:null,declined:!0}},async done(){console.log(`
459
- `)}});console.log(""),console.log(Fu),console.log(`${cm.AGENTIDE_BRAND_NAME} Chat`),console.log(Fu),console.log(`Engine: ${E.engine}`),console.log(`Model: ${E.model}`),o&&console.log(`Cheap: ${o}`),console.log(`Workspace: ${t.workspace}`),n&&console.log(`Agent: ${n.manifest.metadata.name}`),console.log(Fu),console.log("Type a message to chat. Commands: /help"),console.log("");let y=OP.createInterface({input:process.stdin,output:process.stdout}),b=()=>{y.question(`${ue.COLORS.cyan}> ${ue.COLORS.reset}`,async T=>{let O=T.trim();if(!O){b();return}if(O.startsWith("/")){if(!await CP(O,E,y,{createRunner:h,claudeCodePath:f,codexPath:u}))return;b();return}try{let A=await E.runner.run({engineId:E.engine,modelId:E.model,message:O,workspaceRoot:t.workspace,sessionId:E.sessionId,emitter:_(),permissions:g});!A.success&&A.error&&console.error(`
459
+ `)}});console.log(""),console.log(Fu),console.log(`${lm.AGENTIDE_BRAND_NAME} Chat`),console.log(Fu),console.log(`Engine: ${E.engine}`),console.log(`Model: ${E.model}`),o&&console.log(`Cheap: ${o}`),console.log(`Workspace: ${t.workspace}`),n&&console.log(`Agent: ${n.manifest.metadata.name}`),console.log(Fu),console.log("Type a message to chat. Commands: /help"),console.log("");let y=RP.createInterface({input:process.stdin,output:process.stdout}),b=()=>{y.question(`${ue.COLORS.cyan}> ${ue.COLORS.reset}`,async T=>{let O=T.trim();if(!O){b();return}if(O.startsWith("/")){if(!await LP(O,E,y,{createRunner:h,claudeCodePath:f,codexPath:u}))return;b();return}try{let A=await E.runner.run({engineId:E.engine,modelId:E.model,message:O,workspaceRoot:t.workspace,sessionId:E.sessionId,emitter:_(),permissions:g});!A.success&&A.error&&console.error(`
460
460
  ${ue.COLORS.red}Error: ${A.error}${ue.COLORS.reset}
461
461
  `)}catch(A){console.error(`
462
462
  ${ue.COLORS.red}Error: ${A instanceof Error?A.message:A}${ue.COLORS.reset}
463
- `)}b()})};b()}async function CP(t,e,n,r){let[s,...i]=t.split(/\s+/);switch(s){case"/exit":case"/quit":return console.log("Goodbye!"),e.runner.dispose(),n.close(),!1;case"/clear":case"/reset":case"/new":return e.runner.dispose(),e.runner=r.createRunner(),e.sessionId=`cli-${Date.now()}`,console.log("Session cleared. Fresh state."),!0;case"/engine":{let o=i[0]?.trim();return o?o==="claude"&&!r.claudeCodePath?(console.log("Cannot switch to claude: Claude Code CLI not found."),!0):o==="codex"&&!r.codexPath?(console.log("Cannot switch to codex: Codex CLI not found."),!0):(e.engine=o,console.log(`Switched engine to ${e.engine}`),!0):(console.log("Usage: /engine <id>"),!0)}case"/model":{let o=i[0];if(!o)return console.log("Usage: /model <model-id>"),!0;let a=(0,yr.resolveModelAlias)(o);return e.model=a,console.log(a===o?`Switched model to ${e.model}`:`Switched model to ${o} -> ${e.model}`),!0}case"/status":return console.log(["Current session:",` Engine: ${e.engine}`,` Model: ${e.model}`,` Session: ${e.sessionId}`].join(`
463
+ `)}b()})};b()}async function LP(t,e,n,r){let[s,...i]=t.split(/\s+/);switch(s){case"/exit":case"/quit":return console.log("Goodbye!"),e.runner.dispose(),n.close(),!1;case"/clear":case"/reset":case"/new":return e.runner.dispose(),e.runner=r.createRunner(),e.sessionId=`cli-${Date.now()}`,console.log("Session cleared. Fresh state."),!0;case"/engine":{let o=i[0]?.trim();return o?o==="claude"&&!r.claudeCodePath?(console.log("Cannot switch to claude: Claude Code CLI not found."),!0):o==="codex"&&!r.codexPath?(console.log("Cannot switch to codex: Codex CLI not found."),!0):(e.engine=o,console.log(`Switched engine to ${e.engine}`),!0):(console.log("Usage: /engine <id>"),!0)}case"/model":{let o=i[0];if(!o)return console.log("Usage: /model <model-id>"),!0;let a=(0,yr.resolveModelAlias)(o);return e.model=a,console.log(a===o?`Switched model to ${e.model}`:`Switched model to ${o} -> ${e.model}`),!0}case"/status":return console.log(["Current session:",` Engine: ${e.engine}`,` Model: ${e.model}`,` Session: ${e.sessionId}`].join(`
464
464
  `)),!0;case"/help":return console.log(["Commands:"," /exit, /quit Exit the chat"," /clear Clear session history"," /reset, /new Alias for /clear"," /engine <id> Switch engine (claude|codex or custom engine id)"," /model <id> Switch model for this session"," /status Show current engine/model/session"," /help Show this help"].join(`
465
- `)),!0;default:return console.log(`Unknown command: ${s}. Type /help for available commands.`),!0}}});var pm=S(fs=>{"use strict";var kP=fs&&fs.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,s)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),$P=fs&&fs.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),Wu=fs&&fs.__importStar||(function(){var t=function(e){return t=Object.getOwnPropertyNames||function(n){var r=[];for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(r[r.length]=s);return r},t(e)};return function(e){if(e&&e.__esModule)return e;var n={};if(e!=null)for(var r=t(e),s=0;s<r.length;s++)r[s]!=="default"&&kP(n,e,r[s]);return $P(n,e),n}})();Object.defineProperty(fs,"__esModule",{value:!0});fs.askCommand=GP;var DP=Wu(require("fs")),dm=Wu(require("path")),LP=Wu(require("os")),Hr=oi(),ui=ai(),jr=Wn(),MP=Er(),fm=Ns();async function GP(t){let e=(0,ui.getApiConfig)(),n,r="default",s,i,o,a=t.verbose?new Hr.ConsoleLogger("[Sync]"):new Hr.NoOpLogger;if(t.agent)try{n=await(0,ui.loadAgentPack)(t.agent,t.workspace),r=n.manifest.metadata.name,s=t.engine||n.manifest.spec.engine;let E=["claude","codex"].includes(s)?void 0:(0,fm.tryResolveCustomEngineManifest)(t.workspace,s)?.model?.defaultModel,_=t.model||n.manifest.spec.model||E||(0,ui.getEnvDefaultModel)()||(0,ui.getDefaultConfig)().model;i=(0,Hr.resolveModelAlias)(_);let y=n.manifest.spec.cheapModel?.trim();o=y?(0,Hr.resolveModelAlias)(y):void 0,await(0,Hr.syncPackToWorkspace)(t.workspace,n.packPath,r,s,a,(0,jr.findBundledBasePromptsDir)())}catch(E){t.json?console.log(JSON.stringify({error:E instanceof Error?E.message:String(E)})):console.error(`Error: ${E instanceof Error?E.message:E}`),process.exit(1)}else{let E=(0,ui.getDefaultConfig)();s=t.engine||E.engine;let _=["claude","codex"].includes(s)?void 0:(0,fm.tryResolveCustomEngineManifest)(t.workspace,s)?.model?.defaultModel,y=t.model||_||(0,ui.getEnvDefaultModel)()||E.model;i=(0,Hr.resolveModelAlias)(y)}if(!e.apiKey&&(s==="claude"||s==="codex")){if(t.json)console.log(JSON.stringify({error:"No API key found",hint:(0,jr.getLiteLLMQuickstartHintLines)().join(`
465
+ `)),!0;default:return console.log(`Unknown command: ${s}. Type /help for available commands.`),!0}}});var gm=S(ds=>{"use strict";var MP=ds&&ds.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,s)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),GP=ds&&ds.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),Wu=ds&&ds.__importStar||(function(){var t=function(e){return t=Object.getOwnPropertyNames||function(n){var r=[];for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(r[r.length]=s);return r},t(e)};return function(e){if(e&&e.__esModule)return e;var n={};if(e!=null)for(var r=t(e),s=0;s<r.length;s++)r[s]!=="default"&&MP(n,e,r[s]);return GP(n,e),n}})();Object.defineProperty(ds,"__esModule",{value:!0});ds.askCommand=xP;var UP=Wu(require("fs")),fm=Wu(require("path")),HP=Wu(require("os")),Hr=oi(),ui=ai(),jr=Wn(),jP=Er(),pm=Ns();async function xP(t){let e=(0,ui.getApiConfig)(),n,r="default",s,i,o,a=t.verbose?new Hr.ConsoleLogger("[Sync]"):new Hr.NoOpLogger;if(t.agent)try{n=await(0,ui.loadAgentPack)(t.agent,t.workspace),r=n.manifest.metadata.name,s=t.engine||n.manifest.spec.engine;let E=["claude","codex"].includes(s)?void 0:(0,pm.tryResolveCustomEngineManifest)(t.workspace,s)?.model?.defaultModel,_=t.model||n.manifest.spec.model||E||(0,ui.getEnvDefaultModel)()||(0,ui.getDefaultConfig)().model;i=(0,Hr.resolveModelAlias)(_);let y=n.manifest.spec.cheapModel?.trim();o=y?(0,Hr.resolveModelAlias)(y):void 0,await(0,Hr.syncPackToWorkspace)(t.workspace,n.packPath,r,s,a,(0,jr.findBundledBasePromptsDir)())}catch(E){t.json?console.log(JSON.stringify({error:E instanceof Error?E.message:String(E)})):console.error(`Error: ${E instanceof Error?E.message:E}`),process.exit(1)}else{let E=(0,ui.getDefaultConfig)();s=t.engine||E.engine;let _=["claude","codex"].includes(s)?void 0:(0,pm.tryResolveCustomEngineManifest)(t.workspace,s)?.model?.defaultModel,y=t.model||_||(0,ui.getEnvDefaultModel)()||E.model;i=(0,Hr.resolveModelAlias)(y)}if(!e.apiKey&&(s==="claude"||s==="codex")){if(t.json)console.log(JSON.stringify({error:"No API key found",hint:(0,jr.getLiteLLMQuickstartHintLines)().join(`
466
466
  `)}));else{console.error("Error: No API key found. Set AGENTHIPPO_LITELLM_API_KEY or ANTHROPIC_API_KEY");for(let E of(0,jr.getLiteLLMQuickstartHintLines)())console.error(E)}process.exit(1)}let c=t.message;if(t.systemPrompt&&(c=`System prompt:
467
467
  ${t.systemPrompt}
468
468
 
469
469
  User prompt:
470
- ${c}`),t.file)try{let E=dm.resolve(t.workspace,t.file),_=DP.readFileSync(E,"utf-8");c=`${c}
470
+ ${c}`),t.file)try{let E=fm.resolve(t.workspace,t.file),_=UP.readFileSync(E,"utf-8");c=`${c}
471
471
 
472
472
  File content (${t.file}):
473
473
  \`\`\`
474
474
  ${_}
475
- \`\`\``}catch{t.json?console.log(JSON.stringify({error:`Failed to read file: ${t.file}`})):console.error(`Error: Failed to read file: ${t.file}`),process.exit(1)}let l=dm.join(LP.tmpdir(),"agenthippo-cli"),f=t.verbose?new Hr.ConsoleLogger("[Agent]"):new Hr.NoOpLogger,u=(0,jr.findClaudeCodePath)(),d=(0,jr.findCodexPath)(),p=(0,jr.findBundledBasePromptsDir)();s==="claude"&&!u&&(t.json?console.log(JSON.stringify({error:"Claude Code CLI not found. Install: npm install -g @anthropic-ai/claude-code"})):(console.error(`${jr.COLORS.red}Error: Claude Code CLI not found.${jr.COLORS.reset}`),console.error(" Install: npm install -g @anthropic-ai/claude-code"),console.error(" Or set CLAUDE_CODE_PATH, or use --engine codex")),process.exit(1)),s==="codex"&&!d&&(t.json?console.log(JSON.stringify({error:"Codex CLI not found. Install: npm install -g @openai/codex"})):(console.error(`${jr.COLORS.red}Error: Codex CLI not found.${jr.COLORS.reset}`),console.error(" Install: npm install -g @openai/codex"),console.error(" Or set CODEX_PATH, or use --engine claude")),process.exit(1));let g=new Hr.AutoApprovePermissionHandler,m={fileAccess:(0,ui.getFileAccess)(n)},h=(0,Hr.createHeadlessRunner)({storagePath:l,packId:r,packVersion:n?.manifest.metadata.version,bundledPromptsDir:p,apiKey:e.apiKey,baseUrl:e.baseUrl,useLiteLLM:e.useLiteLLM,litellmApiKey:e.litellmApiKey,openaiApiKey:e.openaiApiKey,anthropicApiKey:e.anthropicApiKey,logger:f,freshState:!t.sessionId?.trim(),permissionHandler:g,claudeCodeExecutablePath:u,codexExecutablePath:d,cliEnvPatch:(0,MP.buildCliEnvPatch)({cliPath:process.execPath,workspaceRoot:t.workspace,agentId:r,chatSessionId:t.sessionId,baseEnv:process.env}),...o?{engineSettings:{claudeCheapModel:o}}:{}});try{let E=await h.run({engineId:s,modelId:i,message:c,workspaceRoot:t.workspace,sessionId:t.sessionId,permissions:m});t.json?(t.outputMode==="agent-run"?console.log(JSON.stringify({text:E.text,media:[],session_id:t.sessionId||null,error:E.error||void 0})):console.log(JSON.stringify({success:E.success,text:E.text,thinking:E.thinking||void 0,toolCalls:E.toolCalls,error:E.error})),E.success||process.exit(1)):E.success?console.log(E.text):(console.error(`Error: ${E.error}`),process.exit(1))}catch(E){t.json?console.log(JSON.stringify({error:E instanceof Error?E.message:String(E)})):console.error(`Error: ${E instanceof Error?E.message:E}`),process.exit(1)}finally{h.dispose()}}});var Ku=S(xr=>{"use strict";Object.defineProperty(xr,"__esModule",{value:!0});xr.isTerminalFrame=UP;xr.isTaggedEvent=HP;xr.encodeRunnerFrame=jP;xr.encodeClientFrame=xP;xr.parseRunnerFrame=BP;xr.parseClientFrame=FP;xr.splitFrames=VP;xr.toWireOptions=WP;function UP(t){return"type"in t&&(t.type==="result"||t.type==="failed")}function HP(t){return"event"in t}function jP(t){return`${JSON.stringify(t)}
476
- `}function xP(t){return`${JSON.stringify(t)}
477
- `}function BP(t){let e=hm(t);if(!e)return;let n=e.type;if(n==="ready")return{type:"ready",...e.demux===!0?{demux:!0}:{}};if(typeof e.id=="string"&&e.event&&typeof e.event=="object"){let r=e.event.type;return typeof r=="string"&&gm.has(r)?{id:e.id,event:e.event}:void 0}if(n==="result"&&typeof e.id=="string")return{type:"result",id:e.id,...typeof e.nativeSessionId=="string"?{nativeSessionId:e.nativeSessionId}:{}};if(n==="failed"&&typeof e.id=="string")return{type:"failed",id:e.id,message:typeof e.message=="string"?e.message:"Sandbox turn failed"};if(n==="question"&&e.payload&&typeof e.payload=="object")return{type:"question",payload:e.payload,...typeof e.id=="string"?{id:e.id}:{}};if(typeof n=="string"&&gm.has(n))return e}function FP(t){let e=hm(t);if(e){if(e.type==="run"&&typeof e.id=="string"&&typeof e.message=="string"){let n=e.options&&typeof e.options=="object"?e.options:{};return{type:"run",id:e.id,message:e.message,options:n}}if(e.type==="abort"&&typeof e.id=="string")return{type:"abort",id:e.id}}}var gm=new Set(["text","thinking","toolStart","toolEnd","progress","error","done","nativeSessionId","probe"]);function hm(t){let e;try{e=JSON.parse(t)}catch{return}if(!(!e||typeof e!="object"||Array.isArray(e)))return e}function VP(t){let e=t.split(`
478
- `),n=e.pop()??"";return{lines:e.filter(r=>r.trim().length>0),rest:n}}function WP(t,e){let{apiKey:n,...r}=t;return{...r,...e.baseUrl?{baseUrl:e.baseUrl}:{},...e.modelToken?{modelToken:e.modelToken}:{}}}});var Em=S(hc=>{"use strict";Object.defineProperty(hc,"__esModule",{value:!0});hc.RemoteEngine=void 0;var mm=rc(),bo=Ku(),qu=class{id;displayName;channel;model;logger;pending=new Map;buffer="";seq=0;wired=!1;peerDemux=!1;constructor(e){this.id=e.id,this.displayName=e.displayName,this.channel=e.channel,this.model=e.model??{},this.logger=e.logger}async stream(e,n,r,s,i){this.wire();let o=`r${++this.seq}`,a=new Promise((l,f)=>{this.pending.set(o,{emitter:r,resolve:l,reject:f,chain:Promise.resolve()})}),c=()=>{this.send({type:"abort",id:o})};i&&(i.aborted?c():i.addEventListener("abort",c,{once:!0}));try{let l=this.model.mintToken?await this.model.mintToken()??this.model.modelToken:this.model.modelToken;this.send({type:"run",id:o,message:e,options:(0,bo.toWireOptions)(n,{...this.model,modelToken:l})}),await a}finally{this.pending.delete(o),i?.removeEventListener("abort",c)}}onMaintenance(){}dispose(){}wire(){this.wired||(this.wired=!0,this.channel.input.on("data",e=>{this.buffer+=typeof e=="string"?e:e.toString("utf8");let{lines:n,rest:r}=(0,bo.splitFrames)(this.buffer);this.buffer=r;for(let s of n){let i=(0,bo.parseRunnerFrame)(s);if(!i){this.logger?.warn("[RemoteEngine] dropped malformed runner frame");continue}this.dispatch(i)}}),this.channel.closed?.then(()=>this.failAll(new Error("sandbox channel closed")),e=>this.failAll(e instanceof Error?e:new Error(String(e)))))}dispatch(e){if((0,bo.isTaggedEvent)(e)){this.enqueue(this.pending.get(e.id),n=>(0,mm.applyParsedRunnerEvent)(n.emitter,e.event));return}if(e.type==="ready"){this.peerDemux=e.demux===!0;return}if(e.type==="result"){this.settle(e.id,n=>n.resolve(e.nativeSessionId));return}if(e.type==="failed"){this.settle(e.id,n=>n.reject(new Error(e.message)));return}if(e.type==="question"){let n=e.id?[this.pending.get(e.id)]:[...this.pending.values()];for(let r of n)this.enqueue(r,s=>s.emitter.question(e.payload).then(()=>{}));return}for(let n of this.pending.values())this.enqueue(n,r=>(0,mm.applyParsedRunnerEvent)(r.emitter,e).then(()=>{}))}enqueue(e,n){e&&(e.chain=e.chain.then(()=>n(e)).then(()=>{},r=>{this.logger?.warn(`[RemoteEngine] emitter error: ${r instanceof Error?r.message:String(r)}`)}))}settle(e,n){let r=this.pending.get(e);r&&r.chain.then(()=>n(r))}supportsDemux(){return this.peerDemux}failAll(e){for(let[n,r]of this.pending)r.reject(e),this.pending.delete(n)}send(e){this.channel.output.write((0,bo.encodeClientFrame)(e))}};hc.RemoteEngine=qu});var wm=S(Yu=>{"use strict";Object.defineProperty(Yu,"__esModule",{value:!0});Yu.createSandboxRunner=XP;var KP=Em(),qP=Un(),YP=Is();function XP(t){let e=new Map,n=new Map,r=new Map,s=1e4,i=(u,d)=>{if(r.size>=s&&!r.has(u)){let p=r.keys().next();p.done||r.delete(p.value)}r.set(u,d)},o=u=>r.get(u)??u,a=async(u,d)=>{await t.admit?.({sandboxKey:u,sessionKey:d});let p=await t.driver.create({sandboxKey:u,image:t.image,tier:t.tier,routes:t.routes,fs:await t.fsFor?.(u)??t.fs??{readonly:[],writable:[]},...t.stateDirFor?{stateDir:await t.stateDirFor(u)}:{},limits:t.limits??{ttlSeconds:1800},env:{...t.env??{},...t.provenanceEnv?.()??{}}}),g=await t.mintModelToken?.(p.id,u),m=p.connect(),h=new KP.RemoteEngine({id:"sandbox",displayName:`Sandbox ${p.id}`,channel:m,model:{baseUrl:t.inferenceBaseUrl,modelToken:g,...t.mintModelToken?{mintToken:async()=>t.mintModelToken(p.id,u)}:{}},logger:t.logger}),E={handle:p,engine:h,dead:!1,sessionKeys:new Set([d]),queue:Promise.resolve()},_=y=>{E.dead=!0;let b=e.get(u)===E;b&&e.delete(u);let T=y instanceof Error?`: ${y.message}`:"";t.logger?.info(`[Sandbox] ${p.id} closed${T}; ${u} will rehydrate on next message`),b&&t.driver.destroy(p).catch(()=>{})};return m.closed?.then(()=>_(),_),e.set(u,E),t.logger?.info(`[Sandbox] created ${p.id} for ${u} (tier ${p.tier})`),E},c=(u,d)=>{let p=e.get(u);if(p&&!p.dead)return Promise.resolve(p);p?.dead&&e.delete(u);let g=n.get(u);if(g)return g;let m=a(u,d).finally(()=>{n.delete(u)});return n.set(u,m),m},l=async(u,d)=>{if(u.engine.supportsDemux())return d(u);let p=u.queue,g;if(u.queue=new Promise(m=>{g=m}),await p,u.dead)throw g(),new Error("sandbox channel closed");try{return await d(u)}finally{g()}};return{run:async u=>{let d=u.sessionId??"default",p=u.sandboxKey??d,g=y=>(y.sessionKeys.add(d),i(d,p),y),m={text:"",thinking:"",toolCalls:[]},h=JP(u.emitter,m),E=()=>m.text===""&&m.thinking===""&&m.toolCalls.length===0,_=async y=>{await y.engine.stream(u.message,{engineId:u.engineId,modelId:u.modelId,workspaceRoot:u.workspaceRoot,additionalDirectories:u.additionalDirectories,sessionId:u.sessionId,permissions:u.permissions,analyticsUserId:u.analyticsUserId,engineHomeUserKey:(0,qP.engineHomeUserKey)((0,YP.currentCredential)()?.userId),turnEnv:u.turnEnv,gatewaySessionKey:u.gatewaySessionKey},h,t.runtime,u.signal)};try{let y=g(await c(p,d));try{await l(y,_)}catch(b){let T=_m(b);if(!/channel closed/i.test(T)||!E())throw b;e.get(p)===y&&e.delete(p),t.logger?.info(`[Sandbox] session ${d} lost its sandbox mid-turn; recreating and retrying once`),await l(g(await c(p,d)),_)}return{success:!0,text:m.text,thinking:m.thinking,toolCalls:m.toolCalls}}catch(y){return{success:!1,text:m.text,thinking:m.thinking,toolCalls:m.toolCalls,error:_m(y)}}},dispose(){for(let[u,d]of e)t.driver.destroy(d.handle).catch(()=>{}),e.delete(u)},sandboxes:()=>[...e.entries()].map(([u,d])=>({sandboxKey:u,sandboxId:d.handle.id,tier:d.handle.tier,sessionKeys:[...d.sessionKeys]})),async destroySession(u){let d=o(u),p=e.get(d);p&&(e.delete(d),await t.driver.destroy(p.handle),t.logger?.info(`[Sandbox] destroyed ${p.handle.id} (${d}${ym(p,u)})`))},async revokeRoute(u,d){let p=o(u),g=e.get(p);g&&(await t.driver.revoke(g.handle,d),d==="all"&&e.delete(p),t.logger?.info(`[Sandbox] revoked ${d} on ${g.handle.id} (${p}${ym(g,u)})`))}}}function JP(t,e){return{async thinking(n){e.thinking+=n,await t?.thinking(n)},async text(n){e.text+=n,await t?.text(n)},async toolStart(n,r,s,i){e.toolCalls.push({name:n,input:r}),await t?.toolStart(n,r,s,i)},async toolEnd(n,r,s,i,o){let a=[...e.toolCalls].reverse().find(c=>c.name===n&&c.result===void 0);a&&(a.result=s,a.isError=i),await t?.toolEnd(n,r,s,i,o)},async progress(n){await t?.progress(n)},async question(n){return await t?.question(n),{selected:[],freeText:null,declined:!0}},async error(n){await t?.error(n)},async done(){await t?.done()}}}function _m(t){return t instanceof Error?t.message:String(t)}function ym(t,e){let n=[...t.sessionKeys].filter(r=>r!==e);return n.length===0?"":`, also ending ${n.length}: ${n.join(", ")}`}});var Mi=S(Vt=>{"use strict";var zP=Vt&&Vt.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,s)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),QP=Vt&&Vt.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),ZP=Vt&&Vt.__importStar||(function(){var t=function(e){return t=Object.getOwnPropertyNames||function(n){var r=[];for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(r[r.length]=s);return r},t(e)};return function(e){if(e&&e.__esModule)return e;var n={};if(e!=null)for(var r=t(e),s=0;s<r.length;s++)r[s]!=="default"&&zP(n,e,r[s]);return QP(n,e),n}})();Object.defineProperty(Vt,"__esModule",{value:!0});Vt.b64urlEncode=Xu;Vt.signCompactJws=Am;Vt.verifyCompactJws=Sm;Vt.timingSafeEqualString=eN;Vt.generateWarrantKeypair=tN;Vt.mintWarrant=rN;Vt.verifyWarrant=sN;Vt.jwks=iN;var ps=ZP(require("node:crypto"));function Xu(t){return Buffer.from(t,"utf8").toString("base64url")}function Am(t,e,n){let r={alg:"ES256",typ:t.typ??"JWT",kid:t.kid},s=`${Xu(JSON.stringify(r))}.${Xu(JSON.stringify(e))}`,i=ps.sign("sha256",Buffer.from(s),{key:ps.createPrivateKey(n),dsaEncoding:"ieee-p1363"});return`${s}.${i.toString("base64url")}`}function Sm(t,e,n={}){let r=t.split(".");if(r.length!==3)return{ok:!1,reason:"malformed"};let[s,i,o]=r,a,c;try{a=JSON.parse(Buffer.from(s,"base64url").toString("utf8")),c=JSON.parse(Buffer.from(i,"base64url").toString("utf8"))}catch{return{ok:!1,reason:"unparseable"}}if(a.alg!=="ES256")return{ok:!1,reason:`unsupported alg ${a.alg}`};if(n.typ!==void 0&&a.typ!==void 0&&a.typ!==n.typ)return{ok:!1,reason:`unexpected token type ${a.typ}`};let l=a.kid?e[a.kid]:void 0;if(!l)return{ok:!1,reason:"unknown kid"};let f=!1;try{f=ps.verify("sha256",Buffer.from(`${s}.${i}`),{key:ps.createPublicKey(l),dsaEncoding:"ieee-p1363"},Buffer.from(o,"base64url"))}catch{return{ok:!1,reason:"bad signature"}}return f?{ok:!0,header:a,payload:c,signingInput:`${s}.${i}`}:{ok:!1,reason:"bad signature"}}function eN(t,e){let n=Buffer.from(t,"utf8"),r=Buffer.from(e,"utf8");return n.length!==r.length?!1:ps.timingSafeEqual(n,r)}function tN(t){let{privateKey:e,publicKey:n}=ps.generateKeyPairSync("ec",{namedCurve:"P-256"}),r=n.export({type:"spki",format:"pem"}).toString();return{privateKeyPem:e.export({type:"pkcs8",format:"pem"}).toString(),publicKeyPem:r,kid:t??ps.createHash("sha256").update(r).digest("hex").slice(0,16)}}var nN=300;function rN(t,e){let n=t.nowSeconds??Math.floor(Date.now()/1e3),r=Math.min(t.ttlSeconds??120,nN),s={user:t.user,pack:t.pack,packVersion:t.packVersion,sandboxId:t.sandboxId,tier:t.tier,aud:t.aud,iat:n,exp:n+r,jti:ps.randomUUID()};return Am({typ:"JWT",kid:e.kid},s,e.privateKeyPem)}function sN(t,e,n){let r=Sm(t,e);if(!r.ok)return{ok:!1,reason:r.reason};let s=r.payload,i=n.nowSeconds??Math.floor(Date.now()/1e3);return typeof s.exp!="number"||s.exp<=i?{ok:!1,reason:"expired"}:s.aud!==n.audience?{ok:!1,reason:`wrong audience ${s.aud}`}:n.channelSandboxId!==void 0&&s.sandboxId!==n.channelSandboxId?{ok:!1,reason:"warrant not bound to this channel"}:s.user?{ok:!0,claims:s}:{ok:!1,reason:"no principal"}}function iN(t){return{keys:t.map(e=>({...ps.createPublicKey(e.publicKeyPem).export({format:"jwk"}),kid:e.kid,alg:"ES256",use:"sig"}))}}});var Oo=S(H=>{"use strict";var oN=H&&H.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,s)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),aN=H&&H.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),zu=H&&H.__importStar||(function(){var t=function(e){return t=Object.getOwnPropertyNames||function(n){var r=[];for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(r[r.length]=s);return r},t(e)};return function(e){if(e&&e.__esModule)return e;var n={};if(e!=null)for(var r=t(e),s=0;s<r.length;s++)r[s]!=="default"&&oN(n,e,r[s]);return aN(n,e),n}})();Object.defineProperty(H,"__esModule",{value:!0});H.PACK_FULL_REVERIFY_INTERVAL_MS=H.PACK_PROBE_INTERVAL_MS=H.LEASE_JWKS_PINS_ENV=H.LEASE_JWKS_URL_ENV=H.LEASE_SIGNING_KEYS_ENV=H.ALLOW_INSECURE_TRUST_ROOT_ENV=H.PACK_JWKS_PINS_ENV=H.PACK_JWKS_URL_ENV_LEGACY=H.PACK_JWKS_URL_ENV=H.ALLOW_UNSIGNED_PACK_ENV=H.DIGEST_EXCLUDED_SEGMENTS=H.PACK_SIGNATURE_FILE=void 0;H.isDigestExcluded=Ec;H.computePackDigestFromFiles=bm;H.computePackDigest=Qu;H.packTreeProbe=Ju;H.signPack=cN;H.readPackSignature=vm;H.verifyPack=Om;H.verifyPackFromFiles=lN;H.requireSignedPack=Pm;H.resolveRequireSignedPack=dN;H.allowUnsignedPackFromEnv=fN;H.describePackRefusal=pN;H.publicKeyThumbprints=Nm;H.parseJwksPins=Rm;H.assertSecureTrustUrl=Cm;H.loadPackTrustRoot=$m;H.loadLeaseTrustRoot=EN;H.selectLeaseSigningKeys=_N;H.loadPackSigningKeys=wN;H.createPackVerifier=AN;var Gi=zu(require("node:crypto")),ks=zu(require("node:fs")),mc=zu(require("node:path")),vo=Mi();H.PACK_SIGNATURE_FILE="pack.sig";H.DIGEST_EXCLUDED_SEGMENTS=new Set([".git","node_modules"]);function Ec(t){return t===H.PACK_SIGNATURE_FILE?!0:t.split("/").some(e=>H.DIGEST_EXCLUDED_SEGMENTS.has(e))}function Tm(t){let e=Gi.createHash("sha256"),n=[...t].sort((r,s)=>r.rel<s.rel?-1:r.rel>s.rel?1:0);for(let r of n){r.link&&e.update("L:");let s=Buffer.from(r.rel);e.update(`${s.length}:`),e.update(s),e.update(`${r.body.length}:`),e.update(r.body)}return e.digest("hex")}function bm(t){let e=[];for(let n of t){let r=n.path.replace(/\\/g,"/");Ec(r)||e.push({rel:r,body:n.content,link:n.link})}return Tm(e)}function Qu(t){let e=[],n=(r,s)=>{for(let i of ks.readdirSync(r)){let o=s?`${s}/${i}`:i;if(Ec(o))continue;let a=mc.join(r,i),c=ks.lstatSync(a);c.isSymbolicLink()?e.push({rel:o,body:Buffer.from(ks.readlinkSync(a)),link:!0}):c.isDirectory()?n(a,o):c.isFile()&&e.push({rel:o,body:ks.readFileSync(a)})}};return n(t,""),Tm(e)}function Ju(t){let e=[],n=(r,s)=>{let i;try{i=ks.readdirSync(r).sort()}catch{e.push(`${s}/?unreadable`);return}for(let o of i){let a=s?`${s}/${o}`:o;if(Ec(a))continue;let c=mc.join(r,o),l;try{l=ks.lstatSync(c)}catch{e.push(`${a}|gone`);continue}if(l.isDirectory()){n(c,a);continue}e.push(`${a}|${l.size}|${l.mtimeMs}|${l.ino}|${l.mode}`)}};try{n(t,"")}catch{return"unwalkable"}return Gi.createHash("sha256").update(e.join(`
479
- `)).digest("hex")}function cN(t){let e=Qu(t.packDir),n={pack:t.pack,packVersion:t.packVersion,digest:e,iat:t.nowSeconds??Math.floor(Date.now()/1e3)},r=(0,vo.signCompactJws)({typ:"JWT",kid:t.kid},n,t.privateKeyPem);return ks.writeFileSync(mc.join(t.packDir,H.PACK_SIGNATURE_FILE),`${r}
480
- `),{signature:r,digest:e}}function vm(t){try{return ks.readFileSync(mc.join(t,H.PACK_SIGNATURE_FILE),"utf8").trim()||void 0}catch{return}}function Om(t,e,n){return Im(t,e,n.pack,n.packVersion,()=>Qu(n.packDir))}function lN(t,e,n,r,s){return Im(t,e,n,r,()=>bm(s))}function Im(t,e,n,r,s){if(Object.keys(e).length===0)return{ok:!1,kind:"no-trust-root",reason:"no trusted pack-signing keys are configured on this instance"};let i=(0,vo.verifyCompactJws)(t,e);if(!i.ok)return i.reason==="unknown kid"?{ok:!1,kind:"unknown-key",reason:`unknown signing key ${uN(t)??"(none named)"}`}:i.reason==="bad signature"?{ok:!1,kind:"bad-signature",reason:"signature does not verify"}:i.reason==="malformed"?{ok:!1,kind:"malformed",reason:"malformed signature"}:i.reason==="unparseable"?{ok:!1,kind:"malformed",reason:"unreadable signature"}:{ok:!1,kind:"malformed",reason:i.reason};let o=i.payload;return o.pack!==n?{ok:!1,kind:"identity-mismatch",reason:`signature is for pack ${o.pack}, not ${n}`}:o.packVersion!==r?{ok:!1,kind:"identity-mismatch",reason:`signature is for ${o.pack}@${o.packVersion}, not @${r}`}:typeof o.digest!="string"||!o.digest?{ok:!1,kind:"malformed",reason:"signature carries no digest"}:(0,vo.timingSafeEqualString)(s(),o.digest)?{ok:!0,claims:o}:{ok:!1,kind:"digest-mismatch",reason:"pack contents changed after signing"}}function uN(t){try{return JSON.parse(Buffer.from(t.split(".")[0],"base64url").toString("utf8")).kid}catch{return}}function Pm(t,e){return!!t||!!e}H.ALLOW_UNSIGNED_PACK_ENV="AGENTHIPPO_ALLOW_UNSIGNED_PACK";function dN(t){return Pm(t.lease,t.localRequire)?!0:!t.localAllowUnsigned}function fN(t=process.env){let e=t[H.ALLOW_UNSIGNED_PACK_ENV]?.trim().toLowerCase();return e==="1"||e==="true"||e==="yes"}function pN(t){let n=[`refusing to run ${t.packVersion?`${t.pack}@${t.packVersion}`:t.pack}: ${t.detail}`];switch(t.kind){case"unsigned":n.push(` The pack directory has no ${H.PACK_SIGNATURE_FILE}${t.packDir?` at ${t.packDir}`:""}.`,` Sign it: agenthippo pack sign ${t.pack} --key <private-key.pem> --kid <key-id>`," (generate a key with: agenthippo pack keygen -o key.pem, then publish its public half to JWKS)");break;case"no-trust-root":n.push(" This is NOT a problem with the pack \u2014 this instance has no keys to check it against."," Configure ONE of:",' AGENTHIPPO_PACK_SIGNING_KEYS inline JSON {"<kid>":"<public PEM>"} (air-gapped installs)',` ${H.PACK_JWKS_URL_ENV} https URL of the JWKS document publishing your signing keys`,` ${H.PACK_JWKS_PINS_ENV} optional, comma-separated sha256 thumbprints to pin those keys to`);break;case"trust-root-unavailable":n.push(" A trust root IS configured but could not be loaded, so no signature can be checked.",` ${t.trustRootHint??""}`.trimEnd(),' This is deliberately an error and not an empty keyring: "cannot reach the trust root" and',' "no trust root configured" have different causes and different fixes.');break;case"unknown-key":n.push(" The pack IS signed, but by a key this fleet does not trust."," Either publish that key to your JWKS / AGENTHIPPO_PACK_SIGNING_KEYS, or re-sign the pack"," with a key that is already trusted. A key is never trusted just because it arrived with the pack.");break;case"digest-mismatch":n.push(" The signature is valid but the pack tree no longer matches it \u2014 something changed after signing."," Note that .claude/, .codex/ and .agent-hippo/ are now INSIDE the digest (they carry hooks and"," other executable content), so edits there invalidate a signature that used to survive them.",` Re-sign after reviewing the diff: agenthippo pack sign ${t.pack} --key <private-key.pem> --kid <key-id>`);break;case"identity-mismatch":n.push(" The signature is valid but names a different pack or version \u2014 a replayed signature, not this artifact.");break;case"malformed":case"bad-signature":n.push(` ${H.PACK_SIGNATURE_FILE} is present but unusable. Re-sign the pack; do not hand-edit it.`);break;case"no-pack":break}return n.push(` To run unsigned packs anyway (LOCAL DEVELOPMENT ONLY), set ${H.ALLOW_UNSIGNED_PACK_ENV}=1.`," A lease that sets requireSignedPack overrides that escape hatch \u2014 the control plane's demand cannot be waived locally."),n.join(`
481
- `)}H.PACK_JWKS_URL_ENV="AGENTHIPPO_PACK_JWKS_URL";H.PACK_JWKS_URL_ENV_LEGACY="AGENTHIPPO_PACK_SIGNING_JWKS_URL";H.PACK_JWKS_PINS_ENV="AGENTHIPPO_PACK_JWKS_PINS";H.ALLOW_INSECURE_TRUST_ROOT_ENV="AGENTHIPPO_ALLOW_INSECURE_TRUST_ROOT";H.LEASE_SIGNING_KEYS_ENV="AGENTHIPPO_LEASE_SIGNING_KEYS";H.LEASE_JWKS_URL_ENV="AGENTHIPPO_LEASE_JWKS_URL";H.LEASE_JWKS_PINS_ENV="AGENTHIPPO_LEASE_JWKS_PINS";function Nm(t){let e=Gi.createPublicKey(t),n=e.export({format:"jwk"}),r=n.kty==="EC"?{crv:n.crv,kty:n.kty,x:n.x,y:n.y}:n.kty==="RSA"?{e:n.e,kty:n.kty,n:n.n}:{kty:n.kty};return{jwk:Gi.createHash("sha256").update(JSON.stringify(r)).digest("base64url"),spki:Gi.createHash("sha256").update(e.export({type:"spki",format:"der"})).digest("hex")}}var gN=t=>t.trim().replace(/^sha256:/i,"").toLowerCase();function Rm(t){return(t??"").split(",").map(gN).filter(e=>e.length>0)}function Cm(t,e,n=process.env){let r;try{r=new URL(t)}catch{return{ok:!1,reason:`${e} is not a valid URL: ${t}`}}if(r.protocol==="https:")return{ok:!0,warnings:[]};let s=(n[H.ALLOW_INSECURE_TRUST_ROOT_ENV]??"").trim().toLowerCase();return s==="1"||s==="true"||s==="yes"?{ok:!0,warnings:[`INSECURE: ${e} is ${r.protocol}//${r.host} (not https) and ${H.ALLOW_INSECURE_TRUST_ROOT_ENV} is set. Anyone on the path between this instance and that host can choose which packs it will run and whether the kill switch is honoured. This must never be set outside local development.`]}:{ok:!1,reason:`${e} must be https (got ${r.protocol}//${r.host}). Set ${H.ALLOW_INSECURE_TRUST_ROOT_ENV}=1 to allow plaintext for LOCAL DEVELOPMENT ONLY.`}}var hN={label:"pack",purpose:"pack-signing",inlineEnv:"AGENTHIPPO_PACK_SIGNING_KEYS",urlEnvs:[H.PACK_JWKS_URL_ENV,H.PACK_JWKS_URL_ENV_LEGACY],pinsEnv:H.PACK_JWKS_PINS_ENV,derivedRisk:"chooses which packs this instance will run"},mN={label:"lease",purpose:"lease-signing",inlineEnv:H.LEASE_SIGNING_KEYS_ENV,urlEnvs:[H.LEASE_JWKS_URL_ENV],pinsEnv:H.LEASE_JWKS_PINS_ENV,derivedRisk:"chooses whether this instance's kill switch is ever honoured"};async function km(t,e){let n=e.env??process.env,r=[],s=Rm(n[t.pinsEnv]),i=n[t.inlineEnv]?.trim(),o=t.urlEnvs.map(d=>n[d]).find(d=>d!==void 0&&d.trim()!=="")?.trim(),a=!!i||!!o,c=(d,p,g)=>{if(s.length===0)return Object.keys(d).length===0?{status:"unavailable",keys:{},source:p,url:g,warnings:r,explicitlyConfigured:a,reason:"the trust root published no usable ES256 keys"}:{status:"configured",keys:d,source:p,url:g,warnings:r,explicitlyConfigured:a};let m={};for(let[h,E]of Object.entries(d)){let _;try{_=Nm(E)}catch{r.push(`${t.label} trust root: key ${h} is unreadable and was dropped`);continue}s.some(b=>(0,vo.timingSafeEqualString)(b,_.jwk.toLowerCase())||(0,vo.timingSafeEqualString)(b,_.spki))?m[h]=E:r.push(`${t.label} trust root: key ${h} does not match any pin in ${t.pinsEnv} and was REFUSED (its thumbprints are jwk=${_.jwk} spki=${_.spki})`)}return Object.keys(m).length===0?{status:"unavailable",keys:{},source:p,url:g,warnings:r,explicitlyConfigured:a,reason:`every key offered by the trust root failed the ${t.pinsEnv} pin check`}:{status:"configured",keys:m,source:p,url:g,warnings:r,explicitlyConfigured:a}};if(i){let d;try{d=JSON.parse(i)}catch(p){return{status:"unavailable",keys:{},source:"inline",warnings:r,explicitlyConfigured:a,reason:`${t.inlineEnv} is set but is not valid JSON: ${p instanceof Error?p.message:String(p)}`}}return c(d,"inline")}let l=o,f=!1;if(!l&&e.leaseUrl){try{l=new URL(`/.well-known/jwks.json?purpose=${t.purpose}`,e.leaseUrl).toString()}catch{return{status:"unavailable",keys:{},warnings:r,explicitlyConfigured:a,reason:`AGENTHIPPO_LEASE_URL is not a valid URL: ${e.leaseUrl}`}}f=!0}if(!l)return{status:"unconfigured",keys:{},warnings:r,explicitlyConfigured:a};let u=Cm(l,`the ${t.purpose} JWKS URL`,n);if(!u.ok)return{status:"unavailable",keys:{},source:"jwks",url:l,warnings:r,reason:u.reason,derivedFromLease:f,explicitlyConfigured:a};r.push(...u.warnings),f&&s.length===0&&r.push(`${t.label} trust root is derived from AGENTHIPPO_LEASE_URL (${l}) and is not pinned. Whoever can answer that origin ${t.derivedRisk}. Pin it with ${t.urlEnvs[0]} and ${t.pinsEnv}.`);try{let d=await(e.fetchImpl??fetch)(l);if(!d.ok)return{status:"unavailable",keys:{},source:"jwks",url:l,warnings:r,reason:`JWKS fetch returned HTTP ${d.status}`,derivedFromLease:f,explicitlyConfigured:a};let p=await d.json(),g=yN(p);return g.ok?{...c(g.pems,"jwks",l),derivedFromLease:f}:{status:"unavailable",keys:{},source:"jwks",url:l,warnings:r,reason:g.reason,derivedFromLease:f,explicitlyConfigured:a}}catch(d){return{status:"unavailable",keys:{},source:"jwks",url:l,warnings:r,derivedFromLease:f,explicitlyConfigured:a,reason:`JWKS fetch failed: ${d instanceof Error?d.message:String(d)}`}}}async function $m(t){return km(hN,t)}async function EN(t){return km(mN,t)}function _N(t,e){return t.explicitlyConfigured?{keys:t.keys,packFallback:!1}:{keys:{...e.keys,...t.keys},packFallback:!0}}function yN(t){if(t.pemsByKid&&typeof t.pemsByKid=="object")return{ok:!0,pems:t.pemsByKid};if(!Array.isArray(t.keys))return{ok:!1,reason:"JWKS document has neither `pemsByKid` nor a `keys` array"};let e={};for(let n of t.keys)if(!(!n||typeof n!="object")&&!(n.kty!=="EC"||n.crv!=="P-256")&&!(n.alg!==void 0&&n.alg!=="ES256")&&!(typeof n.kid!="string"||!n.kid))try{e[n.kid]=Gi.createPublicKey({key:n,format:"jwk"}).export({type:"spki",format:"pem"}).toString()}catch{}return Object.keys(e).length===0?{ok:!1,reason:"JWKS document published no usable ES256 (P-256) keys"}:{ok:!0,pems:e}}async function wN(t){return(await $m(t)).keys}H.PACK_PROBE_INTERVAL_MS=1e3;H.PACK_FULL_REVERIFY_INTERVAL_MS=3e4;function AN(t={}){let e=t.probeIntervalMs??H.PACK_PROBE_INTERVAL_MS,n=t.fullReverifyIntervalMs??H.PACK_FULL_REVERIFY_INTERVAL_MS,r,s="",i="",o=0,a=0,c=0,l=u=>`${u.packDir}\0${u.pack}\0${u.packVersion}\0${Object.keys(u.keys).sort().join(",")}`,f=(u,d)=>{c+=1,s=l(u),i=Ju(u.packDir),o=d,a=d;let p=vm(u.packDir);return r=p?Om(p,u.keys,{packDir:u.packDir,pack:u.pack,packVersion:u.packVersion}):{ok:!1,kind:"unsigned",reason:`${u.pack} is not signed (no ${H.PACK_SIGNATURE_FILE} at the pack root)`},r};return{fullVerifications:()=>c,refresh(u,d=Date.now()){return f(u,d)},verify(u,d=Date.now()){return!r||s!==l(u)||d-a>=n?f(u,d):d-o<e||(o=d,Ju(u.packDir)===i)?r:f(u,d)}}}});var td=S(rn=>{"use strict";var SN=rn&&rn.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,s)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),TN=rn&&rn.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),Dm=rn&&rn.__importStar||(function(){var t=function(e){return t=Object.getOwnPropertyNames||function(n){var r=[];for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(r[r.length]=s);return r},t(e)};return function(e){if(e&&e.__esModule)return e;var n={};if(e!=null)for(var r=t(e),s=0;s<r.length;s++)r[s]!=="default"&&SN(n,e,r[s]);return TN(n,e),n}})();Object.defineProperty(rn,"__esModule",{value:!0});rn.CURRENT_LINK=void 0;rn.safeJoin=Lm;rn.promoteCurrent=ed;rn.reconcilePinnedPack=bN;rn.readDirAsFiles=Mm;var $t=Dm(require("node:fs")),gs=Dm(require("node:path")),Zu=Oo();rn.CURRENT_LINK="current";function Lm(t,e){if(gs.isAbsolute(e))return;let n=gs.resolve(t,e),r=t.endsWith(gs.sep)?t:t+gs.sep;return n.startsWith(r)?n:void 0}function ed(t,e){let n=gs.join(t,rn.CURRENT_LINK),r=`${n}.swap-${process.pid}-${Date.now()}`;return $t.symlinkSync(e,r),$t.renameSync(r,n),n}async function bN(t){let{pack:e,pinnedVersion:n,packsRoot:r,logger:s}=t,i=gs.join(r,n);if($t.mkdirSync(r,{recursive:!0}),$t.existsSync(i)){let c=vN(i,e,n,t.publicKeysByKid);if(c.ok)return ed(r,i),{ok:!0,packDir:i,version:n,alreadyPresent:!0};s?.warn(`[Pack] cached ${e}@${n} failed verification (${c.reason}); re-fetching`),$t.rmSync(i,{recursive:!0,force:!0})}let o;try{o=await t.download(e,n)}catch(c){return{ok:!1,reason:`fetch failed: ${c instanceof Error?c.message:String(c)}`}}if(o.length===0)return{ok:!1,reason:`store returned no files for ${e}@${n}`};let a=gs.join(r,`.staging-${n}-${process.pid}-${Date.now()}`);try{$t.mkdirSync(a,{recursive:!0});for(let l of o){let f=Lm(a,l.path);if(!f)return $t.rmSync(a,{recursive:!0,force:!0}),{ok:!1,reason:`refusing artifact: entry escapes the pack root (${l.path})`};if(l.link)return $t.rmSync(a,{recursive:!0,force:!0}),{ok:!1,reason:`refusing artifact: symlink entries are not accepted from the store (${l.path})`};$t.mkdirSync(gs.dirname(f),{recursive:!0}),$t.writeFileSync(f,l.content)}let c=Gm(o,e,n,t.publicKeysByKid);return c.ok?($t.renameSync(a,i),ed(r,i),s?.info(`[Pack] converged to ${e}@${n} (signature verified)`),{ok:!0,packDir:i,version:n,alreadyPresent:!1}):($t.rmSync(a,{recursive:!0,force:!0}),{ok:!1,reason:c.reason})}catch(c){return $t.rmSync(a,{recursive:!0,force:!0}),{ok:!1,reason:`staging failed: ${c instanceof Error?c.message:String(c)}`}}}function Mm(t){let e=[],n=(r,s)=>{for(let i of $t.readdirSync(r)){let o=s?`${s}/${i}`:i;if(Zu.DIGEST_EXCLUDED_SEGMENTS.has(i))continue;let a=gs.join(r,i),c=$t.lstatSync(a);c.isSymbolicLink()?e.push({path:o,content:Buffer.from($t.readlinkSync(a)),link:!0}):c.isDirectory()?n(a,o):c.isFile()&&e.push({path:o,content:$t.readFileSync(a)})}};return n(t,""),e}function Gm(t,e,n,r){if(Object.keys(r).length===0)return{ok:!1,reason:"no trusted signing keys configured"};let s=t.find(a=>a.path.replace(/\\/g,"/")===Zu.PACK_SIGNATURE_FILE);if(!s)return{ok:!1,reason:`${e}@${n} is not signed`};let i=s.content.toString("utf8").trim(),o=(0,Zu.verifyPackFromFiles)(i,r,e,n,t);return o.ok?{ok:!0}:{ok:!1,reason:o.reason}}function vN(t,e,n,r){return Gm(Mm(t),e,n,r)}});var _c=S(_e=>{"use strict";Object.defineProperty(_e,"__esModule",{value:!0});_e.STORE_ICONS=_e.STORE_PATHS=_e.DEFAULT_STORE_BRANCH=_e.DEFAULT_STORE_REPO=_e.DEFAULT_STORE_OWNER=void 0;_e.parseGitHubUrl=Um;_e.parseStoreUrl=ON;_e.formatStoreUrl=IN;_e.isStoreUrl=PN;_e.getStorePath=Hm;_e.getStoreIndexUrl=NN;_e.getTagsApiUrl=RN;_e.isForkOfStoreRepo=CN;_e.formatStorePullRequestError=kN;_e.DEFAULT_STORE_OWNER="agenthippoai";_e.DEFAULT_STORE_REPO="agenthippo-store";_e.DEFAULT_STORE_BRANCH="main";_e.STORE_PATHS={packs:"agent-packs",skills:"skills",mcp:"mcp",engines:"engines",spotlightViews:"spotlight"};_e.STORE_ICONS={local:"\u{1F4BE}",remote:"\u2601\uFE0F",installed:"\u2713",pack:"\u{1F4E6}",skill:"\u{1F3AF}",mcp:"\u{1F50C}",engine:"\u2699\uFE0F",view:"\u{1F4CA}"};function Um(t,e=_e.DEFAULT_STORE_OWNER,n=_e.DEFAULT_STORE_REPO){let r=t.trim(),s=r.match(/github\.com\/([^/]+)\/([^/]+)(?:\/tree\/([^/]+)(?:\/(.+))?)?/);if(s){let[,o,a,c,l]=s,f=o===e&&a===n;return{owner:o,repo:a.replace(/\.git$/,""),ref:c,path:l,isStore:f}}let i=r.match(/^([^/]+)\/([^/@]+)(?:@(.+))?$/);if(i){let[,o,a,c]=i;return{owner:o,repo:a,ref:c,isStore:o===e&&a===n}}throw new Error(`Invalid GitHub URL: ${t}`)}function ON(t){let e=t.trim(),n=e.match(/github\.com\/[^/]+\/[^/]+\/tree\/[^/]+\/(.+)/);n&&(e=n[1]),e=e.replace(/^store:\/\//,"");let r;if(e.includes("@")){let[c,l]=e.split("@");e=c,r=l.replace(/^v/,"")}e=e.replace(/\/$/,"");let s=e.split("/");if(s.length<2)throw new Error(`Invalid store URL: ${t}. Expected format: type/slug[@version]`);let i=s[0],o=s.slice(1).join("/"),a;if(i==="agent-packs"||i==="packs"||i==="pack")a="pack";else if(i==="skills"||i==="skill")a="skill";else if(i==="mcp")a="mcp";else if(i==="engines"||i==="engine")a="engine";else if(i==="spotlight"||i==="spotlight-views"||i==="views"||i==="view")a="view";else throw new Error(`Invalid artifact type: ${i}. Expected: pack, skill, mcp, engine, or view`);return{type:a,slug:o,version:r}}function IN(t){let n=`store://${Hm(t.type)}/${t.slug}`;return t.version&&(n+=`@v${t.version}`),n}function PN(t,e=_e.DEFAULT_STORE_OWNER,n=_e.DEFAULT_STORE_REPO){let r=t.trim().replace(/^store:\/\//,"");if(/^(agent-packs|packs|pack|skills|skill|mcp|engines|engine|spotlight|spotlight-views|views|view)\//.test(r))return!0;try{let s=Um(t,e,n);if(s.isStore&&s.path)return/^(agent-packs|skills|mcp|engines|spotlight|spotlight-views)\//.test(s.path)}catch{}return!1}function Hm(t){switch(t){case"pack":return _e.STORE_PATHS.packs;case"skill":return _e.STORE_PATHS.skills;case"mcp":return _e.STORE_PATHS.mcp;case"engine":return _e.STORE_PATHS.engines;case"view":return _e.STORE_PATHS.spotlightViews}}function NN(t=_e.DEFAULT_STORE_OWNER,e=_e.DEFAULT_STORE_REPO){return`https://${t}.github.io/${e}/store-index.json`}function RN(t=_e.DEFAULT_STORE_OWNER,e=_e.DEFAULT_STORE_REPO){return`https://api.github.com/repos/${t}/${e}/git/refs/tags`}function CN(t,e,n){if(!t.fork)return!1;let r=`${e}/${n}`.toLowerCase();return(t.parentFullName??"").toLowerCase()===r}function kN(t,e,n,r){try{let s=JSON.parse(t),i=[s.message,...s.errors?.map(o=>o.message)??[]].filter(Boolean).join(" ");if(i.includes("no history in common")){let o=r?`https://github.com/${r}/${n}`:`your fork of ${e}/${n}`;return`Cannot open pull request: your fork has no shared git history with ${e}/${n}.
475
+ \`\`\``}catch{t.json?console.log(JSON.stringify({error:`Failed to read file: ${t.file}`})):console.error(`Error: Failed to read file: ${t.file}`),process.exit(1)}let l=fm.join(HP.tmpdir(),"agenthippo-cli"),f=t.verbose?new Hr.ConsoleLogger("[Agent]"):new Hr.NoOpLogger,u=(0,jr.findClaudeCodePath)(),d=(0,jr.findCodexPath)(),p=(0,jr.findBundledBasePromptsDir)();s==="claude"&&!u&&(t.json?console.log(JSON.stringify({error:"Claude Code CLI not found. Install: npm install -g @anthropic-ai/claude-code"})):(console.error(`${jr.COLORS.red}Error: Claude Code CLI not found.${jr.COLORS.reset}`),console.error(" Install: npm install -g @anthropic-ai/claude-code"),console.error(" Or set CLAUDE_CODE_PATH, or use --engine codex")),process.exit(1)),s==="codex"&&!d&&(t.json?console.log(JSON.stringify({error:"Codex CLI not found. Install: npm install -g @openai/codex"})):(console.error(`${jr.COLORS.red}Error: Codex CLI not found.${jr.COLORS.reset}`),console.error(" Install: npm install -g @openai/codex"),console.error(" Or set CODEX_PATH, or use --engine claude")),process.exit(1));let g=new Hr.AutoApprovePermissionHandler,m={fileAccess:(0,ui.getFileAccess)(n)},h=(0,Hr.createHeadlessRunner)({storagePath:l,packId:r,packVersion:n?.manifest.metadata.version,bundledPromptsDir:p,apiKey:e.apiKey,baseUrl:e.baseUrl,useLiteLLM:e.useLiteLLM,litellmApiKey:e.litellmApiKey,openaiApiKey:e.openaiApiKey,anthropicApiKey:e.anthropicApiKey,logger:f,freshState:!t.sessionId?.trim(),permissionHandler:g,claudeCodeExecutablePath:u,codexExecutablePath:d,cliEnvPatch:(0,jP.buildCliEnvPatch)({cliPath:process.execPath,workspaceRoot:t.workspace,agentId:r,chatSessionId:t.sessionId,baseEnv:process.env}),...o?{engineSettings:{claudeCheapModel:o}}:{}});try{let E=await h.run({engineId:s,modelId:i,message:c,workspaceRoot:t.workspace,sessionId:t.sessionId,permissions:m});t.json?(t.outputMode==="agent-run"?console.log(JSON.stringify({text:E.text,media:[],session_id:t.sessionId||null,error:E.error||void 0})):console.log(JSON.stringify({success:E.success,text:E.text,thinking:E.thinking||void 0,toolCalls:E.toolCalls,error:E.error})),E.success||process.exit(1)):E.success?console.log(E.text):(console.error(`Error: ${E.error}`),process.exit(1))}catch(E){t.json?console.log(JSON.stringify({error:E instanceof Error?E.message:String(E)})):console.error(`Error: ${E instanceof Error?E.message:E}`),process.exit(1)}finally{h.dispose()}}});var Ku=S(xr=>{"use strict";Object.defineProperty(xr,"__esModule",{value:!0});xr.isTerminalFrame=BP;xr.isTaggedEvent=FP;xr.encodeRunnerFrame=VP;xr.encodeClientFrame=WP;xr.parseRunnerFrame=KP;xr.parseClientFrame=qP;xr.splitFrames=YP;xr.toWireOptions=XP;function BP(t){return"type"in t&&(t.type==="result"||t.type==="failed")}function FP(t){return"event"in t}function VP(t){return`${JSON.stringify(t)}
476
+ `}function WP(t){return`${JSON.stringify(t)}
477
+ `}function KP(t){let e=mm(t);if(!e)return;let n=e.type;if(n==="ready")return{type:"ready",...e.demux===!0?{demux:!0}:{}};if(typeof e.id=="string"&&e.event&&typeof e.event=="object"){let r=e.event.type;return typeof r=="string"&&hm.has(r)?{id:e.id,event:e.event}:void 0}if(n==="result"&&typeof e.id=="string")return{type:"result",id:e.id,...typeof e.nativeSessionId=="string"?{nativeSessionId:e.nativeSessionId}:{}};if(n==="failed"&&typeof e.id=="string")return{type:"failed",id:e.id,message:typeof e.message=="string"?e.message:"Sandbox turn failed"};if(n==="question"&&e.payload&&typeof e.payload=="object")return{type:"question",payload:e.payload,...typeof e.id=="string"?{id:e.id}:{}};if(typeof n=="string"&&hm.has(n))return e}function qP(t){let e=mm(t);if(e){if(e.type==="run"&&typeof e.id=="string"&&typeof e.message=="string"){let n=e.options&&typeof e.options=="object"?e.options:{};return{type:"run",id:e.id,message:e.message,options:n}}if(e.type==="abort"&&typeof e.id=="string")return{type:"abort",id:e.id}}}var hm=new Set(["text","thinking","toolStart","toolEnd","progress","error","done","nativeSessionId","probe"]);function mm(t){let e;try{e=JSON.parse(t)}catch{return}if(!(!e||typeof e!="object"||Array.isArray(e)))return e}function YP(t){let e=t.split(`
478
+ `),n=e.pop()??"";return{lines:e.filter(r=>r.trim().length>0),rest:n}}function XP(t,e){let{apiKey:n,...r}=t;return{...r,...e.baseUrl?{baseUrl:e.baseUrl}:{},...e.modelToken?{modelToken:e.modelToken}:{}}}});var _m=S(Ec=>{"use strict";Object.defineProperty(Ec,"__esModule",{value:!0});Ec.RemoteEngine=void 0;var Em=sc(),Oo=Ku(),qu=class{id;displayName;channel;model;logger;pending=new Map;buffer="";seq=0;wired=!1;peerDemux=!1;constructor(e){this.id=e.id,this.displayName=e.displayName,this.channel=e.channel,this.model=e.model??{},this.logger=e.logger}async stream(e,n,r,s,i){this.wire();let o=`r${++this.seq}`,a=new Promise((l,f)=>{this.pending.set(o,{emitter:r,resolve:l,reject:f,chain:Promise.resolve()})}),c=()=>{this.send({type:"abort",id:o})};i&&(i.aborted?c():i.addEventListener("abort",c,{once:!0}));try{let l=this.model.mintToken?await this.model.mintToken()??this.model.modelToken:this.model.modelToken;this.send({type:"run",id:o,message:e,options:(0,Oo.toWireOptions)(n,{...this.model,modelToken:l})}),await a}finally{this.pending.delete(o),i?.removeEventListener("abort",c)}}onMaintenance(){}dispose(){}wire(){this.wired||(this.wired=!0,this.channel.input.on("data",e=>{this.buffer+=typeof e=="string"?e:e.toString("utf8");let{lines:n,rest:r}=(0,Oo.splitFrames)(this.buffer);this.buffer=r;for(let s of n){let i=(0,Oo.parseRunnerFrame)(s);if(!i){this.logger?.warn("[RemoteEngine] dropped malformed runner frame");continue}this.dispatch(i)}}),this.channel.closed?.then(()=>this.failAll(new Error("sandbox channel closed")),e=>this.failAll(e instanceof Error?e:new Error(String(e)))))}dispatch(e){if((0,Oo.isTaggedEvent)(e)){this.enqueue(this.pending.get(e.id),n=>(0,Em.applyParsedRunnerEvent)(n.emitter,e.event));return}if(e.type==="ready"){this.peerDemux=e.demux===!0;return}if(e.type==="result"){this.settle(e.id,n=>n.resolve(e.nativeSessionId));return}if(e.type==="failed"){this.settle(e.id,n=>n.reject(new Error(e.message)));return}if(e.type==="question"){let n=e.id?[this.pending.get(e.id)]:[...this.pending.values()];for(let r of n)this.enqueue(r,s=>s.emitter.question(e.payload).then(()=>{}));return}for(let n of this.pending.values())this.enqueue(n,r=>(0,Em.applyParsedRunnerEvent)(r.emitter,e).then(()=>{}))}enqueue(e,n){e&&(e.chain=e.chain.then(()=>n(e)).then(()=>{},r=>{this.logger?.warn(`[RemoteEngine] emitter error: ${r instanceof Error?r.message:String(r)}`)}))}settle(e,n){let r=this.pending.get(e);r&&r.chain.then(()=>n(r))}supportsDemux(){return this.peerDemux}failAll(e){for(let[n,r]of this.pending)r.reject(e),this.pending.delete(n)}send(e){this.channel.output.write((0,Oo.encodeClientFrame)(e))}};Ec.RemoteEngine=qu});var Am=S(Yu=>{"use strict";Object.defineProperty(Yu,"__esModule",{value:!0});Yu.createSandboxRunner=ZP;var JP=_m(),zP=Un(),QP=Is();function ZP(t){let e=new Map,n=new Map,r=new Map,s=1e4,i=(u,d)=>{if(r.size>=s&&!r.has(u)){let p=r.keys().next();p.done||r.delete(p.value)}r.set(u,d)},o=u=>r.get(u)??u,a=async(u,d)=>{await t.admit?.({sandboxKey:u,sessionKey:d});let p=await t.driver.create({sandboxKey:u,image:t.image,tier:t.tier,routes:t.routes,fs:await t.fsFor?.(u)??t.fs??{readonly:[],writable:[]},...t.stateDirFor?{stateDir:await t.stateDirFor(u)}:{},limits:t.limits??{ttlSeconds:1800},env:{...t.env??{},...t.provenanceEnv?.()??{}}}),g=await t.mintModelToken?.(p.id,u),m=p.connect(),h=new JP.RemoteEngine({id:"sandbox",displayName:`Sandbox ${p.id}`,channel:m,model:{baseUrl:t.inferenceBaseUrl,modelToken:g,...t.mintModelToken?{mintToken:async()=>t.mintModelToken(p.id,u)}:{}},logger:t.logger}),E={handle:p,engine:h,dead:!1,sessionKeys:new Set([d]),queue:Promise.resolve()},_=y=>{E.dead=!0;let b=e.get(u)===E;b&&e.delete(u);let T=y instanceof Error?`: ${y.message}`:"";t.logger?.info(`[Sandbox] ${p.id} closed${T}; ${u} will rehydrate on next message`),b&&t.driver.destroy(p).catch(()=>{})};return m.closed?.then(()=>_(),_),e.set(u,E),t.logger?.info(`[Sandbox] created ${p.id} for ${u} (tier ${p.tier})`),E},c=(u,d)=>{let p=e.get(u);if(p&&!p.dead)return Promise.resolve(p);p?.dead&&e.delete(u);let g=n.get(u);if(g)return g;let m=a(u,d).finally(()=>{n.delete(u)});return n.set(u,m),m},l=async(u,d)=>{if(u.engine.supportsDemux())return d(u);let p=u.queue,g;if(u.queue=new Promise(m=>{g=m}),await p,u.dead)throw g(),new Error("sandbox channel closed");try{return await d(u)}finally{g()}};return{run:async u=>{let d=u.sessionId??"default",p=u.sandboxKey??d,g=y=>(y.sessionKeys.add(d),i(d,p),y),m={text:"",thinking:"",toolCalls:[]},h=eN(u.emitter,m),E=()=>m.text===""&&m.thinking===""&&m.toolCalls.length===0,_=async y=>{await y.engine.stream(u.message,{engineId:u.engineId,modelId:u.modelId,workspaceRoot:u.workspaceRoot,additionalDirectories:u.additionalDirectories,sessionId:u.sessionId,permissions:u.permissions,analyticsUserId:u.analyticsUserId,engineHomeUserKey:(0,zP.engineHomeUserKey)((0,QP.currentCredential)()?.userId),turnEnv:u.turnEnv,gatewaySessionKey:u.gatewaySessionKey},h,t.runtime,u.signal)};try{let y=g(await c(p,d));try{await l(y,_)}catch(b){let T=ym(b);if(!/channel closed/i.test(T)||!E())throw b;e.get(p)===y&&e.delete(p),t.logger?.info(`[Sandbox] session ${d} lost its sandbox mid-turn; recreating and retrying once`),await l(g(await c(p,d)),_)}return{success:!0,text:m.text,thinking:m.thinking,toolCalls:m.toolCalls}}catch(y){return{success:!1,text:m.text,thinking:m.thinking,toolCalls:m.toolCalls,error:ym(y)}}},dispose(){for(let[u,d]of e)t.driver.destroy(d.handle).catch(()=>{}),e.delete(u)},sandboxes:()=>[...e.entries()].map(([u,d])=>({sandboxKey:u,sandboxId:d.handle.id,tier:d.handle.tier,sessionKeys:[...d.sessionKeys]})),async destroySession(u){let d=o(u),p=e.get(d);p&&(e.delete(d),await t.driver.destroy(p.handle),t.logger?.info(`[Sandbox] destroyed ${p.handle.id} (${d}${wm(p,u)})`))},async revokeRoute(u,d){let p=o(u),g=e.get(p);g&&(await t.driver.revoke(g.handle,d),d==="all"&&e.delete(p),t.logger?.info(`[Sandbox] revoked ${d} on ${g.handle.id} (${p}${wm(g,u)})`))}}}function eN(t,e){return{async thinking(n){e.thinking+=n,await t?.thinking(n)},async text(n){e.text+=n,await t?.text(n)},async toolStart(n,r,s,i){e.toolCalls.push({name:n,input:r}),await t?.toolStart(n,r,s,i)},async toolEnd(n,r,s,i,o){let a=[...e.toolCalls].reverse().find(c=>c.name===n&&c.result===void 0);a&&(a.result=s,a.isError=i),await t?.toolEnd(n,r,s,i,o)},async progress(n){await t?.progress(n)},async question(n){return await t?.question(n),{selected:[],freeText:null,declined:!0}},async error(n){await t?.error(n)},async done(){await t?.done()}}}function ym(t){return t instanceof Error?t.message:String(t)}function wm(t,e){let n=[...t.sessionKeys].filter(r=>r!==e);return n.length===0?"":`, also ending ${n.length}: ${n.join(", ")}`}});var Mi=S(Vt=>{"use strict";var tN=Vt&&Vt.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,s)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),nN=Vt&&Vt.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),rN=Vt&&Vt.__importStar||(function(){var t=function(e){return t=Object.getOwnPropertyNames||function(n){var r=[];for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(r[r.length]=s);return r},t(e)};return function(e){if(e&&e.__esModule)return e;var n={};if(e!=null)for(var r=t(e),s=0;s<r.length;s++)r[s]!=="default"&&tN(n,e,r[s]);return nN(n,e),n}})();Object.defineProperty(Vt,"__esModule",{value:!0});Vt.b64urlEncode=Xu;Vt.signCompactJws=Sm;Vt.verifyCompactJws=Tm;Vt.timingSafeEqualString=sN;Vt.generateWarrantKeypair=iN;Vt.mintWarrant=aN;Vt.verifyWarrant=cN;Vt.jwks=lN;var fs=rN(require("node:crypto"));function Xu(t){return Buffer.from(t,"utf8").toString("base64url")}function Sm(t,e,n){let r={alg:"ES256",typ:t.typ??"JWT",kid:t.kid},s=`${Xu(JSON.stringify(r))}.${Xu(JSON.stringify(e))}`,i=fs.sign("sha256",Buffer.from(s),{key:fs.createPrivateKey(n),dsaEncoding:"ieee-p1363"});return`${s}.${i.toString("base64url")}`}function Tm(t,e,n={}){let r=t.split(".");if(r.length!==3)return{ok:!1,reason:"malformed"};let[s,i,o]=r,a,c;try{a=JSON.parse(Buffer.from(s,"base64url").toString("utf8")),c=JSON.parse(Buffer.from(i,"base64url").toString("utf8"))}catch{return{ok:!1,reason:"unparseable"}}if(a.alg!=="ES256")return{ok:!1,reason:`unsupported alg ${a.alg}`};if(n.typ!==void 0&&a.typ!==void 0&&a.typ!==n.typ)return{ok:!1,reason:`unexpected token type ${a.typ}`};let l=a.kid?e[a.kid]:void 0;if(!l)return{ok:!1,reason:"unknown kid"};let f=!1;try{f=fs.verify("sha256",Buffer.from(`${s}.${i}`),{key:fs.createPublicKey(l),dsaEncoding:"ieee-p1363"},Buffer.from(o,"base64url"))}catch{return{ok:!1,reason:"bad signature"}}return f?{ok:!0,header:a,payload:c,signingInput:`${s}.${i}`}:{ok:!1,reason:"bad signature"}}function sN(t,e){let n=Buffer.from(t,"utf8"),r=Buffer.from(e,"utf8");return n.length!==r.length?!1:fs.timingSafeEqual(n,r)}function iN(t){let{privateKey:e,publicKey:n}=fs.generateKeyPairSync("ec",{namedCurve:"P-256"}),r=n.export({type:"spki",format:"pem"}).toString();return{privateKeyPem:e.export({type:"pkcs8",format:"pem"}).toString(),publicKeyPem:r,kid:t??fs.createHash("sha256").update(r).digest("hex").slice(0,16)}}var oN=300;function aN(t,e){let n=t.nowSeconds??Math.floor(Date.now()/1e3),r=Math.min(t.ttlSeconds??120,oN),s={user:t.user,pack:t.pack,packVersion:t.packVersion,sandboxId:t.sandboxId,tier:t.tier,aud:t.aud,iat:n,exp:n+r,jti:fs.randomUUID()};return Sm({typ:"JWT",kid:e.kid},s,e.privateKeyPem)}function cN(t,e,n){let r=Tm(t,e);if(!r.ok)return{ok:!1,reason:r.reason};let s=r.payload,i=n.nowSeconds??Math.floor(Date.now()/1e3);return typeof s.exp!="number"||s.exp<=i?{ok:!1,reason:"expired"}:s.aud!==n.audience?{ok:!1,reason:`wrong audience ${s.aud}`}:n.channelSandboxId!==void 0&&s.sandboxId!==n.channelSandboxId?{ok:!1,reason:"warrant not bound to this channel"}:s.user?{ok:!0,claims:s}:{ok:!1,reason:"no principal"}}function lN(t){return{keys:t.map(e=>({...fs.createPublicKey(e.publicKeyPem).export({format:"jwk"}),kid:e.kid,alg:"ES256",use:"sig"}))}}});var Po=S(H=>{"use strict";var uN=H&&H.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,s)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),dN=H&&H.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),zu=H&&H.__importStar||(function(){var t=function(e){return t=Object.getOwnPropertyNames||function(n){var r=[];for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(r[r.length]=s);return r},t(e)};return function(e){if(e&&e.__esModule)return e;var n={};if(e!=null)for(var r=t(e),s=0;s<r.length;s++)r[s]!=="default"&&uN(n,e,r[s]);return dN(n,e),n}})();Object.defineProperty(H,"__esModule",{value:!0});H.PACK_FULL_REVERIFY_INTERVAL_MS=H.PACK_PROBE_INTERVAL_MS=H.LEASE_JWKS_PINS_ENV=H.LEASE_JWKS_URL_ENV=H.LEASE_SIGNING_KEYS_ENV=H.ALLOW_INSECURE_TRUST_ROOT_ENV=H.PACK_JWKS_PINS_ENV=H.PACK_JWKS_URL_ENV_LEGACY=H.PACK_JWKS_URL_ENV=H.ALLOW_UNSIGNED_PACK_ENV=H.DIGEST_EXCLUDED_SEGMENTS=H.PACK_SIGNATURE_FILE=void 0;H.isDigestExcluded=yc;H.computePackDigestFromFiles=vm;H.computePackDigest=Qu;H.packTreeProbe=Ju;H.signPack=fN;H.readPackSignature=Om;H.verifyPack=Im;H.verifyPackFromFiles=pN;H.requireSignedPack=Nm;H.resolveRequireSignedPack=hN;H.allowUnsignedPackFromEnv=mN;H.describePackRefusal=EN;H.publicKeyThumbprints=Rm;H.parseJwksPins=Cm;H.assertSecureTrustUrl=km;H.loadPackTrustRoot=Dm;H.loadLeaseTrustRoot=AN;H.selectLeaseSigningKeys=SN;H.loadPackSigningKeys=bN;H.createPackVerifier=vN;var Gi=zu(require("node:crypto")),ks=zu(require("node:fs")),_c=zu(require("node:path")),Io=Mi();H.PACK_SIGNATURE_FILE="pack.sig";H.DIGEST_EXCLUDED_SEGMENTS=new Set([".git","node_modules"]);function yc(t){return t===H.PACK_SIGNATURE_FILE?!0:t.split("/").some(e=>H.DIGEST_EXCLUDED_SEGMENTS.has(e))}function bm(t){let e=Gi.createHash("sha256"),n=[...t].sort((r,s)=>r.rel<s.rel?-1:r.rel>s.rel?1:0);for(let r of n){r.link&&e.update("L:");let s=Buffer.from(r.rel);e.update(`${s.length}:`),e.update(s),e.update(`${r.body.length}:`),e.update(r.body)}return e.digest("hex")}function vm(t){let e=[];for(let n of t){let r=n.path.replace(/\\/g,"/");yc(r)||e.push({rel:r,body:n.content,link:n.link})}return bm(e)}function Qu(t){let e=[],n=(r,s)=>{for(let i of ks.readdirSync(r)){let o=s?`${s}/${i}`:i;if(yc(o))continue;let a=_c.join(r,i),c=ks.lstatSync(a);c.isSymbolicLink()?e.push({rel:o,body:Buffer.from(ks.readlinkSync(a)),link:!0}):c.isDirectory()?n(a,o):c.isFile()&&e.push({rel:o,body:ks.readFileSync(a)})}};return n(t,""),bm(e)}function Ju(t){let e=[],n=(r,s)=>{let i;try{i=ks.readdirSync(r).sort()}catch{e.push(`${s}/?unreadable`);return}for(let o of i){let a=s?`${s}/${o}`:o;if(yc(a))continue;let c=_c.join(r,o),l;try{l=ks.lstatSync(c)}catch{e.push(`${a}|gone`);continue}if(l.isDirectory()){n(c,a);continue}e.push(`${a}|${l.size}|${l.mtimeMs}|${l.ino}|${l.mode}`)}};try{n(t,"")}catch{return"unwalkable"}return Gi.createHash("sha256").update(e.join(`
479
+ `)).digest("hex")}function fN(t){let e=Qu(t.packDir),n={pack:t.pack,packVersion:t.packVersion,digest:e,iat:t.nowSeconds??Math.floor(Date.now()/1e3)},r=(0,Io.signCompactJws)({typ:"JWT",kid:t.kid},n,t.privateKeyPem);return ks.writeFileSync(_c.join(t.packDir,H.PACK_SIGNATURE_FILE),`${r}
480
+ `),{signature:r,digest:e}}function Om(t){try{return ks.readFileSync(_c.join(t,H.PACK_SIGNATURE_FILE),"utf8").trim()||void 0}catch{return}}function Im(t,e,n){return Pm(t,e,n.pack,n.packVersion,()=>Qu(n.packDir))}function pN(t,e,n,r,s){return Pm(t,e,n,r,()=>vm(s))}function Pm(t,e,n,r,s){if(Object.keys(e).length===0)return{ok:!1,kind:"no-trust-root",reason:"no trusted pack-signing keys are configured on this instance"};let i=(0,Io.verifyCompactJws)(t,e);if(!i.ok)return i.reason==="unknown kid"?{ok:!1,kind:"unknown-key",reason:`unknown signing key ${gN(t)??"(none named)"}`}:i.reason==="bad signature"?{ok:!1,kind:"bad-signature",reason:"signature does not verify"}:i.reason==="malformed"?{ok:!1,kind:"malformed",reason:"malformed signature"}:i.reason==="unparseable"?{ok:!1,kind:"malformed",reason:"unreadable signature"}:{ok:!1,kind:"malformed",reason:i.reason};let o=i.payload;return o.pack!==n?{ok:!1,kind:"identity-mismatch",reason:`signature is for pack ${o.pack}, not ${n}`}:o.packVersion!==r?{ok:!1,kind:"identity-mismatch",reason:`signature is for ${o.pack}@${o.packVersion}, not @${r}`}:typeof o.digest!="string"||!o.digest?{ok:!1,kind:"malformed",reason:"signature carries no digest"}:(0,Io.timingSafeEqualString)(s(),o.digest)?{ok:!0,claims:o}:{ok:!1,kind:"digest-mismatch",reason:"pack contents changed after signing"}}function gN(t){try{return JSON.parse(Buffer.from(t.split(".")[0],"base64url").toString("utf8")).kid}catch{return}}function Nm(t,e){return!!t||!!e}H.ALLOW_UNSIGNED_PACK_ENV="AGENTHIPPO_ALLOW_UNSIGNED_PACK";function hN(t){return Nm(t.lease,t.localRequire)?!0:!t.localAllowUnsigned}function mN(t=process.env){let e=t[H.ALLOW_UNSIGNED_PACK_ENV]?.trim().toLowerCase();return e==="1"||e==="true"||e==="yes"}function EN(t){let n=[`refusing to run ${t.packVersion?`${t.pack}@${t.packVersion}`:t.pack}: ${t.detail}`];switch(t.kind){case"unsigned":n.push(` The pack directory has no ${H.PACK_SIGNATURE_FILE}${t.packDir?` at ${t.packDir}`:""}.`,` Sign it: agenthippo pack sign ${t.pack} --key <private-key.pem> --kid <key-id>`," (generate a key with: agenthippo pack keygen -o key.pem, then publish its public half to JWKS)");break;case"no-trust-root":n.push(" This is NOT a problem with the pack \u2014 this instance has no keys to check it against."," Configure ONE of:",' AGENTHIPPO_PACK_SIGNING_KEYS inline JSON {"<kid>":"<public PEM>"} (air-gapped installs)',` ${H.PACK_JWKS_URL_ENV} https URL of the JWKS document publishing your signing keys`,` ${H.PACK_JWKS_PINS_ENV} optional, comma-separated sha256 thumbprints to pin those keys to`);break;case"trust-root-unavailable":n.push(" A trust root IS configured but could not be loaded, so no signature can be checked.",` ${t.trustRootHint??""}`.trimEnd(),' This is deliberately an error and not an empty keyring: "cannot reach the trust root" and',' "no trust root configured" have different causes and different fixes.');break;case"unknown-key":n.push(" The pack IS signed, but by a key this fleet does not trust."," Either publish that key to your JWKS / AGENTHIPPO_PACK_SIGNING_KEYS, or re-sign the pack"," with a key that is already trusted. A key is never trusted just because it arrived with the pack.");break;case"digest-mismatch":n.push(" The signature is valid but the pack tree no longer matches it \u2014 something changed after signing."," Note that .claude/, .codex/ and .agent-hippo/ are now INSIDE the digest (they carry hooks and"," other executable content), so edits there invalidate a signature that used to survive them.",` Re-sign after reviewing the diff: agenthippo pack sign ${t.pack} --key <private-key.pem> --kid <key-id>`);break;case"identity-mismatch":n.push(" The signature is valid but names a different pack or version \u2014 a replayed signature, not this artifact.");break;case"malformed":case"bad-signature":n.push(` ${H.PACK_SIGNATURE_FILE} is present but unusable. Re-sign the pack; do not hand-edit it.`);break;case"no-pack":break}return n.push(` To run unsigned packs anyway (LOCAL DEVELOPMENT ONLY), set ${H.ALLOW_UNSIGNED_PACK_ENV}=1.`," A lease that sets requireSignedPack overrides that escape hatch \u2014 the control plane's demand cannot be waived locally."),n.join(`
481
+ `)}H.PACK_JWKS_URL_ENV="AGENTHIPPO_PACK_JWKS_URL";H.PACK_JWKS_URL_ENV_LEGACY="AGENTHIPPO_PACK_SIGNING_JWKS_URL";H.PACK_JWKS_PINS_ENV="AGENTHIPPO_PACK_JWKS_PINS";H.ALLOW_INSECURE_TRUST_ROOT_ENV="AGENTHIPPO_ALLOW_INSECURE_TRUST_ROOT";H.LEASE_SIGNING_KEYS_ENV="AGENTHIPPO_LEASE_SIGNING_KEYS";H.LEASE_JWKS_URL_ENV="AGENTHIPPO_LEASE_JWKS_URL";H.LEASE_JWKS_PINS_ENV="AGENTHIPPO_LEASE_JWKS_PINS";function Rm(t){let e=Gi.createPublicKey(t),n=e.export({format:"jwk"}),r=n.kty==="EC"?{crv:n.crv,kty:n.kty,x:n.x,y:n.y}:n.kty==="RSA"?{e:n.e,kty:n.kty,n:n.n}:{kty:n.kty};return{jwk:Gi.createHash("sha256").update(JSON.stringify(r)).digest("base64url"),spki:Gi.createHash("sha256").update(e.export({type:"spki",format:"der"})).digest("hex")}}var _N=t=>t.trim().replace(/^sha256:/i,"").toLowerCase();function Cm(t){return(t??"").split(",").map(_N).filter(e=>e.length>0)}function km(t,e,n=process.env){let r;try{r=new URL(t)}catch{return{ok:!1,reason:`${e} is not a valid URL: ${t}`}}if(r.protocol==="https:")return{ok:!0,warnings:[]};let s=(n[H.ALLOW_INSECURE_TRUST_ROOT_ENV]??"").trim().toLowerCase();return s==="1"||s==="true"||s==="yes"?{ok:!0,warnings:[`INSECURE: ${e} is ${r.protocol}//${r.host} (not https) and ${H.ALLOW_INSECURE_TRUST_ROOT_ENV} is set. Anyone on the path between this instance and that host can choose which packs it will run and whether the kill switch is honoured. This must never be set outside local development.`]}:{ok:!1,reason:`${e} must be https (got ${r.protocol}//${r.host}). Set ${H.ALLOW_INSECURE_TRUST_ROOT_ENV}=1 to allow plaintext for LOCAL DEVELOPMENT ONLY.`}}var yN={label:"pack",purpose:"pack-signing",inlineEnv:"AGENTHIPPO_PACK_SIGNING_KEYS",urlEnvs:[H.PACK_JWKS_URL_ENV,H.PACK_JWKS_URL_ENV_LEGACY],pinsEnv:H.PACK_JWKS_PINS_ENV,derivedRisk:"chooses which packs this instance will run"},wN={label:"lease",purpose:"lease-signing",inlineEnv:H.LEASE_SIGNING_KEYS_ENV,urlEnvs:[H.LEASE_JWKS_URL_ENV],pinsEnv:H.LEASE_JWKS_PINS_ENV,derivedRisk:"chooses whether this instance's kill switch is ever honoured"};async function $m(t,e){let n=e.env??process.env,r=[],s=Cm(n[t.pinsEnv]),i=n[t.inlineEnv]?.trim(),o=t.urlEnvs.map(d=>n[d]).find(d=>d!==void 0&&d.trim()!=="")?.trim(),a=!!i||!!o,c=(d,p,g)=>{if(s.length===0)return Object.keys(d).length===0?{status:"unavailable",keys:{},source:p,url:g,warnings:r,explicitlyConfigured:a,reason:"the trust root published no usable ES256 keys"}:{status:"configured",keys:d,source:p,url:g,warnings:r,explicitlyConfigured:a};let m={};for(let[h,E]of Object.entries(d)){let _;try{_=Rm(E)}catch{r.push(`${t.label} trust root: key ${h} is unreadable and was dropped`);continue}s.some(b=>(0,Io.timingSafeEqualString)(b,_.jwk.toLowerCase())||(0,Io.timingSafeEqualString)(b,_.spki))?m[h]=E:r.push(`${t.label} trust root: key ${h} does not match any pin in ${t.pinsEnv} and was REFUSED (its thumbprints are jwk=${_.jwk} spki=${_.spki})`)}return Object.keys(m).length===0?{status:"unavailable",keys:{},source:p,url:g,warnings:r,explicitlyConfigured:a,reason:`every key offered by the trust root failed the ${t.pinsEnv} pin check`}:{status:"configured",keys:m,source:p,url:g,warnings:r,explicitlyConfigured:a}};if(i){let d;try{d=JSON.parse(i)}catch(p){return{status:"unavailable",keys:{},source:"inline",warnings:r,explicitlyConfigured:a,reason:`${t.inlineEnv} is set but is not valid JSON: ${p instanceof Error?p.message:String(p)}`}}return c(d,"inline")}let l=o,f=!1;if(!l&&e.leaseUrl){try{l=new URL(`/.well-known/jwks.json?purpose=${t.purpose}`,e.leaseUrl).toString()}catch{return{status:"unavailable",keys:{},warnings:r,explicitlyConfigured:a,reason:`AGENTHIPPO_LEASE_URL is not a valid URL: ${e.leaseUrl}`}}f=!0}if(!l)return{status:"unconfigured",keys:{},warnings:r,explicitlyConfigured:a};let u=km(l,`the ${t.purpose} JWKS URL`,n);if(!u.ok)return{status:"unavailable",keys:{},source:"jwks",url:l,warnings:r,reason:u.reason,derivedFromLease:f,explicitlyConfigured:a};r.push(...u.warnings),f&&s.length===0&&r.push(`${t.label} trust root is derived from AGENTHIPPO_LEASE_URL (${l}) and is not pinned. Whoever can answer that origin ${t.derivedRisk}. Pin it with ${t.urlEnvs[0]} and ${t.pinsEnv}.`);try{let d=await(e.fetchImpl??fetch)(l);if(!d.ok)return{status:"unavailable",keys:{},source:"jwks",url:l,warnings:r,reason:`JWKS fetch returned HTTP ${d.status}`,derivedFromLease:f,explicitlyConfigured:a};let p=await d.json(),g=TN(p);return g.ok?{...c(g.pems,"jwks",l),derivedFromLease:f}:{status:"unavailable",keys:{},source:"jwks",url:l,warnings:r,reason:g.reason,derivedFromLease:f,explicitlyConfigured:a}}catch(d){return{status:"unavailable",keys:{},source:"jwks",url:l,warnings:r,derivedFromLease:f,explicitlyConfigured:a,reason:`JWKS fetch failed: ${d instanceof Error?d.message:String(d)}`}}}async function Dm(t){return $m(yN,t)}async function AN(t){return $m(wN,t)}function SN(t,e){return t.explicitlyConfigured?{keys:t.keys,packFallback:!1}:{keys:{...e.keys,...t.keys},packFallback:!0}}function TN(t){if(t.pemsByKid&&typeof t.pemsByKid=="object")return{ok:!0,pems:t.pemsByKid};if(!Array.isArray(t.keys))return{ok:!1,reason:"JWKS document has neither `pemsByKid` nor a `keys` array"};let e={};for(let n of t.keys)if(!(!n||typeof n!="object")&&!(n.kty!=="EC"||n.crv!=="P-256")&&!(n.alg!==void 0&&n.alg!=="ES256")&&!(typeof n.kid!="string"||!n.kid))try{e[n.kid]=Gi.createPublicKey({key:n,format:"jwk"}).export({type:"spki",format:"pem"}).toString()}catch{}return Object.keys(e).length===0?{ok:!1,reason:"JWKS document published no usable ES256 (P-256) keys"}:{ok:!0,pems:e}}async function bN(t){return(await Dm(t)).keys}H.PACK_PROBE_INTERVAL_MS=1e3;H.PACK_FULL_REVERIFY_INTERVAL_MS=3e4;function vN(t={}){let e=t.probeIntervalMs??H.PACK_PROBE_INTERVAL_MS,n=t.fullReverifyIntervalMs??H.PACK_FULL_REVERIFY_INTERVAL_MS,r,s="",i="",o=0,a=0,c=0,l=u=>`${u.packDir}\0${u.pack}\0${u.packVersion}\0${Object.keys(u.keys).sort().join(",")}`,f=(u,d)=>{c+=1,s=l(u),i=Ju(u.packDir),o=d,a=d;let p=Om(u.packDir);return r=p?Im(p,u.keys,{packDir:u.packDir,pack:u.pack,packVersion:u.packVersion}):{ok:!1,kind:"unsigned",reason:`${u.pack} is not signed (no ${H.PACK_SIGNATURE_FILE} at the pack root)`},r};return{fullVerifications:()=>c,refresh(u,d=Date.now()){return f(u,d)},verify(u,d=Date.now()){return!r||s!==l(u)||d-a>=n?f(u,d):d-o<e||(o=d,Ju(u.packDir)===i)?r:f(u,d)}}}});var td=S(rn=>{"use strict";var ON=rn&&rn.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,s)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),IN=rn&&rn.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),Lm=rn&&rn.__importStar||(function(){var t=function(e){return t=Object.getOwnPropertyNames||function(n){var r=[];for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(r[r.length]=s);return r},t(e)};return function(e){if(e&&e.__esModule)return e;var n={};if(e!=null)for(var r=t(e),s=0;s<r.length;s++)r[s]!=="default"&&ON(n,e,r[s]);return IN(n,e),n}})();Object.defineProperty(rn,"__esModule",{value:!0});rn.CURRENT_LINK=void 0;rn.safeJoin=Mm;rn.promoteCurrent=ed;rn.reconcilePinnedPack=PN;rn.readDirAsFiles=Gm;var $t=Lm(require("node:fs")),ps=Lm(require("node:path")),Zu=Po();rn.CURRENT_LINK="current";function Mm(t,e){if(ps.isAbsolute(e))return;let n=ps.resolve(t,e),r=t.endsWith(ps.sep)?t:t+ps.sep;return n.startsWith(r)?n:void 0}function ed(t,e){let n=ps.join(t,rn.CURRENT_LINK),r=`${n}.swap-${process.pid}-${Date.now()}`;return $t.symlinkSync(e,r),$t.renameSync(r,n),n}async function PN(t){let{pack:e,pinnedVersion:n,packsRoot:r,logger:s}=t,i=ps.join(r,n);if($t.mkdirSync(r,{recursive:!0}),$t.existsSync(i)){let c=NN(i,e,n,t.publicKeysByKid);if(c.ok)return ed(r,i),{ok:!0,packDir:i,version:n,alreadyPresent:!0};s?.warn(`[Pack] cached ${e}@${n} failed verification (${c.reason}); re-fetching`),$t.rmSync(i,{recursive:!0,force:!0})}let o;try{o=await t.download(e,n)}catch(c){return{ok:!1,reason:`fetch failed: ${c instanceof Error?c.message:String(c)}`}}if(o.length===0)return{ok:!1,reason:`store returned no files for ${e}@${n}`};let a=ps.join(r,`.staging-${n}-${process.pid}-${Date.now()}`);try{$t.mkdirSync(a,{recursive:!0});for(let l of o){let f=Mm(a,l.path);if(!f)return $t.rmSync(a,{recursive:!0,force:!0}),{ok:!1,reason:`refusing artifact: entry escapes the pack root (${l.path})`};if(l.link)return $t.rmSync(a,{recursive:!0,force:!0}),{ok:!1,reason:`refusing artifact: symlink entries are not accepted from the store (${l.path})`};$t.mkdirSync(ps.dirname(f),{recursive:!0}),$t.writeFileSync(f,l.content)}let c=Um(o,e,n,t.publicKeysByKid);return c.ok?($t.renameSync(a,i),ed(r,i),s?.info(`[Pack] converged to ${e}@${n} (signature verified)`),{ok:!0,packDir:i,version:n,alreadyPresent:!1}):($t.rmSync(a,{recursive:!0,force:!0}),{ok:!1,reason:c.reason})}catch(c){return $t.rmSync(a,{recursive:!0,force:!0}),{ok:!1,reason:`staging failed: ${c instanceof Error?c.message:String(c)}`}}}function Gm(t){let e=[],n=(r,s)=>{for(let i of $t.readdirSync(r)){let o=s?`${s}/${i}`:i;if(Zu.DIGEST_EXCLUDED_SEGMENTS.has(i))continue;let a=ps.join(r,i),c=$t.lstatSync(a);c.isSymbolicLink()?e.push({path:o,content:Buffer.from($t.readlinkSync(a)),link:!0}):c.isDirectory()?n(a,o):c.isFile()&&e.push({path:o,content:$t.readFileSync(a)})}};return n(t,""),e}function Um(t,e,n,r){if(Object.keys(r).length===0)return{ok:!1,reason:"no trusted signing keys configured"};let s=t.find(a=>a.path.replace(/\\/g,"/")===Zu.PACK_SIGNATURE_FILE);if(!s)return{ok:!1,reason:`${e}@${n} is not signed`};let i=s.content.toString("utf8").trim(),o=(0,Zu.verifyPackFromFiles)(i,r,e,n,t);return o.ok?{ok:!0}:{ok:!1,reason:o.reason}}function NN(t,e,n,r){return Um(Gm(t),e,n,r)}});var wc=S(_e=>{"use strict";Object.defineProperty(_e,"__esModule",{value:!0});_e.STORE_ICONS=_e.STORE_PATHS=_e.DEFAULT_STORE_BRANCH=_e.DEFAULT_STORE_REPO=_e.DEFAULT_STORE_OWNER=void 0;_e.parseGitHubUrl=Hm;_e.parseStoreUrl=RN;_e.formatStoreUrl=CN;_e.isStoreUrl=kN;_e.getStorePath=jm;_e.getStoreIndexUrl=$N;_e.getTagsApiUrl=DN;_e.isForkOfStoreRepo=LN;_e.formatStorePullRequestError=MN;_e.DEFAULT_STORE_OWNER="agenthippoai";_e.DEFAULT_STORE_REPO="agenthippo-store";_e.DEFAULT_STORE_BRANCH="main";_e.STORE_PATHS={packs:"agent-packs",skills:"skills",mcp:"mcp",engines:"engines",spotlightViews:"spotlight"};_e.STORE_ICONS={local:"\u{1F4BE}",remote:"\u2601\uFE0F",installed:"\u2713",pack:"\u{1F4E6}",skill:"\u{1F3AF}",mcp:"\u{1F50C}",engine:"\u2699\uFE0F",view:"\u{1F4CA}"};function Hm(t,e=_e.DEFAULT_STORE_OWNER,n=_e.DEFAULT_STORE_REPO){let r=t.trim(),s=r.match(/github\.com\/([^/]+)\/([^/]+)(?:\/tree\/([^/]+)(?:\/(.+))?)?/);if(s){let[,o,a,c,l]=s,f=o===e&&a===n;return{owner:o,repo:a.replace(/\.git$/,""),ref:c,path:l,isStore:f}}let i=r.match(/^([^/]+)\/([^/@]+)(?:@(.+))?$/);if(i){let[,o,a,c]=i;return{owner:o,repo:a,ref:c,isStore:o===e&&a===n}}throw new Error(`Invalid GitHub URL: ${t}`)}function RN(t){let e=t.trim(),n=e.match(/github\.com\/[^/]+\/[^/]+\/tree\/[^/]+\/(.+)/);n&&(e=n[1]),e=e.replace(/^store:\/\//,"");let r;if(e.includes("@")){let[c,l]=e.split("@");e=c,r=l.replace(/^v/,"")}e=e.replace(/\/$/,"");let s=e.split("/");if(s.length<2)throw new Error(`Invalid store URL: ${t}. Expected format: type/slug[@version]`);let i=s[0],o=s.slice(1).join("/"),a;if(i==="agent-packs"||i==="packs"||i==="pack")a="pack";else if(i==="skills"||i==="skill")a="skill";else if(i==="mcp")a="mcp";else if(i==="engines"||i==="engine")a="engine";else if(i==="spotlight"||i==="spotlight-views"||i==="views"||i==="view")a="view";else throw new Error(`Invalid artifact type: ${i}. Expected: pack, skill, mcp, engine, or view`);return{type:a,slug:o,version:r}}function CN(t){let n=`store://${jm(t.type)}/${t.slug}`;return t.version&&(n+=`@v${t.version}`),n}function kN(t,e=_e.DEFAULT_STORE_OWNER,n=_e.DEFAULT_STORE_REPO){let r=t.trim().replace(/^store:\/\//,"");if(/^(agent-packs|packs|pack|skills|skill|mcp|engines|engine|spotlight|spotlight-views|views|view)\//.test(r))return!0;try{let s=Hm(t,e,n);if(s.isStore&&s.path)return/^(agent-packs|skills|mcp|engines|spotlight|spotlight-views)\//.test(s.path)}catch{}return!1}function jm(t){switch(t){case"pack":return _e.STORE_PATHS.packs;case"skill":return _e.STORE_PATHS.skills;case"mcp":return _e.STORE_PATHS.mcp;case"engine":return _e.STORE_PATHS.engines;case"view":return _e.STORE_PATHS.spotlightViews}}function $N(t=_e.DEFAULT_STORE_OWNER,e=_e.DEFAULT_STORE_REPO){return`https://${t}.github.io/${e}/store-index.json`}function DN(t=_e.DEFAULT_STORE_OWNER,e=_e.DEFAULT_STORE_REPO){return`https://api.github.com/repos/${t}/${e}/git/refs/tags`}function LN(t,e,n){if(!t.fork)return!1;let r=`${e}/${n}`.toLowerCase();return(t.parentFullName??"").toLowerCase()===r}function MN(t,e,n,r){try{let s=JSON.parse(t),i=[s.message,...s.errors?.map(o=>o.message)??[]].filter(Boolean).join(" ");if(i.includes("no history in common")){let o=r?`https://github.com/${r}/${n}`:`your fork of ${e}/${n}`;return`Cannot open pull request: your fork has no shared git history with ${e}/${n}.
482
482
 
483
483
  Open ${o} on GitHub, use "Sync fork" \u2192 "Update branch", then publish again.
484
- If sync is unavailable, delete or rename the fork so AgentIDE can create a fresh fork of the store.`}return i?`Failed to create PR: ${i}`:`Failed to create PR: ${t}`}catch{return`Failed to create PR: ${t}`}}});var sd=S(wr=>{"use strict";var $N=wr&&wr.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,s)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),DN=wr&&wr.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),rd=wr&&wr.__importStar||(function(){var t=function(e){return t=Object.getOwnPropertyNames||function(n){var r=[];for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(r[r.length]=s);return r},t(e)};return function(e){if(e&&e.__esModule)return e;var n={};if(e!=null)for(var r=t(e),s=0;s<r.length;s++)r[s]!=="default"&&$N(n,e,r[s]);return DN(n,e),n}})();Object.defineProperty(wr,"__esModule",{value:!0});wr.LocalRegistry=void 0;wr.getRegistry=MN;var Io=rd(require("fs")),jm=rd(require("path")),LN=rd(require("os"));function xm(){return{packs:{},skills:{},mcp:{}}}var yc=class{data=null;registryPath;constructor(e,n){this.registryPath=e||jm.join(LN.homedir(),".agentide","registry.json")}ensureDir(){let e=jm.dirname(this.registryPath);Io.existsSync(e)||Io.mkdirSync(e,{recursive:!0})}load(){if(this.data)return this.data;if(Io.existsSync(this.registryPath))try{let e=Io.readFileSync(this.registryPath,"utf-8");this.data=JSON.parse(e)}catch{this.data=xm()}else this.data=xm();return this.data}save(){this.data&&(this.ensureDir(),Io.writeFileSync(this.registryPath,JSON.stringify(this.data,null,2)))}async registerPack(e){let n=this.load();n.packs[e.slug]={slug:e.slug,displayName:e.displayName,description:e.description,githubOwner:e.github?.owner,githubRepo:e.github?.repo,latestVersion:e.latestVersion,tags:e.tags,installs:e.stats.installs,stars:e.stats.stars,updatedAt:Date.now()},this.save()}async getPack(e){return this.load().packs[e]||null}async listPacks(){let e=this.load();return Object.values(e.packs).sort((n,r)=>r.installs-n.installs)}async trackPackInstall(e){let r=this.load().packs[e];r&&(r.installs+=1,r.updatedAt=Date.now(),this.save())}async registerSkill(e){let n=this.load(),s=n.skills[e.slug]?.installedTo||[];e.agentPackId&&!s.includes(e.agentPackId)&&(s=[...s,e.agentPackId]),n.skills[e.slug]={slug:e.slug,displayName:e.displayName,description:e.description,githubOwner:e.github?.owner,githubRepo:e.github?.repo,githubPath:e.github?.path,latestVersion:e.latestVersion,tags:e.tags,installs:e.stats.installs,updatedAt:Date.now(),installedTo:s},this.save()}async getSkill(e){return this.load().skills[e]||null}async listSkills(){let e=this.load();return Object.values(e.skills).sort((n,r)=>r.installs-n.installs)}async registerMcp(e){let n=this.load(),s=n.mcp[e.slug]?.installedTo||[];e.agentPackId&&!s.includes(e.agentPackId)&&(s=[...s,e.agentPackId]),n.mcp[e.slug]={slug:e.slug,displayName:e.displayName,description:e.description,transport:e.transport,githubOwner:e.github?.owner,githubRepo:e.github?.repo,npmPackage:e.npmPackage,latestVersion:e.latestVersion,tags:e.tags,installs:e.stats.installs,updatedAt:Date.now(),installedTo:s},this.save()}async getMcp(e){return this.load().mcp[e]||null}async listMcp(){let e=this.load();return Object.values(e.mcp).sort((n,r)=>r.installs-n.installs)}async isSkillInstalledTo(e,n){return(await this.getSkill(e))?.installedTo?.includes(n)??!1}async isMcpInstalledTo(e,n){return(await this.getMcp(e))?.installedTo?.includes(n)??!1}async unregisterSkillFromPack(e,n){let s=this.load().skills[e];s&&s.installedTo&&(s.installedTo=s.installedTo.filter(i=>i!==n),s.updatedAt=Date.now(),this.save())}async unregisterMcpFromPack(e,n){let s=this.load().mcp[e];s&&s.installedTo&&(s.installedTo=s.installedTo.filter(i=>i!==n),s.updatedAt=Date.now(),this.save())}async search(e,n){let r=n?.types||["pack","skill","mcp"],s=n?.limit||20,i=[],a=e.toLowerCase().split(/\s+/).filter(l=>l.length>0),c=(l,f)=>{let u=`${l.slug} ${l.displayName} ${l.description||""} ${l.tags.join(" ")}`.toLowerCase(),d=0;for(let p of a)u.includes(p)&&(d+=10);return d===0?0:d+f/100};if(r.includes("pack")){let l=await this.listPacks();for(let f of l){let u=c(f,f.installs);u>0&&i.push({type:"pack",slug:f.slug,displayName:f.displayName,description:f.description,score:u,data:f})}}if(r.includes("skill")){let l=await this.listSkills();for(let f of l){let u=c(f,f.installs);u>0&&i.push({type:"skill",slug:f.slug,displayName:f.displayName,description:f.description,score:u,data:f})}}if(r.includes("mcp")){let l=await this.listMcp();for(let f of l){let u=c(f,f.installs);u>0&&i.push({type:"mcp",slug:f.slug,displayName:f.displayName,description:f.description,score:u,data:f})}}return i.sort((l,f)=>f.score-l.score).slice(0,s)}};wr.LocalRegistry=yc;var nd=null;function MN(t){return nd||(nd=new yc(void 0,t)),nd}});var id=S((exports,module)=>{"use strict";Object.defineProperty(exports,"__esModule",{value:!0});exports.formatStoreUrl=exports.parseStoreUrl=exports.STORE_CONFIG=exports.getRegistry=exports.formatStorePullRequestError=exports.isForkOfStoreRepo=exports.getTagsApiUrl=exports.getStoreIndexUrl=exports.getStorePath=exports.DEFAULT_STORE_BRANCH=exports.DEFAULT_STORE_REPO=exports.DEFAULT_STORE_OWNER=exports.STORE_PATHS=exports.STORE_ICONS=void 0;exports.listStoreVersions=listStoreVersions;exports.getLatestStoreVersion=getLatestStoreVersion;exports.downloadFromStore=downloadFromStore;exports.downloadFromExternalGitHub=downloadFromExternalGitHub;exports.canPublishDirectlyToStore=canPublishDirectlyToStore;exports.publishToStore=publishToStore;exports.parseGitHubUrl=parseGitHubUrl;exports.detectArtifactType=detectArtifactType;exports.isStoreUrl=isStoreUrl;exports.listStoreIndex=listStoreIndex;var utils_1=en(),branding_1=Ke(),github_1=fo(),shared_1=_c(),shared_2=_c();Object.defineProperty(exports,"STORE_ICONS",{enumerable:!0,get:function(){return shared_2.STORE_ICONS}});Object.defineProperty(exports,"STORE_PATHS",{enumerable:!0,get:function(){return shared_2.STORE_PATHS}});Object.defineProperty(exports,"DEFAULT_STORE_OWNER",{enumerable:!0,get:function(){return shared_2.DEFAULT_STORE_OWNER}});Object.defineProperty(exports,"DEFAULT_STORE_REPO",{enumerable:!0,get:function(){return shared_2.DEFAULT_STORE_REPO}});Object.defineProperty(exports,"DEFAULT_STORE_BRANCH",{enumerable:!0,get:function(){return shared_2.DEFAULT_STORE_BRANCH}});Object.defineProperty(exports,"getStorePath",{enumerable:!0,get:function(){return shared_2.getStorePath}});Object.defineProperty(exports,"getStoreIndexUrl",{enumerable:!0,get:function(){return shared_2.getStoreIndexUrl}});Object.defineProperty(exports,"getTagsApiUrl",{enumerable:!0,get:function(){return shared_2.getTagsApiUrl}});Object.defineProperty(exports,"isForkOfStoreRepo",{enumerable:!0,get:function(){return shared_2.isForkOfStoreRepo}});Object.defineProperty(exports,"formatStorePullRequestError",{enumerable:!0,get:function(){return shared_2.formatStorePullRequestError}});var index_1=sd();Object.defineProperty(exports,"getRegistry",{enumerable:!0,get:function(){return index_1.getRegistry}});function getStoreRepo(){let repoEnv=process.env.AGENTHIPPO_STORE_REPO?.trim();if(repoEnv){let t=repoEnv.match(/^(?:https?:\/\/github\.com\/)?([^/]+)\/([^/]+?)(?:\.git)?$/);if(t)return{owner:t[1],repo:t[2]};let e=repoEnv.split("/").filter(Boolean);if(e.length===2)return{owner:e[0],repo:e[1]}}try{let vscode=eval("require")("vscode"),config=vscode.workspace.getConfiguration("agentide"),storeUrl=config.get("storeRepo");if(storeUrl){let t=storeUrl.match(/^(?:https?:\/\/github\.com\/)?([^/]+)\/([^/]+?)(?:\.git)?$/);if(t)return{owner:t[1],repo:t[2]}}}catch{}return{owner:shared_1.DEFAULT_STORE_OWNER,repo:shared_1.DEFAULT_STORE_REPO}}exports.STORE_CONFIG={get owner(){return getStoreRepo().owner},get repo(){return getStoreRepo().repo},defaultBranch:shared_1.DEFAULT_STORE_BRANCH,paths:shared_1.STORE_PATHS};async function listStoreVersions(t,e){let n=`${(0,shared_1.getStorePath)(t)}/${e}/v`,r=`https://api.github.com/repos/${exports.STORE_CONFIG.owner}/${exports.STORE_CONFIG.repo}/git/refs/tags`,s=await fetch(r,{headers:{Accept:"application/vnd.github.v3+json","User-Agent":"AgentIDE"}});if(!s.ok&&(s.status===401||s.status===403||s.status===429)){let a=await(0,github_1.getGitHubToken)();s=await fetch(r,{headers:{Authorization:`Bearer ${a}`,Accept:"application/vnd.github.v3+json","User-Agent":"AgentIDE"}})}if(!s.ok){if(s.status===404)return[];throw new Error(`Failed to list tags: ${s.statusText}`)}let i=await s.json(),o=[];for(let{ref:a}of i){let c=a.replace("refs/tags/","");if(c.startsWith(n)){let l=c.slice(n.length-1);o.push({version:l.replace(/^v/,""),tagName:c,isPrerelease:/-(alpha|beta|rc|pre)/.test(l)})}}return o.sort((a,c)=>c.version.localeCompare(a.version,void 0,{numeric:!0}))}async function getLatestStoreVersion(t,e,n=!1){let r=await listStoreVersions(t,e);return n?r[0]||null:r.find(s=>!s.isPrerelease)||null}var zlib_1=require("zlib");function parseTar(t){let e=new Map,n=0,r,s=i=>i.toString("utf-8").replace(/\0/g,"").trim();for(;n<t.length-512;){let i=t.subarray(n,n+512);if(i.every(g=>g===0))break;let o=s(i.subarray(0,100)),a=s(i.subarray(345,500)),c=s(i.subarray(124,136)),l=i[156],f=parseInt(c,8)||0,u=t.subarray(n+512,n+512+f),d=512+Math.ceil(f/512)*512;if(l===120||l===103){let g=u.toString("utf-8").match(/\d+ path=([^\n]+)\n/);g&&(r=g[1]),n+=d;continue}if(l===76){r=s(u),n+=d;continue}let p=r??(a?`${a}/${o}`:o);r=void 0,p&&(l===0||l===48)&&e.set(p,Buffer.from(u)),n+=d}return e}async function downloadFromStore(t,e){let{type:n,slug:r,version:s,includePrerelease:i}=t,o=(0,shared_1.getStorePath)(n),a;if(s==="main"||s==="latest")a=exports.STORE_CONFIG.defaultBranch,e&&(0,utils_1.logInfo)(e,`[Store] Using ${a} branch (latest)`);else if(s)a=`${o}/${r}/v${s.replace(/^v/,"")}`;else{let h=await getLatestStoreVersion(n,r,i);h?(a=h.tagName,e&&(0,utils_1.logInfo)(e,`[Store] Using latest version: ${h.version}`)):(a=exports.STORE_CONFIG.defaultBranch,e&&(0,utils_1.logInfo)(e,`[Store] No version tags found, using ${a} branch`))}e&&(0,utils_1.logInfo)(e,`[Store] Downloading ${n}/${r} at ${a}`);let c=encodeURIComponent(a),l=`https://api.github.com/repos/${exports.STORE_CONFIG.owner}/${exports.STORE_CONFIG.repo}/tarball/${c}`,f=await fetch(l,{headers:{"User-Agent":"AgentIDE",Accept:"application/vnd.github.v3+json"},redirect:"follow"});if(!f.ok){if(f.status===401||f.status===403||f.status===404||f.status===429){e&&(0,utils_1.logInfo)(e,"[Store] Requires authentication, signing in...");let h=await(0,github_1.getGitHubToken)();f=await fetch(l,{headers:{"User-Agent":"AgentIDE",Accept:"application/vnd.github.v3+json",Authorization:`Bearer ${h}`},redirect:"follow"})}if(!f.ok)throw new Error(`Version ${s||"latest"} not found for ${n} "${r}"`)}let u=Buffer.from(await f.arrayBuffer()),d=(0,zlib_1.gunzipSync)(u),p=parseTar(d),g=`${o}/${r}/`,m=[];for(let[h,E]of p){let _=h.indexOf("/");if(_===-1)continue;let y=h.slice(_+1);if(y.startsWith(g)){let b=y.slice(g.length);b&&(m.push({path:b,content:E}),e&&(0,utils_1.logInfo)(e,`[Store] \u2193 ${b}`))}}return m}async function downloadFromExternalGitHub(t,e){let{owner:n,repo:r,ref:s="main",path:i}=t;e&&(0,utils_1.logInfo)(e,`[GitHub] Downloading ${n}/${r}${i?`/${i}`:""} at ${s}`);let o=encodeURIComponent(s),a=`https://api.github.com/repos/${n}/${r}/tarball/${o}`,c=await fetch(a,{headers:{"User-Agent":"AgentIDE",Accept:"application/vnd.github.v3+json"},redirect:"follow"});if(!c.ok){if(c.status===401||c.status===403||c.status===404||c.status===429){e&&(0,utils_1.logInfo)(e,"[GitHub] Requires authentication, signing in...");let m=await(0,github_1.getGitHubToken)();c=await fetch(a,{headers:{"User-Agent":"AgentIDE",Accept:"application/vnd.github.v3+json",Authorization:`Bearer ${m}`},redirect:"follow"})}if(!c.ok)throw new Error(`Failed to download from ${n}/${r}@${s}: ${c.statusText}`)}let l=Buffer.from(await c.arrayBuffer()),f=(0,zlib_1.gunzipSync)(l),u=parseTar(f),d="";for(let m of u.keys())if(m.includes("/")){d=m.split("/")[0]+"/";break}let p=i?`${d}${i}/`:d,g=[];for(let[m,h]of u)if(m.startsWith(p)){let E=m.slice(p.length);E&&!E.endsWith("/")&&g.push({path:E,content:h.toString("utf-8")})}if(g.length===0)throw new Error(`No files found in ${n}/${r}${i?`/${i}`:""} at ${s}`);return e&&(0,utils_1.logInfo)(e,`[GitHub] Downloaded ${g.length} files`),g}async function getRepoForkMetadata(t,e){let n=await(0,github_1.getGitHubToken)(),r=await fetch(`https://api.github.com/repos/${t}/${e}`,{headers:{Authorization:`Bearer ${n}`,Accept:"application/vnd.github.v3+json","User-Agent":"AgentIDE"}});if(r.status===404)return null;if(!r.ok)throw new Error(`Failed to inspect repo ${t}/${e}: ${r.statusText}`);let s=await r.json();return{fork:s.fork===!0,parentFullName:s.parent?.full_name}}function assertStoreFork(t,e,n){if(!(0,shared_1.isForkOfStoreRepo)(n,exports.STORE_CONFIG.owner,exports.STORE_CONFIG.repo))throw new Error(`Your GitHub repo ${t}/${e} is not a fork of ${exports.STORE_CONFIG.owner}/${exports.STORE_CONFIG.repo}.
484
+ If sync is unavailable, delete or rename the fork so AgentIDE can create a fresh fork of the store.`}return i?`Failed to create PR: ${i}`:`Failed to create PR: ${t}`}catch{return`Failed to create PR: ${t}`}}});var sd=S(wr=>{"use strict";var GN=wr&&wr.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,s)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),UN=wr&&wr.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),rd=wr&&wr.__importStar||(function(){var t=function(e){return t=Object.getOwnPropertyNames||function(n){var r=[];for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(r[r.length]=s);return r},t(e)};return function(e){if(e&&e.__esModule)return e;var n={};if(e!=null)for(var r=t(e),s=0;s<r.length;s++)r[s]!=="default"&&GN(n,e,r[s]);return UN(n,e),n}})();Object.defineProperty(wr,"__esModule",{value:!0});wr.LocalRegistry=void 0;wr.getRegistry=jN;var No=rd(require("fs")),xm=rd(require("path")),HN=rd(require("os"));function Bm(){return{packs:{},skills:{},mcp:{}}}var Ac=class{data=null;registryPath;constructor(e,n){this.registryPath=e||xm.join(HN.homedir(),".agentide","registry.json")}ensureDir(){let e=xm.dirname(this.registryPath);No.existsSync(e)||No.mkdirSync(e,{recursive:!0})}load(){if(this.data)return this.data;if(No.existsSync(this.registryPath))try{let e=No.readFileSync(this.registryPath,"utf-8");this.data=JSON.parse(e)}catch{this.data=Bm()}else this.data=Bm();return this.data}save(){this.data&&(this.ensureDir(),No.writeFileSync(this.registryPath,JSON.stringify(this.data,null,2)))}async registerPack(e){let n=this.load();n.packs[e.slug]={slug:e.slug,displayName:e.displayName,description:e.description,githubOwner:e.github?.owner,githubRepo:e.github?.repo,latestVersion:e.latestVersion,tags:e.tags,installs:e.stats.installs,stars:e.stats.stars,updatedAt:Date.now()},this.save()}async getPack(e){return this.load().packs[e]||null}async listPacks(){let e=this.load();return Object.values(e.packs).sort((n,r)=>r.installs-n.installs)}async trackPackInstall(e){let r=this.load().packs[e];r&&(r.installs+=1,r.updatedAt=Date.now(),this.save())}async registerSkill(e){let n=this.load(),s=n.skills[e.slug]?.installedTo||[];e.agentPackId&&!s.includes(e.agentPackId)&&(s=[...s,e.agentPackId]),n.skills[e.slug]={slug:e.slug,displayName:e.displayName,description:e.description,githubOwner:e.github?.owner,githubRepo:e.github?.repo,githubPath:e.github?.path,latestVersion:e.latestVersion,tags:e.tags,installs:e.stats.installs,updatedAt:Date.now(),installedTo:s},this.save()}async getSkill(e){return this.load().skills[e]||null}async listSkills(){let e=this.load();return Object.values(e.skills).sort((n,r)=>r.installs-n.installs)}async registerMcp(e){let n=this.load(),s=n.mcp[e.slug]?.installedTo||[];e.agentPackId&&!s.includes(e.agentPackId)&&(s=[...s,e.agentPackId]),n.mcp[e.slug]={slug:e.slug,displayName:e.displayName,description:e.description,transport:e.transport,githubOwner:e.github?.owner,githubRepo:e.github?.repo,npmPackage:e.npmPackage,latestVersion:e.latestVersion,tags:e.tags,installs:e.stats.installs,updatedAt:Date.now(),installedTo:s},this.save()}async getMcp(e){return this.load().mcp[e]||null}async listMcp(){let e=this.load();return Object.values(e.mcp).sort((n,r)=>r.installs-n.installs)}async isSkillInstalledTo(e,n){return(await this.getSkill(e))?.installedTo?.includes(n)??!1}async isMcpInstalledTo(e,n){return(await this.getMcp(e))?.installedTo?.includes(n)??!1}async unregisterSkillFromPack(e,n){let s=this.load().skills[e];s&&s.installedTo&&(s.installedTo=s.installedTo.filter(i=>i!==n),s.updatedAt=Date.now(),this.save())}async unregisterMcpFromPack(e,n){let s=this.load().mcp[e];s&&s.installedTo&&(s.installedTo=s.installedTo.filter(i=>i!==n),s.updatedAt=Date.now(),this.save())}async search(e,n){let r=n?.types||["pack","skill","mcp"],s=n?.limit||20,i=[],a=e.toLowerCase().split(/\s+/).filter(l=>l.length>0),c=(l,f)=>{let u=`${l.slug} ${l.displayName} ${l.description||""} ${l.tags.join(" ")}`.toLowerCase(),d=0;for(let p of a)u.includes(p)&&(d+=10);return d===0?0:d+f/100};if(r.includes("pack")){let l=await this.listPacks();for(let f of l){let u=c(f,f.installs);u>0&&i.push({type:"pack",slug:f.slug,displayName:f.displayName,description:f.description,score:u,data:f})}}if(r.includes("skill")){let l=await this.listSkills();for(let f of l){let u=c(f,f.installs);u>0&&i.push({type:"skill",slug:f.slug,displayName:f.displayName,description:f.description,score:u,data:f})}}if(r.includes("mcp")){let l=await this.listMcp();for(let f of l){let u=c(f,f.installs);u>0&&i.push({type:"mcp",slug:f.slug,displayName:f.displayName,description:f.description,score:u,data:f})}}return i.sort((l,f)=>f.score-l.score).slice(0,s)}};wr.LocalRegistry=Ac;var nd=null;function jN(t){return nd||(nd=new Ac(void 0,t)),nd}});var id=S((exports,module)=>{"use strict";Object.defineProperty(exports,"__esModule",{value:!0});exports.formatStoreUrl=exports.parseStoreUrl=exports.STORE_CONFIG=exports.getRegistry=exports.formatStorePullRequestError=exports.isForkOfStoreRepo=exports.getTagsApiUrl=exports.getStoreIndexUrl=exports.getStorePath=exports.DEFAULT_STORE_BRANCH=exports.DEFAULT_STORE_REPO=exports.DEFAULT_STORE_OWNER=exports.STORE_PATHS=exports.STORE_ICONS=void 0;exports.listStoreVersions=listStoreVersions;exports.getLatestStoreVersion=getLatestStoreVersion;exports.downloadFromStore=downloadFromStore;exports.downloadFromExternalGitHub=downloadFromExternalGitHub;exports.canPublishDirectlyToStore=canPublishDirectlyToStore;exports.publishToStore=publishToStore;exports.parseGitHubUrl=parseGitHubUrl;exports.detectArtifactType=detectArtifactType;exports.isStoreUrl=isStoreUrl;exports.listStoreIndex=listStoreIndex;var utils_1=en(),branding_1=Ke(),github_1=go(),shared_1=wc(),shared_2=wc();Object.defineProperty(exports,"STORE_ICONS",{enumerable:!0,get:function(){return shared_2.STORE_ICONS}});Object.defineProperty(exports,"STORE_PATHS",{enumerable:!0,get:function(){return shared_2.STORE_PATHS}});Object.defineProperty(exports,"DEFAULT_STORE_OWNER",{enumerable:!0,get:function(){return shared_2.DEFAULT_STORE_OWNER}});Object.defineProperty(exports,"DEFAULT_STORE_REPO",{enumerable:!0,get:function(){return shared_2.DEFAULT_STORE_REPO}});Object.defineProperty(exports,"DEFAULT_STORE_BRANCH",{enumerable:!0,get:function(){return shared_2.DEFAULT_STORE_BRANCH}});Object.defineProperty(exports,"getStorePath",{enumerable:!0,get:function(){return shared_2.getStorePath}});Object.defineProperty(exports,"getStoreIndexUrl",{enumerable:!0,get:function(){return shared_2.getStoreIndexUrl}});Object.defineProperty(exports,"getTagsApiUrl",{enumerable:!0,get:function(){return shared_2.getTagsApiUrl}});Object.defineProperty(exports,"isForkOfStoreRepo",{enumerable:!0,get:function(){return shared_2.isForkOfStoreRepo}});Object.defineProperty(exports,"formatStorePullRequestError",{enumerable:!0,get:function(){return shared_2.formatStorePullRequestError}});var index_1=sd();Object.defineProperty(exports,"getRegistry",{enumerable:!0,get:function(){return index_1.getRegistry}});function getStoreRepo(){let repoEnv=process.env.AGENTHIPPO_STORE_REPO?.trim();if(repoEnv){let t=repoEnv.match(/^(?:https?:\/\/github\.com\/)?([^/]+)\/([^/]+?)(?:\.git)?$/);if(t)return{owner:t[1],repo:t[2]};let e=repoEnv.split("/").filter(Boolean);if(e.length===2)return{owner:e[0],repo:e[1]}}try{let vscode=eval("require")("vscode"),config=vscode.workspace.getConfiguration("agentide"),storeUrl=config.get("storeRepo");if(storeUrl){let t=storeUrl.match(/^(?:https?:\/\/github\.com\/)?([^/]+)\/([^/]+?)(?:\.git)?$/);if(t)return{owner:t[1],repo:t[2]}}}catch{}return{owner:shared_1.DEFAULT_STORE_OWNER,repo:shared_1.DEFAULT_STORE_REPO}}exports.STORE_CONFIG={get owner(){return getStoreRepo().owner},get repo(){return getStoreRepo().repo},defaultBranch:shared_1.DEFAULT_STORE_BRANCH,paths:shared_1.STORE_PATHS};async function listStoreVersions(t,e){let n=`${(0,shared_1.getStorePath)(t)}/${e}/v`,r=`https://api.github.com/repos/${exports.STORE_CONFIG.owner}/${exports.STORE_CONFIG.repo}/git/refs/tags`,s=await fetch(r,{headers:{Accept:"application/vnd.github.v3+json","User-Agent":"AgentIDE"}});if(!s.ok&&(s.status===401||s.status===403||s.status===429)){let a=await(0,github_1.getGitHubToken)();s=await fetch(r,{headers:{Authorization:`Bearer ${a}`,Accept:"application/vnd.github.v3+json","User-Agent":"AgentIDE"}})}if(!s.ok){if(s.status===404)return[];throw new Error(`Failed to list tags: ${s.statusText}`)}let i=await s.json(),o=[];for(let{ref:a}of i){let c=a.replace("refs/tags/","");if(c.startsWith(n)){let l=c.slice(n.length-1);o.push({version:l.replace(/^v/,""),tagName:c,isPrerelease:/-(alpha|beta|rc|pre)/.test(l)})}}return o.sort((a,c)=>c.version.localeCompare(a.version,void 0,{numeric:!0}))}async function getLatestStoreVersion(t,e,n=!1){let r=await listStoreVersions(t,e);return n?r[0]||null:r.find(s=>!s.isPrerelease)||null}var zlib_1=require("zlib");function parseTar(t){let e=new Map,n=0,r,s=i=>i.toString("utf-8").replace(/\0/g,"").trim();for(;n<t.length-512;){let i=t.subarray(n,n+512);if(i.every(g=>g===0))break;let o=s(i.subarray(0,100)),a=s(i.subarray(345,500)),c=s(i.subarray(124,136)),l=i[156],f=parseInt(c,8)||0,u=t.subarray(n+512,n+512+f),d=512+Math.ceil(f/512)*512;if(l===120||l===103){let g=u.toString("utf-8").match(/\d+ path=([^\n]+)\n/);g&&(r=g[1]),n+=d;continue}if(l===76){r=s(u),n+=d;continue}let p=r??(a?`${a}/${o}`:o);r=void 0,p&&(l===0||l===48)&&e.set(p,Buffer.from(u)),n+=d}return e}async function downloadFromStore(t,e){let{type:n,slug:r,version:s,includePrerelease:i}=t,o=(0,shared_1.getStorePath)(n),a;if(s==="main"||s==="latest")a=exports.STORE_CONFIG.defaultBranch,e&&(0,utils_1.logInfo)(e,`[Store] Using ${a} branch (latest)`);else if(s)a=`${o}/${r}/v${s.replace(/^v/,"")}`;else{let h=await getLatestStoreVersion(n,r,i);h?(a=h.tagName,e&&(0,utils_1.logInfo)(e,`[Store] Using latest version: ${h.version}`)):(a=exports.STORE_CONFIG.defaultBranch,e&&(0,utils_1.logInfo)(e,`[Store] No version tags found, using ${a} branch`))}e&&(0,utils_1.logInfo)(e,`[Store] Downloading ${n}/${r} at ${a}`);let c=encodeURIComponent(a),l=`https://api.github.com/repos/${exports.STORE_CONFIG.owner}/${exports.STORE_CONFIG.repo}/tarball/${c}`,f=await fetch(l,{headers:{"User-Agent":"AgentIDE",Accept:"application/vnd.github.v3+json"},redirect:"follow"});if(!f.ok){if(f.status===401||f.status===403||f.status===404||f.status===429){e&&(0,utils_1.logInfo)(e,"[Store] Requires authentication, signing in...");let h=await(0,github_1.getGitHubToken)();f=await fetch(l,{headers:{"User-Agent":"AgentIDE",Accept:"application/vnd.github.v3+json",Authorization:`Bearer ${h}`},redirect:"follow"})}if(!f.ok)throw new Error(`Version ${s||"latest"} not found for ${n} "${r}"`)}let u=Buffer.from(await f.arrayBuffer()),d=(0,zlib_1.gunzipSync)(u),p=parseTar(d),g=`${o}/${r}/`,m=[];for(let[h,E]of p){let _=h.indexOf("/");if(_===-1)continue;let y=h.slice(_+1);if(y.startsWith(g)){let b=y.slice(g.length);b&&(m.push({path:b,content:E}),e&&(0,utils_1.logInfo)(e,`[Store] \u2193 ${b}`))}}return m}async function downloadFromExternalGitHub(t,e){let{owner:n,repo:r,ref:s="main",path:i}=t;e&&(0,utils_1.logInfo)(e,`[GitHub] Downloading ${n}/${r}${i?`/${i}`:""} at ${s}`);let o=encodeURIComponent(s),a=`https://api.github.com/repos/${n}/${r}/tarball/${o}`,c=await fetch(a,{headers:{"User-Agent":"AgentIDE",Accept:"application/vnd.github.v3+json"},redirect:"follow"});if(!c.ok){if(c.status===401||c.status===403||c.status===404||c.status===429){e&&(0,utils_1.logInfo)(e,"[GitHub] Requires authentication, signing in...");let m=await(0,github_1.getGitHubToken)();c=await fetch(a,{headers:{"User-Agent":"AgentIDE",Accept:"application/vnd.github.v3+json",Authorization:`Bearer ${m}`},redirect:"follow"})}if(!c.ok)throw new Error(`Failed to download from ${n}/${r}@${s}: ${c.statusText}`)}let l=Buffer.from(await c.arrayBuffer()),f=(0,zlib_1.gunzipSync)(l),u=parseTar(f),d="";for(let m of u.keys())if(m.includes("/")){d=m.split("/")[0]+"/";break}let p=i?`${d}${i}/`:d,g=[];for(let[m,h]of u)if(m.startsWith(p)){let E=m.slice(p.length);E&&!E.endsWith("/")&&g.push({path:E,content:h.toString("utf-8")})}if(g.length===0)throw new Error(`No files found in ${n}/${r}${i?`/${i}`:""} at ${s}`);return e&&(0,utils_1.logInfo)(e,`[GitHub] Downloaded ${g.length} files`),g}async function getRepoForkMetadata(t,e){let n=await(0,github_1.getGitHubToken)(),r=await fetch(`https://api.github.com/repos/${t}/${e}`,{headers:{Authorization:`Bearer ${n}`,Accept:"application/vnd.github.v3+json","User-Agent":"AgentIDE"}});if(r.status===404)return null;if(!r.ok)throw new Error(`Failed to inspect repo ${t}/${e}: ${r.statusText}`);let s=await r.json();return{fork:s.fork===!0,parentFullName:s.parent?.full_name}}function assertStoreFork(t,e,n){if(!(0,shared_1.isForkOfStoreRepo)(n,exports.STORE_CONFIG.owner,exports.STORE_CONFIG.repo))throw new Error(`Your GitHub repo ${t}/${e} is not a fork of ${exports.STORE_CONFIG.owner}/${exports.STORE_CONFIG.repo}.
485
485
 
486
486
  Publishing requires a fork of the store repository. Either delete or rename ${t}/${e} and retry (AgentIDE will create a proper fork), or fork ${exports.STORE_CONFIG.owner}/${exports.STORE_CONFIG.repo} on GitHub.`)}async function syncForkWithUpstream(t,e){let n=await(0,github_1.getGitHubToken)(),r=await fetch(`https://api.github.com/repos/${t}/${e}/merge-upstream`,{method:"POST",headers:{Authorization:`Bearer ${n}`,Accept:"application/vnd.github.v3+json","User-Agent":"AgentIDE","Content-Type":"application/json"},body:JSON.stringify({branch:exports.STORE_CONFIG.defaultBranch})});if(r.ok||r.status===409)return;let s=await r.text().catch(()=>"");console.warn(`[Store] Warning: fork sync returned ${r.status}: ${s.slice(0,200)}`)}async function ensureFork(){let t=await(0,github_1.getGitHubToken)(),e=await(0,github_1.getGitHubUser)(),n=await(0,github_1.getRepo)(e.login,exports.STORE_CONFIG.repo);if(n){let o=await getRepoForkMetadata(e.login,exports.STORE_CONFIG.repo);if(!o)throw new Error(`Fork repo not found: ${e.login}/${exports.STORE_CONFIG.repo}`);return assertStoreFork(e.login,exports.STORE_CONFIG.repo,o),n}if(!await(0,github_1.getRepo)(exports.STORE_CONFIG.owner,exports.STORE_CONFIG.repo))throw new Error(`Store repo not found: ${exports.STORE_CONFIG.owner}/${exports.STORE_CONFIG.repo}
487
487
 
@@ -501,135 +501,136 @@ ${o||"No changelog provided."}
501
501
 
502
502
  ---
503
503
  *Submitted via AgentIDE*
504
- `,E=await createPullRequest(p,`[${n}] Add ${r} v${s}`,h,g);return e&&(0,utils_1.logInfo)(e,`[Store] OK Created PR: ${E.url}`),{prUrl:E.url,prNumber:E.number,tagName:c}}function parseGitHubUrl(t){return(0,shared_1.parseGitHubUrl)(t,exports.STORE_CONFIG.owner,exports.STORE_CONFIG.repo)}async function detectArtifactType(t,e,n,r,s){let i=r?`${r}/`:"",o=n||"main",a=async c=>{let l=`https://api.github.com/repos/${t}/${e}/contents/${i}${c}?ref=${o}`;try{return(await fetch(l,{headers:{Accept:"application/vnd.github.v3+json","User-Agent":"AgentIDE"}})).ok}catch{return!1}};if(s&&(0,utils_1.logInfo)(s,`[Store] Detecting artifact type for ${t}/${e}/${i}...`),await a("agent.yaml"))return"pack";if(await a("SKILL.md"))return"skill";if(await a(".mcp.json")||await a("mcp.json"))return"mcp";if(await a("engine.manifest.json"))return"engine";if(await a("view.yaml")&&await a("panel-entry.yaml"))return"view";throw new Error(`Cannot detect artifact type in ${t}/${e}${r?`/${r}`:""}. Expected agent.yaml, SKILL.md, .mcp.json, engine.manifest.json, or view.yaml with panel-entry.yaml`)}exports.parseStoreUrl=shared_1.parseStoreUrl;function isStoreUrl(t){return(0,shared_1.isStoreUrl)(t,exports.STORE_CONFIG.owner,exports.STORE_CONFIG.repo)}async function listStoreIndex(t,e){let n=[],r=t?[(0,shared_1.getStorePath)(t)]:[exports.STORE_CONFIG.paths.packs,exports.STORE_CONFIG.paths.skills,exports.STORE_CONFIG.paths.mcp,exports.STORE_CONFIG.paths.engines,exports.STORE_CONFIG.paths.spotlightViews];for(let s of r){let i=`https://api.github.com/repos/${exports.STORE_CONFIG.owner}/${exports.STORE_CONFIG.repo}/contents/${s}`;try{let o=await fetch(i,{headers:{Accept:"application/vnd.github.v3+json","User-Agent":"AgentIDE"}});if(!o.ok){e&&(0,utils_1.logInfo)(e,`[Store] No ${s} directory found`);continue}let a=await o.json();for(let c of a)if(c.type==="dir"){let l=s===exports.STORE_CONFIG.paths.packs?"pack":s===exports.STORE_CONFIG.paths.skills?"skill":s===exports.STORE_CONFIG.paths.mcp?"mcp":s===exports.STORE_CONFIG.paths.engines?"engine":"view";n.push({type:l,slug:c.name,path:c.path})}}catch(o){e&&(0,utils_1.logInfo)(e,`[Store] Error listing ${s}: ${o}`)}}return n}exports.formatStoreUrl=shared_1.formatStoreUrl});var wc=S(ne=>{"use strict";Object.defineProperty(ne,"__esModule",{value:!0});ne.DENY_SCOPE_ALIASES=ne.DENY_MODE_ALIASES=ne.STRICTEST_DENY_MODE=ne.DENY_MODES=ne.DENY_SCOPES=ne.STRICTEST_ON_BREACH=ne.ON_BREACH_ALIASES=ne.ON_BREACH_ACTIONS=ne.DEPRECATED_CAP_SPELLINGS=ne.LEASE_CAP_ALIASES=ne.LEASE_CAP_FIELDS=void 0;ne.parseCapPolicy=Bm;ne.parseLease=HN;ne.LEASE_CAP_FIELDS={maxTurnsPerSession:{kind:"positive-int"},maxSessionSeconds:{kind:"positive-int"},maxConcurrentSandboxes:{kind:"positive-int"}};ne.LEASE_CAP_ALIASES={maxConcurrentCells:"maxConcurrentSandboxes"};ne.DEPRECATED_CAP_SPELLINGS={maxConcurrentCells:"maxConcurrentSandboxes",AGENTHIPPO_MAX_CONCURRENT_CELLS:"AGENTHIPPO_MAX_CONCURRENT_SANDBOXES","destroy-cell":"destroy-sandbox","--max-concurrent-cells":"--max-concurrent-sandboxes"};ne.ON_BREACH_ACTIONS={"revoke-inference":{strictness:1},"destroy-sandbox":{strictness:2}};ne.ON_BREACH_ALIASES={"destroy-cell":"destroy-sandbox"};ne.STRICTEST_ON_BREACH=Object.keys(ne.ON_BREACH_ACTIONS).reduce((t,e)=>ne.ON_BREACH_ACTIONS[t].strictness>=ne.ON_BREACH_ACTIONS[e].strictness?t:e);ne.DENY_SCOPES=["session","user","pack"];ne.DENY_MODES={drain:{strictness:1},kill:{strictness:2}};ne.STRICTEST_DENY_MODE="kill";ne.DENY_MODE_ALIASES={};ne.DENY_SCOPE_ALIASES={};var od=t=>typeof t=="object"&&t!==null&&!Array.isArray(t);function GN(t,e){return typeof e!="number"?{ok:!1,reason:`${t} must be a number, got ${typeof e} (${JSON.stringify(e)})`}:Number.isFinite(e)?e<=0?{ok:!1,reason:`${t} must be greater than 0, got ${e} (omit the field for "unbounded")`}:Number.isInteger(e)?{ok:!0,value:e}:{ok:!1,reason:`${t} must be a whole number, got ${e}`}:{ok:!1,reason:`${t} must be finite, got ${e}`}}function Bm(t,e="caps"){if(t==null)return{ok:!0,caps:{},warnings:[]};if(!od(t))return{ok:!1,reason:`${e} must be an object`};let n=[],r={};for(let[i,o]of Object.entries(t)){if(o==null||i==="onBreach")continue;let a=i in ne.LEASE_CAP_FIELDS?i:ne.LEASE_CAP_ALIASES[i];if(!a){n.push(`${e}.${i} is not a cap this build understands and is NOT being enforced`);continue}let c=GN(`${e}.${i}`,o);if(!c.ok)return{ok:!1,reason:c.reason};r[a]=c.value}let s=t.onBreach;if(s!=null){if(typeof s!="string")return{ok:!1,reason:`${e}.onBreach must be a string, got ${typeof s}`};let i=s in ne.ON_BREACH_ACTIONS?s:ne.ON_BREACH_ALIASES[s];i?r.onBreach=i:(r.onBreach=ne.STRICTEST_ON_BREACH,n.push(`${e}.onBreach="${s}" is not an action this build understands. Failing CLOSED to "${ne.STRICTEST_ON_BREACH}" (the strictest known action). Known actions: ${Object.keys(ne.ON_BREACH_ACTIONS).join(", ")}.`))}return{ok:!0,caps:r,warnings:n}}function UN(t,e){if(!od(t))return{ok:!1,reason:`deny[${e}] must be an object`};let n=[],r=t.scope;if(typeof r!="string")return{ok:!1,reason:`deny[${e}].scope must be a string`};let s=ne.DENY_SCOPES.includes(r)?r:ne.DENY_SCOPE_ALIASES[r];if(!s)return{ok:!1,reason:`deny[${e}].scope "${r}" is not a scope this build understands (known: ${ne.DENY_SCOPES.join(", ")})`};if(typeof t.match!="string"||t.match.length===0)return{ok:!1,reason:`deny[${e}].match must be a non-empty string`};let i=t.mode;if(typeof i!="string")return{ok:!1,reason:`deny[${e}].mode must be a string`};let o=i in ne.DENY_MODES?i:ne.DENY_MODE_ALIASES[i];o||(o=ne.STRICTEST_DENY_MODE,n.push(`deny[${e}].mode="${i}" is not a mode this build understands. Failing CLOSED to "${ne.STRICTEST_DENY_MODE}". Known modes: ${Object.keys(ne.DENY_MODES).join(", ")}.`));let a={scope:s,match:t.match,mode:o};if(t.reason!==void 0){if(typeof t.reason!="string")return{ok:!1,reason:`deny[${e}].reason must be a string`};a.reason=t.reason}if(t.until!==void 0&&t.until!==null){if(typeof t.until!="number"||!Number.isFinite(t.until))return{ok:!1,reason:`deny[${e}].until must be a finite epoch-seconds number`};a.until=t.until}if(t.user!==void 0&&t.user!==null){if(typeof t.user!="string")return{ok:!1,reason:`deny[${e}].user must be a string`};a.user=t.user}if(t.followUser!==void 0&&t.followUser!==null){if(typeof t.followUser!="boolean")return{ok:!1,reason:`deny[${e}].followUser must be a boolean`};a.followUser=t.followUser}return{ok:!0,rule:a,warnings:n}}function HN(t){if(!od(t))return{ok:!1,reason:"lease must be a JSON object"};let e=[];if(typeof t.pack!="string"||t.pack.length===0)return{ok:!1,reason:"lease.pack must be a non-empty string"};if(typeof t.enabled!="boolean")return{ok:!1,reason:`lease.enabled must be a boolean, got ${typeof t.enabled}`};if(typeof t.expiresAt!="number"||!Number.isFinite(t.expiresAt))return{ok:!1,reason:`lease.expiresAt must be a finite epoch-seconds number, got ${JSON.stringify(t.expiresAt)}`};let n={pack:t.pack,enabled:t.enabled,expiresAt:t.expiresAt};for(let r of["version","imageDigest","reason"]){let s=t[r];if(s!=null){if(typeof s!="string")return{ok:!1,reason:`lease.${r} must be a string, got ${typeof s}`};n[r]=s}}for(let r of["requireSignedPack","requireSignedLease","allowServiceTurns"]){let s=t[r];if(s!=null){if(typeof s!="boolean")return{ok:!1,reason:`lease.${r} must be a boolean, got ${typeof s}`};n[r]=s}}if(t.caps!==void 0&&t.caps!==null){let r=Bm(t.caps,"lease.caps");if(!r.ok)return{ok:!1,reason:r.reason};n.caps=r.caps,e.push(...r.warnings)}if(t.deny!==void 0&&t.deny!==null){if(!Array.isArray(t.deny))return{ok:!1,reason:"lease.deny must be an array"};let r=[];for(let s=0;s<t.deny.length;s++){let i=UN(t.deny[s],s);if(!i.ok)return{ok:!1,reason:i.reason};r.push(i.rule),e.push(...i.warnings)}n.deny=r}return{ok:!0,lease:n,warnings:e}}});var Po=S(ee=>{"use strict";Object.defineProperty(ee,"__esModule",{value:!0});ee.MAX_LEASE_ENVELOPE_TTL_SECONDS=ee.LEASE_JWS_TYP=ee.LeaseDeniedError=ee.LEASE_MAX_STALENESS_ENV=ee.DEFAULT_LEASE_MAX_STALENESS_SECONDS=ee.MIN_LEASE_POLL_SECONDS=ee.DEFAULT_LEASE_POLL_SECONDS=void 0;ee.resolveLeasePollSeconds=ad;ee.leaseCacheSecondsFor=cd;ee.effectiveKillLatencySeconds=BN;ee.leaseMaxStalenessFromEnv=Km;ee.resolveAllowServiceTurns=FN;ee.describeServiceTurnGate=VN;ee.denyVerdict=qm;ee.resolveFollowedUsers=KN;ee.leaseIsDead=qN;ee.policyVersion=YN;ee.assertAdmitted=XN;ee.signLease=JN;ee.verifySignedLease=Xm;ee.requireSignedLease=Jm;ee.createLeaseSource=zN;var jN=require("crypto"),Vm=Mi(),Wm=wc(),xN=Oo();ee.DEFAULT_LEASE_POLL_SECONDS=30;ee.MIN_LEASE_POLL_SECONDS=5;function ad(t){let e=typeof t=="number"&&Number.isFinite(t)?t:ee.DEFAULT_LEASE_POLL_SECONDS;return Math.max(ee.MIN_LEASE_POLL_SECONDS,Math.floor(e))}function cd(t){return ad(t)}function BN(t){let e=ad(t);return e+cd(e)}ee.DEFAULT_LEASE_MAX_STALENESS_SECONDS=1440*60;ee.LEASE_MAX_STALENESS_ENV="AGENTHIPPO_LEASE_MAX_STALENESS_SECONDS";function Km(t=process.env){let e=t[ee.LEASE_MAX_STALENESS_ENV]?.trim();if(e===void 0||e==="")return ee.DEFAULT_LEASE_MAX_STALENESS_SECONDS;let n=Number(e);return!Number.isFinite(n)||n<0?ee.DEFAULT_LEASE_MAX_STALENESS_SECONDS:Math.floor(n)}function FN(t){return t.managed?t.lease===!0?{allowed:!0,gate:"lease_allows"}:{allowed:!1,gate:t.lease===!1?"lease_denies":"lease_absent_field"}:{allowed:!0,gate:"unmanaged_no_lease"}}function VN(t){switch(t){case"lease_allows":return"permitted by the control plane (lease.allowServiceTurns)";case"unmanaged_no_lease":return"permitted: no control plane configured, so AGENTHIPPO_SERVICE_USER is the only gate";case"lease_denies":return"refused: the control plane set lease.allowServiceTurns=false";case"lease_absent_field":return"refused: this is a managed deployment and the lease does not set allowServiceTurns (absent means deny \u2014 enable it in the console)"}}function qm(t,e,n){if(!t?.deny?.length)return{denied:!1};let r=n??Math.floor(Date.now()/1e3),s=e.sessionKey.indexOf("--"),i=s>=0?e.sessionKey.slice(s+2):e.sessionKey,o={denied:!1};for(let a of t.deny){if(a.until!==void 0&&a.until<=r)continue;let c=!1;if(a.scope==="pack"?c=a.match===e.pack:a.scope==="session"?(c=a.match===e.sessionKey||a.match===i,c&&a.user!==void 0&&e.userId!==void 0&&a.user!==e.userId&&(c=!1),!c&&a.followUser!==!1&&e.userId!==void 0&&WN(a,e.userId,e.followedUsers)&&(c=!0)):a.scope==="user"&&(c=e.userId!==void 0&&a.match===e.userId||e.userHash!==void 0&&e.sessionKey.startsWith(`u${e.userHash(a.match)}--`)),!c)continue;let l=`${a.mode==="kill"?"stopped":"draining"} by the control plane${a.reason?`: ${a.reason}`:""}`;if(a.mode==="kill")return{denied:!0,mode:"kill",reason:l};o.denied||(o={denied:!0,mode:"drain",reason:l})}return o}var Ym=t=>`${t.scope}:${t.match}`;function WN(t,e,n){return n?.get(Ym(t))?.has(e)??!1}function KN(t,e,n){let r=new Map;if(!t?.deny?.length)return r;let s=n??Math.floor(Date.now()/1e3);for(let i of t.deny){if(i.scope!=="session"||i.followUser===!1||i.until!==void 0&&i.until<=s)continue;let o=new Set;for(let[a,c]of e){let l=a.indexOf("--"),f=l>=0?a.slice(l+2):a;i.match!==a&&i.match!==f||i.user!==void 0&&i.user!==c||o.add(c)}o.size>0&&r.set(Ym(i),o)}return r}function qN(t,e){if(!t)return{dead:!1};let n=e??Math.floor(Date.now()/1e3);return t.enabled?t.expiresAt<=n?{dead:!0,reason:`lease expired at ${new Date(t.expiresAt*1e3).toISOString()}`}:{dead:!1}:{dead:!0,reason:`kill switch active${t.reason?`: ${t.reason}`:""}`}}function YN(t){if(!t)return;let{expiresAt:e,...n}=t,r=s=>Array.isArray(s)?s.map(r):s&&typeof s=="object"?Object.fromEntries(Object.keys(s).sort().map(i=>[i,r(s[i])])):s;return(0,jN.createHash)("sha256").update(JSON.stringify(r(n))).digest("hex")}var hs=class extends Error{constructor(e){super(e),this.name="LeaseDeniedError"}};ee.LeaseDeniedError=hs;function XN(t,e){if(!t)return;let n=e.nowSeconds??Math.floor(Date.now()/1e3);if(!t.enabled)throw new hs(`kill switch active for pack ${e.pack}${t.reason?`: ${t.reason}`:""}`);if(t.pack!==e.pack)throw new hs(`lease is for pack ${t.pack}, not ${e.pack}`);if(t.expiresAt<=n)throw new hs(`lease for ${e.pack} expired at ${new Date(t.expiresAt*1e3).toISOString()}`);if(t.version&&t.version!==e.version)throw new hs(`pack ${e.pack} is pinned to ${t.version}; refusing to start ${e.version} (rollback in force)`);if(t.imageDigest&&e.image&&!e.image.includes(t.imageDigest))throw new hs(`image for ${e.pack} does not match the leased digest ${t.imageDigest}`);if(e.sessionKey){let r=qm(t,{sessionKey:e.sessionKey,pack:e.pack,userHash:e.userHash,userId:e.userId,followedUsers:e.followedUsers},n);if(r.denied)throw new hs(r.reason??"stopped by the control plane")}}ee.LEASE_JWS_TYP="agenthippo-lease+jws";ee.MAX_LEASE_ENVELOPE_TTL_SECONDS=3600;function JN(t,e,n){let r=n.nowSeconds??Math.floor(Date.now()/1e3),s=Math.min(n.ttlSeconds??300,ee.MAX_LEASE_ENVELOPE_TTL_SECONDS),i={lease:t,aud:n.instanceId??"*",sub:t.pack,iat:r,exp:r+s,...n.iss?{iss:n.iss}:{}};return(0,Vm.signCompactJws)({typ:ee.LEASE_JWS_TYP,kid:e.kid},i,e.privateKeyPem)}function Xm(t,e,n={}){if(Object.keys(e).length===0)return{ok:!1,reason:"no trusted lease-signing keys are configured on this instance"};let r=(0,Vm.verifyCompactJws)(t,e,{typ:ee.LEASE_JWS_TYP});if(!r.ok)return{ok:!1,reason:`lease signature: ${r.reason}`};let s=r.payload,i=n.nowSeconds??Math.floor(Date.now()/1e3),o=n.clockSkewSeconds??60;if(typeof s.iat!="number"||!Number.isFinite(s.iat))return{ok:!1,reason:"lease envelope has no issued-at"};if(typeof s.exp!="number"||!Number.isFinite(s.exp))return{ok:!1,reason:"lease envelope has no expiry"};if(s.exp-s.iat>ee.MAX_LEASE_ENVELOPE_TTL_SECONDS)return{ok:!1,reason:`lease envelope lifetime ${s.exp-s.iat}s exceeds the ${ee.MAX_LEASE_ENVELOPE_TTL_SECONDS}s cap`};if(s.exp+o<=i)return{ok:!1,reason:`lease envelope expired at ${new Date(s.exp*1e3).toISOString()}`};if(s.iat-o>i)return{ok:!1,reason:"lease envelope is issued in the future"};if(n.minIat!==void 0&&s.iat<n.minIat)return{ok:!1,reason:`lease envelope is older than one already accepted (replay/rollback: iat ${s.iat} < ${n.minIat})`};if(n.instanceId!==void 0&&s.aud!=="*"&&s.aud!==n.instanceId)return{ok:!1,reason:`lease envelope is for instance ${s.aud}, not ${n.instanceId}`};let a=(0,Wm.parseLease)(s.lease);return a.ok?s.sub!==a.lease.pack?{ok:!1,reason:`lease envelope subject ${s.sub} does not match lease.pack ${a.lease.pack}`}:{ok:!0,lease:a.lease,claims:s}:{ok:!1,reason:`signed lease is malformed: ${a.reason}`}}function Jm(t,e){return!!t||!!e}var Fm=t=>/^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/.test(t);function zN(t){let e=t.staticLease,n=0,r,s,i=!1,o=!1,a,c=!1,l=!1,f=!1,u=t.cacheSeconds??cd(ee.DEFAULT_LEASE_POLL_SECONDS),d=t.maxStalenessSeconds??Km(t.env),p=t.fetchImpl??fetch,g=()=>Jm(o,t.requireSignedLease),m=E=>({...e??{pack:"",expiresAt:0},enabled:!1,reason:`the control plane has not been reachable for ${E}s, past the ${d}s staleness ceiling (${ee.LEASE_MAX_STALENESS_ENV}). Refusing work rather than running on a lease that can no longer be revoked. Set ${ee.LEASE_MAX_STALENESS_ENV}=0 to accept unbounded staleness.`}),h=(E,_)=>{let y=E.trim(),b,T;if(Fm(y))b=y;else{try{T=JSON.parse(y)}catch(A){return{ok:!1,reason:`lease body is not JSON: ${A instanceof Error?A.message:String(A)}`}}typeof T=="string"&&Fm(T.trim())?b=T.trim():T&&typeof T=="object"&&typeof T.lease=="string"&&(b=T.lease.trim())}if(b){let A=Xm(b,t.signingKeys?.()??{},{instanceId:t.instanceId,minIat:a,nowSeconds:_});return A.ok?(a=A.claims.iat,{ok:!0,lease:A.lease,signed:!0}):{ok:!1,reason:A.reason}}if(g())return{ok:!1,reason:'a signed lease is required but the control plane returned an unsigned one (expected a compact JWS body or {"lease":"<jws>"})'};let O=(0,Wm.parseLease)(T);if(!O.ok)return{ok:!1,reason:O.reason};for(let A of O.warnings)t.logger?.warn(`[Lease] ${A}`);return{ok:!0,lease:O.lease,signed:!1}};return{status(E){let _=E??Math.floor(Date.now()/1e3),y=r===void 0?void 0:_-r;return{signed:i,requireSignedLease:g(),lastGoodAt:r,stalenessSeconds:y,maxStalenessSeconds:d,failClosed:d>0&&y!==void 0&&y>d,lastError:s}},async get(E){let _=E??Math.floor(Date.now()/1e3);if(!t.url)return e;if(!f){f=!0;let y=(0,xN.assertSecureTrustUrl)(t.url,"AGENTHIPPO_LEASE_URL",t.env??process.env);if(y.ok)for(let b of y.warnings)t.logger?.warn(`[Lease] ${b}`);else g()?t.logger?.warn(`[Lease] INSECURE LEASE CHANNEL \u2014 ${y.reason} Signed leases are required here, so the policy itself is still verified \u2014 but the channel is not: anyone on the path can read this instance's identity, pack and version, and can delay a kill switch by up to ${ee.MAX_LEASE_ENVELOPE_TTL_SECONDS}s by replaying the last envelope. requireSignedLease is not a substitute for https; serve the lease over https.`):t.logger?.warn(`[Lease] INSECURE LEASE CHANNEL \u2014 ${y.reason} Anyone on the path can lift this instance's kill switch, widen its caps or change its version pin. Continuing to poll (refusing would disable the kill switch entirely), but this deployment is not governable until the lease is signed: set requireSignedLease and have the control plane sign leases.`)}if(e&&_-n<u)return e;try{let y={accept:"application/json, text/plain"};for(let[A,v]of Object.entries(t.identity?.()??{}))v!==void 0&&v!==""&&(y[`x-agenthippo-${A}`]=String(v));let b=await p(t.url,{headers:y});if(!b.ok)throw new Error(`lease fetch ${b.status}`);let T=typeof b.text=="function"?await b.text():JSON.stringify(await b.json()),O=h(T,_);if(!O.ok)throw new Error(O.reason);return O.signed?(i=!0,O.lease.requireSignedLease&&(o=!0)):l||(l=!0,t.logger?.warn(`[Lease] running on an UNSIGNED lease. Anyone who can answer or intercept ${t.url} can lift this instance's kill switch, widen its caps and change its version pin. Have the control plane sign leases (ES256 compact JWS) and set requireSignedLease.`)),e=O.lease,n=_,r=_,s=void 0,c=!1,e}catch(y){s=y instanceof Error?y.message:String(y),t.logger?.warn(`[Lease] fetch failed, using cached lease: ${s}`),r===void 0&&(r=_);let b=_-r;return d>0&&b>d?(c||(c=!0,t.logger?.warn(`[Lease] STALENESS CEILING PASSED \u2014 no successful lease refresh for ${b}s (ceiling ${d}s). Failing closed: turns are refused until the control plane is reachable.`)),m(b)):e}}}}});var Ac=S(Ue=>{"use strict";Object.defineProperty(Ue,"__esModule",{value:!0});Ue.CapMeter=Ue.CAP_ENV_ALIASES=Ue.parseCapPolicy=Ue.STRICTEST_ON_BREACH=Ue.ON_BREACH_ALIASES=Ue.ON_BREACH_ACTIONS=Ue.LEASE_CAP_FIELDS=Ue.LEASE_CAP_ALIASES=Ue.DEPRECATED_CAP_SPELLINGS=void 0;Ue.resolveOnBreach=zm;Ue.mergeCaps=ZN;Ue.capsAreUnbounded=eR;Ue.capsFromEnv=tR;var Ui=wc(),di=wc();Object.defineProperty(Ue,"DEPRECATED_CAP_SPELLINGS",{enumerable:!0,get:function(){return di.DEPRECATED_CAP_SPELLINGS}});Object.defineProperty(Ue,"LEASE_CAP_ALIASES",{enumerable:!0,get:function(){return di.LEASE_CAP_ALIASES}});Object.defineProperty(Ue,"LEASE_CAP_FIELDS",{enumerable:!0,get:function(){return di.LEASE_CAP_FIELDS}});Object.defineProperty(Ue,"ON_BREACH_ACTIONS",{enumerable:!0,get:function(){return di.ON_BREACH_ACTIONS}});Object.defineProperty(Ue,"ON_BREACH_ALIASES",{enumerable:!0,get:function(){return di.ON_BREACH_ALIASES}});Object.defineProperty(Ue,"STRICTEST_ON_BREACH",{enumerable:!0,get:function(){return di.STRICTEST_ON_BREACH}});Object.defineProperty(Ue,"parseCapPolicy",{enumerable:!0,get:function(){return di.parseCapPolicy}});Ue.CAP_ENV_ALIASES={AGENTHIPPO_MAX_CONCURRENT_CELLS:"AGENTHIPPO_MAX_CONCURRENT_SANDBOXES"};function zm(t,e){let n=t?.trim();if(!n)return{action:void 0,warnings:[]};if(n in Ui.ON_BREACH_ACTIONS)return{action:n,warnings:[]};let r=Ui.ON_BREACH_ALIASES[n];return r?{action:r,warnings:[`${e}="${n}" is DEPRECATED; use "${Ui.DEPRECATED_CAP_SPELLINGS[n]??r}". Treating it as "${r}". The old spelling will stop being accepted.`]}:{action:Ui.STRICTEST_ON_BREACH,warnings:[`${e}="${n}" is not a breach action this build understands. FAILING CLOSED to "${Ui.STRICTEST_ON_BREACH}" \u2014 an unreadable enforcement setting must never weaken enforcement. Known actions: ${Object.keys(Ui.ON_BREACH_ACTIONS).join(", ")}.`]}}var QN=1e4;function ZN(t,e){let n=t??{},r=e??{},s=(i,o)=>i===void 0?o:o===void 0?i:Math.min(i,o);return{maxTurnsPerSession:s(n.maxTurnsPerSession,r.maxTurnsPerSession),maxSessionSeconds:s(n.maxSessionSeconds,r.maxSessionSeconds),maxConcurrentSandboxes:s(n.maxConcurrentSandboxes,r.maxConcurrentSandboxes),onBreach:n.onBreach==="destroy-sandbox"||r.onBreach==="destroy-sandbox"?"destroy-sandbox":n.onBreach??r.onBreach}}function eR(t){return t.maxTurnsPerSession===void 0&&t.maxSessionSeconds===void 0&&t.maxConcurrentSandboxes===void 0}var ld=class{caps;sessions=new Map;constructor(e){this.caps=e}setCaps(e){this.caps=e}policy(){return this.caps}check(e,n,r=Date.now()){let s=this.sessions.get(e);if(this.caps.maxTurnsPerSession!==void 0&&s&&s.turns>=this.caps.maxTurnsPerSession)return{allowed:!1,cap:"turns",reason:`session turn cap reached (${s.turns}/${this.caps.maxTurnsPerSession})`};if(this.caps.maxSessionSeconds!==void 0&&s){let i=Math.floor((r-s.startedAtMs)/1e3);if(i>=this.caps.maxSessionSeconds)return{allowed:!1,cap:"duration",reason:`session duration cap reached (${i}s/${this.caps.maxSessionSeconds}s)`}}return this.caps.maxConcurrentSandboxes!==void 0&&!s&&n>=this.caps.maxConcurrentSandboxes?{allowed:!1,cap:"concurrency",reason:`instance is at its concurrent sandbox cap (${n}/${this.caps.maxConcurrentSandboxes})`}:{allowed:!0}}record(e,n=Date.now()){let r=this.sessions.get(e);if(r){r.turns+=1;return}if(this.sessions.size>=QN){let s,i=1/0;for(let[o,a]of this.sessions)a.startedAtMs<i&&(i=a.startedAtMs,s=o);s&&this.sessions.delete(s)}this.sessions.set(e,{turns:1,startedAtMs:n})}forget(e){this.sessions.delete(e)}usage(e){let n=this.sessions.get(e);if(n)return{turns:n.turns,ageSeconds:Math.floor((Date.now()-n.startedAtMs)/1e3)}}};Ue.CapMeter=ld;function tR(t=process.env,e=n=>console.warn(`Warning: ${n}`)){let n=i=>{let o=parseInt((i??"").trim(),10);return Number.isFinite(o)&&o>0?o:void 0},r=i=>{let o=n(t[i]);if(o!==void 0)return o;for(let[a,c]of Object.entries(Ue.CAP_ENV_ALIASES)){if(c!==i)continue;let l=n(t[a]);if(l!==void 0)return e(`${a} is DEPRECATED; use ${i}. Honouring it for now.`),l}},s=zm(t.AGENTHIPPO_CAP_ON_BREACH,"AGENTHIPPO_CAP_ON_BREACH");for(let i of s.warnings)e(i);return{maxTurnsPerSession:r("AGENTHIPPO_MAX_TURNS_PER_SESSION"),maxSessionSeconds:r("AGENTHIPPO_MAX_SESSION_SECONDS"),maxConcurrentSandboxes:r("AGENTHIPPO_MAX_CONCURRENT_SANDBOXES"),onBreach:s.action}}});var Zm=S(No=>{"use strict";Object.defineProperty(No,"__esModule",{value:!0});No.effectiveDenyMode=Qm;No.createGovernor=nR;No.withGovernor=rR;var Sc=Ac(),Hi=Po();function Qm(t,e){return t==="kill"&&!e?"drain":t}function nR(t){let e=new Sc.CapMeter(t.caps),n=(0,Sc.capsAreUnbounded)(t.caps),r,s,i,o=new Map,a=t.sandboxes.supportsInFlightTermination!==!1,c=new Map,l=new Set,f=(h,E)=>{try{t.audit?.(h,E)}catch{}},u=1e4,d=(h,E)=>{if(o.size>=u&&!o.has(h)){let _=o.keys().next();_.done||o.delete(_.value)}o.set(h,E)},p=async(h,E)=>{let _=e.policy().onBreach??"revoke-inference";try{_==="destroy-sandbox"?await t.sandboxes.destroySession(h):await t.sandboxes.revokeRoute(h,"inference")}catch(y){t.logger?.warn(`[Governor] ${_} failed for ${h}, destroying instead: ${y instanceof Error?y.message:String(y)}`),await t.sandboxes.destroySession(h).catch(()=>{})}t.logger?.warn(`[Governor] cap breach on ${h}: ${E.reason} \u2014 ${_}`),f("cap_breach",{sessionKey:h,cap:E.cap,reason:E.reason,action:_})},g=async h=>{let E=t.sandboxes.sandboxes();for(let _ of E)await t.sandboxes.destroySession(_.sandboxKey).catch(()=>{});return E.length>0?t.logger?.warn(`[Governor] kill switch: destroyed ${E.length} live sandbox(s) \u2014 ${h}`):a||t.logger?.warn(`[Governor] kill switch: no sandbox driver, so nothing running can be stopped \u2014 in-flight turns will finish and only NEW turns are refused (${h}). Run with --sandbox for true in-flight kill.`),f("kill_switch",{reason:h,destroyed:E.length,inFlightTerminated:a}),E.length},m=async()=>{if(t.getLease)try{let h=await t.getLease(),E=(0,Sc.mergeCaps)(h?.caps,t.caps);if(e.setCaps(E),n=(0,Sc.capsAreUnbounded)(E),i=h,c=(0,Hi.resolveFollowedUsers)(h,o),!a)for(let y of h?.deny??[]){if(y.mode!=="kill")continue;let b=`${y.scope}:${y.match}`;l.has(b)||(l.add(b),t.logger?.warn(`[Governor] deny(kill) on ${b} DEGRADED TO DRAIN: this deployment has no sandbox driver, so a turn already executing cannot be stopped. It will run to completion; only the next turn is refused. Run serve with --sandbox for a kill that ends work mid-flight.`),f("deny_kill_degraded",{scope:y.scope,match:y.match,effectiveMode:"drain"}))}for(let y of t.sandboxes.sandboxes()){let b=y.sessionKeys.map(T=>({sessionKey:T,v:(0,Hi.denyVerdict)(h,{sessionKey:T,pack:t.pack??"",userHash:t.userHash,userId:o.get(T),followedUsers:c})})).find(({v:T})=>T.denied&&Qm(T.mode,a)==="kill");if(b){await t.sandboxes.destroySession(y.sandboxKey).catch(()=>{});for(let T of y.sessionKeys)o.delete(T);t.logger?.warn(`[Governor] deny(kill) destroyed ${y.sandboxId} \u2014 ${b.v.reason}`),f("session_killed",{sessionKey:b.sessionKey,sandboxId:y.sandboxId,reason:b.v.reason,collateralSessions:y.sessionKeys.filter(T=>T!==b.sessionKey)})}}let _=(0,Hi.leaseIsDead)(h);_.dead?(s=_.reason??"lease revoked",await g(s)):s&&(t.logger?.info("[Governor] lease restored \u2014 accepting turns again"),f("kill_switch_lifted",{}),s=void 0)}catch(h){t.logger?.warn(`[Governor] lease check failed: ${h instanceof Error?h.message:String(h)}`)}};return{async admitTurn(h,E){if(s)return{allowed:!1,reason:`stopped by the control plane: ${s}`};E&&d(h,E);let _=(0,Hi.denyVerdict)(i,{sessionKey:h,pack:t.pack??"",userHash:t.userHash,userId:E??o.get(h),followedUsers:(0,Hi.resolveFollowedUsers)(i,o)});if(_.denied)return{allowed:!1,reason:_.reason};if(t.admitPack){let b=t.admitPack(h,i);if(!b.allowed)return{allowed:!1,reason:b.reason??"refused by pack admission"}}if(n)return{allowed:!0};let y=e.check(h,t.sandboxes.sandboxes().length);return y.allowed||y.cap!=="concurrency"&&await p(h,y),y},recordTurn(h){e.record(h)},killAll:g,refresh:m,start(){if(!t.getLease||r)return;let h=(0,Hi.resolveLeasePollSeconds)(t.pollSeconds)*1e3;r=setInterval(()=>{m()},h),r.unref?.(),m()},stop(){r&&(clearInterval(r),r=void 0)},policy:()=>e.policy()}}function rR(t,e){return{async run(n){let r=n.sessionId??"default",s=await e.admitTurn(r,n.analyticsUserId);return s.allowed?(e.recordTurn(r),t.run(n)):{success:!1,text:"",thinking:"",toolCalls:[],error:s.reason??"refused by policy"}},dispose(){e.stop(),t.dispose()}}}});var oE=S(Ve=>{"use strict";var sR=Ve&&Ve.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,s)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),iR=Ve&&Ve.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),Co=Ve&&Ve.__importStar||(function(){var t=function(e){return t=Object.getOwnPropertyNames||function(n){var r=[];for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(r[r.length]=s);return r},t(e)};return function(e){if(e&&e.__esModule)return e;var n={};if(e!=null)for(var r=t(e),s=0;s<r.length;s++)r[s]!=="default"&&sR(n,e,r[s]);return iR(n,e),n}})();Object.defineProperty(Ve,"__esModule",{value:!0});Ve.ContainerSandboxDriver=Ve.SANDBOX_PACK_DIR=Ve.SANDBOX_WORKSPACE_DIR=Ve.SANDBOX_STATE_DIR=Ve.SANDBOX_SOCKET_DIR_IN_SANDBOX=void 0;Ve.strictEgressFromEnv=rE;Ve.prepareSocketDir=sE;Ve.assertOwnSocket=iE;var oR=Co(require("node:crypto")),Ar=Co(require("node:fs")),aR=Co(require("node:net")),cR=Co(require("node:os")),Ro=Co(require("node:path")),eE=za();function rE(t=process.env){return t.AGENTHIPPO_SANDBOX_STRICT_EGRESS==="1"}function lR(){let t=[process.env.AGENTHIPPO_SANDBOX_SOCKET_DIR,"/run/agenthippo/sandboxes",process.env.XDG_RUNTIME_DIR?Ro.join(process.env.XDG_RUNTIME_DIR,"agenthippo-sandboxes"):void 0,Ro.join(cR.tmpdir(),"agenthippo-sandboxes")].filter(e=>!!e);for(let e of t)try{if(Ar.mkdirSync(e,{recursive:!0}),Ar.accessSync(e,Ar.constants.W_OK),e.length>60)continue;return e}catch{}return"/run/agenthippo/sandboxes"}var uR=lR(),dR=9e4,fR=150;Ve.SANDBOX_SOCKET_DIR_IN_SANDBOX="/run/sandbox";Ve.SANDBOX_STATE_DIR="/state";Ve.SANDBOX_WORKSPACE_DIR="/state/workspace";Ve.SANDBOX_PACK_DIR="/app/pack";var ud=class{opts;kind="container";tier=2;sandboxes=new Map;seq=0;instance=oR.randomBytes(2).toString("hex");constructor(e){this.opts=e}async create(e){pR(e.image);let n=`sandbox-${this.instance}-${++this.seq}-${ER(e.sandboxKey)}`,r=this.opts.socketDir??uR,s=Ro.join(r,n),i=Ro.join(s,"sandbox.sock");Ar.rmSync(s,{recursive:!0,force:!0}),sE(s,this.opts.socketOwner);let o=e.routes.map(h=>({kind:h.kind,network:hR(h.target)})),c=await this.assertRouteNetworks(o)?this.tier:1,l=o[0],f=["run","--detach","--name",n,"--network",l?l.network:"none","--cap-drop","ALL","--security-opt","no-new-privileges","--read-only","--tmpfs","/tmp:rw,exec,nosuid,size=512m",...e.stateDir?["--volume",`${e.stateDir}:${Ve.SANDBOX_STATE_DIR}`]:["--tmpfs",`${Ve.SANDBOX_STATE_DIR}:rw,exec,nosuid,size=512m,mode=1777`],"--volume",`${s}:${Ve.SANDBOX_SOCKET_DIR_IN_SANDBOX}`,"--label",`ai.agenthippo.sandbox=${n}`,"--label",`ai.agenthippo.session=${e.sandboxKey}`,"--label",`ai.agenthippo.tier=${e.tier}`];for(let h of e.fs.readonly)f.push("--volume",tE(h,!0));for(let h of e.fs.writable)f.push("--volume",tE(h,!1));e.limits.memMiB&&f.push("--memory",`${e.limits.memMiB}m`),e.limits.cpu&&f.push("--cpus",e.limits.cpu);for(let[h,E]of Object.entries(e.env??{}))f.push("--env",`${h}=${E}`);f.push("--env",`${eE.SANDBOX_TIER_ENV}=${c}`),f.push(e.image);let u=await this.opts.exec(f);if(u.code!==0)throw await this.opts.exec(["rm","--force",n]),new Error(`failed to create sandbox ${n}: ${u.stdout.trim()||`exit ${u.code}`}`);let d=u.stdout.trim(),p=new Map;l&&p.set(l.kind,l.network);for(let h of o.slice(1)){let E=await this.opts.exec(["network","connect",h.network,n]);if(E.code!==0)throw await this.opts.exec(["rm","--force",n]),new Error(`failed to attach ${h.kind} route for sandbox ${n}: ${E.stdout.trim()}`);p.set(h.kind,h.network)}await this.waitForSocket(n,i);let g={containerId:d,socketPath:i,networks:p};e.limits.ttlSeconds>0&&(g.ttl=setTimeout(()=>{this.destroyById(n)},e.limits.ttlSeconds*1e3),g.ttl.unref?.()),this.sandboxes.set(n,g);let m=this.opts.connectFn??mR;return{id:n,tier:c,endpoint:i,connect:()=>m(i)}}async assertRouteNetworks(e){let n=new Set,r=!0;for(let s of e){if(n.has(s.network))continue;n.add(s.network);let i=await this.opts.exec(["network","inspect","--format","{{.Internal}}",s.network]);if(i.code!==0)throw new Error(`route network "${s.network}" (${s.kind}) does not exist \u2014 a tier-2 sandbox is created on its declared route networks and nothing creates them for you. Create it (\`docker network create --internal ${s.network}\`) and put the ${s.kind} service on it.`);if(i.stdout.trim()!=="true"){if(r=!1,this.opts.strictEgress??rE())throw new Error(`route network "${s.network}" (${s.kind}) is not --internal, and strict egress containment is enabled (AGENTHIPPO_SANDBOX_STRICT_EGRESS=1). A sandbox on this network can reach any host it routes to, so the tier-2 containment claim would be false. Recreate it as internal (\`docker network rm ${s.network} && docker network create --internal ${s.network}\`), or unset AGENTHIPPO_SANDBOX_STRICT_EGRESS to accept a sandbox whose egress is bounded by the network topology instead.`);this.opts.logger?.warn(`route network "${s.network}" (${s.kind}) is not --internal: this sandbox can reach any host that network routes to, so tier-2 egress is bounded by that network's topology, not by the sandbox. This sandbox is therefore reported as tier 1, not tier 2. Make the network internal (or set AGENTHIPPO_SANDBOX_STRICT_EGRESS=1 to refuse outright).`)}}return r}async waitForSocket(e,n){let r=this.opts.socketWaitMs??dR;if(r<=0)return;let s=Date.now()+r;for(;Date.now()<s;){if(Ar.existsSync(n)){try{iE(n,this.opts.socketOwner)}catch(a){throw await this.opts.exec(["rm","--force",e]),a}return}if((await this.opts.exec(["inspect","--format","{{.State.Running}}",e])).stdout.trim()==="false"){let a=await this.opts.exec(["logs","--tail","20",e]);throw await this.opts.exec(["rm","--force",e]),new Error(`sandbox ${e} exited during boot: ${nE(a)}`)}await new Promise(a=>setTimeout(a,fR))}let i=await this.opts.exec(["logs","--tail","20",e]);throw await this.opts.exec(["rm","--force",e]),new Error(`sandbox ${e} did not bind ${n} within ${r/1e3}s: ${nE(i)}`)}async revoke(e,n){let r=this.sandboxes.get(e.id);if(!r)return;if(n==="all")return this.destroyById(e.id);let s=r.networks.get(n);if(!s)throw new eE.RevocationUnsupportedError("container",n);let i=await this.opts.exec(["network","disconnect","--force",s,e.id]);if(i.code!==0)throw new Error(`failed to revoke ${n} for sandbox ${e.id}: ${i.stdout.trim()}`);r.networks.delete(n)}async destroy(e){await this.destroyById(e.id)}async destroyById(e){let n=this.sandboxes.get(e);if(n){this.sandboxes.delete(e),n.ttl&&clearTimeout(n.ttl),await this.opts.exec(["rm","--force",e]);try{Ar.rmSync(Ro.dirname(n.socketPath),{recursive:!0,force:!0})}catch{}}}};Ve.ContainerSandboxDriver=ud;function sE(t,e){if(Ar.mkdirSync(t,{recursive:!0}),e&&e.uid!==0)try{Ar.chownSync(t,e.uid,e.gid),Ar.chmodSync(t,448);return}catch{}Ar.chmodSync(t,987)}function iE(t,e,n=typeof process.getuid=="function"?process.getuid():void 0){let r=Ar.lstatSync(t);if(r.isSymbolicLink())throw new Error(`sandbox socket ${t} is a symlink \u2014 refusing to connect`);if(!r.isSocket())throw new Error(`sandbox socket ${t} is not a unix socket \u2014 refusing to connect`);let s=new Set;if(n!==void 0&&s.add(n),e&&s.add(e.uid),s.add(0),!s.has(r.uid))throw new Error(`sandbox socket ${t} is owned by uid ${r.uid}, which is neither this process nor the sandbox \u2014 another local user may have raced the bind. Refusing to connect.`)}function tE(t,e){let n=t.indexOf(":"),[r,s]=n===-1?[t,t]:[t.slice(0,n),t.slice(n+1)];return`${r}:${s}${e?":ro":""}`}function pR(t){let e=/@sha256:[a-f0-9]{64}$/.test(t),n=/^sha256:[a-f0-9]{64}$/.test(t);if(!e&&!n)throw new Error(`sandbox image must be pinned by digest (got "${t}") \u2014 a mutable tag makes signing and rollback unverifiable`)}function nE(t){return`${t.stdout??""}${t.stderr??""}`.trim()||"(no output)"}var gR=new Set(["localhost","127.0.0.1","::1","0.0.0.0","[::1]"]);function hR(t){let e=t.replace(/^\w+:\/\//,"").split(/[:/]/)[0];if(gR.has(e.toLowerCase()))throw new Error(`route target "${t}" is loopback, which inside a sandbox means the sandbox itself \u2014 a tier-2 sandbox cannot reach a service on the host this way. Give the service a name the sandbox can resolve (a compose service name, or host.docker.internal) on a network named agenthippo-<host>, or run this deployment with --sandbox process.`);return`agenthippo-${e}`}function mR(t){let e=aR.createConnection(t),n=new Promise((r,s)=>{e.once("close",()=>r()),e.once("error",i=>s(new Error(`sandbox channel closed: ${i.message}`)))});return{input:e,output:{write:r=>e.write(r)},closed:n}}function ER(t){return t.replace(/[^a-zA-Z0-9_-]/g,"").slice(0,32)||"session"}});var fE=S(Qe=>{"use strict";Object.defineProperty(Qe,"__esModule",{value:!0});Qe.ProcessSandboxDriver=Qe.PROVIDER_KEY_PASSTHROUGH_VARS=Qe.NS_PROBE_ARGS=Qe.UNSHARE_WRAP_ARGS=void 0;Qe.namespaceIsolationFromEnv=_R;Qe.probeNamespaceIsolation=cE;Qe.providerKeyPassthroughFromEnv=lE;Qe.sandboxEnvCarriesProviderKey=uE;Qe.baseSandboxEnv=dE;var aE=require("node:child_process"),dd=za();function _R(t=process.env){let e=t.AGENTHIPPO_SANDBOX_NS_ISOLATION?.trim().toLowerCase();return e==="off"||e==="0"?"off":e==="require"?"require":"auto"}Qe.UNSHARE_WRAP_ARGS=["--user","--map-current-user","--pid","--fork","--kill-child=SIGTERM","--mount-proc"];Qe.NS_PROBE_ARGS=[...Qe.UNSHARE_WRAP_ARGS,"unshare","--user","true"];async function cE(t=aE.spawn,e=5e3){return new Promise(n=>{let r,s=!1,i=a=>{s||(s=!0,r&&clearTimeout(r),n(a))},o;try{o=t("unshare",[...Qe.NS_PROBE_ARGS],{stdio:"ignore"})}catch{i(!1);return}r=setTimeout(()=>{o.kill("SIGKILL"),i(!1)},e),r.unref?.(),o.once("error",()=>i(!1)),o.once("exit",a=>i(a===0))})}Qe.PROVIDER_KEY_PASSTHROUGH_VARS=["CURSOR_API_KEY"];function lE(t=process.env){return t.AGENTHIPPO_SANDBOX_ALLOW_PROVIDER_KEY==="1"}function uE(t){return Qe.PROVIDER_KEY_PASSTHROUGH_VARS.some(e=>!!t[e])}var fd=class{opts;kind="process";tier=0;sandboxes=new Map;seq=0;nsWrap;constructor(e){this.opts=e}namespaceWrap(){if(!this.nsWrap){let e=this.opts.namespaceIsolation??"off";if(e==="off")this.nsWrap=Promise.resolve(!1);else{let n=this.opts.probeFn??(()=>cE());this.nsWrap=n().then(r=>{if(r)return this.opts.logger?.info("[Sandbox] namespace isolation active: each sandbox gets its own PID namespace (/proc shows only its own tree)"),!0;if(e==="require")throw new Error(`AGENTHIPPO_SANDBOX_NS_ISOLATION=require, but this host cannot run \`unshare ${Qe.UNSHARE_WRAP_ARGS.join(" ")}\` \u2014 no sandbox may exist here whose env is readable by a concurrent tenant. Enable unprivileged user namespaces (or use --sandbox container), or drop the requirement.`);return this.opts.logger?.warn("namespace isolation unavailable on this host (unshare probe failed) \u2014 tier-0 sandboxes share one /proc, so a concurrent same-uid process can read a turn's env. Fine on a laptop; on a multi-tenant host set AGENTHIPPO_SANDBOX_NS_ISOLATION=require or use --sandbox container."),!1})}}return this.nsWrap}async create(e){let n=`sandbox-${++this.seq}-${yR(e.sandboxKey)}`,r=this.opts.spawnFn??aE.spawn,s=await this.namespaceWrap(),i=s?"unshare":this.opts.command,o=s?[...Qe.UNSHARE_WRAP_ARGS,this.opts.command,...this.opts.args??[]]:this.opts.args??[],c={...dE({...this.opts.allowProviderKeyPassthrough!==void 0?{allowProviderKeyPassthrough:this.opts.allowProviderKeyPassthrough}:{},logger:{warn:g=>console.warn(g)}}),...this.opts.env,...e.env},l=uE(c),f=r(i,o,{cwd:this.opts.cwd,stdio:["pipe","pipe","inherit"],env:{...c,[dd.SANDBOX_TIER_ENV]:String(this.tier),...l?{[dd.SANDBOX_PROVIDER_KEY_ENV]:"1"}:{}}});l&&console.warn(`[Sandbox] ${n} runs WITH a raw provider key in its environment (${Qe.PROVIDER_KEY_PASSTHROUGH_VARS.filter(g=>c[g]).join(", ")}). This sandbox does not have the model-credential containment the other engines get; disclose it in the deployment.`);let u=new Promise(g=>{f.once("exit",()=>g()),f.once("error",()=>g())}),d={input:f.stdout,output:{write:g=>f.stdin?.write(g)??!1},closed:u},p={child:f,channel:d};return e.limits.ttlSeconds>0&&(p.ttl=setTimeout(()=>{this.kill(n)},e.limits.ttlSeconds*1e3),p.ttl.unref?.()),this.sandboxes.set(n,p),{id:n,tier:this.tier,endpoint:"stdio",connect:()=>d}}async revoke(e,n){if(n!=="all")throw new dd.RevocationUnsupportedError("process",n);await this.kill(e.id)}async destroy(e){await this.kill(e.id)}async kill(e){let n=this.sandboxes.get(e);n&&(this.sandboxes.delete(e),n.ttl&&clearTimeout(n.ttl),n.child.exitCode===null&&!n.child.killed&&n.child.kill("SIGTERM"))}};Qe.ProcessSandboxDriver=fd;function dE(t={},e=process.env){let n=["PATH","HOME","LANG","LC_ALL","TMPDIR","TERM","NODE_ENV","CLAUDE_CODE_PATH","CODEX_PATH","AGENTHIPPO_CUSTOM_ENGINES_DIR","AGENTHIPPO_NO_AUTO_INSTALL","AGENTHIPPO_DATA_MCP_URL","AGENTHIPPO_LITELLM_BASE_URL"],r={};for(let i of n){let o=e[i];o&&(r[i]=o)}let s=t.allowProviderKeyPassthrough??lE(e);for(let i of Qe.PROVIDER_KEY_PASSTHROUGH_VARS){let o=e[i];if(o){if(!s){t.logger?.warn(`[Sandbox] ${i} is set but was NOT passed into the sandbox: a raw provider key in a sandbox can call the provider directly, around the inference proxy and its spend cap. Cursor packs need it and cannot be proxied \u2014 set AGENTHIPPO_SANDBOX_ALLOW_PROVIDER_KEY=1 to allow it and accept that this sandbox holds a provider credential.`);continue}r[i]=o}}return r}function yR(t){return t.replace(/[^a-zA-Z0-9_-]/g,"").slice(0,32)||"session"}});var pd=S(gt=>{"use strict";var wR=gt&&gt.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,s)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),AR=gt&&gt.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),gE=gt&&gt.__importStar||(function(){var t=function(e){return t=Object.getOwnPropertyNames||function(n){var r=[];for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(r[r.length]=s);return r},t(e)};return function(e){if(e&&e.__esModule)return e;var n={};if(e!=null)for(var r=t(e),s=0;s<r.length;s++)r[s]!=="default"&&wR(n,e,r[s]);return AR(n,e),n}})();Object.defineProperty(gt,"__esModule",{value:!0});gt.DEPRECATED_SANDBOX_ENV_ALIASES=void 0;gt.dockerExec=bR;gt.alignSandboxWorkspaceOwnership=vR;gt.resolveSandboxImageUser=mE;gt.ensureSandboxStateDir=OR;gt.sandboxScriptArg=NR;gt.applyDeprecatedSandboxEnvAliases=_E;gt.loadWarrantKeypair=CR;gt.mintSandboxInferenceWarrant=kR;var SR=require("node:child_process"),ko=gE(require("node:fs")),TR=gE(require("node:path")),hE=Mi();function bR(t){return new Promise(e=>{(0,SR.execFile)("docker",t,{maxBuffer:8<<20},(n,r,s)=>{if(n){let i=typeof n.code=="number"?n.code:1;e({stdout:`${r??""}${s??""}`,code:i});return}e({stdout:r??"",stderr:s??"",code:0})})})}async function vR(t){let e=t.writable.map(i=>i.includes(":")?i.slice(0,i.indexOf(":")):i);if(e.length===0)return;let n=await mE(t.exec,t.image);if(!n){t.logger?.warn(`[Sandbox] could not determine the sandbox image's uid; if turns fail with EACCES in the workspace, run: chown -R <image-uid> ${e.join(" ")}`);return}if(n.uid===0)return;let{uid:r,gid:s}=n;for(let i of e)try{let o=EE(i,r,s);o>0&&t.logger?.info(`[Sandbox] aligned ${o} path(s) under ${i} to the sandbox image's uid ${r}:${s}`)}catch(o){t.logger?.warn(`[Sandbox] could not align ownership of ${i} for the sandbox (uid ${r}): ${o instanceof Error?o.message:String(o)}. Run: chown -R ${r}:${s} ${i}`)}}async function mE(t,e){let n=await pE(t,e,"-u");if(n!==void 0)return{uid:n,gid:await pE(t,e,"-g")??n}}function OR(t,e){if(ko.mkdirSync(t,{recursive:!0}),e&&e.uid!==0)try{EE(t,e.uid,e.gid)}catch{}return t}async function pE(t,e,n){let r=await t(["run","--rm","--network","none","--entrypoint","id",e,n]);if(r.code!==0)return;let s=Number.parseInt(r.stdout.trim(),10);return Number.isInteger(s)?s:void 0}function EE(t,e,n){let r=0,s=i=>{let o=ko.lstatSync(i);if((o.uid!==e||o.gid!==n)&&(ko.lchownSync(i,e,n),r++),o.isDirectory())for(let a of ko.readdirSync(i))s(TR.join(i,a))};return ko.existsSync(t)?(s(t),r):0}var IR=["/$bunfs","/snapshot"];function PR(t){return t.replace(/\\/g,"/").replace(/^[A-Za-z]:/,"")}function NR(t=process.argv,e=process.execPath){let n=t[1];if(!n||n===e)return[];let r=PR(n);return IR.some(s=>r.startsWith(s))?[]:[n]}gt.DEPRECATED_SANDBOX_ENV_ALIASES=[["AGENTHIPPO_CELL","AGENTHIPPO_SANDBOX"],["AGENTHIPPO_CELL_TIER","AGENTHIPPO_SANDBOX_TIER"],["AGENTHIPPO_CELL_SOCKET_DIR","AGENTHIPPO_SANDBOX_SOCKET_DIR"],["AGENTHIPPO_CELL_STRICT_EGRESS","AGENTHIPPO_SANDBOX_STRICT_EGRESS"],["AGENTHIPPO_CELL_ALLOW_PROVIDER_KEY","AGENTHIPPO_SANDBOX_ALLOW_PROVIDER_KEY"]];var RR=new Set;function _E(t=process.env,e=r=>console.warn(r),n=RR){let r=[];for(let[s,i]of gt.DEPRECATED_SANDBOX_ENV_ALIASES){let o=t[s];if(!(o===void 0||o==="")){if(t[i]!==void 0&&t[i]!==""){n.has(s)||(n.add(s),e(`[Sandbox] DEPRECATED: ${s} is set but ${i} is also set \u2014 using ${i} and IGNORING ${s}. Remove ${s}; it was renamed in the cell \u2192 sandbox migration.`));continue}t[i]=o,r.push(i),n.has(s)||(n.add(s),e(`[Sandbox] DEPRECATED: ${s} was renamed to ${i} in the cell \u2192 sandbox migration. The old value is being honoured for now, but it will stop working \u2014 set ${i}=${o} instead.`))}}return r}_E();function CR(t){let e=process.env.AGENTHIPPO_WARRANT_PRIVATE_KEY?.trim(),n=process.env.AGENTHIPPO_WARRANT_KID?.trim();if(e){let i=require("node:crypto").createPublicKey(e).export({type:"spki",format:"pem"}).toString();return{privateKeyPem:e,publicKeyPem:i,kid:n||"default"}}let r=(0,hE.generateWarrantKeypair)(n);return t?.info(`[Warrant] no AGENTHIPPO_WARRANT_PRIVATE_KEY \u2014 generated an ephemeral key (kid=${r.kid}). Configure gateways with:
505
- GATEWAY_SANDBOX_WARRANT_KEYS=${JSON.stringify({[r.kid]:r.publicKeyPem})}`),r}function kR(t,e){return(0,hE.mintWarrant)({...e,aud:"inference"},t)}});var md=S(hd=>{"use strict";Object.defineProperty(hd,"__esModule",{value:!0});hd.createPackRunner=LR;var $R=oi(),DR=Er(),gd=Wn();function LR(t){return(0,$R.createHeadlessRunner)({storagePath:t.storagePath,analyticsSessionsDir:t.analyticsSessionsDir,packId:t.packId,packVersion:t.packVersion,provenance:t.provenance,bundledPromptsDir:(0,gd.findBundledBasePromptsDir)(),apiKey:t.credentials.apiKey,baseUrl:t.credentials.baseUrl,useLiteLLM:t.credentials.useLiteLLM,litellmApiKey:t.credentials.litellmApiKey,openaiApiKey:t.credentials.openaiApiKey,anthropicApiKey:t.credentials.anthropicApiKey,logger:t.logger,freshState:t.freshState??!1,claudeCodeExecutablePath:(0,gd.findClaudeCodePath)(),codexExecutablePath:(0,gd.findCodexPath)(),permissionHandler:t.permissionHandler,cliEnvPatch:(0,DR.buildCliEnvPatch)({cliPath:process.execPath,workspaceRoot:t.workspaceRoot,agentId:t.packId,chatSessionId:t.chatSessionId,baseEnv:process.env,omitGatewayToken:t.omitGatewayToken}),...t.claudeCheapModel?{engineSettings:{claudeCheapModel:t.claudeCheapModel}}:{}})}});var RE=S(On=>{"use strict";var MR=On&&On.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,s)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),GR=On&&On.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),UR=On&&On.__importStar||(function(){var t=function(e){return t=Object.getOwnPropertyNames||function(n){var r=[];for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(r[r.length]=s);return r},t(e)};return function(e){if(e&&e.__esModule)return e;var n={};if(e!=null)for(var r=t(e),s=0;s<r.length;s++)r[s]!=="default"&&MR(n,e,r[s]);return GR(n,e),n}})();Object.defineProperty(On,"__esModule",{value:!0});On.getEvidenceShipStatus=OE;On.validateEvidenceUrl=PE;On.resolveSessionShipConfig=VR;On.redactSessionLine=NE;On.startSessionShipper=KR;var fi=UR(require("path")),qn=require("fs"),SE=require("crypto"),HR=require("zlib"),jR=Pi(),TE=yo(),Tc="AGENTHIPPO_EVIDENCE_SHIP",$o="AGENTHIPPO_EVIDENCE_URL",yE="AGENTHIPPO_EVIDENCE_SHIP_TOKEN",xR="AGENTHIPPO_EVIDENCE_SHIP_INTERVAL_SEC",bE="AGENTHIPPO_EVIDENCE_SHIP_SINCE_DAYS",vE="AGENTHIPPO_EVIDENCE_SHIP_DRAIN_TIMEOUT_SEC",bc="AGENTHIPPO_EVIDENCE_ALLOW_INSECURE_URL",Ed=30,_d=30,BR=/(^|_)(input|output|result|prompt|completion|content|text|messages?)(_|$)|preview$/i,yd={enabled:!1,disabledReason:"not-configured",consecutiveFailures:0,recordsStaged:0,recordsShipped:0,recordsSkippedTooOld:0,filesSkippedTooOld:0,writeFailures:0,contentCapture:!1};function OE(){return{...yd,writeFailures:(0,TE.getSessionEventWriterStats)().failed}}function ji(t){yd={...yd,...t}}function wd(t){return["1","true","yes","on"].includes((t??"").trim().toLowerCase())}function IE(t){return wd(t[bc])||wd(t.EVIDENCE_ALLOW_INSECURE_URL)}var FR=new Set(["localhost","127.0.0.1","::1","[::1]","0.0.0.0"]);function PE(t,e=process.env){let n;try{n=new URL(t)}catch{return{error:`${$o} is not a valid URL: ${JSON.stringify(t)}`}}if(n.protocol==="https:")return{url:n.toString().replace(/\/$/,"")};if(n.protocol!=="http:")return{error:`${$o} must be https (got ${n.protocol.replace(":","")})`};if(FR.has(n.hostname))return{url:n.toString().replace(/\/$/,"")};if(IE(e)){let r=wd(e[bc])?bc:"EVIDENCE_ALLOW_INSECURE_URL";return console.warn(`[evidence-ship] INSECURE: shipping evidence and the ingest token over plaintext http to ${n.host} because ${r} is set. Use https unless this network is genuinely private.`),{url:n.toString().replace(/\/$/,"")}}return{error:`${$o} must use https \u2014 plaintext http to ${n.host} would put the ingest token and the audit trail on the wire. Use https, a loopback address, or set ${bc}=1 (or EVIDENCE_ALLOW_INSECURE_URL=1) if the network is genuinely private.`}}function VR(t,e,n,r=process.env){if(r[Tc]==="0"||r[Tc]?.toLowerCase()==="false"){console.warn(`
504
+ `,E=await createPullRequest(p,`[${n}] Add ${r} v${s}`,h,g);return e&&(0,utils_1.logInfo)(e,`[Store] OK Created PR: ${E.url}`),{prUrl:E.url,prNumber:E.number,tagName:c}}function parseGitHubUrl(t){return(0,shared_1.parseGitHubUrl)(t,exports.STORE_CONFIG.owner,exports.STORE_CONFIG.repo)}async function detectArtifactType(t,e,n,r,s){let i=r?`${r}/`:"",o=n||"main",a=async c=>{let l=`https://api.github.com/repos/${t}/${e}/contents/${i}${c}?ref=${o}`;try{return(await fetch(l,{headers:{Accept:"application/vnd.github.v3+json","User-Agent":"AgentIDE"}})).ok}catch{return!1}};if(s&&(0,utils_1.logInfo)(s,`[Store] Detecting artifact type for ${t}/${e}/${i}...`),await a("agent.yaml"))return"pack";if(await a("SKILL.md"))return"skill";if(await a(".mcp.json")||await a("mcp.json"))return"mcp";if(await a("engine.manifest.json"))return"engine";if(await a("view.yaml")&&await a("panel-entry.yaml"))return"view";throw new Error(`Cannot detect artifact type in ${t}/${e}${r?`/${r}`:""}. Expected agent.yaml, SKILL.md, .mcp.json, engine.manifest.json, or view.yaml with panel-entry.yaml`)}exports.parseStoreUrl=shared_1.parseStoreUrl;function isStoreUrl(t){return(0,shared_1.isStoreUrl)(t,exports.STORE_CONFIG.owner,exports.STORE_CONFIG.repo)}async function listStoreIndex(t,e){let n=[],r=t?[(0,shared_1.getStorePath)(t)]:[exports.STORE_CONFIG.paths.packs,exports.STORE_CONFIG.paths.skills,exports.STORE_CONFIG.paths.mcp,exports.STORE_CONFIG.paths.engines,exports.STORE_CONFIG.paths.spotlightViews];for(let s of r){let i=`https://api.github.com/repos/${exports.STORE_CONFIG.owner}/${exports.STORE_CONFIG.repo}/contents/${s}`;try{let o=await fetch(i,{headers:{Accept:"application/vnd.github.v3+json","User-Agent":"AgentIDE"}});if(!o.ok){e&&(0,utils_1.logInfo)(e,`[Store] No ${s} directory found`);continue}let a=await o.json();for(let c of a)if(c.type==="dir"){let l=s===exports.STORE_CONFIG.paths.packs?"pack":s===exports.STORE_CONFIG.paths.skills?"skill":s===exports.STORE_CONFIG.paths.mcp?"mcp":s===exports.STORE_CONFIG.paths.engines?"engine":"view";n.push({type:l,slug:c.name,path:c.path})}}catch(o){e&&(0,utils_1.logInfo)(e,`[Store] Error listing ${s}: ${o}`)}}return n}exports.formatStoreUrl=shared_1.formatStoreUrl});var Sc=S(ne=>{"use strict";Object.defineProperty(ne,"__esModule",{value:!0});ne.DENY_SCOPE_ALIASES=ne.DENY_MODE_ALIASES=ne.STRICTEST_DENY_MODE=ne.DENY_MODES=ne.DENY_SCOPES=ne.STRICTEST_ON_BREACH=ne.ON_BREACH_ALIASES=ne.ON_BREACH_ACTIONS=ne.DEPRECATED_CAP_SPELLINGS=ne.LEASE_CAP_ALIASES=ne.LEASE_CAP_FIELDS=void 0;ne.parseCapPolicy=Fm;ne.parseLease=FN;ne.LEASE_CAP_FIELDS={maxTurnsPerSession:{kind:"positive-int"},maxSessionSeconds:{kind:"positive-int"},maxConcurrentSandboxes:{kind:"positive-int"}};ne.LEASE_CAP_ALIASES={maxConcurrentCells:"maxConcurrentSandboxes"};ne.DEPRECATED_CAP_SPELLINGS={maxConcurrentCells:"maxConcurrentSandboxes",AGENTHIPPO_MAX_CONCURRENT_CELLS:"AGENTHIPPO_MAX_CONCURRENT_SANDBOXES","destroy-cell":"destroy-sandbox","--max-concurrent-cells":"--max-concurrent-sandboxes"};ne.ON_BREACH_ACTIONS={"revoke-inference":{strictness:1},"destroy-sandbox":{strictness:2}};ne.ON_BREACH_ALIASES={"destroy-cell":"destroy-sandbox"};ne.STRICTEST_ON_BREACH=Object.keys(ne.ON_BREACH_ACTIONS).reduce((t,e)=>ne.ON_BREACH_ACTIONS[t].strictness>=ne.ON_BREACH_ACTIONS[e].strictness?t:e);ne.DENY_SCOPES=["session","user","pack"];ne.DENY_MODES={drain:{strictness:1},kill:{strictness:2}};ne.STRICTEST_DENY_MODE="kill";ne.DENY_MODE_ALIASES={};ne.DENY_SCOPE_ALIASES={};var od=t=>typeof t=="object"&&t!==null&&!Array.isArray(t);function xN(t,e){return typeof e!="number"?{ok:!1,reason:`${t} must be a number, got ${typeof e} (${JSON.stringify(e)})`}:Number.isFinite(e)?e<=0?{ok:!1,reason:`${t} must be greater than 0, got ${e} (omit the field for "unbounded")`}:Number.isInteger(e)?{ok:!0,value:e}:{ok:!1,reason:`${t} must be a whole number, got ${e}`}:{ok:!1,reason:`${t} must be finite, got ${e}`}}function Fm(t,e="caps"){if(t==null)return{ok:!0,caps:{},warnings:[]};if(!od(t))return{ok:!1,reason:`${e} must be an object`};let n=[],r={};for(let[i,o]of Object.entries(t)){if(o==null||i==="onBreach")continue;let a=i in ne.LEASE_CAP_FIELDS?i:ne.LEASE_CAP_ALIASES[i];if(!a){n.push(`${e}.${i} is not a cap this build understands and is NOT being enforced`);continue}let c=xN(`${e}.${i}`,o);if(!c.ok)return{ok:!1,reason:c.reason};r[a]=c.value}let s=t.onBreach;if(s!=null){if(typeof s!="string")return{ok:!1,reason:`${e}.onBreach must be a string, got ${typeof s}`};let i=s in ne.ON_BREACH_ACTIONS?s:ne.ON_BREACH_ALIASES[s];i?r.onBreach=i:(r.onBreach=ne.STRICTEST_ON_BREACH,n.push(`${e}.onBreach="${s}" is not an action this build understands. Failing CLOSED to "${ne.STRICTEST_ON_BREACH}" (the strictest known action). Known actions: ${Object.keys(ne.ON_BREACH_ACTIONS).join(", ")}.`))}return{ok:!0,caps:r,warnings:n}}function BN(t,e){if(!od(t))return{ok:!1,reason:`deny[${e}] must be an object`};let n=[],r=t.scope;if(typeof r!="string")return{ok:!1,reason:`deny[${e}].scope must be a string`};let s=ne.DENY_SCOPES.includes(r)?r:ne.DENY_SCOPE_ALIASES[r];if(!s)return{ok:!1,reason:`deny[${e}].scope "${r}" is not a scope this build understands (known: ${ne.DENY_SCOPES.join(", ")})`};if(typeof t.match!="string"||t.match.length===0)return{ok:!1,reason:`deny[${e}].match must be a non-empty string`};let i=t.mode;if(typeof i!="string")return{ok:!1,reason:`deny[${e}].mode must be a string`};let o=i in ne.DENY_MODES?i:ne.DENY_MODE_ALIASES[i];o||(o=ne.STRICTEST_DENY_MODE,n.push(`deny[${e}].mode="${i}" is not a mode this build understands. Failing CLOSED to "${ne.STRICTEST_DENY_MODE}". Known modes: ${Object.keys(ne.DENY_MODES).join(", ")}.`));let a={scope:s,match:t.match,mode:o};if(t.reason!==void 0){if(typeof t.reason!="string")return{ok:!1,reason:`deny[${e}].reason must be a string`};a.reason=t.reason}if(t.until!==void 0&&t.until!==null){if(typeof t.until!="number"||!Number.isFinite(t.until))return{ok:!1,reason:`deny[${e}].until must be a finite epoch-seconds number`};a.until=t.until}if(t.user!==void 0&&t.user!==null){if(typeof t.user!="string")return{ok:!1,reason:`deny[${e}].user must be a string`};a.user=t.user}if(t.followUser!==void 0&&t.followUser!==null){if(typeof t.followUser!="boolean")return{ok:!1,reason:`deny[${e}].followUser must be a boolean`};a.followUser=t.followUser}return{ok:!0,rule:a,warnings:n}}function FN(t){if(!od(t))return{ok:!1,reason:"lease must be a JSON object"};let e=[];if(typeof t.pack!="string"||t.pack.length===0)return{ok:!1,reason:"lease.pack must be a non-empty string"};if(typeof t.enabled!="boolean")return{ok:!1,reason:`lease.enabled must be a boolean, got ${typeof t.enabled}`};if(typeof t.expiresAt!="number"||!Number.isFinite(t.expiresAt))return{ok:!1,reason:`lease.expiresAt must be a finite epoch-seconds number, got ${JSON.stringify(t.expiresAt)}`};let n={pack:t.pack,enabled:t.enabled,expiresAt:t.expiresAt};for(let r of["version","imageDigest","reason"]){let s=t[r];if(s!=null){if(typeof s!="string")return{ok:!1,reason:`lease.${r} must be a string, got ${typeof s}`};n[r]=s}}for(let r of["requireSignedPack","requireSignedLease","allowServiceTurns"]){let s=t[r];if(s!=null){if(typeof s!="boolean")return{ok:!1,reason:`lease.${r} must be a boolean, got ${typeof s}`};n[r]=s}}if(t.caps!==void 0&&t.caps!==null){let r=Fm(t.caps,"lease.caps");if(!r.ok)return{ok:!1,reason:r.reason};n.caps=r.caps,e.push(...r.warnings)}if(t.deny!==void 0&&t.deny!==null){if(!Array.isArray(t.deny))return{ok:!1,reason:"lease.deny must be an array"};let r=[];for(let s=0;s<t.deny.length;s++){let i=BN(t.deny[s],s);if(!i.ok)return{ok:!1,reason:i.reason};r.push(i.rule),e.push(...i.warnings)}n.deny=r}return{ok:!0,lease:n,warnings:e}}});var Ro=S(ee=>{"use strict";Object.defineProperty(ee,"__esModule",{value:!0});ee.MAX_LEASE_ENVELOPE_TTL_SECONDS=ee.LEASE_JWS_TYP=ee.LeaseDeniedError=ee.LEASE_MAX_STALENESS_ENV=ee.DEFAULT_LEASE_MAX_STALENESS_SECONDS=ee.MIN_LEASE_POLL_SECONDS=ee.DEFAULT_LEASE_POLL_SECONDS=void 0;ee.resolveLeasePollSeconds=ad;ee.leaseCacheSecondsFor=cd;ee.effectiveKillLatencySeconds=KN;ee.leaseMaxStalenessFromEnv=qm;ee.resolveAllowServiceTurns=qN;ee.describeServiceTurnGate=YN;ee.denyVerdict=Ym;ee.resolveFollowedUsers=JN;ee.leaseIsDead=zN;ee.policyVersion=QN;ee.assertAdmitted=ZN;ee.signLease=eR;ee.verifySignedLease=Jm;ee.requireSignedLease=zm;ee.createLeaseSource=tR;var VN=require("crypto"),Wm=Mi(),Km=Sc(),WN=Po();ee.DEFAULT_LEASE_POLL_SECONDS=30;ee.MIN_LEASE_POLL_SECONDS=5;function ad(t){let e=typeof t=="number"&&Number.isFinite(t)?t:ee.DEFAULT_LEASE_POLL_SECONDS;return Math.max(ee.MIN_LEASE_POLL_SECONDS,Math.floor(e))}function cd(t){return ad(t)}function KN(t){let e=ad(t);return e+cd(e)}ee.DEFAULT_LEASE_MAX_STALENESS_SECONDS=1440*60;ee.LEASE_MAX_STALENESS_ENV="AGENTHIPPO_LEASE_MAX_STALENESS_SECONDS";function qm(t=process.env){let e=t[ee.LEASE_MAX_STALENESS_ENV]?.trim();if(e===void 0||e==="")return ee.DEFAULT_LEASE_MAX_STALENESS_SECONDS;let n=Number(e);return!Number.isFinite(n)||n<0?ee.DEFAULT_LEASE_MAX_STALENESS_SECONDS:Math.floor(n)}function qN(t){return t.managed?t.lease===!0?{allowed:!0,gate:"lease_allows"}:{allowed:!1,gate:t.lease===!1?"lease_denies":"lease_absent_field"}:{allowed:!0,gate:"unmanaged_no_lease"}}function YN(t){switch(t){case"lease_allows":return"permitted by the control plane (lease.allowServiceTurns)";case"unmanaged_no_lease":return"permitted: no control plane configured, so AGENTHIPPO_SERVICE_USER is the only gate";case"lease_denies":return"refused: the control plane set lease.allowServiceTurns=false";case"lease_absent_field":return"refused: this is a managed deployment and the lease does not set allowServiceTurns (absent means deny \u2014 enable it in the console)"}}function Ym(t,e,n){if(!t?.deny?.length)return{denied:!1};let r=n??Math.floor(Date.now()/1e3),s=e.sessionKey.indexOf("--"),i=s>=0?e.sessionKey.slice(s+2):e.sessionKey,o={denied:!1};for(let a of t.deny){if(a.until!==void 0&&a.until<=r)continue;let c=!1;if(a.scope==="pack"?c=a.match===e.pack:a.scope==="session"?(c=a.match===e.sessionKey||a.match===i,c&&a.user!==void 0&&e.userId!==void 0&&a.user!==e.userId&&(c=!1),!c&&a.followUser!==!1&&e.userId!==void 0&&XN(a,e.userId,e.followedUsers)&&(c=!0)):a.scope==="user"&&(c=e.userId!==void 0&&a.match===e.userId||e.userHash!==void 0&&e.sessionKey.startsWith(`u${e.userHash(a.match)}--`)),!c)continue;let l=`${a.mode==="kill"?"stopped":"draining"} by the control plane${a.reason?`: ${a.reason}`:""}`;if(a.mode==="kill")return{denied:!0,mode:"kill",reason:l};o.denied||(o={denied:!0,mode:"drain",reason:l})}return o}var Xm=t=>`${t.scope}:${t.match}`;function XN(t,e,n){return n?.get(Xm(t))?.has(e)??!1}function JN(t,e,n){let r=new Map;if(!t?.deny?.length)return r;let s=n??Math.floor(Date.now()/1e3);for(let i of t.deny){if(i.scope!=="session"||i.followUser===!1||i.until!==void 0&&i.until<=s)continue;let o=new Set;for(let[a,c]of e){let l=a.indexOf("--"),f=l>=0?a.slice(l+2):a;i.match!==a&&i.match!==f||i.user!==void 0&&i.user!==c||o.add(c)}o.size>0&&r.set(Xm(i),o)}return r}function zN(t,e){if(!t)return{dead:!1};let n=e??Math.floor(Date.now()/1e3);return t.enabled?t.expiresAt<=n?{dead:!0,reason:`lease expired at ${new Date(t.expiresAt*1e3).toISOString()}`}:{dead:!1}:{dead:!0,reason:`kill switch active${t.reason?`: ${t.reason}`:""}`}}function QN(t){if(!t)return;let{expiresAt:e,...n}=t,r=s=>Array.isArray(s)?s.map(r):s&&typeof s=="object"?Object.fromEntries(Object.keys(s).sort().map(i=>[i,r(s[i])])):s;return(0,VN.createHash)("sha256").update(JSON.stringify(r(n))).digest("hex")}var gs=class extends Error{constructor(e){super(e),this.name="LeaseDeniedError"}};ee.LeaseDeniedError=gs;function ZN(t,e){if(!t)return;let n=e.nowSeconds??Math.floor(Date.now()/1e3);if(!t.enabled)throw new gs(`kill switch active for pack ${e.pack}${t.reason?`: ${t.reason}`:""}`);if(t.pack!==e.pack)throw new gs(`lease is for pack ${t.pack}, not ${e.pack}`);if(t.expiresAt<=n)throw new gs(`lease for ${e.pack} expired at ${new Date(t.expiresAt*1e3).toISOString()}`);if(t.version&&t.version!==e.version)throw new gs(`pack ${e.pack} is pinned to ${t.version}; refusing to start ${e.version} (rollback in force)`);if(t.imageDigest&&e.image&&!e.image.includes(t.imageDigest))throw new gs(`image for ${e.pack} does not match the leased digest ${t.imageDigest}`);if(e.sessionKey){let r=Ym(t,{sessionKey:e.sessionKey,pack:e.pack,userHash:e.userHash,userId:e.userId,followedUsers:e.followedUsers},n);if(r.denied)throw new gs(r.reason??"stopped by the control plane")}}ee.LEASE_JWS_TYP="agenthippo-lease+jws";ee.MAX_LEASE_ENVELOPE_TTL_SECONDS=3600;function eR(t,e,n){let r=n.nowSeconds??Math.floor(Date.now()/1e3),s=Math.min(n.ttlSeconds??300,ee.MAX_LEASE_ENVELOPE_TTL_SECONDS),i={lease:t,aud:n.instanceId??"*",sub:t.pack,iat:r,exp:r+s,...n.iss?{iss:n.iss}:{}};return(0,Wm.signCompactJws)({typ:ee.LEASE_JWS_TYP,kid:e.kid},i,e.privateKeyPem)}function Jm(t,e,n={}){if(Object.keys(e).length===0)return{ok:!1,reason:"no trusted lease-signing keys are configured on this instance"};let r=(0,Wm.verifyCompactJws)(t,e,{typ:ee.LEASE_JWS_TYP});if(!r.ok)return{ok:!1,reason:`lease signature: ${r.reason}`};let s=r.payload,i=n.nowSeconds??Math.floor(Date.now()/1e3),o=n.clockSkewSeconds??60;if(typeof s.iat!="number"||!Number.isFinite(s.iat))return{ok:!1,reason:"lease envelope has no issued-at"};if(typeof s.exp!="number"||!Number.isFinite(s.exp))return{ok:!1,reason:"lease envelope has no expiry"};if(s.exp-s.iat>ee.MAX_LEASE_ENVELOPE_TTL_SECONDS)return{ok:!1,reason:`lease envelope lifetime ${s.exp-s.iat}s exceeds the ${ee.MAX_LEASE_ENVELOPE_TTL_SECONDS}s cap`};if(s.exp+o<=i)return{ok:!1,reason:`lease envelope expired at ${new Date(s.exp*1e3).toISOString()}`};if(s.iat-o>i)return{ok:!1,reason:"lease envelope is issued in the future"};if(n.minIat!==void 0&&s.iat<n.minIat)return{ok:!1,reason:`lease envelope is older than one already accepted (replay/rollback: iat ${s.iat} < ${n.minIat})`};if(n.instanceId!==void 0&&s.aud!=="*"&&s.aud!==n.instanceId)return{ok:!1,reason:`lease envelope is for instance ${s.aud}, not ${n.instanceId}`};let a=(0,Km.parseLease)(s.lease);return a.ok?s.sub!==a.lease.pack?{ok:!1,reason:`lease envelope subject ${s.sub} does not match lease.pack ${a.lease.pack}`}:{ok:!0,lease:a.lease,claims:s}:{ok:!1,reason:`signed lease is malformed: ${a.reason}`}}function zm(t,e){return!!t||!!e}var Vm=t=>/^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/.test(t);function tR(t){let e=t.staticLease,n=0,r,s,i=!1,o=!1,a,c=!1,l=!1,f=!1,u=t.cacheSeconds??cd(ee.DEFAULT_LEASE_POLL_SECONDS),d=t.maxStalenessSeconds??qm(t.env),p=t.fetchImpl??fetch,g=()=>zm(o,t.requireSignedLease),m=E=>({...e??{pack:"",expiresAt:0},enabled:!1,reason:`the control plane has not been reachable for ${E}s, past the ${d}s staleness ceiling (${ee.LEASE_MAX_STALENESS_ENV}). Refusing work rather than running on a lease that can no longer be revoked. Set ${ee.LEASE_MAX_STALENESS_ENV}=0 to accept unbounded staleness.`}),h=(E,_)=>{let y=E.trim(),b,T;if(Vm(y))b=y;else{try{T=JSON.parse(y)}catch(A){return{ok:!1,reason:`lease body is not JSON: ${A instanceof Error?A.message:String(A)}`}}typeof T=="string"&&Vm(T.trim())?b=T.trim():T&&typeof T=="object"&&typeof T.lease=="string"&&(b=T.lease.trim())}if(b){let A=Jm(b,t.signingKeys?.()??{},{instanceId:t.instanceId,minIat:a,nowSeconds:_});return A.ok?(a=A.claims.iat,{ok:!0,lease:A.lease,signed:!0}):{ok:!1,reason:A.reason}}if(g())return{ok:!1,reason:'a signed lease is required but the control plane returned an unsigned one (expected a compact JWS body or {"lease":"<jws>"})'};let O=(0,Km.parseLease)(T);if(!O.ok)return{ok:!1,reason:O.reason};for(let A of O.warnings)t.logger?.warn(`[Lease] ${A}`);return{ok:!0,lease:O.lease,signed:!1}};return{status(E){let _=E??Math.floor(Date.now()/1e3),y=r===void 0?void 0:_-r;return{signed:i,requireSignedLease:g(),lastGoodAt:r,stalenessSeconds:y,maxStalenessSeconds:d,failClosed:d>0&&y!==void 0&&y>d,lastError:s}},async get(E){let _=E??Math.floor(Date.now()/1e3);if(!t.url)return e;if(!f){f=!0;let y=(0,WN.assertSecureTrustUrl)(t.url,"AGENTHIPPO_LEASE_URL",t.env??process.env);if(y.ok)for(let b of y.warnings)t.logger?.warn(`[Lease] ${b}`);else g()?t.logger?.warn(`[Lease] INSECURE LEASE CHANNEL \u2014 ${y.reason} Signed leases are required here, so the policy itself is still verified \u2014 but the channel is not: anyone on the path can read this instance's identity, pack and version, and can delay a kill switch by up to ${ee.MAX_LEASE_ENVELOPE_TTL_SECONDS}s by replaying the last envelope. requireSignedLease is not a substitute for https; serve the lease over https.`):t.logger?.warn(`[Lease] INSECURE LEASE CHANNEL \u2014 ${y.reason} Anyone on the path can lift this instance's kill switch, widen its caps or change its version pin. Continuing to poll (refusing would disable the kill switch entirely), but this deployment is not governable until the lease is signed: set requireSignedLease and have the control plane sign leases.`)}if(e&&_-n<u)return e;try{let y={accept:"application/json, text/plain"};for(let[A,v]of Object.entries(t.identity?.()??{}))v!==void 0&&v!==""&&(y[`x-agenthippo-${A}`]=String(v));let b=await p(t.url,{headers:y});if(!b.ok)throw new Error(`lease fetch ${b.status}`);let T=typeof b.text=="function"?await b.text():JSON.stringify(await b.json()),O=h(T,_);if(!O.ok)throw new Error(O.reason);return O.signed?(i=!0,O.lease.requireSignedLease&&(o=!0)):l||(l=!0,t.logger?.warn(`[Lease] running on an UNSIGNED lease. Anyone who can answer or intercept ${t.url} can lift this instance's kill switch, widen its caps and change its version pin. Have the control plane sign leases (ES256 compact JWS) and set requireSignedLease.`)),e=O.lease,n=_,r=_,s=void 0,c=!1,e}catch(y){s=y instanceof Error?y.message:String(y),t.logger?.warn(`[Lease] fetch failed, using cached lease: ${s}`),r===void 0&&(r=_);let b=_-r;return d>0&&b>d?(c||(c=!0,t.logger?.warn(`[Lease] STALENESS CEILING PASSED \u2014 no successful lease refresh for ${b}s (ceiling ${d}s). Failing closed: turns are refused until the control plane is reachable.`)),m(b)):e}}}}});var Tc=S(Ue=>{"use strict";Object.defineProperty(Ue,"__esModule",{value:!0});Ue.CapMeter=Ue.CAP_ENV_ALIASES=Ue.parseCapPolicy=Ue.STRICTEST_ON_BREACH=Ue.ON_BREACH_ALIASES=Ue.ON_BREACH_ACTIONS=Ue.LEASE_CAP_FIELDS=Ue.LEASE_CAP_ALIASES=Ue.DEPRECATED_CAP_SPELLINGS=void 0;Ue.resolveOnBreach=Qm;Ue.mergeCaps=rR;Ue.capsAreUnbounded=sR;Ue.capsFromEnv=iR;var Ui=Sc(),di=Sc();Object.defineProperty(Ue,"DEPRECATED_CAP_SPELLINGS",{enumerable:!0,get:function(){return di.DEPRECATED_CAP_SPELLINGS}});Object.defineProperty(Ue,"LEASE_CAP_ALIASES",{enumerable:!0,get:function(){return di.LEASE_CAP_ALIASES}});Object.defineProperty(Ue,"LEASE_CAP_FIELDS",{enumerable:!0,get:function(){return di.LEASE_CAP_FIELDS}});Object.defineProperty(Ue,"ON_BREACH_ACTIONS",{enumerable:!0,get:function(){return di.ON_BREACH_ACTIONS}});Object.defineProperty(Ue,"ON_BREACH_ALIASES",{enumerable:!0,get:function(){return di.ON_BREACH_ALIASES}});Object.defineProperty(Ue,"STRICTEST_ON_BREACH",{enumerable:!0,get:function(){return di.STRICTEST_ON_BREACH}});Object.defineProperty(Ue,"parseCapPolicy",{enumerable:!0,get:function(){return di.parseCapPolicy}});Ue.CAP_ENV_ALIASES={AGENTHIPPO_MAX_CONCURRENT_CELLS:"AGENTHIPPO_MAX_CONCURRENT_SANDBOXES"};function Qm(t,e){let n=t?.trim();if(!n)return{action:void 0,warnings:[]};if(n in Ui.ON_BREACH_ACTIONS)return{action:n,warnings:[]};let r=Ui.ON_BREACH_ALIASES[n];return r?{action:r,warnings:[`${e}="${n}" is DEPRECATED; use "${Ui.DEPRECATED_CAP_SPELLINGS[n]??r}". Treating it as "${r}". The old spelling will stop being accepted.`]}:{action:Ui.STRICTEST_ON_BREACH,warnings:[`${e}="${n}" is not a breach action this build understands. FAILING CLOSED to "${Ui.STRICTEST_ON_BREACH}" \u2014 an unreadable enforcement setting must never weaken enforcement. Known actions: ${Object.keys(Ui.ON_BREACH_ACTIONS).join(", ")}.`]}}var nR=1e4;function rR(t,e){let n=t??{},r=e??{},s=(i,o)=>i===void 0?o:o===void 0?i:Math.min(i,o);return{maxTurnsPerSession:s(n.maxTurnsPerSession,r.maxTurnsPerSession),maxSessionSeconds:s(n.maxSessionSeconds,r.maxSessionSeconds),maxConcurrentSandboxes:s(n.maxConcurrentSandboxes,r.maxConcurrentSandboxes),onBreach:n.onBreach==="destroy-sandbox"||r.onBreach==="destroy-sandbox"?"destroy-sandbox":n.onBreach??r.onBreach}}function sR(t){return t.maxTurnsPerSession===void 0&&t.maxSessionSeconds===void 0&&t.maxConcurrentSandboxes===void 0}var ld=class{caps;sessions=new Map;constructor(e){this.caps=e}setCaps(e){this.caps=e}policy(){return this.caps}check(e,n,r=Date.now()){let s=this.sessions.get(e);if(this.caps.maxTurnsPerSession!==void 0&&s&&s.turns>=this.caps.maxTurnsPerSession)return{allowed:!1,cap:"turns",reason:`session turn cap reached (${s.turns}/${this.caps.maxTurnsPerSession})`};if(this.caps.maxSessionSeconds!==void 0&&s){let i=Math.floor((r-s.startedAtMs)/1e3);if(i>=this.caps.maxSessionSeconds)return{allowed:!1,cap:"duration",reason:`session duration cap reached (${i}s/${this.caps.maxSessionSeconds}s)`}}return this.caps.maxConcurrentSandboxes!==void 0&&!s&&n>=this.caps.maxConcurrentSandboxes?{allowed:!1,cap:"concurrency",reason:`instance is at its concurrent sandbox cap (${n}/${this.caps.maxConcurrentSandboxes})`}:{allowed:!0}}record(e,n=Date.now()){let r=this.sessions.get(e);if(r){r.turns+=1;return}if(this.sessions.size>=nR){let s,i=1/0;for(let[o,a]of this.sessions)a.startedAtMs<i&&(i=a.startedAtMs,s=o);s&&this.sessions.delete(s)}this.sessions.set(e,{turns:1,startedAtMs:n})}forget(e){this.sessions.delete(e)}usage(e){let n=this.sessions.get(e);if(n)return{turns:n.turns,ageSeconds:Math.floor((Date.now()-n.startedAtMs)/1e3)}}};Ue.CapMeter=ld;function iR(t=process.env,e=n=>console.warn(`Warning: ${n}`)){let n=i=>{let o=parseInt((i??"").trim(),10);return Number.isFinite(o)&&o>0?o:void 0},r=i=>{let o=n(t[i]);if(o!==void 0)return o;for(let[a,c]of Object.entries(Ue.CAP_ENV_ALIASES)){if(c!==i)continue;let l=n(t[a]);if(l!==void 0)return e(`${a} is DEPRECATED; use ${i}. Honouring it for now.`),l}},s=Qm(t.AGENTHIPPO_CAP_ON_BREACH,"AGENTHIPPO_CAP_ON_BREACH");for(let i of s.warnings)e(i);return{maxTurnsPerSession:r("AGENTHIPPO_MAX_TURNS_PER_SESSION"),maxSessionSeconds:r("AGENTHIPPO_MAX_SESSION_SECONDS"),maxConcurrentSandboxes:r("AGENTHIPPO_MAX_CONCURRENT_SANDBOXES"),onBreach:s.action}}});var eE=S(Co=>{"use strict";Object.defineProperty(Co,"__esModule",{value:!0});Co.effectiveDenyMode=Zm;Co.createGovernor=oR;Co.withGovernor=aR;var bc=Tc(),Hi=Ro();function Zm(t,e){return t==="kill"&&!e?"drain":t}function oR(t){let e=new bc.CapMeter(t.caps),n=(0,bc.capsAreUnbounded)(t.caps),r,s,i,o=new Map,a=t.sandboxes.supportsInFlightTermination!==!1,c=new Map,l=new Set,f=(h,E)=>{try{t.audit?.(h,E)}catch{}},u=1e4,d=(h,E)=>{if(o.size>=u&&!o.has(h)){let _=o.keys().next();_.done||o.delete(_.value)}o.set(h,E)},p=async(h,E)=>{let _=e.policy().onBreach??"revoke-inference";try{_==="destroy-sandbox"?await t.sandboxes.destroySession(h):await t.sandboxes.revokeRoute(h,"inference")}catch(y){t.logger?.warn(`[Governor] ${_} failed for ${h}, destroying instead: ${y instanceof Error?y.message:String(y)}`),await t.sandboxes.destroySession(h).catch(()=>{})}t.logger?.warn(`[Governor] cap breach on ${h}: ${E.reason} \u2014 ${_}`),f("cap_breach",{sessionKey:h,cap:E.cap,reason:E.reason,action:_})},g=async h=>{let E=t.sandboxes.sandboxes();for(let _ of E)await t.sandboxes.destroySession(_.sandboxKey).catch(()=>{});return E.length>0?t.logger?.warn(`[Governor] kill switch: destroyed ${E.length} live sandbox(s) \u2014 ${h}`):a||t.logger?.warn(`[Governor] kill switch: no sandbox driver, so nothing running can be stopped \u2014 in-flight turns will finish and only NEW turns are refused (${h}). Run with --sandbox for true in-flight kill.`),f("kill_switch",{reason:h,destroyed:E.length,inFlightTerminated:a}),E.length},m=async()=>{if(t.getLease)try{let h=await t.getLease(),E=(0,bc.mergeCaps)(h?.caps,t.caps);if(e.setCaps(E),n=(0,bc.capsAreUnbounded)(E),i=h,c=(0,Hi.resolveFollowedUsers)(h,o),!a)for(let y of h?.deny??[]){if(y.mode!=="kill")continue;let b=`${y.scope}:${y.match}`;l.has(b)||(l.add(b),t.logger?.warn(`[Governor] deny(kill) on ${b} DEGRADED TO DRAIN: this deployment has no sandbox driver, so a turn already executing cannot be stopped. It will run to completion; only the next turn is refused. Run serve with --sandbox for a kill that ends work mid-flight.`),f("deny_kill_degraded",{scope:y.scope,match:y.match,effectiveMode:"drain"}))}for(let y of t.sandboxes.sandboxes()){let b=y.sessionKeys.map(T=>({sessionKey:T,v:(0,Hi.denyVerdict)(h,{sessionKey:T,pack:t.pack??"",userHash:t.userHash,userId:o.get(T),followedUsers:c})})).find(({v:T})=>T.denied&&Zm(T.mode,a)==="kill");if(b){await t.sandboxes.destroySession(y.sandboxKey).catch(()=>{});for(let T of y.sessionKeys)o.delete(T);t.logger?.warn(`[Governor] deny(kill) destroyed ${y.sandboxId} \u2014 ${b.v.reason}`),f("session_killed",{sessionKey:b.sessionKey,sandboxId:y.sandboxId,reason:b.v.reason,collateralSessions:y.sessionKeys.filter(T=>T!==b.sessionKey)})}}let _=(0,Hi.leaseIsDead)(h);_.dead?(s=_.reason??"lease revoked",await g(s)):s&&(t.logger?.info("[Governor] lease restored \u2014 accepting turns again"),f("kill_switch_lifted",{}),s=void 0)}catch(h){t.logger?.warn(`[Governor] lease check failed: ${h instanceof Error?h.message:String(h)}`)}};return{async admitTurn(h,E){if(s)return{allowed:!1,reason:`stopped by the control plane: ${s}`};E&&d(h,E);let _=(0,Hi.denyVerdict)(i,{sessionKey:h,pack:t.pack??"",userHash:t.userHash,userId:E??o.get(h),followedUsers:(0,Hi.resolveFollowedUsers)(i,o)});if(_.denied)return{allowed:!1,reason:_.reason};if(t.admitPack){let b=t.admitPack(h,i);if(!b.allowed)return{allowed:!1,reason:b.reason??"refused by pack admission"}}if(n)return{allowed:!0};let y=e.check(h,t.sandboxes.sandboxes().length);return y.allowed||y.cap!=="concurrency"&&await p(h,y),y},recordTurn(h){e.record(h)},killAll:g,refresh:m,start(){if(!t.getLease||r)return;let h=(0,Hi.resolveLeasePollSeconds)(t.pollSeconds)*1e3;r=setInterval(()=>{m()},h),r.unref?.(),m()},stop(){r&&(clearInterval(r),r=void 0)},policy:()=>e.policy()}}function aR(t,e){return{async run(n){let r=n.sessionId??"default",s=await e.admitTurn(r,n.analyticsUserId);return s.allowed?(e.recordTurn(r),t.run(n)):{success:!1,text:"",thinking:"",toolCalls:[],error:s.reason??"refused by policy"}},dispose(){e.stop(),t.dispose()}}}});var aE=S(Ve=>{"use strict";var cR=Ve&&Ve.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,s)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),lR=Ve&&Ve.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),$o=Ve&&Ve.__importStar||(function(){var t=function(e){return t=Object.getOwnPropertyNames||function(n){var r=[];for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(r[r.length]=s);return r},t(e)};return function(e){if(e&&e.__esModule)return e;var n={};if(e!=null)for(var r=t(e),s=0;s<r.length;s++)r[s]!=="default"&&cR(n,e,r[s]);return lR(n,e),n}})();Object.defineProperty(Ve,"__esModule",{value:!0});Ve.ContainerSandboxDriver=Ve.SANDBOX_PACK_DIR=Ve.SANDBOX_WORKSPACE_DIR=Ve.SANDBOX_STATE_DIR=Ve.SANDBOX_SOCKET_DIR_IN_SANDBOX=void 0;Ve.strictEgressFromEnv=sE;Ve.prepareSocketDir=iE;Ve.assertOwnSocket=oE;var uR=$o(require("node:crypto")),Ar=$o(require("node:fs")),dR=$o(require("node:net")),fR=$o(require("node:os")),ko=$o(require("node:path")),tE=Qa();function sE(t=process.env){return t.AGENTHIPPO_SANDBOX_STRICT_EGRESS==="1"}function pR(){let t=[process.env.AGENTHIPPO_SANDBOX_SOCKET_DIR,"/run/agenthippo/sandboxes",process.env.XDG_RUNTIME_DIR?ko.join(process.env.XDG_RUNTIME_DIR,"agenthippo-sandboxes"):void 0,ko.join(fR.tmpdir(),"agenthippo-sandboxes")].filter(e=>!!e);for(let e of t)try{if(Ar.mkdirSync(e,{recursive:!0}),Ar.accessSync(e,Ar.constants.W_OK),e.length>60)continue;return e}catch{}return"/run/agenthippo/sandboxes"}var gR=pR(),hR=9e4,mR=150;Ve.SANDBOX_SOCKET_DIR_IN_SANDBOX="/run/sandbox";Ve.SANDBOX_STATE_DIR="/state";Ve.SANDBOX_WORKSPACE_DIR="/state/workspace";Ve.SANDBOX_PACK_DIR="/app/pack";var ud=class{opts;kind="container";tier=2;sandboxes=new Map;seq=0;instance=uR.randomBytes(2).toString("hex");constructor(e){this.opts=e}async create(e){ER(e.image);let n=`sandbox-${this.instance}-${++this.seq}-${AR(e.sandboxKey)}`,r=this.opts.socketDir??gR,s=ko.join(r,n),i=ko.join(s,"sandbox.sock");Ar.rmSync(s,{recursive:!0,force:!0}),iE(s,this.opts.socketOwner);let o=e.routes.map(h=>({kind:h.kind,network:yR(h.target)})),c=await this.assertRouteNetworks(o)?this.tier:1,l=o[0],f=["run","--detach","--name",n,"--network",l?l.network:"none","--cap-drop","ALL","--security-opt","no-new-privileges","--read-only","--tmpfs","/tmp:rw,exec,nosuid,size=512m",...e.stateDir?["--volume",`${e.stateDir}:${Ve.SANDBOX_STATE_DIR}`]:["--tmpfs",`${Ve.SANDBOX_STATE_DIR}:rw,exec,nosuid,size=512m,mode=1777`],"--volume",`${s}:${Ve.SANDBOX_SOCKET_DIR_IN_SANDBOX}`,"--label",`ai.agenthippo.sandbox=${n}`,"--label",`ai.agenthippo.session=${e.sandboxKey}`,"--label",`ai.agenthippo.tier=${e.tier}`];for(let h of e.fs.readonly)f.push("--volume",nE(h,!0));for(let h of e.fs.writable)f.push("--volume",nE(h,!1));e.limits.memMiB&&f.push("--memory",`${e.limits.memMiB}m`),e.limits.cpu&&f.push("--cpus",e.limits.cpu);for(let[h,E]of Object.entries(e.env??{}))f.push("--env",`${h}=${E}`);f.push("--env",`${tE.SANDBOX_TIER_ENV}=${c}`),f.push(e.image);let u=await this.opts.exec(f);if(u.code!==0)throw await this.opts.exec(["rm","--force",n]),new Error(`failed to create sandbox ${n}: ${u.stdout.trim()||`exit ${u.code}`}`);let d=u.stdout.trim(),p=new Map;l&&p.set(l.kind,l.network);for(let h of o.slice(1)){let E=await this.opts.exec(["network","connect",h.network,n]);if(E.code!==0)throw await this.opts.exec(["rm","--force",n]),new Error(`failed to attach ${h.kind} route for sandbox ${n}: ${E.stdout.trim()}`);p.set(h.kind,h.network)}await this.waitForSocket(n,i);let g={containerId:d,socketPath:i,networks:p};e.limits.ttlSeconds>0&&(g.ttl=setTimeout(()=>{this.destroyById(n)},e.limits.ttlSeconds*1e3),g.ttl.unref?.()),this.sandboxes.set(n,g);let m=this.opts.connectFn??wR;return{id:n,tier:c,endpoint:i,connect:()=>m(i)}}async assertRouteNetworks(e){let n=new Set,r=!0;for(let s of e){if(n.has(s.network))continue;n.add(s.network);let i=await this.opts.exec(["network","inspect","--format","{{.Internal}}",s.network]);if(i.code!==0)throw new Error(`route network "${s.network}" (${s.kind}) does not exist \u2014 a tier-2 sandbox is created on its declared route networks and nothing creates them for you. Create it (\`docker network create --internal ${s.network}\`) and put the ${s.kind} service on it.`);if(i.stdout.trim()!=="true"){if(r=!1,this.opts.strictEgress??sE())throw new Error(`route network "${s.network}" (${s.kind}) is not --internal, and strict egress containment is enabled (AGENTHIPPO_SANDBOX_STRICT_EGRESS=1). A sandbox on this network can reach any host it routes to, so the tier-2 containment claim would be false. Recreate it as internal (\`docker network rm ${s.network} && docker network create --internal ${s.network}\`), or unset AGENTHIPPO_SANDBOX_STRICT_EGRESS to accept a sandbox whose egress is bounded by the network topology instead.`);this.opts.logger?.warn(`route network "${s.network}" (${s.kind}) is not --internal: this sandbox can reach any host that network routes to, so tier-2 egress is bounded by that network's topology, not by the sandbox. This sandbox is therefore reported as tier 1, not tier 2. Make the network internal (or set AGENTHIPPO_SANDBOX_STRICT_EGRESS=1 to refuse outright).`)}}return r}async waitForSocket(e,n){let r=this.opts.socketWaitMs??hR;if(r<=0)return;let s=Date.now()+r;for(;Date.now()<s;){if(Ar.existsSync(n)){try{oE(n,this.opts.socketOwner)}catch(a){throw await this.opts.exec(["rm","--force",e]),a}return}if((await this.opts.exec(["inspect","--format","{{.State.Running}}",e])).stdout.trim()==="false"){let a=await this.opts.exec(["logs","--tail","20",e]);throw await this.opts.exec(["rm","--force",e]),new Error(`sandbox ${e} exited during boot: ${rE(a)}`)}await new Promise(a=>setTimeout(a,mR))}let i=await this.opts.exec(["logs","--tail","20",e]);throw await this.opts.exec(["rm","--force",e]),new Error(`sandbox ${e} did not bind ${n} within ${r/1e3}s: ${rE(i)}`)}async revoke(e,n){let r=this.sandboxes.get(e.id);if(!r)return;if(n==="all")return this.destroyById(e.id);let s=r.networks.get(n);if(!s)throw new tE.RevocationUnsupportedError("container",n);let i=await this.opts.exec(["network","disconnect","--force",s,e.id]);if(i.code!==0)throw new Error(`failed to revoke ${n} for sandbox ${e.id}: ${i.stdout.trim()}`);r.networks.delete(n)}async destroy(e){await this.destroyById(e.id)}async destroyById(e){let n=this.sandboxes.get(e);if(n){this.sandboxes.delete(e),n.ttl&&clearTimeout(n.ttl),await this.opts.exec(["rm","--force",e]);try{Ar.rmSync(ko.dirname(n.socketPath),{recursive:!0,force:!0})}catch{}}}};Ve.ContainerSandboxDriver=ud;function iE(t,e){if(Ar.mkdirSync(t,{recursive:!0}),e&&e.uid!==0)try{Ar.chownSync(t,e.uid,e.gid),Ar.chmodSync(t,448);return}catch{}Ar.chmodSync(t,987)}function oE(t,e,n=typeof process.getuid=="function"?process.getuid():void 0){let r=Ar.lstatSync(t);if(r.isSymbolicLink())throw new Error(`sandbox socket ${t} is a symlink \u2014 refusing to connect`);if(!r.isSocket())throw new Error(`sandbox socket ${t} is not a unix socket \u2014 refusing to connect`);let s=new Set;if(n!==void 0&&s.add(n),e&&s.add(e.uid),s.add(0),!s.has(r.uid))throw new Error(`sandbox socket ${t} is owned by uid ${r.uid}, which is neither this process nor the sandbox \u2014 another local user may have raced the bind. Refusing to connect.`)}function nE(t,e){let n=t.indexOf(":"),[r,s]=n===-1?[t,t]:[t.slice(0,n),t.slice(n+1)];return`${r}:${s}${e?":ro":""}`}function ER(t){let e=/@sha256:[a-f0-9]{64}$/.test(t),n=/^sha256:[a-f0-9]{64}$/.test(t);if(!e&&!n)throw new Error(`sandbox image must be pinned by digest (got "${t}") \u2014 a mutable tag makes signing and rollback unverifiable`)}function rE(t){return`${t.stdout??""}${t.stderr??""}`.trim()||"(no output)"}var _R=new Set(["localhost","127.0.0.1","::1","0.0.0.0","[::1]"]);function yR(t){let e=t.replace(/^\w+:\/\//,"").split(/[:/]/)[0];if(_R.has(e.toLowerCase()))throw new Error(`route target "${t}" is loopback, which inside a sandbox means the sandbox itself \u2014 a tier-2 sandbox cannot reach a service on the host this way. Give the service a name the sandbox can resolve (a compose service name, or host.docker.internal) on a network named agenthippo-<host>, or run this deployment with --sandbox process.`);return`agenthippo-${e}`}function wR(t){let e=dR.createConnection(t),n=new Promise((r,s)=>{e.once("close",()=>r()),e.once("error",i=>s(new Error(`sandbox channel closed: ${i.message}`)))});return{input:e,output:{write:r=>e.write(r)},closed:n}}function AR(t){return t.replace(/[^a-zA-Z0-9_-]/g,"").slice(0,32)||"session"}});var pE=S(Qe=>{"use strict";Object.defineProperty(Qe,"__esModule",{value:!0});Qe.ProcessSandboxDriver=Qe.PROVIDER_KEY_PASSTHROUGH_VARS=Qe.NS_PROBE_ARGS=Qe.UNSHARE_WRAP_ARGS=void 0;Qe.namespaceIsolationFromEnv=SR;Qe.probeNamespaceIsolation=lE;Qe.providerKeyPassthroughFromEnv=uE;Qe.sandboxEnvCarriesProviderKey=dE;Qe.baseSandboxEnv=fE;var cE=require("node:child_process"),dd=Qa();function SR(t=process.env){let e=t.AGENTHIPPO_SANDBOX_NS_ISOLATION?.trim().toLowerCase();return e==="off"||e==="0"?"off":e==="require"?"require":"auto"}Qe.UNSHARE_WRAP_ARGS=["--user","--map-current-user","--pid","--fork","--kill-child=SIGTERM","--mount-proc"];Qe.NS_PROBE_ARGS=[...Qe.UNSHARE_WRAP_ARGS,"unshare","--user","true"];async function lE(t=cE.spawn,e=5e3){return new Promise(n=>{let r,s=!1,i=a=>{s||(s=!0,r&&clearTimeout(r),n(a))},o;try{o=t("unshare",[...Qe.NS_PROBE_ARGS],{stdio:"ignore"})}catch{i(!1);return}r=setTimeout(()=>{o.kill("SIGKILL"),i(!1)},e),r.unref?.(),o.once("error",()=>i(!1)),o.once("exit",a=>i(a===0))})}Qe.PROVIDER_KEY_PASSTHROUGH_VARS=["CURSOR_API_KEY"];function uE(t=process.env){return t.AGENTHIPPO_SANDBOX_ALLOW_PROVIDER_KEY==="1"}function dE(t){return Qe.PROVIDER_KEY_PASSTHROUGH_VARS.some(e=>!!t[e])}var fd=class{opts;kind="process";tier=0;sandboxes=new Map;seq=0;nsWrap;constructor(e){this.opts=e}namespaceWrap(){if(!this.nsWrap){let e=this.opts.namespaceIsolation??"off";if(e==="off")this.nsWrap=Promise.resolve(!1);else{let n=this.opts.probeFn??(()=>lE());this.nsWrap=n().then(r=>{if(r)return this.opts.logger?.info("[Sandbox] namespace isolation active: each sandbox gets its own PID namespace (/proc shows only its own tree)"),!0;if(e==="require")throw new Error(`AGENTHIPPO_SANDBOX_NS_ISOLATION=require, but this host cannot run \`unshare ${Qe.UNSHARE_WRAP_ARGS.join(" ")}\` \u2014 no sandbox may exist here whose env is readable by a concurrent tenant. Enable unprivileged user namespaces (or use --sandbox container), or drop the requirement.`);return this.opts.logger?.warn("namespace isolation unavailable on this host (unshare probe failed) \u2014 tier-0 sandboxes share one /proc, so a concurrent same-uid process can read a turn's env. Fine on a laptop; on a multi-tenant host set AGENTHIPPO_SANDBOX_NS_ISOLATION=require or use --sandbox container."),!1})}}return this.nsWrap}async create(e){let n=`sandbox-${++this.seq}-${TR(e.sandboxKey)}`,r=this.opts.spawnFn??cE.spawn,s=await this.namespaceWrap(),i=s?"unshare":this.opts.command,o=s?[...Qe.UNSHARE_WRAP_ARGS,this.opts.command,...this.opts.args??[]]:this.opts.args??[],c={...fE({...this.opts.allowProviderKeyPassthrough!==void 0?{allowProviderKeyPassthrough:this.opts.allowProviderKeyPassthrough}:{},logger:{warn:g=>console.warn(g)}}),...this.opts.env,...e.env},l=dE(c),f=r(i,o,{cwd:this.opts.cwd,stdio:["pipe","pipe","inherit"],env:{...c,[dd.SANDBOX_TIER_ENV]:String(this.tier),...l?{[dd.SANDBOX_PROVIDER_KEY_ENV]:"1"}:{}}});l&&console.warn(`[Sandbox] ${n} runs WITH a raw provider key in its environment (${Qe.PROVIDER_KEY_PASSTHROUGH_VARS.filter(g=>c[g]).join(", ")}). This sandbox does not have the model-credential containment the other engines get; disclose it in the deployment.`);let u=new Promise(g=>{f.once("exit",()=>g()),f.once("error",()=>g())}),d={input:f.stdout,output:{write:g=>f.stdin?.write(g)??!1},closed:u},p={child:f,channel:d};return e.limits.ttlSeconds>0&&(p.ttl=setTimeout(()=>{this.kill(n)},e.limits.ttlSeconds*1e3),p.ttl.unref?.()),this.sandboxes.set(n,p),{id:n,tier:this.tier,endpoint:"stdio",connect:()=>d}}async revoke(e,n){if(n!=="all")throw new dd.RevocationUnsupportedError("process",n);await this.kill(e.id)}async destroy(e){await this.kill(e.id)}async kill(e){let n=this.sandboxes.get(e);n&&(this.sandboxes.delete(e),n.ttl&&clearTimeout(n.ttl),n.child.exitCode===null&&!n.child.killed&&n.child.kill("SIGTERM"))}};Qe.ProcessSandboxDriver=fd;function fE(t={},e=process.env){let n=["PATH","HOME","LANG","LC_ALL","TMPDIR","TERM","NODE_ENV","CLAUDE_CODE_PATH","CODEX_PATH","AGENTHIPPO_CUSTOM_ENGINES_DIR","AGENTHIPPO_NO_AUTO_INSTALL","AGENTHIPPO_DATA_MCP_URL","AGENTHIPPO_LITELLM_BASE_URL"],r={};for(let i of n){let o=e[i];o&&(r[i]=o)}let s=t.allowProviderKeyPassthrough??uE(e);for(let i of Qe.PROVIDER_KEY_PASSTHROUGH_VARS){let o=e[i];if(o){if(!s){t.logger?.warn(`[Sandbox] ${i} is set but was NOT passed into the sandbox: a raw provider key in a sandbox can call the provider directly, around the inference proxy and its spend cap. Cursor packs need it and cannot be proxied \u2014 set AGENTHIPPO_SANDBOX_ALLOW_PROVIDER_KEY=1 to allow it and accept that this sandbox holds a provider credential.`);continue}r[i]=o}}return r}function TR(t){return t.replace(/[^a-zA-Z0-9_-]/g,"").slice(0,32)||"session"}});var pd=S(gt=>{"use strict";var bR=gt&&gt.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,s)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),vR=gt&&gt.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),hE=gt&&gt.__importStar||(function(){var t=function(e){return t=Object.getOwnPropertyNames||function(n){var r=[];for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(r[r.length]=s);return r},t(e)};return function(e){if(e&&e.__esModule)return e;var n={};if(e!=null)for(var r=t(e),s=0;s<r.length;s++)r[s]!=="default"&&bR(n,e,r[s]);return vR(n,e),n}})();Object.defineProperty(gt,"__esModule",{value:!0});gt.DEPRECATED_SANDBOX_ENV_ALIASES=void 0;gt.dockerExec=PR;gt.alignSandboxWorkspaceOwnership=NR;gt.resolveSandboxImageUser=EE;gt.ensureSandboxStateDir=RR;gt.sandboxScriptArg=$R;gt.applyDeprecatedSandboxEnvAliases=yE;gt.loadWarrantKeypair=LR;gt.mintSandboxInferenceWarrant=MR;var OR=require("node:child_process"),Do=hE(require("node:fs")),IR=hE(require("node:path")),mE=Mi();function PR(t){return new Promise(e=>{(0,OR.execFile)("docker",t,{maxBuffer:8<<20},(n,r,s)=>{if(n){let i=typeof n.code=="number"?n.code:1;e({stdout:`${r??""}${s??""}`,code:i});return}e({stdout:r??"",stderr:s??"",code:0})})})}async function NR(t){let e=t.writable.map(i=>i.includes(":")?i.slice(0,i.indexOf(":")):i);if(e.length===0)return;let n=await EE(t.exec,t.image);if(!n){t.logger?.warn(`[Sandbox] could not determine the sandbox image's uid; if turns fail with EACCES in the workspace, run: chown -R <image-uid> ${e.join(" ")}`);return}if(n.uid===0)return;let{uid:r,gid:s}=n;for(let i of e)try{let o=_E(i,r,s);o>0&&t.logger?.info(`[Sandbox] aligned ${o} path(s) under ${i} to the sandbox image's uid ${r}:${s}`)}catch(o){t.logger?.warn(`[Sandbox] could not align ownership of ${i} for the sandbox (uid ${r}): ${o instanceof Error?o.message:String(o)}. Run: chown -R ${r}:${s} ${i}`)}}async function EE(t,e){let n=await gE(t,e,"-u");if(n!==void 0)return{uid:n,gid:await gE(t,e,"-g")??n}}function RR(t,e){if(Do.mkdirSync(t,{recursive:!0}),e&&e.uid!==0)try{_E(t,e.uid,e.gid)}catch{}return t}async function gE(t,e,n){let r=await t(["run","--rm","--network","none","--entrypoint","id",e,n]);if(r.code!==0)return;let s=Number.parseInt(r.stdout.trim(),10);return Number.isInteger(s)?s:void 0}function _E(t,e,n){let r=0,s=i=>{let o=Do.lstatSync(i);if((o.uid!==e||o.gid!==n)&&(Do.lchownSync(i,e,n),r++),o.isDirectory())for(let a of Do.readdirSync(i))s(IR.join(i,a))};return Do.existsSync(t)?(s(t),r):0}var CR=["/$bunfs","/snapshot"];function kR(t){return t.replace(/\\/g,"/").replace(/^[A-Za-z]:/,"")}function $R(t=process.argv,e=process.execPath){let n=t[1];if(!n||n===e)return[];let r=kR(n);return CR.some(s=>r.startsWith(s))?[]:[n]}gt.DEPRECATED_SANDBOX_ENV_ALIASES=[["AGENTHIPPO_CELL","AGENTHIPPO_SANDBOX"],["AGENTHIPPO_CELL_TIER","AGENTHIPPO_SANDBOX_TIER"],["AGENTHIPPO_CELL_SOCKET_DIR","AGENTHIPPO_SANDBOX_SOCKET_DIR"],["AGENTHIPPO_CELL_STRICT_EGRESS","AGENTHIPPO_SANDBOX_STRICT_EGRESS"],["AGENTHIPPO_CELL_ALLOW_PROVIDER_KEY","AGENTHIPPO_SANDBOX_ALLOW_PROVIDER_KEY"]];var DR=new Set;function yE(t=process.env,e=r=>console.warn(r),n=DR){let r=[];for(let[s,i]of gt.DEPRECATED_SANDBOX_ENV_ALIASES){let o=t[s];if(!(o===void 0||o==="")){if(t[i]!==void 0&&t[i]!==""){n.has(s)||(n.add(s),e(`[Sandbox] DEPRECATED: ${s} is set but ${i} is also set \u2014 using ${i} and IGNORING ${s}. Remove ${s}; it was renamed in the cell \u2192 sandbox migration.`));continue}t[i]=o,r.push(i),n.has(s)||(n.add(s),e(`[Sandbox] DEPRECATED: ${s} was renamed to ${i} in the cell \u2192 sandbox migration. The old value is being honoured for now, but it will stop working \u2014 set ${i}=${o} instead.`))}}return r}yE();function LR(t){let e=process.env.AGENTHIPPO_WARRANT_PRIVATE_KEY?.trim(),n=process.env.AGENTHIPPO_WARRANT_KID?.trim();if(e){let i=require("node:crypto").createPublicKey(e).export({type:"spki",format:"pem"}).toString();return{privateKeyPem:e,publicKeyPem:i,kid:n||"default"}}let r=(0,mE.generateWarrantKeypair)(n);return t?.info(`[Warrant] no AGENTHIPPO_WARRANT_PRIVATE_KEY \u2014 generated an ephemeral key (kid=${r.kid}). Configure gateways with:
505
+ GATEWAY_SANDBOX_WARRANT_KEYS=${JSON.stringify({[r.kid]:r.publicKeyPem})}`),r}function MR(t,e){return(0,mE.mintWarrant)({...e,aud:"inference"},t)}});var md=S(hd=>{"use strict";Object.defineProperty(hd,"__esModule",{value:!0});hd.createPackRunner=HR;var GR=oi(),UR=Er(),gd=Wn();function HR(t){return(0,GR.createHeadlessRunner)({storagePath:t.storagePath,analyticsSessionsDir:t.analyticsSessionsDir,packId:t.packId,packVersion:t.packVersion,provenance:t.provenance,bundledPromptsDir:(0,gd.findBundledBasePromptsDir)(),apiKey:t.credentials.apiKey,baseUrl:t.credentials.baseUrl,useLiteLLM:t.credentials.useLiteLLM,litellmApiKey:t.credentials.litellmApiKey,openaiApiKey:t.credentials.openaiApiKey,anthropicApiKey:t.credentials.anthropicApiKey,logger:t.logger,freshState:t.freshState??!1,claudeCodeExecutablePath:(0,gd.findClaudeCodePath)(),codexExecutablePath:(0,gd.findCodexPath)(),permissionHandler:t.permissionHandler,cliEnvPatch:(0,UR.buildCliEnvPatch)({cliPath:process.execPath,workspaceRoot:t.workspaceRoot,agentId:t.packId,chatSessionId:t.chatSessionId,baseEnv:process.env,omitGatewayToken:t.omitGatewayToken}),...t.claudeCheapModel?{engineSettings:{claudeCheapModel:t.claudeCheapModel}}:{}})}});var CE=S(On=>{"use strict";var jR=On&&On.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,s)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),xR=On&&On.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),BR=On&&On.__importStar||(function(){var t=function(e){return t=Object.getOwnPropertyNames||function(n){var r=[];for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(r[r.length]=s);return r},t(e)};return function(e){if(e&&e.__esModule)return e;var n={};if(e!=null)for(var r=t(e),s=0;s<r.length;s++)r[s]!=="default"&&jR(n,e,r[s]);return xR(n,e),n}})();Object.defineProperty(On,"__esModule",{value:!0});On.getEvidenceShipStatus=IE;On.validateEvidenceUrl=NE;On.resolveSessionShipConfig=YR;On.redactSessionLine=RE;On.startSessionShipper=JR;var fi=BR(require("path")),qn=require("fs"),TE=require("crypto"),FR=require("zlib"),VR=Pi(),bE=Ao(),vc="AGENTHIPPO_EVIDENCE_SHIP",Lo="AGENTHIPPO_EVIDENCE_URL",wE="AGENTHIPPO_EVIDENCE_SHIP_TOKEN",WR="AGENTHIPPO_EVIDENCE_SHIP_INTERVAL_SEC",vE="AGENTHIPPO_EVIDENCE_SHIP_SINCE_DAYS",OE="AGENTHIPPO_EVIDENCE_SHIP_DRAIN_TIMEOUT_SEC",Oc="AGENTHIPPO_EVIDENCE_ALLOW_INSECURE_URL",Ed=30,_d=30,KR=/(^|_)(input|output|result|prompt|completion|content|text|messages?)(_|$)|preview$/i,yd={enabled:!1,disabledReason:"not-configured",consecutiveFailures:0,recordsStaged:0,recordsShipped:0,recordsSkippedTooOld:0,filesSkippedTooOld:0,writeFailures:0,contentCapture:!1};function IE(){return{...yd,writeFailures:(0,bE.getSessionEventWriterStats)().failed}}function ji(t){yd={...yd,...t}}function wd(t){return["1","true","yes","on"].includes((t??"").trim().toLowerCase())}function PE(t){return wd(t[Oc])||wd(t.EVIDENCE_ALLOW_INSECURE_URL)}var qR=new Set(["localhost","127.0.0.1","::1","[::1]","0.0.0.0"]);function NE(t,e=process.env){let n;try{n=new URL(t)}catch{return{error:`${Lo} is not a valid URL: ${JSON.stringify(t)}`}}if(n.protocol==="https:")return{url:n.toString().replace(/\/$/,"")};if(n.protocol!=="http:")return{error:`${Lo} must be https (got ${n.protocol.replace(":","")})`};if(qR.has(n.hostname))return{url:n.toString().replace(/\/$/,"")};if(PE(e)){let r=wd(e[Oc])?Oc:"EVIDENCE_ALLOW_INSECURE_URL";return console.warn(`[evidence-ship] INSECURE: shipping evidence and the ingest token over plaintext http to ${n.host} because ${r} is set. Use https unless this network is genuinely private.`),{url:n.toString().replace(/\/$/,"")}}return{error:`${Lo} must use https \u2014 plaintext http to ${n.host} would put the ingest token and the audit trail on the wire. Use https, a loopback address, or set ${Oc}=1 (or EVIDENCE_ALLOW_INSECURE_URL=1) if the network is genuinely private.`}}function YR(t,e,n,r=process.env){if(r[vc]==="0"||r[vc]?.toLowerCase()==="false"){console.warn(`
506
506
  ############################################################
507
507
  ## EVIDENCE SHIPPING IS DISABLED ##
508
- ## ${Tc}=${r[Tc]}
508
+ ## ${vc}=${r[vc]}
509
509
  ## Session evidence stays on local disk and is lost when ##
510
510
  ## this instance goes away. Unset to re-enable. ##
511
511
  ############################################################
512
- `),ji({enabled:!1,disabledReason:"disabled-by-env"});return}let s=r[$o]?.trim(),i=r[yE]?.trim();if(!s||!i){(s||i)&&console.warn(`[evidence-ship] disabled \u2014 ${s?yE:$o} is not set (the other half of the pair is)`),ji({enabled:!1,disabledReason:"not-configured"});return}let o=PE(s,r);if("error"in o){console.error(`[evidence-ship] DISABLED \u2014 ${o.error}`),ji({enabled:!1,disabledReason:"invalid-url"});return}let a=Math.max(15,Number(r[xR]??60)||60),c=Math.max(1,Number(r[bE]??Ed)||Ed),l=Math.max(1,Number(r[vE]??_d)||_d);return{evidenceUrl:o.url,shipToken:i,instanceId:t,sessionsDir:e,stateDir:n,intervalSec:a,sinceDays:c,drainTimeoutSec:l,allowInsecure:IE(r)}}function WR(t){return{sha256:(0,SE.createHash)("sha256").update(t,"utf8").digest("hex"),length:Buffer.byteLength(t,"utf8")}}function NE(t,e){if(e)return t;let n;try{n=JSON.parse(t)}catch{return t}if(!n||typeof n!="object")return t;let r=n;if(!r.payload||typeof r.payload!="object")return t;let s=r.payload,i=!1;for(let o of Object.keys(s)){if(!BR.test(o)||o.endsWith("_sha256")||o.endsWith("_length"))continue;let a=s[o];if(a==null)continue;let c=typeof a=="string"?a:JSON.stringify(a),l=WR(c);delete s[o],s[`${o}_sha256`]=l.sha256,s[`${o}_length`]=l.length,s[`${o}_redacted`]=!0,i=!0}return i?JSON.stringify(r):t}function wE(){return{version:1,files:{},pending:{staged:0,shipped:0,skippedRecords:0,skippedFiles:0}}}function AE(t){let e=0;for(let n of t.split(`
513
- `))n.trim()&&e++;return e}function KR(t){let e=fi.join(t.stateDir,".evidence-ship-cursor.json"),n=fi.join(t.stateDir,".evidence-stage-cursor.json"),r=fi.join(t.stateDir,"evidence-staging","sessions"),s=t.logger?.info??(()=>{}),i=t.logger?.warn??(()=>{}),o=t.sinceDays??Ed,a=t.intervalSec??60,c=(t.drainTimeoutSec??_d)*1e3,l=(0,jR.isContentCaptureEnabled)(),f=t.allowInsecure===!0,u=!1,d=!1,p,g=0,m,h,E,_=0,y={staged:0,shipped:0,skippedRecords:0,skippedFiles:0};ji({enabled:!0,disabledReason:void 0,evidenceUrl:t.evidenceUrl,intervalSec:a,sinceDays:o,consecutiveFailures:0,recordsStaged:0,recordsShipped:0,recordsSkippedTooOld:0,filesSkippedTooOld:0,contentCapture:l});let b=()=>(h||(h=import("@agenthippo-ai/evidence-ship").then(({createShipper:R})=>R({serverUrl:t.evidenceUrl,token:t.shipToken,instanceId:t.instanceId,source:"serve",sinceDays:o,cursorFile:e,captureContent:l,allowInsecure:f,heartbeat:!1,log:F=>s(F),error:F=>i(F)}))),h),T=async()=>{if(E)return E;try{let R=await qn.promises.readFile(n,"utf8"),F=JSON.parse(R);E={version:1,files:F.files??{},windowFrom:F.windowFrom,pending:F.pending??wE().pending}}catch{E=wE()}return E},O=async()=>{if(E)try{await qn.promises.mkdir(fi.dirname(n),{recursive:!0}),await qn.promises.writeFile(n,JSON.stringify(E,null,1))}catch(R){i(`[evidence-ship] could not persist stage cursor: ${R instanceof Error?R.message:String(R)}`)}},A=async()=>{let R=await T(),F=Date.now(),re=F-o*864e5,W=0,de;try{de=(await qn.promises.readdir(t.sessionsDir)).filter(z=>z.endsWith(".jsonl"))}catch{return 0}await qn.promises.mkdir(r,{recursive:!0});let he=[];for(let z of de){if(z.startsWith("_evidence-loss"))continue;let Ne=fi.join(t.sessionsDir,z),We;try{We=await qn.promises.stat(Ne)}catch{continue}if(We.mtimeMs<re){let Et=R.files[z];if(!Et?.lostReported){let It=0;try{It=AE(await qn.promises.readFile(Ne,"utf8"))}catch{}y.skippedFiles++,y.skippedRecords+=It,R.pending.skippedFiles++,R.pending.skippedRecords+=It,R.files[z]={size:We.size,sha256:"",stagedAt:0,stagedMtimeMs:Et?.stagedMtimeMs??0,lostReported:!0},i(`[evidence-ship] EVIDENCE PERMANENTLY SKIPPED: ${z} last changed ${new Date(We.mtimeMs).toISOString()}, older than the ${o}-day ship window \u2014 ${It} record(s) will never be shipped. Raise ${bE} before the next restart to recover a backlog this old.`),he.push(JSON.stringify({session_id:"_evidence-loss",request_id:z,timestamp:F,event_type:"evidence_skipped",payload:{reason:"older_than_ship_window",file:z,file_mtime_ms:We.mtimeMs,file_bytes:We.size,records:It,since_days:o,instance_id:t.instanceId,permanent:!0}}))}continue}let Me;try{Me=await qn.promises.readFile(Ne,"utf8")}catch(Et){i(`[evidence-ship] cannot read ${z}: ${Et instanceof Error?Et.message:String(Et)}`);continue}let on=(0,SE.createHash)("sha256").update(Me,"utf8").digest("hex"),ye=R.files[z];if(ye&&ye.sha256===on&&ye.size===Me.length)continue;let cr=Me.split(`
514
- `).map(Et=>Et.trim()?NE(Et,l):Et).join(`
515
- `),ut=fi.join(r,z);await qn.promises.writeFile(ut,cr);let qt=Math.max(Date.now(),(ye?.stagedMtimeMs??0)+1e3),En=qt/1e3;await qn.promises.utimes(ut,En,En);let Dn=AE(cr);W+=Dn,R.files[z]={size:Me.length,sha256:on,stagedAt:F,stagedMtimeMs:qt}}if(he.length>0){let z=fi.join(r,"evidence-loss.jsonl");await qn.promises.appendFile(z,`${he.join(`
512
+ `),ji({enabled:!1,disabledReason:"disabled-by-env"});return}let s=r[Lo]?.trim(),i=r[wE]?.trim();if(!s||!i){(s||i)&&console.warn(`[evidence-ship] disabled \u2014 ${s?wE:Lo} is not set (the other half of the pair is)`),ji({enabled:!1,disabledReason:"not-configured"});return}let o=NE(s,r);if("error"in o){console.error(`[evidence-ship] DISABLED \u2014 ${o.error}`),ji({enabled:!1,disabledReason:"invalid-url"});return}let a=Math.max(15,Number(r[WR]??60)||60),c=Math.max(1,Number(r[vE]??Ed)||Ed),l=Math.max(1,Number(r[OE]??_d)||_d);return{evidenceUrl:o.url,shipToken:i,instanceId:t,sessionsDir:e,stateDir:n,intervalSec:a,sinceDays:c,drainTimeoutSec:l,allowInsecure:PE(r)}}function XR(t){return{sha256:(0,TE.createHash)("sha256").update(t,"utf8").digest("hex"),length:Buffer.byteLength(t,"utf8")}}function RE(t,e){if(e)return t;let n;try{n=JSON.parse(t)}catch{return t}if(!n||typeof n!="object")return t;let r=n;if(!r.payload||typeof r.payload!="object")return t;let s=r.payload,i=!1;for(let o of Object.keys(s)){if(!KR.test(o)||o.endsWith("_sha256")||o.endsWith("_length"))continue;let a=s[o];if(a==null)continue;let c=typeof a=="string"?a:JSON.stringify(a),l=XR(c);delete s[o],s[`${o}_sha256`]=l.sha256,s[`${o}_length`]=l.length,s[`${o}_redacted`]=!0,i=!0}return i?JSON.stringify(r):t}function AE(){return{version:1,files:{},pending:{staged:0,shipped:0,skippedRecords:0,skippedFiles:0}}}function SE(t){let e=0;for(let n of t.split(`
513
+ `))n.trim()&&e++;return e}function JR(t){let e=fi.join(t.stateDir,".evidence-ship-cursor.json"),n=fi.join(t.stateDir,".evidence-stage-cursor.json"),r=fi.join(t.stateDir,"evidence-staging","sessions"),s=t.logger?.info??(()=>{}),i=t.logger?.warn??(()=>{}),o=t.sinceDays??Ed,a=t.intervalSec??60,c=(t.drainTimeoutSec??_d)*1e3,l=(0,VR.isContentCaptureEnabled)(),f=t.allowInsecure===!0,u=!1,d=!1,p,g=0,m,h,E,_=0,y={staged:0,shipped:0,skippedRecords:0,skippedFiles:0};ji({enabled:!0,disabledReason:void 0,evidenceUrl:t.evidenceUrl,intervalSec:a,sinceDays:o,consecutiveFailures:0,recordsStaged:0,recordsShipped:0,recordsSkippedTooOld:0,filesSkippedTooOld:0,contentCapture:l});let b=()=>(h||(h=import("@agenthippo-ai/evidence-ship").then(({createShipper:R})=>R({serverUrl:t.evidenceUrl,token:t.shipToken,instanceId:t.instanceId,source:"serve",sinceDays:o,cursorFile:e,captureContent:l,allowInsecure:f,heartbeat:!1,log:F=>s(F),error:F=>i(F)}))),h),T=async()=>{if(E)return E;try{let R=await qn.promises.readFile(n,"utf8"),F=JSON.parse(R);E={version:1,files:F.files??{},windowFrom:F.windowFrom,pending:F.pending??AE().pending}}catch{E=AE()}return E},O=async()=>{if(E)try{await qn.promises.mkdir(fi.dirname(n),{recursive:!0}),await qn.promises.writeFile(n,JSON.stringify(E,null,1))}catch(R){i(`[evidence-ship] could not persist stage cursor: ${R instanceof Error?R.message:String(R)}`)}},A=async()=>{let R=await T(),F=Date.now(),re=F-o*864e5,W=0,de;try{de=(await qn.promises.readdir(t.sessionsDir)).filter(Q=>Q.endsWith(".jsonl"))}catch{return 0}await qn.promises.mkdir(r,{recursive:!0});let he=[];for(let Q of de){if(Q.startsWith("_evidence-loss"))continue;let Ne=fi.join(t.sessionsDir,Q),We;try{We=await qn.promises.stat(Ne)}catch{continue}if(We.mtimeMs<re){let Et=R.files[Q];if(!Et?.lostReported){let It=0;try{It=SE(await qn.promises.readFile(Ne,"utf8"))}catch{}y.skippedFiles++,y.skippedRecords+=It,R.pending.skippedFiles++,R.pending.skippedRecords+=It,R.files[Q]={size:We.size,sha256:"",stagedAt:0,stagedMtimeMs:Et?.stagedMtimeMs??0,lostReported:!0},i(`[evidence-ship] EVIDENCE PERMANENTLY SKIPPED: ${Q} last changed ${new Date(We.mtimeMs).toISOString()}, older than the ${o}-day ship window \u2014 ${It} record(s) will never be shipped. Raise ${vE} before the next restart to recover a backlog this old.`),he.push(JSON.stringify({session_id:"_evidence-loss",request_id:Q,timestamp:F,event_type:"evidence_skipped",payload:{reason:"older_than_ship_window",file:Q,file_mtime_ms:We.mtimeMs,file_bytes:We.size,records:It,since_days:o,instance_id:t.instanceId,permanent:!0}}))}continue}let Me;try{Me=await qn.promises.readFile(Ne,"utf8")}catch(Et){i(`[evidence-ship] cannot read ${Q}: ${Et instanceof Error?Et.message:String(Et)}`);continue}let on=(0,TE.createHash)("sha256").update(Me,"utf8").digest("hex"),ye=R.files[Q];if(ye&&ye.sha256===on&&ye.size===Me.length)continue;let cr=Me.split(`
514
+ `).map(Et=>Et.trim()?RE(Et,l):Et).join(`
515
+ `),ut=fi.join(r,Q);await qn.promises.writeFile(ut,cr);let qt=Math.max(Date.now(),(ye?.stagedMtimeMs??0)+1e3),En=qt/1e3;await qn.promises.utimes(ut,En,En);let Dn=SE(cr);W+=Dn,R.files[Q]={size:Me.length,sha256:on,stagedAt:F,stagedMtimeMs:qt}}if(he.length>0){let Q=fi.join(r,"evidence-loss.jsonl");await qn.promises.appendFile(Q,`${he.join(`
516
516
  `)}
517
- `);let Ne=Date.now()/1e3;await qn.promises.utimes(z,Ne,Ne),W+=he.length}return y.staged+=W,R.pending.staged+=W,R.windowFrom===void 0&&(R.windowFrom=F),await O(),W},v=async()=>{let R=await T(),F=Date.now(),re=(0,TE.getSessionEventWriterStats)(),W={kind:"session_ship_heartbeat",instance_id:t.instanceId,wire:"agenthippo/session-ship/1",window_from_ms:R.windowFrom??F,window_to_ms:F,interval_sec:a,since_days:o,records_staged:R.pending.staged,records_shipped:R.pending.shipped,records_skipped_too_old:R.pending.skippedRecords,files_skipped_too_old:R.pending.skippedFiles,evidence_write_failures:re.failed,evidence_writes:re.written,consecutive_ship_failures:g,content_capture:l,totals:{...y}},de=1;try{({INGEST_WIRE_VERSION:de}=await import("@agenthippo-ai/evidence-ship"))}catch{}let he=JSON.stringify(W),z=await fetch(`${t.evidenceUrl.replace(/\/$/,"")}/ingest/batch`,{method:"POST",headers:{authorization:`Bearer ${t.shipToken}`,"content-type":"application/json","X-Evidence-Ingest-Version":String(de)},body:JSON.stringify({instance_id:t.instanceId,kind:"heartbeat",name:"heartbeat.json",content_gzip_b64:(0,HR.gzipSync)(Buffer.from(he)).toString("base64")})});if(!z.ok)throw new Error(`heartbeat HTTP ${z.status}`);return R.windowFrom=F,R.pending={staged:0,shipped:0,skippedRecords:0,skippedFiles:0},ji({lastHeartbeatAt:F}),await O(),!0},C=async()=>{if(!(u||d)){d=!0;try{let R=await A();_+=R;try{if(await(await b()).drain({sessions:r,heartbeat:!1})){let W=await T();W.pending.shipped+=_,y.shipped+=_,_=0,p=Date.now(),g=0}else g++,i(`[evidence-ship] drain failed (${g} in a row); ${_} record(s) still unshipped`)}catch(F){g++,i(`[evidence-ship] ${F instanceof Error?F.message:String(F)}`)}}catch(R){g++,i(`[evidence-ship] ${R instanceof Error?R.message:String(R)}`)}finally{try{await v()}catch(R){i(`[evidence-ship] heartbeat failed: ${R instanceof Error?R.message:String(R)}`)}d=!1,ji({lastOkAt:p,consecutiveFailures:g,recordsStaged:y.staged,recordsShipped:y.shipped,recordsSkippedTooOld:y.skippedRecords,filesSkippedTooOld:y.skippedFiles})}}};C(),m=setInterval(()=>void C(),a*1e3),m.unref?.(),s(`[evidence-ship] enabled \u2192 ${t.evidenceUrl} (every ${a}s, ${o}-day window, content capture ${l?"ON":"off"})`);let B=()=>{u=!0,m&&clearInterval(m)};return{stop:B,async flush(){B();let R=Date.now()+c;for(;d&&Date.now()<R;)await new Promise(F=>setTimeout(F,50));if(d){i(`[evidence-ship] FINAL DRAIN ABANDONED after ${Math.round(c/1e3)}s \u2014 a ship was still in flight. ${_} staged record(s) plus anything written since are lost if this state dir is ephemeral. Raise ${vE} if this recurs.`);return}u=!1;try{await C()}finally{u=!0}_>0&&i(`[evidence-ship] final drain finished with ${_} record(s) still unshipped`)},lastOkAt:()=>p,status:()=>OE()}}});var Do=S(In=>{"use strict";Object.defineProperty(In,"__esModule",{value:!0});In.DEFAULT_AUTH_BIND=In.AUTH_PROXY_SECRET_HEADER=In.DEFAULT_JWT_SECRET=void 0;In.resolveAuthBrokerBind=XR;In.loadAuthBrokerConfig=JR;In.emailDomainAllowed=zR;function qR(t){return t?.trim()?t.split(",").map(e=>e.trim().toLowerCase()).filter(Boolean):[]}In.DEFAULT_JWT_SECRET="dev-agenthippo-auth-secret-change-me";In.AUTH_PROXY_SECRET_HEADER="x-agenthippo-proxy-secret";In.DEFAULT_AUTH_BIND="127.0.0.1";var YR=new Set(["127.0.0.1","localhost","::1","[::1]"]);function XR(t=process.env){let e=t.AGENTHIPPO_AUTH_BIND?.trim()||In.DEFAULT_AUTH_BIND;if(!!YR.has(e.toLowerCase()))return{address:e,isPublic:!1};if(t.AGENTHIPPO_AUTH_ALLOW_PUBLIC_BIND!=="1")throw new Error(`Refusing to bind the auth broker to "${e}". This port issues authorization codes and access tokens, and a directly reachable broker can be asked to mint a token for an arbitrary email by forging X-Auth-Request-Email.
517
+ `);let Ne=Date.now()/1e3;await qn.promises.utimes(Q,Ne,Ne),W+=he.length}return y.staged+=W,R.pending.staged+=W,R.windowFrom===void 0&&(R.windowFrom=F),await O(),W},v=async()=>{let R=await T(),F=Date.now(),re=(0,bE.getSessionEventWriterStats)(),W={kind:"session_ship_heartbeat",instance_id:t.instanceId,wire:"agenthippo/session-ship/1",window_from_ms:R.windowFrom??F,window_to_ms:F,interval_sec:a,since_days:o,records_staged:R.pending.staged,records_shipped:R.pending.shipped,records_skipped_too_old:R.pending.skippedRecords,files_skipped_too_old:R.pending.skippedFiles,evidence_write_failures:re.failed,evidence_writes:re.written,consecutive_ship_failures:g,content_capture:l,totals:{...y}},de=1;try{({INGEST_WIRE_VERSION:de}=await import("@agenthippo-ai/evidence-ship"))}catch{}let he=JSON.stringify(W),Q=await fetch(`${t.evidenceUrl.replace(/\/$/,"")}/ingest/batch`,{method:"POST",headers:{authorization:`Bearer ${t.shipToken}`,"content-type":"application/json","X-Evidence-Ingest-Version":String(de)},body:JSON.stringify({instance_id:t.instanceId,kind:"heartbeat",name:"heartbeat.json",content_gzip_b64:(0,FR.gzipSync)(Buffer.from(he)).toString("base64")})});if(!Q.ok)throw new Error(`heartbeat HTTP ${Q.status}`);return R.windowFrom=F,R.pending={staged:0,shipped:0,skippedRecords:0,skippedFiles:0},ji({lastHeartbeatAt:F}),await O(),!0},C=async()=>{if(!(u||d)){d=!0;try{let R=await A();_+=R;try{if(await(await b()).drain({sessions:r,heartbeat:!1})){let W=await T();W.pending.shipped+=_,y.shipped+=_,_=0,p=Date.now(),g=0}else g++,i(`[evidence-ship] drain failed (${g} in a row); ${_} record(s) still unshipped`)}catch(F){g++,i(`[evidence-ship] ${F instanceof Error?F.message:String(F)}`)}}catch(R){g++,i(`[evidence-ship] ${R instanceof Error?R.message:String(R)}`)}finally{try{await v()}catch(R){i(`[evidence-ship] heartbeat failed: ${R instanceof Error?R.message:String(R)}`)}d=!1,ji({lastOkAt:p,consecutiveFailures:g,recordsStaged:y.staged,recordsShipped:y.shipped,recordsSkippedTooOld:y.skippedRecords,filesSkippedTooOld:y.skippedFiles})}}};C(),m=setInterval(()=>void C(),a*1e3),m.unref?.(),s(`[evidence-ship] enabled \u2192 ${t.evidenceUrl} (every ${a}s, ${o}-day window, content capture ${l?"ON":"off"})`);let B=()=>{u=!0,m&&clearInterval(m)};return{stop:B,async flush(){B();let R=Date.now()+c;for(;d&&Date.now()<R;)await new Promise(F=>setTimeout(F,50));if(d){i(`[evidence-ship] FINAL DRAIN ABANDONED after ${Math.round(c/1e3)}s \u2014 a ship was still in flight. ${_} staged record(s) plus anything written since are lost if this state dir is ephemeral. Raise ${OE} if this recurs.`);return}u=!1;try{await C()}finally{u=!0}_>0&&i(`[evidence-ship] final drain finished with ${_} record(s) still unshipped`)},lastOkAt:()=>p,status:()=>IE()}}});var Mo=S(In=>{"use strict";Object.defineProperty(In,"__esModule",{value:!0});In.DEFAULT_AUTH_BIND=In.AUTH_PROXY_SECRET_HEADER=In.DEFAULT_JWT_SECRET=void 0;In.resolveAuthBrokerBind=ZR;In.loadAuthBrokerConfig=eC;In.emailDomainAllowed=tC;function zR(t){return t?.trim()?t.split(",").map(e=>e.trim().toLowerCase()).filter(Boolean):[]}In.DEFAULT_JWT_SECRET="dev-agenthippo-auth-secret-change-me";In.AUTH_PROXY_SECRET_HEADER="x-agenthippo-proxy-secret";In.DEFAULT_AUTH_BIND="127.0.0.1";var QR=new Set(["127.0.0.1","localhost","::1","[::1]"]);function ZR(t=process.env){let e=t.AGENTHIPPO_AUTH_BIND?.trim()||In.DEFAULT_AUTH_BIND;if(!!QR.has(e.toLowerCase()))return{address:e,isPublic:!1};if(t.AGENTHIPPO_AUTH_ALLOW_PUBLIC_BIND!=="1")throw new Error(`Refusing to bind the auth broker to "${e}". This port issues authorization codes and access tokens, and a directly reachable broker can be asked to mint a token for an arbitrary email by forging X-Auth-Request-Email.
518
518
  - Same-host proxy (recommended): bind 127.0.0.1 and run Caddy/oauth2-proxy alongside it.
519
519
  - SEPARATE CONTAINER for the proxy (the compose/Cloud Run layout, where Caddy dials
520
520
  "auth-broker:9780"): the broker must listen on the container's network interface, so set
521
521
  BOTH AGENTHIPPO_AUTH_BIND=${e} AND AGENTHIPPO_AUTH_ALLOW_PUBLIC_BIND=1,
522
522
  and make sure the port is not published outside the private network.
523
- In either case set AGENTHIPPO_AUTH_PROXY_SECRET (and have the proxy send it) so a forged X-Auth-Request-Email is rejected \u2014 that is what actually stops the token-minting attack.`);return{address:e,isPublic:!0}}function JR(t=process.env){let e=t.AGENTHIPPO_AUTH_JWT_SECRET?.trim()||In.DEFAULT_JWT_SECRET,n=(t.AGENTHIPPO_AUTH_PUBLIC_URL?.trim()||`http://127.0.0.1:${t.AGENTHIPPO_AUTH_PORT?.trim()||"9780"}`).replace(/\/+$/,""),r=t.AGENTHIPPO_TEAM_STORE_REPO?.trim()||"agenthippoai/agenthippo-store",s=r.split("/")[0]||"agenthippoai",i=r.split("/")[1]||"agenthippo-store";return{port:Number(t.AGENTHIPPO_AUTH_PORT||9780),publicBaseUrl:n,jwtSecret:e,accessTokenTtlSec:Number(t.AGENTHIPPO_AUTH_ACCESS_TTL_SEC||3600),refreshTokenTtlSec:Number(t.AGENTHIPPO_AUTH_REFRESH_TTL_SEC||720*3600),allowedEmailDomains:qR(t.AGENTHIPPO_AUTH_ALLOWED_DOMAINS),devMode:t.AGENTHIPPO_AUTH_DEV==="1",rateLimitPerMin:t.AGENTHIPPO_AUTH_RATE_LIMIT!==void 0?Number(t.AGENTHIPPO_AUTH_RATE_LIMIT):60,logPii:t.AGENTHIPPO_AUTH_LOG_PII==="1",cookieName:t.AGENTHIPPO_AUTH_COOKIE_NAME?.trim()||"ah_token",cookieDomain:t.AGENTHIPPO_AUTH_COOKIE_DOMAIN?.trim()||"",idpBaseUrl:(t.AGENTHIPPO_AUTH_IDP_URL?.trim()||"").replace(/\/+$/,""),proxySecret:t.AGENTHIPPO_AUTH_PROXY_SECRET?.trim()||"",trustProxyHeadersUnverified:t.AGENTHIPPO_AUTH_TRUST_PROXY_UNVERIFIED==="1",dataDir:t.AGENTHIPPO_AUTH_DATA_DIR?.trim()||void 0,teamConfigured:!!t.AGENTHIPPO_TEAM_ID?.trim(),team:{id:t.AGENTHIPPO_TEAM_ID?.trim()||"team_default",name:t.AGENTHIPPO_TEAM_NAME?.trim()||"Default Team",storeRepo:r,storeIndexUrl:t.AGENTHIPPO_TEAM_STORE_INDEX_URL?.trim()||`https://${s}.github.io/${i}`,githubOrg:t.AGENTHIPPO_TEAM_GITHUB_ORG?.trim()||s,gatewayUrl:t.AGENTHIPPO_TEAM_GATEWAY_URL?.trim()||"https://gateway.agenthippo.ai/v1"}}}function zR(t,e){if(e.length===0)return!0;let n=t.split("@")[1]?.toLowerCase();return!!n&&e.includes(n)}});var Br=S($=>{"use strict";var QR=$&&$.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,s)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),ZR=$&&$.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),bd=$&&$.__importStar||(function(){var t=function(e){return t=Object.getOwnPropertyNames||function(n){var r=[];for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(r[r.length]=s);return r},t(e)};return function(e){if(e&&e.__esModule)return e;var n={};if(e!=null)for(var r=t(e),s=0;s<r.length;s++)r[s]!=="default"&&QR(n,e,r[s]);return ZR(n,e),n}})();Object.defineProperty($,"__esModule",{value:!0});$.TurnGate=$.TURN_LIMIT_BUSY_MESSAGE=$.RATE_LIMIT_BUSY_MESSAGE=$.TURN_GATE_BUSY_MESSAGE=$.TURN_GATE_RETRY_AFTER_SECONDS=$.TURN_QUEUE_ENV=$.MAX_CONCURRENT_TURNS_ENV=$.TurnLimiter=$.SESSION_WITHOUT_USER_REASON=$.REQUIRE_TENANT_ISOLATION_ENV=$.IDENTITY_PROXY_SECRET_ENV=$.IDENTITY_HEADER_ENV=$.PIN_ONLY_IDENTITY_HEADERS=$.RateLimiter=$.XFF_TRUSTED_HOPS_ENV=$.CONTAINER_SERVE_HOST=$.SERVE_HOST_ENV=$.DEFAULT_BIND_HOST=$.SERVICE_USER_ENV=$.DEFAULT_MAX_BODY_BYTES=void 0;$.resolveStateDir=rC;$.resolveAnalyticsSessionsDir=sC;$.resolveServiceIdentity=iC;$.isLoopbackHost=$E;$.resolveBindHost=oC;$.clientIp=aC;$.hasTrustedProxyProof=LE;$.identityHeaderAdvice=cC;$.tenantIsolationAdvice=lC;$.resolveUserId=uC;$.resolveDataToken=fC;$.peerToUserId=pC;$.userNamespaceHash=Sd;$.resolveServeSessionKey=gC;$.corsHeaders=hC;$.createTurnGateFromEnv=mC;$.createRejectionWarner=EC;$.readBodyWithCap=_C;var eC=bd(require("os")),ms=bd(require("path")),vc=bd(require("crypto")),tC=Ys(),nC=Do();$.DEFAULT_MAX_BODY_BYTES=1024*1024;function rC(t,e=process.env){let n=t?.trim();if(n)return{dir:ms.resolve(n),ephemeral:!1};let r=e.AGENTHIPPO_HOME?.trim()||e.AGENTIDE_HOME?.trim();return r?{dir:ms.join(ms.resolve(r),"serve-state"),ephemeral:!1}:{dir:ms.join(eC.tmpdir(),"agenthippo-server"),ephemeral:!0}}function sC(t,e,n=process.env){return!(n.AGENT_HOME_DIR?.trim()||n.AGENTHIPPO_HOME?.trim())&&!e?ms.join(t,"analytics","sessions"):ms.join((0,tC.getAgentideHome)(),"analytics","sessions")}$.SERVICE_USER_ENV="AGENTHIPPO_SERVICE_USER";var CE=256;function iC(t=process.env){let e=t[$.SERVICE_USER_ENV];if(e===void 0)return{};let n=e.trim();return n?/\s/.test(n)?{error:`${$.SERVICE_USER_ENV} must not contain whitespace, got ${JSON.stringify(e)}.`}:n.length>CE?{error:`${$.SERVICE_USER_ENV} is ${n.length} chars; the maximum is ${CE}.`}:/^svc:/.test(n)||/^spiffe:\/\//.test(n)||/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(n)?{identity:n}:{identity:n,warning:`${$.SERVICE_USER_ENV}="${n}" carries no namespace marker (svc: / spiffe:// / GUID). It will be used verbatim and must be mapped in the connector role map, exactly like a human identity. If it can collide with a real user id, prefix it with \`svc:\`.`}:{error:`${$.SERVICE_USER_ENV} is set but empty. Unset it, or give it the identity unattended runs should act as.`}}$.DEFAULT_BIND_HOST="127.0.0.1";function $E(t){let e=t.trim().toLowerCase().replace(/^\[|\]$/g,"");return e==="localhost"||e==="::1"||/^127\./.test(e)}$.SERVE_HOST_ENV="AGENTHIPPO_SERVE_HOST";$.CONTAINER_SERVE_HOST="0.0.0.0";function oC(t,e=process.env){return t?.trim()||e.AGENTHIPPO_SERVE_HOST?.trim()||$.DEFAULT_BIND_HOST}$.XFF_TRUSTED_HOPS_ENV="AGENTHIPPO_XFF_TRUSTED_HOPS";function aC(t,e=process.env){let n=t.headers["x-forwarded-for"],r=Array.isArray(n)?n[0]:n;if(r){let s=r.split(",").map(i=>i.trim()).filter(Boolean);if(s.length>0){let i=Number(e[$.XFF_TRUSTED_HOPS_ENV]),o=Number.isInteger(i)&&i>=1?i:1;return s[Math.max(0,s.length-o)]}}return t.socket?.remoteAddress||"unknown"}var Ad=class t{maxPerWindow;windowMs;hits=new Map;static MAX_KEYS=1e5;constructor(e,n=6e4){this.maxPerWindow=e,this.windowMs=n}tryConsume(e,n=Date.now()){if(!Number.isFinite(this.maxPerWindow)||this.maxPerWindow<=0)return!0;let r=this.hits.get(e);return!r||r.resetAt<=n?(this.hits.size>=t.MAX_KEYS&&this.prune(n),this.hits.set(e,{count:1,resetAt:n+this.windowMs}),!0):r.count>=this.maxPerWindow?!1:(r.count+=1,!0)}retryAfterSeconds(e,n=Date.now()){let r=this.hits.get(e);return r?Math.max(1,Math.ceil((r.resetAt-n)/1e3)):Math.ceil(this.windowMs/1e3)}prune(e){for(let[n,r]of this.hits)r.resetAt<=e&&this.hits.delete(n);this.hits.size>=t.MAX_KEYS&&this.hits.clear()}};$.RateLimiter=Ad;var DE=["x-forwarded-email","x-forwarded-preferred-username","x-goog-authenticated-user-email","cf-access-authenticated-user-email"];$.PIN_ONLY_IDENTITY_HEADERS=["x-agent-user"];$.IDENTITY_HEADER_ENV="AGENTHIPPO_IDENTITY_HEADER";$.IDENTITY_PROXY_SECRET_ENV="AGENTHIPPO_IDENTITY_PROXY_SECRET";function LE(t,e){if(!e)return!1;let n=t[nC.AUTH_PROXY_SECRET_HEADER],r=typeof n=="string"?n:Array.isArray(n)?String(n[0]??""):"";if(!r)return!1;let s=vc.createHash("sha256").update(r).digest(),i=vc.createHash("sha256").update(e).digest();return vc.timingSafeEqual(s,i)}function cC(t=process.env,e){if(t[$.IDENTITY_HEADER_ENV]?.trim())return[];let r=e?.trim();return r&&$E(r)?[`${$.IDENTITY_HEADER_ENV} is not set. Fine for this loopback bind; pin it before exposing serve on a network interface.`]:[...r?[`serve is bound to ${r} \u2014 reachable beyond this machine \u2014 with no ${$.IDENTITY_HEADER_ENV} pinned. Anyone who can reach this port is trusted to state who they are.`]:[],`${$.IDENTITY_HEADER_ENV} is not set, so identity falls back to the platform header aliases (${DE.join(", ")}). That is only safe when your proxy sets AND STRIPS every one of them. Pin the single header your deploy layer really controls, e.g. ${$.IDENTITY_HEADER_ENV}=x-goog-authenticated-user-email.`,`NOTE: ${$.PIN_ONLY_IDENTITY_HEADERS.join(", ")} is NO LONGER trusted by default \u2014 it is not stripped by any platform, so an arbitrary client could send it and be namespaced as another user. If your proxy does set it (the Caddy forward_auth / auth-broker flow does), pin it: ${$.IDENTITY_HEADER_ENV}=x-agent-user.`]}$.REQUIRE_TENANT_ISOLATION_ENV="AGENTHIPPO_REQUIRE_TENANT_ISOLATION";function kE(t,e){let n=ms.resolve(t),r=ms.resolve(e);return n===r||n.startsWith(r+ms.sep)}function lC(t,e=process.env){if(!e[$.IDENTITY_HEADER_ENV]?.trim())return{level:"ok",lines:[]};if(t.sandbox==="container"&&!t.sharedWorkspace)return{level:"ok",lines:[]};let r=t.sandbox==="process"?"a tier-0 (--sandbox=process) sandbox":"no sandbox",s=[`${$.IDENTITY_HEADER_ENV} is pinned \u2014 so this serve has more than one user \u2014 but it runs with ${r}, which shares one uid, one workspace (${t.workspace??"unset"}) and one state dir (${t.stateDir}) across all of them. Any user can read every other user's engine session files, which hold their conversations verbatim. Per-user paths are namespacing, not isolation.`,"The boundary is --sandbox=container (per-session workspace and state, without --shared-workspace) or one serve per tenant. Until then, restrict the pack's tool surface so the agent has no way to read arbitrary files."];return t.workspace&&kE(t.workspace,t.stateDir)?s.push(`--workspace ${t.workspace} sits INSIDE --state-dir ${t.stateDir}: every other user's sessions, analytics and evidence spool are one '..' above the agent's own cwd. Put them in unrelated subtrees (e.g. --workspace=/work --state-dir=/state).`):t.workspace&&kE(t.stateDir,t.workspace)&&s.push(`--state-dir ${t.stateDir} sits INSIDE --workspace ${t.workspace}: every other user's sessions, analytics and evidence spool are inside the directory the agent is pointed at. Put them in unrelated subtrees (e.g. --workspace=/work --state-dir=/state).`),{level:/^(1|true|yes|on)$/i.test(e[$.REQUIRE_TENANT_ISOLATION_ENV]?.trim()??"")?"refuse":"warn",lines:s}}function uC(t,e,n=process.env){let r=n[$.IDENTITY_PROXY_SECRET_ENV]?.trim();if(r&&!LE(t,r))return;let s=n[$.IDENTITY_HEADER_ENV]?.trim().toLowerCase(),i=s?[s]:DE;for(let a of i){let c=t[a],l=(Array.isArray(c)?c[0]:c)?.trim();if(l){let f=l.lastIndexOf(":");return f>=0&&l.slice(f+1).includes("@")?l.slice(f+1):l}}return s||n.AGENTHIPPO_ALLOW_BODY_IDENTITY?.trim()!=="1"?void 0:e?.user_id?.trim()||void 0}var dC=["x-forwarded-access-token","x-agent-data-token"];function fC(t){for(let e of dC){let n=t[e],r=(Array.isArray(n)?n[0]:n)?.trim();if(r)return r}}function pC(t){if(!t)return;let e=t.senderId?.trim()||t.senderUsername?.trim()||t.senderName?.trim();if(!e)return;let n=t.channel?.trim();return n?`${n}:${e}`:e}$.SESSION_WITHOUT_USER_REASON="session_without_verified_user";function Sd(t){return vc.createHash("sha256").update(t).digest("hex").slice(0,16)}function gC(t,e,n="session",r=process.env){let s=t?.trim(),i=e?.trim();if(i){let a=`u${Sd(i)}--${s||"default"}`;return{sessionKey:a,sandboxKey:n==="user"?`u${Sd(i)}`:a}}if(r[$.IDENTITY_HEADER_ENV]?.trim())return{sessionKey:"",sandboxKey:"",rejected:$.SESSION_WITHOUT_USER_REASON};let o=s||"anon-unknown";return{sessionKey:o,sandboxKey:o}}function hC(){return{"Access-Control-Allow-Methods":"GET, POST, OPTIONS","Access-Control-Allow-Headers":"Content-Type, Authorization, X-Agent-User","Access-Control-Allow-Origin":"*"}}var Td=class{maxPerSession;counts=new Map;constructor(e){this.maxPerSession=e}tryConsume(e){if(!Number.isFinite(this.maxPerSession)||this.maxPerSession<=0)return!0;let n=this.counts.get(e)??0;return n>=this.maxPerSession?!1:(this.counts.set(e,n+1),!0)}reset(e){this.counts.delete(e)}};$.TurnLimiter=Td;$.MAX_CONCURRENT_TURNS_ENV="AGENTHIPPO_MAX_CONCURRENT_TURNS";$.TURN_QUEUE_ENV="AGENTHIPPO_TURN_QUEUE";$.TURN_GATE_RETRY_AFTER_SECONDS=15;$.TURN_GATE_BUSY_MESSAGE="At capacity \u2014 please retry in a moment";$.RATE_LIMIT_BUSY_MESSAGE="Rate limit exceeded \u2014 please retry in a moment";$.TURN_LIMIT_BUSY_MESSAGE="Per-session turn limit reached";var Oc=class{maxInflight;maxQueue;queueTimeoutMs;inflightCount=0;waiters=[];constructor(e,n,r=$.TURN_GATE_RETRY_AFTER_SECONDS*1e3){this.maxInflight=e,this.maxQueue=n,this.queueTimeoutMs=r}async acquire(){return!Number.isFinite(this.maxInflight)||this.maxInflight<=0?()=>{}:this.inflightCount<this.maxInflight?(this.inflightCount+=1,()=>this.releaseSlot()):this.waiters.length>=this.maxQueue?null:new Promise(e=>{let n=!1,r=o=>{if(n){o&&o();return}n=!0,clearTimeout(i),e(o)},s={resolve:r,timer:null},i=setTimeout(()=>{let o=this.waiters.indexOf(s);o>=0&&this.waiters.splice(o,1),r(null)},this.queueTimeoutMs);s.timer=i,this.waiters.push(s)})}releaseSlot(){let e=this.waiters.shift();if(e){e.resolve(()=>this.releaseSlot());return}this.inflightCount=Math.max(0,this.inflightCount-1)}get inflight(){return this.inflightCount}get queued(){return this.waiters.length}get max(){return this.maxInflight>0?this.maxInflight:0}};$.TurnGate=Oc;function mC(t=process.env){let e=Number(t[$.MAX_CONCURRENT_TURNS_ENV]??10),n=Number(t[$.TURN_QUEUE_ENV]??20),r=Number.isFinite(e)?e:10,s=Number.isFinite(n)&&n>=0?n:20;return new Oc(r,s)}function EC(t=5e3){let e=0;return n=>{let r=Date.now();r-e<t||(e=r,console.warn(n))}}function _C(t,e=$.DEFAULT_MAX_BODY_BYTES){return new Promise((n,r)=>{let s=0,i=[],o=f=>{if(s+=f.length,s>e){l();let u=new Error(`Request body exceeds ${e} bytes`);u.tooLarge=!0,r(u);return}i.push(f)},a=()=>{l(),n(Buffer.concat(i).toString("utf8"))},c=f=>{l(),r(f)},l=()=>{t.off("data",o),t.off("end",a),t.off("error",c)};t.on("data",o),t.on("end",a),t.on("error",c)})}});var Mo=S($s=>{"use strict";Object.defineProperty($s,"__esModule",{value:!0});$s.TurnRegistry=$s.DEFAULT_TURN_DEADLINE_MS=void 0;$s.hashNonce=Lo;var ME=require("crypto");$s.DEFAULT_TURN_DEADLINE_MS=30*6e4;function Lo(t){return(0,ME.createHash)("sha256").update(t).digest("hex")}var vd=class{entries=new Map;register(e){this.prune();let n=(0,ME.randomBytes)(16).toString("hex"),r=Lo(n);this.entries.set(r,{userId:e.userId,sessionKey:e.sessionKey,inboundToken:e.inboundToken,egressStoreKey:e.egressStoreKey,deadline:e.deadline??Date.now()+$s.DEFAULT_TURN_DEADLINE_MS});let s=!1;return{nonce:n,release:()=>{s||(s=!0,this.entries.delete(r))}}}releaseByNonce(e){return this.entries.delete(Lo(e))}resolve(e,n=Date.now()){let r=this.entries.get(Lo(e));if(r){if(n>r.deadline){this.entries.delete(Lo(e));return}return r}}prune(e=Date.now()){for(let[n,r]of this.entries)e>r.deadline&&this.entries.delete(n)}get size(){return this.entries.size}};$s.TurnRegistry=vd});var Id=S(Sr=>{"use strict";Object.defineProperty(Sr,"__esModule",{value:!0});Sr.CredentialBroker=Sr.identityProvider=Sr.passthroughProvider=void 0;Sr.resolveProvider=yC;Sr.passthroughProvider={name:"passthrough",refreshOnInbound:!0,async acquire({userId:t,inboundToken:e}){let n=e?.trim();if(!n)throw new Error(`No inbound data credential for user (fail-closed) \u2014 the platform did not forward a per-user token on this request (userId=${t})`);return{expiresAt:Date.now()+10*6e4,secretRef:n}}};Sr.identityProvider={name:"identity",async acquire({userId:t}){if(!t.trim())throw new Error("No verified user (fail-closed)");return{expiresAt:Number.MAX_SAFE_INTEGER,secretRef:null}}};function yC(t){let e=(t??"passthrough").trim().toLowerCase();if(e==="passthrough")return Sr.passthroughProvider;if(e==="identity")return Sr.identityProvider;throw new Error(`Unknown data credential provider "${t}" (supported: passthrough, identity)`)}var Od=class{provider;cache=new Map;constructor(e){this.provider=e}async acquire(e,n){if(this.provider.refreshOnInbound)return this.provider.acquire({userId:e,inboundToken:n});let r=this.cache.get(e);if(r&&r.expiresAt>Date.now())return r;this.cache.delete(e);let s=await this.provider.acquire({userId:e,inboundToken:n});return this.cache.set(e,s),s}invalidate(e){this.cache.delete(e)}};Sr.CredentialBroker=Od});var Nd=S(Pn=>{"use strict";var wC=Pn&&Pn.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,s)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),AC=Pn&&Pn.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),SC=Pn&&Pn.__importStar||(function(){var t=function(e){return t=Object.getOwnPropertyNames||function(n){var r=[];for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(r[r.length]=s);return r},t(e)};return function(e){if(e&&e.__esModule)return e;var n={};if(e!=null)for(var r=t(e),s=0;s<r.length;s++)r[s]!=="default"&&wC(n,e,r[s]);return AC(n,e),n}})();Object.defineProperty(Pn,"__esModule",{value:!0});Pn.ConnectorHost=Pn.TURN_META_KEY=void 0;var GE=SC(require("path")),TC=require("fs"),bC=require("@modelcontextprotocol/sdk/client/index.js"),vC=require("@modelcontextprotocol/sdk/client/stdio.js"),OC=require("@modelcontextprotocol/sdk/types.js"),IC=Ya();Pn.TURN_META_KEY="ai.agenthippo/turn";var Pd=class t{client;logger;connectorPath;constructor(e,n,r){this.client=e,this.logger=n,this.connectorPath=r}static async spawn(e){let n=GE.resolve(e.connectorPath);await TC.promises.access(n);let r=await(0,IC.resolveNodeBinary)(),s=new vC.StdioClientTransport({command:r,args:[n],cwd:GE.dirname(n),env:{...process.env,AGENTHIPPO_DATA_CONNECTOR:"1"},stderr:"pipe"}),i=new bC.Client({name:"agenthippo-data-gateway",version:"1.0.0"});return await i.connect(s),s.stderr?.on("data",o=>{e.logger?.warn(`[DataPlane] connector stderr: ${String(o).trimEnd()}`)}),e.logger?.info(`[DataPlane] connector started: ${n}`),new t(i,e.logger,n)}async listTools(){return(await this.client.listTools()).tools.map(n=>({name:n.name,description:n.description,inputSchema:n.inputSchema??{type:"object"}}))}async callTool(e,n,r){return await this.client.request({method:"tools/call",params:{name:e,arguments:n,_meta:{[Pn.TURN_META_KEY]:{userId:r.userId,credential:r.credential}}}},OC.CallToolResultSchema)}async close(){try{await this.client.close()}catch(e){this.logger?.warn(`[DataPlane] connector close: ${e instanceof Error?e.message:String(e)}`)}}};Pn.ConnectorHost=Pd});var Go=S(sn=>{"use strict";var PC=sn&&sn.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,s)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),NC=sn&&sn.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),RC=sn&&sn.__importStar||(function(){var t=function(e){return t=Object.getOwnPropertyNames||function(n){var r=[];for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(r[r.length]=s);return r},t(e)};return function(e){if(e&&e.__esModule)return e;var n={};if(e!=null)for(var r=t(e),s=0;s<r.length;s++)r[s]!=="default"&&PC(n,e,r[s]);return NC(n,e),n}})();Object.defineProperty(sn,"__esModule",{value:!0});sn.TURN_NONCE_HEADER=sn.TURN_NONCE_ENV=sn.DATA_MCP_URL_ENV=void 0;sn.startDataGateway=MC;var CC=RC(require("http")),kC=require("@modelcontextprotocol/sdk/server/index.js"),$C=require("@modelcontextprotocol/sdk/server/streamableHttp.js"),UE=require("@modelcontextprotocol/sdk/types.js"),DC=Br(),LC=Mo();sn.DATA_MCP_URL_ENV="AGENTHIPPO_DATA_MCP_URL";sn.TURN_NONCE_ENV="AGENTHIPPO_TURN_NONCE";sn.TURN_NONCE_HEADER="x-agent-turn-nonce";function HE(t){return t?.match(/^Bearer\s+(\S+)$/i)?.[1]}function jE(t){return t?(0,LC.hashNonce)(t).slice(0,12):"none"}async function MC(t){let e=CC.createServer(async(i,o)=>{try{let a=i.url?.split("?")[0]??"";if(a==="/turn"&&i.method==="DELETE"){let p=HE(i.headers.authorization);if(p){let g=t.registry.releaseByNonce(p);t.audit?.("edge","turn_release",{released:g,nonce_sha256_prefix:jE(p)})}o.writeHead(204),o.end();return}if(a!=="/mcp"){o.writeHead(404,{"Content-Type":"application/json"}),o.end(JSON.stringify({error:"not found"}));return}if(i.method!=="POST"){o.writeHead(405,{"Content-Type":"application/json",Allow:"POST"}),o.end(JSON.stringify({error:"method not allowed"}));return}let c=HE(i.headers.authorization),l=c?t.registry.resolve(c):void 0;if(!l){t.audit?.("unauthorized","nonce_reject",{reason:c?"unknown_or_expired":"missing",nonce_sha256_prefix:jE(c)}),o.writeHead(401,{"Content-Type":"application/json"}),o.end(JSON.stringify({jsonrpc:"2.0",error:{code:-32001,message:"Unauthorized: missing, unknown, or expired turn nonce"},id:null}));return}t.logger?.info(`[DataPlane] authorized request user=${l.userId} session=${l.sessionKey}`);let f;try{f=JSON.parse(await(0,DC.readBodyWithCap)(i))}catch{o.writeHead(400,{"Content-Type":"application/json"}),o.end(JSON.stringify({jsonrpc:"2.0",error:{code:-32700,message:"Parse error"},id:null}));return}let u=GC(t,l),d=new $C.StreamableHTTPServerTransport({sessionIdGenerator:void 0,enableJsonResponse:!0});o.on("close",()=>{d.close(),u.close()}),await u.connect(d),await d.handleRequest(i,o,f)}catch(a){t.logger?.warn(`[DataPlane] gateway error: ${a instanceof Error?a.message:String(a)}`),o.headersSent||o.writeHead(500,{"Content-Type":"application/json"}),o.end(JSON.stringify({jsonrpc:"2.0",error:{code:-32603,message:"Internal error"},id:null}))}}),n=t.host??"127.0.0.1";await new Promise((i,o)=>{e.once("error",o),e.listen(t.port??0,n,()=>i())});let r=e.address();if(!r||typeof r=="string")throw new Error("Data gateway failed to bind a port");let s=`http://${t.advertiseHost??"127.0.0.1"}:${r.port}/mcp`;return t.logger?.info(`[DataPlane] gateway listening at ${s}`),{url:s,close:()=>new Promise(i=>e.close(()=>i()))}}function GC(t,e){let n=new kC.Server({name:"agenthippo-data-gateway",version:"1.0.0"},{capabilities:{tools:{}}});return n.setRequestHandler(UE.ListToolsRequestSchema,async()=>({tools:await t.connector.listTools()})),n.setRequestHandler(UE.CallToolRequestSchema,async r=>{let s=r.params.name,i;try{i=(await t.broker.acquire(e.userId,e.inboundToken)).secretRef,t.audit?.(e.sessionKey,"tool_authorize",{tool:s,userId:e.userId,provider:t.broker.provider.name})}catch(o){let a=o instanceof Error?o.message:String(o);return t.audit?.(e.sessionKey,"tool_deny",{tool:s,userId:e.userId,reason:"acquire_failed",error:a}),{content:[{type:"text",text:JSON.stringify({ok:!1,error:`credential acquire failed (fail-closed): ${a}`})}],isError:!0}}try{return await t.connector.callTool(s,r.params.arguments??{},{userId:e.userId,credential:i})}catch(o){let a=o instanceof Error?o.message:String(o);if(/401|unauthoriz|expired/i.test(a)){t.broker.invalidate(e.userId);try{let c=await t.broker.acquire(e.userId,e.inboundToken);return await t.connector.callTool(s,r.params.arguments??{},{userId:e.userId,credential:c.secretRef})}catch{}}return t.audit?.(e.sessionKey,"tool_deny",{tool:s,userId:e.userId,reason:"call_failed",error:a}),{content:[{type:"text",text:JSON.stringify({ok:!1,error:a})}],isError:!0}}}),n}});var BE=S(Tr=>{"use strict";var UC=Tr&&Tr.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,s)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),HC=Tr&&Tr.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),jC=Tr&&Tr.__importStar||(function(){var t=function(e){return t=Object.getOwnPropertyNames||function(n){var r=[];for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(r[r.length]=s);return r},t(e)};return function(e){if(e&&e.__esModule)return e;var n={};if(e!=null)for(var r=t(e),s=0;s<r.length;s++)r[s]!=="default"&&UC(n,e,r[s]);return HC(n,e),n}})();Object.defineProperty(Tr,"__esModule",{value:!0});Tr.backupTimestamp=BC;Tr.backupPathFor=xE;Tr.renameToBackup=FC;var xC=require("fs"),Rd=jC(require("path"));function BC(t=new Date){return t.toISOString().replace(/[-:]/g,"").replace(/\.\d+Z$/,"Z")}function xE(t,e){let n=Rd.dirname(t),r=Rd.basename(t).replace(/\.json$/i,"");return Rd.join(n,`${r}.${e}.bk`)}async function FC(t,e){let n=xE(t,e);try{return await xC.promises.rename(t,n),n}catch(r){if((r&&typeof r=="object"&&"code"in r?String(r.code):"")==="ENOENT")return;throw r}}});var Rc=S(vt=>{"use strict";var VC=vt&&vt.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,s)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),WC=vt&&vt.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),KC=vt&&vt.__importStar||(function(){var t=function(e){return t=Object.getOwnPropertyNames||function(n){var r=[];for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(r[r.length]=s);return r},t(e)};return function(e){if(e&&e.__esModule)return e;var n={};if(e!=null)for(var r=t(e),s=0;s<r.length;s++)r[s]!=="default"&&VC(n,e,r[s]);return WC(n,e),n}})();Object.defineProperty(vt,"__esModule",{value:!0});vt._resetOutboundHandleStoreLockForTest=YC;vt._setOutboundHandleStorePathForTest=XC;vt.buildGatewayOutboundHandleKey=KE;vt.upsertGatewayOutboundHandle=tk;vt.getLastGatewayOutboundHandle=nk;vt.listGatewayOutboundTargets=rk;vt.mergeGatewayOutboundHandles=sk;vt.resolveGatewayOutboundHandle=ik;vt.backupAndClearOutboundHandlesForAgent=ok;vt.getGatewayOutboundStoreSnapshot=ak;var Ic=require("fs"),qC=KC(require("path")),FE=BE(),kd=1,WE={value:void 0},xi=new Map,Cd=new Map;function $d(t,e){let r=(Cd.get(t)??Promise.resolve()).then(()=>e());return Cd.set(t,r.catch(()=>{})),r}function YC(){Cd.clear(),xi.clear()}function XC(t){WE.value=t,xi.clear()}function Uo(t){return WE.value??t}function KE(t,e){let n=e?.trim();return n?`${t}::thread:${n}`:`${t}::`}function JC(){return{version:kd,lastByAgent:{},targetsByAgent:{}}}async function Ls(t){let e=Uo(t),n=xi.get(e);if(n)return n;try{let s=await Ic.promises.readFile(e,"utf-8"),i=JSON.parse(s);if(i.targetsByAgent&&typeof i.targetsByAgent=="object"){let o={version:i.version??kd,lastByAgent:i.lastByAgent??{},targetsByAgent:i.targetsByAgent};return xi.set(e,o),o}}catch{}let r=JC();return xi.set(e,r),r}async function Dd(t,e){let n=Uo(t);await Ic.promises.mkdir(qC.dirname(n),{recursive:!0});let r={version:kd,lastByAgent:e.lastByAgent,targetsByAgent:e.targetsByAgent},s=`${n}.tmp`;await Ic.promises.writeFile(s,JSON.stringify(r,null,2),"utf-8"),await Ic.promises.rename(s,n),xi.set(n,e)}function Ds(t,e){if(e?.toLowerCase()!=="slack")return t;let n=t.match(/^(user|channel|group):(.+)$/i);return n?`${n[1].toLowerCase()}:${n[2].toUpperCase()}`:t}function VE(t,e,n){let r=Ds(t,n),s=Ds(e,n);return r.toLowerCase()===s.toLowerCase()}function zC(t,e,n){if(n)return t.find(i=>VE(i.target,e,i.channel)&&i.threadId?.trim()===n);let r=t.filter(i=>VE(i.target,e,i.channel));return r.length===0?void 0:r.find(i=>!i.threadId?.trim())??Pc(r)[0]}function QC(t,e){let n=t.match(/:thread:([^:]+)$/),r=n?t.slice(0,-n[0].length):t,s=r.match(/:direct:([^:]+)$/);if(s)return Ds(`user:${s[1]}`,e);let i=r.match(/:dm:([^:]+)$/);if(i)return Ds(`user:${i[1]}`,e);let o=r.match(/:channel:([^:]+)$/);if(o)return Ds(`channel:${o[1]}`,e);let a=r.match(/:group:([^:]+)$/);if(a)return Ds(`channel:${a[1]}`,e)}function ZC(t){let e=t.target?.trim();if(e)return Ds(e,t.channel);let n=t.sessionKey?.trim().toLowerCase();if(n){let s=QC(n,t.channel);if(s)return s}let r=t.senderId?.trim();if(r&&t.channel)return Ds(`user:${r}`,t.channel)}function ek(t){return t.senderName?.trim()?t.senderName.trim():t.senderUsername?.trim()?t.senderUsername.trim():t.target?.trim()||t.senderId?.trim()}function Pc(t){return[...t].sort((e,n)=>n.lastSeenAt-e.lastSeenAt)}function Nc(t,e){let n=e.trim();if(!n||t.lastByAgent[n]||t.targetsByAgent[n])return n;if(n.toLowerCase()==="default"){for(let r of["default","Default"])if(t.lastByAgent[r]||t.targetsByAgent[r])return r}return n}async function tk(t,e,n,r,s){let i=e.trim();if(!i)return;let o=s?.gatewayAgentId?.trim()||void 0,a=n.channel?.trim(),c=n.sessionKey?.trim().toLowerCase();if(!a&&c){let f=c.match(/^agent:[^:]+:([a-z0-9_-]+):/);f&&(a=f[1])}let l=ZC(n);if(!(!a||!l))return $d(Uo(t),async()=>{let f=Date.now(),u=await Ls(t);u.targetsByAgent[i]||(u.targetsByAgent[i]={});let d=KE(l,n.threadId?.trim()),p=u.targetsByAgent[i][d],g={agentId:i,...o?{gatewayAgentId:o}:{},channel:a,accountId:n.accountId?.trim()||void 0,target:l,threadId:n.threadId?.trim()||void 0,sessionKey:n.sessionKey?.trim()||void 0,sessionId:n.sessionId?.trim()||void 0,senderId:n.senderId?.trim()||void 0,senderName:n.senderName?.trim()||void 0,senderUsername:n.senderUsername?.trim()||void 0,label:ek(n),firstSeenAt:p?.firstSeenAt??f,lastSeenAt:f,lastInboundRunId:r,inboundCount:(p?.inboundCount??0)+1};return u.targetsByAgent[i][d]=g,u.lastByAgent[i]=g,await Dd(t,u),g})}async function nk(t,e){let n=await Ls(t),r=Nc(n,e);return n.lastByAgent[r]}async function rk(t,e){let n=await Ls(t);if(e?.trim()){let s=Nc(n,e.trim());return Pc(Object.values(n.targetsByAgent[s]??{}))}let r=[];for(let s of Object.values(n.targetsByAgent))r.push(...Object.values(s));return Pc(r)}async function sk(t,e,n){let r=await Ls(t),s=n?.trim()?[n.trim()]:[...new Set([...Object.keys(r.targetsByAgent),...Object.keys(r.lastByAgent)])];return s.length===0?0:$d(Uo(e),async()=>{let i=await Ls(e),o=0,a=!1;for(let c of s){let l=r.targetsByAgent[c]??{},f=Object.entries(l);f.length>0&&!i.targetsByAgent[c]&&(i.targetsByAgent[c]={});for(let[d,p]of f){let g=i.targetsByAgent[c]?.[d];(!g||p.lastSeenAt>=g.lastSeenAt)&&(i.targetsByAgent[c][d]=p,o++,a=!0)}let u=r.lastByAgent[c];if(u){let d=i.lastByAgent[c];(!d||u.lastSeenAt>=d.lastSeenAt)&&(i.lastByAgent[c]=u,a=!0)}}return a&&await Dd(e,i),o})}async function ik(t,e,n){let r=await Ls(t),s=Nc(r,e),i=n?.target?.trim();if(i){let o=Object.values(r.targetsByAgent[s]??{});return zC(o,i,n?.threadId?.trim())}return r.lastByAgent[s]}async function ok(t,e,n=(0,FE.backupTimestamp)()){let r=Uo(t);return $d(r,async()=>{let s=await Ls(t),i=Nc(s,e),o=s.targetsByAgent[i],a=Object.prototype.hasOwnProperty.call(s.lastByAgent,i),c=o?Object.keys(o).length:0;if(c===0&&!a)return{removed:0};let l=await(0,FE.renameToBackup)(r,n);return delete s.targetsByAgent[i],delete s.lastByAgent[i],await Dd(t,s),{removed:c,backupPath:l}})}async function ak(t){let e=await Ls(t),n={};for(let[r,s]of Object.entries(e.targetsByAgent))n[r]=Pc(Object.values(s));return{lastByAgent:e.lastByAgent,targetsByAgent:n}}});var YE=S(br=>{"use strict";var ck=br&&br.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,s)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),lk=br&&br.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),uk=br&&br.__importStar||(function(){var t=function(e){return t=Object.getOwnPropertyNames||function(n){var r=[];for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(r[r.length]=s);return r},t(e)};return function(e){if(e&&e.__esModule)return e;var n={};if(e!=null)for(var r=t(e),s=0;s<r.length;s++)r[s]!=="default"&&ck(n,e,r[s]);return lk(n,e),n}})();Object.defineProperty(br,"__esModule",{value:!0});br.EGRESS_URL_ENV=void 0;br.startEgressBroker=_k;var dk=uk(require("http")),fk=Br(),pk=Mo(),gk=Rc(),qE=Fa();br.EGRESS_URL_ENV="AGENTHIPPO_EGRESS_URL";function hk(t){return t?.match(/^Bearer\s+(\S+)$/i)?.[1]}function mk(t){return t?(0,pk.hashNonce)(t).slice(0,12):"none"}function Ek(t,e){return(0,qE.getGatewayOutboundFilePath)(t,(0,qE.safeGatewaySessionDirId)(e))}async function _k(t){let e=dk.createServer(async(s,i)=>{let o=(a,c,l,f)=>{l&&t.audit?.("unauthorized",l,f??{}),i.writeHead(a,{"Content-Type":"application/json"}),i.end(JSON.stringify({ok:!1,error:c}))};try{if((s.url?.split("?")[0]??"")!=="/egress/send"){o(404,"not found");return}if(s.method!=="POST"){i.writeHead(405,{"Content-Type":"application/json",Allow:"POST"}),i.end(JSON.stringify({ok:!1,error:"method not allowed"}));return}let c=hk(s.headers.authorization),l=c?t.registry.resolve(c):void 0;if(!l){o(401,"Unauthorized: missing, unknown, or expired turn nonce","egress_nonce_reject",{reason:c?"unknown_or_expired":"missing",nonce_sha256_prefix:mk(c)});return}let f=l.egressStoreKey?.trim();if(!f){o(403,"no outbound route for this turn (not a channel-originated session)","egress_deny",{userId:l.userId,reason:"no_store_key"});return}let u;try{u=JSON.parse(await(0,fk.readBodyWithCap)(s))}catch{o(400,"invalid JSON body");return}let d=typeof u.message=="string"?u.message:"";if(!d.trim()){o(400,"message is required");return}let p=typeof u.to=="string"?u.to.trim():void 0,g=typeof u.media=="string"&&u.media.trim()||void 0,m=Ek(t.workspaceRoot,f),h;try{h=await(0,gk.resolveGatewayOutboundHandle)(m,t.agentId,p?{target:p}:void 0)}catch(_){t.logger?.warn(`[Egress] store read failed: ${_ instanceof Error?_.message:String(_)}`)}if(!h){o(404,p?`no bound handle matches "${p}" for this session (cannot address a new destination)`:"no reply destination bound for this session yet","egress_deny",{userId:l.userId,reason:"no_matching_handle",to:p??"(reply-to-sender)"});return}t.audit?.(l.sessionKey,"egress_authorize",{userId:l.userId,channel:h.channel,target:h.target});let E=await t.send(h,d,g);i.writeHead(E.ok?200:502,{"Content-Type":"application/json"}),i.end(JSON.stringify(E))}catch(a){t.logger?.warn(`[Egress] broker error: ${a instanceof Error?a.message:String(a)}`),i.headersSent||i.writeHead(500,{"Content-Type":"application/json"}),i.end(JSON.stringify({ok:!1,error:"Internal error"}))}});await new Promise((s,i)=>{e.once("error",i),e.listen(0,"127.0.0.1",()=>s())});let n=e.address();if(!n||typeof n=="string")throw new Error("Egress broker failed to bind a loopback port");let r=`http://127.0.0.1:${n.port}/egress/send`;return t.logger?.info(`[Egress] broker listening at ${r}`),{url:r,close:()=>new Promise(s=>e.close(()=>s()))}}});var JE=S(Nn=>{"use strict";var yk=Nn&&Nn.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,s)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),wk=Nn&&Nn.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),Ak=Nn&&Nn.__importStar||(function(){var t=function(e){return t=Object.getOwnPropertyNames||function(n){var r=[];for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(r[r.length]=s);return r},t(e)};return function(e){if(e&&e.__esModule)return e;var n={};if(e!=null)for(var r=t(e),s=0;s<r.length;s++)r[s]!=="default"&&yk(n,e,r[s]);return wk(n,e),n}})();Object.defineProperty(Nn,"__esModule",{value:!0});Nn.ASSERTION_HEADER=void 0;Nn.startDataPlaneSidecar=Rk;var Sk=Ak(require("http")),XE=require("crypto"),Tk=Cc(),bk=Br(),vk=Go();Nn.ASSERTION_HEADER="x-agent-user-assertion";function Ok(t,e){let n=t.headers[e];return(Array.isArray(n)?n[0]:n)?.trim()||void 0}function Ik(t){return(0,XE.createHash)("sha256").update(t).digest("hex").slice(0,12)}function Pk(t){return t?.match(/^Bearer\s+(\S+)$/i)?.[1]}function Nk(t,e){let n=Buffer.from(t),r=Buffer.from(e);return n.length===r.length&&(0,XE.timingSafeEqual)(n,r)}async function Rk(t){let e=t.bindHost??"0.0.0.0",n=await Tk.DataPlane.start(t.config,{logger:t.logger,audit:t.audit,gateway:{host:e,port:t.gatewayPort,advertiseHost:e==="0.0.0.0"?void 0:e}}),r=new Map,s=Sk.createServer(async(a,c)=>{let l=(f,u)=>{c.writeHead(f,{"Content-Type":"application/json"}),c.end(JSON.stringify({error:u}))};try{let f=Pk(a.headers.authorization);if(!f||!Nk(f,t.registerToken))return t.audit?.("unauthorized","sidecar_register_reject",{reason:f?"bad_token":"missing_token"}),l(401,"unauthorized");let u=a.url?.split("?")[0]??"";if((a.method==="GET"||a.method==="POST")&&u==="/edge/turn"){let d=(Array.isArray(a.headers["x-agent-user"])?a.headers["x-agent-user"][0]:a.headers["x-agent-user"])?.trim();if(!d)return t.audit?.("unauthorized","sidecar_edge_reject",{reason:"missing_user"}),l(400,"X-Agent-User required");let p=Ok(a,Nn.ASSERTION_HEADER)?.replace(/^Bearer\s+/i,"").trim()||void 0,{nonce:g}=n.registerTurnRaw({userId:d,sessionKey:d,inboundToken:p});return t.audit?.(d,"sidecar_edge_register",{userId:d,assertion:p?`sha256:${Ik(p)}`:"none"}),c.writeHead(200,{"Content-Type":"application/json",[vk.TURN_NONCE_HEADER]:g}),c.end(JSON.stringify({ok:!0}))}if(a.method==="POST"&&u==="/turns"){let d;try{d=JSON.parse(await(0,bk.readBodyWithCap)(a))}catch{return l(400,"bad json")}let p=(d.userId??"").trim();if(!p)return l(400,"userId required");let g=d.agent?.pack?.trim(),m=!!(g&&t.agent?.pack&&g!==t.agent.pack);m&&console.warn(`Warning: turn registration claims agent "${g}" but this connector loaded "${t.agent?.pack}". One connector is meant to serve one agent \u2014 both now share this connector's base credential, so neither is bounded by the job it was deployed for.`),t.audit?.((d.sessionKey??"").trim()||p,"sidecar_register",{userId:p,claimedAgent:g??"none",binding:"asserted",...m?{agentMismatch:!0,loadedAgent:t.agent?.pack}:{}});let{nonce:h,release:E}=n.registerTurnRaw({userId:p,sessionKey:(d.sessionKey??"").trim()||p,inboundToken:d.inboundToken,egressStoreKey:d.egressStoreKey});return r.set(h,E),c.writeHead(200,{"Content-Type":"application/json"}),c.end(JSON.stringify({nonce:h}))}if(a.method==="DELETE"&&u.startsWith("/turns/")){let d=decodeURIComponent(u.slice(7));return r.get(d)?.(),r.delete(d),c.writeHead(204),c.end()}l(404,"not found")}catch(f){t.logger?.warn(`[Sidecar] control error: ${f instanceof Error?f.message:String(f)}`),c.headersSent||c.writeHead(500,{"Content-Type":"application/json"}),c.end(JSON.stringify({error:"internal"}))}});await new Promise((a,c)=>{s.once("error",c),s.listen(t.controlPort,e,()=>a())});let i=s.address(),o=i&&typeof i!="string"?i.port:t.controlPort;return t.logger?.info(`[Sidecar] gateway ${n.url} | control :${o} (bound ${e})`),(t.config.provider??"passthrough").trim().toLowerCase()==="passthrough"&&console.warn(`Warning: provider=passthrough needs a per-user token on every turn. Edge-registered turns supply it via the ${Nn.ASSERTION_HEADER} header \u2014 if your edge does not forward it, every tool call will fail closed.`),{gatewayUrl:n.url,controlPort:o,close:async()=>{await new Promise(a=>s.close(()=>a())),await n.close()}}}});var zE=S(Ms=>{"use strict";Object.defineProperty(Ms,"__esModule",{value:!0});Ms.RemoteDataPlane=Ms.EdgeDataPlane=void 0;Ms.resolveEdgeDataPlane=Ck;Ms.resolveRemoteDataPlane=kk;var kc=Go();function Ck(t=process.env){let e=t.AGENTHIPPO_DATA_PLANE_EDGE?.trim(),n=t.AGENTHIPPO_DATA_MCP_URL?.trim();return!e||e==="0"||e.toLowerCase()==="false"||!n?null:{gatewayUrl:n}}var Ld=class{cfg;constructor(e){this.cfg=e}get url(){return this.cfg.gatewayUrl}adoptTurn(e){return{nonce:e,env:{[kc.TURN_NONCE_ENV]:e,[kc.DATA_MCP_URL_ENV]:this.cfg.gatewayUrl},release:async()=>{try{await fetch(new URL("/turn",this.cfg.gatewayUrl),{method:"DELETE",headers:{Authorization:`Bearer ${e}`}})}catch{}}}}};Ms.EdgeDataPlane=Ld;function kk(t=process.env){let e=t.AGENTHIPPO_DATA_PLANE_CONTROL_URL?.trim(),n=t.AGENTHIPPO_DATA_PLANE_TOKEN?.trim(),r=t.AGENTHIPPO_DATA_MCP_URL?.trim();return!e||!n||!r?null:{controlUrl:e,registerToken:n,gatewayUrl:r}}var Md=class{cfg;constructor(e){this.cfg=e}get url(){return this.cfg.gatewayUrl}async registerTurn(e){let n=await fetch(`${this.cfg.controlUrl.replace(/\/$/,"")}/turns`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.cfg.registerToken}`},body:JSON.stringify(e)});if(!n.ok)throw new Error(`data-plane sidecar register failed: HTTP ${n.status}`);let{nonce:r}=await n.json();return{nonce:r,env:{[kc.TURN_NONCE_ENV]:r,[kc.DATA_MCP_URL_ENV]:this.cfg.gatewayUrl},release:async()=>{try{await fetch(`${this.cfg.controlUrl.replace(/\/$/,"")}/turns/${encodeURIComponent(r)}`,{method:"DELETE",headers:{Authorization:`Bearer ${this.cfg.registerToken}`}})}catch{}}}}};Ms.RemoteDataPlane=Md});var Cc=S(Y=>{"use strict";var $k=Y&&Y.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,s)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),Dk=Y&&Y.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),Lk=Y&&Y.__importStar||(function(){var t=function(e){return t=Object.getOwnPropertyNames||function(n){var r=[];for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(r[r.length]=s);return r},t(e)};return function(e){if(e&&e.__esModule)return e;var n={};if(e!=null)for(var r=t(e),s=0;s<r.length;s++)r[s]!=="default"&&$k(n,e,r[s]);return Dk(n,e),n}})();Object.defineProperty(Y,"__esModule",{value:!0});Y.DataPlane=Y.resolveEdgeDataPlane=Y.EdgeDataPlane=Y.resolveRemoteDataPlane=Y.RemoteDataPlane=Y.ASSERTION_HEADER=Y.startDataPlaneSidecar=Y.EGRESS_URL_ENV=Y.startEgressBroker=Y.TURN_NONCE_HEADER=Y.TURN_NONCE_ENV=Y.DATA_MCP_URL_ENV=Y.startDataGateway=Y.TURN_META_KEY=Y.ConnectorHost=Y.identityProvider=Y.passthroughProvider=Y.resolveProvider=Y.CredentialBroker=Y.DEFAULT_TURN_DEADLINE_MS=Y.hashNonce=Y.TurnRegistry=void 0;Y.resolveDataPlaneConfig=Uk;var QE=Lk(require("path")),Mk=Mo(),ZE=Id(),Gk=Nd(),Gd=Go(),Hd=Mo();Object.defineProperty(Y,"TurnRegistry",{enumerable:!0,get:function(){return Hd.TurnRegistry}});Object.defineProperty(Y,"hashNonce",{enumerable:!0,get:function(){return Hd.hashNonce}});Object.defineProperty(Y,"DEFAULT_TURN_DEADLINE_MS",{enumerable:!0,get:function(){return Hd.DEFAULT_TURN_DEADLINE_MS}});var $c=Id();Object.defineProperty(Y,"CredentialBroker",{enumerable:!0,get:function(){return $c.CredentialBroker}});Object.defineProperty(Y,"resolveProvider",{enumerable:!0,get:function(){return $c.resolveProvider}});Object.defineProperty(Y,"passthroughProvider",{enumerable:!0,get:function(){return $c.passthroughProvider}});Object.defineProperty(Y,"identityProvider",{enumerable:!0,get:function(){return $c.identityProvider}});var e_=Nd();Object.defineProperty(Y,"ConnectorHost",{enumerable:!0,get:function(){return e_.ConnectorHost}});Object.defineProperty(Y,"TURN_META_KEY",{enumerable:!0,get:function(){return e_.TURN_META_KEY}});var Dc=Go();Object.defineProperty(Y,"startDataGateway",{enumerable:!0,get:function(){return Dc.startDataGateway}});Object.defineProperty(Y,"DATA_MCP_URL_ENV",{enumerable:!0,get:function(){return Dc.DATA_MCP_URL_ENV}});Object.defineProperty(Y,"TURN_NONCE_ENV",{enumerable:!0,get:function(){return Dc.TURN_NONCE_ENV}});Object.defineProperty(Y,"TURN_NONCE_HEADER",{enumerable:!0,get:function(){return Dc.TURN_NONCE_HEADER}});var t_=YE();Object.defineProperty(Y,"startEgressBroker",{enumerable:!0,get:function(){return t_.startEgressBroker}});Object.defineProperty(Y,"EGRESS_URL_ENV",{enumerable:!0,get:function(){return t_.EGRESS_URL_ENV}});var n_=JE();Object.defineProperty(Y,"startDataPlaneSidecar",{enumerable:!0,get:function(){return n_.startDataPlaneSidecar}});Object.defineProperty(Y,"ASSERTION_HEADER",{enumerable:!0,get:function(){return n_.ASSERTION_HEADER}});var Lc=zE();Object.defineProperty(Y,"RemoteDataPlane",{enumerable:!0,get:function(){return Lc.RemoteDataPlane}});Object.defineProperty(Y,"resolveRemoteDataPlane",{enumerable:!0,get:function(){return Lc.resolveRemoteDataPlane}});Object.defineProperty(Y,"EdgeDataPlane",{enumerable:!0,get:function(){return Lc.EdgeDataPlane}});Object.defineProperty(Y,"resolveEdgeDataPlane",{enumerable:!0,get:function(){return Lc.resolveEdgeDataPlane}});function Uk(t,e){let n=t?.dataPlane,r=n?.connector?.trim();if(r)return{connectorPath:QE.isAbsolute(r)?r:QE.join(e,r),provider:n?.provider?.trim()||void 0}}var Ud=class t{url;registry;broker;connector;gateway;constructor(e,n,r,s,i){this.url=e,this.registry=n,this.broker=r,this.connector=s,this.gateway=i}static async start(e,n){let r=n?.registry??new Mk.TurnRegistry,s=new ZE.CredentialBroker((0,ZE.resolveProvider)(e.provider)),i=await Gk.ConnectorHost.spawn({connectorPath:e.connectorPath,logger:n?.logger});try{let o=await(0,Gd.startDataGateway)({registry:r,broker:s,connector:i,logger:n?.logger,audit:n?.audit,host:n?.gateway?.host,port:n?.gateway?.port,advertiseHost:n?.gateway?.advertiseHost});return new t(o.url,r,s,i,o)}catch(o){throw await i.close(),o}}registerTurnRaw(e){return this.registry.register(e)}registerTurn(e){let{nonce:n,release:r}=this.registry.register(e);return{nonce:n,env:{[Gd.TURN_NONCE_ENV]:n,[Gd.DATA_MCP_URL_ENV]:this.url},release:r}}async close(){await this.gateway.close(),await this.connector.close()}};Y.DataPlane=Ud});var r_=S(Yn=>{"use strict";Object.defineProperty(Yn,"__esModule",{value:!0});Yn.PROTOCOL_VERSION=Yn.DEFAULT_GATEWAY_OPERATOR_SCOPES=Yn.GATEWAY_CLIENT_CAPS=Yn.GATEWAY_CLIENT_MODES=Yn.GATEWAY_CLIENT_IDS=void 0;Yn.GATEWAY_CLIENT_IDS={GATEWAY_CLIENT:"gateway-client"};Yn.GATEWAY_CLIENT_MODES={WEBCHAT:"webchat",CLI:"cli",UI:"ui",BACKEND:"backend",AGENT_BACKEND:"agent-backend",NODE:"node",PROBE:"probe",TEST:"test"};Yn.GATEWAY_CLIENT_CAPS={TOOL_EVENTS:"tool-events"};Yn.DEFAULT_GATEWAY_OPERATOR_SCOPES=["operator.admin","operator.read","operator.write","operator.approvals","operator.pairing"];Yn.PROTOCOL_VERSION=3});var Mc=S(Xn=>{"use strict";Object.defineProperty(Xn,"__esModule",{value:!0});Xn.GatewayClient=Xn.MAX_GATEWAY_MESSAGE_CHARS=Xn.MAX_GATEWAY_FRAME_BYTES=void 0;Xn.createAgentIDEGatewayClient=Bk;Xn.createEphemeralGatewayClient=Fk;var Hk=require("events"),Gs=r_();Xn.MAX_GATEWAY_FRAME_BYTES=(()=>{let t=Number(process.env.AGENTHIPPO_GATEWAY_MAX_FRAME_BYTES);return Number.isFinite(t)&&t>=1024*1024?t:16*1024*1024})();Xn.MAX_GATEWAY_MESSAGE_CHARS=256*1024;function jk(t){if(!t)return"WebSocket closed";let e=typeof t.code=="number"?t.code:void 0,n=typeof t.reason=="string"?t.reason.trim():"";if(e===1011)return`WebSocket closed (1011: internal error)${n?`: ${n}`:""}. Check the gateway/server logs for details.`;let r=e!==void 0?` (${e})`:"",s=n?`: ${n}`:"";return`WebSocket closed${r}${s}`}function xk(t){let e=typeof t?.code=="number"?t.code:void 0;return e!==void 0&&e!==1e3&&e!==1001}var Ho=class extends Hk.EventEmitter{options;ws=null;requestId=0;pendingRequests=new Map;connected=!1;reconnectAttempts=0;clientInfo=null;constructor(e){super(),this.options=e,this.on("error",()=>{})}async connect(e){return this.clientInfo=e,new Promise((n,r)=>{try{this.ws=new WebSocket(this.options.url)}catch(s){r(s);return}this.ws.onopen=async()=>{try{let s={minProtocol:Gs.PROTOCOL_VERSION,maxProtocol:Gs.PROTOCOL_VERSION,client:e,caps:[Gs.GATEWAY_CLIENT_CAPS.TOOL_EVENTS],role:"operator",scopes:[...Gs.DEFAULT_GATEWAY_OPERATOR_SCOPES],auth:this.options.token?{token:this.options.token}:void 0},i=await this.request("connect",s);this.connected=!0,this.reconnectAttempts=0,this.emit("connected",i),n(i)}catch(s){r(s)}},this.ws.onmessage=s=>{let i=typeof s.data=="string"?s.data:String(s.data);this.handleMessage(i)},this.ws.onerror=s=>{let i=new Error("WebSocket error");this.emit("error",i),this.connected||r(i)},this.ws.onclose=s=>{let i=this.connected;this.connected=!1,xk(s)&&this.emit("error",new Error(jk(s))),this.emit("disconnected",{code:typeof s?.code=="number"?s.code:void 0,reason:typeof s?.reason=="string"?s.reason:void 0,wasClean:typeof s?.wasClean=="boolean"?s.wasClean:void 0}),i&&this.clientInfo&&this.handleReconnect()}})}async request(e,n,r=3e4){if(!this.ws||this.ws.readyState!==WebSocket.OPEN)throw new Error("Not connected to Gateway");let s=String(++this.requestId);return new Promise((i,o)=>{let a=setTimeout(()=>{this.pendingRequests.delete(s),o(new Error(`Request ${e} timed out`))},r);this.pendingRequests.set(s,{resolve:i,reject:o,timeout:a});let c={type:"req",id:s,method:e,params:n};this.ws?.send(JSON.stringify(c))})}respond(e,n,r=!0,s){if(!this.ws||this.ws.readyState!==WebSocket.OPEN)return;let i={type:"res",id:e,ok:r,payload:r?n:void 0,error:r?void 0:s};this.ws.send(JSON.stringify(i))}sendEvent(e,n){if(!this.ws||this.ws.readyState!==WebSocket.OPEN)return;let r={type:"event",event:e,payload:n};this.ws.send(JSON.stringify(r))}handleMessage(e){let n=typeof e=="string"?Buffer.byteLength(e,"utf8"):0;if(n>Xn.MAX_GATEWAY_FRAME_BYTES){this.emit("error",new Error(`Gateway frame of ${n} bytes exceeds the ${Xn.MAX_GATEWAY_FRAME_BYTES}-byte limit and was dropped. Attachments normally travel as references, so this suggests inline payloads; raise AGENTHIPPO_GATEWAY_MAX_FRAME_BYTES if this traffic is expected.`));return}let r;try{r=JSON.parse(e)}catch{this.emit("error",new Error("Failed to parse Gateway message"));return}r.type==="res"?this.handleResponse(r):r.type==="event"?this.handleEvent(r):r.type==="req"&&this.emit("request",r)}handleResponse(e){let n=this.pendingRequests.get(e.id);if(n)if(clearTimeout(n.timeout),this.pendingRequests.delete(e.id),e.ok)n.resolve(e.payload);else{let r=new Error(e.error?.message||"Request failed");r.code=e.error?.code,n.reject(r)}}handleEvent(e){this.emit("event",e.event,e.payload),this.emit(`event:${e.event}`,e.payload)}reconnectTimer=null;isReconnecting=!1;handleReconnect(){if(this.options.reconnectInterval&&!this.isReconnecting){if(this.reconnectAttempts>=(this.options.maxReconnectAttempts??10)){this.emit("reconnect-failed");return}this.isReconnecting=!0,this.reconnectAttempts++,this.emit("reconnecting",this.reconnectAttempts),this.reconnectTimer&&clearTimeout(this.reconnectTimer),this.reconnectTimer=setTimeout(async()=>{if(this.isReconnecting=!1,this.clientInfo)try{await this.connect(this.clientInfo)}catch(e){this.emit("error",e instanceof Error?e:new Error(String(e)))}},this.options.reconnectInterval)}}async reconnect(){if(!this.clientInfo)throw new Error("Cannot reconnect: never connected");this.close(),this.reconnectAttempts=0,await this.connect(this.clientInfo)}close(){this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null),this.isReconnecting=!1,this.clientInfo=null;for(let[,n]of this.pendingRequests)clearTimeout(n.timeout),n.reject(new Error("Connection closed"));this.pendingRequests.clear();let e=this.ws;this.ws=null,this.connected=!1,e?.close()}get isConnected(){return this.connected}};Xn.GatewayClient=Ho;function Bk(t,e,n="1.0.0"){let r=new Ho({url:t,token:e,reconnectInterval:5e3,maxReconnectAttempts:10}),s={id:Gs.GATEWAY_CLIENT_IDS.GATEWAY_CLIENT,displayName:"AgentHippo IDE",version:n,platform:process.platform,mode:Gs.GATEWAY_CLIENT_MODES.AGENT_BACKEND};return{client:r,clientInfo:s}}function Fk(t,e,n="1.0.0"){let r=new Ho({url:t,token:e}),s={id:Gs.GATEWAY_CLIENT_IDS.GATEWAY_CLIENT,displayName:"AgentHippo CLI",version:n,platform:process.platform,mode:Gs.GATEWAY_CLIENT_MODES.AGENT_BACKEND};return{client:r,clientInfo:s}}});var Fd=S(Dt=>{"use strict";var Vk=Dt&&Dt.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,s)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),Wk=Dt&&Dt.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),xd=Dt&&Dt.__importStar||(function(){var t=function(e){return t=Object.getOwnPropertyNames||function(n){var r=[];for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(r[r.length]=s);return r},t(e)};return function(e){if(e&&e.__esModule)return e;var n={};if(e!=null)for(var r=t(e),s=0;s<r.length;s++)r[s]!=="default"&&Vk(n,e,r[s]);return Wk(n,e),n}})();Object.defineProperty(Dt,"__esModule",{value:!0});Dt.GATEWAY_OUTBOUND_RPC_METHOD=void 0;Dt.stageLocalMediaIfNeeded=s_;Dt.buildGatewayOutboundSendArgs=i_;Dt.buildGatewaySendParams=Bd;Dt.buildGatewayRpcCommand=jd;Dt.sendGatewayOutboundMessage=i$;var Kk=require("child_process"),qk=require("crypto"),Bi=xd(require("fs")),Yk=xd(require("os")),vr=xd(require("path")),Xk=Er(),Jk=Mc(),zk=18789;Dt.GATEWAY_OUTBOUND_RPC_METHOD="send";function Qk(t){return t?.trim()||process.env.AGENTHIPPO_GATEWAY_CLI?.trim()||"hippoclaw"}var Zk=".openclaw",e$=[".clawdbot",".moldbot",".moltbot"];function t$(){let t=Yk.homedir(),e=process.env.OPENCLAW_STATE_DIR?.trim()||process.env.CLAWDBOT_STATE_DIR?.trim();if(e)return e==="~"||e.startsWith("~/")||e.startsWith("~\\")?vr.join(t,e.slice(1)):vr.resolve(e);let n=vr.join(t,Zk);if(Bi.existsSync(n))return n;for(let r of e$){let s=vr.join(t,r);if(Bi.existsSync(s))return s}return n}function n$(t){return/^[a-z][a-z0-9+.-]*:\/\//i.test(t)||t.startsWith("data:")}function s_(t){let e=t?.trim();if(!e||n$(e))return t;let n;try{n=Bi.realpathSync(e)}catch{return e}let r=vr.join(t$(),"media"),s=vr.resolve(r);try{s=Bi.realpathSync(r)}catch{}let i=vr.relative(s,n);if(i&&!i.startsWith("..")&&!vr.isAbsolute(i))return n;let o=vr.extname(n),a=vr.basename(n,o),c=(0,qk.createHash)("sha256").update(n).digest("hex").slice(0,8),l=vr.join(r,`${a}-${c}${o}`);return Bi.mkdirSync(r,{recursive:!0}),Bi.copyFileSync(n,l),l}function i_(t,e,n){let r=["message","send","--channel",t.channel,"--target",t.target,"--message",e];return n?.trim()&&r.push("--media",n.trim()),t.accountId&&r.push("--account",t.accountId),t.threadId&&r.push("--thread-id",t.threadId),r}function Bd(t,e,n){return{to:t.target,message:e,channel:t.channel,accountId:t.accountId,threadId:t.threadId,sessionKey:t.sessionKey,agentId:t.agentId,idempotencyKey:`proactive:${t.agentId}:${Date.now()}`,...n?.trim()?{mediaUrl:n.trim()}:{}}}function jd(t,e,n){return[Dt.GATEWAY_OUTBOUND_RPC_METHOD,JSON.stringify(Bd(t,e,n))]}async function r$(t,e,n,r){let s=process.env.OPENCLAW_GATEWAY_URL?.trim()||`ws://127.0.0.1:${zk}`,i=r?.trim()||(0,Xk.readOpenClawGatewayToken)(),{client:o,clientInfo:a}=(0,Jk.createEphemeralGatewayClient)(s,i);await o.connect(a);try{let c=await o.request(Dt.GATEWAY_OUTBOUND_RPC_METHOD,Bd(t,e,n),6e4);return{stdout:JSON.stringify(c),stderr:""}}finally{o.close()}}function s$(t,e){let n=(0,Kk.spawnSync)(t,e,{encoding:"utf-8",env:process.env});return{stdout:(n.stdout??"").trim(),stderr:(n.stderr??"").trim(),exitCode:n.status}}async function i$(t,e){let n=Qk(e.cli);if(e.dryRun)return{ok:!0,via:"dry-run",command:jd(t,e.message,e.media),stdout:"",stderr:"",exitCode:0};let r=s_(e.media),s=i_(t,e.message,r),i=[n,...s],o=jd(t,e.message,r);try{let a=await r$(t,e.message,r,e.token);return{ok:!0,via:"gateway-rpc",command:o,stdout:a.stdout,stderr:a.stderr,exitCode:0}}catch(a){let c=a instanceof Error?a.message:String(a),l=s$(n,s);if(l.exitCode===0)return{ok:!0,via:"hippoclaw",command:i,stdout:l.stdout,stderr:l.stderr,exitCode:l.exitCode};let f=l.stderr||l.stdout||"unknown error";return{ok:!1,via:"gateway-rpc",command:o,stdout:l.stdout,stderr:`Gateway RPC failed: ${c}
524
- HippoClaw CLI fallback failed (exit ${l.exitCode??"unknown"}): ${f}`.trim(),exitCode:l.exitCode}}}});var p_=S(He=>{"use strict";var o$=He&&He.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,s)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),a$=He&&He.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),o_=He&&He.__importStar||(function(){var t=function(e){return t=Object.getOwnPropertyNames||function(n){var r=[];for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(r[r.length]=s);return r},t(e)};return function(e){if(e&&e.__esModule)return e;var n={};if(e!=null)for(var r=t(e),s=0;s<r.length;s++)r[s]!=="default"&&o$(n,e,r[s]);return a$(n,e),n}})();Object.defineProperty(He,"__esModule",{value:!0});He.isAwsCliAvailable=d$;He.resolveS3StateConfig=f$;He.resolveRestoreBootMode=p$;He.safeSessionId=Uc;He.sessionRemoteUri=Vd;He.shardBelongsToSession=Wd;He.hasLocalSessionState=a_;He.listSessionShardFiles=c_;He.stageSessionPushDir=l_;He.mergeSessionStagingIntoState=u_;He.restoreState=m$;He.pushState=d_;He.pushSessionState=f_;He.ensureSessionLocal=E$;He.clearRestoreAttemptCache=_$;He.makeStatePusher=y$;He.providerSessionShardName=w$;var c$=require("crypto"),l$=require("child_process"),Wt=o_(require("fs/promises")),hn=o_(require("path")),u$=require("util"),jo=(0,u$.promisify)(l$.execFile),Gc=new Set;async function d$(){try{return await jo("aws",["--version"]),!0}catch{return!1}}function f$(t=process.env){let e=t.AGENTHIPPO_STATE_S3_URI?.trim();return e?{uri:e.replace(/\/+$/,""),endpoint:t.AGENTHIPPO_STATE_S3_ENDPOINT?.trim()||void 0}:null}function p$(t=process.env){return t.AGENTHIPPO_STATE_RESTORE_BOOT?.trim().toLowerCase()==="none"?"none":"all"}function Uc(t){return t.trim().replace(/[<>:"/\\|?*\x00-\x1F]+/g,"_").replace(/\.\./g,"_").slice(0,160)||"session"}function Vd(t,e){return`${t.uri}/sessions/${Uc(e)}`}function Hc(t,e,n){let r=["s3","sync",e,n,"--no-progress"];return t.endpoint&&r.push("--endpoint-url",t.endpoint),r}function g$(t,e){return`${hn.resolve(t)}\0${e}`}function Wd(t,e,n){if(n?.chatSessionId&&n.chatSessionId===e)return!0;let r=t.split(":");return r.length>=2&&r[1]===e}async function a_(t,e){let n=hn.join(t,"provider-sessions"),r;try{r=await Wt.readdir(n)}catch{return!1}for(let s of r)if(s.endsWith(".json"))try{let i=await Wt.readFile(hn.join(n,s),"utf8"),o=JSON.parse(i);if(typeof o.key=="string"&&Wd(o.key,e,o.value))return!0}catch{}return!1}async function c_(t,e){let n=hn.join(t,"provider-sessions"),r;try{r=await Wt.readdir(n)}catch{return[]}let s=[];for(let i of r)if(i.endsWith(".json"))try{let o=await Wt.readFile(hn.join(n,i),"utf8"),a=JSON.parse(o);typeof a.key=="string"&&Wd(a.key,e,a.value)&&s.push(i)}catch{}return s}async function h$(t){try{return await Wt.access(t),!0}catch{return!1}}async function l_(t,e,n){await Wt.rm(n,{recursive:!0,force:!0}),await Wt.mkdir(n,{recursive:!0});let r=await c_(t,e),s=hn.join(n,"provider-sessions");if(r.length>0){await Wt.mkdir(s,{recursive:!0});for(let i of r)await Wt.copyFile(hn.join(t,"provider-sessions",i),hn.join(s,i))}return r.length>0}async function u_(t,e){let n=hn.join(t,"provider-sessions");if(await h$(n)){let r=hn.join(e,"provider-sessions");await Wt.mkdir(r,{recursive:!0});for(let s of await Wt.readdir(n))s.endsWith(".json")&&await Wt.copyFile(hn.join(n,s),hn.join(r,s))}}async function m$(t,e,n){try{await jo("aws",Hc(t,t.uri,e)),n?.(`State restored from ${t.uri}`)}catch(r){n?.(`State restore skipped: ${r instanceof Error?r.message:String(r)}`)}}async function d_(t,e,n){try{await jo("aws",Hc(t,e,t.uri))}catch(r){console.error(`[state-sync] push to ${t.uri} failed: ${r instanceof Error?r.message:String(r)}`),n?.(`State push failed: ${r instanceof Error?r.message:String(r)}`)}}async function f_(t,e,n,r){let s=Uc(n),i=hn.join(e,".push-staging",s);try{if(!await l_(e,n,i)){r?.(`State push skipped for session ${s}: nothing local`);return}let a=Vd(t,n);await jo("aws",Hc(t,i,a)),r?.(`State pushed session ${s} \u2192 ${a}`)}catch(o){console.error(`[state-sync] push session ${s} failed: ${o instanceof Error?o.message:String(o)}`),r?.(`State push failed for ${s}: ${o instanceof Error?o.message:String(o)}`)}finally{await Wt.rm(i,{recursive:!0,force:!0}).catch(()=>{})}}async function E$(t,e,n,r){let s=g$(e,n);if(Gc.has(s))return;if(await a_(e,n)){Gc.add(s);return}let i=Uc(n),o=hn.join(e,".restore-staging",i);try{await Wt.rm(o,{recursive:!0,force:!0}),await Wt.mkdir(o,{recursive:!0});let a=Vd(t,n);await jo("aws",Hc(t,a,o)),await u_(o,e),r?.(`State restored session ${i} from ${a}`)}catch(a){r?.(`State restore-on-miss skipped for ${i}: ${a instanceof Error?a.message:String(a)}`)}finally{Gc.add(s),await Wt.rm(o,{recursive:!0,force:!0}).catch(()=>{})}}function _$(){Gc.clear()}function y$(t,e,n,r=1e3){let s=null,i=!1,o=null,a=new Set,c=!1,l=()=>{i=!0;let d=[...a],p=c;return a.clear(),c=!1,o=(async()=>{p&&await d_(t,e,n);for(let g of d)await f_(t,e,g,n)})().catch(g=>{console.error(`[state-sync] push batch failed: ${g instanceof Error?g.message:String(g)}`)}).finally(()=>{i=!1,o=null,(a.size>0||c)&&(s||(s=setTimeout(()=>{s=null,l()},r),s.unref?.()))}),o};return{schedule:d=>{d?.trim()?a.add(d.trim()):c=!0,!i&&(s||(s=setTimeout(()=>{s=null,l()},r),s.unref?.()))},flush:async()=>{s&&(clearTimeout(s),s=null),o&&await o,(a.size>0||c)&&(await l(),o&&await o)}}}function w$(t){return`${(0,c$.createHash)("sha256").update(t).digest("hex").slice(0,40)}.json`}});var g_=S(Fr=>{"use strict";Object.defineProperty(Fr,"__esModule",{value:!0});Fr.CLI_GATEWAY_AGENT_PREFIX=void 0;Fr.resolveCliGatewayAgentId=T$;Fr.isCliGatewayAgentId=b$;var A$=Un();Fr.CLI_GATEWAY_AGENT_PREFIX="agenthippo-cli";function S$(t){return t.toLowerCase().replace(/[^a-z0-9-]/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,"").slice(0,32)||"unnamed"}function T$(t){let e=(t??"").trim().toLowerCase();return!e||e===A$.AGENT_CONSTANTS.DEFAULT_AGENT_ID?Fr.CLI_GATEWAY_AGENT_PREFIX:`${Fr.CLI_GATEWAY_AGENT_PREFIX}-${S$(e)}`}function b$(t){let e=(t??"").trim().toLowerCase();return e===Fr.CLI_GATEWAY_AGENT_PREFIX||e.startsWith(`${Fr.CLI_GATEWAY_AGENT_PREFIX}-`)}});var Yd=S(Es=>{"use strict";Object.defineProperty(Es,"__esModule",{value:!0});Es.fetchMeetAgentChannelContext=h_;Es.mapChannelsStatusToMeetAgentRows=qd;Es.parseChannelBindSpecs=P$;Es.applyAgentChannelBindingsViaConfigPatch=$$;Es.fetchMeetAgentChannelRows=D$;Es.waitForChannelsLive=M$;Es.resolvePublishedGatewayChannelIds=G$;var Kd={probe:!1,timeoutMs:1e4};async function h_(t){let e=await t("channels.status",Kd);return{rows:qd(e),statusPayload:e}}function Us(t){return t&&typeof t=="object"&&!Array.isArray(t)?t:null}function qd(t){let e=Us(t);if(!e)return[];let n=Array.isArray(e.channelOrder)?e.channelOrder:null,r=Us(e.channelLabels)??{},s=Us(e.channels)??{},i=Us(e.channelAccounts)??{},o=Us(e.channelDefaultAccountId)??{},a=n&&n.length>0?n:[...Object.keys(s)].sort((l,f)=>l.localeCompare(f)),c=[];for(let l of a){let f=typeof r[l]=="string"?r[l]:l,u=i[l],d=Array.isArray(u)?u:[],p=d.length>0?d.map(y=>typeof y.accountId=="string"?y.accountId:"default"):[typeof o[l]=="string"?o[l]:"default"],g=Us(s[l]),m=g&&typeof g.connected=="boolean"?g.connected:g?.running===!0,h=d.some(y=>typeof y.connected=="boolean"&&y.connected||y.running===!0),E=m||h,_=g?.configured===!0||d.some(y=>y.configured===!0&&y.enabled!==!1)||E;c.push({id:l,label:f,connected:E,enabled:_,accounts:p})}return c}function v$(t){let e=Us(t);if(!e)return{};let n=Us(e.channelDefaultAccountId)??{},r={};for(let[s,i]of Object.entries(n))typeof i=="string"&&i.trim()&&(r[s]=i.trim());return r}function O$(t,e){if(!t||typeof t!="object"||Array.isArray(t))return!1;let n=t;if(n.type==="acp"||String(n.agentId??"").trim().toLowerCase()!==e)return!1;let r=n.match;return!r||typeof r!="object"||r.peer?!1:typeof r.channel=="string"&&r.channel.trim().length>0}function I$(t){return typeof t!="string"||!t.trim()?"default":t.trim().toLowerCase()}function P$(t){return t.split(",").map(e=>e.trim()).filter(Boolean).map(e=>{let n=e.indexOf(":");if(n===-1)return{channelId:e};let r=e.slice(0,n).trim(),s=e.slice(n+1).trim();return s?{channelId:r,accountId:s}:{channelId:e}})}function N$(t){if(!t||typeof t!="object"||Array.isArray(t))return;let e=t.match?.channel;return typeof e=="string"&&e.trim()?e.trim():void 0}function R$(t){let e=N$(t);return!!(e&&e.includes(":"))}function C$(t,e,n){if(!t||typeof t!="object"||Array.isArray(t))return!1;let r=t;if(r.type==="acp"||String(r.type??"route").toLowerCase()!=="route")return!1;let i=r.match;if(!i||typeof i!="object"||i.peer)return!1;let o=typeof i.channel=="string"?i.channel.trim().toLowerCase():"",a=I$(i.accountId);return o===e.trim().toLowerCase()&&a===n.trim().toLowerCase()}function k$(t){let e=t.agentId.trim().toLowerCase(),n=i=>t.channelAccountOverrides?.[i]??t.channelDefaultAccountId[i]??"default",r=t.existingBindings.filter(i=>{if(R$(i)||O$(i,e))return!1;for(let o of t.selectedChannelIds){let a=n(o);if(C$(i,o,a))return!1}return!0}),s=t.selectedChannelIds.map(i=>{let o=n(i);return{type:"route",agentId:t.agentId.trim(),match:{channel:i,accountId:o}}});return[...r,...s]}async function $$(t,e){let n=e.statusPayload??await t("channels.status",Kd),r=v$(n),s=await t("config.get",{}),i=typeof s.hash=="string"?s.hash.trim():"";if(!i)throw new Error("config.get did not return hash; cannot config.patch bindings");let o=Array.isArray(s.config?.bindings)?s.config.bindings:[],a=k$({existingBindings:o,agentId:e.agentId,selectedChannelIds:e.selectedChannelIds,channelDefaultAccountId:r,channelAccountOverrides:e.channelAccountOverrides});return JSON.stringify(o)===JSON.stringify(a)?!1:(await t("config.patch",{baseHash:i,raw:JSON.stringify({bindings:a})}),!0)}async function D$(t){let{rows:e}=await h_(t);return e}var L$=t=>new Promise(e=>setTimeout(e,t));async function M$(t,e,n={}){let r=[...new Set(e.map(d=>d.trim().toLowerCase()).filter(Boolean))];if(r.length===0)return{ready:!0,live:[],pending:[],polls:0,timedOut:!1};let s=n.timeoutMs??8e3,i=n.intervalMs??400,o=n.sleep??L$,a=n.now??Date.now,c=a(),l=0,f=[],u=[...r];for(;;){l++;let d;try{let g=await t("channels.status",Kd);d=qd(g)}catch{d=[]}let p=new Set(d.filter(g=>g.connected).map(g=>g.id.trim().toLowerCase()));if(f=r.filter(g=>p.has(g)),u=r.filter(g=>!p.has(g)),u.length===0)return{ready:!0,live:f,pending:u,polls:l,timedOut:!1};if(a()-c>=s)return{ready:!1,live:f,pending:u,polls:l,timedOut:!0};await o(i)}}function G$(t,e){let n=e?.trim();return n?t.filter(r=>r.id.toLowerCase()===n.toLowerCase()).map(r=>r.id):t.filter(r=>r.enabled).map(r=>r.id)}});var S_=S(Kt=>{"use strict";var E_=Kt&&Kt.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(Kt,"__esModule",{value:!0});Kt.GatewayBridge=Kt.MAX_GATEWAY_ID_CHARS=void 0;Kt.isIdeThreadCompositeRouteKey=__;Kt.parseIdeThreadIdFromCompositeRouteKey=x$;Kt.findOversizedRunField=y_;Kt.buildIdeSessionRouteKey=w_;Kt.extractRouteLabelFromGatewaySessionKey=A_;Kt.looksLikeGatewayChannelRouteKey=F$;Kt.createGatewayBridge=V$;var U$=require("events"),Xd=Mc(),H$=E_(require("node:os")),Jd=E_(require("node:path")),j$=Rc(),m_=Fa(),Fi="::sid:";function __(t){return!!t?.includes(Fi)}function x$(t){if(!t||!__(t))return;let e=t.lastIndexOf(Fi),n=t.slice(e+Fi.length).trim();return n.length>0?n:void 0}Kt.MAX_GATEWAY_ID_CHARS=512;var B$=["agentId","sessionKey","sessionId","channel","accountId","target","threadId","groupId","senderUsername","senderName","senderId"];function y_(t){let e=t;for(let n of B$){let r=e[n];if(r!=null&&(typeof r!="string"||r.length>Kt.MAX_GATEWAY_ID_CHARS))return n}}function w_(t,e){let n=t?.trim(),r=e?.trim();return n&&r?`${n}${Fi}${r}`:n||r}function A_(t){let e=t.trim(),n="agent:";if(!e.toLowerCase().startsWith(n))return;let r=e.slice(n.length),s=r.indexOf(":");if(s<0)return;let i=r.slice(s+1).trim();return i.length>0?i:void 0}function F$(t){let e=t&&t.includes(Fi)?t.slice(0,t.lastIndexOf(Fi)):t,r=(e?A_(e)??e:void 0)?.split(":").filter(Boolean)??[];return r.length<2?!1:["channel","chat","dm","group","thread","user"].includes(r[1].trim().toLowerCase())}var jc=class extends U$.EventEmitter{options;client;clientInfo;agents=new Map;serverConnId=null;supportsAgentRegistration=null;isUnknownMethodError(e){return(e instanceof Error?e.message:String(e)).toLowerCase().includes("unknown method")}async ensureGatewayRuntimeRegistration(e,n){try{await this.client.request("agents.register",{agent:{id:e.id,name:e.name??e.id,workspace:n}})}catch(r){if(this.isUnknownMethodError(r))return;this.log(`agents.register follow-up failed (non-fatal): ${r instanceof Error?r.message:String(r)}`)}}constructor(e){super(),this.options=e,this.on("error",()=>{});let{client:n,clientInfo:r}=(0,Xd.createAgentIDEGatewayClient)(e.gatewayUrl,e.token,e.version);this.client=n,this.clientInfo=r,this.setupEventHandlers()}setupEventHandlers(){this.client.on("connected",async e=>{this.serverConnId=e.server.connId,this.log(`Connected to Gateway (connId=${this.serverConnId})`),this.emit("connected",e),this.agents.size>0&&await this.reregisterAllAgents()}),this.client.on("disconnected",()=>{this.log("Disconnected from Gateway"),this.emit("disconnected")}),this.client.on("error",e=>{this.log(`Gateway error: ${e.message}`),this.emit("error",e)}),this.client.on("reconnecting",e=>{this.log(`Reconnecting to Gateway (attempt ${e})...`),this.emit("reconnecting",e)}),this.client.on("request",e=>{this.handleServerRequest(e)}),this.client.on("event:agents.updated",e=>{this.emit("agents.updated",e)})}async connect(){return this.log(`Connecting to Gateway at ${this.options.gatewayUrl}...`),this.client.connect(this.clientInfo)}async registerAgent(e){if(this.agents.has(e.id))throw new Error(`Agent ${e.id} is already registered`);let n=(e.workspace??this.resolveOpenClawWorkspaceDir(e.id)).trim();if(!(e.syncOpenClawConfigAgent!==!1))await this.ensureGatewayRuntimeRegistration(e,n);else if(this.supportsAgentRegistration===!1)this.log(`Gateway remote agent management unavailable; using local registration for ${e.id}`);else{try{await this.client.request("agents.create",{name:e.id,workspace:n}),this.supportsAgentRegistration=!0}catch(s){let i=s instanceof Error?s.message:String(s);if(this.isUnknownMethodError(s))this.supportsAgentRegistration=!1,this.log(`Gateway remote agent management rejected (unknown method); using local registration for ${e.id}`);else if(i.toLowerCase().includes("already exists"))await this.client.request("agents.update",{agentId:e.id,workspace:n,name:e.name??e.id}),this.supportsAgentRegistration=!0;else throw s}await this.ensureGatewayRuntimeRegistration(e,n)}this.agents.set(e.id,e),this.log(`Registered agent: ${e.id}`),this.emit("agent.registered",e.id,{needsBinding:!0})}async reregisterAllAgents(){this.log(`Re-registering ${this.agents.size} agent(s) after reconnect...`);for(let e of this.agents.values())try{if(e.syncOpenClawConfigAgent===!1){let r=(e.workspace??this.resolveOpenClawWorkspaceDir(e.id)).trim();await this.ensureGatewayRuntimeRegistration(e,r),this.log(`Re-registered runtime agent: ${e.id}`);continue}if(this.supportsAgentRegistration===!1){this.log(`Skipping remote re-register for ${e.id} (gateway compatibility mode)`);continue}let n=(e.workspace??this.resolveOpenClawWorkspaceDir(e.id)).trim();try{await this.client.request("agents.create",{name:e.id,workspace:n})}catch(r){if((r instanceof Error?r.message:String(r)).toLowerCase().includes("already exists"))await this.client.request("agents.update",{agentId:e.id,workspace:n,name:e.name??e.id});else throw r}await this.ensureGatewayRuntimeRegistration(e,n),this.supportsAgentRegistration=!0,this.log(`Re-registered agent: ${e.id}`)}catch(n){if(this.isUnknownMethodError(n)){this.supportsAgentRegistration=!1,this.log(`Gateway rejected remote agent management during reconnect (unknown method); keeping local registration for ${e.id}`);continue}this.log(`Failed to re-register agent ${e.id}: ${n}`)}this.supportsAgentRegistration===!1&&this.log("Gateway compatibility mode active: inbound routing relies on plugin/session bridge, not agents.register.")}async unregisterAgent(e){if(this.agents.get(e))try{if(this.supportsAgentRegistration===!1){this.agents.delete(e),this.log(`Unregistered local agent: ${e} (gateway compatibility mode)`),this.emit("agent.unregistered",e);return}await this.client.request("agents.delete",{agentId:e,deleteFiles:!1},3e4),this.agents.delete(e),this.log(`Unregistered agent: ${e}`),this.emit("agent.unregistered",e)}catch(r){if(this.isUnknownMethodError(r)){this.supportsAgentRegistration=!1,this.agents.delete(e),this.log(`Gateway rejected remote agent management delete (unknown method); removed local agent ${e} instead`),this.emit("agent.unregistered",e);return}this.log(`Failed to unregister agent ${e}: ${r}`)}}isGatewayCompatMode(){return this.supportsAgentRegistration===!1}resolveOpenClawWorkspaceDir(e){let n=Jd.default.join(H$.default.homedir(),".openclaw");return e==="main"?Jd.default.join(n,"workspace"):Jd.default.join(n,`workspace-${e}`)}async handleServerRequest(e){e.method==="agent.run"?await this.handleAgentRun(e):e.method==="session.new"?await this.handleSessionNew(e):e.method==="agent.cancel"?this.handleAgentCancel(e):this.client.respond(e.id,void 0,!1,{code:"UNKNOWN_METHOD",message:`Unknown method: ${e.method}`})}handleAgentCancel(e){let n=e.params;this.log(`Received agent.cancel (agentId=${n?.agentId}, sessionKey=${n?.sessionKey})`),this.emit("agent.cancel",n),this.client.respond(e.id,{success:!0},!0)}async handleSessionNew(e){let n=e.params;this.log(`Received session.new request from ${n?.requestedBy??"unknown"}`),this.emit("session.new.request",{requestId:e.id,params:n??{}})}respondSessionNew(e,n){this.client.respond(e,n,n.success,n.success?void 0:{code:"SESSION_CREATE_ERROR",message:n.error??"Failed to create session"})}persistHeadlessGatewayOutbound(e,n,r,s,i){let o=e.workspace?.trim();if(!o)return;let a=r.sessionKey?.trim()||i,c=(0,m_.resolveGatewaySessionDirId)({gatewaySessionKey:a});if(!c)return;let l=(0,m_.getGatewayOutboundFilePath)(o,c),f=e.agentId?.trim()||n;(0,j$.upsertGatewayOutboundHandle)(l,f,r,s,{gatewayAgentId:n}).then(u=>{u&&this.log(`Gateway outbound routes: ${l}`)}).catch(u=>{this.log(`Failed to persist outbound handle: ${u instanceof Error?u.message:String(u)}`)})}async handleAgentRun(e){let n=e.params;if(!n?.message||typeof n.message!="string"){this.client.respond(e.id,void 0,!1,{code:"INVALID_PARAMS",message:"message is required"});return}if(n.message.length>Xd.MAX_GATEWAY_MESSAGE_CHARS){this.client.respond(e.id,void 0,!1,{code:"MESSAGE_TOO_LARGE",message:`message exceeds ${Xd.MAX_GATEWAY_MESSAGE_CHARS} characters`});return}let r=y_(n);if(r){this.client.respond(e.id,void 0,!1,{code:"INVALID_PARAMS",message:`${r} is not a valid string`});return}let s=n.agentId||this.getDefaultAgentId();if(!s){this.client.respond(e.id,void 0,!1,{code:"NO_AGENT",message:"No agent available"});return}let i=this.agents.get(s);if(!i){this.client.respond(e.id,void 0,!1,{code:"AGENT_NOT_FOUND",message:`Agent ${s} not found`});return}this.log(`Running agent ${s} for message: ${n.message.slice(0,50)}...`);let o=w_(n.sessionKey,n.sessionId),a=n.idempotencyKey||`${s}-${Date.now()}`;this.emit("agent.message",{agentId:s,message:n.message,channel:n.channel,sessionKey:n.sessionKey,sessionId:n.sessionId,routeKey:o});try{if(!!(i.useChatUI&&i.chatUIHandler)){this.log(`Routing gateway message to Chat UI for agent ${s} (routeKey=${o??"none"})`),await this.handleAgentRunViaChatUI(e,i,n,a,o);return}let l=i.engineId||"claude";if(!i.messageHandler)throw new Error("No message handler configured for agent");this.log(`Agent ${s} processing message via direct handler, engine=${l}`),this.persistHeadlessGatewayOutbound(i,s,n,a,o);let f=this.client,u="",d="",p=0,g=!1,m=150,h=o,E=()=>{u!==d&&(d=u,p=Date.now(),f.sendEvent("agent.stream",{runId:a,agentId:s,sessionKey:h,state:"delta",text:u}))},_={async thinking(){g||(E(),g=!0,f.sendEvent("agent.stream",{runId:a,agentId:s,sessionKey:h,state:"thinking"}))},async text(T){g=!1,u+=T,Date.now()-p>=m&&E()},async toolStart(T){E(),f.sendEvent("agent.stream",{runId:a,agentId:s,sessionKey:h,state:"tool",toolName:T,toolState:"start"})},async toolEnd(T){f.sendEvent("agent.stream",{runId:a,agentId:s,sessionKey:h,state:"tool",toolName:T,toolState:"end"})},async progress(T){f.sendEvent("agent.stream",{runId:a,agentId:s,sessionKey:h,state:"progress",message:T})},async question(T){return f.sendEvent("agent.stream",{runId:a,agentId:s,sessionKey:h,state:"progress",message:`Question: ${T.prompt}`}),{selected:[],freeText:null,declined:!0}},async error(T){u+=`
523
+ In either case set AGENTHIPPO_AUTH_PROXY_SECRET (and have the proxy send it) so a forged X-Auth-Request-Email is rejected \u2014 that is what actually stops the token-minting attack.`);return{address:e,isPublic:!0}}function eC(t=process.env){let e=t.AGENTHIPPO_AUTH_JWT_SECRET?.trim()||In.DEFAULT_JWT_SECRET,n=(t.AGENTHIPPO_AUTH_PUBLIC_URL?.trim()||`http://127.0.0.1:${t.AGENTHIPPO_AUTH_PORT?.trim()||"9780"}`).replace(/\/+$/,""),r=t.AGENTHIPPO_TEAM_STORE_REPO?.trim()||"agenthippoai/agenthippo-store",s=r.split("/")[0]||"agenthippoai",i=r.split("/")[1]||"agenthippo-store";return{port:Number(t.AGENTHIPPO_AUTH_PORT||9780),publicBaseUrl:n,jwtSecret:e,accessTokenTtlSec:Number(t.AGENTHIPPO_AUTH_ACCESS_TTL_SEC||3600),refreshTokenTtlSec:Number(t.AGENTHIPPO_AUTH_REFRESH_TTL_SEC||720*3600),allowedEmailDomains:zR(t.AGENTHIPPO_AUTH_ALLOWED_DOMAINS),devMode:t.AGENTHIPPO_AUTH_DEV==="1",rateLimitPerMin:t.AGENTHIPPO_AUTH_RATE_LIMIT!==void 0?Number(t.AGENTHIPPO_AUTH_RATE_LIMIT):60,logPii:t.AGENTHIPPO_AUTH_LOG_PII==="1",cookieName:t.AGENTHIPPO_AUTH_COOKIE_NAME?.trim()||"ah_token",cookieDomain:t.AGENTHIPPO_AUTH_COOKIE_DOMAIN?.trim()||"",idpBaseUrl:(t.AGENTHIPPO_AUTH_IDP_URL?.trim()||"").replace(/\/+$/,""),proxySecret:t.AGENTHIPPO_AUTH_PROXY_SECRET?.trim()||"",trustProxyHeadersUnverified:t.AGENTHIPPO_AUTH_TRUST_PROXY_UNVERIFIED==="1",dataDir:t.AGENTHIPPO_AUTH_DATA_DIR?.trim()||void 0,teamConfigured:!!t.AGENTHIPPO_TEAM_ID?.trim(),team:{id:t.AGENTHIPPO_TEAM_ID?.trim()||"team_default",name:t.AGENTHIPPO_TEAM_NAME?.trim()||"Default Team",storeRepo:r,storeIndexUrl:t.AGENTHIPPO_TEAM_STORE_INDEX_URL?.trim()||`https://${s}.github.io/${i}`,githubOrg:t.AGENTHIPPO_TEAM_GITHUB_ORG?.trim()||s,gatewayUrl:t.AGENTHIPPO_TEAM_GATEWAY_URL?.trim()||"https://gateway.agenthippo.ai/v1"}}}function tC(t,e){if(e.length===0)return!0;let n=t.split("@")[1]?.toLowerCase();return!!n&&e.includes(n)}});var Br=S($=>{"use strict";var nC=$&&$.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,s)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),rC=$&&$.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),bd=$&&$.__importStar||(function(){var t=function(e){return t=Object.getOwnPropertyNames||function(n){var r=[];for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(r[r.length]=s);return r},t(e)};return function(e){if(e&&e.__esModule)return e;var n={};if(e!=null)for(var r=t(e),s=0;s<r.length;s++)r[s]!=="default"&&nC(n,e,r[s]);return rC(n,e),n}})();Object.defineProperty($,"__esModule",{value:!0});$.TurnGate=$.TURN_LIMIT_BUSY_MESSAGE=$.RATE_LIMIT_BUSY_MESSAGE=$.TURN_GATE_BUSY_MESSAGE=$.TURN_GATE_RETRY_AFTER_SECONDS=$.TURN_QUEUE_ENV=$.MAX_CONCURRENT_TURNS_ENV=$.TurnLimiter=$.SESSION_WITHOUT_USER_REASON=$.REQUIRE_TENANT_ISOLATION_ENV=$.IDENTITY_PROXY_SECRET_ENV=$.IDENTITY_HEADER_ENV=$.PIN_ONLY_IDENTITY_HEADERS=$.RateLimiter=$.XFF_TRUSTED_HOPS_ENV=$.CONTAINER_SERVE_HOST=$.SERVE_HOST_ENV=$.DEFAULT_BIND_HOST=$.SERVICE_USER_ENV=$.DEFAULT_MAX_BODY_BYTES=void 0;$.resolveStateDir=aC;$.resolveAnalyticsSessionsDir=cC;$.resolveServiceIdentity=lC;$.isLoopbackHost=DE;$.resolveBindHost=uC;$.clientIp=dC;$.hasTrustedProxyProof=ME;$.identityHeaderAdvice=fC;$.tenantIsolationAdvice=pC;$.resolveUserId=gC;$.resolveDataToken=mC;$.peerToUserId=EC;$.userNamespaceHash=Sd;$.resolveServeSessionKey=_C;$.corsHeaders=yC;$.createTurnGateFromEnv=wC;$.createRejectionWarner=AC;$.readBodyWithCap=SC;var sC=bd(require("os")),hs=bd(require("path")),Ic=bd(require("crypto")),iC=Ys(),oC=Mo();$.DEFAULT_MAX_BODY_BYTES=1024*1024;function aC(t,e=process.env){let n=t?.trim();if(n)return{dir:hs.resolve(n),ephemeral:!1};let r=e.AGENTHIPPO_HOME?.trim()||e.AGENTIDE_HOME?.trim();return r?{dir:hs.join(hs.resolve(r),"serve-state"),ephemeral:!1}:{dir:hs.join(sC.tmpdir(),"agenthippo-server"),ephemeral:!0}}function cC(t,e,n=process.env){return!(n.AGENT_HOME_DIR?.trim()||n.AGENTHIPPO_HOME?.trim())&&!e?hs.join(t,"analytics","sessions"):hs.join((0,iC.getAgentideHome)(),"analytics","sessions")}$.SERVICE_USER_ENV="AGENTHIPPO_SERVICE_USER";var kE=256;function lC(t=process.env){let e=t[$.SERVICE_USER_ENV];if(e===void 0)return{};let n=e.trim();return n?/\s/.test(n)?{error:`${$.SERVICE_USER_ENV} must not contain whitespace, got ${JSON.stringify(e)}.`}:n.length>kE?{error:`${$.SERVICE_USER_ENV} is ${n.length} chars; the maximum is ${kE}.`}:/^svc:/.test(n)||/^spiffe:\/\//.test(n)||/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(n)?{identity:n}:{identity:n,warning:`${$.SERVICE_USER_ENV}="${n}" carries no namespace marker (svc: / spiffe:// / GUID). It will be used verbatim and must be mapped in the connector role map, exactly like a human identity. If it can collide with a real user id, prefix it with \`svc:\`.`}:{error:`${$.SERVICE_USER_ENV} is set but empty. Unset it, or give it the identity unattended runs should act as.`}}$.DEFAULT_BIND_HOST="127.0.0.1";function DE(t){let e=t.trim().toLowerCase().replace(/^\[|\]$/g,"");return e==="localhost"||e==="::1"||/^127\./.test(e)}$.SERVE_HOST_ENV="AGENTHIPPO_SERVE_HOST";$.CONTAINER_SERVE_HOST="0.0.0.0";function uC(t,e=process.env){return t?.trim()||e.AGENTHIPPO_SERVE_HOST?.trim()||$.DEFAULT_BIND_HOST}$.XFF_TRUSTED_HOPS_ENV="AGENTHIPPO_XFF_TRUSTED_HOPS";function dC(t,e=process.env){let n=t.headers["x-forwarded-for"],r=Array.isArray(n)?n[0]:n;if(r){let s=r.split(",").map(i=>i.trim()).filter(Boolean);if(s.length>0){let i=Number(e[$.XFF_TRUSTED_HOPS_ENV]),o=Number.isInteger(i)&&i>=1?i:1;return s[Math.max(0,s.length-o)]}}return t.socket?.remoteAddress||"unknown"}var Ad=class t{maxPerWindow;windowMs;hits=new Map;static MAX_KEYS=1e5;constructor(e,n=6e4){this.maxPerWindow=e,this.windowMs=n}tryConsume(e,n=Date.now()){if(!Number.isFinite(this.maxPerWindow)||this.maxPerWindow<=0)return!0;let r=this.hits.get(e);return!r||r.resetAt<=n?(this.hits.size>=t.MAX_KEYS&&this.prune(n),this.hits.set(e,{count:1,resetAt:n+this.windowMs}),!0):r.count>=this.maxPerWindow?!1:(r.count+=1,!0)}retryAfterSeconds(e,n=Date.now()){let r=this.hits.get(e);return r?Math.max(1,Math.ceil((r.resetAt-n)/1e3)):Math.ceil(this.windowMs/1e3)}prune(e){for(let[n,r]of this.hits)r.resetAt<=e&&this.hits.delete(n);this.hits.size>=t.MAX_KEYS&&this.hits.clear()}};$.RateLimiter=Ad;var LE=["x-forwarded-email","x-forwarded-preferred-username","x-goog-authenticated-user-email","cf-access-authenticated-user-email"];$.PIN_ONLY_IDENTITY_HEADERS=["x-agent-user"];$.IDENTITY_HEADER_ENV="AGENTHIPPO_IDENTITY_HEADER";$.IDENTITY_PROXY_SECRET_ENV="AGENTHIPPO_IDENTITY_PROXY_SECRET";function ME(t,e){if(!e)return!1;let n=t[oC.AUTH_PROXY_SECRET_HEADER],r=typeof n=="string"?n:Array.isArray(n)?String(n[0]??""):"";if(!r)return!1;let s=Ic.createHash("sha256").update(r).digest(),i=Ic.createHash("sha256").update(e).digest();return Ic.timingSafeEqual(s,i)}function fC(t=process.env,e){if(t[$.IDENTITY_HEADER_ENV]?.trim())return[];let r=e?.trim();return r&&DE(r)?[`${$.IDENTITY_HEADER_ENV} is not set. Fine for this loopback bind; pin it before exposing serve on a network interface.`]:[...r?[`serve is bound to ${r} \u2014 reachable beyond this machine \u2014 with no ${$.IDENTITY_HEADER_ENV} pinned. Anyone who can reach this port is trusted to state who they are.`]:[],`${$.IDENTITY_HEADER_ENV} is not set, so identity falls back to the platform header aliases (${LE.join(", ")}). That is only safe when your proxy sets AND STRIPS every one of them. Pin the single header your deploy layer really controls, e.g. ${$.IDENTITY_HEADER_ENV}=x-goog-authenticated-user-email.`,`NOTE: ${$.PIN_ONLY_IDENTITY_HEADERS.join(", ")} is NO LONGER trusted by default \u2014 it is not stripped by any platform, so an arbitrary client could send it and be namespaced as another user. If your proxy does set it (the Caddy forward_auth / auth-broker flow does), pin it: ${$.IDENTITY_HEADER_ENV}=x-agent-user.`]}$.REQUIRE_TENANT_ISOLATION_ENV="AGENTHIPPO_REQUIRE_TENANT_ISOLATION";function $E(t,e){let n=hs.resolve(t),r=hs.resolve(e);return n===r||n.startsWith(r+hs.sep)}function pC(t,e=process.env){if(!e[$.IDENTITY_HEADER_ENV]?.trim())return{level:"ok",lines:[]};if(t.sandbox==="container"&&!t.sharedWorkspace)return{level:"ok",lines:[]};let r=t.sandbox==="process"?"a tier-0 (--sandbox=process) sandbox":"no sandbox",s=[`${$.IDENTITY_HEADER_ENV} is pinned \u2014 so this serve has more than one user \u2014 but it runs with ${r}, which shares one uid, one workspace (${t.workspace??"unset"}) and one state dir (${t.stateDir}) across all of them. Any user can read every other user's engine session files, which hold their conversations verbatim. Per-user paths are namespacing, not isolation.`,"The boundary is --sandbox=container (per-session workspace and state, without --shared-workspace) or one serve per tenant. Until then, restrict the pack's tool surface so the agent has no way to read arbitrary files."];return t.workspace&&$E(t.workspace,t.stateDir)?s.push(`--workspace ${t.workspace} sits INSIDE --state-dir ${t.stateDir}: every other user's sessions, analytics and evidence spool are one '..' above the agent's own cwd. Put them in unrelated subtrees (e.g. --workspace=/work --state-dir=/state).`):t.workspace&&$E(t.stateDir,t.workspace)&&s.push(`--state-dir ${t.stateDir} sits INSIDE --workspace ${t.workspace}: every other user's sessions, analytics and evidence spool are inside the directory the agent is pointed at. Put them in unrelated subtrees (e.g. --workspace=/work --state-dir=/state).`),{level:/^(1|true|yes|on)$/i.test(e[$.REQUIRE_TENANT_ISOLATION_ENV]?.trim()??"")?"refuse":"warn",lines:s}}function gC(t,e,n=process.env){let r=n[$.IDENTITY_PROXY_SECRET_ENV]?.trim();if(r&&!ME(t,r))return;let s=n[$.IDENTITY_HEADER_ENV]?.trim().toLowerCase(),i=s?[s]:LE;for(let a of i){let c=t[a],l=(Array.isArray(c)?c[0]:c)?.trim();if(l){let f=l.lastIndexOf(":");return f>=0&&l.slice(f+1).includes("@")?l.slice(f+1):l}}return s||n.AGENTHIPPO_ALLOW_BODY_IDENTITY?.trim()!=="1"?void 0:e?.user_id?.trim()||void 0}var hC=["x-forwarded-access-token","x-agent-data-token"];function mC(t){for(let e of hC){let n=t[e],r=(Array.isArray(n)?n[0]:n)?.trim();if(r)return r}}function EC(t){if(!t)return;let e=t.senderId?.trim()||t.senderUsername?.trim()||t.senderName?.trim();if(!e)return;let n=t.channel?.trim();return n?`${n}:${e}`:e}$.SESSION_WITHOUT_USER_REASON="session_without_verified_user";function Sd(t){return Ic.createHash("sha256").update(t).digest("hex").slice(0,16)}function _C(t,e,n="session",r=process.env){let s=t?.trim(),i=e?.trim();if(i){let a=`u${Sd(i)}--${s||"default"}`;return{sessionKey:a,sandboxKey:n==="user"?`u${Sd(i)}`:a}}if(r[$.IDENTITY_HEADER_ENV]?.trim())return{sessionKey:"",sandboxKey:"",rejected:$.SESSION_WITHOUT_USER_REASON};let o=s||"anon-unknown";return{sessionKey:o,sandboxKey:o}}function yC(){return{"Access-Control-Allow-Methods":"GET, POST, OPTIONS","Access-Control-Allow-Headers":"Content-Type, Authorization, X-Agent-User","Access-Control-Allow-Origin":"*"}}var Td=class{maxPerSession;counts=new Map;constructor(e){this.maxPerSession=e}tryConsume(e){if(!Number.isFinite(this.maxPerSession)||this.maxPerSession<=0)return!0;let n=this.counts.get(e)??0;return n>=this.maxPerSession?!1:(this.counts.set(e,n+1),!0)}reset(e){this.counts.delete(e)}};$.TurnLimiter=Td;$.MAX_CONCURRENT_TURNS_ENV="AGENTHIPPO_MAX_CONCURRENT_TURNS";$.TURN_QUEUE_ENV="AGENTHIPPO_TURN_QUEUE";$.TURN_GATE_RETRY_AFTER_SECONDS=15;$.TURN_GATE_BUSY_MESSAGE="At capacity \u2014 please retry in a moment";$.RATE_LIMIT_BUSY_MESSAGE="Rate limit exceeded \u2014 please retry in a moment";$.TURN_LIMIT_BUSY_MESSAGE="Per-session turn limit reached";var Pc=class{maxInflight;maxQueue;queueTimeoutMs;inflightCount=0;waiters=[];constructor(e,n,r=$.TURN_GATE_RETRY_AFTER_SECONDS*1e3){this.maxInflight=e,this.maxQueue=n,this.queueTimeoutMs=r}async acquire(){return!Number.isFinite(this.maxInflight)||this.maxInflight<=0?()=>{}:this.inflightCount<this.maxInflight?(this.inflightCount+=1,()=>this.releaseSlot()):this.waiters.length>=this.maxQueue?null:new Promise(e=>{let n=!1,r=o=>{if(n){o&&o();return}n=!0,clearTimeout(i),e(o)},s={resolve:r,timer:null},i=setTimeout(()=>{let o=this.waiters.indexOf(s);o>=0&&this.waiters.splice(o,1),r(null)},this.queueTimeoutMs);s.timer=i,this.waiters.push(s)})}releaseSlot(){let e=this.waiters.shift();if(e){e.resolve(()=>this.releaseSlot());return}this.inflightCount=Math.max(0,this.inflightCount-1)}get inflight(){return this.inflightCount}get queued(){return this.waiters.length}get max(){return this.maxInflight>0?this.maxInflight:0}};$.TurnGate=Pc;function wC(t=process.env){let e=Number(t[$.MAX_CONCURRENT_TURNS_ENV]??10),n=Number(t[$.TURN_QUEUE_ENV]??20),r=Number.isFinite(e)?e:10,s=Number.isFinite(n)&&n>=0?n:20;return new Pc(r,s)}function AC(t=5e3){let e=0;return n=>{let r=Date.now();r-e<t||(e=r,console.warn(n))}}function SC(t,e=$.DEFAULT_MAX_BODY_BYTES){return new Promise((n,r)=>{let s=0,i=[],o=f=>{if(s+=f.length,s>e){l();let u=new Error(`Request body exceeds ${e} bytes`);u.tooLarge=!0,r(u);return}i.push(f)},a=()=>{l(),n(Buffer.concat(i).toString("utf8"))},c=f=>{l(),r(f)},l=()=>{t.off("data",o),t.off("end",a),t.off("error",c)};t.on("data",o),t.on("end",a),t.on("error",c)})}});var Uo=S($s=>{"use strict";Object.defineProperty($s,"__esModule",{value:!0});$s.TurnRegistry=$s.DEFAULT_TURN_DEADLINE_MS=void 0;$s.hashNonce=Go;var GE=require("crypto");$s.DEFAULT_TURN_DEADLINE_MS=30*6e4;function Go(t){return(0,GE.createHash)("sha256").update(t).digest("hex")}var vd=class{entries=new Map;register(e){this.prune();let n=(0,GE.randomBytes)(16).toString("hex"),r=Go(n);this.entries.set(r,{userId:e.userId,sessionKey:e.sessionKey,inboundToken:e.inboundToken,egressStoreKey:e.egressStoreKey,deadline:e.deadline??Date.now()+$s.DEFAULT_TURN_DEADLINE_MS});let s=!1;return{nonce:n,release:()=>{s||(s=!0,this.entries.delete(r))}}}releaseByNonce(e){return this.entries.delete(Go(e))}resolve(e,n=Date.now()){let r=this.entries.get(Go(e));if(r){if(n>r.deadline){this.entries.delete(Go(e));return}return r}}prune(e=Date.now()){for(let[n,r]of this.entries)e>r.deadline&&this.entries.delete(n)}get size(){return this.entries.size}};$s.TurnRegistry=vd});var Id=S(Sr=>{"use strict";Object.defineProperty(Sr,"__esModule",{value:!0});Sr.CredentialBroker=Sr.identityProvider=Sr.passthroughProvider=void 0;Sr.resolveProvider=TC;Sr.passthroughProvider={name:"passthrough",refreshOnInbound:!0,async acquire({userId:t,inboundToken:e}){let n=e?.trim();if(!n)throw new Error(`No inbound data credential for user (fail-closed) \u2014 the platform did not forward a per-user token on this request (userId=${t})`);return{expiresAt:Date.now()+10*6e4,secretRef:n}}};Sr.identityProvider={name:"identity",async acquire({userId:t}){if(!t.trim())throw new Error("No verified user (fail-closed)");return{expiresAt:Number.MAX_SAFE_INTEGER,secretRef:null}}};function TC(t){let e=(t??"passthrough").trim().toLowerCase();if(e==="passthrough")return Sr.passthroughProvider;if(e==="identity")return Sr.identityProvider;throw new Error(`Unknown data credential provider "${t}" (supported: passthrough, identity)`)}var Od=class{provider;cache=new Map;constructor(e){this.provider=e}async acquire(e,n){if(this.provider.refreshOnInbound)return this.provider.acquire({userId:e,inboundToken:n});let r=this.cache.get(e);if(r&&r.expiresAt>Date.now())return r;this.cache.delete(e);let s=await this.provider.acquire({userId:e,inboundToken:n});return this.cache.set(e,s),s}invalidate(e){this.cache.delete(e)}};Sr.CredentialBroker=Od});var Nd=S(Pn=>{"use strict";var bC=Pn&&Pn.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,s)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),vC=Pn&&Pn.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),OC=Pn&&Pn.__importStar||(function(){var t=function(e){return t=Object.getOwnPropertyNames||function(n){var r=[];for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(r[r.length]=s);return r},t(e)};return function(e){if(e&&e.__esModule)return e;var n={};if(e!=null)for(var r=t(e),s=0;s<r.length;s++)r[s]!=="default"&&bC(n,e,r[s]);return vC(n,e),n}})();Object.defineProperty(Pn,"__esModule",{value:!0});Pn.ConnectorHost=Pn.TURN_META_KEY=void 0;var UE=OC(require("path")),IC=require("fs"),PC=require("@modelcontextprotocol/sdk/client/index.js"),NC=require("@modelcontextprotocol/sdk/client/stdio.js"),RC=require("@modelcontextprotocol/sdk/types.js"),CC=Xa();Pn.TURN_META_KEY="ai.agenthippo/turn";var Pd=class t{client;logger;connectorPath;constructor(e,n,r){this.client=e,this.logger=n,this.connectorPath=r}static async spawn(e){let n=UE.resolve(e.connectorPath);await IC.promises.access(n);let r=await(0,CC.resolveNodeBinary)(),s=new NC.StdioClientTransport({command:r,args:[n],cwd:UE.dirname(n),env:{...process.env,AGENTHIPPO_DATA_CONNECTOR:"1"},stderr:"pipe"}),i=new PC.Client({name:"agenthippo-data-gateway",version:"1.0.0"});return await i.connect(s),s.stderr?.on("data",o=>{e.logger?.warn(`[DataPlane] connector stderr: ${String(o).trimEnd()}`)}),e.logger?.info(`[DataPlane] connector started: ${n}`),new t(i,e.logger,n)}async listTools(){return(await this.client.listTools()).tools.map(n=>({name:n.name,description:n.description,inputSchema:n.inputSchema??{type:"object"}}))}async callTool(e,n,r){return await this.client.request({method:"tools/call",params:{name:e,arguments:n,_meta:{[Pn.TURN_META_KEY]:{userId:r.userId,credential:r.credential}}}},RC.CallToolResultSchema)}async close(){try{await this.client.close()}catch(e){this.logger?.warn(`[DataPlane] connector close: ${e instanceof Error?e.message:String(e)}`)}}};Pn.ConnectorHost=Pd});var Ho=S(sn=>{"use strict";var kC=sn&&sn.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,s)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),$C=sn&&sn.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),DC=sn&&sn.__importStar||(function(){var t=function(e){return t=Object.getOwnPropertyNames||function(n){var r=[];for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(r[r.length]=s);return r},t(e)};return function(e){if(e&&e.__esModule)return e;var n={};if(e!=null)for(var r=t(e),s=0;s<r.length;s++)r[s]!=="default"&&kC(n,e,r[s]);return $C(n,e),n}})();Object.defineProperty(sn,"__esModule",{value:!0});sn.TURN_NONCE_HEADER=sn.TURN_NONCE_ENV=sn.DATA_MCP_URL_ENV=void 0;sn.startDataGateway=jC;var LC=DC(require("http")),MC=require("@modelcontextprotocol/sdk/server/index.js"),GC=require("@modelcontextprotocol/sdk/server/streamableHttp.js"),HE=require("@modelcontextprotocol/sdk/types.js"),UC=Br(),HC=Uo();sn.DATA_MCP_URL_ENV="AGENTHIPPO_DATA_MCP_URL";sn.TURN_NONCE_ENV="AGENTHIPPO_TURN_NONCE";sn.TURN_NONCE_HEADER="x-agent-turn-nonce";function jE(t){return t?.match(/^Bearer\s+(\S+)$/i)?.[1]}function xE(t){return t?(0,HC.hashNonce)(t).slice(0,12):"none"}async function jC(t){let e=LC.createServer(async(i,o)=>{try{let a=i.url?.split("?")[0]??"";if(a==="/turn"&&i.method==="DELETE"){let p=jE(i.headers.authorization);if(p){let g=t.registry.releaseByNonce(p);t.audit?.("edge","turn_release",{released:g,nonce_sha256_prefix:xE(p)})}o.writeHead(204),o.end();return}if(a!=="/mcp"){o.writeHead(404,{"Content-Type":"application/json"}),o.end(JSON.stringify({error:"not found"}));return}if(i.method!=="POST"){o.writeHead(405,{"Content-Type":"application/json",Allow:"POST"}),o.end(JSON.stringify({error:"method not allowed"}));return}let c=jE(i.headers.authorization),l=c?t.registry.resolve(c):void 0;if(!l){t.audit?.("unauthorized","nonce_reject",{reason:c?"unknown_or_expired":"missing",nonce_sha256_prefix:xE(c)}),o.writeHead(401,{"Content-Type":"application/json"}),o.end(JSON.stringify({jsonrpc:"2.0",error:{code:-32001,message:"Unauthorized: missing, unknown, or expired turn nonce"},id:null}));return}t.logger?.info(`[DataPlane] authorized request user=${l.userId} session=${l.sessionKey}`);let f;try{f=JSON.parse(await(0,UC.readBodyWithCap)(i))}catch{o.writeHead(400,{"Content-Type":"application/json"}),o.end(JSON.stringify({jsonrpc:"2.0",error:{code:-32700,message:"Parse error"},id:null}));return}let u=xC(t,l),d=new GC.StreamableHTTPServerTransport({sessionIdGenerator:void 0,enableJsonResponse:!0});o.on("close",()=>{d.close(),u.close()}),await u.connect(d),await d.handleRequest(i,o,f)}catch(a){t.logger?.warn(`[DataPlane] gateway error: ${a instanceof Error?a.message:String(a)}`),o.headersSent||o.writeHead(500,{"Content-Type":"application/json"}),o.end(JSON.stringify({jsonrpc:"2.0",error:{code:-32603,message:"Internal error"},id:null}))}}),n=t.host??"127.0.0.1";await new Promise((i,o)=>{e.once("error",o),e.listen(t.port??0,n,()=>i())});let r=e.address();if(!r||typeof r=="string")throw new Error("Data gateway failed to bind a port");let s=`http://${t.advertiseHost??"127.0.0.1"}:${r.port}/mcp`;return t.logger?.info(`[DataPlane] gateway listening at ${s}`),{url:s,close:()=>new Promise(i=>e.close(()=>i()))}}function xC(t,e){let n=new MC.Server({name:"agenthippo-data-gateway",version:"1.0.0"},{capabilities:{tools:{}}});return n.setRequestHandler(HE.ListToolsRequestSchema,async()=>({tools:await t.connector.listTools()})),n.setRequestHandler(HE.CallToolRequestSchema,async r=>{let s=r.params.name,i;try{i=(await t.broker.acquire(e.userId,e.inboundToken)).secretRef,t.audit?.(e.sessionKey,"tool_authorize",{tool:s,userId:e.userId,provider:t.broker.provider.name})}catch(o){let a=o instanceof Error?o.message:String(o);return t.audit?.(e.sessionKey,"tool_deny",{tool:s,userId:e.userId,reason:"acquire_failed",error:a}),{content:[{type:"text",text:JSON.stringify({ok:!1,error:`credential acquire failed (fail-closed): ${a}`})}],isError:!0}}try{return await t.connector.callTool(s,r.params.arguments??{},{userId:e.userId,credential:i})}catch(o){let a=o instanceof Error?o.message:String(o);if(/401|unauthoriz|expired/i.test(a)){t.broker.invalidate(e.userId);try{let c=await t.broker.acquire(e.userId,e.inboundToken);return await t.connector.callTool(s,r.params.arguments??{},{userId:e.userId,credential:c.secretRef})}catch{}}return t.audit?.(e.sessionKey,"tool_deny",{tool:s,userId:e.userId,reason:"call_failed",error:a}),{content:[{type:"text",text:JSON.stringify({ok:!1,error:a})}],isError:!0}}}),n}});var FE=S(Tr=>{"use strict";var BC=Tr&&Tr.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,s)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),FC=Tr&&Tr.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),VC=Tr&&Tr.__importStar||(function(){var t=function(e){return t=Object.getOwnPropertyNames||function(n){var r=[];for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(r[r.length]=s);return r},t(e)};return function(e){if(e&&e.__esModule)return e;var n={};if(e!=null)for(var r=t(e),s=0;s<r.length;s++)r[s]!=="default"&&BC(n,e,r[s]);return FC(n,e),n}})();Object.defineProperty(Tr,"__esModule",{value:!0});Tr.backupTimestamp=KC;Tr.backupPathFor=BE;Tr.renameToBackup=qC;var WC=require("fs"),Rd=VC(require("path"));function KC(t=new Date){return t.toISOString().replace(/[-:]/g,"").replace(/\.\d+Z$/,"Z")}function BE(t,e){let n=Rd.dirname(t),r=Rd.basename(t).replace(/\.json$/i,"");return Rd.join(n,`${r}.${e}.bk`)}async function qC(t,e){let n=BE(t,e);try{return await WC.promises.rename(t,n),n}catch(r){if((r&&typeof r=="object"&&"code"in r?String(r.code):"")==="ENOENT")return;throw r}}});var kc=S(vt=>{"use strict";var YC=vt&&vt.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,s)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),XC=vt&&vt.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),JC=vt&&vt.__importStar||(function(){var t=function(e){return t=Object.getOwnPropertyNames||function(n){var r=[];for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(r[r.length]=s);return r},t(e)};return function(e){if(e&&e.__esModule)return e;var n={};if(e!=null)for(var r=t(e),s=0;s<r.length;s++)r[s]!=="default"&&YC(n,e,r[s]);return XC(n,e),n}})();Object.defineProperty(vt,"__esModule",{value:!0});vt._resetOutboundHandleStoreLockForTest=QC;vt._setOutboundHandleStorePathForTest=ZC;vt.buildGatewayOutboundHandleKey=qE;vt.upsertGatewayOutboundHandle=ik;vt.getLastGatewayOutboundHandle=ok;vt.listGatewayOutboundTargets=ak;vt.mergeGatewayOutboundHandles=ck;vt.resolveGatewayOutboundHandle=lk;vt.backupAndClearOutboundHandlesForAgent=uk;vt.getGatewayOutboundStoreSnapshot=dk;var Nc=require("fs"),zC=JC(require("path")),VE=FE(),kd=1,KE={value:void 0},xi=new Map,Cd=new Map;function $d(t,e){let r=(Cd.get(t)??Promise.resolve()).then(()=>e());return Cd.set(t,r.catch(()=>{})),r}function QC(){Cd.clear(),xi.clear()}function ZC(t){KE.value=t,xi.clear()}function jo(t){return KE.value??t}function qE(t,e){let n=e?.trim();return n?`${t}::thread:${n}`:`${t}::`}function ek(){return{version:kd,lastByAgent:{},targetsByAgent:{}}}async function Ls(t){let e=jo(t),n=xi.get(e);if(n)return n;try{let s=await Nc.promises.readFile(e,"utf-8"),i=JSON.parse(s);if(i.targetsByAgent&&typeof i.targetsByAgent=="object"){let o={version:i.version??kd,lastByAgent:i.lastByAgent??{},targetsByAgent:i.targetsByAgent};return xi.set(e,o),o}}catch{}let r=ek();return xi.set(e,r),r}async function Dd(t,e){let n=jo(t);await Nc.promises.mkdir(zC.dirname(n),{recursive:!0});let r={version:kd,lastByAgent:e.lastByAgent,targetsByAgent:e.targetsByAgent},s=`${n}.tmp`;await Nc.promises.writeFile(s,JSON.stringify(r,null,2),"utf-8"),await Nc.promises.rename(s,n),xi.set(n,e)}function Ds(t,e){if(e?.toLowerCase()!=="slack")return t;let n=t.match(/^(user|channel|group):(.+)$/i);return n?`${n[1].toLowerCase()}:${n[2].toUpperCase()}`:t}function WE(t,e,n){let r=Ds(t,n),s=Ds(e,n);return r.toLowerCase()===s.toLowerCase()}function tk(t,e,n){if(n)return t.find(i=>WE(i.target,e,i.channel)&&i.threadId?.trim()===n);let r=t.filter(i=>WE(i.target,e,i.channel));return r.length===0?void 0:r.find(i=>!i.threadId?.trim())??Rc(r)[0]}function nk(t,e){let n=t.match(/:thread:([^:]+)$/),r=n?t.slice(0,-n[0].length):t,s=r.match(/:direct:([^:]+)$/);if(s)return Ds(`user:${s[1]}`,e);let i=r.match(/:dm:([^:]+)$/);if(i)return Ds(`user:${i[1]}`,e);let o=r.match(/:channel:([^:]+)$/);if(o)return Ds(`channel:${o[1]}`,e);let a=r.match(/:group:([^:]+)$/);if(a)return Ds(`channel:${a[1]}`,e)}function rk(t){let e=t.target?.trim();if(e)return Ds(e,t.channel);let n=t.sessionKey?.trim().toLowerCase();if(n){let s=nk(n,t.channel);if(s)return s}let r=t.senderId?.trim();if(r&&t.channel)return Ds(`user:${r}`,t.channel)}function sk(t){return t.senderName?.trim()?t.senderName.trim():t.senderUsername?.trim()?t.senderUsername.trim():t.target?.trim()||t.senderId?.trim()}function Rc(t){return[...t].sort((e,n)=>n.lastSeenAt-e.lastSeenAt)}function Cc(t,e){let n=e.trim();if(!n||t.lastByAgent[n]||t.targetsByAgent[n])return n;if(n.toLowerCase()==="default"){for(let r of["default","Default"])if(t.lastByAgent[r]||t.targetsByAgent[r])return r}return n}async function ik(t,e,n,r,s){let i=e.trim();if(!i)return;let o=s?.gatewayAgentId?.trim()||void 0,a=n.channel?.trim(),c=n.sessionKey?.trim().toLowerCase();if(!a&&c){let f=c.match(/^agent:[^:]+:([a-z0-9_-]+):/);f&&(a=f[1])}let l=rk(n);if(!(!a||!l))return $d(jo(t),async()=>{let f=Date.now(),u=await Ls(t);u.targetsByAgent[i]||(u.targetsByAgent[i]={});let d=qE(l,n.threadId?.trim()),p=u.targetsByAgent[i][d],g={agentId:i,...o?{gatewayAgentId:o}:{},channel:a,accountId:n.accountId?.trim()||void 0,target:l,threadId:n.threadId?.trim()||void 0,sessionKey:n.sessionKey?.trim()||void 0,sessionId:n.sessionId?.trim()||void 0,senderId:n.senderId?.trim()||void 0,senderName:n.senderName?.trim()||void 0,senderUsername:n.senderUsername?.trim()||void 0,label:sk(n),firstSeenAt:p?.firstSeenAt??f,lastSeenAt:f,lastInboundRunId:r,inboundCount:(p?.inboundCount??0)+1};return u.targetsByAgent[i][d]=g,u.lastByAgent[i]=g,await Dd(t,u),g})}async function ok(t,e){let n=await Ls(t),r=Cc(n,e);return n.lastByAgent[r]}async function ak(t,e){let n=await Ls(t);if(e?.trim()){let s=Cc(n,e.trim());return Rc(Object.values(n.targetsByAgent[s]??{}))}let r=[];for(let s of Object.values(n.targetsByAgent))r.push(...Object.values(s));return Rc(r)}async function ck(t,e,n){let r=await Ls(t),s=n?.trim()?[n.trim()]:[...new Set([...Object.keys(r.targetsByAgent),...Object.keys(r.lastByAgent)])];return s.length===0?0:$d(jo(e),async()=>{let i=await Ls(e),o=0,a=!1;for(let c of s){let l=r.targetsByAgent[c]??{},f=Object.entries(l);f.length>0&&!i.targetsByAgent[c]&&(i.targetsByAgent[c]={});for(let[d,p]of f){let g=i.targetsByAgent[c]?.[d];(!g||p.lastSeenAt>=g.lastSeenAt)&&(i.targetsByAgent[c][d]=p,o++,a=!0)}let u=r.lastByAgent[c];if(u){let d=i.lastByAgent[c];(!d||u.lastSeenAt>=d.lastSeenAt)&&(i.lastByAgent[c]=u,a=!0)}}return a&&await Dd(e,i),o})}async function lk(t,e,n){let r=await Ls(t),s=Cc(r,e),i=n?.target?.trim();if(i){let o=Object.values(r.targetsByAgent[s]??{});return tk(o,i,n?.threadId?.trim())}return r.lastByAgent[s]}async function uk(t,e,n=(0,VE.backupTimestamp)()){let r=jo(t);return $d(r,async()=>{let s=await Ls(t),i=Cc(s,e),o=s.targetsByAgent[i],a=Object.prototype.hasOwnProperty.call(s.lastByAgent,i),c=o?Object.keys(o).length:0;if(c===0&&!a)return{removed:0};let l=await(0,VE.renameToBackup)(r,n);return delete s.targetsByAgent[i],delete s.lastByAgent[i],await Dd(t,s),{removed:c,backupPath:l}})}async function dk(t){let e=await Ls(t),n={};for(let[r,s]of Object.entries(e.targetsByAgent))n[r]=Rc(Object.values(s));return{lastByAgent:e.lastByAgent,targetsByAgent:n}}});var XE=S(br=>{"use strict";var fk=br&&br.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,s)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),pk=br&&br.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),gk=br&&br.__importStar||(function(){var t=function(e){return t=Object.getOwnPropertyNames||function(n){var r=[];for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(r[r.length]=s);return r},t(e)};return function(e){if(e&&e.__esModule)return e;var n={};if(e!=null)for(var r=t(e),s=0;s<r.length;s++)r[s]!=="default"&&fk(n,e,r[s]);return pk(n,e),n}})();Object.defineProperty(br,"__esModule",{value:!0});br.EGRESS_URL_ENV=void 0;br.startEgressBroker=Sk;var hk=gk(require("http")),mk=Br(),Ek=Uo(),_k=kc(),YE=Va();br.EGRESS_URL_ENV="AGENTHIPPO_EGRESS_URL";function yk(t){return t?.match(/^Bearer\s+(\S+)$/i)?.[1]}function wk(t){return t?(0,Ek.hashNonce)(t).slice(0,12):"none"}function Ak(t,e){return(0,YE.getGatewayOutboundFilePath)(t,(0,YE.safeGatewaySessionDirId)(e))}async function Sk(t){let e=hk.createServer(async(s,i)=>{let o=(a,c,l,f)=>{l&&t.audit?.("unauthorized",l,f??{}),i.writeHead(a,{"Content-Type":"application/json"}),i.end(JSON.stringify({ok:!1,error:c}))};try{if((s.url?.split("?")[0]??"")!=="/egress/send"){o(404,"not found");return}if(s.method!=="POST"){i.writeHead(405,{"Content-Type":"application/json",Allow:"POST"}),i.end(JSON.stringify({ok:!1,error:"method not allowed"}));return}let c=yk(s.headers.authorization),l=c?t.registry.resolve(c):void 0;if(!l){o(401,"Unauthorized: missing, unknown, or expired turn nonce","egress_nonce_reject",{reason:c?"unknown_or_expired":"missing",nonce_sha256_prefix:wk(c)});return}let f=l.egressStoreKey?.trim();if(!f){o(403,"no outbound route for this turn (not a channel-originated session)","egress_deny",{userId:l.userId,reason:"no_store_key"});return}let u;try{u=JSON.parse(await(0,mk.readBodyWithCap)(s))}catch{o(400,"invalid JSON body");return}let d=typeof u.message=="string"?u.message:"";if(!d.trim()){o(400,"message is required");return}let p=typeof u.to=="string"?u.to.trim():void 0,g=typeof u.media=="string"&&u.media.trim()||void 0,m=Ak(t.workspaceRoot,f),h;try{h=await(0,_k.resolveGatewayOutboundHandle)(m,t.agentId,p?{target:p}:void 0)}catch(_){t.logger?.warn(`[Egress] store read failed: ${_ instanceof Error?_.message:String(_)}`)}if(!h){o(404,p?`no bound handle matches "${p}" for this session (cannot address a new destination)`:"no reply destination bound for this session yet","egress_deny",{userId:l.userId,reason:"no_matching_handle",to:p??"(reply-to-sender)"});return}t.audit?.(l.sessionKey,"egress_authorize",{userId:l.userId,channel:h.channel,target:h.target});let E=await t.send(h,d,g);i.writeHead(E.ok?200:502,{"Content-Type":"application/json"}),i.end(JSON.stringify(E))}catch(a){t.logger?.warn(`[Egress] broker error: ${a instanceof Error?a.message:String(a)}`),i.headersSent||i.writeHead(500,{"Content-Type":"application/json"}),i.end(JSON.stringify({ok:!1,error:"Internal error"}))}});await new Promise((s,i)=>{e.once("error",i),e.listen(0,"127.0.0.1",()=>s())});let n=e.address();if(!n||typeof n=="string")throw new Error("Egress broker failed to bind a loopback port");let r=`http://127.0.0.1:${n.port}/egress/send`;return t.logger?.info(`[Egress] broker listening at ${r}`),{url:r,close:()=>new Promise(s=>e.close(()=>s()))}}});var zE=S(Nn=>{"use strict";var Tk=Nn&&Nn.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,s)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),bk=Nn&&Nn.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),vk=Nn&&Nn.__importStar||(function(){var t=function(e){return t=Object.getOwnPropertyNames||function(n){var r=[];for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(r[r.length]=s);return r},t(e)};return function(e){if(e&&e.__esModule)return e;var n={};if(e!=null)for(var r=t(e),s=0;s<r.length;s++)r[s]!=="default"&&Tk(n,e,r[s]);return bk(n,e),n}})();Object.defineProperty(Nn,"__esModule",{value:!0});Nn.ASSERTION_HEADER=void 0;Nn.startDataPlaneSidecar=Dk;var Ok=vk(require("http")),JE=require("crypto"),Ik=$c(),Pk=Br(),Nk=Ho();Nn.ASSERTION_HEADER="x-agent-user-assertion";function Rk(t,e){let n=t.headers[e];return(Array.isArray(n)?n[0]:n)?.trim()||void 0}function Ck(t){return(0,JE.createHash)("sha256").update(t).digest("hex").slice(0,12)}function kk(t){return t?.match(/^Bearer\s+(\S+)$/i)?.[1]}function $k(t,e){let n=Buffer.from(t),r=Buffer.from(e);return n.length===r.length&&(0,JE.timingSafeEqual)(n,r)}async function Dk(t){let e=t.bindHost??"0.0.0.0",n=await Ik.DataPlane.start(t.config,{logger:t.logger,audit:t.audit,gateway:{host:e,port:t.gatewayPort,advertiseHost:e==="0.0.0.0"?void 0:e}}),r=new Map,s=Ok.createServer(async(a,c)=>{let l=(f,u)=>{c.writeHead(f,{"Content-Type":"application/json"}),c.end(JSON.stringify({error:u}))};try{let f=kk(a.headers.authorization);if(!f||!$k(f,t.registerToken))return t.audit?.("unauthorized","sidecar_register_reject",{reason:f?"bad_token":"missing_token"}),l(401,"unauthorized");let u=a.url?.split("?")[0]??"";if((a.method==="GET"||a.method==="POST")&&u==="/edge/turn"){let d=(Array.isArray(a.headers["x-agent-user"])?a.headers["x-agent-user"][0]:a.headers["x-agent-user"])?.trim();if(!d)return t.audit?.("unauthorized","sidecar_edge_reject",{reason:"missing_user"}),l(400,"X-Agent-User required");let p=Rk(a,Nn.ASSERTION_HEADER)?.replace(/^Bearer\s+/i,"").trim()||void 0,{nonce:g}=n.registerTurnRaw({userId:d,sessionKey:d,inboundToken:p});return t.audit?.(d,"sidecar_edge_register",{userId:d,assertion:p?`sha256:${Ck(p)}`:"none"}),c.writeHead(200,{"Content-Type":"application/json",[Nk.TURN_NONCE_HEADER]:g}),c.end(JSON.stringify({ok:!0}))}if(a.method==="POST"&&u==="/turns"){let d;try{d=JSON.parse(await(0,Pk.readBodyWithCap)(a))}catch{return l(400,"bad json")}let p=(d.userId??"").trim();if(!p)return l(400,"userId required");let g=d.agent?.pack?.trim(),m=!!(g&&t.agent?.pack&&g!==t.agent.pack);m&&console.warn(`Warning: turn registration claims agent "${g}" but this connector loaded "${t.agent?.pack}". One connector is meant to serve one agent \u2014 both now share this connector's base credential, so neither is bounded by the job it was deployed for.`),t.audit?.((d.sessionKey??"").trim()||p,"sidecar_register",{userId:p,claimedAgent:g??"none",binding:"asserted",...m?{agentMismatch:!0,loadedAgent:t.agent?.pack}:{}});let{nonce:h,release:E}=n.registerTurnRaw({userId:p,sessionKey:(d.sessionKey??"").trim()||p,inboundToken:d.inboundToken,egressStoreKey:d.egressStoreKey});return r.set(h,E),c.writeHead(200,{"Content-Type":"application/json"}),c.end(JSON.stringify({nonce:h}))}if(a.method==="DELETE"&&u.startsWith("/turns/")){let d=decodeURIComponent(u.slice(7));return r.get(d)?.(),r.delete(d),c.writeHead(204),c.end()}l(404,"not found")}catch(f){t.logger?.warn(`[Sidecar] control error: ${f instanceof Error?f.message:String(f)}`),c.headersSent||c.writeHead(500,{"Content-Type":"application/json"}),c.end(JSON.stringify({error:"internal"}))}});await new Promise((a,c)=>{s.once("error",c),s.listen(t.controlPort,e,()=>a())});let i=s.address(),o=i&&typeof i!="string"?i.port:t.controlPort;return t.logger?.info(`[Sidecar] gateway ${n.url} | control :${o} (bound ${e})`),(t.config.provider??"passthrough").trim().toLowerCase()==="passthrough"&&console.warn(`Warning: provider=passthrough needs a per-user token on every turn. Edge-registered turns supply it via the ${Nn.ASSERTION_HEADER} header \u2014 if your edge does not forward it, every tool call will fail closed.`),{gatewayUrl:n.url,controlPort:o,close:async()=>{await new Promise(a=>s.close(()=>a())),await n.close()}}}});var QE=S(Ms=>{"use strict";Object.defineProperty(Ms,"__esModule",{value:!0});Ms.RemoteDataPlane=Ms.EdgeDataPlane=void 0;Ms.resolveEdgeDataPlane=Lk;Ms.resolveRemoteDataPlane=Mk;var Dc=Ho();function Lk(t=process.env){let e=t.AGENTHIPPO_DATA_PLANE_EDGE?.trim(),n=t.AGENTHIPPO_DATA_MCP_URL?.trim();return!e||e==="0"||e.toLowerCase()==="false"||!n?null:{gatewayUrl:n}}var Ld=class{cfg;constructor(e){this.cfg=e}get url(){return this.cfg.gatewayUrl}adoptTurn(e){return{nonce:e,env:{[Dc.TURN_NONCE_ENV]:e,[Dc.DATA_MCP_URL_ENV]:this.cfg.gatewayUrl},release:async()=>{try{await fetch(new URL("/turn",this.cfg.gatewayUrl),{method:"DELETE",headers:{Authorization:`Bearer ${e}`}})}catch{}}}}};Ms.EdgeDataPlane=Ld;function Mk(t=process.env){let e=t.AGENTHIPPO_DATA_PLANE_CONTROL_URL?.trim(),n=t.AGENTHIPPO_DATA_PLANE_TOKEN?.trim(),r=t.AGENTHIPPO_DATA_MCP_URL?.trim();return!e||!n||!r?null:{controlUrl:e,registerToken:n,gatewayUrl:r}}var Md=class{cfg;constructor(e){this.cfg=e}get url(){return this.cfg.gatewayUrl}async registerTurn(e){let n=await fetch(`${this.cfg.controlUrl.replace(/\/$/,"")}/turns`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.cfg.registerToken}`},body:JSON.stringify(e)});if(!n.ok)throw new Error(`data-plane sidecar register failed: HTTP ${n.status}`);let{nonce:r}=await n.json();return{nonce:r,env:{[Dc.TURN_NONCE_ENV]:r,[Dc.DATA_MCP_URL_ENV]:this.cfg.gatewayUrl},release:async()=>{try{await fetch(`${this.cfg.controlUrl.replace(/\/$/,"")}/turns/${encodeURIComponent(r)}`,{method:"DELETE",headers:{Authorization:`Bearer ${this.cfg.registerToken}`}})}catch{}}}}};Ms.RemoteDataPlane=Md});var $c=S(X=>{"use strict";var Gk=X&&X.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,s)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),Uk=X&&X.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),Hk=X&&X.__importStar||(function(){var t=function(e){return t=Object.getOwnPropertyNames||function(n){var r=[];for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(r[r.length]=s);return r},t(e)};return function(e){if(e&&e.__esModule)return e;var n={};if(e!=null)for(var r=t(e),s=0;s<r.length;s++)r[s]!=="default"&&Gk(n,e,r[s]);return Uk(n,e),n}})();Object.defineProperty(X,"__esModule",{value:!0});X.DataPlane=X.resolveEdgeDataPlane=X.EdgeDataPlane=X.resolveRemoteDataPlane=X.RemoteDataPlane=X.ASSERTION_HEADER=X.startDataPlaneSidecar=X.EGRESS_URL_ENV=X.startEgressBroker=X.TURN_NONCE_HEADER=X.TURN_NONCE_ENV=X.DATA_MCP_URL_ENV=X.startDataGateway=X.TURN_META_KEY=X.ConnectorHost=X.identityProvider=X.passthroughProvider=X.resolveProvider=X.CredentialBroker=X.DEFAULT_TURN_DEADLINE_MS=X.hashNonce=X.TurnRegistry=void 0;X.resolveDataPlaneConfig=Bk;var ZE=Hk(require("path")),jk=Uo(),e_=Id(),xk=Nd(),Gd=Ho(),Hd=Uo();Object.defineProperty(X,"TurnRegistry",{enumerable:!0,get:function(){return Hd.TurnRegistry}});Object.defineProperty(X,"hashNonce",{enumerable:!0,get:function(){return Hd.hashNonce}});Object.defineProperty(X,"DEFAULT_TURN_DEADLINE_MS",{enumerable:!0,get:function(){return Hd.DEFAULT_TURN_DEADLINE_MS}});var Lc=Id();Object.defineProperty(X,"CredentialBroker",{enumerable:!0,get:function(){return Lc.CredentialBroker}});Object.defineProperty(X,"resolveProvider",{enumerable:!0,get:function(){return Lc.resolveProvider}});Object.defineProperty(X,"passthroughProvider",{enumerable:!0,get:function(){return Lc.passthroughProvider}});Object.defineProperty(X,"identityProvider",{enumerable:!0,get:function(){return Lc.identityProvider}});var t_=Nd();Object.defineProperty(X,"ConnectorHost",{enumerable:!0,get:function(){return t_.ConnectorHost}});Object.defineProperty(X,"TURN_META_KEY",{enumerable:!0,get:function(){return t_.TURN_META_KEY}});var Mc=Ho();Object.defineProperty(X,"startDataGateway",{enumerable:!0,get:function(){return Mc.startDataGateway}});Object.defineProperty(X,"DATA_MCP_URL_ENV",{enumerable:!0,get:function(){return Mc.DATA_MCP_URL_ENV}});Object.defineProperty(X,"TURN_NONCE_ENV",{enumerable:!0,get:function(){return Mc.TURN_NONCE_ENV}});Object.defineProperty(X,"TURN_NONCE_HEADER",{enumerable:!0,get:function(){return Mc.TURN_NONCE_HEADER}});var n_=XE();Object.defineProperty(X,"startEgressBroker",{enumerable:!0,get:function(){return n_.startEgressBroker}});Object.defineProperty(X,"EGRESS_URL_ENV",{enumerable:!0,get:function(){return n_.EGRESS_URL_ENV}});var r_=zE();Object.defineProperty(X,"startDataPlaneSidecar",{enumerable:!0,get:function(){return r_.startDataPlaneSidecar}});Object.defineProperty(X,"ASSERTION_HEADER",{enumerable:!0,get:function(){return r_.ASSERTION_HEADER}});var Gc=QE();Object.defineProperty(X,"RemoteDataPlane",{enumerable:!0,get:function(){return Gc.RemoteDataPlane}});Object.defineProperty(X,"resolveRemoteDataPlane",{enumerable:!0,get:function(){return Gc.resolveRemoteDataPlane}});Object.defineProperty(X,"EdgeDataPlane",{enumerable:!0,get:function(){return Gc.EdgeDataPlane}});Object.defineProperty(X,"resolveEdgeDataPlane",{enumerable:!0,get:function(){return Gc.resolveEdgeDataPlane}});function Bk(t,e){let n=t?.dataPlane,r=n?.connector?.trim();if(r)return{connectorPath:ZE.isAbsolute(r)?r:ZE.join(e,r),provider:n?.provider?.trim()||void 0}}var Ud=class t{url;registry;broker;connector;gateway;constructor(e,n,r,s,i){this.url=e,this.registry=n,this.broker=r,this.connector=s,this.gateway=i}static async start(e,n){let r=n?.registry??new jk.TurnRegistry,s=new e_.CredentialBroker((0,e_.resolveProvider)(e.provider)),i=await xk.ConnectorHost.spawn({connectorPath:e.connectorPath,logger:n?.logger});try{let o=await(0,Gd.startDataGateway)({registry:r,broker:s,connector:i,logger:n?.logger,audit:n?.audit,host:n?.gateway?.host,port:n?.gateway?.port,advertiseHost:n?.gateway?.advertiseHost});return new t(o.url,r,s,i,o)}catch(o){throw await i.close(),o}}registerTurnRaw(e){return this.registry.register(e)}registerTurn(e){let{nonce:n,release:r}=this.registry.register(e);return{nonce:n,env:{[Gd.TURN_NONCE_ENV]:n,[Gd.DATA_MCP_URL_ENV]:this.url},release:r}}async close(){await this.gateway.close(),await this.connector.close()}};X.DataPlane=Ud});var s_=S(Yn=>{"use strict";Object.defineProperty(Yn,"__esModule",{value:!0});Yn.PROTOCOL_VERSION=Yn.DEFAULT_GATEWAY_OPERATOR_SCOPES=Yn.GATEWAY_CLIENT_CAPS=Yn.GATEWAY_CLIENT_MODES=Yn.GATEWAY_CLIENT_IDS=void 0;Yn.GATEWAY_CLIENT_IDS={GATEWAY_CLIENT:"gateway-client"};Yn.GATEWAY_CLIENT_MODES={WEBCHAT:"webchat",CLI:"cli",UI:"ui",BACKEND:"backend",AGENT_BACKEND:"agent-backend",NODE:"node",PROBE:"probe",TEST:"test"};Yn.GATEWAY_CLIENT_CAPS={TOOL_EVENTS:"tool-events"};Yn.DEFAULT_GATEWAY_OPERATOR_SCOPES=["operator.admin","operator.read","operator.write","operator.approvals","operator.pairing"];Yn.PROTOCOL_VERSION=3});var Uc=S(Xn=>{"use strict";Object.defineProperty(Xn,"__esModule",{value:!0});Xn.GatewayClient=Xn.MAX_GATEWAY_MESSAGE_CHARS=Xn.MAX_GATEWAY_FRAME_BYTES=void 0;Xn.createAgentIDEGatewayClient=Kk;Xn.createEphemeralGatewayClient=qk;var Fk=require("events"),Gs=s_();Xn.MAX_GATEWAY_FRAME_BYTES=(()=>{let t=Number(process.env.AGENTHIPPO_GATEWAY_MAX_FRAME_BYTES);return Number.isFinite(t)&&t>=1024*1024?t:16*1024*1024})();Xn.MAX_GATEWAY_MESSAGE_CHARS=256*1024;function Vk(t){if(!t)return"WebSocket closed";let e=typeof t.code=="number"?t.code:void 0,n=typeof t.reason=="string"?t.reason.trim():"";if(e===1011)return`WebSocket closed (1011: internal error)${n?`: ${n}`:""}. Check the gateway/server logs for details.`;let r=e!==void 0?` (${e})`:"",s=n?`: ${n}`:"";return`WebSocket closed${r}${s}`}function Wk(t){let e=typeof t?.code=="number"?t.code:void 0;return e!==void 0&&e!==1e3&&e!==1001}var xo=class extends Fk.EventEmitter{options;ws=null;requestId=0;pendingRequests=new Map;connected=!1;reconnectAttempts=0;clientInfo=null;constructor(e){super(),this.options=e,this.on("error",()=>{})}async connect(e){return this.clientInfo=e,new Promise((n,r)=>{try{this.ws=new WebSocket(this.options.url)}catch(s){r(s);return}this.ws.onopen=async()=>{try{let s={minProtocol:Gs.PROTOCOL_VERSION,maxProtocol:Gs.PROTOCOL_VERSION,client:e,caps:[Gs.GATEWAY_CLIENT_CAPS.TOOL_EVENTS],role:"operator",scopes:[...Gs.DEFAULT_GATEWAY_OPERATOR_SCOPES],auth:this.options.token?{token:this.options.token}:void 0},i=await this.request("connect",s);this.connected=!0,this.reconnectAttempts=0,this.emit("connected",i),n(i)}catch(s){r(s)}},this.ws.onmessage=s=>{let i=typeof s.data=="string"?s.data:String(s.data);this.handleMessage(i)},this.ws.onerror=s=>{let i=new Error("WebSocket error");this.emit("error",i),this.connected||r(i)},this.ws.onclose=s=>{let i=this.connected;this.connected=!1,Wk(s)&&this.emit("error",new Error(Vk(s))),this.emit("disconnected",{code:typeof s?.code=="number"?s.code:void 0,reason:typeof s?.reason=="string"?s.reason:void 0,wasClean:typeof s?.wasClean=="boolean"?s.wasClean:void 0}),i&&this.clientInfo&&this.handleReconnect()}})}async request(e,n,r=3e4){if(!this.ws||this.ws.readyState!==WebSocket.OPEN)throw new Error("Not connected to Gateway");let s=String(++this.requestId);return new Promise((i,o)=>{let a=setTimeout(()=>{this.pendingRequests.delete(s),o(new Error(`Request ${e} timed out`))},r);this.pendingRequests.set(s,{resolve:i,reject:o,timeout:a});let c={type:"req",id:s,method:e,params:n};this.ws?.send(JSON.stringify(c))})}respond(e,n,r=!0,s){if(!this.ws||this.ws.readyState!==WebSocket.OPEN)return;let i={type:"res",id:e,ok:r,payload:r?n:void 0,error:r?void 0:s};this.ws.send(JSON.stringify(i))}sendEvent(e,n){if(!this.ws||this.ws.readyState!==WebSocket.OPEN)return;let r={type:"event",event:e,payload:n};this.ws.send(JSON.stringify(r))}handleMessage(e){let n=typeof e=="string"?Buffer.byteLength(e,"utf8"):0;if(n>Xn.MAX_GATEWAY_FRAME_BYTES){this.emit("error",new Error(`Gateway frame of ${n} bytes exceeds the ${Xn.MAX_GATEWAY_FRAME_BYTES}-byte limit and was dropped. Attachments normally travel as references, so this suggests inline payloads; raise AGENTHIPPO_GATEWAY_MAX_FRAME_BYTES if this traffic is expected.`));return}let r;try{r=JSON.parse(e)}catch{this.emit("error",new Error("Failed to parse Gateway message"));return}r.type==="res"?this.handleResponse(r):r.type==="event"?this.handleEvent(r):r.type==="req"&&this.emit("request",r)}handleResponse(e){let n=this.pendingRequests.get(e.id);if(n)if(clearTimeout(n.timeout),this.pendingRequests.delete(e.id),e.ok)n.resolve(e.payload);else{let r=new Error(e.error?.message||"Request failed");r.code=e.error?.code,n.reject(r)}}handleEvent(e){this.emit("event",e.event,e.payload),this.emit(`event:${e.event}`,e.payload)}reconnectTimer=null;isReconnecting=!1;handleReconnect(){if(this.options.reconnectInterval&&!this.isReconnecting){if(this.reconnectAttempts>=(this.options.maxReconnectAttempts??10)){this.emit("reconnect-failed");return}this.isReconnecting=!0,this.reconnectAttempts++,this.emit("reconnecting",this.reconnectAttempts),this.reconnectTimer&&clearTimeout(this.reconnectTimer),this.reconnectTimer=setTimeout(async()=>{if(this.isReconnecting=!1,this.clientInfo)try{await this.connect(this.clientInfo)}catch(e){this.emit("error",e instanceof Error?e:new Error(String(e)))}},this.options.reconnectInterval)}}async reconnect(){if(!this.clientInfo)throw new Error("Cannot reconnect: never connected");this.close(),this.reconnectAttempts=0,await this.connect(this.clientInfo)}close(){this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null),this.isReconnecting=!1,this.clientInfo=null;for(let[,n]of this.pendingRequests)clearTimeout(n.timeout),n.reject(new Error("Connection closed"));this.pendingRequests.clear();let e=this.ws;this.ws=null,this.connected=!1,e?.close()}get isConnected(){return this.connected}};Xn.GatewayClient=xo;function Kk(t,e,n="1.0.0"){let r=new xo({url:t,token:e,reconnectInterval:5e3,maxReconnectAttempts:10}),s={id:Gs.GATEWAY_CLIENT_IDS.GATEWAY_CLIENT,displayName:"AgentHippo IDE",version:n,platform:process.platform,mode:Gs.GATEWAY_CLIENT_MODES.AGENT_BACKEND};return{client:r,clientInfo:s}}function qk(t,e,n="1.0.0"){let r=new xo({url:t,token:e}),s={id:Gs.GATEWAY_CLIENT_IDS.GATEWAY_CLIENT,displayName:"AgentHippo CLI",version:n,platform:process.platform,mode:Gs.GATEWAY_CLIENT_MODES.AGENT_BACKEND};return{client:r,clientInfo:s}}});var Fd=S(Dt=>{"use strict";var Yk=Dt&&Dt.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,s)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),Xk=Dt&&Dt.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),xd=Dt&&Dt.__importStar||(function(){var t=function(e){return t=Object.getOwnPropertyNames||function(n){var r=[];for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(r[r.length]=s);return r},t(e)};return function(e){if(e&&e.__esModule)return e;var n={};if(e!=null)for(var r=t(e),s=0;s<r.length;s++)r[s]!=="default"&&Yk(n,e,r[s]);return Xk(n,e),n}})();Object.defineProperty(Dt,"__esModule",{value:!0});Dt.GATEWAY_OUTBOUND_RPC_METHOD=void 0;Dt.stageLocalMediaIfNeeded=i_;Dt.buildGatewayOutboundSendArgs=o_;Dt.buildGatewaySendParams=Bd;Dt.buildGatewayRpcCommand=jd;Dt.sendGatewayOutboundMessage=l$;var Jk=require("child_process"),zk=require("crypto"),Bi=xd(require("fs")),Qk=xd(require("os")),vr=xd(require("path")),Zk=Er(),e$=Uc(),t$=18789;Dt.GATEWAY_OUTBOUND_RPC_METHOD="send";function n$(t){return t?.trim()||process.env.AGENTHIPPO_GATEWAY_CLI?.trim()||"hippoclaw"}var r$=".openclaw",s$=[".clawdbot",".moldbot",".moltbot"];function i$(){let t=Qk.homedir(),e=process.env.OPENCLAW_STATE_DIR?.trim()||process.env.CLAWDBOT_STATE_DIR?.trim();if(e)return e==="~"||e.startsWith("~/")||e.startsWith("~\\")?vr.join(t,e.slice(1)):vr.resolve(e);let n=vr.join(t,r$);if(Bi.existsSync(n))return n;for(let r of s$){let s=vr.join(t,r);if(Bi.existsSync(s))return s}return n}function o$(t){return/^[a-z][a-z0-9+.-]*:\/\//i.test(t)||t.startsWith("data:")}function i_(t){let e=t?.trim();if(!e||o$(e))return t;let n;try{n=Bi.realpathSync(e)}catch{return e}let r=vr.join(i$(),"media"),s=vr.resolve(r);try{s=Bi.realpathSync(r)}catch{}let i=vr.relative(s,n);if(i&&!i.startsWith("..")&&!vr.isAbsolute(i))return n;let o=vr.extname(n),a=vr.basename(n,o),c=(0,zk.createHash)("sha256").update(n).digest("hex").slice(0,8),l=vr.join(r,`${a}-${c}${o}`);return Bi.mkdirSync(r,{recursive:!0}),Bi.copyFileSync(n,l),l}function o_(t,e,n){let r=["message","send","--channel",t.channel,"--target",t.target,"--message",e];return n?.trim()&&r.push("--media",n.trim()),t.accountId&&r.push("--account",t.accountId),t.threadId&&r.push("--thread-id",t.threadId),r}function Bd(t,e,n){return{to:t.target,message:e,channel:t.channel,accountId:t.accountId,threadId:t.threadId,sessionKey:t.sessionKey,agentId:t.agentId,idempotencyKey:`proactive:${t.agentId}:${Date.now()}`,...n?.trim()?{mediaUrl:n.trim()}:{}}}function jd(t,e,n){return[Dt.GATEWAY_OUTBOUND_RPC_METHOD,JSON.stringify(Bd(t,e,n))]}async function a$(t,e,n,r){let s=process.env.OPENCLAW_GATEWAY_URL?.trim()||`ws://127.0.0.1:${t$}`,i=r?.trim()||(0,Zk.readOpenClawGatewayToken)(),{client:o,clientInfo:a}=(0,e$.createEphemeralGatewayClient)(s,i);await o.connect(a);try{let c=await o.request(Dt.GATEWAY_OUTBOUND_RPC_METHOD,Bd(t,e,n),6e4);return{stdout:JSON.stringify(c),stderr:""}}finally{o.close()}}function c$(t,e){let n=(0,Jk.spawnSync)(t,e,{encoding:"utf-8",env:process.env});return{stdout:(n.stdout??"").trim(),stderr:(n.stderr??"").trim(),exitCode:n.status}}async function l$(t,e){let n=n$(e.cli);if(e.dryRun)return{ok:!0,via:"dry-run",command:jd(t,e.message,e.media),stdout:"",stderr:"",exitCode:0};let r=i_(e.media),s=o_(t,e.message,r),i=[n,...s],o=jd(t,e.message,r);try{let a=await a$(t,e.message,r,e.token);return{ok:!0,via:"gateway-rpc",command:o,stdout:a.stdout,stderr:a.stderr,exitCode:0}}catch(a){let c=a instanceof Error?a.message:String(a),l=c$(n,s);if(l.exitCode===0)return{ok:!0,via:"hippoclaw",command:i,stdout:l.stdout,stderr:l.stderr,exitCode:l.exitCode};let f=l.stderr||l.stdout||"unknown error";return{ok:!1,via:"gateway-rpc",command:o,stdout:l.stdout,stderr:`Gateway RPC failed: ${c}
524
+ HippoClaw CLI fallback failed (exit ${l.exitCode??"unknown"}): ${f}`.trim(),exitCode:l.exitCode}}}});var g_=S(He=>{"use strict";var u$=He&&He.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,s)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),d$=He&&He.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),a_=He&&He.__importStar||(function(){var t=function(e){return t=Object.getOwnPropertyNames||function(n){var r=[];for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(r[r.length]=s);return r},t(e)};return function(e){if(e&&e.__esModule)return e;var n={};if(e!=null)for(var r=t(e),s=0;s<r.length;s++)r[s]!=="default"&&u$(n,e,r[s]);return d$(n,e),n}})();Object.defineProperty(He,"__esModule",{value:!0});He.isAwsCliAvailable=h$;He.resolveS3StateConfig=m$;He.resolveRestoreBootMode=E$;He.safeSessionId=jc;He.sessionRemoteUri=Vd;He.shardBelongsToSession=Wd;He.hasLocalSessionState=c_;He.listSessionShardFiles=l_;He.stageSessionPushDir=u_;He.mergeSessionStagingIntoState=d_;He.restoreState=w$;He.pushState=f_;He.pushSessionState=p_;He.ensureSessionLocal=A$;He.clearRestoreAttemptCache=S$;He.makeStatePusher=T$;He.providerSessionShardName=b$;var f$=require("crypto"),p$=require("child_process"),Wt=a_(require("fs/promises")),hn=a_(require("path")),g$=require("util"),Bo=(0,g$.promisify)(p$.execFile),Hc=new Set;async function h$(){try{return await Bo("aws",["--version"]),!0}catch{return!1}}function m$(t=process.env){let e=t.AGENTHIPPO_STATE_S3_URI?.trim();return e?{uri:e.replace(/\/+$/,""),endpoint:t.AGENTHIPPO_STATE_S3_ENDPOINT?.trim()||void 0}:null}function E$(t=process.env){return t.AGENTHIPPO_STATE_RESTORE_BOOT?.trim().toLowerCase()==="none"?"none":"all"}function jc(t){return t.trim().replace(/[<>:"/\\|?*\x00-\x1F]+/g,"_").replace(/\.\./g,"_").slice(0,160)||"session"}function Vd(t,e){return`${t.uri}/sessions/${jc(e)}`}function xc(t,e,n){let r=["s3","sync",e,n,"--no-progress"];return t.endpoint&&r.push("--endpoint-url",t.endpoint),r}function _$(t,e){return`${hn.resolve(t)}\0${e}`}function Wd(t,e,n){if(n?.chatSessionId&&n.chatSessionId===e)return!0;let r=t.split(":");return r.length>=2&&r[1]===e}async function c_(t,e){let n=hn.join(t,"provider-sessions"),r;try{r=await Wt.readdir(n)}catch{return!1}for(let s of r)if(s.endsWith(".json"))try{let i=await Wt.readFile(hn.join(n,s),"utf8"),o=JSON.parse(i);if(typeof o.key=="string"&&Wd(o.key,e,o.value))return!0}catch{}return!1}async function l_(t,e){let n=hn.join(t,"provider-sessions"),r;try{r=await Wt.readdir(n)}catch{return[]}let s=[];for(let i of r)if(i.endsWith(".json"))try{let o=await Wt.readFile(hn.join(n,i),"utf8"),a=JSON.parse(o);typeof a.key=="string"&&Wd(a.key,e,a.value)&&s.push(i)}catch{}return s}async function y$(t){try{return await Wt.access(t),!0}catch{return!1}}async function u_(t,e,n){await Wt.rm(n,{recursive:!0,force:!0}),await Wt.mkdir(n,{recursive:!0});let r=await l_(t,e),s=hn.join(n,"provider-sessions");if(r.length>0){await Wt.mkdir(s,{recursive:!0});for(let i of r)await Wt.copyFile(hn.join(t,"provider-sessions",i),hn.join(s,i))}return r.length>0}async function d_(t,e){let n=hn.join(t,"provider-sessions");if(await y$(n)){let r=hn.join(e,"provider-sessions");await Wt.mkdir(r,{recursive:!0});for(let s of await Wt.readdir(n))s.endsWith(".json")&&await Wt.copyFile(hn.join(n,s),hn.join(r,s))}}async function w$(t,e,n){try{await Bo("aws",xc(t,t.uri,e)),n?.(`State restored from ${t.uri}`)}catch(r){n?.(`State restore skipped: ${r instanceof Error?r.message:String(r)}`)}}async function f_(t,e,n){try{await Bo("aws",xc(t,e,t.uri))}catch(r){console.error(`[state-sync] push to ${t.uri} failed: ${r instanceof Error?r.message:String(r)}`),n?.(`State push failed: ${r instanceof Error?r.message:String(r)}`)}}async function p_(t,e,n,r){let s=jc(n),i=hn.join(e,".push-staging",s);try{if(!await u_(e,n,i)){r?.(`State push skipped for session ${s}: nothing local`);return}let a=Vd(t,n);await Bo("aws",xc(t,i,a)),r?.(`State pushed session ${s} \u2192 ${a}`)}catch(o){console.error(`[state-sync] push session ${s} failed: ${o instanceof Error?o.message:String(o)}`),r?.(`State push failed for ${s}: ${o instanceof Error?o.message:String(o)}`)}finally{await Wt.rm(i,{recursive:!0,force:!0}).catch(()=>{})}}async function A$(t,e,n,r){let s=_$(e,n);if(Hc.has(s))return;if(await c_(e,n)){Hc.add(s);return}let i=jc(n),o=hn.join(e,".restore-staging",i);try{await Wt.rm(o,{recursive:!0,force:!0}),await Wt.mkdir(o,{recursive:!0});let a=Vd(t,n);await Bo("aws",xc(t,a,o)),await d_(o,e),r?.(`State restored session ${i} from ${a}`)}catch(a){r?.(`State restore-on-miss skipped for ${i}: ${a instanceof Error?a.message:String(a)}`)}finally{Hc.add(s),await Wt.rm(o,{recursive:!0,force:!0}).catch(()=>{})}}function S$(){Hc.clear()}function T$(t,e,n,r=1e3){let s=null,i=!1,o=null,a=new Set,c=!1,l=()=>{i=!0;let d=[...a],p=c;return a.clear(),c=!1,o=(async()=>{p&&await f_(t,e,n);for(let g of d)await p_(t,e,g,n)})().catch(g=>{console.error(`[state-sync] push batch failed: ${g instanceof Error?g.message:String(g)}`)}).finally(()=>{i=!1,o=null,(a.size>0||c)&&(s||(s=setTimeout(()=>{s=null,l()},r),s.unref?.()))}),o};return{schedule:d=>{d?.trim()?a.add(d.trim()):c=!0,!i&&(s||(s=setTimeout(()=>{s=null,l()},r),s.unref?.()))},flush:async()=>{s&&(clearTimeout(s),s=null),o&&await o,(a.size>0||c)&&(await l(),o&&await o)}}}function b$(t){return`${(0,f$.createHash)("sha256").update(t).digest("hex").slice(0,40)}.json`}});var h_=S(Fr=>{"use strict";Object.defineProperty(Fr,"__esModule",{value:!0});Fr.CLI_GATEWAY_AGENT_PREFIX=void 0;Fr.resolveCliGatewayAgentId=I$;Fr.isCliGatewayAgentId=P$;var v$=Un();Fr.CLI_GATEWAY_AGENT_PREFIX="agenthippo-cli";function O$(t){return t.toLowerCase().replace(/[^a-z0-9-]/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,"").slice(0,32)||"unnamed"}function I$(t){let e=(t??"").trim().toLowerCase();return!e||e===v$.AGENT_CONSTANTS.DEFAULT_AGENT_ID?Fr.CLI_GATEWAY_AGENT_PREFIX:`${Fr.CLI_GATEWAY_AGENT_PREFIX}-${O$(e)}`}function P$(t){let e=(t??"").trim().toLowerCase();return e===Fr.CLI_GATEWAY_AGENT_PREFIX||e.startsWith(`${Fr.CLI_GATEWAY_AGENT_PREFIX}-`)}});var Yd=S(ms=>{"use strict";Object.defineProperty(ms,"__esModule",{value:!0});ms.fetchMeetAgentChannelContext=m_;ms.mapChannelsStatusToMeetAgentRows=qd;ms.parseChannelBindSpecs=k$;ms.applyAgentChannelBindingsViaConfigPatch=G$;ms.fetchMeetAgentChannelRows=U$;ms.waitForChannelsLive=j$;ms.resolvePublishedGatewayChannelIds=x$;var Kd={probe:!1,timeoutMs:1e4};async function m_(t){let e=await t("channels.status",Kd);return{rows:qd(e),statusPayload:e}}function Us(t){return t&&typeof t=="object"&&!Array.isArray(t)?t:null}function qd(t){let e=Us(t);if(!e)return[];let n=Array.isArray(e.channelOrder)?e.channelOrder:null,r=Us(e.channelLabels)??{},s=Us(e.channels)??{},i=Us(e.channelAccounts)??{},o=Us(e.channelDefaultAccountId)??{},a=n&&n.length>0?n:[...Object.keys(s)].sort((l,f)=>l.localeCompare(f)),c=[];for(let l of a){let f=typeof r[l]=="string"?r[l]:l,u=i[l],d=Array.isArray(u)?u:[],p=d.length>0?d.map(y=>typeof y.accountId=="string"?y.accountId:"default"):[typeof o[l]=="string"?o[l]:"default"],g=Us(s[l]),m=g&&typeof g.connected=="boolean"?g.connected:g?.running===!0,h=d.some(y=>typeof y.connected=="boolean"&&y.connected||y.running===!0),E=m||h,_=g?.configured===!0||d.some(y=>y.configured===!0&&y.enabled!==!1)||E;c.push({id:l,label:f,connected:E,enabled:_,accounts:p})}return c}function N$(t){let e=Us(t);if(!e)return{};let n=Us(e.channelDefaultAccountId)??{},r={};for(let[s,i]of Object.entries(n))typeof i=="string"&&i.trim()&&(r[s]=i.trim());return r}function R$(t,e){if(!t||typeof t!="object"||Array.isArray(t))return!1;let n=t;if(n.type==="acp"||String(n.agentId??"").trim().toLowerCase()!==e)return!1;let r=n.match;return!r||typeof r!="object"||r.peer?!1:typeof r.channel=="string"&&r.channel.trim().length>0}function C$(t){return typeof t!="string"||!t.trim()?"default":t.trim().toLowerCase()}function k$(t){return t.split(",").map(e=>e.trim()).filter(Boolean).map(e=>{let n=e.indexOf(":");if(n===-1)return{channelId:e};let r=e.slice(0,n).trim(),s=e.slice(n+1).trim();return s?{channelId:r,accountId:s}:{channelId:e}})}function $$(t){if(!t||typeof t!="object"||Array.isArray(t))return;let e=t.match?.channel;return typeof e=="string"&&e.trim()?e.trim():void 0}function D$(t){let e=$$(t);return!!(e&&e.includes(":"))}function L$(t,e,n){if(!t||typeof t!="object"||Array.isArray(t))return!1;let r=t;if(r.type==="acp"||String(r.type??"route").toLowerCase()!=="route")return!1;let i=r.match;if(!i||typeof i!="object"||i.peer)return!1;let o=typeof i.channel=="string"?i.channel.trim().toLowerCase():"",a=C$(i.accountId);return o===e.trim().toLowerCase()&&a===n.trim().toLowerCase()}function M$(t){let e=t.agentId.trim().toLowerCase(),n=i=>t.channelAccountOverrides?.[i]??t.channelDefaultAccountId[i]??"default",r=t.existingBindings.filter(i=>{if(D$(i)||R$(i,e))return!1;for(let o of t.selectedChannelIds){let a=n(o);if(L$(i,o,a))return!1}return!0}),s=t.selectedChannelIds.map(i=>{let o=n(i);return{type:"route",agentId:t.agentId.trim(),match:{channel:i,accountId:o}}});return[...r,...s]}async function G$(t,e){let n=e.statusPayload??await t("channels.status",Kd),r=N$(n),s=await t("config.get",{}),i=typeof s.hash=="string"?s.hash.trim():"";if(!i)throw new Error("config.get did not return hash; cannot config.patch bindings");let o=Array.isArray(s.config?.bindings)?s.config.bindings:[],a=M$({existingBindings:o,agentId:e.agentId,selectedChannelIds:e.selectedChannelIds,channelDefaultAccountId:r,channelAccountOverrides:e.channelAccountOverrides});return JSON.stringify(o)===JSON.stringify(a)?!1:(await t("config.patch",{baseHash:i,raw:JSON.stringify({bindings:a})}),!0)}async function U$(t){let{rows:e}=await m_(t);return e}var H$=t=>new Promise(e=>setTimeout(e,t));async function j$(t,e,n={}){let r=[...new Set(e.map(d=>d.trim().toLowerCase()).filter(Boolean))];if(r.length===0)return{ready:!0,live:[],pending:[],polls:0,timedOut:!1};let s=n.timeoutMs??8e3,i=n.intervalMs??400,o=n.sleep??H$,a=n.now??Date.now,c=a(),l=0,f=[],u=[...r];for(;;){l++;let d;try{let g=await t("channels.status",Kd);d=qd(g)}catch{d=[]}let p=new Set(d.filter(g=>g.connected).map(g=>g.id.trim().toLowerCase()));if(f=r.filter(g=>p.has(g)),u=r.filter(g=>!p.has(g)),u.length===0)return{ready:!0,live:f,pending:u,polls:l,timedOut:!1};if(a()-c>=s)return{ready:!1,live:f,pending:u,polls:l,timedOut:!0};await o(i)}}function x$(t,e){let n=e?.trim();return n?t.filter(r=>r.id.toLowerCase()===n.toLowerCase()).map(r=>r.id):t.filter(r=>r.enabled).map(r=>r.id)}});var T_=S(Kt=>{"use strict";var __=Kt&&Kt.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(Kt,"__esModule",{value:!0});Kt.GatewayBridge=Kt.MAX_GATEWAY_ID_CHARS=void 0;Kt.isIdeThreadCompositeRouteKey=y_;Kt.parseIdeThreadIdFromCompositeRouteKey=W$;Kt.findOversizedRunField=w_;Kt.buildIdeSessionRouteKey=A_;Kt.extractRouteLabelFromGatewaySessionKey=S_;Kt.looksLikeGatewayChannelRouteKey=q$;Kt.createGatewayBridge=Y$;var B$=require("events"),Xd=Uc(),F$=__(require("node:os")),Jd=__(require("node:path")),V$=kc(),E_=Va(),Fi="::sid:";function y_(t){return!!t?.includes(Fi)}function W$(t){if(!t||!y_(t))return;let e=t.lastIndexOf(Fi),n=t.slice(e+Fi.length).trim();return n.length>0?n:void 0}Kt.MAX_GATEWAY_ID_CHARS=512;var K$=["agentId","sessionKey","sessionId","channel","accountId","target","threadId","groupId","senderUsername","senderName","senderId"];function w_(t){let e=t;for(let n of K$){let r=e[n];if(r!=null&&(typeof r!="string"||r.length>Kt.MAX_GATEWAY_ID_CHARS))return n}}function A_(t,e){let n=t?.trim(),r=e?.trim();return n&&r?`${n}${Fi}${r}`:n||r}function S_(t){let e=t.trim(),n="agent:";if(!e.toLowerCase().startsWith(n))return;let r=e.slice(n.length),s=r.indexOf(":");if(s<0)return;let i=r.slice(s+1).trim();return i.length>0?i:void 0}function q$(t){let e=t&&t.includes(Fi)?t.slice(0,t.lastIndexOf(Fi)):t,r=(e?S_(e)??e:void 0)?.split(":").filter(Boolean)??[];return r.length<2?!1:["channel","chat","dm","group","thread","user"].includes(r[1].trim().toLowerCase())}var Bc=class extends B$.EventEmitter{options;client;clientInfo;agents=new Map;serverConnId=null;supportsAgentRegistration=null;isUnknownMethodError(e){return(e instanceof Error?e.message:String(e)).toLowerCase().includes("unknown method")}async ensureGatewayRuntimeRegistration(e,n){try{await this.client.request("agents.register",{agent:{id:e.id,name:e.name??e.id,workspace:n}})}catch(r){if(this.isUnknownMethodError(r))return;this.log(`agents.register follow-up failed (non-fatal): ${r instanceof Error?r.message:String(r)}`)}}constructor(e){super(),this.options=e,this.on("error",()=>{});let{client:n,clientInfo:r}=(0,Xd.createAgentIDEGatewayClient)(e.gatewayUrl,e.token,e.version);this.client=n,this.clientInfo=r,this.setupEventHandlers()}setupEventHandlers(){this.client.on("connected",async e=>{this.serverConnId=e.server.connId,this.log(`Connected to Gateway (connId=${this.serverConnId})`),this.emit("connected",e),this.agents.size>0&&await this.reregisterAllAgents()}),this.client.on("disconnected",()=>{this.log("Disconnected from Gateway"),this.emit("disconnected")}),this.client.on("error",e=>{this.log(`Gateway error: ${e.message}`),this.emit("error",e)}),this.client.on("reconnecting",e=>{this.log(`Reconnecting to Gateway (attempt ${e})...`),this.emit("reconnecting",e)}),this.client.on("request",e=>{this.handleServerRequest(e)}),this.client.on("event:agents.updated",e=>{this.emit("agents.updated",e)})}async connect(){return this.log(`Connecting to Gateway at ${this.options.gatewayUrl}...`),this.client.connect(this.clientInfo)}async registerAgent(e){if(this.agents.has(e.id))throw new Error(`Agent ${e.id} is already registered`);let n=(e.workspace??this.resolveOpenClawWorkspaceDir(e.id)).trim();if(!(e.syncOpenClawConfigAgent!==!1))await this.ensureGatewayRuntimeRegistration(e,n);else if(this.supportsAgentRegistration===!1)this.log(`Gateway remote agent management unavailable; using local registration for ${e.id}`);else{try{await this.client.request("agents.create",{name:e.id,workspace:n}),this.supportsAgentRegistration=!0}catch(s){let i=s instanceof Error?s.message:String(s);if(this.isUnknownMethodError(s))this.supportsAgentRegistration=!1,this.log(`Gateway remote agent management rejected (unknown method); using local registration for ${e.id}`);else if(i.toLowerCase().includes("already exists"))await this.client.request("agents.update",{agentId:e.id,workspace:n,name:e.name??e.id}),this.supportsAgentRegistration=!0;else throw s}await this.ensureGatewayRuntimeRegistration(e,n)}this.agents.set(e.id,e),this.log(`Registered agent: ${e.id}`),this.emit("agent.registered",e.id,{needsBinding:!0})}async reregisterAllAgents(){this.log(`Re-registering ${this.agents.size} agent(s) after reconnect...`);for(let e of this.agents.values())try{if(e.syncOpenClawConfigAgent===!1){let r=(e.workspace??this.resolveOpenClawWorkspaceDir(e.id)).trim();await this.ensureGatewayRuntimeRegistration(e,r),this.log(`Re-registered runtime agent: ${e.id}`);continue}if(this.supportsAgentRegistration===!1){this.log(`Skipping remote re-register for ${e.id} (gateway compatibility mode)`);continue}let n=(e.workspace??this.resolveOpenClawWorkspaceDir(e.id)).trim();try{await this.client.request("agents.create",{name:e.id,workspace:n})}catch(r){if((r instanceof Error?r.message:String(r)).toLowerCase().includes("already exists"))await this.client.request("agents.update",{agentId:e.id,workspace:n,name:e.name??e.id});else throw r}await this.ensureGatewayRuntimeRegistration(e,n),this.supportsAgentRegistration=!0,this.log(`Re-registered agent: ${e.id}`)}catch(n){if(this.isUnknownMethodError(n)){this.supportsAgentRegistration=!1,this.log(`Gateway rejected remote agent management during reconnect (unknown method); keeping local registration for ${e.id}`);continue}this.log(`Failed to re-register agent ${e.id}: ${n}`)}this.supportsAgentRegistration===!1&&this.log("Gateway compatibility mode active: inbound routing relies on plugin/session bridge, not agents.register.")}async unregisterAgent(e){if(this.agents.get(e))try{if(this.supportsAgentRegistration===!1){this.agents.delete(e),this.log(`Unregistered local agent: ${e} (gateway compatibility mode)`),this.emit("agent.unregistered",e);return}await this.client.request("agents.delete",{agentId:e,deleteFiles:!1},3e4),this.agents.delete(e),this.log(`Unregistered agent: ${e}`),this.emit("agent.unregistered",e)}catch(r){if(this.isUnknownMethodError(r)){this.supportsAgentRegistration=!1,this.agents.delete(e),this.log(`Gateway rejected remote agent management delete (unknown method); removed local agent ${e} instead`),this.emit("agent.unregistered",e);return}this.log(`Failed to unregister agent ${e}: ${r}`)}}isGatewayCompatMode(){return this.supportsAgentRegistration===!1}resolveOpenClawWorkspaceDir(e){let n=Jd.default.join(F$.default.homedir(),".openclaw");return e==="main"?Jd.default.join(n,"workspace"):Jd.default.join(n,`workspace-${e}`)}async handleServerRequest(e){e.method==="agent.run"?await this.handleAgentRun(e):e.method==="session.new"?await this.handleSessionNew(e):e.method==="agent.cancel"?this.handleAgentCancel(e):this.client.respond(e.id,void 0,!1,{code:"UNKNOWN_METHOD",message:`Unknown method: ${e.method}`})}handleAgentCancel(e){let n=e.params;this.log(`Received agent.cancel (agentId=${n?.agentId}, sessionKey=${n?.sessionKey})`),this.emit("agent.cancel",n),this.client.respond(e.id,{success:!0},!0)}async handleSessionNew(e){let n=e.params;this.log(`Received session.new request from ${n?.requestedBy??"unknown"}`),this.emit("session.new.request",{requestId:e.id,params:n??{}})}respondSessionNew(e,n){this.client.respond(e,n,n.success,n.success?void 0:{code:"SESSION_CREATE_ERROR",message:n.error??"Failed to create session"})}persistHeadlessGatewayOutbound(e,n,r,s,i){let o=e.workspace?.trim();if(!o)return;let a=r.sessionKey?.trim()||i,c=(0,E_.resolveGatewaySessionDirId)({gatewaySessionKey:a});if(!c)return;let l=(0,E_.getGatewayOutboundFilePath)(o,c),f=e.agentId?.trim()||n;(0,V$.upsertGatewayOutboundHandle)(l,f,r,s,{gatewayAgentId:n}).then(u=>{u&&this.log(`Gateway outbound routes: ${l}`)}).catch(u=>{this.log(`Failed to persist outbound handle: ${u instanceof Error?u.message:String(u)}`)})}async handleAgentRun(e){let n=e.params;if(!n?.message||typeof n.message!="string"){this.client.respond(e.id,void 0,!1,{code:"INVALID_PARAMS",message:"message is required"});return}if(n.message.length>Xd.MAX_GATEWAY_MESSAGE_CHARS){this.client.respond(e.id,void 0,!1,{code:"MESSAGE_TOO_LARGE",message:`message exceeds ${Xd.MAX_GATEWAY_MESSAGE_CHARS} characters`});return}let r=w_(n);if(r){this.client.respond(e.id,void 0,!1,{code:"INVALID_PARAMS",message:`${r} is not a valid string`});return}let s=n.agentId||this.getDefaultAgentId();if(!s){this.client.respond(e.id,void 0,!1,{code:"NO_AGENT",message:"No agent available"});return}let i=this.agents.get(s);if(!i){this.client.respond(e.id,void 0,!1,{code:"AGENT_NOT_FOUND",message:`Agent ${s} not found`});return}this.log(`Running agent ${s} for message: ${n.message.slice(0,50)}...`);let o=A_(n.sessionKey,n.sessionId),a=n.idempotencyKey||`${s}-${Date.now()}`;this.emit("agent.message",{agentId:s,message:n.message,channel:n.channel,sessionKey:n.sessionKey,sessionId:n.sessionId,routeKey:o});try{if(!!(i.useChatUI&&i.chatUIHandler)){this.log(`Routing gateway message to Chat UI for agent ${s} (routeKey=${o??"none"})`),await this.handleAgentRunViaChatUI(e,i,n,a,o);return}let l=i.engineId||"claude";if(!i.messageHandler)throw new Error("No message handler configured for agent");this.log(`Agent ${s} processing message via direct handler, engine=${l}`),this.persistHeadlessGatewayOutbound(i,s,n,a,o);let f=this.client,u="",d="",p=0,g=!1,m=150,h=o,E=()=>{u!==d&&(d=u,p=Date.now(),f.sendEvent("agent.stream",{runId:a,agentId:s,sessionKey:h,state:"delta",text:u}))},_={async thinking(){g||(E(),g=!0,f.sendEvent("agent.stream",{runId:a,agentId:s,sessionKey:h,state:"thinking"}))},async text(T){g=!1,u+=T,Date.now()-p>=m&&E()},async toolStart(T){E(),f.sendEvent("agent.stream",{runId:a,agentId:s,sessionKey:h,state:"tool",toolName:T,toolState:"start"})},async toolEnd(T){f.sendEvent("agent.stream",{runId:a,agentId:s,sessionKey:h,state:"tool",toolName:T,toolState:"end"})},async progress(T){f.sendEvent("agent.stream",{runId:a,agentId:s,sessionKey:h,state:"progress",message:T})},async question(T){return f.sendEvent("agent.stream",{runId:a,agentId:s,sessionKey:h,state:"progress",message:`Question: ${T.prompt}`}),{selected:[],freeText:null,declined:!0}},async error(T){u+=`
525
525
  [Error: ${T}]`,f.sendEvent("agent.stream",{runId:a,agentId:s,sessionKey:h,state:"error",message:T})},async done(){}},y=await i.messageHandler(n.message,{engineId:l,sessionId:o,gatewaySessionKey:n.sessionKey,workspaceRoot:i.workspace,emitter:_,peerInfo:n.senderUsername||n.senderName||n.senderId||n.channel?{senderUsername:n.senderUsername,senderName:n.senderName,senderId:n.senderId,channel:n.channel}:void 0});if(!y.success&&y.error)throw new Error(y.error);this.log(`Agent ${s} completed: fullText.len=${u?.length||0}`),u||this.log(`WARNING: Agent ${s} produced empty response!`),E();let b={text:u,runId:n.idempotencyKey};this.client.respond(e.id,b,!0),this.log(`Agent ${s} completed successfully, response length=${u.length}`),this.emit("agent.response",{agentId:s,message:n.message,response:u})}catch(c){this.client.respond(e.id,void 0,!1,{code:"AGENT_ERROR",message:c instanceof Error?c.message:String(c)}),this.log(`Agent ${s} failed: ${c}`)}}async handleAgentRunViaChatUI(e,n,r,s,i){let o=n.id,a=this.client;this.log(`handleAgentRunViaChatUI: agentId=${o}, message="${r.message.slice(0,50)}...", runId=${s}`);let c="",l=!1,f={async thinking(){l||(l=!0,a.sendEvent("agent.stream",{runId:s,agentId:o,sessionKey:i,state:"thinking"}))},async text(u){l=!1,c+=u,a.sendEvent("agent.stream",{runId:s,agentId:o,sessionKey:i,state:"delta",text:c})},async toolStart(u){a.sendEvent("agent.stream",{runId:s,agentId:o,sessionKey:i,state:"tool",toolName:u,toolState:"start"})},async toolEnd(u){a.sendEvent("agent.stream",{runId:s,agentId:o,sessionKey:i,state:"tool",toolName:u,toolState:"end"})},async progress(u){a.sendEvent("agent.stream",{runId:s,agentId:o,sessionKey:i,state:"progress",message:u})},async question(u){return a.sendEvent("agent.stream",{runId:s,agentId:o,sessionKey:i,state:"progress",message:`Question: ${u.prompt}`}),{selected:[],freeText:null,declined:!0}},async error(u){c+=`
526
- [Error: ${u}]`,a.sendEvent("agent.stream",{runId:s,agentId:o,sessionKey:i,state:"error",message:u})},async done(){a.sendEvent("agent.stream",{runId:s,agentId:o,sessionKey:i,state:"done"})}};try{let u=r.senderUsername||r.senderName||r.senderId||r.channel?{senderUsername:r.senderUsername,senderName:r.senderName,senderId:r.senderId,channel:r.channel}:void 0,d=await n.chatUIHandler(r.message,i,u,f,{params:r,runId:s,agentId:o}),p=c||d;this.log(`Agent ${o} (Chat UI) completed: response.len=${p.length}`),p||this.log(`WARNING: Agent ${o} (Chat UI) produced empty response!`);let g={text:p,runId:r.idempotencyKey};this.client.respond(e.id,g,!0),this.emit("agent.response",{agentId:o,message:r.message,response:p})}catch(u){this.client.respond(e.id,void 0,!1,{code:"CHAT_UI_ERROR",message:u instanceof Error?u.message:String(u)}),this.log(`Agent ${o} (Chat UI) failed: ${u}`)}}getDefaultAgentId(){if(this.agents.size===1){let e=this.agents.keys().next();return e.done?void 0:e.value}}log(e){let n=`[GatewayBridge] ${e}`;this.options.outputChannel&&this.options.outputChannel.appendLine(n),this.emit("log",n)}async disconnect(){for(let e of this.agents.keys())await this.unregisterAgent(e);this.client.close(),this.log("Disconnected from Gateway")}get isConnected(){return this.client.isConnected}get connId(){return this.serverConnId}get registeredAgents(){return Array.from(this.agents.keys())}async reconnect(){this.log("Force reconnecting to Gateway..."),await this.client.reconnect()}async request(e,n){return this.client.request(e,n)}};Kt.GatewayBridge=jc;function V$(t){return new jc(t)}});var M_=S(Qn=>{"use strict";var W$=Qn&&Qn.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,s)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),K$=Qn&&Qn.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),Fo=Qn&&Qn.__importStar||(function(){var t=function(e){return t=Object.getOwnPropertyNames||function(n){var r=[];for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(r[r.length]=s);return r},t(e)};return function(e){if(e&&e.__esModule)return e;var n={};if(e!=null)for(var r=t(e),s=0;s<r.length;s++)r[s]!=="default"&&W$(n,e,r[s]);return K$(n,e),n}})();Object.defineProperty(Qn,"__esModule",{value:!0});Qn.serveCommand=tD;Qn.resolveGatewaySessionKey=k_;Qn.runGatewayTurn=$_;Qn.runBridgeTurn=D_;var T_=Fo(require("crypto")),Hs=Fo(require("fs")),b_=Fo(require("os")),q$=Fo(require("http")),_s=Fo(require("path")),v_=require("node:crypto"),Y$=wm(),xc=To(),Jn=Oo(),zd=td(),X$=id(),pi=Po(),O_=Ac(),I_=Zm(),Bc=oE(),P_=fE(),Vr=pd(),zn=oi(),gi=ai(),L=Wn(),J$=md(),Qd=RE(),ge=Br(),Vc=Is(),Fc=Po(),z$=Pi(),ht=Cc(),N_=Er(),Q$=Fd(),R_=yo(),xo=zs(),js=p_(),Z$=g_(),Zd=Yd(),eD=Ns(),Bo="-".repeat(62);async function tD(t){let e=(0,gi.getApiConfig)();e.useLiteLLM&&!e.litellmApiKey&&console.warn(`${L.COLORS.yellow}Warning:${L.COLORS.reset} AGENTHIPPO_LITELLM_BASE_URL is set without AGENTHIPPO_LITELLM_API_KEY \u2014 gateway calls will authenticate as 'sk-dummy' (a strict gateway will 401). Provider keys are never sent to the gateway.`);let n,r=t.verbose?new zn.ConsoleLogger("[Sync]"):new zn.NoOpLogger;try{n=await(0,gi.loadAgentPack)(t.agent,t.workspace)}catch(w){console.error(`Error: ${w instanceof Error?w.message:w}`),process.exit(1)}let s=n.manifest.metadata.name,i=(0,Z$.resolveCliGatewayAgentId)(s),o=(t.engine||n.manifest.spec.engine||(0,gi.getDefaultConfig)().engine).trim().toLowerCase(),a=["claude","codex"].includes(o)?void 0:(0,eD.tryResolveCustomEngineManifest)(t.workspace,o)?.model?.defaultModel,c=t.model||n.manifest.spec.model||a||(0,gi.getEnvDefaultModel)()||(0,gi.getDefaultConfig)().model,l=(0,zn.resolveModelAlias)(c),f=n.manifest.spec.cheapModel?.trim(),u=f?(0,zn.resolveModelAlias)(f):void 0;if(!(0,gi.hasCredentialForEngine)(o,e)){console.error(`Error: No usable API key for engine "${o}". Set ${o==="claude"?"ANTHROPIC_API_KEY":"OPENAI_API_KEY"}, or configure the LiteLLM proxy (AGENTHIPPO_LITELLM_API_KEY + AGENTHIPPO_LITELLM_BASE_URL).`);for(let k of(0,L.getLiteLLMQuickstartHintLines)())console.error(k);process.exit(1)}let d=t.verbose?new zn.ConsoleLogger("[Server]"):new zn.NoOpLogger,p=n.packPath,g=n.manifest.metadata.version??"0.0.0",m,h=await(0,Jn.loadPackTrustRoot)({leaseUrl:process.env.AGENTHIPPO_LEASE_URL}),E=(w,k="pack")=>{for(let se of w.warnings)console.warn(`${L.COLORS.yellow}Warning:${L.COLORS.reset} ${se}`);w.status==="unavailable"&&console.warn(`${L.COLORS.yellow}Warning:${L.COLORS.reset} ${k} trust root is configured but unusable: ${w.reason}`)};E(h);let _=(0,Jn.createPackVerifier)(),y={ok:!1,kind:"no-pack",reason:"not verified"},b=(w,k)=>(y=_.refresh({packDir:w,pack:s,packVersion:k,keys:h.keys}),m=y.ok?y.claims.digest:void 0,d.info(y.ok?`[Pack] signature verified for ${s}`:`[Pack] unverified \u2014 ${y.reason}`),y),T=w=>{if(w.ok)return"";let k=h.status==="unavailable"&&w.kind==="no-trust-root"?"trust-root-unavailable":w.kind;return(0,Jn.describePackRefusal)({kind:k,detail:k==="trust-root-unavailable"?h.reason??w.reason:w.reason,pack:s,packVersion:g,packDir:p,trustRootHint:h.url?`Trust root: ${h.url} (${h.reason??"unavailable"})`:h.reason})};b(p,g);let O=!!t.allowUnsignedPack||(0,Jn.allowUnsignedPackFromEnv)();y.ok||(O||(console.error(`${L.COLORS.red}Error: ${T(y)}${L.COLORS.reset}`),process.exit(1)),console.warn(Bo),console.warn(`${L.COLORS.yellow}!! RUNNING AN UNVERIFIED PACK \u2014 signature checking is DISABLED on this instance.${L.COLORS.reset}`),console.warn(`${L.COLORS.yellow}!! ${y.reason}${L.COLORS.reset}`),console.warn(`${L.COLORS.yellow}!! Whatever is in ${p} will be executed, verified by nobody.${L.COLORS.reset}`),console.warn(`${L.COLORS.yellow}!! This is a LOCAL DEVELOPMENT setting (AGENTHIPPO_ALLOW_UNSIGNED_PACK). Do not ship it.${L.COLORS.reset}`),console.warn(Bo));let A=(0,L.findBundledBasePromptsDir)();await(0,zn.syncPackToWorkspace)(t.workspace,n.packPath,s,o,r,A),console.log(`OK: Loaded agent: ${n.manifest.metadata.name} v${n.manifest.metadata.version}`),console.log(`agenthippo pack=${n.manifest.metadata.name}@${n.manifest.metadata.version} engine=${o}`);let{dir:v,ephemeral:C}=(0,ge.resolveStateDir)(t.stateDir),B=(0,ge.resolveBindHost)(t.host);for(let w of(0,ge.identityHeaderAdvice)(process.env,B))console.warn(`${L.COLORS.yellow}Warning:${L.COLORS.reset} ${w}`);let R=(0,ge.tenantIsolationAdvice)({sandbox:t.sandbox,sharedWorkspace:!!t.sharedWorkspace,workspace:t.workspace,stateDir:v});if(R.level==="refuse"){for(let w of R.lines)console.error(`${L.COLORS.red}Error:${L.COLORS.reset} ${w}`);console.error(`Refusing to start because ${ge.REQUIRE_TENANT_ISOLATION_ENV} is set. Unset it to downgrade this to a warning.`),process.exit(1)}for(let w of R.lines)console.warn(`${L.COLORS.yellow}Warning:${L.COLORS.reset} ${w}`);let F=(0,ge.resolveAnalyticsSessionsDir)(v,C),re=new R_.SessionEventWriter(F),W=w=>k=>re.append(w,(0,xo.generateRequestId)(),"warrant_denied",{reason:k}),de=(0,ht.resolveDataPlaneConfig)(n.manifest.spec,n.packPath),he=(0,ht.resolveEdgeDataPlane)(),z=he?new ht.EdgeDataPlane(he):null,Ne=z?null:(0,ht.resolveRemoteDataPlane)(),We=Ne?new ht.RemoteDataPlane(Ne):null,Me=de&&!We&&!z||t.gatewayBridge?new ht.TurnRegistry:null,on=(w,k,se)=>re.append(w,(0,xo.generateRequestId)(),k,{...se,agent:{pack:s,version:g,digest:m??null}}),ye=null;if(z)process.env[ht.DATA_MCP_URL_ENV]=z.url,delete process.env.AGENTHIPPO_DATA_PLANE_TOKEN,delete process.env.AGENTHIPPO_DATA_PLANE_CONTROL_URL,console.log(`OK: Data plane EDGE-registered \u2014 gateway ${z.url}; turn nonces are minted at the edge, serve holds no registration credential`);else if(We)process.env[ht.DATA_MCP_URL_ENV]=We.url,delete process.env.AGENTHIPPO_DATA_PLANE_TOKEN,console.log(`OK: Data plane SIDECAR \u2014 gateway ${We.url}; base credentials stay in the connector container, not here`);else if(de)try{ye=await ht.DataPlane.start(de,{logger:t.verbose?new zn.ConsoleLogger("[DataPlane]"):new zn.NoOpLogger,audit:on,registry:Me??void 0}),process.env[ht.DATA_MCP_URL_ENV]=ye.url,console.log(`OK: Data gateway (provider=${ye.broker.provider.name}) on loopback \u2014 connector: ${de.connectorPath}`)}catch(w){console.error(`${L.COLORS.red}Error: failed to start the data-plane gateway:${L.COLORS.reset} ${w instanceof Error?w.message:w}`),process.exit(1)}let cr=(0,N_.readOpenClawGatewayToken)();delete process.env.OPENCLAW_GATEWAY_TOKEN;let ut=null,qt=async w=>{if(z){let X=w.edgeNonce?.trim();if(!X)return console.warn(`${L.COLORS.yellow}Warning:${L.COLORS.reset} edge data plane active but no ${ht.TURN_NONCE_HEADER} header on this turn \u2014 data tools will fail closed (check the edge route's forward_auth)`),null;let De=z.adoptTurn(X),wt={...De.env};return ut&&(wt[ht.EGRESS_URL_ENV]=ut.url),{nonce:De.nonce,env:wt,release:De.release}}if(We){let X=await We.registerTurn({...w,agent:{pack:s,version:g,digest:m}}),De={...X.env};return ut&&(De[ht.EGRESS_URL_ENV]=ut.url),{nonce:X.nonce,env:De,release:X.release}}if(!Me)return null;let{nonce:k,release:se}=Me.register(w),nt={[ht.TURN_NONCE_ENV]:k};return ye&&(nt[ht.DATA_MCP_URL_ENV]=ye.url),ut&&(nt[ht.EGRESS_URL_ENV]=ut.url),{nonce:k,env:nt,release:se}},En=w=>{if(!z)return;let k=w[ht.TURN_NONCE_HEADER];return Array.isArray(k)?k[0]:k},Dn=new ge.TurnLimiter(t.maxTurnsPerSession??0),Et=Number(process.env.AGENTHIPPO_SERVE_RATE_LIMIT??120),It=new ge.RateLimiter(Number.isFinite(Et)?Et:120),Pt=(0,ge.createTurnGateFromEnv)(),vs=(0,ge.createRejectionWarner)(),K;if(t.wwwDir?.trim()){let w=_s.join(_s.resolve(t.wwwDir.trim()),"index.html");try{K=Hs.readFileSync(w,"utf8")}catch{console.warn(`${L.COLORS.yellow}Warning:${L.COLORS.reset} --www-dir set but unreadable: ${w}`)}}C&&console.warn(`${L.COLORS.yellow}Warning:${L.COLORS.reset} Session state is in a tmpdir (ephemeral). Pass --state-dir or set AGENTHIPPO_HOME to persist sessions across restarts.`);let Ut=(0,js.resolveS3StateConfig)(),I=(0,js.resolveRestoreBootMode)();Ut&&(await(0,js.isAwsCliAvailable)()||(console.error(`${L.COLORS.red}Error: AGENTHIPPO_STATE_S3_URI is set but the \`aws\` CLI was not found.${L.COLORS.reset}`),console.error(" State sync requires the AWS CLI (S3-compatible via --endpoint-url). Install it or unset AGENTHIPPO_STATE_S3_URI."),process.exit(1)),I==="all"?(console.log(`State sync: boot-restore from ${Ut.uri} \u2026`),await(0,js.restoreState)(Ut,v,w=>console.log(` ${w}`))):console.log(`State sync: restore-on-miss from ${Ut.uri} (boot restore disabled)`));let Z=Ut?(0,js.makeStatePusher)(Ut,v,t.verbose?w=>console.error(w):void 0):null,j=t.verbose?w=>console.error(w):void 0,pe=async w=>{Ut&&await(0,js.ensureSessionLocal)(Ut,v,w,j)},dt=(0,L.findClaudeCodePath)(),oe=(0,L.findCodexPath)(),_t=t.sandbox==="container";!_t&&o==="claude"&&!dt&&(console.error(`${L.COLORS.red}Error: Claude Code CLI not found.${L.COLORS.reset}`),console.error(" Install: npm install -g @anthropic-ai/claude-code"),console.error(" Or set CLAUDE_CODE_PATH environment variable"),process.exit(1)),!_t&&o==="codex"&&!oe&&(console.error(`${L.COLORS.red}Error: Codex CLI not found.${L.COLORS.reset}`),console.error(" Install: npm install -g @openai/codex"),console.error(" Or set CODEX_PATH environment variable"),process.exit(1));let Yt=new zn.AutoApprovePermissionHandler,Xt={fileAccess:(0,gi.getFileAccess)(n)},Jt,ss=!1,Ti=w=>{let k=(0,pi.policyVersion)(w);ss&&k===Jt||(ss=!0,Jt=k,re.append("serve",(0,xo.generateRequestId)(),"policy_applied",{instance_id:Cr,policy_version:k??null,pack_digest:m??null,engine_version:(0,xc.installedEngineVersion)(o)??null,tier:t.sandbox==="container"?2:t.sandbox?0:null,enabled:w?.enabled??null,pinned_version:w?.version??null,caps:w?.caps??null,deny_count:w?.deny?.length??0}))},to,lr=_s.join(v,"packs"),sa=async(w,k)=>(await(0,X$.downloadFromStore)({type:"pack",slug:w,version:k})).map(nt=>({path:nt.path,content:nt.content})),no=async w=>{if(!t.pullPacks||!w||w===g)return;let k=await(0,zd.reconcilePinnedPack)({pack:s,currentVersion:g,pinnedVersion:w,packsRoot:lr,download:sa,publicKeysByKid:h.keys,logger:{info:se=>d.info(se),warn:se=>d.info(se)}});if(k.ok){g=k.version,p=k.packDir,b(p,g),d.info(`[Pack] now serving ${s}@${g} from ${k.packDir}`);return}console.warn(`${L.COLORS.yellow}Warning:${L.COLORS.reset} cannot converge to ${s}@${w}: ${k.reason}. Still serving @${g}.`)},ia=(0,Vr.loadWarrantKeypair)(d),ro,Cr=(()=>{try{let w=_s.join((0,ge.resolveStateDir)(t.stateDir).dir,"instance-id");if(Hs.existsSync(w))return Hs.readFileSync(w,"utf-8").trim();let k=`${b_.hostname()}-${T_.randomBytes(4).toString("hex")}`;return Hs.mkdirSync(_s.dirname(w),{recursive:!0}),Hs.writeFileSync(w,k),k}catch{return`${b_.hostname()}-${T_.randomBytes(4).toString("hex")}`}})(),so={get:()=>n?.manifest.metadata.version},is=(0,pi.resolveLeasePollSeconds)(t.leasePollSeconds),ur=await(0,Jn.loadLeaseTrustRoot)({leaseUrl:process.env.AGENTHIPPO_LEASE_URL});ur.explicitlyConfigured&&E(ur,"lease");let bi=!1,Ws=()=>{let w=(0,Jn.selectLeaseSigningKeys)(ur,h);return w.packFallback&&!bi&&(bi=!0,console.warn(`${L.COLORS.yellow}Warning:${L.COLORS.reset} verifying signed leases against the PACK trust root \u2014 no lease trust root is configured on this instance. The control plane publishes lease keys under purpose \`lease-signing\` and refuses to register one kid under two purposes, so this stops working the moment the plane rotates to a dedicated lease key \u2014 and requireSignedLease is sticky with no plane-side undo, so that failure cannot be fixed from the console. Set ${Jn.LEASE_JWKS_URL_ENV}=https://<plane>/.well-known/jwks.json?purpose=lease-signing (or ${Jn.LEASE_SIGNING_KEYS_ENV} with inline {"<kid>":"<public PEM>"} for an air-gapped install).`+(ur.reason?` The derived lease trust root is unusable: ${ur.reason}`:""))),w.keys},zt=(0,pi.createLeaseSource)({url:process.env.AGENTHIPPO_LEASE_URL,identity:()=>({instance:Cr,pack:s,version:so.get(),tier:t.sandbox==="container"?2:t.sandbox?0:void 0,sandboxes:ro?.sandboxes().length,engine:o,engineversion:(0,xc.installedEngineVersion)(o)}),cacheSeconds:(0,pi.leaseCacheSecondsFor)(is),signingKeys:()=>Ws(),requireSignedLease:t.requireSignedLease,instanceId:Cr,...t.leaseMaxStalenessSeconds!==void 0?{maxStalenessSeconds:t.leaseMaxStalenessSeconds}:{},logger:{info:w=>d.info(w),warn:w=>console.warn(`${L.COLORS.yellow}Warning:${L.COLORS.reset} ${w}`)}}),oa=async()=>{if(h.status!=="configured"){let w=await(0,Jn.loadPackTrustRoot)({leaseUrl:process.env.AGENTHIPPO_LEASE_URL});w.status==="configured"&&(h=w,E(w),d.info(`[Pack] signing keys now available (${Object.keys(w.keys).length}); re-verifying`),b(p,g))}if(ur.status!=="configured"){let w=await(0,Jn.loadLeaseTrustRoot)({leaseUrl:process.env.AGENTHIPPO_LEASE_URL});w.status==="configured"&&(ur=w,w.explicitlyConfigured&&E(w,"lease"),d.info(`[Lease] lease-signing keys now available (${Object.keys(w.keys).length})`))}};zt.get().then(Ti).catch(()=>{});{let w=is*1e3;setInterval(()=>{zt.get().then(Ti).catch(()=>{}),oa().catch(()=>{})},w).unref?.()}if(t.pullPacks){Hs.mkdirSync(lr,{recursive:!0});let w=_s.join(lr,g);Hs.existsSync(w)||Hs.cpSync(n.packPath,w,{recursive:!0}),(0,zd.promoteCurrent)(lr,w),p=_s.join(lr,zd.CURRENT_LINK),await no((await zt.get())?.version),b(p,g)}if(so.get=()=>g,to=(0,J$.createPackRunner)({storagePath:v,analyticsSessionsDir:F,packId:s,packVersion:g,provenance:()=>({policyVersion:Jt,packDigest:m,engineVersion:(0,xc.installedEngineVersion)(o),tier:t.sandbox==="container"?2:t.sandbox?0:void 0,instanceId:Cr}),workspaceRoot:t.workspace,credentials:{apiKey:e.apiKey,baseUrl:e.baseUrl,useLiteLLM:e.useLiteLLM,litellmApiKey:e.litellmApiKey,openaiApiKey:e.openaiApiKey,anthropicApiKey:e.anthropicApiKey},logger:d,permissionHandler:Yt,claudeCheapModel:u,omitGatewayToken:!0}),t.pullPacks){let w=is*1e3;setInterval(()=>{zt.get().then(se=>no(se?.version)).catch(()=>{})},w).unref?.()}let io=!!t.sharedWorkspace,J=t.sandboxScope==="user"?"user":"session",M=t.sandbox==="container"?{readonly:[`${p}:${Bc.SANDBOX_PACK_DIR}`],writable:[`${t.workspace}:${Bc.SANDBOX_WORKSPACE_DIR}`]}:void 0;M&&io&&console.warn(`${L.COLORS.yellow}Warning:${L.COLORS.reset} --shared-workspace: every session's sandbox mounts ${t.workspace} read-write, so sessions can read and overwrite each other's files. Only safe when all sessions belong to one trust domain.`);let we;M&&t.sandboxImage&&(await(0,Vr.alignSandboxWorkspaceOwnership)({exec:Vr.dockerExec,image:t.sandboxImage,writable:M.writable,logger:{info:w=>d.info(w),warn:w=>console.warn(`${L.COLORS.yellow}Warning:${L.COLORS.reset} ${w}`)}}),we=await(0,Vr.resolveSandboxImageUser)(Vr.dockerExec,t.sandboxImage));let ke=w=>(0,Vr.ensureSandboxStateDir)(_s.join(v,"sandbox-state",(0,js.safeSessionId)(w)),we),Xe=async w=>{if(!M)return{readonly:[],writable:[]};if(io)return M;let k=(0,Vr.ensureSandboxStateDir)(_s.join(v,"sandbox-workspace",(0,js.safeSessionId)(w)),we);return{readonly:M.readonly,writable:[`${k}:${Bc.SANDBOX_WORKSPACE_DIR}`]}},me=(w,k,se)=>{if((0,Jn.resolveRequireSignedPack)({lease:w?.requireSignedPack,localRequire:t.requireSignedPack,localAllowUnsigned:O})){let X=_.verify({packDir:p,pack:s,packVersion:g,keys:h.keys});if(X!==y&&(y=X,m=X.ok?X.claims.digest:void 0),!X.ok)throw new pi.LeaseDeniedError(T(X))}(0,pi.assertAdmitted)(w,{pack:s,version:g,image:t.sandboxImage,sessionKey:k,userHash:ge.userNamespaceHash,userId:se})},Ie=t.sandbox?(0,Y$.createSandboxRunner)({driver:t.sandbox==="container"?new Bc.ContainerSandboxDriver({exec:Vr.dockerExec,socketOwner:we,logger:{info:w=>d.info(w),warn:w=>console.warn(`${L.COLORS.yellow}Warning:${L.COLORS.reset} ${w}`)}}):new P_.ProcessSandboxDriver({command:process.execPath,args:[...(0,Vr.sandboxScriptArg)(),"sandbox","--agent",p,"--stdio","--state-dir",v,"--workspace",t.workspace],namespaceIsolation:(0,P_.namespaceIsolationFromEnv)(),logger:{info:w=>d.info(w),warn:w=>console.warn(`${L.COLORS.yellow}Warning:${L.COLORS.reset} ${w}`)}}),image:t.sandboxImage??"",tier:t.sandbox==="container"?2:0,...M?{fs:M,fsFor:Xe,stateDirFor:ke}:{},routes:[...process.env.AGENTHIPPO_DATA_MCP_URL?[{kind:"data",target:process.env.AGENTHIPPO_DATA_MCP_URL}]:[],...e.baseUrl?[{kind:"inference",target:e.baseUrl}]:[]],limits:{ttlSeconds:t.sandboxTtlSeconds??1800},provenanceEnv:()=>(0,N_.buildProvenanceEnv)({policyVersion:Jt,packDigest:m,engineVersion:(0,xc.installedEngineVersion)(o),tier:t.sandbox==="container"?2:t.sandbox?0:void 0,instanceId:Cr}),admit:async({sessionKey:w})=>{let k=await zt.get();me(k,w)},inferenceBaseUrl:e.baseUrl,mintModelToken:(w,k)=>(0,Vr.mintSandboxInferenceWarrant)(ia,{user:(0,Vc.currentCredential)()?.userId?.trim()||`anon:${k}`,pack:s,packVersion:g,sandboxId:w,tier:t.sandbox==="container"?2:0,ttlSeconds:300}),logger:d,runtime:{logger:d,editTracker:void 0,configProvider:void 0,permissionHandler:Yt}}):void 0;ro=Ie??void 0;let yt=w=>typeof w=="number"&&Number.isFinite(w)&&w>0?w:void 0,et={...(0,O_.capsFromEnv)(),...yt(t.maxTurnsPerSession)!==void 0?{maxTurnsPerSession:t.maxTurnsPerSession}:{},...yt(t.maxSessionSeconds)!==void 0?{maxSessionSeconds:t.maxSessionSeconds}:{},...yt(t.maxConcurrentSandboxes)!==void 0?{maxConcurrentSandboxes:t.maxConcurrentSandboxes}:{},...t.capOnBreach?{onBreach:t.capOnBreach}:{}},tt=et.maxTurnsPerSession!==void 0||et.maxSessionSeconds!==void 0||et.maxConcurrentSandboxes!==void 0,Ae={sandboxes:()=>[],destroySession:async()=>{},revokeRoute:async()=>{},supportsInFlightTermination:!1},Ht=!!(Ie||process.env.AGENTHIPPO_LEASE_URL||tt)?(0,I_.createGovernor)({caps:(0,O_.mergeCaps)((await zt.get())?.caps,et),sandboxes:Ie??Ae,getLease:()=>zt.get(),pollSeconds:is,pack:s,userHash:ge.userNamespaceHash,...Ie?{}:{admitPack:(w,k)=>{try{return me(k,w),{allowed:!0}}catch(se){return{allowed:!1,reason:se instanceof Error?se.message:String(se)}}}},logger:d,audit:(w,k)=>on(String(k.sessionKey??"instance"),w,k)}):void 0;tt&&!Ie&&console.warn(`${L.COLORS.yellow}Warning:${L.COLORS.reset} caps are configured but --sandbox is not set. Turn and duration caps still refuse the turn; the concurrency cap and route revocation need sandboxes, so those are IGNORED.`);let vi=Ie??to,Ln=Ht?(0,I_.withGovernor)(vi,Ht):vi;if(Ht){Ht.start();let w=Ht.policy(),k=(0,pi.effectiveKillLatencySeconds)(is);d.info(`[Serve] control plane: caps turns=${w.maxTurnsPerSession??"\u221E"} session=${w.maxSessionSeconds??"\u221E"}s sandboxes=${w.maxConcurrentSandboxes??"\u221E"} onBreach=${w.onBreach??"revoke-inference"}; lease poll ${is}s (worst-case kill latency ${k}s; an admin refresh is immediate)`),Ie||d.info("[Serve] no sandbox driver: a deny rule with mode=kill takes effect as DRAIN \u2014 the in-flight turn finishes and only the next one is refused.");let se=zt.status();process.env.AGENTHIPPO_LEASE_URL&&!se.requireSignedLease&&d.info("[Serve] lease signature is NOT required \u2014 set --require-signed-lease (or lease.requireSignedLease) once the control plane signs leases.")}let fe=(0,ge.resolveServiceIdentity)();fe.error&&(console.error(`${L.COLORS.red}Error:${L.COLORS.reset} ${fe.error}`),process.exit(1)),fe.warning&&console.warn(`${L.COLORS.yellow}Warning:${L.COLORS.reset} ${fe.warning}`);let _n=!!process.env.AGENTHIPPO_LEASE_URL,Mn=async()=>{if(!fe.identity)return;let w=(0,Fc.resolveAllowServiceTurns)({lease:(await zt.get())?.allowServiceTurns,managed:_n});if(!w.allowed){on("service-turn","service_turn_denied",{identity:(0,z$.hashIdentity)(fe.identity),gate:w.gate,detail:(0,Fc.describeServiceTurnGate)(w.gate)});return}return fe.identity};if(fe.identity){let w=(0,Fc.resolveAllowServiceTurns)({lease:void 0,managed:_n});d.info(`[Serve] unattended runs: identity configured (${ge.SERVICE_USER_ENV}); `+(_n?"the control plane decides per turn via lease.allowServiceTurns \u2014 absent means deny":(0,Fc.describeServiceTurnGate)(w.gate)))}Ie&&(d.info(`[Serve] sandbox mode: ${t.sandbox} (tier ${t.sandbox==="container"?2:0}) \u2014 engines run in per-session sandboxes`),e.baseUrl||console.warn(`${L.COLORS.yellow}Warning:${L.COLORS.reset} --sandbox without an inference proxy: a sandbox holds no provider key, so model calls will fail 401. Set AGENTHIPPO_LITELLM_BASE_URL.`));let yn=null,os=!1,oo,Op=q$.createServer(async(w,k)=>{let se=(0,ge.corsHeaders)();for(let[nt,X]of Object.entries(se))k.setHeader(nt,X);if(w.method==="OPTIONS"){k.writeHead(204),k.end();return}try{if(w.method==="GET"&&w.url==="/health"){let X={status:"ok"};X.evidence_ship_enabled=!!oo;let De=oo?.lastOkAt();De!==void 0&&(X.evidence_ship_last_ok_at=new Date(De).toISOString());let wt=(0,Qd.getEvidenceShipStatus)();X.evidence_ship_disabled_reason=wt.disabledReason??null,X.evidence_ship_consecutive_failures=wt.consecutiveFailures,X.evidence_records_staged=wt.recordsStaged,X.evidence_records_shipped=wt.recordsShipped,X.evidence_records_skipped_too_old=wt.recordsSkippedTooOld,X.evidence_files_skipped_too_old=wt.filesSkippedTooOld,X.evidence_content_capture=wt.contentCapture,wt.lastHeartbeatAt!==void 0&&(X.evidence_ship_last_heartbeat_at=new Date(wt.lastHeartbeatAt).toISOString());let Gn=(0,R_.getSessionEventWriterStats)();X.evidence_writes_ok=Gn.written,X.evidence_writes_failed=Gn.failed,Gn.lastError&&(X.evidence_write_last_error={at:new Date(Gn.lastError.at).toISOString(),event_type:Gn.lastError.eventType,message:Gn.lastError.message});let At=zt.status();X.lease_configured=!!process.env.AGENTHIPPO_LEASE_URL,X.lease_signed=At.signed,X.lease_signature_required=At.requireSignedLease,X.lease_staleness_seconds=At.stalenessSeconds??null,X.lease_fail_closed=At.failClosed,X.pack_signature_ok=y.ok,X.pack_signature_required=(0,Jn.resolveRequireSignedPack)({localRequire:t.requireSignedPack,localAllowUnsigned:O}),X.pack_trust_root=h.status,X.lease_trust_root=ur.status,X.lease_trust_root_source=ur.explicitlyConfigured?"lease":"pack-fallback",X.kill_in_flight_supported=!!Ie,k.writeHead(200,{"Content-Type":"application/json"}),k.end(JSON.stringify(X));return}if(w.method==="GET"&&w.url==="/ready"){k.writeHead(os?200:503,{"Content-Type":"application/json"}),k.end(JSON.stringify({ready:os,inflight:Pt.inflight,queued:Pt.queued,max:Pt.max}));return}let nt=w.url?.split("?")[0]??"";if(w.method==="GET"&&K&&(nt==="/"||nt==="/index.html")){k.writeHead(200,{"Content-Type":"text/html; charset=utf-8"}),k.end(K);return}if(w.method==="POST"&&nt==="/v1/chat"){let X=await C_(w),De=(0,ge.resolveUserId)(w.headers,X),wt=(0,ge.resolveDataToken)(w.headers),Gn=(0,ge.resolveUserId)(w.headers,void 0)??(0,ge.clientIp)(w);if(!It.tryConsume(Gn)){k.writeHead(429,{"Content-Type":"application/json","Retry-After":String(It.retryAfterSeconds(Gn))}),k.end(JSON.stringify({error:"Rate limit exceeded"}));return}let{sessionKey:At,sandboxKey:Ol,rejected:ao}=(0,ge.resolveServeSessionKey)(X.session_id,De,J);if(ao){re.append("unverified",(0,xo.generateRequestId)(),"warrant_denied",{reason:ao}),k.writeHead(403,{"Content-Type":"application/json"}),k.end(JSON.stringify({error:"verified user identity required"}));return}let co=await Pt.acquire();if(!co){vs(`TurnGate: rejecting /v1/chat (inflight=${Pt.inflight} queued=${Pt.queued} max=${Pt.max})`),k.writeHead(429,{"Content-Type":"application/json","Retry-After":String(ge.TURN_GATE_RETRY_AFTER_SECONDS)}),k.end(JSON.stringify({error:"At capacity"}));return}let Ks=null;try{if(!Dn.tryConsume(At)){k.writeHead(429,{"Content-Type":"application/json"}),k.end(JSON.stringify({error:"Per-session turn limit reached"}));return}await pe(At),De?.trim()&&(Ks=await qt({userId:De.trim(),sessionKey:At,inboundToken:wt,edgeNonce:En(w.headers)}));let zw=await(0,Vc.runWithCredential)({userId:De,dataToken:wt},()=>nD(Ln,X,At,Ol,o,l,t.workspace,Xt,De,Ks?.env),{onDenied:W(At)});k.writeHead(200,{"Content-Type":"application/json"}),k.end(JSON.stringify(zw)),Z?.schedule(At)}finally{await Ks?.release(),co()}return}if(w.method==="POST"&&nt==="/v1/chat/stream"){let X=await C_(w),De=(0,ge.resolveUserId)(w.headers,X),wt=(0,ge.resolveDataToken)(w.headers),Gn=(0,ge.resolveUserId)(w.headers,void 0)??(0,ge.clientIp)(w);if(!It.tryConsume(Gn)){k.writeHead(429,{"Content-Type":"application/json","Retry-After":String(It.retryAfterSeconds(Gn))}),k.end(JSON.stringify({error:"Rate limit exceeded"}));return}let{sessionKey:At,sandboxKey:Ol,rejected:ao}=(0,ge.resolveServeSessionKey)(X.session_id,De,J);if(ao){re.append("unverified",(0,xo.generateRequestId)(),"warrant_denied",{reason:ao}),k.writeHead(403,{"Content-Type":"application/json"}),k.end(JSON.stringify({error:"verified user identity required"}));return}let co=await Pt.acquire();if(!co){vs(`TurnGate: rejecting /v1/chat/stream (inflight=${Pt.inflight} queued=${Pt.queued} max=${Pt.max})`),k.writeHead(429,{"Content-Type":"application/json","Retry-After":String(ge.TURN_GATE_RETRY_AFTER_SECONDS)}),k.end(JSON.stringify({error:"At capacity"}));return}let Ks=null;try{if(!Dn.tryConsume(At)){k.writeHead(429,{"Content-Type":"application/json"}),k.end(JSON.stringify({error:"Per-session turn limit reached"}));return}await pe(At),De?.trim()&&(Ks=await qt({userId:De.trim(),sessionKey:At,inboundToken:wt,edgeNonce:En(w.headers)})),await(0,Vc.runWithCredential)({userId:De,dataToken:wt},async()=>{k.writeHead(200,{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}),await iD(Ln,X,At,Ol,o,l,t.workspace,Xt,k,De,Ks?.env)},{onDenied:W(At)}),Z?.schedule(At)}finally{await Ks?.release(),co()}return}k.writeHead(404,{"Content-Type":"application/json"}),k.end(JSON.stringify({error:"Not found"}))}catch(nt){if(nt?.tooLarge===!0){k.headersSent||k.writeHead(413,{"Content-Type":"application/json",Connection:"close"}),k.end(JSON.stringify({error:"Payload too large"}));return}console.error("Request error:",nt),k.headersSent||k.writeHead(500,{"Content-Type":"application/json"}),k.end(JSON.stringify({error:nt instanceof Error?nt.message:"Internal error"}))}});Op.listen(t.port,B,()=>{(async()=>{console.log(""),console.log(Bo),console.log("Agent Hippo Server"),console.log(Bo),console.log(`Host: ${B}`),console.log(`Port: ${t.port}`),console.log(`Engine: ${o}`),console.log(`Model: ${l}`),u&&console.log(`Cheap: ${u}`),console.log(`Workspace: ${t.workspace}`),n&&(console.log(`Pack: ${n.manifest.metadata.name}@${n.manifest.metadata.version}`),console.log(`Gateway: ${i}`)),console.log(Bo),console.log(""),console.log("Endpoints:"),console.log(` POST http://localhost:${t.port}/v1/chat`),console.log(` POST http://localhost:${t.port}/v1/chat/stream`),console.log(` GET http://localhost:${t.port}/health`),console.log(""),console.log("Press Ctrl+C to stop."),console.log("");let w=(0,Qd.resolveSessionShipConfig)(Cr,F,v);w&&(oo=(0,Qd.startSessionShipper)({...w,logger:{info:se=>d.info(se),warn:se=>console.warn(`${L.COLORS.yellow}Warning:${L.COLORS.reset} ${se}`)}}));let k=t.bind?.trim();if(k)try{await sD(i,k,cr)}catch(se){console.error(`${L.COLORS.yellow}Warning:${L.COLORS.reset} Failed to bind channels: ${se instanceof Error?se.message:String(se)}`)}if(t.gatewayBridge){if(Me)try{ut=await(0,ht.startEgressBroker)({registry:Me,workspaceRoot:t.workspace,agentId:n.manifest.metadata.name,send:async(se,nt,X)=>{let De=await(0,Q$.sendGatewayOutboundMessage)(se,{message:nt,media:X,token:cr});return{ok:De.ok,via:De.via,stdout:De.stdout,stderr:De.stderr}},logger:t.verbose?new zn.ConsoleLogger("[Egress]"):new zn.NoOpLogger,audit:on}),process.env[ht.EGRESS_URL_ENV]=ut.url,console.log("OK: Egress broker on loopback \u2014 gateway token stays broker-side; agent sends via turn nonce")}catch(se){console.error(`${L.COLORS.red}Error:${L.COLORS.reset} Egress broker failed to start: ${se instanceof Error?se.message:String(se)}`),process.exit(1)}try{yn=await rD({gatewayAgentId:i,packName:n.manifest.metadata.name,workspace:t.workspace,registerTurn:qt,brokerGatewayToken:cr,engine:o,defaultModel:l,runner:Ln,permissions:Xt,turnGate:Pt,rateLimiter:It,turnLimiter:Dn,warnGateReject:vs,prepareSession:pe,sandboxScope:J,onTurnComplete:se=>Z?.schedule(se),logWarrantDenied:W,serviceUserIfPermitted:Mn})}catch(se){console.error(`${L.COLORS.yellow}Warning:${L.COLORS.reset} Gateway bridge failed: ${se instanceof Error?se.message:String(se)}`)}}os=!0})()});let Ip=!1,Pp=()=>{Ip||(Ip=!0,os=!1,console.log(`
527
- Shutting down...`),(async()=>{if(Z)try{await Z.flush()}catch{}if(yn){try{await yn.unregisterAgent(i)}catch{}yn=null}if(ye)try{await ye.close()}catch{}if(ut)try{await ut.close()}catch{}if(oo)try{await oo.flush()}catch{}Op.close(()=>{Ln.dispose(),process.exit(0)}),setTimeout(()=>{Ln.dispose(),process.exit(0)},1e4).unref()})())};process.on("SIGINT",Pp),process.on("SIGTERM",Pp)}async function C_(t){let e=await(0,ge.readBodyWithCap)(t);try{return JSON.parse(e)}catch{throw new Error("Invalid JSON")}}async function nD(t,e,n,r,s,i,o,a,c,l){let f=await t.run({engineId:L_(e.engine,s),modelId:e.model||i,message:e.message,workspaceRoot:o,sessionId:n,sandboxKey:r,analyticsUserId:c,permissions:a,turnEnv:l});return{success:f.success,text:f.text,thinking:f.thinking||void 0,tool_calls:f.toolCalls,error:f.error}}function k_(t,e,n="session",r=!1){if(r&&e){let a=`gateway-${e}`;return{sessionKey:`${a}--${(0,v_.randomUUID)()}`,sandboxKey:a,outboundKey:t.sessionId?.trim()||t.gatewaySessionKey?.trim()||a,durable:!1}}let s=e?`u${(0,ge.userNamespaceHash)(e)}`:void 0,i=t.sessionId?.trim()||t.gatewaySessionKey?.trim();if(i){let a=e?`u${(0,ge.userNamespaceHash)(e)}--${i}`:i;return{sessionKey:a,sandboxKey:n==="user"&&s?s:a,outboundKey:i,durable:!0}}if(e){let a=`gateway-${e}`;return{sessionKey:a,sandboxKey:n==="user"&&s?s:a,outboundKey:a,durable:!0}}let o=`gateway-anon-${(0,v_.randomUUID)()}`;return{sessionKey:o,sandboxKey:o,outboundKey:o,durable:!1}}async function $_(t){let e=async r=>{try{await t.emitter?.text(r),await t.emitter?.done()}catch{}};if(!t.rateLimiter.tryConsume(t.rlKey))return await e(ge.RATE_LIMIT_BUSY_MESSAGE),{success:!1,error:"rate_limited"};let n=await t.turnGate.acquire();if(!n)return t.warnGateReject(`TurnGate: rejecting gateway turn (inflight=${t.turnGate.inflight} queued=${t.turnGate.queued} max=${t.turnGate.max})`),await e(ge.TURN_GATE_BUSY_MESSAGE),{success:!1,error:"busy"};try{return t.trackSession!==!1&&!t.turnLimiter.tryConsume(t.sessionKey)?(await e(ge.TURN_LIMIT_BUSY_MESSAGE),{success:!1,error:"turn_limit"}):await t.run()}finally{n()}}async function rD(t){let{GatewayBridge:e}=await Promise.resolve().then(()=>wn(S_())),r=process.env.OPENCLAW_GATEWAY_URL??"ws://127.0.0.1:18789",s=t.brokerGatewayToken,i=new e({gatewayUrl:r,token:s});return await i.connect(),await i.registerAgent({id:t.gatewayAgentId,agentId:t.packName,name:`${t.packName} (CLI)`,workspace:t.workspace,engineId:t.engine,syncOpenClawConfigAgent:!0,messageHandler:(o,a)=>D_(t,o,a)}),console.log(`${L.COLORS.green}\u2713${L.COLORS.reset} Gateway bridge: registered "${t.gatewayAgentId}" at ${r}`),console.log(`${L.COLORS.dim} Gateway outbound routes: ${t.workspace}/.agent-hippo/sessions/<sessionKey>/gateway-outbound.json${L.COLORS.reset}`),console.log(`${L.COLORS.dim} openclaw agent --agent ${t.gatewayAgentId} --message "\u2026"${L.COLORS.reset}`),i}async function D_(t,e,n){let r=n.engineId?.trim().toLowerCase(),s=r==="custom"?t.engine:r||t.engine,i=(0,ge.peerToUserId)(n.peerInfo),o=i?void 0:await t.serviceUserIfPermitted?.(),a=i??o,{sessionKey:c,sandboxKey:l,outboundKey:f,durable:u}=k_(n,a,t.sandboxScope,!!o);return $_({rateLimiter:t.rateLimiter,turnLimiter:t.turnLimiter,turnGate:t.turnGate,warnGateReject:t.warnGateReject,rlKey:a??"gateway",sessionKey:c,trackSession:u,emitter:n.emitter,run:async()=>{u&&await t.prepareSession(c);let d=a?.trim()?await t.registerTurn({userId:a.trim(),sessionKey:c,egressStoreKey:f}):null;try{let p=await(0,Vc.runWithCredential)({userId:a},()=>t.runner.run({engineId:s,modelId:t.defaultModel,message:e,workspaceRoot:t.workspace,sessionId:c,sandboxKey:l,gatewaySessionKey:f,analyticsUserId:a,emitter:n.emitter,permissions:t.permissions,turnEnv:d?.env}),{onDenied:t.logWarrantDenied(c)});return u&&t.onTurnComplete?.(c),{success:p.success,error:p.error}}finally{await d?.release()}}})}async function sD(t,e,n){let{createAgentIDEGatewayClient:r}=await Promise.resolve().then(()=>wn(Mc())),i=process.env.OPENCLAW_GATEWAY_URL??"ws://127.0.0.1:18789",{client:o,clientInfo:a}=r(i,n);try{await o.connect(a)}catch(c){throw new Error(`Cannot connect to gateway at ${i}: ${c instanceof Error?c.message:String(c)}`)}try{let c,l,f;if(e.trim()==="*"){let d=await(0,Zd.fetchMeetAgentChannelContext)(o.request.bind(o));c=d.rows.map(p=>p.id),f=d.statusPayload}else{let d=(0,Zd.parseChannelBindSpecs)(e);c=d.map(p=>p.channelId),l=Object.fromEntries(d.filter(p=>p.accountId).map(p=>[p.channelId,p.accountId])),Object.keys(l).length===0&&(l=void 0)}if(c.length===0){console.log(`${L.COLORS.yellow}Warning:${L.COLORS.reset} No channels to bind.`);return}let u=await(0,Zd.applyAgentChannelBindingsViaConfigPatch)(o.request.bind(o),{agentId:t,selectedChannelIds:c,channelAccountOverrides:l,statusPayload:f});console.log(u?`${L.COLORS.green}\u2713${L.COLORS.reset} Bound ${t} to: ${c.join(", ")}`:`${L.COLORS.dim}Slack already bound to ${t}; skipped config.patch${L.COLORS.reset}`)}finally{o.close()}}async function iD(t,e,n,r,s,i,o,a,c,l,f){let u=!1,d=(m,h)=>{u||c.writableEnded||c.write(`data: ${JSON.stringify({type:m,...h})}
526
+ [Error: ${u}]`,a.sendEvent("agent.stream",{runId:s,agentId:o,sessionKey:i,state:"error",message:u})},async done(){a.sendEvent("agent.stream",{runId:s,agentId:o,sessionKey:i,state:"done"})}};try{let u=r.senderUsername||r.senderName||r.senderId||r.channel?{senderUsername:r.senderUsername,senderName:r.senderName,senderId:r.senderId,channel:r.channel}:void 0,d=await n.chatUIHandler(r.message,i,u,f,{params:r,runId:s,agentId:o}),p=c||d;this.log(`Agent ${o} (Chat UI) completed: response.len=${p.length}`),p||this.log(`WARNING: Agent ${o} (Chat UI) produced empty response!`);let g={text:p,runId:r.idempotencyKey};this.client.respond(e.id,g,!0),this.emit("agent.response",{agentId:o,message:r.message,response:p})}catch(u){this.client.respond(e.id,void 0,!1,{code:"CHAT_UI_ERROR",message:u instanceof Error?u.message:String(u)}),this.log(`Agent ${o} (Chat UI) failed: ${u}`)}}getDefaultAgentId(){if(this.agents.size===1){let e=this.agents.keys().next();return e.done?void 0:e.value}}log(e){let n=`[GatewayBridge] ${e}`;this.options.outputChannel&&this.options.outputChannel.appendLine(n),this.emit("log",n)}async disconnect(){for(let e of this.agents.keys())await this.unregisterAgent(e);this.client.close(),this.log("Disconnected from Gateway")}get isConnected(){return this.client.isConnected}get connId(){return this.serverConnId}get registeredAgents(){return Array.from(this.agents.keys())}async reconnect(){this.log("Force reconnecting to Gateway..."),await this.client.reconnect()}async request(e,n){return this.client.request(e,n)}};Kt.GatewayBridge=Bc;function Y$(t){return new Bc(t)}});var G_=S(Qn=>{"use strict";var X$=Qn&&Qn.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,s)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),J$=Qn&&Qn.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),Wo=Qn&&Qn.__importStar||(function(){var t=function(e){return t=Object.getOwnPropertyNames||function(n){var r=[];for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(r[r.length]=s);return r},t(e)};return function(e){if(e&&e.__esModule)return e;var n={};if(e!=null)for(var r=t(e),s=0;s<r.length;s++)r[s]!=="default"&&X$(n,e,r[s]);return J$(n,e),n}})();Object.defineProperty(Qn,"__esModule",{value:!0});Qn.serveCommand=iD;Qn.resolveGatewaySessionKey=$_;Qn.runGatewayTurn=D_;Qn.runBridgeTurn=L_;var b_=Wo(require("crypto")),Hs=Wo(require("fs")),v_=Wo(require("os")),z$=Wo(require("http")),Es=Wo(require("path")),O_=require("node:crypto"),Q$=Am(),Fc=vo(),Jn=Po(),zd=td(),Z$=id(),pi=Ro(),I_=Tc(),P_=eE(),Vc=aE(),N_=pE(),Vr=pd(),zn=oi(),gi=ai(),L=Wn(),eD=md(),Qd=CE(),ge=Br(),Kc=Is(),Wc=Ro(),tD=Pi(),ht=$c(),R_=Er(),nD=Fd(),C_=Ao(),Fo=zs(),js=g_(),rD=h_(),Zd=Yd(),sD=Ns(),Vo="-".repeat(62);async function iD(t){let e=(0,gi.getApiConfig)();e.useLiteLLM&&!e.litellmApiKey&&console.warn(`${L.COLORS.yellow}Warning:${L.COLORS.reset} AGENTHIPPO_LITELLM_BASE_URL is set without AGENTHIPPO_LITELLM_API_KEY \u2014 gateway calls will authenticate as 'sk-dummy' (a strict gateway will 401). Provider keys are never sent to the gateway.`);let n,r=t.verbose?new zn.ConsoleLogger("[Sync]"):new zn.NoOpLogger;try{n=await(0,gi.loadAgentPack)(t.agent,t.workspace)}catch(w){console.error(`Error: ${w instanceof Error?w.message:w}`),process.exit(1)}let s=n.manifest.metadata.name,i=(0,rD.resolveCliGatewayAgentId)(s),o=(t.engine||n.manifest.spec.engine||(0,gi.getDefaultConfig)().engine).trim().toLowerCase(),a=["claude","codex"].includes(o)?void 0:(0,sD.tryResolveCustomEngineManifest)(t.workspace,o)?.model?.defaultModel,c=t.model||n.manifest.spec.model||a||(0,gi.getEnvDefaultModel)()||(0,gi.getDefaultConfig)().model,l=(0,zn.resolveModelAlias)(c),f=n.manifest.spec.cheapModel?.trim(),u=f?(0,zn.resolveModelAlias)(f):void 0;if(!(0,gi.hasCredentialForEngine)(o,e)){console.error(`Error: No usable API key for engine "${o}". Set ${o==="claude"?"ANTHROPIC_API_KEY":"OPENAI_API_KEY"}, or configure the LiteLLM proxy (AGENTHIPPO_LITELLM_API_KEY + AGENTHIPPO_LITELLM_BASE_URL).`);for(let k of(0,L.getLiteLLMQuickstartHintLines)())console.error(k);process.exit(1)}let d=t.verbose?new zn.ConsoleLogger("[Server]"):new zn.NoOpLogger,p=n.packPath,g=n.manifest.metadata.version??"0.0.0",m,h=await(0,Jn.loadPackTrustRoot)({leaseUrl:process.env.AGENTHIPPO_LEASE_URL}),E=(w,k="pack")=>{for(let se of w.warnings)console.warn(`${L.COLORS.yellow}Warning:${L.COLORS.reset} ${se}`);w.status==="unavailable"&&console.warn(`${L.COLORS.yellow}Warning:${L.COLORS.reset} ${k} trust root is configured but unusable: ${w.reason}`)};E(h);let _=(0,Jn.createPackVerifier)(),y={ok:!1,kind:"no-pack",reason:"not verified"},b=(w,k)=>(y=_.refresh({packDir:w,pack:s,packVersion:k,keys:h.keys}),m=y.ok?y.claims.digest:void 0,d.info(y.ok?`[Pack] signature verified for ${s}`:`[Pack] unverified \u2014 ${y.reason}`),y),T=w=>{if(w.ok)return"";let k=h.status==="unavailable"&&w.kind==="no-trust-root"?"trust-root-unavailable":w.kind;return(0,Jn.describePackRefusal)({kind:k,detail:k==="trust-root-unavailable"?h.reason??w.reason:w.reason,pack:s,packVersion:g,packDir:p,trustRootHint:h.url?`Trust root: ${h.url} (${h.reason??"unavailable"})`:h.reason})};b(p,g);let O=!!t.allowUnsignedPack||(0,Jn.allowUnsignedPackFromEnv)();y.ok||(O||(console.error(`${L.COLORS.red}Error: ${T(y)}${L.COLORS.reset}`),process.exit(1)),console.warn(Vo),console.warn(`${L.COLORS.yellow}!! RUNNING AN UNVERIFIED PACK \u2014 signature checking is DISABLED on this instance.${L.COLORS.reset}`),console.warn(`${L.COLORS.yellow}!! ${y.reason}${L.COLORS.reset}`),console.warn(`${L.COLORS.yellow}!! Whatever is in ${p} will be executed, verified by nobody.${L.COLORS.reset}`),console.warn(`${L.COLORS.yellow}!! This is a LOCAL DEVELOPMENT setting (AGENTHIPPO_ALLOW_UNSIGNED_PACK). Do not ship it.${L.COLORS.reset}`),console.warn(Vo));let A=(0,L.findBundledBasePromptsDir)();await(0,zn.syncPackToWorkspace)(t.workspace,n.packPath,s,o,r,A),console.log(`OK: Loaded agent: ${n.manifest.metadata.name} v${n.manifest.metadata.version}`),console.log(`agenthippo pack=${n.manifest.metadata.name}@${n.manifest.metadata.version} engine=${o}`);let{dir:v,ephemeral:C}=(0,ge.resolveStateDir)(t.stateDir),B=(0,ge.resolveBindHost)(t.host);for(let w of(0,ge.identityHeaderAdvice)(process.env,B))console.warn(`${L.COLORS.yellow}Warning:${L.COLORS.reset} ${w}`);let R=(0,ge.tenantIsolationAdvice)({sandbox:t.sandbox,sharedWorkspace:!!t.sharedWorkspace,workspace:t.workspace,stateDir:v});if(R.level==="refuse"){for(let w of R.lines)console.error(`${L.COLORS.red}Error:${L.COLORS.reset} ${w}`);console.error(`Refusing to start because ${ge.REQUIRE_TENANT_ISOLATION_ENV} is set. Unset it to downgrade this to a warning.`),process.exit(1)}for(let w of R.lines)console.warn(`${L.COLORS.yellow}Warning:${L.COLORS.reset} ${w}`);let F=(0,ge.resolveAnalyticsSessionsDir)(v,C),re=new C_.SessionEventWriter(F),W=w=>k=>re.append(w,(0,Fo.generateRequestId)(),"warrant_denied",{reason:k}),de=(0,ht.resolveDataPlaneConfig)(n.manifest.spec,n.packPath),he=(0,ht.resolveEdgeDataPlane)(),Q=he?new ht.EdgeDataPlane(he):null,Ne=Q?null:(0,ht.resolveRemoteDataPlane)(),We=Ne?new ht.RemoteDataPlane(Ne):null,Me=de&&!We&&!Q||t.gatewayBridge?new ht.TurnRegistry:null,on=(w,k,se)=>re.append(w,(0,Fo.generateRequestId)(),k,{...se,agent:{pack:s,version:g,digest:m??null}}),ye=null;if(Q)process.env[ht.DATA_MCP_URL_ENV]=Q.url,delete process.env.AGENTHIPPO_DATA_PLANE_TOKEN,delete process.env.AGENTHIPPO_DATA_PLANE_CONTROL_URL,console.log(`OK: Data plane EDGE-registered \u2014 gateway ${Q.url}; turn nonces are minted at the edge, serve holds no registration credential`);else if(We)process.env[ht.DATA_MCP_URL_ENV]=We.url,delete process.env.AGENTHIPPO_DATA_PLANE_TOKEN,console.log(`OK: Data plane SIDECAR \u2014 gateway ${We.url}; base credentials stay in the connector container, not here`);else if(de)try{ye=await ht.DataPlane.start(de,{logger:t.verbose?new zn.ConsoleLogger("[DataPlane]"):new zn.NoOpLogger,audit:on,registry:Me??void 0}),process.env[ht.DATA_MCP_URL_ENV]=ye.url,console.log(`OK: Data gateway (provider=${ye.broker.provider.name}) on loopback \u2014 connector: ${de.connectorPath}`)}catch(w){console.error(`${L.COLORS.red}Error: failed to start the data-plane gateway:${L.COLORS.reset} ${w instanceof Error?w.message:w}`),process.exit(1)}let cr=(0,R_.readOpenClawGatewayToken)();delete process.env.OPENCLAW_GATEWAY_TOKEN;let ut=null,qt=async w=>{if(Q){let J=w.edgeNonce?.trim();if(!J)return console.warn(`${L.COLORS.yellow}Warning:${L.COLORS.reset} edge data plane active but no ${ht.TURN_NONCE_HEADER} header on this turn \u2014 data tools will fail closed (check the edge route's forward_auth)`),null;let De=Q.adoptTurn(J),wt={...De.env};return ut&&(wt[ht.EGRESS_URL_ENV]=ut.url),{nonce:De.nonce,env:wt,release:De.release}}if(We){let J=await We.registerTurn({...w,agent:{pack:s,version:g,digest:m}}),De={...J.env};return ut&&(De[ht.EGRESS_URL_ENV]=ut.url),{nonce:J.nonce,env:De,release:J.release}}if(!Me)return null;let{nonce:k,release:se}=Me.register(w),nt={[ht.TURN_NONCE_ENV]:k};return ye&&(nt[ht.DATA_MCP_URL_ENV]=ye.url),ut&&(nt[ht.EGRESS_URL_ENV]=ut.url),{nonce:k,env:nt,release:se}},En=w=>{if(!Q)return;let k=w[ht.TURN_NONCE_HEADER];return Array.isArray(k)?k[0]:k},Dn=new ge.TurnLimiter(t.maxTurnsPerSession??0),Et=Number(process.env.AGENTHIPPO_SERVE_RATE_LIMIT??120),It=new ge.RateLimiter(Number.isFinite(Et)?Et:120),Pt=(0,ge.createTurnGateFromEnv)(),vs=(0,ge.createRejectionWarner)(),K;if(t.wwwDir?.trim()){let w=Es.join(Es.resolve(t.wwwDir.trim()),"index.html");try{K=Hs.readFileSync(w,"utf8")}catch{console.warn(`${L.COLORS.yellow}Warning:${L.COLORS.reset} --www-dir set but unreadable: ${w}`)}}C&&console.warn(`${L.COLORS.yellow}Warning:${L.COLORS.reset} Session state is in a tmpdir (ephemeral). Pass --state-dir or set AGENTHIPPO_HOME to persist sessions across restarts.`);let Ut=(0,js.resolveS3StateConfig)(),I=(0,js.resolveRestoreBootMode)();Ut&&(await(0,js.isAwsCliAvailable)()||(console.error(`${L.COLORS.red}Error: AGENTHIPPO_STATE_S3_URI is set but the \`aws\` CLI was not found.${L.COLORS.reset}`),console.error(" State sync requires the AWS CLI (S3-compatible via --endpoint-url). Install it or unset AGENTHIPPO_STATE_S3_URI."),process.exit(1)),I==="all"?(console.log(`State sync: boot-restore from ${Ut.uri} \u2026`),await(0,js.restoreState)(Ut,v,w=>console.log(` ${w}`))):console.log(`State sync: restore-on-miss from ${Ut.uri} (boot restore disabled)`));let Z=Ut?(0,js.makeStatePusher)(Ut,v,t.verbose?w=>console.error(w):void 0):null,j=t.verbose?w=>console.error(w):void 0,pe=async w=>{Ut&&await(0,js.ensureSessionLocal)(Ut,v,w,j)},dt=(0,L.findClaudeCodePath)(),oe=(0,L.findCodexPath)(),_t=t.sandbox==="container";!_t&&o==="claude"&&!dt&&(console.error(`${L.COLORS.red}Error: Claude Code CLI not found.${L.COLORS.reset}`),console.error(" Install: npm install -g @anthropic-ai/claude-code"),console.error(" Or set CLAUDE_CODE_PATH environment variable"),process.exit(1)),!_t&&o==="codex"&&!oe&&(console.error(`${L.COLORS.red}Error: Codex CLI not found.${L.COLORS.reset}`),console.error(" Install: npm install -g @openai/codex"),console.error(" Or set CODEX_PATH environment variable"),process.exit(1));let Yt=new zn.AutoApprovePermissionHandler,Xt={fileAccess:(0,gi.getFileAccess)(n)},Jt,rs=!1,Ti=w=>{let k=(0,pi.policyVersion)(w);rs&&k===Jt||(rs=!0,Jt=k,re.append("serve",(0,Fo.generateRequestId)(),"policy_applied",{instance_id:Cr,policy_version:k??null,pack_digest:m??null,engine_version:(0,Fc.installedEngineVersion)(o)??null,tier:t.sandbox==="container"?2:t.sandbox?0:null,enabled:w?.enabled??null,pinned_version:w?.version??null,caps:w?.caps??null,deny_count:w?.deny?.length??0}))},ro,lr=Es.join(v,"packs"),ia=async(w,k)=>(await(0,Z$.downloadFromStore)({type:"pack",slug:w,version:k})).map(nt=>({path:nt.path,content:nt.content})),so=async w=>{if(!t.pullPacks||!w||w===g)return;let k=await(0,zd.reconcilePinnedPack)({pack:s,currentVersion:g,pinnedVersion:w,packsRoot:lr,download:ia,publicKeysByKid:h.keys,logger:{info:se=>d.info(se),warn:se=>d.info(se)}});if(k.ok){g=k.version,p=k.packDir,b(p,g),d.info(`[Pack] now serving ${s}@${g} from ${k.packDir}`);return}console.warn(`${L.COLORS.yellow}Warning:${L.COLORS.reset} cannot converge to ${s}@${w}: ${k.reason}. Still serving @${g}.`)},oa=(0,Vr.loadWarrantKeypair)(d),io,Cr=(()=>{try{let w=Es.join((0,ge.resolveStateDir)(t.stateDir).dir,"instance-id");if(Hs.existsSync(w))return Hs.readFileSync(w,"utf-8").trim();let k=`${v_.hostname()}-${b_.randomBytes(4).toString("hex")}`;return Hs.mkdirSync(Es.dirname(w),{recursive:!0}),Hs.writeFileSync(w,k),k}catch{return`${v_.hostname()}-${b_.randomBytes(4).toString("hex")}`}})(),oo={get:()=>n?.manifest.metadata.version},ss=(0,pi.resolveLeasePollSeconds)(t.leasePollSeconds),ur=await(0,Jn.loadLeaseTrustRoot)({leaseUrl:process.env.AGENTHIPPO_LEASE_URL});ur.explicitlyConfigured&&E(ur,"lease");let bi=!1,Ws=()=>{let w=(0,Jn.selectLeaseSigningKeys)(ur,h);return w.packFallback&&!bi&&(bi=!0,console.warn(`${L.COLORS.yellow}Warning:${L.COLORS.reset} verifying signed leases against the PACK trust root \u2014 no lease trust root is configured on this instance. The control plane publishes lease keys under purpose \`lease-signing\` and refuses to register one kid under two purposes, so this stops working the moment the plane rotates to a dedicated lease key \u2014 and requireSignedLease is sticky with no plane-side undo, so that failure cannot be fixed from the console. Set ${Jn.LEASE_JWKS_URL_ENV}=https://<plane>/.well-known/jwks.json?purpose=lease-signing (or ${Jn.LEASE_SIGNING_KEYS_ENV} with inline {"<kid>":"<public PEM>"} for an air-gapped install).`+(ur.reason?` The derived lease trust root is unusable: ${ur.reason}`:""))),w.keys},zt=(0,pi.createLeaseSource)({url:process.env.AGENTHIPPO_LEASE_URL,identity:()=>({instance:Cr,pack:s,version:oo.get(),tier:t.sandbox==="container"?2:t.sandbox?0:void 0,sandboxes:io?.sandboxes().length,engine:o,engineversion:(0,Fc.installedEngineVersion)(o)}),cacheSeconds:(0,pi.leaseCacheSecondsFor)(ss),signingKeys:()=>Ws(),requireSignedLease:t.requireSignedLease,instanceId:Cr,...t.leaseMaxStalenessSeconds!==void 0?{maxStalenessSeconds:t.leaseMaxStalenessSeconds}:{},logger:{info:w=>d.info(w),warn:w=>console.warn(`${L.COLORS.yellow}Warning:${L.COLORS.reset} ${w}`)}}),aa=async()=>{if(h.status!=="configured"){let w=await(0,Jn.loadPackTrustRoot)({leaseUrl:process.env.AGENTHIPPO_LEASE_URL});w.status==="configured"&&(h=w,E(w),d.info(`[Pack] signing keys now available (${Object.keys(w.keys).length}); re-verifying`),b(p,g))}if(ur.status!=="configured"){let w=await(0,Jn.loadLeaseTrustRoot)({leaseUrl:process.env.AGENTHIPPO_LEASE_URL});w.status==="configured"&&(ur=w,w.explicitlyConfigured&&E(w,"lease"),d.info(`[Lease] lease-signing keys now available (${Object.keys(w.keys).length})`))}};zt.get().then(Ti).catch(()=>{});{let w=ss*1e3;setInterval(()=>{zt.get().then(Ti).catch(()=>{}),aa().catch(()=>{})},w).unref?.()}if(t.pullPacks){Hs.mkdirSync(lr,{recursive:!0});let w=Es.join(lr,g);Hs.existsSync(w)||Hs.cpSync(n.packPath,w,{recursive:!0}),(0,zd.promoteCurrent)(lr,w),p=Es.join(lr,zd.CURRENT_LINK),await so((await zt.get())?.version),b(p,g)}if(oo.get=()=>g,ro=(0,eD.createPackRunner)({storagePath:v,analyticsSessionsDir:F,packId:s,packVersion:g,provenance:()=>({policyVersion:Jt,packDigest:m,engineVersion:(0,Fc.installedEngineVersion)(o),tier:t.sandbox==="container"?2:t.sandbox?0:void 0,instanceId:Cr}),workspaceRoot:t.workspace,credentials:{apiKey:e.apiKey,baseUrl:e.baseUrl,useLiteLLM:e.useLiteLLM,litellmApiKey:e.litellmApiKey,openaiApiKey:e.openaiApiKey,anthropicApiKey:e.anthropicApiKey},logger:d,permissionHandler:Yt,claudeCheapModel:u,omitGatewayToken:!0}),t.pullPacks){let w=ss*1e3;setInterval(()=>{zt.get().then(se=>so(se?.version)).catch(()=>{})},w).unref?.()}let ao=!!t.sharedWorkspace,z=t.sandboxScope==="user"?"user":"session",M=t.sandbox==="container"?{readonly:[`${p}:${Vc.SANDBOX_PACK_DIR}`],writable:[`${t.workspace}:${Vc.SANDBOX_WORKSPACE_DIR}`]}:void 0;M&&ao&&console.warn(`${L.COLORS.yellow}Warning:${L.COLORS.reset} --shared-workspace: every session's sandbox mounts ${t.workspace} read-write, so sessions can read and overwrite each other's files. Only safe when all sessions belong to one trust domain.`);let we;M&&t.sandboxImage&&(await(0,Vr.alignSandboxWorkspaceOwnership)({exec:Vr.dockerExec,image:t.sandboxImage,writable:M.writable,logger:{info:w=>d.info(w),warn:w=>console.warn(`${L.COLORS.yellow}Warning:${L.COLORS.reset} ${w}`)}}),we=await(0,Vr.resolveSandboxImageUser)(Vr.dockerExec,t.sandboxImage));let ke=w=>(0,Vr.ensureSandboxStateDir)(Es.join(v,"sandbox-state",(0,js.safeSessionId)(w)),we),Xe=async w=>{if(!M)return{readonly:[],writable:[]};if(ao)return M;let k=(0,Vr.ensureSandboxStateDir)(Es.join(v,"sandbox-workspace",(0,js.safeSessionId)(w)),we);return{readonly:M.readonly,writable:[`${k}:${Vc.SANDBOX_WORKSPACE_DIR}`]}},me=(w,k,se)=>{if((0,Jn.resolveRequireSignedPack)({lease:w?.requireSignedPack,localRequire:t.requireSignedPack,localAllowUnsigned:O})){let J=_.verify({packDir:p,pack:s,packVersion:g,keys:h.keys});if(J!==y&&(y=J,m=J.ok?J.claims.digest:void 0),!J.ok)throw new pi.LeaseDeniedError(T(J))}(0,pi.assertAdmitted)(w,{pack:s,version:g,image:t.sandboxImage,sessionKey:k,userHash:ge.userNamespaceHash,userId:se})},Ie=t.sandbox?(0,Q$.createSandboxRunner)({driver:t.sandbox==="container"?new Vc.ContainerSandboxDriver({exec:Vr.dockerExec,socketOwner:we,logger:{info:w=>d.info(w),warn:w=>console.warn(`${L.COLORS.yellow}Warning:${L.COLORS.reset} ${w}`)}}):new N_.ProcessSandboxDriver({command:process.execPath,args:[...(0,Vr.sandboxScriptArg)(),"sandbox","--agent",p,"--stdio","--state-dir",v,"--workspace",t.workspace],namespaceIsolation:(0,N_.namespaceIsolationFromEnv)(),logger:{info:w=>d.info(w),warn:w=>console.warn(`${L.COLORS.yellow}Warning:${L.COLORS.reset} ${w}`)}}),image:t.sandboxImage??"",tier:t.sandbox==="container"?2:0,...M?{fs:M,fsFor:Xe,stateDirFor:ke}:{},routes:[...process.env.AGENTHIPPO_DATA_MCP_URL?[{kind:"data",target:process.env.AGENTHIPPO_DATA_MCP_URL}]:[],...e.baseUrl?[{kind:"inference",target:e.baseUrl}]:[]],limits:{ttlSeconds:t.sandboxTtlSeconds??1800},provenanceEnv:()=>(0,R_.buildProvenanceEnv)({policyVersion:Jt,packDigest:m,engineVersion:(0,Fc.installedEngineVersion)(o),tier:t.sandbox==="container"?2:t.sandbox?0:void 0,instanceId:Cr}),admit:async({sessionKey:w})=>{let k=await zt.get();me(k,w)},inferenceBaseUrl:e.baseUrl,mintModelToken:(w,k)=>(0,Vr.mintSandboxInferenceWarrant)(oa,{user:(0,Kc.currentCredential)()?.userId?.trim()||`anon:${k}`,pack:s,packVersion:g,sandboxId:w,tier:t.sandbox==="container"?2:0,ttlSeconds:300}),logger:d,runtime:{logger:d,editTracker:void 0,configProvider:void 0,permissionHandler:Yt}}):void 0;io=Ie??void 0;let yt=w=>typeof w=="number"&&Number.isFinite(w)&&w>0?w:void 0,et={...(0,I_.capsFromEnv)(),...yt(t.maxTurnsPerSession)!==void 0?{maxTurnsPerSession:t.maxTurnsPerSession}:{},...yt(t.maxSessionSeconds)!==void 0?{maxSessionSeconds:t.maxSessionSeconds}:{},...yt(t.maxConcurrentSandboxes)!==void 0?{maxConcurrentSandboxes:t.maxConcurrentSandboxes}:{},...t.capOnBreach?{onBreach:t.capOnBreach}:{}},tt=et.maxTurnsPerSession!==void 0||et.maxSessionSeconds!==void 0||et.maxConcurrentSandboxes!==void 0,Ae={sandboxes:()=>[],destroySession:async()=>{},revokeRoute:async()=>{},supportsInFlightTermination:!1},Ht=!!(Ie||process.env.AGENTHIPPO_LEASE_URL||tt)?(0,P_.createGovernor)({caps:(0,I_.mergeCaps)((await zt.get())?.caps,et),sandboxes:Ie??Ae,getLease:()=>zt.get(),pollSeconds:ss,pack:s,userHash:ge.userNamespaceHash,...Ie?{}:{admitPack:(w,k)=>{try{return me(k,w),{allowed:!0}}catch(se){return{allowed:!1,reason:se instanceof Error?se.message:String(se)}}}},logger:d,audit:(w,k)=>on(String(k.sessionKey??"instance"),w,k)}):void 0;tt&&!Ie&&console.warn(`${L.COLORS.yellow}Warning:${L.COLORS.reset} caps are configured but --sandbox is not set. Turn and duration caps still refuse the turn; the concurrency cap and route revocation need sandboxes, so those are IGNORED.`);let vi=Ie??ro,Ln=Ht?(0,P_.withGovernor)(vi,Ht):vi;if(Ht){Ht.start();let w=Ht.policy(),k=(0,pi.effectiveKillLatencySeconds)(ss);d.info(`[Serve] control plane: caps turns=${w.maxTurnsPerSession??"\u221E"} session=${w.maxSessionSeconds??"\u221E"}s sandboxes=${w.maxConcurrentSandboxes??"\u221E"} onBreach=${w.onBreach??"revoke-inference"}; lease poll ${ss}s (worst-case kill latency ${k}s; an admin refresh is immediate)`),Ie||d.info("[Serve] no sandbox driver: a deny rule with mode=kill takes effect as DRAIN \u2014 the in-flight turn finishes and only the next one is refused.");let se=zt.status();process.env.AGENTHIPPO_LEASE_URL&&!se.requireSignedLease&&d.info("[Serve] lease signature is NOT required \u2014 set --require-signed-lease (or lease.requireSignedLease) once the control plane signs leases.")}let fe=(0,ge.resolveServiceIdentity)();fe.error&&(console.error(`${L.COLORS.red}Error:${L.COLORS.reset} ${fe.error}`),process.exit(1)),fe.warning&&console.warn(`${L.COLORS.yellow}Warning:${L.COLORS.reset} ${fe.warning}`);let _n=!!process.env.AGENTHIPPO_LEASE_URL,Mn=async()=>{if(!fe.identity)return;let w=(0,Wc.resolveAllowServiceTurns)({lease:(await zt.get())?.allowServiceTurns,managed:_n});if(!w.allowed){on("service-turn","service_turn_denied",{identity:(0,tD.hashIdentity)(fe.identity),gate:w.gate,detail:(0,Wc.describeServiceTurnGate)(w.gate)});return}return fe.identity};if(fe.identity){let w=(0,Wc.resolveAllowServiceTurns)({lease:void 0,managed:_n});d.info(`[Serve] unattended runs: identity configured (${ge.SERVICE_USER_ENV}); `+(_n?"the control plane decides per turn via lease.allowServiceTurns \u2014 absent means deny":(0,Wc.describeServiceTurnGate)(w.gate)))}Ie&&(d.info(`[Serve] sandbox mode: ${t.sandbox} (tier ${t.sandbox==="container"?2:0}) \u2014 engines run in per-session sandboxes`),e.baseUrl||console.warn(`${L.COLORS.yellow}Warning:${L.COLORS.reset} --sandbox without an inference proxy: a sandbox holds no provider key, so model calls will fail 401. Set AGENTHIPPO_LITELLM_BASE_URL.`));let yn=null,is=!1,co,Ip=z$.createServer(async(w,k)=>{let se=(0,ge.corsHeaders)();for(let[nt,J]of Object.entries(se))k.setHeader(nt,J);if(w.method==="OPTIONS"){k.writeHead(204),k.end();return}try{if(w.method==="GET"&&w.url==="/health"){let J={status:"ok"};J.evidence_ship_enabled=!!co;let De=co?.lastOkAt();De!==void 0&&(J.evidence_ship_last_ok_at=new Date(De).toISOString());let wt=(0,Qd.getEvidenceShipStatus)();J.evidence_ship_disabled_reason=wt.disabledReason??null,J.evidence_ship_consecutive_failures=wt.consecutiveFailures,J.evidence_records_staged=wt.recordsStaged,J.evidence_records_shipped=wt.recordsShipped,J.evidence_records_skipped_too_old=wt.recordsSkippedTooOld,J.evidence_files_skipped_too_old=wt.filesSkippedTooOld,J.evidence_content_capture=wt.contentCapture,wt.lastHeartbeatAt!==void 0&&(J.evidence_ship_last_heartbeat_at=new Date(wt.lastHeartbeatAt).toISOString());let Gn=(0,C_.getSessionEventWriterStats)();J.evidence_writes_ok=Gn.written,J.evidence_writes_failed=Gn.failed,Gn.lastError&&(J.evidence_write_last_error={at:new Date(Gn.lastError.at).toISOString(),event_type:Gn.lastError.eventType,message:Gn.lastError.message});let At=zt.status();J.lease_configured=!!process.env.AGENTHIPPO_LEASE_URL,J.lease_signed=At.signed,J.lease_signature_required=At.requireSignedLease,J.lease_staleness_seconds=At.stalenessSeconds??null,J.lease_fail_closed=At.failClosed,J.pack_signature_ok=y.ok,J.pack_signature_required=(0,Jn.resolveRequireSignedPack)({localRequire:t.requireSignedPack,localAllowUnsigned:O}),J.pack_trust_root=h.status,J.lease_trust_root=ur.status,J.lease_trust_root_source=ur.explicitlyConfigured?"lease":"pack-fallback",J.kill_in_flight_supported=!!Ie,k.writeHead(200,{"Content-Type":"application/json"}),k.end(JSON.stringify(J));return}if(w.method==="GET"&&w.url==="/ready"){k.writeHead(is?200:503,{"Content-Type":"application/json"}),k.end(JSON.stringify({ready:is,inflight:Pt.inflight,queued:Pt.queued,max:Pt.max}));return}let nt=w.url?.split("?")[0]??"";if(w.method==="GET"&&K&&(nt==="/"||nt==="/index.html")){k.writeHead(200,{"Content-Type":"text/html; charset=utf-8"}),k.end(K);return}if(w.method==="POST"&&nt==="/v1/chat"){let J=await k_(w),De=(0,ge.resolveUserId)(w.headers,J),wt=(0,ge.resolveDataToken)(w.headers),Gn=(0,ge.resolveUserId)(w.headers,void 0)??(0,ge.clientIp)(w);if(!It.tryConsume(Gn)){k.writeHead(429,{"Content-Type":"application/json","Retry-After":String(It.retryAfterSeconds(Gn))}),k.end(JSON.stringify({error:"Rate limit exceeded"}));return}let{sessionKey:At,sandboxKey:Il,rejected:lo}=(0,ge.resolveServeSessionKey)(J.session_id,De,z);if(lo){re.append("unverified",(0,Fo.generateRequestId)(),"warrant_denied",{reason:lo}),k.writeHead(403,{"Content-Type":"application/json"}),k.end(JSON.stringify({error:"verified user identity required"}));return}let uo=await Pt.acquire();if(!uo){vs(`TurnGate: rejecting /v1/chat (inflight=${Pt.inflight} queued=${Pt.queued} max=${Pt.max})`),k.writeHead(429,{"Content-Type":"application/json","Retry-After":String(ge.TURN_GATE_RETRY_AFTER_SECONDS)}),k.end(JSON.stringify({error:"At capacity"}));return}let Ks=null;try{if(!Dn.tryConsume(At)){k.writeHead(429,{"Content-Type":"application/json"}),k.end(JSON.stringify({error:"Per-session turn limit reached"}));return}await pe(At),De?.trim()&&(Ks=await qt({userId:De.trim(),sessionKey:At,inboundToken:wt,edgeNonce:En(w.headers)}));let tA=await(0,Kc.runWithCredential)({userId:De,dataToken:wt},()=>oD(Ln,J,At,Il,o,l,t.workspace,Xt,De,Ks?.env),{onDenied:W(At)});k.writeHead(200,{"Content-Type":"application/json"}),k.end(JSON.stringify(tA)),Z?.schedule(At)}finally{await Ks?.release(),uo()}return}if(w.method==="POST"&&nt==="/v1/chat/stream"){let J=await k_(w),De=(0,ge.resolveUserId)(w.headers,J),wt=(0,ge.resolveDataToken)(w.headers),Gn=(0,ge.resolveUserId)(w.headers,void 0)??(0,ge.clientIp)(w);if(!It.tryConsume(Gn)){k.writeHead(429,{"Content-Type":"application/json","Retry-After":String(It.retryAfterSeconds(Gn))}),k.end(JSON.stringify({error:"Rate limit exceeded"}));return}let{sessionKey:At,sandboxKey:Il,rejected:lo}=(0,ge.resolveServeSessionKey)(J.session_id,De,z);if(lo){re.append("unverified",(0,Fo.generateRequestId)(),"warrant_denied",{reason:lo}),k.writeHead(403,{"Content-Type":"application/json"}),k.end(JSON.stringify({error:"verified user identity required"}));return}let uo=await Pt.acquire();if(!uo){vs(`TurnGate: rejecting /v1/chat/stream (inflight=${Pt.inflight} queued=${Pt.queued} max=${Pt.max})`),k.writeHead(429,{"Content-Type":"application/json","Retry-After":String(ge.TURN_GATE_RETRY_AFTER_SECONDS)}),k.end(JSON.stringify({error:"At capacity"}));return}let Ks=null;try{if(!Dn.tryConsume(At)){k.writeHead(429,{"Content-Type":"application/json"}),k.end(JSON.stringify({error:"Per-session turn limit reached"}));return}await pe(At),De?.trim()&&(Ks=await qt({userId:De.trim(),sessionKey:At,inboundToken:wt,edgeNonce:En(w.headers)})),await(0,Kc.runWithCredential)({userId:De,dataToken:wt},async()=>{k.writeHead(200,{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}),await lD(Ln,J,At,Il,o,l,t.workspace,Xt,k,De,Ks?.env)},{onDenied:W(At)}),Z?.schedule(At)}finally{await Ks?.release(),uo()}return}k.writeHead(404,{"Content-Type":"application/json"}),k.end(JSON.stringify({error:"Not found"}))}catch(nt){if(nt?.tooLarge===!0){k.headersSent||k.writeHead(413,{"Content-Type":"application/json",Connection:"close"}),k.end(JSON.stringify({error:"Payload too large"}));return}console.error("Request error:",nt),k.headersSent||k.writeHead(500,{"Content-Type":"application/json"}),k.end(JSON.stringify({error:nt instanceof Error?nt.message:"Internal error"}))}});Ip.listen(t.port,B,()=>{(async()=>{console.log(""),console.log(Vo),console.log("Agent Hippo Server"),console.log(Vo),console.log(`Host: ${B}`),console.log(`Port: ${t.port}`),console.log(`Engine: ${o}`),console.log(`Model: ${l}`),u&&console.log(`Cheap: ${u}`),console.log(`Workspace: ${t.workspace}`),n&&(console.log(`Pack: ${n.manifest.metadata.name}@${n.manifest.metadata.version}`),console.log(`Gateway: ${i}`)),console.log(Vo),console.log(""),console.log("Endpoints:"),console.log(` POST http://localhost:${t.port}/v1/chat`),console.log(` POST http://localhost:${t.port}/v1/chat/stream`),console.log(` GET http://localhost:${t.port}/health`),console.log(""),console.log("Press Ctrl+C to stop."),console.log("");let w=(0,Qd.resolveSessionShipConfig)(Cr,F,v);w&&(co=(0,Qd.startSessionShipper)({...w,logger:{info:se=>d.info(se),warn:se=>console.warn(`${L.COLORS.yellow}Warning:${L.COLORS.reset} ${se}`)}}));let k=t.bind?.trim();if(k)try{await cD(i,k,cr)}catch(se){console.error(`${L.COLORS.yellow}Warning:${L.COLORS.reset} Failed to bind channels: ${se instanceof Error?se.message:String(se)}`)}if(t.gatewayBridge){if(Me)try{ut=await(0,ht.startEgressBroker)({registry:Me,workspaceRoot:t.workspace,agentId:n.manifest.metadata.name,send:async(se,nt,J)=>{let De=await(0,nD.sendGatewayOutboundMessage)(se,{message:nt,media:J,token:cr});return{ok:De.ok,via:De.via,stdout:De.stdout,stderr:De.stderr}},logger:t.verbose?new zn.ConsoleLogger("[Egress]"):new zn.NoOpLogger,audit:on}),process.env[ht.EGRESS_URL_ENV]=ut.url,console.log("OK: Egress broker on loopback \u2014 gateway token stays broker-side; agent sends via turn nonce")}catch(se){console.error(`${L.COLORS.red}Error:${L.COLORS.reset} Egress broker failed to start: ${se instanceof Error?se.message:String(se)}`),process.exit(1)}try{yn=await aD({gatewayAgentId:i,packName:n.manifest.metadata.name,workspace:t.workspace,registerTurn:qt,brokerGatewayToken:cr,engine:o,defaultModel:l,runner:Ln,permissions:Xt,turnGate:Pt,rateLimiter:It,turnLimiter:Dn,warnGateReject:vs,prepareSession:pe,sandboxScope:z,onTurnComplete:se=>Z?.schedule(se),logWarrantDenied:W,serviceUserIfPermitted:Mn})}catch(se){console.error(`${L.COLORS.yellow}Warning:${L.COLORS.reset} Gateway bridge failed: ${se instanceof Error?se.message:String(se)}`)}}is=!0})()});let Pp=!1,Np=()=>{Pp||(Pp=!0,is=!1,console.log(`
527
+ Shutting down...`),(async()=>{if(Z)try{await Z.flush()}catch{}if(yn){try{await yn.unregisterAgent(i)}catch{}yn=null}if(ye)try{await ye.close()}catch{}if(ut)try{await ut.close()}catch{}if(co)try{await co.flush()}catch{}Ip.close(()=>{Ln.dispose(),process.exit(0)}),setTimeout(()=>{Ln.dispose(),process.exit(0)},1e4).unref()})())};process.on("SIGINT",Np),process.on("SIGTERM",Np)}async function k_(t){let e=await(0,ge.readBodyWithCap)(t);try{return JSON.parse(e)}catch{throw new Error("Invalid JSON")}}async function oD(t,e,n,r,s,i,o,a,c,l){let f=await t.run({engineId:M_(e.engine,s),modelId:e.model||i,message:e.message,workspaceRoot:o,sessionId:n,sandboxKey:r,analyticsUserId:c,permissions:a,turnEnv:l});return{success:f.success,text:f.text,thinking:f.thinking||void 0,tool_calls:f.toolCalls,error:f.error}}function $_(t,e,n="session",r=!1){if(r&&e){let a=`gateway-${e}`;return{sessionKey:`${a}--${(0,O_.randomUUID)()}`,sandboxKey:a,outboundKey:t.sessionId?.trim()||t.gatewaySessionKey?.trim()||a,durable:!1}}let s=e?`u${(0,ge.userNamespaceHash)(e)}`:void 0,i=t.sessionId?.trim()||t.gatewaySessionKey?.trim();if(i){let a=e?`u${(0,ge.userNamespaceHash)(e)}--${i}`:i;return{sessionKey:a,sandboxKey:n==="user"&&s?s:a,outboundKey:i,durable:!0}}if(e){let a=`gateway-${e}`;return{sessionKey:a,sandboxKey:n==="user"&&s?s:a,outboundKey:a,durable:!0}}let o=`gateway-anon-${(0,O_.randomUUID)()}`;return{sessionKey:o,sandboxKey:o,outboundKey:o,durable:!1}}async function D_(t){let e=async r=>{try{await t.emitter?.text(r),await t.emitter?.done()}catch{}};if(!t.rateLimiter.tryConsume(t.rlKey))return await e(ge.RATE_LIMIT_BUSY_MESSAGE),{success:!1,error:"rate_limited"};let n=await t.turnGate.acquire();if(!n)return t.warnGateReject(`TurnGate: rejecting gateway turn (inflight=${t.turnGate.inflight} queued=${t.turnGate.queued} max=${t.turnGate.max})`),await e(ge.TURN_GATE_BUSY_MESSAGE),{success:!1,error:"busy"};try{return t.trackSession!==!1&&!t.turnLimiter.tryConsume(t.sessionKey)?(await e(ge.TURN_LIMIT_BUSY_MESSAGE),{success:!1,error:"turn_limit"}):await t.run()}finally{n()}}async function aD(t){let{GatewayBridge:e}=await Promise.resolve().then(()=>wn(T_())),r=process.env.OPENCLAW_GATEWAY_URL??"ws://127.0.0.1:18789",s=t.brokerGatewayToken,i=new e({gatewayUrl:r,token:s});return await i.connect(),await i.registerAgent({id:t.gatewayAgentId,agentId:t.packName,name:`${t.packName} (CLI)`,workspace:t.workspace,engineId:t.engine,syncOpenClawConfigAgent:!0,messageHandler:(o,a)=>L_(t,o,a)}),console.log(`${L.COLORS.green}\u2713${L.COLORS.reset} Gateway bridge: registered "${t.gatewayAgentId}" at ${r}`),console.log(`${L.COLORS.dim} Gateway outbound routes: ${t.workspace}/.agent-hippo/sessions/<sessionKey>/gateway-outbound.json${L.COLORS.reset}`),console.log(`${L.COLORS.dim} openclaw agent --agent ${t.gatewayAgentId} --message "\u2026"${L.COLORS.reset}`),i}async function L_(t,e,n){let r=n.engineId?.trim().toLowerCase(),s=r==="custom"?t.engine:r||t.engine,i=(0,ge.peerToUserId)(n.peerInfo),o=i?void 0:await t.serviceUserIfPermitted?.(),a=i??o,{sessionKey:c,sandboxKey:l,outboundKey:f,durable:u}=$_(n,a,t.sandboxScope,!!o);return D_({rateLimiter:t.rateLimiter,turnLimiter:t.turnLimiter,turnGate:t.turnGate,warnGateReject:t.warnGateReject,rlKey:a??"gateway",sessionKey:c,trackSession:u,emitter:n.emitter,run:async()=>{u&&await t.prepareSession(c);let d=a?.trim()?await t.registerTurn({userId:a.trim(),sessionKey:c,egressStoreKey:f}):null;try{let p=await(0,Kc.runWithCredential)({userId:a},()=>t.runner.run({engineId:s,modelId:t.defaultModel,message:e,workspaceRoot:t.workspace,sessionId:c,sandboxKey:l,gatewaySessionKey:f,analyticsUserId:a,emitter:n.emitter,permissions:t.permissions,turnEnv:d?.env}),{onDenied:t.logWarrantDenied(c)});return u&&t.onTurnComplete?.(c),{success:p.success,error:p.error}}finally{await d?.release()}}})}async function cD(t,e,n){let{createAgentIDEGatewayClient:r}=await Promise.resolve().then(()=>wn(Uc())),i=process.env.OPENCLAW_GATEWAY_URL??"ws://127.0.0.1:18789",{client:o,clientInfo:a}=r(i,n);try{await o.connect(a)}catch(c){throw new Error(`Cannot connect to gateway at ${i}: ${c instanceof Error?c.message:String(c)}`)}try{let c,l,f;if(e.trim()==="*"){let d=await(0,Zd.fetchMeetAgentChannelContext)(o.request.bind(o));c=d.rows.map(p=>p.id),f=d.statusPayload}else{let d=(0,Zd.parseChannelBindSpecs)(e);c=d.map(p=>p.channelId),l=Object.fromEntries(d.filter(p=>p.accountId).map(p=>[p.channelId,p.accountId])),Object.keys(l).length===0&&(l=void 0)}if(c.length===0){console.log(`${L.COLORS.yellow}Warning:${L.COLORS.reset} No channels to bind.`);return}let u=await(0,Zd.applyAgentChannelBindingsViaConfigPatch)(o.request.bind(o),{agentId:t,selectedChannelIds:c,channelAccountOverrides:l,statusPayload:f});console.log(u?`${L.COLORS.green}\u2713${L.COLORS.reset} Bound ${t} to: ${c.join(", ")}`:`${L.COLORS.dim}Slack already bound to ${t}; skipped config.patch${L.COLORS.reset}`)}finally{o.close()}}async function lD(t,e,n,r,s,i,o,a,c,l,f){let u=!1,d=(m,h)=>{u||c.writableEnded||c.write(`data: ${JSON.stringify({type:m,...h})}
528
528
 
529
- `)},p=()=>{u||(u=!0,c.end())},g={async thinking(m){d("thinking",{delta:m})},async text(m){d("text",{delta:m})},async toolStart(m,h,E){d("tool_start",{name:m,input:h,tool_call_id:E})},async toolEnd(m,h,E,_){d("tool_end",{name:m,tool_call_id:h,result:E,is_error:_})},async progress(m){d("progress",{message:m})},async question(m){return d("question",{payload:m}),{selected:[],freeText:null,declined:!0}},async error(m){d("error",{message:m})},async done(){d("done",{}),p()}};try{let m=await t.run({engineId:L_(e.engine,s),modelId:e.model||i,message:e.message,workspaceRoot:o,sessionId:n,sandboxKey:r,analyticsUserId:l,emitter:g,permissions:a,turnEnv:f});!m.success&&!u&&d("error",{message:m.error??"refused by policy"}),u||(d("done",{}),p())}catch(m){d("error",{message:m instanceof Error?m.message:"Unknown error"}),p()}}function L_(t,e){let n=t?.trim().toLowerCase();return!n||n==="custom"?e:n}});var F_=S(Wc=>{"use strict";Object.defineProperty(Wc,"__esModule",{value:!0});Wc.createDataPlaneAuditSink=B_;Wc.dataPlaneSidecarCommand=lD;var G_=require("fs"),oD=ai(),U_=Cc(),H_=Br(),x_=yo(),aD=Pi(),cD=zs(),j_=oi(),Vi=Wn();async function B_(t,e){let{dir:n,ephemeral:r}=(0,H_.resolveStateDir)(t),s=(0,H_.resolveAnalyticsSessionsDir)(n,r),i=!0,o;try{await G_.promises.mkdir(s,{recursive:!0}),await G_.promises.access(s)}catch(l){i=!1,o=l instanceof Error?l.message:String(l)}let a=new x_.SessionEventWriter(s);return{audit:(l,f,u)=>{let d=typeof u.userId=="string"?u.userId:void 0,p=(0,aD.hashIdentity)(d),g=p?{...u,userId:p}:u,m=p&&l===d?p:l;a.append(m,(0,cD.generateRequestId)(),f,e?{...g,agent:{...e,digest:null}}:g)},auditDir:s,ephemeral:r,ok:i,error:o}}async function lD(t){let e=process.env.AGENTHIPPO_DATA_PLANE_TOKEN?.trim();e||(console.error("Error: AGENTHIPPO_DATA_PLANE_TOKEN is required (shared secret the trusted EDGE \u2014 or, legacy, the agent's serve \u2014 presents to register turns)."),process.exit(1));let n;try{n=await(0,oD.loadAgentPack)(t.agent,t.workspace)}catch(d){console.error(`Error: ${d instanceof Error?d.message:d}`),process.exit(1);return}let r=(0,U_.resolveDataPlaneConfig)(n.manifest.spec,n.packPath);if(!r){console.error("Error: pack declares no spec.dataPlane \u2014 nothing for the sidecar to run."),process.exit(1);return}let s=t.verbose?new j_.ConsoleLogger("[Sidecar]"):new j_.NoOpLogger,{audit:i,auditDir:o,ephemeral:a,ok:c,error:l}=await B_(t.stateDir,{pack:n.manifest.metadata.name,version:n.manifest.metadata.version??"0.0.0"});if(!c){let d=`${o}: ${l}`;if((0,x_.evidenceRequired)()){console.error(`${Vi.COLORS.red}Error: data-plane audit directory is not writable${Vi.COLORS.reset} \u2014 ${d}`),console.error("AGENTHIPPO_EVIDENCE_REQUIRED is set, so refusing to run an unauditable data plane. Unset it to downgrade this to a warning."),process.exit(1);return}console.warn(`${Vi.COLORS.yellow}Warning:${Vi.COLORS.reset} data-plane audit directory is not writable \u2014 ${d}`),console.warn(" Tool authorizations and denials will NOT be recorded. Set --state-dir or AGENTHIPPO_HOME to a writable path.")}let f;try{f=await(0,U_.startDataPlaneSidecar)({config:r,registerToken:e,gatewayPort:t.gatewayPort,controlPort:t.controlPort,bindHost:t.host??"0.0.0.0",logger:s,audit:i,agent:{pack:n.manifest.metadata.name,version:n.manifest.metadata.version??"0.0.0"}})}catch(d){console.error(`${Vi.COLORS.red}Error: failed to start the data-plane sidecar:${Vi.COLORS.reset} ${d instanceof Error?d.message:d}`),process.exit(1);return}console.log(`OK: Data-plane sidecar (provider=${r.provider??"passthrough"}) \u2014 connector: ${r.connectorPath}`),console.log(` gateway (engine dials, nonce-auth): ${f.gatewayUrl}`),console.log(` control (edge/serve registers, bearer): :${f.controlPort}`),console.log(` audit (tool_authorize / tool_deny / register events): ${o}${a?" (EPHEMERAL \u2014 lost on restart; set AGENTHIPPO_HOME or --state-dir)":""}`),console.log(" Base credentials live here only \u2014 never in the agent container."),console.log(" Edge mode (P1): give the register token to the IdP edge only; serve runs with AGENTHIPPO_DATA_PLANE_EDGE=1 and no token.");let u=()=>{f.close().finally(()=>process.exit(0))};process.on("SIGINT",u),process.on("SIGTERM",u),await new Promise(()=>{})}});var ef=S(Zn=>{"use strict";var uD=Zn&&Zn.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,s)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),dD=Zn&&Zn.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),fD=Zn&&Zn.__importStar||(function(){var t=function(e){return t=Object.getOwnPropertyNames||function(n){var r=[];for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(r[r.length]=s);return r},t(e)};return function(e){if(e&&e.__esModule)return e;var n={};if(e!=null)for(var r=t(e),s=0;s<r.length;s++)r[s]!=="default"&&uD(n,e,r[s]);return dD(n,e),n}})();Object.defineProperty(Zn,"__esModule",{value:!0});Zn.signJwt=pD;Zn.verifyJwt=gD;Zn.extractBearerToken=hD;Zn.looksLikeJwt=mD;var W_=fD(require("crypto"));function V_(t){return(typeof t=="string"?Buffer.from(t,"utf8"):t).toString("base64url")}function pD(t,e,n){let r={alg:"HS256",typ:"JWT"},s=Math.floor(Date.now()/1e3),i={...t,iat:s,exp:s+n},o=V_(JSON.stringify(r)),a=V_(JSON.stringify(i)),c=W_.createHmac("sha256",e).update(`${o}.${a}`).digest("base64url");return`${o}.${a}.${c}`}function gD(t,e){let n=t.split(".");if(n.length!==3)return;let[r,s,i]=n,o=W_.createHmac("sha256",e).update(`${r}.${s}`).digest("base64url");if(i.length!==o.length)return;let a=0;for(let c=0;c<i.length;c++)a|=i.charCodeAt(c)^o.charCodeAt(c);if(a===0)try{let c=JSON.parse(Buffer.from(s,"base64url").toString("utf8")),l=Math.floor(Date.now()/1e3);return typeof c.exp=="number"&&c.exp<l?void 0:c}catch{return}}function hD(t){return t?.trim()&&/^Bearer\s+(.+)$/i.exec(t.trim())?.[1]?.trim()||void 0}function mD(t){return t.split(".").length===3}});var K_=S(Wr=>{"use strict";var ED=Wr&&Wr.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,s)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),_D=Wr&&Wr.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),rf=Wr&&Wr.__importStar||(function(){var t=function(e){return t=Object.getOwnPropertyNames||function(n){var r=[];for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(r[r.length]=s);return r},t(e)};return function(e){if(e&&e.__esModule)return e;var n={};if(e!=null)for(var r=t(e),s=0;s<r.length;s++)r[s]!=="default"&&ED(n,e,r[s]);return _D(n,e),n}})();Object.defineProperty(Wr,"__esModule",{value:!0});Wr.AuthBrokerStore=void 0;var tf=rf(require("crypto")),Wi=rf(require("fs")),yD=rf(require("path")),wD=Do(),AD=ef(),nf=class{config;users=new Map;codes=new Map;refreshTokens=new Map;persistPath;constructor(e,n){this.config=e,this.persistPath=n,n&&this.loadFromDisk(n)}loadFromDisk(e){try{if(!Wi.existsSync(e))return;let n=Wi.readFileSync(e,"utf8"),r=JSON.parse(n);for(let i of r.users??[])this.users.set(i.id,i);let s=Date.now();for(let i of r.refreshTokens??[])i.revoked||i.expiresAt<s||this.refreshTokens.set(i.token,i)}catch{}}persist(){if(!this.persistPath)return;let e=yD.dirname(this.persistPath);Wi.mkdirSync(e,{recursive:!0});let n=Date.now(),r=[...this.refreshTokens.values()].filter(o=>!o.revoked&&o.expiresAt>n),s={users:[...this.users.values()],refreshTokens:r},i=`${this.persistPath}.tmp.${process.pid}`;try{Wi.writeFileSync(i,JSON.stringify(s,null,2),"utf8"),Wi.renameSync(i,this.persistPath)}catch(o){try{Wi.unlinkSync(i)}catch{}throw o}}pruneRefreshTokens(){let e=Date.now();for(let[n,r]of this.refreshTokens)(r.revoked||r.expiresAt<e)&&this.refreshTokens.delete(n)}pruneAuthCodes(){let e=Date.now();for(let[n,r]of this.codes)r.expiresAt<e&&this.codes.delete(n)}upsertUser(e,n){let r=e.trim().toLowerCase();if(!(0,wD.emailDomainAllowed)(r,this.config.allowedEmailDomains)){let i=new Error(`Email domain not allowed for sign-in: ${r}`);throw i.status=403,i}for(let i of this.users.values())if(i.email===r)return i;let s={id:`usr_${tf.randomBytes(8).toString("hex")}`,email:r,displayName:n?.trim()||r.split("@")[0]||r,...this.config.teamConfigured?{teamId:this.config.team.id}:{}};return this.users.set(s.id,s),this.persist(),s}getUser(e){return this.users.get(e)}createAuthCode(e){this.pruneAuthCodes();let n=tf.randomBytes(24).toString("base64url");return this.codes.set(n,{code:n,userId:e.userId,clientId:e.clientId,redirectUri:e.redirectUri,codeChallenge:e.codeChallenge,expiresAt:Date.now()+600*1e3}),n}consumeAuthCode(e){let n=this.codes.get(e);if(n&&(this.codes.delete(e),!(n.expiresAt<Date.now())))return n}createRefreshToken(e,n){let r=tf.randomBytes(32).toString("base64url");return this.refreshTokens.set(r,{token:r,userId:e,clientId:n,expiresAt:Date.now()+this.config.refreshTokenTtlSec*1e3,revoked:!1}),this.persist(),r}consumeRefreshToken(e){let n=this.refreshTokens.get(e);if(!(!n||n.revoked||n.expiresAt<Date.now()))return n.revoked=!0,this.persist(),n}revokeRefreshTokensForUser(e){let n=!1;for(let r of this.refreshTokens.values())r.userId===e&&!r.revoked&&(r.revoked=!0,n=!0);n&&this.persist()}issueTokens(e,n,r){this.pruneRefreshTokens(),this.pruneAuthCodes();let s=(0,AD.signJwt)({sub:e.id,email:e.email,name:e.displayName,...e.teamId?{team_id:e.teamId}:{},scope:r},this.config.jwtSecret,this.config.accessTokenTtlSec),i=this.createRefreshToken(e.id,n);return{accessToken:s,refreshToken:i,expiresIn:this.config.accessTokenTtlSec}}buildBootstrap(e){let n=this.config.teamConfigured;return{version:1,user:{id:e.id,email:e.email,displayName:e.displayName},...n?{team:{id:this.config.team.id,name:this.config.team.name,role:"member"}}:{},store:{repo:this.config.team.storeRepo,indexUrl:this.config.team.storeIndexUrl,githubOrg:this.config.team.githubOrg},routing:{inferenceGatewayUrl:this.config.team.gatewayUrl},policy:{teamManagedSettings:n?["store","routing"]:[]}}}buildMe(e){return{user:{id:e.id,email:e.email,displayName:e.displayName},...this.config.teamConfigured?{team:{id:this.config.team.id,name:this.config.team.name,role:"member"}}:{}}}};Wr.AuthBrokerStore=nf});var X_=S(Or=>{"use strict";var SD=Or&&Or.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,s)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),TD=Or&&Or.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),bD=Or&&Or.__importStar||(function(){var t=function(e){return t=Object.getOwnPropertyNames||function(n){var r=[];for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(r[r.length]=s);return r},t(e)};return function(e){if(e&&e.__esModule)return e;var n={};if(e!=null)for(var r=t(e),s=0;s<r.length;s++)r[s]!=="default"&&SD(n,e,r[s]);return TD(n,e),n}})();Object.defineProperty(Or,"__esModule",{value:!0});Or.generateCodeVerifier=vD;Or.codeChallengeFromVerifier=Y_;Or.verifyPkceChallenge=OD;var sf=bD(require("crypto")),q_="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~";function vD(t=64){let e=sf.randomBytes(t),n="";for(let r=0;r<t;r++)n+=q_[e[r]%q_.length];return n}function Y_(t){return sf.createHash("sha256").update(t).digest("base64url")}function OD(t,e){let n=Buffer.from(Y_(t)),r=Buffer.from(e);return n.length===r.length&&sf.timingSafeEqual(n,r)}});var of=S(er=>{"use strict";Object.defineProperty(er,"__esModule",{value:!0});er.AUTH_CALLBACK_PATH=er.AUTH_EXTENSION_AUTHORITY=er.AUTH_SCOPES=er.AUTH_CLIENT_ID=er.AUTH_PROVIDER_ID=void 0;er.AUTH_PROVIDER_ID="agenthippo";er.AUTH_CLIENT_ID="agenthippo-ide";er.AUTH_SCOPES=["openid","profile","email","agenthippo:ide"];er.AUTH_EXTENSION_AUTHORITY="agenthippo.agenthippo";er.AUTH_CALLBACK_PATH="/auth/callback"});var z_=S(Ki=>{"use strict";Object.defineProperty(Ki,"__esModule",{value:!0});Ki.parseAuthCallback=J_;Ki.parseAuthCallbackFromText=ID;Ki.isAuthCallbackParts=PD;Ki.parseAuthCallbackFromLoopbackUrl=ND;var Kc=of();function J_(t,e){if(t.authority!==Kc.AUTH_EXTENSION_AUTHORITY||t.path!==Kc.AUTH_CALLBACK_PATH)return;let n=new URLSearchParams(t.query),r=n.get("code"),s=n.get("state");if(!(!r||s!==e))return r}function ID(t,e){let n=t.trim();if(n)try{let r=new URL(n);return J_({authority:r.host,path:r.pathname,query:r.search.replace(/^\?/,"")},e)}catch{return}}function PD(t,e){return t===Kc.AUTH_EXTENSION_AUTHORITY&&e===Kc.AUTH_CALLBACK_PATH}function ND(t,e){try{let n=new URL(t.trim());if(n.hostname!=="127.0.0.1"&&n.hostname!=="localhost"||n.pathname!=="/callback")return;let r=n.searchParams.get("code"),s=n.searchParams.get("state");return!r||s!==e?void 0:r}catch{return}}});var ty=S(Rn=>{"use strict";var RD=Rn&&Rn.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,s)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),CD=Rn&&Rn.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),uf=Rn&&Rn.__importStar||(function(){var t=function(e){return t=Object.getOwnPropertyNames||function(n){var r=[];for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(r[r.length]=s);return r},t(e)};return function(e){if(e&&e.__esModule)return e;var n={};if(e!=null)for(var r=t(e),s=0;s<r.length;s++)r[s]!=="default"&&RD(n,e,r[s]);return CD(n,e),n}})();Object.defineProperty(Rn,"__esModule",{value:!0});Rn.hasTrustedProxyProof=void 0;Rn.isAllowedRedirectUri=Z_;Rn.createAuthBrokerServer=ey;Rn.startAuthBrokerServer=BD;var kD=uf(require("http")),$D=uf(require("crypto")),Wo=require("url"),DD=uf(require("path")),Vo=Do(),LD=K_(),MD=X_(),qc=ef(),Yc=of(),GD=z_(),af=Br();function Z_(t){let e;try{e=new Wo.URL(t)}catch{return!1}return e.username||e.password||e.search||e.hash?!1:e.protocol==="http:"?e.hostname!=="127.0.0.1"&&e.hostname!=="localhost"||e.pathname!=="/callback"?!1:e.port!==""&&Number(e.port)>1024:e.protocol==="https:"?!1:(0,GD.isAuthCallbackParts)(e.host,e.pathname)}var UD=Br();Object.defineProperty(Rn,"hasTrustedProxyProof",{enumerable:!0,get:function(){return UD.hasTrustedProxyProof}});function Te(t,e,n){t.writeHead(e,{"Content-Type":"application/json"}),t.end(JSON.stringify(n))}function HD(t){let e=t.indexOf("@");return e<=0?t:`${t[0]}***@${t.slice(e+1)}`}var jD=64*1024;async function cf(t){let e=[],n=0;for await(let r of t){let s=typeof r=="string"?Buffer.from(r):r;if(n+=s.length,n>jD){let i=new Error("Request body too large");throw i.status=413,i}e.push(s)}return Buffer.concat(e).toString("utf8")}function lf(t){let e=new URLSearchParams(t),n={};for(let[r,s]of e.entries())n[r]=s;return n}function Q_(t,e){if(t?.trim())for(let n of t.split(";")){let r=n.indexOf("=");if(r<=0)continue;if(n.slice(0,r).trim()===e){let i=n.slice(r+1).trim();if(i)return i}}}function xD(t,e,n){try{let r=new Wo.URL(t);if(r.protocol!=="http:"&&r.protocol!=="https:")return n;if(e){let s=e.replace(/^\./,"").toLowerCase();if(r.hostname.toLowerCase()===s||r.hostname.toLowerCase().endsWith("."+s))return r.toString()}else if(r.hostname==="127.0.0.1"||r.hostname==="localhost")return r.toString()}catch{}return n}function ey(t){let e=t??(0,Vo.loadAuthBrokerConfig)();if(!e.devMode&&e.jwtSecret===Vo.DEFAULT_JWT_SECRET)throw new Error("AGENTHIPPO_AUTH_JWT_SECRET must be set to a strong secret in production. Generate one with: openssl rand -hex 32");if(!e.devMode&&!e.proxySecret&&!e.trustProxyHeadersUnverified)throw new Error(`AGENTHIPPO_AUTH_PROXY_SECRET must be set in production. The broker trusts X-Auth-Request-Email from the oauth2-proxy/Caddy forward_auth sidecar; without a shared secret proving the header came from that sidecar, any caller that reaches this port can mint a token for an arbitrary email.
529
+ `)},p=()=>{u||(u=!0,c.end())},g={async thinking(m){d("thinking",{delta:m})},async text(m){d("text",{delta:m})},async toolStart(m,h,E){d("tool_start",{name:m,input:h,tool_call_id:E})},async toolEnd(m,h,E,_){d("tool_end",{name:m,tool_call_id:h,result:E,is_error:_})},async progress(m){d("progress",{message:m})},async question(m){return d("question",{payload:m}),{selected:[],freeText:null,declined:!0}},async error(m){d("error",{message:m})},async done(){d("done",{}),p()}};try{let m=await t.run({engineId:M_(e.engine,s),modelId:e.model||i,message:e.message,workspaceRoot:o,sessionId:n,sandboxKey:r,analyticsUserId:l,emitter:g,permissions:a,turnEnv:f});!m.success&&!u&&d("error",{message:m.error??"refused by policy"}),u||(d("done",{}),p())}catch(m){d("error",{message:m instanceof Error?m.message:"Unknown error"}),p()}}function M_(t,e){let n=t?.trim().toLowerCase();return!n||n==="custom"?e:n}});var V_=S(qc=>{"use strict";Object.defineProperty(qc,"__esModule",{value:!0});qc.createDataPlaneAuditSink=F_;qc.dataPlaneSidecarCommand=pD;var U_=require("fs"),uD=ai(),H_=$c(),j_=Br(),B_=Ao(),dD=Pi(),fD=zs(),x_=oi(),Vi=Wn();async function F_(t,e){let{dir:n,ephemeral:r}=(0,j_.resolveStateDir)(t),s=(0,j_.resolveAnalyticsSessionsDir)(n,r),i=!0,o;try{await U_.promises.mkdir(s,{recursive:!0}),await U_.promises.access(s)}catch(l){i=!1,o=l instanceof Error?l.message:String(l)}let a=new B_.SessionEventWriter(s);return{audit:(l,f,u)=>{let d=typeof u.userId=="string"?u.userId:void 0,p=(0,dD.hashIdentity)(d),g=p?{...u,userId:p}:u,m=p&&l===d?p:l;a.append(m,(0,fD.generateRequestId)(),f,e?{...g,agent:{...e,digest:null}}:g)},auditDir:s,ephemeral:r,ok:i,error:o}}async function pD(t){let e=process.env.AGENTHIPPO_DATA_PLANE_TOKEN?.trim();e||(console.error("Error: AGENTHIPPO_DATA_PLANE_TOKEN is required (shared secret the trusted EDGE \u2014 or, legacy, the agent's serve \u2014 presents to register turns)."),process.exit(1));let n;try{n=await(0,uD.loadAgentPack)(t.agent,t.workspace)}catch(d){console.error(`Error: ${d instanceof Error?d.message:d}`),process.exit(1);return}let r=(0,H_.resolveDataPlaneConfig)(n.manifest.spec,n.packPath);if(!r){console.error("Error: pack declares no spec.dataPlane \u2014 nothing for the sidecar to run."),process.exit(1);return}let s=t.verbose?new x_.ConsoleLogger("[Sidecar]"):new x_.NoOpLogger,{audit:i,auditDir:o,ephemeral:a,ok:c,error:l}=await F_(t.stateDir,{pack:n.manifest.metadata.name,version:n.manifest.metadata.version??"0.0.0"});if(!c){let d=`${o}: ${l}`;if((0,B_.evidenceRequired)()){console.error(`${Vi.COLORS.red}Error: data-plane audit directory is not writable${Vi.COLORS.reset} \u2014 ${d}`),console.error("AGENTHIPPO_EVIDENCE_REQUIRED is set, so refusing to run an unauditable data plane. Unset it to downgrade this to a warning."),process.exit(1);return}console.warn(`${Vi.COLORS.yellow}Warning:${Vi.COLORS.reset} data-plane audit directory is not writable \u2014 ${d}`),console.warn(" Tool authorizations and denials will NOT be recorded. Set --state-dir or AGENTHIPPO_HOME to a writable path.")}let f;try{f=await(0,H_.startDataPlaneSidecar)({config:r,registerToken:e,gatewayPort:t.gatewayPort,controlPort:t.controlPort,bindHost:t.host??"0.0.0.0",logger:s,audit:i,agent:{pack:n.manifest.metadata.name,version:n.manifest.metadata.version??"0.0.0"}})}catch(d){console.error(`${Vi.COLORS.red}Error: failed to start the data-plane sidecar:${Vi.COLORS.reset} ${d instanceof Error?d.message:d}`),process.exit(1);return}console.log(`OK: Data-plane sidecar (provider=${r.provider??"passthrough"}) \u2014 connector: ${r.connectorPath}`),console.log(` gateway (engine dials, nonce-auth): ${f.gatewayUrl}`),console.log(` control (edge/serve registers, bearer): :${f.controlPort}`),console.log(` audit (tool_authorize / tool_deny / register events): ${o}${a?" (EPHEMERAL \u2014 lost on restart; set AGENTHIPPO_HOME or --state-dir)":""}`),console.log(" Base credentials live here only \u2014 never in the agent container."),console.log(" Edge mode (P1): give the register token to the IdP edge only; serve runs with AGENTHIPPO_DATA_PLANE_EDGE=1 and no token.");let u=()=>{f.close().finally(()=>process.exit(0))};process.on("SIGINT",u),process.on("SIGTERM",u),await new Promise(()=>{})}});var ef=S(Zn=>{"use strict";var gD=Zn&&Zn.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,s)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),hD=Zn&&Zn.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),mD=Zn&&Zn.__importStar||(function(){var t=function(e){return t=Object.getOwnPropertyNames||function(n){var r=[];for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(r[r.length]=s);return r},t(e)};return function(e){if(e&&e.__esModule)return e;var n={};if(e!=null)for(var r=t(e),s=0;s<r.length;s++)r[s]!=="default"&&gD(n,e,r[s]);return hD(n,e),n}})();Object.defineProperty(Zn,"__esModule",{value:!0});Zn.signJwt=ED;Zn.verifyJwt=_D;Zn.extractBearerToken=yD;Zn.looksLikeJwt=wD;var K_=mD(require("crypto"));function W_(t){return(typeof t=="string"?Buffer.from(t,"utf8"):t).toString("base64url")}function ED(t,e,n){let r={alg:"HS256",typ:"JWT"},s=Math.floor(Date.now()/1e3),i={...t,iat:s,exp:s+n},o=W_(JSON.stringify(r)),a=W_(JSON.stringify(i)),c=K_.createHmac("sha256",e).update(`${o}.${a}`).digest("base64url");return`${o}.${a}.${c}`}function _D(t,e){let n=t.split(".");if(n.length!==3)return;let[r,s,i]=n,o=K_.createHmac("sha256",e).update(`${r}.${s}`).digest("base64url");if(i.length!==o.length)return;let a=0;for(let c=0;c<i.length;c++)a|=i.charCodeAt(c)^o.charCodeAt(c);if(a===0)try{let c=JSON.parse(Buffer.from(s,"base64url").toString("utf8")),l=Math.floor(Date.now()/1e3);return typeof c.exp=="number"&&c.exp<l?void 0:c}catch{return}}function yD(t){return t?.trim()&&/^Bearer\s+(.+)$/i.exec(t.trim())?.[1]?.trim()||void 0}function wD(t){return t.split(".").length===3}});var q_=S(Wr=>{"use strict";var AD=Wr&&Wr.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,s)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),SD=Wr&&Wr.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),rf=Wr&&Wr.__importStar||(function(){var t=function(e){return t=Object.getOwnPropertyNames||function(n){var r=[];for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(r[r.length]=s);return r},t(e)};return function(e){if(e&&e.__esModule)return e;var n={};if(e!=null)for(var r=t(e),s=0;s<r.length;s++)r[s]!=="default"&&AD(n,e,r[s]);return SD(n,e),n}})();Object.defineProperty(Wr,"__esModule",{value:!0});Wr.AuthBrokerStore=void 0;var tf=rf(require("crypto")),Wi=rf(require("fs")),TD=rf(require("path")),bD=Mo(),vD=ef(),nf=class{config;users=new Map;codes=new Map;refreshTokens=new Map;persistPath;constructor(e,n){this.config=e,this.persistPath=n,n&&this.loadFromDisk(n)}loadFromDisk(e){try{if(!Wi.existsSync(e))return;let n=Wi.readFileSync(e,"utf8"),r=JSON.parse(n);for(let i of r.users??[])this.users.set(i.id,i);let s=Date.now();for(let i of r.refreshTokens??[])i.revoked||i.expiresAt<s||this.refreshTokens.set(i.token,i)}catch{}}persist(){if(!this.persistPath)return;let e=TD.dirname(this.persistPath);Wi.mkdirSync(e,{recursive:!0});let n=Date.now(),r=[...this.refreshTokens.values()].filter(o=>!o.revoked&&o.expiresAt>n),s={users:[...this.users.values()],refreshTokens:r},i=`${this.persistPath}.tmp.${process.pid}`;try{Wi.writeFileSync(i,JSON.stringify(s,null,2),"utf8"),Wi.renameSync(i,this.persistPath)}catch(o){try{Wi.unlinkSync(i)}catch{}throw o}}pruneRefreshTokens(){let e=Date.now();for(let[n,r]of this.refreshTokens)(r.revoked||r.expiresAt<e)&&this.refreshTokens.delete(n)}pruneAuthCodes(){let e=Date.now();for(let[n,r]of this.codes)r.expiresAt<e&&this.codes.delete(n)}upsertUser(e,n){let r=e.trim().toLowerCase();if(!(0,bD.emailDomainAllowed)(r,this.config.allowedEmailDomains)){let i=new Error(`Email domain not allowed for sign-in: ${r}`);throw i.status=403,i}for(let i of this.users.values())if(i.email===r)return i;let s={id:`usr_${tf.randomBytes(8).toString("hex")}`,email:r,displayName:n?.trim()||r.split("@")[0]||r,...this.config.teamConfigured?{teamId:this.config.team.id}:{}};return this.users.set(s.id,s),this.persist(),s}getUser(e){return this.users.get(e)}createAuthCode(e){this.pruneAuthCodes();let n=tf.randomBytes(24).toString("base64url");return this.codes.set(n,{code:n,userId:e.userId,clientId:e.clientId,redirectUri:e.redirectUri,codeChallenge:e.codeChallenge,expiresAt:Date.now()+600*1e3}),n}consumeAuthCode(e){let n=this.codes.get(e);if(n&&(this.codes.delete(e),!(n.expiresAt<Date.now())))return n}createRefreshToken(e,n){let r=tf.randomBytes(32).toString("base64url");return this.refreshTokens.set(r,{token:r,userId:e,clientId:n,expiresAt:Date.now()+this.config.refreshTokenTtlSec*1e3,revoked:!1}),this.persist(),r}consumeRefreshToken(e){let n=this.refreshTokens.get(e);if(!(!n||n.revoked||n.expiresAt<Date.now()))return n.revoked=!0,this.persist(),n}revokeRefreshTokensForUser(e){let n=!1;for(let r of this.refreshTokens.values())r.userId===e&&!r.revoked&&(r.revoked=!0,n=!0);n&&this.persist()}issueTokens(e,n,r){this.pruneRefreshTokens(),this.pruneAuthCodes();let s=(0,vD.signJwt)({sub:e.id,email:e.email,name:e.displayName,...e.teamId?{team_id:e.teamId}:{},scope:r},this.config.jwtSecret,this.config.accessTokenTtlSec),i=this.createRefreshToken(e.id,n);return{accessToken:s,refreshToken:i,expiresIn:this.config.accessTokenTtlSec}}buildBootstrap(e){let n=this.config.teamConfigured;return{version:1,user:{id:e.id,email:e.email,displayName:e.displayName},...n?{team:{id:this.config.team.id,name:this.config.team.name,role:"member"}}:{},store:{repo:this.config.team.storeRepo,indexUrl:this.config.team.storeIndexUrl,githubOrg:this.config.team.githubOrg},routing:{inferenceGatewayUrl:this.config.team.gatewayUrl},policy:{teamManagedSettings:n?["store","routing"]:[]}}}buildMe(e){return{user:{id:e.id,email:e.email,displayName:e.displayName},...this.config.teamConfigured?{team:{id:this.config.team.id,name:this.config.team.name,role:"member"}}:{}}}};Wr.AuthBrokerStore=nf});var J_=S(Or=>{"use strict";var OD=Or&&Or.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,s)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),ID=Or&&Or.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),PD=Or&&Or.__importStar||(function(){var t=function(e){return t=Object.getOwnPropertyNames||function(n){var r=[];for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(r[r.length]=s);return r},t(e)};return function(e){if(e&&e.__esModule)return e;var n={};if(e!=null)for(var r=t(e),s=0;s<r.length;s++)r[s]!=="default"&&OD(n,e,r[s]);return ID(n,e),n}})();Object.defineProperty(Or,"__esModule",{value:!0});Or.generateCodeVerifier=ND;Or.codeChallengeFromVerifier=X_;Or.verifyPkceChallenge=RD;var sf=PD(require("crypto")),Y_="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~";function ND(t=64){let e=sf.randomBytes(t),n="";for(let r=0;r<t;r++)n+=Y_[e[r]%Y_.length];return n}function X_(t){return sf.createHash("sha256").update(t).digest("base64url")}function RD(t,e){let n=Buffer.from(X_(t)),r=Buffer.from(e);return n.length===r.length&&sf.timingSafeEqual(n,r)}});var of=S(er=>{"use strict";Object.defineProperty(er,"__esModule",{value:!0});er.AUTH_CALLBACK_PATH=er.AUTH_EXTENSION_AUTHORITY=er.AUTH_SCOPES=er.AUTH_CLIENT_ID=er.AUTH_PROVIDER_ID=void 0;er.AUTH_PROVIDER_ID="agenthippo";er.AUTH_CLIENT_ID="agenthippo-ide";er.AUTH_SCOPES=["openid","profile","email","agenthippo:ide"];er.AUTH_EXTENSION_AUTHORITY="agenthippo.agenthippo";er.AUTH_CALLBACK_PATH="/auth/callback"});var Q_=S(Ki=>{"use strict";Object.defineProperty(Ki,"__esModule",{value:!0});Ki.parseAuthCallback=z_;Ki.parseAuthCallbackFromText=CD;Ki.isAuthCallbackParts=kD;Ki.parseAuthCallbackFromLoopbackUrl=$D;var Yc=of();function z_(t,e){if(t.authority!==Yc.AUTH_EXTENSION_AUTHORITY||t.path!==Yc.AUTH_CALLBACK_PATH)return;let n=new URLSearchParams(t.query),r=n.get("code"),s=n.get("state");if(!(!r||s!==e))return r}function CD(t,e){let n=t.trim();if(n)try{let r=new URL(n);return z_({authority:r.host,path:r.pathname,query:r.search.replace(/^\?/,"")},e)}catch{return}}function kD(t,e){return t===Yc.AUTH_EXTENSION_AUTHORITY&&e===Yc.AUTH_CALLBACK_PATH}function $D(t,e){try{let n=new URL(t.trim());if(n.hostname!=="127.0.0.1"&&n.hostname!=="localhost"||n.pathname!=="/callback")return;let r=n.searchParams.get("code"),s=n.searchParams.get("state");return!r||s!==e?void 0:r}catch{return}}});var ny=S(Rn=>{"use strict";var DD=Rn&&Rn.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,s)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),LD=Rn&&Rn.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),uf=Rn&&Rn.__importStar||(function(){var t=function(e){return t=Object.getOwnPropertyNames||function(n){var r=[];for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(r[r.length]=s);return r},t(e)};return function(e){if(e&&e.__esModule)return e;var n={};if(e!=null)for(var r=t(e),s=0;s<r.length;s++)r[s]!=="default"&&DD(n,e,r[s]);return LD(n,e),n}})();Object.defineProperty(Rn,"__esModule",{value:!0});Rn.hasTrustedProxyProof=void 0;Rn.isAllowedRedirectUri=ey;Rn.createAuthBrokerServer=ty;Rn.startAuthBrokerServer=KD;var MD=uf(require("http")),GD=uf(require("crypto")),qo=require("url"),UD=uf(require("path")),Ko=Mo(),HD=q_(),jD=J_(),Xc=ef(),Jc=of(),xD=Q_(),af=Br();function ey(t){let e;try{e=new qo.URL(t)}catch{return!1}return e.username||e.password||e.search||e.hash?!1:e.protocol==="http:"?e.hostname!=="127.0.0.1"&&e.hostname!=="localhost"||e.pathname!=="/callback"?!1:e.port!==""&&Number(e.port)>1024:e.protocol==="https:"?!1:(0,xD.isAuthCallbackParts)(e.host,e.pathname)}var BD=Br();Object.defineProperty(Rn,"hasTrustedProxyProof",{enumerable:!0,get:function(){return BD.hasTrustedProxyProof}});function Te(t,e,n){t.writeHead(e,{"Content-Type":"application/json"}),t.end(JSON.stringify(n))}function FD(t){let e=t.indexOf("@");return e<=0?t:`${t[0]}***@${t.slice(e+1)}`}var VD=64*1024;async function cf(t){let e=[],n=0;for await(let r of t){let s=typeof r=="string"?Buffer.from(r):r;if(n+=s.length,n>VD){let i=new Error("Request body too large");throw i.status=413,i}e.push(s)}return Buffer.concat(e).toString("utf8")}function lf(t){let e=new URLSearchParams(t),n={};for(let[r,s]of e.entries())n[r]=s;return n}function Z_(t,e){if(t?.trim())for(let n of t.split(";")){let r=n.indexOf("=");if(r<=0)continue;if(n.slice(0,r).trim()===e){let i=n.slice(r+1).trim();if(i)return i}}}function WD(t,e,n){try{let r=new qo.URL(t);if(r.protocol!=="http:"&&r.protocol!=="https:")return n;if(e){let s=e.replace(/^\./,"").toLowerCase();if(r.hostname.toLowerCase()===s||r.hostname.toLowerCase().endsWith("."+s))return r.toString()}else if(r.hostname==="127.0.0.1"||r.hostname==="localhost")return r.toString()}catch{}return n}function ty(t){let e=t??(0,Ko.loadAuthBrokerConfig)();if(!e.devMode&&e.jwtSecret===Ko.DEFAULT_JWT_SECRET)throw new Error("AGENTHIPPO_AUTH_JWT_SECRET must be set to a strong secret in production. Generate one with: openssl rand -hex 32");if(!e.devMode&&!e.proxySecret&&!e.trustProxyHeadersUnverified)throw new Error(`AGENTHIPPO_AUTH_PROXY_SECRET must be set in production. The broker trusts X-Auth-Request-Email from the oauth2-proxy/Caddy forward_auth sidecar; without a shared secret proving the header came from that sidecar, any caller that reaches this port can mint a token for an arbitrary email.
530
530
  1. Generate one: openssl rand -hex 32
531
531
  2. Set it here: AGENTHIPPO_AUTH_PROXY_SECRET=<secret>
532
532
  3. Have the proxy send it, e.g. in the Caddyfile:
533
- header_up ${Vo.AUTH_PROXY_SECRET_HEADER} {env.AGENTHIPPO_AUTH_PROXY_SECRET}
534
- If the broker is genuinely unreachable except through the proxy and you accept the risk, set AGENTHIPPO_AUTH_TRUST_PROXY_UNVERIFIED=1.`);!e.devMode&&!e.proxySecret&&e.trustProxyHeadersUnverified&&console.warn("[auth-broker] WARNING: AGENTHIPPO_AUTH_TRUST_PROXY_UNVERIFIED=1 \u2014 X-Auth-Request-Email is accepted without proof. Anything that can reach this port can mint a token for any email. Set AGENTHIPPO_AUTH_PROXY_SECRET to close this."),!e.devMode&&e.allowedEmailDomains.length===0&&console.warn('[auth-broker] Warning: AGENTHIPPO_AUTH_ALLOWED_DOMAINS is not set \u2014 any upstream-SSO-authenticated email can receive a token. Set it to restrict sign-in (e.g. "example.com").');let n=e.dataDir?DD.join(e.dataDir,"auth-store.json"):void 0,r=new LD.AuthBrokerStore(e,n),s=new af.RateLimiter(e.rateLimitPerMin),i=(m,h={})=>{let E=Object.entries(h).filter(([,_])=>_!==void 0&&_!=="").map(([_,y])=>{let b=!e.logPii&&typeof y=="string"&&y.includes("@")?HD(y):y;return`${_}=${b}`}).join(" ");console.log(`[auth-broker] ${m}${E?" "+E:""}`)},o=1e4,a=2048,c=new Map,l=5e3,f=0;function u(m){let h=(0,qc.extractBearerToken)(m.headers.authorization)||Q_(m.headers.cookie,e.cookieName);if(!h)return;let E=$D.createHash("sha256").update(h).digest("hex"),_=c.get(E);if(_){if(_.exp>Date.now())return _.user;c.delete(E)}let y=(0,qc.verifyJwt)(h,e.jwtSecret);if(!y?.sub||!y.email)return;let b=r.getUser(String(y.sub));if(!b){let T=typeof y.team_id=="string"&&y.team_id?y.team_id:void 0;b={id:String(y.sub),email:String(y.email),displayName:typeof y.name=="string"&&y.name?y.name:String(y.email),teamId:T??(e.teamConfigured?e.team.id:void 0)}}if(y.exp){let T=Math.min(y.exp*1e3,Date.now()+o);if(c.size>=a){let O=Date.now();for(let[A,v]of c)v.exp<O&&c.delete(A);c.size>=a&&c.clear()}c.set(E,{user:b,exp:T})}return b}let d=m=>{let h=(m.headers["x-auth-request-email"]||"").trim().toLowerCase();if(h)return e.devMode||!e.proxySecret&&e.trustProxyHeadersUnverified||(0,af.hasTrustedProxyProof)(m.headers,e.proxySecret)?h:null},p=(m,h,E)=>{i("proxy_header.unverified",{ip:h,path:E}),Te(m,401,{error:"unauthorized",error_description:`X-Auth-Request-Email was present without a valid ${Vo.AUTH_PROXY_SECRET_HEADER} header. Only the trusted reverse proxy may assert an identity to this broker.`})},g=kD.createServer(async(m,h)=>{try{let E=m.headers.host||`127.0.0.1:${e.port}`,_=new Wo.URL(m.url||"/",`http://${E}`),y=_.pathname,b=(0,af.clientIp)(m),T=()=>s.tryConsume(b)?!1:(i("rate_limited",{ip:b,path:y}),h.writeHead(429,{"Content-Type":"application/json","Retry-After":String(s.retryAfterSeconds(b))}),h.end(JSON.stringify({error:"rate_limited"})),!0);if(m.method==="GET"&&(y==="/health"||y==="/api/ide/health")){Te(h,200,{status:"ok",service:"auth-broker"});return}if(m.method==="GET"&&y==="/oauth/authorize"){if(T())return;let A=_.searchParams.get("client_id")||"",v=_.searchParams.get("redirect_uri")||"",C=_.searchParams.get("code_challenge")||"",B=_.searchParams.get("state")||"",R=_.searchParams.get("login_hint")||_.searchParams.get("email")||"";if(A!==Yc.AUTH_CLIENT_ID||!v||!C){i("authorize.invalid_request",{client_id:A}),Te(h,400,{error:"invalid_request"});return}if(!Z_(v)){i("authorize.invalid_redirect_uri",{client_id:A}),Te(h,400,{error:"invalid_request",error_description:"redirect_uri not allowed"});return}if(e.devMode&&R){let he=r.upsertUser(R),z=r.createAuthCode({userId:he.id,clientId:A,redirectUri:v,codeChallenge:C});i("authorize.dev",{user:he.email});let Ne=new Wo.URL(v);Ne.searchParams.set("code",z),B&&Ne.searchParams.set("state",B),h.writeHead(302,{Location:Ne.toString()}),h.end();return}let F=d(m);if(F===null){p(h,b,y);return}if(!F){Te(h,401,{error:"unauthorized",error_description:"No authenticated user (missing X-Auth-Request-Email)"});return}let re=r.upsertUser(F),W=r.createAuthCode({userId:re.id,clientId:A,redirectUri:v,codeChallenge:C});i("authorize.signin",{user:re.email});let de=new Wo.URL(v);de.searchParams.set("code",W),B&&de.searchParams.set("state",B),h.writeHead(302,{Location:de.toString()}),h.end();return}if(m.method==="GET"&&y==="/oauth/browser-login"){if(T())return;let A=d(m);if(A===null){p(h,b,y);return}if(!A){Te(h,401,{error:"unauthorized",error_description:"No authenticated user (missing X-Auth-Request-Email)"});return}let v=r.upsertUser(A),C=r.issueTokens(v,Yc.AUTH_CLIENT_ID,"openid profile email agenthippo:ide");i("browser.login",{user:v.email});let B=e.publicBaseUrl.startsWith("https"),R=[`${e.cookieName}=${C.accessToken}`,"Path=/","HttpOnly","SameSite=Lax",...B?["Secure"]:[],...e.cookieDomain?[`Domain=${e.cookieDomain}`]:[],`Max-Age=${C.expiresIn}`],F=xD(_.searchParams.get("return_to")||"",e.cookieDomain,e.publicBaseUrl||"/");h.writeHead(302,{"Set-Cookie":R.join("; "),Location:F}),h.end();return}if(m.method==="POST"&&y==="/oauth/dev/login"){if(T())return;if(!e.devMode){Te(h,404,{error:"not_found"});return}let A=await cf(m),v=A.trim().startsWith("{")?JSON.parse(A):lf(A),C=v.email?.trim(),B=v.code_challenge?.trim(),R=v.redirect_uri?.trim(),F=v.client_id?.trim()||Yc.AUTH_CLIENT_ID;if(!C||!B||!R){Te(h,400,{error:"invalid_request"});return}let re=r.upsertUser(C),W=r.createAuthCode({userId:re.id,clientId:F,redirectUri:R,codeChallenge:B});i("dev.login",{user:re.email}),Te(h,200,{code:W});return}if(m.method==="POST"&&y==="/oauth/token"){if(T())return;let A=await cf(m),v=lf(A),C=v.grant_type,B=v.client_id||Yc.AUTH_CLIENT_ID,R=v.scope||"openid profile email agenthippo:ide";if(C==="authorization_code"){let F=v.code,re=v.code_verifier,W=v.redirect_uri;if(!F||!re||!W){Te(h,400,{error:"invalid_request"});return}let de=r.consumeAuthCode(F);if(!de||de.clientId!==B||de.redirectUri!==W){Te(h,400,{error:"invalid_grant"});return}if(!(0,MD.verifyPkceChallenge)(re,de.codeChallenge)){Te(h,400,{error:"invalid_grant",error_description:"PKCE verification failed"});return}let he=r.getUser(de.userId);if(!he){Te(h,400,{error:"invalid_grant"});return}let z=r.issueTokens(he,B,R);i("token.signin",{user:he.email,client_id:B}),Te(h,200,{access_token:z.accessToken,refresh_token:z.refreshToken,token_type:"Bearer",expires_in:z.expiresIn,scope:R});return}if(C==="refresh_token"){let F=v.refresh_token;if(!F){Te(h,400,{error:"invalid_request"});return}let re=r.consumeRefreshToken(F);if(!re||re.clientId!==B){i("token.refresh.invalid_grant"),Te(h,400,{error:"invalid_grant"});return}let W=r.getUser(re.userId);if(!W){Te(h,400,{error:"invalid_grant"});return}let de=r.issueTokens(W,B,R);i("token.refresh",{user:W.email}),Te(h,200,{access_token:de.accessToken,refresh_token:de.refreshToken,token_type:"Bearer",expires_in:de.expiresIn,scope:R});return}Te(h,400,{error:"unsupported_grant_type"});return}if(m.method==="POST"&&y==="/oauth/introspect"){if(!u(m)){i("introspect.unauthorized"),Te(h,401,{error:"unauthorized"});return}let A=await cf(m),C=lf(A).token;if(!C){Te(h,400,{error:"invalid_request"});return}let B=(0,qc.verifyJwt)(C,e.jwtSecret);if(!B?.sub){Te(h,200,{active:!1});return}Te(h,200,{active:!0,sub:B.sub,email:B.email,team_id:B.team_id,scope:B.scope,exp:B.exp});return}let O=u(m);if(m.method==="GET"&&y==="/api/ide/me"){if(!O){let v=Date.now();v-f>l&&(f=v,i("me.unauthorized")),Te(h,401,{error:"unauthorized"});return}h.setHeader("X-Agent-User",O.email||O.id);let A=(0,qc.extractBearerToken)(m.headers.authorization)||Q_(m.headers.cookie,e.cookieName);A&&h.setHeader("X-Agent-User-Assertion",A),Te(h,200,r.buildMe(O));return}if(m.method==="GET"&&y==="/api/ide/bootstrap"){if(!O){Te(h,401,{error:"unauthorized"});return}Te(h,200,r.buildBootstrap(O));return}if(m.method==="POST"&&y==="/api/ide/signout"){O&&(r.revokeRefreshTokensForUser(O.id),i("signout",{user:O.email})),Te(h,200,{ok:!0});return}Te(h,404,{error:"not_found"})}catch(E){let _=E.status;if(_===413){Te(h,413,{error:"request_entity_too_large"});return}if(_===403){i("forbidden",{reason:"email_domain"}),Te(h,403,{error:"forbidden",error_description:"email domain not allowed"});return}console.error("[auth-broker] internal error",E),Te(h,500,{error:"server_error"})}});return{server:g,baseUrl:e.publicBaseUrl,store:r,config:e,close:()=>new Promise((m,h)=>{g.close(E=>E?h(E):m())})}}async function BD(t){let e=ey(t),n=(0,Vo.resolveAuthBrokerBind)();return n.isPublic&&console.warn(`[auth-broker] WARNING: listening on ${n.address}:${e.config.port} \u2014 this token-issuing endpoint is reachable from off-host (AGENTHIPPO_AUTH_ALLOW_PUBLIC_BIND=1). Ensure only the reverse proxy can reach it and that AGENTHIPPO_AUTH_PROXY_SECRET is set.`),await new Promise((r,s)=>{e.server.listen(e.config.port,n.address,()=>r()),e.server.once("error",s)}),e}});var ny=S(df=>{"use strict";Object.defineProperty(df,"__esModule",{value:!0});df.authBrokerCommand=WD;var FD=Do(),VD=ty();async function WD(){let t=(0,FD.loadAuthBrokerConfig)(),e=await(0,VD.startAuthBrokerServer)(t);console.log(`AgentHippo auth broker listening on ${e.baseUrl}`),console.log(" GET /health"),console.log(" GET /oauth/authorize"),console.log(" POST /oauth/token"),console.log(" GET /api/ide/bootstrap"),await new Promise(n=>{let r=()=>{e.close().then(n).catch(()=>n())};process.once("SIGINT",r),process.once("SIGTERM",r)})}});var pf=S(Ir=>{"use strict";Object.defineProperty(Ir,"__esModule",{value:!0});Ir.EDGE_AGENT_PORT=void 0;Ir.renderIdentityLayer=ff;Ir.renderSidecarEdgeCaddyfile=KD;Ir.renderSidecarFedCaddyfile=qD;var ry=[" # Proves this hop is the trusted proxy \u2014 the broker 401s X-Auth-Request-Email without it."," header_up x-agenthippo-proxy-secret {env.AGENTHIPPO_AUTH_PROXY_SECRET}"];function ff(t){let{mode:e,authBrokerAddr:n,healthProxy:r,agentProxy:s}=t,i=t.oauth2ProxyAddr??"",o=t.catchallBody??s,a=t.turnRegistration,c=a?[" # Turn registration \u2014 after identity: X-Agent-User (set above) names the user the"," # sidecar mints the nonce for. Only POST chat turns match; others pass through."," # X-Agent-User-Assertion (also set above) rides along as the turn's inboundToken:"," # without it `passthrough` fails closed on every call and an RFC 8693 `exchange`"," # provider has no subject_token.",` forward_auth @turnStart ${a.connectorAddr} {`," uri /edge/turn"," copy_headers X-Agent-Turn-Nonce",` header_up Authorization "Bearer {$${a.tokenEnvVar}}"`," }"]:[],l=d=>d.map(p=>p.trim()?` ${p}`:p),f=(d,p)=>a?[" route {",...l(d),...c,...l(p)," }"]:[...d,...p],u=[];if(a&&u.push(" # Hygiene: never let a client-supplied nonce header through (copy_headers overwrites it"," # on chat paths anyway, and a forged nonce fails closed at the gateway \u2014 belt-and-braces)."," request_header -X-Agent-Turn-Nonce"," # Same for the user assertion: it is set from the verified /api/ide/me response below,"," # never from the client. A forged one would become the turn's inboundToken."," request_header -X-Agent-User-Assertion"),e==="self-issued"&&u.push(" # IDE PKCE sign-in: broker requires X-Auth-Request-Email from oauth2-proxy. Must come"," # before the generic /oauth/* handle so authorize is gated (not dumped straight to broker)."," handle /oauth/authorize {",` forward_auth ${i} {`," uri /oauth2/auth"," copy_headers X-Auth-Request-Email"," header_up X-Forwarded-Proto https"," header_up X-Forwarded-Host {http.request.host}"," @unauth status 401"," handle_response @unauth {",' redir * "/oauth2/sign_in?rd={http.request.uri}"'," }"," }",` reverse_proxy ${n} {`," header_up X-Forwarded-Proto https"," header_up X-Forwarded-Host {http.request.host}",...ry," }"," }"," # Federated SSO (A\u2032): browsers from other subdomains land here to stamp the shared cookie."," # Same oauth2-proxy gate as authorize; must precede the generic /oauth/* handle."," handle /oauth/browser-login {",` forward_auth ${i} {`," uri /oauth2/auth"," copy_headers X-Auth-Request-Email"," header_up X-Forwarded-Proto https"," header_up X-Forwarded-Host {http.request.host}"," @unauth status 401"," handle_response @unauth {",' redir * "/oauth2/sign_in?rd={http.request.uri}"'," }"," }",` reverse_proxy ${n} {`," header_up X-Forwarded-Proto https"," header_up X-Forwarded-Host {http.request.host}",...ry," }"," }"," # Auth-broker: token exchange + other /oauth/* routes that must stay ungated."," handle /oauth/* {",` reverse_proxy ${n} {`," header_up X-Forwarded-Proto https"," header_up X-Forwarded-Host {http.request.host}"," }"," }"),u.push(" handle /api/ide/* {",` reverse_proxy ${n} {`," header_up X-Forwarded-Proto https"," header_up X-Forwarded-Host {http.request.host}"," }"," }"),e==="self-issued"&&u.push(" # oauth2-proxy: Google SSO callback + sign-in."," handle /oauth2/* {",` reverse_proxy ${i} {`," header_up X-Forwarded-Proto https"," header_up X-Forwarded-Host {http.request.host}"," }"," }"),u.push(" @health path /health /ready"," handle @health {",...r," }"),a&&u.push(" # Chat-turn matcher for edge turn registration (P1 fix): only POST chat turns register."," @turnStart {"," method POST"," path /v1/chat /v1/chat/stream"," }"),u.push(" # API clients (IDE) with a Bearer token: validate via auth-broker, copy identity header."," @apiWithAuth {"," path /v1/*"," header Authorization *"," }"," handle @apiWithAuth {",...f([` forward_auth ${n} {`," uri /api/ide/me",` copy_headers X-Agent-User${a?" X-Agent-User-Assertion":""}`," header_up X-Forwarded-Proto https"," header_up X-Forwarded-Host {http.request.host}"," @unauth status 401"," handle_response @unauth {",' respond "Unauthorized" 401'," }"," }"],s)," }"),e==="self-issued")u.push(" # Browser clients: SSO via oauth2-proxy, identity injected as X-Agent-User."," handle {",...f([` forward_auth ${i} {`," uri /oauth2/auth"," copy_headers X-Auth-Request-Email>X-Agent-User"," header_up X-Forwarded-Proto https"," header_up X-Forwarded-Host {http.request.host}"," @unauth status 401"," handle_response @unauth {",' redir * "/oauth2/sign_in?rd={http.request.uri}"'," }"," }"],o)," }");else{let d=t.idpUrl?.trim()||"",p=d?` redir * "${d}/oauth/browser-login?return_to=https://{http.request.host}{http.request.uri}" 302`:' respond "Unauthorized" 401';u.push(" # Browser clients: the shared .agenthippo.ai cookie is verified by auth-broker. No cookie"," # \u2192 redirect to the central IdP to log in (it stamps the cookie), then return."," handle {",...f([` forward_auth ${n} {`," uri /api/ide/me"," copy_headers X-Agent-User"," header_up X-Forwarded-Proto https"," header_up X-Forwarded-Host {http.request.host}"," @unauth status 401"," handle_response @unauth {",p," }"," }"],o)," }")}return u}Ir.EDGE_AGENT_PORT=8090;function KD(){return["# Sidecar-platform edge ingress. TLS terminates in front; Caddy listens on HTTP :{$PORT}.","# Containers share one task/pod's localhost \u2192 upstreams are 127.0.0.1:<port> (not docker-DNS names).","{"," auto_https off","}","",":{$PORT} {",...ff({mode:"self-issued",oauth2ProxyAddr:"localhost:4180",authBrokerAddr:"localhost:9780",healthProxy:[` reverse_proxy localhost:${Ir.EDGE_AGENT_PORT}`],agentProxy:[` reverse_proxy localhost:${Ir.EDGE_AGENT_PORT}`]}),"}",""].join(`
535
- `)}function qD(t){let e=(t||"").trim().replace(/\/+$/,"");return["# Sidecar-platform federated edge (A\u2032). TLS terminates in front; Caddy listens on HTTP :{$PORT}.",`# No oauth2-proxy \u2014 Google login happens once at the central IdP (${e||"<IDP_URL>"});`,"# this agent only verifies the shared AgentHippo JWT (Bearer for IDE, cookie for browser).","{"," auto_https off","}","",":{$PORT} {",...ff({mode:"federated",authBrokerAddr:"localhost:9780",idpUrl:e,healthProxy:[` reverse_proxy localhost:${Ir.EDGE_AGENT_PORT}`],agentProxy:[` reverse_proxy localhost:${Ir.EDGE_AGENT_PORT}`]}),"}",""].join(`
536
- `)}});var _f=S(Q=>{"use strict";var YD=Q&&Q.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,s)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),XD=Q&&Q.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),sy=Q&&Q.__importStar||(function(){var t=function(e){return t=Object.getOwnPropertyNames||function(n){var r=[];for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(r[r.length]=s);return r},t(e)};return function(e){if(e&&e.__esModule)return e;var n={};if(e!=null)for(var r=t(e),s=0;s<r.length;s++)r[s]!=="default"&&YD(n,e,r[s]);return XD(n,e),n}})();Object.defineProperty(Q,"__esModule",{value:!0});Q.AGENTHIPPO_CLI_NPM_VERSION_FALLBACK=Q.AGENTHIPPO_CLI_NPM_PACKAGE=Q.DEPLOY_PUBLIC_HOSTNAME=Q.DEFAULT_DEPLOY_PUBLIC_HOSTNAME=Q.CLAUDE_CODE_NPM_VERSION=Q.AGENTHIPPO_IMAGE_TAG=Q.AGENTHIPPO_IMAGE_REGISTRY=Q.DEPLOY_TARGETS=void 0;Q.isDeployTarget=JD;Q.agenthippoImage=Kr;Q.defaultRuntimeImage=zD;Q.packAttributionBody=iy;Q.packAttributionComment=gf;Q.withPackAttribution=oy;Q.serveCmdArgs=hi;Q.resolveAgentHippoCliNpmVersion=ay;Q.resolveDeployPublicHostname=hf;Q.scanEnvRefs=e0;Q.renderEnvExample=cy;Q.renderAuthEnvExample=ly;Q.renderAuthBrokerDockerfile=mf;Q.isSecretLikeBasename=t0;Q.dataPlaneTokenEnvVar=my;Q.renderTarget=b0;var Xc=sy(require("fs")),qo=sy(require("path")),Jc=Br(),ot=pf();Q.DEPLOY_TARGETS=["vm","compose","cloudrun","databricks-app","spcs","cloudflare","aws-ecs","azure-container-apps"];function JD(t){return Q.DEPLOY_TARGETS.includes(t)}Q.AGENTHIPPO_IMAGE_REGISTRY="ghcr.io/agenthippoai";Q.AGENTHIPPO_IMAGE_TAG="2026.07";Q.CLAUDE_CODE_NPM_VERSION="2.1.220";function Kr(t,e){return`${Q.AGENTHIPPO_IMAGE_REGISTRY}/${t}:${Q.AGENTHIPPO_IMAGE_TAG}${e?`-${e}`:""}`}function zD(t){return t.trim().toLowerCase()==="cursor"?Kr("runtime","cursor"):Kr("runtime")}function iy(t){return`Generated from Agent Pack ${t.packName}@${t.packVersion} \u2014 packs.agenthippo.ai`}function gf(t,e="hash"){let n=iy(t);return e==="html"?`<!-- ${n} -->`:e==="sql"?`-- ${n}`:`# ${n}`}function oy(t,e,n){if(n.slice(0,400).includes("packs.agenthippo.ai"))return n;let s=qo.basename(e),i=qo.extname(s).toLowerCase();if(i===".json"||i===".jsonc"||s==="wrangler.toml"||s==="package.json")return n;let a=gf(t,i===".html"||i===".md"?"html":i===".sql"?"sql":"hash");if(n.startsWith("#!")){let c=n.indexOf(`
533
+ header_up ${Ko.AUTH_PROXY_SECRET_HEADER} {env.AGENTHIPPO_AUTH_PROXY_SECRET}
534
+ If the broker is genuinely unreachable except through the proxy and you accept the risk, set AGENTHIPPO_AUTH_TRUST_PROXY_UNVERIFIED=1.`);!e.devMode&&!e.proxySecret&&e.trustProxyHeadersUnverified&&console.warn("[auth-broker] WARNING: AGENTHIPPO_AUTH_TRUST_PROXY_UNVERIFIED=1 \u2014 X-Auth-Request-Email is accepted without proof. Anything that can reach this port can mint a token for any email. Set AGENTHIPPO_AUTH_PROXY_SECRET to close this."),!e.devMode&&e.allowedEmailDomains.length===0&&console.warn('[auth-broker] Warning: AGENTHIPPO_AUTH_ALLOWED_DOMAINS is not set \u2014 any upstream-SSO-authenticated email can receive a token. Set it to restrict sign-in (e.g. "example.com").');let n=e.dataDir?UD.join(e.dataDir,"auth-store.json"):void 0,r=new HD.AuthBrokerStore(e,n),s=new af.RateLimiter(e.rateLimitPerMin),i=(m,h={})=>{let E=Object.entries(h).filter(([,_])=>_!==void 0&&_!=="").map(([_,y])=>{let b=!e.logPii&&typeof y=="string"&&y.includes("@")?FD(y):y;return`${_}=${b}`}).join(" ");console.log(`[auth-broker] ${m}${E?" "+E:""}`)},o=1e4,a=2048,c=new Map,l=5e3,f=0;function u(m){let h=(0,Xc.extractBearerToken)(m.headers.authorization)||Z_(m.headers.cookie,e.cookieName);if(!h)return;let E=GD.createHash("sha256").update(h).digest("hex"),_=c.get(E);if(_){if(_.exp>Date.now())return _.user;c.delete(E)}let y=(0,Xc.verifyJwt)(h,e.jwtSecret);if(!y?.sub||!y.email)return;let b=r.getUser(String(y.sub));if(!b){let T=typeof y.team_id=="string"&&y.team_id?y.team_id:void 0;b={id:String(y.sub),email:String(y.email),displayName:typeof y.name=="string"&&y.name?y.name:String(y.email),teamId:T??(e.teamConfigured?e.team.id:void 0)}}if(y.exp){let T=Math.min(y.exp*1e3,Date.now()+o);if(c.size>=a){let O=Date.now();for(let[A,v]of c)v.exp<O&&c.delete(A);c.size>=a&&c.clear()}c.set(E,{user:b,exp:T})}return b}let d=m=>{let h=(m.headers["x-auth-request-email"]||"").trim().toLowerCase();if(h)return e.devMode||!e.proxySecret&&e.trustProxyHeadersUnverified||(0,af.hasTrustedProxyProof)(m.headers,e.proxySecret)?h:null},p=(m,h,E)=>{i("proxy_header.unverified",{ip:h,path:E}),Te(m,401,{error:"unauthorized",error_description:`X-Auth-Request-Email was present without a valid ${Ko.AUTH_PROXY_SECRET_HEADER} header. Only the trusted reverse proxy may assert an identity to this broker.`})},g=MD.createServer(async(m,h)=>{try{let E=m.headers.host||`127.0.0.1:${e.port}`,_=new qo.URL(m.url||"/",`http://${E}`),y=_.pathname,b=(0,af.clientIp)(m),T=()=>s.tryConsume(b)?!1:(i("rate_limited",{ip:b,path:y}),h.writeHead(429,{"Content-Type":"application/json","Retry-After":String(s.retryAfterSeconds(b))}),h.end(JSON.stringify({error:"rate_limited"})),!0);if(m.method==="GET"&&(y==="/health"||y==="/api/ide/health")){Te(h,200,{status:"ok",service:"auth-broker"});return}if(m.method==="GET"&&y==="/oauth/authorize"){if(T())return;let A=_.searchParams.get("client_id")||"",v=_.searchParams.get("redirect_uri")||"",C=_.searchParams.get("code_challenge")||"",B=_.searchParams.get("state")||"",R=_.searchParams.get("login_hint")||_.searchParams.get("email")||"";if(A!==Jc.AUTH_CLIENT_ID||!v||!C){i("authorize.invalid_request",{client_id:A}),Te(h,400,{error:"invalid_request"});return}if(!ey(v)){i("authorize.invalid_redirect_uri",{client_id:A}),Te(h,400,{error:"invalid_request",error_description:"redirect_uri not allowed"});return}if(e.devMode&&R){let he=r.upsertUser(R),Q=r.createAuthCode({userId:he.id,clientId:A,redirectUri:v,codeChallenge:C});i("authorize.dev",{user:he.email});let Ne=new qo.URL(v);Ne.searchParams.set("code",Q),B&&Ne.searchParams.set("state",B),h.writeHead(302,{Location:Ne.toString()}),h.end();return}let F=d(m);if(F===null){p(h,b,y);return}if(!F){Te(h,401,{error:"unauthorized",error_description:"No authenticated user (missing X-Auth-Request-Email)"});return}let re=r.upsertUser(F),W=r.createAuthCode({userId:re.id,clientId:A,redirectUri:v,codeChallenge:C});i("authorize.signin",{user:re.email});let de=new qo.URL(v);de.searchParams.set("code",W),B&&de.searchParams.set("state",B),h.writeHead(302,{Location:de.toString()}),h.end();return}if(m.method==="GET"&&y==="/oauth/browser-login"){if(T())return;let A=d(m);if(A===null){p(h,b,y);return}if(!A){Te(h,401,{error:"unauthorized",error_description:"No authenticated user (missing X-Auth-Request-Email)"});return}let v=r.upsertUser(A),C=r.issueTokens(v,Jc.AUTH_CLIENT_ID,"openid profile email agenthippo:ide");i("browser.login",{user:v.email});let B=e.publicBaseUrl.startsWith("https"),R=[`${e.cookieName}=${C.accessToken}`,"Path=/","HttpOnly","SameSite=Lax",...B?["Secure"]:[],...e.cookieDomain?[`Domain=${e.cookieDomain}`]:[],`Max-Age=${C.expiresIn}`],F=WD(_.searchParams.get("return_to")||"",e.cookieDomain,e.publicBaseUrl||"/");h.writeHead(302,{"Set-Cookie":R.join("; "),Location:F}),h.end();return}if(m.method==="POST"&&y==="/oauth/dev/login"){if(T())return;if(!e.devMode){Te(h,404,{error:"not_found"});return}let A=await cf(m),v=A.trim().startsWith("{")?JSON.parse(A):lf(A),C=v.email?.trim(),B=v.code_challenge?.trim(),R=v.redirect_uri?.trim(),F=v.client_id?.trim()||Jc.AUTH_CLIENT_ID;if(!C||!B||!R){Te(h,400,{error:"invalid_request"});return}let re=r.upsertUser(C),W=r.createAuthCode({userId:re.id,clientId:F,redirectUri:R,codeChallenge:B});i("dev.login",{user:re.email}),Te(h,200,{code:W});return}if(m.method==="POST"&&y==="/oauth/token"){if(T())return;let A=await cf(m),v=lf(A),C=v.grant_type,B=v.client_id||Jc.AUTH_CLIENT_ID,R=v.scope||"openid profile email agenthippo:ide";if(C==="authorization_code"){let F=v.code,re=v.code_verifier,W=v.redirect_uri;if(!F||!re||!W){Te(h,400,{error:"invalid_request"});return}let de=r.consumeAuthCode(F);if(!de||de.clientId!==B||de.redirectUri!==W){Te(h,400,{error:"invalid_grant"});return}if(!(0,jD.verifyPkceChallenge)(re,de.codeChallenge)){Te(h,400,{error:"invalid_grant",error_description:"PKCE verification failed"});return}let he=r.getUser(de.userId);if(!he){Te(h,400,{error:"invalid_grant"});return}let Q=r.issueTokens(he,B,R);i("token.signin",{user:he.email,client_id:B}),Te(h,200,{access_token:Q.accessToken,refresh_token:Q.refreshToken,token_type:"Bearer",expires_in:Q.expiresIn,scope:R});return}if(C==="refresh_token"){let F=v.refresh_token;if(!F){Te(h,400,{error:"invalid_request"});return}let re=r.consumeRefreshToken(F);if(!re||re.clientId!==B){i("token.refresh.invalid_grant"),Te(h,400,{error:"invalid_grant"});return}let W=r.getUser(re.userId);if(!W){Te(h,400,{error:"invalid_grant"});return}let de=r.issueTokens(W,B,R);i("token.refresh",{user:W.email}),Te(h,200,{access_token:de.accessToken,refresh_token:de.refreshToken,token_type:"Bearer",expires_in:de.expiresIn,scope:R});return}Te(h,400,{error:"unsupported_grant_type"});return}if(m.method==="POST"&&y==="/oauth/introspect"){if(!u(m)){i("introspect.unauthorized"),Te(h,401,{error:"unauthorized"});return}let A=await cf(m),C=lf(A).token;if(!C){Te(h,400,{error:"invalid_request"});return}let B=(0,Xc.verifyJwt)(C,e.jwtSecret);if(!B?.sub){Te(h,200,{active:!1});return}Te(h,200,{active:!0,sub:B.sub,email:B.email,team_id:B.team_id,scope:B.scope,exp:B.exp});return}let O=u(m);if(m.method==="GET"&&y==="/api/ide/me"){if(!O){let v=Date.now();v-f>l&&(f=v,i("me.unauthorized")),Te(h,401,{error:"unauthorized"});return}h.setHeader("X-Agent-User",O.email||O.id);let A=(0,Xc.extractBearerToken)(m.headers.authorization)||Z_(m.headers.cookie,e.cookieName);A&&h.setHeader("X-Agent-User-Assertion",A),Te(h,200,r.buildMe(O));return}if(m.method==="GET"&&y==="/api/ide/bootstrap"){if(!O){Te(h,401,{error:"unauthorized"});return}Te(h,200,r.buildBootstrap(O));return}if(m.method==="POST"&&y==="/api/ide/signout"){O&&(r.revokeRefreshTokensForUser(O.id),i("signout",{user:O.email})),Te(h,200,{ok:!0});return}Te(h,404,{error:"not_found"})}catch(E){let _=E.status;if(_===413){Te(h,413,{error:"request_entity_too_large"});return}if(_===403){i("forbidden",{reason:"email_domain"}),Te(h,403,{error:"forbidden",error_description:"email domain not allowed"});return}console.error("[auth-broker] internal error",E),Te(h,500,{error:"server_error"})}});return{server:g,baseUrl:e.publicBaseUrl,store:r,config:e,close:()=>new Promise((m,h)=>{g.close(E=>E?h(E):m())})}}async function KD(t){let e=ty(t),n=(0,Ko.resolveAuthBrokerBind)();return n.isPublic&&console.warn(`[auth-broker] WARNING: listening on ${n.address}:${e.config.port} \u2014 this token-issuing endpoint is reachable from off-host (AGENTHIPPO_AUTH_ALLOW_PUBLIC_BIND=1). Ensure only the reverse proxy can reach it and that AGENTHIPPO_AUTH_PROXY_SECRET is set.`),await new Promise((r,s)=>{e.server.listen(e.config.port,n.address,()=>r()),e.server.once("error",s)}),e}});var ry=S(df=>{"use strict";Object.defineProperty(df,"__esModule",{value:!0});df.authBrokerCommand=XD;var qD=Mo(),YD=ny();async function XD(){let t=(0,qD.loadAuthBrokerConfig)(),e=await(0,YD.startAuthBrokerServer)(t);console.log(`AgentHippo auth broker listening on ${e.baseUrl}`),console.log(" GET /health"),console.log(" GET /oauth/authorize"),console.log(" POST /oauth/token"),console.log(" GET /api/ide/bootstrap"),await new Promise(n=>{let r=()=>{e.close().then(n).catch(()=>n())};process.once("SIGINT",r),process.once("SIGTERM",r)})}});var pf=S(Ir=>{"use strict";Object.defineProperty(Ir,"__esModule",{value:!0});Ir.EDGE_AGENT_PORT=void 0;Ir.renderIdentityLayer=ff;Ir.renderSidecarEdgeCaddyfile=JD;Ir.renderSidecarFedCaddyfile=zD;var sy=[" # Proves this hop is the trusted proxy \u2014 the broker 401s X-Auth-Request-Email without it."," header_up x-agenthippo-proxy-secret {env.AGENTHIPPO_AUTH_PROXY_SECRET}"];function ff(t){let{mode:e,authBrokerAddr:n,healthProxy:r,agentProxy:s}=t,i=t.oauth2ProxyAddr??"",o=t.catchallBody??s,a=t.turnRegistration,c=a?[" # Turn registration \u2014 after identity: X-Agent-User (set above) names the user the"," # sidecar mints the nonce for. Only POST chat turns match; others pass through."," # X-Agent-User-Assertion (also set above) rides along as the turn's inboundToken:"," # without it `passthrough` fails closed on every call and an RFC 8693 `exchange`"," # provider has no subject_token.",` forward_auth @turnStart ${a.connectorAddr} {`," uri /edge/turn"," copy_headers X-Agent-Turn-Nonce",` header_up Authorization "Bearer {$${a.tokenEnvVar}}"`," }"]:[],l=d=>d.map(p=>p.trim()?` ${p}`:p),f=(d,p)=>a?[" route {",...l(d),...c,...l(p)," }"]:[...d,...p],u=[];if(a&&u.push(" # Hygiene: never let a client-supplied nonce header through (copy_headers overwrites it"," # on chat paths anyway, and a forged nonce fails closed at the gateway \u2014 belt-and-braces)."," request_header -X-Agent-Turn-Nonce"," # Same for the user assertion: it is set from the verified /api/ide/me response below,"," # never from the client. A forged one would become the turn's inboundToken."," request_header -X-Agent-User-Assertion"),e==="self-issued"&&u.push(" # IDE PKCE sign-in: broker requires X-Auth-Request-Email from oauth2-proxy. Must come"," # before the generic /oauth/* handle so authorize is gated (not dumped straight to broker)."," handle /oauth/authorize {",` forward_auth ${i} {`," uri /oauth2/auth"," copy_headers X-Auth-Request-Email"," header_up X-Forwarded-Proto https"," header_up X-Forwarded-Host {http.request.host}"," @unauth status 401"," handle_response @unauth {",' redir * "/oauth2/sign_in?rd={http.request.uri}"'," }"," }",` reverse_proxy ${n} {`," header_up X-Forwarded-Proto https"," header_up X-Forwarded-Host {http.request.host}",...sy," }"," }"," # Federated SSO (A\u2032): browsers from other subdomains land here to stamp the shared cookie."," # Same oauth2-proxy gate as authorize; must precede the generic /oauth/* handle."," handle /oauth/browser-login {",` forward_auth ${i} {`," uri /oauth2/auth"," copy_headers X-Auth-Request-Email"," header_up X-Forwarded-Proto https"," header_up X-Forwarded-Host {http.request.host}"," @unauth status 401"," handle_response @unauth {",' redir * "/oauth2/sign_in?rd={http.request.uri}"'," }"," }",` reverse_proxy ${n} {`," header_up X-Forwarded-Proto https"," header_up X-Forwarded-Host {http.request.host}",...sy," }"," }"," # Auth-broker: token exchange + other /oauth/* routes that must stay ungated."," handle /oauth/* {",` reverse_proxy ${n} {`," header_up X-Forwarded-Proto https"," header_up X-Forwarded-Host {http.request.host}"," }"," }"),u.push(" handle /api/ide/* {",` reverse_proxy ${n} {`," header_up X-Forwarded-Proto https"," header_up X-Forwarded-Host {http.request.host}"," }"," }"),e==="self-issued"&&u.push(" # oauth2-proxy: Google SSO callback + sign-in."," handle /oauth2/* {",` reverse_proxy ${i} {`," header_up X-Forwarded-Proto https"," header_up X-Forwarded-Host {http.request.host}"," }"," }"),u.push(" @health path /health /ready"," handle @health {",...r," }"),a&&u.push(" # Chat-turn matcher for edge turn registration (P1 fix): only POST chat turns register."," @turnStart {"," method POST"," path /v1/chat /v1/chat/stream"," }"),u.push(" # API clients (IDE) with a Bearer token: validate via auth-broker, copy identity header."," @apiWithAuth {"," path /v1/*"," header Authorization *"," }"," handle @apiWithAuth {",...f([` forward_auth ${n} {`," uri /api/ide/me",` copy_headers X-Agent-User${a?" X-Agent-User-Assertion":""}`," header_up X-Forwarded-Proto https"," header_up X-Forwarded-Host {http.request.host}"," @unauth status 401"," handle_response @unauth {",' respond "Unauthorized" 401'," }"," }"],s)," }"),e==="self-issued")u.push(" # Browser clients: SSO via oauth2-proxy, identity injected as X-Agent-User."," handle {",...f([` forward_auth ${i} {`," uri /oauth2/auth"," copy_headers X-Auth-Request-Email>X-Agent-User"," header_up X-Forwarded-Proto https"," header_up X-Forwarded-Host {http.request.host}"," @unauth status 401"," handle_response @unauth {",' redir * "/oauth2/sign_in?rd={http.request.uri}"'," }"," }"],o)," }");else{let d=t.idpUrl?.trim()||"",p=d?` redir * "${d}/oauth/browser-login?return_to=https://{http.request.host}{http.request.uri}" 302`:' respond "Unauthorized" 401';u.push(" # Browser clients: the shared .agenthippo.ai cookie is verified by auth-broker. No cookie"," # \u2192 redirect to the central IdP to log in (it stamps the cookie), then return."," handle {",...f([` forward_auth ${n} {`," uri /api/ide/me"," copy_headers X-Agent-User"," header_up X-Forwarded-Proto https"," header_up X-Forwarded-Host {http.request.host}"," @unauth status 401"," handle_response @unauth {",p," }"," }"],o)," }")}return u}Ir.EDGE_AGENT_PORT=8090;function JD(){return["# Sidecar-platform edge ingress. TLS terminates in front; Caddy listens on HTTP :{$PORT}.","# Containers share one task/pod's localhost \u2192 upstreams are 127.0.0.1:<port> (not docker-DNS names).","{"," auto_https off","}","",":{$PORT} {",...ff({mode:"self-issued",oauth2ProxyAddr:"localhost:4180",authBrokerAddr:"localhost:9780",healthProxy:[` reverse_proxy localhost:${Ir.EDGE_AGENT_PORT}`],agentProxy:[` reverse_proxy localhost:${Ir.EDGE_AGENT_PORT}`]}),"}",""].join(`
535
+ `)}function zD(t){let e=(t||"").trim().replace(/\/+$/,"");return["# Sidecar-platform federated edge (A\u2032). TLS terminates in front; Caddy listens on HTTP :{$PORT}.",`# No oauth2-proxy \u2014 Google login happens once at the central IdP (${e||"<IDP_URL>"});`,"# this agent only verifies the shared AgentHippo JWT (Bearer for IDE, cookie for browser).","{"," auto_https off","}","",":{$PORT} {",...ff({mode:"federated",authBrokerAddr:"localhost:9780",idpUrl:e,healthProxy:[` reverse_proxy localhost:${Ir.EDGE_AGENT_PORT}`],agentProxy:[` reverse_proxy localhost:${Ir.EDGE_AGENT_PORT}`]}),"}",""].join(`
536
+ `)}});var yf=S(q=>{"use strict";var QD=q&&q.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,s)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),ZD=q&&q.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),iy=q&&q.__importStar||(function(){var t=function(e){return t=Object.getOwnPropertyNames||function(n){var r=[];for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(r[r.length]=s);return r},t(e)};return function(e){if(e&&e.__esModule)return e;var n={};if(e!=null)for(var r=t(e),s=0;s<r.length;s++)r[s]!=="default"&&QD(n,e,r[s]);return ZD(n,e),n}})();Object.defineProperty(q,"__esModule",{value:!0});q.DEPLOY_PUBLIC_HOSTNAME=q.DEFAULT_DEPLOY_PUBLIC_HOSTNAME=q.AGENTHIPPO_HIPPOCLAW_NPM=q.AGENTHIPPO_LITELLM_IMAGE_TAG=q.AGENTHIPPO_RUNTIME_IMAGE_TAG=q.AGENTHIPPO_CLI_NPM_VERSION_FALLBACK=q.AGENTHIPPO_CLI_NPM_PACKAGE=q.AGENTHIPPO_IMAGE_REGISTRY=q.DEPLOY_TARGETS=void 0;q.isDeployTarget=e0;q.resolveCliReleaseVersion=gf;q.resolveAgentHippoCliNpmVersion=cy;q.agenthippoImage=ys;q.defaultRuntimeImage=t0;q.packAttributionBody=ly;q.packAttributionComment=hf;q.withPackAttribution=uy;q.serveCmdArgs=hi;q.resolveDeployPublicHostname=mf;q.scanEnvRefs=s0;q.renderEnvExample=dy;q.renderAuthEnvExample=fy;q.renderAuthBrokerDockerfile=Ef;q.renderChannelsDockerfile=py;q.isSecretLikeBasename=i0;q.dataPlaneTokenEnvVar=wy;q.renderTarget=P0;var qi=iy(require("fs")),Yi=iy(require("path")),zc=Br(),ot=pf();q.DEPLOY_TARGETS=["vm","compose","cloudrun","databricks-app","spcs","cloudflare","aws-ecs","azure-container-apps"];function e0(t){return q.DEPLOY_TARGETS.includes(t)}q.AGENTHIPPO_IMAGE_REGISTRY="ghcr.io/agenthippoai";q.AGENTHIPPO_CLI_NPM_PACKAGE="@agenthippo-ai/agenthippo";q.AGENTHIPPO_CLI_NPM_VERSION_FALLBACK="latest";function oy(){try{return pc()}catch{try{let t=Yi.join(__dirname,"..","..","package.json");if(qi.existsSync(t))return JSON.parse(qi.readFileSync(t,"utf8"))}catch{}return}}function ay(t){let e=oy()?.agenthippo?.[t]?.trim();if(!e)throw new Error(`extensions/agentide/package.json agenthippo.${t} is missing`);return e}function gf(){let t=oy()?.version?.trim();if(t&&t!=="0.0.0"&&t!=="dev")return t;try{let e=Yi.join(__dirname,"..","..","..","..","package.json");if(qi.existsSync(e)){let n=JSON.parse(qi.readFileSync(e,"utf8")).version?.trim();if(n&&n!=="0.0.0"&&n!=="dev")return n}}catch{}}function cy(){return gf()??q.AGENTHIPPO_CLI_NPM_VERSION_FALLBACK}q.AGENTHIPPO_RUNTIME_IMAGE_TAG=gf()??"dev";q.AGENTHIPPO_LITELLM_IMAGE_TAG=ay("litellmImageTag");q.AGENTHIPPO_HIPPOCLAW_NPM=ay("hippoclawNpm");function ys(t,e){let n=t==="runtime"?q.AGENTHIPPO_RUNTIME_IMAGE_TAG:q.AGENTHIPPO_LITELLM_IMAGE_TAG;return`${q.AGENTHIPPO_IMAGE_REGISTRY}/${t}:${n}${e?`-${e}`:""}`}function t0(t){return t.trim().toLowerCase()==="cursor"?ys("runtime","cursor"):ys("runtime")}function ly(t){return`Generated from Agent Pack ${t.packName}@${t.packVersion} \u2014 packs.agenthippo.ai`}function hf(t,e="hash"){let n=ly(t);return e==="html"?`<!-- ${n} -->`:e==="sql"?`-- ${n}`:`# ${n}`}function uy(t,e,n){if(n.slice(0,400).includes("packs.agenthippo.ai"))return n;let s=Yi.basename(e),i=Yi.extname(s).toLowerCase();if(i===".json"||i===".jsonc"||s==="wrangler.toml"||s==="package.json")return n;let a=hf(t,i===".html"||i===".md"?"html":i===".sql"?"sql":"hash");if(n.startsWith("#!")){let c=n.indexOf(`
537
537
  `);return c===-1?`${n}
538
538
  ${a}
539
539
  `:`${n.slice(0,c+1)}${a}
540
540
  ${n.slice(c+1)}`}return`${a}
541
- ${n}`}function hi(t,e){let n=["serve","--agent","/app/pack","--workspace","/state/workspace","--state-dir","/state","--port",String(e?.port??t.port)],r=t.engine?.trim().toLowerCase();r&&!["claude","codex"].includes(r)&&n.push("--engine",r);let s=t.model?.trim();return s&&n.push("--model",s),e?.wwwDir&&n.push("--www-dir",e.wwwDir),n}var QD=new Set([".json",".yaml",".yml",".md",".env",".example",".txt",".mcp"]),ZD=new Set(["node_modules",".git","deploy",".agent-hippo","dist","out"]);Q.DEFAULT_DEPLOY_PUBLIC_HOSTNAME="auth.agenthippo.ai";Q.DEPLOY_PUBLIC_HOSTNAME=Q.DEFAULT_DEPLOY_PUBLIC_HOSTNAME;Q.AGENTHIPPO_CLI_NPM_PACKAGE="@agenthippo-ai/agenthippo";Q.AGENTHIPPO_CLI_NPM_VERSION_FALLBACK="latest";function ay(){try{let t=qo.join(__dirname,"..","..","..","..","package.json");if(Xc.existsSync(t)){let n=JSON.parse(Xc.readFileSync(t,"utf8")).version?.trim();if(n)return n}}catch{}return Q.AGENTHIPPO_CLI_NPM_VERSION_FALLBACK}function hf(t){return t?.trim()||Q.DEFAULT_DEPLOY_PUBLIC_HOSTNAME}function e0(t){let e=new Set,n=/\$\{env:([A-Za-z_][A-Za-z0-9_]*)\}/g,r=s=>{let i;try{i=Xc.readdirSync(s,{withFileTypes:!0})}catch{return}for(let o of i){let a=qo.join(s,o.name);if(o.isDirectory()){ZD.has(o.name)||r(a);continue}let c=qo.extname(o.name).toLowerCase();if(!QD.has(c))continue;let l;try{l=Xc.readFileSync(a,"utf8")}catch{continue}for(let f of l.matchAll(n))e.add(f[1])}};return r(t),[...e].sort()}function cy(t,e){let n=e?.engine?.trim().toLowerCase()==="cursor",r=hf(e?.hostname),s=["# Generated by `agenthippo deploy init`. Copy to .env and fill in."];if(n?s.push("# Cursor engine (pack default model: auto):","CURSOR_API_KEY= # https://cursor.com/settings \u2192 API keys"):e?.gatewayDirect?s.push("# Gateway-direct routing (agent \u2192 gateway.agenthippo.ai \u2014 no in-pod LiteLLM sidecar):","AGENTHIPPO_LITELLM_BASE_URL=https://gateway.agenthippo.ai/v1","AGENTHIPPO_LITELLM_API_KEY= # ahgw_\u2026 from create-gateway-key on the gateway host"):s.push("# Model credential \u2014 pick ONE path (serve-v3 \xA710.2):","# AgentHippo hosted gateway (colocated agents / CI \u2014 long-lived service key):","# AGENTHIPPO_LITELLM_BASE_URL=https://gateway.agenthippo.ai/v1","# AGENTHIPPO_LITELLM_API_KEY=ahgw_\u2026 # bun run create-gateway-key on gateway host","# Direct Anthropic:","ANTHROPIC_API_KEY=","# CLAUDE_CODE_USE_BEDROCK=1 # existing AWS Bedrock entitlement (no new key)","# CLAUDE_CODE_USE_VERTEX=1 # existing GCP Vertex entitlement (no new key)"),t.length>0){s.push("","# Pack-referenced secrets (scanned from ${env:...}):");for(let i of t)s.push(`${i}=`)}return e?.edge&&s.push("","# Public hostname \u2014 set once; Caddyfile reads {$AGENTHIPPO_PUBLIC_HOSTNAME}.",`AGENTHIPPO_PUBLIC_HOSTNAME=${r}`,"","# Multi-replica (serve-v4 P1): sticky by X-Agent-User in Caddyfile.","# docker compose up --scale agent=N","# AGENTHIPPO_STATE_S3_URI=s3://bucket/prefix # S3-compatible (MinIO/R2/GCS/AWS)","# AGENTHIPPO_STATE_S3_ENDPOINT= # optional, e.g. http://minio:9000","# AGENTHIPPO_STATE_RESTORE_BOOT=none # restore-on-miss (required when N>1)","# Scale-down: drain (/ready inflight=0) then remove replica \u2014 see serve-v3-RUNBOOK.","","# Edge auth secrets (JWT signing key, Google OAuth client/cookie) live in .env.auth,","# which is loaded ONLY by the auth-broker and oauth2-proxy services \u2014 never the agent.","# Keeping the token-signing key out of the agent container limits blast radius if the","# agent (which runs model-driven tool calls) is compromised. Copy .env.auth.example.","","# Cloudflare Tunnel (free \u2014 no Access seats), config-file mode in compose:","# cloudflared tunnel create <name> \u2192 save the JSON as deploy/tunnel-credentials.json (gitignored)","# set the tunnel id in deploy/cloudflared.yml; cloudflared tunnel route dns <name> <hostname>","# No token/env needed \u2014 the credentials JSON is mounted into the cloudflared container."),s.join(`
541
+ ${n}`}function hi(t,e){let n=["serve","--agent","/app/pack","--workspace","/state/workspace","--state-dir","/state","--port",String(e?.port??t.port)],r=t.engine?.trim().toLowerCase();r&&!["claude","codex"].includes(r)&&n.push("--engine",r);let s=t.model?.trim();return s&&n.push("--model",s),e?.wwwDir&&n.push("--www-dir",e.wwwDir),n}var n0=new Set([".json",".yaml",".yml",".md",".env",".example",".txt",".mcp"]),r0=new Set(["node_modules",".git","deploy",".agent-hippo","dist","out"]);q.DEFAULT_DEPLOY_PUBLIC_HOSTNAME="auth.agenthippo.ai";q.DEPLOY_PUBLIC_HOSTNAME=q.DEFAULT_DEPLOY_PUBLIC_HOSTNAME;function mf(t){return t?.trim()||q.DEFAULT_DEPLOY_PUBLIC_HOSTNAME}function s0(t){let e=new Set,n=/\$\{env:([A-Za-z_][A-Za-z0-9_]*)\}/g,r=s=>{let i;try{i=qi.readdirSync(s,{withFileTypes:!0})}catch{return}for(let o of i){let a=Yi.join(s,o.name);if(o.isDirectory()){r0.has(o.name)||r(a);continue}let c=Yi.extname(o.name).toLowerCase();if(!n0.has(c))continue;let l;try{l=qi.readFileSync(a,"utf8")}catch{continue}for(let f of l.matchAll(n))e.add(f[1])}};return r(t),[...e].sort()}function dy(t,e){let n=e?.engine?.trim().toLowerCase()==="cursor",r=mf(e?.hostname),s=["# Generated by `agenthippo deploy init`. Copy to .env and fill in."];if(n?s.push("# Cursor engine (pack default model: auto):","CURSOR_API_KEY= # https://cursor.com/settings \u2192 API keys"):e?.gatewayDirect?s.push("# Gateway-direct routing (agent \u2192 gateway.agenthippo.ai \u2014 no in-pod LiteLLM sidecar):","AGENTHIPPO_LITELLM_BASE_URL=https://gateway.agenthippo.ai/v1","AGENTHIPPO_LITELLM_API_KEY= # ahgw_\u2026 from create-gateway-key on the gateway host"):s.push("# Model credential \u2014 pick ONE path (serve-v3 \xA710.2):","# AgentHippo hosted gateway (colocated agents / CI \u2014 long-lived service key):","# AGENTHIPPO_LITELLM_BASE_URL=https://gateway.agenthippo.ai/v1","# AGENTHIPPO_LITELLM_API_KEY=ahgw_\u2026 # bun run create-gateway-key on gateway host","# Direct Anthropic:","ANTHROPIC_API_KEY=","# CLAUDE_CODE_USE_BEDROCK=1 # existing AWS Bedrock entitlement (no new key)","# CLAUDE_CODE_USE_VERTEX=1 # existing GCP Vertex entitlement (no new key)"),t.length>0){s.push("","# Pack-referenced secrets (scanned from ${env:...}):");for(let i of t)s.push(`${i}=`)}return e?.edge&&s.push("","# Public hostname \u2014 set once; Caddyfile reads {$AGENTHIPPO_PUBLIC_HOSTNAME}.",`AGENTHIPPO_PUBLIC_HOSTNAME=${r}`,"","# Multi-replica (serve-v4 P1): sticky by X-Agent-User in Caddyfile.","# docker compose up --scale agent=N","# AGENTHIPPO_STATE_S3_URI=s3://bucket/prefix # S3-compatible (MinIO/R2/GCS/AWS)","# AGENTHIPPO_STATE_S3_ENDPOINT= # optional, e.g. http://minio:9000","# AGENTHIPPO_STATE_RESTORE_BOOT=none # restore-on-miss (required when N>1)","# Scale-down: drain (/ready inflight=0) then remove replica \u2014 see serve-v3-RUNBOOK.","","# Edge auth secrets (JWT signing key, Google OAuth client/cookie) live in .env.auth,","# which is loaded ONLY by the auth-broker and oauth2-proxy services \u2014 never the agent.","# Keeping the token-signing key out of the agent container limits blast radius if the","# agent (which runs model-driven tool calls) is compromised. Copy .env.auth.example.","","# Cloudflare Tunnel (free \u2014 no Access seats), config-file mode in compose:","# cloudflared tunnel create <name> \u2192 save the JSON as deploy/tunnel-credentials.json (gitignored)","# set the tunnel id in deploy/cloudflared.yml; cloudflared tunnel route dns <name> <hostname>","# No token/env needed \u2014 the credentials JSON is mounted into the cloudflared container."),s.join(`
542
542
  `)+`
543
- `}function ly(t){let e=hf(t?.hostname);if(t?.fed){let r=(t.idpUrl||"https://auth.agenthippo.ai").replace(/\/+$/,""),s=t.cookieDomain||".agenthippo.ai";return["# Generated by `agenthippo deploy init --ingress edge-fed`. Copy to .env.auth and fill in.","# Federated edge (A\u2032): NO Google OAuth client here. Google login happens once at the",`# central IdP (${r}); this agent only VERIFIES the shared ${s} AgentHippo JWT.`,"# Loaded only by auth-broker. Never given to the agent (limits token-forgery blast radius).","","# AgentHippo JWT signing key \u2014 MUST match the central IdP (auth.agenthippo.ai).","# Copy it from there (or the GCP secret it stores) so tokens issued by the IdP verify here.","AGENTHIPPO_AUTH_JWT_SECRET= # copy from auth.agenthippo.ai (openssl rand -hex 32 to generate one)",`AGENTHIPPO_AUTH_PUBLIC_URL=https://${e}`,"AGENTHIPPO_AUTH_ALLOWED_DOMAINS=agenthippo.ai","AGENTHIPPO_AUTH_DEV=0 # 1 enables /oauth/dev/login (tests only; never in production)",`AGENTHIPPO_AUTH_COOKIE_DOMAIN=${s} # scope the shared cookie to all subdomains`,`AGENTHIPPO_AUTH_IDP_URL=${r} # where browsers are sent to log in`,"AGENTHIPPO_AUTH_COOKIE_NAME=ah_token","","# Team bootstrap (store + gateway routing) \u2014 same as the IdP if you want parity.","AGENTHIPPO_TEAM_ID=team_default","AGENTHIPPO_TEAM_NAME=Default Team","AGENTHIPPO_TEAM_STORE_REPO=agenthippoai/agenthippo-store","AGENTHIPPO_TEAM_STORE_INDEX_URL=https://agenthippoai.github.io/agenthippo-store","AGENTHIPPO_TEAM_GITHUB_ORG=agenthippoai","# An agenthippo-gateway deployment (JWT lane) \u2014 NOT bare LiteLLM. No key: the account","# JWT is the routing credential.","AGENTHIPPO_TEAM_GATEWAY_URL=https://gateway.agenthippo.ai/v1","","# No OAUTH2_PROXY_* here \u2014 this agent does not talk to Google. The one oauth2-proxy +","# one Google OAuth client live only at the IdP."].join(`
543
+ `}function fy(t){let e=mf(t?.hostname);if(t?.fed){let r=(t.idpUrl||"https://auth.agenthippo.ai").replace(/\/+$/,""),s=t.cookieDomain||".agenthippo.ai";return["# Generated by `agenthippo deploy init --ingress edge-fed`. Copy to .env.auth and fill in.","# Federated edge (A\u2032): NO Google OAuth client here. Google login happens once at the",`# central IdP (${r}); this agent only VERIFIES the shared ${s} AgentHippo JWT.`,"# Loaded only by auth-broker. Never given to the agent (limits token-forgery blast radius).","","# AgentHippo JWT signing key \u2014 MUST match the central IdP (auth.agenthippo.ai).","# Copy it from there (or the GCP secret it stores) so tokens issued by the IdP verify here.","AGENTHIPPO_AUTH_JWT_SECRET= # copy from auth.agenthippo.ai (openssl rand -hex 32 to generate one)",`AGENTHIPPO_AUTH_PUBLIC_URL=https://${e}`,"AGENTHIPPO_AUTH_ALLOWED_DOMAINS=agenthippo.ai","AGENTHIPPO_AUTH_DEV=0 # 1 enables /oauth/dev/login (tests only; never in production)",`AGENTHIPPO_AUTH_COOKIE_DOMAIN=${s} # scope the shared cookie to all subdomains`,`AGENTHIPPO_AUTH_IDP_URL=${r} # where browsers are sent to log in`,"AGENTHIPPO_AUTH_COOKIE_NAME=ah_token","","# Team bootstrap (store + gateway routing) \u2014 same as the IdP if you want parity.","AGENTHIPPO_TEAM_ID=team_default","AGENTHIPPO_TEAM_NAME=Default Team","AGENTHIPPO_TEAM_STORE_REPO=agenthippoai/agenthippo-store","AGENTHIPPO_TEAM_STORE_INDEX_URL=https://agenthippoai.github.io/agenthippo-store","AGENTHIPPO_TEAM_GITHUB_ORG=agenthippoai","# An agenthippo-gateway deployment (JWT lane) \u2014 NOT bare LiteLLM. No key: the account","# JWT is the routing credential.","AGENTHIPPO_TEAM_GATEWAY_URL=https://gateway.agenthippo.ai/v1","","# No OAUTH2_PROXY_* here \u2014 this agent does not talk to Google. The one oauth2-proxy +","# one Google OAuth client live only at the IdP."].join(`
544
544
  `)+`
545
545
  `}let n=t?.cookieDomain||".agenthippo.ai";return["# Generated by `agenthippo deploy init`. Copy to .env.auth and fill in.","# Loaded only by auth-broker + oauth2-proxy (docker-compose.yml). Never given to the agent.","","# Google SSO (oauth2-proxy). GCP \u2192 OAuth client (Web):",`# Authorized origins: https://${e}`,`# Redirect URI: https://${e}/oauth2/callback`,"OAUTH2_PROXY_CLIENT_ID=","OAUTH2_PROXY_CLIENT_SECRET=","OAUTH2_PROXY_COOKIE_SECRET= # openssl rand -base64 32 | head -c 32","OAUTH2_PROXY_PROVIDER=google","OAUTH2_PROXY_EMAIL_DOMAINS=example.com","OAUTH2_PROXY_REVERSE_PROXY=true",`OAUTH2_PROXY_REDIRECT_URL=https://${e}/oauth2/callback`,"# Federated SSO (A\u2032) \u2014 set when this edge is the central IdP for a fleet of agents:",`OAUTH2_PROXY_COOKIE_DOMAINS=${n} # scope the oauth2-proxy session cookie to all subdomains`,"","# IDE auth broker (team bootstrap for store + LiteLLM routing)","AGENTHIPPO_AUTH_JWT_SECRET= # openssl rand -hex 32","AGENTHIPPO_AUTH_PUBLIC_URL=https://"+e,"AGENTHIPPO_AUTH_ALLOWED_DOMAINS=example.com","AGENTHIPPO_AUTH_DEV=0 # 1 enables /oauth/dev/login (tests only; never in production)","AGENTHIPPO_AUTH_COOKIE_NAME=ah_token # federated cookie holding the AgentHippo JWT",`AGENTHIPPO_AUTH_COOKIE_DOMAIN=${n} # set so /oauth/browser-login stamps a cross-subdomain cookie`,"AGENTHIPPO_TEAM_ID=team_default","AGENTHIPPO_TEAM_NAME=Default Team","AGENTHIPPO_TEAM_STORE_REPO=agenthippoai/agenthippo-store","AGENTHIPPO_TEAM_STORE_INDEX_URL=https://agenthippoai.github.io/agenthippo-store","AGENTHIPPO_TEAM_GITHUB_ORG=agenthippoai","# An agenthippo-gateway deployment (JWT lane) \u2014 NOT bare LiteLLM. No key: the account","# JWT is the routing credential.","AGENTHIPPO_TEAM_GATEWAY_URL=https://gateway.agenthippo.ai/v1"].join(`
546
546
  `)+`
547
- `}function mf(){return["# Auth broker for IDE sign-in + team bootstrap API.","# Build context = pack root: docker build -f deploy/Dockerfile.auth-broker -t <pack>-auth-broker:local .",`FROM ${Kr("runtime")}`,"ENV AGENTHIPPO_AUTH_PORT=9780","ENV AGENTHIPPO_AUTH_DATA_DIR=/data","EXPOSE 9780",'VOLUME ["/data"]','CMD ["auth-broker"]',""].join(`
548
- `)}function t0(t){return!!(/credentials/i.test(t)||/\.(pem|key|p12|pfx|jks|gpg|pgp)$/i.test(t)||/^id_(rsa|dsa|ecdsa|ed25519)$/i.test(t))}function n0(){return["# Generated by `agenthippo deploy init`. Keeps skills/, references/, scripts/","# (needed at runtime) and drops only VCS/cache/build cruft. node_modules is","# excluded so the Dockerfile reinstalls fresh linux/amd64 deps for skills.",".git",".gitignore",".gitattributes","**/node_modules","**/__pycache__","**/.pytest_cache","**/.mypy_cache","**/.ruff_cache","**/.venv","**/venv","**/*.log","**/dist","**/build","**/.next","**/.turbo","**/.cache",".DS_Store","**/.DS_Store",".idea",".vscode","*.swp","# Secrets anywhere in the pack (defensive; deploy/ secrets are also covered below).","# Keep in sync with isSecretLikeBasename() above.","**/.env","**/.env.*","**/*credentials*","**/*.pem","**/*.key","**/*.p12","**/*.pfx","**/*.jks","**/*.gpg","**/*.pgp","**/id_rsa","**/id_dsa","**/id_ecdsa","**/id_ed25519","# \u2026but *.example templates are safe and are what the README tells customers to copy.","!**/.env.example","!**/.env.*.example","# deploy/ holds build/deploy artifacts + secrets; only deploy/www/ ships at runtime.","deploy/*","!deploy/www","!deploy/www/**",""].join(`
549
- `)}function r0(){return["# Skill dependencies \u2014 installed at BUILD time so skills that ship their own","# requirements.txt / package.json have their libs present at runtime","# (AGENTHIPPO_NO_AUTO_INSTALL=1 skips runtime installs). No-op when none exist.","USER root","RUN set -e; \\",' py_reqs=$(find /app/pack/skills /app/pack/scripts -type f -name requirements.txt -not -path "*/node_modules/*" 2>/dev/null || true); \\',' if [ -n "$py_reqs" ]; then \\'," pip3 --version 2>/dev/null || (apt-get update && apt-get install -y --no-install-recommends python3-pip && rm -rf /var/lib/apt/lists/*); \\",' echo "$py_reqs" | while IFS= read -r f; do [ -n "$f" ] && pip3 install --no-cache-dir --break-system-packages -r "$f" || true; done; \\'," fi; \\",' pkg_json=$(find /app/pack/skills /app/pack/scripts -type f -name package.json -not -path "*/node_modules/*" 2>/dev/null || true); \\',' if [ -n "$pkg_json" ]; then \\',' echo "$pkg_json" | while IFS= read -r f; do [ -n "$f" ] && (cd "$(dirname "$f")" && npm install --omit=dev --no-audit --no-fund || true) || true; done; \\'," fi","USER agent"]}function zc(t=" "){return`${t}- { name: ${Jc.SERVE_HOST_ENV}, value: ${Jc.CONTAINER_SERVE_HOST} }`}function Cn(t,e){let n=hi(t,e).map(r=>`"${r}"`).join(",");return[`${gf(t)}. Build context = pack root:`,`# docker build -f deploy/Dockerfile -t ${t.packName}:local .`,`FROM ${t.image}`,`LABEL ai.agenthippo.pack.name="${t.packName}"`,`LABEL ai.agenthippo.pack.version="${t.packVersion}"`,`LABEL ai.agenthippo.pack.engine="${t.engine}"`,"COPY . /app/pack/",...r0(),"ENV AGENTHIPPO_NO_AUTO_INSTALL=1",`ENV ${Jc.SERVE_HOST_ENV}=${Jc.CONTAINER_SERVE_HOST}`,...Object.entries(e?.extraEnv??{}).map(([r,s])=>`ENV ${r}=${s}`),`EXPOSE ${t.port}`,`CMD [${n}]`,""].join(`
547
+ `}function Ef(){return["# Auth broker for IDE sign-in + team bootstrap API.","# Build context = pack root: docker build -f deploy/Dockerfile.auth-broker -t <pack>-auth-broker:local .",`FROM ${ys("runtime")}`,"ENV AGENTHIPPO_AUTH_PORT=9780","ENV AGENTHIPPO_AUTH_DATA_DIR=/data","EXPOSE 9780",'VOLUME ["/data"]','CMD ["auth-broker"]',""].join(`
548
+ `)}function py(){return["# Agent Anywhere channels gateway \u2014 built from this pack, not pulled from GHCR.",`# Pins ${q.AGENTHIPPO_HIPPOCLAW_NPM} (same pin as the IDE installSource default).`,"# node:22-alpine: HippoClaw requires Node 22+; apk git is needed for the npm install.","# Avoid Debian slim+apt-get (GPG failures on some Docker Desktop hosts) and full node:22 (huge).","FROM node:22-alpine","RUN apk add --no-cache git",`RUN npm i -g ${q.AGENTHIPPO_HIPPOCLAW_NPM}`,"EXPOSE 18789",'ENTRYPOINT ["openclaw"]','CMD ["gateway"]',""].join(`
549
+ `)}function i0(t){return!!(/credentials/i.test(t)||/\.(pem|key|p12|pfx|jks|gpg|pgp)$/i.test(t)||/^id_(rsa|dsa|ecdsa|ed25519)$/i.test(t))}function o0(){return["# Generated by `agenthippo deploy init`. Keeps skills/, references/, scripts/","# (needed at runtime) and drops only VCS/cache/build cruft. node_modules is","# excluded so the Dockerfile reinstalls fresh linux/amd64 deps for skills.",".git",".gitignore",".gitattributes","**/node_modules","**/__pycache__","**/.pytest_cache","**/.mypy_cache","**/.ruff_cache","**/.venv","**/venv","**/*.log","**/dist","**/build","**/.next","**/.turbo","**/.cache",".DS_Store","**/.DS_Store",".idea",".vscode","*.swp","# Secrets anywhere in the pack (defensive; deploy/ secrets are also covered below).","# Keep in sync with isSecretLikeBasename() above.","**/.env","**/.env.*","**/*credentials*","**/*.pem","**/*.key","**/*.p12","**/*.pfx","**/*.jks","**/*.gpg","**/*.pgp","**/id_rsa","**/id_dsa","**/id_ecdsa","**/id_ed25519","# \u2026but *.example templates are safe and are what the README tells customers to copy.","!**/.env.example","!**/.env.*.example","# deploy/ holds build/deploy artifacts + secrets; only deploy/www/ ships at runtime.","deploy/*","!deploy/www","!deploy/www/**",""].join(`
550
+ `)}function a0(){return["# Skill dependencies \u2014 installed at BUILD time so skills that ship their own","# requirements.txt / package.json have their libs present at runtime","# (AGENTHIPPO_NO_AUTO_INSTALL=1 skips runtime installs). No-op when none exist.","USER root","RUN set -e; \\",' py_reqs=$(find /app/pack/skills /app/pack/scripts -type f -name requirements.txt -not -path "*/node_modules/*" 2>/dev/null || true); \\',' if [ -n "$py_reqs" ]; then \\'," pip3 --version 2>/dev/null || (apt-get update && apt-get install -y --no-install-recommends python3-pip && rm -rf /var/lib/apt/lists/*); \\",' echo "$py_reqs" | while IFS= read -r f; do [ -n "$f" ] && pip3 install --no-cache-dir --break-system-packages -r "$f" || true; done; \\'," fi; \\",' pkg_json=$(find /app/pack/skills /app/pack/scripts -type f -name package.json -not -path "*/node_modules/*" 2>/dev/null || true); \\',' if [ -n "$pkg_json" ]; then \\',' echo "$pkg_json" | while IFS= read -r f; do [ -n "$f" ] && (cd "$(dirname "$f")" && npm install --omit=dev --no-audit --no-fund || true) || true; done; \\'," fi","USER agent"]}function Qc(t=" "){return`${t}- { name: ${zc.SERVE_HOST_ENV}, value: ${zc.CONTAINER_SERVE_HOST} }`}function Cn(t,e){let n=hi(t,e).map(r=>`"${r}"`).join(",");return[`${hf(t)}. Build context = pack root:`,`# docker build -f deploy/Dockerfile -t ${t.packName}:local .`,`FROM ${t.image}`,`LABEL ai.agenthippo.pack.name="${t.packName}"`,`LABEL ai.agenthippo.pack.version="${t.packVersion}"`,`LABEL ai.agenthippo.pack.engine="${t.engine}"`,"COPY . /app/pack/",...a0(),"ENV AGENTHIPPO_NO_AUTO_INSTALL=1",`ENV ${zc.SERVE_HOST_ENV}=${zc.CONTAINER_SERVE_HOST}`,...Object.entries(e?.extraEnv??{}).map(([r,s])=>`ENV ${r}=${s}`),`EXPOSE ${t.port}`,`CMD [${n}]`,""].join(`
550
551
  `)}function ws(t){return["<!DOCTYPE html>",'<html lang="en">',"<head>",' <meta charset="utf-8" />',' <meta name="viewport" content="width=device-width, initial-scale=1" />',` <title>${t}</title>`," <style>"," :root { color-scheme: light dark; font-family: system-ui, sans-serif; }"," body { max-width: 720px; margin: 2rem auto; padding: 0 1rem; line-height: 1.5; }"," h1 { font-size: 1.4rem; margin-bottom: 0.25rem; }"," .sub { opacity: 0.7; font-size: 0.9rem; margin-bottom: 1.5rem; }"," #log { border: 1px solid #8884; border-radius: 8px; min-height: 200px; padding: 1rem; white-space: pre-wrap; margin-bottom: 1rem; }"," form { display: flex; gap: 0.5rem; }"," input[type=text] { flex: 1; padding: 0.6rem 0.75rem; border-radius: 6px; border: 1px solid #8886; font: inherit; }"," button { padding: 0.6rem 1rem; border-radius: 6px; border: 0; background: #2563eb; color: #fff; font: inherit; cursor: pointer; }"," button:disabled { opacity: 0.6; cursor: wait; }"," </style>","</head>","<body>",` <h1>${t}</h1>`,' <p class="sub">Signed in via Google SSO. Chat uses the agent API behind this page.</p>',' <div id="log">Ready. Send a message below.</div>',' <form id="chat">',' <input id="msg" type="text" placeholder="Ask the agent\u2026" autocomplete="off" required />',' <button type="submit">Send</button>'," </form>"," <script>",' const log = document.getElementById("log");',' const form = document.getElementById("chat");',' const input = document.getElementById("msg");'," // Stable per-browser session id so turns resume the same conversation (multi-turn).",' const sessionId = (self.crypto && crypto.randomUUID) ? crypto.randomUUID() : ("web-" + Date.now().toString(36) + Math.random().toString(36).slice(2));'," function append(text) {",' log.textContent += (log.textContent.endsWith("\\n") || log.textContent === "Ready. Send a message below." ? "" : "\\n") + text;'," }",' form.addEventListener("submit", async (e) => {'," e.preventDefault();"," const message = input.value.trim();"," if (!message) return;",' input.value = "";',' form.querySelector("button").disabled = true;',' append("\\nYou: " + message + "\\nAgent: ");'," try {"," const body = { message, session_id: sessionId };",' const res = await fetch("/v1/chat", {',' method: "POST",',' headers: { "Content-Type": "application/json" },'," body: JSON.stringify(body),"," });"," const data = await res.json();"," if (!res.ok) throw new Error(data.error || res.statusText);"," append(data.text || data.response || JSON.stringify(data));"," } catch (err) {",' append("[error] " + (err.message || err));'," } finally {",' form.querySelector("button").disabled = false;'," input.focus();"," }"," });"," input.focus();"," </script>","</body>","</html>",""].join(`
551
- `)}function Ko(t,e=" "){return[`${e}# serve-v4 P1.1: sticky by user identity (not session body \u2014 edge can't hash POST).`,`${e}# In-process RateLimiter is globally correct per user under this policy.`,`${e}reverse_proxy agent:${t} {`,`${e} lb_policy header X-Agent-User {`,`${e} fallback ip_hash`,`${e} }`,`${e}}`]}function uy(t){let e=t.ingress==="edge-fed",n=(t.idpUrl||"").trim().replace(/\/+$/,""),r=[" @api path /v1/*"," handle @api {",...Ko(t.port," ")," }"," root * /srv/www"," file_server"];return["# SSO edge + Cloudflare Tunnel. Set AGENTHIPPO_PUBLIC_HOSTNAME in .env (Caddy reads it below).","# TLS terminates at Cloudflare; origin listens on HTTP only.",...e?[`# No oauth2-proxy \u2014 Google login happens once at the central IdP (${n||"<IDP_URL>"});`,"# this agent only verifies the shared AgentHippo JWT (Bearer for IDE, cookie for browser)."]:[],"{"," auto_https off","}","","http://{$AGENTHIPPO_PUBLIC_HOSTNAME} {",...e?(0,ot.renderIdentityLayer)({mode:"federated",authBrokerAddr:"auth-broker:9780",idpUrl:n,healthProxy:Ko(t.port," "),agentProxy:Ko(t.port," "),catchallBody:r}):(0,ot.renderIdentityLayer)({mode:"self-issued",oauth2ProxyAddr:"oauth2-proxy:4180",authBrokerAddr:"auth-broker:9780",healthProxy:Ko(t.port," "),agentProxy:Ko(t.port," "),catchallBody:r}),"}",""].join(`
552
- `)}function dy(t){return["# Cloudflare Tunnel \u2014 run as the compose `cloudflared` service (config-file mode).","# One-time setup:","# cloudflared tunnel create <name> # creates the tunnel + a credentials JSON","# cp <that-creds>.json deploy/tunnel-credentials.json # mounted into the container (gitignore it!)",`# cloudflared tunnel route dns <name> ${t}`,"# set the tunnel id below, then: docker compose --profile edge --profile tunnel up -d","tunnel: <TUNNEL_ID>","credentials-file: /etc/cloudflared/credentials.json # mounted from deploy/tunnel-credentials.json","ingress:",` - hostname: ${t} # must match AGENTHIPPO_PUBLIC_HOSTNAME in .env`," service: http://caddy:80 # cloudflared container \u2192 Caddy over the compose network"," - service: http_status:404",""].join(`
553
- `)}function fy(t,e=[]){return[" agent:"," build:"," context: .."," dockerfile: deploy/Dockerfile"," env_file:"," - path: .env"," required: false",...e,' volumes: ["agenthippo-state:/state"]',` expose: ["${t.port}"]`," # No host port \u2014 edge reaches agent on the Docker network only."," # T0.5a VPN: bash deploy/run.sh binds 127.0.0.1:"+t.port+" via docker run -p.",""]}function py(t){return[...t?[]:[" oauth2-proxy:",' profiles: ["edge"]'," image: quay.io/oauth2-proxy/oauth2-proxy:v7.7.1"," env_file:"," - path: .env"," required: false"," - path: .env.auth # OAuth client/cookie secrets \u2014 not shared with the agent"," required: false"," environment:"," OAUTH2_PROXY_HTTP_ADDRESS: 0.0.0.0:4180"," OAUTH2_PROXY_UPSTREAMS: file:///dev/null",' OAUTH2_PROXY_SET_XAUTHREQUEST: "true"',' OAUTH2_PROXY_PASS_AUTHORIZATION_HEADER: "true"',' OAUTH2_PROXY_SKIP_PROVIDER_BUTTON: "true"',' OAUTH2_PROXY_REVERSE_PROXY: "true"',' expose: ["4180"]',""]," auth-broker:",' profiles: ["edge"]'," build:"," context: .."," dockerfile: deploy/Dockerfile.auth-broker"," env_file:"," - path: .env"," required: false"," - path: .env.auth # JWT signing key + team config \u2014 not shared with the agent"," required: false"," environment:",' AGENTHIPPO_AUTH_PORT: "9780"'," AGENTHIPPO_AUTH_DATA_DIR: /data",' user: "0:0" # named volume /data is root-owned on first create',' volumes: ["auth-broker-data:/data"]',' expose: ["9780"]',""," caddy:",' profiles: ["edge"]'," image: caddy:2.8-alpine"," env_file:"," - path: .env"," required: false",' ports: ["80:80", "443:443"] # use 80:80 not 127.0.0.1:80 \u2014 breaks vmnetd on some Docker Desktop builds',' volumes: ["./Caddyfile:/etc/caddy/Caddyfile:ro", "./www:/srv/www:ro"]',` depends_on: [${t?"agent, auth-broker":"oauth2-proxy, agent, auth-broker"}]`,""]}function gy(){return[" cloudflared:",' profiles: ["tunnel"]'," image: cloudflare/cloudflared:2024.12.2"," restart: unless-stopped"," # Config-file mode: routing lives in deploy/cloudflared.yml (GitOps), credentials"," # in deploy/tunnel-credentials.json (gitignored secret from `cloudflared tunnel create`)."," command: tunnel --config /etc/cloudflared/config.yml run"," volumes:"," - ./cloudflared.yml:/etc/cloudflared/config.yml:ro"," - ./tunnel-credentials.json:/etc/cloudflared/credentials.json:ro"," depends_on: [caddy]",""]}function hy(t){return["#!/usr/bin/env bash","# T0.5b \u2014 Cloudflare Tunnel + Google SSO (no Access seats). Run: bash deploy/run-edge-tunnel.sh","set -euo pipefail",'cd "$(dirname "$0")"',"docker compose --profile edge --profile tunnel up -d --build",'echo "Public URL: https://'+t+' (after DNS + tunnel route configured)"',""].join(`
554
- `)}function my(t){return t.toUpperCase().replace(/[^A-Z0-9]/g,"_")+"_DATA_PLANE_TOKEN"}function Ey(t){let e=(t.idpUrl||"").trim().replace(/\/+$/,""),n=`${t.packName}-agent`,r=my(t.packName),s=["# Colocated agent \u2014 no Caddy/oauth2-proxy/auth-broker of its","# own. Joins the org IdP's docker network so its already-running Caddy can reach this","# agent by name; identity is verified entirely by the IdP's auth-broker (see","# deploy/agent-route.caddy for the route to copy onto the IdP host).",`name: ${t.packName}`,"services:"," agent:",` container_name: ${n}`," build:"," context: .."," dockerfile: deploy/Dockerfile"," env_file:"," - path: .env"," required: false",' volumes: ["agenthippo-state:/state"]'," networks: [colocate]",` expose: ["${t.port}"]`,"","networks:"," colocate:"," external: true"," name: ${AGENTHIPPO_IDP_NETWORK:-agenthippo-idp-colocate}","","volumes:"," agenthippo-state:",""].join(`
552
+ `)}function Yo(t,e=" "){return[`${e}# serve-v4 P1.1: sticky by user identity (not session body \u2014 edge can't hash POST).`,`${e}# In-process RateLimiter is globally correct per user under this policy.`,`${e}reverse_proxy agent:${t} {`,`${e} lb_policy header X-Agent-User {`,`${e} fallback ip_hash`,`${e} }`,`${e}}`]}function gy(t){let e=t.ingress==="edge-fed",n=(t.idpUrl||"").trim().replace(/\/+$/,""),r=[" @api path /v1/*"," handle @api {",...Yo(t.port," ")," }"," root * /srv/www"," file_server"];return["# SSO edge + Cloudflare Tunnel. Set AGENTHIPPO_PUBLIC_HOSTNAME in .env (Caddy reads it below).","# TLS terminates at Cloudflare; origin listens on HTTP only.",...e?[`# No oauth2-proxy \u2014 Google login happens once at the central IdP (${n||"<IDP_URL>"});`,"# this agent only verifies the shared AgentHippo JWT (Bearer for IDE, cookie for browser)."]:[],"{"," auto_https off","}","","http://{$AGENTHIPPO_PUBLIC_HOSTNAME} {",...e?(0,ot.renderIdentityLayer)({mode:"federated",authBrokerAddr:"auth-broker:9780",idpUrl:n,healthProxy:Yo(t.port," "),agentProxy:Yo(t.port," "),catchallBody:r}):(0,ot.renderIdentityLayer)({mode:"self-issued",oauth2ProxyAddr:"oauth2-proxy:4180",authBrokerAddr:"auth-broker:9780",healthProxy:Yo(t.port," "),agentProxy:Yo(t.port," "),catchallBody:r}),"}",""].join(`
553
+ `)}function hy(t){return["# Cloudflare Tunnel \u2014 run as the compose `cloudflared` service (config-file mode).","# One-time setup:","# cloudflared tunnel create <name> # creates the tunnel + a credentials JSON","# cp <that-creds>.json deploy/tunnel-credentials.json # mounted into the container (gitignore it!)",`# cloudflared tunnel route dns <name> ${t}`,"# set the tunnel id below, then: docker compose --profile edge --profile tunnel up -d","tunnel: <TUNNEL_ID>","credentials-file: /etc/cloudflared/credentials.json # mounted from deploy/tunnel-credentials.json","ingress:",` - hostname: ${t} # must match AGENTHIPPO_PUBLIC_HOSTNAME in .env`," service: http://caddy:80 # cloudflared container \u2192 Caddy over the compose network"," - service: http_status:404",""].join(`
554
+ `)}function my(t,e=[]){return[" agent:"," build:"," context: .."," dockerfile: deploy/Dockerfile"," env_file:"," - path: .env"," required: false",...e,' volumes: ["agenthippo-state:/state"]',` expose: ["${t.port}"]`," # No host port \u2014 edge reaches agent on the Docker network only."," # T0.5a VPN: bash deploy/run.sh binds 127.0.0.1:"+t.port+" via docker run -p.",""]}function Ey(t){return[...t?[]:[" oauth2-proxy:",' profiles: ["edge"]'," image: quay.io/oauth2-proxy/oauth2-proxy:v7.7.1"," env_file:"," - path: .env"," required: false"," - path: .env.auth # OAuth client/cookie secrets \u2014 not shared with the agent"," required: false"," environment:"," OAUTH2_PROXY_HTTP_ADDRESS: 0.0.0.0:4180"," OAUTH2_PROXY_UPSTREAMS: file:///dev/null",' OAUTH2_PROXY_SET_XAUTHREQUEST: "true"',' OAUTH2_PROXY_PASS_AUTHORIZATION_HEADER: "true"',' OAUTH2_PROXY_SKIP_PROVIDER_BUTTON: "true"',' OAUTH2_PROXY_REVERSE_PROXY: "true"',' expose: ["4180"]',""]," auth-broker:",' profiles: ["edge"]'," build:"," context: .."," dockerfile: deploy/Dockerfile.auth-broker"," env_file:"," - path: .env"," required: false"," - path: .env.auth # JWT signing key + team config \u2014 not shared with the agent"," required: false"," environment:",' AGENTHIPPO_AUTH_PORT: "9780"'," AGENTHIPPO_AUTH_DATA_DIR: /data",' user: "0:0" # named volume /data is root-owned on first create',' volumes: ["auth-broker-data:/data"]',' expose: ["9780"]',""," caddy:",' profiles: ["edge"]'," image: caddy:2.8-alpine"," env_file:"," - path: .env"," required: false",' ports: ["80:80", "443:443"] # use 80:80 not 127.0.0.1:80 \u2014 breaks vmnetd on some Docker Desktop builds',' volumes: ["./Caddyfile:/etc/caddy/Caddyfile:ro", "./www:/srv/www:ro"]',` depends_on: [${t?"agent, auth-broker":"oauth2-proxy, agent, auth-broker"}]`,""]}function _y(){return[" cloudflared:",' profiles: ["tunnel"]'," image: cloudflare/cloudflared:2024.12.2"," restart: unless-stopped"," # Config-file mode: routing lives in deploy/cloudflared.yml (GitOps), credentials"," # in deploy/tunnel-credentials.json (gitignored secret from `cloudflared tunnel create`)."," command: tunnel --config /etc/cloudflared/config.yml run"," volumes:"," - ./cloudflared.yml:/etc/cloudflared/config.yml:ro"," - ./tunnel-credentials.json:/etc/cloudflared/credentials.json:ro"," depends_on: [caddy]",""]}function yy(t){return["#!/usr/bin/env bash","# T0.5b \u2014 Cloudflare Tunnel + Google SSO (no Access seats). Run: bash deploy/run-edge-tunnel.sh","set -euo pipefail",'cd "$(dirname "$0")"',"docker compose --profile edge --profile tunnel up -d --build",'echo "Public URL: https://'+t+' (after DNS + tunnel route configured)"',""].join(`
555
+ `)}function wy(t){return t.toUpperCase().replace(/[^A-Z0-9]/g,"_")+"_DATA_PLANE_TOKEN"}function Ay(t){let e=(t.idpUrl||"").trim().replace(/\/+$/,""),n=`${t.packName}-agent`,r=wy(t.packName),s=["# Colocated agent \u2014 no Caddy/oauth2-proxy/auth-broker of its","# own. Joins the org IdP's docker network so its already-running Caddy can reach this","# agent by name; identity is verified entirely by the IdP's auth-broker (see","# deploy/agent-route.caddy for the route to copy onto the IdP host).",`name: ${t.packName}`,"services:"," agent:",` container_name: ${n}`," build:"," context: .."," dockerfile: deploy/Dockerfile"," env_file:"," - path: .env"," required: false",' volumes: ["agenthippo-state:/state"]'," networks: [colocate]",` expose: ["${t.port}"]`,"","networks:"," colocate:"," external: true"," name: ${AGENTHIPPO_IDP_NETWORK:-agenthippo-idp-colocate}","","volumes:"," agenthippo-state:",""].join(`
555
556
  `),i=[`# Colocated route for ${t.publicHostname} \u2014 copy into enterprise-deploy/idp/agents/`,"# (rename e.g. to "+t.packName+".caddy), then on the IdP host:","# docker compose exec caddy caddy reload --config /etc/caddy/Caddyfile","# Requires this agent's docker-compose.yml (already generated) to be up, so",`# ${n} exists on the shared \`agenthippo-idp-colocate\` network.`,"# http:// (not https://) to match the IdP Caddyfile's TLS model: auto_https is off","# there and TLS terminates in front (Cloudflare Tunnel/nginx), so every site block \u2014","# including this imported one \u2014 must be plain HTTP, same as the IdP's own site address.",`http://${t.publicHostname} {`,...(0,ot.renderIdentityLayer)({mode:"federated",authBrokerAddr:"auth-broker:9780",idpUrl:e,healthProxy:[` reverse_proxy ${n}:${t.port}`],agentProxy:[` reverse_proxy ${n}:${t.port}`],...t.edgeTurnConnector?{turnRegistration:{connectorAddr:t.edgeTurnConnector,tokenEnvVar:r}}:{}}),"}",""].join(`
556
557
  `);return{Dockerfile:Cn(t,{wwwDir:"/app/pack/deploy/www"}),"docker-compose.yml":s,"agent-route.caddy":i,"www/index.html":ws(t.packName),"README.md":[`# Deploy: ${t.packName} \u2014 colocated with the org IdP`,"","No Caddy, no oauth2-proxy, no local auth-broker, no auth secrets on this host \u2014 this","agent rides the org IdP's already-running edge (`enterprise-deploy/idp/`) instead.","","```bash","cp deploy/.env.example deploy/.env # model key only \u2014 no auth secrets here at all","# Point at the IdP's colocate network if it was created under a different compose","# project name: export AGENTHIPPO_IDP_NETWORK=agenthippo-idp-colocate (the default)","docker compose -f deploy/docker-compose.yml up -d --build","","# Wire the route into the IdP's Caddy (one-time per agent):",`cp deploy/agent-route.caddy <idp-host>:enterprise-deploy/idp/agents/${t.packName}.caddy`,...t.edgeTurnConnector?["","# EDGE turn registration (P1 fix): the route registers each chat turn with the connector",`# sidecar (${t.edgeTurnConnector}). Set the register token in the IdP stack's env \u2014`,"# same value as the connector's AGENTHIPPO_DATA_PLANE_TOKEN \u2014 before reloading:",`# echo "${r}=<token>" >> enterprise-deploy/idp/.env`,"# The agent container never holds this token (that is the point)."]:[],"docker compose -f enterprise-deploy/idp/docker-compose.yml exec caddy \\"," caddy reload --config /etc/caddy/Caddyfile","```","",`DNS: point \`${t.publicHostname}\` at the IdP host (same as every other agent it fronts).`,"","**hippopennyg / bare-metal (Cloudflare \u2192 nginx:443 \u2192 IdP Caddy :8080):** `deploy init` does","**not** create DNS or nginx for you. Without an explicit Cloudflare **A record**, the name","falls through to the `*.agenthippo.ai` wildcard (`ghs.googlehosted.com` from",'`setup-agenthippo-domain.sh` for Cloud Run) \u2014 the site will look "broken" or hit Google.',"After the steps above, run:","","```bash","./enterprise-deploy/scripts/setup-colocated-agent-edge.sh \\",` --hostname ${t.publicHostname} --ssh root@168.119.174.239`,"```","","See `enterprise-deploy/idp/agents/README.md` for the full checklist.","**Browser:** after Google SSO, open `https://"+t.publicHostname+"/` for the static chat UI","(`deploy/www/index.html` served by the agent container at GET /).","",...tr(t)].join(`
557
- `)}}function s0(t){if(t.ingress==="edge-fed"&&t.colocate)return Ey(t);let e=t.publicHostname,n=["#!/usr/bin/env bash","# T0.5a \u2014 VPN + localhost only (no SSO edge). Binds 127.0.0.1 so LAN cannot bypass the proxy.","set -euo pipefail",...qr(),`IMAGE="${t.packName}:local"`,'docker build -f deploy/Dockerfile -t "$IMAGE" .',"docker rm -f agenthippo-agent 2>/dev/null || true","docker run -d --name agenthippo-agent --restart unless-stopped \\"," --env-file deploy/.env \\",` -v agenthippo-state:/state -p 127.0.0.1:${t.port}:${t.port} "$IMAGE"`,`echo "agent on 127.0.0.1:${t.port} \u2014 health: curl localhost:${t.port}/health"`,""].join(`
558
+ `)}}function c0(t){if(t.ingress==="edge-fed"&&t.colocate)return Ay(t);let e=t.publicHostname,n=["#!/usr/bin/env bash","# T0.5a \u2014 VPN + localhost only (no SSO edge). Binds 127.0.0.1 so LAN cannot bypass the proxy.","set -euo pipefail",...Kr(),`IMAGE="${t.packName}:local"`,'docker build -f deploy/Dockerfile -t "$IMAGE" .',"docker rm -f agenthippo-agent 2>/dev/null || true","docker run -d --name agenthippo-agent --restart unless-stopped \\"," --env-file deploy/.env \\",` -v agenthippo-state:/state -p 127.0.0.1:${t.port}:${t.port} "$IMAGE"`,`echo "agent on 127.0.0.1:${t.port} \u2014 health: curl localhost:${t.port}/health"`,""].join(`
558
559
  `),r=["# systemd user unit \u2014 survives logout (run: loginctl enable-linger $USER).","# VPN path: cp deploy/agenthippo.service ~/.config/systemd/user/","# SSO path: use agenthippo-edge.service (compose --profile edge)","# install: systemctl --user enable --now agenthippo","[Unit]","Description=AgentHippo agent (serve)","After=network-online.target docker.service","","[Service]",`WorkingDirectory=%h/${t.packName}`,"ExecStart=/usr/bin/env bash deploy/run.sh","Restart=always","RestartSec=5","","[Install]","WantedBy=default.target",""].join(`
559
560
  `),s=["# systemd user unit \u2014 Cloudflare Tunnel + Google SSO + agent.","# install: cp deploy/agenthippo-edge.service ~/.config/systemd/user/","# loginctl enable-linger $USER && systemctl --user enable --now agenthippo-edge","[Unit]","Description=AgentHippo agent (Tunnel + Google SSO)","After=network-online.target docker.service","","[Service]",`WorkingDirectory=%h/${t.packName}/deploy`,"ExecStart=/usr/bin/env docker compose -f docker-compose.yml --profile edge --profile tunnel up --build","ExecStop=/usr/bin/env docker compose -f docker-compose.yml --profile edge --profile tunnel down","Restart=always","RestartSec=5","","[Install]","WantedBy=default.target",""].join(`
560
- `),i=["# T0.5 workbench/VM. Paths:","# T0.5a VPN: bash deploy/run.sh","# T0.5b remote: bash deploy/run-edge-tunnel.sh (Tunnel + Google SSO \u2014 recommended WFH)","# edge only: docker compose --profile edge up -d (SSO on :443, no tunnel)","services:",...fy(t),...py(t.ingress==="edge-fed"),...gy(),"volumes:"," agenthippo-state:"," auth-broker-data:",""].join(`
561
- `);return{Dockerfile:Cn(t),"Dockerfile.auth-broker":mf(),"docker-compose.yml":i,"run.sh":n,"run-edge-tunnel.sh":hy(e),"agenthippo.service":r,"agenthippo-edge.service":s,Caddyfile:uy(t),"www/index.html":ws(t.packName),"cloudflared.yml":dy(e),"README.md":[`# Deploy: ${t.packName} \u2014 T0.5 workbench/VM`,"","Staging root = this directory's parent (full pack copy). Commands below run from the staging root unless noted.","","To regenerate: run `agenthippo deploy init <path-to-pack> --target vm` from the **parent** of the pack (not from inside the pack), then `cd deploy-out/"+t.packName+"-vm`.","","`cp deploy/.env.example deploy/.env` and fill in, then pick a path:","","**T0.5a \u2014 VPN only (simplest internal pilot)**","```bash","bash deploy/run.sh","# curl http://127.0.0.1:"+t.port+`/v1/chat -d '{"message":"hi"}' ...`,"```","","**T0.5b \u2014 Cloudflare Tunnel + Google SSO (recommended for WFH, no Access seats)**","```bash","cp deploy/.env.example deploy/.env # agent: model key + public hostname","cp deploy/.env.auth.example deploy/.env.auth # broker/oauth2-proxy: JWT + OAuth secrets (never loaded by the agent)","# 1. Google Cloud \u2192 OAuth Web client for https://"+e,"# Authorized origin + redirect: https://"+e+"/oauth2/callback","# 2. cloudflared tunnel create <name>","# cp ~/.cloudflared/<tunnel-id>.json ~/.agent-hippo/tunnel-credentials.json # secret","# set tunnel: <tunnel-id> in deploy/cloudflared.yml","# cloudflared tunnel route dns <name> "+e,"# 3. Fill deploy/.env (hostname, model key) and deploy/.env.auth (OAUTH2_PROXY_*, AGENTHIPPO_AUTH_JWT_SECRET)","bash deploy/run-edge-tunnel.sh","# Users open https://"+e+" \u2192 Google login \u2192 static chat UI \u2192 /v1/chat","```","Tunnel routing is **config-file mode** (`deploy/cloudflared.yml` \u2192 `http://caddy:80` on the compose network), not the Cloudflare dashboard public-hostname UI alone.","Optional: `agenthippo-edge.service` + `loginctl enable-linger $USER` for persistence.","","**Edge only (no tunnel)** \u2014 `docker compose --profile edge up -d` on LAN/VPN.","","Identity: Google \u2192 oauth2-proxy \u2192 `X-Agent-User` \u2192 serve (`www/index.html` sends a per-tab `session_id` for multi-turn).","Per-user *data* scoping needs Design B (\xA711.1) in the app layer \u2014 generic `serve` alone does not filter warehouse rows.","","**Do not commit** `deploy/.env`, `deploy/.env.auth`, or `deploy/tunnel-credentials.json`.","",...tr(t)].join(`
562
- `)}}var Qc=["# Spotlight OTEL collector (compose-tuned: 0.0.0.0 bind). Writes JSONL to","# ${AGENT_HOME_DIR}/analytics/traces/ \u2014 query with query-analytics.sh (DuckDB).","receivers:"," otlp:"," protocols:"," http: { endpoint: 0.0.0.0:4318 }"," grpc: { endpoint: 0.0.0.0:4317 }","processors:"," batch: { timeout: 500ms, send_batch_size: 10 }"," resource:"," attributes:"," - { key: service.name, value: agentide-litellm, action: upsert }","exporters:"," file/jsonl:"," path: ${AGENT_HOME_DIR}/analytics/traces/traces.jsonl"," rotation: { max_megabytes: 100, max_days: 30, max_backups: 10 }","service:"," pipelines:"," traces: { receivers: [otlp], processors: [batch, resource], exporters: [file/jsonl] }",""].join(`
563
- `);function i0(t){if(t.ingress==="edge-fed"&&t.colocate)return Ey(t);let e=t.gatewayChannels?.trim(),n=t.publicHostname,r=e?[" command:",' ["serve","--agent","/app/pack","--workspace","/state/workspace",',` "--state-dir","/state","--port","${t.port}",`,` "--gateway-bridge","--bind","${e}"]`]:[],s=e?[""," # Agent Anywhere gateway (OpenClaw) \u2014 Slack/Telegram bridge."," # Build: docker build -f extensions/agentide/scripts/Dockerfile.gateway -t this-tag ."," # NOTE: the gateway runs in secured auth mode \u2014 the agent bridge needs"," # OPENCLAW_GATEWAY_TOKEN (or a paired device) to connect. Set it in .env."," openclaw-gateway:",' profiles: ["channels"]',` image: ${Kr("openclaw-gateway")}`," env_file:"," - path: .env"," required: false",' volumes: ["openclaw-config:/root/.openclaw"]',' expose: ["18789"]']:[],i=[" environment:"," # Routed through LiteLLM only when the gateway profile is up; harmless otherwise."," AGENTHIPPO_LITELLM_BASE_URL: http://litellm:4443",...e?[" OPENCLAW_GATEWAY_URL: ws://openclaw-gateway:18789"]:[],...r],o=["# T2 team/fleet stack (serve-v3 \xA78). Profiles:","# default = agent only (Docker network; no host port \u2014 use deploy/run.sh for T0.5a VPN)","# --profile edge = + Caddy + oauth2-proxy (Google SSO)","# --profile tunnel = + cloudflared (with edge; route hostname \u2192 http://caddy:80)","# --profile gateway = + LiteLLM + Spotlight OTEL collector","# --profile channels = + OpenClaw gateway (Agent Anywhere)","# e.g.: docker compose -f deploy/docker-compose.yml --profile edge --profile tunnel up -d","services:",...fy(t,i),...py(t.ingress==="edge-fed"),...gy()," # LiteLLM gateway \u2014 self-contained image bakes the Spotlight config + OTEL hooks"," # (build: docker build -f extensions/agentide/scripts/Dockerfile.litellm -t this-tag .)"," litellm:",' profiles: ["gateway"]',` image: ${Kr("agenthippo-litellm")}`," env_file:"," - path: .env"," required: false"," environment:"," OTEL_EXPORTER: otlp_http"," OTEL_EXPORTER_OTLP_ENDPOINT: http://otel-collector:4318"," # The image defaults to --host 127.0.0.1 (safe when someone runs it bare)."," # Here it must answer the agent container over the compose network, so bind"," # 0.0.0.0 \u2014 and keep `expose:` rather than `ports:` so it is never reachable"," # from the host. Requires general_settings.master_key in the baked config.",' command: ["--config", "/config/litellm.config.yaml", "--port", "4443", "--host", "0.0.0.0"]',' expose: ["4443"]'," depends_on: [otel-collector]",""," # Spotlight collector \u2192 JSONL traces volume (query with query-analytics.sh / DuckDB)."," otel-collector:",' profiles: ["gateway"]'," image: otel/opentelemetry-collector-contrib:0.118.0",' command: ["--config=/etc/otel-collector.yaml"]'," # Root so the collector can create /data/analytics on a fresh named volume"," # (the contrib image runs non-root; the volume root is root-owned).",' user: "0:0"'," environment: { AGENT_HOME_DIR: /data }"," volumes:"," - ./otel-collector.yaml:/etc/otel-collector.yaml:ro"," - spotlight-traces:/data",...s,"","volumes:"," agenthippo-state:"," auth-broker-data:"," spotlight-traces:",...e?[" openclaw-config:"]:[],""].join(`
564
- `);return{Dockerfile:Cn(t),"Dockerfile.auth-broker":mf(),"docker-compose.yml":o,Caddyfile:uy(t),"www/index.html":ws(t.packName),"cloudflared.yml":dy(n),"run-edge-tunnel.sh":hy(n),"otel-collector.yaml":Qc,"README.md":[`# Deploy: ${t.packName} \u2014 T2 team/fleet`,"","- Agent only (VPN): `docker compose -f deploy/docker-compose.yml up -d`","- + Tunnel + Google SSO: `bash deploy/run-edge-tunnel.sh` (see vm README T0.5b).","- + LiteLLM gateway + Spotlight: `--profile gateway`.","- + Agent Anywhere: `--profile channels` + gateway env vars in `.env`.","","Profiles compose: e.g. `--profile gateway --profile edge --profile tunnel up -d`.","LiteLLM must speak Anthropic API format \u2014 our gateway image does.","",...tr(t)].join(`
565
- `)}}function mi(t){let e=(t||"").toLowerCase();return e==="ah-auto"?"AGENTHIPPO_GATEWAY_KEY":e.includes("codex")?"OPENAI_CODEX_API_KEY":e.includes("gpt")||e.includes("openai")?"OPENAI_API_KEY":e.includes("claude")||e.includes("anthropic")?"ANTHROPIC_API_KEY":"OPENAI_API_KEY"}function Yo(t){return(t||"").trim().toLowerCase()==="ah-auto"}var _y="https://gateway.agenthippo.ai/v1";function Ef(t){return t.modelRouting==="gateway"}function yy(t){if(t.engine.trim().toLowerCase()==="cursor")return"api2.cursor.sh";if(Yo(t.model))return"gateway.agenthippo.ai";let e=(t.model||"").toLowerCase();return e.includes("codex")||e.includes("gpt")||e.includes("openai")?"api.openai.com":"api.anthropic.com"}function tr(t){let e=Ef(t)?".":" \u2014 and, if the LiteLLM gateway/Spotlight sidecar is enabled, its own outbound is the same host.";return[`**Egress:** this container only needs outbound access to \`${yy(t)}:443\` (your model provider)${e}`,"Restrict egress to this allowlist if your org requires it.",""]}function o0(t,e,n,r,s){let i=[`\`${mi(t.model)}\` (or the pack's configured provider key) \u2014 your model provider credential`],o=["**agent container** \u2014 can reach your model provider and read/write its own state volume. Never holds the JWT signing secret or any OAuth client secret (`.env` vs `.env.auth` split)."];return n?(i.push("`AGENTHIPPO_AUTH_JWT_SECRET` \u2014 signs/verifies IDE bootstrap tokens (auth-broker only, never the agent)"),o.push("**auth-broker** \u2014 holds the JWT signing secret"+(r?" (shared with the central IdP)":"")+"; mints/verifies IDE tokens. Does not hold model provider credentials."),r||(i.push("`OAUTH2_PROXY_CLIENT_SECRET` + `OAUTH2_PROXY_COOKIE_SECRET` \u2014 this deployment's own Google OAuth client (oauth2-proxy only, never the agent)"),o.push("**oauth2-proxy** \u2014 holds this deployment's Google OAuth client secret; terminates the Google login flow. Does not hold the JWT signing secret or model credentials."))):s&&o.push("**this deployment holds no auth secrets at all** \u2014 identity is verified entirely by the org IdP's own auth-broker (see `agent-route.caddy`); nothing here signs or stores a JWT secret."),[`# Data & access summary \u2014 ${t.packName} (${e}${t.ingress?` / ${t.ingress}`:""})`,"","Generated by `agenthippo deploy init` \u2014 answers the questions a security review asks first.","","## Secrets",...i.map(a=>`- ${a}`),"","## Egress",`- Outbound network access is needed only to \`${yy(t)}:443\` (your model provider).`,...n&&r?["- API/Bearer requests are verified locally against the shared JWT secret \u2014 no network call to the central IdP per request. The one-time browser login flow (unauthenticated visitors) does redirect to the central IdP's public URL to sign in."]:[],...n&&!r?["- Google SSO calls `accounts.google.com` during login only (oauth2-proxy); no other third party is contacted per request."]:[],...s?["- Identity is verified via the org IdP's own auth-broker over the shared private docker network (`agenthippo-idp-colocate`), not a public network call. The one-time browser login flow (unauthenticated visitors) still redirects to the central IdP's public URL to sign in."]:[],"","## Blast radius per component",...o.map(a=>`- ${a}`),""].join(`
566
- `)}function a0(t){let e=mi(t.model);return["# Cloud Run multi-container: agent (ingress) + LiteLLM + Spotlight OTEL collector.","# Generated by `agenthippo deploy init`. Deploy with `bash deploy/cloudrun-deploy.sh`","# (it substitutes ${...} and runs `gcloud run services replace`). Traces land in the GCS","# /state volume at /state/analytics/traces \u2014 query with query-analytics.sh (DuckDB).","apiVersion: serving.knative.dev/v1","kind: Service","metadata:"," name: ${SERVICE}","spec:"," template:"," metadata:"," annotations:"," # Sidecars need CPU between requests (the collector flushes async); no scale-to-zero throttle.",' run.googleapis.com/cpu-throttling: "false"',' run.googleapis.com/startup-cpu-boost: "true"'," # Start order: collector \u2192 litellm \u2192 agent, so traces are never dropped on cold start.",` run.googleapis.com/container-dependencies: '{"litellm":["otel-collector"],"agent":["litellm"]}'`,' autoscaling.knative.dev/maxScale: "1"',...t.gatewayChannels?.trim()?[' autoscaling.knative.dev/minScale: "1"']:[]," spec:"," timeoutSeconds: 3600"," containers:"," # Ingress container \u2014 the ONLY one with a port. Routes the engine through LiteLLM."," - name: agent"," image: ${IMAGE}"," ports:"," - name: http1",` containerPort: ${t.port}`," env:"," - { name: AGENTHIPPO_HOME, value: /state }",' - { name: AGENTHIPPO_NO_AUTO_INSTALL, value: "1" }',' - { name: AGENTHIPPO_IDENTITY_HEADER, value: "${IDENTITY_HEADER_VALUE}" }',zc()," - { name: AGENTHIPPO_LITELLM_BASE_URL, value: http://localhost:4443 }"," - name: AGENTHIPPO_LITELLM_API_KEY"," valueFrom:"," secretKeyRef: { name: ${SERVICE}-litellm-key, key: latest }"," volumeMounts:"," - { name: state, mountPath: /state }"," # LiteLLM gateway sidecar \u2014 exports every call to the collector (Spotlight cost/latency/tokens)."," - name: litellm"," image: ${LITELLM_IMAGE}"," env:"," - { name: OTEL_EXPORTER, value: otlp_http }"," - { name: OTEL_EXPORTER_OTLP_ENDPOINT, value: http://localhost:4318 }"," - name: LITELLM_MASTER_KEY"," valueFrom:"," secretKeyRef: { name: ${SERVICE}-litellm-key, key: latest }",` # Upstream provider key for ${t.model||"this model"} (matches the gateway's os.environ/${e} ref).`," # Other models need their own key var \u2014 rename to match your model map.",` - name: ${e}`," valueFrom:"," secretKeyRef: { name: ${SERVICE}-provider-key, key: latest }"," # Spotlight OTEL collector sidecar \u2014 writes JSONL traces into the shared /state volume."," - name: otel-collector"," image: otel/opentelemetry-collector-contrib:0.118.0",' args: ["--config=/etc/otel/config.yaml"]'," env:"," - { name: AGENT_HOME_DIR, value: /state }"," volumeMounts:"," - { name: otel-config, mountPath: /etc/otel, readOnly: true }"," - { name: state, mountPath: /state }"," volumes:"," - name: state"," csi:"," driver: gcsfuse.run.googleapis.com"," volumeAttributes:"," bucketName: ${STATE_BUCKET}"," - name: otel-config"," secret:"," secretName: ${SERVICE}-otel-config"," items:"," - { key: latest, path: config.yaml }",""].join(`
567
- `)}function qr(){return["# Anchor to the staging root (parent of deploy/) \u2014 this script runs from any cwd.",'cd "$(dirname "$0")/.."']}function wy(){return["# Ingress: corp SSO via IAP (forwards X-Goog-Authenticated-User-Email \u2192 user_id).","# --iap is beta-track only on `gcloud run`; public access on an existing service is","# controlled via the run.invoker IAM binding (no --no-allow-unauthenticated on","# `services update`). So: enable IAP on the beta track, strip any allUsers invoker","# binding (keeps the service private), and grant IAP-secured Web User to each","# principal in IAP_MEMBERS (space-separated, e.g.","# IAP_MEMBERS='user:you@corp.com serviceAccount:sa@project.iam.gserviceaccount.com'","# ). Omit IAP_MEMBERS to rely on bindings you manage out-of-band.",'if [[ "${ENABLE_IAP:-1}" == "1" ]]; then',' gcloud beta run services update "$SERVICE" --region "$REGION" --iap',' gcloud run services remove-iam-policy-binding "$SERVICE" --region "$REGION" \\'," --member=allUsers --role=roles/run.invoker >/dev/null 2>&1 || true"," for m in ${IAP_MEMBERS:-}; do"," gcloud beta iap web add-iam-policy-binding \\",' --resource-type=cloud-run --service="$SERVICE" --region="$REGION" \\',' --member="$m" --role=roles/iap.httpsResourceAccessor'," done","fi"]}function c0(t){return["#!/usr/bin/env bash",`# Cloud Run + Spotlight: agent + LiteLLM + OTEL collector sidecars (engine: ${t.engine}${t.model?`, model ${t.model}`:""}).`,"# Traces persist in the GCS /state bucket; query with query-analytics.sh (DuckDB).","set -euo pipefail",...qr(),`SERVICE="${t.packName}"`,'REGION="${REGION:-us-central1}"','PROJECT_ID="${PROJECT_ID:-$(gcloud config get-value project)}"','REPO="${ARTIFACT_REPO:-agenthippo}"','IMAGE="${REGION}-docker.pkg.dev/${PROJECT_ID}/${REPO}/${SERVICE}:latest"',`LITELLM_IMAGE="\${LITELLM_IMAGE:-${Kr("agenthippo-litellm")}}"`,'STATE_BUCKET="${STATE_BUCKET:?set STATE_BUCKET=your-gcs-bucket (gcloud storage buckets create gs://...)}"',"# LITELLM_KEY = the proxy key the agent presents to LiteLLM (and LiteLLM master key).",'LITELLM_KEY="${LITELLM_KEY:?set LITELLM_KEY=<litellm proxy key>}"',`# PROVIDER_KEY = upstream key the gateway uses for ${t.model||"your model"} (gateway reads ${mi(t.model)}).`,'PROVIDER_KEY="${PROVIDER_KEY:?set PROVIDER_KEY=<upstream provider key>}"',"",'gcloud artifacts repositories describe "$REPO" --location="$REGION" 2>/dev/null \\',' || gcloud artifacts repositories create "$REPO" --repository-format=docker --location="$REGION"','gcloud auth configure-docker "${REGION}-docker.pkg.dev" --quiet',"","# Rewrite the runtime base to this project Artifact Registry. Customer artifacts pin a","# dated ghcr.io/agenthippoai/runtime tag; mirror that exact tag into AR. No-op if already AR.",'DF_TMP="$(mktemp)"','sed "s|FROM ghcr.io/agenthippoai/runtime:|FROM ${REGION}-docker.pkg.dev/${PROJECT_ID}/${REPO}/runtime:|" deploy/Dockerfile > "$DF_TMP"','docker build --pull --platform linux/amd64 -f "$DF_TMP" -t "$IMAGE" .','docker push "$IMAGE"',"","# Secrets: Spotlight collector config + the LiteLLM proxy key.",'ensure_secret() { gcloud secrets describe "$1" >/dev/null 2>&1 || gcloud secrets create "$1" --replication-policy=automatic; }','ensure_secret "${SERVICE}-otel-config"; gcloud secrets versions add "${SERVICE}-otel-config" --data-file=deploy/otel-collector.yaml','ensure_secret "${SERVICE}-litellm-key"; printf %s "$LITELLM_KEY" | gcloud secrets versions add "${SERVICE}-litellm-key" --data-file=-','ensure_secret "${SERVICE}-provider-key"; printf %s "$PROVIDER_KEY" | gcloud secrets versions add "${SERVICE}-provider-key" --data-file=-',"","# IAP (finalized below) forwards X-Goog-Authenticated-User-Email; pin serve to trust ONLY","# that header so an authenticated caller cannot impersonate another user via a spoofed","# X-Agent-User header. Skipped when ENABLE_IAP=0 (first-deploy bootstrap) since IAP never","# sets the header then.",'IDENTITY_HEADER_VALUE=""','[[ "${ENABLE_IAP:-1}" == "1" ]] && IDENTITY_HEADER_VALUE="x-goog-authenticated-user-email" || true',"","# Render the multi-container template for this project (sed \u2014 no gettext dependency) and deploy.",'RENDERED="$(mktemp)"','sed -e "s|\\${SERVICE}|${SERVICE}|g" -e "s|\\${IMAGE}|${IMAGE}|g" \\',' -e "s|\\${LITELLM_IMAGE}|${LITELLM_IMAGE}|g" -e "s|\\${STATE_BUCKET}|${STATE_BUCKET}|g" \\',' -e "s|\\${IDENTITY_HEADER_VALUE}|${IDENTITY_HEADER_VALUE}|g" \\',' deploy/service.yaml > "$RENDERED"','gcloud run services replace "$RENDERED" --region "$REGION"',"",...wy(),"","# Grant the runtime SA access to the secrets if needed:",`# SA="$(gcloud run services describe "$SERVICE" --region "$REGION" --format='value(spec.template.spec.serviceAccountName)')"`,'# for s in "${SERVICE}-otel-config" "${SERVICE}-litellm-key"; do gcloud secrets add-iam-policy-binding "$s" --member="serviceAccount:$SA" --role=roles/secretmanager.secretAccessor; done',""].join(`
568
- `)}function l0(t){let e=t.engine.trim().toLowerCase()==="cursor",n=mi(t.model),r=hi(t,{wwwDir:"/app/pack/deploy/www",port:ot.EDGE_AGENT_PORT}).map(o=>`"${o.replace(/"/g,'\\"')}"`).join(", "),i=["# Cloud Run + AgentHippo edge (Option B): Caddy (ingress) + oauth2-proxy + auth-broker","# + agent (+ LiteLLM + OTEL collector for Spotlight). No IAP \u2014 Caddy gates via SSO,","# so the IDE hits the public hostname directly with its AgentHippo Bearer token.","# Generated by `agenthippo deploy init --target cloudrun --ingress edge`.","apiVersion: serving.knative.dev/v1","kind: Service","metadata:"," name: ${SERVICE}","spec:"," template:"," metadata:"," annotations:",' run.googleapis.com/cpu-throttling: "false"',' run.googleapis.com/startup-cpu-boost: "true"',` run.googleapis.com/container-dependencies: '${e?'{"caddy":["agent","oauth2-proxy","auth-broker"]}':'{"caddy":["agent","oauth2-proxy","auth-broker"],"agent":["litellm"],"litellm":["otel-collector"]}'}'`,' autoscaling.knative.dev/maxScale: "1"',...t.gatewayChannels?.trim()?[' autoscaling.knative.dev/minScale: "1"']:[]," spec:"," timeoutSeconds: 3600"," containers:"," # Ingress \u2014 the ONLY container with a port. SSO edge for browsers + IDE Bearer."," - name: caddy"," image: caddy:2.8-alpine"," ports:"," - name: http1",` containerPort: ${t.port}`," volumeMounts:"," - { name: caddy-config, mountPath: /etc/caddy, readOnly: true }"," # Auth broker \u2014 validates IDE Bearer JWTs (/api/ide/me) + IDE sign-in (/oauth/*)."," # Reuses the agent runtime image (the `agenthippo` CLI ships `auth-broker`)."," - name: auth-broker"," image: ${IMAGE}",' args: ["auth-broker"]'," env:",' - { name: AGENTHIPPO_AUTH_PORT, value: "9780" }'," - { name: AGENTHIPPO_AUTH_DATA_DIR, value: /data }"," - { name: AGENTHIPPO_AUTH_PUBLIC_URL, value: https://${PUBLIC_HOSTNAME} }"," - { name: AGENTHIPPO_AUTH_ALLOWED_DOMAINS, value: ${ALLOWED_DOMAINS} }"," - name: AGENTHIPPO_AUTH_JWT_SECRET"," valueFrom:"," secretKeyRef: { name: ${SERVICE}-auth-jwt-secret, key: latest }"," # oauth2-proxy \u2014 Google SSO for browser clients (provider=google)."," - name: oauth2-proxy"," image: quay.io/oauth2-proxy/oauth2-proxy:v7.7.1"," env:"," - { name: OAUTH2_PROXY_HTTP_ADDRESS, value: 0.0.0.0:4180 }"," - { name: OAUTH2_PROXY_UPSTREAMS, value: file:///dev/null }",' - { name: OAUTH2_PROXY_SET_XAUTHREQUEST, value: "true" }',' - { name: OAUTH2_PROXY_PASS_AUTHORIZATION_HEADER, value: "true" }',' - { name: OAUTH2_PROXY_SKIP_PROVIDER_BUTTON, value: "true" }',' - { name: OAUTH2_PROXY_REVERSE_PROXY, value: "true" }'," - { name: OAUTH2_PROXY_PROVIDER, value: google }"," - { name: OAUTH2_PROXY_EMAIL_DOMAINS, value: ${ALLOWED_DOMAINS} }"," - { name: OAUTH2_PROXY_REDIRECT_URL, value: https://${PUBLIC_HOSTNAME}/oauth2/callback }"," - name: OAUTH2_PROXY_CLIENT_ID"," valueFrom:"," secretKeyRef: { name: ${SERVICE}-oauth-client-id, key: latest }"," - name: OAUTH2_PROXY_CLIENT_SECRET"," valueFrom:"," secretKeyRef: { name: ${SERVICE}-oauth-client-secret, key: latest }"," - name: OAUTH2_PROXY_COOKIE_SECRET"," valueFrom:"," secretKeyRef: { name: ${SERVICE}-oauth-cookie-secret, key: latest }"," # Agent \u2014 serves www + /v1/* on localhost (NOT ingress). Routed through LiteLLM."," - name: agent"," image: ${IMAGE}",` args: [${r}]`," env:"," - { name: AGENTHIPPO_HOME, value: /state }",' - { name: AGENTHIPPO_NO_AUTO_INSTALL, value: "1" }',zc(),...e?[" - { name: AGENTHIPPO_CUSTOM_ENGINES_DIR, value: /engines }"," - name: CURSOR_API_KEY"," valueFrom:"," secretKeyRef: { name: ${SERVICE}-provider-key, key: latest }"]:[" - { name: AGENTHIPPO_LITELLM_BASE_URL, value: http://localhost:4443 }"," - name: AGENTHIPPO_LITELLM_API_KEY"," valueFrom:"," secretKeyRef: { name: ${SERVICE}-litellm-key, key: latest }"]," volumeMounts:"," - { name: state, mountPath: /state }",...ys(ot.EDGE_AGENT_PORT,!0),...Pr("2000m","2Gi")];return e||i.push(" # LiteLLM gateway sidecar \u2014 exports every call to the collector (Spotlight)."," - name: litellm"," image: ${LITELLM_IMAGE}"," env:"," - { name: OTEL_EXPORTER, value: otlp_http }"," - { name: OTEL_EXPORTER_OTLP_ENDPOINT, value: http://localhost:4318 }"," - name: LITELLM_MASTER_KEY"," valueFrom:"," secretKeyRef: { name: ${SERVICE}-litellm-key, key: latest }",` # Upstream provider key for ${t.model||"this model"} (matches the gateway's os.environ/${n} ref).`,` - name: ${n}`," valueFrom:"," secretKeyRef: { name: ${SERVICE}-provider-key, key: latest }",...ys(4443),...Pr("1000m","1Gi")," # Spotlight OTEL collector sidecar \u2014 writes JSONL traces into the shared /state volume."," - name: otel-collector"," image: otel/opentelemetry-collector-contrib:0.118.0",' args: ["--config=/etc/otel/config.yaml"]'," env:"," - { name: AGENT_HOME_DIR, value: /state }"," volumeMounts:"," - { name: otel-config, mountPath: /etc/otel, readOnly: true }"," - { name: state, mountPath: /state }",...ys(4318),...Pr("1000m","512Mi")),i.push(" volumes:"," - name: state"," csi:"," driver: gcsfuse.run.googleapis.com"," volumeAttributes:"," bucketName: ${STATE_BUCKET}"," - name: caddy-config"," secret:"," secretName: ${SERVICE}-caddyfile"," items:"," - { key: latest, path: Caddyfile }"),e||i.push(" - name: otel-config"," secret:"," secretName: ${SERVICE}-otel-config"," items:"," - { key: latest, path: config.yaml }"),i.push(""),i.join(`
569
- `)}function u0(t){let e=t.engine.trim().toLowerCase()==="cursor",n=t.model?.trim()?`, model ${t.model.trim()}`:"",r=["#!/usr/bin/env bash","# Cloud Run + AgentHippo edge (Option B): Caddy + oauth2-proxy + auth-broker front the agent.",`# Engine: ${t.engine}${n}. No IAP \u2014 Caddy gates via SSO (Google for browsers, AgentHippo JWT for IDE).`,"# The IDE points spec.remote.url straight at https://$PUBLIC_HOSTNAME (same flow as remote-vm).","set -euo pipefail",...qr(),`SERVICE="${t.packName}"`,'REGION="${REGION:-us-central1}"','PROJECT_ID="${PROJECT_ID:-$(gcloud config get-value project)}"','REPO="${ARTIFACT_REPO:-agenthippo}"','IMAGE="${REGION}-docker.pkg.dev/${PROJECT_ID}/${REPO}/${SERVICE}:latest"',`LITELLM_IMAGE="\${LITELLM_IMAGE:-${Kr("agenthippo-litellm")}}"`,"# Public hostname (custom domain mapped to the service) + the Google Workspace domain allowed by SSO.",'PUBLIC_HOSTNAME="${PUBLIC_HOSTNAME:?set PUBLIC_HOSTNAME=your.edge.hostname (gcloud run domain-mappings create --service $SERVICE --domain ...)}"','ALLOWED_DOMAINS="${ALLOWED_DOMAINS:?set ALLOWED_DOMAINS=yourworkspace.com (oauth2-proxy email domain + broker allowed domains)}"','STATE_BUCKET="${STATE_BUCKET:?set STATE_BUCKET=your-gcs-bucket (gcloud storage buckets create gs://...)}"',"# Edge secrets (from .env.auth): Google OAuth client + cookie secret + AgentHippo JWT signing key.",'OAUTH_CLIENT_ID="${OAUTH_CLIENT_ID:?set OAUTH_CLIENT_ID=<google oauth web client id>}"','OAUTH_CLIENT_SECRET="${OAUTH_CLIENT_SECRET:?set OAUTH_CLIENT_SECRET=<google oauth web client secret>}"','OAUTH_COOKIE_SECRET="${OAUTH_COOKIE_SECRET:?set OAUTH_COOKIE_SECRET=$(openssl rand -base64 32 | head -c 32)}"','AUTH_JWT_SECRET="${AUTH_JWT_SECRET:?set AUTH_JWT_SECRET=$(openssl rand -hex 32)}"',...e?['PROVIDER_KEY="${PROVIDER_KEY:?set PROVIDER_KEY=<cursor api key>}"']:["# LiteLLM proxy key + the upstream provider key the gateway uses for the model.",'LITELLM_KEY="${LITELLM_KEY:?set LITELLM_KEY=<litellm proxy key>}"','PROVIDER_KEY="${PROVIDER_KEY:?set PROVIDER_KEY=<upstream provider key>}"'],"",'gcloud artifacts repositories describe "$REPO" --location="$REGION" 2>/dev/null \\',' || gcloud artifacts repositories create "$REPO" --repository-format=docker --location="$REGION"','gcloud auth configure-docker "${REGION}-docker.pkg.dev" --quiet',"","# One agent image serves both the agent and the auth-broker containers (CLI ships `auth-broker`).","# Rewrite the runtime base to this project Artifact Registry. Customer artifacts pin a","# dated ghcr.io/agenthippoai/runtime tag; mirror that exact tag into AR. No-op if already AR.",'DF_TMP="$(mktemp)"','sed "s|FROM ghcr.io/agenthippoai/runtime:|FROM ${REGION}-docker.pkg.dev/${PROJECT_ID}/${REPO}/runtime:|" deploy/Dockerfile > "$DF_TMP"','docker build --pull --platform linux/amd64 -f "$DF_TMP" -t "$IMAGE" .','docker push "$IMAGE"',"","# Secrets: edge config + provider/litellm keys.",'ensure_secret() { gcloud secrets describe "$1" >/dev/null 2>&1 || gcloud secrets create "$1" --replication-policy=automatic; }','ensure_secret "${SERVICE}-caddyfile"; gcloud secrets versions add "${SERVICE}-caddyfile" --data-file=deploy/Caddyfile','ensure_secret "${SERVICE}-auth-jwt-secret"; printf %s "$AUTH_JWT_SECRET" | gcloud secrets versions add "${SERVICE}-auth-jwt-secret" --data-file=-','ensure_secret "${SERVICE}-oauth-client-id"; printf %s "$OAUTH_CLIENT_ID" | gcloud secrets versions add "${SERVICE}-oauth-client-id" --data-file=-','ensure_secret "${SERVICE}-oauth-client-secret"; printf %s "$OAUTH_CLIENT_SECRET" | gcloud secrets versions add "${SERVICE}-oauth-client-secret" --data-file=-','ensure_secret "${SERVICE}-oauth-cookie-secret"; printf %s "$OAUTH_COOKIE_SECRET" | gcloud secrets versions add "${SERVICE}-oauth-cookie-secret" --data-file=-','ensure_secret "${SERVICE}-provider-key"; printf %s "$PROVIDER_KEY" | gcloud secrets versions add "${SERVICE}-provider-key" --data-file=-'];return e||r.push('ensure_secret "${SERVICE}-otel-config"; gcloud secrets versions add "${SERVICE}-otel-config" --data-file=deploy/otel-collector.yaml','ensure_secret "${SERVICE}-litellm-key"; printf %s "$LITELLM_KEY" | gcloud secrets versions add "${SERVICE}-litellm-key" --data-file=-'),r.push("","# Render the multi-container template for this project (sed \u2014 no gettext dependency) and deploy.",'RENDERED="$(mktemp)"','sed -e "s|\\${SERVICE}|${SERVICE}|g" -e "s|\\${IMAGE}|${IMAGE}|g" \\',' -e "s|\\${LITELLM_IMAGE}|${LITELLM_IMAGE}|g" -e "s|\\${STATE_BUCKET}|${STATE_BUCKET}|g" \\',' -e "s|\\${PUBLIC_HOSTNAME}|${PUBLIC_HOSTNAME}|g" -e "s|\\${ALLOWED_DOMAINS}|${ALLOWED_DOMAINS}|g" \\',' deploy/service.yaml > "$RENDERED"','gcloud run services replace "$RENDERED" --region "$REGION"',"","# No IAP: Caddy is the gate, so Cloud Run itself must allow public ingress (allUsers invoker).","# Without this, Cloud Run 403s before Caddy ever sees the request to run SSO.",'gcloud run services add-iam-policy-binding "$SERVICE" --region "$REGION" \\'," --member=allUsers --role=roles/run.invoker >/dev/null 2>&1 || true","",'# Map the custom domain (once): gcloud run domain-mappings create --service "$SERVICE" --region "$REGION" --domain "$PUBLIC_HOSTNAME"',"# Then add the CNAME Cloud Run prints to your DNS. Google OAuth Web client must list","# https://$PUBLIC_HOSTNAME as an authorized origin + https://$PUBLIC_HOSTNAME/oauth2/callback as a redirect.","","# Grant the runtime SA access to the secrets if needed:",`# SA="$(gcloud run services describe "$SERVICE" --region "$REGION" --format='value(spec.template.spec.serviceAccountName)')"`,'# for s in "${SERVICE}-caddyfile" "${SERVICE}-auth-jwt-secret" "${SERVICE}-oauth-client-id" "${SERVICE}-oauth-client-secret" "${SERVICE}-oauth-cookie-secret" "${SERVICE}-provider-key"; do','# gcloud secrets add-iam-policy-binding "$s" --member="serviceAccount:$SA" --role=roles/secretmanager.secretAccessor',"# done",""),r.join(`
570
- `)}function d0(t){let e=!!t.gatewayChannels?.trim(),n=t.engine.trim().toLowerCase()==="cursor";if(t.ingress==="edge")return f0(t,e,n);if(t.ingress==="edge-fed")return E0(t,e,n);if(!n)return{Dockerfile:Cn(t,{wwwDir:"/app/pack/deploy/www"}),"www/index.html":ws(t.packName),"service.yaml":a0(t),"otel-collector.yaml":Qc,"cloudrun-deploy.sh":c0(t),"README.md":[`# Deploy: ${t.packName} \u2014 Cloud Run + Spotlight (multi-container)`,"",`Engine: **${t.engine}**${t.model?`, model: **${t.model}**`:""}. Runtime base: \`${t.image}\`.`,"","Three sidecars share the pod's localhost (Cloud Run multi-container):","- **agent** (ingress) \u2192 routes the engine to `http://localhost:4443`","- **litellm** gateway \u2192 exports OTLP to `http://localhost:4318`","- **otel-collector** \u2192 writes JSONL traces to the GCS `/state` volume (`/state/analytics/traces`).","","```bash","gcloud storage buckets create gs://<your-state-bucket> # once","export STATE_BUCKET=<your-state-bucket> LITELLM_KEY=<litellm proxy key>","bash deploy/cloudrun-deploy.sh # builds linux/amd64, creates secrets, `gcloud run services replace service.yaml`","```","","`service.yaml` is the multi-container template (checked in so the wiring is reviewable);","the deploy script substitutes `${SERVICE} ${IMAGE} ${STATE_BUCKET} ${LITELLM_IMAGE}`.","Provider creds (Anthropic key / Vertex ADC / OpenAI \u2026) go on the **litellm** sidecar, not the agent.","",e?"**Inbound channel (1b):** `minScale: 1` pins one always-on instance (the socket can't scale to zero).":"**No inbound channel (1a):** scales to zero; traces + sessions persist on the GCS `/state` volume.","","**Spotlight:** once traffic flows, query the GCS-backed traces with `query-analytics.sh` (DuckDB) against `/state/analytics/traces`.","","**Lean alternative (no Spotlight):** a single-container deploy that calls a provider directly","(or an external LiteLLM) \u2014 set `AGENTHIPPO_LITELLM_BASE_URL` to your endpoint and drop the sidecars.","",...tr(t)].join(`
571
- `)};let r=e?" --min-instances 1 --max-instances 1 --no-cpu-throttling \\":" --min-instances 0 --max-instances 1 \\",s=n?"AGENTHIPPO_NO_AUTO_INSTALL=1,AGENTHIPPO_HOME=/state,AGENTHIPPO_CUSTOM_ENGINES_DIR=/engines":"CLAUDE_CODE_USE_VERTEX=1,AGENTHIPPO_NO_AUTO_INSTALL=1,AGENTHIPPO_HOME=/state",i=n?"CURSOR_API_KEY=agenthippo-cursor-key:latest":void 0,o=t.model?.trim()?`, model ${t.model.trim()}`:"",a=["#!/usr/bin/env bash","# T1-generic: Cloud Run with built-in IAP (corp SSO, no load balancer).",`# Engine: ${t.engine}${o}. IAP forwards X-Goog-Authenticated-User-Email \u2192 user_id.`,"set -euo pipefail",...qr(),`SERVICE="${t.packName}"`,'REGION="${REGION:-us-central1}"','PROJECT_ID="${PROJECT_ID:-$(gcloud config get-value project)}"','REPO="${ARTIFACT_REPO:-agenthippo}"','IMAGE="${REGION}-docker.pkg.dev/${PROJECT_ID}/${REPO}/${SERVICE}:latest"',"# Q1: durable state. Cloud Run local disk is ephemeral (wiped on scale-to-zero),","# so mount a GCS bucket at /state \u2014 sessions/provider-sessions/analytics survive.",'STATE_BUCKET="${STATE_BUCKET:?set STATE_BUCKET=your-gcs-bucket (gcloud storage buckets create gs://...)}"',"",'gcloud artifacts repositories describe "$REPO" --location="$REGION" 2>/dev/null \\',' || gcloud artifacts repositories create "$REPO" --repository-format=docker --location="$REGION"','gcloud auth configure-docker "${REGION}-docker.pkg.dev" --quiet',"","# Build from pack root; Dockerfile is deploy/Dockerfile (not pack root \u2014 gcloud --source . misses it).","# Rewrite the runtime base to this project Artifact Registry. Customer artifacts pin a","# dated ghcr.io/agenthippoai/runtime tag; mirror that exact tag into AR. No-op if already AR.",'DF_TMP="$(mktemp)"','sed "s|FROM ghcr.io/agenthippoai/runtime:|FROM ${REGION}-docker.pkg.dev/${PROJECT_ID}/${REPO}/runtime:|" deploy/Dockerfile > "$DF_TMP"','docker build --pull --platform linux/amd64 -f "$DF_TMP" -t "$IMAGE" .','docker push "$IMAGE"',"","# IAP (when enabled below) forwards X-Goog-Authenticated-User-Email; pin serve to trust","# ONLY that header so an authenticated caller cannot impersonate another user via a","# spoofed X-Agent-User header. Skipped when ENABLE_IAP=0 (first-deploy bootstrap) since","# IAP never sets the header then \u2014 pinning to an absent header would make every request","# anonymous instead of leaving body-supplied identity usable during bootstrap.",'IDENTITY_ENV=""','[[ "${ENABLE_IAP:-1}" == "1" ]] && IDENTITY_ENV=",AGENTHIPPO_IDENTITY_HEADER=x-goog-authenticated-user-email" || true',"","# Deploy private (no --allow-unauthenticated). IAP + role grants are applied below on the beta track.",'gcloud run deploy "$SERVICE" \\',' --image "$IMAGE" \\'," --no-allow-unauthenticated \\",` --port ${t.port} \\`,r," --timeout 3600 \\",' --add-volume name=state,type=cloud-storage,bucket="$STATE_BUCKET" \\'," --add-volume-mount volume=state,mount-path=/state \\",` --set-env-vars "${s}\${IDENTITY_ENV}" \\`,...i?[` --set-secrets ${i} \\`]:[],' --region "$REGION"',"",...wy(),"","# Notes:",e?"# - INBOUND channel (1b): pinned min=max=1 + CPU-always-on so the socket stays alive (can't scale to zero).":"# - No inbound channel (1a): scales to zero; state on the GCS volume survives the instance dying.","# - GCS-FUSE adds latency on session read/write vs local disk; fine for chat, watch for heavy I/O.",n?`# - Cursor engine: CURSOR_API_KEY secret + ${Kr("runtime","cursor")} base (AGENTHIPPO_CUSTOM_ENGINES_DIR=/engines).`:"# - Vertex path = keyless Claude on your existing GCP entitlement; swap for ANTHROPIC_API_KEY if preferred.","# - First deploy without IAP org setup: ENABLE_IAP=0 bash deploy/cloudrun-deploy.sh",""].join(`
561
+ `),i=["# T0.5 workbench/VM. Paths:","# T0.5a VPN: bash deploy/run.sh","# T0.5b remote: bash deploy/run-edge-tunnel.sh (Tunnel + Google SSO \u2014 recommended WFH)","# edge only: docker compose --profile edge up -d (SSO on :443, no tunnel)","services:",...my(t),...Ey(t.ingress==="edge-fed"),..._y(),"volumes:"," agenthippo-state:"," auth-broker-data:",""].join(`
562
+ `);return{Dockerfile:Cn(t),"Dockerfile.auth-broker":Ef(),"docker-compose.yml":i,"run.sh":n,"run-edge-tunnel.sh":yy(e),"agenthippo.service":r,"agenthippo-edge.service":s,Caddyfile:gy(t),"www/index.html":ws(t.packName),"cloudflared.yml":hy(e),"README.md":[`# Deploy: ${t.packName} \u2014 T0.5 workbench/VM`,"","Staging root = this directory's parent (full pack copy). Commands below run from the staging root unless noted.","","To regenerate: run `agenthippo deploy init <path-to-pack> --target vm` from the **parent** of the pack (not from inside the pack), then `cd deploy-out/"+t.packName+"-vm`.","","`cp deploy/.env.example deploy/.env` and fill in, then pick a path:","","**T0.5a \u2014 VPN only (simplest internal pilot)**","```bash","bash deploy/run.sh","# curl http://127.0.0.1:"+t.port+`/v1/chat -d '{"message":"hi"}' ...`,"```","","**T0.5b \u2014 Cloudflare Tunnel + Google SSO (recommended for WFH, no Access seats)**","```bash","cp deploy/.env.example deploy/.env # agent: model key + public hostname","cp deploy/.env.auth.example deploy/.env.auth # broker/oauth2-proxy: JWT + OAuth secrets (never loaded by the agent)","# 1. Google Cloud \u2192 OAuth Web client for https://"+e,"# Authorized origin + redirect: https://"+e+"/oauth2/callback","# 2. cloudflared tunnel create <name>","# cp ~/.cloudflared/<tunnel-id>.json ~/.agent-hippo/tunnel-credentials.json # secret","# set tunnel: <tunnel-id> in deploy/cloudflared.yml","# cloudflared tunnel route dns <name> "+e,"# 3. Fill deploy/.env (hostname, model key) and deploy/.env.auth (OAUTH2_PROXY_*, AGENTHIPPO_AUTH_JWT_SECRET)","bash deploy/run-edge-tunnel.sh","# Users open https://"+e+" \u2192 Google login \u2192 static chat UI \u2192 /v1/chat","```","Tunnel routing is **config-file mode** (`deploy/cloudflared.yml` \u2192 `http://caddy:80` on the compose network), not the Cloudflare dashboard public-hostname UI alone.","Optional: `agenthippo-edge.service` + `loginctl enable-linger $USER` for persistence.","","**Edge only (no tunnel)** \u2014 `docker compose --profile edge up -d` on LAN/VPN.","","Identity: Google \u2192 oauth2-proxy \u2192 `X-Agent-User` \u2192 serve (`www/index.html` sends a per-tab `session_id` for multi-turn).","Per-user *data* scoping needs Design B (\xA711.1) in the app layer \u2014 generic `serve` alone does not filter warehouse rows.","","**Do not commit** `deploy/.env`, `deploy/.env.auth`, or `deploy/tunnel-credentials.json`.","",...tr(t)].join(`
563
+ `)}}var Zc=["# Spotlight OTEL collector (compose-tuned: 0.0.0.0 bind). Writes JSONL to","# ${AGENT_HOME_DIR}/analytics/traces/ \u2014 query with query-analytics.sh (DuckDB).","receivers:"," otlp:"," protocols:"," http: { endpoint: 0.0.0.0:4318 }"," grpc: { endpoint: 0.0.0.0:4317 }","processors:"," batch: { timeout: 500ms, send_batch_size: 10 }"," resource:"," attributes:"," - { key: service.name, value: agentide-litellm, action: upsert }","exporters:"," file/jsonl:"," path: ${AGENT_HOME_DIR}/analytics/traces/traces.jsonl"," rotation: { max_megabytes: 100, max_days: 30, max_backups: 10 }","service:"," pipelines:"," traces: { receivers: [otlp], processors: [batch, resource], exporters: [file/jsonl] }",""].join(`
564
+ `);function l0(t){if(t.ingress==="edge-fed"&&t.colocate)return Ay(t);let e=t.gatewayChannels?.trim(),n=t.publicHostname,r=e?[" command:",' ["serve","--agent","/app/pack","--workspace","/state/workspace",',` "--state-dir","/state","--port","${t.port}",`,` "--gateway-bridge","--bind","${e}"]`]:[],s=e?[""," # Agent Anywhere gateway (OpenClaw) \u2014 Slack/Telegram bridge."," # Built from deploy/Dockerfile.channels (pinned HippoClaw npm). Not a GHCR image."," # NOTE: the gateway runs in secured auth mode \u2014 the agent bridge needs"," # OPENCLAW_GATEWAY_TOKEN (or a paired device) to connect. Set it in .env."," openclaw-gateway:",' profiles: ["channels"]'," build:"," context: ."," dockerfile: Dockerfile.channels"," env_file:"," - path: .env"," required: false",' volumes: ["openclaw-config:/root/.openclaw"]',' expose: ["18789"]']:[],i=[" environment:"," # Routed through LiteLLM only when the gateway profile is up; harmless otherwise."," AGENTHIPPO_LITELLM_BASE_URL: http://litellm:4443",...e?[" OPENCLAW_GATEWAY_URL: ws://openclaw-gateway:18789"]:[],...r],o=["# T2 team/fleet stack (serve-v3 \xA78). Profiles:","# default = agent only (Docker network; no host port \u2014 use deploy/run.sh for T0.5a VPN)","# --profile edge = + Caddy + oauth2-proxy (Google SSO)","# --profile tunnel = + cloudflared (with edge; route hostname \u2192 http://caddy:80)","# --profile gateway = + LiteLLM + Spotlight OTEL collector","# --profile channels = + OpenClaw gateway (Agent Anywhere)","# e.g.: docker compose -f deploy/docker-compose.yml --profile edge --profile tunnel up -d","services:",...my(t,i),...Ey(t.ingress==="edge-fed"),..._y()," # LiteLLM gateway \u2014 self-contained image bakes the Spotlight config + OTEL hooks"," # (build: docker build -f extensions/agentide/scripts/Dockerfile.litellm -t this-tag .)"," litellm:",' profiles: ["gateway"]',` image: ${ys("agenthippo-litellm")}`," env_file:"," - path: .env"," required: false"," environment:"," OTEL_EXPORTER: otlp_http"," OTEL_EXPORTER_OTLP_ENDPOINT: http://otel-collector:4318"," # The image defaults to --host 127.0.0.1 (safe when someone runs it bare)."," # Here it must answer the agent container over the compose network, so bind"," # 0.0.0.0 \u2014 and keep `expose:` rather than `ports:` so it is never reachable"," # from the host. Requires general_settings.master_key in the baked config.",' command: ["--config", "/config/litellm.config.yaml", "--port", "4443", "--host", "0.0.0.0"]',' expose: ["4443"]'," depends_on: [otel-collector]",""," # Spotlight collector \u2192 JSONL traces volume (query with query-analytics.sh / DuckDB)."," otel-collector:",' profiles: ["gateway"]'," image: otel/opentelemetry-collector-contrib:0.118.0",' command: ["--config=/etc/otel-collector.yaml"]'," # Root so the collector can create /data/analytics on a fresh named volume"," # (the contrib image runs non-root; the volume root is root-owned).",' user: "0:0"'," environment: { AGENT_HOME_DIR: /data }"," volumes:"," - ./otel-collector.yaml:/etc/otel-collector.yaml:ro"," - spotlight-traces:/data",...s,"","volumes:"," agenthippo-state:"," auth-broker-data:"," spotlight-traces:",...e?[" openclaw-config:"]:[],""].join(`
565
+ `);return{Dockerfile:Cn(t),"Dockerfile.auth-broker":Ef(),...e?{"Dockerfile.channels":py()}:{},"docker-compose.yml":o,Caddyfile:gy(t),"www/index.html":ws(t.packName),"cloudflared.yml":hy(n),"run-edge-tunnel.sh":yy(n),"otel-collector.yaml":Zc,"README.md":[`# Deploy: ${t.packName} \u2014 T2 team/fleet`,"","- Agent only (VPN): `docker compose -f deploy/docker-compose.yml up -d`","- + Tunnel + Google SSO: `bash deploy/run-edge-tunnel.sh` (see vm README T0.5b).","- + LiteLLM gateway + Spotlight: `--profile gateway`.","- + Agent Anywhere: `docker compose -f deploy/docker-compose.yml --profile channels up -d --build` + gateway env vars in `.env`.","","Profiles compose: e.g. `--profile gateway --profile edge --profile tunnel up -d`.","LiteLLM must speak Anthropic API format \u2014 our gateway image does.","",...tr(t)].join(`
566
+ `)}}function mi(t){let e=(t||"").toLowerCase();return e==="ah-auto"?"AGENTHIPPO_GATEWAY_KEY":e.includes("codex")?"OPENAI_CODEX_API_KEY":e.includes("gpt")||e.includes("openai")?"OPENAI_API_KEY":e.includes("claude")||e.includes("anthropic")?"ANTHROPIC_API_KEY":"OPENAI_API_KEY"}function Xo(t){return(t||"").trim().toLowerCase()==="ah-auto"}var Sy="https://gateway.agenthippo.ai/v1";function _f(t){return t.modelRouting==="gateway"}function Ty(t){if(t.engine.trim().toLowerCase()==="cursor")return"api2.cursor.sh";if(Xo(t.model))return"gateway.agenthippo.ai";let e=(t.model||"").toLowerCase();return e.includes("codex")||e.includes("gpt")||e.includes("openai")?"api.openai.com":"api.anthropic.com"}function tr(t){let e=_f(t)?".":" \u2014 and, if the LiteLLM gateway/Spotlight sidecar is enabled, its own outbound is the same host.";return[`**Egress:** this container only needs outbound access to \`${Ty(t)}:443\` (your model provider)${e}`,"Restrict egress to this allowlist if your org requires it.",""]}function u0(t,e,n,r,s){let i=[`\`${mi(t.model)}\` (or the pack's configured provider key) \u2014 your model provider credential`],o=["**agent container** \u2014 can reach your model provider and read/write its own state volume. Never holds the JWT signing secret or any OAuth client secret (`.env` vs `.env.auth` split)."];return n?(i.push("`AGENTHIPPO_AUTH_JWT_SECRET` \u2014 signs/verifies IDE bootstrap tokens (auth-broker only, never the agent)"),o.push("**auth-broker** \u2014 holds the JWT signing secret"+(r?" (shared with the central IdP)":"")+"; mints/verifies IDE tokens. Does not hold model provider credentials."),r||(i.push("`OAUTH2_PROXY_CLIENT_SECRET` + `OAUTH2_PROXY_COOKIE_SECRET` \u2014 this deployment's own Google OAuth client (oauth2-proxy only, never the agent)"),o.push("**oauth2-proxy** \u2014 holds this deployment's Google OAuth client secret; terminates the Google login flow. Does not hold the JWT signing secret or model credentials."))):s&&o.push("**this deployment holds no auth secrets at all** \u2014 identity is verified entirely by the org IdP's own auth-broker (see `agent-route.caddy`); nothing here signs or stores a JWT secret."),[`# Data & access summary \u2014 ${t.packName} (${e}${t.ingress?` / ${t.ingress}`:""})`,"","Generated by `agenthippo deploy init` \u2014 answers the questions a security review asks first.","","## Secrets",...i.map(a=>`- ${a}`),"","## Egress",`- Outbound network access is needed only to \`${Ty(t)}:443\` (your model provider).`,...n&&r?["- API/Bearer requests are verified locally against the shared JWT secret \u2014 no network call to the central IdP per request. The one-time browser login flow (unauthenticated visitors) does redirect to the central IdP's public URL to sign in."]:[],...n&&!r?["- Google SSO calls `accounts.google.com` during login only (oauth2-proxy); no other third party is contacted per request."]:[],...s?["- Identity is verified via the org IdP's own auth-broker over the shared private docker network (`agenthippo-idp-colocate`), not a public network call. The one-time browser login flow (unauthenticated visitors) still redirects to the central IdP's public URL to sign in."]:[],"","## Blast radius per component",...o.map(a=>`- ${a}`),""].join(`
567
+ `)}function d0(t){let e=mi(t.model);return["# Cloud Run multi-container: agent (ingress) + LiteLLM + Spotlight OTEL collector.","# Generated by `agenthippo deploy init`. Deploy with `bash deploy/cloudrun-deploy.sh`","# (it substitutes ${...} and runs `gcloud run services replace`). Traces land in the GCS","# /state volume at /state/analytics/traces \u2014 query with query-analytics.sh (DuckDB).","apiVersion: serving.knative.dev/v1","kind: Service","metadata:"," name: ${SERVICE}","spec:"," template:"," metadata:"," annotations:"," # Sidecars need CPU between requests (the collector flushes async); no scale-to-zero throttle.",' run.googleapis.com/cpu-throttling: "false"',' run.googleapis.com/startup-cpu-boost: "true"'," # Start order: collector \u2192 litellm \u2192 agent, so traces are never dropped on cold start.",` run.googleapis.com/container-dependencies: '{"litellm":["otel-collector"],"agent":["litellm"]}'`,' autoscaling.knative.dev/maxScale: "1"',...t.gatewayChannels?.trim()?[' autoscaling.knative.dev/minScale: "1"']:[]," spec:"," timeoutSeconds: 3600"," containers:"," # Ingress container \u2014 the ONLY one with a port. Routes the engine through LiteLLM."," - name: agent"," image: ${IMAGE}"," ports:"," - name: http1",` containerPort: ${t.port}`," env:"," - { name: AGENTHIPPO_HOME, value: /state }",' - { name: AGENTHIPPO_NO_AUTO_INSTALL, value: "1" }',' - { name: AGENTHIPPO_IDENTITY_HEADER, value: "${IDENTITY_HEADER_VALUE}" }',Qc()," - { name: AGENTHIPPO_LITELLM_BASE_URL, value: http://localhost:4443 }"," - name: AGENTHIPPO_LITELLM_API_KEY"," valueFrom:"," secretKeyRef: { name: ${SERVICE}-litellm-key, key: latest }"," volumeMounts:"," - { name: state, mountPath: /state }"," # LiteLLM gateway sidecar \u2014 exports every call to the collector (Spotlight cost/latency/tokens)."," - name: litellm"," image: ${LITELLM_IMAGE}"," env:"," - { name: OTEL_EXPORTER, value: otlp_http }"," - { name: OTEL_EXPORTER_OTLP_ENDPOINT, value: http://localhost:4318 }"," - name: LITELLM_MASTER_KEY"," valueFrom:"," secretKeyRef: { name: ${SERVICE}-litellm-key, key: latest }",` # Upstream provider key for ${t.model||"this model"} (matches the gateway's os.environ/${e} ref).`," # Other models need their own key var \u2014 rename to match your model map.",` - name: ${e}`," valueFrom:"," secretKeyRef: { name: ${SERVICE}-provider-key, key: latest }"," # Spotlight OTEL collector sidecar \u2014 writes JSONL traces into the shared /state volume."," - name: otel-collector"," image: otel/opentelemetry-collector-contrib:0.118.0",' args: ["--config=/etc/otel/config.yaml"]'," env:"," - { name: AGENT_HOME_DIR, value: /state }"," volumeMounts:"," - { name: otel-config, mountPath: /etc/otel, readOnly: true }"," - { name: state, mountPath: /state }"," volumes:"," - name: state"," csi:"," driver: gcsfuse.run.googleapis.com"," volumeAttributes:"," bucketName: ${STATE_BUCKET}"," - name: otel-config"," secret:"," secretName: ${SERVICE}-otel-config"," items:"," - { key: latest, path: config.yaml }",""].join(`
568
+ `)}function Kr(){return["# Anchor to the staging root (parent of deploy/) \u2014 this script runs from any cwd.",'cd "$(dirname "$0")/.."']}function by(){return["# Ingress: corp SSO via IAP (forwards X-Goog-Authenticated-User-Email \u2192 user_id).","# --iap is beta-track only on `gcloud run`; public access on an existing service is","# controlled via the run.invoker IAM binding (no --no-allow-unauthenticated on","# `services update`). So: enable IAP on the beta track, strip any allUsers invoker","# binding (keeps the service private), and grant IAP-secured Web User to each","# principal in IAP_MEMBERS (space-separated, e.g.","# IAP_MEMBERS='user:you@corp.com serviceAccount:sa@project.iam.gserviceaccount.com'","# ). Omit IAP_MEMBERS to rely on bindings you manage out-of-band.",'if [[ "${ENABLE_IAP:-1}" == "1" ]]; then',' gcloud beta run services update "$SERVICE" --region "$REGION" --iap',' gcloud run services remove-iam-policy-binding "$SERVICE" --region "$REGION" \\'," --member=allUsers --role=roles/run.invoker >/dev/null 2>&1 || true"," for m in ${IAP_MEMBERS:-}; do"," gcloud beta iap web add-iam-policy-binding \\",' --resource-type=cloud-run --service="$SERVICE" --region="$REGION" \\',' --member="$m" --role=roles/iap.httpsResourceAccessor'," done","fi"]}function f0(t){return["#!/usr/bin/env bash",`# Cloud Run + Spotlight: agent + LiteLLM + OTEL collector sidecars (engine: ${t.engine}${t.model?`, model ${t.model}`:""}).`,"# Traces persist in the GCS /state bucket; query with query-analytics.sh (DuckDB).","set -euo pipefail",...Kr(),`SERVICE="${t.packName}"`,'REGION="${REGION:-us-central1}"','PROJECT_ID="${PROJECT_ID:-$(gcloud config get-value project)}"','REPO="${ARTIFACT_REPO:-agenthippo}"','IMAGE="${REGION}-docker.pkg.dev/${PROJECT_ID}/${REPO}/${SERVICE}:latest"',`LITELLM_IMAGE="\${LITELLM_IMAGE:-${ys("agenthippo-litellm")}}"`,'STATE_BUCKET="${STATE_BUCKET:?set STATE_BUCKET=your-gcs-bucket (gcloud storage buckets create gs://...)}"',"# LITELLM_KEY = the proxy key the agent presents to LiteLLM (and LiteLLM master key).",'LITELLM_KEY="${LITELLM_KEY:?set LITELLM_KEY=<litellm proxy key>}"',`# PROVIDER_KEY = upstream key the gateway uses for ${t.model||"your model"} (gateway reads ${mi(t.model)}).`,'PROVIDER_KEY="${PROVIDER_KEY:?set PROVIDER_KEY=<upstream provider key>}"',"",'gcloud artifacts repositories describe "$REPO" --location="$REGION" 2>/dev/null \\',' || gcloud artifacts repositories create "$REPO" --repository-format=docker --location="$REGION"','gcloud auth configure-docker "${REGION}-docker.pkg.dev" --quiet',"","# Rewrite the runtime base to this project Artifact Registry. Customer artifacts pin a","# dated ghcr.io/agenthippoai/runtime tag; mirror that exact tag into AR. No-op if already AR.",'DF_TMP="$(mktemp)"','sed "s|FROM ghcr.io/agenthippoai/runtime:|FROM ${REGION}-docker.pkg.dev/${PROJECT_ID}/${REPO}/runtime:|" deploy/Dockerfile > "$DF_TMP"','docker build --pull --platform linux/amd64 -f "$DF_TMP" -t "$IMAGE" .','docker push "$IMAGE"',"","# Secrets: Spotlight collector config + the LiteLLM proxy key.",'ensure_secret() { gcloud secrets describe "$1" >/dev/null 2>&1 || gcloud secrets create "$1" --replication-policy=automatic; }','ensure_secret "${SERVICE}-otel-config"; gcloud secrets versions add "${SERVICE}-otel-config" --data-file=deploy/otel-collector.yaml','ensure_secret "${SERVICE}-litellm-key"; printf %s "$LITELLM_KEY" | gcloud secrets versions add "${SERVICE}-litellm-key" --data-file=-','ensure_secret "${SERVICE}-provider-key"; printf %s "$PROVIDER_KEY" | gcloud secrets versions add "${SERVICE}-provider-key" --data-file=-',"","# IAP (finalized below) forwards X-Goog-Authenticated-User-Email; pin serve to trust ONLY","# that header so an authenticated caller cannot impersonate another user via a spoofed","# X-Agent-User header. Skipped when ENABLE_IAP=0 (first-deploy bootstrap) since IAP never","# sets the header then.",'IDENTITY_HEADER_VALUE=""','[[ "${ENABLE_IAP:-1}" == "1" ]] && IDENTITY_HEADER_VALUE="x-goog-authenticated-user-email" || true',"","# Render the multi-container template for this project (sed \u2014 no gettext dependency) and deploy.",'RENDERED="$(mktemp)"','sed -e "s|\\${SERVICE}|${SERVICE}|g" -e "s|\\${IMAGE}|${IMAGE}|g" \\',' -e "s|\\${LITELLM_IMAGE}|${LITELLM_IMAGE}|g" -e "s|\\${STATE_BUCKET}|${STATE_BUCKET}|g" \\',' -e "s|\\${IDENTITY_HEADER_VALUE}|${IDENTITY_HEADER_VALUE}|g" \\',' deploy/service.yaml > "$RENDERED"','gcloud run services replace "$RENDERED" --region "$REGION"',"",...by(),"","# Grant the runtime SA access to the secrets if needed:",`# SA="$(gcloud run services describe "$SERVICE" --region "$REGION" --format='value(spec.template.spec.serviceAccountName)')"`,'# for s in "${SERVICE}-otel-config" "${SERVICE}-litellm-key"; do gcloud secrets add-iam-policy-binding "$s" --member="serviceAccount:$SA" --role=roles/secretmanager.secretAccessor; done',""].join(`
569
+ `)}function p0(t){let e=t.engine.trim().toLowerCase()==="cursor",n=mi(t.model),r=hi(t,{wwwDir:"/app/pack/deploy/www",port:ot.EDGE_AGENT_PORT}).map(o=>`"${o.replace(/"/g,'\\"')}"`).join(", "),i=["# Cloud Run + AgentHippo edge (Option B): Caddy (ingress) + oauth2-proxy + auth-broker","# + agent (+ LiteLLM + OTEL collector for Spotlight). No IAP \u2014 Caddy gates via SSO,","# so the IDE hits the public hostname directly with its AgentHippo Bearer token.","# Generated by `agenthippo deploy init --target cloudrun --ingress edge`.","apiVersion: serving.knative.dev/v1","kind: Service","metadata:"," name: ${SERVICE}","spec:"," template:"," metadata:"," annotations:",' run.googleapis.com/cpu-throttling: "false"',' run.googleapis.com/startup-cpu-boost: "true"',` run.googleapis.com/container-dependencies: '${e?'{"caddy":["agent","oauth2-proxy","auth-broker"]}':'{"caddy":["agent","oauth2-proxy","auth-broker"],"agent":["litellm"],"litellm":["otel-collector"]}'}'`,' autoscaling.knative.dev/maxScale: "1"',...t.gatewayChannels?.trim()?[' autoscaling.knative.dev/minScale: "1"']:[]," spec:"," timeoutSeconds: 3600"," containers:"," # Ingress \u2014 the ONLY container with a port. SSO edge for browsers + IDE Bearer."," - name: caddy"," image: caddy:2.8-alpine"," ports:"," - name: http1",` containerPort: ${t.port}`," volumeMounts:"," - { name: caddy-config, mountPath: /etc/caddy, readOnly: true }"," # Auth broker \u2014 validates IDE Bearer JWTs (/api/ide/me) + IDE sign-in (/oauth/*)."," # Reuses the agent runtime image (the `agenthippo` CLI ships `auth-broker`)."," - name: auth-broker"," image: ${IMAGE}",' args: ["auth-broker"]'," env:",' - { name: AGENTHIPPO_AUTH_PORT, value: "9780" }'," - { name: AGENTHIPPO_AUTH_DATA_DIR, value: /data }"," - { name: AGENTHIPPO_AUTH_PUBLIC_URL, value: https://${PUBLIC_HOSTNAME} }"," - { name: AGENTHIPPO_AUTH_ALLOWED_DOMAINS, value: ${ALLOWED_DOMAINS} }"," - name: AGENTHIPPO_AUTH_JWT_SECRET"," valueFrom:"," secretKeyRef: { name: ${SERVICE}-auth-jwt-secret, key: latest }"," # oauth2-proxy \u2014 Google SSO for browser clients (provider=google)."," - name: oauth2-proxy"," image: quay.io/oauth2-proxy/oauth2-proxy:v7.7.1"," env:"," - { name: OAUTH2_PROXY_HTTP_ADDRESS, value: 0.0.0.0:4180 }"," - { name: OAUTH2_PROXY_UPSTREAMS, value: file:///dev/null }",' - { name: OAUTH2_PROXY_SET_XAUTHREQUEST, value: "true" }',' - { name: OAUTH2_PROXY_PASS_AUTHORIZATION_HEADER, value: "true" }',' - { name: OAUTH2_PROXY_SKIP_PROVIDER_BUTTON, value: "true" }',' - { name: OAUTH2_PROXY_REVERSE_PROXY, value: "true" }'," - { name: OAUTH2_PROXY_PROVIDER, value: google }"," - { name: OAUTH2_PROXY_EMAIL_DOMAINS, value: ${ALLOWED_DOMAINS} }"," - { name: OAUTH2_PROXY_REDIRECT_URL, value: https://${PUBLIC_HOSTNAME}/oauth2/callback }"," - name: OAUTH2_PROXY_CLIENT_ID"," valueFrom:"," secretKeyRef: { name: ${SERVICE}-oauth-client-id, key: latest }"," - name: OAUTH2_PROXY_CLIENT_SECRET"," valueFrom:"," secretKeyRef: { name: ${SERVICE}-oauth-client-secret, key: latest }"," - name: OAUTH2_PROXY_COOKIE_SECRET"," valueFrom:"," secretKeyRef: { name: ${SERVICE}-oauth-cookie-secret, key: latest }"," # Agent \u2014 serves www + /v1/* on localhost (NOT ingress). Routed through LiteLLM."," - name: agent"," image: ${IMAGE}",` args: [${r}]`," env:"," - { name: AGENTHIPPO_HOME, value: /state }",' - { name: AGENTHIPPO_NO_AUTO_INSTALL, value: "1" }',Qc(),...e?[" - { name: AGENTHIPPO_CUSTOM_ENGINES_DIR, value: /engines }"," - name: CURSOR_API_KEY"," valueFrom:"," secretKeyRef: { name: ${SERVICE}-provider-key, key: latest }"]:[" - { name: AGENTHIPPO_LITELLM_BASE_URL, value: http://localhost:4443 }"," - name: AGENTHIPPO_LITELLM_API_KEY"," valueFrom:"," secretKeyRef: { name: ${SERVICE}-litellm-key, key: latest }"]," volumeMounts:"," - { name: state, mountPath: /state }",..._s(ot.EDGE_AGENT_PORT,!0),...Pr("2000m","2Gi")];return e||i.push(" # LiteLLM gateway sidecar \u2014 exports every call to the collector (Spotlight)."," - name: litellm"," image: ${LITELLM_IMAGE}"," env:"," - { name: OTEL_EXPORTER, value: otlp_http }"," - { name: OTEL_EXPORTER_OTLP_ENDPOINT, value: http://localhost:4318 }"," - name: LITELLM_MASTER_KEY"," valueFrom:"," secretKeyRef: { name: ${SERVICE}-litellm-key, key: latest }",` # Upstream provider key for ${t.model||"this model"} (matches the gateway's os.environ/${n} ref).`,` - name: ${n}`," valueFrom:"," secretKeyRef: { name: ${SERVICE}-provider-key, key: latest }",..._s(4443),...Pr("1000m","1Gi")," # Spotlight OTEL collector sidecar \u2014 writes JSONL traces into the shared /state volume."," - name: otel-collector"," image: otel/opentelemetry-collector-contrib:0.118.0",' args: ["--config=/etc/otel/config.yaml"]'," env:"," - { name: AGENT_HOME_DIR, value: /state }"," volumeMounts:"," - { name: otel-config, mountPath: /etc/otel, readOnly: true }"," - { name: state, mountPath: /state }",..._s(4318),...Pr("1000m","512Mi")),i.push(" volumes:"," - name: state"," csi:"," driver: gcsfuse.run.googleapis.com"," volumeAttributes:"," bucketName: ${STATE_BUCKET}"," - name: caddy-config"," secret:"," secretName: ${SERVICE}-caddyfile"," items:"," - { key: latest, path: Caddyfile }"),e||i.push(" - name: otel-config"," secret:"," secretName: ${SERVICE}-otel-config"," items:"," - { key: latest, path: config.yaml }"),i.push(""),i.join(`
570
+ `)}function g0(t){let e=t.engine.trim().toLowerCase()==="cursor",n=t.model?.trim()?`, model ${t.model.trim()}`:"",r=["#!/usr/bin/env bash","# Cloud Run + AgentHippo edge (Option B): Caddy + oauth2-proxy + auth-broker front the agent.",`# Engine: ${t.engine}${n}. No IAP \u2014 Caddy gates via SSO (Google for browsers, AgentHippo JWT for IDE).`,"# The IDE points spec.remote.url straight at https://$PUBLIC_HOSTNAME (same flow as remote-vm).","set -euo pipefail",...Kr(),`SERVICE="${t.packName}"`,'REGION="${REGION:-us-central1}"','PROJECT_ID="${PROJECT_ID:-$(gcloud config get-value project)}"','REPO="${ARTIFACT_REPO:-agenthippo}"','IMAGE="${REGION}-docker.pkg.dev/${PROJECT_ID}/${REPO}/${SERVICE}:latest"',`LITELLM_IMAGE="\${LITELLM_IMAGE:-${ys("agenthippo-litellm")}}"`,"# Public hostname (custom domain mapped to the service) + the Google Workspace domain allowed by SSO.",'PUBLIC_HOSTNAME="${PUBLIC_HOSTNAME:?set PUBLIC_HOSTNAME=your.edge.hostname (gcloud run domain-mappings create --service $SERVICE --domain ...)}"','ALLOWED_DOMAINS="${ALLOWED_DOMAINS:?set ALLOWED_DOMAINS=yourworkspace.com (oauth2-proxy email domain + broker allowed domains)}"','STATE_BUCKET="${STATE_BUCKET:?set STATE_BUCKET=your-gcs-bucket (gcloud storage buckets create gs://...)}"',"# Edge secrets (from .env.auth): Google OAuth client + cookie secret + AgentHippo JWT signing key.",'OAUTH_CLIENT_ID="${OAUTH_CLIENT_ID:?set OAUTH_CLIENT_ID=<google oauth web client id>}"','OAUTH_CLIENT_SECRET="${OAUTH_CLIENT_SECRET:?set OAUTH_CLIENT_SECRET=<google oauth web client secret>}"','OAUTH_COOKIE_SECRET="${OAUTH_COOKIE_SECRET:?set OAUTH_COOKIE_SECRET=$(openssl rand -base64 32 | head -c 32)}"','AUTH_JWT_SECRET="${AUTH_JWT_SECRET:?set AUTH_JWT_SECRET=$(openssl rand -hex 32)}"',...e?['PROVIDER_KEY="${PROVIDER_KEY:?set PROVIDER_KEY=<cursor api key>}"']:["# LiteLLM proxy key + the upstream provider key the gateway uses for the model.",'LITELLM_KEY="${LITELLM_KEY:?set LITELLM_KEY=<litellm proxy key>}"','PROVIDER_KEY="${PROVIDER_KEY:?set PROVIDER_KEY=<upstream provider key>}"'],"",'gcloud artifacts repositories describe "$REPO" --location="$REGION" 2>/dev/null \\',' || gcloud artifacts repositories create "$REPO" --repository-format=docker --location="$REGION"','gcloud auth configure-docker "${REGION}-docker.pkg.dev" --quiet',"","# One agent image serves both the agent and the auth-broker containers (CLI ships `auth-broker`).","# Rewrite the runtime base to this project Artifact Registry. Customer artifacts pin a","# dated ghcr.io/agenthippoai/runtime tag; mirror that exact tag into AR. No-op if already AR.",'DF_TMP="$(mktemp)"','sed "s|FROM ghcr.io/agenthippoai/runtime:|FROM ${REGION}-docker.pkg.dev/${PROJECT_ID}/${REPO}/runtime:|" deploy/Dockerfile > "$DF_TMP"','docker build --pull --platform linux/amd64 -f "$DF_TMP" -t "$IMAGE" .','docker push "$IMAGE"',"","# Secrets: edge config + provider/litellm keys.",'ensure_secret() { gcloud secrets describe "$1" >/dev/null 2>&1 || gcloud secrets create "$1" --replication-policy=automatic; }','ensure_secret "${SERVICE}-caddyfile"; gcloud secrets versions add "${SERVICE}-caddyfile" --data-file=deploy/Caddyfile','ensure_secret "${SERVICE}-auth-jwt-secret"; printf %s "$AUTH_JWT_SECRET" | gcloud secrets versions add "${SERVICE}-auth-jwt-secret" --data-file=-','ensure_secret "${SERVICE}-oauth-client-id"; printf %s "$OAUTH_CLIENT_ID" | gcloud secrets versions add "${SERVICE}-oauth-client-id" --data-file=-','ensure_secret "${SERVICE}-oauth-client-secret"; printf %s "$OAUTH_CLIENT_SECRET" | gcloud secrets versions add "${SERVICE}-oauth-client-secret" --data-file=-','ensure_secret "${SERVICE}-oauth-cookie-secret"; printf %s "$OAUTH_COOKIE_SECRET" | gcloud secrets versions add "${SERVICE}-oauth-cookie-secret" --data-file=-','ensure_secret "${SERVICE}-provider-key"; printf %s "$PROVIDER_KEY" | gcloud secrets versions add "${SERVICE}-provider-key" --data-file=-'];return e||r.push('ensure_secret "${SERVICE}-otel-config"; gcloud secrets versions add "${SERVICE}-otel-config" --data-file=deploy/otel-collector.yaml','ensure_secret "${SERVICE}-litellm-key"; printf %s "$LITELLM_KEY" | gcloud secrets versions add "${SERVICE}-litellm-key" --data-file=-'),r.push("","# Render the multi-container template for this project (sed \u2014 no gettext dependency) and deploy.",'RENDERED="$(mktemp)"','sed -e "s|\\${SERVICE}|${SERVICE}|g" -e "s|\\${IMAGE}|${IMAGE}|g" \\',' -e "s|\\${LITELLM_IMAGE}|${LITELLM_IMAGE}|g" -e "s|\\${STATE_BUCKET}|${STATE_BUCKET}|g" \\',' -e "s|\\${PUBLIC_HOSTNAME}|${PUBLIC_HOSTNAME}|g" -e "s|\\${ALLOWED_DOMAINS}|${ALLOWED_DOMAINS}|g" \\',' deploy/service.yaml > "$RENDERED"','gcloud run services replace "$RENDERED" --region "$REGION"',"","# No IAP: Caddy is the gate, so Cloud Run itself must allow public ingress (allUsers invoker).","# Without this, Cloud Run 403s before Caddy ever sees the request to run SSO.",'gcloud run services add-iam-policy-binding "$SERVICE" --region "$REGION" \\'," --member=allUsers --role=roles/run.invoker >/dev/null 2>&1 || true","",'# Map the custom domain (once): gcloud run domain-mappings create --service "$SERVICE" --region "$REGION" --domain "$PUBLIC_HOSTNAME"',"# Then add the CNAME Cloud Run prints to your DNS. Google OAuth Web client must list","# https://$PUBLIC_HOSTNAME as an authorized origin + https://$PUBLIC_HOSTNAME/oauth2/callback as a redirect.","","# Grant the runtime SA access to the secrets if needed:",`# SA="$(gcloud run services describe "$SERVICE" --region "$REGION" --format='value(spec.template.spec.serviceAccountName)')"`,'# for s in "${SERVICE}-caddyfile" "${SERVICE}-auth-jwt-secret" "${SERVICE}-oauth-client-id" "${SERVICE}-oauth-client-secret" "${SERVICE}-oauth-cookie-secret" "${SERVICE}-provider-key"; do','# gcloud secrets add-iam-policy-binding "$s" --member="serviceAccount:$SA" --role=roles/secretmanager.secretAccessor',"# done",""),r.join(`
571
+ `)}function h0(t){let e=!!t.gatewayChannels?.trim(),n=t.engine.trim().toLowerCase()==="cursor";if(t.ingress==="edge")return m0(t,e,n);if(t.ingress==="edge-fed")return A0(t,e,n);if(!n)return{Dockerfile:Cn(t,{wwwDir:"/app/pack/deploy/www"}),"www/index.html":ws(t.packName),"service.yaml":d0(t),"otel-collector.yaml":Zc,"cloudrun-deploy.sh":f0(t),"README.md":[`# Deploy: ${t.packName} \u2014 Cloud Run + Spotlight (multi-container)`,"",`Engine: **${t.engine}**${t.model?`, model: **${t.model}**`:""}. Runtime base: \`${t.image}\`.`,"","Three sidecars share the pod's localhost (Cloud Run multi-container):","- **agent** (ingress) \u2192 routes the engine to `http://localhost:4443`","- **litellm** gateway \u2192 exports OTLP to `http://localhost:4318`","- **otel-collector** \u2192 writes JSONL traces to the GCS `/state` volume (`/state/analytics/traces`).","","```bash","gcloud storage buckets create gs://<your-state-bucket> # once","export STATE_BUCKET=<your-state-bucket> LITELLM_KEY=<litellm proxy key>","bash deploy/cloudrun-deploy.sh # builds linux/amd64, creates secrets, `gcloud run services replace service.yaml`","```","","`service.yaml` is the multi-container template (checked in so the wiring is reviewable);","the deploy script substitutes `${SERVICE} ${IMAGE} ${STATE_BUCKET} ${LITELLM_IMAGE}`.","Provider creds (Anthropic key / Vertex ADC / OpenAI \u2026) go on the **litellm** sidecar, not the agent.","",e?"**Inbound channel (1b):** `minScale: 1` pins one always-on instance (the socket can't scale to zero).":"**No inbound channel (1a):** scales to zero; traces + sessions persist on the GCS `/state` volume.","","**Spotlight:** once traffic flows, query the GCS-backed traces with `query-analytics.sh` (DuckDB) against `/state/analytics/traces`.","","**Lean alternative (no Spotlight):** a single-container deploy that calls a provider directly","(or an external LiteLLM) \u2014 set `AGENTHIPPO_LITELLM_BASE_URL` to your endpoint and drop the sidecars.","",...tr(t)].join(`
572
+ `)};let r=e?" --min-instances 1 --max-instances 1 --no-cpu-throttling \\":" --min-instances 0 --max-instances 1 \\",s=n?"AGENTHIPPO_NO_AUTO_INSTALL=1,AGENTHIPPO_HOME=/state,AGENTHIPPO_CUSTOM_ENGINES_DIR=/engines":"CLAUDE_CODE_USE_VERTEX=1,AGENTHIPPO_NO_AUTO_INSTALL=1,AGENTHIPPO_HOME=/state",i=n?"CURSOR_API_KEY=agenthippo-cursor-key:latest":void 0,o=t.model?.trim()?`, model ${t.model.trim()}`:"",a=["#!/usr/bin/env bash","# T1-generic: Cloud Run with built-in IAP (corp SSO, no load balancer).",`# Engine: ${t.engine}${o}. IAP forwards X-Goog-Authenticated-User-Email \u2192 user_id.`,"set -euo pipefail",...Kr(),`SERVICE="${t.packName}"`,'REGION="${REGION:-us-central1}"','PROJECT_ID="${PROJECT_ID:-$(gcloud config get-value project)}"','REPO="${ARTIFACT_REPO:-agenthippo}"','IMAGE="${REGION}-docker.pkg.dev/${PROJECT_ID}/${REPO}/${SERVICE}:latest"',"# Q1: durable state. Cloud Run local disk is ephemeral (wiped on scale-to-zero),","# so mount a GCS bucket at /state \u2014 sessions/provider-sessions/analytics survive.",'STATE_BUCKET="${STATE_BUCKET:?set STATE_BUCKET=your-gcs-bucket (gcloud storage buckets create gs://...)}"',"",'gcloud artifacts repositories describe "$REPO" --location="$REGION" 2>/dev/null \\',' || gcloud artifacts repositories create "$REPO" --repository-format=docker --location="$REGION"','gcloud auth configure-docker "${REGION}-docker.pkg.dev" --quiet',"","# Build from pack root; Dockerfile is deploy/Dockerfile (not pack root \u2014 gcloud --source . misses it).","# Rewrite the runtime base to this project Artifact Registry. Customer artifacts pin a","# dated ghcr.io/agenthippoai/runtime tag; mirror that exact tag into AR. No-op if already AR.",'DF_TMP="$(mktemp)"','sed "s|FROM ghcr.io/agenthippoai/runtime:|FROM ${REGION}-docker.pkg.dev/${PROJECT_ID}/${REPO}/runtime:|" deploy/Dockerfile > "$DF_TMP"','docker build --pull --platform linux/amd64 -f "$DF_TMP" -t "$IMAGE" .','docker push "$IMAGE"',"","# IAP (when enabled below) forwards X-Goog-Authenticated-User-Email; pin serve to trust","# ONLY that header so an authenticated caller cannot impersonate another user via a","# spoofed X-Agent-User header. Skipped when ENABLE_IAP=0 (first-deploy bootstrap) since","# IAP never sets the header then \u2014 pinning to an absent header would make every request","# anonymous instead of leaving body-supplied identity usable during bootstrap.",'IDENTITY_ENV=""','[[ "${ENABLE_IAP:-1}" == "1" ]] && IDENTITY_ENV=",AGENTHIPPO_IDENTITY_HEADER=x-goog-authenticated-user-email" || true',"","# Deploy private (no --allow-unauthenticated). IAP + role grants are applied below on the beta track.",'gcloud run deploy "$SERVICE" \\',' --image "$IMAGE" \\'," --no-allow-unauthenticated \\",` --port ${t.port} \\`,r," --timeout 3600 \\",' --add-volume name=state,type=cloud-storage,bucket="$STATE_BUCKET" \\'," --add-volume-mount volume=state,mount-path=/state \\",` --set-env-vars "${s}\${IDENTITY_ENV}" \\`,...i?[` --set-secrets ${i} \\`]:[],' --region "$REGION"',"",...by(),"","# Notes:",e?"# - INBOUND channel (1b): pinned min=max=1 + CPU-always-on so the socket stays alive (can't scale to zero).":"# - No inbound channel (1a): scales to zero; state on the GCS volume survives the instance dying.","# - GCS-FUSE adds latency on session read/write vs local disk; fine for chat, watch for heavy I/O.",n?`# - Cursor engine: CURSOR_API_KEY secret + ${ys("runtime","cursor")} base (AGENTHIPPO_CUSTOM_ENGINES_DIR=/engines).`:"# - Vertex path = keyless Claude on your existing GCP entitlement; swap for ANTHROPIC_API_KEY if preferred.","# - First deploy without IAP org setup: ENABLE_IAP=0 bash deploy/cloudrun-deploy.sh",""].join(`
572
573
  `),c=n?["2. `gcloud secrets create agenthippo-cursor-key --data-file=-` (paste your `CURSOR_API_KEY`).","3. Grant Cloud Run access: `gcloud secrets add-iam-policy-binding agenthippo-cursor-key --member=serviceAccount:PROJECT_NUMBER-compute@developer.gserviceaccount.com --role=roles/secretmanager.secretAccessor`.","4. `bash deploy/cloudrun-deploy.sh` \u2014 builds linux/amd64, pushes to Artifact Registry, deploys with GCS /state."]:["2. `bash deploy/cloudrun-deploy.sh` \u2014 builds linux/amd64, pushes to Artifact Registry, deploys with `--iap` + GCS /state."];return{Dockerfile:Cn(t,{wwwDir:"/app/pack/deploy/www"}),"www/index.html":ws(t.packName),"cloudrun-deploy.sh":a,"README.md":[`# Deploy: ${t.packName} \u2014 Cloud Run (T1-generic)`,"",`Engine: **${t.engine}**${t.model?`, model: **${t.model}**`:""}. Runtime base: \`${t.image}\`.`,"","1. `gcloud storage buckets create gs://<your-state-bucket>` then `export STATE_BUCKET=<your-state-bucket>`.",...c,"","SSO + ingress: built-in IAP (`X-Goog-Authenticated-User-Email`). **Q1:** `/state` is a mounted GCS bucket.",t.gatewayChannels?"**Inbound channel (1b):** pinned single always-on instance (no scale-to-zero).":"**No inbound channel (1a):** scales to zero; state persists on GCS.","","**Browser:** open the service URL \u2192 Google login \u2192 chat UI at `/` (same as vm `deploy/www/index.html`).","","**Verify** (smoke test via local proxy \u2014 bypasses IAP auth for direct testing):","```bash",`gcloud run services proxy ${t.packName} --region "\${REGION:-us-central1}" &`,"PROXY=http://127.0.0.1:8080",'curl -s "$PROXY/ready"','curl -s -XPOST "$PROXY/v1/chat" \\',' -H "X-Goog-Authenticated-User-Email: accounts.google.com:you@corp.com" \\',' -H "Content-Type: application/json" \\',` -d '{"message":"Reply with exactly: CLOUDRUN_OK","session_id":"cr-1"}'`,"```","",...tr(t)].join(`
573
- `)}}function f0(t,e,n){let r=n?"Caddy (ingress) + oauth2-proxy + auth-broker + agent.":"Caddy (ingress) + oauth2-proxy + auth-broker + agent + LiteLLM + OTEL collector (Spotlight).",s={Dockerfile:Cn(t,{wwwDir:"/app/pack/deploy/www"}),"www/index.html":ws(t.packName),Caddyfile:(0,ot.renderSidecarEdgeCaddyfile)(),"service.yaml":l0(t),"cloudrun-deploy.sh":u0(t)};return n||(s["otel-collector.yaml"]=Qc),s["README.md"]=[`# Deploy: ${t.packName} \u2014 Cloud Run + AgentHippo edge (Option B)`,"",`Engine: **${t.engine}**${t.model?`, model: **${t.model}**`:""}. Runtime base: \`${t.image}\`.`,"",`${r} Sidecars share the pod's localhost (Cloud Run multi-container):`,"- **caddy** (ingress, the only port) \u2192 SSO edge: oauth2-proxy for browsers, auth-broker for IDE Bearer",`- **agent** \u2192 serves www + /v1/* on localhost:${ot.EDGE_AGENT_PORT} (NOT ingress)`,"- **auth-broker** \u2192 validates IDE AgentHippo JWTs (`/api/ide/me`) + IDE sign-in (`/oauth/*`)","- **oauth2-proxy** \u2192 Google SSO for browser clients (`provider=google`)",...n?[]:["- **litellm** gateway \u2192 exports OTLP to `http://localhost:4318`","- **otel-collector** \u2192 writes JSONL traces to the GCS `/state` volume"],"","**No IAP** \u2014 Caddy is the gate, so the IDE points `spec.remote.url` straight at","`https://$PUBLIC_HOSTNAME` and the existing AgentHippo SSO flow works (same as `remote-vm`).","Cloud Run itself is public (`allUsers` invoker) so traffic can reach Caddy to be authed.","","```bash","gcloud storage buckets create gs://<state-bucket> # once","cp deploy/.env.example deploy/.env && cp deploy/.env.auth.example deploy/.env.auth # fill both","export PUBLIC_HOSTNAME=<your.edge.hostname> ALLOWED_DOMAINS=<yourworkspace.com>","export OAUTH_CLIENT_ID=\u2026 OAUTH_CLIENT_SECRET=\u2026 OAUTH_COOKIE_SECRET=\u2026 AUTH_JWT_SECRET=\u2026",...n?["export PROVIDER_KEY=<cursor api key>"]:["export LITELLM_KEY=\u2026 PROVIDER_KEY=\u2026 STATE_BUCKET=<state-bucket>"],"bash deploy/cloudrun-deploy.sh # builds linux/amd64, upserts secrets, `gcloud run services replace`",'gcloud run domain-mappings create --service "$SERVICE" --region "${REGION:-us-central1}" --domain "$PUBLIC_HOSTNAME" # once',"```","","Google OAuth Web client (for oauth2-proxy): authorized origin `https://$PUBLIC_HOSTNAME`,","redirect `https://$PUBLIC_HOSTNAME/oauth2/callback`. Restrict to your Workspace domain via","`ALLOWED_DOMAINS` (oauth2-proxy `email_domains` + broker `allowed_domains`).","","`service.yaml` placeholders (`${SERVICE} ${IMAGE} ${LITELLM_IMAGE} ${STATE_BUCKET} ${PUBLIC_HOSTNAME} ${ALLOWED_DOMAINS}`)","are substituted by the deploy script. The Caddyfile is stored in Secret Manager (`${SERVICE}-caddyfile`).","",e?"**Inbound channel (1b):** `minScale: 1` pins one always-on instance (the socket can't scale to zero).":"**No inbound channel (1a):** scales to zero; traces + sessions persist on the GCS `/state` volume.","",...tr(t)].join(`
574
- `),s}function ys(t,e=!1){return e?[" startupProbe:"," failureThreshold: 48"," periodSeconds: 5"," tcpSocket:",` port: ${t}`," timeoutSeconds: 3"]:[" startupProbe:"," failureThreshold: 30"," periodSeconds: 5"," tcpSocket:",` port: ${t}`," timeoutSeconds: 3"]}function Pr(t,e){return[" resources:"," limits:",` cpu: ${t}`,` memory: ${e}`]}function p0(t){let e=t.engine.trim().toLowerCase()==="cursor",n=mi(t.model),r=hi(t,{wwwDir:"/app/pack/deploy/www",port:ot.EDGE_AGENT_PORT}).map(c=>`"${c.replace(/"/g,'\\"')}"`).join(", "),s=(t.cookieDomain||".agenthippo.ai").trim(),i=(t.idpUrl||"https://auth.agenthippo.ai").trim().replace(/\/+$/,""),a=["# Cloud Run + AgentHippo federated edge (A\u2032): Caddy (ingress) + auth-broker + agent","# (+ LiteLLM + OTEL collector for Spotlight). No oauth2-proxy \u2014 Google login happens once","# at the central IdP; this agent verifies the shared .agenthippo.ai AgentHippo JWT.","# Generated by `agenthippo deploy init --target cloudrun --ingress edge-fed`.","apiVersion: serving.knative.dev/v1","kind: Service","metadata:"," name: ${SERVICE}","spec:"," template:"," metadata:"," annotations:",' run.googleapis.com/cpu-throttling: "false"',' run.googleapis.com/startup-cpu-boost: "true"',` run.googleapis.com/container-dependencies: '${e?'{"caddy":["agent","auth-broker"]}':'{"caddy":["agent","auth-broker"],"agent":["litellm"],"litellm":["otel-collector"]}'}'`,' autoscaling.knative.dev/maxScale: "1"',...t.gatewayChannels?.trim()?[' autoscaling.knative.dev/minScale: "1"']:[]," spec:"," timeoutSeconds: 3600"," containers:"," # Ingress \u2014 the ONLY container with a port. Verifies the shared JWT (no Google here)."," - name: caddy"," image: caddy:2.8-alpine"," ports:"," - name: http1",` containerPort: ${t.port}`," volumeMounts:"," - { name: caddy-config, mountPath: /etc/caddy, readOnly: true }",...Pr("1000m","512Mi")," # Auth broker \u2014 verifies IDE Bearer JWTs AND the federated .agenthippo.ai cookie (/api/ide/me)."," # Same shared AGENTHIPPO_AUTH_JWT_SECRET as the central IdP so its tokens verify here."," - name: auth-broker"," image: ${IMAGE}",' args: ["auth-broker"]'," env:",' - { name: AGENTHIPPO_AUTH_PORT, value: "9780" }'," - { name: AGENTHIPPO_AUTH_DATA_DIR, value: /data }"," - { name: AGENTHIPPO_AUTH_PUBLIC_URL, value: https://${PUBLIC_HOSTNAME} }"," - { name: AGENTHIPPO_AUTH_ALLOWED_DOMAINS, value: ${ALLOWED_DOMAINS} }",` - { name: AGENTHIPPO_AUTH_COOKIE_DOMAIN, value: "${s}" }`,` - { name: AGENTHIPPO_AUTH_IDP_URL, value: "${i}" }`,' - { name: AGENTHIPPO_AUTH_COOKIE_NAME, value: "ah_token" }'," - name: AGENTHIPPO_AUTH_JWT_SECRET"," valueFrom:"," secretKeyRef: { name: ${SERVICE}-auth-jwt-secret, key: latest }",...ys(9780),...Pr("1000m","512Mi")," # Agent \u2014 serves www + /v1/* on localhost (NOT ingress). Routed through LiteLLM."," - name: agent"," image: ${IMAGE}",` args: [${r}]`," env:"," - { name: AGENTHIPPO_HOME, value: /state }",' - { name: AGENTHIPPO_NO_AUTO_INSTALL, value: "1" }',zc(),...e?[" - { name: AGENTHIPPO_CUSTOM_ENGINES_DIR, value: /engines }"," - name: CURSOR_API_KEY"," valueFrom:"," secretKeyRef: { name: ${SERVICE}-provider-key, key: latest }"]:[" - { name: AGENTHIPPO_LITELLM_BASE_URL, value: http://localhost:4443 }"," - name: AGENTHIPPO_LITELLM_API_KEY"," valueFrom:"," secretKeyRef: { name: ${SERVICE}-litellm-key, key: latest }"]," volumeMounts:"," - { name: state, mountPath: /state }",...ys(ot.EDGE_AGENT_PORT,!0),...Pr("2000m","2Gi")];return e||a.push(" # LiteLLM gateway sidecar \u2014 exports every call to the collector (Spotlight)."," - name: litellm"," image: ${LITELLM_IMAGE}"," env:"," - { name: OTEL_EXPORTER, value: otlp_http }"," - { name: OTEL_EXPORTER_OTLP_ENDPOINT, value: http://localhost:4318 }"," - name: LITELLM_MASTER_KEY"," valueFrom:"," secretKeyRef: { name: ${SERVICE}-litellm-key, key: latest }",Yo(t.model)?" # ah-auto \u2192 gateway.agenthippo.ai (AGENTHIPPO_GATEWAY_KEY = ahgw_\u2026 service key).":` # Upstream provider key for ${t.model||"this model"} (matches os.environ/${n}).`,` - name: ${n}`," valueFrom:"," secretKeyRef: { name: ${SERVICE}-provider-key, key: latest }",...ys(4443),...Pr("1000m","1Gi")," # Spotlight OTEL collector sidecar \u2014 writes JSONL traces into the shared /state volume."," - name: otel-collector"," image: otel/opentelemetry-collector-contrib:0.118.0",' args: ["--config=/etc/otel/config.yaml"]'," env:"," - { name: AGENT_HOME_DIR, value: /state }"," volumeMounts:"," - { name: otel-config, mountPath: /etc/otel, readOnly: true }"," - { name: state, mountPath: /state }",...ys(4318),...Pr("1000m","512Mi")),a.push(" volumes:"," # In-memory state (matches the working spotlight deploy \u2014 no GCS SA perms needed)."," - name: state"," emptyDir:"," medium: Memory"," sizeLimit: 1Gi"," - name: caddy-config"," secret:"," secretName: ${SERVICE}-caddyfile"," items:"," - { key: latest, path: Caddyfile }"),e||a.push(" - name: otel-config"," secret:"," secretName: ${SERVICE}-otel-config"," items:"," - { key: latest, path: config.yaml }"),a.push(""),a.join(`
575
- `)}function g0(t){let e=hi(t,{wwwDir:"/app/pack/deploy/www",port:ot.EDGE_AGENT_PORT}).map(i=>`"${i.replace(/"/g,'\\"')}"`).join(", "),n=(t.cookieDomain||".agenthippo.ai").trim(),r=(t.idpUrl||"https://auth.agenthippo.ai").trim().replace(/\/+$/,"");return["# Cloud Run + AgentHippo federated edge (A\u2032) \u2014 gateway-direct (lean):","# Caddy (ingress) + auth-broker + agent. No LiteLLM/OTEL sidecars.","# Agent routes ah-auto (and other gateway models) to gateway.agenthippo.ai directly.","# Generated by `agenthippo deploy init --target cloudrun --ingress edge-fed --model-routing gateway`.","apiVersion: serving.knative.dev/v1","kind: Service","metadata:"," name: ${SERVICE}","spec:"," template:"," metadata:"," annotations:",' run.googleapis.com/cpu-throttling: "false"',' run.googleapis.com/startup-cpu-boost: "true"',` run.googleapis.com/container-dependencies: '{"caddy":["agent","auth-broker"]}'`,' autoscaling.knative.dev/maxScale: "1"',...t.gatewayChannels?.trim()?[' autoscaling.knative.dev/minScale: "1"']:[]," spec:"," timeoutSeconds: 3600"," containers:"," - name: caddy"," image: caddy:2.8-alpine"," ports:"," - name: http1",` containerPort: ${t.port}`," volumeMounts:"," - { name: caddy-config, mountPath: /etc/caddy, readOnly: true }",...Pr("1000m","512Mi")," - name: auth-broker"," image: ${IMAGE}",' args: ["auth-broker"]'," env:",' - { name: AGENTHIPPO_AUTH_PORT, value: "9780" }'," - { name: AGENTHIPPO_AUTH_DATA_DIR, value: /data }"," - { name: AGENTHIPPO_AUTH_PUBLIC_URL, value: https://${PUBLIC_HOSTNAME} }"," - { name: AGENTHIPPO_AUTH_ALLOWED_DOMAINS, value: ${ALLOWED_DOMAINS} }",` - { name: AGENTHIPPO_AUTH_COOKIE_DOMAIN, value: "${n}" }`,` - { name: AGENTHIPPO_AUTH_IDP_URL, value: "${r}" }`,' - { name: AGENTHIPPO_AUTH_COOKIE_NAME, value: "ah_token" }'," - name: AGENTHIPPO_AUTH_JWT_SECRET"," valueFrom:"," secretKeyRef: { name: ${SERVICE}-auth-jwt-secret, key: latest }",...ys(9780),...Pr("1000m","512Mi")," - name: agent"," image: ${IMAGE}",` args: [${e}]`," env:"," - { name: AGENTHIPPO_HOME, value: /state }",' - { name: AGENTHIPPO_NO_AUTO_INSTALL, value: "1" }',zc(),` - { name: AGENTHIPPO_LITELLM_BASE_URL, value: "${_y}" }`," - name: AGENTHIPPO_LITELLM_API_KEY"," valueFrom:"," secretKeyRef: { name: ${SERVICE}-provider-key, key: latest }"," volumeMounts:"," - { name: state, mountPath: /state }",...ys(ot.EDGE_AGENT_PORT,!0),...Pr("2000m","2Gi")," volumes:"," - name: state"," emptyDir:"," medium: Memory"," sizeLimit: 1Gi"," - name: caddy-config"," secret:"," secretName: ${SERVICE}-caddyfile"," items:"," - { key: latest, path: Caddyfile }",""].join(`
576
- `)}function h0(t){let e=t.model?.trim()?`, model ${t.model.trim()}`:"",n=Yo(t.model)?'PROVIDER_KEY="${PROVIDER_KEY:?set PROVIDER_KEY=<ahgw_\u2026 from create-gateway-key on gateway host>}"':'PROVIDER_KEY="${PROVIDER_KEY:?set PROVIDER_KEY=<gateway service key or provider key>}"';return["#!/usr/bin/env bash","# Cloud Run + AgentHippo federated edge (A\u2032) \u2014 gateway-direct (lean).",`# Engine: ${t.engine}${e}. Caddy + auth-broker + agent only \u2014 agent calls`,"# gateway.agenthippo.ai directly (no in-pod LiteLLM/OTEL sidecars). Same model routing","# as colocated agents on hippopennyg.","set -euo pipefail",...qr(),`SERVICE="${t.packName}"`,'REGION="${REGION:-us-central1}"','PROJECT_ID="${PROJECT_ID:-$(gcloud config get-value project)}"','REPO="${ARTIFACT_REPO:-agenthippo}"','IMAGE="${REGION}-docker.pkg.dev/${PROJECT_ID}/${REPO}/${SERVICE}:latest"','PUBLIC_HOSTNAME="${PUBLIC_HOSTNAME:?set PUBLIC_HOSTNAME=<subdomain>.agenthippo.ai}"','ALLOWED_DOMAINS="${ALLOWED_DOMAINS:-agenthippo.ai}"','AUTH_JWT_SECRET="${AUTH_JWT_SECRET:?set AUTH_JWT_SECRET=<copy from auth.agenthippo.ai>}"',n,"",'gcloud artifacts repositories describe "$REPO" --location="$REGION" 2>/dev/null \\',' || gcloud artifacts repositories create "$REPO" --repository-format=docker --location="$REGION"','gcloud auth configure-docker "${REGION}-docker.pkg.dev" --quiet',"",'DF_TMP="$(mktemp)"','sed "s|FROM ghcr.io/agenthippoai/runtime:|FROM ${REGION}-docker.pkg.dev/${PROJECT_ID}/${REPO}/runtime:|" deploy/Dockerfile > "$DF_TMP"','docker build --pull --platform linux/amd64 -f "$DF_TMP" -t "$IMAGE" .','docker push "$IMAGE"',"",'ensure_secret() { gcloud secrets describe "$1" >/dev/null 2>&1 || gcloud secrets create "$1" --replication-policy=automatic; }','ensure_secret "${SERVICE}-caddyfile"; gcloud secrets versions add "${SERVICE}-caddyfile" --data-file=deploy/Caddyfile','ensure_secret "${SERVICE}-auth-jwt-secret"; printf %s "$AUTH_JWT_SECRET" | gcloud secrets versions add "${SERVICE}-auth-jwt-secret" --data-file=-','ensure_secret "${SERVICE}-provider-key"; printf %s "$PROVIDER_KEY" | gcloud secrets versions add "${SERVICE}-provider-key" --data-file=-',"",'RENDERED="$(mktemp)"','sed -e "s|\\${SERVICE}|${SERVICE}|g" -e "s|\\${IMAGE}|${IMAGE}|g" \\',' -e "s|\\${PUBLIC_HOSTNAME}|${PUBLIC_HOSTNAME}|g" -e "s|\\${ALLOWED_DOMAINS}|${ALLOWED_DOMAINS}|g" \\',' deploy/service.yaml > "$RENDERED"','gcloud run services replace "$RENDERED" --region "$REGION"',"",'gcloud run services add-iam-policy-binding "$SERVICE" --region "$REGION" \\'," --member=allUsers --role=roles/run.invoker >/dev/null 2>&1 || true","",'if [[ "$PUBLIC_HOSTNAME" != *.run.app ]]; then \\',' gcloud beta run domain-mappings describe "$PUBLIC_HOSTNAME" --region "$REGION" >/dev/null 2>&1 \\',' || gcloud beta run domain-mappings create --service "$SERVICE" --region "$REGION" --domain "$PUBLIC_HOSTNAME"; \\',"fi",""].join(`
577
- `)}function m0(t){let e=t.engine.trim().toLowerCase()==="cursor",n=t.model?.trim()?`, model ${t.model.trim()}`:"",r=["#!/usr/bin/env bash","# Cloud Run + AgentHippo federated edge (A\u2032): Caddy + auth-broker front the agent.",`# Engine: ${t.engine}${n}. No oauth2-proxy, no per-service Google OAuth client \u2014`,"# Google login happens once at the central IdP (auth.agenthippo.ai); this agent verifies","# the shared .agenthippo.ai AgentHippo JWT (Bearer for IDE, cookie for browser). No IAP.","# The IDE points spec.remote.url straight at https://$PUBLIC_HOSTNAME (same flow as remote-vm).","set -euo pipefail",...qr(),`SERVICE="${t.packName}"`,'REGION="${REGION:-us-central1}"','PROJECT_ID="${PROJECT_ID:-$(gcloud config get-value project)}"','REPO="${ARTIFACT_REPO:-agenthippo}"','IMAGE="${REGION}-docker.pkg.dev/${PROJECT_ID}/${REPO}/${SERVICE}:latest"',`LITELLM_IMAGE="\${LITELLM_IMAGE:-${Kr("agenthippo-litellm")}}"`,"# Public hostname = a *.agenthippo.ai subdomain mapped to this service (one-time wildcard DNS).",'PUBLIC_HOSTNAME="${PUBLIC_HOSTNAME:?set PUBLIC_HOSTNAME=<subdomain>.agenthippo.ai}"','ALLOWED_DOMAINS="${ALLOWED_DOMAINS:-agenthippo.ai}"',"# Shared AgentHippo JWT signing key \u2014 MUST match the central IdP (auth.agenthippo.ai).","# Copy it from the IdP (or the GCP secret it stores) so tokens issued there verify here.",'AUTH_JWT_SECRET="${AUTH_JWT_SECRET:?set AUTH_JWT_SECRET=<copy from auth.agenthippo.ai>}"',...e?['PROVIDER_KEY="${PROVIDER_KEY:?set PROVIDER_KEY=<cursor api key>}"']:Yo(t.model)?["# LiteLLM proxy key + AgentHippo gateway service key (ahgw_\u2026) for ah-auto routing.",'LITELLM_KEY="${LITELLM_KEY:?set LITELLM_KEY=<litellm proxy key>}"','PROVIDER_KEY="${PROVIDER_KEY:?set PROVIDER_KEY=<ahgw_\u2026 from create-gateway-key on gateway host>}"']:["# LiteLLM proxy key + the upstream provider key the gateway uses for the model.",'LITELLM_KEY="${LITELLM_KEY:?set LITELLM_KEY=<litellm proxy key>}"','PROVIDER_KEY="${PROVIDER_KEY:?set PROVIDER_KEY=<upstream provider key>}"'],"",'gcloud artifacts repositories describe "$REPO" --location="$REGION" 2>/dev/null \\',' || gcloud artifacts repositories create "$REPO" --repository-format=docker --location="$REGION"','gcloud auth configure-docker "${REGION}-docker.pkg.dev" --quiet',"","# One agent image serves both the agent and the auth-broker containers (CLI ships `auth-broker`).","# Rewrite the runtime base to this project Artifact Registry. Customer artifacts pin a","# dated ghcr.io/agenthippoai/runtime tag; mirror that exact tag into AR. No-op if already AR.",'DF_TMP="$(mktemp)"','sed "s|FROM ghcr.io/agenthippoai/runtime:|FROM ${REGION}-docker.pkg.dev/${PROJECT_ID}/${REPO}/runtime:|" deploy/Dockerfile > "$DF_TMP"','docker build --pull --platform linux/amd64 -f "$DF_TMP" -t "$IMAGE" .','docker push "$IMAGE"',"","# Secrets: caddyfile + shared JWT secret + provider/litellm keys. NO OAuth client secrets.",'ensure_secret() { gcloud secrets describe "$1" >/dev/null 2>&1 || gcloud secrets create "$1" --replication-policy=automatic; }','ensure_secret "${SERVICE}-caddyfile"; gcloud secrets versions add "${SERVICE}-caddyfile" --data-file=deploy/Caddyfile','ensure_secret "${SERVICE}-auth-jwt-secret"; printf %s "$AUTH_JWT_SECRET" | gcloud secrets versions add "${SERVICE}-auth-jwt-secret" --data-file=-','ensure_secret "${SERVICE}-provider-key"; printf %s "$PROVIDER_KEY" | gcloud secrets versions add "${SERVICE}-provider-key" --data-file=-'];return e||r.push('ensure_secret "${SERVICE}-otel-config"; gcloud secrets versions add "${SERVICE}-otel-config" --data-file=deploy/otel-collector.yaml','ensure_secret "${SERVICE}-litellm-key"; printf %s "$LITELLM_KEY" | gcloud secrets versions add "${SERVICE}-litellm-key" --data-file=-'),r.push("","# Render the multi-container template (sed \u2014 no gettext) and deploy.",'RENDERED="$(mktemp)"','sed -e "s|\\${SERVICE}|${SERVICE}|g" -e "s|\\${IMAGE}|${IMAGE}|g" \\',' -e "s|\\${LITELLM_IMAGE}|${LITELLM_IMAGE}|g" \\',' -e "s|\\${PUBLIC_HOSTNAME}|${PUBLIC_HOSTNAME}|g" -e "s|\\${ALLOWED_DOMAINS}|${ALLOWED_DOMAINS}|g" \\',' deploy/service.yaml > "$RENDERED"','gcloud run services replace "$RENDERED" --region "$REGION"',"","# No IAP: Caddy is the gate, so Cloud Run must allow public ingress (allUsers invoker).",'gcloud run services add-iam-policy-binding "$SERVICE" --region "$REGION" \\'," --member=allUsers --role=roles/run.invoker >/dev/null 2>&1 || true","","# Map the *.agenthippo.ai subdomain (idempotent). Requires one-time wildcard DNS","# *.agenthippo.ai \u2192 Cloud Run (gctrl.run.app). No per-subdomain DNS, no Google OAuth edit.","# Skip for *.run.app default URLs (no custom mapping needed there).",'if [[ "$PUBLIC_HOSTNAME" != *.run.app ]]; then \\',' gcloud beta run domain-mappings describe "$PUBLIC_HOSTNAME" --region "$REGION" >/dev/null 2>&1 \\',' || gcloud beta run domain-mappings create --service "$SERVICE" --region "$REGION" --domain "$PUBLIC_HOSTNAME"; \\',"fi","","# Grant the runtime SA access to the secrets if needed:",`# SA="$(gcloud run services describe "$SERVICE" --region "$REGION" --format='value(spec.template.spec.serviceAccountName)')"`,"# for s in caddyfile auth-jwt-secret provider-key; do",'# gcloud secrets add-iam-policy-binding "${SERVICE}-$s" --member="serviceAccount:$SA" --role=roles/secretmanager.secretAccessor',"# done",""),r.join(`
578
- `)}function E0(t,e,n){let r=Ef(t)&&!n,s=n?"Caddy (ingress) + auth-broker + agent.":r?"Caddy (ingress) + auth-broker + agent (gateway-direct \u2014 no LiteLLM/OTEL sidecars).":"Caddy (ingress) + auth-broker + agent + LiteLLM + OTEL collector (Spotlight).",i=(t.idpUrl||"https://auth.agenthippo.ai").trim().replace(/\/+$/,""),o={Dockerfile:Cn(t,{wwwDir:"/app/pack/deploy/www"}),"www/index.html":ws(t.packName),Caddyfile:(0,ot.renderSidecarFedCaddyfile)(t.idpUrl),"service.yaml":r?g0(t):p0(t),"cloudrun-deploy.sh":r?h0(t):m0(t)};return!n&&!r&&(o["otel-collector.yaml"]=Qc),o["README.md"]=[`# Deploy: ${t.packName} \u2014 Cloud Run + AgentHippo federated edge (A\u2032${r?", gateway-direct":""})`,"",`Engine: **${t.engine}**${t.model?`, model: **${t.model}**`:""}. Runtime base: \`${t.image}\`.`,"",`${s} Sidecars share the pod's localhost (Cloud Run multi-container):`,"- **caddy** (ingress, the only port) \u2192 verifies the shared AgentHippo JWT (Bearer for IDE, cookie for browser)",`- **agent** \u2192 serves www + /v1/* on localhost:${ot.EDGE_AGENT_PORT} (NOT ingress)`,"- **auth-broker** \u2192 validates the shared `.agenthippo.ai` JWT via `/api/ide/me` (same secret as the IdP)",...r?[`- **model routing** \u2192 agent calls \`${_y}\` directly (ahgw_\u2026 service key) \u2014 same as colocated agents`,"- **no Spotlight sidecars** \u2014 traces are not collected in-pod; use gateway/Spotlight fleet analytics instead"]:n?[]:["- **litellm** gateway \u2192 exports OTLP to `http://localhost:4318`","- **otel-collector** \u2192 writes JSONL traces to the in-memory `/state` volume"],"","**No oauth2-proxy, no per-service Google OAuth client.** Google login happens once at the",`central IdP (${i}); this agent only verifies the resulting shared \`.agenthippo.ai\` JWT.`,"The IDE points `spec.remote.url` at `https://$PUBLIC_HOSTNAME` and the existing AgentHippo","SSO flow works (same as `remote-vm`). Browser visits with no cookie are redirected to the","IdP to log in, then return. Cloud Run is public (`allUsers` invoker) so traffic reaches Caddy.","","```bash","cp deploy/.env.example deploy/.env && cp deploy/.env.auth.example deploy/.env.auth # fill both","export PUBLIC_HOSTNAME=<subdomain>.agenthippo.ai # e.g. cs.agenthippo.ai","export AUTH_JWT_SECRET=<copy from auth.agenthippo.ai> # shared signing key",...n?["export PROVIDER_KEY=<cursor api key>"]:r?["export PROVIDER_KEY=<ahgw_\u2026 from create-gateway-key on gateway host>"]:Yo(t.model)?["export LITELLM_KEY=\u2026 PROVIDER_KEY=<ahgw_\u2026 from create-gateway-key on gateway host>"]:["export LITELLM_KEY=\u2026 PROVIDER_KEY=\u2026"],"bash deploy/cloudrun-deploy.sh # builds linux/amd64, upserts secrets, `gcloud run services replace`, maps the subdomain","```","","**One-time setup (not per agent):** wildcard DNS `*.agenthippo.ai` \u2192 Cloud Run (`gctrl.run.app`),",`and the IdP (${i}) must run the \`/oauth/browser-login\` route (oauth2-proxy forward_auth \u2192`,"auth-broker sets the `ah_token` cookie on `.agenthippo.ai`). After that, every new agent is",r?"just: `deploy init --ingress edge-fed --model-routing gateway` + this script \u2014 zero Console/OAuth work.":"just: `deploy init --ingress edge-fed` + this script \u2014 zero Console/OAuth work.","",r?"`service.yaml` placeholders (`${SERVICE} ${IMAGE} ${PUBLIC_HOSTNAME} ${ALLOWED_DOMAINS}`) are substituted by the deploy script. The Caddyfile is stored in Secret Manager (`${SERVICE}-caddyfile`).":"`service.yaml` placeholders (`${SERVICE} ${IMAGE} ${LITELLM_IMAGE} ${PUBLIC_HOSTNAME} ${ALLOWED_DOMAINS}`) are substituted by the deploy script. The Caddyfile is stored in Secret Manager (`${SERVICE}-caddyfile`).","`AGENTHIPPO_AUTH_COOKIE_DOMAIN` / `AGENTHIPPO_AUTH_IDP_URL` are baked in at generation time.","",e?"**Inbound channel (1b):** `minScale: 1` pins one always-on instance (the socket can't scale to zero).":"**No inbound channel (1a):** scales to zero; in-memory `/state` is wiped on cold start (use the `edge` mode + GCS bucket if you need durable state).","",...tr(t)].join(`
579
- `),o}function _0(t){let e=["# Databricks App (serverless source app). Databricks runs `npm ci` then start.",'command: ["node", "start.js"]',"env:"," - name: PORT",` value: "${t.port}"`,"user_authorization:"," # OBO: Databricks forwards X-Forwarded-Access-Token (the asking user's"," # downscoped token) so SQL runs as that user \u2192 Unity Catalog enforces"," # per-user grants. serve-v3 \xA711.1.",' scopes: ["sql"]',""].join(`
580
- `),n=JSON.stringify({name:t.packName,private:!0,dependencies:{[Q.AGENTHIPPO_CLI_NPM_PACKAGE]:ay(),"@anthropic-ai/claude-code":Q.CLAUDE_CODE_NPM_VERSION}},null,2)+`
574
+ `)}}function m0(t,e,n){let r=n?"Caddy (ingress) + oauth2-proxy + auth-broker + agent.":"Caddy (ingress) + oauth2-proxy + auth-broker + agent + LiteLLM + OTEL collector (Spotlight).",s={Dockerfile:Cn(t,{wwwDir:"/app/pack/deploy/www"}),"www/index.html":ws(t.packName),Caddyfile:(0,ot.renderSidecarEdgeCaddyfile)(),"service.yaml":p0(t),"cloudrun-deploy.sh":g0(t)};return n||(s["otel-collector.yaml"]=Zc),s["README.md"]=[`# Deploy: ${t.packName} \u2014 Cloud Run + AgentHippo edge (Option B)`,"",`Engine: **${t.engine}**${t.model?`, model: **${t.model}**`:""}. Runtime base: \`${t.image}\`.`,"",`${r} Sidecars share the pod's localhost (Cloud Run multi-container):`,"- **caddy** (ingress, the only port) \u2192 SSO edge: oauth2-proxy for browsers, auth-broker for IDE Bearer",`- **agent** \u2192 serves www + /v1/* on localhost:${ot.EDGE_AGENT_PORT} (NOT ingress)`,"- **auth-broker** \u2192 validates IDE AgentHippo JWTs (`/api/ide/me`) + IDE sign-in (`/oauth/*`)","- **oauth2-proxy** \u2192 Google SSO for browser clients (`provider=google`)",...n?[]:["- **litellm** gateway \u2192 exports OTLP to `http://localhost:4318`","- **otel-collector** \u2192 writes JSONL traces to the GCS `/state` volume"],"","**No IAP** \u2014 Caddy is the gate, so the IDE points `spec.remote.url` straight at","`https://$PUBLIC_HOSTNAME` and the existing AgentHippo SSO flow works (same as `remote-vm`).","Cloud Run itself is public (`allUsers` invoker) so traffic can reach Caddy to be authed.","","```bash","gcloud storage buckets create gs://<state-bucket> # once","cp deploy/.env.example deploy/.env && cp deploy/.env.auth.example deploy/.env.auth # fill both","export PUBLIC_HOSTNAME=<your.edge.hostname> ALLOWED_DOMAINS=<yourworkspace.com>","export OAUTH_CLIENT_ID=\u2026 OAUTH_CLIENT_SECRET=\u2026 OAUTH_COOKIE_SECRET=\u2026 AUTH_JWT_SECRET=\u2026",...n?["export PROVIDER_KEY=<cursor api key>"]:["export LITELLM_KEY=\u2026 PROVIDER_KEY=\u2026 STATE_BUCKET=<state-bucket>"],"bash deploy/cloudrun-deploy.sh # builds linux/amd64, upserts secrets, `gcloud run services replace`",'gcloud run domain-mappings create --service "$SERVICE" --region "${REGION:-us-central1}" --domain "$PUBLIC_HOSTNAME" # once',"```","","Google OAuth Web client (for oauth2-proxy): authorized origin `https://$PUBLIC_HOSTNAME`,","redirect `https://$PUBLIC_HOSTNAME/oauth2/callback`. Restrict to your Workspace domain via","`ALLOWED_DOMAINS` (oauth2-proxy `email_domains` + broker `allowed_domains`).","","`service.yaml` placeholders (`${SERVICE} ${IMAGE} ${LITELLM_IMAGE} ${STATE_BUCKET} ${PUBLIC_HOSTNAME} ${ALLOWED_DOMAINS}`)","are substituted by the deploy script. The Caddyfile is stored in Secret Manager (`${SERVICE}-caddyfile`).","",e?"**Inbound channel (1b):** `minScale: 1` pins one always-on instance (the socket can't scale to zero).":"**No inbound channel (1a):** scales to zero; traces + sessions persist on the GCS `/state` volume.","",...tr(t)].join(`
575
+ `),s}function _s(t,e=!1){return e?[" startupProbe:"," failureThreshold: 48"," periodSeconds: 5"," tcpSocket:",` port: ${t}`," timeoutSeconds: 3"]:[" startupProbe:"," failureThreshold: 30"," periodSeconds: 5"," tcpSocket:",` port: ${t}`," timeoutSeconds: 3"]}function Pr(t,e){return[" resources:"," limits:",` cpu: ${t}`,` memory: ${e}`]}function E0(t){let e=t.engine.trim().toLowerCase()==="cursor",n=mi(t.model),r=hi(t,{wwwDir:"/app/pack/deploy/www",port:ot.EDGE_AGENT_PORT}).map(c=>`"${c.replace(/"/g,'\\"')}"`).join(", "),s=(t.cookieDomain||".agenthippo.ai").trim(),i=(t.idpUrl||"https://auth.agenthippo.ai").trim().replace(/\/+$/,""),a=["# Cloud Run + AgentHippo federated edge (A\u2032): Caddy (ingress) + auth-broker + agent","# (+ LiteLLM + OTEL collector for Spotlight). No oauth2-proxy \u2014 Google login happens once","# at the central IdP; this agent verifies the shared .agenthippo.ai AgentHippo JWT.","# Generated by `agenthippo deploy init --target cloudrun --ingress edge-fed`.","apiVersion: serving.knative.dev/v1","kind: Service","metadata:"," name: ${SERVICE}","spec:"," template:"," metadata:"," annotations:",' run.googleapis.com/cpu-throttling: "false"',' run.googleapis.com/startup-cpu-boost: "true"',` run.googleapis.com/container-dependencies: '${e?'{"caddy":["agent","auth-broker"]}':'{"caddy":["agent","auth-broker"],"agent":["litellm"],"litellm":["otel-collector"]}'}'`,' autoscaling.knative.dev/maxScale: "1"',...t.gatewayChannels?.trim()?[' autoscaling.knative.dev/minScale: "1"']:[]," spec:"," timeoutSeconds: 3600"," containers:"," # Ingress \u2014 the ONLY container with a port. Verifies the shared JWT (no Google here)."," - name: caddy"," image: caddy:2.8-alpine"," ports:"," - name: http1",` containerPort: ${t.port}`," volumeMounts:"," - { name: caddy-config, mountPath: /etc/caddy, readOnly: true }",...Pr("1000m","512Mi")," # Auth broker \u2014 verifies IDE Bearer JWTs AND the federated .agenthippo.ai cookie (/api/ide/me)."," # Same shared AGENTHIPPO_AUTH_JWT_SECRET as the central IdP so its tokens verify here."," - name: auth-broker"," image: ${IMAGE}",' args: ["auth-broker"]'," env:",' - { name: AGENTHIPPO_AUTH_PORT, value: "9780" }'," - { name: AGENTHIPPO_AUTH_DATA_DIR, value: /data }"," - { name: AGENTHIPPO_AUTH_PUBLIC_URL, value: https://${PUBLIC_HOSTNAME} }"," - { name: AGENTHIPPO_AUTH_ALLOWED_DOMAINS, value: ${ALLOWED_DOMAINS} }",` - { name: AGENTHIPPO_AUTH_COOKIE_DOMAIN, value: "${s}" }`,` - { name: AGENTHIPPO_AUTH_IDP_URL, value: "${i}" }`,' - { name: AGENTHIPPO_AUTH_COOKIE_NAME, value: "ah_token" }'," - name: AGENTHIPPO_AUTH_JWT_SECRET"," valueFrom:"," secretKeyRef: { name: ${SERVICE}-auth-jwt-secret, key: latest }",..._s(9780),...Pr("1000m","512Mi")," # Agent \u2014 serves www + /v1/* on localhost (NOT ingress). Routed through LiteLLM."," - name: agent"," image: ${IMAGE}",` args: [${r}]`," env:"," - { name: AGENTHIPPO_HOME, value: /state }",' - { name: AGENTHIPPO_NO_AUTO_INSTALL, value: "1" }',Qc(),...e?[" - { name: AGENTHIPPO_CUSTOM_ENGINES_DIR, value: /engines }"," - name: CURSOR_API_KEY"," valueFrom:"," secretKeyRef: { name: ${SERVICE}-provider-key, key: latest }"]:[" - { name: AGENTHIPPO_LITELLM_BASE_URL, value: http://localhost:4443 }"," - name: AGENTHIPPO_LITELLM_API_KEY"," valueFrom:"," secretKeyRef: { name: ${SERVICE}-litellm-key, key: latest }"]," volumeMounts:"," - { name: state, mountPath: /state }",..._s(ot.EDGE_AGENT_PORT,!0),...Pr("2000m","2Gi")];return e||a.push(" # LiteLLM gateway sidecar \u2014 exports every call to the collector (Spotlight)."," - name: litellm"," image: ${LITELLM_IMAGE}"," env:"," - { name: OTEL_EXPORTER, value: otlp_http }"," - { name: OTEL_EXPORTER_OTLP_ENDPOINT, value: http://localhost:4318 }"," - name: LITELLM_MASTER_KEY"," valueFrom:"," secretKeyRef: { name: ${SERVICE}-litellm-key, key: latest }",Xo(t.model)?" # ah-auto \u2192 gateway.agenthippo.ai (AGENTHIPPO_GATEWAY_KEY = ahgw_\u2026 service key).":` # Upstream provider key for ${t.model||"this model"} (matches os.environ/${n}).`,` - name: ${n}`," valueFrom:"," secretKeyRef: { name: ${SERVICE}-provider-key, key: latest }",..._s(4443),...Pr("1000m","1Gi")," # Spotlight OTEL collector sidecar \u2014 writes JSONL traces into the shared /state volume."," - name: otel-collector"," image: otel/opentelemetry-collector-contrib:0.118.0",' args: ["--config=/etc/otel/config.yaml"]'," env:"," - { name: AGENT_HOME_DIR, value: /state }"," volumeMounts:"," - { name: otel-config, mountPath: /etc/otel, readOnly: true }"," - { name: state, mountPath: /state }",..._s(4318),...Pr("1000m","512Mi")),a.push(" volumes:"," # In-memory state (matches the working spotlight deploy \u2014 no GCS SA perms needed)."," - name: state"," emptyDir:"," medium: Memory"," sizeLimit: 1Gi"," - name: caddy-config"," secret:"," secretName: ${SERVICE}-caddyfile"," items:"," - { key: latest, path: Caddyfile }"),e||a.push(" - name: otel-config"," secret:"," secretName: ${SERVICE}-otel-config"," items:"," - { key: latest, path: config.yaml }"),a.push(""),a.join(`
576
+ `)}function _0(t){let e=hi(t,{wwwDir:"/app/pack/deploy/www",port:ot.EDGE_AGENT_PORT}).map(i=>`"${i.replace(/"/g,'\\"')}"`).join(", "),n=(t.cookieDomain||".agenthippo.ai").trim(),r=(t.idpUrl||"https://auth.agenthippo.ai").trim().replace(/\/+$/,"");return["# Cloud Run + AgentHippo federated edge (A\u2032) \u2014 gateway-direct (lean):","# Caddy (ingress) + auth-broker + agent. No LiteLLM/OTEL sidecars.","# Agent routes ah-auto (and other gateway models) to gateway.agenthippo.ai directly.","# Generated by `agenthippo deploy init --target cloudrun --ingress edge-fed --model-routing gateway`.","apiVersion: serving.knative.dev/v1","kind: Service","metadata:"," name: ${SERVICE}","spec:"," template:"," metadata:"," annotations:",' run.googleapis.com/cpu-throttling: "false"',' run.googleapis.com/startup-cpu-boost: "true"',` run.googleapis.com/container-dependencies: '{"caddy":["agent","auth-broker"]}'`,' autoscaling.knative.dev/maxScale: "1"',...t.gatewayChannels?.trim()?[' autoscaling.knative.dev/minScale: "1"']:[]," spec:"," timeoutSeconds: 3600"," containers:"," - name: caddy"," image: caddy:2.8-alpine"," ports:"," - name: http1",` containerPort: ${t.port}`," volumeMounts:"," - { name: caddy-config, mountPath: /etc/caddy, readOnly: true }",...Pr("1000m","512Mi")," - name: auth-broker"," image: ${IMAGE}",' args: ["auth-broker"]'," env:",' - { name: AGENTHIPPO_AUTH_PORT, value: "9780" }'," - { name: AGENTHIPPO_AUTH_DATA_DIR, value: /data }"," - { name: AGENTHIPPO_AUTH_PUBLIC_URL, value: https://${PUBLIC_HOSTNAME} }"," - { name: AGENTHIPPO_AUTH_ALLOWED_DOMAINS, value: ${ALLOWED_DOMAINS} }",` - { name: AGENTHIPPO_AUTH_COOKIE_DOMAIN, value: "${n}" }`,` - { name: AGENTHIPPO_AUTH_IDP_URL, value: "${r}" }`,' - { name: AGENTHIPPO_AUTH_COOKIE_NAME, value: "ah_token" }'," - name: AGENTHIPPO_AUTH_JWT_SECRET"," valueFrom:"," secretKeyRef: { name: ${SERVICE}-auth-jwt-secret, key: latest }",..._s(9780),...Pr("1000m","512Mi")," - name: agent"," image: ${IMAGE}",` args: [${e}]`," env:"," - { name: AGENTHIPPO_HOME, value: /state }",' - { name: AGENTHIPPO_NO_AUTO_INSTALL, value: "1" }',Qc(),` - { name: AGENTHIPPO_LITELLM_BASE_URL, value: "${Sy}" }`," - name: AGENTHIPPO_LITELLM_API_KEY"," valueFrom:"," secretKeyRef: { name: ${SERVICE}-provider-key, key: latest }"," volumeMounts:"," - { name: state, mountPath: /state }",..._s(ot.EDGE_AGENT_PORT,!0),...Pr("2000m","2Gi")," volumes:"," - name: state"," emptyDir:"," medium: Memory"," sizeLimit: 1Gi"," - name: caddy-config"," secret:"," secretName: ${SERVICE}-caddyfile"," items:"," - { key: latest, path: Caddyfile }",""].join(`
577
+ `)}function y0(t){let e=t.model?.trim()?`, model ${t.model.trim()}`:"",n=Xo(t.model)?'PROVIDER_KEY="${PROVIDER_KEY:?set PROVIDER_KEY=<ahgw_\u2026 from create-gateway-key on gateway host>}"':'PROVIDER_KEY="${PROVIDER_KEY:?set PROVIDER_KEY=<gateway service key or provider key>}"';return["#!/usr/bin/env bash","# Cloud Run + AgentHippo federated edge (A\u2032) \u2014 gateway-direct (lean).",`# Engine: ${t.engine}${e}. Caddy + auth-broker + agent only \u2014 agent calls`,"# gateway.agenthippo.ai directly (no in-pod LiteLLM/OTEL sidecars). Same model routing","# as colocated agents on hippopennyg.","set -euo pipefail",...Kr(),`SERVICE="${t.packName}"`,'REGION="${REGION:-us-central1}"','PROJECT_ID="${PROJECT_ID:-$(gcloud config get-value project)}"','REPO="${ARTIFACT_REPO:-agenthippo}"','IMAGE="${REGION}-docker.pkg.dev/${PROJECT_ID}/${REPO}/${SERVICE}:latest"','PUBLIC_HOSTNAME="${PUBLIC_HOSTNAME:?set PUBLIC_HOSTNAME=<subdomain>.agenthippo.ai}"','ALLOWED_DOMAINS="${ALLOWED_DOMAINS:-agenthippo.ai}"','AUTH_JWT_SECRET="${AUTH_JWT_SECRET:?set AUTH_JWT_SECRET=<copy from auth.agenthippo.ai>}"',n,"",'gcloud artifacts repositories describe "$REPO" --location="$REGION" 2>/dev/null \\',' || gcloud artifacts repositories create "$REPO" --repository-format=docker --location="$REGION"','gcloud auth configure-docker "${REGION}-docker.pkg.dev" --quiet',"",'DF_TMP="$(mktemp)"','sed "s|FROM ghcr.io/agenthippoai/runtime:|FROM ${REGION}-docker.pkg.dev/${PROJECT_ID}/${REPO}/runtime:|" deploy/Dockerfile > "$DF_TMP"','docker build --pull --platform linux/amd64 -f "$DF_TMP" -t "$IMAGE" .','docker push "$IMAGE"',"",'ensure_secret() { gcloud secrets describe "$1" >/dev/null 2>&1 || gcloud secrets create "$1" --replication-policy=automatic; }','ensure_secret "${SERVICE}-caddyfile"; gcloud secrets versions add "${SERVICE}-caddyfile" --data-file=deploy/Caddyfile','ensure_secret "${SERVICE}-auth-jwt-secret"; printf %s "$AUTH_JWT_SECRET" | gcloud secrets versions add "${SERVICE}-auth-jwt-secret" --data-file=-','ensure_secret "${SERVICE}-provider-key"; printf %s "$PROVIDER_KEY" | gcloud secrets versions add "${SERVICE}-provider-key" --data-file=-',"",'RENDERED="$(mktemp)"','sed -e "s|\\${SERVICE}|${SERVICE}|g" -e "s|\\${IMAGE}|${IMAGE}|g" \\',' -e "s|\\${PUBLIC_HOSTNAME}|${PUBLIC_HOSTNAME}|g" -e "s|\\${ALLOWED_DOMAINS}|${ALLOWED_DOMAINS}|g" \\',' deploy/service.yaml > "$RENDERED"','gcloud run services replace "$RENDERED" --region "$REGION"',"",'gcloud run services add-iam-policy-binding "$SERVICE" --region "$REGION" \\'," --member=allUsers --role=roles/run.invoker >/dev/null 2>&1 || true","",'if [[ "$PUBLIC_HOSTNAME" != *.run.app ]]; then \\',' gcloud beta run domain-mappings describe "$PUBLIC_HOSTNAME" --region "$REGION" >/dev/null 2>&1 \\',' || gcloud beta run domain-mappings create --service "$SERVICE" --region "$REGION" --domain "$PUBLIC_HOSTNAME"; \\',"fi",""].join(`
578
+ `)}function w0(t){let e=t.engine.trim().toLowerCase()==="cursor",n=t.model?.trim()?`, model ${t.model.trim()}`:"",r=["#!/usr/bin/env bash","# Cloud Run + AgentHippo federated edge (A\u2032): Caddy + auth-broker front the agent.",`# Engine: ${t.engine}${n}. No oauth2-proxy, no per-service Google OAuth client \u2014`,"# Google login happens once at the central IdP (auth.agenthippo.ai); this agent verifies","# the shared .agenthippo.ai AgentHippo JWT (Bearer for IDE, cookie for browser). No IAP.","# The IDE points spec.remote.url straight at https://$PUBLIC_HOSTNAME (same flow as remote-vm).","set -euo pipefail",...Kr(),`SERVICE="${t.packName}"`,'REGION="${REGION:-us-central1}"','PROJECT_ID="${PROJECT_ID:-$(gcloud config get-value project)}"','REPO="${ARTIFACT_REPO:-agenthippo}"','IMAGE="${REGION}-docker.pkg.dev/${PROJECT_ID}/${REPO}/${SERVICE}:latest"',`LITELLM_IMAGE="\${LITELLM_IMAGE:-${ys("agenthippo-litellm")}}"`,"# Public hostname = a *.agenthippo.ai subdomain mapped to this service (one-time wildcard DNS).",'PUBLIC_HOSTNAME="${PUBLIC_HOSTNAME:?set PUBLIC_HOSTNAME=<subdomain>.agenthippo.ai}"','ALLOWED_DOMAINS="${ALLOWED_DOMAINS:-agenthippo.ai}"',"# Shared AgentHippo JWT signing key \u2014 MUST match the central IdP (auth.agenthippo.ai).","# Copy it from the IdP (or the GCP secret it stores) so tokens issued there verify here.",'AUTH_JWT_SECRET="${AUTH_JWT_SECRET:?set AUTH_JWT_SECRET=<copy from auth.agenthippo.ai>}"',...e?['PROVIDER_KEY="${PROVIDER_KEY:?set PROVIDER_KEY=<cursor api key>}"']:Xo(t.model)?["# LiteLLM proxy key + AgentHippo gateway service key (ahgw_\u2026) for ah-auto routing.",'LITELLM_KEY="${LITELLM_KEY:?set LITELLM_KEY=<litellm proxy key>}"','PROVIDER_KEY="${PROVIDER_KEY:?set PROVIDER_KEY=<ahgw_\u2026 from create-gateway-key on gateway host>}"']:["# LiteLLM proxy key + the upstream provider key the gateway uses for the model.",'LITELLM_KEY="${LITELLM_KEY:?set LITELLM_KEY=<litellm proxy key>}"','PROVIDER_KEY="${PROVIDER_KEY:?set PROVIDER_KEY=<upstream provider key>}"'],"",'gcloud artifacts repositories describe "$REPO" --location="$REGION" 2>/dev/null \\',' || gcloud artifacts repositories create "$REPO" --repository-format=docker --location="$REGION"','gcloud auth configure-docker "${REGION}-docker.pkg.dev" --quiet',"","# One agent image serves both the agent and the auth-broker containers (CLI ships `auth-broker`).","# Rewrite the runtime base to this project Artifact Registry. Customer artifacts pin a","# dated ghcr.io/agenthippoai/runtime tag; mirror that exact tag into AR. No-op if already AR.",'DF_TMP="$(mktemp)"','sed "s|FROM ghcr.io/agenthippoai/runtime:|FROM ${REGION}-docker.pkg.dev/${PROJECT_ID}/${REPO}/runtime:|" deploy/Dockerfile > "$DF_TMP"','docker build --pull --platform linux/amd64 -f "$DF_TMP" -t "$IMAGE" .','docker push "$IMAGE"',"","# Secrets: caddyfile + shared JWT secret + provider/litellm keys. NO OAuth client secrets.",'ensure_secret() { gcloud secrets describe "$1" >/dev/null 2>&1 || gcloud secrets create "$1" --replication-policy=automatic; }','ensure_secret "${SERVICE}-caddyfile"; gcloud secrets versions add "${SERVICE}-caddyfile" --data-file=deploy/Caddyfile','ensure_secret "${SERVICE}-auth-jwt-secret"; printf %s "$AUTH_JWT_SECRET" | gcloud secrets versions add "${SERVICE}-auth-jwt-secret" --data-file=-','ensure_secret "${SERVICE}-provider-key"; printf %s "$PROVIDER_KEY" | gcloud secrets versions add "${SERVICE}-provider-key" --data-file=-'];return e||r.push('ensure_secret "${SERVICE}-otel-config"; gcloud secrets versions add "${SERVICE}-otel-config" --data-file=deploy/otel-collector.yaml','ensure_secret "${SERVICE}-litellm-key"; printf %s "$LITELLM_KEY" | gcloud secrets versions add "${SERVICE}-litellm-key" --data-file=-'),r.push("","# Render the multi-container template (sed \u2014 no gettext) and deploy.",'RENDERED="$(mktemp)"','sed -e "s|\\${SERVICE}|${SERVICE}|g" -e "s|\\${IMAGE}|${IMAGE}|g" \\',' -e "s|\\${LITELLM_IMAGE}|${LITELLM_IMAGE}|g" \\',' -e "s|\\${PUBLIC_HOSTNAME}|${PUBLIC_HOSTNAME}|g" -e "s|\\${ALLOWED_DOMAINS}|${ALLOWED_DOMAINS}|g" \\',' deploy/service.yaml > "$RENDERED"','gcloud run services replace "$RENDERED" --region "$REGION"',"","# No IAP: Caddy is the gate, so Cloud Run must allow public ingress (allUsers invoker).",'gcloud run services add-iam-policy-binding "$SERVICE" --region "$REGION" \\'," --member=allUsers --role=roles/run.invoker >/dev/null 2>&1 || true","","# Map the *.agenthippo.ai subdomain (idempotent). Requires one-time wildcard DNS","# *.agenthippo.ai \u2192 Cloud Run (gctrl.run.app). No per-subdomain DNS, no Google OAuth edit.","# Skip for *.run.app default URLs (no custom mapping needed there).",'if [[ "$PUBLIC_HOSTNAME" != *.run.app ]]; then \\',' gcloud beta run domain-mappings describe "$PUBLIC_HOSTNAME" --region "$REGION" >/dev/null 2>&1 \\',' || gcloud beta run domain-mappings create --service "$SERVICE" --region "$REGION" --domain "$PUBLIC_HOSTNAME"; \\',"fi","","# Grant the runtime SA access to the secrets if needed:",`# SA="$(gcloud run services describe "$SERVICE" --region "$REGION" --format='value(spec.template.spec.serviceAccountName)')"`,"# for s in caddyfile auth-jwt-secret provider-key; do",'# gcloud secrets add-iam-policy-binding "${SERVICE}-$s" --member="serviceAccount:$SA" --role=roles/secretmanager.secretAccessor',"# done",""),r.join(`
579
+ `)}function A0(t,e,n){let r=_f(t)&&!n,s=n?"Caddy (ingress) + auth-broker + agent.":r?"Caddy (ingress) + auth-broker + agent (gateway-direct \u2014 no LiteLLM/OTEL sidecars).":"Caddy (ingress) + auth-broker + agent + LiteLLM + OTEL collector (Spotlight).",i=(t.idpUrl||"https://auth.agenthippo.ai").trim().replace(/\/+$/,""),o={Dockerfile:Cn(t,{wwwDir:"/app/pack/deploy/www"}),"www/index.html":ws(t.packName),Caddyfile:(0,ot.renderSidecarFedCaddyfile)(t.idpUrl),"service.yaml":r?_0(t):E0(t),"cloudrun-deploy.sh":r?y0(t):w0(t)};return!n&&!r&&(o["otel-collector.yaml"]=Zc),o["README.md"]=[`# Deploy: ${t.packName} \u2014 Cloud Run + AgentHippo federated edge (A\u2032${r?", gateway-direct":""})`,"",`Engine: **${t.engine}**${t.model?`, model: **${t.model}**`:""}. Runtime base: \`${t.image}\`.`,"",`${s} Sidecars share the pod's localhost (Cloud Run multi-container):`,"- **caddy** (ingress, the only port) \u2192 verifies the shared AgentHippo JWT (Bearer for IDE, cookie for browser)",`- **agent** \u2192 serves www + /v1/* on localhost:${ot.EDGE_AGENT_PORT} (NOT ingress)`,"- **auth-broker** \u2192 validates the shared `.agenthippo.ai` JWT via `/api/ide/me` (same secret as the IdP)",...r?[`- **model routing** \u2192 agent calls \`${Sy}\` directly (ahgw_\u2026 service key) \u2014 same as colocated agents`,"- **no Spotlight sidecars** \u2014 traces are not collected in-pod; use gateway/Spotlight fleet analytics instead"]:n?[]:["- **litellm** gateway \u2192 exports OTLP to `http://localhost:4318`","- **otel-collector** \u2192 writes JSONL traces to the in-memory `/state` volume"],"","**No oauth2-proxy, no per-service Google OAuth client.** Google login happens once at the",`central IdP (${i}); this agent only verifies the resulting shared \`.agenthippo.ai\` JWT.`,"The IDE points `spec.remote.url` at `https://$PUBLIC_HOSTNAME` and the existing AgentHippo","SSO flow works (same as `remote-vm`). Browser visits with no cookie are redirected to the","IdP to log in, then return. Cloud Run is public (`allUsers` invoker) so traffic reaches Caddy.","","```bash","cp deploy/.env.example deploy/.env && cp deploy/.env.auth.example deploy/.env.auth # fill both","export PUBLIC_HOSTNAME=<subdomain>.agenthippo.ai # e.g. cs.agenthippo.ai","export AUTH_JWT_SECRET=<copy from auth.agenthippo.ai> # shared signing key",...n?["export PROVIDER_KEY=<cursor api key>"]:r?["export PROVIDER_KEY=<ahgw_\u2026 from create-gateway-key on gateway host>"]:Xo(t.model)?["export LITELLM_KEY=\u2026 PROVIDER_KEY=<ahgw_\u2026 from create-gateway-key on gateway host>"]:["export LITELLM_KEY=\u2026 PROVIDER_KEY=\u2026"],"bash deploy/cloudrun-deploy.sh # builds linux/amd64, upserts secrets, `gcloud run services replace`, maps the subdomain","```","","**One-time setup (not per agent):** wildcard DNS `*.agenthippo.ai` \u2192 Cloud Run (`gctrl.run.app`),",`and the IdP (${i}) must run the \`/oauth/browser-login\` route (oauth2-proxy forward_auth \u2192`,"auth-broker sets the `ah_token` cookie on `.agenthippo.ai`). After that, every new agent is",r?"just: `deploy init --ingress edge-fed --model-routing gateway` + this script \u2014 zero Console/OAuth work.":"just: `deploy init --ingress edge-fed` + this script \u2014 zero Console/OAuth work.","",r?"`service.yaml` placeholders (`${SERVICE} ${IMAGE} ${PUBLIC_HOSTNAME} ${ALLOWED_DOMAINS}`) are substituted by the deploy script. The Caddyfile is stored in Secret Manager (`${SERVICE}-caddyfile`).":"`service.yaml` placeholders (`${SERVICE} ${IMAGE} ${LITELLM_IMAGE} ${PUBLIC_HOSTNAME} ${ALLOWED_DOMAINS}`) are substituted by the deploy script. The Caddyfile is stored in Secret Manager (`${SERVICE}-caddyfile`).","`AGENTHIPPO_AUTH_COOKIE_DOMAIN` / `AGENTHIPPO_AUTH_IDP_URL` are baked in at generation time.","",e?"**Inbound channel (1b):** `minScale: 1` pins one always-on instance (the socket can't scale to zero).":"**No inbound channel (1a):** scales to zero; in-memory `/state` is wiped on cold start (use the `edge` mode + GCS bucket if you need durable state).","",...tr(t)].join(`
580
+ `),o}function S0(t){let e=["# Databricks App (serverless source app). Databricks runs `npm ci` then start.",'command: ["node", "start.js"]',"env:"," - name: PORT",` value: "${t.port}"`,"user_authorization:"," # OBO: Databricks forwards X-Forwarded-Access-Token (the asking user's"," # downscoped token) so SQL runs as that user \u2192 Unity Catalog enforces"," # per-user grants. serve-v3 \xA711.1.",' scopes: ["sql"]',""].join(`
581
+ `),n=JSON.stringify({name:t.packName,private:!0,dependencies:{[q.AGENTHIPPO_CLI_NPM_PACKAGE]:cy()}},null,2)+`
581
582
  `,r=["// Databricks App entrypoint: exec serve against the bundled pack.","const { spawn } = require('node:child_process');","const port = process.env.PORT || '"+t.port+"';","const child = spawn('agenthippo', ["," 'serve', '--agent', './pack',"," '--workspace', '/tmp/agenthippo/workspace',"," '--state-dir', '/tmp/agenthippo/state',"," '--port', port,","], { stdio: 'inherit', env: {"," ...process.env,"," AGENTHIPPO_SERVE_HOST: '0.0.0.0',"," // Databricks Apps workspace SSO sets X-Forwarded-Email; pin serve to trust ONLY that"," // header so an authenticated caller cannot impersonate another user via a spoofed"," // X-Agent-User header (Databricks does not know about or strip that header)."," // Skipped when AGENTHIPPO_PIN_IDENTITY=0 (bootstrap escape hatch) \u2014 same idea as"," // Cloud Run's ENABLE_IAP=0: pinning to an absent header would make every request"," // anonymous instead of leaving body-supplied identity usable during bootstrap."," ...(process.env.AGENTHIPPO_PIN_IDENTITY === '0' ? {} : { AGENTHIPPO_IDENTITY_HEADER: 'x-forwarded-email' }),","} });","child.on('exit', (code) => process.exit(code ?? 0));",""].join(`
582
583
  `);return{"app.yaml":e,"package.json":n,"start.js":r,"README.md":[`# Deploy: ${t.packName} \u2014 Databricks App (T1-native, the wedge)`,"","```bash","cp -r . ./databricks-app/pack # bundle the pack next to start.js","databricks apps deploy "+t.packName,"```","","**Per-user permissions:** workspace SSO authenticates the user; OBO forwards","`X-Forwarded-Access-Token`, and the SQL tool authenticates to the warehouse as","that user, so Unity Catalog row filters apply automatically (serve-v3 \xA711.1).","","> \u26A0\uFE0F The OBO *credential* seam (per-turn token \u2192 SQL tool) is the load-bearing","> spike (serve-v3 \xA713.2). Without it serve queries as one app identity. Identity","> attribution (`user_id`) works today; per-user *data* enforcement needs the spike.","",...tr(t)].join(`
583
- `)}}function y0(t){let e=["# Snowpark Container Services spec. Push the runtime image to your account","# registry, then run deploy.sql in a worksheet. serve-v3 \xA76.","spec:"," containers:",` - name: ${t.packName}`,` image: /<db>/<schema>/<repo>/${t.packName}:latest`," env:",' AGENTHIPPO_NO_AUTO_INSTALL: "1"'," AGENTHIPPO_HOME: /state"," readinessProbe:",` port: ${t.port}`," path: /ready"," # Q1: durable state on a block volume \u2014 survives compute-pool suspend/resume."," volumeMounts:"," - name: state"," mountPath: /state"," volumes:"," - name: state"," source: block"," size: 10Gi"," endpoints:"," - name: api",` port: ${t.port}`," public: true",""].join(`
584
+ `)}}function T0(t){let e=["# Snowpark Container Services spec. Push the runtime image to your account","# registry, then run deploy.sql in a worksheet. serve-v3 \xA76.","spec:"," containers:",` - name: ${t.packName}`,` image: /<db>/<schema>/<repo>/${t.packName}:latest`," env:",' AGENTHIPPO_NO_AUTO_INSTALL: "1"'," AGENTHIPPO_HOME: /state"," readinessProbe:",` port: ${t.port}`," path: /ready"," # Q1: durable state on a block volume \u2014 survives compute-pool suspend/resume."," volumeMounts:"," - name: state"," mountPath: /state"," volumes:"," - name: state"," source: block"," size: 10Gi"," endpoints:"," - name: api",` port: ${t.port}`," public: true",""].join(`
584
585
  `),n=["-- Run in a Snowflake worksheet. SPCS injects an OAuth session token at","-- /snowflake/session/token \u2192 the agent queries as the service role (no key-pair).","CREATE COMPUTE POOL IF NOT EXISTS agenthippo_pool"," MIN_NODES = 1 MAX_NODES = 1 INSTANCE_FAMILY = CPU_X64_S AUTO_SUSPEND_SECS = 600;","","-- Only egress: the model API. Everything else stays inside Snowflake.","CREATE OR REPLACE NETWORK RULE anthropic_rule"," MODE = EGRESS TYPE = HOST_PORT VALUE_LIST = ('api.anthropic.com:443');","CREATE OR REPLACE EXTERNAL ACCESS INTEGRATION anthropic_eai"," ALLOWED_NETWORK_RULES = (anthropic_rule) ENABLED = TRUE;","",`CREATE SERVICE ${t.packName}`," IN COMPUTE POOL agenthippo_pool"," FROM SPECIFICATION_FILE = 'spec.yaml'"," EXTERNAL_ACCESS_INTEGRATIONS = (anthropic_eai);",""].join(`
585
586
  `);return{Dockerfile:Cn(t),"spec.yaml":e,"deploy.sql":n,"README.md":[`# Deploy: ${t.packName} \u2014 Snowflake SPCS (T1-native)`,"","1. Build + push: `docker build -f deploy/Dockerfile -t <account-registry>/.../"+t.packName+":latest . && docker push ...`","2. Upload `spec.yaml` to a stage, then run `deploy.sql` in a worksheet.","","Zero Snowflake credentials: SPCS injects a session token; the agent queries as the",'service role, so RBAC is the permission system. Security review = "one EAI to api.anthropic.com".',""].join(`
586
- `)}}function w0(t){let e=JSON.stringify({name:t.packName,compatibility_date:"2026-05-01",containers:[{class_name:"Agent",image:"./deploy/Dockerfile",max_instances:1,instance_type:{vcpu:2,memory_mib:6144,disk_mb:8192}}],durable_objects:{bindings:[{name:"AGENT",class_name:"Agent"}]},migrations:[{tag:"v1",new_sqlite_classes:["Agent"]}]},null,2)+`
587
+ `)}}function b0(t){let e=JSON.stringify({name:t.packName,compatibility_date:"2026-05-01",containers:[{class_name:"Agent",image:"./deploy/Dockerfile",max_instances:1,instance_type:{vcpu:2,memory_mib:6144,disk_mb:8192}}],durable_objects:{bindings:[{name:"AGENT",class_name:"Agent"}]},migrations:[{tag:"v1",new_sqlite_classes:["Agent"]}]},null,2)+`
587
588
  `;return{Dockerfile:Cn(t,{extraEnv:{AGENTHIPPO_IDENTITY_HEADER:"x-agent-user"}}),"wrangler.jsonc":e,"README.md":[`# Deploy: ${t.packName} \u2014 Cloudflare Container (T1-generic)`,"","`wrangler deploy` builds the Dockerfile and ships the container (scale-to-zero).","Front it with a Worker that does Cloudflare Access (SSO) and sets `X-Agent-User`,","then proxies to the container binding. For the *external/unauthenticated* case","(customer support), use the full reference at `examples/deploy/external-support/`.","","**Identity pin:** the container trusts *only* `X-Agent-User` (`AGENTHIPPO_IDENTITY_HEADER`,","baked into the image) \u2014 the Worker must set it after Cloudflare Access verifies the user.","Requests without it resolve to no identity, even if the container is ever reachable","directly, bypassing the Worker.","","**Egress:** this container only needs outbound access to your model provider","(e.g. `api.anthropic.com:443`) \u2014 restrict it with a Cloudflare Worker/Zero Trust","egress policy if your org requires one.",""].join(`
588
- `)}}function A0(t){let e=t.ingress==="edge-fed",n=t.ingress==="edge"||e,r=mi(t.model);if(!n){let c={family:"${SERVICE}",networkMode:"awsvpc",requiresCompatibilities:["FARGATE"],cpu:"512",memory:"1024",containerDefinitions:[{name:"agent",image:"${IMAGE}",essential:!0,portMappings:[{containerPort:t.port,protocol:"tcp"}],environment:[{name:"AGENTHIPPO_NO_AUTO_INSTALL",value:"1"}],secrets:[{name:r,valueFrom:"${PROVIDER_KEY_SECRET_ARN}"}],logConfiguration:{logDriver:"awslogs",options:{"awslogs-group":"/ecs/${SERVICE}","awslogs-region":"${REGION}","awslogs-stream-prefix":"agent"}}}]},l=["#!/usr/bin/env bash","# T1-generic: AWS ECS Fargate, single container \u2014 bring your own ingress (ALB/API","# Gateway/internal VPC). For a self-contained ALB + AgentHippo edge, use --ingress edge","# or --ingress edge-fed instead.","set -euo pipefail",...qr(),'SERVICE="'+t.packName+'"','REGION="${AWS_REGION:-us-east-1}"','ACCOUNT_ID="${ACCOUNT_ID:-$(aws sts get-caller-identity --query Account --output text)}"','REPO="agenthippo/${SERVICE}"','IMAGE="${ACCOUNT_ID}.dkr.ecr.${REGION}.amazonaws.com/${REPO}:latest"',"",'aws ecr describe-repositories --repository-names "$REPO" --region "$REGION" >/dev/null 2>&1 \\',' || aws ecr create-repository --repository-name "$REPO" --region "$REGION"','aws ecr get-login-password --region "$REGION" \\',' | docker login --username AWS --password-stdin "${ACCOUNT_ID}.dkr.ecr.${REGION}.amazonaws.com"',"",'docker build --platform linux/amd64 -f deploy/Dockerfile -t "$IMAGE" .','docker push "$IMAGE"',"",`PROVIDER_KEY_SECRET_ARN="\${PROVIDER_KEY_SECRET_ARN:?set PROVIDER_KEY_SECRET_ARN \u2014 Secrets Manager ARN holding ${r}}"`,'TASK_JSON="$(sed -e "s|\\${IMAGE}|${IMAGE}|g" -e "s|\\${SERVICE}|${SERVICE}|g" \\',' -e "s|\\${REGION}|${REGION}|g" -e "s|\\${PROVIDER_KEY_SECRET_ARN}|${PROVIDER_KEY_SECRET_ARN}|g" \\',' deploy/task-definition.json)"','aws ecs register-task-definition --region "$REGION" --cli-input-json "$TASK_JSON" >/dev/null',"",'CLUSTER="${CLUSTER:?set CLUSTER \u2014 the ECS cluster to run in}"','aws ecs describe-services --cluster "$CLUSTER" --services "$SERVICE" --region "$REGION" 2>/dev/null \\',` | grep -q '"status": "ACTIVE"' \\`,' && aws ecs update-service --cluster "$CLUSTER" --service "$SERVICE" \\',' --task-definition "$SERVICE" --region "$REGION" >/dev/null \\',' || aws ecs create-service --cluster "$CLUSTER" --service-name "$SERVICE" \\',' --task-definition "$SERVICE" --desired-count 1 --launch-type FARGATE \\',' --network-configuration "awsvpcConfiguration={subnets=[${SUBNETS:?set SUBNETS}],securityGroups=[${SECURITY_GROUPS:?set SECURITY_GROUPS}],assignPublicIp=ENABLED}" \\',' --region "$REGION" >/dev/null','echo "Deployed $SERVICE to ECS cluster $CLUSTER"',""].join(`
589
+ `)}}function v0(t){let e=t.ingress==="edge-fed",n=t.ingress==="edge"||e,r=mi(t.model);if(!n){let c={family:"${SERVICE}",networkMode:"awsvpc",requiresCompatibilities:["FARGATE"],cpu:"512",memory:"1024",containerDefinitions:[{name:"agent",image:"${IMAGE}",essential:!0,portMappings:[{containerPort:t.port,protocol:"tcp"}],environment:[{name:"AGENTHIPPO_NO_AUTO_INSTALL",value:"1"}],secrets:[{name:r,valueFrom:"${PROVIDER_KEY_SECRET_ARN}"}],logConfiguration:{logDriver:"awslogs",options:{"awslogs-group":"/ecs/${SERVICE}","awslogs-region":"${REGION}","awslogs-stream-prefix":"agent"}}}]},l=["#!/usr/bin/env bash","# T1-generic: AWS ECS Fargate, single container \u2014 bring your own ingress (ALB/API","# Gateway/internal VPC). For a self-contained ALB + AgentHippo edge, use --ingress edge","# or --ingress edge-fed instead.","set -euo pipefail",...Kr(),'SERVICE="'+t.packName+'"','REGION="${AWS_REGION:-us-east-1}"','ACCOUNT_ID="${ACCOUNT_ID:-$(aws sts get-caller-identity --query Account --output text)}"','REPO="agenthippo/${SERVICE}"','IMAGE="${ACCOUNT_ID}.dkr.ecr.${REGION}.amazonaws.com/${REPO}:latest"',"",'aws ecr describe-repositories --repository-names "$REPO" --region "$REGION" >/dev/null 2>&1 \\',' || aws ecr create-repository --repository-name "$REPO" --region "$REGION"','aws ecr get-login-password --region "$REGION" \\',' | docker login --username AWS --password-stdin "${ACCOUNT_ID}.dkr.ecr.${REGION}.amazonaws.com"',"",'docker build --platform linux/amd64 -f deploy/Dockerfile -t "$IMAGE" .','docker push "$IMAGE"',"",`PROVIDER_KEY_SECRET_ARN="\${PROVIDER_KEY_SECRET_ARN:?set PROVIDER_KEY_SECRET_ARN \u2014 Secrets Manager ARN holding ${r}}"`,'TASK_JSON="$(sed -e "s|\\${IMAGE}|${IMAGE}|g" -e "s|\\${SERVICE}|${SERVICE}|g" \\',' -e "s|\\${REGION}|${REGION}|g" -e "s|\\${PROVIDER_KEY_SECRET_ARN}|${PROVIDER_KEY_SECRET_ARN}|g" \\',' deploy/task-definition.json)"','aws ecs register-task-definition --region "$REGION" --cli-input-json "$TASK_JSON" >/dev/null',"",'CLUSTER="${CLUSTER:?set CLUSTER \u2014 the ECS cluster to run in}"','aws ecs describe-services --cluster "$CLUSTER" --services "$SERVICE" --region "$REGION" 2>/dev/null \\',` | grep -q '"status": "ACTIVE"' \\`,' && aws ecs update-service --cluster "$CLUSTER" --service "$SERVICE" \\',' --task-definition "$SERVICE" --region "$REGION" >/dev/null \\',' || aws ecs create-service --cluster "$CLUSTER" --service-name "$SERVICE" \\',' --task-definition "$SERVICE" --desired-count 1 --launch-type FARGATE \\',' --network-configuration "awsvpcConfiguration={subnets=[${SUBNETS:?set SUBNETS}],securityGroups=[${SECURITY_GROUPS:?set SECURITY_GROUPS}],assignPublicIp=ENABLED}" \\',' --region "$REGION" >/dev/null','echo "Deployed $SERVICE to ECS cluster $CLUSTER"',""].join(`
589
590
  `);return{Dockerfile:Cn(t),"task-definition.json":JSON.stringify(c,null,2)+`
590
591
  `,"deploy.sh":l,"README.md":[`# Deploy: ${t.packName} \u2014 AWS ECS Fargate (T1-generic)`,"",`Engine: **${t.engine}**${t.model?`, model: **${t.model}**`:""}.`,"","Single container, no ingress opinion \u2014 front it with whatever your org already runs","(ALB, API Gateway, internal VPC access). Use `--ingress edge` or `--ingress edge-fed`","for a self-contained ALB + AgentHippo edge instead.","","```bash","export CLUSTER=<ecs-cluster> SUBNETS=<subnet-ids> SECURITY_GROUPS=<sg-ids>","export PROVIDER_KEY_SECRET_ARN=<Secrets Manager ARN for your model provider key>","bash deploy/deploy.sh","```","","> \u26A0\uFE0F Newer and far less exercised than the Cloud Run target \u2014 read `deploy.sh` before","> running it against a real account.","",...tr(t)].join(`
591
- `)}}let s=[{name:"caddy",image:"caddy:2.8-alpine",essential:!0,portMappings:[{containerPort:8080,protocol:"tcp"}],environment:[{name:"AGENTHIPPO_PUBLIC_HOSTNAME",value:t.publicHostname}],mountPoints:[{sourceVolume:"caddy-config",containerPath:"/etc/caddy"}],logConfiguration:{logDriver:"awslogs",options:{"awslogs-group":"/ecs/${SERVICE}","awslogs-region":"${REGION}","awslogs-stream-prefix":"caddy"}}},...e?[]:[{name:"oauth2-proxy",image:"quay.io/oauth2-proxy/oauth2-proxy:v7.7.1",essential:!0,environment:[{name:"OAUTH2_PROXY_HTTP_ADDRESS",value:"0.0.0.0:4180"},{name:"OAUTH2_PROXY_UPSTREAMS",value:"file:///dev/null"},{name:"OAUTH2_PROXY_SET_XAUTHREQUEST",value:"true"},{name:"OAUTH2_PROXY_PASS_AUTHORIZATION_HEADER",value:"true"},{name:"OAUTH2_PROXY_SKIP_PROVIDER_BUTTON",value:"true"},{name:"OAUTH2_PROXY_REVERSE_PROXY",value:"true"}],secrets:[{name:"OAUTH2_PROXY_CLIENT_ID",valueFrom:"${OAUTH_CLIENT_ID_SECRET_ARN}"},{name:"OAUTH2_PROXY_CLIENT_SECRET",valueFrom:"${OAUTH_CLIENT_SECRET_SECRET_ARN}"},{name:"OAUTH2_PROXY_COOKIE_SECRET",valueFrom:"${OAUTH_COOKIE_SECRET_SECRET_ARN}"}],logConfiguration:{logDriver:"awslogs",options:{"awslogs-group":"/ecs/${SERVICE}","awslogs-region":"${REGION}","awslogs-stream-prefix":"oauth2-proxy"}}}],{name:"auth-broker",image:"${IMAGE}",essential:!0,command:["auth-broker"],environment:[{name:"AGENTHIPPO_AUTH_PORT",value:"9780"},...e?[{name:"AGENTHIPPO_AUTH_COOKIE_DOMAIN",value:t.cookieDomain||""},{name:"AGENTHIPPO_AUTH_IDP_URL",value:t.idpUrl||""}]:[]],secrets:[{name:"AGENTHIPPO_AUTH_JWT_SECRET",valueFrom:"${AUTH_JWT_SECRET_SECRET_ARN}"}],logConfiguration:{logDriver:"awslogs",options:{"awslogs-group":"/ecs/${SERVICE}","awslogs-region":"${REGION}","awslogs-stream-prefix":"auth-broker"}}},{name:"agent",image:"${IMAGE}",essential:!0,command:hi(t,{wwwDir:"/app/pack/deploy/www",port:ot.EDGE_AGENT_PORT}),environment:[{name:"AGENTHIPPO_NO_AUTO_INSTALL",value:"1"}],secrets:[{name:r,valueFrom:"${PROVIDER_KEY_SECRET_ARN}"}],logConfiguration:{logDriver:"awslogs",options:{"awslogs-group":"/ecs/${SERVICE}","awslogs-region":"${REGION}","awslogs-stream-prefix":"agent"}}}],i={family:"${SERVICE}",networkMode:"awsvpc",requiresCompatibilities:["FARGATE"],cpu:"1024",memory:"2048",volumes:[{name:"caddy-config"}],containerDefinitions:s},o=e?"PROVIDER_KEY_SECRET_ARN=<...> AUTH_JWT_SECRET_SECRET_ARN=<...>":"PROVIDER_KEY_SECRET_ARN=<...> AUTH_JWT_SECRET_SECRET_ARN=<...> OAUTH_CLIENT_ID_SECRET_ARN=<...> OAUTH_CLIENT_SECRET_SECRET_ARN=<...> OAUTH_COOKIE_SECRET_SECRET_ARN=<...>",a=["#!/usr/bin/env bash",`# AWS ECS Fargate + AgentHippo edge (${e?"edge-fed: federated identity, no oauth2-proxy":"edge: self-issued"}).`,"# One-time setup (not per deploy): create an ALB + target group (protocol HTTP, port 8080,","# target type ip) pointed at this service, and an HTTPS listener forwarding to it \u2014 ALB","# terminates TLS, same as Cloud Run's edge path (Caddy listens on plain HTTP behind it).","set -euo pipefail",...qr(),'SERVICE="'+t.packName+'"','REGION="${AWS_REGION:-us-east-1}"','ACCOUNT_ID="${ACCOUNT_ID:-$(aws sts get-caller-identity --query Account --output text)}"','REPO="agenthippo/${SERVICE}"','IMAGE="${ACCOUNT_ID}.dkr.ecr.${REGION}.amazonaws.com/${REPO}:latest"',"",'aws ecr describe-repositories --repository-names "$REPO" --region "$REGION" >/dev/null 2>&1 \\',' || aws ecr create-repository --repository-name "$REPO" --region "$REGION"','aws ecr get-login-password --region "$REGION" \\',' | docker login --username AWS --password-stdin "${ACCOUNT_ID}.dkr.ecr.${REGION}.amazonaws.com"',"","# auth-broker reuses the agent image (CLI ships `auth-broker`).",'docker build --platform linux/amd64 -f deploy/Dockerfile -t "$IMAGE" .','docker push "$IMAGE"',"",'PROVIDER_KEY_SECRET_ARN="${PROVIDER_KEY_SECRET_ARN:?set PROVIDER_KEY_SECRET_ARN}"','AUTH_JWT_SECRET_SECRET_ARN="${AUTH_JWT_SECRET_SECRET_ARN:?set AUTH_JWT_SECRET_SECRET_ARN}"',...e?[]:['OAUTH_CLIENT_ID_SECRET_ARN="${OAUTH_CLIENT_ID_SECRET_ARN:?set OAUTH_CLIENT_ID_SECRET_ARN}"','OAUTH_CLIENT_SECRET_SECRET_ARN="${OAUTH_CLIENT_SECRET_SECRET_ARN:?set OAUTH_CLIENT_SECRET_SECRET_ARN}"','OAUTH_COOKIE_SECRET_SECRET_ARN="${OAUTH_COOKIE_SECRET_SECRET_ARN:?set OAUTH_COOKIE_SECRET_SECRET_ARN}"'],'TASK_JSON="$(sed -e "s|\\${IMAGE}|${IMAGE}|g" -e "s|\\${SERVICE}|${SERVICE}|g" -e "s|\\${REGION}|${REGION}|g" \\',' -e "s|\\${PROVIDER_KEY_SECRET_ARN}|${PROVIDER_KEY_SECRET_ARN}|g" \\',' -e "s|\\${AUTH_JWT_SECRET_SECRET_ARN}|${AUTH_JWT_SECRET_SECRET_ARN}|g" \\',...e?[]:[' -e "s|\\${OAUTH_CLIENT_ID_SECRET_ARN}|${OAUTH_CLIENT_ID_SECRET_ARN}|g" \\',' -e "s|\\${OAUTH_CLIENT_SECRET_SECRET_ARN}|${OAUTH_CLIENT_SECRET_SECRET_ARN}|g" \\',' -e "s|\\${OAUTH_COOKIE_SECRET_SECRET_ARN}|${OAUTH_COOKIE_SECRET_SECRET_ARN}|g" \\'],' deploy/task-definition.json)"','aws ecs register-task-definition --region "$REGION" --cli-input-json "$TASK_JSON" >/dev/null',"",'CLUSTER="${CLUSTER:?set CLUSTER}"','TARGET_GROUP_ARN="${TARGET_GROUP_ARN:?set TARGET_GROUP_ARN \u2014 from the one-time ALB setup above}"','aws ecs describe-services --cluster "$CLUSTER" --services "$SERVICE" --region "$REGION" 2>/dev/null \\',` | grep -q '"status": "ACTIVE"' \\`,' && aws ecs update-service --cluster "$CLUSTER" --service "$SERVICE" \\',' --task-definition "$SERVICE" --region "$REGION" >/dev/null \\',' || aws ecs create-service --cluster "$CLUSTER" --service-name "$SERVICE" \\',' --task-definition "$SERVICE" --desired-count 1 --launch-type FARGATE \\',' --load-balancers "targetGroupArn=$TARGET_GROUP_ARN,containerName=caddy,containerPort=8080" \\',' --network-configuration "awsvpcConfiguration={subnets=[${SUBNETS:?set SUBNETS}],securityGroups=[${SECURITY_GROUPS:?set SECURITY_GROUPS}],assignPublicIp=ENABLED}" \\',' --region "$REGION" >/dev/null','echo "Deployed $SERVICE behind the AgentHippo edge on ECS cluster $CLUSTER"',""].join(`
592
+ `)}}let s=[{name:"caddy",image:"caddy:2.8-alpine",essential:!0,portMappings:[{containerPort:8080,protocol:"tcp"}],environment:[{name:"AGENTHIPPO_PUBLIC_HOSTNAME",value:t.publicHostname}],mountPoints:[{sourceVolume:"caddy-config",containerPath:"/etc/caddy"}],logConfiguration:{logDriver:"awslogs",options:{"awslogs-group":"/ecs/${SERVICE}","awslogs-region":"${REGION}","awslogs-stream-prefix":"caddy"}}},...e?[]:[{name:"oauth2-proxy",image:"quay.io/oauth2-proxy/oauth2-proxy:v7.7.1",essential:!0,environment:[{name:"OAUTH2_PROXY_HTTP_ADDRESS",value:"0.0.0.0:4180"},{name:"OAUTH2_PROXY_UPSTREAMS",value:"file:///dev/null"},{name:"OAUTH2_PROXY_SET_XAUTHREQUEST",value:"true"},{name:"OAUTH2_PROXY_PASS_AUTHORIZATION_HEADER",value:"true"},{name:"OAUTH2_PROXY_SKIP_PROVIDER_BUTTON",value:"true"},{name:"OAUTH2_PROXY_REVERSE_PROXY",value:"true"}],secrets:[{name:"OAUTH2_PROXY_CLIENT_ID",valueFrom:"${OAUTH_CLIENT_ID_SECRET_ARN}"},{name:"OAUTH2_PROXY_CLIENT_SECRET",valueFrom:"${OAUTH_CLIENT_SECRET_SECRET_ARN}"},{name:"OAUTH2_PROXY_COOKIE_SECRET",valueFrom:"${OAUTH_COOKIE_SECRET_SECRET_ARN}"}],logConfiguration:{logDriver:"awslogs",options:{"awslogs-group":"/ecs/${SERVICE}","awslogs-region":"${REGION}","awslogs-stream-prefix":"oauth2-proxy"}}}],{name:"auth-broker",image:"${IMAGE}",essential:!0,command:["auth-broker"],environment:[{name:"AGENTHIPPO_AUTH_PORT",value:"9780"},...e?[{name:"AGENTHIPPO_AUTH_COOKIE_DOMAIN",value:t.cookieDomain||""},{name:"AGENTHIPPO_AUTH_IDP_URL",value:t.idpUrl||""}]:[]],secrets:[{name:"AGENTHIPPO_AUTH_JWT_SECRET",valueFrom:"${AUTH_JWT_SECRET_SECRET_ARN}"}],logConfiguration:{logDriver:"awslogs",options:{"awslogs-group":"/ecs/${SERVICE}","awslogs-region":"${REGION}","awslogs-stream-prefix":"auth-broker"}}},{name:"agent",image:"${IMAGE}",essential:!0,command:hi(t,{wwwDir:"/app/pack/deploy/www",port:ot.EDGE_AGENT_PORT}),environment:[{name:"AGENTHIPPO_NO_AUTO_INSTALL",value:"1"}],secrets:[{name:r,valueFrom:"${PROVIDER_KEY_SECRET_ARN}"}],logConfiguration:{logDriver:"awslogs",options:{"awslogs-group":"/ecs/${SERVICE}","awslogs-region":"${REGION}","awslogs-stream-prefix":"agent"}}}],i={family:"${SERVICE}",networkMode:"awsvpc",requiresCompatibilities:["FARGATE"],cpu:"1024",memory:"2048",volumes:[{name:"caddy-config"}],containerDefinitions:s},o=e?"PROVIDER_KEY_SECRET_ARN=<...> AUTH_JWT_SECRET_SECRET_ARN=<...>":"PROVIDER_KEY_SECRET_ARN=<...> AUTH_JWT_SECRET_SECRET_ARN=<...> OAUTH_CLIENT_ID_SECRET_ARN=<...> OAUTH_CLIENT_SECRET_SECRET_ARN=<...> OAUTH_COOKIE_SECRET_SECRET_ARN=<...>",a=["#!/usr/bin/env bash",`# AWS ECS Fargate + AgentHippo edge (${e?"edge-fed: federated identity, no oauth2-proxy":"edge: self-issued"}).`,"# One-time setup (not per deploy): create an ALB + target group (protocol HTTP, port 8080,","# target type ip) pointed at this service, and an HTTPS listener forwarding to it \u2014 ALB","# terminates TLS, same as Cloud Run's edge path (Caddy listens on plain HTTP behind it).","set -euo pipefail",...Kr(),'SERVICE="'+t.packName+'"','REGION="${AWS_REGION:-us-east-1}"','ACCOUNT_ID="${ACCOUNT_ID:-$(aws sts get-caller-identity --query Account --output text)}"','REPO="agenthippo/${SERVICE}"','IMAGE="${ACCOUNT_ID}.dkr.ecr.${REGION}.amazonaws.com/${REPO}:latest"',"",'aws ecr describe-repositories --repository-names "$REPO" --region "$REGION" >/dev/null 2>&1 \\',' || aws ecr create-repository --repository-name "$REPO" --region "$REGION"','aws ecr get-login-password --region "$REGION" \\',' | docker login --username AWS --password-stdin "${ACCOUNT_ID}.dkr.ecr.${REGION}.amazonaws.com"',"","# auth-broker reuses the agent image (CLI ships `auth-broker`).",'docker build --platform linux/amd64 -f deploy/Dockerfile -t "$IMAGE" .','docker push "$IMAGE"',"",'PROVIDER_KEY_SECRET_ARN="${PROVIDER_KEY_SECRET_ARN:?set PROVIDER_KEY_SECRET_ARN}"','AUTH_JWT_SECRET_SECRET_ARN="${AUTH_JWT_SECRET_SECRET_ARN:?set AUTH_JWT_SECRET_SECRET_ARN}"',...e?[]:['OAUTH_CLIENT_ID_SECRET_ARN="${OAUTH_CLIENT_ID_SECRET_ARN:?set OAUTH_CLIENT_ID_SECRET_ARN}"','OAUTH_CLIENT_SECRET_SECRET_ARN="${OAUTH_CLIENT_SECRET_SECRET_ARN:?set OAUTH_CLIENT_SECRET_SECRET_ARN}"','OAUTH_COOKIE_SECRET_SECRET_ARN="${OAUTH_COOKIE_SECRET_SECRET_ARN:?set OAUTH_COOKIE_SECRET_SECRET_ARN}"'],'TASK_JSON="$(sed -e "s|\\${IMAGE}|${IMAGE}|g" -e "s|\\${SERVICE}|${SERVICE}|g" -e "s|\\${REGION}|${REGION}|g" \\',' -e "s|\\${PROVIDER_KEY_SECRET_ARN}|${PROVIDER_KEY_SECRET_ARN}|g" \\',' -e "s|\\${AUTH_JWT_SECRET_SECRET_ARN}|${AUTH_JWT_SECRET_SECRET_ARN}|g" \\',...e?[]:[' -e "s|\\${OAUTH_CLIENT_ID_SECRET_ARN}|${OAUTH_CLIENT_ID_SECRET_ARN}|g" \\',' -e "s|\\${OAUTH_CLIENT_SECRET_SECRET_ARN}|${OAUTH_CLIENT_SECRET_SECRET_ARN}|g" \\',' -e "s|\\${OAUTH_COOKIE_SECRET_SECRET_ARN}|${OAUTH_COOKIE_SECRET_SECRET_ARN}|g" \\'],' deploy/task-definition.json)"','aws ecs register-task-definition --region "$REGION" --cli-input-json "$TASK_JSON" >/dev/null',"",'CLUSTER="${CLUSTER:?set CLUSTER}"','TARGET_GROUP_ARN="${TARGET_GROUP_ARN:?set TARGET_GROUP_ARN \u2014 from the one-time ALB setup above}"','aws ecs describe-services --cluster "$CLUSTER" --services "$SERVICE" --region "$REGION" 2>/dev/null \\',` | grep -q '"status": "ACTIVE"' \\`,' && aws ecs update-service --cluster "$CLUSTER" --service "$SERVICE" \\',' --task-definition "$SERVICE" --region "$REGION" >/dev/null \\',' || aws ecs create-service --cluster "$CLUSTER" --service-name "$SERVICE" \\',' --task-definition "$SERVICE" --desired-count 1 --launch-type FARGATE \\',' --load-balancers "targetGroupArn=$TARGET_GROUP_ARN,containerName=caddy,containerPort=8080" \\',' --network-configuration "awsvpcConfiguration={subnets=[${SUBNETS:?set SUBNETS}],securityGroups=[${SECURITY_GROUPS:?set SECURITY_GROUPS}],assignPublicIp=ENABLED}" \\',' --region "$REGION" >/dev/null','echo "Deployed $SERVICE behind the AgentHippo edge on ECS cluster $CLUSTER"',""].join(`
592
593
  `);return{Dockerfile:Cn(t,{wwwDir:"/app/pack/deploy/www"}),"www/index.html":ws(t.packName),Caddyfile:e?(0,ot.renderSidecarFedCaddyfile)(t.idpUrl):(0,ot.renderSidecarEdgeCaddyfile)(),"task-definition.json":JSON.stringify(i,null,2)+`
593
594
  `,"deploy.sh":a,"README.md":[`# Deploy: ${t.packName} \u2014 AWS ECS Fargate + AgentHippo edge (${e?"edge-fed":"edge"})`,"",`Engine: **${t.engine}**${t.model?`, model: **${t.model}**`:""}.`,"","One Fargate task, containers share the task's localhost (`awsvpc` network mode) \u2014","the same sidecar shape Cloud Run uses, so the Caddyfile is identical:","- **caddy** (ingress, the only published port) \u2192 "+(e?"verifies the shared AgentHippo JWT":"SSO edge: oauth2-proxy for browsers, auth-broker for IDE Bearer"),`- **agent** \u2192 serves www + /v1/* on localhost:${ot.EDGE_AGENT_PORT} (not published)`,"- **auth-broker** \u2192 validates IDE AgentHippo JWTs (`/api/ide/me`)"+(e?" against the shared IdP secret":""),...e?[]:["- **oauth2-proxy** \u2192 Google SSO for browser clients"],"","**One-time setup (not per deploy):** an ALB + HTTPS listener + target group (HTTP, port","8080, target type `ip`) pointed at this service \u2014 ALB terminates TLS, Caddy stays HTTP.","","```bash","export CLUSTER=<ecs-cluster> SUBNETS=<subnet-ids> SECURITY_GROUPS=<sg-ids> TARGET_GROUP_ARN=<from ALB setup>",`export ${o}`,"bash deploy/deploy.sh","```","","> \u26A0\uFE0F Newer and far less exercised than the Cloud Run target \u2014 read `deploy.sh` before","> running it against a real account.","",...tr(t)].join(`
594
- `)}}function S0(t){let e=t.ingress==="edge-fed",n=t.ingress==="edge"||e,r=mi(t.model),s=8080;if(!n){let l={properties:{configuration:{ingress:{external:!0,targetPort:t.port},secrets:[{name:"provider-key",value:"${PROVIDER_KEY}"}]},template:{containers:[{name:"agent",image:"${IMAGE}",env:[{name:"AGENTHIPPO_NO_AUTO_INSTALL",value:"1"},{name:r,secretRef:"provider-key"}],resources:{cpu:.5,memory:"1Gi"}}]}}},f=["#!/usr/bin/env bash","# T1-generic: Azure Container Apps, single container \u2014 built-in ingress + TLS, no separate","# load balancer to stand up. For a self-contained AgentHippo edge, use --ingress edge or","# --ingress edge-fed instead.","set -euo pipefail",...qr(),'SERVICE="'+t.packName+'"','RESOURCE_GROUP="${RESOURCE_GROUP:?set RESOURCE_GROUP}"','ENVIRONMENT="${CONTAINERAPPS_ENVIRONMENT:?set CONTAINERAPPS_ENVIRONMENT \u2014 az containerapp env create (one-time)}"','ACR_NAME="${ACR_NAME:?set ACR_NAME \u2014 an Azure Container Registry (one-time: az acr create)}"','IMAGE="${ACR_NAME}.azurecr.io/${SERVICE}:latest"',`PROVIDER_KEY="\${PROVIDER_KEY:?set PROVIDER_KEY \u2014 your ${r}}"`,"","# Builds in ACR (no local docker login/push step needed).",'az acr build --registry "$ACR_NAME" --image "${SERVICE}:latest" --file deploy/Dockerfile .',"",'az containerapp show --name "$SERVICE" --resource-group "$RESOURCE_GROUP" >/dev/null 2>&1 \\',' && az containerapp update --name "$SERVICE" --resource-group "$RESOURCE_GROUP" \\',' --image "$IMAGE" >/dev/null \\',' || az containerapp create --name "$SERVICE" --resource-group "$RESOURCE_GROUP" \\',' --environment "$ENVIRONMENT" --image "$IMAGE" \\'," --target-port "+t.port+" --ingress external \\",' --secrets "provider-key=$PROVIDER_KEY" \\',` --env-vars "AGENTHIPPO_NO_AUTO_INSTALL=1" "${r}=secretref:provider-key" \\`," >/dev/null",'echo "Deployed $SERVICE to Container Apps environment $ENVIRONMENT"',""].join(`
595
+ `)}}function O0(t){let e=t.ingress==="edge-fed",n=t.ingress==="edge"||e,r=mi(t.model),s=8080;if(!n){let l={properties:{configuration:{ingress:{external:!0,targetPort:t.port},secrets:[{name:"provider-key",value:"${PROVIDER_KEY}"}]},template:{containers:[{name:"agent",image:"${IMAGE}",env:[{name:"AGENTHIPPO_NO_AUTO_INSTALL",value:"1"},{name:r,secretRef:"provider-key"}],resources:{cpu:.5,memory:"1Gi"}}]}}},f=["#!/usr/bin/env bash","# T1-generic: Azure Container Apps, single container \u2014 built-in ingress + TLS, no separate","# load balancer to stand up. For a self-contained AgentHippo edge, use --ingress edge or","# --ingress edge-fed instead.","set -euo pipefail",...Kr(),'SERVICE="'+t.packName+'"','RESOURCE_GROUP="${RESOURCE_GROUP:?set RESOURCE_GROUP}"','ENVIRONMENT="${CONTAINERAPPS_ENVIRONMENT:?set CONTAINERAPPS_ENVIRONMENT \u2014 az containerapp env create (one-time)}"','ACR_NAME="${ACR_NAME:?set ACR_NAME \u2014 an Azure Container Registry (one-time: az acr create)}"','IMAGE="${ACR_NAME}.azurecr.io/${SERVICE}:latest"',`PROVIDER_KEY="\${PROVIDER_KEY:?set PROVIDER_KEY \u2014 your ${r}}"`,"","# Builds in ACR (no local docker login/push step needed).",'az acr build --registry "$ACR_NAME" --image "${SERVICE}:latest" --file deploy/Dockerfile .',"",'az containerapp show --name "$SERVICE" --resource-group "$RESOURCE_GROUP" >/dev/null 2>&1 \\',' && az containerapp update --name "$SERVICE" --resource-group "$RESOURCE_GROUP" \\',' --image "$IMAGE" >/dev/null \\',' || az containerapp create --name "$SERVICE" --resource-group "$RESOURCE_GROUP" \\',' --environment "$ENVIRONMENT" --image "$IMAGE" \\'," --target-port "+t.port+" --ingress external \\",' --secrets "provider-key=$PROVIDER_KEY" \\',` --env-vars "AGENTHIPPO_NO_AUTO_INSTALL=1" "${r}=secretref:provider-key" \\`," >/dev/null",'echo "Deployed $SERVICE to Container Apps environment $ENVIRONMENT"',""].join(`
595
596
  `);return{Dockerfile:Cn(t),"containerapp.json":JSON.stringify(l,null,2)+`
596
597
  `,"deploy.sh":f,"README.md":[`# Deploy: ${t.packName} \u2014 Azure Container Apps (T1-generic)`,"",`Engine: **${t.engine}**${t.model?`, model: **${t.model}**`:""}.`,"","Single container, built-in ingress + TLS \u2014 no separate load balancer to stand up.","Use `--ingress edge` or `--ingress edge-fed` for a self-contained AgentHippo edge instead.","","```bash","export RESOURCE_GROUP=<rg> CONTAINERAPPS_ENVIRONMENT=<env> ACR_NAME=<registry>",`export PROVIDER_KEY=<your ${r}>`,"bash deploy/deploy.sh","```","","> \u26A0\uFE0F Newer and far less exercised than the Cloud Run target \u2014 read `deploy.sh` before","> running it against a real account.","",...tr(t)].join(`
597
- `)}}let i=[{name:"caddy",image:"caddy:2.8-alpine",env:[{name:"PORT",value:String(s)},{name:"AGENTHIPPO_PUBLIC_HOSTNAME",value:t.publicHostname}],resources:{cpu:.25,memory:"0.5Gi"}},...e?[]:[{name:"oauth2-proxy",image:"quay.io/oauth2-proxy/oauth2-proxy:v7.7.1",env:[{name:"OAUTH2_PROXY_HTTP_ADDRESS",value:"0.0.0.0:4180"},{name:"OAUTH2_PROXY_UPSTREAMS",value:"file:///dev/null"},{name:"OAUTH2_PROXY_SET_XAUTHREQUEST",value:"true"},{name:"OAUTH2_PROXY_PASS_AUTHORIZATION_HEADER",value:"true"},{name:"OAUTH2_PROXY_SKIP_PROVIDER_BUTTON",value:"true"},{name:"OAUTH2_PROXY_REVERSE_PROXY",value:"true"},{name:"OAUTH2_PROXY_CLIENT_ID",secretRef:"oauth-client-id"},{name:"OAUTH2_PROXY_CLIENT_SECRET",secretRef:"oauth-client-secret"},{name:"OAUTH2_PROXY_COOKIE_SECRET",secretRef:"oauth-cookie-secret"}],resources:{cpu:.25,memory:"0.5Gi"}}],{name:"auth-broker",image:"${IMAGE}",command:["agenthippo","auth-broker"],env:[{name:"AGENTHIPPO_AUTH_PORT",value:"9780"},{name:"AGENTHIPPO_AUTH_JWT_SECRET",secretRef:"auth-jwt-secret"},...e?[{name:"AGENTHIPPO_AUTH_COOKIE_DOMAIN",value:t.cookieDomain||""},{name:"AGENTHIPPO_AUTH_IDP_URL",value:t.idpUrl||""}]:[]],resources:{cpu:.25,memory:"0.5Gi"}},{name:"agent",image:"${IMAGE}",command:hi(t,{wwwDir:"/app/pack/deploy/www",port:ot.EDGE_AGENT_PORT}),env:[{name:"AGENTHIPPO_NO_AUTO_INSTALL",value:"1"},{name:r,secretRef:"provider-key"}],resources:{cpu:.5,memory:"1Gi"}}],o={properties:{configuration:{ingress:{external:!0,targetPort:s},secrets:[{name:"auth-jwt-secret",value:"${AUTH_JWT_SECRET}"},{name:"provider-key",value:"${PROVIDER_KEY}"},...e?[]:[{name:"oauth-client-id",value:"${OAUTH_CLIENT_ID}"},{name:"oauth-client-secret",value:"${OAUTH_CLIENT_SECRET}"},{name:"oauth-cookie-secret",value:"${OAUTH_COOKIE_SECRET}"}]]},template:{containers:i}}},a=['AUTH_JWT_SECRET="${AUTH_JWT_SECRET:?set AUTH_JWT_SECRET}"',`PROVIDER_KEY="\${PROVIDER_KEY:?set PROVIDER_KEY \u2014 your ${r}}"`,...e?[]:['OAUTH_CLIENT_ID="${OAUTH_CLIENT_ID:?set OAUTH_CLIENT_ID}"','OAUTH_CLIENT_SECRET="${OAUTH_CLIENT_SECRET:?set OAUTH_CLIENT_SECRET}"','OAUTH_COOKIE_SECRET="${OAUTH_COOKIE_SECRET:?set OAUTH_COOKIE_SECRET}"']],c=["#!/usr/bin/env bash",`# Azure Container Apps + AgentHippo edge (${e?"edge-fed: federated identity, no oauth2-proxy":"edge: self-issued"}).`,"# Container Apps environments provide built-in ingress + TLS \u2014 no separate load balancer.","set -euo pipefail",...qr(),'SERVICE="'+t.packName+'"','RESOURCE_GROUP="${RESOURCE_GROUP:?set RESOURCE_GROUP}"','ENVIRONMENT="${CONTAINERAPPS_ENVIRONMENT:?set CONTAINERAPPS_ENVIRONMENT \u2014 az containerapp env create (one-time)}"','ACR_NAME="${ACR_NAME:?set ACR_NAME \u2014 an Azure Container Registry (one-time: az acr create)}"','IMAGE="${ACR_NAME}.azurecr.io/${SERVICE}:latest"',"","# auth-broker reuses the agent image (CLI ships `auth-broker`). Builds in ACR.",'az acr build --registry "$ACR_NAME" --image "${SERVICE}:latest" --file deploy/Dockerfile .',"",...a,'SPEC_JSON="$(sed -e "s|\\${IMAGE}|${IMAGE}|g" -e "s|\\${AUTH_JWT_SECRET}|${AUTH_JWT_SECRET}|g" \\',' -e "s|\\${PROVIDER_KEY}|${PROVIDER_KEY}|g" \\',...e?[]:[' -e "s|\\${OAUTH_CLIENT_ID}|${OAUTH_CLIENT_ID}|g" -e "s|\\${OAUTH_CLIENT_SECRET}|${OAUTH_CLIENT_SECRET}|g" \\',' -e "s|\\${OAUTH_COOKIE_SECRET}|${OAUTH_COOKIE_SECRET}|g" \\'],' deploy/containerapp.json)"','echo "$SPEC_JSON" > /tmp/${SERVICE}-containerapp.json',"","# `--yaml` also accepts JSON (JSON is valid YAML) \u2014 kept as .json so it's reviewable","# alongside the other checked-in templates without a format switch.",'az containerapp show --name "$SERVICE" --resource-group "$RESOURCE_GROUP" >/dev/null 2>&1 \\',' && az containerapp update --name "$SERVICE" --resource-group "$RESOURCE_GROUP" \\'," --yaml /tmp/${SERVICE}-containerapp.json >/dev/null \\",' || az containerapp create --name "$SERVICE" --resource-group "$RESOURCE_GROUP" \\',' --environment "$ENVIRONMENT" --yaml /tmp/${SERVICE}-containerapp.json >/dev/null','echo "Deployed $SERVICE behind the AgentHippo edge in $ENVIRONMENT"',""].join(`
598
+ `)}}let i=[{name:"caddy",image:"caddy:2.8-alpine",env:[{name:"PORT",value:String(s)},{name:"AGENTHIPPO_PUBLIC_HOSTNAME",value:t.publicHostname}],resources:{cpu:.25,memory:"0.5Gi"}},...e?[]:[{name:"oauth2-proxy",image:"quay.io/oauth2-proxy/oauth2-proxy:v7.7.1",env:[{name:"OAUTH2_PROXY_HTTP_ADDRESS",value:"0.0.0.0:4180"},{name:"OAUTH2_PROXY_UPSTREAMS",value:"file:///dev/null"},{name:"OAUTH2_PROXY_SET_XAUTHREQUEST",value:"true"},{name:"OAUTH2_PROXY_PASS_AUTHORIZATION_HEADER",value:"true"},{name:"OAUTH2_PROXY_SKIP_PROVIDER_BUTTON",value:"true"},{name:"OAUTH2_PROXY_REVERSE_PROXY",value:"true"},{name:"OAUTH2_PROXY_CLIENT_ID",secretRef:"oauth-client-id"},{name:"OAUTH2_PROXY_CLIENT_SECRET",secretRef:"oauth-client-secret"},{name:"OAUTH2_PROXY_COOKIE_SECRET",secretRef:"oauth-cookie-secret"}],resources:{cpu:.25,memory:"0.5Gi"}}],{name:"auth-broker",image:"${IMAGE}",command:["agenthippo","auth-broker"],env:[{name:"AGENTHIPPO_AUTH_PORT",value:"9780"},{name:"AGENTHIPPO_AUTH_JWT_SECRET",secretRef:"auth-jwt-secret"},...e?[{name:"AGENTHIPPO_AUTH_COOKIE_DOMAIN",value:t.cookieDomain||""},{name:"AGENTHIPPO_AUTH_IDP_URL",value:t.idpUrl||""}]:[]],resources:{cpu:.25,memory:"0.5Gi"}},{name:"agent",image:"${IMAGE}",command:hi(t,{wwwDir:"/app/pack/deploy/www",port:ot.EDGE_AGENT_PORT}),env:[{name:"AGENTHIPPO_NO_AUTO_INSTALL",value:"1"},{name:r,secretRef:"provider-key"}],resources:{cpu:.5,memory:"1Gi"}}],o={properties:{configuration:{ingress:{external:!0,targetPort:s},secrets:[{name:"auth-jwt-secret",value:"${AUTH_JWT_SECRET}"},{name:"provider-key",value:"${PROVIDER_KEY}"},...e?[]:[{name:"oauth-client-id",value:"${OAUTH_CLIENT_ID}"},{name:"oauth-client-secret",value:"${OAUTH_CLIENT_SECRET}"},{name:"oauth-cookie-secret",value:"${OAUTH_COOKIE_SECRET}"}]]},template:{containers:i}}},a=['AUTH_JWT_SECRET="${AUTH_JWT_SECRET:?set AUTH_JWT_SECRET}"',`PROVIDER_KEY="\${PROVIDER_KEY:?set PROVIDER_KEY \u2014 your ${r}}"`,...e?[]:['OAUTH_CLIENT_ID="${OAUTH_CLIENT_ID:?set OAUTH_CLIENT_ID}"','OAUTH_CLIENT_SECRET="${OAUTH_CLIENT_SECRET:?set OAUTH_CLIENT_SECRET}"','OAUTH_COOKIE_SECRET="${OAUTH_COOKIE_SECRET:?set OAUTH_COOKIE_SECRET}"']],c=["#!/usr/bin/env bash",`# Azure Container Apps + AgentHippo edge (${e?"edge-fed: federated identity, no oauth2-proxy":"edge: self-issued"}).`,"# Container Apps environments provide built-in ingress + TLS \u2014 no separate load balancer.","set -euo pipefail",...Kr(),'SERVICE="'+t.packName+'"','RESOURCE_GROUP="${RESOURCE_GROUP:?set RESOURCE_GROUP}"','ENVIRONMENT="${CONTAINERAPPS_ENVIRONMENT:?set CONTAINERAPPS_ENVIRONMENT \u2014 az containerapp env create (one-time)}"','ACR_NAME="${ACR_NAME:?set ACR_NAME \u2014 an Azure Container Registry (one-time: az acr create)}"','IMAGE="${ACR_NAME}.azurecr.io/${SERVICE}:latest"',"","# auth-broker reuses the agent image (CLI ships `auth-broker`). Builds in ACR.",'az acr build --registry "$ACR_NAME" --image "${SERVICE}:latest" --file deploy/Dockerfile .',"",...a,'SPEC_JSON="$(sed -e "s|\\${IMAGE}|${IMAGE}|g" -e "s|\\${AUTH_JWT_SECRET}|${AUTH_JWT_SECRET}|g" \\',' -e "s|\\${PROVIDER_KEY}|${PROVIDER_KEY}|g" \\',...e?[]:[' -e "s|\\${OAUTH_CLIENT_ID}|${OAUTH_CLIENT_ID}|g" -e "s|\\${OAUTH_CLIENT_SECRET}|${OAUTH_CLIENT_SECRET}|g" \\',' -e "s|\\${OAUTH_COOKIE_SECRET}|${OAUTH_COOKIE_SECRET}|g" \\'],' deploy/containerapp.json)"','echo "$SPEC_JSON" > /tmp/${SERVICE}-containerapp.json',"","# `--yaml` also accepts JSON (JSON is valid YAML) \u2014 kept as .json so it's reviewable","# alongside the other checked-in templates without a format switch.",'az containerapp show --name "$SERVICE" --resource-group "$RESOURCE_GROUP" >/dev/null 2>&1 \\',' && az containerapp update --name "$SERVICE" --resource-group "$RESOURCE_GROUP" \\'," --yaml /tmp/${SERVICE}-containerapp.json >/dev/null \\",' || az containerapp create --name "$SERVICE" --resource-group "$RESOURCE_GROUP" \\',' --environment "$ENVIRONMENT" --yaml /tmp/${SERVICE}-containerapp.json >/dev/null','echo "Deployed $SERVICE behind the AgentHippo edge in $ENVIRONMENT"',""].join(`
598
599
  `);return{Dockerfile:Cn(t,{wwwDir:"/app/pack/deploy/www"}),"www/index.html":ws(t.packName),Caddyfile:e?(0,ot.renderSidecarFedCaddyfile)(t.idpUrl):(0,ot.renderSidecarEdgeCaddyfile)(),"containerapp.json":JSON.stringify(o,null,2)+`
599
600
  `,"deploy.sh":c,"README.md":[`# Deploy: ${t.packName} \u2014 Azure Container Apps + AgentHippo edge (${e?"edge-fed":"edge"})`,"",`Engine: **${t.engine}**${t.model?`, model: **${t.model}**`:""}.`,"","One Container App, containers share the replica's localhost \u2014 the same sidecar shape","Cloud Run/ECS Fargate use, so the Caddyfile is identical:","- **caddy** (ingress, the only published port) \u2192 "+(e?"verifies the shared AgentHippo JWT":"SSO edge: oauth2-proxy for browsers, auth-broker for IDE Bearer"),`- **agent** \u2192 serves www + /v1/* on localhost:${ot.EDGE_AGENT_PORT} (not published)`,"- **auth-broker** \u2192 validates IDE AgentHippo JWTs (`/api/ide/me`)"+(e?" against the shared IdP secret":""),...e?[]:["- **oauth2-proxy** \u2192 Google SSO for browser clients"],"","Built-in ingress + TLS termination \u2014 no separate load balancer to stand up.","","```bash","export RESOURCE_GROUP=<rg> CONTAINERAPPS_ENVIRONMENT=<env> ACR_NAME=<registry>",...a.map(l=>"export "+l.split("=")[0]+"=<...>"),"bash deploy/deploy.sh","```","","> \u26A0\uFE0F Newer and far less exercised than the Cloud Run target \u2014 read `deploy.sh` before","> running it against a real account.","",...tr(t)].join(`
600
- `)}}var T0={vm:s0,compose:i0,cloudrun:d0,"databricks-app":_0,spcs:y0,cloudflare:w0,"aws-ecs":A0,"azure-container-apps":S0};function b0(t,e){let n=T0[t](e),r=e.ingress==="edge-fed",s=!!e.colocate&&r&&(t==="vm"||t==="compose"),i=Ef(e)&&t==="cloudrun"&&r,o=!s&&(t==="vm"||t==="compose"||(t==="cloudrun"||t==="aws-ecs"||t==="azure-container-apps")&&(e.ingress==="edge"||r)),a=Object.keys(n).some(f=>f==="Dockerfile"||f.endsWith("/Dockerfile")),c={...n,...a?{".dockerignore":n0()}:{},".env.example":cy(e.envVars,{edge:o,engine:e.engine,hostname:e.publicHostname,gatewayDirect:i}),...o?{".env.auth.example":ly({hostname:e.publicHostname,fed:r,idpUrl:e.idpUrl,cookieDomain:e.cookieDomain})}:{},"DATA-ACCESS.md":o0(e,t,o,r,s)},l={};for(let[f,u]of Object.entries(c))l[f]=oy(e,f,u);return l}});var Ay=S(Yr=>{"use strict";Object.defineProperty(Yr,"__esModule",{value:!0});Yr.BLUEPRINTS=Yr.BLUEPRINT_IDS=void 0;Yr.isBlueprintId=v0;Yr.resolveBlueprint=O0;Yr.BLUEPRINT_IDS=["sandbox","prospect-demo","team-pilot","regulated-air-gapped","enterprise-fleet"];function v0(t){return Yr.BLUEPRINT_IDS.includes(t)}Yr.BLUEPRINTS={sandbox:{id:"sandbox",description:"Internal test, no external users \u2014 no edge, no SSO, no host port beyond localhost.",targets:["vm"]},"prospect-demo":{id:"prospect-demo",description:"Throwaway public demo for a prospect \u2014 Cloudflare Tunnel + a throwaway Google OAuth client.",targets:["vm","compose"]},"team-pilot":{id:"team-pilot",description:"Single-agent pilot. Rides the customer platform's own identity when one exists (GCP IAP, Databricks workspace SSO, Snowflake network, Cloudflare Access); falls back to a self-issued edge (own Caddy + oauth2-proxy + Google client) on vm/compose/aws-ecs/azure-container-apps, which have no platform-native option yet.",targets:["cloudrun","databricks-app","spcs","cloudflare","vm","compose","aws-ecs","azure-container-apps"]},"regulated-air-gapped":{id:"regulated-air-gapped",description:"VPN/localhost only, no tunnel, no external telemetry \u2014 the highest-scrutiny buyer profile. Currently generator-identical to sandbox; the distinction is buyer framing, not yet enforced posture.",targets:["vm"]},"enterprise-fleet":{id:"enterprise-fleet",description:"Federated identity against a central IdP (enterprise-deploy/idp/) for a growing fleet of agents. Same-host colocation (no edge of its own) is available for vm/compose via the raw `--ingress edge-fed --colocate` flag \u2014 not yet encoded as a blueprint variant.",targets:["cloudrun","vm","compose","aws-ecs","azure-container-apps"]}};function O0(t,e){let n=Yr.BLUEPRINTS[t],r=e??n.targets[0];if(!n.targets.includes(r))throw new Error(`Blueprint "${t}" does not support --platform ${r}. Supported: ${n.targets.join(", ")}.`);switch(t){case"sandbox":case"regulated-air-gapped":return{target:r};case"prospect-demo":return{target:r,ingress:"edge"};case"enterprise-fleet":return{target:r,ingress:"edge-fed"};case"team-pilot":return r==="cloudrun"?{target:r,ingress:"iap"}:r==="databricks-app"||r==="spcs"||r==="cloudflare"?{target:r}:{target:r,ingress:"edge"}}}});var Ty=S(zr=>{"use strict";var I0=zr&&zr.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,s)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),P0=zr&&zr.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),wf=zr&&zr.__importStar||(function(){var t=function(e){return t=Object.getOwnPropertyNames||function(n){var r=[];for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(r[r.length]=s);return r},t(e)};return function(e){if(e&&e.__esModule)return e;var n={};if(e!=null)for(var r=t(e),s=0;s<r.length;s++)r[s]!=="default"&&I0(n,e,r[s]);return P0(n,e),n}})();Object.defineProperty(zr,"__esModule",{value:!0});zr.copyPackToStaging=Sy;zr.deployCommand=$0;var Jr=wf(require("fs")),Lt=wf(require("path")),N0=wf(require("js-yaml")),Xr=_f(),yf=Ay(),nr=Wn(),R0=8080;function C0(t){let e=Lt.join(t,"agent.yaml");if(!Jr.existsSync(e))throw new Error(`No agent.yaml in ${t} \u2014 point deploy init at a pack directory.`);let n=N0.load(Jr.readFileSync(e,"utf8")),r=n?.metadata?.name?.trim();if(!r)throw new Error(`agent.yaml is missing metadata.name in ${t}`);let s=n?.metadata?.version?.trim();if(!s)throw new Error(`agent.yaml is missing metadata.version in ${t}`);let i=n?.spec?.model?.trim();return{name:r,version:s,engine:n?.spec?.engine?.trim()||"claude",...i?{model:i}:{}}}var k0=new Set([".git","node_modules","__pycache__",".pytest_cache",".mypy_cache",".ruff_cache",".venv","venv",".next",".turbo",".cache","dist","build",".DS_Store",".idea",".vscode"]);function Sy(t,e){let n=[],r=Lt.resolve(e);return Jr.cpSync(t,e,{recursive:!0,force:!0,dereference:!0,preserveTimestamps:!0,filter:s=>{let i=Lt.relative(t,s);if(!i)return!0;if(s===r||s.startsWith(r+Lt.sep))return!1;let o=Lt.basename(s);if(i==="deploy"||i.startsWith("deploy"+Lt.sep)||i==="deploy-out"||i.startsWith("deploy-out"+Lt.sep)||k0.has(o)||o.startsWith(".nfs"))return!1;try{if(Jr.lstatSync(s).isSymbolicLink()&&!Jr.existsSync(s))return n.push(i),!1}catch{return!1}return!(o===".env"||o===".env.local"||o===".env.production"||o.endsWith(".log")||(0,Xr.isSecretLikeBasename)(o))}}),n}async function $0(t,e,n){t!=="init"&&(console.error(`Unknown deploy action "${t}". Supported: init`),process.exit(1));let r=n.target,s=n.ingress;if(n.blueprint){if(!(0,yf.isBlueprintId)(n.blueprint)){console.error(`Unknown --blueprint "${n.blueprint}". Supported: ${Object.keys(yf.BLUEPRINTS).join(", ")}`),process.exit(1);return}if(n.platform&&!(0,Xr.isDeployTarget)(n.platform)){console.error(`Unknown --platform "${n.platform}". Supported: ${Xr.DEPLOY_TARGETS.join(", ")}`),process.exit(1);return}try{let d=(0,yf.resolveBlueprint)(n.blueprint,n.platform);r=d.target,s=d.ingress}catch(d){console.error(`Error: ${d instanceof Error?d.message:d}`),process.exit(1);return}}let i=Lt.resolve(n.packdir||e||process.cwd()),o=r==="all"?[...Xr.DEPLOY_TARGETS]:[r];for(let d of o)(0,Xr.isDeployTarget)(d)||(console.error(`Unknown --target "${d}". Supported: ${Xr.DEPLOY_TARGETS.join(", ")}, all`),process.exit(1));let a;try{a=C0(i)}catch(d){console.error(`Error: ${d instanceof Error?d.message:d}`),process.exit(1);return}let c=(0,Xr.scanEnvRefs)(i),l=n.gateway?.trim();if(l)for(let d of["OPENCLAW_GATEWAY_TOKEN","SLACK_BOT_TOKEN","SLACK_APP_TOKEN"])c.includes(d)||c.push(d);let f=n.modelRouting==="gateway"?"gateway":n.modelRouting==="sidecar"?"sidecar":void 0;n.modelRouting&&n.modelRouting!=="gateway"&&n.modelRouting!=="sidecar"&&(console.error(`Unknown --model-routing "${n.modelRouting}". Supported: sidecar, gateway`),process.exit(1));let u={packName:a.name,packVersion:a.version,image:n.image||(0,Xr.defaultRuntimeImage)(a.engine),port:n.port||R0,engine:a.engine,model:a.model,envVars:c,gatewayChannels:l,publicHostname:(0,Xr.resolveDeployPublicHostname)(n.hostname),ingress:s,idpUrl:n.idpUrl,cookieDomain:n.cookieDomain,colocate:n.colocate,modelRouting:f,edgeTurnConnector:n.edgeTurnConnector?.trim()||void 0};for(let d of o){let p=f==="gateway"?"-gateway":"",g=n.out?o.length>1?Lt.join(Lt.resolve(n.out),d+p):Lt.resolve(n.out):Lt.join(process.cwd(),"deploy-out",`${a.name}-${d}${p}`);Jr.mkdirSync(g,{recursive:!0});let m=Sy(i,g);if(m.length>0){let y=m.slice(0,3).join(", ");console.log(` ${nr.COLORS.yellow}\u26A0 ${m.length} broken symlink(s) skipped (not staged \u2014 the image would have no content for these). Sample: ${y}${m.length>3?", \u2026":""}${nr.COLORS.reset}`)}Jr.mkdirSync(Lt.join(g,"deploy"),{recursive:!0});let h=(0,Xr.renderTarget)(d,u),E=[],_=[];for(let[y,b]of Object.entries(h)){let T=y===".dockerignore"?Lt.join(g,".dockerignore"):Lt.join(g,"deploy",y);if(Jr.existsSync(T)&&!n.force){_.push(y);continue}Jr.mkdirSync(Lt.dirname(T),{recursive:!0}),Jr.writeFileSync(T,b),E.push(y)}console.log(`${nr.COLORS.green}\u2713${nr.COLORS.reset} ${d} \u2192 ${Lt.relative(process.cwd(),g)||"."}`);for(let y of E)console.log(` ${nr.COLORS.dim}+ ${y}${nr.COLORS.reset}`);for(let y of _)console.log(` ${nr.COLORS.yellow}\u2022 ${y} (exists; --force to overwrite)${nr.COLORS.reset}`)}c.length>0&&console.log(`
601
- ${nr.COLORS.dim}Scanned pack secrets into .env.example: ${c.join(", ")}${nr.COLORS.reset}`),console.log("\nNext: cd into the staging dir above, `cp deploy/.env.example deploy/.env`, then run the command in deploy/README.md (scripts anchor themselves to the staging root)."),console.log(`${nr.COLORS.dim}Tip: run deploy init from the pack's parent directory \u2014 not from inside the pack (default deploy-out/ inside the pack copies into itself and fails).${nr.COLORS.reset}`)}});var vy=S(Af=>{"use strict";Object.defineProperty(Af,"__esModule",{value:!0});Af.renderIdpArtifacts=U0;var D0=pf(),by=_f();function L0(t){if(t.cookieDomain?.trim())return t.cookieDomain.trim();let e=t.hostname.split(".");return e.length>2?`.${e.slice(-2).join(".")}`:`.${t.hostname}`}function M0(){return["# Central IdP.","#","# ./run.sh","#","# Env split (matches `agenthippo deploy init`):","# ~/.agent-hippo/.env (+ optional ./.env) \u2014 hostname only","# ~/.agent-hippo/.env.auth (+ optional ./.env.auth) \u2014 JWT/OAuth; broker + oauth2-proxy ONLY","# Profiles: edge (SSO stack), tunnel (Cloudflare \u2192 Caddy)","# Org identity infra only \u2014 no agent runs here. Per-agent edges are generated separately","# by `agenthippo deploy init` and deployed on their own host/service.","services:"," oauth2-proxy:",' profiles: ["edge"]'," image: quay.io/oauth2-proxy/oauth2-proxy:v7.7.1"," env_file:"," - path: ${HOME}/.agent-hippo/.env"," required: false"," - path: .env"," required: false"," - path: ${HOME}/.agent-hippo/.env.auth"," required: false"," - path: .env.auth"," required: false"," environment:"," OAUTH2_PROXY_HTTP_ADDRESS: 0.0.0.0:4180"," OAUTH2_PROXY_UPSTREAMS: file:///dev/null",' OAUTH2_PROXY_SET_XAUTHREQUEST: "true"',' OAUTH2_PROXY_PASS_AUTHORIZATION_HEADER: "true"',' OAUTH2_PROXY_SKIP_PROVIDER_BUTTON: "true"',' OAUTH2_PROXY_REVERSE_PROXY: "true"',' expose: ["4180"]',""," auth-broker:",' profiles: ["edge"]'," build:"," context: ."," dockerfile: Dockerfile.auth-broker"," env_file:"," - path: ${HOME}/.agent-hippo/.env"," required: false"," - path: .env"," required: false"," - path: ${HOME}/.agent-hippo/.env.auth"," required: false"," - path: .env.auth"," required: false"," environment:",' AGENTHIPPO_AUTH_PORT: "9780"'," AGENTHIPPO_AUTH_DATA_DIR: /data"," # The broker now defaults to binding 127.0.0.1 and REFUSES a public bind unless told"," # otherwise. Here it must listen on the container interface, because Caddy reaches it"," # as `auth-broker:9780` over the compose network \u2014 a loopback bind makes it unreachable."," # Safe: the port is `expose`d, never published to the host, so the only thing that can"," # dial it is another service on this network.",' AGENTHIPPO_AUTH_BIND: "0.0.0.0"',' AGENTHIPPO_AUTH_ALLOW_PUBLIC_BIND: "1"'," # Shared secret proving an X-Auth-Request-Email came from THIS Caddy. Without it the"," # broker treats that header as unverified and 401s the forward_auth-gated routes."," # No default on purpose: compose FAILS to start rather than silently running with an"," # empty secret on both sides, which would accept every caller. Put it in ./.env.",' AGENTHIPPO_AUTH_PROXY_SECRET: "${AGENTHIPPO_AUTH_PROXY_SECRET:?set AGENTHIPPO_AUTH_PROXY_SECRET in .env (openssl rand -hex 32)}"'," # Proxy hops in front of the broker: 1 = Caddy only (edge profile), 2 = Cloudflare"," # Tunnel \u2192 Caddy (run.sh sets 2; at 1 the rate limiter would key every tunnel"," # client on cloudflared's IP \u2014 one shared bucket)."," AGENTHIPPO_XFF_TRUSTED_HOPS: ${AGENTHIPPO_XFF_TRUSTED_HOPS:-1}",' volumes: ["auth-broker-data:/data"]',' expose: ["9780"]',""," caddy:",' profiles: ["edge"]'," image: caddy:2.8-alpine"," env_file:"," - path: ${HOME}/.agent-hippo/.env"," required: false"," - path: .env"," required: false"," # With the tunnel profile, set AGENTHIPPO_CADDY_BIND=127.0.0.1 so a public-IP host"," # cannot be hit directly on 80/443, bypassing Cloudflare."," # Bare-metal / BYO nginx or ALB already on 80/443? Set AGENTHIPPO_CADDY_HTTP_PORT /"," # AGENTHIPPO_CADDY_HTTPS_PORT to alternate host ports and point your own reverse proxy"," # at them \u2014 the container still listens on 80 internally, only the host mapping moves."," ports:",' - "${AGENTHIPPO_CADDY_BIND:-0.0.0.0}:${AGENTHIPPO_CADDY_HTTP_PORT:-80}:80"',' - "${AGENTHIPPO_CADDY_BIND:-0.0.0.0}:${AGENTHIPPO_CADDY_HTTPS_PORT:-443}:443"'," environment:"," # Caddy stamps this on the two broker hops that forward a verified X-Auth-Request-Email"," # (/oauth/authorize, /oauth/browser-login). Same value the broker checks; same fail-closed"," # rule \u2014 compose refuses to start rather than send an empty secret.",' AGENTHIPPO_AUTH_PROXY_SECRET: "${AGENTHIPPO_AUTH_PROXY_SECRET:?set AGENTHIPPO_AUTH_PROXY_SECRET in .env (openssl rand -hex 32)}"'," volumes:"," - ./Caddyfile:/etc/caddy/Caddyfile:ro"," # Colocated agents (deploy init --colocate) drop a route snippet here \u2014 see Caddyfile."," - ./agents:/etc/caddy/agents:ro"," networks: [default, colocate]"," depends_on: [oauth2-proxy, auth-broker]",""," cloudflared:",' profiles: ["tunnel"]'," image: cloudflare/cloudflared:2024.12.2"," restart: unless-stopped"," command: tunnel --config /etc/cloudflared/config.yml run"," volumes:"," - ./cloudflared.yml:/etc/cloudflared/config.yml:ro"," # Set by run.sh from its argument (./run.sh /path/to/tunnel-credentials.json);"," # falls back to the conventional location for a direct `docker compose` invocation."," - ${AGENTHIPPO_TUNNEL_CREDENTIALS:-${HOME}/.agent-hippo/tunnel-credentials.json}:/etc/cloudflared/credentials.json:ro"," depends_on: [caddy]","","volumes:"," auth-broker-data:","","networks:"," default:",` # Stable, explicitly-named network (not the implicit "idp_default") so a colocated agent's`," # own compose project can join it reliably regardless of which directory `docker compose`"," # runs from. Only Caddy needs it \u2014 its per-agent snippets `reverse_proxy` straight to the"," # agent container by name; auth-broker is reached over the (already-shared) default network."," colocate:"," name: agenthippo-idp-colocate",""].join(`
602
- `)}function G0(){return["# SSO edge + Cloudflare Tunnel. Set AGENTHIPPO_PUBLIC_HOSTNAME in .env (Caddy reads it below).","# TLS terminates at Cloudflare; origin listens on HTTP only.","{"," auto_https off","}","","# Same-host colocation: agents deployed with `deploy init --ingress edge-fed --colocate`","# on THIS host ship a route snippet instead of their own Caddy/oauth2-proxy/auth-broker.","# Drop it in ./agents/<name>.caddy (mounted in docker-compose.yml) and","# `docker compose exec caddy caddy reload --config /etc/caddy/Caddyfile` to pick it up \u2014","# no rebuild, no restart of the IdP itself.","import agents/*.caddy","","http://{$AGENTHIPPO_PUBLIC_HOSTNAME} {",...(0,D0.renderIdentityLayer)({mode:"self-issued",oauth2ProxyAddr:"oauth2-proxy:4180",authBrokerAddr:"auth-broker:9780",healthProxy:[" reverse_proxy auth-broker:9780"],agentProxy:[' respond "not_found" 404'],catchallBody:[' respond "AgentHippo IdP" 200']}),"}",""].join(`
603
- `)}function U0(t){let e=L0(t);return{"docker-compose.yml":M0(),"Dockerfile.auth-broker":(0,by.renderAuthBrokerDockerfile)(),Caddyfile:G0(),".env.example":["# Caddy hostname for the central IdP. No agent runs on this stack \u2014 auth secrets:","# see .env.auth.example \u2192 ~/.agent-hippo/.env.auth (broker + oauth2-proxy only).","",`AGENTHIPPO_PUBLIC_HOSTNAME=${t.hostname}`,"","# REQUIRED. Shared secret between Caddy and auth-broker, proving that an","# X-Auth-Request-Email reached the broker through this Caddy rather than from a client","# that merely found the port. The broker 401s that header without a matching secret, and","# docker compose refuses to start if this is unset \u2014 an empty secret on both sides would","# accept everyone. It lives HERE (not .env.auth) because Caddy needs it too, and Caddy","# must not be handed the OAuth client secret or the JWT signing key.","# openssl rand -hex 32","AGENTHIPPO_AUTH_PROXY_SECRET=","","# Proxy hops / Caddy bind (optional; run.sh sets XFF hops=2 for tunnel)","# AGENTHIPPO_XFF_TRUSTED_HOPS=1","# AGENTHIPPO_CADDY_BIND=0.0.0.0","","# Bare metal / BYO nginx or ALB already on 80/443? Rebind Caddy to alternate host ports","# and point your reverse proxy at them (container still listens on 80 internally):","# AGENTHIPPO_CADDY_HTTP_PORT=8080","# AGENTHIPPO_CADDY_HTTPS_PORT=8443",""].join(`
604
- `),".env.auth.example":(0,by.renderAuthEnvExample)({hostname:t.hostname,fed:!1,cookieDomain:e}),"cloudflared.yml.example":["# Copy to cloudflared.yml; the credentials JSON lives in ~/.agent-hippo/ (never in the repo).","# cloudflared tunnel create agenthippo-auth","# cp ~/.cloudflared/<tunnel-id>.json ~/.agent-hippo/tunnel-credentials.json",`# cloudflared tunnel route dns agenthippo-auth ${t.hostname}`,"tunnel: REPLACE_WITH_TUNNEL_ID","credentials-file: /etc/cloudflared/credentials.json","ingress:",` - hostname: ${t.hostname}`," service: http://caddy:80"," - service: http_status:404",""].join(`
601
+ `)}}var I0={vm:c0,compose:l0,cloudrun:h0,"databricks-app":S0,spcs:T0,cloudflare:b0,"aws-ecs":v0,"azure-container-apps":O0};function P0(t,e){let n=I0[t](e),r=e.ingress==="edge-fed",s=!!e.colocate&&r&&(t==="vm"||t==="compose"),i=_f(e)&&t==="cloudrun"&&r,o=!s&&(t==="vm"||t==="compose"||(t==="cloudrun"||t==="aws-ecs"||t==="azure-container-apps")&&(e.ingress==="edge"||r)),a=Object.keys(n).some(f=>f==="Dockerfile"||f.endsWith("/Dockerfile")),c={...n,...a?{".dockerignore":o0()}:{},".env.example":dy(e.envVars,{edge:o,engine:e.engine,hostname:e.publicHostname,gatewayDirect:i}),...o?{".env.auth.example":fy({hostname:e.publicHostname,fed:r,idpUrl:e.idpUrl,cookieDomain:e.cookieDomain})}:{},"DATA-ACCESS.md":u0(e,t,o,r,s)},l={};for(let[f,u]of Object.entries(c))l[f]=uy(e,f,u);return l}});var vy=S(qr=>{"use strict";Object.defineProperty(qr,"__esModule",{value:!0});qr.BLUEPRINTS=qr.BLUEPRINT_IDS=void 0;qr.isBlueprintId=N0;qr.resolveBlueprint=R0;qr.BLUEPRINT_IDS=["sandbox","prospect-demo","team-pilot","regulated-air-gapped","enterprise-fleet"];function N0(t){return qr.BLUEPRINT_IDS.includes(t)}qr.BLUEPRINTS={sandbox:{id:"sandbox",description:"Internal test, no external users \u2014 no edge, no SSO, no host port beyond localhost.",targets:["vm"]},"prospect-demo":{id:"prospect-demo",description:"Throwaway public demo for a prospect \u2014 Cloudflare Tunnel + a throwaway Google OAuth client.",targets:["vm","compose"]},"team-pilot":{id:"team-pilot",description:"Single-agent pilot. Rides the customer platform's own identity when one exists (GCP IAP, Databricks workspace SSO, Snowflake network, Cloudflare Access); falls back to a self-issued edge (own Caddy + oauth2-proxy + Google client) on vm/compose/aws-ecs/azure-container-apps, which have no platform-native option yet.",targets:["cloudrun","databricks-app","spcs","cloudflare","vm","compose","aws-ecs","azure-container-apps"]},"regulated-air-gapped":{id:"regulated-air-gapped",description:"VPN/localhost only, no tunnel, no external telemetry \u2014 the highest-scrutiny buyer profile. Currently generator-identical to sandbox; the distinction is buyer framing, not yet enforced posture.",targets:["vm"]},"enterprise-fleet":{id:"enterprise-fleet",description:"Federated identity against a central IdP (enterprise-deploy/idp/) for a growing fleet of agents. Same-host colocation (no edge of its own) is available for vm/compose via the raw `--ingress edge-fed --colocate` flag \u2014 not yet encoded as a blueprint variant.",targets:["cloudrun","vm","compose","aws-ecs","azure-container-apps"]}};function R0(t,e){let n=qr.BLUEPRINTS[t],r=e??n.targets[0];if(!n.targets.includes(r))throw new Error(`Blueprint "${t}" does not support --platform ${r}. Supported: ${n.targets.join(", ")}.`);switch(t){case"sandbox":case"regulated-air-gapped":return{target:r};case"prospect-demo":return{target:r,ingress:"edge"};case"enterprise-fleet":return{target:r,ingress:"edge-fed"};case"team-pilot":return r==="cloudrun"?{target:r,ingress:"iap"}:r==="databricks-app"||r==="spcs"||r==="cloudflare"?{target:r}:{target:r,ingress:"edge"}}}});var Iy=S(Jr=>{"use strict";var C0=Jr&&Jr.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,s)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),k0=Jr&&Jr.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),Af=Jr&&Jr.__importStar||(function(){var t=function(e){return t=Object.getOwnPropertyNames||function(n){var r=[];for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(r[r.length]=s);return r},t(e)};return function(e){if(e&&e.__esModule)return e;var n={};if(e!=null)for(var r=t(e),s=0;s<r.length;s++)r[s]!=="default"&&C0(n,e,r[s]);return k0(n,e),n}})();Object.defineProperty(Jr,"__esModule",{value:!0});Jr.copyPackToStaging=Oy;Jr.deployCommand=G0;var Xr=Af(require("fs")),Lt=Af(require("path")),$0=Af(require("js-yaml")),Yr=yf(),wf=vy(),nr=Wn(),D0=8080;function L0(t){let e=Lt.join(t,"agent.yaml");if(!Xr.existsSync(e))throw new Error(`No agent.yaml in ${t} \u2014 point deploy init at a pack directory.`);let n=$0.load(Xr.readFileSync(e,"utf8")),r=n?.metadata?.name?.trim();if(!r)throw new Error(`agent.yaml is missing metadata.name in ${t}`);let s=n?.metadata?.version?.trim();if(!s)throw new Error(`agent.yaml is missing metadata.version in ${t}`);let i=n?.spec?.model?.trim();return{name:r,version:s,engine:n?.spec?.engine?.trim()||"claude",...i?{model:i}:{}}}var M0=new Set([".git","node_modules","__pycache__",".pytest_cache",".mypy_cache",".ruff_cache",".venv","venv",".next",".turbo",".cache","dist","build",".DS_Store",".idea",".vscode"]);function Oy(t,e){let n=[],r=Lt.resolve(e);return Xr.cpSync(t,e,{recursive:!0,force:!0,dereference:!0,preserveTimestamps:!0,filter:s=>{let i=Lt.relative(t,s);if(!i)return!0;if(s===r||s.startsWith(r+Lt.sep))return!1;let o=Lt.basename(s);if(i==="deploy"||i.startsWith("deploy"+Lt.sep)||i==="deploy-out"||i.startsWith("deploy-out"+Lt.sep)||M0.has(o)||o.startsWith(".nfs"))return!1;try{if(Xr.lstatSync(s).isSymbolicLink()&&!Xr.existsSync(s))return n.push(i),!1}catch{return!1}return!(o===".env"||o===".env.local"||o===".env.production"||o.endsWith(".log")||(0,Yr.isSecretLikeBasename)(o))}}),n}async function G0(t,e,n){t!=="init"&&(console.error(`Unknown deploy action "${t}". Supported: init`),process.exit(1));let r=n.target,s=n.ingress;if(n.blueprint){if(!(0,wf.isBlueprintId)(n.blueprint)){console.error(`Unknown --blueprint "${n.blueprint}". Supported: ${Object.keys(wf.BLUEPRINTS).join(", ")}`),process.exit(1);return}if(n.platform&&!(0,Yr.isDeployTarget)(n.platform)){console.error(`Unknown --platform "${n.platform}". Supported: ${Yr.DEPLOY_TARGETS.join(", ")}`),process.exit(1);return}try{let d=(0,wf.resolveBlueprint)(n.blueprint,n.platform);r=d.target,s=d.ingress}catch(d){console.error(`Error: ${d instanceof Error?d.message:d}`),process.exit(1);return}}let i=Lt.resolve(n.packdir||e||process.cwd()),o=r==="all"?[...Yr.DEPLOY_TARGETS]:[r];for(let d of o)(0,Yr.isDeployTarget)(d)||(console.error(`Unknown --target "${d}". Supported: ${Yr.DEPLOY_TARGETS.join(", ")}, all`),process.exit(1));let a;try{a=L0(i)}catch(d){console.error(`Error: ${d instanceof Error?d.message:d}`),process.exit(1);return}let c=(0,Yr.scanEnvRefs)(i),l=n.gateway?.trim();if(l)for(let d of["OPENCLAW_GATEWAY_TOKEN","SLACK_BOT_TOKEN","SLACK_APP_TOKEN"])c.includes(d)||c.push(d);let f=n.modelRouting==="gateway"?"gateway":n.modelRouting==="sidecar"?"sidecar":void 0;n.modelRouting&&n.modelRouting!=="gateway"&&n.modelRouting!=="sidecar"&&(console.error(`Unknown --model-routing "${n.modelRouting}". Supported: sidecar, gateway`),process.exit(1));let u={packName:a.name,packVersion:a.version,image:n.image||(0,Yr.defaultRuntimeImage)(a.engine),port:n.port||D0,engine:a.engine,model:a.model,envVars:c,gatewayChannels:l,publicHostname:(0,Yr.resolveDeployPublicHostname)(n.hostname),ingress:s,idpUrl:n.idpUrl,cookieDomain:n.cookieDomain,colocate:n.colocate,modelRouting:f,edgeTurnConnector:n.edgeTurnConnector?.trim()||void 0};for(let d of o){let p=f==="gateway"?"-gateway":"",g=n.out?o.length>1?Lt.join(Lt.resolve(n.out),d+p):Lt.resolve(n.out):Lt.join(process.cwd(),"deploy-out",`${a.name}-${d}${p}`);Xr.mkdirSync(g,{recursive:!0});let m=Oy(i,g);if(m.length>0){let y=m.slice(0,3).join(", ");console.log(` ${nr.COLORS.yellow}\u26A0 ${m.length} broken symlink(s) skipped (not staged \u2014 the image would have no content for these). Sample: ${y}${m.length>3?", \u2026":""}${nr.COLORS.reset}`)}Xr.mkdirSync(Lt.join(g,"deploy"),{recursive:!0});let h=(0,Yr.renderTarget)(d,u),E=[],_=[];for(let[y,b]of Object.entries(h)){let T=y===".dockerignore"?Lt.join(g,".dockerignore"):Lt.join(g,"deploy",y);if(Xr.existsSync(T)&&!n.force){_.push(y);continue}Xr.mkdirSync(Lt.dirname(T),{recursive:!0}),Xr.writeFileSync(T,b),E.push(y)}console.log(`${nr.COLORS.green}\u2713${nr.COLORS.reset} ${d} \u2192 ${Lt.relative(process.cwd(),g)||"."}`);for(let y of E)console.log(` ${nr.COLORS.dim}+ ${y}${nr.COLORS.reset}`);for(let y of _)console.log(` ${nr.COLORS.yellow}\u2022 ${y} (exists; --force to overwrite)${nr.COLORS.reset}`)}c.length>0&&console.log(`
602
+ ${nr.COLORS.dim}Scanned pack secrets into .env.example: ${c.join(", ")}${nr.COLORS.reset}`),console.log("\nNext: cd into the staging dir above, `cp deploy/.env.example deploy/.env`, then run the command in deploy/README.md (scripts anchor themselves to the staging root)."),console.log(`${nr.COLORS.dim}Tip: run deploy init from the pack's parent directory \u2014 not from inside the pack (default deploy-out/ inside the pack copies into itself and fails).${nr.COLORS.reset}`)}});var Ny=S(Sf=>{"use strict";Object.defineProperty(Sf,"__esModule",{value:!0});Sf.renderIdpArtifacts=B0;var U0=pf(),Py=yf();function H0(t){if(t.cookieDomain?.trim())return t.cookieDomain.trim();let e=t.hostname.split(".");return e.length>2?`.${e.slice(-2).join(".")}`:`.${t.hostname}`}function j0(){return["# Central IdP.","#","# ./run.sh","#","# Env split (matches `agenthippo deploy init`):","# ~/.agent-hippo/.env (+ optional ./.env) \u2014 hostname only","# ~/.agent-hippo/.env.auth (+ optional ./.env.auth) \u2014 JWT/OAuth; broker + oauth2-proxy ONLY","# Profiles: edge (SSO stack), tunnel (Cloudflare \u2192 Caddy)","# Org identity infra only \u2014 no agent runs here. Per-agent edges are generated separately","# by `agenthippo deploy init` and deployed on their own host/service.","services:"," oauth2-proxy:",' profiles: ["edge"]'," image: quay.io/oauth2-proxy/oauth2-proxy:v7.7.1"," env_file:"," - path: ${HOME}/.agent-hippo/.env"," required: false"," - path: .env"," required: false"," - path: ${HOME}/.agent-hippo/.env.auth"," required: false"," - path: .env.auth"," required: false"," environment:"," OAUTH2_PROXY_HTTP_ADDRESS: 0.0.0.0:4180"," OAUTH2_PROXY_UPSTREAMS: file:///dev/null",' OAUTH2_PROXY_SET_XAUTHREQUEST: "true"',' OAUTH2_PROXY_PASS_AUTHORIZATION_HEADER: "true"',' OAUTH2_PROXY_SKIP_PROVIDER_BUTTON: "true"',' OAUTH2_PROXY_REVERSE_PROXY: "true"',' expose: ["4180"]',""," auth-broker:",' profiles: ["edge"]'," build:"," context: ."," dockerfile: Dockerfile.auth-broker"," env_file:"," - path: ${HOME}/.agent-hippo/.env"," required: false"," - path: .env"," required: false"," - path: ${HOME}/.agent-hippo/.env.auth"," required: false"," - path: .env.auth"," required: false"," environment:",' AGENTHIPPO_AUTH_PORT: "9780"'," AGENTHIPPO_AUTH_DATA_DIR: /data"," # The broker now defaults to binding 127.0.0.1 and REFUSES a public bind unless told"," # otherwise. Here it must listen on the container interface, because Caddy reaches it"," # as `auth-broker:9780` over the compose network \u2014 a loopback bind makes it unreachable."," # Safe: the port is `expose`d, never published to the host, so the only thing that can"," # dial it is another service on this network.",' AGENTHIPPO_AUTH_BIND: "0.0.0.0"',' AGENTHIPPO_AUTH_ALLOW_PUBLIC_BIND: "1"'," # Shared secret proving an X-Auth-Request-Email came from THIS Caddy. Without it the"," # broker treats that header as unverified and 401s the forward_auth-gated routes."," # No default on purpose: compose FAILS to start rather than silently running with an"," # empty secret on both sides, which would accept every caller. Put it in ./.env.",' AGENTHIPPO_AUTH_PROXY_SECRET: "${AGENTHIPPO_AUTH_PROXY_SECRET:?set AGENTHIPPO_AUTH_PROXY_SECRET in .env (openssl rand -hex 32)}"'," # Proxy hops in front of the broker: 1 = Caddy only (edge profile), 2 = Cloudflare"," # Tunnel \u2192 Caddy (run.sh sets 2; at 1 the rate limiter would key every tunnel"," # client on cloudflared's IP \u2014 one shared bucket)."," AGENTHIPPO_XFF_TRUSTED_HOPS: ${AGENTHIPPO_XFF_TRUSTED_HOPS:-1}",' volumes: ["auth-broker-data:/data"]',' expose: ["9780"]',""," caddy:",' profiles: ["edge"]'," image: caddy:2.8-alpine"," env_file:"," - path: ${HOME}/.agent-hippo/.env"," required: false"," - path: .env"," required: false"," # With the tunnel profile, set AGENTHIPPO_CADDY_BIND=127.0.0.1 so a public-IP host"," # cannot be hit directly on 80/443, bypassing Cloudflare."," # Bare-metal / BYO nginx or ALB already on 80/443? Set AGENTHIPPO_CADDY_HTTP_PORT /"," # AGENTHIPPO_CADDY_HTTPS_PORT to alternate host ports and point your own reverse proxy"," # at them \u2014 the container still listens on 80 internally, only the host mapping moves."," ports:",' - "${AGENTHIPPO_CADDY_BIND:-0.0.0.0}:${AGENTHIPPO_CADDY_HTTP_PORT:-80}:80"',' - "${AGENTHIPPO_CADDY_BIND:-0.0.0.0}:${AGENTHIPPO_CADDY_HTTPS_PORT:-443}:443"'," environment:"," # Caddy stamps this on the two broker hops that forward a verified X-Auth-Request-Email"," # (/oauth/authorize, /oauth/browser-login). Same value the broker checks; same fail-closed"," # rule \u2014 compose refuses to start rather than send an empty secret.",' AGENTHIPPO_AUTH_PROXY_SECRET: "${AGENTHIPPO_AUTH_PROXY_SECRET:?set AGENTHIPPO_AUTH_PROXY_SECRET in .env (openssl rand -hex 32)}"'," volumes:"," - ./Caddyfile:/etc/caddy/Caddyfile:ro"," # Colocated agents (deploy init --colocate) drop a route snippet here \u2014 see Caddyfile."," - ./agents:/etc/caddy/agents:ro"," networks: [default, colocate]"," depends_on: [oauth2-proxy, auth-broker]",""," cloudflared:",' profiles: ["tunnel"]'," image: cloudflare/cloudflared:2024.12.2"," restart: unless-stopped"," command: tunnel --config /etc/cloudflared/config.yml run"," volumes:"," - ./cloudflared.yml:/etc/cloudflared/config.yml:ro"," # Set by run.sh from its argument (./run.sh /path/to/tunnel-credentials.json);"," # falls back to the conventional location for a direct `docker compose` invocation."," - ${AGENTHIPPO_TUNNEL_CREDENTIALS:-${HOME}/.agent-hippo/tunnel-credentials.json}:/etc/cloudflared/credentials.json:ro"," depends_on: [caddy]","","volumes:"," auth-broker-data:","","networks:"," default:",` # Stable, explicitly-named network (not the implicit "idp_default") so a colocated agent's`," # own compose project can join it reliably regardless of which directory `docker compose`"," # runs from. Only Caddy needs it \u2014 its per-agent snippets `reverse_proxy` straight to the"," # agent container by name; auth-broker is reached over the (already-shared) default network."," colocate:"," name: agenthippo-idp-colocate",""].join(`
603
+ `)}function x0(){return["# SSO edge + Cloudflare Tunnel. Set AGENTHIPPO_PUBLIC_HOSTNAME in .env (Caddy reads it below).","# TLS terminates at Cloudflare; origin listens on HTTP only.","{"," auto_https off","}","","# Same-host colocation: agents deployed with `deploy init --ingress edge-fed --colocate`","# on THIS host ship a route snippet instead of their own Caddy/oauth2-proxy/auth-broker.","# Drop it in ./agents/<name>.caddy (mounted in docker-compose.yml) and","# `docker compose exec caddy caddy reload --config /etc/caddy/Caddyfile` to pick it up \u2014","# no rebuild, no restart of the IdP itself.","import agents/*.caddy","","http://{$AGENTHIPPO_PUBLIC_HOSTNAME} {",...(0,U0.renderIdentityLayer)({mode:"self-issued",oauth2ProxyAddr:"oauth2-proxy:4180",authBrokerAddr:"auth-broker:9780",healthProxy:[" reverse_proxy auth-broker:9780"],agentProxy:[' respond "not_found" 404'],catchallBody:[' respond "AgentHippo IdP" 200']}),"}",""].join(`
604
+ `)}function B0(t){let e=H0(t);return{"docker-compose.yml":j0(),"Dockerfile.auth-broker":(0,Py.renderAuthBrokerDockerfile)(),Caddyfile:x0(),".env.example":["# Caddy hostname for the central IdP. No agent runs on this stack \u2014 auth secrets:","# see .env.auth.example \u2192 ~/.agent-hippo/.env.auth (broker + oauth2-proxy only).","",`AGENTHIPPO_PUBLIC_HOSTNAME=${t.hostname}`,"","# REQUIRED. Shared secret between Caddy and auth-broker, proving that an","# X-Auth-Request-Email reached the broker through this Caddy rather than from a client","# that merely found the port. The broker 401s that header without a matching secret, and","# docker compose refuses to start if this is unset \u2014 an empty secret on both sides would","# accept everyone. It lives HERE (not .env.auth) because Caddy needs it too, and Caddy","# must not be handed the OAuth client secret or the JWT signing key.","# openssl rand -hex 32","AGENTHIPPO_AUTH_PROXY_SECRET=","","# Proxy hops / Caddy bind (optional; run.sh sets XFF hops=2 for tunnel)","# AGENTHIPPO_XFF_TRUSTED_HOPS=1","# AGENTHIPPO_CADDY_BIND=0.0.0.0","","# Bare metal / BYO nginx or ALB already on 80/443? Rebind Caddy to alternate host ports","# and point your reverse proxy at them (container still listens on 80 internally):","# AGENTHIPPO_CADDY_HTTP_PORT=8080","# AGENTHIPPO_CADDY_HTTPS_PORT=8443",""].join(`
605
+ `),".env.auth.example":(0,Py.renderAuthEnvExample)({hostname:t.hostname,fed:!1,cookieDomain:e}),"cloudflared.yml.example":["# Copy to cloudflared.yml; the credentials JSON lives in ~/.agent-hippo/ (never in the repo).","# cloudflared tunnel create agenthippo-auth","# cp ~/.cloudflared/<tunnel-id>.json ~/.agent-hippo/tunnel-credentials.json",`# cloudflared tunnel route dns agenthippo-auth ${t.hostname}`,"tunnel: REPLACE_WITH_TUNNEL_ID","credentials-file: /etc/cloudflared/credentials.json","ingress:",` - hostname: ${t.hostname}`," service: http://caddy:80"," - service: http_status:404",""].join(`
605
606
  `),"run.sh":["#!/usr/bin/env bash","# Start central IdP: Caddy + oauth2-proxy + auth-broker (+ Cloudflare tunnel, if requested).","# No agent here \u2014 per-agent edges are generated separately by `agenthippo deploy init`.","#","# Usage:","# ./run.sh bare metal / BYO nginx or ALB in front","# ./run.sh /path/to/tunnel-credentials.json Cloudflare Tunnel","#","# Bare metal / BYO nginx or ALB: run with no argument \u2014 starts --profile edge only.","# If 80/443 are already taken by your reverse proxy, set AGENTHIPPO_CADDY_HTTP_PORT/","# _HTTPS_PORT in .env first so Caddy rebinds elsewhere.","set -euo pipefail",'cd "$(dirname "$0")"',"if [[ $# -ge 1 ]]; then",' export AGENTHIPPO_TUNNEL_CREDENTIALS="$1"',' [[ -f "$AGENTHIPPO_TUNNEL_CREDENTIALS" ]] || {',' echo "Tunnel credentials file not found: $AGENTHIPPO_TUNNEL_CREDENTIALS" >&2; exit 1; }'," # Two proxy hops behind the tunnel (cloudflared \u2192 Caddy) \u2014 see docker-compose.yml.",' export AGENTHIPPO_XFF_TRUSTED_HOPS="${AGENTHIPPO_XFF_TRUSTED_HOPS:-2}"'," docker compose --profile edge --profile tunnel up -d --build",` echo "IdP: https://\${AGENTHIPPO_PUBLIC_HOSTNAME:-${t.hostname}} (via Cloudflare Tunnel)"`,"else",' echo "No tunnel credentials path given \u2014 starting --profile edge only (no tunnel)."',' echo "Front this host with your own nginx/ALB; see AGENTHIPPO_CADDY_HTTP_PORT/AGENTHIPPO_CADDY_BIND in .env."',' echo "(To use a Cloudflare Tunnel instead: ./run.sh /path/to/tunnel-credentials.json)"'," docker compose --profile edge up -d --build",` echo "IdP: http://\${AGENTHIPPO_PUBLIC_HOSTNAME:-${t.hostname}} (behind your own reverse proxy)"`,"fi",""].join(`
606
607
  `),"agents/README.md":["# Colocated agent routes","","Drop `*.caddy` route snippets here for agents deployed on **this same host** via:","","```bash","agenthippo deploy init <pack> --target compose --ingress edge-fed --colocate","```","","That command generates `deploy/agent-route.caddy` (copy it here, renamed to something","identifying the agent) plus a `docker-compose.yml` containing only the `agent` service","(no Caddy/oauth2-proxy/auth-broker of its own \u2014 it joins this IdP's","`agenthippo-idp-colocate` network and rides the IdP's existing edge).","","After copying a new snippet in:","","```bash","docker compose exec caddy caddy reload --config /etc/caddy/Caddyfile","```","","No rebuild, no restart of the IdP itself. See `../Caddyfile`'s `import agents/*.caddy` and","the IdP documentation for the full picture.",""].join(`
607
608
  `),"README.md":["# Central IdP","","**One per organization.** Hosts Google SSO (oauth2-proxy) and the IDE auth-broker only \u2014","no agent runs here. Agent edges are generated and deployed separately.","","Generated by `agenthippo idp init` \u2014 regenerate (don't hand-edit `Caddyfile`, which comes","straight from the same identity module every agent's Caddyfile uses) if you need to change","routing: that lives in the CLI itself, not in this output.","","This stack runs on **any host with Docker** \u2014 local laptop, team VM, cloud VM, or on-prem.","`./run.sh` picks the path below based on whether you pass it a tunnel credentials path.","","## Quick start","","```bash","cp .env.example ~/.agent-hippo/.env","cp .env.auth.example ~/.agent-hippo/.env.auth # fill in; never put AGENTHIPPO_AUTH_JWT_SECRET in .env","","# REQUIRED: the Caddy\u2194broker proxy secret. It must be visible to `docker compose`","# ITSELF (compose interpolates it into both services), so it goes in ./.env here \u2014","# not only in ~/.agent-hippo/.env, which is read by containers but not by compose.",'echo "AGENTHIPPO_AUTH_PROXY_SECRET=$(openssl rand -hex 32)" >> .env',"```","","Without it `docker compose up` fails immediately with a message naming the variable. That","is deliberate: the broker refuses an `X-Auth-Request-Email` that arrives without a matching","`x-agenthippo-proxy-secret`, so an empty secret on both sides would accept every caller.","","**Cloudflare Tunnel** (no public ports to manage yourself):","","```bash","cp cloudflared.yml.example cloudflared.yml # set tunnel id","cloudflared tunnel create agenthippo-auth # writes ~/.cloudflared/<tunnel-id>.json","cp ~/.cloudflared/<tunnel-id>.json ~/.agent-hippo/tunnel-credentials.json","./run.sh ~/.agent-hippo/tunnel-credentials.json","```","","**Bare metal / BYO nginx or ALB already fronting this host:**","","```bash","# skip cloudflared.yml entirely. If 80/443 are already taken by your reverse proxy,","# set AGENTHIPPO_CADDY_HTTP_PORT/AGENTHIPPO_CADDY_HTTPS_PORT in .env first.","./run.sh # no argument \u2014 starts --profile edge only","# point your nginx/ALB at this host's Caddy (AGENTHIPPO_CADDY_BIND / _HTTP_PORT above)","```","","Agent edges (e.g. `cs.corp.example`) are separate.",""].join(`
608
- `)}}});var Iy=S(As=>{"use strict";var H0=As&&As.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,s)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),j0=As&&As.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),Oy=As&&As.__importStar||(function(){var t=function(e){return t=Object.getOwnPropertyNames||function(n){var r=[];for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(r[r.length]=s);return r},t(e)};return function(e){if(e&&e.__esModule)return e;var n={};if(e!=null)for(var r=t(e),s=0;s<r.length;s++)r[s]!=="default"&&H0(n,e,r[s]);return j0(n,e),n}})();Object.defineProperty(As,"__esModule",{value:!0});As.idpCommand=B0;var Zc=Oy(require("fs")),Xo=Oy(require("path")),x0=vy(),qi=Wn();async function B0(t,e){if(t!=="init"){console.error(`Unknown idp action "${t}". Supported: init`),process.exit(1);return}if(!e.hostname?.trim()){console.error("idp init requires --hostname <public-hostname> (e.g. auth.corp.example)"),process.exit(1);return}let n=Xo.resolve(e.out||"./enterprise-deploy/idp");Zc.mkdirSync(n,{recursive:!0});let r={hostname:e.hostname.trim(),cookieDomain:e.cookieDomain},s=(0,x0.renderIdpArtifacts)(r),i=[],o=[];for(let[a,c]of Object.entries(s)){let l=Xo.join(n,a);if(Zc.existsSync(l)&&!e.force){o.push(a);continue}Zc.mkdirSync(Xo.dirname(l),{recursive:!0}),Zc.writeFileSync(l,c),i.push(a)}console.log(`${qi.COLORS.green}\u2713${qi.COLORS.reset} idp \u2192 ${Xo.relative(process.cwd(),n)||"."}`);for(let a of i)console.log(` ${qi.COLORS.dim}+ ${a}${qi.COLORS.reset}`);for(let a of o)console.log(` ${qi.COLORS.yellow}\u2022 ${a} (exists; --force to overwrite)${qi.COLORS.reset}`);console.log(`Next: cd ${Xo.relative(process.cwd(),n)||"."}, cp .env.example ~/.agent-hippo/.env, cp .env.auth.example ~/.agent-hippo/.env.auth (fill in), then ./run.sh`)}});var bf=S($n=>{"use strict";var F0=$n&&$n.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,s)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),V0=$n&&$n.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),W0=$n&&$n.__importStar||(function(){var t=function(e){return t=Object.getOwnPropertyNames||function(n){var r=[];for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(r[r.length]=s);return r},t(e)};return function(e){if(e&&e.__esModule)return e;var n={};if(e!=null)for(var r=t(e),s=0;s<r.length;s++)r[s]!=="default"&&F0(n,e,r[s]);return V0(n,e),n}})();Object.defineProperty($n,"__esModule",{value:!0});$n.discoverPublishableEngines=Ry;$n.resolveEngineSourceDir=tL;$n.validateEngineForPublish=nL;$n.collectEngineFiles=rL;$n.isValidPublishVersion=sL;var K0=require("child_process"),xs=require("fs"),kn=W0(require("path")),q0=require("util"),Y0=Ke(),Ei=en(),X0=Pa(),J0=(0,q0.promisify)(K0.execFile),el="engine.manifest.json",z0=new Set([".git",".hg",".svn",".DS_Store","node_modules","dist","coverage",".turbo",".cache",".pnpm-store","Thumbs.db"]),Q0=[["private key",/-----BEGIN (?:RSA |EC |OPENSSH |DSA )?PRIVATE KEY-----/],["OpenAI-style key",/\bsk-(?!dummy\b|ant-)[A-Za-z0-9_-]{20,}\b/],["Anthropic key",/\bsk-ant-[A-Za-z0-9_-]{20,}\b/],["Google API key",/\bAIza[0-9A-Za-z_-]{30,}\b/],["GitHub token",/\bgh[pousr]_[A-Za-z0-9_]{20,}\b/],["Atlassian API token",/\bATATT[A-Za-z0-9_=+/\-]{20,}\b/],["AWS access key",/\bAKIA[0-9A-Z]{16}\b/],["JWT",/\beyJ[A-Za-z0-9_-]{20,}\.[A-Za-z0-9_-]{20,}\.[A-Za-z0-9_-]{10,}\b/]];function Py(t){return!!(z0.has(t)||/^\.env(?:\.|$)/.test(t)||/\.log$/i.test(t))}function Sf(t){let e=t.replace(/\\/g,"/").trim().replace(/^\.\//,"");if(!e||e==="."||e==="..")throw new Error("must be a non-empty relative path");if(e.includes("\0")||kn.posix.isAbsolute(e)||/^[A-Za-z]:[\\/]/.test(e))throw new Error(`must be a safe relative path: ${t}`);for(let n of e.split("/"))if(!n||n==="."||n==="..")throw new Error(`must not contain empty, "." or ".." segments: ${t}`);return e}async function Ny(t){let e=kn.join(t,el),n=await xs.promises.readFile(e,"utf-8"),r=JSON.parse(n);if(!r||typeof r!="object"||Array.isArray(r))throw new Error(`${e} must contain a JSON object`);if(r.version!==2)throw new Error(`${e} must use custom engine manifest version 2`);if(typeof r.id!="string"||!/^[a-z0-9][a-z0-9._-]*$/.test(r.id))throw new Error(`${e} has invalid id: ${String(r.id)}`);if(typeof r.entry!="string")throw new Error(`${e} must define string entry`);let s=Sf(r.entry),i=kn.join(t,s);if(!await(0,Ei.pathExists)(i))throw new Error(`${e} entry does not exist: ${s}`);if(r.workspaceSync&&typeof r.workspaceSync=="object"){let o=r.workspaceSync;o.enabled&&(typeof o.dir=="string"&&Sf(o.dir),typeof o.rulesFile=="string"&&Sf(o.rulesFile))}return{manifest:r,manifestPath:e,entryPath:i}}async function Tf(t,e=""){let n=kn.join(t,e),r=await xs.promises.readdir(n,{withFileTypes:!0}),s=[];for(let i of r){if(Py(i.name))continue;let o=e?kn.join(e,i.name):i.name,a=kn.join(t,o);i.isDirectory()?s.push(...await Tf(t,o)):i.isFile()&&s.push({rel:o.replace(/\\/g,"/"),abs:a})}return s}async function Z0(t){let e=[];for(let n of t){if((await xs.promises.stat(n.abs)).size>5*1024*1024)continue;let s=await xs.promises.readFile(n.abs);if(s.includes(0))continue;let i=s.toString("utf8");for(let[o,a]of Q0)a.test(i)&&e.push(`${n.rel}: ${o}`)}return e}async function eL(t){let e=kn.join(t,"package.json");if(await(0,Ei.pathExists)(e))try{let n=JSON.parse(await xs.promises.readFile(e,"utf-8"));if(n.version&&/^\d+\.\d+\.\d+/.test(n.version))return n.version}catch{return}}async function Ry(t){let e=[];t?.trim()&&e.push({root:kn.join(kn.resolve(t),Y0.AGENTIDE_DIR_NAME,"engines"),label:"workspace"}),e.push({root:(0,X0.getDefaultCustomEnginesInstallRoot)(),label:"home"});let n=new Map;for(let{root:r,label:s}of e){if(!await(0,Ei.pathExists)(r))continue;let i=await xs.promises.readdir(r,{withFileTypes:!0});for(let o of i){if(!o.isDirectory()||Py(o.name))continue;let a=kn.join(r,o.name),c=kn.join(a,el);if(await(0,Ei.pathExists)(c))try{let{manifest:l}=await Ny(a),f=l.id;if(n.has(f))continue;n.set(f,{id:f,displayName:typeof l.displayName=="string"?l.displayName:f,sourceDir:a,sourceLabel:s})}catch{}}}return[...n.values()].sort((r,s)=>r.id.localeCompare(s.id))}async function tL(t,e){return(await Ry(e)).find(r=>r.id===t)?.sourceDir}async function nL(t,e){let n=[],r=[];if(!await(0,Ei.pathExists)(t))return{valid:!1,errors:[`Engine directory not found: ${t}`],warnings:r};let s,i;try{({manifest:s,entryPath:i}=await Ny(t))}catch(u){return{valid:!1,errors:[u instanceof Error?u.message:String(u)],warnings:r}}let o=s.id;e&&e!==o&&n.push(`Engine folder id "${e}" does not match manifest id "${o}"`);let a=kn.join(t,"package.json");await(0,Ei.pathExists)(a)&&!await(0,Ei.pathExists)(kn.join(t,"package-lock.json"))&&n.push("package.json present but package-lock.json is missing");let c=await Tf(t);c.some(u=>u.rel===el)||n.push(`Missing ${el} in publishable files`);let l=await Z0(c);l.length>0&&n.push(`Possible secrets found:
609
+ `)}}});var Cy=S(As=>{"use strict";var F0=As&&As.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,s)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),V0=As&&As.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),Ry=As&&As.__importStar||(function(){var t=function(e){return t=Object.getOwnPropertyNames||function(n){var r=[];for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(r[r.length]=s);return r},t(e)};return function(e){if(e&&e.__esModule)return e;var n={};if(e!=null)for(var r=t(e),s=0;s<r.length;s++)r[s]!=="default"&&F0(n,e,r[s]);return V0(n,e),n}})();Object.defineProperty(As,"__esModule",{value:!0});As.idpCommand=K0;var el=Ry(require("fs")),Jo=Ry(require("path")),W0=Ny(),Xi=Wn();async function K0(t,e){if(t!=="init"){console.error(`Unknown idp action "${t}". Supported: init`),process.exit(1);return}if(!e.hostname?.trim()){console.error("idp init requires --hostname <public-hostname> (e.g. auth.corp.example)"),process.exit(1);return}let n=Jo.resolve(e.out||"./enterprise-deploy/idp");el.mkdirSync(n,{recursive:!0});let r={hostname:e.hostname.trim(),cookieDomain:e.cookieDomain},s=(0,W0.renderIdpArtifacts)(r),i=[],o=[];for(let[a,c]of Object.entries(s)){let l=Jo.join(n,a);if(el.existsSync(l)&&!e.force){o.push(a);continue}el.mkdirSync(Jo.dirname(l),{recursive:!0}),el.writeFileSync(l,c),i.push(a)}console.log(`${Xi.COLORS.green}\u2713${Xi.COLORS.reset} idp \u2192 ${Jo.relative(process.cwd(),n)||"."}`);for(let a of i)console.log(` ${Xi.COLORS.dim}+ ${a}${Xi.COLORS.reset}`);for(let a of o)console.log(` ${Xi.COLORS.yellow}\u2022 ${a} (exists; --force to overwrite)${Xi.COLORS.reset}`);console.log(`Next: cd ${Jo.relative(process.cwd(),n)||"."}, cp .env.example ~/.agent-hippo/.env, cp .env.auth.example ~/.agent-hippo/.env.auth (fill in), then ./run.sh`)}});var vf=S($n=>{"use strict";var q0=$n&&$n.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,s)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),Y0=$n&&$n.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),X0=$n&&$n.__importStar||(function(){var t=function(e){return t=Object.getOwnPropertyNames||function(n){var r=[];for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(r[r.length]=s);return r},t(e)};return function(e){if(e&&e.__esModule)return e;var n={};if(e!=null)for(var r=t(e),s=0;s<r.length;s++)r[s]!=="default"&&q0(n,e,r[s]);return Y0(n,e),n}})();Object.defineProperty($n,"__esModule",{value:!0});$n.discoverPublishableEngines=Dy;$n.resolveEngineSourceDir=iL;$n.validateEngineForPublish=oL;$n.collectEngineFiles=aL;$n.isValidPublishVersion=cL;var J0=require("child_process"),xs=require("fs"),kn=X0(require("path")),z0=require("util"),Q0=Ke(),Ei=en(),Z0=Na(),eL=(0,z0.promisify)(J0.execFile),tl="engine.manifest.json",tL=new Set([".git",".hg",".svn",".DS_Store","node_modules","dist","coverage",".turbo",".cache",".pnpm-store","Thumbs.db"]),nL=[["private key",/-----BEGIN (?:RSA |EC |OPENSSH |DSA )?PRIVATE KEY-----/],["OpenAI-style key",/\bsk-(?!dummy\b|ant-)[A-Za-z0-9_-]{20,}\b/],["Anthropic key",/\bsk-ant-[A-Za-z0-9_-]{20,}\b/],["Google API key",/\bAIza[0-9A-Za-z_-]{30,}\b/],["GitHub token",/\bgh[pousr]_[A-Za-z0-9_]{20,}\b/],["Atlassian API token",/\bATATT[A-Za-z0-9_=+/\-]{20,}\b/],["AWS access key",/\bAKIA[0-9A-Z]{16}\b/],["JWT",/\beyJ[A-Za-z0-9_-]{20,}\.[A-Za-z0-9_-]{20,}\.[A-Za-z0-9_-]{10,}\b/]];function ky(t){return!!(tL.has(t)||/^\.env(?:\.|$)/.test(t)||/\.log$/i.test(t))}function Tf(t){let e=t.replace(/\\/g,"/").trim().replace(/^\.\//,"");if(!e||e==="."||e==="..")throw new Error("must be a non-empty relative path");if(e.includes("\0")||kn.posix.isAbsolute(e)||/^[A-Za-z]:[\\/]/.test(e))throw new Error(`must be a safe relative path: ${t}`);for(let n of e.split("/"))if(!n||n==="."||n==="..")throw new Error(`must not contain empty, "." or ".." segments: ${t}`);return e}async function $y(t){let e=kn.join(t,tl),n=await xs.promises.readFile(e,"utf-8"),r=JSON.parse(n);if(!r||typeof r!="object"||Array.isArray(r))throw new Error(`${e} must contain a JSON object`);if(r.version!==2)throw new Error(`${e} must use custom engine manifest version 2`);if(typeof r.id!="string"||!/^[a-z0-9][a-z0-9._-]*$/.test(r.id))throw new Error(`${e} has invalid id: ${String(r.id)}`);if(typeof r.entry!="string")throw new Error(`${e} must define string entry`);let s=Tf(r.entry),i=kn.join(t,s);if(!await(0,Ei.pathExists)(i))throw new Error(`${e} entry does not exist: ${s}`);if(r.workspaceSync&&typeof r.workspaceSync=="object"){let o=r.workspaceSync;o.enabled&&(typeof o.dir=="string"&&Tf(o.dir),typeof o.rulesFile=="string"&&Tf(o.rulesFile))}return{manifest:r,manifestPath:e,entryPath:i}}async function bf(t,e=""){let n=kn.join(t,e),r=await xs.promises.readdir(n,{withFileTypes:!0}),s=[];for(let i of r){if(ky(i.name))continue;let o=e?kn.join(e,i.name):i.name,a=kn.join(t,o);i.isDirectory()?s.push(...await bf(t,o)):i.isFile()&&s.push({rel:o.replace(/\\/g,"/"),abs:a})}return s}async function rL(t){let e=[];for(let n of t){if((await xs.promises.stat(n.abs)).size>5*1024*1024)continue;let s=await xs.promises.readFile(n.abs);if(s.includes(0))continue;let i=s.toString("utf8");for(let[o,a]of nL)a.test(i)&&e.push(`${n.rel}: ${o}`)}return e}async function sL(t){let e=kn.join(t,"package.json");if(await(0,Ei.pathExists)(e))try{let n=JSON.parse(await xs.promises.readFile(e,"utf-8"));if(n.version&&/^\d+\.\d+\.\d+/.test(n.version))return n.version}catch{return}}async function Dy(t){let e=[];t?.trim()&&e.push({root:kn.join(kn.resolve(t),Q0.AGENTIDE_DIR_NAME,"engines"),label:"workspace"}),e.push({root:(0,Z0.getDefaultCustomEnginesInstallRoot)(),label:"home"});let n=new Map;for(let{root:r,label:s}of e){if(!await(0,Ei.pathExists)(r))continue;let i=await xs.promises.readdir(r,{withFileTypes:!0});for(let o of i){if(!o.isDirectory()||ky(o.name))continue;let a=kn.join(r,o.name),c=kn.join(a,tl);if(await(0,Ei.pathExists)(c))try{let{manifest:l}=await $y(a),f=l.id;if(n.has(f))continue;n.set(f,{id:f,displayName:typeof l.displayName=="string"?l.displayName:f,sourceDir:a,sourceLabel:s})}catch{}}}return[...n.values()].sort((r,s)=>r.id.localeCompare(s.id))}async function iL(t,e){return(await Dy(e)).find(r=>r.id===t)?.sourceDir}async function oL(t,e){let n=[],r=[];if(!await(0,Ei.pathExists)(t))return{valid:!1,errors:[`Engine directory not found: ${t}`],warnings:r};let s,i;try{({manifest:s,entryPath:i}=await $y(t))}catch(u){return{valid:!1,errors:[u instanceof Error?u.message:String(u)],warnings:r}}let o=s.id;e&&e!==o&&n.push(`Engine folder id "${e}" does not match manifest id "${o}"`);let a=kn.join(t,"package.json");await(0,Ei.pathExists)(a)&&!await(0,Ei.pathExists)(kn.join(t,"package-lock.json"))&&n.push("package.json present but package-lock.json is missing");let c=await bf(t);c.some(u=>u.rel===tl)||n.push(`Missing ${tl} in publishable files`);let l=await rL(c);l.length>0&&n.push(`Possible secrets found:
609
610
  ${l.map(u=>` - ${u}`).join(`
610
- `)}`);try{await J0(process.execPath,["--check",i],{windowsHide:!0})}catch(u){let d=u instanceof Error?u.message:String(u);n.push(`engine entry failed node --check: ${d}`)}s.description||r.push("Consider adding description to engine.manifest.json");let f=await eL(t);return f||r.push("No package.json version found; you will be prompted for a publish version"),{valid:n.length===0,errors:n,warnings:r,metadata:n.length===0?{id:o,displayName:typeof s.displayName=="string"?s.displayName:o,description:typeof s.description=="string"?s.description:void 0,suggestedVersion:f}:void 0}}async function rL(t){let e=await Tf(t),n=[];for(let r of e){if((await xs.promises.stat(r.abs)).size>5*1024*1024)throw new Error(`File too large to publish (>5MB): ${r.rel}`);let i=await xs.promises.readFile(r.abs);if(i.includes(0))throw new Error(`Binary file cannot be published as text: ${r.rel}`);n.push({path:r.rel,content:i.toString("utf8")})}return n}function sL(t){return/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/.test(t.trim())}});var My=S(Oe=>{"use strict";Object.defineProperty(Oe,"__esModule",{value:!0});Oe.REQUEST_VIEW_EXPORT_SNAPSHOT_MESSAGE=Oe.VIEW_EXPORT_SNAPSHOT_MESSAGE=Oe.WORKFLOWS_SIDECAR_SCRIPTS=Oe.WORKFLOWS_RUN_SCRIPT=Oe.WORKFLOWS_VIEW_ID=Oe.FLEET_WIDGET_SCRIPT=void 0;Oe.createDefaultWorkflowsView=Cy;Oe.viewRunsFleetWidget=ky;Oe.resolveRefreshOnNavigate=If;Oe.resolveGalleryLayout=$y;Oe.resolvePreserveFleetIframe=Dy;Oe.shouldPreserveFleetIframe=oL;Oe.buildViewExportSnapshotMessages=cL;Oe.shouldRunScriptsOnNavigation=lL;Oe.normalizeDashboardViewId=Jo;Oe.formatDisplayNameForAllocatedViewId=uL;Oe.createDefaultDashboardViewsConfig=Ly;Oe.resolveMergedActiveViewId=Of;Oe.mergeDashboardViewsConfigs=dL;Oe.FLEET_WIDGET_SCRIPT="agent-fleet-widget.js";Oe.WORKFLOWS_VIEW_ID="workflows";Oe.WORKFLOWS_RUN_SCRIPT="workflows-widget.cjs";Oe.WORKFLOWS_SIDECAR_SCRIPTS=["workflows-collector.cjs","workflows-daemon.mjs","fleet-workflow.sh"];function Cy(){return{id:Oe.WORKFLOWS_VIEW_ID,name:"Workflows",scope:"global",scripts:[Oe.WORKFLOWS_RUN_SCRIPT],bundledScripts:Oe.WORKFLOWS_SIDECAR_SCRIPTS,system:!0,refreshOnNavigate:"always",layout:"fleet-dashboard",preserveFleetIframe:!0}}Oe.VIEW_EXPORT_SNAPSHOT_MESSAGE="viewExportSnapshot";Oe.REQUEST_VIEW_EXPORT_SNAPSHOT_MESSAGE="requestViewExportSnapshot";function iL(t){return t.trim().replace(/^.*[/\\]/,"").toLowerCase()}function ky(t){return t.scripts.some(e=>iL(e)===Oe.FLEET_WIDGET_SCRIPT)}function If(t){return t.refreshOnNavigate==="always"||t.refreshOnNavigate==="when-empty"?t.refreshOnNavigate:ky(t)?"always":"when-empty"}function $y(t){return t.layout==="fleet-dashboard"||t.layout==="gallery"?t.layout:If(t)==="always"?"fleet-dashboard":"gallery"}function Dy(t){return t.preserveFleetIframe===!1?!1:t.preserveFleetIframe===!0?!0:$y(t)==="fleet-dashboard"}function oL(t){return Dy(t)}var aL=192*1024,vf=100;function cL(t){let e=Array.isArray(t.sessions)?t.sessions:[],n={ok:!0,sessionCount:e.length,cliActive:!!t.diagnostics?.cliActive,daemonHint:!1};if(!Array.isArray(t.sessions))return[{payload:t,meta:n}];let r=Buffer.byteLength(JSON.stringify(e),"utf8");if(r<=aL)return[{payload:t,meta:n}];let s={...t,sessions:[]},i=Math.max(1,Math.ceil(e.length/vf)),o=`${Date.now()}-${e.length}-${r}`,a=[];for(let c=0;c<i;c+=1)a.push({payload:{...s,sessions:e.slice(c*vf,(c+1)*vf)},meta:{...n,chunkedSessions:!0,chunkIndex:c,chunkCount:i,snapshotId:o}});return a}function lL(t,e){return If(t)==="always"?!0:!e.some(n=>n==="chart")}function Jo(t,e="global"){return(t??e).trim().toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")||e}function uL(t,e,n=Jo){let r=n(t,"view");if(e===r)return t;let s=`${r}-`;if(e.startsWith(s)){let i=e.slice(s.length);if(/^\d+$/.test(i))return`${t} ${i}`}return t}function Ly(t="global"){return{version:1,activeViewId:t,views:[{id:"global",name:"Global",scope:"global",scripts:[],system:!0},{id:"workspace",name:"Workspace",scope:"workspace",scripts:[],system:!0},{id:"fleet",name:"Fleet",scope:"global",scripts:["agent-fleet-widget.js"],system:!0},Cy()]}}function Of(t,e,n,r){let s=r?.preferWorkspaceScopeFallback===!0,i=e?Jo(e,""):"";if(i&&t.some(a=>a.id===i))return i;if(s&&t.some(a=>a.id==="workspace"))return"workspace";if(t.some(a=>a.id===n.activeViewId))return n.activeViewId;if(t.some(a=>a.id==="global"))return"global";let o=t.find(a=>a.system!==!0&&a.id!=="fleet"&&a.id!=="workspace"&&a.id!=="global");return o?o.id:n.activeViewId}function dL(t,e,n=Ly()){let r=t??n,s=new Map;for(let a of r.views)s.set(a.id,a);if(e)for(let a of e.views)s.set(a.id,a);let i=[...s.values()];if(e){let a=Jo(e.activeViewId,n.activeViewId);return{activeViewId:Of(i,a,n,{preferWorkspaceScopeFallback:!0}),views:i}}let o=Jo(r.activeViewId,n.activeViewId);return{activeViewId:Of(i,o,n,{preferWorkspaceScopeFallback:!1}),views:i}}});var Pf=S(zo=>{"use strict";Object.defineProperty(zo,"__esModule",{value:!0});zo.normalizeSpotlightViewId=pL;zo.parseSpotlightYamlRecord=gL;zo.dumpSpotlightYaml=hL;var fL=My();function pL(t,e="view"){return(0,fL.normalizeDashboardViewId)(t,e)}function gL(t){let n=require("js-yaml").load(t);return n&&typeof n=="object"&&!Array.isArray(n)?n:void 0}function hL(t){return require("js-yaml").dump(t,{lineWidth:120,noRefs:!0})}});var kf=S(rr=>{"use strict";var mL=rr&&rr.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,s)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),EL=rr&&rr.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),_L=rr&&rr.__importStar||(function(){var t=function(e){return t=Object.getOwnPropertyNames||function(n){var r=[];for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(r[r.length]=s);return r},t(e)};return function(e){if(e&&e.__esModule)return e;var n={};if(e!=null)for(var r=t(e),s=0;s<r.length;s++)r[s]!=="default"&&mL(n,e,r[s]);return EL(n,e),n}})();Object.defineProperty(rr,"__esModule",{value:!0});rr.resolveViewPublishVersionFromParsed=Gy;rr.discoverPublishableViews=$L;rr.validateViewForPublish=DL;rr.collectViewFiles=LL;var Ss=require("fs"),Ot=_L(require("path")),yL=Ke(),Rf=bf(),Qr=en(),wL=Eo(),Yi=Pf();function Gy(t){if(t){if(typeof t.version=="string"&&t.version.trim()){let e=t.version.trim().replace(/^v/,"");if((0,Rf.isValidPublishVersion)(e))return e}if(typeof t.semver=="string"&&t.semver.trim()){let e=t.semver.trim().replace(/^v/,"");if((0,Rf.isValidPublishVersion)(e))return e}}}var Uy=new Set(["global","workspace","fleet","workflows","default"]),Hy="view.yaml",AL="panel-entry.yaml",SL=new Set(["charts","reports","exports","panel-state","assets","images"]),jy=["assets","images","charts","reports","exports"],Cf="manifest.json",TL=new Set([".png",".jpg",".jpeg",".gif",".webp",".pdf",".ico",".woff",".woff2"]),bL=new Set([...SL,"node_modules",".git",".hg",".svn",".DS_Store","__pycache__",".turbo",".cache"]),xy=new Set([".DS_Store","Thumbs.db"]),vL=[["private key",/-----BEGIN (?:RSA |EC |OPENSSH |DSA )?PRIVATE KEY-----/],["OpenAI-style key",/\bsk-(?!dummy\b|ant-)[A-Za-z0-9_-]{20,}\b/],["Anthropic key",/\bsk-ant-[A-Za-z0-9_-]{20,}\b/],["Google API key",/\bAIza[0-9A-Za-z_-]{30,}\b/],["GitHub token",/\bgh[pousr]_[A-Za-z0-9_]{20,}\b/],["Atlassian API token",/\bATATT[A-Za-z0-9_=+/\-]{20,}\b/],["AWS access key",/\bAKIA[0-9A-Z]{16}\b/],["JWT",/\beyJ[A-Za-z0-9_-]{20,}\.[A-Za-z0-9_-]{20,}\.[A-Za-z0-9_-]{10,}\b/]],OL=1024*1024,IL=10*1024*1024;function By(t){return Array.isArray(t)?t.filter(e=>typeof e=="string"&&e.trim().length>0).map(e=>Ot.basename(e.trim())):[]}function tl(t){let e=new Set,n=[];for(let r of t){let s=Ot.basename(r.trim());!s||e.has(s)||(e.add(s),n.push(s))}return n}function PL(t){let e=[];return t?.trim()&&e.push({root:Ot.join(t.trim(),yL.AGENTIDE_DIR_NAME,"analytics"),label:"workspace"}),e.push({root:Ot.join((0,wL.getAgentideHome)(),"analytics"),label:"home"}),e}function NL(t){return Ot.join(t,"panel","views.yaml")}async function RL(t){try{let e=await Ss.promises.readFile(t,"utf-8"),n=(0,Yi.parseSpotlightYamlRecord)(e),r=Array.isArray(n?.views)?n.views:[],s=[];for(let i of r){if(!i||typeof i!="object")continue;let o=i,a=(0,Yi.normalizeSpotlightViewId)(typeof o.id=="string"?o.id:void 0);if(!a)continue;let c=o.scope==="workspace"?"workspace":"global",l=typeof o.name=="string"&&o.name.trim()?o.name.trim():a,f=tl(By(o.scripts)),u=o.system===!0;s.push({id:a,name:l,scope:c,scripts:f,system:u})}return s}catch{return[]}}async function Fy(t){let e=Ot.join(t,Hy);try{let n=await Ss.promises.readFile(e,"utf-8"),r=(0,Yi.parseSpotlightYamlRecord)(n);if(!r)return;let s=(0,Yi.normalizeSpotlightViewId)(typeof r.id=="string"?r.id:void 0);if(!s)return;let i=r.scope==="workspace"?"workspace":"global",o=typeof r.name=="string"&&r.name.trim()?r.name.trim():s;return{id:s,name:o,description:typeof r.description=="string"?r.description.trim():void 0,author:typeof r.author=="string"?r.author.trim():void 0,publishVersion:Gy(r),scope:i,tags:Array.isArray(r.tags)?r.tags.filter(a=>typeof a=="string"):void 0,scripts:tl(By(r.scripts))}}catch{return}}async function CL(t){let e=[];for(let n of t)for(let[r,s]of vL)s.test(n.content)&&e.push(`${n.rel}: possible ${r}`);return e}function Vy(t,e){return!!(xy.has(t)||t.startsWith(".")&&t!=="."||e&&bL.has(t)||/^\.env(?:\.|$)/.test(t)||/\.log$/i.test(t))}function Wy(t,e){return!!(xy.has(t)||t.startsWith(".")||e&&(t==="node_modules"||t==="__pycache__")||/^\.env(?:\.|$)/.test(t)||/\.log$/i.test(t))}function Ky(t){let e=Ot.extname(t).toLowerCase();return TL.has(e)}async function Nf(t,e){let n=await Ss.promises.readFile(t);return n.includes(0)||Ky(e)?{path:e,content:n.toString("base64"),encoding:"base64"}:{path:e,content:n.toString("utf-8"),encoding:"utf-8"}}async function kL(t){let e=0;for(let n of jy){let r=Ot.join(t,n);if(!await(0,Qr.pathExists)(r))continue;async function s(i){let o=await Ss.promises.readdir(i,{withFileTypes:!0});for(let a of o){if(Wy(a.name,a.isDirectory()))continue;let c=Ot.join(i,a.name);if(a.isDirectory()){await s(c);continue}e++}}await s(r)}return await(0,Qr.pathExists)(Ot.join(t,Cf))&&e++,e}async function qy(t,e){for(let r of jy){let s=Ot.join(t,r);await(0,Qr.pathExists)(s)&&await nl(s,r,Wy,e)}let n=Ot.join(t,Cf);if(await(0,Qr.pathExists)(n)){let r=await Ss.promises.stat(n);await e(n,Cf,r.size)}}async function nl(t,e,n,r){let s=await Ss.promises.readdir(t,{withFileTypes:!0});for(let i of s){if(n(i.name,i.isDirectory()))continue;let o=Ot.join(t,i.name),a=e?`${e}/${i.name}`:i.name;if(i.isDirectory()){await nl(o,a,n,r);continue}let c=await Ss.promises.stat(o);await r(o,a,c.size)}}async function $L(t){let e=new Map;for(let{root:n,label:r}of PL(t)){let s=NL(n);if(!await(0,Qr.pathExists)(s))continue;let i=await RL(s);for(let o of i){if(o.system||Uy.has(o.id)||e.has(o.id))continue;let a=Ot.join(n,"views",o.id),c=await Fy(a),l=tl(c?.scripts.length?c.scripts:o.scripts);e.set(o.id,{id:o.id,name:c?.name??o.name,scope:c?.scope??o.scope,scripts:l,viewRoot:a,viewsConfigPath:s,analyticsRoot:n,sourceLabel:r})}}return[...e.values()].sort((n,r)=>n.id.localeCompare(r.id))}async function DL(t,e){let n=e?.mode??"scripts-only",r=e?.expectedId,s=[],i=[];if(r&&r!==t.id&&s.push(`View id "${r}" does not match selected view "${t.id}"`),Uy.has(t.id)&&s.push(`View id "${t.id}" is reserved for built-in Spotlight views`),!await(0,Qr.pathExists)(t.viewRoot))return s.push(`View directory not found: ${t.viewRoot}`),{valid:!1,errors:s,warnings:i};let o=await Fy(t.viewRoot),a=tl(o?.scripts.length?o.scripts:t.scripts),c=n==="full"?await kL(t.viewRoot):0;o||i.push("Missing view.yaml; publish will generate manifest from panel config"),o?.description||i.push("Consider adding description to view.yaml for store discoverability"),(!o?.tags||o.tags.length===0)&&i.push("Consider adding tags to view.yaml for store discoverability"),n==="scripts-only"?a.length===0&&s.push("View has no scripts registered"):a.length===0&&c===0?s.push("Full bundle requires at least one script or content under assets/, images/, charts/, reports/, exports/, or manifest.json"):a.length===0&&i.push("Publishing generated artifacts only (no widget scripts)");let l=Ot.join(t.viewRoot,"scripts");for(let m of a){let h=Ot.join(l,m);await(0,Qr.pathExists)(h)||s.push(`Missing script file: scripts/${m}`)}let f=[],u=0;async function d(m,h,E){if(E===void 0&&(E=(await Ss.promises.stat(m)).size),E>OL){s.push(`File too large (>1MB): ${h}`);return}if(u+=E,u>IL){s.push("Total bundle size exceeds 10MB");return}if(Ky(h))return;let _=await Ss.promises.readFile(m);f.push({rel:h,content:_.toString("utf-8")})}await(0,Qr.pathExists)(l)&&await nl(l,"scripts",Vy,d),n==="full"&&await qy(t.viewRoot,d);let p=await CL(f);p.length>0&&s.push(`Possible secrets found:
611
+ `)}`);try{await eL(process.execPath,["--check",i],{windowsHide:!0})}catch(u){let d=u instanceof Error?u.message:String(u);n.push(`engine entry failed node --check: ${d}`)}s.description||r.push("Consider adding description to engine.manifest.json");let f=await sL(t);return f||r.push("No package.json version found; you will be prompted for a publish version"),{valid:n.length===0,errors:n,warnings:r,metadata:n.length===0?{id:o,displayName:typeof s.displayName=="string"?s.displayName:o,description:typeof s.description=="string"?s.description:void 0,suggestedVersion:f}:void 0}}async function aL(t){let e=await bf(t),n=[];for(let r of e){if((await xs.promises.stat(r.abs)).size>5*1024*1024)throw new Error(`File too large to publish (>5MB): ${r.rel}`);let i=await xs.promises.readFile(r.abs);if(i.includes(0))throw new Error(`Binary file cannot be published as text: ${r.rel}`);n.push({path:r.rel,content:i.toString("utf8")})}return n}function cL(t){return/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/.test(t.trim())}});var jy=S(Oe=>{"use strict";Object.defineProperty(Oe,"__esModule",{value:!0});Oe.REQUEST_VIEW_EXPORT_SNAPSHOT_MESSAGE=Oe.VIEW_EXPORT_SNAPSHOT_MESSAGE=Oe.WORKFLOWS_SIDECAR_SCRIPTS=Oe.WORKFLOWS_RUN_SCRIPT=Oe.WORKFLOWS_VIEW_ID=Oe.FLEET_WIDGET_SCRIPT=void 0;Oe.createDefaultWorkflowsView=Ly;Oe.viewRunsFleetWidget=My;Oe.resolveRefreshOnNavigate=Pf;Oe.resolveGalleryLayout=Gy;Oe.resolvePreserveFleetIframe=Uy;Oe.shouldPreserveFleetIframe=uL;Oe.buildViewExportSnapshotMessages=fL;Oe.shouldRunScriptsOnNavigation=pL;Oe.normalizeDashboardViewId=zo;Oe.formatDisplayNameForAllocatedViewId=gL;Oe.createDefaultDashboardViewsConfig=Hy;Oe.resolveMergedActiveViewId=If;Oe.mergeDashboardViewsConfigs=hL;Oe.FLEET_WIDGET_SCRIPT="agent-fleet-widget.js";Oe.WORKFLOWS_VIEW_ID="workflows";Oe.WORKFLOWS_RUN_SCRIPT="workflows-widget.cjs";Oe.WORKFLOWS_SIDECAR_SCRIPTS=["workflows-collector.cjs","workflows-daemon.mjs","fleet-workflow.sh"];function Ly(){return{id:Oe.WORKFLOWS_VIEW_ID,name:"Workflows",scope:"global",scripts:[Oe.WORKFLOWS_RUN_SCRIPT],bundledScripts:Oe.WORKFLOWS_SIDECAR_SCRIPTS,system:!0,refreshOnNavigate:"always",layout:"fleet-dashboard",preserveFleetIframe:!0}}Oe.VIEW_EXPORT_SNAPSHOT_MESSAGE="viewExportSnapshot";Oe.REQUEST_VIEW_EXPORT_SNAPSHOT_MESSAGE="requestViewExportSnapshot";function lL(t){return t.trim().replace(/^.*[/\\]/,"").toLowerCase()}function My(t){return t.scripts.some(e=>lL(e)===Oe.FLEET_WIDGET_SCRIPT)}function Pf(t){return t.refreshOnNavigate==="always"||t.refreshOnNavigate==="when-empty"?t.refreshOnNavigate:My(t)?"always":"when-empty"}function Gy(t){return t.layout==="fleet-dashboard"||t.layout==="gallery"?t.layout:Pf(t)==="always"?"fleet-dashboard":"gallery"}function Uy(t){return t.preserveFleetIframe===!1?!1:t.preserveFleetIframe===!0?!0:Gy(t)==="fleet-dashboard"}function uL(t){return Uy(t)}var dL=192*1024,Of=100;function fL(t){let e=Array.isArray(t.sessions)?t.sessions:[],n={ok:!0,sessionCount:e.length,cliActive:!!t.diagnostics?.cliActive,daemonHint:!1};if(!Array.isArray(t.sessions))return[{payload:t,meta:n}];let r=Buffer.byteLength(JSON.stringify(e),"utf8");if(r<=dL)return[{payload:t,meta:n}];let s={...t,sessions:[]},i=Math.max(1,Math.ceil(e.length/Of)),o=`${Date.now()}-${e.length}-${r}`,a=[];for(let c=0;c<i;c+=1)a.push({payload:{...s,sessions:e.slice(c*Of,(c+1)*Of)},meta:{...n,chunkedSessions:!0,chunkIndex:c,chunkCount:i,snapshotId:o}});return a}function pL(t,e){return Pf(t)==="always"?!0:!e.some(n=>n==="chart")}function zo(t,e="global"){return(t??e).trim().toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")||e}function gL(t,e,n=zo){let r=n(t,"view");if(e===r)return t;let s=`${r}-`;if(e.startsWith(s)){let i=e.slice(s.length);if(/^\d+$/.test(i))return`${t} ${i}`}return t}function Hy(t="global"){return{version:1,activeViewId:t,views:[{id:"global",name:"Global",scope:"global",scripts:[],system:!0},{id:"workspace",name:"Workspace",scope:"workspace",scripts:[],system:!0},{id:"fleet",name:"Fleet",scope:"global",scripts:["agent-fleet-widget.js"],system:!0},Ly()]}}function If(t,e,n,r){let s=r?.preferWorkspaceScopeFallback===!0,i=e?zo(e,""):"";if(i&&t.some(a=>a.id===i))return i;if(s&&t.some(a=>a.id==="workspace"))return"workspace";if(t.some(a=>a.id===n.activeViewId))return n.activeViewId;if(t.some(a=>a.id==="global"))return"global";let o=t.find(a=>a.system!==!0&&a.id!=="fleet"&&a.id!=="workspace"&&a.id!=="global");return o?o.id:n.activeViewId}function hL(t,e,n=Hy()){let r=t??n,s=new Map;for(let a of r.views)s.set(a.id,a);if(e)for(let a of e.views)s.set(a.id,a);let i=[...s.values()];if(e){let a=zo(e.activeViewId,n.activeViewId);return{activeViewId:If(i,a,n,{preferWorkspaceScopeFallback:!0}),views:i}}let o=zo(r.activeViewId,n.activeViewId);return{activeViewId:If(i,o,n,{preferWorkspaceScopeFallback:!1}),views:i}}});var Nf=S(Qo=>{"use strict";Object.defineProperty(Qo,"__esModule",{value:!0});Qo.normalizeSpotlightViewId=EL;Qo.parseSpotlightYamlRecord=_L;Qo.dumpSpotlightYaml=yL;var mL=jy();function EL(t,e="view"){return(0,mL.normalizeDashboardViewId)(t,e)}function _L(t){let n=require("js-yaml").load(t);return n&&typeof n=="object"&&!Array.isArray(n)?n:void 0}function yL(t){return require("js-yaml").dump(t,{lineWidth:120,noRefs:!0})}});var $f=S(rr=>{"use strict";var wL=rr&&rr.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,s)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),AL=rr&&rr.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),SL=rr&&rr.__importStar||(function(){var t=function(e){return t=Object.getOwnPropertyNames||function(n){var r=[];for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(r[r.length]=s);return r},t(e)};return function(e){if(e&&e.__esModule)return e;var n={};if(e!=null)for(var r=t(e),s=0;s<r.length;s++)r[s]!=="default"&&wL(n,e,r[s]);return AL(n,e),n}})();Object.defineProperty(rr,"__esModule",{value:!0});rr.resolveViewPublishVersionFromParsed=xy;rr.discoverPublishableViews=GL;rr.validateViewForPublish=UL;rr.collectViewFiles=HL;var Ss=require("fs"),Ot=SL(require("path")),TL=Ke(),Cf=vf(),zr=en(),bL=yo(),Ji=Nf();function xy(t){if(t){if(typeof t.version=="string"&&t.version.trim()){let e=t.version.trim().replace(/^v/,"");if((0,Cf.isValidPublishVersion)(e))return e}if(typeof t.semver=="string"&&t.semver.trim()){let e=t.semver.trim().replace(/^v/,"");if((0,Cf.isValidPublishVersion)(e))return e}}}var By=new Set(["global","workspace","fleet","workflows","default"]),Fy="view.yaml",vL="panel-entry.yaml",OL=new Set(["charts","reports","exports","panel-state","assets","images"]),Vy=["assets","images","charts","reports","exports"],kf="manifest.json",IL=new Set([".png",".jpg",".jpeg",".gif",".webp",".pdf",".ico",".woff",".woff2"]),PL=new Set([...OL,"node_modules",".git",".hg",".svn",".DS_Store","__pycache__",".turbo",".cache"]),Wy=new Set([".DS_Store","Thumbs.db"]),NL=[["private key",/-----BEGIN (?:RSA |EC |OPENSSH |DSA )?PRIVATE KEY-----/],["OpenAI-style key",/\bsk-(?!dummy\b|ant-)[A-Za-z0-9_-]{20,}\b/],["Anthropic key",/\bsk-ant-[A-Za-z0-9_-]{20,}\b/],["Google API key",/\bAIza[0-9A-Za-z_-]{30,}\b/],["GitHub token",/\bgh[pousr]_[A-Za-z0-9_]{20,}\b/],["Atlassian API token",/\bATATT[A-Za-z0-9_=+/\-]{20,}\b/],["AWS access key",/\bAKIA[0-9A-Z]{16}\b/],["JWT",/\beyJ[A-Za-z0-9_-]{20,}\.[A-Za-z0-9_-]{20,}\.[A-Za-z0-9_-]{10,}\b/]],RL=1024*1024,CL=10*1024*1024;function Ky(t){return Array.isArray(t)?t.filter(e=>typeof e=="string"&&e.trim().length>0).map(e=>Ot.basename(e.trim())):[]}function nl(t){let e=new Set,n=[];for(let r of t){let s=Ot.basename(r.trim());!s||e.has(s)||(e.add(s),n.push(s))}return n}function kL(t){let e=[];return t?.trim()&&e.push({root:Ot.join(t.trim(),TL.AGENTIDE_DIR_NAME,"analytics"),label:"workspace"}),e.push({root:Ot.join((0,bL.getAgentideHome)(),"analytics"),label:"home"}),e}function $L(t){return Ot.join(t,"panel","views.yaml")}async function DL(t){try{let e=await Ss.promises.readFile(t,"utf-8"),n=(0,Ji.parseSpotlightYamlRecord)(e),r=Array.isArray(n?.views)?n.views:[],s=[];for(let i of r){if(!i||typeof i!="object")continue;let o=i,a=(0,Ji.normalizeSpotlightViewId)(typeof o.id=="string"?o.id:void 0);if(!a)continue;let c=o.scope==="workspace"?"workspace":"global",l=typeof o.name=="string"&&o.name.trim()?o.name.trim():a,f=nl(Ky(o.scripts)),u=o.system===!0;s.push({id:a,name:l,scope:c,scripts:f,system:u})}return s}catch{return[]}}async function qy(t){let e=Ot.join(t,Fy);try{let n=await Ss.promises.readFile(e,"utf-8"),r=(0,Ji.parseSpotlightYamlRecord)(n);if(!r)return;let s=(0,Ji.normalizeSpotlightViewId)(typeof r.id=="string"?r.id:void 0);if(!s)return;let i=r.scope==="workspace"?"workspace":"global",o=typeof r.name=="string"&&r.name.trim()?r.name.trim():s;return{id:s,name:o,description:typeof r.description=="string"?r.description.trim():void 0,author:typeof r.author=="string"?r.author.trim():void 0,publishVersion:xy(r),scope:i,tags:Array.isArray(r.tags)?r.tags.filter(a=>typeof a=="string"):void 0,scripts:nl(Ky(r.scripts))}}catch{return}}async function LL(t){let e=[];for(let n of t)for(let[r,s]of NL)s.test(n.content)&&e.push(`${n.rel}: possible ${r}`);return e}function Yy(t,e){return!!(Wy.has(t)||t.startsWith(".")&&t!=="."||e&&PL.has(t)||/^\.env(?:\.|$)/.test(t)||/\.log$/i.test(t))}function Xy(t,e){return!!(Wy.has(t)||t.startsWith(".")||e&&(t==="node_modules"||t==="__pycache__")||/^\.env(?:\.|$)/.test(t)||/\.log$/i.test(t))}function Jy(t){let e=Ot.extname(t).toLowerCase();return IL.has(e)}async function Rf(t,e){let n=await Ss.promises.readFile(t);return n.includes(0)||Jy(e)?{path:e,content:n.toString("base64"),encoding:"base64"}:{path:e,content:n.toString("utf-8"),encoding:"utf-8"}}async function ML(t){let e=0;for(let n of Vy){let r=Ot.join(t,n);if(!await(0,zr.pathExists)(r))continue;async function s(i){let o=await Ss.promises.readdir(i,{withFileTypes:!0});for(let a of o){if(Xy(a.name,a.isDirectory()))continue;let c=Ot.join(i,a.name);if(a.isDirectory()){await s(c);continue}e++}}await s(r)}return await(0,zr.pathExists)(Ot.join(t,kf))&&e++,e}async function zy(t,e){for(let r of Vy){let s=Ot.join(t,r);await(0,zr.pathExists)(s)&&await rl(s,r,Xy,e)}let n=Ot.join(t,kf);if(await(0,zr.pathExists)(n)){let r=await Ss.promises.stat(n);await e(n,kf,r.size)}}async function rl(t,e,n,r){let s=await Ss.promises.readdir(t,{withFileTypes:!0});for(let i of s){if(n(i.name,i.isDirectory()))continue;let o=Ot.join(t,i.name),a=e?`${e}/${i.name}`:i.name;if(i.isDirectory()){await rl(o,a,n,r);continue}let c=await Ss.promises.stat(o);await r(o,a,c.size)}}async function GL(t){let e=new Map;for(let{root:n,label:r}of kL(t)){let s=$L(n);if(!await(0,zr.pathExists)(s))continue;let i=await DL(s);for(let o of i){if(o.system||By.has(o.id)||e.has(o.id))continue;let a=Ot.join(n,"views",o.id),c=await qy(a),l=nl(c?.scripts.length?c.scripts:o.scripts);e.set(o.id,{id:o.id,name:c?.name??o.name,scope:c?.scope??o.scope,scripts:l,viewRoot:a,viewsConfigPath:s,analyticsRoot:n,sourceLabel:r})}}return[...e.values()].sort((n,r)=>n.id.localeCompare(r.id))}async function UL(t,e){let n=e?.mode??"scripts-only",r=e?.expectedId,s=[],i=[];if(r&&r!==t.id&&s.push(`View id "${r}" does not match selected view "${t.id}"`),By.has(t.id)&&s.push(`View id "${t.id}" is reserved for built-in Spotlight views`),!await(0,zr.pathExists)(t.viewRoot))return s.push(`View directory not found: ${t.viewRoot}`),{valid:!1,errors:s,warnings:i};let o=await qy(t.viewRoot),a=nl(o?.scripts.length?o.scripts:t.scripts),c=n==="full"?await ML(t.viewRoot):0;o||i.push("Missing view.yaml; publish will generate manifest from panel config"),o?.description||i.push("Consider adding description to view.yaml for store discoverability"),(!o?.tags||o.tags.length===0)&&i.push("Consider adding tags to view.yaml for store discoverability"),n==="scripts-only"?a.length===0&&s.push("View has no scripts registered"):a.length===0&&c===0?s.push("Full bundle requires at least one script or content under assets/, images/, charts/, reports/, exports/, or manifest.json"):a.length===0&&i.push("Publishing generated artifacts only (no widget scripts)");let l=Ot.join(t.viewRoot,"scripts");for(let m of a){let h=Ot.join(l,m);await(0,zr.pathExists)(h)||s.push(`Missing script file: scripts/${m}`)}let f=[],u=0;async function d(m,h,E){if(E===void 0&&(E=(await Ss.promises.stat(m)).size),E>RL){s.push(`File too large (>1MB): ${h}`);return}if(u+=E,u>CL){s.push("Total bundle size exceeds 10MB");return}if(Jy(h))return;let _=await Ss.promises.readFile(m);f.push({rel:h,content:_.toString("utf-8")})}await(0,zr.pathExists)(l)&&await rl(l,"scripts",Yy,d),n==="full"&&await zy(t.viewRoot,d);let p=await LL(f);p.length>0&&s.push(`Possible secrets found:
611
612
  ${p.map(m=>` - ${m}`).join(`
612
- `)}`);let g={id:t.id,name:o?.name??t.name,description:o?.description,author:o?.author,publishVersion:o?.publishVersion,scope:o?.scope??t.scope,tags:o?.tags,scripts:a,...n==="full"?{publishBundle:"full"}:{}};return{valid:s.length===0,errors:s,warnings:i,metadata:s.length===0?g:void 0}}async function LL(t,e,n,r="scripts-only"){if(!(0,Rf.isValidPublishVersion)(e.replace(/^v/,"")))throw new Error(`Invalid publish version: ${e}`);let s=[],i=Ot.join(t.viewRoot,"scripts"),a={version:e.replace(/^v/,""),id:t.id,name:n.name,scope:n.scope,scripts:n.scripts,...n.description?{description:n.description}:{},...n.author?{author:n.author}:{},...n.tags?.length?{tags:n.tags}:{},...r==="full"?{publishBundle:"full"}:{}};s.push({path:Hy,content:(0,Yi.dumpSpotlightYaml)(a),encoding:"utf-8"}),s.push({path:AL,content:(0,Yi.dumpSpotlightYaml)({id:t.id,name:n.name,scope:n.scope,scripts:n.scripts}),encoding:"utf-8"});let c=Ot.join(t.viewRoot,"README.md");return await(0,Qr.pathExists)(c)&&s.push(await Nf(c,"README.md")),await(0,Qr.pathExists)(i)&&await nl(i,"scripts",Vy,async(l,f)=>{s.push(await Nf(l,f))}),r==="full"&&await qy(t.viewRoot,async(l,f)=>{s.push(await Nf(l,f))}),s}});var Xy=S(sr=>{"use strict";var ML=sr&&sr.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,s)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),GL=sr&&sr.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),UL=sr&&sr.__importStar||(function(){var t=function(e){return t=Object.getOwnPropertyNames||function(n){var r=[];for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(r[r.length]=s);return r},t(e)};return function(e){if(e&&e.__esModule)return e;var n={};if(e!=null)for(var r=t(e),s=0;s<r.length;s++)r[s]!=="default"&&ML(n,e,r[s]);return GL(n,e),n}})();Object.defineProperty(sr,"__esModule",{value:!0});sr.installSpotlightViewFromFiles=BL;sr.listInstalledSpotlightViews=FL;sr.setActiveSpotlightView=VL;sr.isSpotlightViewInstalled=WL;var mn=require("fs"),mt=UL(require("path")),Lf=Ke(),rl=en(),Mf=Eo(),Df=kf(),Mt=Pf();function $f(t){return Array.isArray(t)?t.filter(e=>typeof e=="string"&&e.trim().length>0).map(e=>mt.basename(e.trim())):[]}function Yy(t){let e=new Set,n=[];for(let r of t){let s=mt.basename(r.trim());!s||e.has(s)||(e.add(s),n.push(s))}return n}function HL(t,e){if(t==="workspace"){if(!e?.trim())throw new Error("Workspace-scoped views require an open workspace folder");return mt.join(e.trim(),Lf.AGENTIDE_DIR_NAME,"analytics")}return mt.join((0,Mf.getAgentideHome)(),"analytics")}function jL(t){let e=new Map;for(let n of t){let r=Buffer.isBuffer(n.content)?n.content:Buffer.from(n.content,"utf-8");e.set(n.path.replace(/\\/g,"/"),r)}return e}async function xL(t,e,n){await mn.promises.mkdir(mt.dirname(t),{recursive:!0});let r;try{let c=await mn.promises.readFile(t,"utf-8");r=(0,Mt.parseSpotlightYamlRecord)(c)??{version:1,activeViewId:"global",views:[]}}catch{r={version:1,activeViewId:"global",views:[]}}let s=Array.isArray(r.views)?[...r.views]:[],i=(0,Mt.normalizeSpotlightViewId)(e.id),o=s.findIndex(c=>{if(!c||typeof c!="object")return!1;let l=c;return(0,Mt.normalizeSpotlightViewId)(typeof l.id=="string"?l.id:void 0)===i}),a={id:i,name:e.name,scope:e.scope,scripts:Yy(e.scripts)};if(o>=0){if(!n)throw new Error(`Spotlight view "${i}" is already registered in ${t}`);s[o]=a}else s.push(a);r.views=s,typeof r.version!="number"&&(r.version=1),typeof r.activeViewId!="string"&&(r.activeViewId="global"),await mn.promises.writeFile(t,(0,Mt.dumpSpotlightYaml)(r),"utf-8")}async function BL(t,e){let n=jL(t),r=n.get("view.yaml"),s=n.get("panel-entry.yaml");if(!r||!s)throw new Error("Store bundle is missing view.yaml or panel-entry.yaml");let i=(0,Mt.parseSpotlightYamlRecord)(r.toString("utf-8")),o=(0,Mt.parseSpotlightYamlRecord)(s.toString("utf-8"));if(!i||!o)throw new Error("Invalid view.yaml or panel-entry.yaml in store bundle");let a=(0,Mt.normalizeSpotlightViewId)(typeof i.id=="string"?i.id:e.slug,e.slug);if(a!==(0,Mt.normalizeSpotlightViewId)(e.slug,e.slug))throw new Error(`Bundle id "${a}" does not match requested slug "${e.slug}"`);let c=i.scope==="workspace"||o.scope==="workspace"?"workspace":"global",l=typeof i.name=="string"&&i.name.trim()?i.name.trim():typeof o.name=="string"&&o.name.trim()?o.name.trim():a,f=Yy($f(i.scripts).length?$f(i.scripts):$f(o.scripts)),u=HL(c,e.workspaceRoot),d=mt.join(u,"views",a),p=mt.join(u,"panel","views.yaml"),g=mt.join(d,"scripts");if(!e.overwrite&&await(0,rl.pathExists)(d))throw new Error(`Spotlight view "${a}" already exists at ${d}`);e.overwrite&&await mn.promises.rm(d,{recursive:!0,force:!0}),await mn.promises.mkdir(g,{recursive:!0});let m=["scripts/","assets/","images/","charts/","reports/","exports/"],h=new Set(["manifest.json","README.md"]),E=new Set(["view.yaml","panel-entry.yaml"]);for(let[T,O]of n.entries()){if(E.has(T)||!h.has(T)&&!m.some(C=>T.startsWith(C)))continue;let A=mt.resolve(d),v=mt.resolve(A,T);if(!v.startsWith(A+mt.sep))throw new Error(`Store bundle entry "${T}" escapes the install directory`);await mn.promises.mkdir(mt.dirname(v),{recursive:!0}),await mn.promises.writeFile(v,O)}let _=new Date().toISOString(),y=(0,Df.resolveViewPublishVersionFromParsed)(i)??e.version??"1.0.0",b={version:y,id:a,name:l,description:typeof i.description=="string"?i.description:"",author:typeof i.author=="string"?i.author:void 0,scope:c,projectId:"",agentId:"",createdAt:_,updatedAt:_,scripts:f,storeVersion:y};if(Array.isArray(i.tags)&&(b.tags=i.tags.filter(T=>typeof T=="string")),await mn.promises.writeFile(mt.join(d,"view.yaml"),(0,Mt.dumpSpotlightYaml)(b),"utf-8"),await xL(p,{id:a,name:l,scope:c,scripts:f},!!e.overwrite),e.activate){let T;try{let O=await mn.promises.readFile(p,"utf-8");T=(0,Mt.parseSpotlightYamlRecord)(O)??{}}catch{T={version:1,views:[]}}T.activeViewId=a,typeof T.version!="number"&&(T.version=1),await mn.promises.writeFile(p,(0,Mt.dumpSpotlightYaml)(T),"utf-8")}return e.logger&&(0,rl.logInfo)(e.logger,`[Spotlight] Installed view "${a}" to ${d}`),{id:a,scope:c,installDir:d,viewsConfigPath:p,version:(0,Df.resolveViewPublishVersionFromParsed)(i)??e.version??"1.0.0"}}async function FL(t){let e=[],n=new Set;async function r(s){let i=mt.join(s,"views");if(!await(0,rl.pathExists)(i))return;let o=await mn.promises.readdir(i,{withFileTypes:!0});for(let a of o){if(!a.isDirectory()||a.name.startsWith("."))continue;let c=a.name.toLowerCase();if(n.has(c))continue;let l=mt.join(i,a.name,"view.yaml");try{let f=await mn.promises.readFile(l,"utf-8"),u=(0,Mt.parseSpotlightYamlRecord)(f);if(!u)continue;let d=(0,Mt.normalizeSpotlightViewId)(typeof u.id=="string"?u.id:a.name,a.name),p=u.scope==="workspace"?"workspace":"global";n.add(c),e.push({slug:d,displayName:typeof u.name=="string"&&u.name.trim()?u.name.trim():d,description:typeof u.description=="string"?u.description.trim():void 0,tags:Array.isArray(u.tags)?u.tags.filter(g=>typeof g=="string"):["spotlight"],latestVersion:typeof u.storeVersion=="string"?u.storeVersion:(0,Df.resolveViewPublishVersionFromParsed)(u)??"local",scope:p})}catch{}}}return await r(mt.join((0,Mf.getAgentideHome)(),"analytics")),t?.trim()&&await r(mt.join(t.trim(),Lf.AGENTIDE_DIR_NAME,"analytics")),e.sort((s,i)=>s.slug.localeCompare(i.slug))}async function VL(t,e){let n=(0,Mt.normalizeSpotlightViewId)(e,e),r;try{let s=await mn.promises.readFile(t,"utf-8");r=(0,Mt.parseSpotlightYamlRecord)(s)??{version:1,views:[]}}catch{r={version:1,views:[]}}r.activeViewId=n,typeof r.version!="number"&&(r.version=1),await mn.promises.writeFile(t,(0,Mt.dumpSpotlightYaml)(r),"utf-8")}async function WL(t,e){let n=(0,Mt.normalizeSpotlightViewId)(t,t);for(let r of[mt.join((0,Mf.getAgentideHome)(),"analytics","views",n,"view.yaml"),e?.trim()?mt.join(e.trim(),Lf.AGENTIDE_DIR_NAME,"analytics","views",n,"view.yaml"):""].filter(Boolean))if(await(0,rl.pathExists)(r))return!0;return!1}});var Wf=S(Nr=>{"use strict";var KL=Nr&&Nr.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,s)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),qL=Nr&&Nr.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),jf=Nr&&Nr.__importStar||(function(){var t=function(e){return t=Object.getOwnPropertyNames||function(n){var r=[];for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(r[r.length]=s);return r},t(e)};return function(e){if(e&&e.__esModule)return e;var n={};if(e!=null)for(var r=t(e),s=0;s<r.length;s++)r[s]!=="default"&&KL(n,e,r[s]);return qL(n,e),n}})();Object.defineProperty(Nr,"__esModule",{value:!0});Nr.storeCommand=QL;Nr.installFromStore=Qy;Nr.resolvePublishBundleMode=Zy;var Xi=jf(require("fs/promises")),_i=jf(require("path")),Jy=jf(require("os")),YL=require("zlib"),sl=Ke(),XL=td(),zy=sd(),Bs=_c(),xf=Pa(),Qo=bf(),JL=id(),Gf=kf();function Ji(){let t=process.env.AGENTHIPPO_STORE_REPO,e=Bs.DEFAULT_STORE_OWNER,n=Bs.DEFAULT_STORE_REPO;if(t){let r=t.split("/");r.length===2&&(e=r[0],n=r[1])}return{owner:e,repo:n,defaultBranch:Bs.DEFAULT_STORE_BRANCH,paths:Bs.STORE_PATHS}}function zL(){if(process.env.AGENTHIPPO_STORE_URL)return process.env.AGENTHIPPO_STORE_URL;let t=Ji();return`https://${t.owner}.github.io/${t.repo}/store-index.json`}function Bf(){return process.env.GITHUB_TOKEN||process.env.GH_TOKEN||process.env.AGENTHIPPO_GITHUB_TOKEN}async function Ff(t,e={}){let n=Bf(),r={"User-Agent":"AgentHippo-CLI",Accept:"application/vnd.github.v3+json",...e.headers||{}};return n&&(r.Authorization=`Bearer ${n}`),fetch(t,{...e,headers:r,redirect:"follow"})}var Fs={appendLine:t=>{process.env.VERBOSE==="1"&&console.error(t)}};async function QL(t){switch(t.verbose&&(process.env.VERBOSE="1"),t.action){case"search":await ZL(t);break;case"install":await Qy(t);break;case"publish":await eM(t);break;case"uninstall":case"remove":await rM(t);break;case"info":await sM(t);break;case"list":await iM(t);break;default:console.error(`Error: Unknown action: ${t.action}`),console.log(""),console.log("Available actions:"),console.log(" search <query> Search for skills, packs, MCP servers, engines"),console.log(" install <ref> Install artifact (e.g., skill/pdf-tools@1.0.0)"),console.log(" publish <ref> Publish engine/<id> or view/<id>[@version]"),console.log(" uninstall <ref> Uninstall artifact (currently engine/<slug>)"),console.log(" info <ref> Show artifact details"),console.log(" list List all available artifacts"),console.log(""),console.log(" Override store repo (CLI): AGENTHIPPO_STORE_REPO=owner/repo"),process.exit(1)}}var ir=Bs.STORE_ICONS;async function ZL(t){let e=t.query?.toLowerCase()||"",n=t.limit||20,r=t.type,s=await Vf(),i=new zy.LocalRegistry,o=new Set((await i.listPacks()).map(g=>g.slug)),a=await i.listSkills(),c=await i.listMcp(),l=await tw(),f=new Map(a.map(g=>[g.slug,g.installedTo||[]])),u=new Map(c.map(g=>[g.slug,g.installedTo||[]])),d=s.artifacts.filter(g=>r&&g.type!==r?!1:e?[g.slug,g.displayName,g.description,...g.tags||[]].join(" ").toLowerCase().includes(e):!0);d.sort((g,m)=>{let h=g.slug.toLowerCase()===e,E=m.slug.toLowerCase()===e;return h&&!E?-1:!h&&E?1:g.slug.localeCompare(m.slug)}),d=d.slice(0,n);let p=d.map(g=>{let m=!1,h;return g.type==="pack"?m=o.has(g.slug):g.type==="skill"?(h=f.get(g.slug),m=h!==void 0&&h.length>0):g.type==="mcp"?(h=u.get(g.slug),m=h!==void 0&&h.length>0):g.type==="engine"&&(m=l.has(g.slug)),{...g,isLocal:m,installedTo:h}});if(t.json){console.log(JSON.stringify(p,null,2));return}if(p.length===0){console.log(`No results found for "${e}"`);return}console.log(""),console.log(`Found ${p.length} result(s):`),console.log("");for(let g of p){let m=g.latestVersion?`v${g.latestVersion}`:"",h=g.isLocal?ir.local:ir.remote,E=g.isLocal?` ${ir.installed}`:"";if(console.log(` ${h} ${g.type}/${g.slug} ${m}${E}`),g.description){let _=g.description.length>60?g.description.slice(0,57)+"...":g.description;console.log(` ${_}`)}g.installedTo&&g.installedTo.length>0&&console.log(` Installed to: ${g.installedTo.join(", ")}`)}console.log(""),console.log(`Legend: ${ir.local} Local ${ir.remote} Remote ${ir.installed} Installed`),console.log(""),console.log("Install with:"),console.log(" agenthippo store install <type>/<slug>"),console.log("")}async function Qy(t){t.query||(console.error("Error: Artifact reference required."),console.log("Usage: agenthippo store install <type>/<slug>[@version]"),console.log(""),console.log("Examples:"),console.log(" agenthippo store install skill/pdf-tools"),console.log(" agenthippo store install pack/code-reviewer@1.0.0"),console.log(" agenthippo store install mcp/filesystem"),console.log(" agenthippo store install engine/gemini"),console.log(" agenthippo store install view/cost-ops@1.0.0"),process.exit(1));let e=il(t.query),{type:n,slug:r,version:s}=e,i=t.workspace||process.cwd();console.log(`Installing ${n}/${r}${s?`@${s}`:""}...`);let o=s||t.version;if(!o){let f=await Hf(n,r);f.length>0?(o=f.find(d=>!d.isPrerelease)?.version||f[0].version,console.log(` Using latest version: ${o}`)):(o="main",console.log(" No versions found, using main branch"))}if(n==="view"){console.log(" Downloading...");let f=await Uf(n,r,o);f.length===0&&(console.error(`Error: No files found for ${n}/${r}`),process.exit(1));let{installSpotlightViewFromFiles:u}=await Promise.resolve().then(()=>wn(Xy())),d=await u(f.map(p=>({path:p.path,content:p.content})),{slug:r,version:o,overwrite:!!t.force,workspaceRoot:i,logger:Fs});console.log(""),console.log(`\u2713 Installed view/${d.id} to:`),console.log(` ${d.installDir}`),console.log(` Panel config: ${d.viewsConfigPath}`),console.log("");return}if(n==="engine"){console.log(" Downloading...");let f=await Uf(n,r,o);f.length===0&&(console.error(`Error: No files found for ${n}/${r}`),process.exit(1));let u=await(0,xf.installCustomEngineFromFiles)(f,{slug:r,version:o,overwrite:!!t.force,logger:Fs});console.log(""),console.log(`\u2713 Installed engine/${u.id} to:`),console.log(` ${u.installDir}`),console.log("");return}let a=t.agent||"default",c;switch(n){case"skill":c=_i.join(i,sl.AGENTIDE_DIR_NAME,"agents",a,"skills",r);break;case"pack":c=t.installDir?_i.resolve(t.installDir):_i.join(Jy.homedir(),sl.AGENTIDE_DIR_NAME,"agents",r,o);break;case"mcp":c=_i.join(i,sl.AGENTIDE_DIR_NAME,"agents",a,"mcp",r);break}try{await Xi.access(c),t.force||(console.error(`Error: ${n}/${r} already exists at ${c}`),console.log("Use --force to overwrite."),process.exit(1)),console.log(" Removing existing installation..."),await Xi.rm(c,{recursive:!0,force:!0})}catch{}console.log(" Downloading...");let l=await Uf(n,r,o);l.length===0&&(console.error(`Error: No files found for ${n}/${r}`),process.exit(1)),console.log(` Extracting ${l.length} files...`),await Xi.mkdir(c,{recursive:!0});for(let f of l){let u=(0,XL.safeJoin)(c,f.path);u||(console.error(`Error: refusing install \u2014 artifact path escapes destination (${f.path})`),process.exit(1)),await Xi.mkdir(_i.dirname(u),{recursive:!0}),await Xi.writeFile(u,f.content)}if(n==="pack"&&!t.installDir){let f=_i.join(Jy.homedir(),sl.AGENTIDE_DIR_NAME,"agents",r);await Xi.writeFile(_i.join(f,"current.txt"),o)}console.log(""),console.log(`\u2713 Installed ${n}/${r} to:`),console.log(` ${c}`),console.log("")}function Zy(t){if(t.full&&t.bundle&&t.bundle.trim().toLowerCase()!=="full"&&(console.error("Error: Cannot combine --full with --bundle scripts-only"),process.exit(1)),t.full)return"full";if(t.bundle){let e=t.bundle.trim().toLowerCase();if(e==="full"||e==="scripts-only")return e;console.error("Error: Invalid --bundle value. Use scripts-only or full."),process.exit(1)}return"scripts-only"}async function eM(t){t.query||(console.error("Error: Artifact reference required."),console.log("Usage: agenthippo store publish <engine|view>/<slug>[@version]"),console.log(""),console.log("Examples:"),console.log(" agenthippo store publish engine/rovo"),console.log(" agenthippo store publish engine/rovo@1.0.0"),console.log(" agenthippo store publish view/cost-ops@1.0.0"),console.log(" agenthippo store publish view/brand-board --bundle full"),console.log(" agenthippo store publish view/brand-board --full"),console.log(""),console.log("Requires GITHUB_TOKEN (or GH_TOKEN / AGENTHIPPO_GITHUB_TOKEN) with fork + PR access."),console.log("Override store repo (CLI): AGENTHIPPO_STORE_REPO=owner/repo"),process.exit(1));let e=il(t.query),{type:n,slug:r,version:s}=e;if(n!=="engine"&&n!=="view"&&(console.error(`Error: store publish supports engine and view only, got ${n}/${r}`),console.log("Use: agenthippo store publish engine/<id>[@version]"),console.log(" agenthippo store publish view/<id>[@version] [--bundle full|scripts-only]"),process.exit(1)),Bf()||(console.error("Error: GitHub token required to publish."),console.log("Set GITHUB_TOKEN, GH_TOKEN, or AGENTHIPPO_GITHUB_TOKEN, then retry."),process.exit(1)),n==="engine"){await tM(t,r,s);return}await nM(t,r,s)}async function tM(t,e,n){let r=t.workspace||process.cwd(),s=await(0,Qo.resolveEngineSourceDir)(e,r);s||(console.error(`Error: Engine "${e}" not found under .agent-hippo/engines/ (workspace or home).`),process.exit(1)),console.log(`Publishing engine/${e} from ${s}...`);let i=await(0,Qo.validateEngineForPublish)(s,e);if(!i.valid){console.error(`Error: Cannot publish engine/${e}`);for(let l of i.errors)console.error(` - ${l}`);process.exit(1)}for(let l of i.warnings)console.log(` Warning: ${l}`);let o=n||t.version||i.metadata?.suggestedVersion;o||(console.error("Error: Publish version required."),console.log("Pass a version: agenthippo store publish engine/<slug>@1.0.0"),console.log("Or add a semver version field to package.json in the engine folder."),process.exit(1)),o=o.replace(/^v/,""),(0,Qo.isValidPublishVersion)(o)||(console.error(`Error: Invalid version "${o}". Use semver (e.g., 1.0.0).`),process.exit(1));let a=await(0,Qo.collectEngineFiles)(s),c=Ji();console.log(` Target store: ${c.owner}/${c.repo}`),console.log(` Version tag: engines/${e}/v${o}`),console.log(` Files: ${a.length}`),await ew({options:t,type:"engine",slug:e,version:o,files:a,installHint:`agenthippo store install engine/${e}`})}async function nM(t,e,n){let r=t.workspace||process.cwd(),s=Zy(t),i=await(0,Gf.discoverPublishableViews)(r),o=i.find(d=>d.id===e);if(!o){if(console.error(`Error: Spotlight view "${e}" not found.`),console.log("Register a user view in .agent-hippo/analytics/panel/views.yaml (non-system id)."),i.length>0){console.log(""),console.log("Publishable views:");for(let d of i)console.log(` - view/${d.id} (${d.sourceLabel}, ${d.scope})`)}process.exit(1)}console.log(`Publishing view/${e} from ${o.viewRoot}...`),console.log(` Bundle: ${s==="full"?"full (scripts + assets + charts/reports/exports + manifest.json)":"scripts only"}`);let a=await(0,Gf.validateViewForPublish)(o,{expectedId:e,mode:s});if(!a.valid){console.error(`Error: Cannot publish view/${e}`);for(let d of a.errors)console.error(` - ${d}`);process.exit(1)}for(let d of a.warnings)console.log(` Warning: ${d}`);a.metadata||(console.error("Error: Validation succeeded but metadata is missing."),process.exit(1));let c=n||t.version||a.metadata.publishVersion;c||(console.error("Error: Publish version required."),console.log("Pass a version: agenthippo store publish view/<slug>@1.0.0"),console.log("Or add version to view.yaml (e.g. version: 1.0.0)."),process.exit(1)),c=c.replace(/^v/,""),(0,Qo.isValidPublishVersion)(c)||(console.error(`Error: Invalid version "${c}". Use semver (e.g., 1.0.0).`),process.exit(1));let l=await(0,Gf.collectViewFiles)(o,c,a.metadata,s),f=Ji(),u=l.filter(d=>d.encoding==="base64").length;console.log(` Target store: ${f.owner}/${f.repo}`),console.log(` Version tag: spotlight/${e}/v${c}`),console.log(` Files: ${l.length}${u>0?` (${u} binary)`:""}`),await ew({options:t,type:"view",slug:e,version:c,files:l,bundle:s,installHint:`agenthippo store install view/${e}`})}async function ew(t){let{options:e,type:n,slug:r,version:s,files:i,bundle:o,installHint:a}=t;try{let c=await(0,JL.publishToStore)({type:n,slug:r,version:s,files:i},Fs);e.json?console.log(JSON.stringify({success:!0,type:n,slug:r,version:s,bundle:o,prUrl:c.prUrl,prNumber:c.prNumber,tagName:c.tagName},null,2)):(console.log(""),console.log(`\u2713 Opened pull request for ${n}/${r} v${s}${o==="full"?" (full bundle)":""}`),console.log(` ${c.prUrl}`),console.log(""),console.log(`After merge, install with: ${a}`))}catch(c){let l=c instanceof Error?c.message:String(c);e.json?console.log(JSON.stringify({success:!1,error:l})):console.error(`Error: ${l}`),process.exit(1)}}async function rM(t){t.query||(console.error("Error: Artifact reference required."),console.log("Usage: agenthippo store uninstall engine/<slug>"),console.log(""),console.log("Examples:"),console.log(" agenthippo store uninstall engine/gemini"),process.exit(1));let{type:e,slug:n}=il(t.query);e!=="engine"&&(console.error(`Error: store uninstall currently supports custom engines only, got ${e}/${n}`),process.exit(1));let r=await(0,xf.uninstallCustomEngine)(n,{logger:Fs});r.removed||(console.error(`Error: engine/${r.id} is not installed.`),process.exit(1)),console.log(""),console.log(`\u2713 Uninstalled engine/${r.id} from:`),console.log(` ${r.installDir}`),console.log("")}async function sM(t){t.query||(console.error("Error: Artifact reference required."),console.log("Usage: agenthippo store info <type>/<slug>"),process.exit(1));let e=il(t.query),r=(await Vf()).artifacts.find(i=>i.type===e.type&&i.slug===e.slug);if(r||(console.error(`Error: ${e.type}/${e.slug} not found in store.`),process.exit(1)),t.json){let i=await Hf(e.type,e.slug);console.log(JSON.stringify({...r,versions:i},null,2));return}console.log(""),console.log("\u2500".repeat(60)),console.log(`${r.type}/${r.slug}`),console.log("\u2500".repeat(60)),console.log(`Name: ${r.displayName}`),console.log(`Type: ${r.type}`),console.log(`Version: ${r.latestVersion||"N/A"}`),r.author&&console.log(`Author: ${r.author}`),r.description&&console.log(`Description: ${r.description}`),r.tags?.length&&console.log(`Tags: ${r.tags.join(", ")}`);let s=await Hf(e.type,e.slug);if(s.length>0){console.log(""),console.log("Available versions:");for(let i of s.slice(0,10)){let o=i.isPrerelease?" (pre-release)":"";console.log(` - ${i.version}${o}`)}s.length>10&&console.log(` ... and ${s.length-10} more`)}console.log("\u2500".repeat(60)),console.log(""),console.log("Install with:"),console.log(` agenthippo store install ${r.type}/${r.slug}`),console.log("")}async function iM(t){let e=await Vf(),n=t.type,r=new zy.LocalRegistry,s=new Set((await r.listPacks()).map(p=>p.slug)),i=await r.listSkills(),o=await r.listMcp(),a=await tw(),c=new Map(i.map(p=>[p.slug,p.installedTo||[]])),l=new Map(o.map(p=>[p.slug,p.installedTo||[]])),f=e.artifacts;n&&(f=f.filter(p=>p.type===n));let u=p=>{if(p.type==="pack")return s.has(p.slug);if(p.type==="skill"){let g=c.get(p.slug);return g!==void 0&&g.length>0}if(p.type==="mcp"){let g=l.get(p.slug);return g!==void 0&&g.length>0}return p.type==="engine"?a.has(p.slug):!1};if(t.json){let p=f.map(g=>({...g,isLocal:u(g),installedTo:g.type==="skill"?c.get(g.slug):g.type==="mcp"?l.get(g.slug):void 0}));console.log(JSON.stringify(p,null,2));return}console.log(""),console.log(`Store contains ${f.length} artifact(s):`),console.log("");let d={};for(let p of f)d[p.type]=d[p.type]||[],d[p.type].push(p);for(let p of["pack","skill","mcp","engine"]){let g=d[p]||[];if(g.length!==0){console.log(`${p}s (${g.length}):`);for(let m of g){let h=m.latestVersion?` v${m.latestVersion}`:"",E=u(m),_=E?ir.local:ir.remote,y=E?` ${ir.installed}`:"";console.log(` ${_} ${m.slug}${h}${y}`)}console.log("")}}console.log(`Legend: ${ir.local} Local ${ir.remote} Remote ${ir.installed} Installed`),console.log("")}function il(t){try{return(0,Bs.parseStoreUrl)(t)}catch(e){let n=e instanceof Error?e.message:String(e);console.error(`Error: ${n}`),console.log("Expected format: <type>/<slug>[@version]"),console.log("Examples: skill/pdf-tools, pack/code-reviewer@1.0.0, engine/gemini, view/cost-ops"),process.exit(1)}}async function tw(){return new Set((await(0,xf.listInstalledCustomEngines)()).map(t=>t.id))}async function Vf(){let t=zL();Fs.appendLine(`[Store] Fetching index from ${t}`);let e=await fetch(t,{headers:{"User-Agent":"AgentHippo-CLI",Accept:"application/json"}});if(e.ok)return await e.json();if(Bf()&&(e.status===403||e.status===404)){Fs.appendLine("[Store] GitHub Pages not available, trying API with auth...");let r=Ji(),s=`https://api.github.com/repos/${r.owner}/${r.repo}/contents/dist/store-index.json`;if(e=await Ff(s,{headers:{Accept:"application/vnd.github.raw+json"}}),e.ok)return await e.json()}throw new Error(`Failed to fetch store index: ${e.status} ${e.statusText}`)}async function Hf(t,e){let n=Ji(),s=`${(0,Bs.getStorePath)(t)}/${e}/v`,i=`https://api.github.com/repos/${n.owner}/${n.repo}/git/refs/tags`;Fs.appendLine(`[Store] Listing versions for ${t}/${e}`);let o=await Ff(i);if(!o.ok){if(o.status===404)return[];throw new Error(`Failed to list versions: ${o.statusText}`)}let a=await o.json(),c=[];for(let{ref:l}of a){let f=l.replace("refs/tags/","");if(f.startsWith(s)){let u=f.slice(s.length-1);c.push({version:u.replace(/^v/,""),tagName:f,isPrerelease:/-(alpha|beta|rc|pre)/.test(u)})}}return c.sort((l,f)=>f.version.localeCompare(l.version,void 0,{numeric:!0}))}async function Uf(t,e,n){let r=Ji(),s=(0,Bs.getStorePath)(t),i;n==="main"||n==="latest"?i=r.defaultBranch:i=`${s}/${e}/v${n.replace(/^v/,"")}`,Fs.appendLine(`[Store] Downloading ${t}/${e} at ${i}`);let o=encodeURIComponent(i),a=`https://api.github.com/repos/${r.owner}/${r.repo}/tarball/${o}`,c=await Ff(a);if(!c.ok)throw new Error(`Failed to download: ${c.status} ${c.statusText}`);let l=Buffer.from(await c.arrayBuffer()),f=(0,YL.gunzipSync)(l),u=oM(f),d=`${s}/${e}/`,p=[];for(let[g,m]of u){let h=g.indexOf("/");if(h===-1)continue;let E=g.slice(h+1);if(E.startsWith(d)){let _=E.slice(d.length);_&&p.push({path:_,content:m})}}return p}function oM(t){let e=new Map,n=0;for(;n<t.length-512;){let r=t.subarray(n,n+512);if(r.every(c=>c===0))break;let s=r.subarray(0,100).toString("utf-8").replace(/\0/g,"").trim(),i=r.subarray(124,136).toString("utf-8").replace(/\0/g,"").trim(),o=r[156];if(!s){n+=512;continue}let a=parseInt(i,8)||0;n+=512,(o===0||o===48)&&e.set(s,Buffer.from(t.subarray(n,n+a))),n+=Math.ceil(a/512)*512}return e}});var nw=S(Kf=>{"use strict";Object.defineProperty(Kf,"__esModule",{value:!0});Kf.parsePackInstallRef=aM;function aM(t){let e=t.trim(),n=e.lastIndexOf("@");return n>0?{slug:e.slice(0,n),version:e.slice(n+1)||void 0}:{slug:e}}});var sw=S(Ts=>{"use strict";var cM=Ts&&Ts.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,s)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),lM=Ts&&Ts.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),rw=Ts&&Ts.__importStar||(function(){var t=function(e){return t=Object.getOwnPropertyNames||function(n){var r=[];for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(r[r.length]=s);return r},t(e)};return function(e){if(e&&e.__esModule)return e;var n={};if(e!=null)for(var r=t(e),s=0;s<r.length;s++)r[s]!=="default"&&cM(n,e,r[s]);return lM(n,e),n}})();Object.defineProperty(Ts,"__esModule",{value:!0});Ts.packCommand=pM;var zi=rw(require("fs")),al=rw(require("path")),Qi=ai(),ol=Ke(),uM=Mi(),or=Oo(),dM=Wf(),fM=nw(),qf="-".repeat(62);async function pM(t){let e=t.workspace;switch(t.action){case"list":await hM(e);break;case"validate":t.name||(console.error("Error: Pack name required. Usage: agenthippo pack validate <name>"),process.exit(1)),await mM(t.name,e);break;case"info":t.name||(console.error("Error: Pack name required. Usage: agenthippo pack info <name>"),process.exit(1)),await EM(t.name,e);break;case"sign":await yM(t);break;case"verify":await wM(t);break;case"digest":await AM(t);break;case"keygen":_M(t);break;case"install":await gM(t);break;case"export":console.log("Pack export is not yet implemented.");break;default:console.error(`Error: Unknown action: ${t.action}`),console.log(""),console.log("Available actions:"),console.log(" list List installed packs"),console.log(" validate Validate a pack"),console.log(" info Show pack details"),console.log(" sign Sign a pack so a fleet can verify it before running"),console.log(" verify Verify a pack against trusted public keys"),console.log(" digest Print the pack content digest (what a signature covers)"),console.log(" keygen Generate an ES256 signing keypair"),console.log(" install Install a pack from the store to a folder"),console.log(" export Export a pack (coming soon)"),process.exit(1)}}async function gM(t){t.name?.trim()||(console.error("Error: pack slug required."),console.log("Usage: agenthippo pack install <slug>[@version] --to <dir>"),console.log(""),console.log("Examples:"),console.log(" agenthippo pack install joker1 --to ./packs/joker1"),console.log(" agenthippo pack install code-reviewer@1.0.0 --to ./packs/code-reviewer"),process.exit(1));let e=t.to?.trim();e||(console.error("Error: --to <dir> is required."),console.log("Usage: agenthippo pack install <slug>[@version] --to <dir>"),console.log(""),console.log("Same download as `agenthippo store install pack/<slug>`, extracted flat for serve/deploy."),process.exit(1));let{slug:n,version:r}=(0,fM.parsePackInstallRef)(t.name);await(0,dM.installFromStore)({action:"install",query:`pack/${n}${r?`@${r}`:""}`,workspace:t.workspace,version:r,force:t.force,installDir:al.resolve(e),verbose:t.verbose})}async function hM(t){let e=(0,Qi.listAvailablePacks)(t);if(e.length===0){console.log("No agent packs found."),console.log(""),console.log("Agent packs are stored in:"),t&&console.log(` Workspace: ${t}/${ol.AGENTIDE_DIR_NAME}/agents/`),console.log(` User library: ~/${ol.AGENTIDE_DIR_NAME}/agents/`),console.log(""),console.log("Create a pack with:"),console.log(` mkdir -p ~/${ol.AGENTIDE_DIR_NAME}/agents/my-agent/1.0.0`),console.log(` echo "1.0.0" > ~/${ol.AGENTIDE_DIR_NAME}/agents/my-agent/current.txt`),console.log(" # Add agent.yaml and AGENTS.md");return}console.log(""),console.log("Installed Agent Packs:"),console.log("");for(let n of e){let r=n.version?` (v${n.version})`:"",s=n.source==="workspace"?" [workspace]":"";console.log(` ${n.name}${r}${s}`),console.log(` ${n.path}`)}console.log("")}async function mM(t,e){console.log(`Validating pack: ${t}`),console.log("");let n=(0,Qi.resolvePackPath)(t,e);n||(console.error(`Error: Pack not found: ${t}`),process.exit(1));let r=[],s=[],i=al.join(n,"agent.yaml");zi.existsSync(i)?console.log(" OK: agent.yaml exists"):r.push("Missing agent.yaml");try{let o=await(0,Qi.loadAgentPack)(t,e);console.log(` OK: metadata.name: ${o.manifest.metadata.name}`),console.log(` OK: metadata.version: ${o.manifest.metadata.version}`),console.log(` OK: spec.engine: ${o.manifest.spec.engine}`),o.manifest.spec.model?console.log(` OK: spec.model: ${o.manifest.spec.model}`):s.push("spec.model not specified, will use default"),o.manifest.spec.cheapModel&&console.log(` OK: spec.cheapModel: ${o.manifest.spec.cheapModel}`);let a=al.join(n,"AGENTS.md");if(zi.existsSync(a)){let c=zi.statSync(a);console.log(` OK: AGENTS.md exists (${(c.size/1024).toFixed(1)} KB)`)}else s.push("No AGENTS.md found")}catch(o){r.push(o instanceof Error?o.message:String(o))}if(console.log(""),s.length>0)for(let o of s)console.log(` Warning: ${o}`);if(r.length>0){for(let o of r)console.log(` Error: ${o}`);console.log(""),console.log("Pack is INVALID"),process.exit(1)}console.log(""),console.log("Pack is valid.")}async function EM(t,e){try{let n=await(0,Qi.loadAgentPack)(t,e);if(console.log(""),console.log(qf),console.log(`Agent: ${n.manifest.metadata.name}`),console.log(qf),console.log(`Version: ${n.manifest.metadata.version}`),n.manifest.metadata.description&&console.log(`Description: ${n.manifest.metadata.description}`),n.manifest.metadata.author&&console.log(`Author: ${n.manifest.metadata.author}`),console.log(`Engine: ${n.manifest.spec.engine}`),n.manifest.spec.model&&console.log(`Model: ${n.manifest.spec.model}`),n.manifest.spec.cheapModel&&console.log(`Cheap Model: ${n.manifest.spec.cheapModel}`),console.log(`Path: ${n.packPath}`),n.manifest.spec.permissions&&(console.log(""),console.log("Permissions:"),console.log(` File Access: ${n.manifest.spec.permissions.fileAccess||"default"}`)),n.manifest.spec.mcpServers&&n.manifest.spec.mcpServers.length>0){console.log(""),console.log("MCP Servers:");for(let r of n.manifest.spec.mcpServers)console.log(` - ${r.name}`)}console.log(qf),console.log("")}catch(n){console.error(`Error: ${n instanceof Error?n.message:n}`),process.exit(1)}}async function Yf(t,e){t||(console.error("Error: pack name or path required"),process.exit(1));let n=(0,Qi.resolvePackPath)(t,e);n||(console.error(`Error: pack not found: ${t}`),process.exit(1));let r=await(0,Qi.loadAgentPack)(n,e);return{packPath:r.packPath,name:r.manifest.metadata.name,version:r.manifest.metadata.version??"0.0.0"}}function _M(t){let e=t.kid||`sign-${new Date().toISOString().slice(0,10)}`,n=(0,uM.generateWarrantKeypair)(e),r=t.output;r?(zi.writeFileSync(r,n.privateKeyPem,{mode:384}),console.log(`Private key written to ${r} (mode 0600) \u2014 keep it off shared disks.`)):console.log(n.privateKeyPem),console.log(""),console.log(`kid: ${e}`),console.log("Public half \u2014 publish this to the control plane so instances can verify:"),console.log(n.publicKeyPem.trim()),console.log(""),console.log(` curl -X POST "$CONTROL/api/keys" -H 'content-type: application/json' \\`),console.log(` -d '{"kid":"${e}","publicPem":"\u2026"}'`)}async function yM(t){let{packPath:e,name:n,version:r}=await Yf(t.name,t.workspace);t.key||(console.error("Error: --key <private-key.pem> required. Generate one with: agenthippo pack keygen -o key.pem"),process.exit(1));let s;try{s=zi.readFileSync(t.key,"utf8")}catch(a){console.error(`Error: cannot read key ${t.key}: ${a instanceof Error?a.message:a}`),process.exit(1);return}let i=t.kid;i||(console.error("Error: --kid <id> required \u2014 it is how a verifier finds the public half in JWKS."),process.exit(1));let{digest:o}=(0,or.signPack)({packDir:e,pack:n,packVersion:r,privateKeyPem:s,kid:i});console.log(`Signed ${n}@${r}`),console.log(` digest ${o}`),console.log(` key ${i}`),console.log(` written ${al.join(e,or.PACK_SIGNATURE_FILE)}`),console.log(""),console.log("Commit pack.sig with the pack: it travels WITH the artifact, and a fleet that"),console.log("requires signatures refuses anything whose contents no longer match it.")}async function wM(t){let{packPath:e,name:n,version:r}=await Yf(t.name,t.workspace),s=(0,or.readPackSignature)(e);s||(console.error(`UNSIGNED: no ${or.PACK_SIGNATURE_FILE} at ${e}`),console.error((0,or.describePackRefusal)({kind:"unsigned",detail:`no ${or.PACK_SIGNATURE_FILE}`,pack:n,packVersion:r,packDir:e})),process.exit(1));let i={};if(t.keys)try{i=JSON.parse(zi.readFileSync(t.keys,"utf8"))}catch(a){console.error(`Error: cannot read keys ${t.keys}: ${a instanceof Error?a.message:a}`),process.exit(1)}else{let a=await(0,or.loadPackTrustRoot)({env:t.jwks?{...process.env,[or.PACK_JWKS_URL_ENV]:t.jwks}:process.env,leaseUrl:process.env.AGENTHIPPO_LEASE_URL});for(let c of a.warnings)console.error(`Warning: ${c}`);a.status==="unavailable"&&(console.error(`REFUSED: a trust root is configured but could not be loaded \u2014 ${a.reason}`),console.error((0,or.describePackRefusal)({kind:"trust-root-unavailable",detail:a.reason??"unavailable",pack:n,packVersion:r,packDir:e,trustRootHint:a.url?`Trust root: ${a.url}`:void 0})),process.exit(1)),i=a.keys}Object.keys(i).length===0&&(console.error("REFUSED: no trusted public keys. Pass --keys <file>, --jwks <url>, or set AGENTHIPPO_PACK_SIGNING_KEYS."),process.exit(1));let o=(0,or.verifyPack)(s,i,{packDir:e,pack:n,packVersion:r});o.ok||(console.error(`INVALID: ${o.reason}`),console.error((0,or.describePackRefusal)({kind:o.kind,detail:o.reason,pack:n,packVersion:r,packDir:e})),process.exit(1)),console.log(`OK: ${n}@${r} verified`),console.log(` digest ${o.claims.digest}`),console.log(" NOTE: .claude/, .codex/ and .agent-hippo/ ARE covered by this digest \u2014 they carry hooks"),console.log(" and other executable content, and were previously outside the signature.")}async function AM(t){let{packPath:e,name:n,version:r}=await Yf(t.name,t.workspace);console.log(`${(0,or.computePackDigest)(e)} ${n}@${r}`)}});var ow=S(Zo=>{"use strict";Object.defineProperty(Zo,"__esModule",{value:!0});Zo.parseStrictJsonConfig=iw;Zo.collectMissingChannelEnvSecrets=TM;Zo.disableChannelsInConfigText=bM;var SM=8;function yi(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function iw(t){try{return JSON.parse(t)}catch{return}}function Xf(t,e,n){if(!(n>SM)){if(Array.isArray(t)){for(let r of t)Xf(r,e,n+1);return}if(yi(t)){if(t.source==="env"&&typeof t.id=="string"&&t.id.trim()){e.add(t.id.trim());return}for(let r of Object.values(t))Xf(r,e,n+1)}}}function TM(t,e){if(!yi(t)||!yi(t.channels))return[];let n=[];for(let[r,s]of Object.entries(t.channels)){if(!yi(s)||s.enabled===!1)continue;let i=new Set;Xf(s,i,0);let o=[...i].filter(a=>!e[a]?.trim()).sort();o.length&&n.push({channel:r,envVars:o})}return n}function bM(t,e){let n=iw(t);if(!(!yi(n)||!yi(n.channels))){for(let r of e){let s=n.channels[r];yi(s)&&(s.enabled=!1)}return`${JSON.stringify(n,null,2)}
613
- `}}});var cw=S(cl=>{"use strict";Object.defineProperty(cl,"__esModule",{value:!0});cl.quoteWindowsCommandLineArg=aw;cl.buildWindowsArgumentLine=vM;function aw(t){return t.length===0?'""':/[ \t"]/u.test(t)?`"${t.replace(/(\\*)"/g,'$1$1\\"').replace(/(\\+)$/g,"$1$1")}"`:t}function vM(t){return t.map(e=>aw(e)).join(" ")}});var lw=S(Jf=>{"use strict";Object.defineProperty(Jf,"__esModule",{value:!0});Jf.isGatewayScopeAuthError=OM;function OM(t){let e=t.toLowerCase();return e.includes("missing scope")||e.includes("operator.admin")}});var uw=S(ar=>{"use strict";Object.defineProperty(ar,"__esModule",{value:!0});ar.ANYWHERE_INSTALL_SOURCE_FORMS=ar.ANYWHERE_CONFIG_TEMPLATE_ENV=ar.ANYWHERE_SETUP_SCRIPT_ENV=ar.ANYWHERE_INSTALL_SOURCE_ENV=void 0;ar.validateAnywhereInstallSource=kM;ar.ANYWHERE_INSTALL_SOURCE_ENV="AH_INSTALL_SOURCE";ar.ANYWHERE_SETUP_SCRIPT_ENV="AH_SETUP_SCRIPT";ar.ANYWHERE_CONFIG_TEMPLATE_ENV="AH_CONFIG_TEMPLATE";var IM=/^(?:@[a-z0-9][a-z0-9._-]*\/)?[a-z0-9][a-z0-9._-]*(?:@[a-zA-Z0-9^~*><=][a-zA-Z0-9.^~*+><=|_-]*)?$/,PM=/^github:[A-Za-z0-9][A-Za-z0-9._-]*\/[A-Za-z0-9][A-Za-z0-9._-]*(?:#[A-Za-z0-9._/-]+)?$/,NM=/^https:\/\/[A-Za-z0-9._-]+(?::\d+)?\/[A-Za-z0-9._~!$'()*+,;=:@%/-]*\.(?:tgz|tar\.gz)$/,RM=/^(?:\.{1,2})?\/[^\0<>"'`;|&$\n\r]*$/,CM=/^[A-Za-z]:[\\/][^\0<>"'`;|&$\n\r]*$/;ar.ANYWHERE_INSTALL_SOURCE_FORMS="accepted forms are: an npm specifier (e.g. @agenthippo-ai/hippoclaw@2026.7.28), github:owner/repo[#ref], an https:// .tgz/.tar.gz URL, or a local path";function kM(t){let e=r=>({ok:!1,reason:`${r} \u2014 ${ar.ANYWHERE_INSTALL_SOURCE_FORMS}`}),n=t.trim();return n?n!==t?e("it has leading or trailing whitespace"):IM.test(n)||PM.test(n)||NM.test(n)||RM.test(n)||CM.test(n)?{ok:!0}:e("it is not one of the accepted forms"):e("it is empty")}});var Rw=S(D=>{"use strict";var $M=D&&D.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,s)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),DM=D&&D.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),El=D&&D.__importStar||(function(){var t=function(e){return t=Object.getOwnPropertyNames||function(n){var r=[];for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(r[r.length]=s);return r},t(e)};return function(e){if(e&&e.__esModule)return e;var n={};if(e!=null)for(var r=t(e),s=0;s<r.length;s++)r[s]!=="default"&&$M(n,e,r[s]);return DM(n,e),n}})();Object.defineProperty(D,"__esModule",{value:!0});D.GatewayLifecycleManager=D.validateAnywhereInstallSource=D.ANYWHERE_SETUP_SCRIPT_ENV=D.ANYWHERE_INSTALL_SOURCE_ENV=D.ANYWHERE_CONFIG_TEMPLATE_ENV=D.AGENT_ANYWHERE_LABEL=void 0;D.detectGateway=fl;var N=El(require("vscode")),pl=require("child_process"),zf=require("crypto"),yw=require("util"),G=El(require("fs")),V=El(require("path")),ts=El(require("os")),be=Eo(),Qf=fa(),Zf=ow(),LM=cw(),MM=lw(),ep=Yd(),tp=Ke(),Gt=(0,yw.promisify)(pl.exec),GM=(0,yw.promisify)(pl.execFile),le=process.platform==="win32",ww=process.platform==="darwin";function dw(t,e){if(e)for(let n of e.split(V.delimiter)){let r=n.trim();r.length>0&&t.add(r)}}function UM(){let t=new Set,e=ts.homedir();dw(t,"/usr/bin:/bin:/usr/sbin:/sbin"),dw(t,process.env.PATH);let n=[V.join(e,".local","bin"),V.join(e,"Library","pnpm"),V.join(e,".local","share","pnpm"),V.join(e,".npm-global","bin"),V.join(e,".volta","bin"),V.join(e,".fnm"),V.join(e,".asdf","shims"),"/opt/homebrew/bin","/usr/local/bin"];for(let i of n)G.existsSync(i)&&t.add(i);let r=process.env.NVM_DIR||V.join(e,".nvm"),s=V.join(r,"versions","node");if(G.existsSync(s))try{let i=G.readdirSync(s,{withFileTypes:!0}).filter(o=>o.isDirectory()).map(o=>o.name).sort().reverse().slice(0,8);for(let o of i){let a=V.join(s,o,"bin");G.existsSync(a)&&t.add(a)}}catch{}return Array.from(t).join(V.delimiter)}function ll(){return ww&&G.existsSync("/bin/zsh")?"/bin/zsh":"/bin/bash"}function ul(t){return ww?["-lic",t]:["-lc",t]}function np(){if(!le)return{...process.env,PATH:UM(),npm_config_script_shell:"/bin/sh"}}D.AGENT_ANYWHERE_LABEL="Agent Anywhere";var Zi=`${D.AGENT_ANYWHERE_LABEL} Setup`,wi=`${D.AGENT_ANYWHERE_LABEL} Uninstall`,Ai=18789,rp=V.join(ts.homedir(),".openclaw","gateway.log"),fw="Open Gateway Log";function HM(t){return t.replace(/\x1b\[[0-9;]*m/g,"")}function jM(t){try{if(!G.existsSync(t))return;let n=G.readFileSync(t,"utf8").split(/\r?\n/).filter(r=>r.trim());for(let r=n.length-1;r>=Math.max(0,n.length-50);r--){let s=HM(n[r]).trim();if(!s||/Doctor warnings|force: no listeners/i.test(s))continue;let i=s.match(/Gateway failed to start:\s*(.+)/i);if(i?.[1])return i[1].trim().slice(0,160);if(/SecretRefResolutionError|is missing or empty|required secrets are unavailable/i.test(s))return s.replace(/^\d{4}-\d{2}-\d{2}T[\d:.+-]+\s*/,"").slice(0,160);if(/errorCode=|errorMessage=/i.test(s))return s.slice(0,160)}}catch{}}async function ea(t){let e=jM(t),n=e?`${D.AGENT_ANYWHERE_LABEL}: Gateway failed to start. ${e}`:`${D.AGENT_ANYWHERE_LABEL}: Gateway failed to start.`;if(await N.window.showErrorMessage(n,fw)===fw)try{let s=await N.workspace.openTextDocument(N.Uri.file(t));await N.window.showTextDocument(s,{preview:!1})}catch(s){let i=s instanceof Error?s.message:String(s);N.window.showErrorMessage(`${D.AGENT_ANYWHERE_LABEL}: Could not open gateway log (${i}). Path: ${t}`)}}var xM=3e4,BM=le?75e3:2e4,FM=3e4,_l=be.PID_FILES.gateway(),Zr="hippoclaw",pp=["@agenthippo-ai/hippoclaw","openclaw"],gp=V.join(ts.homedir(),".agenthippo","gateway"),gl=V.join(gp,"install.json"),op=V.join(gp,"install-status.json"),hp=le?V.join(process.env.LOCALAPPDATA||V.join(ts.homedir(),"AppData","Local"),"AgentHippo","bin"):V.join(ts.homedir(),".local","bin"),Aw=V.join(hp,le?"hippoclaw.cmd":"hippoclaw"),ap=V.join(hp,le?"openclaw.cmd":"openclaw"),cp=le?"REM Managed by Agent Anywhere":"# Managed by Agent Anywhere",lt=uw();Object.defineProperty(D,"ANYWHERE_CONFIG_TEMPLATE_ENV",{enumerable:!0,get:function(){return lt.ANYWHERE_CONFIG_TEMPLATE_ENV}});Object.defineProperty(D,"ANYWHERE_INSTALL_SOURCE_ENV",{enumerable:!0,get:function(){return lt.ANYWHERE_INSTALL_SOURCE_ENV}});Object.defineProperty(D,"ANYWHERE_SETUP_SCRIPT_ENV",{enumerable:!0,get:function(){return lt.ANYWHERE_SETUP_SCRIPT_ENV}});Object.defineProperty(D,"validateAnywhereInstallSource",{enumerable:!0,get:function(){return lt.validateAnywhereInstallSource}});function VM(t){return t?t.startsWith("\\")||t.startsWith("/")||t.startsWith(".")||/^[A-Za-z]:/.test(t)||t.startsWith("github:")||t.startsWith("git+http:")||t.startsWith("git+https:")||/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+(?:#.+)?$/.test(t):!1}var pw=[["npmInstallComplete","npm install complete"],["wrapperExists","wrapper exists"],["configExists","config exists"],["distExists","dist exists"],["webUiExists","web UI exists"],["finalCheckPassed","final check passed"]];function es(t){return t.replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function Sw(t,e){let n=es(t),r=es(e);return n===r||n.startsWith(`${r}/`)}function Si(){try{if(!G.existsSync(gl))return;let t=G.readFileSync(gl,"utf8").replace(/^/,"");return JSON.parse(t)}catch{return}}function WM(t){G.mkdirSync(gp,{recursive:!0}),G.writeFileSync(gl,JSON.stringify(t,null,2),"utf8")}function mp(t){let e=t?.packageRoot;if(!(!e||!G.existsSync(e)))try{return G.realpathSync(e)}catch{return e}}function KM(t){if(!t)return;let e=Si();return!e?.entryScriptPath&&!e?.cliPath?t:(e.wrapperPath||e.openclawWrapperPath)&&[e.wrapperPath,e.openclawWrapperPath].some(n=>n&&es(t)===es(n))&&(e.entryScriptPath&&G.existsSync(e.entryScriptPath)||e.cliPath&&G.existsSync(e.cliPath))?e.entryScriptPath&&G.existsSync(e.entryScriptPath)?e.entryScriptPath:e.cliPath:t}function Tw(t){if(!t)return;let e=Si();return e?.cliPath&&[e.wrapperPath,e.openclawWrapperPath,e.entryScriptPath].some(n=>n&&es(t)===es(n))&&G.existsSync(e.cliPath)?e.cliPath:t}function bw(t){for(let e of[t?.wrapperPath,t?.openclawWrapperPath,t?.cliPath])if(e&&G.existsSync(e))return e}function vw(t){let e=t?.nodePath;if(!(!e||!G.existsSync(e)))return e}function qM(t){let e=t?.entryScriptPath;if(!(!e||!G.existsSync(e)))return e}async function lp(t,e){let n=e??Si(),r=t??bw(n)??await Nw(),s=Tw(r)??r;if(!s||!G.existsSync(s))return;let i=mp(n)??Ep(s);if(!i)return;let o=vw(n)??XM(s),a=qM(n)??YM(i);if(!(!o||!a))return{launcherPath:s,packageRoot:i,nodePath:o,entryScriptPath:a}}function Ow(t){try{return G.existsSync(t)?G.readFileSync(t,"utf8").includes(cp):!1}catch{return!1}}function gw(t,e,n){G.mkdirSync(V.dirname(n),{recursive:!0});let r=le?`@echo off\r
614
- ${cp}\r
613
+ `)}`);let g={id:t.id,name:o?.name??t.name,description:o?.description,author:o?.author,publishVersion:o?.publishVersion,scope:o?.scope??t.scope,tags:o?.tags,scripts:a,...n==="full"?{publishBundle:"full"}:{}};return{valid:s.length===0,errors:s,warnings:i,metadata:s.length===0?g:void 0}}async function HL(t,e,n,r="scripts-only"){if(!(0,Cf.isValidPublishVersion)(e.replace(/^v/,"")))throw new Error(`Invalid publish version: ${e}`);let s=[],i=Ot.join(t.viewRoot,"scripts"),a={version:e.replace(/^v/,""),id:t.id,name:n.name,scope:n.scope,scripts:n.scripts,...n.description?{description:n.description}:{},...n.author?{author:n.author}:{},...n.tags?.length?{tags:n.tags}:{},...r==="full"?{publishBundle:"full"}:{}};s.push({path:Fy,content:(0,Ji.dumpSpotlightYaml)(a),encoding:"utf-8"}),s.push({path:vL,content:(0,Ji.dumpSpotlightYaml)({id:t.id,name:n.name,scope:n.scope,scripts:n.scripts}),encoding:"utf-8"});let c=Ot.join(t.viewRoot,"README.md");return await(0,zr.pathExists)(c)&&s.push(await Rf(c,"README.md")),await(0,zr.pathExists)(i)&&await rl(i,"scripts",Yy,async(l,f)=>{s.push(await Rf(l,f))}),r==="full"&&await zy(t.viewRoot,async(l,f)=>{s.push(await Rf(l,f))}),s}});var Zy=S(sr=>{"use strict";var jL=sr&&sr.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,s)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),xL=sr&&sr.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),BL=sr&&sr.__importStar||(function(){var t=function(e){return t=Object.getOwnPropertyNames||function(n){var r=[];for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(r[r.length]=s);return r},t(e)};return function(e){if(e&&e.__esModule)return e;var n={};if(e!=null)for(var r=t(e),s=0;s<r.length;s++)r[s]!=="default"&&jL(n,e,r[s]);return xL(n,e),n}})();Object.defineProperty(sr,"__esModule",{value:!0});sr.installSpotlightViewFromFiles=KL;sr.listInstalledSpotlightViews=qL;sr.setActiveSpotlightView=YL;sr.isSpotlightViewInstalled=XL;var mn=require("fs"),mt=BL(require("path")),Mf=Ke(),sl=en(),Gf=yo(),Lf=$f(),Mt=Nf();function Df(t){return Array.isArray(t)?t.filter(e=>typeof e=="string"&&e.trim().length>0).map(e=>mt.basename(e.trim())):[]}function Qy(t){let e=new Set,n=[];for(let r of t){let s=mt.basename(r.trim());!s||e.has(s)||(e.add(s),n.push(s))}return n}function FL(t,e){if(t==="workspace"){if(!e?.trim())throw new Error("Workspace-scoped views require an open workspace folder");return mt.join(e.trim(),Mf.AGENTIDE_DIR_NAME,"analytics")}return mt.join((0,Gf.getAgentideHome)(),"analytics")}function VL(t){let e=new Map;for(let n of t){let r=Buffer.isBuffer(n.content)?n.content:Buffer.from(n.content,"utf-8");e.set(n.path.replace(/\\/g,"/"),r)}return e}async function WL(t,e,n){await mn.promises.mkdir(mt.dirname(t),{recursive:!0});let r;try{let c=await mn.promises.readFile(t,"utf-8");r=(0,Mt.parseSpotlightYamlRecord)(c)??{version:1,activeViewId:"global",views:[]}}catch{r={version:1,activeViewId:"global",views:[]}}let s=Array.isArray(r.views)?[...r.views]:[],i=(0,Mt.normalizeSpotlightViewId)(e.id),o=s.findIndex(c=>{if(!c||typeof c!="object")return!1;let l=c;return(0,Mt.normalizeSpotlightViewId)(typeof l.id=="string"?l.id:void 0)===i}),a={id:i,name:e.name,scope:e.scope,scripts:Qy(e.scripts)};if(o>=0){if(!n)throw new Error(`Spotlight view "${i}" is already registered in ${t}`);s[o]=a}else s.push(a);r.views=s,typeof r.version!="number"&&(r.version=1),typeof r.activeViewId!="string"&&(r.activeViewId="global"),await mn.promises.writeFile(t,(0,Mt.dumpSpotlightYaml)(r),"utf-8")}async function KL(t,e){let n=VL(t),r=n.get("view.yaml"),s=n.get("panel-entry.yaml");if(!r||!s)throw new Error("Store bundle is missing view.yaml or panel-entry.yaml");let i=(0,Mt.parseSpotlightYamlRecord)(r.toString("utf-8")),o=(0,Mt.parseSpotlightYamlRecord)(s.toString("utf-8"));if(!i||!o)throw new Error("Invalid view.yaml or panel-entry.yaml in store bundle");let a=(0,Mt.normalizeSpotlightViewId)(typeof i.id=="string"?i.id:e.slug,e.slug);if(a!==(0,Mt.normalizeSpotlightViewId)(e.slug,e.slug))throw new Error(`Bundle id "${a}" does not match requested slug "${e.slug}"`);let c=i.scope==="workspace"||o.scope==="workspace"?"workspace":"global",l=typeof i.name=="string"&&i.name.trim()?i.name.trim():typeof o.name=="string"&&o.name.trim()?o.name.trim():a,f=Qy(Df(i.scripts).length?Df(i.scripts):Df(o.scripts)),u=FL(c,e.workspaceRoot),d=mt.join(u,"views",a),p=mt.join(u,"panel","views.yaml"),g=mt.join(d,"scripts");if(!e.overwrite&&await(0,sl.pathExists)(d))throw new Error(`Spotlight view "${a}" already exists at ${d}`);e.overwrite&&await mn.promises.rm(d,{recursive:!0,force:!0}),await mn.promises.mkdir(g,{recursive:!0});let m=["scripts/","assets/","images/","charts/","reports/","exports/"],h=new Set(["manifest.json","README.md"]),E=new Set(["view.yaml","panel-entry.yaml"]);for(let[T,O]of n.entries()){if(E.has(T)||!h.has(T)&&!m.some(C=>T.startsWith(C)))continue;let A=mt.resolve(d),v=mt.resolve(A,T);if(!v.startsWith(A+mt.sep))throw new Error(`Store bundle entry "${T}" escapes the install directory`);await mn.promises.mkdir(mt.dirname(v),{recursive:!0}),await mn.promises.writeFile(v,O)}let _=new Date().toISOString(),y=(0,Lf.resolveViewPublishVersionFromParsed)(i)??e.version??"1.0.0",b={version:y,id:a,name:l,description:typeof i.description=="string"?i.description:"",author:typeof i.author=="string"?i.author:void 0,scope:c,projectId:"",agentId:"",createdAt:_,updatedAt:_,scripts:f,storeVersion:y};if(Array.isArray(i.tags)&&(b.tags=i.tags.filter(T=>typeof T=="string")),await mn.promises.writeFile(mt.join(d,"view.yaml"),(0,Mt.dumpSpotlightYaml)(b),"utf-8"),await WL(p,{id:a,name:l,scope:c,scripts:f},!!e.overwrite),e.activate){let T;try{let O=await mn.promises.readFile(p,"utf-8");T=(0,Mt.parseSpotlightYamlRecord)(O)??{}}catch{T={version:1,views:[]}}T.activeViewId=a,typeof T.version!="number"&&(T.version=1),await mn.promises.writeFile(p,(0,Mt.dumpSpotlightYaml)(T),"utf-8")}return e.logger&&(0,sl.logInfo)(e.logger,`[Spotlight] Installed view "${a}" to ${d}`),{id:a,scope:c,installDir:d,viewsConfigPath:p,version:(0,Lf.resolveViewPublishVersionFromParsed)(i)??e.version??"1.0.0"}}async function qL(t){let e=[],n=new Set;async function r(s){let i=mt.join(s,"views");if(!await(0,sl.pathExists)(i))return;let o=await mn.promises.readdir(i,{withFileTypes:!0});for(let a of o){if(!a.isDirectory()||a.name.startsWith("."))continue;let c=a.name.toLowerCase();if(n.has(c))continue;let l=mt.join(i,a.name,"view.yaml");try{let f=await mn.promises.readFile(l,"utf-8"),u=(0,Mt.parseSpotlightYamlRecord)(f);if(!u)continue;let d=(0,Mt.normalizeSpotlightViewId)(typeof u.id=="string"?u.id:a.name,a.name),p=u.scope==="workspace"?"workspace":"global";n.add(c),e.push({slug:d,displayName:typeof u.name=="string"&&u.name.trim()?u.name.trim():d,description:typeof u.description=="string"?u.description.trim():void 0,tags:Array.isArray(u.tags)?u.tags.filter(g=>typeof g=="string"):["spotlight"],latestVersion:typeof u.storeVersion=="string"?u.storeVersion:(0,Lf.resolveViewPublishVersionFromParsed)(u)??"local",scope:p})}catch{}}}return await r(mt.join((0,Gf.getAgentideHome)(),"analytics")),t?.trim()&&await r(mt.join(t.trim(),Mf.AGENTIDE_DIR_NAME,"analytics")),e.sort((s,i)=>s.slug.localeCompare(i.slug))}async function YL(t,e){let n=(0,Mt.normalizeSpotlightViewId)(e,e),r;try{let s=await mn.promises.readFile(t,"utf-8");r=(0,Mt.parseSpotlightYamlRecord)(s)??{version:1,views:[]}}catch{r={version:1,views:[]}}r.activeViewId=n,typeof r.version!="number"&&(r.version=1),await mn.promises.writeFile(t,(0,Mt.dumpSpotlightYaml)(r),"utf-8")}async function XL(t,e){let n=(0,Mt.normalizeSpotlightViewId)(t,t);for(let r of[mt.join((0,Gf.getAgentideHome)(),"analytics","views",n,"view.yaml"),e?.trim()?mt.join(e.trim(),Mf.AGENTIDE_DIR_NAME,"analytics","views",n,"view.yaml"):""].filter(Boolean))if(await(0,sl.pathExists)(r))return!0;return!1}});var Kf=S(Nr=>{"use strict";var JL=Nr&&Nr.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,s)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),zL=Nr&&Nr.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),xf=Nr&&Nr.__importStar||(function(){var t=function(e){return t=Object.getOwnPropertyNames||function(n){var r=[];for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(r[r.length]=s);return r},t(e)};return function(e){if(e&&e.__esModule)return e;var n={};if(e!=null)for(var r=t(e),s=0;s<r.length;s++)r[s]!=="default"&&JL(n,e,r[s]);return zL(n,e),n}})();Object.defineProperty(Nr,"__esModule",{value:!0});Nr.storeCommand=nM;Nr.installFromStore=nw;Nr.resolvePublishBundleMode=rw;var zi=xf(require("fs/promises")),_i=xf(require("path")),ew=xf(require("os")),QL=require("zlib"),il=Ke(),ZL=td(),tw=sd(),Bs=wc(),Bf=Na(),Zo=vf(),eM=id(),Uf=$f();function Qi(){let t=process.env.AGENTHIPPO_STORE_REPO,e=Bs.DEFAULT_STORE_OWNER,n=Bs.DEFAULT_STORE_REPO;if(t){let r=t.split("/");r.length===2&&(e=r[0],n=r[1])}return{owner:e,repo:n,defaultBranch:Bs.DEFAULT_STORE_BRANCH,paths:Bs.STORE_PATHS}}function tM(){if(process.env.AGENTHIPPO_STORE_URL)return process.env.AGENTHIPPO_STORE_URL;let t=Qi();return`https://${t.owner}.github.io/${t.repo}/store-index.json`}function Ff(){return process.env.GITHUB_TOKEN||process.env.GH_TOKEN||process.env.AGENTHIPPO_GITHUB_TOKEN}async function Vf(t,e={}){let n=Ff(),r={"User-Agent":"AgentHippo-CLI",Accept:"application/vnd.github.v3+json",...e.headers||{}};return n&&(r.Authorization=`Bearer ${n}`),fetch(t,{...e,headers:r,redirect:"follow"})}var Fs={appendLine:t=>{process.env.VERBOSE==="1"&&console.error(t)}};async function nM(t){switch(t.verbose&&(process.env.VERBOSE="1"),t.action){case"search":await rM(t);break;case"install":await nw(t);break;case"publish":await sM(t);break;case"uninstall":case"remove":await aM(t);break;case"info":await cM(t);break;case"list":await lM(t);break;default:console.error(`Error: Unknown action: ${t.action}`),console.log(""),console.log("Available actions:"),console.log(" search <query> Search for skills, packs, MCP servers, engines"),console.log(" install <ref> Install artifact (e.g., skill/pdf-tools@1.0.0)"),console.log(" publish <ref> Publish engine/<id> or view/<id>[@version]"),console.log(" uninstall <ref> Uninstall artifact (currently engine/<slug>)"),console.log(" info <ref> Show artifact details"),console.log(" list List all available artifacts"),console.log(""),console.log(" Override store repo (CLI): AGENTHIPPO_STORE_REPO=owner/repo"),process.exit(1)}}var ir=Bs.STORE_ICONS;async function rM(t){let e=t.query?.toLowerCase()||"",n=t.limit||20,r=t.type,s=await Wf(),i=new tw.LocalRegistry,o=new Set((await i.listPacks()).map(g=>g.slug)),a=await i.listSkills(),c=await i.listMcp(),l=await iw(),f=new Map(a.map(g=>[g.slug,g.installedTo||[]])),u=new Map(c.map(g=>[g.slug,g.installedTo||[]])),d=s.artifacts.filter(g=>r&&g.type!==r?!1:e?[g.slug,g.displayName,g.description,...g.tags||[]].join(" ").toLowerCase().includes(e):!0);d.sort((g,m)=>{let h=g.slug.toLowerCase()===e,E=m.slug.toLowerCase()===e;return h&&!E?-1:!h&&E?1:g.slug.localeCompare(m.slug)}),d=d.slice(0,n);let p=d.map(g=>{let m=!1,h;return g.type==="pack"?m=o.has(g.slug):g.type==="skill"?(h=f.get(g.slug),m=h!==void 0&&h.length>0):g.type==="mcp"?(h=u.get(g.slug),m=h!==void 0&&h.length>0):g.type==="engine"&&(m=l.has(g.slug)),{...g,isLocal:m,installedTo:h}});if(t.json){console.log(JSON.stringify(p,null,2));return}if(p.length===0){console.log(`No results found for "${e}"`);return}console.log(""),console.log(`Found ${p.length} result(s):`),console.log("");for(let g of p){let m=g.latestVersion?`v${g.latestVersion}`:"",h=g.isLocal?ir.local:ir.remote,E=g.isLocal?` ${ir.installed}`:"";if(console.log(` ${h} ${g.type}/${g.slug} ${m}${E}`),g.description){let _=g.description.length>60?g.description.slice(0,57)+"...":g.description;console.log(` ${_}`)}g.installedTo&&g.installedTo.length>0&&console.log(` Installed to: ${g.installedTo.join(", ")}`)}console.log(""),console.log(`Legend: ${ir.local} Local ${ir.remote} Remote ${ir.installed} Installed`),console.log(""),console.log("Install with:"),console.log(" agenthippo store install <type>/<slug>"),console.log("")}async function nw(t){t.query||(console.error("Error: Artifact reference required."),console.log("Usage: agenthippo store install <type>/<slug>[@version]"),console.log(""),console.log("Examples:"),console.log(" agenthippo store install skill/pdf-tools"),console.log(" agenthippo store install pack/code-reviewer@1.0.0"),console.log(" agenthippo store install mcp/filesystem"),console.log(" agenthippo store install engine/gemini"),console.log(" agenthippo store install view/cost-ops@1.0.0"),process.exit(1));let e=ol(t.query),{type:n,slug:r,version:s}=e,i=t.workspace||process.cwd();console.log(`Installing ${n}/${r}${s?`@${s}`:""}...`);let o=s||t.version;if(!o){let f=await jf(n,r);f.length>0?(o=f.find(d=>!d.isPrerelease)?.version||f[0].version,console.log(` Using latest version: ${o}`)):(o="main",console.log(" No versions found, using main branch"))}if(n==="view"){console.log(" Downloading...");let f=await Hf(n,r,o);f.length===0&&(console.error(`Error: No files found for ${n}/${r}`),process.exit(1));let{installSpotlightViewFromFiles:u}=await Promise.resolve().then(()=>wn(Zy())),d=await u(f.map(p=>({path:p.path,content:p.content})),{slug:r,version:o,overwrite:!!t.force,workspaceRoot:i,logger:Fs});console.log(""),console.log(`\u2713 Installed view/${d.id} to:`),console.log(` ${d.installDir}`),console.log(` Panel config: ${d.viewsConfigPath}`),console.log("");return}if(n==="engine"){console.log(" Downloading...");let f=await Hf(n,r,o);f.length===0&&(console.error(`Error: No files found for ${n}/${r}`),process.exit(1));let u=await(0,Bf.installCustomEngineFromFiles)(f,{slug:r,version:o,overwrite:!!t.force,logger:Fs});console.log(""),console.log(`\u2713 Installed engine/${u.id} to:`),console.log(` ${u.installDir}`),console.log("");return}let a=t.agent||"default",c;switch(n){case"skill":c=_i.join(i,il.AGENTIDE_DIR_NAME,"agents",a,"skills",r);break;case"pack":c=t.installDir?_i.resolve(t.installDir):_i.join(ew.homedir(),il.AGENTIDE_DIR_NAME,"agents",r,o);break;case"mcp":c=_i.join(i,il.AGENTIDE_DIR_NAME,"agents",a,"mcp",r);break}try{await zi.access(c),t.force||(console.error(`Error: ${n}/${r} already exists at ${c}`),console.log("Use --force to overwrite."),process.exit(1)),console.log(" Removing existing installation..."),await zi.rm(c,{recursive:!0,force:!0})}catch{}console.log(" Downloading...");let l=await Hf(n,r,o);l.length===0&&(console.error(`Error: No files found for ${n}/${r}`),process.exit(1)),console.log(` Extracting ${l.length} files...`),await zi.mkdir(c,{recursive:!0});for(let f of l){let u=(0,ZL.safeJoin)(c,f.path);u||(console.error(`Error: refusing install \u2014 artifact path escapes destination (${f.path})`),process.exit(1)),await zi.mkdir(_i.dirname(u),{recursive:!0}),await zi.writeFile(u,f.content)}if(n==="pack"&&!t.installDir){let f=_i.join(ew.homedir(),il.AGENTIDE_DIR_NAME,"agents",r);await zi.writeFile(_i.join(f,"current.txt"),o)}console.log(""),console.log(`\u2713 Installed ${n}/${r} to:`),console.log(` ${c}`),console.log("")}function rw(t){if(t.full&&t.bundle&&t.bundle.trim().toLowerCase()!=="full"&&(console.error("Error: Cannot combine --full with --bundle scripts-only"),process.exit(1)),t.full)return"full";if(t.bundle){let e=t.bundle.trim().toLowerCase();if(e==="full"||e==="scripts-only")return e;console.error("Error: Invalid --bundle value. Use scripts-only or full."),process.exit(1)}return"scripts-only"}async function sM(t){t.query||(console.error("Error: Artifact reference required."),console.log("Usage: agenthippo store publish <engine|view>/<slug>[@version]"),console.log(""),console.log("Examples:"),console.log(" agenthippo store publish engine/rovo"),console.log(" agenthippo store publish engine/rovo@1.0.0"),console.log(" agenthippo store publish view/cost-ops@1.0.0"),console.log(" agenthippo store publish view/brand-board --bundle full"),console.log(" agenthippo store publish view/brand-board --full"),console.log(""),console.log("Requires GITHUB_TOKEN (or GH_TOKEN / AGENTHIPPO_GITHUB_TOKEN) with fork + PR access."),console.log("Override store repo (CLI): AGENTHIPPO_STORE_REPO=owner/repo"),process.exit(1));let e=ol(t.query),{type:n,slug:r,version:s}=e;if(n!=="engine"&&n!=="view"&&(console.error(`Error: store publish supports engine and view only, got ${n}/${r}`),console.log("Use: agenthippo store publish engine/<id>[@version]"),console.log(" agenthippo store publish view/<id>[@version] [--bundle full|scripts-only]"),process.exit(1)),Ff()||(console.error("Error: GitHub token required to publish."),console.log("Set GITHUB_TOKEN, GH_TOKEN, or AGENTHIPPO_GITHUB_TOKEN, then retry."),process.exit(1)),n==="engine"){await iM(t,r,s);return}await oM(t,r,s)}async function iM(t,e,n){let r=t.workspace||process.cwd(),s=await(0,Zo.resolveEngineSourceDir)(e,r);s||(console.error(`Error: Engine "${e}" not found under .agent-hippo/engines/ (workspace or home).`),process.exit(1)),console.log(`Publishing engine/${e} from ${s}...`);let i=await(0,Zo.validateEngineForPublish)(s,e);if(!i.valid){console.error(`Error: Cannot publish engine/${e}`);for(let l of i.errors)console.error(` - ${l}`);process.exit(1)}for(let l of i.warnings)console.log(` Warning: ${l}`);let o=n||t.version||i.metadata?.suggestedVersion;o||(console.error("Error: Publish version required."),console.log("Pass a version: agenthippo store publish engine/<slug>@1.0.0"),console.log("Or add a semver version field to package.json in the engine folder."),process.exit(1)),o=o.replace(/^v/,""),(0,Zo.isValidPublishVersion)(o)||(console.error(`Error: Invalid version "${o}". Use semver (e.g., 1.0.0).`),process.exit(1));let a=await(0,Zo.collectEngineFiles)(s),c=Qi();console.log(` Target store: ${c.owner}/${c.repo}`),console.log(` Version tag: engines/${e}/v${o}`),console.log(` Files: ${a.length}`),await sw({options:t,type:"engine",slug:e,version:o,files:a,installHint:`agenthippo store install engine/${e}`})}async function oM(t,e,n){let r=t.workspace||process.cwd(),s=rw(t),i=await(0,Uf.discoverPublishableViews)(r),o=i.find(d=>d.id===e);if(!o){if(console.error(`Error: Spotlight view "${e}" not found.`),console.log("Register a user view in .agent-hippo/analytics/panel/views.yaml (non-system id)."),i.length>0){console.log(""),console.log("Publishable views:");for(let d of i)console.log(` - view/${d.id} (${d.sourceLabel}, ${d.scope})`)}process.exit(1)}console.log(`Publishing view/${e} from ${o.viewRoot}...`),console.log(` Bundle: ${s==="full"?"full (scripts + assets + charts/reports/exports + manifest.json)":"scripts only"}`);let a=await(0,Uf.validateViewForPublish)(o,{expectedId:e,mode:s});if(!a.valid){console.error(`Error: Cannot publish view/${e}`);for(let d of a.errors)console.error(` - ${d}`);process.exit(1)}for(let d of a.warnings)console.log(` Warning: ${d}`);a.metadata||(console.error("Error: Validation succeeded but metadata is missing."),process.exit(1));let c=n||t.version||a.metadata.publishVersion;c||(console.error("Error: Publish version required."),console.log("Pass a version: agenthippo store publish view/<slug>@1.0.0"),console.log("Or add version to view.yaml (e.g. version: 1.0.0)."),process.exit(1)),c=c.replace(/^v/,""),(0,Zo.isValidPublishVersion)(c)||(console.error(`Error: Invalid version "${c}". Use semver (e.g., 1.0.0).`),process.exit(1));let l=await(0,Uf.collectViewFiles)(o,c,a.metadata,s),f=Qi(),u=l.filter(d=>d.encoding==="base64").length;console.log(` Target store: ${f.owner}/${f.repo}`),console.log(` Version tag: spotlight/${e}/v${c}`),console.log(` Files: ${l.length}${u>0?` (${u} binary)`:""}`),await sw({options:t,type:"view",slug:e,version:c,files:l,bundle:s,installHint:`agenthippo store install view/${e}`})}async function sw(t){let{options:e,type:n,slug:r,version:s,files:i,bundle:o,installHint:a}=t;try{let c=await(0,eM.publishToStore)({type:n,slug:r,version:s,files:i},Fs);e.json?console.log(JSON.stringify({success:!0,type:n,slug:r,version:s,bundle:o,prUrl:c.prUrl,prNumber:c.prNumber,tagName:c.tagName},null,2)):(console.log(""),console.log(`\u2713 Opened pull request for ${n}/${r} v${s}${o==="full"?" (full bundle)":""}`),console.log(` ${c.prUrl}`),console.log(""),console.log(`After merge, install with: ${a}`))}catch(c){let l=c instanceof Error?c.message:String(c);e.json?console.log(JSON.stringify({success:!1,error:l})):console.error(`Error: ${l}`),process.exit(1)}}async function aM(t){t.query||(console.error("Error: Artifact reference required."),console.log("Usage: agenthippo store uninstall engine/<slug>"),console.log(""),console.log("Examples:"),console.log(" agenthippo store uninstall engine/gemini"),process.exit(1));let{type:e,slug:n}=ol(t.query);e!=="engine"&&(console.error(`Error: store uninstall currently supports custom engines only, got ${e}/${n}`),process.exit(1));let r=await(0,Bf.uninstallCustomEngine)(n,{logger:Fs});r.removed||(console.error(`Error: engine/${r.id} is not installed.`),process.exit(1)),console.log(""),console.log(`\u2713 Uninstalled engine/${r.id} from:`),console.log(` ${r.installDir}`),console.log("")}async function cM(t){t.query||(console.error("Error: Artifact reference required."),console.log("Usage: agenthippo store info <type>/<slug>"),process.exit(1));let e=ol(t.query),r=(await Wf()).artifacts.find(i=>i.type===e.type&&i.slug===e.slug);if(r||(console.error(`Error: ${e.type}/${e.slug} not found in store.`),process.exit(1)),t.json){let i=await jf(e.type,e.slug);console.log(JSON.stringify({...r,versions:i},null,2));return}console.log(""),console.log("\u2500".repeat(60)),console.log(`${r.type}/${r.slug}`),console.log("\u2500".repeat(60)),console.log(`Name: ${r.displayName}`),console.log(`Type: ${r.type}`),console.log(`Version: ${r.latestVersion||"N/A"}`),r.author&&console.log(`Author: ${r.author}`),r.description&&console.log(`Description: ${r.description}`),r.tags?.length&&console.log(`Tags: ${r.tags.join(", ")}`);let s=await jf(e.type,e.slug);if(s.length>0){console.log(""),console.log("Available versions:");for(let i of s.slice(0,10)){let o=i.isPrerelease?" (pre-release)":"";console.log(` - ${i.version}${o}`)}s.length>10&&console.log(` ... and ${s.length-10} more`)}console.log("\u2500".repeat(60)),console.log(""),console.log("Install with:"),console.log(` agenthippo store install ${r.type}/${r.slug}`),console.log("")}async function lM(t){let e=await Wf(),n=t.type,r=new tw.LocalRegistry,s=new Set((await r.listPacks()).map(p=>p.slug)),i=await r.listSkills(),o=await r.listMcp(),a=await iw(),c=new Map(i.map(p=>[p.slug,p.installedTo||[]])),l=new Map(o.map(p=>[p.slug,p.installedTo||[]])),f=e.artifacts;n&&(f=f.filter(p=>p.type===n));let u=p=>{if(p.type==="pack")return s.has(p.slug);if(p.type==="skill"){let g=c.get(p.slug);return g!==void 0&&g.length>0}if(p.type==="mcp"){let g=l.get(p.slug);return g!==void 0&&g.length>0}return p.type==="engine"?a.has(p.slug):!1};if(t.json){let p=f.map(g=>({...g,isLocal:u(g),installedTo:g.type==="skill"?c.get(g.slug):g.type==="mcp"?l.get(g.slug):void 0}));console.log(JSON.stringify(p,null,2));return}console.log(""),console.log(`Store contains ${f.length} artifact(s):`),console.log("");let d={};for(let p of f)d[p.type]=d[p.type]||[],d[p.type].push(p);for(let p of["pack","skill","mcp","engine"]){let g=d[p]||[];if(g.length!==0){console.log(`${p}s (${g.length}):`);for(let m of g){let h=m.latestVersion?` v${m.latestVersion}`:"",E=u(m),_=E?ir.local:ir.remote,y=E?` ${ir.installed}`:"";console.log(` ${_} ${m.slug}${h}${y}`)}console.log("")}}console.log(`Legend: ${ir.local} Local ${ir.remote} Remote ${ir.installed} Installed`),console.log("")}function ol(t){try{return(0,Bs.parseStoreUrl)(t)}catch(e){let n=e instanceof Error?e.message:String(e);console.error(`Error: ${n}`),console.log("Expected format: <type>/<slug>[@version]"),console.log("Examples: skill/pdf-tools, pack/code-reviewer@1.0.0, engine/gemini, view/cost-ops"),process.exit(1)}}async function iw(){return new Set((await(0,Bf.listInstalledCustomEngines)()).map(t=>t.id))}async function Wf(){let t=tM();Fs.appendLine(`[Store] Fetching index from ${t}`);let e=await fetch(t,{headers:{"User-Agent":"AgentHippo-CLI",Accept:"application/json"}});if(e.ok)return await e.json();if(Ff()&&(e.status===403||e.status===404)){Fs.appendLine("[Store] GitHub Pages not available, trying API with auth...");let r=Qi(),s=`https://api.github.com/repos/${r.owner}/${r.repo}/contents/dist/store-index.json`;if(e=await Vf(s,{headers:{Accept:"application/vnd.github.raw+json"}}),e.ok)return await e.json()}throw new Error(`Failed to fetch store index: ${e.status} ${e.statusText}`)}async function jf(t,e){let n=Qi(),s=`${(0,Bs.getStorePath)(t)}/${e}/v`,i=`https://api.github.com/repos/${n.owner}/${n.repo}/git/refs/tags`;Fs.appendLine(`[Store] Listing versions for ${t}/${e}`);let o=await Vf(i);if(!o.ok){if(o.status===404)return[];throw new Error(`Failed to list versions: ${o.statusText}`)}let a=await o.json(),c=[];for(let{ref:l}of a){let f=l.replace("refs/tags/","");if(f.startsWith(s)){let u=f.slice(s.length-1);c.push({version:u.replace(/^v/,""),tagName:f,isPrerelease:/-(alpha|beta|rc|pre)/.test(u)})}}return c.sort((l,f)=>f.version.localeCompare(l.version,void 0,{numeric:!0}))}async function Hf(t,e,n){let r=Qi(),s=(0,Bs.getStorePath)(t),i;n==="main"||n==="latest"?i=r.defaultBranch:i=`${s}/${e}/v${n.replace(/^v/,"")}`,Fs.appendLine(`[Store] Downloading ${t}/${e} at ${i}`);let o=encodeURIComponent(i),a=`https://api.github.com/repos/${r.owner}/${r.repo}/tarball/${o}`,c=await Vf(a);if(!c.ok)throw new Error(`Failed to download: ${c.status} ${c.statusText}`);let l=Buffer.from(await c.arrayBuffer()),f=(0,QL.gunzipSync)(l),u=uM(f),d=`${s}/${e}/`,p=[];for(let[g,m]of u){let h=g.indexOf("/");if(h===-1)continue;let E=g.slice(h+1);if(E.startsWith(d)){let _=E.slice(d.length);_&&p.push({path:_,content:m})}}return p}function uM(t){let e=new Map,n=0;for(;n<t.length-512;){let r=t.subarray(n,n+512);if(r.every(c=>c===0))break;let s=r.subarray(0,100).toString("utf-8").replace(/\0/g,"").trim(),i=r.subarray(124,136).toString("utf-8").replace(/\0/g,"").trim(),o=r[156];if(!s){n+=512;continue}let a=parseInt(i,8)||0;n+=512,(o===0||o===48)&&e.set(s,Buffer.from(t.subarray(n,n+a))),n+=Math.ceil(a/512)*512}return e}});var ow=S(qf=>{"use strict";Object.defineProperty(qf,"__esModule",{value:!0});qf.parsePackInstallRef=dM;function dM(t){let e=t.trim(),n=e.lastIndexOf("@");return n>0?{slug:e.slice(0,n),version:e.slice(n+1)||void 0}:{slug:e}}});var cw=S(Ts=>{"use strict";var fM=Ts&&Ts.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,s)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),pM=Ts&&Ts.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),aw=Ts&&Ts.__importStar||(function(){var t=function(e){return t=Object.getOwnPropertyNames||function(n){var r=[];for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(r[r.length]=s);return r},t(e)};return function(e){if(e&&e.__esModule)return e;var n={};if(e!=null)for(var r=t(e),s=0;s<r.length;s++)r[s]!=="default"&&fM(n,e,r[s]);return pM(n,e),n}})();Object.defineProperty(Ts,"__esModule",{value:!0});Ts.packCommand=EM;var Zi=aw(require("fs")),cl=aw(require("path")),eo=ai(),al=Ke(),gM=Mi(),or=Po(),hM=Kf(),mM=ow(),Yf="-".repeat(62);async function EM(t){let e=t.workspace;switch(t.action){case"list":await yM(e);break;case"validate":t.name||(console.error("Error: Pack name required. Usage: agenthippo pack validate <name>"),process.exit(1)),await wM(t.name,e);break;case"info":t.name||(console.error("Error: Pack name required. Usage: agenthippo pack info <name>"),process.exit(1)),await AM(t.name,e);break;case"sign":await TM(t);break;case"verify":await bM(t);break;case"digest":await vM(t);break;case"keygen":SM(t);break;case"install":await _M(t);break;case"export":console.log("Pack export is not yet implemented.");break;default:console.error(`Error: Unknown action: ${t.action}`),console.log(""),console.log("Available actions:"),console.log(" list List installed packs"),console.log(" validate Validate a pack"),console.log(" info Show pack details"),console.log(" sign Sign a pack so a fleet can verify it before running"),console.log(" verify Verify a pack against trusted public keys"),console.log(" digest Print the pack content digest (what a signature covers)"),console.log(" keygen Generate an ES256 signing keypair"),console.log(" install Install a pack from the store to a folder"),console.log(" export Export a pack (coming soon)"),process.exit(1)}}async function _M(t){t.name?.trim()||(console.error("Error: pack slug required."),console.log("Usage: agenthippo pack install <slug>[@version] --to <dir>"),console.log(""),console.log("Examples:"),console.log(" agenthippo pack install joker1 --to ./packs/joker1"),console.log(" agenthippo pack install code-reviewer@1.0.0 --to ./packs/code-reviewer"),process.exit(1));let e=t.to?.trim();e||(console.error("Error: --to <dir> is required."),console.log("Usage: agenthippo pack install <slug>[@version] --to <dir>"),console.log(""),console.log("Same download as `agenthippo store install pack/<slug>`, extracted flat for serve/deploy."),process.exit(1));let{slug:n,version:r}=(0,mM.parsePackInstallRef)(t.name);await(0,hM.installFromStore)({action:"install",query:`pack/${n}${r?`@${r}`:""}`,workspace:t.workspace,version:r,force:t.force,installDir:cl.resolve(e),verbose:t.verbose})}async function yM(t){let e=(0,eo.listAvailablePacks)(t);if(e.length===0){console.log("No agent packs found."),console.log(""),console.log("Agent packs are stored in:"),t&&console.log(` Workspace: ${t}/${al.AGENTIDE_DIR_NAME}/agents/`),console.log(` User library: ~/${al.AGENTIDE_DIR_NAME}/agents/`),console.log(""),console.log("Create a pack with:"),console.log(` mkdir -p ~/${al.AGENTIDE_DIR_NAME}/agents/my-agent/1.0.0`),console.log(` echo "1.0.0" > ~/${al.AGENTIDE_DIR_NAME}/agents/my-agent/current.txt`),console.log(" # Add agent.yaml and AGENTS.md");return}console.log(""),console.log("Installed Agent Packs:"),console.log("");for(let n of e){let r=n.version?` (v${n.version})`:"",s=n.source==="workspace"?" [workspace]":"";console.log(` ${n.name}${r}${s}`),console.log(` ${n.path}`)}console.log("")}async function wM(t,e){console.log(`Validating pack: ${t}`),console.log("");let n=(0,eo.resolvePackPath)(t,e);n||(console.error(`Error: Pack not found: ${t}`),process.exit(1));let r=[],s=[],i=cl.join(n,"agent.yaml");Zi.existsSync(i)?console.log(" OK: agent.yaml exists"):r.push("Missing agent.yaml");try{let o=await(0,eo.loadAgentPack)(t,e);console.log(` OK: metadata.name: ${o.manifest.metadata.name}`),console.log(` OK: metadata.version: ${o.manifest.metadata.version}`),console.log(` OK: spec.engine: ${o.manifest.spec.engine}`),o.manifest.spec.model?console.log(` OK: spec.model: ${o.manifest.spec.model}`):s.push("spec.model not specified, will use default"),o.manifest.spec.cheapModel&&console.log(` OK: spec.cheapModel: ${o.manifest.spec.cheapModel}`);let a=cl.join(n,"AGENTS.md");if(Zi.existsSync(a)){let c=Zi.statSync(a);console.log(` OK: AGENTS.md exists (${(c.size/1024).toFixed(1)} KB)`)}else s.push("No AGENTS.md found")}catch(o){r.push(o instanceof Error?o.message:String(o))}if(console.log(""),s.length>0)for(let o of s)console.log(` Warning: ${o}`);if(r.length>0){for(let o of r)console.log(` Error: ${o}`);console.log(""),console.log("Pack is INVALID"),process.exit(1)}console.log(""),console.log("Pack is valid.")}async function AM(t,e){try{let n=await(0,eo.loadAgentPack)(t,e);if(console.log(""),console.log(Yf),console.log(`Agent: ${n.manifest.metadata.name}`),console.log(Yf),console.log(`Version: ${n.manifest.metadata.version}`),n.manifest.metadata.description&&console.log(`Description: ${n.manifest.metadata.description}`),n.manifest.metadata.author&&console.log(`Author: ${n.manifest.metadata.author}`),console.log(`Engine: ${n.manifest.spec.engine}`),n.manifest.spec.model&&console.log(`Model: ${n.manifest.spec.model}`),n.manifest.spec.cheapModel&&console.log(`Cheap Model: ${n.manifest.spec.cheapModel}`),console.log(`Path: ${n.packPath}`),n.manifest.spec.permissions&&(console.log(""),console.log("Permissions:"),console.log(` File Access: ${n.manifest.spec.permissions.fileAccess||"default"}`)),n.manifest.spec.mcpServers&&n.manifest.spec.mcpServers.length>0){console.log(""),console.log("MCP Servers:");for(let r of n.manifest.spec.mcpServers)console.log(` - ${r.name}`)}console.log(Yf),console.log("")}catch(n){console.error(`Error: ${n instanceof Error?n.message:n}`),process.exit(1)}}async function Xf(t,e){t||(console.error("Error: pack name or path required"),process.exit(1));let n=(0,eo.resolvePackPath)(t,e);n||(console.error(`Error: pack not found: ${t}`),process.exit(1));let r=await(0,eo.loadAgentPack)(n,e);return{packPath:r.packPath,name:r.manifest.metadata.name,version:r.manifest.metadata.version??"0.0.0"}}function SM(t){let e=t.kid||`sign-${new Date().toISOString().slice(0,10)}`,n=(0,gM.generateWarrantKeypair)(e),r=t.output;r?(Zi.writeFileSync(r,n.privateKeyPem,{mode:384}),console.log(`Private key written to ${r} (mode 0600) \u2014 keep it off shared disks.`)):console.log(n.privateKeyPem),console.log(""),console.log(`kid: ${e}`),console.log("Public half \u2014 publish this to the control plane so instances can verify:"),console.log(n.publicKeyPem.trim()),console.log(""),console.log(` curl -X POST "$CONTROL/api/keys" -H 'content-type: application/json' \\`),console.log(` -d '{"kid":"${e}","publicPem":"\u2026"}'`)}async function TM(t){let{packPath:e,name:n,version:r}=await Xf(t.name,t.workspace);t.key||(console.error("Error: --key <private-key.pem> required. Generate one with: agenthippo pack keygen -o key.pem"),process.exit(1));let s;try{s=Zi.readFileSync(t.key,"utf8")}catch(a){console.error(`Error: cannot read key ${t.key}: ${a instanceof Error?a.message:a}`),process.exit(1);return}let i=t.kid;i||(console.error("Error: --kid <id> required \u2014 it is how a verifier finds the public half in JWKS."),process.exit(1));let{digest:o}=(0,or.signPack)({packDir:e,pack:n,packVersion:r,privateKeyPem:s,kid:i});console.log(`Signed ${n}@${r}`),console.log(` digest ${o}`),console.log(` key ${i}`),console.log(` written ${cl.join(e,or.PACK_SIGNATURE_FILE)}`),console.log(""),console.log("Commit pack.sig with the pack: it travels WITH the artifact, and a fleet that"),console.log("requires signatures refuses anything whose contents no longer match it.")}async function bM(t){let{packPath:e,name:n,version:r}=await Xf(t.name,t.workspace),s=(0,or.readPackSignature)(e);s||(console.error(`UNSIGNED: no ${or.PACK_SIGNATURE_FILE} at ${e}`),console.error((0,or.describePackRefusal)({kind:"unsigned",detail:`no ${or.PACK_SIGNATURE_FILE}`,pack:n,packVersion:r,packDir:e})),process.exit(1));let i={};if(t.keys)try{i=JSON.parse(Zi.readFileSync(t.keys,"utf8"))}catch(a){console.error(`Error: cannot read keys ${t.keys}: ${a instanceof Error?a.message:a}`),process.exit(1)}else{let a=await(0,or.loadPackTrustRoot)({env:t.jwks?{...process.env,[or.PACK_JWKS_URL_ENV]:t.jwks}:process.env,leaseUrl:process.env.AGENTHIPPO_LEASE_URL});for(let c of a.warnings)console.error(`Warning: ${c}`);a.status==="unavailable"&&(console.error(`REFUSED: a trust root is configured but could not be loaded \u2014 ${a.reason}`),console.error((0,or.describePackRefusal)({kind:"trust-root-unavailable",detail:a.reason??"unavailable",pack:n,packVersion:r,packDir:e,trustRootHint:a.url?`Trust root: ${a.url}`:void 0})),process.exit(1)),i=a.keys}Object.keys(i).length===0&&(console.error("REFUSED: no trusted public keys. Pass --keys <file>, --jwks <url>, or set AGENTHIPPO_PACK_SIGNING_KEYS."),process.exit(1));let o=(0,or.verifyPack)(s,i,{packDir:e,pack:n,packVersion:r});o.ok||(console.error(`INVALID: ${o.reason}`),console.error((0,or.describePackRefusal)({kind:o.kind,detail:o.reason,pack:n,packVersion:r,packDir:e})),process.exit(1)),console.log(`OK: ${n}@${r} verified`),console.log(` digest ${o.claims.digest}`),console.log(" NOTE: .claude/, .codex/ and .agent-hippo/ ARE covered by this digest \u2014 they carry hooks"),console.log(" and other executable content, and were previously outside the signature.")}async function vM(t){let{packPath:e,name:n,version:r}=await Xf(t.name,t.workspace);console.log(`${(0,or.computePackDigest)(e)} ${n}@${r}`)}});var uw=S(ea=>{"use strict";Object.defineProperty(ea,"__esModule",{value:!0});ea.parseStrictJsonConfig=lw;ea.collectMissingChannelEnvSecrets=IM;ea.disableChannelsInConfigText=PM;var OM=8;function yi(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function lw(t){try{return JSON.parse(t)}catch{return}}function Jf(t,e,n){if(!(n>OM)){if(Array.isArray(t)){for(let r of t)Jf(r,e,n+1);return}if(yi(t)){if(t.source==="env"&&typeof t.id=="string"&&t.id.trim()){e.add(t.id.trim());return}for(let r of Object.values(t))Jf(r,e,n+1)}}}function IM(t,e){if(!yi(t)||!yi(t.channels))return[];let n=[];for(let[r,s]of Object.entries(t.channels)){if(!yi(s)||s.enabled===!1)continue;let i=new Set;Jf(s,i,0);let o=[...i].filter(a=>!e[a]?.trim()).sort();o.length&&n.push({channel:r,envVars:o})}return n}function PM(t,e){let n=lw(t);if(!(!yi(n)||!yi(n.channels))){for(let r of e){let s=n.channels[r];yi(s)&&(s.enabled=!1)}return`${JSON.stringify(n,null,2)}
614
+ `}}});var fw=S(ll=>{"use strict";Object.defineProperty(ll,"__esModule",{value:!0});ll.quoteWindowsCommandLineArg=dw;ll.buildWindowsArgumentLine=NM;function dw(t){return t.length===0?'""':/[ \t"]/u.test(t)?`"${t.replace(/(\\*)"/g,'$1$1\\"').replace(/(\\+)$/g,"$1$1")}"`:t}function NM(t){return t.map(e=>dw(e)).join(" ")}});var pw=S(zf=>{"use strict";Object.defineProperty(zf,"__esModule",{value:!0});zf.isGatewayScopeAuthError=RM;function RM(t){let e=t.toLowerCase();return e.includes("missing scope")||e.includes("operator.admin")}});var gw=S(ar=>{"use strict";Object.defineProperty(ar,"__esModule",{value:!0});ar.ANYWHERE_INSTALL_SOURCE_FORMS=ar.ANYWHERE_CONFIG_TEMPLATE_ENV=ar.ANYWHERE_SETUP_SCRIPT_ENV=ar.ANYWHERE_INSTALL_SOURCE_ENV=void 0;ar.validateAnywhereInstallSource=MM;ar.ANYWHERE_INSTALL_SOURCE_ENV="AH_INSTALL_SOURCE";ar.ANYWHERE_SETUP_SCRIPT_ENV="AH_SETUP_SCRIPT";ar.ANYWHERE_CONFIG_TEMPLATE_ENV="AH_CONFIG_TEMPLATE";var CM=/^(?:@[a-z0-9][a-z0-9._-]*\/)?[a-z0-9][a-z0-9._-]*(?:@[a-zA-Z0-9^~*><=][a-zA-Z0-9.^~*+><=|_-]*)?$/,kM=/^github:[A-Za-z0-9][A-Za-z0-9._-]*\/[A-Za-z0-9][A-Za-z0-9._-]*(?:#[A-Za-z0-9._/-]+)?$/,$M=/^https:\/\/[A-Za-z0-9._-]+(?::\d+)?\/[A-Za-z0-9._~!$'()*+,;=:@%/-]*\.(?:tgz|tar\.gz)$/,DM=/^(?:\.{1,2})?\/[^\0<>"'`;|&$\n\r]*$/,LM=/^[A-Za-z]:[\\/][^\0<>"'`;|&$\n\r]*$/;ar.ANYWHERE_INSTALL_SOURCE_FORMS="accepted forms are: an npm specifier (e.g. @agenthippo-ai/hippoclaw@2026.7.28), github:owner/repo[#ref], an https:// .tgz/.tar.gz URL, or a local path";function MM(t){let e=r=>({ok:!1,reason:`${r} \u2014 ${ar.ANYWHERE_INSTALL_SOURCE_FORMS}`}),n=t.trim();return n?n!==t?e("it has leading or trailing whitespace"):CM.test(n)||kM.test(n)||$M.test(n)||DM.test(n)||LM.test(n)?{ok:!0}:e("it is not one of the accepted forms"):e("it is empty")}});var Dw=S(D=>{"use strict";var GM=D&&D.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,s)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),UM=D&&D.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),_l=D&&D.__importStar||(function(){var t=function(e){return t=Object.getOwnPropertyNames||function(n){var r=[];for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(r[r.length]=s);return r},t(e)};return function(e){if(e&&e.__esModule)return e;var n={};if(e!=null)for(var r=t(e),s=0;s<r.length;s++)r[s]!=="default"&&GM(n,e,r[s]);return UM(n,e),n}})();Object.defineProperty(D,"__esModule",{value:!0});D.GatewayLifecycleManager=D.validateAnywhereInstallSource=D.ANYWHERE_SETUP_SCRIPT_ENV=D.ANYWHERE_INSTALL_SOURCE_ENV=D.ANYWHERE_CONFIG_TEMPLATE_ENV=D.AGENT_ANYWHERE_LABEL=void 0;D.detectGateway=pl;var N=_l(require("vscode")),gl=require("child_process"),Qf=require("crypto"),Tw=require("util"),G=_l(require("fs")),V=_l(require("path")),es=_l(require("os")),be=yo(),Zf=pa(),ep=uw(),HM=fw(),jM=pw(),tp=Yd(),np=Ke(),Gt=(0,Tw.promisify)(gl.exec),xM=(0,Tw.promisify)(gl.execFile),le=process.platform==="win32",bw=process.platform==="darwin";function hw(t,e){if(e)for(let n of e.split(V.delimiter)){let r=n.trim();r.length>0&&t.add(r)}}function BM(){let t=new Set,e=es.homedir();hw(t,"/usr/bin:/bin:/usr/sbin:/sbin"),hw(t,process.env.PATH);let n=[V.join(e,".local","bin"),V.join(e,"Library","pnpm"),V.join(e,".local","share","pnpm"),V.join(e,".npm-global","bin"),V.join(e,".volta","bin"),V.join(e,".fnm"),V.join(e,".asdf","shims"),"/opt/homebrew/bin","/usr/local/bin"];for(let i of n)G.existsSync(i)&&t.add(i);let r=process.env.NVM_DIR||V.join(e,".nvm"),s=V.join(r,"versions","node");if(G.existsSync(s))try{let i=G.readdirSync(s,{withFileTypes:!0}).filter(o=>o.isDirectory()).map(o=>o.name).sort().reverse().slice(0,8);for(let o of i){let a=V.join(s,o,"bin");G.existsSync(a)&&t.add(a)}}catch{}return Array.from(t).join(V.delimiter)}function ul(){return bw&&G.existsSync("/bin/zsh")?"/bin/zsh":"/bin/bash"}function dl(t){return bw?["-lic",t]:["-lc",t]}function rp(){if(!le)return{...process.env,PATH:BM(),npm_config_script_shell:"/bin/sh"}}D.AGENT_ANYWHERE_LABEL="Agent Anywhere";var to=`${D.AGENT_ANYWHERE_LABEL} Setup`,wi=`${D.AGENT_ANYWHERE_LABEL} Uninstall`,Ai=18789,sp=V.join(es.homedir(),".openclaw","gateway.log"),mw="Open Gateway Log";function FM(t){return t.replace(/\x1b\[[0-9;]*m/g,"")}function VM(t){try{if(!G.existsSync(t))return;let n=G.readFileSync(t,"utf8").split(/\r?\n/).filter(r=>r.trim());for(let r=n.length-1;r>=Math.max(0,n.length-50);r--){let s=FM(n[r]).trim();if(!s||/Doctor warnings|force: no listeners/i.test(s))continue;let i=s.match(/Gateway failed to start:\s*(.+)/i);if(i?.[1])return i[1].trim().slice(0,160);if(/SecretRefResolutionError|is missing or empty|required secrets are unavailable/i.test(s))return s.replace(/^\d{4}-\d{2}-\d{2}T[\d:.+-]+\s*/,"").slice(0,160);if(/errorCode=|errorMessage=/i.test(s))return s.slice(0,160)}}catch{}}async function ta(t){let e=VM(t),n=e?`${D.AGENT_ANYWHERE_LABEL}: Gateway failed to start. ${e}`:`${D.AGENT_ANYWHERE_LABEL}: Gateway failed to start.`;if(await N.window.showErrorMessage(n,mw)===mw)try{let s=await N.workspace.openTextDocument(N.Uri.file(t));await N.window.showTextDocument(s,{preview:!1})}catch(s){let i=s instanceof Error?s.message:String(s);N.window.showErrorMessage(`${D.AGENT_ANYWHERE_LABEL}: Could not open gateway log (${i}). Path: ${t}`)}}var WM=3e4,KM=le?75e3:2e4,qM=3e4,yl=be.PID_FILES.gateway(),Qr="hippoclaw",gp=["@agenthippo-ai/hippoclaw","openclaw"],hp=V.join(es.homedir(),".agenthippo","gateway"),hl=V.join(hp,"install.json"),ap=V.join(hp,"install-status.json"),mp=le?V.join(process.env.LOCALAPPDATA||V.join(es.homedir(),"AppData","Local"),"AgentHippo","bin"):V.join(es.homedir(),".local","bin"),vw=V.join(mp,le?"hippoclaw.cmd":"hippoclaw"),cp=V.join(mp,le?"openclaw.cmd":"openclaw"),lp=le?"REM Managed by Agent Anywhere":"# Managed by Agent Anywhere",lt=gw();Object.defineProperty(D,"ANYWHERE_CONFIG_TEMPLATE_ENV",{enumerable:!0,get:function(){return lt.ANYWHERE_CONFIG_TEMPLATE_ENV}});Object.defineProperty(D,"ANYWHERE_INSTALL_SOURCE_ENV",{enumerable:!0,get:function(){return lt.ANYWHERE_INSTALL_SOURCE_ENV}});Object.defineProperty(D,"ANYWHERE_SETUP_SCRIPT_ENV",{enumerable:!0,get:function(){return lt.ANYWHERE_SETUP_SCRIPT_ENV}});Object.defineProperty(D,"validateAnywhereInstallSource",{enumerable:!0,get:function(){return lt.validateAnywhereInstallSource}});function YM(t){return t?t.startsWith("\\")||t.startsWith("/")||t.startsWith(".")||/^[A-Za-z]:/.test(t)||t.startsWith("github:")||t.startsWith("git+http:")||t.startsWith("git+https:")||/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+(?:#.+)?$/.test(t):!1}var Ew=[["npmInstallComplete","npm install complete"],["wrapperExists","wrapper exists"],["configExists","config exists"],["distExists","dist exists"],["webUiExists","web UI exists"],["finalCheckPassed","final check passed"]];function Zr(t){return t.replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function Ow(t,e){let n=Zr(t),r=Zr(e);return n===r||n.startsWith(`${r}/`)}function Si(){try{if(!G.existsSync(hl))return;let t=G.readFileSync(hl,"utf8").replace(/^/,"");return JSON.parse(t)}catch{return}}function XM(t){G.mkdirSync(hp,{recursive:!0}),G.writeFileSync(hl,JSON.stringify(t,null,2),"utf8")}function Ep(t){let e=t?.packageRoot;if(!(!e||!G.existsSync(e)))try{return G.realpathSync(e)}catch{return e}}function JM(t){if(!t)return;let e=Si();return!e?.entryScriptPath&&!e?.cliPath?t:(e.wrapperPath||e.openclawWrapperPath)&&[e.wrapperPath,e.openclawWrapperPath].some(n=>n&&Zr(t)===Zr(n))&&(e.entryScriptPath&&G.existsSync(e.entryScriptPath)||e.cliPath&&G.existsSync(e.cliPath))?e.entryScriptPath&&G.existsSync(e.entryScriptPath)?e.entryScriptPath:e.cliPath:t}function Iw(t){if(!t)return;let e=Si();return e?.cliPath&&[e.wrapperPath,e.openclawWrapperPath,e.entryScriptPath].some(n=>n&&Zr(t)===Zr(n))&&G.existsSync(e.cliPath)?e.cliPath:t}function Pw(t){for(let e of[t?.wrapperPath,t?.openclawWrapperPath,t?.cliPath])if(e&&G.existsSync(e))return e}function Nw(t){let e=t?.nodePath;if(!(!e||!G.existsSync(e)))return e}function zM(t){let e=t?.entryScriptPath;if(!(!e||!G.existsSync(e)))return e}async function up(t,e){let n=e??Si(),r=t??Pw(n)??await $w(),s=Iw(r)??r;if(!s||!G.existsSync(s))return;let i=Ep(n)??_p(s);if(!i)return;let o=Nw(n)??ZM(s),a=zM(n)??QM(i);if(!(!o||!a))return{launcherPath:s,packageRoot:i,nodePath:o,entryScriptPath:a}}function Rw(t){try{return G.existsSync(t)?G.readFileSync(t,"utf8").includes(lp):!1}catch{return!1}}function _w(t,e,n){G.mkdirSync(V.dirname(n),{recursive:!0});let r=le?`@echo off\r
615
+ ${lp}\r
615
616
  "${t}" "${e}" %*\r
616
617
  `:`#!/bin/sh
617
- ${cp}
618
+ ${lp}
618
619
  exec "${t}" "${e}" "$@"
619
- `;return G.writeFileSync(n,r,le?"ascii":"utf8"),le||G.chmodSync(n,493),n}function YM(t){if(t)try{let e=V.join(t,"package.json");if(!G.existsSync(e))return;let n=JSON.parse(G.readFileSync(e,"utf8")),r=n.bin;typeof r=="string"&&(r={[n.name||"openclaw"]:r});let s=[...new Set(["hippoclaw","openclaw",...Object.keys(r||{})])];for(let i of s){let o=r&&typeof r[i]=="string"?r[i]:void 0;if(!o)continue;let a=V.resolve(t,o);if(G.existsSync(a))return a}}catch{}}function XM(t){let e=Tw(t)??t;if(e){let n=V.join(V.dirname(e),le?"node.exe":"node");if(G.existsSync(n))return n}for(let n of(0,be.getCommonBinaryPaths)("node"))if(G.existsSync(n))return n}function hw(){for(let t of[Aw,ap])if(Ow(t))try{G.rmSync(t,{force:!0})}catch{}try{G.rmSync(gl,{force:!0})}catch{}}function Iw(t,e){if(G.existsSync(e))try{t.add(G.realpathSync(e))}catch{t.add(e)}}function mw(t,e){for(let n of pp)Iw(t,V.join(e,n))}function JM(){let t=ts.homedir(),e=process.env.NVM_DIR||V.join(t,".nvm"),n=V.join(e,"versions","node");if(!G.existsSync(n))return[];let r=[];try{for(let s of G.readdirSync(n,{withFileTypes:!0}))s.isDirectory()&&r.push(...pp.map(i=>V.join(n,s.name,"lib","node_modules",i)))}catch{}return r}async function ta(){let t=new Set,e=Si(),n=mp(e);n&&G.existsSync(n)&&t.add(n);let r=V.join(ts.homedir(),".agenthippo","tools","node");if(G.existsSync(r))try{let s=G.readdirSync(r,{withFileTypes:!0});for(let i of s)if(i.isDirectory())for(let o of pp){let a=V.join(r,i.name,...le?["node_modules"]:["lib","node_modules"],o);if(G.existsSync(a))try{t.add(G.realpathSync(a))}catch{t.add(a)}}}catch{}mw(t,V.join(ts.homedir(),".npm-global",...le?["node_modules"]:["lib","node_modules"]));for(let s of JM())Iw(t,s);try{let{stdout:s}=await Gt("npm root -g",{timeout:3e3}),i=s.trim();i&&mw(t,i)}catch{}return Array.from(t)}function Ep(t){try{let e=KM(t)??t,n=G.realpathSync(e),r=V.dirname(n);for(let s=0;s<8;s++){if(G.existsSync(V.join(r,"package.json")))return r;let i=V.dirname(r);if(i===r)break;r=i}}catch{}}async function up(t,e){let n=e??await ta();if(n.length===0)return!1;let r=Ep(t);return r?n.some(s=>Sw(r,s)):!1}async function zM(t){if(!Number.isFinite(t)||t<1||t>65535)return[];if(le)try{let e=`$listenerPids=Get-NetTCPConnection -LocalPort ${t} -State Listen -ErrorAction SilentlyContinue | Select-Object -ExpandProperty OwningProcess -Unique; foreach($listenerProcId in $listenerPids){$proc=Get-CimInstance Win32_Process -Filter \\"ProcessId=$listenerProcId\\" -ErrorAction SilentlyContinue; if($proc -and $proc.CommandLine){$proc.CommandLine}}`,{stdout:n}=await Gt(`powershell.exe -NoProfile -Command "${e}"`,{timeout:1e4});return n.split(/\r?\n/).map(r=>r.trim()).filter(r=>r.length>0)}catch{return[]}try{let{stdout:e}=await Gt(`lsof -nP -iTCP:${t} -sTCP:LISTEN -t 2>/dev/null || true`,{timeout:5e3}),n=[...new Set(e.trim().split(/\n/).map(s=>s.trim()).filter(s=>/^\d+$/.test(s)))],r=[];for(let s of n)try{let{stdout:i}=await Gt(`ps -p ${s} -o command=`,{timeout:3e3}),o=i.trim();o&&r.push(o)}catch{}return r}catch{return[]}}async function hl(t,e){let n=await ta();if(n.length===0)return!1;let r=!1,s="";if(e&&(r=await up(e,n),r))try{s=G.realpathSync(e)}catch{s=e}let i=await zM(t);if(i.length===0)return!1;let o=Si(),a=vw(o),c=[...i];a&&c.push(a);let l=n.map(u=>es(u));a&&l.push(es(V.dirname(a)));let f=s?es(s):"";for(let u of c){let d=es(u);if(d.includes(Zr)&&r||f&&d.includes(f)||l.some(p=>d.includes(p)))return!0}return!1}async function fl(t=Ai){let[e,n]=await Promise.all([(0,be.probePort)(t),ta()]),r=await Nw(n),s;if(r)try{let{stdout:a}=await Gt(`"${r}" --version`,{timeout:3e3});s=a.trim().split(`
620
- `)[0]}catch{}let i=!!r&&!!s,o=e?await hl(t,r):!1;return{installed:i,binaryPath:r,version:s,running:o,port:t}}async function Pw(t,e){try{if(le){let n=await lp(t);if(n){e("Running gateway stop via managed node runtime..."),await GM(n.nodePath,[n.entryScriptPath,"gateway","stop"],{timeout:2e4,windowsHide:!0});return}}e(`Running ${V.basename(t)} gateway stop (CLI)...`),await Gt(`"${t}" gateway stop`,{timeout:2e4,windowsHide:!0})}catch{}}function QM(){try{if(!G.existsSync(op))return;let t=G.readFileSync(op,"utf8").replace(/^\uFEFF/,"");return JSON.parse(t)}catch{return}}function ZM(t){return t?.phase==="complete"&&t.steps?.finalCheckPassed===!0}function eG(t){if(!t)return{message:"Waiting for setup status...",percent:0};if(t.phase==="failed")return{message:t.lastError?.trim()||t.message?.trim()||"Install failed.",percent:100};let e=pw.filter(([i])=>t.steps?.[i]).map(([,i])=>i),n=e.length,r=t.message?.trim()||"Installing Agent Anywhere...";return{message:e.length>0?`${r} (done: ${e.join(", ")})`:r,percent:Math.min(95,Math.floor(n/pw.length*100))}}function dl(t){return t.replace(/'/g,"''")}async function eo(t){if(!Number.isFinite(t)||t<1||t>65535)return[];if(le)try{let{stdout:e}=await Gt(`powershell.exe -NoProfile -Command "Get-NetTCPConnection -LocalPort ${t} -State Listen -ErrorAction SilentlyContinue | ForEach-Object { $_.OwningProcess } | Sort-Object -Unique"`,{timeout:1e4,windowsHide:!0});return[...new Set(e.trim().split(/\r?\n/).map(n=>parseInt(n.trim(),10)).filter(n=>Number.isInteger(n)&&n>0))]}catch{return[]}try{let{stdout:e}=await Gt(`lsof -nP -iTCP:${t} -sTCP:LISTEN -t 2>/dev/null || true`,{timeout:5e3});return[...new Set(e.trim().split(/\n/).map(n=>parseInt(n.trim(),10)).filter(n=>Number.isInteger(n)&&n>0))]}catch{return[]}}async function ml(t,e,n=8e3){let r=[...new Set(e.filter(o=>Number.isInteger(o)&&o>0))],s=Date.now()+n,i=0;for(;Date.now()<s;){let o=await(0,be.probePort)(t),a=r.filter(c=>(0,be.isProcessRunning)(c));if(!o&&a.length===0){if(i===0&&(i=Date.now()),Date.now()-i>=750)return!0}else i=0;await new Promise(c=>setTimeout(c,250))}return!await(0,be.probePort)(t)&&r.every(o=>!(0,be.isProcessRunning)(o))}function Ew(t,e,n){if(e&&e>0)try{process.kill(-e,n);return}catch{}try{t.kill(n)}catch{}}async function dp(t){if(!(!Number.isFinite(t)||t<1||t>65535)){if(le){try{let{stdout:e}=await Gt(`powershell.exe -NoProfile -Command "Get-NetTCPConnection -LocalPort ${t} -State Listen -ErrorAction SilentlyContinue | ForEach-Object { $_.OwningProcess } | Sort-Object -Unique"`,{timeout:1e4}),n=e.trim().split(/\r?\n/).map(r=>r.trim()).filter(r=>/^\d+$/.test(r));for(let r of n)await Gt(`taskkill /F /T /PID ${r}`,{timeout:5e3}).catch(()=>{})}catch{}return}try{let{stdout:e}=await Gt(`lsof -nP -iTCP:${t} -sTCP:LISTEN -t 2>/dev/null || true`,{timeout:5e3}),n=[...new Set(e.trim().split(/\n/).map(i=>i.trim()).filter(i=>/^\d+$/.test(i)))];for(let i of n)await Gt(`kill ${i}`,{timeout:3e3}).catch(()=>{});await new Promise(i=>setTimeout(i,800));let{stdout:r}=await Gt(`lsof -nP -iTCP:${t} -sTCP:LISTEN -t 2>/dev/null || true`,{timeout:5e3}),s=[...new Set(r.trim().split(/\n/).map(i=>i.trim()).filter(i=>/^\d+$/.test(i)))];for(let i of s)await Gt(`kill -9 ${i}`,{timeout:3e3}).catch(()=>{})}catch{}}}async function _w(t,e,n){let r=await eo(t);if(e&&(await Pw(e,n),await ml(t,r)))return!0;n(`Stopping listener(s) on port ${t}...`),await dp(t);let s=[...r];return t!==Ai&&await(0,be.probePort)(Ai)&&(s.push(...await eo(Ai)),n(`Stopping listener(s) on port ${Ai} (default gateway port)...`),await dp(Ai)),ml(t,s)}async function tG(t,e,n){await(0,be.writePidFile)(_l,t,e,n)}async function sp(){await(0,be.removePidFile)(_l)}async function ip(t){let e=await(0,be.checkPidFileWithCleanup)(_l);if(!e)return null;let n=e.metadata?.[0]?parseInt(e.metadata[0],10):void 0,r=e.metadata?.[1]||void 0,s=n??t;return!await(0,be.probePort)(s)||!await hl(s,r)?null:{installed:!0,binaryPath:r,running:!0,port:s}}async function Nw(t){let e=t??await ta();return nG(e)}async function nG(t){let e=Si(),n=mp(e),r=bw(e);if(n&&r&&G.existsSync(r)&&(t.length===0||t.some(a=>Sw(n,a))))return r;let s=await(0,be.findBinaryCached)(Zr,(0,be.getCommonBinaryPaths)(Zr));if(s&&await up(s,t))return s;let i=le?`${Zr}.cmd`:Zr;for(let o of t){let a=le?V.dirname(V.dirname(o)):V.dirname(V.dirname(V.dirname(o))),c=le?V.join(a,i):V.join(a,"bin",i);if(G.existsSync(c)&&await up(c,t))return c}}var fp=class{outputChannel;process=null;healthCheckTimer=null;_status="not-installed";_bridgeConnected=!1;_lastDetection=null;_bridgeRef=null;_gatewayInstallInProgress=!1;_installProgressMessage;_installSetupTerminal=null;_gatewayUninstallInProgress=!1;_uninstallSetupTerminal=null;_startInFlight=null;_lastStartInProgressNoticeAt=0;_hasConfiguredChannelsCache;disposables=[];statusBarItem;_onStatusChange=new N.EventEmitter;onStatusChange=this._onStatusChange.event;setBridgeRef(e){this._bridgeRef=e}constructor(e,n){this.outputChannel=e,this.statusBarItem=N.window.createStatusBarItem(N.StatusBarAlignment.Right,100),this.statusBarItem.command="agentide.anywhere.toggle",this.statusBarItem.name=D.AGENT_ANYWHERE_LABEL,N.commands.executeCommand("setContext","agentide.anywhere.connected",this._bridgeConnected),this.disposables.push(N.window.onDidCloseTerminal(r=>{this._installSetupTerminal===r&&(this._installSetupTerminal=null,this._gatewayInstallInProgress&&this.reconcileInstallProgressState()),this._uninstallSetupTerminal===r&&(this._uninstallSetupTerminal=null,this._gatewayUninstallInProgress&&this.reconcileUninstallProgressState())})),this.registerCommands(),this.registerConfigWatcher(),this.initializeLazy()}setInstallProgressFlag(e,n){this._gatewayInstallInProgress!==e&&(this._gatewayInstallInProgress=e,this.log(`Install flag -> ${e?"true":`false (${n})`}`))}get status(){return this._status}get lastDetection(){return this._lastDetection}async initializeLazy(){if(this.getConfig("hidden",!1)){this.statusBarItem.hide();return}if(!this.getConfig("enabled",!1)){this.updateStatusBar("not-installed"),this.statusBarItem.show();return}let r=this.getGatewayPort(),s=await ip(r);s?(this._lastDetection=s,this.setStatus("running")):await this.detect(),this.getConfig("autoStart",!1)&&this._lastDetection?.installed&&!this._lastDetection?.running&&(this.log(`Auto-starting gateway (${(0,tp.toSettingsDisplayKey)("agentide.anywhere.autoStart")} = true)`),await this.start())}registerCommands(){this.disposables.push(N.commands.registerCommand("agentide.anywhere.toggle",()=>this.toggle()),N.commands.registerCommand("agentide.anywhere.install",()=>this.install()),N.commands.registerCommand("agentide.anywhere.uninstall",()=>this.uninstall()),N.commands.registerCommand("agentide.anywhere.start",()=>this.start()),N.commands.registerCommand("agentide.anywhere.stop",()=>this.stop()),N.commands.registerCommand("agentide.anywhere.status",()=>this.showStatus()),N.commands.registerCommand("agentide.anywhere.openConfig",()=>this.openConfig()),N.commands.registerCommand("agentide.anywhere.connect",()=>this.connectBridge()),N.commands.registerCommand("agentide.anywhere.disconnect",()=>this.disconnectBridge()),N.commands.registerCommand("agentide.anywhere.openWebUI",()=>this.openWebUI()),N.commands.registerCommand("agentide.anywhere.detect",()=>this.detect()),N.commands.registerCommand("agentide.anywhere.meetAgent",()=>this.showMeetAgentPicker()))}setBridgeConnected(e){this._bridgeConnected=e,N.commands.executeCommand("setContext","agentide.anywhere.connected",e)}registerConfigWatcher(){this.disposables.push(N.workspace.onDidChangeConfiguration(e=>{e.affectsConfiguration("agentide.anywhere")&&this.initializeLazy()}))}async toggle(){if(!this.getConfig("hidden",!1)){if(this._gatewayInstallInProgress){await this.showGatewayInstallInProgressPrompt();return}if(this._gatewayUninstallInProgress){await this.showGatewayUninstallInProgressPrompt();return}if(this._startInFlight){this.setStatus("starting");let n=Date.now();n-this._lastStartInProgressNoticeAt>4e3&&(this._lastStartInProgressNoticeAt=n,N.window.showInformationMessage(`${D.AGENT_ANYWHERE_LABEL}: Starting gateway... please wait.`));return}switch(this.setBridgeConnected(this._bridgeRef?.isConnected??!1),this._status){case"error":{this._lastDetection?.installed===!0?await this.showDisconnectedQuickMenu():await this.showNotInstalledQuickMenu();break}case"starting":case"stopping":N.window.showInformationMessage(`${D.AGENT_ANYWHERE_LABEL}: Operation in progress...`);break;case"running":this._bridgeConnected?await this.showConnectedQuickMenu():await this.showDisconnectedQuickMenu();break;case"installed":await this.showDisconnectedQuickMenu();break;case"not-installed":default:{if(this._lastDetection?.installed===!0){await this.showDisconnectedQuickMenu();break}await this.showNotInstalledQuickMenu();break}}}}queueBackgroundDetect(e){this._gatewayInstallInProgress||this._gatewayUninstallInProgress||this._startInFlight||this._status==="starting"||this._status==="stopping"||setTimeout(()=>{this._gatewayInstallInProgress||this._gatewayUninstallInProgress||this._startInFlight||this._status==="starting"||this._status==="stopping"||this.detect().catch(n=>{this.log(`Background detect failed after ${e}: ${n instanceof Error?n.message:String(n)}`)})},100)}async showConnectedQuickMenu(){let n=this._hasConfiguredChannelsCache??await this.refreshHasConfiguredChannels()?"Meet at...":"Web UI",r=N.window.showInformationMessage(`${D.AGENT_ANYWHERE_LABEL} is running (bridge: connected).`,n,"Disconnect","Ask Agent Hippo","More");switch(this.queueBackgroundDetect("opening connected menu"),this.refreshHasConfiguredChannels(),await r){case"Meet at...":await this.showMeetAgentPicker();break;case"Web UI":await this.openWebUI();break;case"Disconnect":await this.disconnectBridge();break;case"More":await this.showMaintenanceQuickMenu();break;case"Ask Agent Hippo":await this.openAskAgentHippoChat();break}}async showDisconnectedQuickMenu(){let e=N.window.showInformationMessage(`${D.AGENT_ANYWHERE_LABEL}: Disconnected.`,"Connect","Reinstall","Ask Agent Hippo","More");switch(this.queueBackgroundDetect("opening disconnected menu"),await e){case"Connect":await this.start(),this._status==="running"&&(await this.connectBridge(),this.setBridgeConnected(this._bridgeRef?.isConnected??!1),this._bridgeConnected&&await this.showConnectedQuickMenu());break;case"Reinstall":await this.install();break;case"More":await this.showMaintenanceQuickMenu();break;case"Ask Agent Hippo":await this.openAskAgentHippoChat();break}}async showGatewayInstallInProgressPrompt(){await N.window.showInformationMessage(`${D.AGENT_ANYWHERE_LABEL}: Install in progress. Follow the "${D.AGENT_ANYWHERE_LABEL} Setup" terminal; when it finishes, status updates automatically.`,"Show Setup Terminal","OK")==="Show Setup Terminal"&&(this.revealInstallSetupTerminal()||await this.showMissingInstallSetupTerminalPrompt())}async showMissingInstallSetupTerminalPrompt(){(await this.reconcileInstallProgressState())?.installed?N.window.showInformationMessage(`${D.AGENT_ANYWHERE_LABEL}: Install completed. Status has been refreshed.`):N.window.showWarningMessage(`${D.AGENT_ANYWHERE_LABEL}: Setup terminal is no longer available. Install did not complete; run Install again to relaunch setup.`)}async showGatewayUninstallInProgressPrompt(){await N.window.showInformationMessage(`${D.AGENT_ANYWHERE_LABEL}: Uninstall in progress. Follow the "${wi}" terminal; when it finishes, status updates automatically.`,"Show Uninstall Terminal","OK")==="Show Uninstall Terminal"&&(this.revealUninstallSetupTerminal()||await this.showMissingUninstallSetupTerminalPrompt())}async showMissingUninstallSetupTerminalPrompt(){let e=await this.reconcileUninstallProgressState();e&&!e.installed&&!e.running?N.window.showInformationMessage(`${D.AGENT_ANYWHERE_LABEL}: Uninstall completed. Status has been refreshed.`):N.window.showWarningMessage(`${D.AGENT_ANYWHERE_LABEL}: Uninstall terminal is no longer available. Uninstall may still be running or did not complete; run Status to confirm.`)}revealInstallSetupTerminal(){let e=this._installSetupTerminal??N.window.terminals.find(n=>n.name===Zi||n.name.startsWith(`${Zi} `))??null;return e?(this._installSetupTerminal=e,e.show(),!0):!1}revealUninstallSetupTerminal(){let e=this._uninstallSetupTerminal??N.window.terminals.find(n=>n.name===wi||n.name.startsWith(`${wi} `))??null;return e?(this._uninstallSetupTerminal=e,e.show(),!0):!1}async reconcileInstallProgressState(){if(!this._gatewayInstallInProgress)return this._lastDetection;if(this.revealInstallSetupTerminal())return this._lastDetection;if(await this.sleep(2e3),this.revealInstallSetupTerminal())return this._lastDetection;(0,be.clearBinaryCache)(Zr),(0,be.clearBinaryCache)("openclaw");let e=await this.detectGatewayState(this.getGatewayPort());return this._lastDetection=e,e.running?this.finishInstallUiState("running","terminal reconciliation"):e.installed?this.finishInstallUiState("installed","terminal reconciliation"):(this.log("Setup terminal closed before gateway install was detected"),this.setInstallProgressFlag(!1,"terminal reconciliation"),this._installProgressMessage=void 0,this.setStatus("not-installed")),e}finishInstallUiState(e,n){this.setInstallProgressFlag(!1,n),this._installProgressMessage=void 0,this.setStatus(e)}readInstallStatusSnapshot(){return QM()}getInstallProgressSummary(e){return eG(e)}async detectGatewayState(e){return fl(e)}async detectGatewayFastState(e){return ip(e)}async probeGatewayPort(e){return(0,be.probePort)(e)}isStartedGatewayProcessAlive(e){return e!==void 0&&(0,be.isProcessRunning)(e)}getStartupTimeoutMs(){return BM}getStartupCheckIntervalMs(){return 500}getStartupLaunchGraceMs(){return le?15e3:0}getUninstallInitialDelayMs(){return le?2e3:3e3}getUninstallVerificationTimeoutMs(){return le?15e3:9e4}getUninstallCheckIntervalMs(){return le?1e3:4e3}async sleep(e){await new Promise(n=>setTimeout(n,e))}isWindowsLaunch(){return le}async stopExistingGatewayBeforeStart(e){await Pw(e,n=>this.log(n))}getGatewayLockPathForConfig(){let e=(0,zf.createHash)("sha256").update(this.configPath).digest("hex").slice(0,8);return V.join(ts.tmpdir(),"openclaw",`gateway.${e}.lock`)}async removeStaleGatewayLockBeforeStart(e){if(!le)return;let n=this.getGatewayLockPathForConfig();if(!G.existsSync(n))return;if(await this.probeGatewayPort(e)){this.log(`Gateway lock present but port ${e} is open; leaving lock in place.`);return}let r=Number.POSITIVE_INFINITY;try{let s=await G.promises.stat(n);r=Date.now()-s.mtimeMs}catch(s){this.log(`Could not stat gateway lock before start: ${s instanceof Error?s.message:String(s)}`);return}if(r<FM){this.log(`Gateway lock is only ${Math.round(r/1e3)}s old; not removing (possible concurrent start still binding).`);return}try{G.rmSync(n,{force:!0}),this.log(`Removed stale gateway lock before start (${Math.round(r/1e3)}s old): ${n}`)}catch(s){this.log(`Could not remove stale gateway lock before start: ${s instanceof Error?s.message:String(s)}`)}}async writeGatewayPidRecord(e,n,r){await tG(e,n,r)}async reconcileUninstallProgressState(){if(!this._gatewayUninstallInProgress)return this._lastDetection;if(this.revealUninstallSetupTerminal())return this._lastDetection;let e=await fl(this.getGatewayPort());return this._lastDetection=e,this._gatewayUninstallInProgress=!1,e.running?this.setStatus("running"):e.installed?this.setStatus("installed"):this.setStatus("not-installed"),e}async showNotInstalledQuickMenu(){let e=N.window.showInformationMessage(`${D.AGENT_ANYWHERE_LABEL}: Reach your AgentHippo IDE or CLI agents from WhatsApp, Telegram, Slack, Discord, and more - right from your phone or any messaging app. This will also install OpenClaw fork on your computer.`,"Install","Ask Agent Hippo");switch(this.queueBackgroundDetect("opening not-installed menu"),await e){case"Install":await this.install();break;case"Ask Agent Hippo":await this.openAskAgentHippoChat();break}}async showMaintenanceQuickMenu(){let e=this._status==="running"||this._status==="installed"||this._lastDetection?.installed===!0,r=[...this._status==="running"&&this._hasConfiguredChannelsCache===!0?["Web UI"]:[],"Config","Reset auth","Reset mappings",...e?["Restart"]:[],"Uninstall"],s=N.window.showInformationMessage(`${D.AGENT_ANYWHERE_LABEL}: More options`,...r);switch(this.queueBackgroundDetect("opening maintenance menu"),await s){case"Web UI":await this.openWebUI();break;case"Config":await this.openConfig();break;case"Reset auth":await this.resetAuth();break;case"Reset mappings":await N.commands.executeCommand("agentide.gateway.resetMappings");break;case"Restart":await this.restartGateway();break;case"Uninstall":await this.uninstall();break}}async refreshHasConfiguredChannels(){let e=this._bridgeRef;if(!e?.request)return this._hasConfiguredChannelsCache??!1;try{let{rows:n}=await(0,ep.fetchMeetAgentChannelContext)(e.request.bind(e));this._hasConfiguredChannelsCache=n.length>0}catch(n){this.log(`channels.status probe failed (non-fatal): ${n instanceof Error?n.message:String(n)}`),this._hasConfiguredChannelsCache??=!1}return this._hasConfiguredChannelsCache}async openAskAgentHippoChat(){await N.commands.executeCommand("workbench.action.chat.newChat",{agentMode:!0}),await N.commands.executeCommand("workbench.action.chat.open",{mode:"agent",query:"use openclaw skill as needed.",isPartialQuery:!0})}async showMeetAgentPicker(e){if(!this._bridgeRef?.request){N.window.showWarningMessage("Not connected to gateway.");return}let n=this._bridgeRef.request.bind(this._bridgeRef),r=!1,s=async(i,o)=>{try{return await n(i,o)}catch(a){let c=a instanceof Error?a.message:String(a);if(!r&&(0,MM.isGatewayScopeAuthError)(c)){if(r=!0,this.log(`Gateway denied RPC (${c}); reconnecting with fresh handshake...`),await this.disconnectBridge(),await this.connectBridge(),!this._bridgeRef?.request)throw a;return await this._bridgeRef.request(i,o)}throw a}};try{this.log("Meet Agent: fetching channels.status...");let{rows:i,statusPayload:o}=await(0,ep.fetchMeetAgentChannelContext)(s);if(this.log(`Meet Agent: got ${i?.length??0} channel(s): ${i?.map(g=>g.id).join(", ")??"none"}`),!i||i.length===0){let g=await N.window.showInformationMessage("No messaging channels (Telegram, WhatsApp, etc.) are configured. You can chat with your agent in the Gateway Web UI, or set up channels in OpenClaw config.","Open Web UI","Open Config");g==="Open Web UI"?await this.openWebUI():g==="Open Config"&&await this.openConfig();return}let a=e??await this.getFirstRegisteredAgentId();if(!a){N.window.showWarningMessage("No agent registered with the gateway.");return}let l=(await s("agents.list")).external?.find(g=>g.id.toLowerCase()===a.toLowerCase()),f=new Set(l?.boundChannels?.map(g=>g.toLowerCase())??[]),u=i.map(g=>({channelId:g.id,label:g.label,description:g.connected?"connected":"offline",detail:g.accounts.length>1?`Accounts: ${g.accounts.join(", ")}`:void 0,picked:f.has(g.id.toLowerCase())})),d=await N.window.showQuickPick(u,{canPickMany:!0,title:`Meet ${a} at...`,placeHolder:"Select channels where people can reach this agent"});if(!d)return;let p=d.map(g=>g.channelId);if(await(0,ep.applyAgentChannelBindingsViaConfigPatch)(s,{agentId:a,selectedChannelIds:p,statusPayload:o}),p.length===0)N.window.showInformationMessage(`${a}: all channel bindings removed.`);else{let g=d.map(m=>m.label).join(", ");N.window.showInformationMessage(`${a} can now be reached at: ${g}`)}}catch(i){this.log(`Meet Agent picker failed: ${i}`),N.window.showErrorMessage(`Failed to configure channels: ${i instanceof Error?i.message:String(i)}`)}}async getFirstRegisteredAgentId(){if(this._bridgeRef?.request)try{return(await this._bridgeRef.request("agents.list")).external?.[0]?.id}catch{return}}async detect(){let e=this.getGatewayPort(),r=await fl(e);return this._gatewayInstallInProgress||this._gatewayUninstallInProgress?(this._lastDetection=r,r):this._startInFlight&&this._status==="starting"?(this._lastDetection=r,r):(!r.running&&r.installed&&(await this.hasGlobalNpmOpenclawTree()||(r={...r,installed:!1})),this._lastDetection=r,r.running?this.setStatus("running"):r.installed?this.setStatus("installed"):this.setStatus("not-installed"),r)}async install(){let e=this.getConfig("installSource",""),n=this.getGatewayPort();if(!e)return N.window.showErrorMessage(`${D.AGENT_ANYWHERE_LABEL}: Install source not configured. Set "${(0,tp.toSettingsDisplayKey)("agentide.anywhere.installSource")}" in settings.`),!1;let r=(0,lt.validateAnywhereInstallSource)(e);if(!r.ok)return N.window.showErrorMessage(`${D.AGENT_ANYWHERE_LABEL}: Refusing to install from "${e}" \u2014 ${r.reason}. Fix "${(0,tp.toSettingsDisplayKey)("agentide.anywhere.installSource")}" in your user settings.`),this.log(`Rejected installSource (${r.reason}): ${e}`),!1;if(this._gatewayInstallInProgress)return await N.window.showInformationMessage(`${D.AGENT_ANYWHERE_LABEL}: Install is already in progress. Watch the "${D.AGENT_ANYWHERE_LABEL} Setup" terminal.`,"Show Setup Terminal","OK")==="Show Setup Terminal"&&(this.revealInstallSetupTerminal()||await this.showMissingInstallSetupTerminalPrompt()),!1;this.setInstallProgressFlag(!0,"install command started");try{this.log(`Installing gateway from: ${e}`),(0,be.clearBinaryCache)(Zr),(0,be.clearBinaryCache)("openclaw"),this.setStatus("starting"),this.stopHealthChecks();let s=await this.detectGatewayState(n);this._lastDetection=s,s.running&&(this.log("Stopping gateway before install..."),await this.disconnectBridge(),await this.stop());let i=le?"setup-gateway.ps1":"setup-gateway.sh",a=[V.join(__dirname,"..","..","scripts","gateway",i),V.join(__dirname,"..","scripts","gateway",i)].find(h=>G.existsSync(h)),l=[V.join(__dirname,"..","..","base-prompts","gateway","openclaw-starter.json5"),V.join(__dirname,"..","base-prompts","gateway","openclaw-starter.json5")].find(h=>G.existsSync(h)),f,u={...np(),[lt.ANYWHERE_INSTALL_SOURCE_ENV]:e,...a?{[lt.ANYWHERE_SETUP_SCRIPT_ENV]:a}:{},...l?{[lt.ANYWHERE_CONFIG_TEMPLATE_ENV]:l}:{}};if(a&&le){let h=[`-Source $env:${lt.ANYWHERE_INSTALL_SOURCE_ENV}`];l&&h.push(`-ConfigTemplate $env:${lt.ANYWHERE_CONFIG_TEMPLATE_ENV}`);let E=`& $env:${lt.ANYWHERE_SETUP_SCRIPT_ENV} ${h.join(" ")}; Write-Host ""; Write-Host "You can close this window."`;f={name:Zi,shellPath:"powershell.exe",shellArgs:["-NoProfile","-NoExit","-ExecutionPolicy","Bypass","-Command",E],env:{[lt.ANYWHERE_INSTALL_SOURCE_ENV]:e,[lt.ANYWHERE_SETUP_SCRIPT_ENV]:a,...l?{[lt.ANYWHERE_CONFIG_TEMPLATE_ENV]:l}:{}}}}else if(a){let h=[`--source "$${lt.ANYWHERE_INSTALL_SOURCE_ENV}"`];l&&h.push(`--config-template "$${lt.ANYWHERE_CONFIG_TEMPLATE_ENV}"`);let _=`${`bash "$${lt.ANYWHERE_SETUP_SCRIPT_ENV}" ${h.join(" ")}`}; echo ""; echo "Press Enter to close..."; read`;f={name:Zi,shellPath:ll(),shellArgs:ul(_),env:u}}else{this.log("Setup script not found, falling back to npm install");let E=`${`npm install -g "$${lt.ANYWHERE_INSTALL_SOURCE_ENV}"`}; echo ""; echo "Press Enter to close..."; read`;f=le?{name:Zi,shellPath:"cmd.exe",shellArgs:["/c",`npm install -g "%${lt.ANYWHERE_INSTALL_SOURCE_ENV}%" && echo. && echo Setup complete. && pause`],env:{[lt.ANYWHERE_INSTALL_SOURCE_ENV]:e}}:{name:Zi,shellPath:ll(),shellArgs:ul(E),env:u}}try{G.rmSync(op,{force:!0})}catch{}this._installProgressMessage="Launching setup...",this.updateStatusBar("starting");let d=N.window.createTerminal(f);this._installSetupTerminal=d,d.show();let p=VM(e)?10*6e4:12e4;this.log(`Waiting up to ${Math.round(p/6e4)} minute(s) for gateway install completion...`);let g=le&&!!a;return await N.window.withProgress({location:N.ProgressLocation.Window,title:`${D.AGENT_ANYWHERE_LABEL}: Installing gateway...`,cancellable:!1},async h=>{let E=Date.now()+p,_=0;for(;Date.now()<E;){if(!this._gatewayInstallInProgress)return this.log("Gateway install wait aborted \u2014 setup terminal closed before completion was detected"),!1;let y=this.readInstallStatusSnapshot(),b=this.getInstallProgressSummary(y);this._installProgressMessage=b.message,this.updateStatusBar("starting");let T=Math.max(0,b.percent-_);if(h.report({message:b.message,increment:T}),_=Math.max(_,b.percent),y?.phase==="failed")return this.log(`Gateway install failed: ${y.lastError||y.message||"unknown error"}`),!1;(0,be.clearBinaryCache)(Zr),(0,be.clearBinaryCache)("openclaw");let O=await this.detectGatewayState(n);if(this._lastDetection=O,g?ZM(y)&&O.installed:O.installed)return this.log("Gateway installed successfully"),await this.ensureManagedGatewayWrapperState(O.binaryPath),await this.ensureWebUIBuilt(O.binaryPath),this.writeStarterConfig(),await N.workspace.getConfiguration("agentide.anywhere").update("enabled",!0,N.ConfigurationTarget.Global),O.running?(this.finishInstallUiState("running","success"),h.report({message:`Install complete. Gateway is running on port ${n}.`,increment:Math.max(0,100-_)})):(this.finishInstallUiState("installed","success"),h.report({message:"Install complete. Gateway is installed. Click Agent Anywhere to start.",increment:Math.max(0,100-_)})),N.window.showInformationMessage(O.running?`${D.AGENT_ANYWHERE_LABEL}: Installed and running. Open the config to add your channels or use the status bar to connect.`:`${D.AGENT_ANYWHERE_LABEL}: Installed. Open the config to add your channels, then click Agent Anywhere to start.`,"Open Config").then(async C=>{C==="Open Config"&&await this.openConfig()}),!0;await new Promise(v=>setTimeout(v,1e3))}return!1})?!0:(this.log("Gateway install timed out or failed"),this.finishInstallUiState("error","failure"),!1)}catch(s){return this.log(`Install failed: ${s instanceof Error?s.message:String(s)}`),this.finishInstallUiState("error","failure"),!1}finally{this._gatewayInstallInProgress&&(this.setInstallProgressFlag(!1,"finally"),this._installProgressMessage=void 0),this.updateStatusBar(this._status)}}async uninstall(){if(this._gatewayUninstallInProgress){await this.showGatewayUninstallInProgressPrompt();return}await this.stop();let e=le?"setup-gateway.ps1":"setup-gateway.sh",r=[V.join(__dirname,"..","scripts","gateway",e),V.join(__dirname,"..","..","scripts","gateway",e)].find(i=>G.existsSync(i)),s;if(r&&le){let i=`& "${r}" -Uninstall; Write-Host ""; Write-Host "You can close this window."`;s={name:wi,shellPath:"powershell.exe",shellArgs:["-NoProfile","-NoExit","-ExecutionPolicy","Bypass","-Command",i]}}else if(r){let o=`${`bash "${r}" --uninstall`}; echo ""; echo "Press Enter to close..."; read`;s={name:wi,shellPath:ll(),shellArgs:ul(o),env:np()}}else{let i="npm uninstall -g openclaw",o=`${i}; echo ""; echo "Press Enter to close..."; read`;s=le?{name:wi,shellPath:"cmd.exe",shellArgs:["/c",`${i} && echo. && pause`]}:{name:wi,shellPath:ll(),shellArgs:ul(o),env:np()}}this._gatewayUninstallInProgress=!0,this.setStatus("stopping");try{let i=N.window.createTerminal(s);this._uninstallSetupTerminal=i,i.show(),this.log("Gateway uninstall started in terminal"),(0,be.clearBinaryCache)(Zr),(0,be.clearBinaryCache)("openclaw"),await this.sleep(this.getUninstallInitialDelayMs());let o=Date.now()+this.getUninstallVerificationTimeoutMs(),a,c=!0;for(;Date.now()<o;){(0,be.clearBinaryCache)(Zr),(0,be.clearBinaryCache)("openclaw");let l=await this.detectGatewayState(this.getGatewayPort());if(a=l,this._lastDetection=l,c=await this.hasGlobalNpmOpenclawTree(),!c&&!l.running){hw(),this.setStatus("not-installed"),l.installed?this.log("Managed OpenClaw npm package removed; another OpenClaw binary remains on PATH (likely external/self-updated)."):this.log("Global OpenClaw package removed (or no longer detected).");return}if(!l.installed){hw(),this.setStatus("not-installed"),this.log("Global OpenClaw package removed (or no longer detected).");return}await this.sleep(this.getUninstallCheckIntervalMs())}!c&&a?.running?N.window.showWarningMessage(`${D.AGENT_ANYWHERE_LABEL}: Managed package was removed, but the gateway listener still appears to be running. Finish the terminal command or run Status.`):N.window.showWarningMessage(`${D.AGENT_ANYWHERE_LABEL}: Uninstall is still verifying managed package removal. Finish the terminal command or run Status.`)}finally{this._gatewayUninstallInProgress=!1,this.updateStatusBar(this._status)}}get configPath(){return V.join(ts.homedir(),".openclaw","openclaw.json")}writeStarterConfig(){let e=V.dirname(this.configPath);if(G.existsSync(this.configPath)){this.log("Config already exists, skipping starter config");return}let r=[V.join(__dirname,"..","base-prompts","gateway","openclaw-starter.json5"),V.join(__dirname,"..","..","base-prompts","gateway","openclaw-starter.json5")].find(o=>G.existsSync(o));if(!r){this.log("Starter config template not found, skipping");return}G.mkdirSync(e,{recursive:!0,mode:448});let s=G.readFileSync(r,"utf-8"),i=`ah-${(0,zf.randomBytes)(24).toString("hex")}`;s=s.replace("__GENERATED_TOKEN__",i),G.writeFileSync(this.configPath,s,{encoding:"utf-8",mode:le?void 0:384}),this.log(`Wrote starter config to ${this.configPath}`)}async openConfig(){G.existsSync(this.configPath)||this.writeStarterConfig();let e=await N.workspace.openTextDocument(this.configPath);await N.window.showTextDocument(e)}async preflightChannelSecrets(e){let n;try{n=G.readFileSync(this.configPath,"utf-8")}catch{return"continue"}let r=(0,Zf.parseStrictJsonConfig)(n);if(r===void 0)return"continue";let s=(0,Zf.collectMissingChannelEnvSecrets)(r,e);if(s.length===0)return"continue";let i=(0,Qf.getAgentHomeEnvFilePath)(),o=s.map(u=>u.channel).join(", "),a=[...new Set(s.flatMap(u=>u.envVars))];this.log(`Channel secrets preflight: ${o} missing ${a.join(", ")}`);let c=`Disable ${o} & Start`,l="Add Secrets",f=await N.window.showErrorMessage(`${D.AGENT_ANYWHERE_LABEL}: The ${o} channel needs ${a.join(", ")}, which ${a.length===1?"is":"are"} not set in ${i} or the IDE environment. Add the secret${a.length===1?"":"s"} or disable the channel to start the gateway.`,c,l);if(f===c){let u=(0,Zf.disableChannelsInConfigText)(n,s.map(p=>p.channel));if(!u)return N.window.showErrorMessage(`${D.AGENT_ANYWHERE_LABEL}: Could not update ${this.configPath}. Set "enabled": false on the ${o} channel manually, then start again.`),"abort";let d=`${this.configPath}.bak-missing-secrets`;try{G.copyFileSync(this.configPath,d),G.writeFileSync(this.configPath,u,{encoding:"utf-8",mode:le?void 0:384})}catch(p){let g=p instanceof Error?p.message:String(p);return N.window.showErrorMessage(`${D.AGENT_ANYWHERE_LABEL}: Could not update ${this.configPath} (${g}).`),"abort"}return this.log(`Disabled channels missing secrets: ${o} (backup: ${d})`),N.window.showInformationMessage(`${D.AGENT_ANYWHERE_LABEL}: Disabled the ${o} channel (backup: ${V.basename(d)}). To re-enable: add ${a.join(", ")} to ${i}, set "enabled": true in the config, then restart the gateway.`),"continue"}return f===l&&await this.openEnvFileWithSecretStubs(i,a),"abort"}async openEnvFileWithSecretStubs(e,n){try{let r="";try{r=G.readFileSync(e,"utf-8")}catch{}let s=n.filter(o=>!new RegExp(`^\\s*#?\\s*${o}=`,"m").test(r));if(s.length){let o=r.length&&!r.endsWith(`
620
+ `;return G.writeFileSync(n,r,le?"ascii":"utf8"),le||G.chmodSync(n,493),n}function QM(t){if(t)try{let e=V.join(t,"package.json");if(!G.existsSync(e))return;let n=JSON.parse(G.readFileSync(e,"utf8")),r=n.bin;typeof r=="string"&&(r={[n.name||"openclaw"]:r});let s=[...new Set(["hippoclaw","openclaw",...Object.keys(r||{})])];for(let i of s){let o=r&&typeof r[i]=="string"?r[i]:void 0;if(!o)continue;let a=V.resolve(t,o);if(G.existsSync(a))return a}}catch{}}function ZM(t){let e=Iw(t)??t;if(e){let n=V.join(V.dirname(e),le?"node.exe":"node");if(G.existsSync(n))return n}for(let n of(0,be.getCommonBinaryPaths)("node"))if(G.existsSync(n))return n}function yw(){for(let t of[vw,cp])if(Rw(t))try{G.rmSync(t,{force:!0})}catch{}try{G.rmSync(hl,{force:!0})}catch{}}function Cw(t,e){if(G.existsSync(e))try{t.add(G.realpathSync(e))}catch{t.add(e)}}function ww(t,e){for(let n of gp)Cw(t,V.join(e,n))}function eG(){let t=es.homedir(),e=process.env.NVM_DIR||V.join(t,".nvm"),n=V.join(e,"versions","node");if(!G.existsSync(n))return[];let r=[];try{for(let s of G.readdirSync(n,{withFileTypes:!0}))s.isDirectory()&&r.push(...gp.map(i=>V.join(n,s.name,"lib","node_modules",i)))}catch{}return r}async function na(){let t=new Set,e=Si(),n=Ep(e);n&&G.existsSync(n)&&t.add(n);let r=V.join(es.homedir(),".agenthippo","tools","node");if(G.existsSync(r))try{let s=G.readdirSync(r,{withFileTypes:!0});for(let i of s)if(i.isDirectory())for(let o of gp){let a=V.join(r,i.name,...le?["node_modules"]:["lib","node_modules"],o);if(G.existsSync(a))try{t.add(G.realpathSync(a))}catch{t.add(a)}}}catch{}ww(t,V.join(es.homedir(),".npm-global",...le?["node_modules"]:["lib","node_modules"]));for(let s of eG())Cw(t,s);try{let{stdout:s}=await Gt("npm root -g",{timeout:3e3}),i=s.trim();i&&ww(t,i)}catch{}return Array.from(t)}function _p(t){try{let e=JM(t)??t,n=G.realpathSync(e),r=V.dirname(n);for(let s=0;s<8;s++){if(G.existsSync(V.join(r,"package.json")))return r;let i=V.dirname(r);if(i===r)break;r=i}}catch{}}async function dp(t,e){let n=e??await na();if(n.length===0)return!1;let r=_p(t);return r?n.some(s=>Ow(r,s)):!1}async function tG(t){if(!Number.isFinite(t)||t<1||t>65535)return[];if(le)try{let e=`$listenerPids=Get-NetTCPConnection -LocalPort ${t} -State Listen -ErrorAction SilentlyContinue | Select-Object -ExpandProperty OwningProcess -Unique; foreach($listenerProcId in $listenerPids){$proc=Get-CimInstance Win32_Process -Filter \\"ProcessId=$listenerProcId\\" -ErrorAction SilentlyContinue; if($proc -and $proc.CommandLine){$proc.CommandLine}}`,{stdout:n}=await Gt(`powershell.exe -NoProfile -Command "${e}"`,{timeout:1e4});return n.split(/\r?\n/).map(r=>r.trim()).filter(r=>r.length>0)}catch{return[]}try{let{stdout:e}=await Gt(`lsof -nP -iTCP:${t} -sTCP:LISTEN -t 2>/dev/null || true`,{timeout:5e3}),n=[...new Set(e.trim().split(/\n/).map(s=>s.trim()).filter(s=>/^\d+$/.test(s)))],r=[];for(let s of n)try{let{stdout:i}=await Gt(`ps -p ${s} -o command=`,{timeout:3e3}),o=i.trim();o&&r.push(o)}catch{}return r}catch{return[]}}async function ml(t,e){let n=await na();if(n.length===0)return!1;let r=!1,s="";if(e&&(r=await dp(e,n),r))try{s=G.realpathSync(e)}catch{s=e}let i=await tG(t);if(i.length===0)return!1;let o=Si(),a=Nw(o),c=[...i];a&&c.push(a);let l=n.map(u=>Zr(u));a&&l.push(Zr(V.dirname(a)));let f=s?Zr(s):"";for(let u of c){let d=Zr(u);if(d.includes(Qr)&&r||f&&d.includes(f)||l.some(p=>d.includes(p)))return!0}return!1}async function pl(t=Ai){let[e,n]=await Promise.all([(0,be.probePort)(t),na()]),r=await $w(n),s;if(r)try{let{stdout:a}=await Gt(`"${r}" --version`,{timeout:3e3});s=a.trim().split(`
621
+ `)[0]}catch{}let i=!!r&&!!s,o=e?await ml(t,r):!1;return{installed:i,binaryPath:r,version:s,running:o,port:t}}async function kw(t,e){try{if(le){let n=await up(t);if(n){e("Running gateway stop via managed node runtime..."),await xM(n.nodePath,[n.entryScriptPath,"gateway","stop"],{timeout:2e4,windowsHide:!0});return}}e(`Running ${V.basename(t)} gateway stop (CLI)...`),await Gt(`"${t}" gateway stop`,{timeout:2e4,windowsHide:!0})}catch{}}function nG(){try{if(!G.existsSync(ap))return;let t=G.readFileSync(ap,"utf8").replace(/^\uFEFF/,"");return JSON.parse(t)}catch{return}}function rG(t){return t?.phase==="complete"&&t.steps?.finalCheckPassed===!0}function sG(t){if(!t)return{message:"Waiting for setup status...",percent:0};if(t.phase==="failed")return{message:t.lastError?.trim()||t.message?.trim()||"Install failed.",percent:100};let e=Ew.filter(([i])=>t.steps?.[i]).map(([,i])=>i),n=e.length,r=t.message?.trim()||"Installing Agent Anywhere...";return{message:e.length>0?`${r} (done: ${e.join(", ")})`:r,percent:Math.min(95,Math.floor(n/Ew.length*100))}}function fl(t){return t.replace(/'/g,"''")}async function no(t){if(!Number.isFinite(t)||t<1||t>65535)return[];if(le)try{let{stdout:e}=await Gt(`powershell.exe -NoProfile -Command "Get-NetTCPConnection -LocalPort ${t} -State Listen -ErrorAction SilentlyContinue | ForEach-Object { $_.OwningProcess } | Sort-Object -Unique"`,{timeout:1e4,windowsHide:!0});return[...new Set(e.trim().split(/\r?\n/).map(n=>parseInt(n.trim(),10)).filter(n=>Number.isInteger(n)&&n>0))]}catch{return[]}try{let{stdout:e}=await Gt(`lsof -nP -iTCP:${t} -sTCP:LISTEN -t 2>/dev/null || true`,{timeout:5e3});return[...new Set(e.trim().split(/\n/).map(n=>parseInt(n.trim(),10)).filter(n=>Number.isInteger(n)&&n>0))]}catch{return[]}}async function El(t,e,n=8e3){let r=[...new Set(e.filter(o=>Number.isInteger(o)&&o>0))],s=Date.now()+n,i=0;for(;Date.now()<s;){let o=await(0,be.probePort)(t),a=r.filter(c=>(0,be.isProcessRunning)(c));if(!o&&a.length===0){if(i===0&&(i=Date.now()),Date.now()-i>=750)return!0}else i=0;await new Promise(c=>setTimeout(c,250))}return!await(0,be.probePort)(t)&&r.every(o=>!(0,be.isProcessRunning)(o))}function Aw(t,e,n){if(e&&e>0)try{process.kill(-e,n);return}catch{}try{t.kill(n)}catch{}}async function fp(t){if(!(!Number.isFinite(t)||t<1||t>65535)){if(le){try{let{stdout:e}=await Gt(`powershell.exe -NoProfile -Command "Get-NetTCPConnection -LocalPort ${t} -State Listen -ErrorAction SilentlyContinue | ForEach-Object { $_.OwningProcess } | Sort-Object -Unique"`,{timeout:1e4}),n=e.trim().split(/\r?\n/).map(r=>r.trim()).filter(r=>/^\d+$/.test(r));for(let r of n)await Gt(`taskkill /F /T /PID ${r}`,{timeout:5e3}).catch(()=>{})}catch{}return}try{let{stdout:e}=await Gt(`lsof -nP -iTCP:${t} -sTCP:LISTEN -t 2>/dev/null || true`,{timeout:5e3}),n=[...new Set(e.trim().split(/\n/).map(i=>i.trim()).filter(i=>/^\d+$/.test(i)))];for(let i of n)await Gt(`kill ${i}`,{timeout:3e3}).catch(()=>{});await new Promise(i=>setTimeout(i,800));let{stdout:r}=await Gt(`lsof -nP -iTCP:${t} -sTCP:LISTEN -t 2>/dev/null || true`,{timeout:5e3}),s=[...new Set(r.trim().split(/\n/).map(i=>i.trim()).filter(i=>/^\d+$/.test(i)))];for(let i of s)await Gt(`kill -9 ${i}`,{timeout:3e3}).catch(()=>{})}catch{}}}async function Sw(t,e,n){let r=await no(t);if(e&&(await kw(e,n),await El(t,r)))return!0;n(`Stopping listener(s) on port ${t}...`),await fp(t);let s=[...r];return t!==Ai&&await(0,be.probePort)(Ai)&&(s.push(...await no(Ai)),n(`Stopping listener(s) on port ${Ai} (default gateway port)...`),await fp(Ai)),El(t,s)}async function iG(t,e,n){await(0,be.writePidFile)(yl,t,e,n)}async function ip(){await(0,be.removePidFile)(yl)}async function op(t){let e=await(0,be.checkPidFileWithCleanup)(yl);if(!e)return null;let n=e.metadata?.[0]?parseInt(e.metadata[0],10):void 0,r=e.metadata?.[1]||void 0,s=n??t;return!await(0,be.probePort)(s)||!await ml(s,r)?null:{installed:!0,binaryPath:r,running:!0,port:s}}async function $w(t){let e=t??await na();return oG(e)}async function oG(t){let e=Si(),n=Ep(e),r=Pw(e);if(n&&r&&G.existsSync(r)&&(t.length===0||t.some(a=>Ow(n,a))))return r;let s=await(0,be.findBinaryCached)(Qr,(0,be.getCommonBinaryPaths)(Qr));if(s&&await dp(s,t))return s;let i=le?`${Qr}.cmd`:Qr;for(let o of t){let a=le?V.dirname(V.dirname(o)):V.dirname(V.dirname(V.dirname(o))),c=le?V.join(a,i):V.join(a,"bin",i);if(G.existsSync(c)&&await dp(c,t))return c}}var pp=class{outputChannel;process=null;healthCheckTimer=null;_status="not-installed";_bridgeConnected=!1;_lastDetection=null;_bridgeRef=null;_gatewayInstallInProgress=!1;_installProgressMessage;_installSetupTerminal=null;_gatewayUninstallInProgress=!1;_uninstallSetupTerminal=null;_startInFlight=null;_lastStartInProgressNoticeAt=0;_hasConfiguredChannelsCache;disposables=[];statusBarItem;_onStatusChange=new N.EventEmitter;onStatusChange=this._onStatusChange.event;setBridgeRef(e){this._bridgeRef=e}constructor(e,n){this.outputChannel=e,this.statusBarItem=N.window.createStatusBarItem(N.StatusBarAlignment.Right,100),this.statusBarItem.command="agentide.anywhere.toggle",this.statusBarItem.name=D.AGENT_ANYWHERE_LABEL,N.commands.executeCommand("setContext","agentide.anywhere.connected",this._bridgeConnected),this.disposables.push(N.window.onDidCloseTerminal(r=>{this._installSetupTerminal===r&&(this._installSetupTerminal=null,this._gatewayInstallInProgress&&this.reconcileInstallProgressState()),this._uninstallSetupTerminal===r&&(this._uninstallSetupTerminal=null,this._gatewayUninstallInProgress&&this.reconcileUninstallProgressState())})),this.registerCommands(),this.registerConfigWatcher(),this.initializeLazy()}setInstallProgressFlag(e,n){this._gatewayInstallInProgress!==e&&(this._gatewayInstallInProgress=e,this.log(`Install flag -> ${e?"true":`false (${n})`}`))}get status(){return this._status}get lastDetection(){return this._lastDetection}async initializeLazy(){if(this.getConfig("hidden",!1)){this.statusBarItem.hide();return}if(!this.getConfig("enabled",!1)){this.updateStatusBar("not-installed"),this.statusBarItem.show();return}let r=this.getGatewayPort(),s=await op(r);s?(this._lastDetection=s,this.setStatus("running")):await this.detect(),this.getConfig("autoStart",!1)&&this._lastDetection?.installed&&!this._lastDetection?.running&&(this.log(`Auto-starting gateway (${(0,np.toSettingsDisplayKey)("agentide.anywhere.autoStart")} = true)`),await this.start())}registerCommands(){this.disposables.push(N.commands.registerCommand("agentide.anywhere.toggle",()=>this.toggle()),N.commands.registerCommand("agentide.anywhere.install",()=>this.install()),N.commands.registerCommand("agentide.anywhere.uninstall",()=>this.uninstall()),N.commands.registerCommand("agentide.anywhere.start",()=>this.start()),N.commands.registerCommand("agentide.anywhere.stop",()=>this.stop()),N.commands.registerCommand("agentide.anywhere.status",()=>this.showStatus()),N.commands.registerCommand("agentide.anywhere.openConfig",()=>this.openConfig()),N.commands.registerCommand("agentide.anywhere.connect",()=>this.connectBridge()),N.commands.registerCommand("agentide.anywhere.disconnect",()=>this.disconnectBridge()),N.commands.registerCommand("agentide.anywhere.openWebUI",()=>this.openWebUI()),N.commands.registerCommand("agentide.anywhere.detect",()=>this.detect()),N.commands.registerCommand("agentide.anywhere.meetAgent",()=>this.showMeetAgentPicker()))}setBridgeConnected(e){this._bridgeConnected=e,N.commands.executeCommand("setContext","agentide.anywhere.connected",e)}registerConfigWatcher(){this.disposables.push(N.workspace.onDidChangeConfiguration(e=>{e.affectsConfiguration("agentide.anywhere")&&this.initializeLazy()}))}async toggle(){if(!this.getConfig("hidden",!1)){if(this._gatewayInstallInProgress){await this.showGatewayInstallInProgressPrompt();return}if(this._gatewayUninstallInProgress){await this.showGatewayUninstallInProgressPrompt();return}if(this._startInFlight){this.setStatus("starting");let n=Date.now();n-this._lastStartInProgressNoticeAt>4e3&&(this._lastStartInProgressNoticeAt=n,N.window.showInformationMessage(`${D.AGENT_ANYWHERE_LABEL}: Starting gateway... please wait.`));return}switch(this.setBridgeConnected(this._bridgeRef?.isConnected??!1),this._status){case"error":{this._lastDetection?.installed===!0?await this.showDisconnectedQuickMenu():await this.showNotInstalledQuickMenu();break}case"starting":case"stopping":N.window.showInformationMessage(`${D.AGENT_ANYWHERE_LABEL}: Operation in progress...`);break;case"running":this._bridgeConnected?await this.showConnectedQuickMenu():await this.showDisconnectedQuickMenu();break;case"installed":await this.showDisconnectedQuickMenu();break;case"not-installed":default:{if(this._lastDetection?.installed===!0){await this.showDisconnectedQuickMenu();break}await this.showNotInstalledQuickMenu();break}}}}queueBackgroundDetect(e){this._gatewayInstallInProgress||this._gatewayUninstallInProgress||this._startInFlight||this._status==="starting"||this._status==="stopping"||setTimeout(()=>{this._gatewayInstallInProgress||this._gatewayUninstallInProgress||this._startInFlight||this._status==="starting"||this._status==="stopping"||this.detect().catch(n=>{this.log(`Background detect failed after ${e}: ${n instanceof Error?n.message:String(n)}`)})},100)}async showConnectedQuickMenu(){let n=this._hasConfiguredChannelsCache??await this.refreshHasConfiguredChannels()?"Meet at...":"Web UI",r=N.window.showInformationMessage(`${D.AGENT_ANYWHERE_LABEL} is running (bridge: connected).`,n,"Disconnect","Ask Agent Hippo","More");switch(this.queueBackgroundDetect("opening connected menu"),this.refreshHasConfiguredChannels(),await r){case"Meet at...":await this.showMeetAgentPicker();break;case"Web UI":await this.openWebUI();break;case"Disconnect":await this.disconnectBridge();break;case"More":await this.showMaintenanceQuickMenu();break;case"Ask Agent Hippo":await this.openAskAgentHippoChat();break}}async showDisconnectedQuickMenu(){let e=N.window.showInformationMessage(`${D.AGENT_ANYWHERE_LABEL}: Disconnected.`,"Connect","Reinstall","Ask Agent Hippo","More");switch(this.queueBackgroundDetect("opening disconnected menu"),await e){case"Connect":await this.start(),this._status==="running"&&(await this.connectBridge(),this.setBridgeConnected(this._bridgeRef?.isConnected??!1),this._bridgeConnected&&await this.showConnectedQuickMenu());break;case"Reinstall":await this.install();break;case"More":await this.showMaintenanceQuickMenu();break;case"Ask Agent Hippo":await this.openAskAgentHippoChat();break}}async showGatewayInstallInProgressPrompt(){await N.window.showInformationMessage(`${D.AGENT_ANYWHERE_LABEL}: Install in progress. Follow the "${D.AGENT_ANYWHERE_LABEL} Setup" terminal; when it finishes, status updates automatically.`,"Show Setup Terminal","OK")==="Show Setup Terminal"&&(this.revealInstallSetupTerminal()||await this.showMissingInstallSetupTerminalPrompt())}async showMissingInstallSetupTerminalPrompt(){(await this.reconcileInstallProgressState())?.installed?N.window.showInformationMessage(`${D.AGENT_ANYWHERE_LABEL}: Install completed. Status has been refreshed.`):N.window.showWarningMessage(`${D.AGENT_ANYWHERE_LABEL}: Setup terminal is no longer available. Install did not complete; run Install again to relaunch setup.`)}async showGatewayUninstallInProgressPrompt(){await N.window.showInformationMessage(`${D.AGENT_ANYWHERE_LABEL}: Uninstall in progress. Follow the "${wi}" terminal; when it finishes, status updates automatically.`,"Show Uninstall Terminal","OK")==="Show Uninstall Terminal"&&(this.revealUninstallSetupTerminal()||await this.showMissingUninstallSetupTerminalPrompt())}async showMissingUninstallSetupTerminalPrompt(){let e=await this.reconcileUninstallProgressState();e&&!e.installed&&!e.running?N.window.showInformationMessage(`${D.AGENT_ANYWHERE_LABEL}: Uninstall completed. Status has been refreshed.`):N.window.showWarningMessage(`${D.AGENT_ANYWHERE_LABEL}: Uninstall terminal is no longer available. Uninstall may still be running or did not complete; run Status to confirm.`)}revealInstallSetupTerminal(){let e=this._installSetupTerminal??N.window.terminals.find(n=>n.name===to||n.name.startsWith(`${to} `))??null;return e?(this._installSetupTerminal=e,e.show(),!0):!1}revealUninstallSetupTerminal(){let e=this._uninstallSetupTerminal??N.window.terminals.find(n=>n.name===wi||n.name.startsWith(`${wi} `))??null;return e?(this._uninstallSetupTerminal=e,e.show(),!0):!1}async reconcileInstallProgressState(){if(!this._gatewayInstallInProgress)return this._lastDetection;if(this.revealInstallSetupTerminal())return this._lastDetection;if(await this.sleep(2e3),this.revealInstallSetupTerminal())return this._lastDetection;(0,be.clearBinaryCache)(Qr),(0,be.clearBinaryCache)("openclaw");let e=await this.detectGatewayState(this.getGatewayPort());return this._lastDetection=e,e.running?this.finishInstallUiState("running","terminal reconciliation"):e.installed?this.finishInstallUiState("installed","terminal reconciliation"):(this.log("Setup terminal closed before gateway install was detected"),this.setInstallProgressFlag(!1,"terminal reconciliation"),this._installProgressMessage=void 0,this.setStatus("not-installed")),e}finishInstallUiState(e,n){this.setInstallProgressFlag(!1,n),this._installProgressMessage=void 0,this.setStatus(e)}readInstallStatusSnapshot(){return nG()}getInstallProgressSummary(e){return sG(e)}async detectGatewayState(e){return pl(e)}async detectGatewayFastState(e){return op(e)}async probeGatewayPort(e){return(0,be.probePort)(e)}isStartedGatewayProcessAlive(e){return e!==void 0&&(0,be.isProcessRunning)(e)}getStartupTimeoutMs(){return KM}getStartupCheckIntervalMs(){return 500}getStartupLaunchGraceMs(){return le?15e3:0}getUninstallInitialDelayMs(){return le?2e3:3e3}getUninstallVerificationTimeoutMs(){return le?15e3:9e4}getUninstallCheckIntervalMs(){return le?1e3:4e3}async sleep(e){await new Promise(n=>setTimeout(n,e))}isWindowsLaunch(){return le}async stopExistingGatewayBeforeStart(e){await kw(e,n=>this.log(n))}getGatewayLockPathForConfig(){let e=(0,Qf.createHash)("sha256").update(this.configPath).digest("hex").slice(0,8);return V.join(es.tmpdir(),"openclaw",`gateway.${e}.lock`)}async removeStaleGatewayLockBeforeStart(e){if(!le)return;let n=this.getGatewayLockPathForConfig();if(!G.existsSync(n))return;if(await this.probeGatewayPort(e)){this.log(`Gateway lock present but port ${e} is open; leaving lock in place.`);return}let r=Number.POSITIVE_INFINITY;try{let s=await G.promises.stat(n);r=Date.now()-s.mtimeMs}catch(s){this.log(`Could not stat gateway lock before start: ${s instanceof Error?s.message:String(s)}`);return}if(r<qM){this.log(`Gateway lock is only ${Math.round(r/1e3)}s old; not removing (possible concurrent start still binding).`);return}try{G.rmSync(n,{force:!0}),this.log(`Removed stale gateway lock before start (${Math.round(r/1e3)}s old): ${n}`)}catch(s){this.log(`Could not remove stale gateway lock before start: ${s instanceof Error?s.message:String(s)}`)}}async writeGatewayPidRecord(e,n,r){await iG(e,n,r)}async reconcileUninstallProgressState(){if(!this._gatewayUninstallInProgress)return this._lastDetection;if(this.revealUninstallSetupTerminal())return this._lastDetection;let e=await pl(this.getGatewayPort());return this._lastDetection=e,this._gatewayUninstallInProgress=!1,e.running?this.setStatus("running"):e.installed?this.setStatus("installed"):this.setStatus("not-installed"),e}async showNotInstalledQuickMenu(){let e=N.window.showInformationMessage(`${D.AGENT_ANYWHERE_LABEL}: Reach your AgentHippo IDE or CLI agents from WhatsApp, Telegram, Slack, Discord, and more - right from your phone or any messaging app. This will also install OpenClaw fork on your computer.`,"Install","Ask Agent Hippo");switch(this.queueBackgroundDetect("opening not-installed menu"),await e){case"Install":await this.install();break;case"Ask Agent Hippo":await this.openAskAgentHippoChat();break}}async showMaintenanceQuickMenu(){let e=this._status==="running"||this._status==="installed"||this._lastDetection?.installed===!0,r=[...this._status==="running"&&this._hasConfiguredChannelsCache===!0?["Web UI"]:[],"Config","Reset auth","Reset mappings",...e?["Restart"]:[],"Uninstall"],s=N.window.showInformationMessage(`${D.AGENT_ANYWHERE_LABEL}: More options`,...r);switch(this.queueBackgroundDetect("opening maintenance menu"),await s){case"Web UI":await this.openWebUI();break;case"Config":await this.openConfig();break;case"Reset auth":await this.resetAuth();break;case"Reset mappings":await N.commands.executeCommand("agentide.gateway.resetMappings");break;case"Restart":await this.restartGateway();break;case"Uninstall":await this.uninstall();break}}async refreshHasConfiguredChannels(){let e=this._bridgeRef;if(!e?.request)return this._hasConfiguredChannelsCache??!1;try{let{rows:n}=await(0,tp.fetchMeetAgentChannelContext)(e.request.bind(e));this._hasConfiguredChannelsCache=n.length>0}catch(n){this.log(`channels.status probe failed (non-fatal): ${n instanceof Error?n.message:String(n)}`),this._hasConfiguredChannelsCache??=!1}return this._hasConfiguredChannelsCache}async openAskAgentHippoChat(){await N.commands.executeCommand("workbench.action.chat.newChat",{agentMode:!0}),await N.commands.executeCommand("workbench.action.chat.open",{mode:"agent",query:"use openclaw skill as needed.",isPartialQuery:!0})}async showMeetAgentPicker(e){if(!this._bridgeRef?.request){N.window.showWarningMessage("Not connected to gateway.");return}let n=this._bridgeRef.request.bind(this._bridgeRef),r=!1,s=async(i,o)=>{try{return await n(i,o)}catch(a){let c=a instanceof Error?a.message:String(a);if(!r&&(0,jM.isGatewayScopeAuthError)(c)){if(r=!0,this.log(`Gateway denied RPC (${c}); reconnecting with fresh handshake...`),await this.disconnectBridge(),await this.connectBridge(),!this._bridgeRef?.request)throw a;return await this._bridgeRef.request(i,o)}throw a}};try{this.log("Meet Agent: fetching channels.status...");let{rows:i,statusPayload:o}=await(0,tp.fetchMeetAgentChannelContext)(s);if(this.log(`Meet Agent: got ${i?.length??0} channel(s): ${i?.map(g=>g.id).join(", ")??"none"}`),!i||i.length===0){let g=await N.window.showInformationMessage("No messaging channels (Telegram, WhatsApp, etc.) are configured. You can chat with your agent in the Gateway Web UI, or set up channels in OpenClaw config.","Open Web UI","Open Config");g==="Open Web UI"?await this.openWebUI():g==="Open Config"&&await this.openConfig();return}let a=e??await this.getFirstRegisteredAgentId();if(!a){N.window.showWarningMessage("No agent registered with the gateway.");return}let l=(await s("agents.list")).external?.find(g=>g.id.toLowerCase()===a.toLowerCase()),f=new Set(l?.boundChannels?.map(g=>g.toLowerCase())??[]),u=i.map(g=>({channelId:g.id,label:g.label,description:g.connected?"connected":"offline",detail:g.accounts.length>1?`Accounts: ${g.accounts.join(", ")}`:void 0,picked:f.has(g.id.toLowerCase())})),d=await N.window.showQuickPick(u,{canPickMany:!0,title:`Meet ${a} at...`,placeHolder:"Select channels where people can reach this agent"});if(!d)return;let p=d.map(g=>g.channelId);if(await(0,tp.applyAgentChannelBindingsViaConfigPatch)(s,{agentId:a,selectedChannelIds:p,statusPayload:o}),p.length===0)N.window.showInformationMessage(`${a}: all channel bindings removed.`);else{let g=d.map(m=>m.label).join(", ");N.window.showInformationMessage(`${a} can now be reached at: ${g}`)}}catch(i){this.log(`Meet Agent picker failed: ${i}`),N.window.showErrorMessage(`Failed to configure channels: ${i instanceof Error?i.message:String(i)}`)}}async getFirstRegisteredAgentId(){if(this._bridgeRef?.request)try{return(await this._bridgeRef.request("agents.list")).external?.[0]?.id}catch{return}}async detect(){let e=this.getGatewayPort(),r=await pl(e);return this._gatewayInstallInProgress||this._gatewayUninstallInProgress?(this._lastDetection=r,r):this._startInFlight&&this._status==="starting"?(this._lastDetection=r,r):(!r.running&&r.installed&&(await this.hasGlobalNpmOpenclawTree()||(r={...r,installed:!1})),this._lastDetection=r,r.running?this.setStatus("running"):r.installed?this.setStatus("installed"):this.setStatus("not-installed"),r)}async install(){let e=this.getConfig("installSource",""),n=this.getGatewayPort();if(!e)return N.window.showErrorMessage(`${D.AGENT_ANYWHERE_LABEL}: Install source not configured. Set "${(0,np.toSettingsDisplayKey)("agentide.anywhere.installSource")}" in settings.`),!1;let r=(0,lt.validateAnywhereInstallSource)(e);if(!r.ok)return N.window.showErrorMessage(`${D.AGENT_ANYWHERE_LABEL}: Refusing to install from "${e}" \u2014 ${r.reason}. Fix "${(0,np.toSettingsDisplayKey)("agentide.anywhere.installSource")}" in your user settings.`),this.log(`Rejected installSource (${r.reason}): ${e}`),!1;if(this._gatewayInstallInProgress)return await N.window.showInformationMessage(`${D.AGENT_ANYWHERE_LABEL}: Install is already in progress. Watch the "${D.AGENT_ANYWHERE_LABEL} Setup" terminal.`,"Show Setup Terminal","OK")==="Show Setup Terminal"&&(this.revealInstallSetupTerminal()||await this.showMissingInstallSetupTerminalPrompt()),!1;this.setInstallProgressFlag(!0,"install command started");try{this.log(`Installing gateway from: ${e}`),(0,be.clearBinaryCache)(Qr),(0,be.clearBinaryCache)("openclaw"),this.setStatus("starting"),this.stopHealthChecks();let s=await this.detectGatewayState(n);this._lastDetection=s,s.running&&(this.log("Stopping gateway before install..."),await this.disconnectBridge(),await this.stop());let i=le?"setup-gateway.ps1":"setup-gateway.sh",a=[V.join(__dirname,"..","..","scripts","gateway",i),V.join(__dirname,"..","scripts","gateway",i)].find(h=>G.existsSync(h)),l=[V.join(__dirname,"..","..","base-prompts","gateway","openclaw-starter.json5"),V.join(__dirname,"..","base-prompts","gateway","openclaw-starter.json5")].find(h=>G.existsSync(h)),f,u={...rp(),[lt.ANYWHERE_INSTALL_SOURCE_ENV]:e,...a?{[lt.ANYWHERE_SETUP_SCRIPT_ENV]:a}:{},...l?{[lt.ANYWHERE_CONFIG_TEMPLATE_ENV]:l}:{}};if(a&&le){let h=[`-Source $env:${lt.ANYWHERE_INSTALL_SOURCE_ENV}`];l&&h.push(`-ConfigTemplate $env:${lt.ANYWHERE_CONFIG_TEMPLATE_ENV}`);let E=`& $env:${lt.ANYWHERE_SETUP_SCRIPT_ENV} ${h.join(" ")}; Write-Host ""; Write-Host "You can close this window."`;f={name:to,shellPath:"powershell.exe",shellArgs:["-NoProfile","-NoExit","-ExecutionPolicy","Bypass","-Command",E],env:{[lt.ANYWHERE_INSTALL_SOURCE_ENV]:e,[lt.ANYWHERE_SETUP_SCRIPT_ENV]:a,...l?{[lt.ANYWHERE_CONFIG_TEMPLATE_ENV]:l}:{}}}}else if(a){let h=[`--source "$${lt.ANYWHERE_INSTALL_SOURCE_ENV}"`];l&&h.push(`--config-template "$${lt.ANYWHERE_CONFIG_TEMPLATE_ENV}"`);let _=`${`bash "$${lt.ANYWHERE_SETUP_SCRIPT_ENV}" ${h.join(" ")}`}; echo ""; echo "Press Enter to close..."; read`;f={name:to,shellPath:ul(),shellArgs:dl(_),env:u}}else{this.log("Setup script not found, falling back to npm install");let E=`${`npm install -g "$${lt.ANYWHERE_INSTALL_SOURCE_ENV}"`}; echo ""; echo "Press Enter to close..."; read`;f=le?{name:to,shellPath:"cmd.exe",shellArgs:["/c",`npm install -g "%${lt.ANYWHERE_INSTALL_SOURCE_ENV}%" && echo. && echo Setup complete. && pause`],env:{[lt.ANYWHERE_INSTALL_SOURCE_ENV]:e}}:{name:to,shellPath:ul(),shellArgs:dl(E),env:u}}try{G.rmSync(ap,{force:!0})}catch{}this._installProgressMessage="Launching setup...",this.updateStatusBar("starting");let d=N.window.createTerminal(f);this._installSetupTerminal=d,d.show();let p=YM(e)?10*6e4:12e4;this.log(`Waiting up to ${Math.round(p/6e4)} minute(s) for gateway install completion...`);let g=le&&!!a;return await N.window.withProgress({location:N.ProgressLocation.Window,title:`${D.AGENT_ANYWHERE_LABEL}: Installing gateway...`,cancellable:!1},async h=>{let E=Date.now()+p,_=0;for(;Date.now()<E;){if(!this._gatewayInstallInProgress)return this.log("Gateway install wait aborted \u2014 setup terminal closed before completion was detected"),!1;let y=this.readInstallStatusSnapshot(),b=this.getInstallProgressSummary(y);this._installProgressMessage=b.message,this.updateStatusBar("starting");let T=Math.max(0,b.percent-_);if(h.report({message:b.message,increment:T}),_=Math.max(_,b.percent),y?.phase==="failed")return this.log(`Gateway install failed: ${y.lastError||y.message||"unknown error"}`),!1;(0,be.clearBinaryCache)(Qr),(0,be.clearBinaryCache)("openclaw");let O=await this.detectGatewayState(n);if(this._lastDetection=O,g?rG(y)&&O.installed:O.installed)return this.log("Gateway installed successfully"),await this.ensureManagedGatewayWrapperState(O.binaryPath),await this.ensureWebUIBuilt(O.binaryPath),this.writeStarterConfig(),await N.workspace.getConfiguration("agentide.anywhere").update("enabled",!0,N.ConfigurationTarget.Global),O.running?(this.finishInstallUiState("running","success"),h.report({message:`Install complete. Gateway is running on port ${n}.`,increment:Math.max(0,100-_)})):(this.finishInstallUiState("installed","success"),h.report({message:"Install complete. Gateway is installed. Click Agent Anywhere to start.",increment:Math.max(0,100-_)})),N.window.showInformationMessage(O.running?`${D.AGENT_ANYWHERE_LABEL}: Installed and running. Open the config to add your channels or use the status bar to connect.`:`${D.AGENT_ANYWHERE_LABEL}: Installed. Open the config to add your channels, then click Agent Anywhere to start.`,"Open Config").then(async C=>{C==="Open Config"&&await this.openConfig()}),!0;await new Promise(v=>setTimeout(v,1e3))}return!1})?!0:(this.log("Gateway install timed out or failed"),this.finishInstallUiState("error","failure"),!1)}catch(s){return this.log(`Install failed: ${s instanceof Error?s.message:String(s)}`),this.finishInstallUiState("error","failure"),!1}finally{this._gatewayInstallInProgress&&(this.setInstallProgressFlag(!1,"finally"),this._installProgressMessage=void 0),this.updateStatusBar(this._status)}}async uninstall(){if(this._gatewayUninstallInProgress){await this.showGatewayUninstallInProgressPrompt();return}await this.stop();let e=le?"setup-gateway.ps1":"setup-gateway.sh",r=[V.join(__dirname,"..","scripts","gateway",e),V.join(__dirname,"..","..","scripts","gateway",e)].find(i=>G.existsSync(i)),s;if(r&&le){let i=`& "${r}" -Uninstall; Write-Host ""; Write-Host "You can close this window."`;s={name:wi,shellPath:"powershell.exe",shellArgs:["-NoProfile","-NoExit","-ExecutionPolicy","Bypass","-Command",i]}}else if(r){let o=`${`bash "${r}" --uninstall`}; echo ""; echo "Press Enter to close..."; read`;s={name:wi,shellPath:ul(),shellArgs:dl(o),env:rp()}}else{let i="npm uninstall -g openclaw",o=`${i}; echo ""; echo "Press Enter to close..."; read`;s=le?{name:wi,shellPath:"cmd.exe",shellArgs:["/c",`${i} && echo. && pause`]}:{name:wi,shellPath:ul(),shellArgs:dl(o),env:rp()}}this._gatewayUninstallInProgress=!0,this.setStatus("stopping");try{let i=N.window.createTerminal(s);this._uninstallSetupTerminal=i,i.show(),this.log("Gateway uninstall started in terminal"),(0,be.clearBinaryCache)(Qr),(0,be.clearBinaryCache)("openclaw"),await this.sleep(this.getUninstallInitialDelayMs());let o=Date.now()+this.getUninstallVerificationTimeoutMs(),a,c=!0;for(;Date.now()<o;){(0,be.clearBinaryCache)(Qr),(0,be.clearBinaryCache)("openclaw");let l=await this.detectGatewayState(this.getGatewayPort());if(a=l,this._lastDetection=l,c=await this.hasGlobalNpmOpenclawTree(),!c&&!l.running){yw(),this.setStatus("not-installed"),l.installed?this.log("Managed OpenClaw npm package removed; another OpenClaw binary remains on PATH (likely external/self-updated)."):this.log("Global OpenClaw package removed (or no longer detected).");return}if(!l.installed){yw(),this.setStatus("not-installed"),this.log("Global OpenClaw package removed (or no longer detected).");return}await this.sleep(this.getUninstallCheckIntervalMs())}!c&&a?.running?N.window.showWarningMessage(`${D.AGENT_ANYWHERE_LABEL}: Managed package was removed, but the gateway listener still appears to be running. Finish the terminal command or run Status.`):N.window.showWarningMessage(`${D.AGENT_ANYWHERE_LABEL}: Uninstall is still verifying managed package removal. Finish the terminal command or run Status.`)}finally{this._gatewayUninstallInProgress=!1,this.updateStatusBar(this._status)}}get configPath(){return V.join(es.homedir(),".openclaw","openclaw.json")}writeStarterConfig(){let e=V.dirname(this.configPath);if(G.existsSync(this.configPath)){this.log("Config already exists, skipping starter config");return}let r=[V.join(__dirname,"..","base-prompts","gateway","openclaw-starter.json5"),V.join(__dirname,"..","..","base-prompts","gateway","openclaw-starter.json5")].find(o=>G.existsSync(o));if(!r){this.log("Starter config template not found, skipping");return}G.mkdirSync(e,{recursive:!0,mode:448});let s=G.readFileSync(r,"utf-8"),i=`ah-${(0,Qf.randomBytes)(24).toString("hex")}`;s=s.replace("__GENERATED_TOKEN__",i),G.writeFileSync(this.configPath,s,{encoding:"utf-8",mode:le?void 0:384}),this.log(`Wrote starter config to ${this.configPath}`)}async openConfig(){G.existsSync(this.configPath)||this.writeStarterConfig();let e=await N.workspace.openTextDocument(this.configPath);await N.window.showTextDocument(e)}async preflightChannelSecrets(e){let n;try{n=G.readFileSync(this.configPath,"utf-8")}catch{return"continue"}let r=(0,ep.parseStrictJsonConfig)(n);if(r===void 0)return"continue";let s=(0,ep.collectMissingChannelEnvSecrets)(r,e);if(s.length===0)return"continue";let i=(0,Zf.getAgentHomeEnvFilePath)(),o=s.map(u=>u.channel).join(", "),a=[...new Set(s.flatMap(u=>u.envVars))];this.log(`Channel secrets preflight: ${o} missing ${a.join(", ")}`);let c=`Disable ${o} & Start`,l="Add Secrets",f=await N.window.showErrorMessage(`${D.AGENT_ANYWHERE_LABEL}: The ${o} channel needs ${a.join(", ")}, which ${a.length===1?"is":"are"} not set in ${i} or the IDE environment. Add the secret${a.length===1?"":"s"} or disable the channel to start the gateway.`,c,l);if(f===c){let u=(0,ep.disableChannelsInConfigText)(n,s.map(p=>p.channel));if(!u)return N.window.showErrorMessage(`${D.AGENT_ANYWHERE_LABEL}: Could not update ${this.configPath}. Set "enabled": false on the ${o} channel manually, then start again.`),"abort";let d=`${this.configPath}.bak-missing-secrets`;try{G.copyFileSync(this.configPath,d),G.writeFileSync(this.configPath,u,{encoding:"utf-8",mode:le?void 0:384})}catch(p){let g=p instanceof Error?p.message:String(p);return N.window.showErrorMessage(`${D.AGENT_ANYWHERE_LABEL}: Could not update ${this.configPath} (${g}).`),"abort"}return this.log(`Disabled channels missing secrets: ${o} (backup: ${d})`),N.window.showInformationMessage(`${D.AGENT_ANYWHERE_LABEL}: Disabled the ${o} channel (backup: ${V.basename(d)}). To re-enable: add ${a.join(", ")} to ${i}, set "enabled": true in the config, then restart the gateway.`),"continue"}return f===l&&await this.openEnvFileWithSecretStubs(i,a),"abort"}async openEnvFileWithSecretStubs(e,n){try{let r="";try{r=G.readFileSync(e,"utf-8")}catch{}let s=n.filter(o=>!new RegExp(`^\\s*#?\\s*${o}=`,"m").test(r));if(s.length){let o=r.length&&!r.endsWith(`
621
622
  `)?`
622
623
  `:"",a=[`# Added by ${D.AGENT_ANYWHERE_LABEL} \u2014 fill in, then start the gateway again.`,...s.map(c=>`${c}=`)].join(`
623
624
  `);G.writeFileSync(e,`${r}${o}${a}
624
- `,{encoding:"utf-8",mode:le?void 0:384})}let i=await N.workspace.openTextDocument(N.Uri.file(e));await N.window.showTextDocument(i,{preview:!1})}catch(r){let s=r instanceof Error?r.message:String(r);N.window.showErrorMessage(`${D.AGENT_ANYWHERE_LABEL}: Could not open ${e} (${s}).`)}}async startGatewayViaHiddenWindowsProcess(e,n,r,s,i){let o=(0,LM.buildWindowsArgumentLine)(n),a=o.length>0?` -ArgumentList '${dl(o)}'`:"",c=[`$proc = Start-Process -FilePath '${dl(e)}' -WindowStyle Hidden${a} -RedirectStandardOutput '${dl(r)}' -RedirectStandardError '${dl(s)}' -PassThru`,"Write-Output $proc.Id"].join("; ");return new Promise(l=>{let f="",u="",d=(0,pl.spawn)("powershell.exe",["-NoProfile","-ExecutionPolicy","Bypass","-Command",c],{windowsHide:!0,env:i});d.stdout.on("data",p=>{f+=p.toString()}),d.stderr.on("data",p=>{u+=p.toString()}),d.once("error",p=>{this.log(`Gateway hidden Windows launcher failed to spawn: ${p}`),l(void 0)}),d.once("exit",p=>{if(p!==0){let m=u.trim()||f.trim();this.log(`Gateway hidden Windows launcher exited with code ${p}${m?`: ${m}`:""}`),l(void 0);return}let g=parseInt(f.trim(),10);if(!Number.isNaN(g)){this.log(`Gateway hidden Windows process started (PID: ${g})`),l(g);return}this.log("Gateway hidden Windows launcher did not return a PID"),l(void 0)})})}async start(){if(this._gatewayUninstallInProgress){await this.showGatewayUninstallInProgressPrompt();return}if(this._startInFlight){this.setStatus("starting"),await this._startInFlight;return}this.setStatus("starting");let e=this.doStart();this._startInFlight=e;try{await e}finally{this._startInFlight===e&&(this._startInFlight=null)}}async doStart(){let e=this.getGatewayPort(),n=await this.detectGatewayFastState(e);if(n?.running){this.log("Gateway already running (fast check)"),this._lastDetection=n,this.setStatus("running");return}let r=await this.detect(),s=await this.probeGatewayPort(e);if(!r.installed){if(s&&(!await this.promptNonManagedPortTakeover(e,"start")||await this.probeGatewayPort(e))){this.setStatus("error");return}await N.window.showWarningMessage(`${D.AGENT_ANYWHERE_LABEL}: Gateway is not installed.`,"Install Now")==="Install Now"?await this.install():this.setStatus("not-installed");return}if(r.running){this.log("Gateway already running"),this.setStatus("running");return}if(s&&(!await this.promptNonManagedPortTakeover(e,"start")||await this.probeGatewayPort(e))){this.setStatus("error");return}if(!r.binaryPath){this.setStatus("error"),N.window.showErrorMessage(`${D.AGENT_ANYWHERE_LABEL}: Gateway binary not found. Try reinstalling.`);return}let i=r.binaryPath;if(await this.probeGatewayPort(e)&&await hl(e,i)){this.log("Healthy gateway already listening; attaching instead of starting a new one"),this._lastDetection={...r,running:!0},this.setStatus("running");return}await this.stopExistingGatewayBeforeStart(i),await this.removeStaleGatewayLockBeforeStart(e);let o=["gateway","run","--bind","loopback","--port",String(e)];await this.probeGatewayPort(e)&&o.push("--force");let a=i,c=o,l=!1,f=this.isWindowsLaunch();if(f){let h=await this.resolveWindowsManagedGatewayLaunchRuntime(i);if(!h){this.setStatus("installed"),await N.window.showWarningMessage(`${D.AGENT_ANYWHERE_LABEL}: Windows background start requires managed gateway runtime metadata. Reinstall Agent Anywhere to refresh the launch configuration.`,"Reinstall")==="Reinstall"&&await this.install();return}a=h.nodePath,c=[h.entryScriptPath,...o]}let u=V.dirname(rp);G.mkdirSync(u,{recursive:!0});let d=rp,p=V.join(u,"gateway.error.log");this.log(`Starting gateway: ${a} ${c.join(" ")}`),this.log(`Gateway log: ${d}`);let g=await(0,Qf.readGatewayChildProcessEnv)();g.OPENCLAW_NO_RESPAWN="1";for(let h of Qf.GATEWAY_SECRET_ENV_KEYS)g[h]?.trim()&&this.log(`Gateway env: ${h} present for child process`);if(await this.preflightChannelSecrets(g)==="abort"){this.setStatus("installed");return}let m;if(f){if(m=await this.startGatewayViaHiddenWindowsProcess(a,c,d,p,g),this.process=null,!m){this.setStatus("error"),await ea(d);return}}else{let h=G.openSync(d,"a");this.process=(0,pl.spawn)(a,c,{stdio:["ignore",h,h],detached:!0,env:g,shell:l,windowsHide:!0}),G.closeSync(h),this.process.unref(),this.process.on("exit",E=>{this.log(`Gateway process exited with code ${E}`),this.process=null,sp(),!this._startInFlight&&this.setStatus(E!==0&&E!==null?"error":"installed")})}await N.window.withProgress({location:N.ProgressLocation.Window,title:`${D.AGENT_ANYWHERE_LABEL}: Starting gateway...`},async h=>{try{let E=Date.now(),_=this.getStartupTimeoutMs(),y=this.getStartupLaunchGraceMs(),b=this.getStartupCheckIntervalMs(),T=0,O=0,A=!1,v=!1,C=this.process?.pid??m;for(;;){if(await this.probeGatewayPort(e)){this.setStatus("running"),this.log(`Gateway started and ready (${T}ms)`);let Ne=this.process?.pid??m;Ne&&(await this.writeGatewayPidRecord(Ne,e,i),this.log(`PID file written: ${_l}`)),this.startHealthChecks(e),h.report({message:"Ready!",increment:100});return}let B=this.isStartedGatewayProcessAlive(C);C&&B&&(A=!0),T=Date.now()-E;let R=T<_,F=C!==void 0&&B&&A&&T<_+y,re=!B&&(A||this.process===null);if(C&&re&&!f){this.setStatus("error"),this.log(`Gateway process exited before opening port ${e}`),await ea(d);return}if(C&&A&&!B&&f&&!v&&(v=!0,this.log(`Gateway launch process exited before opening port ${e}; continuing to wait for port readiness`)),!R&&!F)break;let W=Math.max(_+(F?y:0),1),de=Math.min(90,Math.floor(T/W*100)),he=Math.max(0,de-O);O=de;let z=C!==void 0?B?`Gateway launched (PID ${C}), waiting for port ${e}...`:"Waiting for gateway process to initialize...":`Waiting for port ${e}...`;h.report({message:z,increment:he}),await this.sleep(b)}this.setStatus("error"),this.log(`Gateway failed to start within timeout (pid=${C??"n/a"}, alive=${C!==void 0?this.isStartedGatewayProcessAlive(C):!1})`),await ea(d)}catch{this.setStatus("error"),this.log("Gateway failed to start"),await ea(d)}})}async stop(){if(this.stopHealthChecks(),await this.disconnectBridge(),this.process){this.setStatus("stopping"),this.log("Stopping gateway...");let r=this.getGatewayPort(),s=this.process.pid,i=await eo(r),o=[...new Set([s,...i].filter(l=>typeof l=="number"&&l>0))];le&&s?await Gt(`taskkill /F /T /PID ${s}`,{timeout:5e3}).catch(()=>{}):Ew(this.process,s,"SIGTERM"),!await new Promise(l=>{let f=setTimeout(()=>l(!1),5e3);this.process?.once("exit",()=>{clearTimeout(f),l(!0)})})&&this.process&&(this.log("Forcefully killing gateway..."),le&&s?await Gt(`taskkill /F /T /PID ${s}`,{timeout:5e3}).catch(()=>{}):Ew(this.process,s,"SIGKILL")),this.process=null,await sp();let c=await ml(r,o);c||(this.log("Gateway port still held after process exit; reaping listener(s)..."),await dp(r),c=await ml(r,[...o,...await eo(r)])),c?(this.setStatus("installed"),this.log("Gateway stopped")):(this.setStatus("running"),this.log("Could not free gateway port after stop"),N.window.showWarningMessage(`${D.AGENT_ANYWHERE_LABEL}: Could not fully stop the gateway. Try stopping it manually.`));return}let e=await this.detect();if(!e.running){this.log("Gateway is not running");return}this.setStatus("stopping"),this.log("Stopping externally started gateway...");let n=await _w(e.port,e.binaryPath,r=>this.log(r));await sp(),n?(this.setStatus("installed"),this.log("Gateway stopped")):(this.setStatus("running"),this.log("Could not stop gateway process"),N.window.showWarningMessage(`${D.AGENT_ANYWHERE_LABEL}: Could not stop the gateway. Try stopping it manually.`))}async restartGateway(){let e=this._bridgeRef?.isConnected??!1;await this.disconnectBridge();let n=this._status==="running";n||(n=await(0,be.probePort)(this.getGatewayPort(),"127.0.0.1",250)),n?await this.stop():this.log("Restart requested while gateway is stopped; skipping stop."),await this.start(),e&&this._status==="running"&&await this.connectBridge()}async showStatus(){this.setBridgeConnected(this._bridgeRef?.isConnected??!1);let e=this.getGatewayPort(),n=this._lastDetection??await this.detect(),r=n.running?"\u{1F7E2} Running":n.installed?"\u26AB Stopped":"\u2B1C Not installed",s=this._bridgeConnected?"\u{1F7E2} Connected":"\u26AB Disconnected",i=n.version?` (${n.version})`:"",o=[`Gateway: ${r}${i}`,`Bridge: ${s}`,`Port: ${e}`].join(`
625
+ `,{encoding:"utf-8",mode:le?void 0:384})}let i=await N.workspace.openTextDocument(N.Uri.file(e));await N.window.showTextDocument(i,{preview:!1})}catch(r){let s=r instanceof Error?r.message:String(r);N.window.showErrorMessage(`${D.AGENT_ANYWHERE_LABEL}: Could not open ${e} (${s}).`)}}async startGatewayViaHiddenWindowsProcess(e,n,r,s,i){let o=(0,HM.buildWindowsArgumentLine)(n),a=o.length>0?` -ArgumentList '${fl(o)}'`:"",c=[`$proc = Start-Process -FilePath '${fl(e)}' -WindowStyle Hidden${a} -RedirectStandardOutput '${fl(r)}' -RedirectStandardError '${fl(s)}' -PassThru`,"Write-Output $proc.Id"].join("; ");return new Promise(l=>{let f="",u="",d=(0,gl.spawn)("powershell.exe",["-NoProfile","-ExecutionPolicy","Bypass","-Command",c],{windowsHide:!0,env:i});d.stdout.on("data",p=>{f+=p.toString()}),d.stderr.on("data",p=>{u+=p.toString()}),d.once("error",p=>{this.log(`Gateway hidden Windows launcher failed to spawn: ${p}`),l(void 0)}),d.once("exit",p=>{if(p!==0){let m=u.trim()||f.trim();this.log(`Gateway hidden Windows launcher exited with code ${p}${m?`: ${m}`:""}`),l(void 0);return}let g=parseInt(f.trim(),10);if(!Number.isNaN(g)){this.log(`Gateway hidden Windows process started (PID: ${g})`),l(g);return}this.log("Gateway hidden Windows launcher did not return a PID"),l(void 0)})})}async start(){if(this._gatewayUninstallInProgress){await this.showGatewayUninstallInProgressPrompt();return}if(this._startInFlight){this.setStatus("starting"),await this._startInFlight;return}this.setStatus("starting");let e=this.doStart();this._startInFlight=e;try{await e}finally{this._startInFlight===e&&(this._startInFlight=null)}}async doStart(){let e=this.getGatewayPort(),n=await this.detectGatewayFastState(e);if(n?.running){this.log("Gateway already running (fast check)"),this._lastDetection=n,this.setStatus("running");return}let r=await this.detect(),s=await this.probeGatewayPort(e);if(!r.installed){if(s&&(!await this.promptNonManagedPortTakeover(e,"start")||await this.probeGatewayPort(e))){this.setStatus("error");return}await N.window.showWarningMessage(`${D.AGENT_ANYWHERE_LABEL}: Gateway is not installed.`,"Install Now")==="Install Now"?await this.install():this.setStatus("not-installed");return}if(r.running){this.log("Gateway already running"),this.setStatus("running");return}if(s&&(!await this.promptNonManagedPortTakeover(e,"start")||await this.probeGatewayPort(e))){this.setStatus("error");return}if(!r.binaryPath){this.setStatus("error"),N.window.showErrorMessage(`${D.AGENT_ANYWHERE_LABEL}: Gateway binary not found. Try reinstalling.`);return}let i=r.binaryPath;if(await this.probeGatewayPort(e)&&await ml(e,i)){this.log("Healthy gateway already listening; attaching instead of starting a new one"),this._lastDetection={...r,running:!0},this.setStatus("running");return}await this.stopExistingGatewayBeforeStart(i),await this.removeStaleGatewayLockBeforeStart(e);let o=["gateway","run","--bind","loopback","--port",String(e)];await this.probeGatewayPort(e)&&o.push("--force");let a=i,c=o,l=!1,f=this.isWindowsLaunch();if(f){let h=await this.resolveWindowsManagedGatewayLaunchRuntime(i);if(!h){this.setStatus("installed"),await N.window.showWarningMessage(`${D.AGENT_ANYWHERE_LABEL}: Windows background start requires managed gateway runtime metadata. Reinstall Agent Anywhere to refresh the launch configuration.`,"Reinstall")==="Reinstall"&&await this.install();return}a=h.nodePath,c=[h.entryScriptPath,...o]}let u=V.dirname(sp);G.mkdirSync(u,{recursive:!0});let d=sp,p=V.join(u,"gateway.error.log");this.log(`Starting gateway: ${a} ${c.join(" ")}`),this.log(`Gateway log: ${d}`);let g=await(0,Zf.readGatewayChildProcessEnv)();g.OPENCLAW_NO_RESPAWN="1";for(let h of Zf.GATEWAY_SECRET_ENV_KEYS)g[h]?.trim()&&this.log(`Gateway env: ${h} present for child process`);if(await this.preflightChannelSecrets(g)==="abort"){this.setStatus("installed");return}let m;if(f){if(m=await this.startGatewayViaHiddenWindowsProcess(a,c,d,p,g),this.process=null,!m){this.setStatus("error"),await ta(d);return}}else{let h=G.openSync(d,"a");this.process=(0,gl.spawn)(a,c,{stdio:["ignore",h,h],detached:!0,env:g,shell:l,windowsHide:!0}),G.closeSync(h),this.process.unref(),this.process.on("exit",E=>{this.log(`Gateway process exited with code ${E}`),this.process=null,ip(),!this._startInFlight&&this.setStatus(E!==0&&E!==null?"error":"installed")})}await N.window.withProgress({location:N.ProgressLocation.Window,title:`${D.AGENT_ANYWHERE_LABEL}: Starting gateway...`},async h=>{try{let E=Date.now(),_=this.getStartupTimeoutMs(),y=this.getStartupLaunchGraceMs(),b=this.getStartupCheckIntervalMs(),T=0,O=0,A=!1,v=!1,C=this.process?.pid??m;for(;;){if(await this.probeGatewayPort(e)){this.setStatus("running"),this.log(`Gateway started and ready (${T}ms)`);let Ne=this.process?.pid??m;Ne&&(await this.writeGatewayPidRecord(Ne,e,i),this.log(`PID file written: ${yl}`)),this.startHealthChecks(e),h.report({message:"Ready!",increment:100});return}let B=this.isStartedGatewayProcessAlive(C);C&&B&&(A=!0),T=Date.now()-E;let R=T<_,F=C!==void 0&&B&&A&&T<_+y,re=!B&&(A||this.process===null);if(C&&re&&!f){this.setStatus("error"),this.log(`Gateway process exited before opening port ${e}`),await ta(d);return}if(C&&A&&!B&&f&&!v&&(v=!0,this.log(`Gateway launch process exited before opening port ${e}; continuing to wait for port readiness`)),!R&&!F)break;let W=Math.max(_+(F?y:0),1),de=Math.min(90,Math.floor(T/W*100)),he=Math.max(0,de-O);O=de;let Q=C!==void 0?B?`Gateway launched (PID ${C}), waiting for port ${e}...`:"Waiting for gateway process to initialize...":`Waiting for port ${e}...`;h.report({message:Q,increment:he}),await this.sleep(b)}this.setStatus("error"),this.log(`Gateway failed to start within timeout (pid=${C??"n/a"}, alive=${C!==void 0?this.isStartedGatewayProcessAlive(C):!1})`),await ta(d)}catch{this.setStatus("error"),this.log("Gateway failed to start"),await ta(d)}})}async stop(){if(this.stopHealthChecks(),await this.disconnectBridge(),this.process){this.setStatus("stopping"),this.log("Stopping gateway...");let r=this.getGatewayPort(),s=this.process.pid,i=await no(r),o=[...new Set([s,...i].filter(l=>typeof l=="number"&&l>0))];le&&s?await Gt(`taskkill /F /T /PID ${s}`,{timeout:5e3}).catch(()=>{}):Aw(this.process,s,"SIGTERM"),!await new Promise(l=>{let f=setTimeout(()=>l(!1),5e3);this.process?.once("exit",()=>{clearTimeout(f),l(!0)})})&&this.process&&(this.log("Forcefully killing gateway..."),le&&s?await Gt(`taskkill /F /T /PID ${s}`,{timeout:5e3}).catch(()=>{}):Aw(this.process,s,"SIGKILL")),this.process=null,await ip();let c=await El(r,o);c||(this.log("Gateway port still held after process exit; reaping listener(s)..."),await fp(r),c=await El(r,[...o,...await no(r)])),c?(this.setStatus("installed"),this.log("Gateway stopped")):(this.setStatus("running"),this.log("Could not free gateway port after stop"),N.window.showWarningMessage(`${D.AGENT_ANYWHERE_LABEL}: Could not fully stop the gateway. Try stopping it manually.`));return}let e=await this.detect();if(!e.running){this.log("Gateway is not running");return}this.setStatus("stopping"),this.log("Stopping externally started gateway...");let n=await Sw(e.port,e.binaryPath,r=>this.log(r));await ip(),n?(this.setStatus("installed"),this.log("Gateway stopped")):(this.setStatus("running"),this.log("Could not stop gateway process"),N.window.showWarningMessage(`${D.AGENT_ANYWHERE_LABEL}: Could not stop the gateway. Try stopping it manually.`))}async restartGateway(){let e=this._bridgeRef?.isConnected??!1;await this.disconnectBridge();let n=this._status==="running";n||(n=await(0,be.probePort)(this.getGatewayPort(),"127.0.0.1",250)),n?await this.stop():this.log("Restart requested while gateway is stopped; skipping stop."),await this.start(),e&&this._status==="running"&&await this.connectBridge()}async showStatus(){this.setBridgeConnected(this._bridgeRef?.isConnected??!1);let e=this.getGatewayPort(),n=this._lastDetection??await this.detect(),r=n.running?"\u{1F7E2} Running":n.installed?"\u26AB Stopped":"\u2B1C Not installed",s=this._bridgeConnected?"\u{1F7E2} Connected":"\u26AB Disconnected",i=n.version?` (${n.version})`:"",o=[`Gateway: ${r}${i}`,`Bridge: ${s}`,`Port: ${e}`].join(`
625
626
  `);if(!n.installed){await N.window.showInformationMessage(`${D.AGENT_ANYWHERE_LABEL}
626
627
  ${o}`,"Set Up")==="Set Up"&&await this.install();return}if(!n.running){switch(await N.window.showInformationMessage(`${D.AGENT_ANYWHERE_LABEL}
627
628
  ${o}`,"Connect","Config","Uninstall")){case"Connect":await this.start(),this._status==="running"&&await this.connectBridge();break;case"Config":await this.openConfig();break;case"Uninstall":await this.uninstall();break}return}switch(await N.window.showInformationMessage(`${D.AGENT_ANYWHERE_LABEL}
628
- ${o}`,"Web UI","Config","Restart","Reset auth","Uninstall")){case"Web UI":await this.openWebUI();break;case"Config":await this.openConfig();break;case"Restart":await this.restartGateway();break;case"Reset auth":await this.resetAuth();break;case"Uninstall":await this.uninstall();break}}async resetAuth(){try{G.existsSync(this.configPath)||this.writeStarterConfig();let n=G.readFileSync(this.configPath,"utf-8").replace(/^\s*\/\/.*$/gm,"").replace(/,\s*([}\]])/g,"$1"),r=JSON.parse(n);(!r.gateway||typeof r.gateway!="object")&&(r.gateway={}),(!r.gateway.auth||typeof r.gateway.auth!="object")&&(r.gateway.auth={});let s=`ah-${(0,zf.randomBytes)(24).toString("hex")}`;r.gateway.auth.token=s,G.writeFileSync(this.configPath,`${JSON.stringify(r,null,2)}
629
- `,{encoding:"utf-8",mode:le?void 0:384}),await N.workspace.getConfiguration("agentide.gateway").update("token",s,N.ConfigurationTarget.Global),await this.restartGateway(),N.window.showInformationMessage(`${D.AGENT_ANYWHERE_LABEL}: Auth reset; gateway restarted. If you use the Web UI, paste the new token in Control UI settings.`)}catch(e){this.log(`Failed to reset auth: ${e instanceof Error?e.message:String(e)}`),N.window.showErrorMessage(`${D.AGENT_ANYWHERE_LABEL}: Failed to reset auth. Open Config to update it manually.`)}}async connectBridge(){if(!this._bridgeRef){this.log("Bridge ref not set -- cannot connect");return}if(this._gatewayUninstallInProgress){await this.showGatewayUninstallInProgressPrompt();return}if(this._bridgeRef.isConnected){this.log("Bridge already connected");return}let e=this.getGatewayPort();if(await(0,be.probePort)(e)&&!await hl(e,this._lastDetection?.binaryPath)&&(!await this.promptNonManagedPortTakeover(e,"connect")||await(0,be.probePort)(e))){this._status==="running"&&this.setStatus("installed");return}let n=this._status==="running";if(!n){let c=await ip(e);c?.running&&(n=!0,this._lastDetection=c,this.setStatus("running"))}if(!n){let c=await this.detect();if(!c.running){if(!c.installed){await N.window.showInformationMessage(`${D.AGENT_ANYWHERE_LABEL}: Reach your AgentHippo IDE or CLI agents from WhatsApp, Telegram, Slack, Discord, and more - right from your phone or any messaging app. This will also install OpenClaw fork on your computer.`,"Set Up Agent Anywhere")==="Set Up Agent Anywhere"&&await this.install();return}if(await this.start(),!(await this.detect()).running){this.log("Gateway failed to start, cannot connect"),await ea(rp);return}}}let r=N.workspace.getConfiguration("agentide.gateway"),s=r.get("url","").trim();s||(s=`ws://127.0.0.1:${e}`,await r.update("url",s,N.ConfigurationTarget.Global));let i=/127\.0\.0\.1|localhost|\[::1\]/i.test(s),o=this.readGatewayToken();o&&i&&(await r.update("token",o,N.ConfigurationTarget.Global),this.log("Gateway token applied from openclaw.json (user scope)")),await this._bridgeRef.connect(),this.setBridgeConnected(this._bridgeRef.isConnected),await(0,be.probePort)(e)?this._status!=="running"&&this.setStatus("running"):this._status!=="installed"&&this.setStatus("installed"),this.updateStatusBar(this._status),this.log("Bridge connected")}async disconnectBridge(){this._bridgeRef&&(await this._bridgeRef.disconnect(),this.setBridgeConnected(!1),this.updateStatusBar(this._status),this.log("Bridge disconnected"))}async openWebUI(){let e=this.getGatewayPort();if(!(this._status==="running"||await(0,be.probePort)(e))){await N.window.showWarningMessage(`${D.AGENT_ANYWHERE_LABEL}: Gateway is not running. Start it first to use the web UI.`,"Start Now")==="Start Now"&&await this.start();return}let r=(N.workspace.getConfiguration("agentide.gateway").get("token")??"").trim(),s=this.readGatewayToken()??(r||void 0),i=s?`#token=${encodeURIComponent(s)}`:"",o=`http://127.0.0.1:${e}/${i}`;await N.env.openExternal(N.Uri.parse(o))}startHealthChecks(e){this.stopHealthChecks(),this.healthCheckTimer=setInterval(async()=>{await(0,be.probePort)(e)||(this.log("Health check failed -- gateway is no longer running"),this.stopHealthChecks(),this.process=null,this.setStatus("installed"))},xM)}stopHealthChecks(){this.healthCheckTimer&&(clearInterval(this.healthCheckTimer),this.healthCheckTimer=null)}async ensureWebUIBuilt(e){if(e)try{let n=Ep(e);if(!n)return;let r=V.join(n,"dist","control-ui","index.html");if(G.existsSync(r))return;this.log("Web UI not built - building now..."),await Gt(le?"pnpm.cmd ui:build":"pnpm ui:build",{cwd:n,timeout:6e4,env:{...process.env},...le?{shell:"cmd.exe"}:{}}),this.log("Web UI built successfully")}catch(n){this.log(`Web UI build failed (non-fatal): ${n instanceof Error?n.message:String(n)}`)}}async promptNonManagedPortTakeover(e,n){let r=n==="connect"?"connect Agent Anywhere":"start Agent Anywhere";if(await N.window.showWarningMessage(`${D.AGENT_ANYWHERE_LABEL}: Port ${e} is in use by a non-managed process. Stop that process and ${r}?`,{modal:!0},"Yes","No")!=="Yes")return this.log(`User declined non-managed port takeover on ${e}`),!1;this.log(`User approved non-managed port takeover on ${e}`);let i=new Set(await eo(e));if(!await _w(e,void 0,a=>this.log(a))){let a=await eo(e);return i.size>0&&a.some(l=>!i.has(l))?N.window.showWarningMessage(`${D.AGENT_ANYWHERE_LABEL}: Port ${e} is held by a self-restarting gateway service. Run \`openclaw daemon uninstall\` to remove it, then try again.`):N.window.showErrorMessage(`${D.AGENT_ANYWHERE_LABEL}: Could not free port ${e}. Stop that process manually and try again.`),!1}return!0}async ensureManagedGatewayWrapperState(e,n=!1){try{let r=Si(),s=await lp(e,r);if(!s)return;let{launcherPath:i,packageRoot:o,nodePath:a,entryScriptPath:c}=s,l=gw(a,c,Aw),f;return(n||Ow(ap))&&(f=gw(a,c,ap)),WM({...r,nodePath:a,cliPath:i,entryScriptPath:c,packageRoot:o,wrapperPath:l,wrapperDir:hp,openclawWrapperPath:f,updatedAt:new Date().toISOString()}),l}catch(r){this.log(`Managed gateway wrapper setup failed: ${r instanceof Error?r.message:String(r)}`);return}}async resolveWindowsManagedGatewayLaunchRuntime(e){if(!le)return;await this.ensureManagedGatewayWrapperState(e);let n=await lp(e);if(n)return{nodePath:n.nodePath,entryScriptPath:n.entryScriptPath}}readGatewayToken(){try{if(!G.existsSync(this.configPath))return;let n=G.readFileSync(this.configPath,"utf-8").replace(/^\s*\/\/.*$/gm,"").replace(/,\s*([}\]])/g,"$1"),s=JSON.parse(n)?.gateway?.auth?.token;return typeof s=="string"&&s.trim()?s.trim():void 0}catch(e){this.log(`Could not read gateway token: ${e}`);return}}setStatus(e){this._status=e,this.updateStatusBar(e),this._onStatusChange.fire(e)}updateStatusBar(e){if(this.getConfig("hidden",!1)){this.statusBarItem.hide();return}switch(e){case"not-installed":this.statusBarItem.text=`$(cloud-download) ${D.AGENT_ANYWHERE_LABEL}`,this.statusBarItem.tooltip=`${D.AGENT_ANYWHERE_LABEL}: Reach your agents from WhatsApp, Telegram, Slack (click to set up)`,this.statusBarItem.color=void 0,this.statusBarItem.backgroundColor=void 0;break;case"installed":this.statusBarItem.text=`$(debug-disconnect) ${D.AGENT_ANYWHERE_LABEL}`,this.statusBarItem.tooltip=`${D.AGENT_ANYWHERE_LABEL}: Installed, not running (click to start)`,this.statusBarItem.color=void 0,this.statusBarItem.backgroundColor=void 0;break;case"starting":this.statusBarItem.text=`$(sync~spin) ${D.AGENT_ANYWHERE_LABEL}`,this.statusBarItem.tooltip=this._gatewayInstallInProgress?`${D.AGENT_ANYWHERE_LABEL}: ${this._installProgressMessage??"Installing... (see Setup terminal)"}`:`${D.AGENT_ANYWHERE_LABEL}: Starting...`,this.statusBarItem.color=void 0,this.statusBarItem.backgroundColor=void 0;break;case"running":this._bridgeConnected?(this.statusBarItem.text=`$(broadcast) ${D.AGENT_ANYWHERE_LABEL}`,this.statusBarItem.tooltip=`${D.AGENT_ANYWHERE_LABEL}: Connected (click for options)`,this.statusBarItem.color=new N.ThemeColor("testing.iconPassed")):(this.statusBarItem.text=`$(debug-disconnect) ${D.AGENT_ANYWHERE_LABEL}`,this.statusBarItem.tooltip=`${D.AGENT_ANYWHERE_LABEL}: Disconnected (click to connect)`,this.statusBarItem.color=void 0),this.statusBarItem.backgroundColor=void 0;break;case"stopping":this.statusBarItem.text=`$(sync~spin) ${D.AGENT_ANYWHERE_LABEL}`,this.statusBarItem.tooltip=this._gatewayUninstallInProgress?`${D.AGENT_ANYWHERE_LABEL}: Uninstalling... (see Uninstall terminal)`:`${D.AGENT_ANYWHERE_LABEL}: Stopping...`,this.statusBarItem.color=void 0,this.statusBarItem.backgroundColor=void 0;break;case"error":this.statusBarItem.text=`$(warning) ${D.AGENT_ANYWHERE_LABEL}`,this.statusBarItem.tooltip=`${D.AGENT_ANYWHERE_LABEL}: Error (click for details)`,this.statusBarItem.color=new N.ThemeColor("errorForeground"),this.statusBarItem.backgroundColor=void 0;break}this.statusBarItem.show()}getConfig(e,n){return N.workspace.getConfiguration("agentide.anywhere").get(e,n)}async hasGlobalNpmOpenclawTree(){return(await ta()).length>0}readGatewayPortFromOpenclawJson(){try{if(!G.existsSync(this.configPath))return;let n=G.readFileSync(this.configPath,"utf-8").replace(/^\s*\/\/.*$/gm,"").replace(/,\s*([}\]])/g,"$1"),s=JSON.parse(n)?.gateway?.port;if(typeof s=="number"&&Number.isFinite(s)){let i=Math.floor(s);if(i>=1&&i<=65535)return i}if(typeof s=="string"&&/^\d+$/.test(s)){let i=parseInt(s,10);if(i>=1&&i<=65535)return i}return}catch{return}}getGatewayPort(){let e=this.readGatewayPortFromOpenclawJson();return e!==void 0?e:this.getConfig("port",Ai)}log(e){this.outputChannel.appendLine(`[${D.AGENT_ANYWHERE_LABEL}] ${e}`)}dispose(){this.stopHealthChecks(),this.process=null,this.statusBarItem.dispose(),this._onStatusChange.dispose();for(let e of this.disposables)e.dispose()}};D.GatewayLifecycleManager=fp});var kw=S(_p=>{"use strict";Object.defineProperty(_p,"__esModule",{value:!0});_p.anywhereCommand=sG;var yl=Rw(),ns=Wn(),rG=18789;async function sG(t){switch(t.action?.trim().toLowerCase()){case"status":case"detect":await iG(t);return;case"help":case"usage":case"":case void 0:Cw();return;default:console.error(`${ns.COLORS.red}Error:${ns.COLORS.reset} Unsupported action "${t.action}".`),Cw(),process.exitCode=1;return}}async function iG(t){let e=t.port??rG;try{let n=await(0,yl.detectGateway)(e),r=n.running?"Running":n.installed?"Installed":"Not installed",s=n.running?ns.COLORS.green:n.installed?ns.COLORS.yellow:ns.COLORS.red;console.log(`${s}${yl.AGENT_ANYWHERE_LABEL}:${ns.COLORS.reset} ${r}`),console.log(`Port: ${n.port}`),n.binaryPath&&console.log(`Binary: ${n.binaryPath}`),n.version&&console.log(`Version: ${n.version}`),n.installed||console.log(`${ns.COLORS.dim}Install via the Agent Anywhere UI inside ${yl.AGENT_ANYWHERE_LABEL} in VS Code.${ns.COLORS.reset}`)}catch(n){console.error(`${ns.COLORS.red}Error:${ns.COLORS.reset} ${n instanceof Error?n.message:String(n)}`),process.exitCode=1}}function Cw(){console.log([`${yl.AGENT_ANYWHERE_LABEL} CLI`,"","Usage:"," agenthippo anywhere status"," agenthippo anywhere detect","","Note: install/start/stop is currently managed via the Agent Anywhere UI in VS Code."].join(`
630
- `))}});var Mw=S(rs=>{"use strict";var oG=rs&&rs.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,s)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),aG=rs&&rs.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),cG=rs&&rs.__importStar||(function(){var t=function(e){return t=Object.getOwnPropertyNames||function(n){var r=[];for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(r[r.length]=s);return r},t(e)};return function(e){if(e&&e.__esModule)return e;var n={};if(e!=null)for(var r=t(e),s=0;s<r.length;s++)r[s]!=="default"&&oG(n,e,r[s]);return aG(n,e),n}})();Object.defineProperty(rs,"__esModule",{value:!0});rs.gatewaySendCommand=pG;rs.gatewayListCommand=gG;var lG=require("fs/promises"),uG=cG(require("path")),wl=Rc(),dG=Fd(),Ze=Wn();function Dw(t){let e=t.trim();return e||(console.error("Error: --outbound is required"),process.exit(1)),uG.resolve(e)}async function Lw(t){try{await(0,lG.access)(t)}catch{console.error(`Error: gateway outbound file not found: ${t}`),process.exit(1)}}async function fG(t,e,n){let r=n.message.trim();r||(console.error("Error: --message is required"),process.exit(1)),n.dryRun&&(console.log(`${Ze.COLORS.dim}Dry run (egress broker):${Ze.COLORS.reset} POST ${t} { to: ${n.target??"(reply-to-sender)"} }`),process.exit(0));let s;try{s=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify({message:r,to:n.target?.trim()||void 0,media:n.media?.trim()||void 0})})}catch(a){console.error(`${Ze.COLORS.red}\u2717${Ze.COLORS.reset} Egress broker unreachable: ${a instanceof Error?a.message:String(a)}`),process.exit(1)}let i=await s.text(),o={};try{o=JSON.parse(i)}catch{}n.json?console.log(JSON.stringify({via:"egress-broker",status:s.status,result:o},null,2)):s.ok&&o.ok?console.log(`${Ze.COLORS.green}\u2713${Ze.COLORS.reset} Sent (via egress broker${o.via?`, ${o.via}`:""})`):(console.error(`${Ze.COLORS.red}\u2717${Ze.COLORS.reset} Egress send rejected (HTTP ${s.status}): ${o.error||i||"unknown error"}`),process.exit(1)),process.exit(s.ok&&o.ok?0:1)}async function pG(t){let e=process.env.AGENTHIPPO_EGRESS_URL?.trim(),n=process.env.AGENTHIPPO_TURN_NONCE?.trim();if(e&&n){await fG(e,n,t);return}e&&(console.error("Error: egress broker is active but AGENTHIPPO_TURN_NONCE is missing \u2014 refusing direct gateway send"),process.exit(1));let r=Dw(t.outbound);await Lw(r);let s=t.agent.trim(),i=t.message.trim();s||(console.error("Error: --agent is required"),process.exit(1)),i||(console.error("Error: --message is required"),process.exit(1));let o=await(0,wl.resolveGatewayOutboundHandle)(r,s,{target:t.target,threadId:t.threadId});o||(console.error(`Error: No gateway outbound handle for agent "${s}" in ${r}.`),t.target&&console.error(`No stored route matching target "${t.target}".`),console.error(`Run \`agenthippo gateway list --outbound "${r}" --agent ${s}\` to see known routes.`),process.exit(1));let a=await(0,dG.sendGatewayOutboundMessage)(o,{message:i,media:t.media,dryRun:t.dryRun});if(t.json)console.log(JSON.stringify({file:r,handle:o,result:a},null,2));else if(t.dryRun)console.log(`${Ze.COLORS.dim}Dry run:${Ze.COLORS.reset} ${a.command.join(" ")}`);else if(a.ok){let c=a.via==="hippoclaw"?" (via hippoclaw CLI fallback)":"";console.log(`${Ze.COLORS.green}\u2713${Ze.COLORS.reset} Sent via ${o.channel}:${o.target}${c}`),a.stdout&&console.log(a.stdout)}else console.error(`${Ze.COLORS.red}\u2717${Ze.COLORS.reset} Gateway send failed (exit ${a.exitCode??"unknown"})`),a.stderr&&console.error(a.stderr),a.stdout&&console.error(a.stdout),process.exit(1);process.exit(0)}function $w(t,e){let n=t.label?` (${t.label})`:"",r=t.threadId?` thread=${t.threadId}`:"",s=t.inboundCount>1?` \xD7${t.inboundCount}`:"";return`${e?`${Ze.COLORS.green}*${Ze.COLORS.reset} `:" "}${t.agentId}${n}: ${t.channel} \u2192 ${t.target}${r}${s}`}async function gG(t){let e=Dw(t.outbound);await Lw(e);let n=await(0,wl.getGatewayOutboundStoreSnapshot)(e);if(t.json){console.log(JSON.stringify({file:e,...n},null,2));return}let r=t.agent?.trim(),s=r?[r]:[...new Set([...Object.keys(n.targetsByAgent),...Object.keys(n.lastByAgent)])];if(s.length===0){console.log(`No gateway outbound routes in ${e}.`);return}console.log(`${Ze.COLORS.dim}${e}${Ze.COLORS.reset}`);for(let i of s.sort()){let o=n.targetsByAgent[i]??[],a=n.lastByAgent[i],c=a?(0,wl.buildGatewayOutboundHandleKey)(a.target,a.threadId):void 0;if(o.length===0&&a){console.log($w(a,!0));continue}console.log(`${Ze.COLORS.dim}${i}:${Ze.COLORS.reset}`);for(let l of o){let f=(0,wl.buildGatewayOutboundHandleKey)(l.target,l.threadId);console.log($w(l,f===c))}o.length>1&&a&&console.log(`${Ze.COLORS.dim} * = last inbound (default for gateway send without --target)${Ze.COLORS.reset}`)}}});var Gw=S(bs=>{"use strict";var hG=bs&&bs.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,s)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),mG=bs&&bs.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),EG=bs&&bs.__importStar||(function(){var t=function(e){return t=Object.getOwnPropertyNames||function(n){var r=[];for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(r[r.length]=s);return r},t(e)};return function(e){if(e&&e.__esModule)return e;var n={};if(e!=null)for(var r=t(e),s=0;s<r.length;s++)r[s]!=="default"&&hG(n,e,r[s]);return mG(n,e),n}})();Object.defineProperty(bs,"__esModule",{value:!0});bs.probeCustomEngineCommand=TG;var _G=EG(require("node:path")),yG=Lu(),wG=Ns(),AG=["in-process","node-subprocess"];function SG(t){if(!t?.trim()||t==="all")return"all";let e=t.trim().toLowerCase();if(e==="a"||e==="in-process"||e==="inprocess")return"in-process";if(e==="b"||e==="c"||e==="bun-subprocess"||e==="bun"||e==="node-subprocess"||e==="node")return"node-subprocess";throw new Error(`Unknown strategy "${t}". Use in-process, node-subprocess, or all.`)}async function TG(t){let e=t.engine.trim(),n=_G.resolve(t.workspace),r=(0,wG.resolveCustomEngineManifest)(n,e),s=SG(t.strategy),i=s==="all"?AG:[s];console.log(`Probing custom engine "${r.id}" import (${r.entryPath})`),console.log(`Workspace: ${n}`),console.log("");let o=!1;for(let a of i){let c=await(0,yG.probeCustomEngineImport)(r,a);c.ok?(o=!0,console.log(` [PASS] ${a}`)):(console.log(` [FAIL] ${a}`),console.log(` ${c.error??"unknown error"}`))}console.log(""),o||process.exit(1)}});var Uw=S(yp=>{"use strict";Object.defineProperty(yp,"__esModule",{value:!0});yp.conformanceCommand=$G;var bG=require("node:child_process"),vG=require("node:util"),OG=pd(),Al=Po(),Vs=Mi(),IG=(0,vG.promisify)(bG.execFile);async function Tl(t,e){try{let{stdout:n}=await IG(t,e,{maxBuffer:8388608});return{out:n,code:0}}catch(n){let r=n;return{out:`${r.stdout??""}${r.stderr??""}`,code:typeof r.code=="number"?r.code:1}}}async function PG(t){let e="credential-confinement";if(!t.sandbox)return{name:e,status:"skip",detail:"no --sandbox given; cannot probe inside a running sandbox"};let n=t.runtime??"docker",r=await Tl(n,["exec",t.sandbox,"sh","-c","env"]);if(r.code!==0)return{name:e,status:"skip",detail:`cannot exec in sandbox ${t.sandbox}: ${r.out.trim().slice(0,120)}`};let s=[["provider-key",/sk-[A-Za-z0-9]{16,}/],["api-key-var",/(^|\n)[A-Z_]*API_KEY=\S/],["db-password",/(^|\n)PG(PASSWORD|PASSFILE)=\S/],["aws-secret",/(^|\n)AWS_SECRET_ACCESS_KEY=\S/],["bearer-token-var",/(^|\n)[A-Z_]*_TOKEN=\S/],["generic-secret-var",/(^|\n)[A-Z_]*SECRET[A-Z_]*=\S/]],i=f=>f.replace(/^[A-Z_]*=ahc_\S*$/gm,""),o=f=>s.filter(([,u])=>u.test(i(f))).map(([u])=>u),a=o(r.out),c=await Tl(n,["exec",t.sandbox,"sh","-c",'for p in /proc/[0-9]*; do tr "\\0" "\\n" < $p/environ 2>/dev/null; done']),l=o(c.out);if(a.length===0&&l.length===0){let f=/=ahc_/.test(r.out);return{name:e,status:"pass",detail:f?"only a sandbox-scoped model token is present; no provider key, DB password, or bearer secret in env or any /proc environ":"no credential reachable in the sandbox env or any process environ"}}return{name:e,status:"fail",detail:`credential material reachable inside the sandbox \u2014 env: [${a.join(", ")||"none"}], /proc: [${l.join(", ")||"none"}]`}}async function NG(t){let e="isolation-tier";if(t.tier===void 0)return{name:e,status:"skip",detail:"no --tier declared"};if(t.tier===0)return{name:e,status:"pass",detail:"tier 0 declares no boundary \u2014 nothing to enforce"};if(!t.sandbox)return{name:e,status:"skip",detail:"no --sandbox given; cannot probe the boundary"};let n=t.runtime??"docker",r=await Tl(n,["exec",t.sandbox,"sh","-c","ls -d /proc/[0-9]* | wc -l"]);if(r.code!==0)return{name:e,status:"skip",detail:"cannot probe the sandbox"};let s=parseInt(r.out.trim(),10);if(!Number.isFinite(s))return{name:e,status:"skip",detail:"unreadable process count"};if(s>50)return{name:e,status:"fail",detail:`sandbox sees ${s} processes \u2014 PID namespace is NOT isolated despite tier ${t.tier}`};let i=await Tl(n,["inspect",t.sandbox,"--format","{{json .NetworkSettings.Networks}}"]),o=Object.keys(JSON.parse(i.out.trim()||"{}"));return o.includes("bridge")?{name:e,status:"fail",detail:"sandbox is on the default bridge \u2014 it is not route-confined"}:{name:e,status:"pass",detail:`tier ${t.tier} in force: own PID namespace (${s} procs), routes=${o.join(",")||"none"}`}}function RG(){let t="cost-cap",e="sk-conformance-upstream-key",n=(0,Vs.generateWarrantKeypair)("conformance-cost-cap"),r={[n.kid]:n.publicKeyPem},s=(0,OG.mintSandboxInferenceWarrant)(n,{user:"probe@corp.com",pack:"probe",packVersion:"0.0.0",sandboxId:"sandbox-A",tier:2}),i=(0,Vs.verifyWarrant)(s,r,{audience:"inference",channelSandboxId:"sandbox-A"}).ok,o=(0,Vs.verifyWarrant)(s,r,{audience:"inference",channelSandboxId:"sandbox-B"}).ok,a=s.includes(e);return i&&!o&&!a?{name:t,status:"pass",detail:"model token is a sandbox-bound signed warrant and carries no provider key \u2014 a cap cannot be evaded by replay"}:{name:t,status:"fail",detail:`warrant binding broken (own=${i}, elsewhere=${o}, leaks=${a})`}}function CG(){let t="warrant-integrity",e=(0,Vs.generateWarrantKeypair)("conformance"),n={[e.kid]:e.publicKeyPem},r=(0,Vs.mintWarrant)({user:"probe@corp.com",pack:"probe",packVersion:"0.0.0",sandboxId:"sandbox-A",tier:2,aud:"data"},e),s=(0,Vs.verifyWarrant)(r,n,{audience:"data",channelSandboxId:"sandbox-A"}),i=(0,Vs.verifyWarrant)(r,n,{audience:"data",channelSandboxId:"sandbox-B"}),o=(0,Vs.verifyWarrant)(r,n,{audience:"inference",channelSandboxId:"sandbox-A"});return s.ok&&!i.ok&&!o.ok?{name:t,status:"pass",detail:"warrants are signed, sandbox-bound, and audience-scoped; gateways verify but cannot mint"}:{name:t,status:"fail",detail:`warrant binding broken (own=${s.ok}, lifted=${i.ok}, wrongAud=${o.ok})`}}function kG(){let t="rollback-kill-switch",e=Math.floor(Date.now()/1e3),n={pack:"probe",version:"1.0.0",expiresAt:e+60,enabled:!0},r={pinnedAdmits:Sl(()=>(0,Al.assertAdmitted)(n,{pack:"probe",version:"1.0.0",nowSeconds:e})),otherVersionRefused:!Sl(()=>(0,Al.assertAdmitted)(n,{pack:"probe",version:"1.0.1",nowSeconds:e})),killSwitchRefuses:!Sl(()=>(0,Al.assertAdmitted)({...n,enabled:!1},{pack:"probe",version:"1.0.0",nowSeconds:e})),expiredRefused:!Sl(()=>(0,Al.assertAdmitted)({...n,expiresAt:e-1},{pack:"probe",version:"1.0.0",nowSeconds:e}))},s=Object.values(r).every(Boolean);return{name:t,status:s?"pass":"fail",detail:s?"pinned version admits, other versions refused, kill switch and expiry both fail closed":`admission contract broken: ${JSON.stringify(r)}`}}function Sl(t){try{return t(),!0}catch{return!1}}async function $G(t){let e=a=>c=>({...c,kind:a}),n=[e("deployment")(await PG(t)),e("deployment")(await NG(t)),e("algorithm")(RG()),e("algorithm")(CG()),e("algorithm")(kG())],r=n.filter(a=>a.kind==="deployment"),s=r.filter(a=>a.status!=="skip"),i=n.filter(a=>a.status==="fail"),o=s.length===0;if(t.json)console.log(JSON.stringify({results:n,deployment_probed:!o,summary:o?"no deployment was probed \u2014 algorithm checks verify this binary only":`${s.filter(a=>a.status==="pass").length}/${s.length} deployment checks passed`},null,2));else{console.log(`
629
+ ${o}`,"Web UI","Config","Restart","Reset auth","Uninstall")){case"Web UI":await this.openWebUI();break;case"Config":await this.openConfig();break;case"Restart":await this.restartGateway();break;case"Reset auth":await this.resetAuth();break;case"Uninstall":await this.uninstall();break}}async resetAuth(){try{G.existsSync(this.configPath)||this.writeStarterConfig();let n=G.readFileSync(this.configPath,"utf-8").replace(/^\s*\/\/.*$/gm,"").replace(/,\s*([}\]])/g,"$1"),r=JSON.parse(n);(!r.gateway||typeof r.gateway!="object")&&(r.gateway={}),(!r.gateway.auth||typeof r.gateway.auth!="object")&&(r.gateway.auth={});let s=`ah-${(0,Qf.randomBytes)(24).toString("hex")}`;r.gateway.auth.token=s,G.writeFileSync(this.configPath,`${JSON.stringify(r,null,2)}
630
+ `,{encoding:"utf-8",mode:le?void 0:384}),await N.workspace.getConfiguration("agentide.gateway").update("token",s,N.ConfigurationTarget.Global),await this.restartGateway(),N.window.showInformationMessage(`${D.AGENT_ANYWHERE_LABEL}: Auth reset; gateway restarted. If you use the Web UI, paste the new token in Control UI settings.`)}catch(e){this.log(`Failed to reset auth: ${e instanceof Error?e.message:String(e)}`),N.window.showErrorMessage(`${D.AGENT_ANYWHERE_LABEL}: Failed to reset auth. Open Config to update it manually.`)}}async connectBridge(){if(!this._bridgeRef){this.log("Bridge ref not set -- cannot connect");return}if(this._gatewayUninstallInProgress){await this.showGatewayUninstallInProgressPrompt();return}if(this._bridgeRef.isConnected){this.log("Bridge already connected");return}let e=this.getGatewayPort();if(await(0,be.probePort)(e)&&!await ml(e,this._lastDetection?.binaryPath)&&(!await this.promptNonManagedPortTakeover(e,"connect")||await(0,be.probePort)(e))){this._status==="running"&&this.setStatus("installed");return}let n=this._status==="running";if(!n){let c=await op(e);c?.running&&(n=!0,this._lastDetection=c,this.setStatus("running"))}if(!n){let c=await this.detect();if(!c.running){if(!c.installed){await N.window.showInformationMessage(`${D.AGENT_ANYWHERE_LABEL}: Reach your AgentHippo IDE or CLI agents from WhatsApp, Telegram, Slack, Discord, and more - right from your phone or any messaging app. This will also install OpenClaw fork on your computer.`,"Set Up Agent Anywhere")==="Set Up Agent Anywhere"&&await this.install();return}if(await this.start(),!(await this.detect()).running){this.log("Gateway failed to start, cannot connect"),await ta(sp);return}}}let r=N.workspace.getConfiguration("agentide.gateway"),s=r.get("url","").trim();s||(s=`ws://127.0.0.1:${e}`,await r.update("url",s,N.ConfigurationTarget.Global));let i=/127\.0\.0\.1|localhost|\[::1\]/i.test(s),o=this.readGatewayToken();o&&i&&(await r.update("token",o,N.ConfigurationTarget.Global),this.log("Gateway token applied from openclaw.json (user scope)")),await this._bridgeRef.connect(),this.setBridgeConnected(this._bridgeRef.isConnected),await(0,be.probePort)(e)?this._status!=="running"&&this.setStatus("running"):this._status!=="installed"&&this.setStatus("installed"),this.updateStatusBar(this._status),this.log("Bridge connected")}async disconnectBridge(){this._bridgeRef&&(await this._bridgeRef.disconnect(),this.setBridgeConnected(!1),this.updateStatusBar(this._status),this.log("Bridge disconnected"))}async openWebUI(){let e=this.getGatewayPort();if(!(this._status==="running"||await(0,be.probePort)(e))){await N.window.showWarningMessage(`${D.AGENT_ANYWHERE_LABEL}: Gateway is not running. Start it first to use the web UI.`,"Start Now")==="Start Now"&&await this.start();return}let r=(N.workspace.getConfiguration("agentide.gateway").get("token")??"").trim(),s=this.readGatewayToken()??(r||void 0),i=s?`#token=${encodeURIComponent(s)}`:"",o=`http://127.0.0.1:${e}/${i}`;await N.env.openExternal(N.Uri.parse(o))}startHealthChecks(e){this.stopHealthChecks(),this.healthCheckTimer=setInterval(async()=>{await(0,be.probePort)(e)||(this.log("Health check failed -- gateway is no longer running"),this.stopHealthChecks(),this.process=null,this.setStatus("installed"))},WM)}stopHealthChecks(){this.healthCheckTimer&&(clearInterval(this.healthCheckTimer),this.healthCheckTimer=null)}async ensureWebUIBuilt(e){if(e)try{let n=_p(e);if(!n)return;let r=V.join(n,"dist","control-ui","index.html");if(G.existsSync(r))return;this.log("Web UI not built - building now..."),await Gt(le?"pnpm.cmd ui:build":"pnpm ui:build",{cwd:n,timeout:6e4,env:{...process.env},...le?{shell:"cmd.exe"}:{}}),this.log("Web UI built successfully")}catch(n){this.log(`Web UI build failed (non-fatal): ${n instanceof Error?n.message:String(n)}`)}}async promptNonManagedPortTakeover(e,n){let r=n==="connect"?"connect Agent Anywhere":"start Agent Anywhere";if(await N.window.showWarningMessage(`${D.AGENT_ANYWHERE_LABEL}: Port ${e} is in use by a non-managed process. Stop that process and ${r}?`,{modal:!0},"Yes","No")!=="Yes")return this.log(`User declined non-managed port takeover on ${e}`),!1;this.log(`User approved non-managed port takeover on ${e}`);let i=new Set(await no(e));if(!await Sw(e,void 0,a=>this.log(a))){let a=await no(e);return i.size>0&&a.some(l=>!i.has(l))?N.window.showWarningMessage(`${D.AGENT_ANYWHERE_LABEL}: Port ${e} is held by a self-restarting gateway service. Run \`openclaw daemon uninstall\` to remove it, then try again.`):N.window.showErrorMessage(`${D.AGENT_ANYWHERE_LABEL}: Could not free port ${e}. Stop that process manually and try again.`),!1}return!0}async ensureManagedGatewayWrapperState(e,n=!1){try{let r=Si(),s=await up(e,r);if(!s)return;let{launcherPath:i,packageRoot:o,nodePath:a,entryScriptPath:c}=s,l=_w(a,c,vw),f;return(n||Rw(cp))&&(f=_w(a,c,cp)),XM({...r,nodePath:a,cliPath:i,entryScriptPath:c,packageRoot:o,wrapperPath:l,wrapperDir:mp,openclawWrapperPath:f,updatedAt:new Date().toISOString()}),l}catch(r){this.log(`Managed gateway wrapper setup failed: ${r instanceof Error?r.message:String(r)}`);return}}async resolveWindowsManagedGatewayLaunchRuntime(e){if(!le)return;await this.ensureManagedGatewayWrapperState(e);let n=await up(e);if(n)return{nodePath:n.nodePath,entryScriptPath:n.entryScriptPath}}readGatewayToken(){try{if(!G.existsSync(this.configPath))return;let n=G.readFileSync(this.configPath,"utf-8").replace(/^\s*\/\/.*$/gm,"").replace(/,\s*([}\]])/g,"$1"),s=JSON.parse(n)?.gateway?.auth?.token;return typeof s=="string"&&s.trim()?s.trim():void 0}catch(e){this.log(`Could not read gateway token: ${e}`);return}}setStatus(e){this._status=e,this.updateStatusBar(e),this._onStatusChange.fire(e)}updateStatusBar(e){if(this.getConfig("hidden",!1)){this.statusBarItem.hide();return}switch(e){case"not-installed":this.statusBarItem.text=`$(cloud-download) ${D.AGENT_ANYWHERE_LABEL}`,this.statusBarItem.tooltip=`${D.AGENT_ANYWHERE_LABEL}: Reach your agents from WhatsApp, Telegram, Slack (click to set up)`,this.statusBarItem.color=void 0,this.statusBarItem.backgroundColor=void 0;break;case"installed":this.statusBarItem.text=`$(debug-disconnect) ${D.AGENT_ANYWHERE_LABEL}`,this.statusBarItem.tooltip=`${D.AGENT_ANYWHERE_LABEL}: Installed, not running (click to start)`,this.statusBarItem.color=void 0,this.statusBarItem.backgroundColor=void 0;break;case"starting":this.statusBarItem.text=`$(sync~spin) ${D.AGENT_ANYWHERE_LABEL}`,this.statusBarItem.tooltip=this._gatewayInstallInProgress?`${D.AGENT_ANYWHERE_LABEL}: ${this._installProgressMessage??"Installing... (see Setup terminal)"}`:`${D.AGENT_ANYWHERE_LABEL}: Starting...`,this.statusBarItem.color=void 0,this.statusBarItem.backgroundColor=void 0;break;case"running":this._bridgeConnected?(this.statusBarItem.text=`$(broadcast) ${D.AGENT_ANYWHERE_LABEL}`,this.statusBarItem.tooltip=`${D.AGENT_ANYWHERE_LABEL}: Connected (click for options)`,this.statusBarItem.color=new N.ThemeColor("testing.iconPassed")):(this.statusBarItem.text=`$(debug-disconnect) ${D.AGENT_ANYWHERE_LABEL}`,this.statusBarItem.tooltip=`${D.AGENT_ANYWHERE_LABEL}: Disconnected (click to connect)`,this.statusBarItem.color=void 0),this.statusBarItem.backgroundColor=void 0;break;case"stopping":this.statusBarItem.text=`$(sync~spin) ${D.AGENT_ANYWHERE_LABEL}`,this.statusBarItem.tooltip=this._gatewayUninstallInProgress?`${D.AGENT_ANYWHERE_LABEL}: Uninstalling... (see Uninstall terminal)`:`${D.AGENT_ANYWHERE_LABEL}: Stopping...`,this.statusBarItem.color=void 0,this.statusBarItem.backgroundColor=void 0;break;case"error":this.statusBarItem.text=`$(warning) ${D.AGENT_ANYWHERE_LABEL}`,this.statusBarItem.tooltip=`${D.AGENT_ANYWHERE_LABEL}: Error (click for details)`,this.statusBarItem.color=new N.ThemeColor("errorForeground"),this.statusBarItem.backgroundColor=void 0;break}this.statusBarItem.show()}getConfig(e,n){return N.workspace.getConfiguration("agentide.anywhere").get(e,n)}async hasGlobalNpmOpenclawTree(){return(await na()).length>0}readGatewayPortFromOpenclawJson(){try{if(!G.existsSync(this.configPath))return;let n=G.readFileSync(this.configPath,"utf-8").replace(/^\s*\/\/.*$/gm,"").replace(/,\s*([}\]])/g,"$1"),s=JSON.parse(n)?.gateway?.port;if(typeof s=="number"&&Number.isFinite(s)){let i=Math.floor(s);if(i>=1&&i<=65535)return i}if(typeof s=="string"&&/^\d+$/.test(s)){let i=parseInt(s,10);if(i>=1&&i<=65535)return i}return}catch{return}}getGatewayPort(){let e=this.readGatewayPortFromOpenclawJson();return e!==void 0?e:this.getConfig("port",Ai)}log(e){this.outputChannel.appendLine(`[${D.AGENT_ANYWHERE_LABEL}] ${e}`)}dispose(){this.stopHealthChecks(),this.process=null,this.statusBarItem.dispose(),this._onStatusChange.dispose();for(let e of this.disposables)e.dispose()}};D.GatewayLifecycleManager=pp});var Mw=S(yp=>{"use strict";Object.defineProperty(yp,"__esModule",{value:!0});yp.anywhereCommand=cG;var wl=Dw(),ts=Wn(),aG=18789;async function cG(t){switch(t.action?.trim().toLowerCase()){case"status":case"detect":await lG(t);return;case"help":case"usage":case"":case void 0:Lw();return;default:console.error(`${ts.COLORS.red}Error:${ts.COLORS.reset} Unsupported action "${t.action}".`),Lw(),process.exitCode=1;return}}async function lG(t){let e=t.port??aG;try{let n=await(0,wl.detectGateway)(e),r=n.running?"Running":n.installed?"Installed":"Not installed",s=n.running?ts.COLORS.green:n.installed?ts.COLORS.yellow:ts.COLORS.red;console.log(`${s}${wl.AGENT_ANYWHERE_LABEL}:${ts.COLORS.reset} ${r}`),console.log(`Port: ${n.port}`),n.binaryPath&&console.log(`Binary: ${n.binaryPath}`),n.version&&console.log(`Version: ${n.version}`),n.installed||console.log(`${ts.COLORS.dim}Install via the Agent Anywhere UI inside ${wl.AGENT_ANYWHERE_LABEL} in VS Code.${ts.COLORS.reset}`)}catch(n){console.error(`${ts.COLORS.red}Error:${ts.COLORS.reset} ${n instanceof Error?n.message:String(n)}`),process.exitCode=1}}function Lw(){console.log([`${wl.AGENT_ANYWHERE_LABEL} CLI`,"","Usage:"," agenthippo anywhere status"," agenthippo anywhere detect","","Note: install/start/stop is currently managed via the Agent Anywhere UI in VS Code."].join(`
631
+ `))}});var jw=S(ns=>{"use strict";var uG=ns&&ns.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,s)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),dG=ns&&ns.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),fG=ns&&ns.__importStar||(function(){var t=function(e){return t=Object.getOwnPropertyNames||function(n){var r=[];for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(r[r.length]=s);return r},t(e)};return function(e){if(e&&e.__esModule)return e;var n={};if(e!=null)for(var r=t(e),s=0;s<r.length;s++)r[s]!=="default"&&uG(n,e,r[s]);return dG(n,e),n}})();Object.defineProperty(ns,"__esModule",{value:!0});ns.gatewaySendCommand=EG;ns.gatewayListCommand=_G;var pG=require("fs/promises"),gG=fG(require("path")),Al=kc(),hG=Fd(),Ze=Wn();function Uw(t){let e=t.trim();return e||(console.error("Error: --outbound is required"),process.exit(1)),gG.resolve(e)}async function Hw(t){try{await(0,pG.access)(t)}catch{console.error(`Error: gateway outbound file not found: ${t}`),process.exit(1)}}async function mG(t,e,n){let r=n.message.trim();r||(console.error("Error: --message is required"),process.exit(1)),n.dryRun&&(console.log(`${Ze.COLORS.dim}Dry run (egress broker):${Ze.COLORS.reset} POST ${t} { to: ${n.target??"(reply-to-sender)"} }`),process.exit(0));let s;try{s=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify({message:r,to:n.target?.trim()||void 0,media:n.media?.trim()||void 0})})}catch(a){console.error(`${Ze.COLORS.red}\u2717${Ze.COLORS.reset} Egress broker unreachable: ${a instanceof Error?a.message:String(a)}`),process.exit(1)}let i=await s.text(),o={};try{o=JSON.parse(i)}catch{}n.json?console.log(JSON.stringify({via:"egress-broker",status:s.status,result:o},null,2)):s.ok&&o.ok?console.log(`${Ze.COLORS.green}\u2713${Ze.COLORS.reset} Sent (via egress broker${o.via?`, ${o.via}`:""})`):(console.error(`${Ze.COLORS.red}\u2717${Ze.COLORS.reset} Egress send rejected (HTTP ${s.status}): ${o.error||i||"unknown error"}`),process.exit(1)),process.exit(s.ok&&o.ok?0:1)}async function EG(t){let e=process.env.AGENTHIPPO_EGRESS_URL?.trim(),n=process.env.AGENTHIPPO_TURN_NONCE?.trim();if(e&&n){await mG(e,n,t);return}e&&(console.error("Error: egress broker is active but AGENTHIPPO_TURN_NONCE is missing \u2014 refusing direct gateway send"),process.exit(1));let r=Uw(t.outbound);await Hw(r);let s=t.agent.trim(),i=t.message.trim();s||(console.error("Error: --agent is required"),process.exit(1)),i||(console.error("Error: --message is required"),process.exit(1));let o=await(0,Al.resolveGatewayOutboundHandle)(r,s,{target:t.target,threadId:t.threadId});o||(console.error(`Error: No gateway outbound handle for agent "${s}" in ${r}.`),t.target&&console.error(`No stored route matching target "${t.target}".`),console.error(`Run \`agenthippo gateway list --outbound "${r}" --agent ${s}\` to see known routes.`),process.exit(1));let a=await(0,hG.sendGatewayOutboundMessage)(o,{message:i,media:t.media,dryRun:t.dryRun});if(t.json)console.log(JSON.stringify({file:r,handle:o,result:a},null,2));else if(t.dryRun)console.log(`${Ze.COLORS.dim}Dry run:${Ze.COLORS.reset} ${a.command.join(" ")}`);else if(a.ok){let c=a.via==="hippoclaw"?" (via hippoclaw CLI fallback)":"";console.log(`${Ze.COLORS.green}\u2713${Ze.COLORS.reset} Sent via ${o.channel}:${o.target}${c}`),a.stdout&&console.log(a.stdout)}else console.error(`${Ze.COLORS.red}\u2717${Ze.COLORS.reset} Gateway send failed (exit ${a.exitCode??"unknown"})`),a.stderr&&console.error(a.stderr),a.stdout&&console.error(a.stdout),process.exit(1);process.exit(0)}function Gw(t,e){let n=t.label?` (${t.label})`:"",r=t.threadId?` thread=${t.threadId}`:"",s=t.inboundCount>1?` \xD7${t.inboundCount}`:"";return`${e?`${Ze.COLORS.green}*${Ze.COLORS.reset} `:" "}${t.agentId}${n}: ${t.channel} \u2192 ${t.target}${r}${s}`}async function _G(t){let e=Uw(t.outbound);await Hw(e);let n=await(0,Al.getGatewayOutboundStoreSnapshot)(e);if(t.json){console.log(JSON.stringify({file:e,...n},null,2));return}let r=t.agent?.trim(),s=r?[r]:[...new Set([...Object.keys(n.targetsByAgent),...Object.keys(n.lastByAgent)])];if(s.length===0){console.log(`No gateway outbound routes in ${e}.`);return}console.log(`${Ze.COLORS.dim}${e}${Ze.COLORS.reset}`);for(let i of s.sort()){let o=n.targetsByAgent[i]??[],a=n.lastByAgent[i],c=a?(0,Al.buildGatewayOutboundHandleKey)(a.target,a.threadId):void 0;if(o.length===0&&a){console.log(Gw(a,!0));continue}console.log(`${Ze.COLORS.dim}${i}:${Ze.COLORS.reset}`);for(let l of o){let f=(0,Al.buildGatewayOutboundHandleKey)(l.target,l.threadId);console.log(Gw(l,f===c))}o.length>1&&a&&console.log(`${Ze.COLORS.dim} * = last inbound (default for gateway send without --target)${Ze.COLORS.reset}`)}}});var xw=S(bs=>{"use strict";var yG=bs&&bs.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,s)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),wG=bs&&bs.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),AG=bs&&bs.__importStar||(function(){var t=function(e){return t=Object.getOwnPropertyNames||function(n){var r=[];for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(r[r.length]=s);return r},t(e)};return function(e){if(e&&e.__esModule)return e;var n={};if(e!=null)for(var r=t(e),s=0;s<r.length;s++)r[s]!=="default"&&yG(n,e,r[s]);return wG(n,e),n}})();Object.defineProperty(bs,"__esModule",{value:!0});bs.probeCustomEngineCommand=IG;var SG=AG(require("node:path")),TG=Mu(),bG=Ns(),vG=["in-process","node-subprocess"];function OG(t){if(!t?.trim()||t==="all")return"all";let e=t.trim().toLowerCase();if(e==="a"||e==="in-process"||e==="inprocess")return"in-process";if(e==="b"||e==="c"||e==="bun-subprocess"||e==="bun"||e==="node-subprocess"||e==="node")return"node-subprocess";throw new Error(`Unknown strategy "${t}". Use in-process, node-subprocess, or all.`)}async function IG(t){let e=t.engine.trim(),n=SG.resolve(t.workspace),r=(0,bG.resolveCustomEngineManifest)(n,e),s=OG(t.strategy),i=s==="all"?vG:[s];console.log(`Probing custom engine "${r.id}" import (${r.entryPath})`),console.log(`Workspace: ${n}`),console.log("");let o=!1;for(let a of i){let c=await(0,TG.probeCustomEngineImport)(r,a);c.ok?(o=!0,console.log(` [PASS] ${a}`)):(console.log(` [FAIL] ${a}`),console.log(` ${c.error??"unknown error"}`))}console.log(""),o||process.exit(1)}});var Bw=S(wp=>{"use strict";Object.defineProperty(wp,"__esModule",{value:!0});wp.conformanceCommand=GG;var PG=require("node:child_process"),NG=require("node:util"),RG=pd(),Sl=Ro(),Vs=Mi(),CG=(0,NG.promisify)(PG.execFile);async function bl(t,e){try{let{stdout:n}=await CG(t,e,{maxBuffer:8388608});return{out:n,code:0}}catch(n){let r=n;return{out:`${r.stdout??""}${r.stderr??""}`,code:typeof r.code=="number"?r.code:1}}}async function kG(t){let e="credential-confinement";if(!t.sandbox)return{name:e,status:"skip",detail:"no --sandbox given; cannot probe inside a running sandbox"};let n=t.runtime??"docker",r=await bl(n,["exec",t.sandbox,"sh","-c","env"]);if(r.code!==0)return{name:e,status:"skip",detail:`cannot exec in sandbox ${t.sandbox}: ${r.out.trim().slice(0,120)}`};let s=[["provider-key",/sk-[A-Za-z0-9]{16,}/],["api-key-var",/(^|\n)[A-Z_]*API_KEY=\S/],["db-password",/(^|\n)PG(PASSWORD|PASSFILE)=\S/],["aws-secret",/(^|\n)AWS_SECRET_ACCESS_KEY=\S/],["bearer-token-var",/(^|\n)[A-Z_]*_TOKEN=\S/],["generic-secret-var",/(^|\n)[A-Z_]*SECRET[A-Z_]*=\S/]],i=f=>f.replace(/^[A-Z_]*=ahc_\S*$/gm,""),o=f=>s.filter(([,u])=>u.test(i(f))).map(([u])=>u),a=o(r.out),c=await bl(n,["exec",t.sandbox,"sh","-c",'for p in /proc/[0-9]*; do tr "\\0" "\\n" < $p/environ 2>/dev/null; done']),l=o(c.out);if(a.length===0&&l.length===0){let f=/=ahc_/.test(r.out);return{name:e,status:"pass",detail:f?"only a sandbox-scoped model token is present; no provider key, DB password, or bearer secret in env or any /proc environ":"no credential reachable in the sandbox env or any process environ"}}return{name:e,status:"fail",detail:`credential material reachable inside the sandbox \u2014 env: [${a.join(", ")||"none"}], /proc: [${l.join(", ")||"none"}]`}}async function $G(t){let e="isolation-tier";if(t.tier===void 0)return{name:e,status:"skip",detail:"no --tier declared"};if(t.tier===0)return{name:e,status:"pass",detail:"tier 0 declares no boundary \u2014 nothing to enforce"};if(!t.sandbox)return{name:e,status:"skip",detail:"no --sandbox given; cannot probe the boundary"};let n=t.runtime??"docker",r=await bl(n,["exec",t.sandbox,"sh","-c","ls -d /proc/[0-9]* | wc -l"]);if(r.code!==0)return{name:e,status:"skip",detail:"cannot probe the sandbox"};let s=parseInt(r.out.trim(),10);if(!Number.isFinite(s))return{name:e,status:"skip",detail:"unreadable process count"};if(s>50)return{name:e,status:"fail",detail:`sandbox sees ${s} processes \u2014 PID namespace is NOT isolated despite tier ${t.tier}`};let i=await bl(n,["inspect",t.sandbox,"--format","{{json .NetworkSettings.Networks}}"]),o=Object.keys(JSON.parse(i.out.trim()||"{}"));return o.includes("bridge")?{name:e,status:"fail",detail:"sandbox is on the default bridge \u2014 it is not route-confined"}:{name:e,status:"pass",detail:`tier ${t.tier} in force: own PID namespace (${s} procs), routes=${o.join(",")||"none"}`}}function DG(){let t="cost-cap",e="sk-conformance-upstream-key",n=(0,Vs.generateWarrantKeypair)("conformance-cost-cap"),r={[n.kid]:n.publicKeyPem},s=(0,RG.mintSandboxInferenceWarrant)(n,{user:"probe@corp.com",pack:"probe",packVersion:"0.0.0",sandboxId:"sandbox-A",tier:2}),i=(0,Vs.verifyWarrant)(s,r,{audience:"inference",channelSandboxId:"sandbox-A"}).ok,o=(0,Vs.verifyWarrant)(s,r,{audience:"inference",channelSandboxId:"sandbox-B"}).ok,a=s.includes(e);return i&&!o&&!a?{name:t,status:"pass",detail:"model token is a sandbox-bound signed warrant and carries no provider key \u2014 a cap cannot be evaded by replay"}:{name:t,status:"fail",detail:`warrant binding broken (own=${i}, elsewhere=${o}, leaks=${a})`}}function LG(){let t="warrant-integrity",e=(0,Vs.generateWarrantKeypair)("conformance"),n={[e.kid]:e.publicKeyPem},r=(0,Vs.mintWarrant)({user:"probe@corp.com",pack:"probe",packVersion:"0.0.0",sandboxId:"sandbox-A",tier:2,aud:"data"},e),s=(0,Vs.verifyWarrant)(r,n,{audience:"data",channelSandboxId:"sandbox-A"}),i=(0,Vs.verifyWarrant)(r,n,{audience:"data",channelSandboxId:"sandbox-B"}),o=(0,Vs.verifyWarrant)(r,n,{audience:"inference",channelSandboxId:"sandbox-A"});return s.ok&&!i.ok&&!o.ok?{name:t,status:"pass",detail:"warrants are signed, sandbox-bound, and audience-scoped; gateways verify but cannot mint"}:{name:t,status:"fail",detail:`warrant binding broken (own=${s.ok}, lifted=${i.ok}, wrongAud=${o.ok})`}}function MG(){let t="rollback-kill-switch",e=Math.floor(Date.now()/1e3),n={pack:"probe",version:"1.0.0",expiresAt:e+60,enabled:!0},r={pinnedAdmits:Tl(()=>(0,Sl.assertAdmitted)(n,{pack:"probe",version:"1.0.0",nowSeconds:e})),otherVersionRefused:!Tl(()=>(0,Sl.assertAdmitted)(n,{pack:"probe",version:"1.0.1",nowSeconds:e})),killSwitchRefuses:!Tl(()=>(0,Sl.assertAdmitted)({...n,enabled:!1},{pack:"probe",version:"1.0.0",nowSeconds:e})),expiredRefused:!Tl(()=>(0,Sl.assertAdmitted)({...n,expiresAt:e-1},{pack:"probe",version:"1.0.0",nowSeconds:e}))},s=Object.values(r).every(Boolean);return{name:t,status:s?"pass":"fail",detail:s?"pinned version admits, other versions refused, kill switch and expiry both fail closed":`admission contract broken: ${JSON.stringify(r)}`}}function Tl(t){try{return t(),!0}catch{return!1}}async function GG(t){let e=a=>c=>({...c,kind:a}),n=[e("deployment")(await kG(t)),e("deployment")(await $G(t)),e("algorithm")(DG()),e("algorithm")(LG()),e("algorithm")(MG())],r=n.filter(a=>a.kind==="deployment"),s=r.filter(a=>a.status!=="skip"),i=n.filter(a=>a.status==="fail"),o=s.length===0;if(t.json)console.log(JSON.stringify({results:n,deployment_probed:!o,summary:o?"no deployment was probed \u2014 algorithm checks verify this binary only":`${s.filter(a=>a.status==="pass").length}/${s.length} deployment checks passed`},null,2));else{console.log(`
631
632
  AgentHippo conformance
632
633
  `);let a=c=>{let l=c.status==="pass"?"PASS":c.status==="fail"?"FAIL":"SKIP";console.log(` ${l} ${c.name}
633
634
  ${c.detail}`)};if(console.log("THIS DEPLOYMENT (probes a running sandbox)"),r.forEach(a),console.log(`
634
- THIS BINARY (contract checks \u2014 environment-independent, pass with no deployment)`),n.filter(c=>c.kind==="algorithm").forEach(a),console.log(""),o)console.log("NO DEPLOYMENT WAS PROBED. The binary checks above say nothing about a running"),console.log("system \u2014 pass --sandbox <container> --tier <n> to actually test one.");else{let c=s.filter(l=>l.status==="pass").length;console.log(`${c}/${s.length} deployment checks passed`+(r.length-s.length?`, ${r.length-s.length} not probed`:""))}i.length&&console.log(`${i.length} FAILED`)}return i.length?1:o?2:0}});var Hw=S(Sp=>{"use strict";Object.defineProperty(Sp,"__esModule",{value:!0});Sp.startRunnerHost=MG;var wp=Ku(),DG=1e3*60*5,LG={selected:[],freeText:null,declined:!0};function MG(t){let e=f=>{t.output.write((0,wp.encodeRunnerFrame)(f))},n=new Map,r="",s=!1,i=setInterval(()=>{try{t.engine.onMaintenance(t.logger??UG())}catch(f){t.logger?.warn(`[Runner] maintenance failed: ${Ap(f)}`)}},t.maintenanceIntervalMs??DG);typeof i.unref=="function"&&i.unref();let o=()=>{},a=new Promise(f=>{o=()=>{if(!s){s=!0,clearInterval(i);for(let u of n.values())u.abort();n.clear(),f()}},t.input.on("data",u=>{r+=typeof u=="string"?u:u.toString("utf8");let{lines:d,rest:p}=(0,wp.splitFrames)(r);r=p;for(let g of d){let m=(0,wp.parseClientFrame)(g);if(!m){t.logger?.warn("[Runner] dropped malformed client frame");continue}c(m)}}),t.input.on("end",o),t.input.on("close",o),t.input.on("error",u=>{t.logger?.warn(`[Runner] input error: ${Ap(u)}`),o()})});async function c(f){if(f.type==="abort"){n.get(f.id)?.abort();return}await l(f.id,f.message,f.options)}async function l(f,u,d){if(n.has(f)){e({type:"failed",id:f,message:`duplicate run id ${f}`});return}let p=new AbortController;n.set(f,p);let g=GG(e,f);try{await t.engine.stream(u,d,g,t.runtime,p.signal);let m=t.nativeSessionId?.();e({type:"result",id:f,...m?{nativeSessionId:m}:{}})}catch(m){let h=p.signal.aborted?"aborted":Ap(m);e({type:"failed",id:f,message:h})}finally{n.delete(f)}}return e({type:"ready",demux:!0}),{done:a,close:()=>o()}}function GG(t,e){let n=r=>t({id:e,event:r});return{async thinking(r){n({type:"thinking",delta:r})},async text(r){n({type:"text",delta:r})},async toolStart(r,s,i){n({type:"toolStart",toolName:r,...s!==void 0?{input:s}:{},...i?{toolCallId:i}:{}})},async toolEnd(r,s,i,o){n({type:"toolEnd",toolName:r,toolCallId:s,...i!==void 0?{result:i}:{},...o!==void 0?{isError:o}:{}})},async progress(r){n({type:"progress",message:r})},async question(r){return t({type:"question",payload:r,id:e}),LG},async error(r){n({type:"error",message:r})},async done(){n({type:"done"})}}}function Ap(t){return t instanceof Error?t.message:String(t)}function UG(){return{info:()=>{},warn:()=>{},error:()=>{},debug:()=>{}}}});var Vw=S(Rr=>{"use strict";var HG=Rr&&Rr.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,s)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),jG=Rr&&Rr.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),vp=Rr&&Rr.__importStar||(function(){var t=function(e){return t=Object.getOwnPropertyNames||function(n){var r=[];for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(r[r.length]=s);return r},t(e)};return function(e){if(e&&e.__esModule)return e;var n={};if(e!=null)for(var r=t(e),s=0;s<r.length;s++)r[s]!=="default"&&HG(n,e,r[s]);return jG(n,e),n}})();Object.defineProperty(Rr,"__esModule",{value:!0});Rr.resolveSandboxWorkspace=Bw;Rr.isForeignWorkspace=Fw;Rr.sandboxCommand=YG;var na=vp(require("fs")),xG=vp(require("net")),bl=vp(require("path")),Tp=oi(),BG=Wn(),jw=ai(),FG=md(),VG=To(),WG=Br(),KG=Er(),xw=Hw();function Bw(t,e){return e}function Fw(t,e){return t?bl.resolve(t)!==bl.resolve(e):!1}var bp=class{defaults;id="sandbox";displayName="Sandbox runner";runner;builtWith;warnedWorkspace=!1;nativeSessionId;constructor(e){this.defaults=e}ensureRunner(e){let n=e.baseUrl??"";return this.runner&&this.builtWith===n?this.runner:(this.runner?.dispose(),this.runner=(0,FG.createPackRunner)({storagePath:this.defaults.storagePath,analyticsSessionsDir:this.defaults.analyticsSessionsDir,packId:this.defaults.packId,packVersion:this.defaults.packVersion,provenance:()=>(0,KG.readProvenanceEnvFromProcess)(),workspaceRoot:this.defaults.workspace,credentials:{baseUrl:e.baseUrl,litellmApiKey:e.modelToken,useLiteLLM:!!e.baseUrl},claudeCheapModel:this.defaults.claudeCheapModel,omitGatewayToken:!0}),this.builtWith=n,this.runner)}async stream(e,n,r,s,i){let o=n,a=o.workspaceRoot,c=Bw(a,this.defaults.workspace);Fw(a,c)&&!this.warnedWorkspace&&(this.warnedWorkspace=!0,console.warn(`[sandbox] ignoring workspaceRoot ${a} from the wire \u2014 this sandbox works in ${c}`));try{na.mkdirSync(c,{recursive:!0}),process.chdir(c)}catch(p){throw new Error(`sandbox cannot use workspace ${c}: ${p instanceof Error?p.message:String(p)}`)}let l=this.ensureRunner(o),f=o,u=f.permissions??(f.fileAccess?{fileAccess:f.fileAccess}:{fileAccess:this.defaults.fileAccess}),d=await l.run({engineId:o.engineId??this.defaults.engineId,modelId:o.modelId??this.defaults.modelId,message:e,workspaceRoot:c,additionalDirectories:o.additionalDirectories,sessionId:o.sessionId,modelToken:o.modelToken,permissions:u,analyticsUserId:o.analyticsUserId,engineHomeUserKey:o.engineHomeUserKey,turnEnv:o.turnEnv,gatewaySessionKey:o.gatewaySessionKey,emitter:r,signal:i});if(!d.success&&d.error)throw new Error(d.error)}onMaintenance(){}dispose(){this.runner?.dispose()}};function qG(){process.on("unhandledRejection",t=>{let e=t instanceof Error?t.message:String(t);console.error(`[sandbox] unhandled rejection (session kept alive): ${e}`)}),process.on("uncaughtException",t=>{console.error(`[sandbox] uncaught exception \u2014 exiting so the driver recreates this sandbox: ${t.message}`),process.exit(1)})}async function YG(t){await(0,VG.ensureDeps)(!1);let e=t.stateDir??"/state",n=t.workspace??bl.join(e,"workspace");na.mkdirSync(n,{recursive:!0});let r=await(0,jw.loadAgentPack)(t.agent,n),s={name:r.manifest.metadata.name,version:r.manifest.metadata.version,engine:r.manifest.spec?.engine??"claude"};t.stateDir?process.env.AGENTHIPPO_HOME=e:process.env.AGENTHIPPO_HOME=process.env.AGENTHIPPO_HOME??e,process.env.AGENTHIPPO_SANDBOX="1";let i=bl.join(e,"home");na.mkdirSync(i,{recursive:!0}),process.env.HOME=i;let o=n;await(0,Tp.syncPackToWorkspace)(o,r.packPath,s.name,s.engine,console,(0,BG.findBundledBasePromptsDir)()),console.log(`[sandbox] pack ${s.name}@${s.version??"?"} synced into ${o} (engine ${s.engine})`),qG();let a=r.manifest.spec?.cheapModel?.trim(),c=new bp({storagePath:e,analyticsSessionsDir:(0,WG.resolveAnalyticsSessionsDir)(e,!1),packId:s.name,packVersion:s.version,engineId:s.engine,modelId:(0,Tp.resolveModelAlias)(r.manifest.spec?.model?.trim()||"ah-auto"),claudeCheapModel:a?(0,Tp.resolveModelAlias)(a):void 0,fileAccess:(0,jw.getFileAccess)(r),workspace:o}),l={logger:console};if(t.stdio){await(0,xw.startRunnerHost)({engine:c,runtime:l,input:process.stdin,output:{write:p=>process.stdout.write(p)},nativeSessionId:()=>c.nativeSessionId}).done;return}let f=t.socket;if(!f)throw new Error("sandbox requires --socket <path> or --stdio");try{na.unlinkSync(f)}catch{}let u=xG.createServer(d=>{(0,xw.startRunnerHost)({engine:c,runtime:l,input:d,output:{write:p=>d.write(p)},nativeSessionId:()=>c.nativeSessionId})});try{await new Promise((d,p)=>{u.once("error",p),u.listen(f,()=>d())})}catch(d){console.error(`[sandbox] FATAL: cannot listen at ${f}: ${d instanceof Error?d.message:String(d)}`),process.exit(1)}try{na.chmodSync(f,432)}catch{}console.log(`[sandbox] ${t.sandboxId??"sandbox"} listening on ${f} (pack ${s.name}@${s.version??"?"})`),await new Promise(d=>{let p=()=>{u.close(()=>d()),c.dispose()};process.once("SIGTERM",p),process.once("SIGINT",p),u.once("close",()=>d())})}});Object.defineProperty(exports,"__esModule",{value:!0});var Ww=require("module"),XG=Ww.prototype.require;Ww.prototype.require=function(t){return t==="vscode"?{window:{showInformationMessage:()=>{},showErrorMessage:()=>{},showWarningMessage:()=>Promise.resolve(void 0)},workspace:{getConfiguration:()=>({get:(e,n)=>n,inspect:()=>{}})},commands:{executeCommand:async()=>{}},Memento:class{}}:XG.apply(this,arguments)};var Kw=require("commander"),JG=um(),qw=pm(),zG=M_(),QG=F_(),ZG=ny(),eU=Ty(),tU=Iy(),nU=sw(),rU=Wf(),sU=kw(),Yw=Mw(),iU=Gw(),ra=To(),vl=Ke(),oU=fa(),Xw=Ac();function aU(t){let e=parseInt(t.maxConcurrentSandboxes??"",10);if(Number.isFinite(e)&&e>0)return e;let n=parseInt(t.maxConcurrentCells??"",10);if(Number.isFinite(n)&&n>0)return console.warn(`Warning: --max-concurrent-cells is DEPRECATED; use ${Xw.DEPRECATED_CAP_SPELLINGS["--max-concurrent-cells"]}. Honouring it for now.`),n}function cU(){try{return Hu().version??"dev"}catch{return"dev"}}var lU=cU(),uU=[`${vl.AGENTIDE_BRAND_NAME} CLI - Run agent packs from the command line`,"","Environment Variables:"," AGENTHIPPO_LITELLM_API_KEY API key for LiteLLM proxy"," AGENTHIPPO_LITELLM_BASE_URL Base URL for LiteLLM proxy"," ANTHROPIC_API_KEY Direct Anthropic API key"," OPENAI_API_KEY Direct OpenAI API key"," AGENTHIPPO_DEFAULT_ENGINE Default engine (claude/codex/<custom-engine-id>)"," AGENTHIPPO_DEFAULT_MODEL Default model ID"," AGENTHIPPO_HOME Override ~/.agent-hippo directory"," AGENTHIPPO_SERVE_HOST Listen address for serve (default 127.0.0.1; use 0.0.0.0 in containers)"," AGENTHIPPO_STORE_REPO Override store GitHub repo (owner/repo; CLI store commands)","","Quickstart:",` AGENTHIPPO_LITELLM_BASE_URL="http://localhost:4000" AGENTHIPPO_LITELLM_API_KEY="dummy" AGENTHIPPO_DEFAULT_MODEL="litellm/gpt-5.5" AGENTHIPPO_DEFAULT_ENGINE="codex" ${vl.AGENTIDE_CLI_NAME} ask "Reply with exactly: CLI_TEST_OK"`,"","Agent Packs:",` Loaded from ~/${vl.AGENTIDE_DIR_NAME}/agents/<name>/ or absolute/relative paths.`," Pack permissions control filesystem access scope."].join(`
635
- `),Le=new Kw.Command;Le.hook("preAction",async(t,e)=>{e?.name()!=="sandbox"&&await(0,oU.mergeAgentHomeEnvIntoProcessEnv)()});Le.name(vl.AGENTIDE_CLI_NAME).description(uU).version(lU);Le.option("-v, --verbose","Enable verbose logging").option("--config <path>","Path to config file");Le.command("chat").description("Start interactive chat session").option("-a, --agent <name>","Agent pack to use").option("-e, --engine <id>","Override pack engine: claude|codex|<custom-engine-id>").option("-m, --model <id>","Override pack model (e.g. litellm/gpt-5.6-luna)").option("-w, --workspace <path>","Workspace directory",process.cwd()).action(async t=>{let e=Le.opts().verbose;await(0,ra.ensureDeps)(e),await(0,JG.chatCommand)({agent:t.agent,engine:t.engine,model:t.model,workspace:t.workspace,verbose:e})});Le.command("ask <message...>").description("Send a single message and exit").option("-a, --agent <name>","Agent pack to use").option("-e, --engine <id>","Override pack engine: claude|codex|<custom-engine-id>").option("-m, --model <id>","Override pack model (e.g. litellm/gpt-5.6-luna)").option("-w, --workspace <path>","Workspace directory",process.cwd()).option("-f, --file <path>","Include file content in context").option("--json","Output as JSON").option("--session-id <id>","Conversation session id (enables multi-turn resume across ask invocations)").action(async(t,e)=>{let n=Le.opts().verbose;await(0,ra.ensureDeps)(n);let r=t.join(" ");await(0,qw.askCommand)({message:r,agent:e.agent,engine:e.engine,model:e.model,workspace:e.workspace,file:e.file,json:e.json,sessionId:e.sessionId,verbose:n})});Le.command("agent").description("Run agent operations").command("run").description("Run a single prompt and output JSON").requiredOption("--json","Output JSON (required)").requiredOption("--prompt <message>","Prompt text").option("--pack <name>","Agent pack to use").option("-e, --engine <id>","Override pack engine: claude|codex|<custom-engine-id>").option("-m, --model <id>","Override pack model (e.g. litellm/gpt-5.6-luna)").option("-w, --workspace <path>","Workspace directory",process.cwd()).option("--session-id <id>","Optional session id for the caller").option("--system-prompt <text>","Optional system prompt override").option("-f, --file <path>","Include file content in context").action(async t=>{let e=Le.opts().verbose;await(0,ra.ensureDeps)(e),await(0,qw.askCommand)({message:t.prompt,agent:t.pack,engine:t.engine,model:t.model,workspace:t.workspace,file:t.file,json:!0,sessionId:t.sessionId,systemPrompt:t.systemPrompt,outputMode:"agent-run",verbose:e})});Le.command("serve").description("Start HTTP server").requiredOption("-a, --agent <name>","Agent pack to use (required)").option("-e, --engine <id>","Override pack engine: claude|codex|<custom-engine-id>").option("-m, --model <id>","Override pack model (e.g. litellm/gpt-5.6-luna)").option("-p, --port <port>","Port to listen on","3000").option("--host <address>","Address to bind the HTTP server (default 127.0.0.1; use 0.0.0.0 in containers/behind a proxy)").option("-w, --workspace <path>","Default workspace directory",process.cwd()).option("--bind <channels>",'Bind agent to gateway channels (comma-separated, e.g. "telegram,whatsapp" or "*" for all)').option("--gateway-bridge","Keep a WebSocket to OpenClaw and register this pack so `openclaw agent --agent <id>` routes here (needs OPENCLAW_GATEWAY_TOKEN if your gateway requires it)").option("--state-dir <path>","Persist session state here (honors AGENTHIPPO_HOME; replaces the tmpdir default)").option("--max-turns-per-session <n>","Cap turns per session (abuse/runaway guard); 0 = unlimited","0").option("--www-dir <path>","Serve deploy/www/index.html at GET / (static browser chat UI)").option("--sandbox <mode>","Run each session's engine in a sandbox: process (tier 0, no boundary) or container (tier 2, one disposable container per session with only its declared routes). Unset = in-process (default, unchanged)").option("--sandbox-image <ref>","--sandbox container: sandbox image pinned BY DIGEST (image@sha256:...)").option("--sandbox-scope <scope>","--sandbox: what one sandbox holds \u2014 session (default, one per conversation) or user (one per verified user on this instance, so their sessions share a container, workspace, TTL and kill). Unidentified callers get one each either way").option("--pull-packs","Fetch the version the lease pins from the store instead of only refusing others. Always verifies the signature; a fetch or verification failure keeps serving the current version").option("--require-signed-pack","Refuse to start a sandbox unless the pack is signed by a trusted key (the lease may also require this; neither side can waive the other). Now the DEFAULT \u2014 kept so existing invocations still mean something").option("--allow-unsigned-pack","LOCAL DEVELOPMENT ONLY: run a pack this instance cannot verify. Signature checking is required by default; this disables it and warns loudly on every boot. A lease that sets requireSignedPack still overrides it").option("--require-signed-lease","Refuse to act on a lease that is not signed (ES256 compact JWS) by a trusted key. Tighten-only with lease.requireSignedLease, and sticky once a signed lease has been seen").option("--lease-max-staleness <seconds>","Refuse turns after this long with no successful lease refresh, so network denial cannot hold a revoked fleet open (default 86400; 0 disables)").option("--sandbox-ttl <seconds>","--sandbox: reap an idle sandbox after N seconds; the next message recreates it and resumes the session","1800").option("--shared-workspace","--sandbox container: mount ONE workspace into every session's sandbox (default: one per session). Sessions can then read and overwrite each other's files \u2014 only for a single trust domain").option("--max-session-seconds <seconds>","--sandbox: cap one session's wall-clock lifetime; a breach revokes or destroys its sandbox").option("--max-concurrent-sandboxes <n>","--sandbox: cap live sandboxes on this instance (blast radius)").addOption(new Kw.Option("--max-concurrent-cells <n>","DEPRECATED alias for --max-concurrent-sandboxes").hideHelp()).option("--cap-on-breach <action>","--sandbox: what a cap breach does \u2014 revoke-inference (default) or destroy-sandbox. An unrecognised value fails CLOSED to destroy-sandbox").option("--lease-poll <seconds>","--sandbox: how often to re-check the lease, so a kill switch stops RUNNING sandboxes. Worst-case kill latency is 2x this (poll + cache); an admin refresh is immediate","30").action(async t=>{let e=Le.opts().verbose;await(0,ra.ensureDeps)(e),await(0,zG.serveCommand)({sandbox:t.sandbox==="container"?"container":t.sandbox==="process"?"process":void 0,sandboxImage:t.sandboxImage,sandboxScope:t.sandboxScope==="user"?"user":"session",requireSignedPack:!!t.requireSignedPack,allowUnsignedPack:!!t.allowUnsignedPack,requireSignedLease:!!t.requireSignedLease,leaseMaxStalenessSeconds:t.leaseMaxStaleness!==void 0&&Number.isFinite(Number(t.leaseMaxStaleness))?Number(t.leaseMaxStaleness):void 0,pullPacks:!!t.pullPacks,sandboxTtlSeconds:parseInt(t.sandboxTtl,10)||void 0,sharedWorkspace:!!t.sharedWorkspace,maxSessionSeconds:parseInt(t.maxSessionSeconds,10)||void 0,maxConcurrentSandboxes:aU(t),capOnBreach:(()=>{let n=(0,Xw.resolveOnBreach)(t.capOnBreach,"--cap-on-breach");for(let r of n.warnings)console.warn(`Warning: ${r}`);return n.action})(),leasePollSeconds:parseInt(t.leasePoll,10)||void 0,agent:t.agent,engine:t.engine,model:t.model,port:parseInt(t.port,10),host:t.host,workspace:t.workspace,bind:t.bind,gatewayBridge:!!t.gatewayBridge,stateDir:t.stateDir,maxTurnsPerSession:parseInt(t.maxTurnsPerSession,10),wwwDir:t.wwwDir,verbose:e})});Le.command("conformance").description("Probe a deployment against its own claims: credential confinement, isolation tier, cost-cap binding, warrant integrity, rollback/kill switch. Exit 1 on any failure, 2 when no deployment was probed (--sandbox/--tier omitted) \u2014 only exit 0 means a real deployment was measured.").option("--sandbox <id>","Running sandbox container id/name \u2014 required to probe INSIDE a sandbox").option("--tier <n>","Declared isolation tier (0-3); probed, not trusted").option("--runtime <bin>","Container runtime binary","docker").option("--json","Emit JSON").action(async t=>{let{conformanceCommand:e}=await Promise.resolve().then(()=>wn(Uw())),n=await e({sandbox:t.sandbox,tier:t.tier===void 0?void 0:parseInt(t.tier,10),runtime:t.runtime,json:!!t.json});process.exitCode=n});Le.command("sandbox").description("Run the in-sandbox engine host (sandbox runner). Speaks the frame protocol to serve over a unix socket or stdio; holds no data or model credential.").requiredOption("-a, --agent <path>","Pack directory mounted into the sandbox").option("--socket <path>","Unix socket to listen on (container driver)").option("--stdio","Speak the protocol on stdin/stdout instead (process driver)").option("-w, --workspace <path>","Workspace directory (default: <state-dir>/workspace)").option("--state-dir <path>","State directory","/state").option("--sandbox-id <id>","Sandbox id (joins evidence records)").action(async t=>{let{sandboxCommand:e}=await Promise.resolve().then(()=>wn(Vw()));await e({agent:t.agent,socket:t.socket,stdio:!!t.stdio,workspace:t.workspace,stateDir:t.stateDir,sandboxId:t.sandboxId})});Le.command("data-plane").description("Run the connector as a sidecar (holds the backend base credential; the agent container does not)").requiredOption("-a, --agent <name>","Agent pack (reads spec.dataPlane connector + provider)").option("-w, --workspace <path>","Workspace directory",process.cwd()).option("--gateway-port <port>","Port the engine dials (nonce-auth MCP)","9090").option("--control-port <port>","Port serve dials to register turns (bearer-auth)","9091").option("--host <address>","Bind address (default 0.0.0.0 for the pod network)").option("--state-dir <path>","Where data-plane audit events are written. Same precedence as serve: --state-dir, then AGENTHIPPO_HOME, then tmpdir").action(async t=>{let e=Le.opts().verbose;await(0,ra.ensureDeps)(e),await(0,QG.dataPlaneSidecarCommand)({agent:t.agent,workspace:t.workspace,gatewayPort:parseInt(t.gatewayPort,10),controlPort:parseInt(t.controlPort,10),host:t.host,stateDir:t.stateDir,verbose:e})});Le.command("auth-broker").description("Start the AgentHippo auth broker (OAuth + IDE bootstrap API)").action(async()=>{await(0,ZG.authBrokerCommand)()});Le.command("deploy <action> [pack]").description("Generate a self-contained deploy staging dir (init). Targets: vm, compose, cloudrun, databricks-app, spcs, cloudflare, aws-ecs, azure-container-apps, all. Or pick a --blueprint instead of raw --target/--ingress.").option("-t, --target <target>","Deploy target","vm").option("--blueprint <id>","Named preset (sandbox, prospect-demo, team-pilot, regulated-air-gapped, enterprise-fleet) \u2014 resolves --target/--ingress for you; overrides both when set").option("--platform <platform>","Which platform to use within --blueprint's supported set (defaults to the blueprint's first); ignored without --blueprint").option("-o, --out <path>","Staging directory (default: ./deploy-out/<pack>-<target> relative to cwd; run from the pack parent, not from inside the pack)").option("--packdir <path>","Pack directory (defaults to [pack] arg or cwd)").option("--image <ref>","Runtime image ref (default: engine runtime:latest, or :latest-cursor for cursor packs)").option("-p, --port <port>","Container port","8080").option("--gateway <channels>",'Agent Anywhere: bind channels (e.g. "slack") + add OpenClaw gateway service (compose target)').option("--hostname <host>","Public hostname for SSO edge (Caddy, OAuth, tunnel)","auth.agenthippo.ai").option("--ingress <mode>","iap (Cloud Run built-in IAP only), edge (self-issued AgentHippo edge + Google OAuth \u2014 vm/compose/cloudrun/aws-ecs/azure-container-apps), or edge-fed (federated: auth via the central IdP, no per-target OAuth client \u2014 same targets as edge)","iap").option("--idp-url <url>","edge-fed: central IdP base URL browsers redirect to for login (e.g. https://auth.agenthippo.ai)","https://auth.agenthippo.ai").option("--cookie-domain <domain>","edge-fed: parent domain the shared auth cookie is scoped to (e.g. .agenthippo.ai)",".agenthippo.ai").option("--colocate","edge-fed + vm/compose only: ride the org IdP's already-running Caddy + auth-broker instead of shipping this agent's own").option("--edge-turn-connector <addr>","EDGE turn registration (P1 fix): connector sidecar control-API address (e.g. mypack-connector:9091); the generated route registers each chat turn via forward_auth /edge/turn and copies X-Agent-Turn-Nonce \u2014 the agent container never holds the register token").option("--model-routing <mode>","Cloud Run + edge-fed: sidecar (in-pod LiteLLM+OTEL, default) or gateway (agent \u2192 gateway.agenthippo.ai directly, lean)").option("--force","Overwrite existing files").action(async(t,e,n)=>{let r=n.ingress==="edge"?"edge":n.ingress==="edge-fed"?"edge-fed":"iap",s=n.modelRouting==="gateway"?"gateway":n.modelRouting==="sidecar"?"sidecar":void 0;await(0,eU.deployCommand)(t,e,{target:n.target,blueprint:n.blueprint,platform:n.platform,out:n.out,image:n.image,gateway:n.gateway,hostname:n.hostname,port:parseInt(n.port,10),force:!!n.force,packdir:n.packdir,ingress:r,idpUrl:n.idpUrl,cookieDomain:n.cookieDomain,colocate:!!n.colocate,modelRouting:s,edgeTurnConnector:n.edgeTurnConnector})});Le.command("idp <action>").description("Generate the central IdP stack (init) \u2014 Caddy + oauth2-proxy + auth-broker. One per organization; agents federate against it with `deploy init --ingress edge-fed`.").option("--hostname <host>","Public hostname the IdP is reachable at (e.g. auth.corp.example) \u2014 required").option("--cookie-domain <domain>","Parent domain the shared auth cookie is scoped to (e.g. .corp.example); defaults to the hostname's own domain").option("-o, --out <path>","Output directory (default: ./enterprise-deploy/idp)").option("--force","Overwrite existing files").action(async(t,e)=>{await(0,tU.idpCommand)(t,{hostname:e.hostname,cookieDomain:e.cookieDomain,out:e.out,force:!!e.force})});Le.command("pack <action>").description("Manage agent packs (list, validate, sign, verify, digest, keygen, install)").argument("[name]","Pack name or path").option("-o, --output <path>","Output path for export, or for a generated signing key").option("--key <path>","pack sign: PEM file holding the ES256 private key").option("--kid <id>","pack sign/keygen: key id published in JWKS so verifiers can find the public half").option("--keys <path>","pack verify: JSON file of kid -> public PEM").option("--jwks <url>","pack verify: JWKS endpoint to fetch public halves from").option("--to <dir>","pack install: destination folder (flat layout for serve/deploy)").option("-f, --force","pack install: overwrite an existing folder").option("-w, --workspace <path>","Workspace directory for local packs",process.cwd()).action(async(t,e,n)=>{await(0,nU.packCommand)({action:t,name:e,output:n.output,to:n.to,force:n.force,workspace:n.workspace,key:n.key,kid:n.kid,keys:n.keys,jwks:n.jwks,verbose:Le.opts().verbose})});Le.command("store <action>").description("Search, install, and uninstall store artifacts").argument("[query]","Search query or artifact reference (e.g., skill/pdf-tools)").option("-t, --type <type>","Filter by type: pack, skill, mcp, engine, spotlight view").option("-l, --limit <n>","Max results for search","20").option("--version <ver>","Specific version to install or publish").option("-w, --workspace <path>","Workspace directory",process.cwd()).option("-a, --agent <id>","Target agent ID for skill/mcp install","default").option("-f, --force","Overwrite existing installation").option("--bundle <mode>","Spotlight view publish bundle: scripts-only (default) or full").option("--full","Publish Spotlight view full bundle: scripts, assets, charts, exports, manifest.json (same as --bundle full)").option("--json","Output as JSON").action(async(t,e,n)=>{await(0,rU.storeCommand)({action:t,query:e,type:n.type,limit:parseInt(n.limit,10),version:n.version,workspace:n.workspace,agent:n.agent,force:n.force,bundle:n.bundle,full:n.full,json:n.json,verbose:Le.opts().verbose})});var Jw=Le.command("gateway").description("Gateway outbound messaging");Jw.command("send").description("Send a proactive message via the gateway (WebSocket RPC; hippoclaw CLI fallback)").option("--outbound <path>","Session gateway-outbound.json (see AGENTHIPPO_GATEWAY_OUTBOUND_FILE)").option("-a, --agent <id>","Agent pack id").requiredOption("-m, --message <text>","Message to send").option("--media <path-or-url>","Attach media (image/audio/video/document); local path or URL. Sent via gateway RPC so the bot token resolves from the gateway runtime snapshot.").option("-t, --target <target>","Explicit target (e.g. channel:C01234567); defaults to last inbound route").option("--thread-id <id>","Slack thread ts when sending to a threaded route").option("--dry-run","Print gateway RPC payload without sending").option("--json","Output handle + result as JSON").action(async t=>{await(0,Yw.gatewaySendCommand)({outbound:t.outbound??"",agent:t.agent??"",message:t.message,media:t.media,target:t.target,threadId:t.threadId,dryRun:!!t.dryRun,json:!!t.json})});Jw.command("list").description("List stored gateway outbound routes from a session file").requiredOption("--outbound <path>","Session gateway-outbound.json (see AGENTHIPPO_GATEWAY_OUTBOUND_FILE)").option("-a, --agent <id>","Filter to one agent pack id").option("--json","Output as JSON").action(async t=>{await(0,Yw.gatewayListCommand)({outbound:t.outbound,agent:t.agent,json:!!t.json})});Le.command("anywhere <action>").description("Manage Agent Anywhere gateway lifecycle").option("-s, --source <source>","Install source (e.g. openclaw@latest, org/repo#branch, /path/to/openclaw)").option("-p, --port <port>","Gateway port","18789").option("-b, --bind <address>","Gateway bind address","127.0.0.1").option("-t, --token <token>","Gateway auth token for starter config").option("--no-start","For setup: install/configure without starting").option("--config-template <path>","Path to openclaw.json template").action(async(t,e)=>{let n=parseInt(e.port,10);await(0,sU.anywhereCommand)({action:t,source:e.source,port:Number.isNaN(n)?void 0:n,bind:e.bind,token:e.token,noStart:e.start===!1,configTemplate:e.configTemplate})});Le.command("__probe-custom-engine").description("Test custom engine load strategies (import probe)").option("-e, --engine <id>","Custom engine id","cursor").option("-w, --workspace <path>","Workspace directory",process.cwd()).option("-s, --strategy <mode>","in-process|node-subprocess|all|a|c","all").action(async t=>{await(0,iU.probeCustomEngineCommand)({engine:t.engine,workspace:t.workspace,strategy:t.strategy})});Le.parseAsync();
635
+ THIS BINARY (contract checks \u2014 environment-independent, pass with no deployment)`),n.filter(c=>c.kind==="algorithm").forEach(a),console.log(""),o)console.log("NO DEPLOYMENT WAS PROBED. The binary checks above say nothing about a running"),console.log("system \u2014 pass --sandbox <container> --tier <n> to actually test one.");else{let c=s.filter(l=>l.status==="pass").length;console.log(`${c}/${s.length} deployment checks passed`+(r.length-s.length?`, ${r.length-s.length} not probed`:""))}i.length&&console.log(`${i.length} FAILED`)}return i.length?1:o?2:0}});var Fw=S(Tp=>{"use strict";Object.defineProperty(Tp,"__esModule",{value:!0});Tp.startRunnerHost=jG;var Ap=Ku(),UG=1e3*60*5,HG={selected:[],freeText:null,declined:!0};function jG(t){let e=f=>{t.output.write((0,Ap.encodeRunnerFrame)(f))},n=new Map,r="",s=!1,i=setInterval(()=>{try{t.engine.onMaintenance(t.logger??BG())}catch(f){t.logger?.warn(`[Runner] maintenance failed: ${Sp(f)}`)}},t.maintenanceIntervalMs??UG);typeof i.unref=="function"&&i.unref();let o=()=>{},a=new Promise(f=>{o=()=>{if(!s){s=!0,clearInterval(i);for(let u of n.values())u.abort();n.clear(),f()}},t.input.on("data",u=>{r+=typeof u=="string"?u:u.toString("utf8");let{lines:d,rest:p}=(0,Ap.splitFrames)(r);r=p;for(let g of d){let m=(0,Ap.parseClientFrame)(g);if(!m){t.logger?.warn("[Runner] dropped malformed client frame");continue}c(m)}}),t.input.on("end",o),t.input.on("close",o),t.input.on("error",u=>{t.logger?.warn(`[Runner] input error: ${Sp(u)}`),o()})});async function c(f){if(f.type==="abort"){n.get(f.id)?.abort();return}await l(f.id,f.message,f.options)}async function l(f,u,d){if(n.has(f)){e({type:"failed",id:f,message:`duplicate run id ${f}`});return}let p=new AbortController;n.set(f,p);let g=xG(e,f);try{await t.engine.stream(u,d,g,t.runtime,p.signal);let m=t.nativeSessionId?.();e({type:"result",id:f,...m?{nativeSessionId:m}:{}})}catch(m){let h=p.signal.aborted?"aborted":Sp(m);e({type:"failed",id:f,message:h})}finally{n.delete(f)}}return e({type:"ready",demux:!0}),{done:a,close:()=>o()}}function xG(t,e){let n=r=>t({id:e,event:r});return{async thinking(r){n({type:"thinking",delta:r})},async text(r){n({type:"text",delta:r})},async toolStart(r,s,i){n({type:"toolStart",toolName:r,...s!==void 0?{input:s}:{},...i?{toolCallId:i}:{}})},async toolEnd(r,s,i,o){n({type:"toolEnd",toolName:r,toolCallId:s,...i!==void 0?{result:i}:{},...o!==void 0?{isError:o}:{}})},async progress(r){n({type:"progress",message:r})},async question(r){return t({type:"question",payload:r,id:e}),HG},async error(r){n({type:"error",message:r})},async done(){n({type:"done"})}}}function Sp(t){return t instanceof Error?t.message:String(t)}function BG(){return{info:()=>{},warn:()=>{},error:()=>{},debug:()=>{}}}});var Yw=S(Rr=>{"use strict";var FG=Rr&&Rr.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,s)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),VG=Rr&&Rr.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),Op=Rr&&Rr.__importStar||(function(){var t=function(e){return t=Object.getOwnPropertyNames||function(n){var r=[];for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(r[r.length]=s);return r},t(e)};return function(e){if(e&&e.__esModule)return e;var n={};if(e!=null)for(var r=t(e),s=0;s<r.length;s++)r[s]!=="default"&&FG(n,e,r[s]);return VG(n,e),n}})();Object.defineProperty(Rr,"__esModule",{value:!0});Rr.resolveSandboxWorkspace=Kw;Rr.isForeignWorkspace=qw;Rr.sandboxCommand=QG;var ra=Op(require("fs")),WG=Op(require("net")),vl=Op(require("path")),bp=oi(),KG=Wn(),Vw=ai(),qG=md(),YG=vo(),XG=Br(),JG=Er(),Ww=Fw();function Kw(t,e){return e}function qw(t,e){return t?vl.resolve(t)!==vl.resolve(e):!1}var vp=class{defaults;id="sandbox";displayName="Sandbox runner";runner;builtWith;warnedWorkspace=!1;nativeSessionId;constructor(e){this.defaults=e}ensureRunner(e){let n=e.baseUrl??"";return this.runner&&this.builtWith===n?this.runner:(this.runner?.dispose(),this.runner=(0,qG.createPackRunner)({storagePath:this.defaults.storagePath,analyticsSessionsDir:this.defaults.analyticsSessionsDir,packId:this.defaults.packId,packVersion:this.defaults.packVersion,provenance:()=>(0,JG.readProvenanceEnvFromProcess)(),workspaceRoot:this.defaults.workspace,credentials:{baseUrl:e.baseUrl,litellmApiKey:e.modelToken,useLiteLLM:!!e.baseUrl},claudeCheapModel:this.defaults.claudeCheapModel,omitGatewayToken:!0}),this.builtWith=n,this.runner)}async stream(e,n,r,s,i){let o=n,a=o.workspaceRoot,c=Kw(a,this.defaults.workspace);qw(a,c)&&!this.warnedWorkspace&&(this.warnedWorkspace=!0,console.warn(`[sandbox] ignoring workspaceRoot ${a} from the wire \u2014 this sandbox works in ${c}`));try{ra.mkdirSync(c,{recursive:!0}),process.chdir(c)}catch(p){throw new Error(`sandbox cannot use workspace ${c}: ${p instanceof Error?p.message:String(p)}`)}let l=this.ensureRunner(o),f=o,u=f.permissions??(f.fileAccess?{fileAccess:f.fileAccess}:{fileAccess:this.defaults.fileAccess}),d=await l.run({engineId:o.engineId??this.defaults.engineId,modelId:o.modelId??this.defaults.modelId,message:e,workspaceRoot:c,additionalDirectories:o.additionalDirectories,sessionId:o.sessionId,modelToken:o.modelToken,permissions:u,analyticsUserId:o.analyticsUserId,engineHomeUserKey:o.engineHomeUserKey,turnEnv:o.turnEnv,gatewaySessionKey:o.gatewaySessionKey,emitter:r,signal:i});if(!d.success&&d.error)throw new Error(d.error)}onMaintenance(){}dispose(){this.runner?.dispose()}};function zG(){process.on("unhandledRejection",t=>{let e=t instanceof Error?t.message:String(t);console.error(`[sandbox] unhandled rejection (session kept alive): ${e}`)}),process.on("uncaughtException",t=>{console.error(`[sandbox] uncaught exception \u2014 exiting so the driver recreates this sandbox: ${t.message}`),process.exit(1)})}async function QG(t){await(0,YG.ensureDeps)(!1);let e=t.stateDir??"/state",n=t.workspace??vl.join(e,"workspace");ra.mkdirSync(n,{recursive:!0});let r=await(0,Vw.loadAgentPack)(t.agent,n),s={name:r.manifest.metadata.name,version:r.manifest.metadata.version,engine:r.manifest.spec?.engine??"claude"};t.stateDir?process.env.AGENTHIPPO_HOME=e:process.env.AGENTHIPPO_HOME=process.env.AGENTHIPPO_HOME??e,process.env.AGENTHIPPO_SANDBOX="1";let i=vl.join(e,"home");ra.mkdirSync(i,{recursive:!0}),process.env.HOME=i;let o=n;await(0,bp.syncPackToWorkspace)(o,r.packPath,s.name,s.engine,console,(0,KG.findBundledBasePromptsDir)()),console.log(`[sandbox] pack ${s.name}@${s.version??"?"} synced into ${o} (engine ${s.engine})`),zG();let a=r.manifest.spec?.cheapModel?.trim(),c=new vp({storagePath:e,analyticsSessionsDir:(0,XG.resolveAnalyticsSessionsDir)(e,!1),packId:s.name,packVersion:s.version,engineId:s.engine,modelId:(0,bp.resolveModelAlias)(r.manifest.spec?.model?.trim()||"ah-auto"),claudeCheapModel:a?(0,bp.resolveModelAlias)(a):void 0,fileAccess:(0,Vw.getFileAccess)(r),workspace:o}),l={logger:console};if(t.stdio){await(0,Ww.startRunnerHost)({engine:c,runtime:l,input:process.stdin,output:{write:p=>process.stdout.write(p)},nativeSessionId:()=>c.nativeSessionId}).done;return}let f=t.socket;if(!f)throw new Error("sandbox requires --socket <path> or --stdio");try{ra.unlinkSync(f)}catch{}let u=WG.createServer(d=>{(0,Ww.startRunnerHost)({engine:c,runtime:l,input:d,output:{write:p=>d.write(p)},nativeSessionId:()=>c.nativeSessionId})});try{await new Promise((d,p)=>{u.once("error",p),u.listen(f,()=>d())})}catch(d){console.error(`[sandbox] FATAL: cannot listen at ${f}: ${d instanceof Error?d.message:String(d)}`),process.exit(1)}try{ra.chmodSync(f,432)}catch{}console.log(`[sandbox] ${t.sandboxId??"sandbox"} listening on ${f} (pack ${s.name}@${s.version??"?"})`),await new Promise(d=>{let p=()=>{u.close(()=>d()),c.dispose()};process.once("SIGTERM",p),process.once("SIGINT",p),u.once("close",()=>d())})}});Object.defineProperty(exports,"__esModule",{value:!0});var Xw=require("module"),ZG=Xw.prototype.require;Xw.prototype.require=function(t){return t==="vscode"?{window:{showInformationMessage:()=>{},showErrorMessage:()=>{},showWarningMessage:()=>Promise.resolve(void 0)},workspace:{getConfiguration:()=>({get:(e,n)=>n,inspect:()=>{}})},commands:{executeCommand:async()=>{}},Memento:class{}}:ZG.apply(this,arguments)};var Jw=require("commander"),eU=dm(),zw=gm(),tU=G_(),nU=V_(),rU=ry(),sU=Iy(),iU=Cy(),oU=cw(),aU=Kf(),cU=Mw(),Qw=jw(),lU=xw(),sa=vo(),Ol=Ke(),uU=pa(),Zw=Tc();function dU(t){let e=parseInt(t.maxConcurrentSandboxes??"",10);if(Number.isFinite(e)&&e>0)return e;let n=parseInt(t.maxConcurrentCells??"",10);if(Number.isFinite(n)&&n>0)return console.warn(`Warning: --max-concurrent-cells is DEPRECATED; use ${Zw.DEPRECATED_CAP_SPELLINGS["--max-concurrent-cells"]}. Honouring it for now.`),n}function fU(){try{return pc().version??"dev"}catch{return"dev"}}var pU=fU(),gU=[`${Ol.AGENTIDE_BRAND_NAME} CLI - Run agent packs from the command line`,"","Environment Variables:"," AGENTHIPPO_LITELLM_API_KEY API key for LiteLLM proxy"," AGENTHIPPO_LITELLM_BASE_URL Base URL for LiteLLM proxy"," ANTHROPIC_API_KEY Direct Anthropic API key"," OPENAI_API_KEY Direct OpenAI API key"," AGENTHIPPO_DEFAULT_ENGINE Default engine (claude/codex/<custom-engine-id>)"," AGENTHIPPO_DEFAULT_MODEL Default model ID"," AGENTHIPPO_HOME Override ~/.agent-hippo directory"," AGENTHIPPO_SERVE_HOST Listen address for serve (default 127.0.0.1; use 0.0.0.0 in containers)"," AGENTHIPPO_STORE_REPO Override store GitHub repo (owner/repo; CLI store commands)","","Quickstart:",` AGENTHIPPO_LITELLM_BASE_URL="http://localhost:4000" AGENTHIPPO_LITELLM_API_KEY="dummy" AGENTHIPPO_DEFAULT_MODEL="litellm/gpt-5.5" AGENTHIPPO_DEFAULT_ENGINE="codex" ${Ol.AGENTIDE_CLI_NAME} ask "Reply with exactly: CLI_TEST_OK"`,"","Agent Packs:",` Loaded from ~/${Ol.AGENTIDE_DIR_NAME}/agents/<name>/ or absolute/relative paths.`," Pack permissions control filesystem access scope."].join(`
636
+ `),Le=new Jw.Command;Le.hook("preAction",async(t,e)=>{e?.name()!=="sandbox"&&await(0,uU.mergeAgentHomeEnvIntoProcessEnv)()});Le.name(Ol.AGENTIDE_CLI_NAME).description(gU).version(pU);Le.option("-v, --verbose","Enable verbose logging").option("--config <path>","Path to config file");Le.command("chat").description("Start interactive chat session").option("-a, --agent <name>","Agent pack to use").option("-e, --engine <id>","Override pack engine: claude|codex|<custom-engine-id>").option("-m, --model <id>","Override pack model (e.g. litellm/gpt-5.6-luna)").option("-w, --workspace <path>","Workspace directory",process.cwd()).action(async t=>{let e=Le.opts().verbose;await(0,sa.ensureDeps)(e),await(0,eU.chatCommand)({agent:t.agent,engine:t.engine,model:t.model,workspace:t.workspace,verbose:e})});Le.command("ask <message...>").description("Send a single message and exit").option("-a, --agent <name>","Agent pack to use").option("-e, --engine <id>","Override pack engine: claude|codex|<custom-engine-id>").option("-m, --model <id>","Override pack model (e.g. litellm/gpt-5.6-luna)").option("-w, --workspace <path>","Workspace directory",process.cwd()).option("-f, --file <path>","Include file content in context").option("--json","Output as JSON").option("--session-id <id>","Conversation session id (enables multi-turn resume across ask invocations)").action(async(t,e)=>{let n=Le.opts().verbose;await(0,sa.ensureDeps)(n);let r=t.join(" ");await(0,zw.askCommand)({message:r,agent:e.agent,engine:e.engine,model:e.model,workspace:e.workspace,file:e.file,json:e.json,sessionId:e.sessionId,verbose:n})});Le.command("agent").description("Run agent operations").command("run").description("Run a single prompt and output JSON").requiredOption("--json","Output JSON (required)").requiredOption("--prompt <message>","Prompt text").option("--pack <name>","Agent pack to use").option("-e, --engine <id>","Override pack engine: claude|codex|<custom-engine-id>").option("-m, --model <id>","Override pack model (e.g. litellm/gpt-5.6-luna)").option("-w, --workspace <path>","Workspace directory",process.cwd()).option("--session-id <id>","Optional session id for the caller").option("--system-prompt <text>","Optional system prompt override").option("-f, --file <path>","Include file content in context").action(async t=>{let e=Le.opts().verbose;await(0,sa.ensureDeps)(e),await(0,zw.askCommand)({message:t.prompt,agent:t.pack,engine:t.engine,model:t.model,workspace:t.workspace,file:t.file,json:!0,sessionId:t.sessionId,systemPrompt:t.systemPrompt,outputMode:"agent-run",verbose:e})});Le.command("serve").description("Start HTTP server").requiredOption("-a, --agent <name>","Agent pack to use (required)").option("-e, --engine <id>","Override pack engine: claude|codex|<custom-engine-id>").option("-m, --model <id>","Override pack model (e.g. litellm/gpt-5.6-luna)").option("-p, --port <port>","Port to listen on","3000").option("--host <address>","Address to bind the HTTP server (default 127.0.0.1; use 0.0.0.0 in containers/behind a proxy)").option("-w, --workspace <path>","Default workspace directory",process.cwd()).option("--bind <channels>",'Bind agent to gateway channels (comma-separated, e.g. "telegram,whatsapp" or "*" for all)').option("--gateway-bridge","Keep a WebSocket to OpenClaw and register this pack so `openclaw agent --agent <id>` routes here (needs OPENCLAW_GATEWAY_TOKEN if your gateway requires it)").option("--state-dir <path>","Persist session state here (honors AGENTHIPPO_HOME; replaces the tmpdir default)").option("--max-turns-per-session <n>","Cap turns per session (abuse/runaway guard); 0 = unlimited","0").option("--www-dir <path>","Serve deploy/www/index.html at GET / (static browser chat UI)").option("--sandbox <mode>","Run each session's engine in a sandbox: process (tier 0, no boundary) or container (tier 2, one disposable container per session with only its declared routes). Unset = in-process (default, unchanged)").option("--sandbox-image <ref>","--sandbox container: sandbox image pinned BY DIGEST (image@sha256:...)").option("--sandbox-scope <scope>","--sandbox: what one sandbox holds \u2014 session (default, one per conversation) or user (one per verified user on this instance, so their sessions share a container, workspace, TTL and kill). Unidentified callers get one each either way").option("--pull-packs","Fetch the version the lease pins from the store instead of only refusing others. Always verifies the signature; a fetch or verification failure keeps serving the current version").option("--require-signed-pack","Refuse to start a sandbox unless the pack is signed by a trusted key (the lease may also require this; neither side can waive the other). Now the DEFAULT \u2014 kept so existing invocations still mean something").option("--allow-unsigned-pack","LOCAL DEVELOPMENT ONLY: run a pack this instance cannot verify. Signature checking is required by default; this disables it and warns loudly on every boot. A lease that sets requireSignedPack still overrides it").option("--require-signed-lease","Refuse to act on a lease that is not signed (ES256 compact JWS) by a trusted key. Tighten-only with lease.requireSignedLease, and sticky once a signed lease has been seen").option("--lease-max-staleness <seconds>","Refuse turns after this long with no successful lease refresh, so network denial cannot hold a revoked fleet open (default 86400; 0 disables)").option("--sandbox-ttl <seconds>","--sandbox: reap an idle sandbox after N seconds; the next message recreates it and resumes the session","1800").option("--shared-workspace","--sandbox container: mount ONE workspace into every session's sandbox (default: one per session). Sessions can then read and overwrite each other's files \u2014 only for a single trust domain").option("--max-session-seconds <seconds>","--sandbox: cap one session's wall-clock lifetime; a breach revokes or destroys its sandbox").option("--max-concurrent-sandboxes <n>","--sandbox: cap live sandboxes on this instance (blast radius)").addOption(new Jw.Option("--max-concurrent-cells <n>","DEPRECATED alias for --max-concurrent-sandboxes").hideHelp()).option("--cap-on-breach <action>","--sandbox: what a cap breach does \u2014 revoke-inference (default) or destroy-sandbox. An unrecognised value fails CLOSED to destroy-sandbox").option("--lease-poll <seconds>","--sandbox: how often to re-check the lease, so a kill switch stops RUNNING sandboxes. Worst-case kill latency is 2x this (poll + cache); an admin refresh is immediate","30").action(async t=>{let e=Le.opts().verbose;await(0,sa.ensureDeps)(e),await(0,tU.serveCommand)({sandbox:t.sandbox==="container"?"container":t.sandbox==="process"?"process":void 0,sandboxImage:t.sandboxImage,sandboxScope:t.sandboxScope==="user"?"user":"session",requireSignedPack:!!t.requireSignedPack,allowUnsignedPack:!!t.allowUnsignedPack,requireSignedLease:!!t.requireSignedLease,leaseMaxStalenessSeconds:t.leaseMaxStaleness!==void 0&&Number.isFinite(Number(t.leaseMaxStaleness))?Number(t.leaseMaxStaleness):void 0,pullPacks:!!t.pullPacks,sandboxTtlSeconds:parseInt(t.sandboxTtl,10)||void 0,sharedWorkspace:!!t.sharedWorkspace,maxSessionSeconds:parseInt(t.maxSessionSeconds,10)||void 0,maxConcurrentSandboxes:dU(t),capOnBreach:(()=>{let n=(0,Zw.resolveOnBreach)(t.capOnBreach,"--cap-on-breach");for(let r of n.warnings)console.warn(`Warning: ${r}`);return n.action})(),leasePollSeconds:parseInt(t.leasePoll,10)||void 0,agent:t.agent,engine:t.engine,model:t.model,port:parseInt(t.port,10),host:t.host,workspace:t.workspace,bind:t.bind,gatewayBridge:!!t.gatewayBridge,stateDir:t.stateDir,maxTurnsPerSession:parseInt(t.maxTurnsPerSession,10),wwwDir:t.wwwDir,verbose:e})});Le.command("conformance").description("Probe a deployment against its own claims: credential confinement, isolation tier, cost-cap binding, warrant integrity, rollback/kill switch. Exit 1 on any failure, 2 when no deployment was probed (--sandbox/--tier omitted) \u2014 only exit 0 means a real deployment was measured.").option("--sandbox <id>","Running sandbox container id/name \u2014 required to probe INSIDE a sandbox").option("--tier <n>","Declared isolation tier (0-3); probed, not trusted").option("--runtime <bin>","Container runtime binary","docker").option("--json","Emit JSON").action(async t=>{let{conformanceCommand:e}=await Promise.resolve().then(()=>wn(Bw())),n=await e({sandbox:t.sandbox,tier:t.tier===void 0?void 0:parseInt(t.tier,10),runtime:t.runtime,json:!!t.json});process.exitCode=n});Le.command("sandbox").description("Run the in-sandbox engine host (sandbox runner). Speaks the frame protocol to serve over a unix socket or stdio; holds no data or model credential.").requiredOption("-a, --agent <path>","Pack directory mounted into the sandbox").option("--socket <path>","Unix socket to listen on (container driver)").option("--stdio","Speak the protocol on stdin/stdout instead (process driver)").option("-w, --workspace <path>","Workspace directory (default: <state-dir>/workspace)").option("--state-dir <path>","State directory","/state").option("--sandbox-id <id>","Sandbox id (joins evidence records)").action(async t=>{let{sandboxCommand:e}=await Promise.resolve().then(()=>wn(Yw()));await e({agent:t.agent,socket:t.socket,stdio:!!t.stdio,workspace:t.workspace,stateDir:t.stateDir,sandboxId:t.sandboxId})});Le.command("data-plane").description("Run the connector as a sidecar (holds the backend base credential; the agent container does not)").requiredOption("-a, --agent <name>","Agent pack (reads spec.dataPlane connector + provider)").option("-w, --workspace <path>","Workspace directory",process.cwd()).option("--gateway-port <port>","Port the engine dials (nonce-auth MCP)","9090").option("--control-port <port>","Port serve dials to register turns (bearer-auth)","9091").option("--host <address>","Bind address (default 0.0.0.0 for the pod network)").option("--state-dir <path>","Where data-plane audit events are written. Same precedence as serve: --state-dir, then AGENTHIPPO_HOME, then tmpdir").action(async t=>{let e=Le.opts().verbose;await(0,sa.ensureDeps)(e),await(0,nU.dataPlaneSidecarCommand)({agent:t.agent,workspace:t.workspace,gatewayPort:parseInt(t.gatewayPort,10),controlPort:parseInt(t.controlPort,10),host:t.host,stateDir:t.stateDir,verbose:e})});Le.command("auth-broker").description("Start the AgentHippo auth broker (OAuth + IDE bootstrap API)").action(async()=>{await(0,rU.authBrokerCommand)()});Le.command("deploy <action> [pack]").description("Generate a self-contained deploy staging dir (init). Targets: vm, compose, cloudrun, databricks-app, spcs, cloudflare, aws-ecs, azure-container-apps, all. Or pick a --blueprint instead of raw --target/--ingress.").option("-t, --target <target>","Deploy target","vm").option("--blueprint <id>","Named preset (sandbox, prospect-demo, team-pilot, regulated-air-gapped, enterprise-fleet) \u2014 resolves --target/--ingress for you; overrides both when set").option("--platform <platform>","Which platform to use within --blueprint's supported set (defaults to the blueprint's first); ignored without --blueprint").option("-o, --out <path>","Staging directory (default: ./deploy-out/<pack>-<target> relative to cwd; run from the pack parent, not from inside the pack)").option("--packdir <path>","Pack directory (defaults to [pack] arg or cwd)").option("--image <ref>","Runtime image ref (default: engine runtime:latest, or :latest-cursor for cursor packs)").option("-p, --port <port>","Container port","8080").option("--gateway <channels>",'Agent Anywhere: bind channels (e.g. "slack") + add OpenClaw gateway service (compose target)').option("--hostname <host>","Public hostname for SSO edge (Caddy, OAuth, tunnel)","auth.agenthippo.ai").option("--ingress <mode>","iap (Cloud Run built-in IAP only), edge (self-issued AgentHippo edge + Google OAuth \u2014 vm/compose/cloudrun/aws-ecs/azure-container-apps), or edge-fed (federated: auth via the central IdP, no per-target OAuth client \u2014 same targets as edge)","iap").option("--idp-url <url>","edge-fed: central IdP base URL browsers redirect to for login (e.g. https://auth.agenthippo.ai)","https://auth.agenthippo.ai").option("--cookie-domain <domain>","edge-fed: parent domain the shared auth cookie is scoped to (e.g. .agenthippo.ai)",".agenthippo.ai").option("--colocate","edge-fed + vm/compose only: ride the org IdP's already-running Caddy + auth-broker instead of shipping this agent's own").option("--edge-turn-connector <addr>","EDGE turn registration (P1 fix): connector sidecar control-API address (e.g. mypack-connector:9091); the generated route registers each chat turn via forward_auth /edge/turn and copies X-Agent-Turn-Nonce \u2014 the agent container never holds the register token").option("--model-routing <mode>","Cloud Run + edge-fed: sidecar (in-pod LiteLLM+OTEL, default) or gateway (agent \u2192 gateway.agenthippo.ai directly, lean)").option("--force","Overwrite existing files").action(async(t,e,n)=>{let r=n.ingress==="edge"?"edge":n.ingress==="edge-fed"?"edge-fed":"iap",s=n.modelRouting==="gateway"?"gateway":n.modelRouting==="sidecar"?"sidecar":void 0;await(0,sU.deployCommand)(t,e,{target:n.target,blueprint:n.blueprint,platform:n.platform,out:n.out,image:n.image,gateway:n.gateway,hostname:n.hostname,port:parseInt(n.port,10),force:!!n.force,packdir:n.packdir,ingress:r,idpUrl:n.idpUrl,cookieDomain:n.cookieDomain,colocate:!!n.colocate,modelRouting:s,edgeTurnConnector:n.edgeTurnConnector})});Le.command("idp <action>").description("Generate the central IdP stack (init) \u2014 Caddy + oauth2-proxy + auth-broker. One per organization; agents federate against it with `deploy init --ingress edge-fed`.").option("--hostname <host>","Public hostname the IdP is reachable at (e.g. auth.corp.example) \u2014 required").option("--cookie-domain <domain>","Parent domain the shared auth cookie is scoped to (e.g. .corp.example); defaults to the hostname's own domain").option("-o, --out <path>","Output directory (default: ./enterprise-deploy/idp)").option("--force","Overwrite existing files").action(async(t,e)=>{await(0,iU.idpCommand)(t,{hostname:e.hostname,cookieDomain:e.cookieDomain,out:e.out,force:!!e.force})});Le.command("pack <action>").description("Manage agent packs (list, validate, sign, verify, digest, keygen, install)").argument("[name]","Pack name or path").option("-o, --output <path>","Output path for export, or for a generated signing key").option("--key <path>","pack sign: PEM file holding the ES256 private key").option("--kid <id>","pack sign/keygen: key id published in JWKS so verifiers can find the public half").option("--keys <path>","pack verify: JSON file of kid -> public PEM").option("--jwks <url>","pack verify: JWKS endpoint to fetch public halves from").option("--to <dir>","pack install: destination folder (flat layout for serve/deploy)").option("-f, --force","pack install: overwrite an existing folder").option("-w, --workspace <path>","Workspace directory for local packs",process.cwd()).action(async(t,e,n)=>{await(0,oU.packCommand)({action:t,name:e,output:n.output,to:n.to,force:n.force,workspace:n.workspace,key:n.key,kid:n.kid,keys:n.keys,jwks:n.jwks,verbose:Le.opts().verbose})});Le.command("store <action>").description("Search, install, and uninstall store artifacts").argument("[query]","Search query or artifact reference (e.g., skill/pdf-tools)").option("-t, --type <type>","Filter by type: pack, skill, mcp, engine, spotlight view").option("-l, --limit <n>","Max results for search","20").option("--version <ver>","Specific version to install or publish").option("-w, --workspace <path>","Workspace directory",process.cwd()).option("-a, --agent <id>","Target agent ID for skill/mcp install","default").option("-f, --force","Overwrite existing installation").option("--bundle <mode>","Spotlight view publish bundle: scripts-only (default) or full").option("--full","Publish Spotlight view full bundle: scripts, assets, charts, exports, manifest.json (same as --bundle full)").option("--json","Output as JSON").action(async(t,e,n)=>{await(0,aU.storeCommand)({action:t,query:e,type:n.type,limit:parseInt(n.limit,10),version:n.version,workspace:n.workspace,agent:n.agent,force:n.force,bundle:n.bundle,full:n.full,json:n.json,verbose:Le.opts().verbose})});var eA=Le.command("gateway").description("Gateway outbound messaging");eA.command("send").description("Send a proactive message via the gateway (WebSocket RPC; hippoclaw CLI fallback)").option("--outbound <path>","Session gateway-outbound.json (see AGENTHIPPO_GATEWAY_OUTBOUND_FILE)").option("-a, --agent <id>","Agent pack id").requiredOption("-m, --message <text>","Message to send").option("--media <path-or-url>","Attach media (image/audio/video/document); local path or URL. Sent via gateway RPC so the bot token resolves from the gateway runtime snapshot.").option("-t, --target <target>","Explicit target (e.g. channel:C01234567); defaults to last inbound route").option("--thread-id <id>","Slack thread ts when sending to a threaded route").option("--dry-run","Print gateway RPC payload without sending").option("--json","Output handle + result as JSON").action(async t=>{await(0,Qw.gatewaySendCommand)({outbound:t.outbound??"",agent:t.agent??"",message:t.message,media:t.media,target:t.target,threadId:t.threadId,dryRun:!!t.dryRun,json:!!t.json})});eA.command("list").description("List stored gateway outbound routes from a session file").requiredOption("--outbound <path>","Session gateway-outbound.json (see AGENTHIPPO_GATEWAY_OUTBOUND_FILE)").option("-a, --agent <id>","Filter to one agent pack id").option("--json","Output as JSON").action(async t=>{await(0,Qw.gatewayListCommand)({outbound:t.outbound,agent:t.agent,json:!!t.json})});Le.command("anywhere <action>").description("Manage Agent Anywhere gateway lifecycle").option("-s, --source <source>","Install source (e.g. openclaw@latest, org/repo#branch, /path/to/openclaw)").option("-p, --port <port>","Gateway port","18789").option("-b, --bind <address>","Gateway bind address","127.0.0.1").option("-t, --token <token>","Gateway auth token for starter config").option("--no-start","For setup: install/configure without starting").option("--config-template <path>","Path to openclaw.json template").action(async(t,e)=>{let n=parseInt(e.port,10);await(0,cU.anywhereCommand)({action:t,source:e.source,port:Number.isNaN(n)?void 0:n,bind:e.bind,token:e.token,noStart:e.start===!1,configTemplate:e.configTemplate})});Le.command("__probe-custom-engine").description("Test custom engine load strategies (import probe)").option("-e, --engine <id>","Custom engine id","cursor").option("-w, --workspace <path>","Workspace directory",process.cwd()).option("-s, --strategy <mode>","in-process|node-subprocess|all|a|c","all").action(async t=>{await(0,lU.probeCustomEngineCommand)({engine:t.engine,workspace:t.workspace,strategy:t.strategy})});Le.parseAsync();