makecoder 4.0.57 → 4.0.58

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 (45) hide show
  1. package/dist/cc.mjs +2 -2
  2. package/dist/coder.js +39 -39
  3. package/dist/darwin-arm64/cc.js +2 -2
  4. package/dist/darwin-x64/cc.js +2 -2
  5. package/dist/gemini/{chunk-P6AAZN7C.js → chunk-266SNVZB.js} +1 -1
  6. package/dist/gemini/{chunk-C7WYZFGG.js → chunk-2AH4XFVC.js} +2 -2
  7. package/dist/gemini/{chunk-YHLOYN7E.js → chunk-2BCRFXVD.js} +1 -1
  8. package/dist/gemini/{chunk-GMCQZQGQ.js → chunk-2I73JSEP.js} +3 -3
  9. package/dist/gemini/{chunk-VVPG7N67.js → chunk-3AZIBTSH.js} +1 -1
  10. package/dist/gemini/{chunk-UC3K4MCZ.js → chunk-7U34TXLX.js} +1 -1
  11. package/dist/gemini/{chunk-LA23QQDZ.js → chunk-C7ISM6PN.js} +1 -1
  12. package/dist/gemini/{chunk-QQRA4YFW.js → chunk-FJ6IIWF5.js} +1 -1
  13. package/dist/gemini/{chunk-QCMDS3PD.js → chunk-JKCNEXJF.js} +3 -3
  14. package/dist/gemini/{chunk-JNCEWGIV.js → chunk-JX43KPLT.js} +1 -1
  15. package/dist/gemini/{chunk-RKJKHDZC.js → chunk-P6YMHMJL.js} +1 -1
  16. package/dist/gemini/{chunk-HCTUJMZR.js → chunk-PZSSXHHP.js} +1 -1
  17. package/dist/gemini/{chunk-YG6QM4WI.js → chunk-QTFKUXKM.js} +1 -1
  18. package/dist/gemini/{chunk-MUVQ2FAZ.js → chunk-QYJUTNIU.js} +1 -1
  19. package/dist/gemini/{chunk-ZJ2D6ILW.js → chunk-STX7FBUU.js} +1 -1
  20. package/dist/gemini/{chunk-NJ4BSMX7.js → chunk-YJXXYFOM.js} +2 -2
  21. package/dist/gemini/{cleanup-S2LRI2Y4.js → cleanup-HVASUFMM.js} +1 -1
  22. package/dist/gemini/{cleanup-ZZNAJRKJ.js → cleanup-MJ7HQT46.js} +1 -1
  23. package/dist/gemini/{core-C22BYMS6.js → core-EOYLD74V.js} +1 -1
  24. package/dist/gemini/{devtoolsService-EGQAB3JU.js → devtoolsService-B7SSRNHW.js} +2 -2
  25. package/dist/gemini/{devtoolsService-YXEESS76.js → devtoolsService-FLOV3S5Z.js} +2 -2
  26. package/dist/gemini/{dist-X3AUJEIX.js → dist-NVGK4PVU.js} +1 -1
  27. package/dist/gemini/{gemini-X6HMGNFO.js → gemini-2Z2AJTYC.js} +5 -5
  28. package/dist/gemini/{gemini-ENBHDO7W.js → gemini-DRGPGRHF.js} +5 -5
  29. package/dist/gemini/gemini.js +2 -2
  30. package/dist/gemini/{interactiveCli-SZJWTGR5.js → interactiveCli-4K2UKYKF.js} +3 -3
  31. package/dist/gemini/{interactiveCli-CI6V7WL5.js → interactiveCli-TAIO5CBT.js} +9 -9
  32. package/dist/gemini/{liteRtServerManager-J7BSXFBK.js → liteRtServerManager-TUTNSHFW.js} +1 -1
  33. package/dist/gemini/{liteRtServerManager-BDF74U3A.js → liteRtServerManager-XJXZSOE7.js} +1 -1
  34. package/dist/gemini/{oauth2-provider-P65NTFUD.js → oauth2-provider-NEH5B4N6.js} +1 -1
  35. package/dist/gemini/{oauth2-provider-3MTIBHLN.js → oauth2-provider-QU5NILIP.js} +1 -1
  36. package/dist/gemini/{start-DYZJFE46.js → start-SOY6W5ZY.js} +1 -1
  37. package/dist/gemini/{start-KAI6HBJ2.js → start-TUGBMFO3.js} +1 -1
  38. package/dist/linux-x64/cc.js +2 -2
  39. package/dist/win32-x64/cc.js +2 -2
  40. package/package.json +5 -5
  41. package/packages/mcp-channel/wecom/package-lock.json +1313 -0
  42. package/scripts/postinstall.js +12 -12
  43. /package/{claude → packages}/mcp-channel/wecom/.mcp.json +0 -0
  44. /package/{claude → packages}/mcp-channel/wecom/package.json +0 -0
  45. /package/{claude → packages}/mcp-channel/wecom/server.js +0 -0
@@ -1088,7 +1088,7 @@ Please try running again with NO_BROWSER=true set.`}),new Ua(`Failed to open bro
1088
1088
  `);let s,c=await new Promise((u,d)=>{let l=B3r.createInterface({input:process.stdin,output:qq().stdout,terminal:!0}),a=new AbortController;s=setTimeout(()=>{a.abort(new Ua("Authorization timed out after 5 minutes."))},3e5),s.unref();let p=()=>{l.close(),d(a.signal.reason)};a.signal.addEventListener("abort",p,{once:!0}),l.question("Enter the authorization code: ",f=>{a.signal.removeEventListener("abort",p),l.close(),u(f.trim())})}).finally(()=>{s&&clearTimeout(s)});if(!c)return hS(`Authorization code is required.
1089
1089
  `),B.error("Authorization code is required."),!1;try{let{tokens:u}=await t.getToken({code:c,codeVerifier:r.codeVerifier,redirect_uri:e});t.setCredentials(u)}catch(u){return hS("Failed to authenticate with authorization code:"+Se(u)+`
1090
1090
  `),B.error("Failed to authenticate with authorization code:",Se(u)),!1}return!0}catch(e){if(e instanceof U1)throw e;return hS("Failed to authenticate with user code:"+Se(e)+`
1091
- `),B.error("Failed to authenticate with user code:",Se(e)),!1}}async function Q3r(t){let e=await G3r(),r=process.env.OAUTH_CALLBACK_HOST||"127.0.0.1",n=`http://127.0.0.1:${e}/oauth2callback`,o=kpt.randomBytes(32).toString("hex"),s=t.generateAuthUrl({redirect_uri:n,access_type:"offline",scope:iEe,state:o}),c=new Promise((u,d)=>{let l=Npt.createServer(async(a,p)=>{try{if(a.url.indexOf("/oauth2callback")===-1){p.writeHead(zq,{Location:nEe}),p.end(),d(new Ua("OAuth callback not received. Unexpected request: "+a.url));return}let f=new D3r.URL(a.url,"http://127.0.0.1:3000").searchParams;if(f.get("error")){p.writeHead(zq,{Location:nEe}),p.end();let g=f.get("error"),y=f.get("error_description")||"No additional details provided";d(new Ua(`Google OAuth error: ${g}. ${y}`))}else if(f.get("state")!==o)p.end("State mismatch. Possible CSRF attack"),d(new Ua("OAuth state mismatch. Possible CSRF attack or browser session issue."));else if(f.get("code"))try{let{tokens:g}=await t.getToken({code:f.get("code"),redirect_uri:n});t.setCredentials(g);try{await Wq(t)}catch(y){B.warn("Failed to retrieve Google Account ID during authentication:",Se(y))}p.writeHead(zq,{Location:U3r}),p.end(),u()}catch(g){p.writeHead(zq,{Location:nEe}),p.end(),d(new Ua(`Failed to exchange authorization code for tokens: ${Se(g)}`))}else d(new Ua("No authorization code received from Google OAuth. Please try authenticating again."))}catch(f){f instanceof Ua?d(f):d(new Ua(`Unexpected error during OAuth authentication: ${Se(f)}`))}finally{l.close()}});l.listen(e,r,()=>{}),l.on("error",a=>{d(new Ua(`OAuth callback server error: ${Se(a)}`))})});return{authUrl:s,loginCompletePromise:c}}function G3r(){return new Promise((t,e)=>{let r=0;try{let n=process.env.OAUTH_CALLBACK_PORT;if(n)return r=parseInt(n,10),isNaN(r)||r<=0||r>65535?e(new Error(`Invalid value for OAUTH_CALLBACK_PORT: "${n}"`)):t(r);let o=Dpt.createServer();o.listen(0,()=>{let s=o.address();s&&typeof s=="object"&&(r=s.port)}),o.on("listening",()=>{o.close(),o.unref()}),o.on("error",s=>e(s)),o.on("close",()=>t(r))}catch(n){e(n)}})}async function $3r(){if(oEe())return N2.loadCredentials();let e=[Yt.getOAuthCredsPath(),process.env.GOOGLE_APPLICATION_CREDENTIALS].filter(r=>!!r);for(let r of e)try{let n=await I3.readFile(r,"utf-8");return JSON.parse(n)}catch(n){B.debug(`Failed to load credentials from ${r}:`,Se(n))}return null}function q3r(){R3.clear()}async function hLi(){try{oEe()?await N2.clearCredentials():await I3.rm(Yt.getOAuthCredsPath(),{force:!0}),await Jq.clearCachedGoogleAccount(),q3r()}catch(t){B.warn("Failed to clear cached credentials:",t)}}async function Wq(t){try{let{token:e}=await t.getAccessToken();if(!e)return;let r=await fetch("https://www.googleapis.com/oauth2/v2/userinfo",{headers:{Authorization:`Bearer ${e}`}});if(!r.ok){B.log("Failed to fetch user info:",r.status,r.statusText);return}let n=await r.json();await Jq.cacheGoogleAccount(n.email)}catch(e){B.log("Error retrieving user info:",e)}}function gLi(){R3.clear()}async function V3r(t){let e=Yt.getOAuthCredsPath();await I3.mkdir(M3r.dirname(e),{recursive:!0});let r=JSON.stringify(t,null,2);await I3.writeFile(e,r,{mode:384});try{await I3.chmod(e,384)}catch{}}var Kq;(function(t){t.DASHER_USER="DASHER_USER",t.INELIGIBLE_ACCOUNT="INELIGIBLE_ACCOUNT",t.NON_USER_ACCOUNT="NON_USER_ACCOUNT",t.RESTRICTED_AGE="RESTRICTED_AGE",t.RESTRICTED_NETWORK="RESTRICTED_NETWORK",t.UNKNOWN="UNKNOWN",t.UNKNOWN_LOCATION="UNKNOWN_LOCATION",t.UNSUPPORTED_LOCATION="UNSUPPORTED_LOCATION",t.VALIDATION_REQUIRED="VALIDATION_REQUIRED"})(Kq||(Kq={}));var D0={FREE:"free-tier",LEGACY:"legacy-tier",STANDARD:"standard-tier"},Upt;(function(t){t.Default="DEFAULT",t.Notice="NOTICE",t.Warning="WARNING",t.Error="ERROR"})(Upt||(Upt={}));var Xq;(function(t){t[t.UNKNOWN=0]="UNKNOWN",t[t.THUMBSUP=1]="THUMBSUP",t[t.THUMBSDOWN=2]="THUMBSDOWN",t[t.COPY=3]="COPY",t[t.INSERT=4]="INSERT",t[t.ACCEPT_CODE_BLOCK=5]="ACCEPT_CODE_BLOCK",t[t.ACCEPT_ALL=6]="ACCEPT_ALL",t[t.ACCEPT_FILE=7]="ACCEPT_FILE",t[t.DIFF=8]="DIFF",t[t.ACCEPT_RANGE=9]="ACCEPT_RANGE"})(Xq||(Xq={}));var Hh;(function(t){t[t.ACTION_STATUS_UNSPECIFIED=0]="ACTION_STATUS_UNSPECIFIED",t[t.ACTION_STATUS_NO_ERROR=1]="ACTION_STATUS_NO_ERROR",t[t.ACTION_STATUS_ERROR_UNKNOWN=2]="ACTION_STATUS_ERROR_UNKNOWN",t[t.ACTION_STATUS_CANCELLED=3]="ACTION_STATUS_CANCELLED",t[t.ACTION_STATUS_EMPTY=4]="ACTION_STATUS_EMPTY"})(Hh||(Hh={}));var P3;(function(t){t[t.INITIATION_METHOD_UNSPECIFIED=0]="INITIATION_METHOD_UNSPECIFIED",t[t.TAB=1]="TAB",t[t.COMMAND=2]="COMMAND",t[t.AGENT=3]="AGENT"})(P3||(P3={}));var H3r=Y.object({extensionsEnabled:Y.boolean().optional()}),Fpt=Y.object({extensionsSetting:H3r.optional(),unmanagedCapabilitiesEnabled:Y.boolean().optional()}),z3r=Y.object({url:Y.string().optional(),type:Y.enum(["sse","http"]).optional(),trust:Y.boolean().optional(),includeTools:Y.array(Y.string()).optional(),excludeTools:Y.array(Y.string()).optional()}),W3r=Y.object({scopes:Y.array(Y.string()).optional(),clientId:Y.string().optional(),clientSecret:Y.string().optional()}),jpt=Y.object({url:Y.string(),type:Y.enum(["sse","http"]),authProviderType:Y.nativeEnum(tf).optional(),oauth:W3r.optional(),targetAudience:Y.string().optional(),targetServiceAccount:Y.string().optional(),headers:Y.record(Y.string()).optional(),trust:Y.boolean().optional(),timeout:Y.number().optional(),description:Y.string().optional(),includeTools:Y.array(Y.string()).optional(),excludeTools:Y.array(Y.string()).optional()}),sEe=Y.object({mcpServers:Y.record(z3r).optional(),requiredMcpServers:Y.record(jpt).optional()}),Y3r=Y.object({mcpEnabled:Y.boolean().optional(),mcpConfigJson:Y.string().optional()}),_Li=Y.object({strictModeDisabled:Y.boolean().optional(),mcpSetting:Y.object({mcpEnabled:Y.boolean().optional(),mcpConfig:sEe.optional(),requiredMcpConfig:Y.record(jpt).optional()}).optional(),cliFeatureSetting:Fpt.optional()}),Qpt=Y.object({secureModeEnabled:Y.boolean().optional(),strictModeDisabled:Y.boolean().optional(),mcpSetting:Y3r.optional(),cliFeatureSetting:Fpt.optional(),adminControlsApplicable:Y.boolean().optional()});import*as nYt from"node:readline";import{Readable as nqn}from"node:stream";var gS="GOOGLE_ONE_AI",J3r=new Set([Ch,Ex,ta]);function Gpt(t){return J3r.has(t)}var K3r="https://one.google.com/ai",X3r="https://accounts.google.com/AccountChooser",Z3r="gemini_cli",eMr="web";function tMr(t,e){let r=new URLSearchParams({Email:t,continue:e});return`${X3r}?${r.toString()}`}var vLi={MANAGE_ACTIVITY:"hydrogen_cli_settings_ai_credits_activity_page",MANAGE_ADD_CREDITS:"hydrogen_cli_settings_add_credits",EMPTY_WALLET_ADD_CREDITS:"hydrogen_cli_insufficient_credits_add_credits"};function SLi(t,e,r){let n=`${K3r}/${t}`,o=new URLSearchParams({utm_source:Z3r,utm_medium:eMr,utm_campaign:r}),s=`${n}?${o.toString()}`;return tMr(e,s)}function $pt(t){if(!t?.availableCredits)return null;let e=t.availableCredits.filter(r=>r.creditType===gS);return e.length===0?null:e.reduce((r,n)=>{let o=parseInt(n.creditAmount??"0",10);return r+(isNaN(o)?0:o)},0)}var aEe=50;function qpt(t,e){return t==="always"&&e!=null&&e>=aEe}function TLi(t,e){return t==="ask"&&e!=null&&e>=aEe}function wLi(t,e){return t!=="never"&&e!=null&&e<aEe}var Zt=Fe(Yh(),1);je();var vMt=Fe(Nwe(),1),SMt=Fe(Dwe(),1),TMt=Fe(jwe(),1),wMt=Fe(Gwe(),1),CMt=Fe(qwe(),1),xMt=Fe(n6(),1);nf();var OMt=Fe(vCt(),1);xl();var IMt=Fe(Y0(),1),Pre=Fe(kJ(),1),Nre=Fe(iJ(),1),Ub=Fe(Ef(),1),RMt=Fe(VCt(),1);var H2t=Fe(G2t(),1),z2t=Fe(tKe(),1);import{createHash as Fsn}from"node:crypto";import*as jI from"node:os";var oe;(function(t){t[t.GEMINI_CLI_KEY_UNKNOWN=0]="GEMINI_CLI_KEY_UNKNOWN",t[t.GEMINI_CLI_START_SESSION_MODEL=1]="GEMINI_CLI_START_SESSION_MODEL",t[t.GEMINI_CLI_START_SESSION_EMBEDDING_MODEL=2]="GEMINI_CLI_START_SESSION_EMBEDDING_MODEL",t[t.GEMINI_CLI_START_SESSION_SANDBOX=3]="GEMINI_CLI_START_SESSION_SANDBOX",t[t.GEMINI_CLI_START_SESSION_CORE_TOOLS=4]="GEMINI_CLI_START_SESSION_CORE_TOOLS",t[t.GEMINI_CLI_START_SESSION_APPROVAL_MODE=5]="GEMINI_CLI_START_SESSION_APPROVAL_MODE",t[t.GEMINI_CLI_START_SESSION_API_KEY_ENABLED=6]="GEMINI_CLI_START_SESSION_API_KEY_ENABLED",t[t.GEMINI_CLI_START_SESSION_VERTEX_API_ENABLED=7]="GEMINI_CLI_START_SESSION_VERTEX_API_ENABLED",t[t.GEMINI_CLI_START_SESSION_DEBUG_MODE_ENABLED=8]="GEMINI_CLI_START_SESSION_DEBUG_MODE_ENABLED",t[t.GEMINI_CLI_START_SESSION_MCP_SERVERS=9]="GEMINI_CLI_START_SESSION_MCP_SERVERS",t[t.GEMINI_CLI_START_SESSION_TELEMETRY_ENABLED=10]="GEMINI_CLI_START_SESSION_TELEMETRY_ENABLED",t[t.GEMINI_CLI_START_SESSION_TELEMETRY_LOG_USER_PROMPTS_ENABLED=11]="GEMINI_CLI_START_SESSION_TELEMETRY_LOG_USER_PROMPTS_ENABLED",t[t.GEMINI_CLI_START_SESSION_RESPECT_GITIGNORE=12]="GEMINI_CLI_START_SESSION_RESPECT_GITIGNORE",t[t.GEMINI_CLI_START_SESSION_OUTPUT_FORMAT=94]="GEMINI_CLI_START_SESSION_OUTPUT_FORMAT",t[t.GEMINI_CLI_STARTUP_PHASES=172]="GEMINI_CLI_STARTUP_PHASES",t[t.GEMINI_CLI_STARTUP_OS_PLATFORM=173]="GEMINI_CLI_STARTUP_OS_PLATFORM",t[t.GEMINI_CLI_STARTUP_OS_RELEASE=174]="GEMINI_CLI_STARTUP_OS_RELEASE",t[t.GEMINI_CLI_STARTUP_IS_DOCKER=175]="GEMINI_CLI_STARTUP_IS_DOCKER",t[t.GEMINI_CLI_USER_PROMPT_LENGTH=13]="GEMINI_CLI_USER_PROMPT_LENGTH",t[t.GEMINI_CLI_TOOL_CALL_NAME=14]="GEMINI_CLI_TOOL_CALL_NAME",t[t.GEMINI_CLI_TOOL_CALL_MCP_SERVER_NAME=95]="GEMINI_CLI_TOOL_CALL_MCP_SERVER_NAME",t[t.GEMINI_CLI_TOOL_CALL_DECISION=15]="GEMINI_CLI_TOOL_CALL_DECISION",t[t.GEMINI_CLI_TOOL_CALL_SUCCESS=16]="GEMINI_CLI_TOOL_CALL_SUCCESS",t[t.GEMINI_CLI_TOOL_CALL_DURATION_MS=17]="GEMINI_CLI_TOOL_CALL_DURATION_MS",t[t.DEPRECATED_GEMINI_CLI_TOOL_ERROR_MESSAGE=18]="DEPRECATED_GEMINI_CLI_TOOL_ERROR_MESSAGE",t[t.GEMINI_CLI_TOOL_CALL_ERROR_TYPE=19]="GEMINI_CLI_TOOL_CALL_ERROR_TYPE",t[t.GEMINI_CLI_TOOL_CALL_CONTENT_LENGTH=93]="GEMINI_CLI_TOOL_CALL_CONTENT_LENGTH",t[t.GEMINI_CLI_EDIT_STRATEGY=109]="GEMINI_CLI_EDIT_STRATEGY",t[t.GEMINI_CLI_EDIT_CORRECTION=110]="GEMINI_CLI_EDIT_CORRECTION",t[t.GEMINI_CLI_WEB_FETCH_FALLBACK_REASON=116]="GEMINI_CLI_WEB_FETCH_FALLBACK_REASON",t[t.GEMINI_CLI_API_REQUEST_MODEL=20]="GEMINI_CLI_API_REQUEST_MODEL",t[t.GEMINI_CLI_API_RESPONSE_MODEL=21]="GEMINI_CLI_API_RESPONSE_MODEL",t[t.GEMINI_CLI_API_RESPONSE_STATUS_CODE=22]="GEMINI_CLI_API_RESPONSE_STATUS_CODE",t[t.GEMINI_CLI_API_RESPONSE_DURATION_MS=23]="GEMINI_CLI_API_RESPONSE_DURATION_MS",t[t.GEMINI_CLI_API_RESPONSE_INPUT_TOKEN_COUNT=25]="GEMINI_CLI_API_RESPONSE_INPUT_TOKEN_COUNT",t[t.GEMINI_CLI_API_RESPONSE_OUTPUT_TOKEN_COUNT=26]="GEMINI_CLI_API_RESPONSE_OUTPUT_TOKEN_COUNT",t[t.GEMINI_CLI_API_RESPONSE_CACHED_TOKEN_COUNT=27]="GEMINI_CLI_API_RESPONSE_CACHED_TOKEN_COUNT",t[t.GEMINI_CLI_API_RESPONSE_THINKING_TOKEN_COUNT=28]="GEMINI_CLI_API_RESPONSE_THINKING_TOKEN_COUNT",t[t.GEMINI_CLI_API_RESPONSE_TOOL_TOKEN_COUNT=29]="GEMINI_CLI_API_RESPONSE_TOOL_TOKEN_COUNT",t[t.GEMINI_CLI_API_RESPONSE_CONTEXT_BREAKDOWN_SYSTEM_INSTRUCTIONS=167]="GEMINI_CLI_API_RESPONSE_CONTEXT_BREAKDOWN_SYSTEM_INSTRUCTIONS",t[t.GEMINI_CLI_API_RESPONSE_CONTEXT_BREAKDOWN_TOOL_DEFINITIONS=168]="GEMINI_CLI_API_RESPONSE_CONTEXT_BREAKDOWN_TOOL_DEFINITIONS",t[t.GEMINI_CLI_API_RESPONSE_CONTEXT_BREAKDOWN_HISTORY=169]="GEMINI_CLI_API_RESPONSE_CONTEXT_BREAKDOWN_HISTORY",t[t.GEMINI_CLI_API_RESPONSE_CONTEXT_BREAKDOWN_TOOL_CALLS=170]="GEMINI_CLI_API_RESPONSE_CONTEXT_BREAKDOWN_TOOL_CALLS",t[t.GEMINI_CLI_API_RESPONSE_CONTEXT_BREAKDOWN_MCP_SERVERS=171]="GEMINI_CLI_API_RESPONSE_CONTEXT_BREAKDOWN_MCP_SERVERS",t[t.GEMINI_CLI_API_ERROR_MODEL=30]="GEMINI_CLI_API_ERROR_MODEL",t[t.GEMINI_CLI_API_ERROR_TYPE=31]="GEMINI_CLI_API_ERROR_TYPE",t[t.GEMINI_CLI_API_ERROR_STATUS_CODE=32]="GEMINI_CLI_API_ERROR_STATUS_CODE",t[t.GEMINI_CLI_API_ERROR_DURATION_MS=33]="GEMINI_CLI_API_ERROR_DURATION_MS",t[t.GEMINI_CLI_END_SESSION_ID=34]="GEMINI_CLI_END_SESSION_ID",t[t.GEMINI_CLI_PROMPT_ID=35]="GEMINI_CLI_PROMPT_ID",t[t.GEMINI_CLI_AUTH_TYPE=36]="GEMINI_CLI_AUTH_TYPE",t[t.GEMINI_CLI_GOOGLE_ACCOUNTS_COUNT=37]="GEMINI_CLI_GOOGLE_ACCOUNTS_COUNT",t[t.GEMINI_CLI_SURFACE=39]="GEMINI_CLI_SURFACE",t[t.GEMINI_CLI_SESSION_ID=40]="GEMINI_CLI_SESSION_ID",t[t.GEMINI_CLI_VERSION=54]="GEMINI_CLI_VERSION",t[t.GEMINI_CLI_GIT_COMMIT_HASH=55]="GEMINI_CLI_GIT_COMMIT_HASH",t[t.GEMINI_CLI_OS=82]="GEMINI_CLI_OS",t[t.GEMINI_CLI_USER_SETTINGS=84]="GEMINI_CLI_USER_SETTINGS",t[t.GEMINI_CLI_GH_WORKFLOW_NAME=130]="GEMINI_CLI_GH_WORKFLOW_NAME",t[t.GEMINI_CLI_EXPERIMENT_IDS=131]="GEMINI_CLI_EXPERIMENT_IDS",t[t.GEMINI_CLI_GH_REPOSITORY_NAME_HASH=132]="GEMINI_CLI_GH_REPOSITORY_NAME_HASH",t[t.GEMINI_CLI_GH_EVENT_NAME=176]="GEMINI_CLI_GH_EVENT_NAME",t[t.GEMINI_CLI_GH_PR_NUMBER=177]="GEMINI_CLI_GH_PR_NUMBER",t[t.GEMINI_CLI_GH_ISSUE_NUMBER=178]="GEMINI_CLI_GH_ISSUE_NUMBER",t[t.GEMINI_CLI_GH_CUSTOM_TRACKING_ID=179]="GEMINI_CLI_GH_CUSTOM_TRACKING_ID",t[t.GEMINI_CLI_LOOP_DETECTED_TYPE=38]="GEMINI_CLI_LOOP_DETECTED_TYPE",t[t.GEMINI_CLI_SLASH_COMMAND_NAME=41]="GEMINI_CLI_SLASH_COMMAND_NAME",t[t.GEMINI_CLI_SLASH_COMMAND_SUBCOMMAND=42]="GEMINI_CLI_SLASH_COMMAND_SUBCOMMAND",t[t.GEMINI_CLI_SLASH_COMMAND_STATUS=51]="GEMINI_CLI_SLASH_COMMAND_STATUS",t[t.GEMINI_CLI_RESPONSE_FINISH_REASON=43]="GEMINI_CLI_RESPONSE_FINISH_REASON",t[t.GEMINI_CLI_NEXT_SPEAKER_CHECK_RESULT=44]="GEMINI_CLI_NEXT_SPEAKER_CHECK_RESULT",t[t.GEMINI_CLI_MALFORMED_JSON_RESPONSE_MODEL=45]="GEMINI_CLI_MALFORMED_JSON_RESPONSE_MODEL",t[t.GEMINI_CLI_IDE_CONNECTION_TYPE=46]="GEMINI_CLI_IDE_CONNECTION_TYPE",t[t.GEMINI_CLI_AI_ADDED_LINES=47]="GEMINI_CLI_AI_ADDED_LINES",t[t.GEMINI_CLI_AI_REMOVED_LINES=48]="GEMINI_CLI_AI_REMOVED_LINES",t[t.GEMINI_CLI_USER_ADDED_LINES=49]="GEMINI_CLI_USER_ADDED_LINES",t[t.GEMINI_CLI_USER_REMOVED_LINES=50]="GEMINI_CLI_USER_REMOVED_LINES",t[t.GEMINI_CLI_AI_ADDED_CHARS=103]="GEMINI_CLI_AI_ADDED_CHARS",t[t.GEMINI_CLI_AI_REMOVED_CHARS=104]="GEMINI_CLI_AI_REMOVED_CHARS",t[t.GEMINI_CLI_USER_ADDED_CHARS=105]="GEMINI_CLI_USER_ADDED_CHARS",t[t.GEMINI_CLI_USER_REMOVED_CHARS=106]="GEMINI_CLI_USER_REMOVED_CHARS",t[t.DEPRECATED_GEMINI_CLI_KITTY_TRUNCATED_SEQUENCE=52]="DEPRECATED_GEMINI_CLI_KITTY_TRUNCATED_SEQUENCE",t[t.GEMINI_CLI_KITTY_SEQUENCE_LENGTH=53]="GEMINI_CLI_KITTY_SEQUENCE_LENGTH",t[t.GEMINI_CLI_APPROVAL_MODE=58]="GEMINI_CLI_APPROVAL_MODE",t[t.GEMINI_CLI_CONVERSATION_TURN_COUNT=59]="GEMINI_CLI_CONVERSATION_TURN_COUNT",t[t.GEMINI_CLI_COMPRESSION_TOKENS_BEFORE=60]="GEMINI_CLI_COMPRESSION_TOKENS_BEFORE",t[t.GEMINI_CLI_COMPRESSION_TOKENS_AFTER=61]="GEMINI_CLI_COMPRESSION_TOKENS_AFTER",t[t.GEMINI_CLI_TOOL_TYPE=62]="GEMINI_CLI_TOOL_TYPE",t[t.GEMINI_CLI_START_SESSION_MCP_SERVERS_COUNT=63]="GEMINI_CLI_START_SESSION_MCP_SERVERS_COUNT",t[t.GEMINI_CLI_START_SESSION_MCP_TOOLS_COUNT=64]="GEMINI_CLI_START_SESSION_MCP_TOOLS_COUNT",t[t.GEMINI_CLI_START_SESSION_MCP_TOOLS=65]="GEMINI_CLI_START_SESSION_MCP_TOOLS",t[t.GEMINI_CLI_RESEARCH_OPT_IN_STATUS=66]="GEMINI_CLI_RESEARCH_OPT_IN_STATUS",t[t.GEMINI_CLI_RESEARCH_CONTACT_EMAIL=67]="GEMINI_CLI_RESEARCH_CONTACT_EMAIL",t[t.GEMINI_CLI_RESEARCH_USER_ID=68]="GEMINI_CLI_RESEARCH_USER_ID",t[t.GEMINI_CLI_RESEARCH_FEEDBACK_TYPE=69]="GEMINI_CLI_RESEARCH_FEEDBACK_TYPE",t[t.GEMINI_CLI_RESEARCH_FEEDBACK_CONTENT=70]="GEMINI_CLI_RESEARCH_FEEDBACK_CONTENT",t[t.GEMINI_CLI_RESEARCH_SURVEY_RESPONSES=71]="GEMINI_CLI_RESEARCH_SURVEY_RESPONSES",t[t.GEMINI_CLI_PROGRAMMING_LANGUAGE=56]="GEMINI_CLI_PROGRAMMING_LANGUAGE",t[t.GEMINI_CLI_FILE_OPERATION_TYPE=57]="GEMINI_CLI_FILE_OPERATION_TYPE",t[t.GEMINI_CLI_FILE_OPERATION_LINES=72]="GEMINI_CLI_FILE_OPERATION_LINES",t[t.GEMINI_CLI_FILE_OPERATION_MIMETYPE=73]="GEMINI_CLI_FILE_OPERATION_MIMETYPE",t[t.GEMINI_CLI_FILE_OPERATION_EXTENSION=74]="GEMINI_CLI_FILE_OPERATION_EXTENSION",t[t.GEMINI_CLI_INVALID_CHUNK_ERROR_MESSAGE=75]="GEMINI_CLI_INVALID_CHUNK_ERROR_MESSAGE",t[t.GEMINI_CLI_CONTENT_RETRY_ATTEMPT_NUMBER=76]="GEMINI_CLI_CONTENT_RETRY_ATTEMPT_NUMBER",t[t.GEMINI_CLI_CONTENT_RETRY_ERROR_TYPE=77]="GEMINI_CLI_CONTENT_RETRY_ERROR_TYPE",t[t.GEMINI_CLI_CONTENT_RETRY_DELAY_MS=78]="GEMINI_CLI_CONTENT_RETRY_DELAY_MS",t[t.GEMINI_CLI_CONTENT_RETRY_FAILURE_TOTAL_ATTEMPTS=79]="GEMINI_CLI_CONTENT_RETRY_FAILURE_TOTAL_ATTEMPTS",t[t.GEMINI_CLI_CONTENT_RETRY_FAILURE_FINAL_ERROR_TYPE=80]="GEMINI_CLI_CONTENT_RETRY_FAILURE_FINAL_ERROR_TYPE",t[t.GEMINI_CLI_CONTENT_RETRY_FAILURE_TOTAL_DURATION_MS=81]="GEMINI_CLI_CONTENT_RETRY_FAILURE_TOTAL_DURATION_MS",t[t.GEMINI_CLI_NODE_VERSION=83]="GEMINI_CLI_NODE_VERSION",t[t.GEMINI_CLI_EXTENSION_NAME=85]="GEMINI_CLI_EXTENSION_NAME",t[t.GEMINI_CLI_EXTENSION_ID=121]="GEMINI_CLI_EXTENSION_ID",t[t.GEMINI_CLI_EXTENSION_VERSION=86]="GEMINI_CLI_EXTENSION_VERSION",t[t.GEMINI_CLI_EXTENSION_PREVIOUS_VERSION=117]="GEMINI_CLI_EXTENSION_PREVIOUS_VERSION",t[t.GEMINI_CLI_EXTENSION_SOURCE=87]="GEMINI_CLI_EXTENSION_SOURCE",t[t.GEMINI_CLI_EXTENSION_INSTALL_STATUS=88]="GEMINI_CLI_EXTENSION_INSTALL_STATUS",t[t.GEMINI_CLI_EXTENSION_UNINSTALL_STATUS=96]="GEMINI_CLI_EXTENSION_UNINSTALL_STATUS",t[t.GEMINI_CLI_EXTENSION_UPDATE_STATUS=118]="GEMINI_CLI_EXTENSION_UPDATE_STATUS",t[t.GEMINI_CLI_START_SESSION_EXTENSIONS_COUNT=119]="GEMINI_CLI_START_SESSION_EXTENSIONS_COUNT",t[t.GEMINI_CLI_START_SESSION_EXTENSION_IDS=120]="GEMINI_CLI_START_SESSION_EXTENSION_IDS",t[t.GEMINI_CLI_START_SESSION_WORKTREE_ACTIVE=191]="GEMINI_CLI_START_SESSION_WORKTREE_ACTIVE",t[t.GEMINI_CLI_EXTENSION_ENABLE_SETTING_SCOPE=102]="GEMINI_CLI_EXTENSION_ENABLE_SETTING_SCOPE",t[t.GEMINI_CLI_EXTENSION_DISABLE_SETTING_SCOPE=107]="GEMINI_CLI_EXTENSION_DISABLE_SETTING_SCOPE",t[t.GEMINI_CLI_TOOL_OUTPUT_TRUNCATED_ORIGINAL_LENGTH=89]="GEMINI_CLI_TOOL_OUTPUT_TRUNCATED_ORIGINAL_LENGTH",t[t.GEMINI_CLI_TOOL_OUTPUT_TRUNCATED_TRUNCATED_LENGTH=90]="GEMINI_CLI_TOOL_OUTPUT_TRUNCATED_TRUNCATED_LENGTH",t[t.GEMINI_CLI_TOOL_OUTPUT_TRUNCATED_THRESHOLD=91]="GEMINI_CLI_TOOL_OUTPUT_TRUNCATED_THRESHOLD",t[t.GEMINI_CLI_TOOL_OUTPUT_TRUNCATED_LINES=92]="GEMINI_CLI_TOOL_OUTPUT_TRUNCATED_LINES",t[t.GEMINI_CLI_ROUTING_DECISION=97]="GEMINI_CLI_ROUTING_DECISION",t[t.GEMINI_CLI_ROUTING_FAILURE=98]="GEMINI_CLI_ROUTING_FAILURE",t[t.GEMINI_CLI_ROUTING_LATENCY_MS=99]="GEMINI_CLI_ROUTING_LATENCY_MS",t[t.GEMINI_CLI_ROUTING_FAILURE_REASON=100]="GEMINI_CLI_ROUTING_FAILURE_REASON",t[t.GEMINI_CLI_ROUTING_DECISION_SOURCE=101]="GEMINI_CLI_ROUTING_DECISION_SOURCE",t[t.GEMINI_CLI_MODEL_SLASH_COMMAND=108]="GEMINI_CLI_MODEL_SLASH_COMMAND",t[t.GEMINI_CLI_AGENT_NAME=111]="GEMINI_CLI_AGENT_NAME",t[t.GEMINI_CLI_AGENT_ID=112]="GEMINI_CLI_AGENT_ID",t[t.GEMINI_CLI_AGENT_DURATION_MS=113]="GEMINI_CLI_AGENT_DURATION_MS",t[t.GEMINI_CLI_AGENT_TURN_COUNT=114]="GEMINI_CLI_AGENT_TURN_COUNT",t[t.GEMINI_CLI_AGENT_TERMINATE_REASON=115]="GEMINI_CLI_AGENT_TERMINATE_REASON",t[t.GEMINI_CLI_AGENT_RECOVERY_REASON=122]="GEMINI_CLI_AGENT_RECOVERY_REASON",t[t.GEMINI_CLI_AGENT_RECOVERY_DURATION_MS=123]="GEMINI_CLI_AGENT_RECOVERY_DURATION_MS",t[t.GEMINI_CLI_AGENT_RECOVERY_SUCCESS=124]="GEMINI_CLI_AGENT_RECOVERY_SUCCESS",t[t.GEMINI_CLI_INTERACTIVE=125]="GEMINI_CLI_INTERACTIVE",t[t.GEMINI_CLI_LLM_LOOP_CHECK_FLASH_CONFIDENCE=126]="GEMINI_CLI_LLM_LOOP_CHECK_FLASH_CONFIDENCE",t[t.GEMINI_CLI_LLM_LOOP_CHECK_MAIN_MODEL=127]="GEMINI_CLI_LLM_LOOP_CHECK_MAIN_MODEL",t[t.GEMINI_CLI_LLM_LOOP_CHECK_MAIN_MODEL_CONFIDENCE=128]="GEMINI_CLI_LLM_LOOP_CHECK_MAIN_MODEL_CONFIDENCE",t[t.GEMINI_CLI_LOOP_DETECTED_CONFIRMED_BY_MODEL=129]="GEMINI_CLI_LOOP_DETECTED_CONFIRMED_BY_MODEL",t[t.GEMINI_CLI_HOOK_EVENT_NAME=133]="GEMINI_CLI_HOOK_EVENT_NAME",t[t.GEMINI_CLI_HOOK_DURATION_MS=134]="GEMINI_CLI_HOOK_DURATION_MS",t[t.GEMINI_CLI_HOOK_SUCCESS=135]="GEMINI_CLI_HOOK_SUCCESS",t[t.GEMINI_CLI_HOOK_EXIT_CODE=136]="GEMINI_CLI_HOOK_EXIT_CODE",t[t.GEMINI_CLI_CPU_INFO=137]="GEMINI_CLI_CPU_INFO",t[t.GEMINI_CLI_CPU_CORES=138]="GEMINI_CLI_CPU_CORES",t[t.GEMINI_CLI_GPU_INFO=139]="GEMINI_CLI_GPU_INFO",t[t.GEMINI_CLI_RAM_TOTAL_GB=140]="GEMINI_CLI_RAM_TOTAL_GB",t[t.GEMINI_CLI_ACTIVE_APPROVAL_MODE=141]="GEMINI_CLI_ACTIVE_APPROVAL_MODE",t[t.GEMINI_CLI_APPROVAL_MODE_TO=142]="GEMINI_CLI_APPROVAL_MODE_TO",t[t.GEMINI_CLI_APPROVAL_MODE_DURATION_MS=143]="GEMINI_CLI_APPROVAL_MODE_DURATION_MS",t[t.GEMINI_CLI_REWIND_OUTCOME=144]="GEMINI_CLI_REWIND_OUTCOME",t[t.GEMINI_CLI_ROUTING_REASONING=145]="GEMINI_CLI_ROUTING_REASONING",t[t.GEMINI_CLI_ROUTING_NUMERICAL_ENABLED=146]="GEMINI_CLI_ROUTING_NUMERICAL_ENABLED",t[t.GEMINI_CLI_ROUTING_CLASSIFIER_THRESHOLD=147]="GEMINI_CLI_ROUTING_CLASSIFIER_THRESHOLD",t[t.GEMINI_CLI_TOOL_OUTPUT_MASKING_TOKENS_BEFORE=148]="GEMINI_CLI_TOOL_OUTPUT_MASKING_TOKENS_BEFORE",t[t.GEMINI_CLI_TOOL_OUTPUT_MASKING_TOKENS_AFTER=149]="GEMINI_CLI_TOOL_OUTPUT_MASKING_TOKENS_AFTER",t[t.GEMINI_CLI_TOOL_OUTPUT_MASKING_MASKED_COUNT=150]="GEMINI_CLI_TOOL_OUTPUT_MASKING_MASKED_COUNT",t[t.GEMINI_CLI_TOOL_OUTPUT_MASKING_TOTAL_PRUNABLE_TOKENS=151]="GEMINI_CLI_TOOL_OUTPUT_MASKING_TOTAL_PRUNABLE_TOKENS",t[t.GEMINI_CLI_ASK_USER_QUESTION_TYPES=152]="GEMINI_CLI_ASK_USER_QUESTION_TYPES",t[t.GEMINI_CLI_ASK_USER_DISMISSED=153]="GEMINI_CLI_ASK_USER_DISMISSED",t[t.GEMINI_CLI_ASK_USER_EMPTY_SUBMISSION=154]="GEMINI_CLI_ASK_USER_EMPTY_SUBMISSION",t[t.GEMINI_CLI_ASK_USER_ANSWER_COUNT=155]="GEMINI_CLI_ASK_USER_ANSWER_COUNT",t[t.GEMINI_CLI_KEYCHAIN_AVAILABLE=156]="GEMINI_CLI_KEYCHAIN_AVAILABLE",t[t.GEMINI_CLI_TOKEN_STORAGE_TYPE=157]="GEMINI_CLI_TOKEN_STORAGE_TYPE",t[t.GEMINI_CLI_TOKEN_STORAGE_FORCED=158]="GEMINI_CLI_TOKEN_STORAGE_FORCED",t[t.CONSECA_POLICY_GENERATION=159]="CONSECA_POLICY_GENERATION",t[t.CONSECA_VERDICT=160]="CONSECA_VERDICT",t[t.CONSECA_GENERATED_POLICY=161]="CONSECA_GENERATED_POLICY",t[t.CONSECA_VERDICT_RESULT=162]="CONSECA_VERDICT_RESULT",t[t.CONSECA_VERDICT_RATIONALE=163]="CONSECA_VERDICT_RATIONALE",t[t.CONSECA_TRUSTED_CONTENT=164]="CONSECA_TRUSTED_CONTENT",t[t.CONSECA_USER_PROMPT=165]="CONSECA_USER_PROMPT",t[t.CONSECA_ERROR=166]="CONSECA_ERROR",t[t.GEMINI_CLI_NETWORK_RETRY_ATTEMPT_NUMBER=180]="GEMINI_CLI_NETWORK_RETRY_ATTEMPT_NUMBER",t[t.GEMINI_CLI_NETWORK_RETRY_DELAY_MS=181]="GEMINI_CLI_NETWORK_RETRY_DELAY_MS",t[t.GEMINI_CLI_NETWORK_RETRY_ERROR_TYPE=182]="GEMINI_CLI_NETWORK_RETRY_ERROR_TYPE",t[t.GEMINI_CLI_BILLING_MODEL=185]="GEMINI_CLI_BILLING_MODEL",t[t.GEMINI_CLI_BILLING_CREDITS_CONSUMED=186]="GEMINI_CLI_BILLING_CREDITS_CONSUMED",t[t.GEMINI_CLI_BILLING_CREDITS_REMAINING=187]="GEMINI_CLI_BILLING_CREDITS_REMAINING",t[t.GEMINI_CLI_BILLING_SELECTED_OPTION=188]="GEMINI_CLI_BILLING_SELECTED_OPTION",t[t.GEMINI_CLI_BILLING_CREDIT_BALANCE=189]="GEMINI_CLI_BILLING_CREDIT_BALANCE",t[t.GEMINI_CLI_BILLING_PURCHASE_SOURCE=190]="GEMINI_CLI_BILLING_PURCHASE_SOURCE",t[t.GEMINI_CLI_ONBOARDING_START=192]="GEMINI_CLI_ONBOARDING_START",t[t.GEMINI_CLI_ONBOARDING_USER_TIER=193]="GEMINI_CLI_ONBOARDING_USER_TIER",t[t.GEMINI_CLI_ONBOARDING_DURATION_MS=194]="GEMINI_CLI_ONBOARDING_DURATION_MS",t[t.GEMINI_CLI_BROWSER_AGENT_SESSION_MODE=195]="GEMINI_CLI_BROWSER_AGENT_SESSION_MODE",t[t.GEMINI_CLI_BROWSER_AGENT_HEADLESS=196]="GEMINI_CLI_BROWSER_AGENT_HEADLESS",t[t.GEMINI_CLI_BROWSER_AGENT_SUCCESS=197]="GEMINI_CLI_BROWSER_AGENT_SUCCESS",t[t.GEMINI_CLI_BROWSER_AGENT_ERROR_TYPE=198]="GEMINI_CLI_BROWSER_AGENT_ERROR_TYPE",t[t.GEMINI_CLI_BROWSER_AGENT_DURATION_MS=199]="GEMINI_CLI_BROWSER_AGENT_DURATION_MS",t[t.GEMINI_CLI_BROWSER_AGENT_VISION_ENABLED=200]="GEMINI_CLI_BROWSER_AGENT_VISION_ENABLED",t[t.GEMINI_CLI_BROWSER_AGENT_VISION_DISABLED_REASON=201]="GEMINI_CLI_BROWSER_AGENT_VISION_DISABLED_REASON",t[t.GEMINI_CLI_BROWSER_AGENT_TOOL_COUNT=202]="GEMINI_CLI_BROWSER_AGENT_TOOL_COUNT"})(oe||(oe={}));var $2t="2380563",q2t="0.43.0";var Hr={devin:{name:"devin",displayName:"Devin"},replit:{name:"replit",displayName:"Replit"},cursor:{name:"cursor",displayName:"Cursor"},cloudshell:{name:"cloudshell",displayName:"Cloud Shell"},codespaces:{name:"codespaces",displayName:"GitHub Codespaces"},firebasestudio:{name:"firebasestudio",displayName:"Firebase Studio"},trae:{name:"trae",displayName:"Trae"},vscode:{name:"vscode",displayName:"VS Code"},vscodefork:{name:"vscodefork",displayName:"IDE"},positron:{name:"positron",displayName:"Positron"},antigravity:{name:"antigravity",displayName:"Antigravity"},sublimetext:{name:"sublimetext",displayName:"Sublime Text"},jetbrains:{name:"jetbrains",displayName:"JetBrains IDE"},intellijidea:{name:"intellijidea",displayName:"IntelliJ IDEA"},webstorm:{name:"webstorm",displayName:"WebStorm"},pycharm:{name:"pycharm",displayName:"PyCharm"},goland:{name:"goland",displayName:"GoLand"},androidstudio:{name:"androidstudio",displayName:"Android Studio"},clion:{name:"clion",displayName:"CLion"},rustrover:{name:"rustrover",displayName:"RustRover"},datagrip:{name:"datagrip",displayName:"DataGrip"},phpstorm:{name:"phpstorm",displayName:"PhpStorm"},zed:{name:"zed",displayName:"Zed"},xcode:{name:"xcode",displayName:"XCode"}};function UI(){return!!(process.env.EDITOR_IN_CLOUD_SHELL||process.env.CLOUD_SHELL)}function SIe(){return!!process.env.TERMINAL_EMULATOR?.toLowerCase().includes("jetbrains")}function FI(){return process.env.ANTIGRAVITY_CLI_ALIAS?Hr.antigravity:process.env.__COG_BASHRC_SOURCED?Hr.devin:process.env.REPLIT_USER?Hr.replit:process.env.CURSOR_TRACE_ID?Hr.cursor:process.env.CODESPACES?Hr.codespaces:UI()?Hr.cloudshell:process.env.TERM_PRODUCT==="Trae"?Hr.trae:process.env.MONOSPACE_ENV?Hr.firebasestudio:process.env.POSITRON==="1"?Hr.positron:process.env.TERM_PROGRAM==="sublime"?Hr.sublimetext:process.env.ZED_SESSION_ID||process.env.TERM_PROGRAM==="Zed"?Hr.zed:process.env.XCODE_VERSION_ACTUAL?Hr.xcode:SIe()?Hr.jetbrains:Hr.vscode}function Bsn(t,e){return t.name!==Hr.vscode.name?t:!e.command||e.command.toLowerCase().includes("code")?Hr.vscode:Hr.vscodefork}function Usn(t,e){if(t.name!==Hr.jetbrains.name||!e.command)return t;let r=e.command.toLowerCase(),n=[["idea",Hr.intellijidea],["webstorm",Hr.webstorm],["pycharm",Hr.pycharm],["goland",Hr.goland],["studio",Hr.androidstudio],["clion",Hr.clion],["rustrover",Hr.rustrover],["datagrip",Hr.datagrip],["phpstorm",Hr.phpstorm]];for(let[o,s]of n)if(r.includes(o))return s;return t}function V2t(t,e){if(e?.name&&e.displayName)return{name:e.name,displayName:e.displayName};if(process.env.TERM_PROGRAM!=="vscode"&&process.env.TERM_PROGRAM!=="sublime"&&process.env.TERM_PROGRAM!=="Zed"&&!process.env.ZED_SESSION_ID&&!process.env.XCODE_VERSION_ACTUAL&&!SIe())return;let r=FI();return SIe()?Usn(r,t):Bsn(r,t)}var gt;(function(t){t.START_SESSION="start_session",t.NEW_PROMPT="new_prompt",t.TOOL_CALL="tool_call",t.FILE_OPERATION="file_operation",t.API_REQUEST="api_request",t.API_RESPONSE="api_response",t.API_ERROR="api_error",t.END_SESSION="end_session",t.FLASH_FALLBACK="flash_fallback",t.RIPGREP_FALLBACK="ripgrep_fallback",t.LOOP_DETECTED="loop_detected",t.LOOP_DETECTION_DISABLED="loop_detection_disabled",t.NEXT_SPEAKER_CHECK="next_speaker_check",t.SLASH_COMMAND="slash_command",t.REWIND="rewind",t.MALFORMED_JSON_RESPONSE="malformed_json_response",t.IDE_CONNECTION="ide_connection",t.KITTY_SEQUENCE_OVERFLOW="kitty_sequence_overflow",t.CHAT_COMPRESSION="chat_compression",t.CONVERSATION_FINISHED="conversation_finished",t.INVALID_CHUNK="invalid_chunk",t.CONTENT_RETRY="content_retry",t.CONTENT_RETRY_FAILURE="content_retry_failure",t.RETRY_ATTEMPT="retry_attempt",t.EXTENSION_ENABLE="extension_enable",t.EXTENSION_DISABLE="extension_disable",t.EXTENSION_INSTALL="extension_install",t.EXTENSION_UNINSTALL="extension_uninstall",t.EXTENSION_UPDATE="extension_update",t.TOOL_OUTPUT_TRUNCATED="tool_output_truncated",t.MODEL_ROUTING="model_routing",t.MODEL_SLASH_COMMAND="model_slash_command",t.EDIT_STRATEGY="edit_strategy",t.EDIT_CORRECTION="edit_correction",t.AGENT_START="agent_start",t.AGENT_FINISH="agent_finish",t.RECOVERY_ATTEMPT="recovery_attempt",t.WEB_FETCH_FALLBACK_ATTEMPT="web_fetch_fallback_attempt",t.LLM_LOOP_CHECK="llm_loop_check",t.HOOK_CALL="hook_call",t.APPROVAL_MODE_SWITCH="approval_mode_switch",t.APPROVAL_MODE_DURATION="approval_mode_duration",t.PLAN_EXECUTION="plan_execution",t.TOOL_OUTPUT_MASKING="tool_output_masking",t.KEYCHAIN_AVAILABILITY="keychain_availability",t.TOKEN_STORAGE_INITIALIZATION="token_storage_initialization",t.ONBOARDING_START="onboarding_start",t.ONBOARDING_SUCCESS="onboarding_success",t.CONSECA_POLICY_GENERATION="conseca_policy_generation",t.CONSECA_VERDICT="conseca_verdict",t.STARTUP_STATS="startup_stats",t.CREDITS_USED="credits_used",t.OVERAGE_OPTION_SELECTED="overage_option_selected",t.EMPTY_WALLET_MENU_SHOWN="empty_wallet_menu_shown",t.CREDIT_PURCHASE_CLICK="credit_purchase_click",t.BROWSER_AGENT_CONNECTION="browser_agent_connection",t.BROWSER_AGENT_VISION_STATUS="browser_agent_vision_status",t.BROWSER_AGENT_TASK_OUTCOME="browser_agent_task_outcome",t.BROWSER_AGENT_CLEANUP="browser_agent_cleanup"})(gt||(gt={}));function jsn(){return process.env.SURFACE?process.env.SURFACE:UI()?Hr.cloudshell.name:process.env.GITHUB_SHA?"GitHub":process.env.TERM_PROGRAM==="vscode"?FI().name||Hr.vscode.name:"SURFACE_NOT_SET"}function Qsn(){return process.env.GH_WORKFLOW_NAME}function Gsn(){return process.env.GITHUB_REPOSITORY}function $sn(){return process.env.GITHUB_EVENT_NAME}function qsn(){return process.env.GH_PR_NUMBER}function Vsn(){return process.env.GH_ISSUE_NUMBER}function Hsn(){return process.env.GH_CUSTOM_TRACKING_ID}var zsn="https://play.googleapis.com/log?format=json&hasfast=true",Wsn=1e3*60,yZ=1e3,AZ=100,W2t="NA",I4;async function Ysn(){try{let t=await H2t.default.graphics();t.controllers&&t.controllers.length>0?I4=t.controllers.map(e=>e.model).join(", "):I4=W2t}catch(t){I4="FAILED",B.error("Failed to get GPU information for telemetry",Se(t))}}async function Jsn(){return I4||await Ysn(),I4??W2t}var St=class t{static instance;config;sessionData=[];promptId="";installationManager;userAccountManager;hashedGHRepositoryName;events;lastFlushTime=Date.now();flushing=!1;pendingFlush=!1;constructor(e){this.config=e,this.events=new Wme.default(Array,yZ),this.promptId=e?.getSessionId()??"",this.installationManager=new A_,this.userAccountManager=new y_;let r=Gsn();r&&(this.hashedGHRepositoryName=Fsn("sha256").update(r).digest("hex"))}static getInstance(e){if(!(e===void 0||!e?.getUsageStatisticsEnabled()))return t.instance||(t.instance=new t(e)),t.instance}static clearInstance(){t.instance=void 0}enqueueHelper(e,r){let n=this.events.size>=yZ;n&&this.events.shift();let o={event_time_ms:Date.now(),source_extension_json:Lr(e)};r!==void 0&&(o.exp={gws_experiment:r}),this.events.push([o]),n&&this.config?.getDebugMode()&&B.debug(`ClearcutLogger: Dropped old event to prevent memory leak (queue size: ${this.events.size})`)}enqueueLogEvent(e){try{this.enqueueHelper(e)}catch(r){this.config?.getDebugMode()&&B.warn("ClearcutLogger: Failed to enqueue log event.",r)}}async enqueueLogEventAfterExperimentsLoadAsync(e){try{this.config?.getExperimentsAsync().then(r=>{if(r){let n=[{gemini_cli_key:oe.GEMINI_CLI_EXPERIMENT_IDS,value:r.experimentIds.toString()??"NA"}];e.event_metadata=[[...e.event_metadata[0],...n]]}this.enqueueHelper(e,r?.experimentIds)})}catch(r){B.warn("ClearcutLogger: Failed to enqueue log event.",r)}}createBasicLogEvent(e,r=[]){let n=this.userAccountManager.getCachedGoogleAccount(),o=jsn(),s=Qsn(),c=$sn(),u=qsn(),d=Vsn(),l=Hsn(),a=[...r,{gemini_cli_key:oe.GEMINI_CLI_SURFACE,value:o},{gemini_cli_key:oe.GEMINI_CLI_VERSION,value:q2t},{gemini_cli_key:oe.GEMINI_CLI_GIT_COMMIT_HASH,value:$2t},{gemini_cli_key:oe.GEMINI_CLI_OS,value:process.platform}];s&&a.push({gemini_cli_key:oe.GEMINI_CLI_GH_WORKFLOW_NAME,value:s}),this.hashedGHRepositoryName&&a.push({gemini_cli_key:oe.GEMINI_CLI_GH_REPOSITORY_NAME_HASH,value:this.hashedGHRepositoryName}),c&&a.push({gemini_cli_key:oe.GEMINI_CLI_GH_EVENT_NAME,value:c}),u&&a.push({gemini_cli_key:oe.GEMINI_CLI_GH_PR_NUMBER,value:u}),d&&a.push({gemini_cli_key:oe.GEMINI_CLI_GH_ISSUE_NUMBER,value:d}),l&&a.push({gemini_cli_key:oe.GEMINI_CLI_GH_CUSTOM_TRACKING_ID,value:l});let p={console_type:"GEMINI_CLI",application:102,event_name:e,event_metadata:[a]};return n?p.client_email=n:p.client_install_id=this.installationManager.getInstallationId(),p}createLogEvent(e,r=[]){e!==gt.START_SESSION&&r.push(...this.sessionData);let n=this.userAccountManager.getLifetimeGoogleAccounts();return r=this.addDefaultFields(r,n),this.createBasicLogEvent(e,r)}flushIfNeeded(){Date.now()-this.lastFlushTime<Wsn||this.flushToClearcut().catch(e=>{B.debug("Error flushing to Clearcut:",e)})}async flushToClearcut(){if(this.flushing)return this.config?.getDebugMode()&&B.debug("ClearcutLogger: Flush already in progress, marking pending flush."),this.pendingFlush=!0,Promise.resolve({});this.flushing=!0,this.config?.getDebugMode()&&B.log("Flushing log events to Clearcut.");let e=this.events.toArray();this.events.clear();let r=[{log_source_name:"CONCORD",request_time_ms:Date.now(),log_event:e}],n={};try{let o=await fetch(zsn,{method:"POST",body:Lr(r),headers:{"Content-Type":"application/json"}}),s=await o.text();if(o.status>=200&&o.status<300){this.lastFlushTime=Date.now();let c=Number(JSON.parse(s)[0]);n={...n,nextRequestWaitMs:c}}else this.config?.getDebugMode()&&B.warn(`Error flushing log events: HTTP ${o.status}: ${o.statusText}`),this.requeueFailedEvents(e)}catch(o){this.config?.getDebugMode()&&B.warn("Error flushing log events:",o),this.requeueFailedEvents(e)}return this.flushing=!1,this.pendingFlush&&(this.pendingFlush=!1,this.flushToClearcut().catch(o=>{this.config?.getDebugMode()&&B.debug("Error in pending flush to Clearcut:",o)})),n}async logStartSessionEvent(e){let r=[{gemini_cli_key:oe.GEMINI_CLI_START_SESSION_MODEL,value:e.model},{gemini_cli_key:oe.GEMINI_CLI_START_SESSION_EMBEDDING_MODEL,value:e.embedding_model},{gemini_cli_key:oe.GEMINI_CLI_START_SESSION_SANDBOX,value:e.sandbox_enabled.toString()},{gemini_cli_key:oe.GEMINI_CLI_START_SESSION_CORE_TOOLS,value:e.core_tools_enabled},{gemini_cli_key:oe.GEMINI_CLI_START_SESSION_APPROVAL_MODE,value:e.approval_mode},{gemini_cli_key:oe.GEMINI_CLI_START_SESSION_API_KEY_ENABLED,value:e.api_key_enabled.toString()},{gemini_cli_key:oe.GEMINI_CLI_START_SESSION_VERTEX_API_ENABLED,value:e.vertex_ai_enabled.toString()},{gemini_cli_key:oe.GEMINI_CLI_START_SESSION_DEBUG_MODE_ENABLED,value:e.debug_enabled.toString()},{gemini_cli_key:oe.GEMINI_CLI_START_SESSION_VERTEX_API_ENABLED,value:e.vertex_ai_enabled.toString()},{gemini_cli_key:oe.GEMINI_CLI_START_SESSION_MCP_SERVERS,value:e.mcp_servers},{gemini_cli_key:oe.GEMINI_CLI_START_SESSION_VERTEX_API_ENABLED,value:e.vertex_ai_enabled.toString()},{gemini_cli_key:oe.GEMINI_CLI_START_SESSION_TELEMETRY_ENABLED,value:e.telemetry_enabled.toString()},{gemini_cli_key:oe.GEMINI_CLI_START_SESSION_TELEMETRY_LOG_USER_PROMPTS_ENABLED,value:e.telemetry_log_user_prompts_enabled.toString()},{gemini_cli_key:oe.GEMINI_CLI_START_SESSION_MCP_SERVERS_COUNT,value:e.mcp_servers_count?e.mcp_servers_count.toString():""},{gemini_cli_key:oe.GEMINI_CLI_START_SESSION_MCP_TOOLS_COUNT,value:e.mcp_tools_count?.toString()??""},{gemini_cli_key:oe.GEMINI_CLI_START_SESSION_MCP_TOOLS,value:e.mcp_tools?e.mcp_tools:""},{gemini_cli_key:oe.GEMINI_CLI_START_SESSION_EXTENSIONS_COUNT,value:e.extensions_count.toString()},{gemini_cli_key:oe.GEMINI_CLI_START_SESSION_EXTENSION_IDS,value:e.extension_ids.toString()},{gemini_cli_key:oe.GEMINI_CLI_START_SESSION_WORKTREE_ACTIVE,value:e.worktree_active.toString()}],n=jI.cpus();n&&n.length>0&&r.push({gemini_cli_key:oe.GEMINI_CLI_CPU_INFO,value:n[0].model}),r.push({gemini_cli_key:oe.GEMINI_CLI_CPU_CORES,value:jI.availableParallelism().toString()},{gemini_cli_key:oe.GEMINI_CLI_RAM_TOTAL_GB,value:(jI.totalmem()/1024**3).toFixed(2).toString()});let o=await Jsn();r.push({gemini_cli_key:oe.GEMINI_CLI_GPU_INFO,value:o}),this.sessionData=r,this.enqueueLogEventAfterExperimentsLoadAsync(this.createLogEvent(gt.START_SESSION,r)).then(()=>{this.flushToClearcut().catch(s=>{B.debug("Error flushing to Clearcut:",s)})})}logNewPromptEvent(e){this.promptId=e.prompt_id;let r=[{gemini_cli_key:oe.GEMINI_CLI_USER_PROMPT_LENGTH,value:JSON.stringify(e.prompt_length)}];this.enqueueLogEvent(this.createLogEvent(gt.NEW_PROMPT,r)),this.flushIfNeeded()}logToolCallEvent(e){let r=[{gemini_cli_key:oe.GEMINI_CLI_TOOL_CALL_NAME,value:JSON.stringify(e.function_name)},{gemini_cli_key:oe.GEMINI_CLI_TOOL_CALL_DECISION,value:JSON.stringify(e.decision)},{gemini_cli_key:oe.GEMINI_CLI_TOOL_CALL_SUCCESS,value:JSON.stringify(e.success)},{gemini_cli_key:oe.GEMINI_CLI_TOOL_CALL_DURATION_MS,value:JSON.stringify(e.duration_ms)},{gemini_cli_key:oe.GEMINI_CLI_TOOL_CALL_ERROR_TYPE,value:JSON.stringify(e.error_type)},{gemini_cli_key:oe.GEMINI_CLI_TOOL_TYPE,value:JSON.stringify(e.tool_type)},{gemini_cli_key:oe.GEMINI_CLI_TOOL_CALL_CONTENT_LENGTH,value:JSON.stringify(e.content_length)},{gemini_cli_key:oe.GEMINI_CLI_TOOL_CALL_MCP_SERVER_NAME,value:JSON.stringify(e.mcp_server_name)}];if(e.metadata){let o={model_added_lines:oe.GEMINI_CLI_AI_ADDED_LINES,model_removed_lines:oe.GEMINI_CLI_AI_REMOVED_LINES,model_added_chars:oe.GEMINI_CLI_AI_ADDED_CHARS,model_removed_chars:oe.GEMINI_CLI_AI_REMOVED_CHARS,user_added_lines:oe.GEMINI_CLI_USER_ADDED_LINES,user_removed_lines:oe.GEMINI_CLI_USER_REMOVED_LINES,user_added_chars:oe.GEMINI_CLI_USER_ADDED_CHARS,user_removed_chars:oe.GEMINI_CLI_USER_REMOVED_CHARS};if(e.function_name===bs&&e.metadata.ask_user){let s=e.metadata.ask_user,c={question_types:oe.GEMINI_CLI_ASK_USER_QUESTION_TYPES,dismissed:oe.GEMINI_CLI_ASK_USER_DISMISSED,empty_submission:oe.GEMINI_CLI_ASK_USER_EMPTY_SUBMISSION,answer_count:oe.GEMINI_CLI_ASK_USER_ANSWER_COUNT};for(let[u,d]of Object.entries(c))s[u]!==void 0&&r.push({gemini_cli_key:d,value:JSON.stringify(s[u])})}for(let[s,c]of Object.entries(o))e.metadata[s]!==void 0&&r.push({gemini_cli_key:c,value:JSON.stringify(e.metadata[s])})}e.extension_id&&r.push({gemini_cli_key:oe.GEMINI_CLI_EXTENSION_ID,value:e.extension_id});let n=this.createLogEvent(gt.TOOL_CALL,r);this.enqueueLogEvent(n),this.flushIfNeeded()}logFileOperationEvent(e){let r=[{gemini_cli_key:oe.GEMINI_CLI_TOOL_CALL_NAME,value:JSON.stringify(e.tool_name)},{gemini_cli_key:oe.GEMINI_CLI_FILE_OPERATION_TYPE,value:JSON.stringify(e.operation)},{gemini_cli_key:oe.GEMINI_CLI_FILE_OPERATION_LINES,value:JSON.stringify(e.lines)},{gemini_cli_key:oe.GEMINI_CLI_FILE_OPERATION_MIMETYPE,value:JSON.stringify(e.mimetype)},{gemini_cli_key:oe.GEMINI_CLI_FILE_OPERATION_EXTENSION,value:JSON.stringify(e.extension)}];e.programming_language&&r.push({gemini_cli_key:oe.GEMINI_CLI_PROGRAMMING_LANGUAGE,value:e.programming_language});let n=this.createLogEvent(gt.FILE_OPERATION,r);this.enqueueLogEvent(n),this.flushIfNeeded()}logApiRequestEvent(e){let r=[{gemini_cli_key:oe.GEMINI_CLI_API_REQUEST_MODEL,value:JSON.stringify(e.model)}];this.enqueueLogEvent(this.createLogEvent(gt.API_REQUEST,r)),this.flushIfNeeded()}logApiResponseEvent(e){let r=[{gemini_cli_key:oe.GEMINI_CLI_API_RESPONSE_MODEL,value:JSON.stringify(e.model)},{gemini_cli_key:oe.GEMINI_CLI_API_RESPONSE_STATUS_CODE,value:JSON.stringify(e.status_code)},{gemini_cli_key:oe.GEMINI_CLI_API_RESPONSE_DURATION_MS,value:JSON.stringify(e.duration_ms)},{gemini_cli_key:oe.GEMINI_CLI_API_RESPONSE_INPUT_TOKEN_COUNT,value:JSON.stringify(e.usage.input_token_count)},{gemini_cli_key:oe.GEMINI_CLI_API_RESPONSE_OUTPUT_TOKEN_COUNT,value:JSON.stringify(e.usage.output_token_count)},{gemini_cli_key:oe.GEMINI_CLI_API_RESPONSE_CACHED_TOKEN_COUNT,value:JSON.stringify(e.usage.cached_content_token_count)},{gemini_cli_key:oe.GEMINI_CLI_API_RESPONSE_THINKING_TOKEN_COUNT,value:JSON.stringify(e.usage.thoughts_token_count)},{gemini_cli_key:oe.GEMINI_CLI_API_RESPONSE_TOOL_TOKEN_COUNT,value:JSON.stringify(e.usage.tool_token_count)},{gemini_cli_key:oe.GEMINI_CLI_API_RESPONSE_CONTEXT_BREAKDOWN_SYSTEM_INSTRUCTIONS,value:JSON.stringify(e.usage.context_breakdown?.system_instructions??0)},{gemini_cli_key:oe.GEMINI_CLI_API_RESPONSE_CONTEXT_BREAKDOWN_TOOL_DEFINITIONS,value:JSON.stringify(e.usage.context_breakdown?.tool_definitions??0)},{gemini_cli_key:oe.GEMINI_CLI_API_RESPONSE_CONTEXT_BREAKDOWN_HISTORY,value:JSON.stringify(e.usage.context_breakdown?.history??0)},{gemini_cli_key:oe.GEMINI_CLI_API_RESPONSE_CONTEXT_BREAKDOWN_TOOL_CALLS,value:JSON.stringify(e.usage.context_breakdown?.tool_calls??{})},{gemini_cli_key:oe.GEMINI_CLI_API_RESPONSE_CONTEXT_BREAKDOWN_MCP_SERVERS,value:JSON.stringify(e.usage.context_breakdown?.mcp_servers??0)}];this.enqueueLogEvent(this.createLogEvent(gt.API_RESPONSE,r)),this.flushIfNeeded()}logApiErrorEvent(e){let r=[{gemini_cli_key:oe.GEMINI_CLI_API_ERROR_MODEL,value:JSON.stringify(e.model)},{gemini_cli_key:oe.GEMINI_CLI_API_ERROR_TYPE,value:JSON.stringify(e.error_type)},{gemini_cli_key:oe.GEMINI_CLI_API_ERROR_STATUS_CODE,value:JSON.stringify(e.status_code)},{gemini_cli_key:oe.GEMINI_CLI_API_ERROR_DURATION_MS,value:JSON.stringify(e.duration_ms)}];this.enqueueLogEvent(this.createLogEvent(gt.API_ERROR,r)),this.flushIfNeeded()}logChatCompressionEvent(e){let r=[{gemini_cli_key:oe.GEMINI_CLI_COMPRESSION_TOKENS_BEFORE,value:`${e.tokens_before}`},{gemini_cli_key:oe.GEMINI_CLI_COMPRESSION_TOKENS_AFTER,value:`${e.tokens_after}`}];this.enqueueLogEvent(this.createLogEvent(gt.CHAT_COMPRESSION,r))}logFlashFallbackEvent(){this.enqueueLogEvent(this.createLogEvent(gt.FLASH_FALLBACK,[])),this.flushToClearcut().catch(e=>{B.debug("Error flushing to Clearcut:",e)})}logRipgrepFallbackEvent(){this.enqueueLogEvent(this.createLogEvent(gt.RIPGREP_FALLBACK,[])),this.flushToClearcut().catch(e=>{B.debug("Error flushing to Clearcut:",e)})}logLoopDetectedEvent(e){let r=[{gemini_cli_key:oe.GEMINI_CLI_LOOP_DETECTED_TYPE,value:JSON.stringify(e.loop_type)}];e.confirmed_by_model&&r.push({gemini_cli_key:oe.GEMINI_CLI_LOOP_DETECTED_CONFIRMED_BY_MODEL,value:e.confirmed_by_model}),this.enqueueLogEvent(this.createLogEvent(gt.LOOP_DETECTED,r)),this.flushIfNeeded()}logLoopDetectionDisabledEvent(){let e=[];this.enqueueLogEvent(this.createLogEvent(gt.LOOP_DETECTION_DISABLED,e)),this.flushIfNeeded()}logNextSpeakerCheck(e){let r=[{gemini_cli_key:oe.GEMINI_CLI_RESPONSE_FINISH_REASON,value:JSON.stringify(e.finish_reason)},{gemini_cli_key:oe.GEMINI_CLI_NEXT_SPEAKER_CHECK_RESULT,value:JSON.stringify(e.result)}];this.enqueueLogEvent(this.createLogEvent(gt.NEXT_SPEAKER_CHECK,r)),this.flushIfNeeded()}logSlashCommandEvent(e){let r=[{gemini_cli_key:oe.GEMINI_CLI_SLASH_COMMAND_NAME,value:JSON.stringify(e.command)}];e.subcommand&&r.push({gemini_cli_key:oe.GEMINI_CLI_SLASH_COMMAND_SUBCOMMAND,value:JSON.stringify(e.subcommand)}),e.status&&r.push({gemini_cli_key:oe.GEMINI_CLI_SLASH_COMMAND_STATUS,value:JSON.stringify(e.status)}),e.extension_id&&r.push({gemini_cli_key:oe.GEMINI_CLI_EXTENSION_ID,value:e.extension_id}),this.enqueueLogEvent(this.createLogEvent(gt.SLASH_COMMAND,r)),this.flushIfNeeded()}logRewindEvent(e){let r=[{gemini_cli_key:oe.GEMINI_CLI_REWIND_OUTCOME,value:e.outcome}];this.enqueueLogEvent(this.createLogEvent(gt.REWIND,r)),this.flushIfNeeded()}logMalformedJsonResponseEvent(e){let r=[{gemini_cli_key:oe.GEMINI_CLI_MALFORMED_JSON_RESPONSE_MODEL,value:JSON.stringify(e.model)}];this.enqueueLogEvent(this.createLogEvent(gt.MALFORMED_JSON_RESPONSE,r)),this.flushIfNeeded()}logIdeConnectionEvent(e){let r=[{gemini_cli_key:oe.GEMINI_CLI_IDE_CONNECTION_TYPE,value:JSON.stringify(e.connection_type)}];this.enqueueLogEventAfterExperimentsLoadAsync(this.createLogEvent(gt.START_SESSION,r)).then(()=>{this.flushToClearcut().catch(n=>{B.debug("Error flushing to Clearcut:",n)})})}logConversationFinishedEvent(e){let r=[{gemini_cli_key:oe.GEMINI_CLI_SESSION_ID,value:this.config?.getSessionId()??""},{gemini_cli_key:oe.GEMINI_CLI_CONVERSATION_TURN_COUNT,value:JSON.stringify(e.turnCount)},{gemini_cli_key:oe.GEMINI_CLI_APPROVAL_MODE,value:e.approvalMode}];this.enqueueLogEvent(this.createLogEvent(gt.CONVERSATION_FINISHED,r)),this.flushIfNeeded()}logEndSessionEvent(){this.enqueueLogEvent(this.createLogEvent(gt.END_SESSION,[])),this.flushToClearcut().catch(e=>{B.debug("Error flushing to Clearcut:",e)})}logInvalidChunkEvent(e){let r=[];e.error_message&&r.push({gemini_cli_key:oe.GEMINI_CLI_INVALID_CHUNK_ERROR_MESSAGE,value:e.error_message}),this.enqueueLogEvent(this.createLogEvent(gt.INVALID_CHUNK,r)),this.flushIfNeeded()}logContentRetryEvent(e){let r=[{gemini_cli_key:oe.GEMINI_CLI_CONTENT_RETRY_ATTEMPT_NUMBER,value:String(e.attempt_number)},{gemini_cli_key:oe.GEMINI_CLI_CONTENT_RETRY_ERROR_TYPE,value:e.error_type},{gemini_cli_key:oe.GEMINI_CLI_CONTENT_RETRY_DELAY_MS,value:String(e.retry_delay_ms)},{gemini_cli_key:oe.GEMINI_CLI_API_REQUEST_MODEL,value:e.model}];this.enqueueLogEvent(this.createLogEvent(gt.CONTENT_RETRY,r)),this.flushIfNeeded()}logContentRetryFailureEvent(e){let r=[{gemini_cli_key:oe.GEMINI_CLI_CONTENT_RETRY_FAILURE_TOTAL_ATTEMPTS,value:String(e.total_attempts)},{gemini_cli_key:oe.GEMINI_CLI_CONTENT_RETRY_FAILURE_FINAL_ERROR_TYPE,value:e.final_error_type},{gemini_cli_key:oe.GEMINI_CLI_API_REQUEST_MODEL,value:e.model}];e.total_duration_ms&&r.push({gemini_cli_key:oe.GEMINI_CLI_CONTENT_RETRY_FAILURE_TOTAL_DURATION_MS,value:String(e.total_duration_ms)}),this.enqueueLogEvent(this.createLogEvent(gt.CONTENT_RETRY_FAILURE,r)),this.flushIfNeeded()}logNetworkRetryAttemptEvent(e){let r=[{gemini_cli_key:oe.GEMINI_CLI_NETWORK_RETRY_ATTEMPT_NUMBER,value:String(e.attempt)},{gemini_cli_key:oe.GEMINI_CLI_NETWORK_RETRY_DELAY_MS,value:String(e.delay_ms)},{gemini_cli_key:oe.GEMINI_CLI_NETWORK_RETRY_ERROR_TYPE,value:e.error_type},{gemini_cli_key:oe.GEMINI_CLI_API_REQUEST_MODEL,value:e.model}];this.enqueueLogEvent(this.createLogEvent(gt.RETRY_ATTEMPT,r)),this.flushIfNeeded()}async logExtensionInstallEvent(e){let r=[{gemini_cli_key:oe.GEMINI_CLI_EXTENSION_NAME,value:e.hashed_extension_name},{gemini_cli_key:oe.GEMINI_CLI_EXTENSION_ID,value:e.extension_id},{gemini_cli_key:oe.GEMINI_CLI_EXTENSION_VERSION,value:e.extension_version},{gemini_cli_key:oe.GEMINI_CLI_EXTENSION_SOURCE,value:e.extension_source},{gemini_cli_key:oe.GEMINI_CLI_EXTENSION_INSTALL_STATUS,value:e.status}];this.enqueueLogEvent(this.createBasicLogEvent(gt.EXTENSION_INSTALL,r)),await this.flushToClearcut().catch(n=>{B.debug("Error flushing to Clearcut:",n)})}async logExtensionUninstallEvent(e){let r=[{gemini_cli_key:oe.GEMINI_CLI_EXTENSION_NAME,value:e.hashed_extension_name},{gemini_cli_key:oe.GEMINI_CLI_EXTENSION_ID,value:e.extension_id},{gemini_cli_key:oe.GEMINI_CLI_EXTENSION_UNINSTALL_STATUS,value:e.status}];this.enqueueLogEvent(this.createBasicLogEvent(gt.EXTENSION_UNINSTALL,r)),await this.flushToClearcut().catch(n=>{B.debug("Error flushing to Clearcut:",n)})}async logExtensionUpdateEvent(e){let r=[{gemini_cli_key:oe.GEMINI_CLI_EXTENSION_NAME,value:e.hashed_extension_name},{gemini_cli_key:oe.GEMINI_CLI_EXTENSION_ID,value:e.extension_id},{gemini_cli_key:oe.GEMINI_CLI_EXTENSION_VERSION,value:e.extension_version},{gemini_cli_key:oe.GEMINI_CLI_EXTENSION_PREVIOUS_VERSION,value:e.extension_previous_version},{gemini_cli_key:oe.GEMINI_CLI_EXTENSION_SOURCE,value:e.extension_source},{gemini_cli_key:oe.GEMINI_CLI_EXTENSION_UPDATE_STATUS,value:e.status}];this.enqueueLogEvent(this.createBasicLogEvent(gt.EXTENSION_UPDATE,r)),await this.flushToClearcut().catch(n=>{B.debug("Error flushing to Clearcut:",n)})}logToolOutputTruncatedEvent(e){let r=[{gemini_cli_key:oe.GEMINI_CLI_TOOL_CALL_NAME,value:JSON.stringify(e.tool_name)},{gemini_cli_key:oe.GEMINI_CLI_TOOL_OUTPUT_TRUNCATED_ORIGINAL_LENGTH,value:JSON.stringify(e.original_content_length)},{gemini_cli_key:oe.GEMINI_CLI_TOOL_OUTPUT_TRUNCATED_TRUNCATED_LENGTH,value:JSON.stringify(e.truncated_content_length)},{gemini_cli_key:oe.GEMINI_CLI_TOOL_OUTPUT_TRUNCATED_THRESHOLD,value:JSON.stringify(e.threshold)}],n=this.createLogEvent(gt.TOOL_OUTPUT_TRUNCATED,r);this.enqueueLogEvent(n),this.flushIfNeeded()}logToolOutputMaskingEvent(e){let r=[{gemini_cli_key:oe.GEMINI_CLI_TOOL_OUTPUT_MASKING_TOKENS_BEFORE,value:e.tokens_before.toString()},{gemini_cli_key:oe.GEMINI_CLI_TOOL_OUTPUT_MASKING_TOKENS_AFTER,value:e.tokens_after.toString()},{gemini_cli_key:oe.GEMINI_CLI_TOOL_OUTPUT_MASKING_MASKED_COUNT,value:e.masked_count.toString()},{gemini_cli_key:oe.GEMINI_CLI_TOOL_OUTPUT_MASKING_TOTAL_PRUNABLE_TOKENS,value:e.total_prunable_tokens.toString()}];this.enqueueLogEvent(this.createLogEvent(gt.TOOL_OUTPUT_MASKING,r)),this.flushIfNeeded()}logModelRoutingEvent(e){let r=[{gemini_cli_key:oe.GEMINI_CLI_ROUTING_DECISION,value:e.decision_model},{gemini_cli_key:oe.GEMINI_CLI_ROUTING_DECISION_SOURCE,value:e.decision_source},{gemini_cli_key:oe.GEMINI_CLI_ROUTING_LATENCY_MS,value:e.routing_latency_ms.toString()},{gemini_cli_key:oe.GEMINI_CLI_ROUTING_FAILURE,value:e.failed.toString()}];e.error_message&&r.push({gemini_cli_key:oe.GEMINI_CLI_ROUTING_FAILURE_REASON,value:e.error_message}),e.reasoning&&this.config?.getTelemetryLogPromptsEnabled()&&r.push({gemini_cli_key:oe.GEMINI_CLI_ROUTING_REASONING,value:e.reasoning}),e.enable_numerical_routing!==void 0&&r.push({gemini_cli_key:oe.GEMINI_CLI_ROUTING_NUMERICAL_ENABLED,value:e.enable_numerical_routing.toString()}),e.classifier_threshold&&r.push({gemini_cli_key:oe.GEMINI_CLI_ROUTING_CLASSIFIER_THRESHOLD,value:e.classifier_threshold}),this.enqueueLogEvent(this.createLogEvent(gt.MODEL_ROUTING,r)),this.flushIfNeeded()}async logExtensionEnableEvent(e){let r=[{gemini_cli_key:oe.GEMINI_CLI_EXTENSION_NAME,value:e.hashed_extension_name},{gemini_cli_key:oe.GEMINI_CLI_EXTENSION_ID,value:e.extension_id},{gemini_cli_key:oe.GEMINI_CLI_EXTENSION_ENABLE_SETTING_SCOPE,value:e.setting_scope}];this.enqueueLogEvent(this.createBasicLogEvent(gt.EXTENSION_ENABLE,r)),await this.flushToClearcut().catch(n=>{B.debug("Error flushing to Clearcut:",n)})}logModelSlashCommandEvent(e){let r=[{gemini_cli_key:oe.GEMINI_CLI_MODEL_SLASH_COMMAND,value:e.model_name}];this.enqueueLogEvent(this.createLogEvent(gt.MODEL_SLASH_COMMAND,r)),this.flushIfNeeded()}async logExtensionDisableEvent(e){let r=[{gemini_cli_key:oe.GEMINI_CLI_EXTENSION_NAME,value:e.hashed_extension_name},{gemini_cli_key:oe.GEMINI_CLI_EXTENSION_ID,value:e.extension_id},{gemini_cli_key:oe.GEMINI_CLI_EXTENSION_DISABLE_SETTING_SCOPE,value:e.setting_scope}];this.enqueueLogEvent(this.createBasicLogEvent(gt.EXTENSION_DISABLE,r)),await this.flushToClearcut().catch(n=>{B.debug("Error flushing to Clearcut:",n)})}logEditStrategyEvent(e){let r=[{gemini_cli_key:oe.GEMINI_CLI_EDIT_STRATEGY,value:e.strategy}];this.enqueueLogEvent(this.createLogEvent(gt.EDIT_STRATEGY,r)),this.flushIfNeeded()}logEditCorrectionEvent(e){let r=[{gemini_cli_key:oe.GEMINI_CLI_EDIT_CORRECTION,value:e.correction}];this.enqueueLogEvent(this.createLogEvent(gt.EDIT_CORRECTION,r)),this.flushIfNeeded()}logAgentStartEvent(e){let r=[{gemini_cli_key:oe.GEMINI_CLI_AGENT_ID,value:e.agent_id},{gemini_cli_key:oe.GEMINI_CLI_AGENT_NAME,value:e.agent_name}];this.enqueueLogEvent(this.createLogEvent(gt.AGENT_START,r)),this.flushIfNeeded()}logAgentFinishEvent(e){let r=[{gemini_cli_key:oe.GEMINI_CLI_AGENT_ID,value:e.agent_id},{gemini_cli_key:oe.GEMINI_CLI_AGENT_NAME,value:e.agent_name},{gemini_cli_key:oe.GEMINI_CLI_AGENT_DURATION_MS,value:e.duration_ms.toString()},{gemini_cli_key:oe.GEMINI_CLI_AGENT_TURN_COUNT,value:e.turn_count.toString()},{gemini_cli_key:oe.GEMINI_CLI_AGENT_TERMINATE_REASON,value:e.terminate_reason}];this.enqueueLogEvent(this.createLogEvent(gt.AGENT_FINISH,r)),this.flushIfNeeded()}logRecoveryAttemptEvent(e){let r=[{gemini_cli_key:oe.GEMINI_CLI_AGENT_ID,value:e.agent_id},{gemini_cli_key:oe.GEMINI_CLI_AGENT_NAME,value:e.agent_name},{gemini_cli_key:oe.GEMINI_CLI_AGENT_RECOVERY_REASON,value:e.reason},{gemini_cli_key:oe.GEMINI_CLI_AGENT_RECOVERY_DURATION_MS,value:e.duration_ms.toString()},{gemini_cli_key:oe.GEMINI_CLI_AGENT_RECOVERY_SUCCESS,value:e.success.toString()},{gemini_cli_key:oe.GEMINI_CLI_AGENT_TURN_COUNT,value:e.turn_count.toString()}];this.enqueueLogEvent(this.createLogEvent(gt.RECOVERY_ATTEMPT,r)),this.flushIfNeeded()}logWebFetchFallbackAttemptEvent(e){let r=[{gemini_cli_key:oe.GEMINI_CLI_WEB_FETCH_FALLBACK_REASON,value:e.reason}];this.enqueueLogEvent(this.createLogEvent(gt.WEB_FETCH_FALLBACK_ATTEMPT,r)),this.flushIfNeeded()}logLlmLoopCheckEvent(e){let r=[{gemini_cli_key:oe.GEMINI_CLI_PROMPT_ID,value:e.prompt_id},{gemini_cli_key:oe.GEMINI_CLI_LLM_LOOP_CHECK_FLASH_CONFIDENCE,value:e.flash_confidence.toString()},{gemini_cli_key:oe.GEMINI_CLI_LLM_LOOP_CHECK_MAIN_MODEL,value:e.main_model},{gemini_cli_key:oe.GEMINI_CLI_LLM_LOOP_CHECK_MAIN_MODEL_CONFIDENCE,value:e.main_model_confidence.toString()}];this.enqueueLogEvent(this.createLogEvent(gt.LLM_LOOP_CHECK,r)),this.flushIfNeeded()}logHookCallEvent(e){let r=[{gemini_cli_key:oe.GEMINI_CLI_HOOK_EVENT_NAME,value:e.hook_event_name},{gemini_cli_key:oe.GEMINI_CLI_HOOK_DURATION_MS,value:e.duration_ms.toString()},{gemini_cli_key:oe.GEMINI_CLI_HOOK_SUCCESS,value:e.success.toString()}];e.exit_code!==void 0&&r.push({gemini_cli_key:oe.GEMINI_CLI_HOOK_EXIT_CODE,value:e.exit_code.toString()}),this.enqueueLogEvent(this.createLogEvent(gt.HOOK_CALL,r)),this.flushIfNeeded()}logApprovalModeSwitchEvent(e){let r=[{gemini_cli_key:oe.GEMINI_CLI_ACTIVE_APPROVAL_MODE,value:e.from_mode},{gemini_cli_key:oe.GEMINI_CLI_APPROVAL_MODE_TO,value:e.to_mode}];this.enqueueLogEvent(this.createLogEvent(gt.APPROVAL_MODE_SWITCH,r)),this.flushIfNeeded()}logApprovalModeDurationEvent(e){let r=[{gemini_cli_key:oe.GEMINI_CLI_ACTIVE_APPROVAL_MODE,value:e.mode},{gemini_cli_key:oe.GEMINI_CLI_APPROVAL_MODE_DURATION_MS,value:e.duration_ms.toString()}];this.enqueueLogEvent(this.createLogEvent(gt.APPROVAL_MODE_DURATION,r)),this.flushIfNeeded()}logPlanExecutionEvent(e){let r=[{gemini_cli_key:oe.GEMINI_CLI_APPROVAL_MODE,value:e.approval_mode}];this.enqueueLogEvent(this.createLogEvent(gt.PLAN_EXECUTION,r)),this.flushIfNeeded()}logKeychainAvailabilityEvent(e){let r=[{gemini_cli_key:oe.GEMINI_CLI_KEYCHAIN_AVAILABLE,value:JSON.stringify(e.available)}];this.enqueueLogEvent(this.createLogEvent(gt.KEYCHAIN_AVAILABILITY,r)),this.flushIfNeeded()}logTokenStorageInitializationEvent(e){let r=[{gemini_cli_key:oe.GEMINI_CLI_TOKEN_STORAGE_TYPE,value:e.type},{gemini_cli_key:oe.GEMINI_CLI_TOKEN_STORAGE_FORCED,value:JSON.stringify(e.forced)}];this.enqueueLogEvent(this.createLogEvent(gt.TOKEN_STORAGE_INITIALIZATION,r)),this.flushIfNeeded()}logOnboardingStartEvent(e){let r=[{gemini_cli_key:oe.GEMINI_CLI_ONBOARDING_START,value:"true"}];this.enqueueLogEvent(this.createLogEvent(gt.ONBOARDING_START,r)),this.flushIfNeeded()}logOnboardingSuccessEvent(e){let r=[];e.userTier&&r.push({gemini_cli_key:oe.GEMINI_CLI_ONBOARDING_USER_TIER,value:e.userTier}),e.duration_ms!==void 0&&r.push({gemini_cli_key:oe.GEMINI_CLI_ONBOARDING_DURATION_MS,value:e.duration_ms.toString()}),this.enqueueLogEvent(this.createLogEvent(gt.ONBOARDING_SUCCESS,r)),this.flushIfNeeded()}logStartupStatsEvent(e){let r=[{gemini_cli_key:oe.GEMINI_CLI_STARTUP_PHASES,value:JSON.stringify(e.phases)},{gemini_cli_key:oe.GEMINI_CLI_STARTUP_OS_PLATFORM,value:e.os_platform},{gemini_cli_key:oe.GEMINI_CLI_STARTUP_OS_RELEASE,value:e.os_release},{gemini_cli_key:oe.GEMINI_CLI_STARTUP_IS_DOCKER,value:JSON.stringify(e.is_docker)}];this.enqueueLogEvent(this.createLogEvent(gt.STARTUP_STATS,r)),this.flushIfNeeded()}logCreditsUsedEvent(e){let r=[{gemini_cli_key:oe.GEMINI_CLI_BILLING_MODEL,value:JSON.stringify(e.model)},{gemini_cli_key:oe.GEMINI_CLI_BILLING_CREDITS_CONSUMED,value:JSON.stringify(e.credits_consumed)},{gemini_cli_key:oe.GEMINI_CLI_BILLING_CREDITS_REMAINING,value:JSON.stringify(e.credits_remaining)}];this.enqueueLogEvent(this.createLogEvent(gt.CREDITS_USED,r)),this.flushIfNeeded()}logOverageOptionSelectedEvent(e){let r=[{gemini_cli_key:oe.GEMINI_CLI_BILLING_MODEL,value:JSON.stringify(e.model)},{gemini_cli_key:oe.GEMINI_CLI_BILLING_SELECTED_OPTION,value:JSON.stringify(e.selected_option)},{gemini_cli_key:oe.GEMINI_CLI_BILLING_CREDIT_BALANCE,value:JSON.stringify(e.credit_balance)}];this.enqueueLogEvent(this.createLogEvent(gt.OVERAGE_OPTION_SELECTED,r)),this.flushIfNeeded()}logEmptyWalletMenuShownEvent(e){let r=[{gemini_cli_key:oe.GEMINI_CLI_BILLING_MODEL,value:JSON.stringify(e.model)}];this.enqueueLogEvent(this.createLogEvent(gt.EMPTY_WALLET_MENU_SHOWN,r)),this.flushIfNeeded()}logCreditPurchaseClickEvent(e){let r=[{gemini_cli_key:oe.GEMINI_CLI_BILLING_MODEL,value:JSON.stringify(e.model)},{gemini_cli_key:oe.GEMINI_CLI_BILLING_PURCHASE_SOURCE,value:JSON.stringify(e.source)}];this.enqueueLogEvent(this.createLogEvent(gt.CREDIT_PURCHASE_CLICK,r)),this.flushIfNeeded()}logBrowserAgentConnectionEvent(e){let r=[{gemini_cli_key:oe.GEMINI_CLI_BROWSER_AGENT_SESSION_MODE,value:e.session_mode},{gemini_cli_key:oe.GEMINI_CLI_BROWSER_AGENT_HEADLESS,value:e.headless.toString()},{gemini_cli_key:oe.GEMINI_CLI_BROWSER_AGENT_SUCCESS,value:e.success.toString()},{gemini_cli_key:oe.GEMINI_CLI_BROWSER_AGENT_DURATION_MS,value:e.duration_ms.toString()}];e.error_type&&r.push({gemini_cli_key:oe.GEMINI_CLI_BROWSER_AGENT_ERROR_TYPE,value:e.error_type}),e.tool_count!==void 0&&r.push({gemini_cli_key:oe.GEMINI_CLI_BROWSER_AGENT_TOOL_COUNT,value:e.tool_count.toString()}),this.enqueueLogEvent(this.createLogEvent(gt.BROWSER_AGENT_CONNECTION,r)),this.flushIfNeeded()}logBrowserAgentVisionStatusEvent(e){let r=[{gemini_cli_key:oe.GEMINI_CLI_BROWSER_AGENT_VISION_ENABLED,value:e.enabled.toString()}];e.disabled_reason&&r.push({gemini_cli_key:oe.GEMINI_CLI_BROWSER_AGENT_VISION_DISABLED_REASON,value:e.disabled_reason}),this.enqueueLogEvent(this.createLogEvent(gt.BROWSER_AGENT_VISION_STATUS,r)),this.flushIfNeeded()}logBrowserAgentTaskOutcomeEvent(e){let r=[{gemini_cli_key:oe.GEMINI_CLI_BROWSER_AGENT_SUCCESS,value:e.success.toString()},{gemini_cli_key:oe.GEMINI_CLI_BROWSER_AGENT_SESSION_MODE,value:e.session_mode},{gemini_cli_key:oe.GEMINI_CLI_BROWSER_AGENT_VISION_ENABLED,value:e.vision_enabled.toString()},{gemini_cli_key:oe.GEMINI_CLI_BROWSER_AGENT_HEADLESS,value:e.headless.toString()},{gemini_cli_key:oe.GEMINI_CLI_BROWSER_AGENT_DURATION_MS,value:e.duration_ms.toString()}];this.enqueueLogEvent(this.createLogEvent(gt.BROWSER_AGENT_TASK_OUTCOME,r)),this.flushIfNeeded()}logBrowserAgentCleanupEvent(e){let r=[{gemini_cli_key:oe.GEMINI_CLI_BROWSER_AGENT_SESSION_MODE,value:e.session_mode},{gemini_cli_key:oe.GEMINI_CLI_BROWSER_AGENT_SUCCESS,value:e.success.toString()},{gemini_cli_key:oe.GEMINI_CLI_BROWSER_AGENT_DURATION_MS,value:e.duration_ms.toString()}];this.enqueueLogEvent(this.createLogEvent(gt.BROWSER_AGENT_CLEANUP,r)),this.flushIfNeeded()}addDefaultFields(e,r){let n=[{gemini_cli_key:oe.GEMINI_CLI_SESSION_ID,value:this.config?.getSessionId()??""},{gemini_cli_key:oe.GEMINI_CLI_AUTH_TYPE,value:JSON.stringify(this.config?.getContentGeneratorConfig()?.authType)},{gemini_cli_key:oe.GEMINI_CLI_GOOGLE_ACCOUNTS_COUNT,value:`${r}`},{gemini_cli_key:oe.GEMINI_CLI_PROMPT_ID,value:this.promptId},{gemini_cli_key:oe.GEMINI_CLI_NODE_VERSION,value:process.versions.node},{gemini_cli_key:oe.GEMINI_CLI_USER_SETTINGS,value:this.getConfigJson()},{gemini_cli_key:oe.GEMINI_CLI_INTERACTIVE,value:this.config?.isInteractive().toString()??"false"},{gemini_cli_key:oe.GEMINI_CLI_ACTIVE_APPROVAL_MODE,value:typeof this.config?.getPolicyEngine=="function"&&typeof this.config.getPolicyEngine()?.getApprovalMode=="function"?this.config.getPolicyEngine().getApprovalMode():""}];return this.config?.getExperiments()&&n.push({gemini_cli_key:oe.GEMINI_CLI_EXPERIMENT_IDS,value:this.config?.getExperiments()?.experimentIds.toString()??"NA"}),[...e,...n]}getProxyAgent(){let e=this.config?.getProxy();if(e){if(e.startsWith("http"))return new z2t.HttpsProxyAgent(e);throw new Error("Unsupported proxy type")}}getConfigJson(){return BKe(this.config)}shutdown(){this.logEndSessionEvent()}requeueFailedEvents(e){let r=e.slice(-AZ);e.length>AZ&&this.config?.getDebugMode()&&B.warn(`ClearcutLogger: Dropping ${e.length-AZ} events due to retry queue limit. Total events: ${e.length}, keeping: ${AZ}`);let n=yZ-this.events.size,o=Math.min(r.length,n);if(o===0){this.config?.getDebugMode()&&B.debug(`ClearcutLogger: No events re-queued (queue size: ${this.events.size})`);return}let s=r.slice(r.length-o);for(let c=s.length-1;c>=0;c--)this.events.unshift(s[c]);for(;this.events.size>yZ;)this.events.pop();this.config?.getDebugMode()&&B.debug(`ClearcutLogger: Re-queued ${o} events for retry (queue size: ${this.events.size})`)}};var IT=Fe(Bt(),1),J2t=Fe(Ef(),1);import*as Y2t from"node:fs";var R4=class{writeStream;constructor(e){this.writeStream=Y2t.createWriteStream(e,{flags:"a"})}serialize(e){return Lr(e,2)+`
1091
+ `),B.error("Failed to authenticate with user code:",Se(e)),!1}}async function Q3r(t){let e=await G3r(),r=process.env.OAUTH_CALLBACK_HOST||"127.0.0.1",n=`http://127.0.0.1:${e}/oauth2callback`,o=kpt.randomBytes(32).toString("hex"),s=t.generateAuthUrl({redirect_uri:n,access_type:"offline",scope:iEe,state:o}),c=new Promise((u,d)=>{let l=Npt.createServer(async(a,p)=>{try{if(a.url.indexOf("/oauth2callback")===-1){p.writeHead(zq,{Location:nEe}),p.end(),d(new Ua("OAuth callback not received. Unexpected request: "+a.url));return}let f=new D3r.URL(a.url,"http://127.0.0.1:3000").searchParams;if(f.get("error")){p.writeHead(zq,{Location:nEe}),p.end();let g=f.get("error"),y=f.get("error_description")||"No additional details provided";d(new Ua(`Google OAuth error: ${g}. ${y}`))}else if(f.get("state")!==o)p.end("State mismatch. Possible CSRF attack"),d(new Ua("OAuth state mismatch. Possible CSRF attack or browser session issue."));else if(f.get("code"))try{let{tokens:g}=await t.getToken({code:f.get("code"),redirect_uri:n});t.setCredentials(g);try{await Wq(t)}catch(y){B.warn("Failed to retrieve Google Account ID during authentication:",Se(y))}p.writeHead(zq,{Location:U3r}),p.end(),u()}catch(g){p.writeHead(zq,{Location:nEe}),p.end(),d(new Ua(`Failed to exchange authorization code for tokens: ${Se(g)}`))}else d(new Ua("No authorization code received from Google OAuth. Please try authenticating again."))}catch(f){f instanceof Ua?d(f):d(new Ua(`Unexpected error during OAuth authentication: ${Se(f)}`))}finally{l.close()}});l.listen(e,r,()=>{}),l.on("error",a=>{d(new Ua(`OAuth callback server error: ${Se(a)}`))})});return{authUrl:s,loginCompletePromise:c}}function G3r(){return new Promise((t,e)=>{let r=0;try{let n=process.env.OAUTH_CALLBACK_PORT;if(n)return r=parseInt(n,10),isNaN(r)||r<=0||r>65535?e(new Error(`Invalid value for OAUTH_CALLBACK_PORT: "${n}"`)):t(r);let o=Dpt.createServer();o.listen(0,()=>{let s=o.address();s&&typeof s=="object"&&(r=s.port)}),o.on("listening",()=>{o.close(),o.unref()}),o.on("error",s=>e(s)),o.on("close",()=>t(r))}catch(n){e(n)}})}async function $3r(){if(oEe())return N2.loadCredentials();let e=[Yt.getOAuthCredsPath(),process.env.GOOGLE_APPLICATION_CREDENTIALS].filter(r=>!!r);for(let r of e)try{let n=await I3.readFile(r,"utf-8");return JSON.parse(n)}catch(n){B.debug(`Failed to load credentials from ${r}:`,Se(n))}return null}function q3r(){R3.clear()}async function hLi(){try{oEe()?await N2.clearCredentials():await I3.rm(Yt.getOAuthCredsPath(),{force:!0}),await Jq.clearCachedGoogleAccount(),q3r()}catch(t){B.warn("Failed to clear cached credentials:",t)}}async function Wq(t){try{let{token:e}=await t.getAccessToken();if(!e)return;let r=await fetch("https://www.googleapis.com/oauth2/v2/userinfo",{headers:{Authorization:`Bearer ${e}`}});if(!r.ok){B.log("Failed to fetch user info:",r.status,r.statusText);return}let n=await r.json();await Jq.cacheGoogleAccount(n.email)}catch(e){B.log("Error retrieving user info:",e)}}function gLi(){R3.clear()}async function V3r(t){let e=Yt.getOAuthCredsPath();await I3.mkdir(M3r.dirname(e),{recursive:!0});let r=JSON.stringify(t,null,2);await I3.writeFile(e,r,{mode:384});try{await I3.chmod(e,384)}catch{}}var Kq;(function(t){t.DASHER_USER="DASHER_USER",t.INELIGIBLE_ACCOUNT="INELIGIBLE_ACCOUNT",t.NON_USER_ACCOUNT="NON_USER_ACCOUNT",t.RESTRICTED_AGE="RESTRICTED_AGE",t.RESTRICTED_NETWORK="RESTRICTED_NETWORK",t.UNKNOWN="UNKNOWN",t.UNKNOWN_LOCATION="UNKNOWN_LOCATION",t.UNSUPPORTED_LOCATION="UNSUPPORTED_LOCATION",t.VALIDATION_REQUIRED="VALIDATION_REQUIRED"})(Kq||(Kq={}));var D0={FREE:"free-tier",LEGACY:"legacy-tier",STANDARD:"standard-tier"},Upt;(function(t){t.Default="DEFAULT",t.Notice="NOTICE",t.Warning="WARNING",t.Error="ERROR"})(Upt||(Upt={}));var Xq;(function(t){t[t.UNKNOWN=0]="UNKNOWN",t[t.THUMBSUP=1]="THUMBSUP",t[t.THUMBSDOWN=2]="THUMBSDOWN",t[t.COPY=3]="COPY",t[t.INSERT=4]="INSERT",t[t.ACCEPT_CODE_BLOCK=5]="ACCEPT_CODE_BLOCK",t[t.ACCEPT_ALL=6]="ACCEPT_ALL",t[t.ACCEPT_FILE=7]="ACCEPT_FILE",t[t.DIFF=8]="DIFF",t[t.ACCEPT_RANGE=9]="ACCEPT_RANGE"})(Xq||(Xq={}));var Hh;(function(t){t[t.ACTION_STATUS_UNSPECIFIED=0]="ACTION_STATUS_UNSPECIFIED",t[t.ACTION_STATUS_NO_ERROR=1]="ACTION_STATUS_NO_ERROR",t[t.ACTION_STATUS_ERROR_UNKNOWN=2]="ACTION_STATUS_ERROR_UNKNOWN",t[t.ACTION_STATUS_CANCELLED=3]="ACTION_STATUS_CANCELLED",t[t.ACTION_STATUS_EMPTY=4]="ACTION_STATUS_EMPTY"})(Hh||(Hh={}));var P3;(function(t){t[t.INITIATION_METHOD_UNSPECIFIED=0]="INITIATION_METHOD_UNSPECIFIED",t[t.TAB=1]="TAB",t[t.COMMAND=2]="COMMAND",t[t.AGENT=3]="AGENT"})(P3||(P3={}));var H3r=Y.object({extensionsEnabled:Y.boolean().optional()}),Fpt=Y.object({extensionsSetting:H3r.optional(),unmanagedCapabilitiesEnabled:Y.boolean().optional()}),z3r=Y.object({url:Y.string().optional(),type:Y.enum(["sse","http"]).optional(),trust:Y.boolean().optional(),includeTools:Y.array(Y.string()).optional(),excludeTools:Y.array(Y.string()).optional()}),W3r=Y.object({scopes:Y.array(Y.string()).optional(),clientId:Y.string().optional(),clientSecret:Y.string().optional()}),jpt=Y.object({url:Y.string(),type:Y.enum(["sse","http"]),authProviderType:Y.nativeEnum(tf).optional(),oauth:W3r.optional(),targetAudience:Y.string().optional(),targetServiceAccount:Y.string().optional(),headers:Y.record(Y.string()).optional(),trust:Y.boolean().optional(),timeout:Y.number().optional(),description:Y.string().optional(),includeTools:Y.array(Y.string()).optional(),excludeTools:Y.array(Y.string()).optional()}),sEe=Y.object({mcpServers:Y.record(z3r).optional(),requiredMcpServers:Y.record(jpt).optional()}),Y3r=Y.object({mcpEnabled:Y.boolean().optional(),mcpConfigJson:Y.string().optional()}),_Li=Y.object({strictModeDisabled:Y.boolean().optional(),mcpSetting:Y.object({mcpEnabled:Y.boolean().optional(),mcpConfig:sEe.optional(),requiredMcpConfig:Y.record(jpt).optional()}).optional(),cliFeatureSetting:Fpt.optional()}),Qpt=Y.object({secureModeEnabled:Y.boolean().optional(),strictModeDisabled:Y.boolean().optional(),mcpSetting:Y3r.optional(),cliFeatureSetting:Fpt.optional(),adminControlsApplicable:Y.boolean().optional()});import*as nYt from"node:readline";import{Readable as nqn}from"node:stream";var gS="GOOGLE_ONE_AI",J3r=new Set([Ch,Ex,ta]);function Gpt(t){return J3r.has(t)}var K3r="https://one.google.com/ai",X3r="https://accounts.google.com/AccountChooser",Z3r="gemini_cli",eMr="web";function tMr(t,e){let r=new URLSearchParams({Email:t,continue:e});return`${X3r}?${r.toString()}`}var vLi={MANAGE_ACTIVITY:"hydrogen_cli_settings_ai_credits_activity_page",MANAGE_ADD_CREDITS:"hydrogen_cli_settings_add_credits",EMPTY_WALLET_ADD_CREDITS:"hydrogen_cli_insufficient_credits_add_credits"};function SLi(t,e,r){let n=`${K3r}/${t}`,o=new URLSearchParams({utm_source:Z3r,utm_medium:eMr,utm_campaign:r}),s=`${n}?${o.toString()}`;return tMr(e,s)}function $pt(t){if(!t?.availableCredits)return null;let e=t.availableCredits.filter(r=>r.creditType===gS);return e.length===0?null:e.reduce((r,n)=>{let o=parseInt(n.creditAmount??"0",10);return r+(isNaN(o)?0:o)},0)}var aEe=50;function qpt(t,e){return t==="always"&&e!=null&&e>=aEe}function TLi(t,e){return t==="ask"&&e!=null&&e>=aEe}function wLi(t,e){return t!=="never"&&e!=null&&e<aEe}var Zt=Fe(Yh(),1);je();var vMt=Fe(Nwe(),1),SMt=Fe(Dwe(),1),TMt=Fe(jwe(),1),wMt=Fe(Gwe(),1),CMt=Fe(qwe(),1),xMt=Fe(n6(),1);nf();var OMt=Fe(vCt(),1);xl();var IMt=Fe(Y0(),1),Pre=Fe(kJ(),1),Nre=Fe(iJ(),1),Ub=Fe(Ef(),1),RMt=Fe(VCt(),1);var H2t=Fe(G2t(),1),z2t=Fe(tKe(),1);import{createHash as Fsn}from"node:crypto";import*as jI from"node:os";var oe;(function(t){t[t.GEMINI_CLI_KEY_UNKNOWN=0]="GEMINI_CLI_KEY_UNKNOWN",t[t.GEMINI_CLI_START_SESSION_MODEL=1]="GEMINI_CLI_START_SESSION_MODEL",t[t.GEMINI_CLI_START_SESSION_EMBEDDING_MODEL=2]="GEMINI_CLI_START_SESSION_EMBEDDING_MODEL",t[t.GEMINI_CLI_START_SESSION_SANDBOX=3]="GEMINI_CLI_START_SESSION_SANDBOX",t[t.GEMINI_CLI_START_SESSION_CORE_TOOLS=4]="GEMINI_CLI_START_SESSION_CORE_TOOLS",t[t.GEMINI_CLI_START_SESSION_APPROVAL_MODE=5]="GEMINI_CLI_START_SESSION_APPROVAL_MODE",t[t.GEMINI_CLI_START_SESSION_API_KEY_ENABLED=6]="GEMINI_CLI_START_SESSION_API_KEY_ENABLED",t[t.GEMINI_CLI_START_SESSION_VERTEX_API_ENABLED=7]="GEMINI_CLI_START_SESSION_VERTEX_API_ENABLED",t[t.GEMINI_CLI_START_SESSION_DEBUG_MODE_ENABLED=8]="GEMINI_CLI_START_SESSION_DEBUG_MODE_ENABLED",t[t.GEMINI_CLI_START_SESSION_MCP_SERVERS=9]="GEMINI_CLI_START_SESSION_MCP_SERVERS",t[t.GEMINI_CLI_START_SESSION_TELEMETRY_ENABLED=10]="GEMINI_CLI_START_SESSION_TELEMETRY_ENABLED",t[t.GEMINI_CLI_START_SESSION_TELEMETRY_LOG_USER_PROMPTS_ENABLED=11]="GEMINI_CLI_START_SESSION_TELEMETRY_LOG_USER_PROMPTS_ENABLED",t[t.GEMINI_CLI_START_SESSION_RESPECT_GITIGNORE=12]="GEMINI_CLI_START_SESSION_RESPECT_GITIGNORE",t[t.GEMINI_CLI_START_SESSION_OUTPUT_FORMAT=94]="GEMINI_CLI_START_SESSION_OUTPUT_FORMAT",t[t.GEMINI_CLI_STARTUP_PHASES=172]="GEMINI_CLI_STARTUP_PHASES",t[t.GEMINI_CLI_STARTUP_OS_PLATFORM=173]="GEMINI_CLI_STARTUP_OS_PLATFORM",t[t.GEMINI_CLI_STARTUP_OS_RELEASE=174]="GEMINI_CLI_STARTUP_OS_RELEASE",t[t.GEMINI_CLI_STARTUP_IS_DOCKER=175]="GEMINI_CLI_STARTUP_IS_DOCKER",t[t.GEMINI_CLI_USER_PROMPT_LENGTH=13]="GEMINI_CLI_USER_PROMPT_LENGTH",t[t.GEMINI_CLI_TOOL_CALL_NAME=14]="GEMINI_CLI_TOOL_CALL_NAME",t[t.GEMINI_CLI_TOOL_CALL_MCP_SERVER_NAME=95]="GEMINI_CLI_TOOL_CALL_MCP_SERVER_NAME",t[t.GEMINI_CLI_TOOL_CALL_DECISION=15]="GEMINI_CLI_TOOL_CALL_DECISION",t[t.GEMINI_CLI_TOOL_CALL_SUCCESS=16]="GEMINI_CLI_TOOL_CALL_SUCCESS",t[t.GEMINI_CLI_TOOL_CALL_DURATION_MS=17]="GEMINI_CLI_TOOL_CALL_DURATION_MS",t[t.DEPRECATED_GEMINI_CLI_TOOL_ERROR_MESSAGE=18]="DEPRECATED_GEMINI_CLI_TOOL_ERROR_MESSAGE",t[t.GEMINI_CLI_TOOL_CALL_ERROR_TYPE=19]="GEMINI_CLI_TOOL_CALL_ERROR_TYPE",t[t.GEMINI_CLI_TOOL_CALL_CONTENT_LENGTH=93]="GEMINI_CLI_TOOL_CALL_CONTENT_LENGTH",t[t.GEMINI_CLI_EDIT_STRATEGY=109]="GEMINI_CLI_EDIT_STRATEGY",t[t.GEMINI_CLI_EDIT_CORRECTION=110]="GEMINI_CLI_EDIT_CORRECTION",t[t.GEMINI_CLI_WEB_FETCH_FALLBACK_REASON=116]="GEMINI_CLI_WEB_FETCH_FALLBACK_REASON",t[t.GEMINI_CLI_API_REQUEST_MODEL=20]="GEMINI_CLI_API_REQUEST_MODEL",t[t.GEMINI_CLI_API_RESPONSE_MODEL=21]="GEMINI_CLI_API_RESPONSE_MODEL",t[t.GEMINI_CLI_API_RESPONSE_STATUS_CODE=22]="GEMINI_CLI_API_RESPONSE_STATUS_CODE",t[t.GEMINI_CLI_API_RESPONSE_DURATION_MS=23]="GEMINI_CLI_API_RESPONSE_DURATION_MS",t[t.GEMINI_CLI_API_RESPONSE_INPUT_TOKEN_COUNT=25]="GEMINI_CLI_API_RESPONSE_INPUT_TOKEN_COUNT",t[t.GEMINI_CLI_API_RESPONSE_OUTPUT_TOKEN_COUNT=26]="GEMINI_CLI_API_RESPONSE_OUTPUT_TOKEN_COUNT",t[t.GEMINI_CLI_API_RESPONSE_CACHED_TOKEN_COUNT=27]="GEMINI_CLI_API_RESPONSE_CACHED_TOKEN_COUNT",t[t.GEMINI_CLI_API_RESPONSE_THINKING_TOKEN_COUNT=28]="GEMINI_CLI_API_RESPONSE_THINKING_TOKEN_COUNT",t[t.GEMINI_CLI_API_RESPONSE_TOOL_TOKEN_COUNT=29]="GEMINI_CLI_API_RESPONSE_TOOL_TOKEN_COUNT",t[t.GEMINI_CLI_API_RESPONSE_CONTEXT_BREAKDOWN_SYSTEM_INSTRUCTIONS=167]="GEMINI_CLI_API_RESPONSE_CONTEXT_BREAKDOWN_SYSTEM_INSTRUCTIONS",t[t.GEMINI_CLI_API_RESPONSE_CONTEXT_BREAKDOWN_TOOL_DEFINITIONS=168]="GEMINI_CLI_API_RESPONSE_CONTEXT_BREAKDOWN_TOOL_DEFINITIONS",t[t.GEMINI_CLI_API_RESPONSE_CONTEXT_BREAKDOWN_HISTORY=169]="GEMINI_CLI_API_RESPONSE_CONTEXT_BREAKDOWN_HISTORY",t[t.GEMINI_CLI_API_RESPONSE_CONTEXT_BREAKDOWN_TOOL_CALLS=170]="GEMINI_CLI_API_RESPONSE_CONTEXT_BREAKDOWN_TOOL_CALLS",t[t.GEMINI_CLI_API_RESPONSE_CONTEXT_BREAKDOWN_MCP_SERVERS=171]="GEMINI_CLI_API_RESPONSE_CONTEXT_BREAKDOWN_MCP_SERVERS",t[t.GEMINI_CLI_API_ERROR_MODEL=30]="GEMINI_CLI_API_ERROR_MODEL",t[t.GEMINI_CLI_API_ERROR_TYPE=31]="GEMINI_CLI_API_ERROR_TYPE",t[t.GEMINI_CLI_API_ERROR_STATUS_CODE=32]="GEMINI_CLI_API_ERROR_STATUS_CODE",t[t.GEMINI_CLI_API_ERROR_DURATION_MS=33]="GEMINI_CLI_API_ERROR_DURATION_MS",t[t.GEMINI_CLI_END_SESSION_ID=34]="GEMINI_CLI_END_SESSION_ID",t[t.GEMINI_CLI_PROMPT_ID=35]="GEMINI_CLI_PROMPT_ID",t[t.GEMINI_CLI_AUTH_TYPE=36]="GEMINI_CLI_AUTH_TYPE",t[t.GEMINI_CLI_GOOGLE_ACCOUNTS_COUNT=37]="GEMINI_CLI_GOOGLE_ACCOUNTS_COUNT",t[t.GEMINI_CLI_SURFACE=39]="GEMINI_CLI_SURFACE",t[t.GEMINI_CLI_SESSION_ID=40]="GEMINI_CLI_SESSION_ID",t[t.GEMINI_CLI_VERSION=54]="GEMINI_CLI_VERSION",t[t.GEMINI_CLI_GIT_COMMIT_HASH=55]="GEMINI_CLI_GIT_COMMIT_HASH",t[t.GEMINI_CLI_OS=82]="GEMINI_CLI_OS",t[t.GEMINI_CLI_USER_SETTINGS=84]="GEMINI_CLI_USER_SETTINGS",t[t.GEMINI_CLI_GH_WORKFLOW_NAME=130]="GEMINI_CLI_GH_WORKFLOW_NAME",t[t.GEMINI_CLI_EXPERIMENT_IDS=131]="GEMINI_CLI_EXPERIMENT_IDS",t[t.GEMINI_CLI_GH_REPOSITORY_NAME_HASH=132]="GEMINI_CLI_GH_REPOSITORY_NAME_HASH",t[t.GEMINI_CLI_GH_EVENT_NAME=176]="GEMINI_CLI_GH_EVENT_NAME",t[t.GEMINI_CLI_GH_PR_NUMBER=177]="GEMINI_CLI_GH_PR_NUMBER",t[t.GEMINI_CLI_GH_ISSUE_NUMBER=178]="GEMINI_CLI_GH_ISSUE_NUMBER",t[t.GEMINI_CLI_GH_CUSTOM_TRACKING_ID=179]="GEMINI_CLI_GH_CUSTOM_TRACKING_ID",t[t.GEMINI_CLI_LOOP_DETECTED_TYPE=38]="GEMINI_CLI_LOOP_DETECTED_TYPE",t[t.GEMINI_CLI_SLASH_COMMAND_NAME=41]="GEMINI_CLI_SLASH_COMMAND_NAME",t[t.GEMINI_CLI_SLASH_COMMAND_SUBCOMMAND=42]="GEMINI_CLI_SLASH_COMMAND_SUBCOMMAND",t[t.GEMINI_CLI_SLASH_COMMAND_STATUS=51]="GEMINI_CLI_SLASH_COMMAND_STATUS",t[t.GEMINI_CLI_RESPONSE_FINISH_REASON=43]="GEMINI_CLI_RESPONSE_FINISH_REASON",t[t.GEMINI_CLI_NEXT_SPEAKER_CHECK_RESULT=44]="GEMINI_CLI_NEXT_SPEAKER_CHECK_RESULT",t[t.GEMINI_CLI_MALFORMED_JSON_RESPONSE_MODEL=45]="GEMINI_CLI_MALFORMED_JSON_RESPONSE_MODEL",t[t.GEMINI_CLI_IDE_CONNECTION_TYPE=46]="GEMINI_CLI_IDE_CONNECTION_TYPE",t[t.GEMINI_CLI_AI_ADDED_LINES=47]="GEMINI_CLI_AI_ADDED_LINES",t[t.GEMINI_CLI_AI_REMOVED_LINES=48]="GEMINI_CLI_AI_REMOVED_LINES",t[t.GEMINI_CLI_USER_ADDED_LINES=49]="GEMINI_CLI_USER_ADDED_LINES",t[t.GEMINI_CLI_USER_REMOVED_LINES=50]="GEMINI_CLI_USER_REMOVED_LINES",t[t.GEMINI_CLI_AI_ADDED_CHARS=103]="GEMINI_CLI_AI_ADDED_CHARS",t[t.GEMINI_CLI_AI_REMOVED_CHARS=104]="GEMINI_CLI_AI_REMOVED_CHARS",t[t.GEMINI_CLI_USER_ADDED_CHARS=105]="GEMINI_CLI_USER_ADDED_CHARS",t[t.GEMINI_CLI_USER_REMOVED_CHARS=106]="GEMINI_CLI_USER_REMOVED_CHARS",t[t.DEPRECATED_GEMINI_CLI_KITTY_TRUNCATED_SEQUENCE=52]="DEPRECATED_GEMINI_CLI_KITTY_TRUNCATED_SEQUENCE",t[t.GEMINI_CLI_KITTY_SEQUENCE_LENGTH=53]="GEMINI_CLI_KITTY_SEQUENCE_LENGTH",t[t.GEMINI_CLI_APPROVAL_MODE=58]="GEMINI_CLI_APPROVAL_MODE",t[t.GEMINI_CLI_CONVERSATION_TURN_COUNT=59]="GEMINI_CLI_CONVERSATION_TURN_COUNT",t[t.GEMINI_CLI_COMPRESSION_TOKENS_BEFORE=60]="GEMINI_CLI_COMPRESSION_TOKENS_BEFORE",t[t.GEMINI_CLI_COMPRESSION_TOKENS_AFTER=61]="GEMINI_CLI_COMPRESSION_TOKENS_AFTER",t[t.GEMINI_CLI_TOOL_TYPE=62]="GEMINI_CLI_TOOL_TYPE",t[t.GEMINI_CLI_START_SESSION_MCP_SERVERS_COUNT=63]="GEMINI_CLI_START_SESSION_MCP_SERVERS_COUNT",t[t.GEMINI_CLI_START_SESSION_MCP_TOOLS_COUNT=64]="GEMINI_CLI_START_SESSION_MCP_TOOLS_COUNT",t[t.GEMINI_CLI_START_SESSION_MCP_TOOLS=65]="GEMINI_CLI_START_SESSION_MCP_TOOLS",t[t.GEMINI_CLI_RESEARCH_OPT_IN_STATUS=66]="GEMINI_CLI_RESEARCH_OPT_IN_STATUS",t[t.GEMINI_CLI_RESEARCH_CONTACT_EMAIL=67]="GEMINI_CLI_RESEARCH_CONTACT_EMAIL",t[t.GEMINI_CLI_RESEARCH_USER_ID=68]="GEMINI_CLI_RESEARCH_USER_ID",t[t.GEMINI_CLI_RESEARCH_FEEDBACK_TYPE=69]="GEMINI_CLI_RESEARCH_FEEDBACK_TYPE",t[t.GEMINI_CLI_RESEARCH_FEEDBACK_CONTENT=70]="GEMINI_CLI_RESEARCH_FEEDBACK_CONTENT",t[t.GEMINI_CLI_RESEARCH_SURVEY_RESPONSES=71]="GEMINI_CLI_RESEARCH_SURVEY_RESPONSES",t[t.GEMINI_CLI_PROGRAMMING_LANGUAGE=56]="GEMINI_CLI_PROGRAMMING_LANGUAGE",t[t.GEMINI_CLI_FILE_OPERATION_TYPE=57]="GEMINI_CLI_FILE_OPERATION_TYPE",t[t.GEMINI_CLI_FILE_OPERATION_LINES=72]="GEMINI_CLI_FILE_OPERATION_LINES",t[t.GEMINI_CLI_FILE_OPERATION_MIMETYPE=73]="GEMINI_CLI_FILE_OPERATION_MIMETYPE",t[t.GEMINI_CLI_FILE_OPERATION_EXTENSION=74]="GEMINI_CLI_FILE_OPERATION_EXTENSION",t[t.GEMINI_CLI_INVALID_CHUNK_ERROR_MESSAGE=75]="GEMINI_CLI_INVALID_CHUNK_ERROR_MESSAGE",t[t.GEMINI_CLI_CONTENT_RETRY_ATTEMPT_NUMBER=76]="GEMINI_CLI_CONTENT_RETRY_ATTEMPT_NUMBER",t[t.GEMINI_CLI_CONTENT_RETRY_ERROR_TYPE=77]="GEMINI_CLI_CONTENT_RETRY_ERROR_TYPE",t[t.GEMINI_CLI_CONTENT_RETRY_DELAY_MS=78]="GEMINI_CLI_CONTENT_RETRY_DELAY_MS",t[t.GEMINI_CLI_CONTENT_RETRY_FAILURE_TOTAL_ATTEMPTS=79]="GEMINI_CLI_CONTENT_RETRY_FAILURE_TOTAL_ATTEMPTS",t[t.GEMINI_CLI_CONTENT_RETRY_FAILURE_FINAL_ERROR_TYPE=80]="GEMINI_CLI_CONTENT_RETRY_FAILURE_FINAL_ERROR_TYPE",t[t.GEMINI_CLI_CONTENT_RETRY_FAILURE_TOTAL_DURATION_MS=81]="GEMINI_CLI_CONTENT_RETRY_FAILURE_TOTAL_DURATION_MS",t[t.GEMINI_CLI_NODE_VERSION=83]="GEMINI_CLI_NODE_VERSION",t[t.GEMINI_CLI_EXTENSION_NAME=85]="GEMINI_CLI_EXTENSION_NAME",t[t.GEMINI_CLI_EXTENSION_ID=121]="GEMINI_CLI_EXTENSION_ID",t[t.GEMINI_CLI_EXTENSION_VERSION=86]="GEMINI_CLI_EXTENSION_VERSION",t[t.GEMINI_CLI_EXTENSION_PREVIOUS_VERSION=117]="GEMINI_CLI_EXTENSION_PREVIOUS_VERSION",t[t.GEMINI_CLI_EXTENSION_SOURCE=87]="GEMINI_CLI_EXTENSION_SOURCE",t[t.GEMINI_CLI_EXTENSION_INSTALL_STATUS=88]="GEMINI_CLI_EXTENSION_INSTALL_STATUS",t[t.GEMINI_CLI_EXTENSION_UNINSTALL_STATUS=96]="GEMINI_CLI_EXTENSION_UNINSTALL_STATUS",t[t.GEMINI_CLI_EXTENSION_UPDATE_STATUS=118]="GEMINI_CLI_EXTENSION_UPDATE_STATUS",t[t.GEMINI_CLI_START_SESSION_EXTENSIONS_COUNT=119]="GEMINI_CLI_START_SESSION_EXTENSIONS_COUNT",t[t.GEMINI_CLI_START_SESSION_EXTENSION_IDS=120]="GEMINI_CLI_START_SESSION_EXTENSION_IDS",t[t.GEMINI_CLI_START_SESSION_WORKTREE_ACTIVE=191]="GEMINI_CLI_START_SESSION_WORKTREE_ACTIVE",t[t.GEMINI_CLI_EXTENSION_ENABLE_SETTING_SCOPE=102]="GEMINI_CLI_EXTENSION_ENABLE_SETTING_SCOPE",t[t.GEMINI_CLI_EXTENSION_DISABLE_SETTING_SCOPE=107]="GEMINI_CLI_EXTENSION_DISABLE_SETTING_SCOPE",t[t.GEMINI_CLI_TOOL_OUTPUT_TRUNCATED_ORIGINAL_LENGTH=89]="GEMINI_CLI_TOOL_OUTPUT_TRUNCATED_ORIGINAL_LENGTH",t[t.GEMINI_CLI_TOOL_OUTPUT_TRUNCATED_TRUNCATED_LENGTH=90]="GEMINI_CLI_TOOL_OUTPUT_TRUNCATED_TRUNCATED_LENGTH",t[t.GEMINI_CLI_TOOL_OUTPUT_TRUNCATED_THRESHOLD=91]="GEMINI_CLI_TOOL_OUTPUT_TRUNCATED_THRESHOLD",t[t.GEMINI_CLI_TOOL_OUTPUT_TRUNCATED_LINES=92]="GEMINI_CLI_TOOL_OUTPUT_TRUNCATED_LINES",t[t.GEMINI_CLI_ROUTING_DECISION=97]="GEMINI_CLI_ROUTING_DECISION",t[t.GEMINI_CLI_ROUTING_FAILURE=98]="GEMINI_CLI_ROUTING_FAILURE",t[t.GEMINI_CLI_ROUTING_LATENCY_MS=99]="GEMINI_CLI_ROUTING_LATENCY_MS",t[t.GEMINI_CLI_ROUTING_FAILURE_REASON=100]="GEMINI_CLI_ROUTING_FAILURE_REASON",t[t.GEMINI_CLI_ROUTING_DECISION_SOURCE=101]="GEMINI_CLI_ROUTING_DECISION_SOURCE",t[t.GEMINI_CLI_MODEL_SLASH_COMMAND=108]="GEMINI_CLI_MODEL_SLASH_COMMAND",t[t.GEMINI_CLI_AGENT_NAME=111]="GEMINI_CLI_AGENT_NAME",t[t.GEMINI_CLI_AGENT_ID=112]="GEMINI_CLI_AGENT_ID",t[t.GEMINI_CLI_AGENT_DURATION_MS=113]="GEMINI_CLI_AGENT_DURATION_MS",t[t.GEMINI_CLI_AGENT_TURN_COUNT=114]="GEMINI_CLI_AGENT_TURN_COUNT",t[t.GEMINI_CLI_AGENT_TERMINATE_REASON=115]="GEMINI_CLI_AGENT_TERMINATE_REASON",t[t.GEMINI_CLI_AGENT_RECOVERY_REASON=122]="GEMINI_CLI_AGENT_RECOVERY_REASON",t[t.GEMINI_CLI_AGENT_RECOVERY_DURATION_MS=123]="GEMINI_CLI_AGENT_RECOVERY_DURATION_MS",t[t.GEMINI_CLI_AGENT_RECOVERY_SUCCESS=124]="GEMINI_CLI_AGENT_RECOVERY_SUCCESS",t[t.GEMINI_CLI_INTERACTIVE=125]="GEMINI_CLI_INTERACTIVE",t[t.GEMINI_CLI_LLM_LOOP_CHECK_FLASH_CONFIDENCE=126]="GEMINI_CLI_LLM_LOOP_CHECK_FLASH_CONFIDENCE",t[t.GEMINI_CLI_LLM_LOOP_CHECK_MAIN_MODEL=127]="GEMINI_CLI_LLM_LOOP_CHECK_MAIN_MODEL",t[t.GEMINI_CLI_LLM_LOOP_CHECK_MAIN_MODEL_CONFIDENCE=128]="GEMINI_CLI_LLM_LOOP_CHECK_MAIN_MODEL_CONFIDENCE",t[t.GEMINI_CLI_LOOP_DETECTED_CONFIRMED_BY_MODEL=129]="GEMINI_CLI_LOOP_DETECTED_CONFIRMED_BY_MODEL",t[t.GEMINI_CLI_HOOK_EVENT_NAME=133]="GEMINI_CLI_HOOK_EVENT_NAME",t[t.GEMINI_CLI_HOOK_DURATION_MS=134]="GEMINI_CLI_HOOK_DURATION_MS",t[t.GEMINI_CLI_HOOK_SUCCESS=135]="GEMINI_CLI_HOOK_SUCCESS",t[t.GEMINI_CLI_HOOK_EXIT_CODE=136]="GEMINI_CLI_HOOK_EXIT_CODE",t[t.GEMINI_CLI_CPU_INFO=137]="GEMINI_CLI_CPU_INFO",t[t.GEMINI_CLI_CPU_CORES=138]="GEMINI_CLI_CPU_CORES",t[t.GEMINI_CLI_GPU_INFO=139]="GEMINI_CLI_GPU_INFO",t[t.GEMINI_CLI_RAM_TOTAL_GB=140]="GEMINI_CLI_RAM_TOTAL_GB",t[t.GEMINI_CLI_ACTIVE_APPROVAL_MODE=141]="GEMINI_CLI_ACTIVE_APPROVAL_MODE",t[t.GEMINI_CLI_APPROVAL_MODE_TO=142]="GEMINI_CLI_APPROVAL_MODE_TO",t[t.GEMINI_CLI_APPROVAL_MODE_DURATION_MS=143]="GEMINI_CLI_APPROVAL_MODE_DURATION_MS",t[t.GEMINI_CLI_REWIND_OUTCOME=144]="GEMINI_CLI_REWIND_OUTCOME",t[t.GEMINI_CLI_ROUTING_REASONING=145]="GEMINI_CLI_ROUTING_REASONING",t[t.GEMINI_CLI_ROUTING_NUMERICAL_ENABLED=146]="GEMINI_CLI_ROUTING_NUMERICAL_ENABLED",t[t.GEMINI_CLI_ROUTING_CLASSIFIER_THRESHOLD=147]="GEMINI_CLI_ROUTING_CLASSIFIER_THRESHOLD",t[t.GEMINI_CLI_TOOL_OUTPUT_MASKING_TOKENS_BEFORE=148]="GEMINI_CLI_TOOL_OUTPUT_MASKING_TOKENS_BEFORE",t[t.GEMINI_CLI_TOOL_OUTPUT_MASKING_TOKENS_AFTER=149]="GEMINI_CLI_TOOL_OUTPUT_MASKING_TOKENS_AFTER",t[t.GEMINI_CLI_TOOL_OUTPUT_MASKING_MASKED_COUNT=150]="GEMINI_CLI_TOOL_OUTPUT_MASKING_MASKED_COUNT",t[t.GEMINI_CLI_TOOL_OUTPUT_MASKING_TOTAL_PRUNABLE_TOKENS=151]="GEMINI_CLI_TOOL_OUTPUT_MASKING_TOTAL_PRUNABLE_TOKENS",t[t.GEMINI_CLI_ASK_USER_QUESTION_TYPES=152]="GEMINI_CLI_ASK_USER_QUESTION_TYPES",t[t.GEMINI_CLI_ASK_USER_DISMISSED=153]="GEMINI_CLI_ASK_USER_DISMISSED",t[t.GEMINI_CLI_ASK_USER_EMPTY_SUBMISSION=154]="GEMINI_CLI_ASK_USER_EMPTY_SUBMISSION",t[t.GEMINI_CLI_ASK_USER_ANSWER_COUNT=155]="GEMINI_CLI_ASK_USER_ANSWER_COUNT",t[t.GEMINI_CLI_KEYCHAIN_AVAILABLE=156]="GEMINI_CLI_KEYCHAIN_AVAILABLE",t[t.GEMINI_CLI_TOKEN_STORAGE_TYPE=157]="GEMINI_CLI_TOKEN_STORAGE_TYPE",t[t.GEMINI_CLI_TOKEN_STORAGE_FORCED=158]="GEMINI_CLI_TOKEN_STORAGE_FORCED",t[t.CONSECA_POLICY_GENERATION=159]="CONSECA_POLICY_GENERATION",t[t.CONSECA_VERDICT=160]="CONSECA_VERDICT",t[t.CONSECA_GENERATED_POLICY=161]="CONSECA_GENERATED_POLICY",t[t.CONSECA_VERDICT_RESULT=162]="CONSECA_VERDICT_RESULT",t[t.CONSECA_VERDICT_RATIONALE=163]="CONSECA_VERDICT_RATIONALE",t[t.CONSECA_TRUSTED_CONTENT=164]="CONSECA_TRUSTED_CONTENT",t[t.CONSECA_USER_PROMPT=165]="CONSECA_USER_PROMPT",t[t.CONSECA_ERROR=166]="CONSECA_ERROR",t[t.GEMINI_CLI_NETWORK_RETRY_ATTEMPT_NUMBER=180]="GEMINI_CLI_NETWORK_RETRY_ATTEMPT_NUMBER",t[t.GEMINI_CLI_NETWORK_RETRY_DELAY_MS=181]="GEMINI_CLI_NETWORK_RETRY_DELAY_MS",t[t.GEMINI_CLI_NETWORK_RETRY_ERROR_TYPE=182]="GEMINI_CLI_NETWORK_RETRY_ERROR_TYPE",t[t.GEMINI_CLI_BILLING_MODEL=185]="GEMINI_CLI_BILLING_MODEL",t[t.GEMINI_CLI_BILLING_CREDITS_CONSUMED=186]="GEMINI_CLI_BILLING_CREDITS_CONSUMED",t[t.GEMINI_CLI_BILLING_CREDITS_REMAINING=187]="GEMINI_CLI_BILLING_CREDITS_REMAINING",t[t.GEMINI_CLI_BILLING_SELECTED_OPTION=188]="GEMINI_CLI_BILLING_SELECTED_OPTION",t[t.GEMINI_CLI_BILLING_CREDIT_BALANCE=189]="GEMINI_CLI_BILLING_CREDIT_BALANCE",t[t.GEMINI_CLI_BILLING_PURCHASE_SOURCE=190]="GEMINI_CLI_BILLING_PURCHASE_SOURCE",t[t.GEMINI_CLI_ONBOARDING_START=192]="GEMINI_CLI_ONBOARDING_START",t[t.GEMINI_CLI_ONBOARDING_USER_TIER=193]="GEMINI_CLI_ONBOARDING_USER_TIER",t[t.GEMINI_CLI_ONBOARDING_DURATION_MS=194]="GEMINI_CLI_ONBOARDING_DURATION_MS",t[t.GEMINI_CLI_BROWSER_AGENT_SESSION_MODE=195]="GEMINI_CLI_BROWSER_AGENT_SESSION_MODE",t[t.GEMINI_CLI_BROWSER_AGENT_HEADLESS=196]="GEMINI_CLI_BROWSER_AGENT_HEADLESS",t[t.GEMINI_CLI_BROWSER_AGENT_SUCCESS=197]="GEMINI_CLI_BROWSER_AGENT_SUCCESS",t[t.GEMINI_CLI_BROWSER_AGENT_ERROR_TYPE=198]="GEMINI_CLI_BROWSER_AGENT_ERROR_TYPE",t[t.GEMINI_CLI_BROWSER_AGENT_DURATION_MS=199]="GEMINI_CLI_BROWSER_AGENT_DURATION_MS",t[t.GEMINI_CLI_BROWSER_AGENT_VISION_ENABLED=200]="GEMINI_CLI_BROWSER_AGENT_VISION_ENABLED",t[t.GEMINI_CLI_BROWSER_AGENT_VISION_DISABLED_REASON=201]="GEMINI_CLI_BROWSER_AGENT_VISION_DISABLED_REASON",t[t.GEMINI_CLI_BROWSER_AGENT_TOOL_COUNT=202]="GEMINI_CLI_BROWSER_AGENT_TOOL_COUNT"})(oe||(oe={}));var $2t="135b8a5",q2t="0.43.0";var Hr={devin:{name:"devin",displayName:"Devin"},replit:{name:"replit",displayName:"Replit"},cursor:{name:"cursor",displayName:"Cursor"},cloudshell:{name:"cloudshell",displayName:"Cloud Shell"},codespaces:{name:"codespaces",displayName:"GitHub Codespaces"},firebasestudio:{name:"firebasestudio",displayName:"Firebase Studio"},trae:{name:"trae",displayName:"Trae"},vscode:{name:"vscode",displayName:"VS Code"},vscodefork:{name:"vscodefork",displayName:"IDE"},positron:{name:"positron",displayName:"Positron"},antigravity:{name:"antigravity",displayName:"Antigravity"},sublimetext:{name:"sublimetext",displayName:"Sublime Text"},jetbrains:{name:"jetbrains",displayName:"JetBrains IDE"},intellijidea:{name:"intellijidea",displayName:"IntelliJ IDEA"},webstorm:{name:"webstorm",displayName:"WebStorm"},pycharm:{name:"pycharm",displayName:"PyCharm"},goland:{name:"goland",displayName:"GoLand"},androidstudio:{name:"androidstudio",displayName:"Android Studio"},clion:{name:"clion",displayName:"CLion"},rustrover:{name:"rustrover",displayName:"RustRover"},datagrip:{name:"datagrip",displayName:"DataGrip"},phpstorm:{name:"phpstorm",displayName:"PhpStorm"},zed:{name:"zed",displayName:"Zed"},xcode:{name:"xcode",displayName:"XCode"}};function UI(){return!!(process.env.EDITOR_IN_CLOUD_SHELL||process.env.CLOUD_SHELL)}function SIe(){return!!process.env.TERMINAL_EMULATOR?.toLowerCase().includes("jetbrains")}function FI(){return process.env.ANTIGRAVITY_CLI_ALIAS?Hr.antigravity:process.env.__COG_BASHRC_SOURCED?Hr.devin:process.env.REPLIT_USER?Hr.replit:process.env.CURSOR_TRACE_ID?Hr.cursor:process.env.CODESPACES?Hr.codespaces:UI()?Hr.cloudshell:process.env.TERM_PRODUCT==="Trae"?Hr.trae:process.env.MONOSPACE_ENV?Hr.firebasestudio:process.env.POSITRON==="1"?Hr.positron:process.env.TERM_PROGRAM==="sublime"?Hr.sublimetext:process.env.ZED_SESSION_ID||process.env.TERM_PROGRAM==="Zed"?Hr.zed:process.env.XCODE_VERSION_ACTUAL?Hr.xcode:SIe()?Hr.jetbrains:Hr.vscode}function Bsn(t,e){return t.name!==Hr.vscode.name?t:!e.command||e.command.toLowerCase().includes("code")?Hr.vscode:Hr.vscodefork}function Usn(t,e){if(t.name!==Hr.jetbrains.name||!e.command)return t;let r=e.command.toLowerCase(),n=[["idea",Hr.intellijidea],["webstorm",Hr.webstorm],["pycharm",Hr.pycharm],["goland",Hr.goland],["studio",Hr.androidstudio],["clion",Hr.clion],["rustrover",Hr.rustrover],["datagrip",Hr.datagrip],["phpstorm",Hr.phpstorm]];for(let[o,s]of n)if(r.includes(o))return s;return t}function V2t(t,e){if(e?.name&&e.displayName)return{name:e.name,displayName:e.displayName};if(process.env.TERM_PROGRAM!=="vscode"&&process.env.TERM_PROGRAM!=="sublime"&&process.env.TERM_PROGRAM!=="Zed"&&!process.env.ZED_SESSION_ID&&!process.env.XCODE_VERSION_ACTUAL&&!SIe())return;let r=FI();return SIe()?Usn(r,t):Bsn(r,t)}var gt;(function(t){t.START_SESSION="start_session",t.NEW_PROMPT="new_prompt",t.TOOL_CALL="tool_call",t.FILE_OPERATION="file_operation",t.API_REQUEST="api_request",t.API_RESPONSE="api_response",t.API_ERROR="api_error",t.END_SESSION="end_session",t.FLASH_FALLBACK="flash_fallback",t.RIPGREP_FALLBACK="ripgrep_fallback",t.LOOP_DETECTED="loop_detected",t.LOOP_DETECTION_DISABLED="loop_detection_disabled",t.NEXT_SPEAKER_CHECK="next_speaker_check",t.SLASH_COMMAND="slash_command",t.REWIND="rewind",t.MALFORMED_JSON_RESPONSE="malformed_json_response",t.IDE_CONNECTION="ide_connection",t.KITTY_SEQUENCE_OVERFLOW="kitty_sequence_overflow",t.CHAT_COMPRESSION="chat_compression",t.CONVERSATION_FINISHED="conversation_finished",t.INVALID_CHUNK="invalid_chunk",t.CONTENT_RETRY="content_retry",t.CONTENT_RETRY_FAILURE="content_retry_failure",t.RETRY_ATTEMPT="retry_attempt",t.EXTENSION_ENABLE="extension_enable",t.EXTENSION_DISABLE="extension_disable",t.EXTENSION_INSTALL="extension_install",t.EXTENSION_UNINSTALL="extension_uninstall",t.EXTENSION_UPDATE="extension_update",t.TOOL_OUTPUT_TRUNCATED="tool_output_truncated",t.MODEL_ROUTING="model_routing",t.MODEL_SLASH_COMMAND="model_slash_command",t.EDIT_STRATEGY="edit_strategy",t.EDIT_CORRECTION="edit_correction",t.AGENT_START="agent_start",t.AGENT_FINISH="agent_finish",t.RECOVERY_ATTEMPT="recovery_attempt",t.WEB_FETCH_FALLBACK_ATTEMPT="web_fetch_fallback_attempt",t.LLM_LOOP_CHECK="llm_loop_check",t.HOOK_CALL="hook_call",t.APPROVAL_MODE_SWITCH="approval_mode_switch",t.APPROVAL_MODE_DURATION="approval_mode_duration",t.PLAN_EXECUTION="plan_execution",t.TOOL_OUTPUT_MASKING="tool_output_masking",t.KEYCHAIN_AVAILABILITY="keychain_availability",t.TOKEN_STORAGE_INITIALIZATION="token_storage_initialization",t.ONBOARDING_START="onboarding_start",t.ONBOARDING_SUCCESS="onboarding_success",t.CONSECA_POLICY_GENERATION="conseca_policy_generation",t.CONSECA_VERDICT="conseca_verdict",t.STARTUP_STATS="startup_stats",t.CREDITS_USED="credits_used",t.OVERAGE_OPTION_SELECTED="overage_option_selected",t.EMPTY_WALLET_MENU_SHOWN="empty_wallet_menu_shown",t.CREDIT_PURCHASE_CLICK="credit_purchase_click",t.BROWSER_AGENT_CONNECTION="browser_agent_connection",t.BROWSER_AGENT_VISION_STATUS="browser_agent_vision_status",t.BROWSER_AGENT_TASK_OUTCOME="browser_agent_task_outcome",t.BROWSER_AGENT_CLEANUP="browser_agent_cleanup"})(gt||(gt={}));function jsn(){return process.env.SURFACE?process.env.SURFACE:UI()?Hr.cloudshell.name:process.env.GITHUB_SHA?"GitHub":process.env.TERM_PROGRAM==="vscode"?FI().name||Hr.vscode.name:"SURFACE_NOT_SET"}function Qsn(){return process.env.GH_WORKFLOW_NAME}function Gsn(){return process.env.GITHUB_REPOSITORY}function $sn(){return process.env.GITHUB_EVENT_NAME}function qsn(){return process.env.GH_PR_NUMBER}function Vsn(){return process.env.GH_ISSUE_NUMBER}function Hsn(){return process.env.GH_CUSTOM_TRACKING_ID}var zsn="https://play.googleapis.com/log?format=json&hasfast=true",Wsn=1e3*60,yZ=1e3,AZ=100,W2t="NA",I4;async function Ysn(){try{let t=await H2t.default.graphics();t.controllers&&t.controllers.length>0?I4=t.controllers.map(e=>e.model).join(", "):I4=W2t}catch(t){I4="FAILED",B.error("Failed to get GPU information for telemetry",Se(t))}}async function Jsn(){return I4||await Ysn(),I4??W2t}var St=class t{static instance;config;sessionData=[];promptId="";installationManager;userAccountManager;hashedGHRepositoryName;events;lastFlushTime=Date.now();flushing=!1;pendingFlush=!1;constructor(e){this.config=e,this.events=new Wme.default(Array,yZ),this.promptId=e?.getSessionId()??"",this.installationManager=new A_,this.userAccountManager=new y_;let r=Gsn();r&&(this.hashedGHRepositoryName=Fsn("sha256").update(r).digest("hex"))}static getInstance(e){if(!(e===void 0||!e?.getUsageStatisticsEnabled()))return t.instance||(t.instance=new t(e)),t.instance}static clearInstance(){t.instance=void 0}enqueueHelper(e,r){let n=this.events.size>=yZ;n&&this.events.shift();let o={event_time_ms:Date.now(),source_extension_json:Lr(e)};r!==void 0&&(o.exp={gws_experiment:r}),this.events.push([o]),n&&this.config?.getDebugMode()&&B.debug(`ClearcutLogger: Dropped old event to prevent memory leak (queue size: ${this.events.size})`)}enqueueLogEvent(e){try{this.enqueueHelper(e)}catch(r){this.config?.getDebugMode()&&B.warn("ClearcutLogger: Failed to enqueue log event.",r)}}async enqueueLogEventAfterExperimentsLoadAsync(e){try{this.config?.getExperimentsAsync().then(r=>{if(r){let n=[{gemini_cli_key:oe.GEMINI_CLI_EXPERIMENT_IDS,value:r.experimentIds.toString()??"NA"}];e.event_metadata=[[...e.event_metadata[0],...n]]}this.enqueueHelper(e,r?.experimentIds)})}catch(r){B.warn("ClearcutLogger: Failed to enqueue log event.",r)}}createBasicLogEvent(e,r=[]){let n=this.userAccountManager.getCachedGoogleAccount(),o=jsn(),s=Qsn(),c=$sn(),u=qsn(),d=Vsn(),l=Hsn(),a=[...r,{gemini_cli_key:oe.GEMINI_CLI_SURFACE,value:o},{gemini_cli_key:oe.GEMINI_CLI_VERSION,value:q2t},{gemini_cli_key:oe.GEMINI_CLI_GIT_COMMIT_HASH,value:$2t},{gemini_cli_key:oe.GEMINI_CLI_OS,value:process.platform}];s&&a.push({gemini_cli_key:oe.GEMINI_CLI_GH_WORKFLOW_NAME,value:s}),this.hashedGHRepositoryName&&a.push({gemini_cli_key:oe.GEMINI_CLI_GH_REPOSITORY_NAME_HASH,value:this.hashedGHRepositoryName}),c&&a.push({gemini_cli_key:oe.GEMINI_CLI_GH_EVENT_NAME,value:c}),u&&a.push({gemini_cli_key:oe.GEMINI_CLI_GH_PR_NUMBER,value:u}),d&&a.push({gemini_cli_key:oe.GEMINI_CLI_GH_ISSUE_NUMBER,value:d}),l&&a.push({gemini_cli_key:oe.GEMINI_CLI_GH_CUSTOM_TRACKING_ID,value:l});let p={console_type:"GEMINI_CLI",application:102,event_name:e,event_metadata:[a]};return n?p.client_email=n:p.client_install_id=this.installationManager.getInstallationId(),p}createLogEvent(e,r=[]){e!==gt.START_SESSION&&r.push(...this.sessionData);let n=this.userAccountManager.getLifetimeGoogleAccounts();return r=this.addDefaultFields(r,n),this.createBasicLogEvent(e,r)}flushIfNeeded(){Date.now()-this.lastFlushTime<Wsn||this.flushToClearcut().catch(e=>{B.debug("Error flushing to Clearcut:",e)})}async flushToClearcut(){if(this.flushing)return this.config?.getDebugMode()&&B.debug("ClearcutLogger: Flush already in progress, marking pending flush."),this.pendingFlush=!0,Promise.resolve({});this.flushing=!0,this.config?.getDebugMode()&&B.log("Flushing log events to Clearcut.");let e=this.events.toArray();this.events.clear();let r=[{log_source_name:"CONCORD",request_time_ms:Date.now(),log_event:e}],n={};try{let o=await fetch(zsn,{method:"POST",body:Lr(r),headers:{"Content-Type":"application/json"}}),s=await o.text();if(o.status>=200&&o.status<300){this.lastFlushTime=Date.now();let c=Number(JSON.parse(s)[0]);n={...n,nextRequestWaitMs:c}}else this.config?.getDebugMode()&&B.warn(`Error flushing log events: HTTP ${o.status}: ${o.statusText}`),this.requeueFailedEvents(e)}catch(o){this.config?.getDebugMode()&&B.warn("Error flushing log events:",o),this.requeueFailedEvents(e)}return this.flushing=!1,this.pendingFlush&&(this.pendingFlush=!1,this.flushToClearcut().catch(o=>{this.config?.getDebugMode()&&B.debug("Error in pending flush to Clearcut:",o)})),n}async logStartSessionEvent(e){let r=[{gemini_cli_key:oe.GEMINI_CLI_START_SESSION_MODEL,value:e.model},{gemini_cli_key:oe.GEMINI_CLI_START_SESSION_EMBEDDING_MODEL,value:e.embedding_model},{gemini_cli_key:oe.GEMINI_CLI_START_SESSION_SANDBOX,value:e.sandbox_enabled.toString()},{gemini_cli_key:oe.GEMINI_CLI_START_SESSION_CORE_TOOLS,value:e.core_tools_enabled},{gemini_cli_key:oe.GEMINI_CLI_START_SESSION_APPROVAL_MODE,value:e.approval_mode},{gemini_cli_key:oe.GEMINI_CLI_START_SESSION_API_KEY_ENABLED,value:e.api_key_enabled.toString()},{gemini_cli_key:oe.GEMINI_CLI_START_SESSION_VERTEX_API_ENABLED,value:e.vertex_ai_enabled.toString()},{gemini_cli_key:oe.GEMINI_CLI_START_SESSION_DEBUG_MODE_ENABLED,value:e.debug_enabled.toString()},{gemini_cli_key:oe.GEMINI_CLI_START_SESSION_VERTEX_API_ENABLED,value:e.vertex_ai_enabled.toString()},{gemini_cli_key:oe.GEMINI_CLI_START_SESSION_MCP_SERVERS,value:e.mcp_servers},{gemini_cli_key:oe.GEMINI_CLI_START_SESSION_VERTEX_API_ENABLED,value:e.vertex_ai_enabled.toString()},{gemini_cli_key:oe.GEMINI_CLI_START_SESSION_TELEMETRY_ENABLED,value:e.telemetry_enabled.toString()},{gemini_cli_key:oe.GEMINI_CLI_START_SESSION_TELEMETRY_LOG_USER_PROMPTS_ENABLED,value:e.telemetry_log_user_prompts_enabled.toString()},{gemini_cli_key:oe.GEMINI_CLI_START_SESSION_MCP_SERVERS_COUNT,value:e.mcp_servers_count?e.mcp_servers_count.toString():""},{gemini_cli_key:oe.GEMINI_CLI_START_SESSION_MCP_TOOLS_COUNT,value:e.mcp_tools_count?.toString()??""},{gemini_cli_key:oe.GEMINI_CLI_START_SESSION_MCP_TOOLS,value:e.mcp_tools?e.mcp_tools:""},{gemini_cli_key:oe.GEMINI_CLI_START_SESSION_EXTENSIONS_COUNT,value:e.extensions_count.toString()},{gemini_cli_key:oe.GEMINI_CLI_START_SESSION_EXTENSION_IDS,value:e.extension_ids.toString()},{gemini_cli_key:oe.GEMINI_CLI_START_SESSION_WORKTREE_ACTIVE,value:e.worktree_active.toString()}],n=jI.cpus();n&&n.length>0&&r.push({gemini_cli_key:oe.GEMINI_CLI_CPU_INFO,value:n[0].model}),r.push({gemini_cli_key:oe.GEMINI_CLI_CPU_CORES,value:jI.availableParallelism().toString()},{gemini_cli_key:oe.GEMINI_CLI_RAM_TOTAL_GB,value:(jI.totalmem()/1024**3).toFixed(2).toString()});let o=await Jsn();r.push({gemini_cli_key:oe.GEMINI_CLI_GPU_INFO,value:o}),this.sessionData=r,this.enqueueLogEventAfterExperimentsLoadAsync(this.createLogEvent(gt.START_SESSION,r)).then(()=>{this.flushToClearcut().catch(s=>{B.debug("Error flushing to Clearcut:",s)})})}logNewPromptEvent(e){this.promptId=e.prompt_id;let r=[{gemini_cli_key:oe.GEMINI_CLI_USER_PROMPT_LENGTH,value:JSON.stringify(e.prompt_length)}];this.enqueueLogEvent(this.createLogEvent(gt.NEW_PROMPT,r)),this.flushIfNeeded()}logToolCallEvent(e){let r=[{gemini_cli_key:oe.GEMINI_CLI_TOOL_CALL_NAME,value:JSON.stringify(e.function_name)},{gemini_cli_key:oe.GEMINI_CLI_TOOL_CALL_DECISION,value:JSON.stringify(e.decision)},{gemini_cli_key:oe.GEMINI_CLI_TOOL_CALL_SUCCESS,value:JSON.stringify(e.success)},{gemini_cli_key:oe.GEMINI_CLI_TOOL_CALL_DURATION_MS,value:JSON.stringify(e.duration_ms)},{gemini_cli_key:oe.GEMINI_CLI_TOOL_CALL_ERROR_TYPE,value:JSON.stringify(e.error_type)},{gemini_cli_key:oe.GEMINI_CLI_TOOL_TYPE,value:JSON.stringify(e.tool_type)},{gemini_cli_key:oe.GEMINI_CLI_TOOL_CALL_CONTENT_LENGTH,value:JSON.stringify(e.content_length)},{gemini_cli_key:oe.GEMINI_CLI_TOOL_CALL_MCP_SERVER_NAME,value:JSON.stringify(e.mcp_server_name)}];if(e.metadata){let o={model_added_lines:oe.GEMINI_CLI_AI_ADDED_LINES,model_removed_lines:oe.GEMINI_CLI_AI_REMOVED_LINES,model_added_chars:oe.GEMINI_CLI_AI_ADDED_CHARS,model_removed_chars:oe.GEMINI_CLI_AI_REMOVED_CHARS,user_added_lines:oe.GEMINI_CLI_USER_ADDED_LINES,user_removed_lines:oe.GEMINI_CLI_USER_REMOVED_LINES,user_added_chars:oe.GEMINI_CLI_USER_ADDED_CHARS,user_removed_chars:oe.GEMINI_CLI_USER_REMOVED_CHARS};if(e.function_name===bs&&e.metadata.ask_user){let s=e.metadata.ask_user,c={question_types:oe.GEMINI_CLI_ASK_USER_QUESTION_TYPES,dismissed:oe.GEMINI_CLI_ASK_USER_DISMISSED,empty_submission:oe.GEMINI_CLI_ASK_USER_EMPTY_SUBMISSION,answer_count:oe.GEMINI_CLI_ASK_USER_ANSWER_COUNT};for(let[u,d]of Object.entries(c))s[u]!==void 0&&r.push({gemini_cli_key:d,value:JSON.stringify(s[u])})}for(let[s,c]of Object.entries(o))e.metadata[s]!==void 0&&r.push({gemini_cli_key:c,value:JSON.stringify(e.metadata[s])})}e.extension_id&&r.push({gemini_cli_key:oe.GEMINI_CLI_EXTENSION_ID,value:e.extension_id});let n=this.createLogEvent(gt.TOOL_CALL,r);this.enqueueLogEvent(n),this.flushIfNeeded()}logFileOperationEvent(e){let r=[{gemini_cli_key:oe.GEMINI_CLI_TOOL_CALL_NAME,value:JSON.stringify(e.tool_name)},{gemini_cli_key:oe.GEMINI_CLI_FILE_OPERATION_TYPE,value:JSON.stringify(e.operation)},{gemini_cli_key:oe.GEMINI_CLI_FILE_OPERATION_LINES,value:JSON.stringify(e.lines)},{gemini_cli_key:oe.GEMINI_CLI_FILE_OPERATION_MIMETYPE,value:JSON.stringify(e.mimetype)},{gemini_cli_key:oe.GEMINI_CLI_FILE_OPERATION_EXTENSION,value:JSON.stringify(e.extension)}];e.programming_language&&r.push({gemini_cli_key:oe.GEMINI_CLI_PROGRAMMING_LANGUAGE,value:e.programming_language});let n=this.createLogEvent(gt.FILE_OPERATION,r);this.enqueueLogEvent(n),this.flushIfNeeded()}logApiRequestEvent(e){let r=[{gemini_cli_key:oe.GEMINI_CLI_API_REQUEST_MODEL,value:JSON.stringify(e.model)}];this.enqueueLogEvent(this.createLogEvent(gt.API_REQUEST,r)),this.flushIfNeeded()}logApiResponseEvent(e){let r=[{gemini_cli_key:oe.GEMINI_CLI_API_RESPONSE_MODEL,value:JSON.stringify(e.model)},{gemini_cli_key:oe.GEMINI_CLI_API_RESPONSE_STATUS_CODE,value:JSON.stringify(e.status_code)},{gemini_cli_key:oe.GEMINI_CLI_API_RESPONSE_DURATION_MS,value:JSON.stringify(e.duration_ms)},{gemini_cli_key:oe.GEMINI_CLI_API_RESPONSE_INPUT_TOKEN_COUNT,value:JSON.stringify(e.usage.input_token_count)},{gemini_cli_key:oe.GEMINI_CLI_API_RESPONSE_OUTPUT_TOKEN_COUNT,value:JSON.stringify(e.usage.output_token_count)},{gemini_cli_key:oe.GEMINI_CLI_API_RESPONSE_CACHED_TOKEN_COUNT,value:JSON.stringify(e.usage.cached_content_token_count)},{gemini_cli_key:oe.GEMINI_CLI_API_RESPONSE_THINKING_TOKEN_COUNT,value:JSON.stringify(e.usage.thoughts_token_count)},{gemini_cli_key:oe.GEMINI_CLI_API_RESPONSE_TOOL_TOKEN_COUNT,value:JSON.stringify(e.usage.tool_token_count)},{gemini_cli_key:oe.GEMINI_CLI_API_RESPONSE_CONTEXT_BREAKDOWN_SYSTEM_INSTRUCTIONS,value:JSON.stringify(e.usage.context_breakdown?.system_instructions??0)},{gemini_cli_key:oe.GEMINI_CLI_API_RESPONSE_CONTEXT_BREAKDOWN_TOOL_DEFINITIONS,value:JSON.stringify(e.usage.context_breakdown?.tool_definitions??0)},{gemini_cli_key:oe.GEMINI_CLI_API_RESPONSE_CONTEXT_BREAKDOWN_HISTORY,value:JSON.stringify(e.usage.context_breakdown?.history??0)},{gemini_cli_key:oe.GEMINI_CLI_API_RESPONSE_CONTEXT_BREAKDOWN_TOOL_CALLS,value:JSON.stringify(e.usage.context_breakdown?.tool_calls??{})},{gemini_cli_key:oe.GEMINI_CLI_API_RESPONSE_CONTEXT_BREAKDOWN_MCP_SERVERS,value:JSON.stringify(e.usage.context_breakdown?.mcp_servers??0)}];this.enqueueLogEvent(this.createLogEvent(gt.API_RESPONSE,r)),this.flushIfNeeded()}logApiErrorEvent(e){let r=[{gemini_cli_key:oe.GEMINI_CLI_API_ERROR_MODEL,value:JSON.stringify(e.model)},{gemini_cli_key:oe.GEMINI_CLI_API_ERROR_TYPE,value:JSON.stringify(e.error_type)},{gemini_cli_key:oe.GEMINI_CLI_API_ERROR_STATUS_CODE,value:JSON.stringify(e.status_code)},{gemini_cli_key:oe.GEMINI_CLI_API_ERROR_DURATION_MS,value:JSON.stringify(e.duration_ms)}];this.enqueueLogEvent(this.createLogEvent(gt.API_ERROR,r)),this.flushIfNeeded()}logChatCompressionEvent(e){let r=[{gemini_cli_key:oe.GEMINI_CLI_COMPRESSION_TOKENS_BEFORE,value:`${e.tokens_before}`},{gemini_cli_key:oe.GEMINI_CLI_COMPRESSION_TOKENS_AFTER,value:`${e.tokens_after}`}];this.enqueueLogEvent(this.createLogEvent(gt.CHAT_COMPRESSION,r))}logFlashFallbackEvent(){this.enqueueLogEvent(this.createLogEvent(gt.FLASH_FALLBACK,[])),this.flushToClearcut().catch(e=>{B.debug("Error flushing to Clearcut:",e)})}logRipgrepFallbackEvent(){this.enqueueLogEvent(this.createLogEvent(gt.RIPGREP_FALLBACK,[])),this.flushToClearcut().catch(e=>{B.debug("Error flushing to Clearcut:",e)})}logLoopDetectedEvent(e){let r=[{gemini_cli_key:oe.GEMINI_CLI_LOOP_DETECTED_TYPE,value:JSON.stringify(e.loop_type)}];e.confirmed_by_model&&r.push({gemini_cli_key:oe.GEMINI_CLI_LOOP_DETECTED_CONFIRMED_BY_MODEL,value:e.confirmed_by_model}),this.enqueueLogEvent(this.createLogEvent(gt.LOOP_DETECTED,r)),this.flushIfNeeded()}logLoopDetectionDisabledEvent(){let e=[];this.enqueueLogEvent(this.createLogEvent(gt.LOOP_DETECTION_DISABLED,e)),this.flushIfNeeded()}logNextSpeakerCheck(e){let r=[{gemini_cli_key:oe.GEMINI_CLI_RESPONSE_FINISH_REASON,value:JSON.stringify(e.finish_reason)},{gemini_cli_key:oe.GEMINI_CLI_NEXT_SPEAKER_CHECK_RESULT,value:JSON.stringify(e.result)}];this.enqueueLogEvent(this.createLogEvent(gt.NEXT_SPEAKER_CHECK,r)),this.flushIfNeeded()}logSlashCommandEvent(e){let r=[{gemini_cli_key:oe.GEMINI_CLI_SLASH_COMMAND_NAME,value:JSON.stringify(e.command)}];e.subcommand&&r.push({gemini_cli_key:oe.GEMINI_CLI_SLASH_COMMAND_SUBCOMMAND,value:JSON.stringify(e.subcommand)}),e.status&&r.push({gemini_cli_key:oe.GEMINI_CLI_SLASH_COMMAND_STATUS,value:JSON.stringify(e.status)}),e.extension_id&&r.push({gemini_cli_key:oe.GEMINI_CLI_EXTENSION_ID,value:e.extension_id}),this.enqueueLogEvent(this.createLogEvent(gt.SLASH_COMMAND,r)),this.flushIfNeeded()}logRewindEvent(e){let r=[{gemini_cli_key:oe.GEMINI_CLI_REWIND_OUTCOME,value:e.outcome}];this.enqueueLogEvent(this.createLogEvent(gt.REWIND,r)),this.flushIfNeeded()}logMalformedJsonResponseEvent(e){let r=[{gemini_cli_key:oe.GEMINI_CLI_MALFORMED_JSON_RESPONSE_MODEL,value:JSON.stringify(e.model)}];this.enqueueLogEvent(this.createLogEvent(gt.MALFORMED_JSON_RESPONSE,r)),this.flushIfNeeded()}logIdeConnectionEvent(e){let r=[{gemini_cli_key:oe.GEMINI_CLI_IDE_CONNECTION_TYPE,value:JSON.stringify(e.connection_type)}];this.enqueueLogEventAfterExperimentsLoadAsync(this.createLogEvent(gt.START_SESSION,r)).then(()=>{this.flushToClearcut().catch(n=>{B.debug("Error flushing to Clearcut:",n)})})}logConversationFinishedEvent(e){let r=[{gemini_cli_key:oe.GEMINI_CLI_SESSION_ID,value:this.config?.getSessionId()??""},{gemini_cli_key:oe.GEMINI_CLI_CONVERSATION_TURN_COUNT,value:JSON.stringify(e.turnCount)},{gemini_cli_key:oe.GEMINI_CLI_APPROVAL_MODE,value:e.approvalMode}];this.enqueueLogEvent(this.createLogEvent(gt.CONVERSATION_FINISHED,r)),this.flushIfNeeded()}logEndSessionEvent(){this.enqueueLogEvent(this.createLogEvent(gt.END_SESSION,[])),this.flushToClearcut().catch(e=>{B.debug("Error flushing to Clearcut:",e)})}logInvalidChunkEvent(e){let r=[];e.error_message&&r.push({gemini_cli_key:oe.GEMINI_CLI_INVALID_CHUNK_ERROR_MESSAGE,value:e.error_message}),this.enqueueLogEvent(this.createLogEvent(gt.INVALID_CHUNK,r)),this.flushIfNeeded()}logContentRetryEvent(e){let r=[{gemini_cli_key:oe.GEMINI_CLI_CONTENT_RETRY_ATTEMPT_NUMBER,value:String(e.attempt_number)},{gemini_cli_key:oe.GEMINI_CLI_CONTENT_RETRY_ERROR_TYPE,value:e.error_type},{gemini_cli_key:oe.GEMINI_CLI_CONTENT_RETRY_DELAY_MS,value:String(e.retry_delay_ms)},{gemini_cli_key:oe.GEMINI_CLI_API_REQUEST_MODEL,value:e.model}];this.enqueueLogEvent(this.createLogEvent(gt.CONTENT_RETRY,r)),this.flushIfNeeded()}logContentRetryFailureEvent(e){let r=[{gemini_cli_key:oe.GEMINI_CLI_CONTENT_RETRY_FAILURE_TOTAL_ATTEMPTS,value:String(e.total_attempts)},{gemini_cli_key:oe.GEMINI_CLI_CONTENT_RETRY_FAILURE_FINAL_ERROR_TYPE,value:e.final_error_type},{gemini_cli_key:oe.GEMINI_CLI_API_REQUEST_MODEL,value:e.model}];e.total_duration_ms&&r.push({gemini_cli_key:oe.GEMINI_CLI_CONTENT_RETRY_FAILURE_TOTAL_DURATION_MS,value:String(e.total_duration_ms)}),this.enqueueLogEvent(this.createLogEvent(gt.CONTENT_RETRY_FAILURE,r)),this.flushIfNeeded()}logNetworkRetryAttemptEvent(e){let r=[{gemini_cli_key:oe.GEMINI_CLI_NETWORK_RETRY_ATTEMPT_NUMBER,value:String(e.attempt)},{gemini_cli_key:oe.GEMINI_CLI_NETWORK_RETRY_DELAY_MS,value:String(e.delay_ms)},{gemini_cli_key:oe.GEMINI_CLI_NETWORK_RETRY_ERROR_TYPE,value:e.error_type},{gemini_cli_key:oe.GEMINI_CLI_API_REQUEST_MODEL,value:e.model}];this.enqueueLogEvent(this.createLogEvent(gt.RETRY_ATTEMPT,r)),this.flushIfNeeded()}async logExtensionInstallEvent(e){let r=[{gemini_cli_key:oe.GEMINI_CLI_EXTENSION_NAME,value:e.hashed_extension_name},{gemini_cli_key:oe.GEMINI_CLI_EXTENSION_ID,value:e.extension_id},{gemini_cli_key:oe.GEMINI_CLI_EXTENSION_VERSION,value:e.extension_version},{gemini_cli_key:oe.GEMINI_CLI_EXTENSION_SOURCE,value:e.extension_source},{gemini_cli_key:oe.GEMINI_CLI_EXTENSION_INSTALL_STATUS,value:e.status}];this.enqueueLogEvent(this.createBasicLogEvent(gt.EXTENSION_INSTALL,r)),await this.flushToClearcut().catch(n=>{B.debug("Error flushing to Clearcut:",n)})}async logExtensionUninstallEvent(e){let r=[{gemini_cli_key:oe.GEMINI_CLI_EXTENSION_NAME,value:e.hashed_extension_name},{gemini_cli_key:oe.GEMINI_CLI_EXTENSION_ID,value:e.extension_id},{gemini_cli_key:oe.GEMINI_CLI_EXTENSION_UNINSTALL_STATUS,value:e.status}];this.enqueueLogEvent(this.createBasicLogEvent(gt.EXTENSION_UNINSTALL,r)),await this.flushToClearcut().catch(n=>{B.debug("Error flushing to Clearcut:",n)})}async logExtensionUpdateEvent(e){let r=[{gemini_cli_key:oe.GEMINI_CLI_EXTENSION_NAME,value:e.hashed_extension_name},{gemini_cli_key:oe.GEMINI_CLI_EXTENSION_ID,value:e.extension_id},{gemini_cli_key:oe.GEMINI_CLI_EXTENSION_VERSION,value:e.extension_version},{gemini_cli_key:oe.GEMINI_CLI_EXTENSION_PREVIOUS_VERSION,value:e.extension_previous_version},{gemini_cli_key:oe.GEMINI_CLI_EXTENSION_SOURCE,value:e.extension_source},{gemini_cli_key:oe.GEMINI_CLI_EXTENSION_UPDATE_STATUS,value:e.status}];this.enqueueLogEvent(this.createBasicLogEvent(gt.EXTENSION_UPDATE,r)),await this.flushToClearcut().catch(n=>{B.debug("Error flushing to Clearcut:",n)})}logToolOutputTruncatedEvent(e){let r=[{gemini_cli_key:oe.GEMINI_CLI_TOOL_CALL_NAME,value:JSON.stringify(e.tool_name)},{gemini_cli_key:oe.GEMINI_CLI_TOOL_OUTPUT_TRUNCATED_ORIGINAL_LENGTH,value:JSON.stringify(e.original_content_length)},{gemini_cli_key:oe.GEMINI_CLI_TOOL_OUTPUT_TRUNCATED_TRUNCATED_LENGTH,value:JSON.stringify(e.truncated_content_length)},{gemini_cli_key:oe.GEMINI_CLI_TOOL_OUTPUT_TRUNCATED_THRESHOLD,value:JSON.stringify(e.threshold)}],n=this.createLogEvent(gt.TOOL_OUTPUT_TRUNCATED,r);this.enqueueLogEvent(n),this.flushIfNeeded()}logToolOutputMaskingEvent(e){let r=[{gemini_cli_key:oe.GEMINI_CLI_TOOL_OUTPUT_MASKING_TOKENS_BEFORE,value:e.tokens_before.toString()},{gemini_cli_key:oe.GEMINI_CLI_TOOL_OUTPUT_MASKING_TOKENS_AFTER,value:e.tokens_after.toString()},{gemini_cli_key:oe.GEMINI_CLI_TOOL_OUTPUT_MASKING_MASKED_COUNT,value:e.masked_count.toString()},{gemini_cli_key:oe.GEMINI_CLI_TOOL_OUTPUT_MASKING_TOTAL_PRUNABLE_TOKENS,value:e.total_prunable_tokens.toString()}];this.enqueueLogEvent(this.createLogEvent(gt.TOOL_OUTPUT_MASKING,r)),this.flushIfNeeded()}logModelRoutingEvent(e){let r=[{gemini_cli_key:oe.GEMINI_CLI_ROUTING_DECISION,value:e.decision_model},{gemini_cli_key:oe.GEMINI_CLI_ROUTING_DECISION_SOURCE,value:e.decision_source},{gemini_cli_key:oe.GEMINI_CLI_ROUTING_LATENCY_MS,value:e.routing_latency_ms.toString()},{gemini_cli_key:oe.GEMINI_CLI_ROUTING_FAILURE,value:e.failed.toString()}];e.error_message&&r.push({gemini_cli_key:oe.GEMINI_CLI_ROUTING_FAILURE_REASON,value:e.error_message}),e.reasoning&&this.config?.getTelemetryLogPromptsEnabled()&&r.push({gemini_cli_key:oe.GEMINI_CLI_ROUTING_REASONING,value:e.reasoning}),e.enable_numerical_routing!==void 0&&r.push({gemini_cli_key:oe.GEMINI_CLI_ROUTING_NUMERICAL_ENABLED,value:e.enable_numerical_routing.toString()}),e.classifier_threshold&&r.push({gemini_cli_key:oe.GEMINI_CLI_ROUTING_CLASSIFIER_THRESHOLD,value:e.classifier_threshold}),this.enqueueLogEvent(this.createLogEvent(gt.MODEL_ROUTING,r)),this.flushIfNeeded()}async logExtensionEnableEvent(e){let r=[{gemini_cli_key:oe.GEMINI_CLI_EXTENSION_NAME,value:e.hashed_extension_name},{gemini_cli_key:oe.GEMINI_CLI_EXTENSION_ID,value:e.extension_id},{gemini_cli_key:oe.GEMINI_CLI_EXTENSION_ENABLE_SETTING_SCOPE,value:e.setting_scope}];this.enqueueLogEvent(this.createBasicLogEvent(gt.EXTENSION_ENABLE,r)),await this.flushToClearcut().catch(n=>{B.debug("Error flushing to Clearcut:",n)})}logModelSlashCommandEvent(e){let r=[{gemini_cli_key:oe.GEMINI_CLI_MODEL_SLASH_COMMAND,value:e.model_name}];this.enqueueLogEvent(this.createLogEvent(gt.MODEL_SLASH_COMMAND,r)),this.flushIfNeeded()}async logExtensionDisableEvent(e){let r=[{gemini_cli_key:oe.GEMINI_CLI_EXTENSION_NAME,value:e.hashed_extension_name},{gemini_cli_key:oe.GEMINI_CLI_EXTENSION_ID,value:e.extension_id},{gemini_cli_key:oe.GEMINI_CLI_EXTENSION_DISABLE_SETTING_SCOPE,value:e.setting_scope}];this.enqueueLogEvent(this.createBasicLogEvent(gt.EXTENSION_DISABLE,r)),await this.flushToClearcut().catch(n=>{B.debug("Error flushing to Clearcut:",n)})}logEditStrategyEvent(e){let r=[{gemini_cli_key:oe.GEMINI_CLI_EDIT_STRATEGY,value:e.strategy}];this.enqueueLogEvent(this.createLogEvent(gt.EDIT_STRATEGY,r)),this.flushIfNeeded()}logEditCorrectionEvent(e){let r=[{gemini_cli_key:oe.GEMINI_CLI_EDIT_CORRECTION,value:e.correction}];this.enqueueLogEvent(this.createLogEvent(gt.EDIT_CORRECTION,r)),this.flushIfNeeded()}logAgentStartEvent(e){let r=[{gemini_cli_key:oe.GEMINI_CLI_AGENT_ID,value:e.agent_id},{gemini_cli_key:oe.GEMINI_CLI_AGENT_NAME,value:e.agent_name}];this.enqueueLogEvent(this.createLogEvent(gt.AGENT_START,r)),this.flushIfNeeded()}logAgentFinishEvent(e){let r=[{gemini_cli_key:oe.GEMINI_CLI_AGENT_ID,value:e.agent_id},{gemini_cli_key:oe.GEMINI_CLI_AGENT_NAME,value:e.agent_name},{gemini_cli_key:oe.GEMINI_CLI_AGENT_DURATION_MS,value:e.duration_ms.toString()},{gemini_cli_key:oe.GEMINI_CLI_AGENT_TURN_COUNT,value:e.turn_count.toString()},{gemini_cli_key:oe.GEMINI_CLI_AGENT_TERMINATE_REASON,value:e.terminate_reason}];this.enqueueLogEvent(this.createLogEvent(gt.AGENT_FINISH,r)),this.flushIfNeeded()}logRecoveryAttemptEvent(e){let r=[{gemini_cli_key:oe.GEMINI_CLI_AGENT_ID,value:e.agent_id},{gemini_cli_key:oe.GEMINI_CLI_AGENT_NAME,value:e.agent_name},{gemini_cli_key:oe.GEMINI_CLI_AGENT_RECOVERY_REASON,value:e.reason},{gemini_cli_key:oe.GEMINI_CLI_AGENT_RECOVERY_DURATION_MS,value:e.duration_ms.toString()},{gemini_cli_key:oe.GEMINI_CLI_AGENT_RECOVERY_SUCCESS,value:e.success.toString()},{gemini_cli_key:oe.GEMINI_CLI_AGENT_TURN_COUNT,value:e.turn_count.toString()}];this.enqueueLogEvent(this.createLogEvent(gt.RECOVERY_ATTEMPT,r)),this.flushIfNeeded()}logWebFetchFallbackAttemptEvent(e){let r=[{gemini_cli_key:oe.GEMINI_CLI_WEB_FETCH_FALLBACK_REASON,value:e.reason}];this.enqueueLogEvent(this.createLogEvent(gt.WEB_FETCH_FALLBACK_ATTEMPT,r)),this.flushIfNeeded()}logLlmLoopCheckEvent(e){let r=[{gemini_cli_key:oe.GEMINI_CLI_PROMPT_ID,value:e.prompt_id},{gemini_cli_key:oe.GEMINI_CLI_LLM_LOOP_CHECK_FLASH_CONFIDENCE,value:e.flash_confidence.toString()},{gemini_cli_key:oe.GEMINI_CLI_LLM_LOOP_CHECK_MAIN_MODEL,value:e.main_model},{gemini_cli_key:oe.GEMINI_CLI_LLM_LOOP_CHECK_MAIN_MODEL_CONFIDENCE,value:e.main_model_confidence.toString()}];this.enqueueLogEvent(this.createLogEvent(gt.LLM_LOOP_CHECK,r)),this.flushIfNeeded()}logHookCallEvent(e){let r=[{gemini_cli_key:oe.GEMINI_CLI_HOOK_EVENT_NAME,value:e.hook_event_name},{gemini_cli_key:oe.GEMINI_CLI_HOOK_DURATION_MS,value:e.duration_ms.toString()},{gemini_cli_key:oe.GEMINI_CLI_HOOK_SUCCESS,value:e.success.toString()}];e.exit_code!==void 0&&r.push({gemini_cli_key:oe.GEMINI_CLI_HOOK_EXIT_CODE,value:e.exit_code.toString()}),this.enqueueLogEvent(this.createLogEvent(gt.HOOK_CALL,r)),this.flushIfNeeded()}logApprovalModeSwitchEvent(e){let r=[{gemini_cli_key:oe.GEMINI_CLI_ACTIVE_APPROVAL_MODE,value:e.from_mode},{gemini_cli_key:oe.GEMINI_CLI_APPROVAL_MODE_TO,value:e.to_mode}];this.enqueueLogEvent(this.createLogEvent(gt.APPROVAL_MODE_SWITCH,r)),this.flushIfNeeded()}logApprovalModeDurationEvent(e){let r=[{gemini_cli_key:oe.GEMINI_CLI_ACTIVE_APPROVAL_MODE,value:e.mode},{gemini_cli_key:oe.GEMINI_CLI_APPROVAL_MODE_DURATION_MS,value:e.duration_ms.toString()}];this.enqueueLogEvent(this.createLogEvent(gt.APPROVAL_MODE_DURATION,r)),this.flushIfNeeded()}logPlanExecutionEvent(e){let r=[{gemini_cli_key:oe.GEMINI_CLI_APPROVAL_MODE,value:e.approval_mode}];this.enqueueLogEvent(this.createLogEvent(gt.PLAN_EXECUTION,r)),this.flushIfNeeded()}logKeychainAvailabilityEvent(e){let r=[{gemini_cli_key:oe.GEMINI_CLI_KEYCHAIN_AVAILABLE,value:JSON.stringify(e.available)}];this.enqueueLogEvent(this.createLogEvent(gt.KEYCHAIN_AVAILABILITY,r)),this.flushIfNeeded()}logTokenStorageInitializationEvent(e){let r=[{gemini_cli_key:oe.GEMINI_CLI_TOKEN_STORAGE_TYPE,value:e.type},{gemini_cli_key:oe.GEMINI_CLI_TOKEN_STORAGE_FORCED,value:JSON.stringify(e.forced)}];this.enqueueLogEvent(this.createLogEvent(gt.TOKEN_STORAGE_INITIALIZATION,r)),this.flushIfNeeded()}logOnboardingStartEvent(e){let r=[{gemini_cli_key:oe.GEMINI_CLI_ONBOARDING_START,value:"true"}];this.enqueueLogEvent(this.createLogEvent(gt.ONBOARDING_START,r)),this.flushIfNeeded()}logOnboardingSuccessEvent(e){let r=[];e.userTier&&r.push({gemini_cli_key:oe.GEMINI_CLI_ONBOARDING_USER_TIER,value:e.userTier}),e.duration_ms!==void 0&&r.push({gemini_cli_key:oe.GEMINI_CLI_ONBOARDING_DURATION_MS,value:e.duration_ms.toString()}),this.enqueueLogEvent(this.createLogEvent(gt.ONBOARDING_SUCCESS,r)),this.flushIfNeeded()}logStartupStatsEvent(e){let r=[{gemini_cli_key:oe.GEMINI_CLI_STARTUP_PHASES,value:JSON.stringify(e.phases)},{gemini_cli_key:oe.GEMINI_CLI_STARTUP_OS_PLATFORM,value:e.os_platform},{gemini_cli_key:oe.GEMINI_CLI_STARTUP_OS_RELEASE,value:e.os_release},{gemini_cli_key:oe.GEMINI_CLI_STARTUP_IS_DOCKER,value:JSON.stringify(e.is_docker)}];this.enqueueLogEvent(this.createLogEvent(gt.STARTUP_STATS,r)),this.flushIfNeeded()}logCreditsUsedEvent(e){let r=[{gemini_cli_key:oe.GEMINI_CLI_BILLING_MODEL,value:JSON.stringify(e.model)},{gemini_cli_key:oe.GEMINI_CLI_BILLING_CREDITS_CONSUMED,value:JSON.stringify(e.credits_consumed)},{gemini_cli_key:oe.GEMINI_CLI_BILLING_CREDITS_REMAINING,value:JSON.stringify(e.credits_remaining)}];this.enqueueLogEvent(this.createLogEvent(gt.CREDITS_USED,r)),this.flushIfNeeded()}logOverageOptionSelectedEvent(e){let r=[{gemini_cli_key:oe.GEMINI_CLI_BILLING_MODEL,value:JSON.stringify(e.model)},{gemini_cli_key:oe.GEMINI_CLI_BILLING_SELECTED_OPTION,value:JSON.stringify(e.selected_option)},{gemini_cli_key:oe.GEMINI_CLI_BILLING_CREDIT_BALANCE,value:JSON.stringify(e.credit_balance)}];this.enqueueLogEvent(this.createLogEvent(gt.OVERAGE_OPTION_SELECTED,r)),this.flushIfNeeded()}logEmptyWalletMenuShownEvent(e){let r=[{gemini_cli_key:oe.GEMINI_CLI_BILLING_MODEL,value:JSON.stringify(e.model)}];this.enqueueLogEvent(this.createLogEvent(gt.EMPTY_WALLET_MENU_SHOWN,r)),this.flushIfNeeded()}logCreditPurchaseClickEvent(e){let r=[{gemini_cli_key:oe.GEMINI_CLI_BILLING_MODEL,value:JSON.stringify(e.model)},{gemini_cli_key:oe.GEMINI_CLI_BILLING_PURCHASE_SOURCE,value:JSON.stringify(e.source)}];this.enqueueLogEvent(this.createLogEvent(gt.CREDIT_PURCHASE_CLICK,r)),this.flushIfNeeded()}logBrowserAgentConnectionEvent(e){let r=[{gemini_cli_key:oe.GEMINI_CLI_BROWSER_AGENT_SESSION_MODE,value:e.session_mode},{gemini_cli_key:oe.GEMINI_CLI_BROWSER_AGENT_HEADLESS,value:e.headless.toString()},{gemini_cli_key:oe.GEMINI_CLI_BROWSER_AGENT_SUCCESS,value:e.success.toString()},{gemini_cli_key:oe.GEMINI_CLI_BROWSER_AGENT_DURATION_MS,value:e.duration_ms.toString()}];e.error_type&&r.push({gemini_cli_key:oe.GEMINI_CLI_BROWSER_AGENT_ERROR_TYPE,value:e.error_type}),e.tool_count!==void 0&&r.push({gemini_cli_key:oe.GEMINI_CLI_BROWSER_AGENT_TOOL_COUNT,value:e.tool_count.toString()}),this.enqueueLogEvent(this.createLogEvent(gt.BROWSER_AGENT_CONNECTION,r)),this.flushIfNeeded()}logBrowserAgentVisionStatusEvent(e){let r=[{gemini_cli_key:oe.GEMINI_CLI_BROWSER_AGENT_VISION_ENABLED,value:e.enabled.toString()}];e.disabled_reason&&r.push({gemini_cli_key:oe.GEMINI_CLI_BROWSER_AGENT_VISION_DISABLED_REASON,value:e.disabled_reason}),this.enqueueLogEvent(this.createLogEvent(gt.BROWSER_AGENT_VISION_STATUS,r)),this.flushIfNeeded()}logBrowserAgentTaskOutcomeEvent(e){let r=[{gemini_cli_key:oe.GEMINI_CLI_BROWSER_AGENT_SUCCESS,value:e.success.toString()},{gemini_cli_key:oe.GEMINI_CLI_BROWSER_AGENT_SESSION_MODE,value:e.session_mode},{gemini_cli_key:oe.GEMINI_CLI_BROWSER_AGENT_VISION_ENABLED,value:e.vision_enabled.toString()},{gemini_cli_key:oe.GEMINI_CLI_BROWSER_AGENT_HEADLESS,value:e.headless.toString()},{gemini_cli_key:oe.GEMINI_CLI_BROWSER_AGENT_DURATION_MS,value:e.duration_ms.toString()}];this.enqueueLogEvent(this.createLogEvent(gt.BROWSER_AGENT_TASK_OUTCOME,r)),this.flushIfNeeded()}logBrowserAgentCleanupEvent(e){let r=[{gemini_cli_key:oe.GEMINI_CLI_BROWSER_AGENT_SESSION_MODE,value:e.session_mode},{gemini_cli_key:oe.GEMINI_CLI_BROWSER_AGENT_SUCCESS,value:e.success.toString()},{gemini_cli_key:oe.GEMINI_CLI_BROWSER_AGENT_DURATION_MS,value:e.duration_ms.toString()}];this.enqueueLogEvent(this.createLogEvent(gt.BROWSER_AGENT_CLEANUP,r)),this.flushIfNeeded()}addDefaultFields(e,r){let n=[{gemini_cli_key:oe.GEMINI_CLI_SESSION_ID,value:this.config?.getSessionId()??""},{gemini_cli_key:oe.GEMINI_CLI_AUTH_TYPE,value:JSON.stringify(this.config?.getContentGeneratorConfig()?.authType)},{gemini_cli_key:oe.GEMINI_CLI_GOOGLE_ACCOUNTS_COUNT,value:`${r}`},{gemini_cli_key:oe.GEMINI_CLI_PROMPT_ID,value:this.promptId},{gemini_cli_key:oe.GEMINI_CLI_NODE_VERSION,value:process.versions.node},{gemini_cli_key:oe.GEMINI_CLI_USER_SETTINGS,value:this.getConfigJson()},{gemini_cli_key:oe.GEMINI_CLI_INTERACTIVE,value:this.config?.isInteractive().toString()??"false"},{gemini_cli_key:oe.GEMINI_CLI_ACTIVE_APPROVAL_MODE,value:typeof this.config?.getPolicyEngine=="function"&&typeof this.config.getPolicyEngine()?.getApprovalMode=="function"?this.config.getPolicyEngine().getApprovalMode():""}];return this.config?.getExperiments()&&n.push({gemini_cli_key:oe.GEMINI_CLI_EXPERIMENT_IDS,value:this.config?.getExperiments()?.experimentIds.toString()??"NA"}),[...e,...n]}getProxyAgent(){let e=this.config?.getProxy();if(e){if(e.startsWith("http"))return new z2t.HttpsProxyAgent(e);throw new Error("Unsupported proxy type")}}getConfigJson(){return BKe(this.config)}shutdown(){this.logEndSessionEvent()}requeueFailedEvents(e){let r=e.slice(-AZ);e.length>AZ&&this.config?.getDebugMode()&&B.warn(`ClearcutLogger: Dropping ${e.length-AZ} events due to retry queue limit. Total events: ${e.length}, keeping: ${AZ}`);let n=yZ-this.events.size,o=Math.min(r.length,n);if(o===0){this.config?.getDebugMode()&&B.debug(`ClearcutLogger: No events re-queued (queue size: ${this.events.size})`);return}let s=r.slice(r.length-o);for(let c=s.length-1;c>=0;c--)this.events.unshift(s[c]);for(;this.events.size>yZ;)this.events.pop();this.config?.getDebugMode()&&B.debug(`ClearcutLogger: Re-queued ${o} events for retry (queue size: ${this.events.size})`)}};var IT=Fe(Bt(),1),J2t=Fe(Ef(),1);import*as Y2t from"node:fs";var R4=class{writeStream;constructor(e){this.writeStream=Y2t.createWriteStream(e,{flags:"a"})}serialize(e){return Lr(e,2)+`
1092
1092
  `}shutdown(){return new Promise(e=>{this.writeStream.end(e)})}},_Z=class extends R4{export(e,r){let n=e.map(o=>this.serialize(o)).join("");this.writeStream.write(n,o=>{r({code:o?IT.ExportResultCode.FAILED:IT.ExportResultCode.SUCCESS,error:o||void 0})})}},EZ=class extends R4{export(e,r){let n=e.map(o=>this.serialize(o)).join("");this.writeStream.write(n,o=>{r({code:o?IT.ExportResultCode.FAILED:IT.ExportResultCode.SUCCESS,error:o||void 0})})}},bZ=class extends R4{export(e,r){let n=this.serialize(e);this.writeStream.write(n,o=>{r({code:o?IT.ExportResultCode.FAILED:IT.ExportResultCode.SUCCESS,error:o||void 0})})}getPreferredAggregationTemporality(){return J2t.AggregationTemporality.CUMULATIVE}async forceFlush(){return Promise.resolve()}};var lqi=Fe(Cs(),1),nMt=Fe(jOt(),1),iMt=Fe(LPt(),1),oMt=Fe(rMt(),1),Pb=Fe(Bt(),1);var n5=class extends nMt.TraceExporter{constructor(e,r){super({projectId:e,credentials:r,resourceFilter:/^gcp\./})}},i5=class extends iMt.MetricExporter{constructor(e,r){super({projectId:e,credentials:r,prefix:"custom.googleapis.com/gemini_cli"})}export(e,r){super.export(e,n=>{if(n.code===Pb.ExportResultCode.FAILED&&n.error){let o=n.error.message||String(n.error);if(process.env.GEMINI_STRICT_TELEMETRY_LIMITS==="true"&&o.includes("written more frequently than the maximum sampling period")){r({code:Pb.ExportResultCode.SUCCESS});return}}r(n)})}};function r5(t,e=2e5){if(typeof t=="string")return t.length>e?t.substring(0,e)+"... (truncated due to size)":t;if(Array.isArray(t))return t.map(r=>r5(r,e));if(t!==null&&typeof t=="object"){let r={};for(let[n,o]of Object.entries(t))r[n]=r5(o,e);return r}return t}var o5=class{logging;log;pendingWrites=[];constructor(e,r){this.logging=new oMt.Logging({projectId:e,credentials:r}),this.log=this.logging.log("gemini_cli")}export(e,r){try{let n=e.map(s=>{let c={...s.attributes,...s.resource?.attributes,message:s.body},u=process.env.GEMINI_STRICT_TELEMETRY_LIMITS==="true",d=c;if(u){let a=r5(c,1e4),p=JSON.stringify(a);p&&p.length>1e5&&(a=r5(c,2e3),p=JSON.stringify(a),p&&p.length>1e5&&(a=r5(c,5e3),p=JSON.stringify(a),p&&p.length>1e5&&(a={_warning:"Payload heavily truncated due to strict limits",data:p.substring(0,5e4)+"... (truncated)"}))),d=a}return this.log.entry({severity:this.mapSeverityToCloudLogging(s.severityNumber),timestamp:new Date((0,Pb.hrTimeToMilliseconds)(s.hrTime)),resource:{type:"global",labels:{project_id:this.logging.projectId}}},d)}),o=this.log.write(n).then(()=>{r({code:Pb.ExportResultCode.SUCCESS})}).catch(s=>{r({code:Pb.ExportResultCode.FAILED,error:s})}).finally(()=>{let s=this.pendingWrites.indexOf(o);s>-1&&this.pendingWrites.splice(s,1)});this.pendingWrites.push(o)}catch(n){r({code:Pb.ExportResultCode.FAILED,error:n})}}async forceFlush(){this.pendingWrites.length>0&&await Promise.all(this.pendingWrites)}async shutdown(){await this.forceFlush(),this.pendingWrites=[]}mapSeverityToCloudLogging(e){return e?e>=21?"CRITICAL":e>=17?"ERROR":e>=13?"WARNING":e>=9?"INFO":e>=5?"DEBUG":"DEFAULT":"DEFAULT"}};function LR(t){if(t!==void 0)return t==="true"||t==="1"}function sMt(t){if(t!==void 0){if(t===tm.LOCAL||t==="local")return tm.LOCAL;if(t===tm.GCP||t==="gcp")return tm.GCP}}async function Ibn(t){let e=t.argv??{},r=t.env??{},n=t.settings??{},o=e.telemetry??LR(r.GEMINI_TELEMETRY_ENABLED)??n.enabled,s=LR(r.GEMINI_TELEMETRY_TRACES_ENABLED)??n.traces,c=e.telemetryTarget??r.GEMINI_TELEMETRY_TARGET??n.target,u=sMt(c);if(c!==void 0&&u===void 0)throw new Ax(`Invalid telemetry target: ${String(c)}. Valid values are: local, gcp`);let d=e.telemetryOtlpEndpoint??r.GEMINI_TELEMETRY_OTLP_ENDPOINT??r.OTEL_EXPORTER_OTLP_ENDPOINT??n.otlpEndpoint,l=e.telemetryOtlpProtocol??r.GEMINI_TELEMETRY_OTLP_PROTOCOL??n.otlpProtocol,a=["grpc","http"].find(y=>y===l);if(l!==void 0&&a===void 0)throw new Ax(`Invalid telemetry OTLP protocol: ${String(l)}. Valid values are: grpc, http`);let p=e.telemetryLogPrompts??LR(r.GEMINI_TELEMETRY_LOG_PROMPTS)??n.logPrompts,f=e.telemetryOutfile??r.GEMINI_TELEMETRY_OUTFILE??n.outfile,g=LR(r.GEMINI_TELEMETRY_USE_COLLECTOR)??n.useCollector;return{enabled:o,traces:s,target:u,otlpEndpoint:d,otlpProtocol:a,logPrompts:p,outfile:f,useCollector:g,useCliAuth:LR(r.GEMINI_TELEMETRY_USE_CLI_AUTH)??n.useCliAuth}}var Dke=Fe(Yh(),1);function Lke(t,e){B.debug("Conseca Policy Generation Event:",e);let r=St.getInstance(t);if(r){let s=[];t.getTelemetryLogPromptsEnabled()&&s.push({gemini_cli_key:oe.CONSECA_USER_PROMPT,value:Lr(e.user_prompt)},{gemini_cli_key:oe.CONSECA_TRUSTED_CONTENT,value:Lr(e.trusted_content)},{gemini_cli_key:oe.CONSECA_GENERATED_POLICY,value:Lr(e.policy)}),e.error&&s.push({gemini_cli_key:oe.CONSECA_ERROR,value:e.error}),r.enqueueLogEvent(r.createLogEvent(gt.CONSECA_POLICY_GENERATION,s))}if(!pre())return;let n=Dke.logs.getLogger(It),o={body:e.toLogBody(),attributes:e.toOpenTelemetryAttributes(t)};n.emit(o)}function Mke(t,e){B.debug("Conseca Verdict Event:",e);let r=St.getInstance(t);if(r){let s=[{gemini_cli_key:oe.CONSECA_VERDICT_RESULT,value:Lr(e.verdict)}];t.getTelemetryLogPromptsEnabled()&&s.push({gemini_cli_key:oe.CONSECA_USER_PROMPT,value:Lr(e.user_prompt)},{gemini_cli_key:oe.CONSECA_GENERATED_POLICY,value:Lr(e.policy)},{gemini_cli_key:oe.GEMINI_CLI_TOOL_CALL_NAME,value:Lr(e.tool_call)},{gemini_cli_key:oe.CONSECA_VERDICT_RATIONALE,value:e.verdict_rationale}),e.error&&s.push({gemini_cli_key:oe.CONSECA_ERROR,value:e.error}),r.enqueueLogEvent(r.createLogEvent(gt.CONSECA_VERDICT,s))}if(!pre())return;let n=Dke.logs.getLogger(It),o={body:e.toLogBody(),attributes:e.toOpenTelemetryAttributes(t)};n.emit(o)}je();xl();import{EventEmitter as jbn}from"node:events";var Bke="**",aMt="**";function fre(t){let e=t.indexOf(Bke);if(e===-1)return{subject:"",description:t.trim()};let r=t.indexOf(aMt,e+Bke.length);if(r===-1)return{subject:"",description:t.trim()};let n=t.substring(e+Bke.length,r).trim(),o=(t.substring(0,e)+t.substring(r+aMt.length)).trim();return{subject:n,description:o}}import MR from"node:path";import*as Sa from"node:fs";import*as gy from"node:fs/promises";import hy from"node:path";var Rbn="logs",Pbn="tool-outputs";function lMt(t){if(!t||t==="."||t==="..")throw new Error(`Invalid sessionId: ${t}`);let e=vs(t);if(!e)throw new Error(`Invalid sessionId after sanitization: ${t}`);return e}async function hre(t,e){try{let r=lMt(t),n=hy.join(e,Rbn),o=hy.join(n,`session-${r}.jsonl`);await gy.unlink(o).catch(d=>{if(d.code!=="ENOENT")throw d});let s=hy.join(e,Pbn),c=hy.join(s,`session-${r}`);await gy.rm(c,{recursive:!0,force:!0}).catch(d=>{if(d.code!=="ENOENT")throw d});let u=hy.join(e,r);await gy.rm(u,{recursive:!0,force:!0}).catch(d=>{if(d.code!=="ENOENT")throw d})}catch(r){B.error(`Error deleting session artifacts for ${t}:`,r)}}async function cMt(t,e,r){let n=lMt(t),o=hy.join(e,n);if(!o.startsWith(e+hy.sep))throw new Error(`Dangerous subagent directory path: ${o}`);try{let s=await gy.readdir(o,{withFileTypes:!0}).catch(c=>{if(c.code==="ENOENT")return[];throw c});for(let c of s)if(c.isFile()&&(c.name.endsWith(".json")||c.name.endsWith(".jsonl"))){let u=hy.basename(c.name,hy.extname(c.name));await hre(u,r)}await gy.rm(o,{recursive:!0,force:!0}).catch(c=>{if(c.code!=="ENOENT")throw c})}catch(s){B.error(`Error cleaning up subagents for parent ${t}:`,s),await gy.rm(o,{recursive:!0,force:!0}).catch(()=>{})}}import Nbn from"node:readline";import{randomUUID as kbn}from"node:crypto";var Nb="session-",Cqi=50,xqi=50*1024;var uMt="Chat recording disabled: No space left on device. The conversation will continue but will not be saved to disk. Free up disk space and restart to enable recording.";function BR(t,e){return t!==null&&typeof t=="object"&&e in t}function UR(t,e){return BR(t,e)&&typeof t[e]=="string"}function Dbn(t,e){return BR(t,e)&&t[e]!==null&&typeof t[e]=="object"}function Lbn(t){return UR(t,"$rewindTo")}function Mbn(t){return UR(t,"id")}function Bbn(t){return Dbn(t,"$set")}function Ubn(t){return UR(t,"sessionId")&&UR(t,"projectHash")}function Uke(t){return UR(t,"text")}function dMt(t){return UR(t,"sessionId")}async function kb(t,e){if(!Sa.existsSync(t))return null;try{let r=Sa.createReadStream(t),n=Nbn.createInterface({input:r,crlfDelay:1/0}),o={},s=new Map,c=[],u=new Map,d=!1,l=!1,a;for await(let b of n)if(b.trim())try{let v=JSON.parse(b);if(Lbn(v)){d&&(l=!0);let T=v.$rewindTo;if(e?.metadataOnly){let O=c.indexOf(T);if(O!==-1){let N=c.splice(O);for(let k of N)u.delete(k)}else c.length=0,u.clear()}else{let O=!1,N=[];for(let[k]of s)k===T&&(O=!0),O&&N.push(k);if(O)for(let k of N)s.delete(k);else s.clear()}}else if(Mbn(v)){d&&(l=!0);let T=v.id,O=BR(v,"type")&&v.type==="user",N=BR(v,"type")&&(v.type==="user"||v.type==="gemini");if(e?.metadataOnly&&(c.push(T),u.set(T,{isUser:O,isUserOrAssistant:N})),!a&&O&&BR(v,"content")&&v.content){let k=v.content;Array.isArray(k)?a=k.map(L=>Uke(L)?L.text:"").join(""):typeof k=="string"&&(a=k)}if(!e?.metadataOnly&&(s.set(T,v),e?.maxMessages&&s.size>e.maxMessages)){let k=s.keys().next().value;typeof k=="string"&&s.delete(k)}}else Bbn(v)?(BR(v.$set,"memoryScratchpad")&&(d=!!v.$set.memoryScratchpad,l=!1),o={...o,...v.$set}):Ubn(v)&&(o={...o,...v})}catch{}if(!o.sessionId||!o.projectHash)return await Fbn(t,e);let p=Array.isArray(o.messages)?o.messages:[],f=p.length>0?p:Array.from(s.values()),g=p.find(b=>b.type==="user")??null,y=a;if(!y&&g){let b=g.content;Array.isArray(b)?y=b.map(v=>Uke(v)?v.text:"").join(""):typeof b=="string"&&(y=b)}let _=e?.metadataOnly?Array.from(u.values()).filter(b=>b.isUser).length:f.filter(b=>b.type==="user").length,E=e?.metadataOnly?Array.from(u.values()).some(b=>b.isUserOrAssistant):f.some(b=>b.type==="user"||b.type==="gemini");return{sessionId:o.sessionId,projectHash:o.projectHash,startTime:o.startTime||new Date().toISOString(),lastUpdated:o.lastUpdated||new Date().toISOString(),summary:o.summary,memoryScratchpad:o.memoryScratchpad,directories:o.directories,kind:o.kind,messages:e?.metadataOnly?[]:f,messageCount:e?.metadataOnly?p.length||c.length:f.length,userMessageCount:e?.metadataOnly&&p.length>0?p.filter(b=>b.type==="user").length:_,memoryScratchpadIsStale:d?l:void 0,firstUserMessage:y,hasUserOrAssistantMessage:e?.metadataOnly&&p.length>0?p.some(b=>b.type==="user"||b.type==="gemini"):E}}catch(r){return B.error("Error loading conversation record from JSONL:",r),null}}var gre=class{conversationFile=null;cachedConversation=null;sessionId;projectHash;kind;queuedThoughts=[];queuedTokens=null;context;constructor(e){this.context=e,this.sessionId=e.promptId,this.projectHash=dKe(e.config.getProjectRoot())}async initialize(e,r){try{if(this.kind=r,e){this.conversationFile=e.filePath,this.sessionId=e.conversation.sessionId,this.kind=e.conversation.kind;let n=await kb(this.conversationFile);if(n){if(this.cachedConversation=n,this.projectHash=this.cachedConversation.projectHash,this.conversationFile.endsWith(".json")){this.conversationFile=this.conversationFile+"l";let o={sessionId:this.sessionId,projectHash:this.projectHash,startTime:this.cachedConversation.startTime,lastUpdated:this.cachedConversation.lastUpdated,kind:this.cachedConversation.kind,directories:this.cachedConversation.directories,summary:this.cachedConversation.summary};this.appendRecord(o);for(let s of this.cachedConversation.messages)this.appendRecord(s);this.cachedConversation.memoryScratchpad&&this.appendRecord({$set:{memoryScratchpad:this.cachedConversation.memoryScratchpad}})}this.updateMetadata({sessionId:this.sessionId})}else throw new Error("Failed to load resumed session data from file")}else{this.sessionId=this.context.promptId;let n=MR.join(this.context.config.storage.getProjectTempDir(),"chats");if(this.kind==="subagent"&&this.context.parentSessionId){let l=vs(this.context.parentSessionId);if(!l)throw new Error(`Invalid parentSessionId after sanitization: ${this.context.parentSessionId}`);n=MR.join(n,l)}Sa.mkdirSync(n,{recursive:!0});let o=new Date().toISOString().slice(0,16).replace(/:/g,"-"),s=vs(this.sessionId);if(!s)throw new Error(`Invalid sessionId after sanitization: ${this.sessionId}`);let c;this.kind==="subagent"?c=`${s}.jsonl`:c=`${Nb}${o}-${s.slice(0,8)}.jsonl`,this.conversationFile=MR.join(n,c);let u=this.kind==="subagent"?[...this.context.config.getWorkspaceContext()?.getDirectories()??[]]:void 0,d={sessionId:this.sessionId,projectHash:this.projectHash,startTime:new Date().toISOString(),lastUpdated:new Date().toISOString(),kind:this.kind,directories:u};this.appendRecord(d),this.cachedConversation={...d,messages:[]}}this.queuedThoughts=[],this.queuedTokens=null}catch(n){if(yt(n)&&n.code==="ENOSPC"){this.conversationFile=null,B.warn(uMt);return}throw B.error("Error initializing chat recording service:",n),n}}appendRecord(e){if(this.conversationFile)try{let r=JSON.stringify(e)+`
1093
1093
  `;Sa.mkdirSync(MR.dirname(this.conversationFile),{recursive:!0}),Sa.appendFileSync(this.conversationFile,r)}catch(r){if(yt(r)&&r.code==="ENOSPC")this.conversationFile=null,B.warn(uMt);else throw r}}updateMetadata(e){this.cachedConversation&&(Object.assign(this.cachedConversation,e),this.appendRecord({$set:e}))}pushMessage(e){if(!this.cachedConversation)return;this.appendRecord(e);let r=this.cachedConversation.messages.findIndex(n=>n.id===e.id);r!==-1?this.cachedConversation.messages[r]=e:this.cachedConversation.messages.push(e)}getLastMessage(e){return e.messages.at(-1)}newMessage(e,r,n){return{id:kbn(),timestamp:new Date().toISOString(),type:e,content:r,displayContent:n}}recordMessage(e){if(!(!this.conversationFile||!this.cachedConversation))try{let r=this.newMessage(e.type,e.content,e.displayContent);r.type==="gemini"&&(r.thoughts=this.queuedThoughts,r.tokens=this.queuedTokens,r.model=e.model,this.queuedThoughts=[],this.queuedTokens=null),this.pushMessage(r),this.updateMetadata({lastUpdated:new Date().toISOString()})}catch(r){throw B.error("Error saving message to chat history.",r),r}}recordThought(e){this.conversationFile&&this.queuedThoughts.push({...e,timestamp:new Date().toISOString()})}recordMessageTokens(e){if(!(!this.conversationFile||!this.cachedConversation))try{let r={input:e.promptTokenCount??0,output:e.candidatesTokenCount??0,cached:e.cachedContentTokenCount??0,thoughts:e.thoughtsTokenCount??0,tool:e.toolUsePromptTokenCount??0,total:e.totalTokenCount??0},n=this.getLastMessage(this.cachedConversation);n&&n.type==="gemini"&&!n.tokens?(n.tokens=r,this.queuedTokens=null,this.pushMessage(n)):this.queuedTokens=r}catch(r){throw B.error("Error updating message tokens in chat history.",r),r}}recordToolCalls(e,r){if(!this.conversationFile||!this.cachedConversation)return;let n=this.context.toolRegistry,o=r.map(s=>{let c=n.getTool(s.name);return{...s,displayName:c?.displayName||s.name,description:s.description?.trim()||c?.description||"",renderOutputAsMarkdown:c?.isOutputMarkdown||!1}});try{let s=this.getLastMessage(this.cachedConversation);if(!s||s.type!=="gemini"||this.queuedThoughts.length>0){let c={...this.newMessage("gemini",""),type:"gemini",toolCalls:o,thoughts:this.queuedThoughts,model:e};this.queuedThoughts.length>0&&(c.thoughts=this.queuedThoughts,this.queuedThoughts=[]),this.queuedTokens&&(c.tokens=this.queuedTokens,this.queuedTokens=null),this.pushMessage(c)}else{s.toolCalls||(s.toolCalls=[]);let c=[...s.toolCalls];for(let u of o){let d=c.findIndex(l=>l.id===u.id);d!==-1?c[d]={...c[d],...u}:c.push(u)}s.toolCalls=c,this.pushMessage(s)}}catch(s){throw B.error("Error adding tool call to message in chat history.",s),s}}saveSummary(e){if(this.conversationFile)try{this.updateMetadata({summary:e})}catch(r){B.error("Error saving summary to chat history.",r)}}recordDirectories(e){if(this.conversationFile)try{this.updateMetadata({directories:[...e]})}catch(r){B.error("Error saving directories to chat history.",r)}}getConversation(){return this.conversationFile?this.cachedConversation:null}getConversationFilePath(){return this.conversationFile}async deleteSession(e){try{let r=this.context.config.storage.getProjectTempDir(),n=MR.join(r,"chats"),o=this.deriveShortId(e);if(!await Sa.promises.stat(n).catch(()=>null))return;let s=await this.getMatchingSessionFiles(n,o);for(let c of s)await this.deleteSessionAndArtifacts(n,c,r)}catch(r){throw B.error("Error deleting session file.",r),r}}deriveShortId(e){let r=e;if(e.startsWith(Nb)){let o=e.replace(/\.jsonl?$/,"").split("-");r=o[o.length-1]}else if(e.length>=8)r=e.slice(0,8);else throw new Error("Invalid sessionId or basename provided for deletion");if(r.length!==8)throw new Error("Derived shortId must be exactly 8 characters");return r}async getMatchingSessionFiles(e,r){return(await Sa.promises.readdir(e)).filter(o=>o.startsWith(Nb)&&(o.endsWith(`-${r}.json`)||o.endsWith(`-${r}.jsonl`)))}async deleteSessionAndArtifacts(e,r,n){let o=MR.join(e,r),s;try{let u=Buffer.alloc(4096),d,l;try{l=await Sa.promises.open(o,"r");let{bytesRead:a}=await l.read(u,0,4096,0);if(a>0){let p=u.toString("utf8",0,a),f=p.indexOf(`
1094
1094
  `);d=f!==-1?p.substring(0,f):p;try{let g=JSON.parse(d);dMt(g)&&(s=g.sessionId)}catch{}}}finally{l!==void 0&&await l.close()}if(!s)try{let a=await Sa.promises.readFile(o,"utf8"),p=JSON.parse(a);dMt(p)&&(s=p.sessionId)}catch{}s&&(await hre(s,n),await cMt(s,e,n))}catch(c){B.error(`Error deleting artifacts for session file ${r}:`,c)}finally{try{await Sa.promises.unlink(o)}catch(c){yt(c)&&c.code!=="ENOENT"&&B.error(`Error unlinking session file ${r}:`,c)}}}async deleteCurrentSessionAsync(){if(this.conversationFile)try{let e=this.context.config.storage.getProjectTempDir();await Sa.promises.unlink(this.conversationFile).catch(()=>{}),await hre(this.sessionId,e)}catch(e){throw B.error("Error deleting current session.",e),e}}rewindTo(e){if(!this.conversationFile||!this.cachedConversation)return null;let r=this.cachedConversation.messages.findIndex(n=>n.id===e);return r===-1?(B.error("Message to rewind to not found in conversation history"),this.cachedConversation):(this.cachedConversation.messages=this.cachedConversation.messages.slice(0,r),this.appendRecord({$rewindTo:e}),this.cachedConversation)}updateMessagesFromHistory(e){if(!(!this.conversationFile||!this.cachedConversation))try{let r=new Map;for(let n of e)if(n.role==="user"&&n.parts){let o=n.parts.map(c=>c.functionResponse?.id).filter(c=>!!c);if(o.length===0)continue;let s=o[0];for(let c of n.parts)c.functionResponse?.id&&(s=c.functionResponse.id),r.has(s)||r.set(s,[]),r.get(s).push(c)}for(let n of this.cachedConversation.messages){let o=!1;if(n.type==="gemini"&&n.toolCalls)for(let s of n.toolCalls){let c=r.get(s.id);c!==void 0&&(s.result=c,o=!0)}o&&this.pushMessage(n)}}catch(r){throw B.error("Error updating conversation history from memory.",r),r}}};async function Fbn(t,e){try{let r=await Sa.promises.readFile(t,"utf8"),n=JSON.parse(r);if((s=>typeof s=="object"&&s!==null&&"sessionId"in s)(n)){let s=n;if(e?.metadataOnly){let c,u=s.messages?.find(d=>d.type==="user");if(u){let d=u.content;Array.isArray(d)?c=d.map(l=>Uke(l)?l.text:"").join(""):typeof d=="string"&&(c=d)}return{...s,messages:[],messageCount:s.messages?.length||0,userMessageCount:s.messages?.filter(d=>d.type==="user").length||0,firstUserMessage:c,hasUserOrAssistantMessage:s.messages?.some(d=>d.type==="user"||d.type==="gemini")||!1}}return{...s,userMessageCount:s.messages?.filter(c=>c.type==="user").length||0,hasUserOrAssistantMessage:s.messages?.some(c=>c.type==="user"||c.type==="gemini")||!1}}}catch{}return null}var pMt=()=>({totalRequests:0,totalErrors:0,totalLatencyMs:0,tokens:{input:0,prompt:0,candidates:0,total:0,cached:0,thoughts:0,tool:0}}),Qbn=()=>({api:{totalRequests:0,totalErrors:0,totalLatencyMs:0},tokens:{input:0,prompt:0,candidates:0,total:0,cached:0,thoughts:0,tool:0},roles:{}}),fMt=()=>({models:{},tools:{totalCalls:0,totalSuccess:0,totalFail:0,totalDurationMs:0,totalDecisions:{[po.ACCEPT]:0,[po.REJECT]:0,[po.MODIFY]:0,[po.AUTO_ACCEPT]:0},byName:{}},files:{totalLinesAdded:0,totalLinesRemoved:0}}),Fke=class extends jbn{#e=fMt();#t=0;addEvent(e){switch(e["event.name"]){case S3:this.processApiResponse(e);break;case v3:this.processApiError(e);break;case b3:this.processToolCall(e);break;default:return}this.emit("update",{metrics:this.#e,lastPromptTokenCount:this.#t})}getMetrics(){return this.#e}getLastPromptTokenCount(){return this.#t}setLastPromptTokenCount(e){this.#t=e,this.emit("update",{metrics:this.#e,lastPromptTokenCount:this.#t})}clear(e){this.#e=fMt(),this.#t=0,this.emit("clear",e),this.emit("update",{metrics:this.#e,lastPromptTokenCount:this.#t})}hydrate(e){this.clear(e.sessionId);let r=0;for(let n of e.messages)if(n.type==="gemini"){let o=n.model||"unknown",s=this.getOrCreateModelMetrics(o);if(s.api.totalRequests++,n.tokens&&(s.tokens.prompt+=n.tokens.input,s.tokens.candidates+=n.tokens.output,s.tokens.total+=n.tokens.total,s.tokens.cached+=n.tokens.cached,s.tokens.thoughts+=n.tokens.thoughts||0,s.tokens.tool+=n.tokens.tool||0,s.tokens.input=Math.max(0,s.tokens.prompt-s.tokens.cached),r=n.tokens.total),n.toolCalls)for(let c of n.toolCalls){this.#e.tools.totalCalls++,c.status==="success"?this.#e.tools.totalSuccess++:c.status==="error"&&this.#e.tools.totalFail++,this.#e.tools.byName[c.name]||(this.#e.tools.byName[c.name]={count:0,success:0,fail:0,durationMs:0,decisions:{[po.ACCEPT]:0,[po.REJECT]:0,[po.MODIFY]:0,[po.AUTO_ACCEPT]:0}});let u=this.#e.tools.byName[c.name];u.count++,c.status==="success"?u.success++:c.status==="error"&&u.fail++}}this.#t=r,this.emit("update",{metrics:this.#e,lastPromptTokenCount:this.#t})}getOrCreateModelMetrics(e){return this.#e.models[e]||(this.#e.models[e]=Qbn()),this.#e.models[e]}processApiResponse(e){let r=this.getOrCreateModelMetrics(e.model);if(r.api.totalRequests++,r.api.totalLatencyMs+=e.duration_ms,r.tokens.prompt+=e.usage.input_token_count,r.tokens.candidates+=e.usage.output_token_count,r.tokens.total+=e.usage.total_token_count,r.tokens.cached+=e.usage.cached_content_token_count,r.tokens.thoughts+=e.usage.thoughts_token_count,r.tokens.tool+=e.usage.tool_token_count,r.tokens.input=Math.max(0,r.tokens.prompt-r.tokens.cached),e.role){r.roles[e.role]||(r.roles[e.role]=pMt());let n=r.roles[e.role];n.totalRequests++,n.totalLatencyMs+=e.duration_ms,n.tokens.prompt+=e.usage.input_token_count,n.tokens.candidates+=e.usage.output_token_count,n.tokens.total+=e.usage.total_token_count,n.tokens.cached+=e.usage.cached_content_token_count,n.tokens.thoughts+=e.usage.thoughts_token_count,n.tokens.tool+=e.usage.tool_token_count,n.tokens.input=Math.max(0,n.tokens.prompt-n.tokens.cached)}}processApiError(e){let r=this.getOrCreateModelMetrics(e.model);if(r.api.totalRequests++,r.api.totalErrors++,r.api.totalLatencyMs+=e.duration_ms,e.role){r.roles[e.role]||(r.roles[e.role]=pMt());let n=r.roles[e.role];n.totalRequests++,n.totalErrors++,n.totalLatencyMs+=e.duration_ms}}processToolCall(e){let{tools:r,files:n}=this.#e;r.totalCalls++,r.totalDurationMs+=e.duration_ms,e.success?r.totalSuccess++:r.totalFail++,r.byName[e.function_name]||(r.byName[e.function_name]={count:0,success:0,fail:0,durationMs:0,decisions:{[po.ACCEPT]:0,[po.REJECT]:0,[po.MODIFY]:0,[po.AUTO_ACCEPT]:0}});let o=r.byName[e.function_name];o.count++,o.durationMs+=e.duration_ms,e.success?o.success++:o.fail++,e.decision&&(r.totalDecisions[e.decision]++,o.decisions[e.decision]++),e.metadata&&(e.metadata.model_added_lines!==void 0&&(n.totalLinesAdded+=e.metadata.model_added_lines),e.metadata.model_removed_lines!==void 0&&(n.totalLinesRemoved+=e.metadata.model_removed_lines))}},my=new Fke;var Gbn="gemini_cli.overage_menu_shown",hMt=class{"event.name";"event.timestamp";model;credit_balance;overage_strategy;constructor(e,r,n){this["event.name"]="overage_menu_shown",this["event.timestamp"]=new Date().toISOString(),this.model=e,this.credit_balance=r,this.overage_strategy=n}toOpenTelemetryAttributes(e){return{..._t(e),"event.name":Gbn,"event.timestamp":this["event.timestamp"],model:this.model,credit_balance:this.credit_balance,overage_strategy:this.overage_strategy}}toLogBody(){return`Overage menu shown for model ${this.model} with ${this.credit_balance} credits available.`}},$bn="gemini_cli.overage_option_selected",mre=class{"event.name";"event.timestamp";model;selected_option;credit_balance;constructor(e,r,n){this["event.name"]="overage_option_selected",this["event.timestamp"]=new Date().toISOString(),this.model=e,this.selected_option=r,this.credit_balance=n}toOpenTelemetryAttributes(e){return{..._t(e),"event.name":$bn,"event.timestamp":this["event.timestamp"],model:this.model,selected_option:this.selected_option,credit_balance:this.credit_balance}}toLogBody(){return`Overage option '${this.selected_option}' selected for model ${this.model}.`}},qbn="gemini_cli.empty_wallet_menu_shown",yre=class{"event.name";"event.timestamp";model;constructor(e){this["event.name"]="empty_wallet_menu_shown",this["event.timestamp"]=new Date().toISOString(),this.model=e}toOpenTelemetryAttributes(e){return{..._t(e),"event.name":qbn,"event.timestamp":this["event.timestamp"],model:this.model}}toLogBody(){return`Empty wallet menu shown for model ${this.model}.`}},Vbn="gemini_cli.credit_purchase_click",Are=class{"event.name";"event.timestamp";source;model;constructor(e,r){this["event.name"]="credit_purchase_click",this["event.timestamp"]=new Date().toISOString(),this.source=e,this.model=r}toOpenTelemetryAttributes(e){return{..._t(e),"event.name":Vbn,"event.timestamp":this["event.timestamp"],source:this.source,model:this.model}}toLogBody(){return`Credit purchase clicked from ${this.source} for model ${this.model}.`}},Hbn="gemini_cli.credits_used",FR=class{"event.name";"event.timestamp";model;credits_consumed;credits_remaining;constructor(e,r,n){this["event.name"]="credits_used",this["event.timestamp"]=new Date().toISOString(),this.model=e,this.credits_consumed=r,this.credits_remaining=n}toOpenTelemetryAttributes(e){return{..._t(e),"event.name":Hbn,"event.timestamp":this["event.timestamp"],model:this.model,credits_consumed:this.credits_consumed,credits_remaining:this.credits_remaining}}toLogBody(){return`${this.credits_consumed} credits consumed for model ${this.model}. ${this.credits_remaining} remaining.`}},zbn="gemini_cli.api_key_updated",gMt=class{"event.name";"event.timestamp";previous_auth_type;new_auth_type;constructor(e,r){this["event.name"]="api_key_updated",this["event.timestamp"]=new Date().toISOString(),this.previous_auth_type=e,this.new_auth_type=r}toOpenTelemetryAttributes(e){return{..._t(e),"event.name":zbn,"event.timestamp":this["event.timestamp"],previous_auth_type:this.previous_auth_type,new_auth_type:this.new_auth_type}}toLogBody(){return`Auth type changed from ${this.previous_auth_type} to ${this.new_auth_type}.`}};import l5 from"node:v8";import Lb from"node:process";var Db=t=>t/1048576,mMt=t=>{let e=t/1073741824;return t<1048576?`${(t/1024).toFixed(1)} KB`:t<1073741824?`${Db(t).toFixed(1)} MB`:`${e.toFixed(2)} GB`};var _re=class{lastActivityTime=Date.now();idleThresholdMs;constructor(e=3e4){this.idleThresholdMs=e}recordActivity(){this.lastActivityTime=Date.now()}isUserActive(){return Date.now()-this.lastActivityTime<this.idleThresholdMs}getTimeSinceLastActivity(){return Date.now()-this.lastActivityTime}getLastActivityTime(){return this.lastActivityTime}},jke=new _re;function Wbn(){return jke}function Ybn(){jke.recordActivity()}function Qke(){return jke.isUserActive()}var s5=class{waterMarks=new Map;lastUpdateTimes=new Map;growthThresholdPercent;constructor(e=5){if(e<0)throw new Error("growthThresholdPercent must be non-negative.");this.growthThresholdPercent=e}shouldRecordMetric(e,r){let n=Date.now();this.lastUpdateTimes.set(e,n);let o=this.waterMarks.get(e)||0;if(o===0)return this.waterMarks.set(e,r),this.lastUpdateTimes.set(e,n),!0;let s=o*(1+this.growthThresholdPercent/100);return r>s?(this.waterMarks.set(e,r),this.lastUpdateTimes.set(e,n),!0):!1}getHighWaterMark(e){return this.waterMarks.get(e)||0}getAllHighWaterMarks(){return Object.fromEntries(this.waterMarks)}resetHighWaterMark(e){this.waterMarks.delete(e),this.lastUpdateTimes.delete(e)}resetAllHighWaterMarks(){this.waterMarks.clear(),this.lastUpdateTimes.clear()}cleanup(e=36e5){let r=Date.now()-e;for(let[n,o]of this.lastUpdateTimes.entries())o<r&&(this.lastUpdateTimes.delete(n),this.waterMarks.delete(n))}};var a5=class t{lastRecordTimes=new Map;minIntervalMs;static HIGH_PRIORITY_DIVISOR=2;constructor(e=6e4){if(e<0)throw new Error("minIntervalMs must be non-negative.");this.minIntervalMs=e}shouldRecord(e,r=!1){let n=Date.now(),o=this.lastRecordTimes.get(e)||0,s=r?Math.round(this.minIntervalMs/t.HIGH_PRIORITY_DIVISOR):this.minIntervalMs;return n-o>=s?(this.lastRecordTimes.set(e,n),!0):!1}forceRecord(e){this.lastRecordTimes.set(e,Date.now())}getTimeUntilNextAllowed(e,r=!1){let n=Date.now(),o=this.lastRecordTimes.get(e)||0,s=r?Math.round(this.minIntervalMs/t.HIGH_PRIORITY_DIVISOR):this.minIntervalMs,c=o+s;return Math.max(0,c-n)}getStats(){let e=Array.from(this.lastRecordTimes.values());if(e.length===0)return{totalMetrics:0,oldestRecord:0,newestRecord:0,averageInterval:0};let r=Math.min(...e),n=Math.max(...e),o=n-r,s=e.length>1?o/(e.length-1):0;return{totalMetrics:e.length,oldestRecord:r,newestRecord:n,averageInterval:s}}reset(){this.lastRecordTimes.clear()}cleanup(e=36e5){let r=Date.now()-e;for(let[n,o]of this.lastRecordTimes.entries())o<r&&this.lastRecordTimes.delete(n)}};import Jbn from"node:v8";import yMt from"node:path";import Kbn from"node:fs";import Xbn from"node:os";function Gke(){try{let e=`gemini-heap-${Date.now()}.heapsnapshot`,r=Kbn.mkdtempSync(yMt.join(Xbn.tmpdir(),"gemini-heap-")),n=yMt.join(r,e);return Jbn.writeHeapSnapshot(n),n}catch(t){return B.error("Failed to capture heap snapshot:",t),null}}var Ere=class t{intervalId=null;isRunning=!1;lastSnapshot=null;lastCpuUsage=null;monitoringInterval=1e4;highWaterMarkTracker;rateLimiter;useEnhancedMonitoring=!0;lastCleanupTimestamp=Date.now();static STATE_CLEANUP_INTERVAL_MS=15*60*1e3;static STATE_CLEANUP_MAX_AGE_MS=60*60*1e3;constructor(){this.highWaterMarkTracker=new s5(5),this.rateLimiter=new a5(6e4)}start(e,r=1e4){!v_()||this.isRunning||(this.monitoringInterval=r,this.isRunning=!0,this.takeSnapshot("monitoring_start",e),this.intervalId=setInterval(()=>{this.checkAndRecordIfNeeded(e)},this.monitoringInterval).unref())}checkAndRecordIfNeeded(e){if(this.performPeriodicCleanup(),!this.useEnhancedMonitoring){this.takeSnapshot("periodic",e);return}if(!Qke())return;let r=this.getCurrentMemoryUsage(),n=this.highWaterMarkTracker.shouldRecordMetric("rss",r.rss),o=this.highWaterMarkTracker.shouldRecordMetric("heap_used",r.heapUsed),s=this.rateLimiter.shouldRecord("periodic_memory"),c=this.rateLimiter.shouldRecord("high_water_memory",!0);if((n||o)&&c){let u=n?"rss_growth":"heap_growth";this.takeSnapshot(u,e)}else s&&this.takeSnapshotWithoutRecording("periodic_check",e)}performPeriodicCleanup(){let e=Date.now();e-this.lastCleanupTimestamp<t.STATE_CLEANUP_INTERVAL_MS||(this.lastCleanupTimestamp=e,this.highWaterMarkTracker.cleanup(t.STATE_CLEANUP_MAX_AGE_MS),this.rateLimiter.cleanup(t.STATE_CLEANUP_MAX_AGE_MS))}stop(e){this.isRunning&&(this.intervalId&&(clearInterval(this.intervalId),this.intervalId=null),e&&this.takeSnapshot("monitoring_stop",e),this.isRunning=!1)}takeSnapshot(e,r){let n=Lb.memoryUsage(),o=l5.getHeapStatistics(),s={timestamp:Date.now(),heapUsed:n.heapUsed,heapTotal:n.heapTotal,external:n.external,rss:n.rss,arrayBuffers:n.arrayBuffers,heapSizeLimit:o.heap_size_limit};if(v_()){C2(r,s.heapUsed,{memory_type:E_.HEAP_USED,component:e}),C2(r,s.heapTotal,{memory_type:E_.HEAP_TOTAL,component:e}),C2(r,s.external,{memory_type:E_.EXTERNAL,component:e}),C2(r,s.rss,{memory_type:E_.RSS,component:e});let c=Lb.cpuUsage(this.lastCpuUsage??void 0);this.lastCpuUsage=Lb.cpuUsage(),I_e(r,c.user+c.system,{component:e})}return this.lastSnapshot=s,s}takeSnapshotWithoutRecording(e,r){let n=Lb.memoryUsage(),o=l5.getHeapStatistics(),s={timestamp:Date.now(),heapUsed:n.heapUsed,heapTotal:n.heapTotal,external:n.external,rss:n.rss,arrayBuffers:n.arrayBuffers,heapSizeLimit:o.heap_size_limit};return this.highWaterMarkTracker.shouldRecordMetric("rss",s.rss),this.highWaterMarkTracker.shouldRecordMetric("heap_used",s.heapUsed),this.lastSnapshot=s,s}getCurrentMemoryUsage(){let e=Lb.memoryUsage(),r=l5.getHeapStatistics();return{timestamp:Date.now(),heapUsed:e.heapUsed,heapTotal:e.heapTotal,external:e.external,rss:e.rss,arrayBuffers:e.arrayBuffers,heapSizeLimit:r.heap_size_limit}}getMemoryGrowth(){if(!this.lastSnapshot)return null;let e=this.getCurrentMemoryUsage();return{heapUsed:e.heapUsed-this.lastSnapshot.heapUsed,heapTotal:e.heapTotal-this.lastSnapshot.heapTotal,external:e.external-this.lastSnapshot.external,rss:e.rss-this.lastSnapshot.rss,arrayBuffers:e.arrayBuffers-this.lastSnapshot.arrayBuffers}}getHeapStatistics(){return l5.getHeapStatistics()}getHeapSpaceStatistics(){return l5.getHeapSpaceStatistics()}getProcessMetrics(){return{cpuUsage:Lb.cpuUsage(),memoryUsage:Lb.memoryUsage(),uptime:Lb.uptime()}}recordComponentMemoryUsage(e,r,n){return this.takeSnapshot(n?`${r}_${n}`:r,e)}checkMemoryThreshold(e){let r=this.getCurrentMemoryUsage();return Db(r.heapUsed)>e}getMemoryUsageSummary(){let e=this.getCurrentMemoryUsage();return{heapUsedMB:Math.round(Db(e.heapUsed)*100)/100,heapTotalMB:Math.round(Db(e.heapTotal)*100)/100,externalMB:Math.round(Db(e.external)*100)/100,rssMB:Math.round(Db(e.rss)*100)/100,heapSizeLimitMB:Math.round(Db(e.heapSizeLimit)*100)/100}}setEnhancedMonitoring(e){this.useEnhancedMonitoring=e}getHighWaterMarkStats(){return this.highWaterMarkTracker.getAllHighWaterMarks()}getRateLimitingStats(){return this.rateLimiter.getStats()}forceRecordMemory(e,r="forced"){return this.rateLimiter.forceRecord("forced_memory"),this.takeSnapshot(r,e)}resetHighWaterMarks(){this.highWaterMarkTracker.resetAllHighWaterMarks()}captureHeapSnapshot(){return Gke()}destroy(){this.stop(),this.rateLimiter.reset(),this.highWaterMarkTracker.resetAllHighWaterMarks()}},jR=null;function $ke(){return jR||(jR=new Ere),jR}function c5(){return jR}function Zbn(t,e){return $ke().takeSnapshot(e,t)}function qke(t,e=1e4){$ke().start(t,e)}function evn(t){jR&&jR.stop(t)}import tvn from"node:process";import{monitorEventLoopDelay as rvn}from"node:perf_hooks";var bre=class{eventLoopHistogram=null;intervalId=null;isRunning=!1;start(e,r=1e4){!(tvn.env.GEMINI_EVENT_LOOP_MONITOR_ENABLED==="true")||!v_()||this.isRunning||(this.isRunning=!0,this.eventLoopHistogram=rvn({resolution:10}),this.eventLoopHistogram.enable(),this.intervalId=setInterval(()=>{this.takeSnapshot(e)},r).unref())}stop(){this.isRunning&&(this.intervalId&&(clearInterval(this.intervalId),this.intervalId=null),this.eventLoopHistogram&&(this.eventLoopHistogram.disable(),this.eventLoopHistogram=null),this.isRunning=!1)}takeSnapshot(e){if(!this.eventLoopHistogram)return;let r=this.eventLoopHistogram.percentile(50)/1e6,n=this.eventLoopHistogram.percentile(95)/1e6,o=this.eventLoopHistogram.max/1e6;s3(e,r,{percentile:"p50",component:"event_loop_monitor"}),s3(e,n,{percentile:"p95",component:"event_loop_monitor"}),s3(e,o,{percentile:"max",component:"event_loop_monitor"})}},tw=null;function Vke(t,e){tw||(tw=new bre),tw.start(t,e)}function nvn(){tw&&(tw.stop(),tw=null)}function ivn(){return tw}var rm;(function(t){t.USER_INPUT_START="user_input_start",t.USER_INPUT_END="user_input_end",t.MESSAGE_ADDED="message_added",t.TOOL_CALL_SCHEDULED="tool_call_scheduled",t.TOOL_CALL_COMPLETED="tool_call_completed",t.STREAM_START="stream_start",t.STREAM_END="stream_end",t.HISTORY_UPDATED="history_updated",t.MANUAL_TRIGGER="manual_trigger"})(rm||(rm={}));var ovn={enabled:!0,snapshotThrottleMs:1e3,maxEventBuffer:100,triggerActivities:[rm.USER_INPUT_START,rm.MESSAGE_ADDED,rm.TOOL_CALL_SCHEDULED,rm.TOOL_CALL_COMPLETED,rm.STREAM_START]},vre=class{listeners=new Set;eventBuffer=[];lastSnapshotTime=0;config;isActive=!1;memoryMonitoringListener=null;constructor(e=ovn){this.config={...e}}start(e){!v_()||this.isActive||(this.isActive=!0,this.memoryMonitoringListener=r=>{this.handleMemoryMonitoringActivity(r,e)},this.addListener(this.memoryMonitoringListener),this.recordActivity(rm.MANUAL_TRIGGER,"activity_monitoring_start"))}stop(){this.isActive&&(this.isActive=!1,this.memoryMonitoringListener&&(this.removeListener(this.memoryMonitoringListener),this.memoryMonitoringListener=null),this.eventBuffer=[])}addListener(e){this.listeners.add(e)}removeListener(e){this.listeners.delete(e)}recordActivity(e,r,n){if(!this.isActive||!this.config.enabled)return;let o={type:e,timestamp:Date.now(),context:r,metadata:n};this.eventBuffer.push(o),this.eventBuffer.length>this.config.maxEventBuffer&&this.eventBuffer.shift(),this.listeners.forEach(s=>{try{s(o)}catch(c){B.debug("ActivityMonitor listener error:",c)}})}getRecentActivity(e){let r=[...this.eventBuffer];return e?r.slice(-e):r}getActivityStats(){let e={},r=Number.MAX_SAFE_INTEGER,n=0;for(let o of this.eventBuffer)e[o.type]=(e[o.type]||0)+1,r=Math.min(r,o.timestamp),n=Math.max(n,o.timestamp);return{totalEvents:this.eventBuffer.length,eventTypes:e,timeRange:this.eventBuffer.length>0?{start:r,end:n}:null}}updateConfig(e){this.config={...this.config,...e}}handleMemoryMonitoringActivity(e,r){if(!this.config.triggerActivities.includes(e.type))return;let n=Date.now();if(n-this.lastSnapshotTime<this.config.snapshotThrottleMs)return;this.lastSnapshotTime=n;let o=c5();if(o){let s=e.context?`activity_${e.type}_${e.context}`:`activity_${e.type}`;o.takeSnapshot(s,r)}}isMonitoringActive(){return this.isActive&&this.config.enabled}},QR=null;function AMt(t){return QR||(QR=new vre(t)),QR}function svn(){return QR}function avn(t,e){AMt(e).start(t)}function lvn(){QR&&QR.stop()}je();var cvn="gemini-cli",uvn="v1",dvn=new FinalizationRegistry(t=>{try{t()}catch(e){B.warn("Error in FinalizationRegistry callback for span cleanup",e)}});function Sre(t,e=1e4){if(typeof t=="string")return pc(t,e,`...[TRUNCATED: original length ${t.length}]`);if(typeof t=="object"&&t!==null){let r=Lr(t);return pc(r,e,`...[TRUNCATED: original length ${r.length}]`)}if(typeof t=="number"||typeof t=="boolean")return t}function pvn(t){return typeof t=="object"&&t!==null&&Symbol.asyncIterator in t}async function Lf(t,e){let{operation:r,logPrompts:n,sessionId:o,tracesEnabled:s,...c}=t;return c.attributes={...c.attributes,[aq]:o},AG.getTracer(cvn,uvn).startActiveSpan(r,c,async d=>{let l={name:r,attributes:{[uAe]:r,[t3]:It,[r3]:git,[aq]:o}},a=!1,p=()=>{if(!a){a=!0;try{if(s){if(n!==!1){if(l.input!==void 0){let g=Sre(l.input);g!==void 0&&d.setAttribute(mit,g)}if(l.output!==void 0){let g=Sre(l.output);g!==void 0&&d.setAttribute(yit,g)}}for(let[g,y]of Object.entries(l.attributes)){let _=Sre(y);_!==void 0&&d.setAttribute(g,_)}}else for(let[g,y]of Object.entries(l.attributes))if(g===uAe||g===t3||g===r3||g===aq){let _=Sre(y);_!==void 0&&d.setAttribute(g,_)}l.error?(d.setStatus({code:gL.ERROR,message:_Mt(l.error)}),l.error instanceof Error&&d.recordException(l.error)):d.setStatus({code:gL.OK})}catch(g){Rn.error("Error setting span attributes in endSpan",g),d.setStatus({code:gL.ERROR,message:`Error in endSpan: ${_Mt(g)}`})}finally{d.end()}}},f=!1;try{let g=await e({metadata:l});if(pvn(g)){f=!0;let y=async function*(){try{yield*g}catch(E){throw l.error=E,E}finally{p()}}(),_=Object.assign(y,g);return dvn.register(_,p),_}return g}catch(g){throw l.error=g,g}finally{f||p()}})}function _Mt(t){return t instanceof Error?t.message:typeof t=="string"?t:Lr(t)}import{performance as nm}from"node:perf_hooks";import*as Mb from"node:os";import*as Hke from"node:fs";var Tre=class t{phases=new Map;static instance;constructor(){}static getInstance(){return t.instance||(t.instance=new t),t.instance}getStartMarkName(e){return`startup:${e}:start`}getEndMarkName(e){return`startup:${e}:end`}start(e,r){let n=this.phases.get(e);if(n&&!n.ended){B.warn(`[STARTUP] Cannot start phase '${e}': phase is already active. Call end() before starting again.`);return}let o=this.getStartMarkName(e);nm.mark(o,{detail:r});let s={name:e,startCpuUsage:process.cpuUsage(),details:r,ended:!1};return this.phases.set(e,s),{end:c=>{this._end(s,c)}}}_end(e,r){if(e.ended){B.warn(`[STARTUP] Cannot end phase '${e.name}': phase was already ended.`);return}let n=this.getStartMarkName(e.name),o=this.getEndMarkName(e.name);if(nm.getEntriesByName(n).length===0){B.warn(`[STARTUP] Cannot measure phase '${e.name}': start mark '${n}' not found (likely cleared by reset).`),e.ended=!0;return}nm.mark(o,{detail:r}),nm.measure(e.name,n,o),e.cpuUsage=process.cpuUsage(e.startCpuUsage),e.ended=!0,r&&(e.details={...e.details,...r})}flush(e){B.debug("[STARTUP] StartupProfiler.flush() called with",this.phases.size,"phases");let r={os_platform:Mb.platform(),os_arch:Mb.arch(),os_release:Mb.release(),is_docker:Hke.existsSync("/.dockerenv")},n=nm.getEntriesByType("measure");for(let s of this.phases.values()){if(!s.ended){B.warn(`[STARTUP] Phase '${s.name}' was started but never ended. Skipping metrics.`);continue}let c=n.find(u=>u.name===s.name);if(c&&s.cpuUsage){let u={...r,cpu_usage_user:s.cpuUsage.user,cpu_usage_system:s.cpuUsage.system,...s.details};B.debug("[STARTUP] Recording metric for phase:",s.name,"duration:",c.duration),O_e(e,c.duration,{phase:s.name,details:u})}else B.debug("[STARTUP] Skipping phase without measure:",s.name)}let o=[];for(let s of this.phases.values()){if(!s.ended)continue;let c=n.find(u=>u.name===s.name);c&&s.cpuUsage&&o.push({name:s.name,duration_ms:Math.round(c.duration),cpu_usage_user_usec:s.cpuUsage.user,cpu_usage_system_usec:s.cpuUsage.system,start_time_usec:Math.round((nm.timeOrigin+c.startTime)*1e3),end_time_usec:Math.round((nm.timeOrigin+c.startTime+c.duration)*1e3)})}o.length>0&&EMt(e,new Rq(o,Mb.platform(),Mb.release(),Hke.existsSync("/.dockerenv")));for(let s of this.phases.keys()){let c=this.getStartMarkName(s),u=this.getEndMarkName(s);nm.clearMarks(c),nm.clearMarks(u),nm.clearMeasures(s)}this.phases.clear()}},zke=Tre.getInstance();var tm;(function(t){t.GCP="gcp",t.LOCAL="local"})(tm||(tm={}));var Wke=tm.LOCAL,Yke="http://localhost:4317";var nDe=class{error(e,...r){B.error(e,...r)}warn(e,...r){B.warn(e,...r)}info(e,...r){B.log(e,...r)}debug(e,...r){B.debug(e,...r)}verbose(e,...r){B.debug(e,...r)}};Rn.setLogger(new nDe,JKe.INFO);var d5,Ire,Rre,Bb,Fb=!1,iDe=!1,p5,$R,qR,oDe=[],u5;function pre(){return Fb}function rr(t){Fb?t():oDe.push(t)}async function vvn(){if(Fb)for(;oDe.length>0;){let t=oDe.shift();if(t)try{await t()}catch(e){B.error("Error executing buffered telemetry event",e)}}}function Svn(t,e){if(!t)return;let r=t.replace(/^["']|["']$/g,"");try{let n=new URL(r);return e==="grpc"?n.origin:n.href}catch(n){Rn.error("Invalid OTLP endpoint URL provided:",r,n);return}}async function wre(t,e){if(!t.getTelemetryEnabled())return;if(Fb){if(e?.client_email&&u5&&e.client_email!==u5){let y=`Telemetry credentials have changed (from ${u5} to ${e.client_email}), but telemetry cannot be re-initialized in this process. Please restart the CLI to use the new account for telemetry.`;B.error(y)}return}if(t.getTelemetryUseCollector()&&t.getTelemetryUseCliAuth()){B.error('Telemetry configuration error: "useCollector" and "useCliAuth" cannot both be true. CLI authentication is only supported with in-process exporters. Disabling telemetry.');return}if(t.getTelemetryUseCliAuth()&&!e){iDe||(iDe=!0,p5=async y=>{t.getTelemetryEnabled()&&t.getTelemetryUseCliAuth()&&(B.log("Telemetry reinit with credentials."),await wre(t,y))},Yq.on("post_auth",p5)),B.log("CLI auth is requested but no credentials, deferring telemetry initialization.");return}let r=(0,IMt.resourceFromAttributes)({[dq.SERVICE_NAME]:It,[dq.SERVICE_VERSION]:process.version,"session.id":t.getSessionId()});$R||($R=y=>{PMt(t,y)},Ee.on(vr.TelemetryKeychainAvailability,$R)),qR||(qR=y=>{NMt(t,y)},Ee.on(vr.TelemetryTokenStorageType,qR));let n=t.getTelemetryOtlpEndpoint(),o=t.getTelemetryOtlpProtocol(),s=t.getTelemetryTarget(),c=t.getTelemetryUseCollector(),u=Svn(n,o),d=t.getTelemetryOutfile(),l=!!u&&!d,a=process.env.OTLP_GOOGLE_CLOUD_PROJECT||process.env.GOOGLE_CLOUD_PROJECT,p=s===tm.GCP&&!c,f,g;if(p)B.log("Creating GCP exporters with projectId:",a,"using",e?"provided credentials":"ADC"),f=new n5(a,e),g=new o5(a,e),Bb=new Ub.PeriodicExportingMetricReader({exporter:new i5(a,e),exportIntervalMillis:3e4});else if(l)if(o==="http"){let y=_=>{let E=new URL(u);return E.pathname=[E.pathname.replace(/\/$/,""),_].join("/"),E.href};f=new wMt.OTLPTraceExporter({url:y("v1/traces")}),g=new CMt.OTLPLogExporter({url:y("v1/logs")}),Bb=new Ub.PeriodicExportingMetricReader({exporter:new xMt.OTLPMetricExporter({url:y("v1/metrics")}),exportIntervalMillis:1e4})}else f=new vMt.OTLPTraceExporter({url:u,compression:P_.GZIP}),g=new SMt.OTLPLogExporter({url:u,compression:P_.GZIP}),Bb=new Ub.PeriodicExportingMetricReader({exporter:new TMt.OTLPMetricExporter({url:u,compression:P_.GZIP}),exportIntervalMillis:1e4});else d?(f=new _Z(d),g=new EZ(d),Bb=new Ub.PeriodicExportingMetricReader({exporter:new bZ(d),exportIntervalMillis:1e4})):(f=new Pre.ConsoleSpanExporter,g=new Nre.ConsoleLogRecordExporter,Bb=new Ub.PeriodicExportingMetricReader({exporter:new Ub.ConsoleMetricExporter,exportIntervalMillis:1e4}));Ire=new Pre.BatchSpanProcessor(f),Rre=new Nre.BatchLogRecordProcessor(g),d5=new OMt.NodeSDK({resource:r,spanProcessors:[Ire],logRecordProcessors:[Rre],metricReader:Bb,instrumentations:[new RMt.HttpInstrumentation]});try{d5.start(),t.getDebugMode()&&B.log("OpenTelemetry SDK started successfully."),u5=e?.client_email,Tit(t);let y=process.env.GEMINI_MEMORY_MONITOR_INTERVAL;if(B.log(`[TELEMETRY] GEMINI_MEMORY_MONITOR_INTERVAL: ${y}`),y){let _=parseInt(y,10);if(!isNaN(_)&&_>0){qke(t,_),Vke(t,_);let E=c5();E&&E.setEnhancedMonitoring(!1)}}Fb=!0,vvn()}catch(y){B.error("Error starting OpenTelemetry SDK:",y)}process.on("SIGTERM",()=>{Jke(t)}),process.on("SIGINT",()=>{Jke(t)})}async function fvn(t){if(!(!Fb||!Ire||!Rre))try{await Promise.all([Ire.forceFlush(),Rre.forceFlush(),Bb?Bb.forceFlush():Promise.resolve()]),t.getDebugMode()&&B.log("OpenTelemetry SDK flushed successfully.")}catch(e){B.error("Error flushing SDK:",e)}}async function Jke(t,e=!0){if(!(!Fb||!d5))try{St.getInstance()?.shutdown(),await d5.shutdown(),t.getDebugMode()&&e&&B.log("OpenTelemetry SDK shut down successfully.")}catch(r){B.error("Error shutting down SDK:",r)}finally{Fb=!1,d5=void 0,AG.disable(),KKe.disable(),yG.disable(),XKe.disable(),Rn.disable(),p5&&(Yq.off("post_auth",p5),p5=void 0),$R&&(Ee.off(vr.TelemetryKeychainAvailability,$R),$R=void 0),qR&&(Ee.off(vr.TelemetryTokenStorageType,qR),qR=void 0),iDe=!1,u5=void 0}}function hvn(t,e){St.getInstance(t)?.logStartSessionEvent(e),rr(()=>{t.getExperimentsAsync().then(()=>{let r=Zt.logs.getLogger(It),n={body:e.toLogBody(),attributes:e.toOpenTelemetryAttributes(t)};r.emit(n)}).catch(r=>{B.error("Failed to log telemetry event",r)})})}function gvn(t,e){St.getInstance(t)?.logNewPromptEvent(e),rr(()=>{let r=Zt.logs.getLogger(It),n={body:e.toLogBody(),attributes:e.toOpenTelemetryAttributes(t)};r.emit(n)})}function Cre(t,e){let r={...e,"event.name":b3,"event.timestamp":new Date().toISOString()};my.addEvent(r),St.getInstance(t)?.logToolCallEvent(e),rr(()=>{let n=Zt.logs.getLogger(It),o={body:e.toLogBody(),attributes:e.toOpenTelemetryAttributes(t)};if(n.emit(o),__e(t,e.duration_ms,{function_name:e.function_name,success:e.success,decision:e.decision,tool_type:e.tool_type}),e.metadata){let s=e.metadata.model_added_lines;typeof s=="number"&&s>0&&v_e(t,s,"added",{function_name:e.function_name});let c=e.metadata.model_removed_lines;typeof c=="number"&&c>0&&v_e(t,c,"removed",{function_name:e.function_name})}})}function GR(t,e){St.getInstance(t)?.logToolOutputTruncatedEvent(e),rr(()=>{let r=Zt.logs.getLogger(It),n={body:e.toLogBody(),attributes:e.toOpenTelemetryAttributes(t)};r.emit(n)})}function kMt(t,e){St.getInstance(t)?.logToolOutputMaskingEvent(e),rr(()=>{let r=Zt.logs.getLogger(It),n={body:e.toLogBody(),attributes:e.toOpenTelemetryAttributes(t)};r.emit(n)})}function VR(t,e){St.getInstance(t)?.logFileOperationEvent(e),rr(()=>{let r=Zt.logs.getLogger(It),n={body:e.toLogBody(),attributes:e.toOpenTelemetryAttributes(t)};r.emit(n),b_e(t,{operation:e.operation,lines:e.lines,mimetype:e.mimetype,extension:e.extension,programming_language:e.programming_language})})}function Kke(t,e){St.getInstance(t)?.logApiRequestEvent(e),rr(()=>{let r=Zt.logs.getLogger(It);r.emit(e.toLogRecord(t)),r.emit(e.toSemanticLogRecord(t))})}function Xke(t,e){St.getInstance(t)?.logFlashFallbackEvent(),rr(()=>{let r=Zt.logs.getLogger(It),n={body:e.toLogBody(),attributes:e.toOpenTelemetryAttributes(t)};r.emit(n)})}function DMt(t,e){St.getInstance(t)?.logRipgrepFallbackEvent(),rr(()=>{let r=Zt.logs.getLogger(It),n={body:e.toLogBody(),attributes:e.toOpenTelemetryAttributes(t)};r.emit(n)})}function Zke(t,e){let r={...e,"event.name":v3,"event.timestamp":new Date().toISOString()};my.addEvent(r),St.getInstance(t)?.logApiErrorEvent(e),rr(()=>{let n=Zt.logs.getLogger(It);n.emit(e.toLogRecord(t)),n.emit(e.toSemanticLogRecord(t)),E_e(t,e.duration_ms,{model:e.model,status_code:e.status_code,error_type:e.error_type}),uq(t,e.duration_ms,{model:e.model,status_code:e.status_code,genAiAttributes:{...b_(e),"error.type":e.error_type||"unknown"}})})}function eDe(t,e){let r={...e,"event.name":S3,"event.timestamp":new Date().toISOString()};my.addEvent(r),St.getInstance(t)?.logApiResponseEvent(e),rr(()=>{let n=Zt.logs.getLogger(It);n.emit(e.toLogRecord(t)),n.emit(e.toSemanticLogRecord(t));let o=b_(e);uq(t,e.duration_ms,{model:e.model,status_code:e.status_code,genAiAttributes:o});let s=[{count:e.usage.input_token_count,type:"input"},{count:e.usage.output_token_count,type:"output"},{count:e.usage.cached_content_token_count,type:"cache"},{count:e.usage.thoughts_token_count,type:"thought"},{count:e.usage.tool_token_count,type:"tool"}];for(let{count:c,type:u}of s)R_e(t,c,{model:e.model,type:u,genAiAttributes:o})})}function sDe(t,e){St.getInstance(t)?.logLoopDetectedEvent(e),rr(()=>{let r=Zt.logs.getLogger(It),n={body:e.toLogBody(),attributes:e.toOpenTelemetryAttributes(t)};r.emit(n)})}function LMt(t,e){St.getInstance(t)?.logLoopDetectionDisabledEvent(),rr(()=>{let r=Zt.logs.getLogger(It),n={body:e.toLogBody(),attributes:e.toOpenTelemetryAttributes(t)};r.emit(n)})}function MMt(t,e){St.getInstance(t)?.logNextSpeakerCheck(e),rr(()=>{let r=Zt.logs.getLogger(It),n={body:e.toLogBody(),attributes:e.toOpenTelemetryAttributes(t)};r.emit(n)})}function mvn(t,e){St.getInstance(t)?.logSlashCommandEvent(e),rr(()=>{let r=Zt.logs.getLogger(It),n={body:e.toLogBody(),attributes:e.toOpenTelemetryAttributes(t)};r.emit(n)})}function yvn(t,e){let r={...e,"event.name":X_e,"event.timestamp":new Date().toISOString()};my.addEvent(r),St.getInstance(t)?.logRewindEvent(e),rr(()=>{let n=Zt.logs.getLogger(It),o={body:e.toLogBody(),attributes:e.toOpenTelemetryAttributes(t)};n.emit(o)})}function Tvn(t,e){St.getInstance(t)?.logIdeConnectionEvent(e),rr(()=>{let r=Zt.logs.getLogger(It),n={body:e.toLogBody(),attributes:e.toOpenTelemetryAttributes(t)};r.emit(n)})}function Avn(t,e){St.getInstance(t)?.logConversationFinishedEvent(e),rr(()=>{let r=Zt.logs.getLogger(It),n={body:e.toLogBody(),attributes:e.toOpenTelemetryAttributes(t)};r.emit(n)})}function xre(t,e){St.getInstance(t)?.logChatCompressionEvent(e);let r=Zt.logs.getLogger(It),n={body:e.toLogBody(),attributes:e.toOpenTelemetryAttributes(t)};r.emit(n),wit(t,{tokens_before:e.tokens_before,tokens_after:e.tokens_after})}function BMt(t,e){St.getInstance(t)?.logMalformedJsonResponseEvent(e),rr(()=>{let r=Zt.logs.getLogger(It),n={body:e.toLogBody(),attributes:e.toOpenTelemetryAttributes(t)};r.emit(n)})}function UMt(t,e){St.getInstance(t)?.logInvalidChunkEvent(e),rr(()=>{let r=Zt.logs.getLogger(It),n={body:e.toLogBody(),attributes:e.toOpenTelemetryAttributes(t)};r.emit(n),S_e(t)})}function rw(t,e){St.getInstance(t)?.logNetworkRetryAttemptEvent(e),rr(()=>{let r=Zt.logs.getLogger(It),n={body:e.toLogBody(),attributes:e.toOpenTelemetryAttributes(t)};r.emit(n),T_e(t,{model:e.model,attempt:e.attempt})})}function FMt(t,e){St.getInstance(t)?.logContentRetryEvent(e),rr(()=>{let r=Zt.logs.getLogger(It),n={body:e.toLogBody(),attributes:e.toOpenTelemetryAttributes(t)};r.emit(n),w_e(t)})}function jMt(t,e){St.getInstance(t)?.logContentRetryFailureEvent(e),rr(()=>{let r=Zt.logs.getLogger(It),n={body:e.toLogBody(),attributes:e.toOpenTelemetryAttributes(t)};r.emit(n),C_e(t)})}function QMt(t,e){St.getInstance(t)?.logModelRoutingEvent(e),rr(()=>{let r=Zt.logs.getLogger(It),n={body:e.toLogBody(),attributes:e.toOpenTelemetryAttributes(t)};r.emit(n),x_e(t,e)})}function wvn(t,e){St.getInstance(t)?.logModelSlashCommandEvent(e),rr(()=>{let r=Zt.logs.getLogger(It),n={body:e.toLogBody(),attributes:e.toOpenTelemetryAttributes(t)};r.emit(n),Pit(t,e)})}async function _vn(t,e){await St.getInstance(t)?.logExtensionInstallEvent(e),rr(()=>{let r=Zt.logs.getLogger(It),n={body:e.toLogBody(),attributes:e.toOpenTelemetryAttributes(t)};r.emit(n)})}async function Evn(t,e){await St.getInstance(t)?.logExtensionUninstallEvent(e),rr(()=>{let r=Zt.logs.getLogger(It),n={body:e.toLogBody(),attributes:e.toOpenTelemetryAttributes(t)};r.emit(n)})}async function bvn(t,e){await St.getInstance(t)?.logExtensionUpdateEvent(e),rr(()=>{let r=Zt.logs.getLogger(It),n={body:e.toLogBody(),attributes:e.toOpenTelemetryAttributes(t)};r.emit(n)})}async function bMt(t,e){await St.getInstance(t)?.logExtensionEnableEvent(e),rr(()=>{let r=Zt.logs.getLogger(It),n={body:e.toLogBody(),attributes:e.toOpenTelemetryAttributes(t)};r.emit(n)})}async function Cvn(t,e){await St.getInstance(t)?.logExtensionDisableEvent(e),rr(()=>{let r=Zt.logs.getLogger(It),n={body:e.toLogBody(),attributes:e.toOpenTelemetryAttributes(t)};r.emit(n)})}function f5(t,e){St.getInstance(t)?.logEditStrategyEvent(e),rr(()=>{let r=Zt.logs.getLogger(It),n={body:e.toLogBody(),attributes:e.toOpenTelemetryAttributes(t)};r.emit(n)})}function aDe(t,e){St.getInstance(t)?.logEditCorrectionEvent(e),rr(()=>{let r=Zt.logs.getLogger(It),n={body:e.toLogBody(),attributes:e.toOpenTelemetryAttributes(t)};r.emit(n)})}function GMt(t,e){St.getInstance(t)?.logAgentStartEvent(e),rr(()=>{let r=Zt.logs.getLogger(It),n={body:e.toLogBody(),attributes:e.toOpenTelemetryAttributes(t)};r.emit(n)})}function $Mt(t,e){St.getInstance(t)?.logAgentFinishEvent(e),rr(()=>{let r=Zt.logs.getLogger(It),n={body:e.toLogBody(),attributes:e.toOpenTelemetryAttributes(t)};r.emit(n),Nit(t,e)})}function qMt(t,e){St.getInstance(t)?.logRecoveryAttemptEvent(e),rr(()=>{let r=Zt.logs.getLogger(It),n={body:e.toLogBody(),attributes:e.toOpenTelemetryAttributes(t)};r.emit(n),kit(t,e)})}function Ore(t,e){St.getInstance(t)?.logWebFetchFallbackAttemptEvent(e),rr(()=>{let r=Zt.logs.getLogger(It),n={body:e.toLogBody(),attributes:e.toOpenTelemetryAttributes(t)};r.emit(n)})}function lDe(t,e){St.getInstance(t)?.logLlmLoopCheckEvent(e),rr(()=>{let r=Zt.logs.getLogger(It),n={body:e.toLogBody(),attributes:e.toOpenTelemetryAttributes(t)};r.emit(n)})}function VMt(t,e){St.getInstance(t)?.logApprovalModeSwitchEvent(e),rr(()=>{Zt.logs.getLogger(It).emit({body:e.toLogBody(),attributes:e.toOpenTelemetryAttributes(t)})})}function HMt(t,e){St.getInstance(t)?.logApprovalModeDurationEvent(e),rr(()=>{Zt.logs.getLogger(It).emit({body:e.toLogBody(),attributes:e.toOpenTelemetryAttributes(t)})})}function zMt(t,e){St.getInstance(t)?.logPlanExecutionEvent(e),rr(()=>{Zt.logs.getLogger(It).emit({body:e.toLogBody(),attributes:e.toOpenTelemetryAttributes(t)}),Rit(t,{approval_mode:e.approval_mode})})}function WMt(t,e){St.getInstance(t)?.logHookCallEvent(e),rr(()=>{let r=Zt.logs.getLogger(It),n={body:e.toLogBody(),attributes:e.toOpenTelemetryAttributes(t)};r.emit(n),Mit(t,e.hook_event_name,e.hook_name,e.duration_ms,e.success)})}function EMt(t,e){St.getInstance(t)?.logStartupStatsEvent(e),rr(()=>{t.getExperimentsAsync().then(()=>{let r=Zt.logs.getLogger(It),n={body:e.toLogBody(),attributes:e.toOpenTelemetryAttributes(t)};r.emit(n)}).catch(r=>{B.error("Failed to log telemetry event",r)})})}function PMt(t,e){St.getInstance(t)?.logKeychainAvailabilityEvent(e),rr(()=>{let r=Zt.logs.getLogger(It),n={body:e.toLogBody(),attributes:e.toOpenTelemetryAttributes(t)};r.emit(n),Bit(t,e)})}function NMt(t,e){St.getInstance(t)?.logTokenStorageInitializationEvent(e),rr(()=>{let r=Zt.logs.getLogger(It),n={body:e.toLogBody(),attributes:e.toOpenTelemetryAttributes(t)};r.emit(n),Uit(t,e)})}function tDe(t,e){St.getInstance(t)?.logOnboardingStartEvent(e),rr(()=>{let r=Zt.logs.getLogger(It),n={body:e.toLogBody(),attributes:e.toOpenTelemetryAttributes(t)};r.emit(n),Oit(t)})}function rDe(t,e){St.getInstance(t)?.logOnboardingSuccessEvent(e),rr(()=>{let r=Zt.logs.getLogger(It),n={body:e.toLogBody(),attributes:e.toOpenTelemetryAttributes(t)};r.emit(n),Iit(t,e.userTier,e.duration_ms)})}function cDe(t,e){rr(()=>{let n=Zt.logs.getLogger(It),o={body:e.toLogBody(),attributes:e.toOpenTelemetryAttributes(t)};n.emit(o)});let r=St.getInstance(t);r&&(e instanceof FR?r.logCreditsUsedEvent(e):e instanceof mre?r.logOverageOptionSelectedEvent(e):e instanceof yre?r.logEmptyWalletMenuShownEvent(e):e instanceof Are&&r.logCreditPurchaseClickEvent(e))}function uDe(t,e,r){St.getInstance(t)?.logBrowserAgentConnectionEvent({session_mode:r.session_mode,headless:r.headless,success:r.success,duration_ms:e,error_type:r.error_type,tool_count:r.tool_count}),Fit(t,e,r)}function YMt(t,e){St.getInstance(t)?.logBrowserAgentVisionStatusEvent({enabled:e.enabled,disabled_reason:e.disabled_reason}),Qit(t,e)}function JMt(t,e){St.getInstance(t)?.logBrowserAgentTaskOutcomeEvent({success:e.success,session_mode:e.session_mode,vision_enabled:e.vision_enabled,headless:e.headless,duration_ms:e.duration_ms}),Git(t,e)}function KMt(t){return{request:{model:"models/"+t.model,contents:nw(t.contents)}}}function XMt(t){return t.totalTokens===void 0&&B.warn("Warning: Code Assist API did not return totalTokens. Defaulting to 0."),{totalTokens:t.totalTokens??0}}function pDe(t,e,r,n,o){return{model:t.model,project:r,user_prompt_id:e,request:xvn(t,n),enabled_credit_types:o}}function fDe(t){let e=new oL;e.responseId=t.traceId;let r=t.response;return r?(e.candidates=r.candidates??[],e.automaticFunctionCallingHistory=r.automaticFunctionCallingHistory,e.promptFeedback=r.promptFeedback,e.usageMetadata=r.usageMetadata,e.modelVersion=r.modelVersion,e):(e.candidates=[],e)}function xvn(t,e){return{contents:nw(t.contents),systemInstruction:Ovn(t.config?.systemInstruction),cachedContent:t.config?.cachedContent,tools:t.config?.tools,toolConfig:t.config?.toolConfig,labels:t.config?.labels,safetySettings:t.config?.safetySettings,generationConfig:Rvn(t.config),session_id:e}}function nw(t){return Array.isArray(t)?t.map(dDe):[dDe(t)]}function Ovn(t){if(t)return dDe(t)}function Ivn(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)&&!("parts"in t)&&!("role"in t)}function dDe(t){return Array.isArray(t)?{role:"user",parts:kre(t)}:typeof t=="string"?{role:"user",parts:[{text:t}]}:Ivn(t)?{role:"user",parts:[ZMt(t)]}:{...t,parts:t.parts?kre(t.parts.filter(e=>e!=null)):[]}}function kre(t){return t.map(ZMt)}function ZMt(t){if(typeof t=="string")return{text:t};if("thought"in t&&t.thought){let e=`[Thought: ${t.thought}]`,r={...t};if(delete r.thought,"functionCall"in r||"functionResponse"in r||"inlineData"in r||"fileData"in r)return r;let o=r.text,s=o?String(o):"",c=s?`${s}
@@ -2514,7 +2514,7 @@ CRITICAL: When you have fully completed the user's task, you MUST call the compl
2514
2514
  \${task}
2515
2515
  </task>
2516
2516
 
2517
- First, use <list_pages/> to check if there are any existing pages that can fulfill the user's request. If not, you MUST use <new_page/> to open the relevant URL unless the user explicitly provides different instructions.`,systemPrompt:Dei(e,t.getBrowserAgentConfig().customConfig.allowedDomains)}}};var ah=class t{static MAX_AUTH_RETRIES=2;authRetryCount=0;async shouldRetryWithHeaders(e,r){if(r.status===401||r.status===403)return this.authRetryCount>=t.MAX_AUTH_RETRIES?void 0:(this.authRetryCount++,this.headers());this.authRetryCount=0}async initialize(){}};var per=6e4;async function Vv(t){if(t.startsWith("$$")||t.startsWith("!!"))return t.slice(1);if(t.startsWith("$")){let e=t.slice(1),r=process.env[e];if(r===void 0||r==="")throw new Error(`Environment variable '${e}' is not set or is empty. Please set it before using this agent.`);return B.debug(`[AuthValueResolver] Resolved env var: ${e}`),r}if(t.startsWith("!")){let e=t.slice(1).trim();if(!e)throw new Error("Empty command in auth value. Expected format: !command");B.debug("[AuthValueResolver] Executing command for auth value");let r=T0();try{let{stdout:n}=await Sl(r.executable,[...r.argsPrefix,e],{signal:AbortSignal.timeout(per),windowsHide:!0}),o=n.trim();if(!o)throw new Error(`Command '${e}' returned empty output`);return o}catch(n){throw n instanceof Error&&n.name==="AbortError"?new Error(`Command '${e}' timed out after ${per/1e3} seconds`):n}}return t}function fer(t){return t.startsWith("$")||t.startsWith("!")}var Lei="X-API-Key",Zle=class extends ah{config;type="apiKey";resolvedKey;headerName;constructor(e){super(),this.config=e,this.headerName=e.name??Lei}async initialize(){fer(this.config.key)?(this.resolvedKey=await Vv(this.config.key),B.debug(`[ApiKeyAuthProvider] Resolved API key from: ${this.config.key.startsWith("$")?"env var":"command"}`)):this.resolvedKey=this.config.key}async headers(){if(!this.resolvedKey)throw new Error("ApiKeyAuthProvider not initialized. Call initialize() first.");return{[this.headerName]:this.resolvedKey}}async shouldRetryWithHeaders(e,r){if(r.status!==401&&r.status!==403){this.authRetryCount=0;return}if(!(!this.config.key.startsWith("!")||this.config.key.startsWith("!!"))&&!(this.authRetryCount>=ah.MAX_AUTH_RETRIES))return this.authRetryCount++,B.debug("[ApiKeyAuthProvider] Re-resolving API key after auth failure"),this.resolvedKey=await Vv(this.config.key),this.headers()}};var ece=class extends ah{config;type="http";resolvedToken;resolvedUsername;resolvedPassword;resolvedValue;constructor(e){super(),this.config=e}async initialize(){let e=this.config;"token"in e?this.resolvedToken=await Vv(e.token):"username"in e?(this.resolvedUsername=await Vv(e.username),this.resolvedPassword=await Vv(e.password)):this.resolvedValue=await Vv(e.value),B.debug(`[HttpAuthProvider] Initialized with scheme: ${this.config.scheme}`)}async headers(){let e=this.config;if("token"in e){if(!this.resolvedToken)throw new Error("HttpAuthProvider not initialized");return{Authorization:`Bearer ${this.resolvedToken}`}}if("username"in e){if(!this.resolvedUsername||!this.resolvedPassword)throw new Error("HttpAuthProvider not initialized");return{Authorization:`Basic ${Buffer.from(`${this.resolvedUsername}:${this.resolvedPassword}`).toString("base64")}`}}if(!this.resolvedValue)throw new Error("HttpAuthProvider not initialized");return{Authorization:`${e.scheme} ${this.resolvedValue}`}}async shouldRetryWithHeaders(e,r){if(r.status===401||r.status===403){if(this.authRetryCount>=ah.MAX_AUTH_RETRIES)return;B.debug("[HttpAuthProvider] Re-resolving values after auth failure"),await this.initialize()}return super.shouldRetryWithHeaders(e,r)}};var her=Fe(Cs(),1);var RC=class extends Error{constructor(e){super(e),this.name="ResourceMismatchError"}},wk=5*60*1e3,Ws=class{static buildWellKnownUrls(e,r=!1){let n=new URL(e),o=`${n.protocol}//${n.host}`,s=r?"":n.pathname.replace(/\/$/,"");return{protectedResource:new URL(`/.well-known/oauth-protected-resource${s}`,o).toString(),authorizationServer:new URL(`/.well-known/oauth-authorization-server${s}`,o).toString()}}static async fetchProtectedResourceMetadata(e){try{let r=await fetch(e);return r.ok?await r.json():null}catch(r){return B.debug(`Failed to fetch protected resource metadata from ${e}: ${Se(r)}`),null}}static async fetchAuthorizationServerMetadata(e){try{let r=await fetch(e);return r.ok?await r.json():null}catch(r){return B.debug(`Failed to fetch authorization server metadata from ${e}: ${Se(r)}`),null}}static metadataToOAuthConfig(e){return{authorizationUrl:e.authorization_endpoint,issuer:e.issuer,tokenUrl:e.token_endpoint,scopes:e.scopes_supported||[],registrationUrl:e.registration_endpoint}}static async discoverAuthorizationServerMetadata(e){let r=new URL(e),n=`${r.protocol}//${r.host}`,o=[];r.pathname!=="/"&&(o.push(new URL(`/.well-known/oauth-authorization-server${r.pathname}`,n).toString()),o.push(new URL(`/.well-known/openid-configuration${r.pathname}`,n).toString()),o.push(new URL(`${r.pathname}/.well-known/openid-configuration`,n).toString())),o.push(new URL("/.well-known/oauth-authorization-server",n).toString()),o.push(new URL("/.well-known/openid-configuration",n).toString());for(let s of o){let c=await this.fetchAuthorizationServerMetadata(s);if(c)return c}return B.debug(`Metadata discovery failed for authorization server ${e}`),null}static async discoverOAuthConfig(e){try{let r=this.buildWellKnownUrls(e),n=await this.fetchProtectedResourceMetadata(r.protectedResource);if(!n){let s=new URL(e);if(s.pathname&&s.pathname!=="/"){let c=this.buildWellKnownUrls(e,!0);n=await this.fetchProtectedResourceMetadata(c.protectedResource)}}if(n){let s=this.buildResourceParameter(e);if(!this.isEquivalentResourceIdentifier(n.resource,s))throw new RC(`Protected resource ${n.resource} does not match expected ${s}`)}if(n?.authorization_servers?.length){let s=n.authorization_servers[0],c=await this.discoverAuthorizationServerMetadata(s);if(c){let u=this.metadataToOAuthConfig(c);return c.registration_endpoint&&B.log("Dynamic client registration is supported at:",c.registration_endpoint),u}}B.debug(`Trying OAuth discovery fallback at ${e}`);let o=await this.discoverAuthorizationServerMetadata(e);if(o){let s=this.metadataToOAuthConfig(o);return o.registration_endpoint&&B.log("Dynamic client registration is supported at:",o.registration_endpoint),s}return null}catch(r){if(r instanceof RC)throw r;return B.debug(`Failed to discover OAuth configuration: ${Se(r)}`),null}}static parseWWWAuthenticateHeader(e){let r=e.match(/resource_metadata="([^"]+)"/);return r?r[1]:null}static async discoverOAuthFromWWWAuthenticate(e,r){let n=this.parseWWWAuthenticateHeader(e);if(!n)return null;let o=await this.fetchProtectedResourceMetadata(n);if(o&&r){let u=this.buildResourceParameter(r);if(!this.isEquivalentResourceIdentifier(o.resource,u))throw new RC(`Protected resource ${o.resource} does not match expected ${u}`)}if(!o?.authorization_servers?.length)return null;let s=o.authorization_servers[0],c=await this.discoverAuthorizationServerMetadata(s);return c?this.metadataToOAuthConfig(c):null}static extractBaseUrl(e){let r=new URL(e);return`${r.protocol}//${r.host}`}static isSSEEndpoint(e){return e.includes("/sse")||!e.includes("/mcp")}static buildResourceParameter(e){let r=new URL(e);return`${r.protocol}//${r.host}${r.pathname}`}static isEquivalentResourceIdentifier(e,r){let n=o=>{try{return this.buildResourceParameter(o)}catch{return o}};return n(e)===n(r)}static parseTokenExpiry(e){try{let r=JSON.parse(Buffer.from(e.split(".")[1],"base64").toString());if(r&&typeof r.exp=="number")return r.exp*1e3}catch(r){B.error("Failed to parse ID token for expiry time with error:",r)}}};var ger=/^(.*\.)?run\.app$/,Mei=[/^.+\.googleapis\.com$/,ger],tce=class extends ah{config;type="google-credentials";auth;useIdToken=!1;audience;cachedToken;tokenExpiryTime;constructor(e,r){if(super(),this.config=e,!r)throw new Error("targetUrl must be provided to GoogleCredentialsAuthProvider to determine token audience.");let n=new URL(r).hostname;if(ger.test(n)&&(this.useIdToken=!0),this.audience=n,!this.useIdToken&&!Mei.some(c=>c.test(n)))throw new Error(`Host "${n}" is not an allowed host for Google Credential provider.`);let s=this.config.scopes&&this.config.scopes.length>0?this.config.scopes:["https://www.googleapis.com/auth/cloud-platform"];this.auth=new her.GoogleAuth({scopes:s})}async initialize(){}async headers(){if(this.cachedToken&&this.tokenExpiryTime&&Date.now()<this.tokenExpiryTime-wk)return{Authorization:`Bearer ${this.cachedToken}`};if(this.cachedToken=void 0,this.tokenExpiryTime=void 0,this.useIdToken)try{let r=await(await this.auth.getIdTokenClient(this.audience)).idTokenProvider.fetchIdToken(this.audience),n=Ws.parseTokenExpiry(r);return n&&(this.tokenExpiryTime=n,this.cachedToken=r),{Authorization:`Bearer ${r}`}}catch(e){let r=`Failed to get ADC ID token: ${e instanceof Error?e.message:String(e)}`;throw B.error(r,e),new Error(r)}try{let e=await this.auth.getClient(),r=await e.getAccessToken();if(r.token){this.cachedToken=r.token;let n=e.credentials;return n.expiry_date&&(this.tokenExpiryTime=n.expiry_date),{Authorization:`Bearer ${r.token}`}}throw new Error("Failed to retrieve ADC access token.")}catch(e){let r=`Failed to get ADC access token: ${e instanceof Error?e.message:String(e)}`;throw B.error(r,e),new Error(r)}}async shouldRetryWithHeaders(e,r){if(r.status!==401&&r.status!==403){this.authRetryCount=0;return}if(!(this.authRetryCount>=ah.MAX_AUTH_RETRIES))return this.authRetryCount++,B.debug("[GoogleCredentialsAuthProvider] Re-fetching token after auth failure"),this.cachedToken=void 0,this.tokenExpiryTime=void 0,this.headers()}};var Hv=class t{static async create(e){let{agentName:r,authConfig:n,agentCard:o}=e;if(!n)return o?.securitySchemes&&Object.keys(o.securitySchemes).length>0,void 0;switch(n.type){case"google-credentials":{let s=new tce(n,e.targetUrl);return await s.initialize(),s}case"apiKey":{let s=new Zle(n);return await s.initialize(),s}case"http":{let s=new ece(n);return await s.initialize(),s}case"oauth2":{let{OAuth2AuthProvider:s}=await import("./oauth2-provider-P65NTFUD.js"),c=new s(n,e.agentName??"unknown",o,e.agentCardUrl);return await c.initialize(),c}case"openIdConnect":throw new Error("openIdConnect auth provider not yet implemented");default:{let s=n;throw new Error(`Unknown auth type: ${s.type}`)}}}static async createFromConfig(e,r){return await t.create({authConfig:e,agentName:r})}static validateAuthConfig(e,r){if(!r||Object.keys(r).length===0)return{valid:!0};let n=Object.keys(r);if(!e)return{valid:!1,diff:{requiredSchemes:n,configuredType:void 0,missingConfig:["Authentication is required but not configured"]}};let o=t.findMatchingScheme(e,r);return o.matched?{valid:!0}:{valid:!1,diff:{requiredSchemes:n,configuredType:e.type,missingConfig:o.missingConfig}}}static findMatchingScheme(e,r){let n=[];for(let[o,s]of Object.entries(r))switch(s.type){case"apiKey":if(e.type==="apiKey")return{matched:!0,missingConfig:[]};n.push(`Scheme '${o}' requires apiKey authentication`);break;case"http":if(e.type==="http"){if(e.scheme.toLowerCase()===s.scheme.toLowerCase())return{matched:!0,missingConfig:[]};n.push(`Scheme '${o}' requires HTTP ${s.scheme} authentication, but ${e.scheme} was configured`)}else{if(e.type==="google-credentials"&&s.scheme.toLowerCase()==="bearer")return{matched:!0,missingConfig:[]};n.push(`Scheme '${o}' requires HTTP ${s.scheme} authentication`)}break;case"oauth2":if(e.type==="oauth2")return{matched:!0,missingConfig:[]};n.push(`Scheme '${o}' requires OAuth 2.0 authentication`);break;case"openIdConnect":if(e.type==="openIdConnect")return{matched:!0,missingConfig:[]};n.push(`Scheme '${o}' requires OpenID Connect authentication`);break;case"mutualTLS":n.push(`Scheme '${o}' requires mTLS authentication (not yet supported)`);break;default:{let c=s;n.push(`Unknown security scheme type: ${c.type}`)}}return{matched:!1,missingConfig:n}}static describeRequiredAuth(e){let r=[];for(let[n,o]of Object.entries(e))switch(o.type){case"apiKey":r.push(`API Key (${n}): Send ${o.name} in ${o.in}`);break;case"http":r.push(`HTTP ${o.scheme} (${n})`);break;case"oauth2":r.push(`OAuth 2.0 (${n})`);break;case"openIdConnect":r.push(`OpenID Connect (${n})`);break;case"mutualTLS":r.push(`Mutual TLS (${n})`);break;default:{let s=o;r.push(`Unknown (${n}): ${s.type}`)}}return r.join(" OR ")}};var mer=100,Ck=class t{config;runtimeAliases={};runtimeOverrides=[];constructor(e){this.config=e}getAvailableModelOptions(e){let r=this.config.modelDefinitions??{},n=e.hasAccessToPreview??!1,o=e.useGemini3_1??!1,s=e.useGemini3_1FlashLite??!1,c=Object.entries(r).filter(([a,p])=>!(p.isVisible!==!0||p.isPreview&&!n||p.tier!=="auto")).map(([a,p])=>({modelId:a,name:p.displayName??j1(a),description:a==="auto-gemini-3"&&o?(p.dialogDescription??"").replace("gemini-3-pro","gemini-3.1-pro"):p.dialogDescription??"",tier:p.tier??"auto"})),u=Object.entries(r).filter(([a,p])=>!(p.isVisible!==!0||p.isPreview&&!n||p.tier==="auto"||e.hasAccessToProModel===!1&&_Ke(a)||a===Ex&&!o||a===VQ&&!s)).map(([a,p])=>{let f=this.resolveModelId(a,e),g=this.resolveModelId(a,{useGemini3_1:o,useGemini3_1FlashLite:s});return{modelId:f,name:p.displayName??j1(g),description:p.dialogDescription??"",tier:p.tier??"custom"}}),d=new Set,l=u.filter(a=>d.has(a.modelId)?!1:(d.add(a.modelId),!0));return[...c,...l]}getModelDefinition(e){let r=this.config.modelDefinitions?.[e];if(r)return r;if(!e.startsWith("gemini-"))return{tier:"custom",family:"custom",features:{}}}getModelDefinitions(){return this.config.modelDefinitions??{}}matches(e,r){return Object.entries(e).every(([n,o])=>{if(o===void 0)return!0;switch(n){case"useGemini3_1":return o===r.useGemini3_1;case"useGemini3_1FlashLite":return o===r.useGemini3_1FlashLite;case"useCustomTools":return o===r.useCustomTools;case"hasAccessToPreview":return o===r.hasAccessToPreview;case"requestedModels":return Array.isArray(o)&&!!r.requestedModel&&o.includes(r.requestedModel);default:return!1}})}resolveModelId(e,r={}){let n=this.config.modelIdResolutions?.[e];if(!n)return e;for(let o of n.contexts??[])if(this.matches(o.condition,r))return o.target;return n.default}resolveClassifierModelId(e,r,n={}){let o=this.config.classifierIdResolutions?.[e],s={...n,requestedModel:r};if(!o)return this.resolveModelId(e,s);for(let c of o.contexts??[])if(this.matches(c.condition,s))return c.target;return o.default}getModelChain(e){return this.config.modelChains?.[e]}resolveChain(e,r={}){let n=this.config.modelChains?.[e];if(n)return n.map(o=>({...o,model:this.resolveModelId(o.model,r)}))}registerRuntimeModelConfig(e,r){this.runtimeAliases[e]=r}registerRuntimeModelOverride(e){this.runtimeOverrides.push(e)}internalGetResolvedConfig(e){let{aliases:r={},customAliases:n={},overrides:o=[],customOverrides:s=[]}=this.config||{},c={...r,...n,...this.runtimeAliases},{aliasChain:u,baseModel:d,resolvedConfig:l}=this.resolveAliasChain(e.model,c,e.isChatModel),a=this.buildModelLevelMap(u,d),p=[...o,...s,...this.runtimeOverrides],f=this.findMatchingOverrides(p,e,a);this.sortOverrides(f);let g={model:d,generateContentConfig:l};for(let y of f)g=t.merge(g,y.modelConfig);return{model:g.model,generateContentConfig:g.generateContentConfig??{}}}resolveAliasChain(e,r,n){let o=[];if(r[e]){let s=e,c=new Set;for(;s;){let l=r[s];if(!l)throw new Error(`Alias "${s}" not found.`);if(c.size>=mer)throw new Error(`Alias inheritance chain exceeded maximum depth of ${mer}.`);if(c.has(s))throw new Error(`Circular alias dependency: ${[...c,s].join(" -> ")}`);c.add(s),o.push(s),s=l.extends}let u=[...o].reverse(),d={};for(let l of u){let a=r[l];d=t.merge(d,a.modelConfig)}return{aliasChain:u,baseModel:d.model,resolvedConfig:d.generateContentConfig??{}}}if(n){let s="chat-base";if(r[s]){let c=this.resolveAliasChain(s,r);return{aliasChain:[...c.aliasChain,e],baseModel:e,resolvedConfig:c.resolvedConfig}}}return{aliasChain:[e],baseModel:e,resolvedConfig:{}}}buildModelLevelMap(e,r){let n=new Map;return r&&n.set(r,0),e.forEach((o,s)=>n.set(o,s+1)),n}findMatchingOverrides(e,r,n){return e.map((o,s)=>{let c=Object.entries(o.match);if(c.length===0)return null;let u=0;return c.every(([l,a])=>{if(l==="model"){let p=n.get(a);return p===void 0?!1:(u=p,!0)}return l==="overrideScope"&&a==="core"?r.overrideScope==="core"||!r.overrideScope:r[l]===a})?{specificity:c.length,level:u,modelConfig:o.modelConfig,index:s}:null}).filter(o=>o!==null)}sortOverrides(e){e.sort((r,n)=>r.level!==n.level?r.level-n.level:r.specificity!==n.specificity?r.specificity-n.specificity:r.index-n.index)}getResolvedConfig(e){let r=this.internalGetResolvedConfig(e);if(!r.model)throw new Error(`Could not resolve a model name for alias "${e.model}". Please ensure the alias chain or a matching override specifies a model.`);return{model:r.model,generateContentConfig:r.generateContentConfig}}static isObject(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}static merge(e,r){return{model:r.model??e.model,generateContentConfig:t.deepMerge(e.generateContentConfig,r.generateContentConfig)}}static deepMerge(e,r){return t.genericDeepMerge(e,r)}static genericDeepMerge(...e){return e.reduce((r,n)=>(n&&Object.keys(n).forEach(o=>{let s=r[o],c=n[o];t.isObject(s)&&t.isObject(c)?r[o]=t.genericDeepMerge(s,c):r[o]=c}),r),{})}};var $m=class extends Error{userMessage;agentName;constructor(e,r,n,o){super(r,o),this.name="A2AAgentError",this.agentName=e,this.userMessage=n}},WQe=class extends $m{constructor(e,r){let n=`Agent card not found at ${r} (HTTP 404)`,o=`Agent card not found (404) at ${r}. Verify the agent_card_url in your agent definition.`;super(e,n,o),this.name="AgentCardNotFoundError"}},rce=class extends $m{statusCode;constructor(e,r,n){let o=n===401?"Unauthorized":"Forbidden",s=`Agent card request returned ${n} ${o} for ${r}`,c=`Authentication failed (${n} ${o}) at ${r}. Check the "auth" configuration in your agent definition.`;super(e,s,c),this.name="AgentCardAuthError",this.statusCode=n}},nce=class extends $m{requiredAuth;missingFields;constructor(e,r,n){let o=`Agent "${e}" requires authentication but none is configured`,s=`Agent requires ${r} but no auth is configured. Missing: ${n.join(", ")}`;super(e,o,s),this.name="AgentAuthConfigMissingError",this.requiredAuth=r,this.missingFields=n}},ice=class extends $m{constructor(e,r,n){let o=n instanceof Error?n.message:String(n),s=`Failed to connect to agent "${e}" at ${r}: ${o}`,c=`Connection failed for ${r}: ${o}`;super(e,s,c,{cause:n}),this.name="AgentConnectionError"}};function Bei(t){return typeof t=="object"&&t!==null}function Uei(t){let e=[],r=t,n=0,o=10;for(;r&&n<o;){if(Bei(r)){let s=r;r instanceof Error?e.push(r.message):typeof s.message=="string"&&e.push(s.message),typeof s.code=="string"&&e.push(s.code),typeof s.status=="number"?e.push(String(s.status)):typeof s.statusCode=="number"&&e.push(String(s.statusCode)),r=s.cause}else if(typeof r=="string"){e.push(r);break}else{e.push(String(r));break}n++}return e.join(" ")}function yer(t,e,r){let n=Uei(r);return/\b(ECONNREFUSED|ENOTFOUND|EHOSTUNREACH|ETIMEDOUT)\b/i.test(n)?new ice(t,e,r):/\b404\b|\bnot[\s_-]?found\b/i.test(n)?new WQe(t,e):/\b401\b|unauthorized/i.test(n)?new rce(t,e,401):/\b403\b|forbidden/i.test(n)?new rce(t,e,403):new ice(t,e,r)}function n7(t){return`${t.name}-config`}var Aer="AgentRegistry (Dynamic)",oce=class{config;agents=new Map;allDefinitions=new Map;builtInAgents=new Set;initialized=!1;constructor(e){this.config=e}async initialize(){if(this.initialized){await this.loadAgents();return}this.initialized=!0,Ee.on(vr.ModelChanged,this.onModelChanged),await this.loadAgents()}isBuiltIn(e){return this.builtInAgents.has(e)}onModelChanged=()=>{this.refreshAgents("local").catch(e=>{B.error("[AgentRegistry] Failed to refresh agents on model change:",e)})};async reload(){let e=new Map(this.agents),r=[];this.config.getA2AClientManager()?.clearCache(),await this.config.reloadAgents(),await this.loadAgents(r);let n=Array.from(this.agents.values()),o=[],s=[],c=[],u=0,d=0;for(let l of n){l.kind==="local"?u++:l.kind==="remote"&&d++;let a=e.get(l.name);a?l.metadata?.hash!==a.metadata?.hash&&s.push(l.name):o.push(l.name)}for(let l of e.keys())this.agents.has(l)||c.push(l);return Ee.emitAgentsRefreshed(),{totalLoaded:n.length,localCount:u,remoteCount:d,newAgents:o,updatedAgents:s,deletedAgents:c,errors:r}}async acknowledgeAgent(e){let r=this.config.getAcknowledgedAgentsService(),n=this.config.getProjectRoot();e.metadata?.hash&&(await r.acknowledge(n,e.name,e.metadata.hash),await this.registerAgent(e),Ee.emitAgentsRefreshed())}dispose(){Ee.off(vr.ModelChanged,this.onModelChanged)}async loadAgents(e){if(this.agents.clear(),this.allDefinitions.clear(),this.loadBuiltInAgents(),this.config.getPolicyEngine()?.removeRulesBySource(Aer),!this.config.isAgentsEnabled())return;let r=Yt.getUserAgentsDir(),n=await qQe(r);for(let c of n.errors){B.warn(`[AgentRegistry] Error loading user agent: ${c.message}`);let u=`Agent loading error: ${c.message}`;e?.push(u),Ee.emitFeedback("error",u)}await Promise.allSettled(n.agents.map(async c=>{try{this.ensureRemoteAgentHash(c),await this.registerAgent(c,e)}catch(u){let d=`Error registering user agent "${c.name}": ${u instanceof Error?u.message:String(u)}`;B.warn(`[AgentRegistry] ${d}`,u),e?.push(d),Ee.emitFeedback("error",d)}}));let o=this.config.getFolderTrust(),s=this.config.isTrustedFolder();if(!o||s){let c=this.config.storage.getProjectAgentsDir(),u=await qQe(c);for(let f of u.errors){let g=`Agent loading error: ${f.message}`;e?.push(g),Ee.emitFeedback("error",g)}let d=this.config.getAcknowledgedAgentsService(),l=this.config.getProjectRoot(),a=[],p=[];for(let f of u.agents){if(this.ensureRemoteAgentHash(f),!f.metadata?.hash){p.push(f);continue}await d.isAcknowledged(l,f.name,f.metadata.hash)?p.push(f):a.push(f)}a.length>0&&Ee.emitAgentsDiscovered(a),await Promise.allSettled(p.map(async f=>{try{await this.registerAgent(f,e)}catch(g){let y=`Error registering project agent "${f.name}": ${g instanceof Error?g.message:String(g)}`;B.warn(`[AgentRegistry] ${y}`,g),e?.push(y),Ee.emitFeedback("error",y)}}))}else Ee.emitFeedback("info","Skipping project agents due to untrusted folder. To enable, ensure that the project root is trusted.");for(let c of this.config.getExtensions())c.isActive&&c.agents&&await Promise.allSettled(c.agents.map(async u=>{try{await this.registerAgent(u,e)}catch(d){let l=`Error registering extension agent "${u.name}": ${d instanceof Error?d.message:String(d)}`;B.warn(`[AgentRegistry] ${l}`,d),e?.push(l),Ee.emitFeedback("error",l)}}));this.config.getDebugMode()&&B.log(`[AgentRegistry] Loaded with ${this.agents.size} agents.`)}loadBuiltInAgents(){let e=Ile(this.config);this.builtInAgents.add(e.name),this.registerLocalAgent(e);let r=ler(this.config);this.builtInAgents.add(r.name),this.registerLocalAgent(r);let n=cer(this.config);this.builtInAgents.add(n.name),this.registerLocalAgent(n);let o=this.config.getBrowserAgentConfig();if(o.enabled){let s=process.env.SANDBOX,c=!!s&&s!=="sandbox-exec"&&s!=="sandbox:none",u=o.customConfig.sessionMode??"persistent";if(c&&u!=="existing")Ee.emitFeedback("info",'Browser agent disabled in container sandbox. To use it, set sessionMode to "existing" in settings and start Chrome with --remote-debugging-port=9222 on the host.');else{let d=Xle(this.config);this.builtInAgents.add(d.name),this.registerLocalAgent(d)}}}async refreshAgents(e="all"){this.loadBuiltInAgents(),await Promise.allSettled(Array.from(this.agents.values()).map(async r=>{(e==="all"||r.kind===e)&&await this.registerAgent(r)}))}async registerAgent(e,r){e.kind==="local"?this.registerLocalAgent(e):e.kind==="remote"&&await this.registerRemoteAgent(e,r)}registerLocalAgent(e){if(e.kind!=="local")return;if(!e.name||!e.description){B.warn("[AgentRegistry] Skipping invalid agent definition. Missing name or description.");return}this.allDefinitions.set(e.name,e);let r=this.config.getAgentsSettings().overrides?.[e.name];if(!this.isAgentEnabled(e,r)){this.config.getDebugMode()&&B.log(`[AgentRegistry] Skipping disabled agent '${e.name}'`);return}this.agents.has(e.name)&&this.config.getDebugMode()&&B.log(`[AgentRegistry] Overriding agent '${e.name}'`);let n=this.applyOverrides(e,r);this.agents.set(n.name,n),this.registerModelConfigs(n),this.addAgentPolicy(n)}addAgentPolicy(e){let r=this.config.getPolicyEngine();if(r){if(r.hasRuleForTool(e.name,!0)){this.config.getDebugMode()&&B.log(`[AgentRegistry] User policy exists for '${e.name}', skipping dynamic registration.`);return}e.kind==="remote"&&r.addRule({toolName:PC.Name,argsPattern:new RegExp(`"agent_name":\\s*"${e.name}"`),decision:Ke.ASK_USER,priority:UQ+.1,source:Aer})}}isAgentEnabled(e,r){let o=!(e.experimental===!0);return r&&r.enabled!==void 0&&(o=r.enabled),o}async registerRemoteAgent(e,r){if(e.kind!=="remote")return;if(!e.name){B.warn("[AgentRegistry] Skipping invalid agent definition. Missing name.");return}this.allDefinitions.set(e.name,e);let n=this.config.getAgentsSettings().overrides?.[e.name];if(!this.isAgentEnabled(e,n)){this.config.getDebugMode()&&B.log(`[AgentRegistry] Skipping disabled remote agent '${e.name}'`);return}this.agents.has(e.name)&&this.config.getDebugMode()&&B.log(`[AgentRegistry] Overriding agent '${e.name}'`);let o=e;o.originalDescription===void 0&&(o.originalDescription=o.description);try{let s=this.config.getA2AClientManager();if(!s){B.warn(`[AgentRegistry] Skipping remote agent '${e.name}': A2AClientManager is not available.`);return}let c=jle(o),u;if(e.auth){let f=await Hv.create({authConfig:e.auth,agentName:e.name,targetUrl:c,agentCardUrl:o.agentCardUrl});if(!f)throw new Error(`Failed to create auth provider for agent '${e.name}'`);u=f}let d=await s.loadAgent(o.name,Fle(o),u);if(d.securitySchemes){let f=Hv.validateAuthConfig(e.auth,d.securitySchemes);if(!f.valid&&f.diff){let g=Hv.describeRequiredAuth(d.securitySchemes),y=new nce(e.name,g,f.diff.missingConfig);Ee.emitFeedback("warning",`[${e.name}] Agent requires authentication: ${g}`),B.warn(`[AgentRegistry] ${y.message}`)}}let l=o.originalDescription,a=d.description,p=[];if(l?.trim()&&p.push(`User Description: ${l.trim()}`),a?.trim()&&p.push(`Agent Description: ${a.trim()}`),d.skills&&d.skills.length>0){let f=d.skills.map(g=>`${g.name}: ${g.description||"No description provided"}`).join(`
2517
+ First, use <list_pages/> to check if there are any existing pages that can fulfill the user's request. If not, you MUST use <new_page/> to open the relevant URL unless the user explicitly provides different instructions.`,systemPrompt:Dei(e,t.getBrowserAgentConfig().customConfig.allowedDomains)}}};var ah=class t{static MAX_AUTH_RETRIES=2;authRetryCount=0;async shouldRetryWithHeaders(e,r){if(r.status===401||r.status===403)return this.authRetryCount>=t.MAX_AUTH_RETRIES?void 0:(this.authRetryCount++,this.headers());this.authRetryCount=0}async initialize(){}};var per=6e4;async function Vv(t){if(t.startsWith("$$")||t.startsWith("!!"))return t.slice(1);if(t.startsWith("$")){let e=t.slice(1),r=process.env[e];if(r===void 0||r==="")throw new Error(`Environment variable '${e}' is not set or is empty. Please set it before using this agent.`);return B.debug(`[AuthValueResolver] Resolved env var: ${e}`),r}if(t.startsWith("!")){let e=t.slice(1).trim();if(!e)throw new Error("Empty command in auth value. Expected format: !command");B.debug("[AuthValueResolver] Executing command for auth value");let r=T0();try{let{stdout:n}=await Sl(r.executable,[...r.argsPrefix,e],{signal:AbortSignal.timeout(per),windowsHide:!0}),o=n.trim();if(!o)throw new Error(`Command '${e}' returned empty output`);return o}catch(n){throw n instanceof Error&&n.name==="AbortError"?new Error(`Command '${e}' timed out after ${per/1e3} seconds`):n}}return t}function fer(t){return t.startsWith("$")||t.startsWith("!")}var Lei="X-API-Key",Zle=class extends ah{config;type="apiKey";resolvedKey;headerName;constructor(e){super(),this.config=e,this.headerName=e.name??Lei}async initialize(){fer(this.config.key)?(this.resolvedKey=await Vv(this.config.key),B.debug(`[ApiKeyAuthProvider] Resolved API key from: ${this.config.key.startsWith("$")?"env var":"command"}`)):this.resolvedKey=this.config.key}async headers(){if(!this.resolvedKey)throw new Error("ApiKeyAuthProvider not initialized. Call initialize() first.");return{[this.headerName]:this.resolvedKey}}async shouldRetryWithHeaders(e,r){if(r.status!==401&&r.status!==403){this.authRetryCount=0;return}if(!(!this.config.key.startsWith("!")||this.config.key.startsWith("!!"))&&!(this.authRetryCount>=ah.MAX_AUTH_RETRIES))return this.authRetryCount++,B.debug("[ApiKeyAuthProvider] Re-resolving API key after auth failure"),this.resolvedKey=await Vv(this.config.key),this.headers()}};var ece=class extends ah{config;type="http";resolvedToken;resolvedUsername;resolvedPassword;resolvedValue;constructor(e){super(),this.config=e}async initialize(){let e=this.config;"token"in e?this.resolvedToken=await Vv(e.token):"username"in e?(this.resolvedUsername=await Vv(e.username),this.resolvedPassword=await Vv(e.password)):this.resolvedValue=await Vv(e.value),B.debug(`[HttpAuthProvider] Initialized with scheme: ${this.config.scheme}`)}async headers(){let e=this.config;if("token"in e){if(!this.resolvedToken)throw new Error("HttpAuthProvider not initialized");return{Authorization:`Bearer ${this.resolvedToken}`}}if("username"in e){if(!this.resolvedUsername||!this.resolvedPassword)throw new Error("HttpAuthProvider not initialized");return{Authorization:`Basic ${Buffer.from(`${this.resolvedUsername}:${this.resolvedPassword}`).toString("base64")}`}}if(!this.resolvedValue)throw new Error("HttpAuthProvider not initialized");return{Authorization:`${e.scheme} ${this.resolvedValue}`}}async shouldRetryWithHeaders(e,r){if(r.status===401||r.status===403){if(this.authRetryCount>=ah.MAX_AUTH_RETRIES)return;B.debug("[HttpAuthProvider] Re-resolving values after auth failure"),await this.initialize()}return super.shouldRetryWithHeaders(e,r)}};var her=Fe(Cs(),1);var RC=class extends Error{constructor(e){super(e),this.name="ResourceMismatchError"}},wk=5*60*1e3,Ws=class{static buildWellKnownUrls(e,r=!1){let n=new URL(e),o=`${n.protocol}//${n.host}`,s=r?"":n.pathname.replace(/\/$/,"");return{protectedResource:new URL(`/.well-known/oauth-protected-resource${s}`,o).toString(),authorizationServer:new URL(`/.well-known/oauth-authorization-server${s}`,o).toString()}}static async fetchProtectedResourceMetadata(e){try{let r=await fetch(e);return r.ok?await r.json():null}catch(r){return B.debug(`Failed to fetch protected resource metadata from ${e}: ${Se(r)}`),null}}static async fetchAuthorizationServerMetadata(e){try{let r=await fetch(e);return r.ok?await r.json():null}catch(r){return B.debug(`Failed to fetch authorization server metadata from ${e}: ${Se(r)}`),null}}static metadataToOAuthConfig(e){return{authorizationUrl:e.authorization_endpoint,issuer:e.issuer,tokenUrl:e.token_endpoint,scopes:e.scopes_supported||[],registrationUrl:e.registration_endpoint}}static async discoverAuthorizationServerMetadata(e){let r=new URL(e),n=`${r.protocol}//${r.host}`,o=[];r.pathname!=="/"&&(o.push(new URL(`/.well-known/oauth-authorization-server${r.pathname}`,n).toString()),o.push(new URL(`/.well-known/openid-configuration${r.pathname}`,n).toString()),o.push(new URL(`${r.pathname}/.well-known/openid-configuration`,n).toString())),o.push(new URL("/.well-known/oauth-authorization-server",n).toString()),o.push(new URL("/.well-known/openid-configuration",n).toString());for(let s of o){let c=await this.fetchAuthorizationServerMetadata(s);if(c)return c}return B.debug(`Metadata discovery failed for authorization server ${e}`),null}static async discoverOAuthConfig(e){try{let r=this.buildWellKnownUrls(e),n=await this.fetchProtectedResourceMetadata(r.protectedResource);if(!n){let s=new URL(e);if(s.pathname&&s.pathname!=="/"){let c=this.buildWellKnownUrls(e,!0);n=await this.fetchProtectedResourceMetadata(c.protectedResource)}}if(n){let s=this.buildResourceParameter(e);if(!this.isEquivalentResourceIdentifier(n.resource,s))throw new RC(`Protected resource ${n.resource} does not match expected ${s}`)}if(n?.authorization_servers?.length){let s=n.authorization_servers[0],c=await this.discoverAuthorizationServerMetadata(s);if(c){let u=this.metadataToOAuthConfig(c);return c.registration_endpoint&&B.log("Dynamic client registration is supported at:",c.registration_endpoint),u}}B.debug(`Trying OAuth discovery fallback at ${e}`);let o=await this.discoverAuthorizationServerMetadata(e);if(o){let s=this.metadataToOAuthConfig(o);return o.registration_endpoint&&B.log("Dynamic client registration is supported at:",o.registration_endpoint),s}return null}catch(r){if(r instanceof RC)throw r;return B.debug(`Failed to discover OAuth configuration: ${Se(r)}`),null}}static parseWWWAuthenticateHeader(e){let r=e.match(/resource_metadata="([^"]+)"/);return r?r[1]:null}static async discoverOAuthFromWWWAuthenticate(e,r){let n=this.parseWWWAuthenticateHeader(e);if(!n)return null;let o=await this.fetchProtectedResourceMetadata(n);if(o&&r){let u=this.buildResourceParameter(r);if(!this.isEquivalentResourceIdentifier(o.resource,u))throw new RC(`Protected resource ${o.resource} does not match expected ${u}`)}if(!o?.authorization_servers?.length)return null;let s=o.authorization_servers[0],c=await this.discoverAuthorizationServerMetadata(s);return c?this.metadataToOAuthConfig(c):null}static extractBaseUrl(e){let r=new URL(e);return`${r.protocol}//${r.host}`}static isSSEEndpoint(e){return e.includes("/sse")||!e.includes("/mcp")}static buildResourceParameter(e){let r=new URL(e);return`${r.protocol}//${r.host}${r.pathname}`}static isEquivalentResourceIdentifier(e,r){let n=o=>{try{return this.buildResourceParameter(o)}catch{return o}};return n(e)===n(r)}static parseTokenExpiry(e){try{let r=JSON.parse(Buffer.from(e.split(".")[1],"base64").toString());if(r&&typeof r.exp=="number")return r.exp*1e3}catch(r){B.error("Failed to parse ID token for expiry time with error:",r)}}};var ger=/^(.*\.)?run\.app$/,Mei=[/^.+\.googleapis\.com$/,ger],tce=class extends ah{config;type="google-credentials";auth;useIdToken=!1;audience;cachedToken;tokenExpiryTime;constructor(e,r){if(super(),this.config=e,!r)throw new Error("targetUrl must be provided to GoogleCredentialsAuthProvider to determine token audience.");let n=new URL(r).hostname;if(ger.test(n)&&(this.useIdToken=!0),this.audience=n,!this.useIdToken&&!Mei.some(c=>c.test(n)))throw new Error(`Host "${n}" is not an allowed host for Google Credential provider.`);let s=this.config.scopes&&this.config.scopes.length>0?this.config.scopes:["https://www.googleapis.com/auth/cloud-platform"];this.auth=new her.GoogleAuth({scopes:s})}async initialize(){}async headers(){if(this.cachedToken&&this.tokenExpiryTime&&Date.now()<this.tokenExpiryTime-wk)return{Authorization:`Bearer ${this.cachedToken}`};if(this.cachedToken=void 0,this.tokenExpiryTime=void 0,this.useIdToken)try{let r=await(await this.auth.getIdTokenClient(this.audience)).idTokenProvider.fetchIdToken(this.audience),n=Ws.parseTokenExpiry(r);return n&&(this.tokenExpiryTime=n,this.cachedToken=r),{Authorization:`Bearer ${r}`}}catch(e){let r=`Failed to get ADC ID token: ${e instanceof Error?e.message:String(e)}`;throw B.error(r,e),new Error(r)}try{let e=await this.auth.getClient(),r=await e.getAccessToken();if(r.token){this.cachedToken=r.token;let n=e.credentials;return n.expiry_date&&(this.tokenExpiryTime=n.expiry_date),{Authorization:`Bearer ${r.token}`}}throw new Error("Failed to retrieve ADC access token.")}catch(e){let r=`Failed to get ADC access token: ${e instanceof Error?e.message:String(e)}`;throw B.error(r,e),new Error(r)}}async shouldRetryWithHeaders(e,r){if(r.status!==401&&r.status!==403){this.authRetryCount=0;return}if(!(this.authRetryCount>=ah.MAX_AUTH_RETRIES))return this.authRetryCount++,B.debug("[GoogleCredentialsAuthProvider] Re-fetching token after auth failure"),this.cachedToken=void 0,this.tokenExpiryTime=void 0,this.headers()}};var Hv=class t{static async create(e){let{agentName:r,authConfig:n,agentCard:o}=e;if(!n)return o?.securitySchemes&&Object.keys(o.securitySchemes).length>0,void 0;switch(n.type){case"google-credentials":{let s=new tce(n,e.targetUrl);return await s.initialize(),s}case"apiKey":{let s=new Zle(n);return await s.initialize(),s}case"http":{let s=new ece(n);return await s.initialize(),s}case"oauth2":{let{OAuth2AuthProvider:s}=await import("./oauth2-provider-NEH5B4N6.js"),c=new s(n,e.agentName??"unknown",o,e.agentCardUrl);return await c.initialize(),c}case"openIdConnect":throw new Error("openIdConnect auth provider not yet implemented");default:{let s=n;throw new Error(`Unknown auth type: ${s.type}`)}}}static async createFromConfig(e,r){return await t.create({authConfig:e,agentName:r})}static validateAuthConfig(e,r){if(!r||Object.keys(r).length===0)return{valid:!0};let n=Object.keys(r);if(!e)return{valid:!1,diff:{requiredSchemes:n,configuredType:void 0,missingConfig:["Authentication is required but not configured"]}};let o=t.findMatchingScheme(e,r);return o.matched?{valid:!0}:{valid:!1,diff:{requiredSchemes:n,configuredType:e.type,missingConfig:o.missingConfig}}}static findMatchingScheme(e,r){let n=[];for(let[o,s]of Object.entries(r))switch(s.type){case"apiKey":if(e.type==="apiKey")return{matched:!0,missingConfig:[]};n.push(`Scheme '${o}' requires apiKey authentication`);break;case"http":if(e.type==="http"){if(e.scheme.toLowerCase()===s.scheme.toLowerCase())return{matched:!0,missingConfig:[]};n.push(`Scheme '${o}' requires HTTP ${s.scheme} authentication, but ${e.scheme} was configured`)}else{if(e.type==="google-credentials"&&s.scheme.toLowerCase()==="bearer")return{matched:!0,missingConfig:[]};n.push(`Scheme '${o}' requires HTTP ${s.scheme} authentication`)}break;case"oauth2":if(e.type==="oauth2")return{matched:!0,missingConfig:[]};n.push(`Scheme '${o}' requires OAuth 2.0 authentication`);break;case"openIdConnect":if(e.type==="openIdConnect")return{matched:!0,missingConfig:[]};n.push(`Scheme '${o}' requires OpenID Connect authentication`);break;case"mutualTLS":n.push(`Scheme '${o}' requires mTLS authentication (not yet supported)`);break;default:{let c=s;n.push(`Unknown security scheme type: ${c.type}`)}}return{matched:!1,missingConfig:n}}static describeRequiredAuth(e){let r=[];for(let[n,o]of Object.entries(e))switch(o.type){case"apiKey":r.push(`API Key (${n}): Send ${o.name} in ${o.in}`);break;case"http":r.push(`HTTP ${o.scheme} (${n})`);break;case"oauth2":r.push(`OAuth 2.0 (${n})`);break;case"openIdConnect":r.push(`OpenID Connect (${n})`);break;case"mutualTLS":r.push(`Mutual TLS (${n})`);break;default:{let s=o;r.push(`Unknown (${n}): ${s.type}`)}}return r.join(" OR ")}};var mer=100,Ck=class t{config;runtimeAliases={};runtimeOverrides=[];constructor(e){this.config=e}getAvailableModelOptions(e){let r=this.config.modelDefinitions??{},n=e.hasAccessToPreview??!1,o=e.useGemini3_1??!1,s=e.useGemini3_1FlashLite??!1,c=Object.entries(r).filter(([a,p])=>!(p.isVisible!==!0||p.isPreview&&!n||p.tier!=="auto")).map(([a,p])=>({modelId:a,name:p.displayName??j1(a),description:a==="auto-gemini-3"&&o?(p.dialogDescription??"").replace("gemini-3-pro","gemini-3.1-pro"):p.dialogDescription??"",tier:p.tier??"auto"})),u=Object.entries(r).filter(([a,p])=>!(p.isVisible!==!0||p.isPreview&&!n||p.tier==="auto"||e.hasAccessToProModel===!1&&_Ke(a)||a===Ex&&!o||a===VQ&&!s)).map(([a,p])=>{let f=this.resolveModelId(a,e),g=this.resolveModelId(a,{useGemini3_1:o,useGemini3_1FlashLite:s});return{modelId:f,name:p.displayName??j1(g),description:p.dialogDescription??"",tier:p.tier??"custom"}}),d=new Set,l=u.filter(a=>d.has(a.modelId)?!1:(d.add(a.modelId),!0));return[...c,...l]}getModelDefinition(e){let r=this.config.modelDefinitions?.[e];if(r)return r;if(!e.startsWith("gemini-"))return{tier:"custom",family:"custom",features:{}}}getModelDefinitions(){return this.config.modelDefinitions??{}}matches(e,r){return Object.entries(e).every(([n,o])=>{if(o===void 0)return!0;switch(n){case"useGemini3_1":return o===r.useGemini3_1;case"useGemini3_1FlashLite":return o===r.useGemini3_1FlashLite;case"useCustomTools":return o===r.useCustomTools;case"hasAccessToPreview":return o===r.hasAccessToPreview;case"requestedModels":return Array.isArray(o)&&!!r.requestedModel&&o.includes(r.requestedModel);default:return!1}})}resolveModelId(e,r={}){let n=this.config.modelIdResolutions?.[e];if(!n)return e;for(let o of n.contexts??[])if(this.matches(o.condition,r))return o.target;return n.default}resolveClassifierModelId(e,r,n={}){let o=this.config.classifierIdResolutions?.[e],s={...n,requestedModel:r};if(!o)return this.resolveModelId(e,s);for(let c of o.contexts??[])if(this.matches(c.condition,s))return c.target;return o.default}getModelChain(e){return this.config.modelChains?.[e]}resolveChain(e,r={}){let n=this.config.modelChains?.[e];if(n)return n.map(o=>({...o,model:this.resolveModelId(o.model,r)}))}registerRuntimeModelConfig(e,r){this.runtimeAliases[e]=r}registerRuntimeModelOverride(e){this.runtimeOverrides.push(e)}internalGetResolvedConfig(e){let{aliases:r={},customAliases:n={},overrides:o=[],customOverrides:s=[]}=this.config||{},c={...r,...n,...this.runtimeAliases},{aliasChain:u,baseModel:d,resolvedConfig:l}=this.resolveAliasChain(e.model,c,e.isChatModel),a=this.buildModelLevelMap(u,d),p=[...o,...s,...this.runtimeOverrides],f=this.findMatchingOverrides(p,e,a);this.sortOverrides(f);let g={model:d,generateContentConfig:l};for(let y of f)g=t.merge(g,y.modelConfig);return{model:g.model,generateContentConfig:g.generateContentConfig??{}}}resolveAliasChain(e,r,n){let o=[];if(r[e]){let s=e,c=new Set;for(;s;){let l=r[s];if(!l)throw new Error(`Alias "${s}" not found.`);if(c.size>=mer)throw new Error(`Alias inheritance chain exceeded maximum depth of ${mer}.`);if(c.has(s))throw new Error(`Circular alias dependency: ${[...c,s].join(" -> ")}`);c.add(s),o.push(s),s=l.extends}let u=[...o].reverse(),d={};for(let l of u){let a=r[l];d=t.merge(d,a.modelConfig)}return{aliasChain:u,baseModel:d.model,resolvedConfig:d.generateContentConfig??{}}}if(n){let s="chat-base";if(r[s]){let c=this.resolveAliasChain(s,r);return{aliasChain:[...c.aliasChain,e],baseModel:e,resolvedConfig:c.resolvedConfig}}}return{aliasChain:[e],baseModel:e,resolvedConfig:{}}}buildModelLevelMap(e,r){let n=new Map;return r&&n.set(r,0),e.forEach((o,s)=>n.set(o,s+1)),n}findMatchingOverrides(e,r,n){return e.map((o,s)=>{let c=Object.entries(o.match);if(c.length===0)return null;let u=0;return c.every(([l,a])=>{if(l==="model"){let p=n.get(a);return p===void 0?!1:(u=p,!0)}return l==="overrideScope"&&a==="core"?r.overrideScope==="core"||!r.overrideScope:r[l]===a})?{specificity:c.length,level:u,modelConfig:o.modelConfig,index:s}:null}).filter(o=>o!==null)}sortOverrides(e){e.sort((r,n)=>r.level!==n.level?r.level-n.level:r.specificity!==n.specificity?r.specificity-n.specificity:r.index-n.index)}getResolvedConfig(e){let r=this.internalGetResolvedConfig(e);if(!r.model)throw new Error(`Could not resolve a model name for alias "${e.model}". Please ensure the alias chain or a matching override specifies a model.`);return{model:r.model,generateContentConfig:r.generateContentConfig}}static isObject(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}static merge(e,r){return{model:r.model??e.model,generateContentConfig:t.deepMerge(e.generateContentConfig,r.generateContentConfig)}}static deepMerge(e,r){return t.genericDeepMerge(e,r)}static genericDeepMerge(...e){return e.reduce((r,n)=>(n&&Object.keys(n).forEach(o=>{let s=r[o],c=n[o];t.isObject(s)&&t.isObject(c)?r[o]=t.genericDeepMerge(s,c):r[o]=c}),r),{})}};var $m=class extends Error{userMessage;agentName;constructor(e,r,n,o){super(r,o),this.name="A2AAgentError",this.agentName=e,this.userMessage=n}},WQe=class extends $m{constructor(e,r){let n=`Agent card not found at ${r} (HTTP 404)`,o=`Agent card not found (404) at ${r}. Verify the agent_card_url in your agent definition.`;super(e,n,o),this.name="AgentCardNotFoundError"}},rce=class extends $m{statusCode;constructor(e,r,n){let o=n===401?"Unauthorized":"Forbidden",s=`Agent card request returned ${n} ${o} for ${r}`,c=`Authentication failed (${n} ${o}) at ${r}. Check the "auth" configuration in your agent definition.`;super(e,s,c),this.name="AgentCardAuthError",this.statusCode=n}},nce=class extends $m{requiredAuth;missingFields;constructor(e,r,n){let o=`Agent "${e}" requires authentication but none is configured`,s=`Agent requires ${r} but no auth is configured. Missing: ${n.join(", ")}`;super(e,o,s),this.name="AgentAuthConfigMissingError",this.requiredAuth=r,this.missingFields=n}},ice=class extends $m{constructor(e,r,n){let o=n instanceof Error?n.message:String(n),s=`Failed to connect to agent "${e}" at ${r}: ${o}`,c=`Connection failed for ${r}: ${o}`;super(e,s,c,{cause:n}),this.name="AgentConnectionError"}};function Bei(t){return typeof t=="object"&&t!==null}function Uei(t){let e=[],r=t,n=0,o=10;for(;r&&n<o;){if(Bei(r)){let s=r;r instanceof Error?e.push(r.message):typeof s.message=="string"&&e.push(s.message),typeof s.code=="string"&&e.push(s.code),typeof s.status=="number"?e.push(String(s.status)):typeof s.statusCode=="number"&&e.push(String(s.statusCode)),r=s.cause}else if(typeof r=="string"){e.push(r);break}else{e.push(String(r));break}n++}return e.join(" ")}function yer(t,e,r){let n=Uei(r);return/\b(ECONNREFUSED|ENOTFOUND|EHOSTUNREACH|ETIMEDOUT)\b/i.test(n)?new ice(t,e,r):/\b404\b|\bnot[\s_-]?found\b/i.test(n)?new WQe(t,e):/\b401\b|unauthorized/i.test(n)?new rce(t,e,401):/\b403\b|forbidden/i.test(n)?new rce(t,e,403):new ice(t,e,r)}function n7(t){return`${t.name}-config`}var Aer="AgentRegistry (Dynamic)",oce=class{config;agents=new Map;allDefinitions=new Map;builtInAgents=new Set;initialized=!1;constructor(e){this.config=e}async initialize(){if(this.initialized){await this.loadAgents();return}this.initialized=!0,Ee.on(vr.ModelChanged,this.onModelChanged),await this.loadAgents()}isBuiltIn(e){return this.builtInAgents.has(e)}onModelChanged=()=>{this.refreshAgents("local").catch(e=>{B.error("[AgentRegistry] Failed to refresh agents on model change:",e)})};async reload(){let e=new Map(this.agents),r=[];this.config.getA2AClientManager()?.clearCache(),await this.config.reloadAgents(),await this.loadAgents(r);let n=Array.from(this.agents.values()),o=[],s=[],c=[],u=0,d=0;for(let l of n){l.kind==="local"?u++:l.kind==="remote"&&d++;let a=e.get(l.name);a?l.metadata?.hash!==a.metadata?.hash&&s.push(l.name):o.push(l.name)}for(let l of e.keys())this.agents.has(l)||c.push(l);return Ee.emitAgentsRefreshed(),{totalLoaded:n.length,localCount:u,remoteCount:d,newAgents:o,updatedAgents:s,deletedAgents:c,errors:r}}async acknowledgeAgent(e){let r=this.config.getAcknowledgedAgentsService(),n=this.config.getProjectRoot();e.metadata?.hash&&(await r.acknowledge(n,e.name,e.metadata.hash),await this.registerAgent(e),Ee.emitAgentsRefreshed())}dispose(){Ee.off(vr.ModelChanged,this.onModelChanged)}async loadAgents(e){if(this.agents.clear(),this.allDefinitions.clear(),this.loadBuiltInAgents(),this.config.getPolicyEngine()?.removeRulesBySource(Aer),!this.config.isAgentsEnabled())return;let r=Yt.getUserAgentsDir(),n=await qQe(r);for(let c of n.errors){B.warn(`[AgentRegistry] Error loading user agent: ${c.message}`);let u=`Agent loading error: ${c.message}`;e?.push(u),Ee.emitFeedback("error",u)}await Promise.allSettled(n.agents.map(async c=>{try{this.ensureRemoteAgentHash(c),await this.registerAgent(c,e)}catch(u){let d=`Error registering user agent "${c.name}": ${u instanceof Error?u.message:String(u)}`;B.warn(`[AgentRegistry] ${d}`,u),e?.push(d),Ee.emitFeedback("error",d)}}));let o=this.config.getFolderTrust(),s=this.config.isTrustedFolder();if(!o||s){let c=this.config.storage.getProjectAgentsDir(),u=await qQe(c);for(let f of u.errors){let g=`Agent loading error: ${f.message}`;e?.push(g),Ee.emitFeedback("error",g)}let d=this.config.getAcknowledgedAgentsService(),l=this.config.getProjectRoot(),a=[],p=[];for(let f of u.agents){if(this.ensureRemoteAgentHash(f),!f.metadata?.hash){p.push(f);continue}await d.isAcknowledged(l,f.name,f.metadata.hash)?p.push(f):a.push(f)}a.length>0&&Ee.emitAgentsDiscovered(a),await Promise.allSettled(p.map(async f=>{try{await this.registerAgent(f,e)}catch(g){let y=`Error registering project agent "${f.name}": ${g instanceof Error?g.message:String(g)}`;B.warn(`[AgentRegistry] ${y}`,g),e?.push(y),Ee.emitFeedback("error",y)}}))}else Ee.emitFeedback("info","Skipping project agents due to untrusted folder. To enable, ensure that the project root is trusted.");for(let c of this.config.getExtensions())c.isActive&&c.agents&&await Promise.allSettled(c.agents.map(async u=>{try{await this.registerAgent(u,e)}catch(d){let l=`Error registering extension agent "${u.name}": ${d instanceof Error?d.message:String(d)}`;B.warn(`[AgentRegistry] ${l}`,d),e?.push(l),Ee.emitFeedback("error",l)}}));this.config.getDebugMode()&&B.log(`[AgentRegistry] Loaded with ${this.agents.size} agents.`)}loadBuiltInAgents(){let e=Ile(this.config);this.builtInAgents.add(e.name),this.registerLocalAgent(e);let r=ler(this.config);this.builtInAgents.add(r.name),this.registerLocalAgent(r);let n=cer(this.config);this.builtInAgents.add(n.name),this.registerLocalAgent(n);let o=this.config.getBrowserAgentConfig();if(o.enabled){let s=process.env.SANDBOX,c=!!s&&s!=="sandbox-exec"&&s!=="sandbox:none",u=o.customConfig.sessionMode??"persistent";if(c&&u!=="existing")Ee.emitFeedback("info",'Browser agent disabled in container sandbox. To use it, set sessionMode to "existing" in settings and start Chrome with --remote-debugging-port=9222 on the host.');else{let d=Xle(this.config);this.builtInAgents.add(d.name),this.registerLocalAgent(d)}}}async refreshAgents(e="all"){this.loadBuiltInAgents(),await Promise.allSettled(Array.from(this.agents.values()).map(async r=>{(e==="all"||r.kind===e)&&await this.registerAgent(r)}))}async registerAgent(e,r){e.kind==="local"?this.registerLocalAgent(e):e.kind==="remote"&&await this.registerRemoteAgent(e,r)}registerLocalAgent(e){if(e.kind!=="local")return;if(!e.name||!e.description){B.warn("[AgentRegistry] Skipping invalid agent definition. Missing name or description.");return}this.allDefinitions.set(e.name,e);let r=this.config.getAgentsSettings().overrides?.[e.name];if(!this.isAgentEnabled(e,r)){this.config.getDebugMode()&&B.log(`[AgentRegistry] Skipping disabled agent '${e.name}'`);return}this.agents.has(e.name)&&this.config.getDebugMode()&&B.log(`[AgentRegistry] Overriding agent '${e.name}'`);let n=this.applyOverrides(e,r);this.agents.set(n.name,n),this.registerModelConfigs(n),this.addAgentPolicy(n)}addAgentPolicy(e){let r=this.config.getPolicyEngine();if(r){if(r.hasRuleForTool(e.name,!0)){this.config.getDebugMode()&&B.log(`[AgentRegistry] User policy exists for '${e.name}', skipping dynamic registration.`);return}e.kind==="remote"&&r.addRule({toolName:PC.Name,argsPattern:new RegExp(`"agent_name":\\s*"${e.name}"`),decision:Ke.ASK_USER,priority:UQ+.1,source:Aer})}}isAgentEnabled(e,r){let o=!(e.experimental===!0);return r&&r.enabled!==void 0&&(o=r.enabled),o}async registerRemoteAgent(e,r){if(e.kind!=="remote")return;if(!e.name){B.warn("[AgentRegistry] Skipping invalid agent definition. Missing name.");return}this.allDefinitions.set(e.name,e);let n=this.config.getAgentsSettings().overrides?.[e.name];if(!this.isAgentEnabled(e,n)){this.config.getDebugMode()&&B.log(`[AgentRegistry] Skipping disabled remote agent '${e.name}'`);return}this.agents.has(e.name)&&this.config.getDebugMode()&&B.log(`[AgentRegistry] Overriding agent '${e.name}'`);let o=e;o.originalDescription===void 0&&(o.originalDescription=o.description);try{let s=this.config.getA2AClientManager();if(!s){B.warn(`[AgentRegistry] Skipping remote agent '${e.name}': A2AClientManager is not available.`);return}let c=jle(o),u;if(e.auth){let f=await Hv.create({authConfig:e.auth,agentName:e.name,targetUrl:c,agentCardUrl:o.agentCardUrl});if(!f)throw new Error(`Failed to create auth provider for agent '${e.name}'`);u=f}let d=await s.loadAgent(o.name,Fle(o),u);if(d.securitySchemes){let f=Hv.validateAuthConfig(e.auth,d.securitySchemes);if(!f.valid&&f.diff){let g=Hv.describeRequiredAuth(d.securitySchemes),y=new nce(e.name,g,f.diff.missingConfig);Ee.emitFeedback("warning",`[${e.name}] Agent requires authentication: ${g}`),B.warn(`[AgentRegistry] ${y.message}`)}}let l=o.originalDescription,a=d.description,p=[];if(l?.trim()&&p.push(`User Description: ${l.trim()}`),a?.trim()&&p.push(`Agent Description: ${a.trim()}`),d.skills&&d.skills.length>0){let f=d.skills.map(g=>`${g.name}: ${g.description||"No description provided"}`).join(`
2518
2518
  `);p.push(`Skills:
2519
2519
  ${f}`)}p.length>0&&(e.description=p.join(`
2520
2520
  `)),this.config.getDebugMode()&&B.log(`[AgentRegistry] Registered remote agent '${e.name}' with card: ${e.agentCardUrl??"inline JSON"}`),this.agents.set(e.name,e),this.addAgentPolicy(e)}catch(s){let c;s instanceof $m?c=`[${e.name}] ${s.userMessage}`:c=`[${e.name}] Failed to load remote agent: ${s instanceof Error?s.message:String(s)}`,r?.push(c),Ee.emitFeedback("error",c),B.warn(`[AgentRegistry] Error loading A2A agent "${e.name}":`,s)}}applyOverrides(e,r){if(e.kind!=="local"||!r)return e;let n={get kind(){return e.kind},get name(){return e.name},get displayName(){return e.displayName},get description(){return e.description},get experimental(){return e.experimental},get metadata(){return e.metadata},get inputConfig(){return e.inputConfig},get outputConfig(){return e.outputConfig},get promptConfig(){return e.promptConfig},get toolConfig(){return e.toolConfig},get processOutput(){return e.processOutput},get runConfig(){return r.runConfig?{...e.runConfig,...r.runConfig}:e.runConfig},get modelConfig(){return r.modelConfig?Ck.merge(e.modelConfig,r.modelConfig):e.modelConfig}};return r.tools&&(n.toolConfig={tools:r.tools}),r.mcpServers&&(n.mcpServers={...e.mcpServers,...r.mcpServers}),n}registerModelConfigs(e){let r=e.modelConfig,n=r.model;n==="inherit"&&(n=this.config.getModel());let o={...r,model:n};this.config.modelConfigService.registerRuntimeModelConfig(n7(e),{modelConfig:o}),o.model&&sc(o.model)&&this.config.modelConfigService.registerRuntimeModelOverride({match:{overrideScope:e.name},modelConfig:{generateContentConfig:o.generateContentConfig}})}getDefinition(e){return this.agents.get(e)}getAllDefinitions(){return Array.from(this.agents.values())}getAllAgentNames(){return Array.from(this.agents.keys())}getAllDiscoveredAgentNames(){return Array.from(this.allDefinitions.keys())}getDiscoveredDefinition(e){return this.allDefinitions.get(e)}ensureRemoteAgentHash(e){e.kind==="remote"&&(e.metadata||(e.metadata={}),e.agentCardUrl?e.metadata.hash=e.agentCardUrl:e.agentCardJson&&(e.metadata.hash=_er.createHash("sha256").update(e.agentCardJson).digest("hex")))}};import{AsyncLocalStorage as Fei}from"node:async_hooks";var Eer=new Fei;function YQe(t,e){return Eer.run(t,e)}function sce(){return Eer.getStore()}var ber=Fe(Yse(),1);function i7(t){return typeof t=="object"&&t!==null&&"callId"in t&&"responseParts"in t}function o7(t,e,r=3){let n=e.map(c=>({name:c,distance:ber.default.get(t,c)}));n.sort((c,u)=>c.distance-u.distance);let o=n.slice(0,r);if(o.length===0)return"";let s=o.map(c=>`"${c.name}"`).join(", ");return o.length>1?` Did you mean one of: ${s}?`:` Did you mean ${s}?`}function K0o(t,e,r){let n;cKe(t)?n=[t.name,t.constructor.name]:n=[t],n.some(o=>jp.includes(o))&&(n=[...new Set([...n,...jp])]);for(let o of r){let s=o.indexOf("(");if(s===-1){if(n.includes(o))return!0;continue}let c=o.substring(0,s);if(!n.includes(c)||!o.endsWith(")"))continue;let u=o.substring(s+1,o.length-1),d;if(typeof e=="string")d=e;else{if(!("command"in e.params))continue;d=String(e.params.command)}if(n.some(l=>jp.includes(l))&&(d===u||d.startsWith(u+" ")))return!0}return!1}var ace=class{messageBus;schedulerId;onTerminalCall;activeCalls=new Map;queue=[];_completedBatch=[];constructor(e,r=fit,n){this.messageBus=e,this.schedulerId=r,this.onTerminalCall=n}addToolCalls(e){this.enqueue(e)}getToolCall(e){return this.activeCalls.get(e)||this.queue.find(r=>r.request.callId===e)||this._completedBatch.find(r=>r.request.callId===e)}enqueue(e){this.queue.push(...e),this.emitUpdate()}dequeue(){let e=this.queue.shift();return e&&(this.activeCalls.set(e.request.callId,e),this.emitUpdate()),e}peekQueue(){return this.queue[0]}get isActive(){return this.activeCalls.size>0}get allActiveCalls(){return Array.from(this.activeCalls.values())}get activeCallCount(){return this.activeCalls.size}get queueLength(){return this.queue.length}get firstActiveCall(){return this.activeCalls.values().next().value}updateStatus(e,r,n){let o=this.activeCalls.get(e);if(!o)return;let s=this.transitionCall(o,r,n);this.activeCalls.set(e,s),this.emitUpdate()}finalizeCall(e){let r=this.activeCalls.get(e);r&&this.isTerminalCall(r)&&(this._completedBatch.push(r),this.activeCalls.delete(e),this.onTerminalCall?.(r),this.emitUpdate())}updateArgs(e,r,n){let o=this.activeCalls.get(e);if(!o||o.status===Ne.Error)return;let s=o.request.display?{...o.request.display}:{name:o.request.name};s.description=n.getDescription(),this.activeCalls.set(e,this.patchCall(o,{request:{...o.request,args:r,display:s},invocation:n})),this.emitUpdate()}setOutcome(e,r){let n=this.activeCalls.get(e);n&&(this.activeCalls.set(e,this.patchCall(n,{outcome:r})),this.emitUpdate())}replaceActiveCallWithTailCall(e,r){this.activeCalls.has(e)&&(this.activeCalls.delete(e),this.queue.unshift(r),this.emitUpdate())}cancelAllQueued(e){if(this.queue.length!==0){for(;this.queue.length>0;){let r=this.queue.shift();if(r.status===Ne.Error){this._completedBatch.push(r),this.onTerminalCall?.(r);continue}let n=this.toCancelled(r,e);this._completedBatch.push(n),this.onTerminalCall?.(n)}this.emitUpdate()}}getSnapshot(){return[...this._completedBatch,...Array.from(this.activeCalls.values()),...this.queue]}clearBatch(){this._completedBatch.length!==0&&(this._completedBatch=[],this.emitUpdate())}get completedBatch(){return[...this._completedBatch]}emitUpdate(){let e=this.getSnapshot();this.messageBus.publish({type:Bi.TOOL_CALLS_UPDATE,toolCalls:e,schedulerId:this.schedulerId})}isTerminalCall(e){let{status:r}=e;return r===Ne.Success||r===Ne.Error||r===Ne.Cancelled}transitionCall(e,r,n){switch(r){case Ne.Success:{if(!i7(n))throw new Error(`Invalid data for 'success' transition (callId: ${e.request.callId})`);return this.toSuccess(e,n)}case Ne.Error:{if(!i7(n))throw new Error(`Invalid data for 'error' transition (callId: ${e.request.callId})`);return this.toError(e,n)}case Ne.AwaitingApproval:{if(!n)throw new Error(`Missing data for 'awaiting_approval' transition (callId: ${e.request.callId})`);return this.toAwaitingApproval(e,n)}case Ne.Scheduled:return this.toScheduled(e);case Ne.Cancelled:{if(typeof n!="string"&&!i7(n))throw new Error(`Invalid reason (string) or response for 'cancelled' transition (callId: ${e.request.callId})`);return this.toCancelled(e,n)}case Ne.Validating:return this.toValidating(e);case Ne.Executing:{if(n!==void 0&&!this.isExecutingToolCallPatch(n))throw new Error(`Invalid patch for 'executing' transition (callId: ${e.request.callId})`);return this.toExecuting(e,n)}default:return r}}isExecutingToolCallPatch(e){return typeof e=="object"&&e!==null}validateHasToolAndInvocation(e,r){if(!("tool"in e&&e.tool&&"invocation"in e&&e.invocation))throw new Error(`Invalid state transition: cannot transition to ${r} without tool/invocation (callId: ${e.request.callId})`)}toSuccess(e,r){this.validateHasToolAndInvocation(e,Ne.Success);let n="startTime"in e?e.startTime:void 0;return{request:e.request,tool:e.tool,invocation:e.invocation,status:Ne.Success,response:r,durationMs:n?Date.now()-n:void 0,outcome:e.outcome,schedulerId:e.schedulerId,approvalMode:e.approvalMode}}toError(e,r){let n="startTime"in e?e.startTime:void 0;return{request:e.request,status:Ne.Error,tool:"tool"in e?e.tool:void 0,response:r,durationMs:n?Date.now()-n:void 0,outcome:e.outcome,schedulerId:e.schedulerId,approvalMode:e.approvalMode}}toAwaitingApproval(e,r){this.validateHasToolAndInvocation(e,Ne.AwaitingApproval);let n,o;return this.isEventDrivenApprovalData(r)?(o=r.correlationId,n=r.confirmationDetails):n=r,{request:e.request,tool:e.tool,status:Ne.AwaitingApproval,correlationId:o,confirmationDetails:n,startTime:"startTime"in e?e.startTime:void 0,outcome:e.outcome,invocation:e.invocation,schedulerId:e.schedulerId,approvalMode:e.approvalMode}}isEventDrivenApprovalData(e){return typeof e=="object"&&e!==null&&"correlationId"in e&&"confirmationDetails"in e}toScheduled(e){return this.validateHasToolAndInvocation(e,Ne.Scheduled),{request:e.request,tool:e.tool,status:Ne.Scheduled,startTime:"startTime"in e?e.startTime:void 0,outcome:e.outcome,invocation:e.invocation,schedulerId:e.schedulerId,approvalMode:e.approvalMode}}toCancelled(e,r){this.validateHasToolAndInvocation(e,Ne.Cancelled);let n="startTime"in e?e.startTime:void 0,o;if(this.isWaitingToolCall(e)){let u=e.confirmationDetails;u.type==="edit"&&"fileDiff"in u&&"fileName"in u&&"filePath"in u&&"originalContent"in u&&"newContent"in u&&(o={fileDiff:u.fileDiff,fileName:u.fileName,filePath:u.filePath,originalContent:u.originalContent,newContent:u.newContent,diffStat:u.diffStat??yKe(u.fileDiff)})}let s;if(e.status===Ne.Executing&&e.liveOutput&&(s=e.liveOutput),i7(r)){let u={...r};return u.resultDisplay||(u.resultDisplay=o??s),{request:e.request,tool:e.tool,invocation:e.invocation,status:Ne.Cancelled,response:u,durationMs:n?Date.now()-n:void 0,outcome:e.outcome,schedulerId:e.schedulerId,approvalMode:e.approvalMode}}let c=`[Operation Cancelled] Reason: ${r}`;return{request:e.request,tool:e.tool,invocation:e.invocation,status:Ne.Cancelled,response:{callId:e.request.callId,responseParts:[{functionResponse:{id:e.request.callId,name:e.request.originalRequestName??e.request.name,response:{error:c}}}],resultDisplay:o??s,error:void 0,errorType:void 0,contentLength:c.length},durationMs:n?Date.now()-n:void 0,outcome:e.outcome,schedulerId:e.schedulerId,approvalMode:e.approvalMode}}isWaitingToolCall(e){return e.status===Ne.AwaitingApproval}patchCall(e,r){return{...e,...r}}toValidating(e){return this.validateHasToolAndInvocation(e,Ne.Validating),{request:e.request,tool:e.tool,status:Ne.Validating,startTime:"startTime"in e?e.startTime:void 0,outcome:e.outcome,invocation:e.invocation,schedulerId:e.schedulerId,approvalMode:e.approvalMode}}toExecuting(e,r){this.validateHasToolAndInvocation(e,Ne.Executing);let n=r,o=n?.liveOutput??("liveOutput"in e?e.liveOutput:void 0),s=n?.pid??("pid"in e?e.pid:void 0),c=n?.progressMessage??("progressMessage"in e?e.progressMessage:void 0),u=n?.progressPercent??("progressPercent"in e?e.progressPercent:void 0),d=n?.progress??("progress"in e?e.progress:void 0),l=n?.progressTotal??("progressTotal"in e?e.progressTotal:void 0);return{request:e.request,tool:e.tool,status:Ne.Executing,startTime:"startTime"in e?e.startTime:void 0,outcome:e.outcome,invocation:e.invocation,liveOutput:o,pid:s,progressMessage:c,progressPercent:u,progress:d,progressTotal:l,schedulerId:e.schedulerId,approvalMode:e.approvalMode}}};import{on as jei}from"node:events";import{randomUUID as Qei}from"node:crypto";async function Gei(t,e,r){if(r.aborted)throw new Error("Operation cancelled");try{for await(let[n]of jei(t,Bi.TOOL_CONFIRMATION_RESPONSE,{signal:r})){let o=n;if(o.correlationId===e)return{outcome:o.outcome??(o.confirmed?Vt.ProceedOnce:Vt.Cancel),payload:o.payload}}}catch(n){throw r.aborted||n.name==="AbortError"?new Error("Operation cancelled"):n}throw new Error("Operation cancelled")}async function JQe(t,e,r){let{state:n,onWaitingForConfirmation:o}=r,s=t.request.callId,c=Vt.ModifyWithEditor,u;for(;c===Vt.ModifyWithEditor;){if(e.aborted)throw new Error("Operation cancelled by user");let d=n.getToolCall(s);if(!d||!("invocation"in d))throw new Error(`Tool call ${s} lost during confirmation loop`);let a=await d.invocation.shouldConfirmExecute(e,r.forcedDecision);if(!a){c=Vt.ProceedOnce;break}r.systemMessage&&(a.systemMessage=r.systemMessage),await $ei(r,a);let p=Qei(),f=a;u=f;let g="ideConfirmation"in a?a.ideConfirmation:void 0;n.updateStatus(s,Ne.AwaitingApproval,{confirmationDetails:f,correlationId:p}),o?.(!0);let y=await Hei(r.messageBus,p,e,g);if(o?.(!1),c=y.outcome,"onConfirm"in a&&typeof a.onConfirm=="function"&&await a.onConfirm(c,y.payload),c===Vt.ModifyWithEditor){let _=await qei(r,t,e);_.error&&Ee.emitFeedback("error",_.error)}else y.payload&&"newContent"in y.payload&&(await Vei(r,t,y.payload,e),c=Vt.ProceedOnce)}return{outcome:c,lastDetails:u}}async function $ei(t,e){t.config.getHookSystem()&&await t.config.getHookSystem()?.fireToolNotificationEvent({...e,onConfirm:async()=>{}})}async function qei(t,e,r){let{state:n,modifier:o,getPreferredEditor:s}=t,c=s(),u=await p6t(c,r);if(!u)return{error:l6t};let d=await o.handleModifyWithEditor(n.firstActiveCall,u,r);if(d){let l=e.tool.build(d.updatedParams);n.updateArgs(e.request.callId,d.updatedParams,l)}return{}}async function Vei(t,e,r,n){let{state:o,modifier:s}=t,c=await s.applyInlineModify(o.firstActiveCall,r,n);if(c){let u=e.tool.build(c.updatedParams);o.updateArgs(e.request.callId,c.updatedParams,u)}}async function Hei(t,e,r,n){let o=new AbortController,s=o.signal,c=()=>o.abort();r.aborted?o.abort():r.addEventListener("abort",c);try{let u=Gei(t,e,s);if(!n)return await u;let d=n.then(l=>({outcome:l.status==="accepted"?Vt.ProceedOnce:Vt.Cancel,payload:l.content?{newContent:l.content}:void 0})).catch(l=>(B.warn("Error waiting for confirmation via IDE",l),new Promise(()=>{})));return await Promise.race([u,d])}finally{r.removeEventListener("abort",c),o.abort()}}function ver(t,e){return{errorMessage:`Tool execution denied by policy.${e?.denyMessage?` ${e.denyMessage}`:""}`,errorType:Re.POLICY_VIOLATION}}async function Ser(t,e,r){let n=t.tool instanceof Ei?t.tool.serverName:void 0,o=t.tool.toolAnnotations,s=await e.getPolicyEngine().check({name:t.request.name,args:t.request.args},n,o,r),{decision:c}=s;if(c===Ke.ASK_USER&&t.request.isClientInitiated&&!t.request.args?.additional_permissions)return{decision:Ke.ALLOW,rule:s.rule};if(c===Ke.ASK_USER&&!e.isInteractive())throw new Error(`Tool execution for "${t.tool.displayName||t.tool.name}" requires user confirmation, which is not supported in non-interactive mode.`);return{decision:c,rule:s.rule}}async function Ter(t,e,r,n,o,s){let c=n.config.getApprovalMode();zei(t,e)&&n.config.setApprovalMode(vt.AUTO_EDIT);let u,d;if(e===Vt.ProceedAlways||e===Vt.ProceedAlwaysTool||e===Vt.ProceedAlwaysServer||e===Vt.ProceedAlwaysAndSave){let l=Dge.indexOf(c);l!==-1&&(d=Dge.slice(l))}if(e===Vt.ProceedAlwaysAndSave&&(n.config&&n.config.isTrustedFolder()&&n.config.getWorkspacePoliciesDir()!==void 0?u="workspace":u="user"),r?.type==="mcp"){await Yei(t,e,r,o,u,d);return}await Wei(t,e,r,o,u,s,n.config,d)}function zei(t,e){return e===Vt.ProceedAlways&&pL.has(t.name)}async function Wei(t,e,r,n,o,s,c,u){if(e===Vt.ProceedAlways||e===Vt.ProceedAlwaysAndSave){let d=s?.getPolicyUpdateOptions?.(e)||{};if(!d.commandPrefix&&r?.type==="exec")d.commandPrefix=r.rootCommands;else if(!d.argsPattern&&r?.type==="edit"){let l=c?Hi(r.filePath,c.getTargetDir()):r.filePath;d.argsPattern=jb(l)}await n.publish({type:Bi.UPDATE_POLICY,toolName:t.name,persist:e===Vt.ProceedAlwaysAndSave,persistScope:o,modes:u,...d})}}async function Yei(t,e,r,n,o,s){if(!(e===Vt.ProceedAlways||e===Vt.ProceedAlwaysTool||e===Vt.ProceedAlwaysServer||e===Vt.ProceedAlwaysAndSave))return;let u=t.name,d=e===Vt.ProceedAlwaysAndSave;e===Vt.ProceedAlwaysServer&&(u=$1(r.serverName,"*")),await n.publish({type:Bi.UPDATE_POLICY,toolName:u,mcpName:r.serverName,persist:d,persistScope:o,modes:s})}function KQe(t,e){if(!(t instanceof UKe))return;let n=(e.getMcpClientManager()?.getMcpServers()??e.getMcpServers()??{})[t.serverName];if(n)return{server_name:t.serverName,tool_name:t.serverToolName,command:n.command,args:n.args,cwd:n.cwd,url:n.url??n.httpUrl,tcp:n.tcp}}async function wer(t,e,r,n,o,s,c,u,d){let l=t.params||{},a=!1,p=[],f=c?KQe(t,c):void 0,g=c?.getHookSystem();if(g&&!d){let _=await g.fireBeforeToolEvent(e,l,f,u);if(_?.shouldStopExecution()){let b=_.getEffectiveReason();return{llmContent:`Agent execution stopped by hook: ${b}`,returnDisplay:`Agent execution stopped by hook: ${b}`,error:{type:Re.STOP_EXECUTION,message:b}}}let E=_?.getBlockingError();if(E?.blocked)return{llmContent:`Tool execution blocked: ${E.reason}`,returnDisplay:`Tool execution blocked: ${E.reason}`,error:{type:Re.EXECUTION_FAILED,message:E.reason}};if(_ instanceof pA){let b=_.getModifiedToolInput();if(b){Object.assign(t.params,b),B.debug(`Tool input modified by hook for ${e}`),a=!0,p=Object.keys(b);try{t=n.build(t.params)}catch(v){return{llmContent:`Tool parameter modification by hook failed validation: ${v instanceof Error?v.message:String(v)}`,returnDisplay:"Tool parameter modification by hook failed validation.",error:{type:Re.INVALID_TOOL_PARAMS,message:String(v)}}}}}}let y=await t.execute({...s,abortSignal:r,updateOutput:o});if(a){let _=`