makecoder 2.0.82 → 2.0.83
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cc.mjs +2384 -2307
- package/dist/coder.js +1 -1
- package/dist/gemini/{chunk-5BEOVOB4.js → chunk-CTQJGFLJ.js} +4 -4
- package/dist/gemini/{chunk-ZF44RIRK.js → chunk-EBB2IYKE.js} +4 -4
- package/dist/gemini/{chunk-2BSGDHZW.js → chunk-L5FDAQJS.js} +3 -3
- package/dist/gemini/{chunk-3S73IM76.js → chunk-UYYXENF2.js} +3 -3
- package/dist/gemini/{core-56B7CHS2.js → core-B3NSJHXB.js} +1 -1
- package/dist/gemini/{devtoolsService-RNB7OJ6P.js → devtoolsService-AGS6ID67.js} +2 -2
- package/dist/gemini/{devtoolsService-NH25LG4W.js → devtoolsService-LHW3U2EN.js} +2 -2
- package/dist/gemini/{dist-I4ITZJCU.js → dist-EZT2EOAT.js} +1 -1
- package/dist/gemini/gemini.js +72 -69
- package/dist/gemini/{interactiveCli-RHVVREXZ.js → interactiveCli-FGI25PZI.js} +2 -2
- package/dist/gemini/{interactiveCli-W6EKULZA.js → interactiveCli-NC2XXIRS.js} +2 -2
- package/dist/gemini/node_modules/@google/gemini-cli-devtools/package.json +1 -1
- package/dist/gemini/{oauth2-provider-7WYWCO22.js → oauth2-provider-HTOFGZYE.js} +1 -1
- package/dist/gemini/{oauth2-provider-XUGLSHUZ.js → oauth2-provider-VD7VX4RN.js} +1 -1
- package/package.json +4 -4
- /package/dist/gemini/{tree-sitter-NXEUY244.js → tree-sitter-JU2EI3Z2.js} +0 -0
- /package/dist/gemini/{tree-sitter-bash-CUUXV34I.js → tree-sitter-bash-IAB7XJEE.js} +0 -0
|
@@ -814,7 +814,7 @@ ${s}
|
|
|
814
814
|
|
|
815
815
|
... [${u.toLocaleString()} characters omitted] ...
|
|
816
816
|
|
|
817
|
-
${c}`}var $br="tool-outputs";async function Jv(t,e,r,n,o){let s=Yu(e).toLowerCase(),c=Yu(r.toString()).toLowerCase(),u=c.startsWith(s)?`${c}.txt`:`${s}_${c}.txt`,d=Wu.join(n,$br);if(o){let a=Yu(o);d=Wu.join(d,`session-${a}`)}let l=Wu.join(d,u);return await Ox.mkdir(d,{recursive:!0}),await Ox.writeFile(l,t),{outputFile:l}}async function eet(t,e){await ul();let r=[t,...e].join(" "),n=Ju(r),o=KA(n).filter(s=>s!=="shopt"&&s!=="set");return o.length>0?o[0]:Kq.basename(t)}function Px(t){return typeof t=="string"?t:"pattern"in t?t.pattern:"op"in t?t.op:("comment"in t,"")}var Ch=["run_shell_command","ShellTool"];async function ret(t){if(Kq.isAbsolute(t))try{return await Yq.promises.access(t,Yq.constants.X_OK),t}catch{return}let e=(process.env.PATH||"").split(Kq.delimiter),r=KZe.platform()==="win32"?[".exe",".cmd",".bat",""]:[""];for(let n of e)for(let o of r){let s=Kq.join(n,t+o);try{return await Yq.promises.access(s,Yq.constants.X_OK),s}catch{continue}}}var Kv=null,Jq=null,Rx=null,Xq=class extends Error{constructor(e){super(`Failed to initialize bash parser: ${e.message}`,{cause:e}),this.name="ShellParserInitializationError"}};function zbr(t){return t instanceof Error?t:typeof t=="string"?new Error(t):new Error("Unknown tree-sitter initialization error",{cause:t})}async function Wbr(){try{Rx=null;let[t,e]=await Promise.all([Mme(()=>import("./tree-sitter-
|
|
817
|
+
${c}`}var $br="tool-outputs";async function Jv(t,e,r,n,o){let s=Yu(e).toLowerCase(),c=Yu(r.toString()).toLowerCase(),u=c.startsWith(s)?`${c}.txt`:`${s}_${c}.txt`,d=Wu.join(n,$br);if(o){let a=Yu(o);d=Wu.join(d,`session-${a}`)}let l=Wu.join(d,u);return await Ox.mkdir(d,{recursive:!0}),await Ox.writeFile(l,t),{outputFile:l}}async function eet(t,e){await ul();let r=[t,...e].join(" "),n=Ju(r),o=KA(n).filter(s=>s!=="shopt"&&s!=="set");return o.length>0?o[0]:Kq.basename(t)}function Px(t){return typeof t=="string"?t:"pattern"in t?t.pattern:"op"in t?t.op:("comment"in t,"")}var Ch=["run_shell_command","ShellTool"];async function ret(t){if(Kq.isAbsolute(t))try{return await Yq.promises.access(t,Yq.constants.X_OK),t}catch{return}let e=(process.env.PATH||"").split(Kq.delimiter),r=KZe.platform()==="win32"?[".exe",".cmd",".bat",""]:[""];for(let n of e)for(let o of r){let s=Kq.join(n,t+o);try{return await Yq.promises.access(s,Yq.constants.X_OK),s}catch{continue}}}var Kv=null,Jq=null,Rx=null,Xq=class extends Error{constructor(e){super(`Failed to initialize bash parser: ${e.message}`,{cause:e}),this.name="ShellParserInitializationError"}};function zbr(t){return t instanceof Error?t:typeof t=="string"?new Error(t):new Error("Unknown tree-sitter initialization error",{cause:t})}async function Wbr(){try{Rx=null;let[t,e]=await Promise.all([Mme(()=>import("./tree-sitter-JU2EI3Z2.js"),"web-tree-sitter/tree-sitter.wasm"),Mme(()=>import("./tree-sitter-bash-IAB7XJEE.js"),"tree-sitter-bash/tree-sitter-bash.wasm")]);await Nme.init({wasmBinary:t}),Kv=await Pme.load(e)}catch(t){Kv=null;let e=zbr(t),r=e instanceof Xq?e:new Xq(e);throw Rx=r,r}}async function ul(){Jq||(Jq=Wbr().catch(t=>{Jq=null,B.debug("Failed to initialize shell parsers:",t)})),await Jq}var net="__GCLI_POWERSHELL_COMMAND__",Ybr=1e3*1e3,Jbr=Buffer.from(`
|
|
818
818
|
$ErrorActionPreference = 'Stop'
|
|
819
819
|
$commandText = $env:${net}
|
|
820
820
|
if ([string]::IsNullOrEmpty($commandText)) {
|
|
@@ -1058,7 +1058,7 @@ Please try running again with NO_BROWSER=true set.`}),new Ca(`Failed to open bro
|
|
|
1058
1058
|
`);let s=await new Promise((c,u)=>{let d=J6r.createInterface({input:process.stdin,output:r$().stdout,terminal:!0}),l=setTimeout(()=>{d.close(),u(new Ca("Authorization timed out after 5 minutes."))},3e5);d.question("Enter the authorization code: ",a=>{clearTimeout(l),d.close(),c(a.trim())})});if(!s)return dS(`Authorization code is required.
|
|
1059
1059
|
`),B.error("Authorization code is required."),!1;try{let{tokens:c}=await t.getToken({code:s,codeVerifier:r.codeVerifier,redirect_uri:e});t.setCredentials(c)}catch(c){return dS("Failed to authenticate with authorization code:"+Se(c)+`
|
|
1060
1060
|
`),B.error("Failed to authenticate with authorization code:",Se(c)),!1}return!0}catch(e){if(e instanceof qv)throw e;return dS("Failed to authenticate with user code:"+Se(e)+`
|
|
1061
|
-
`),B.error("Failed to authenticate with user code:",Se(e)),!1}}async function e4r(t){let e=await t4r(),r=process.env.OAUTH_CALLBACK_HOST||"127.0.0.1",n=`http://127.0.0.1:${e}/oauth2callback`,o=opt.randomBytes(32).toString("hex"),s=t.generateAuthUrl({redirect_uri:n,access_type:"offline",scope:F_e,state:o}),c=new Promise((u,d)=>{let l=ipt.createServer(async(a,p)=>{try{if(a.url.indexOf("/oauth2callback")===-1){p.writeHead(o$,{Location:U_e}),p.end(),d(new Ca("OAuth callback not received. Unexpected request: "+a.url));return}let f=new z6r.URL(a.url,"http://127.0.0.1:3000").searchParams;if(f.get("error")){p.writeHead(o$,{Location:U_e}),p.end();let g=f.get("error"),y=f.get("error_description")||"No additional details provided";d(new Ca(`Google OAuth error: ${g}. ${y}`))}else if(f.get("state")!==o)p.end("State mismatch. Possible CSRF attack"),d(new Ca("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 s$(t)}catch(y){B.warn("Failed to retrieve Google Account ID during authentication:",Se(y))}p.writeHead(o$,{Location:K6r}),p.end(),u()}catch(g){p.writeHead(o$,{Location:U_e}),p.end(),d(new Ca(`Failed to exchange authorization code for tokens: ${Se(g)}`))}else d(new Ca("No authorization code received from Google OAuth. Please try authenticating again."))}catch(f){f instanceof Ca?d(f):d(new Ca(`Unexpected error during OAuth authentication: ${Se(f)}`))}finally{l.close()}});l.listen(e,r,()=>{}),l.on("error",a=>{d(new Ca(`OAuth callback server error: ${Se(a)}`))})});return{authUrl:s,loginCompletePromise:c}}function t4r(){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=spt.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 r4r(){if(j_e())return C2.loadCredentials();let e=[pr.getOAuthCredsPath(),process.env.GOOGLE_APPLICATION_CREDENTIALS].filter(r=>!!r);for(let r of e)try{let n=await xL.readFile(r,"utf-8");return JSON.parse(n)}catch(n){B.debug(`Failed to load credentials from ${r}:`,Se(n))}return null}function n4r(){OL.clear()}async function JBi(){try{j_e()?await C2.clearCredentials():await xL.rm(pr.getOAuthCredsPath(),{force:!0}),await l$.clearCachedGoogleAccount(),n4r()}catch(t){B.warn("Failed to clear cached credentials:",t)}}async function s$(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 l$.cacheGoogleAccount(n.email)}catch(e){B.log("Error retrieving user info:",e)}}function KBi(){OL.clear()}async function i4r(t){let e=pr.getOAuthCredsPath();await xL.mkdir(Y6r.dirname(e),{recursive:!0});let r=JSON.stringify(t,null,2);await xL.writeFile(e,r,{mode:384});try{await xL.chmod(e,384)}catch{}}var c$;(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"})(c$||(c$={}));var x0={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 u$;(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"})(u$||(u$={}));var Mh;(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"})(Mh||(Mh={}));var IL;(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"})(IL||(IL={}));var o4r=Y.object({extensionsEnabled:Y.boolean().optional()}),dpt=Y.object({extensionsSetting:o4r.optional(),unmanagedCapabilitiesEnabled:Y.boolean().optional()}),s4r=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()}),a4r=Y.object({scopes:Y.array(Y.string()).optional(),clientId:Y.string().optional(),clientSecret:Y.string().optional()}),ppt=Y.object({url:Y.string(),type:Y.enum(["sse","http"]),authProviderType:Y.nativeEnum(O0).optional(),oauth:a4r.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()}),Q_e=Y.object({mcpServers:Y.record(s4r).optional(),requiredMcpServers:Y.record(ppt).optional()}),l4r=Y.object({mcpEnabled:Y.boolean().optional(),mcpConfigJson:Y.string().optional()}),t5i=Y.object({strictModeDisabled:Y.boolean().optional(),mcpSetting:Y.object({mcpEnabled:Y.boolean().optional(),mcpConfig:Q_e.optional(),requiredMcpConfig:Y.record(ppt).optional()}).optional(),cliFeatureSetting:dpt.optional()}),fpt=Y.object({secureModeEnabled:Y.boolean().optional(),strictModeDisabled:Y.boolean().optional(),mcpSetting:l4r.optional(),cliFeatureSetting:dpt.optional(),adminControlsApplicable:Y.boolean().optional()});import*as lYt from"node:readline";import{Readable as jHn}from"node:stream";var pS="GOOGLE_ONE_AI",c4r=new Set([Eh,_x,cl]);function hpt(t){return c4r.has(t)}var u4r="https://one.google.com/ai",d4r="https://accounts.google.com/AccountChooser",p4r="gemini_cli",f4r="web";function h4r(t,e){let r=new URLSearchParams({Email:t,continue:e});return`${d4r}?${r.toString()}`}var i5i={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 o5i(t,e,r){let n=`${u4r}/${t}`,o=new URLSearchParams({utm_source:p4r,utm_medium:f4r,utm_campaign:r}),s=`${n}?${o.toString()}`;return h4r(e,s)}function gpt(t){if(!t?.availableCredits)return null;let e=t.availableCredits.filter(r=>r.creditType===pS);return e.length===0?null:e.reduce((r,n)=>{let o=parseInt(n.creditAmount??"0",10);return r+(isNaN(o)?0:o)},0)}var q_e=50;function mpt(t,e){return t==="always"&&e!=null&&e>=q_e}function s5i(t,e){return t==="ask"&&e!=null&&e>=q_e}function a5i(t,e){return t!=="never"&&e!=null&&e<q_e}var Kt=Fe(Fh(),1);qe();var PMt=Fe(fwe(),1),NMt=Fe(gwe(),1),kMt=Fe(bwe(),1),DMt=Fe(Swe(),1),LMt=Fe(wwe(),1),MMt=Fe(t6(),1);Wp();var BMt=Fe(Wwt(),1);hl();var UMt=Fe(G0(),1),$re=Fe($J(),1),Hre=Fe(mJ(),1),kb=Fe(df(),1),FMt=Fe(yCt(),1);var nOt=Fe(h2t(),1),iOt=Fe(TKe(),1);import{createHash as Ucn}from"node:crypto";import*as UI from"node:os";var ie;(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"})(ie||(ie={}));var mIe=Fe(w2t(),1),yIe=Fe(N2t(),1),Z2t=Fe(B2t(),1),vf=Fe(q2t(),1);var AIe=Fe($2t(),1);var OT=Fe(hIe(),1);var Dcn=Fe(J2t(),1),Lcn=Fe(X2t(),1);var HVi=mIe.default.MinFibonacciHeap,zVi=mIe.default.MaxFibonacciHeap,WVi=yIe.default.MinHeap,YVi=yIe.default.MaxHeap,JVi=Z2t.default.GeneralizedSuffixArray,KVi=vf.default.Uint8Vector,XVi=vf.default.Uint8ClampedVector,ZVi=vf.default.Int8Vector,e$i=vf.default.Uint16Vector,t$i=vf.default.Int16Vector,r$i=vf.default.Uint32Vector,n$i=vf.default.Int32Vector,i$i=vf.default.Float32Vector,o$i=vf.default.Float64Vector,s$i=vf.default.PointerVector;var eOt="f8e1854",tOt="0.37.0";var Gr={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 MI(){return!!(process.env.EDITOR_IN_CLOUD_SHELL||process.env.CLOUD_SHELL)}function _Ie(){return!!process.env.TERMINAL_EMULATOR?.toLowerCase().includes("jetbrains")}function BI(){return process.env.ANTIGRAVITY_CLI_ALIAS?Gr.antigravity:process.env.__COG_BASHRC_SOURCED?Gr.devin:process.env.REPLIT_USER?Gr.replit:process.env.CURSOR_TRACE_ID?Gr.cursor:process.env.CODESPACES?Gr.codespaces:MI()?Gr.cloudshell:process.env.TERM_PRODUCT==="Trae"?Gr.trae:process.env.MONOSPACE_ENV?Gr.firebasestudio:process.env.POSITRON==="1"?Gr.positron:process.env.TERM_PROGRAM==="sublime"?Gr.sublimetext:process.env.ZED_SESSION_ID||process.env.TERM_PROGRAM==="Zed"?Gr.zed:process.env.XCODE_VERSION_ACTUAL?Gr.xcode:_Ie()?Gr.jetbrains:Gr.vscode}function Mcn(t,e){return t.name!==Gr.vscode.name?t:!e.command||e.command.toLowerCase().includes("code")?Gr.vscode:Gr.vscodefork}function Bcn(t,e){if(t.name!==Gr.jetbrains.name||!e.command)return t;let r=e.command.toLowerCase(),n=[["idea",Gr.intellijidea],["webstorm",Gr.webstorm],["pycharm",Gr.pycharm],["goland",Gr.goland],["studio",Gr.androidstudio],["clion",Gr.clion],["rustrover",Gr.rustrover],["datagrip",Gr.datagrip],["phpstorm",Gr.phpstorm]];for(let[o,s]of n)if(r.includes(o))return s;return t}function rOt(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&&!_Ie())return;let r=BI();return _Ie()?Bcn(r,t):Mcn(r,t)}var Ct;(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"})(Ct||(Ct={}));function Fcn(){return process.env.SURFACE?process.env.SURFACE:MI()?Gr.cloudshell.name:process.env.GITHUB_SHA?"GitHub":process.env.TERM_PROGRAM==="vscode"?BI().name||Gr.vscode.name:"SURFACE_NOT_SET"}function jcn(){return process.env.GH_WORKFLOW_NAME}function Qcn(){return process.env.GITHUB_REPOSITORY}function qcn(){return process.env.GITHUB_EVENT_NAME}function Gcn(){return process.env.GH_PR_NUMBER}function Vcn(){return process.env.GH_ISSUE_NUMBER}function $cn(){return process.env.GH_CUSTOM_TRACKING_ID}var Hcn="https://play.googleapis.com/log?format=json&hasfast=true",zcn=1e3*60,DZ=1e3,LZ=100,oOt="NA",P4;async function Wcn(){try{let t=await nOt.default.graphics();t.controllers&&t.controllers.length>0?P4=t.controllers.map(e=>e.model).join(", "):P4=oOt}catch(t){P4="FAILED",B.error("Failed to get GPU information for telemetry",Se(t))}}async function Ycn(){return P4||await Wcn(),P4??oOt}var Pt=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 AIe.default(Array,DZ),this.promptId=e?.getSessionId()??"",this.installationManager=new g_,this.userAccountManager=new h_;let r=Qcn();r&&(this.hashedGHRepositoryName=Ucn("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>=DZ;n&&this.events.shift();let o={event_time_ms:Date.now(),source_extension_json:Mr(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:ie.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=Fcn(),s=jcn(),c=qcn(),u=Gcn(),d=Vcn(),l=$cn(),a=[...r,{gemini_cli_key:ie.GEMINI_CLI_SURFACE,value:o},{gemini_cli_key:ie.GEMINI_CLI_VERSION,value:tOt},{gemini_cli_key:ie.GEMINI_CLI_GIT_COMMIT_HASH,value:eOt},{gemini_cli_key:ie.GEMINI_CLI_OS,value:process.platform}];s&&a.push({gemini_cli_key:ie.GEMINI_CLI_GH_WORKFLOW_NAME,value:s}),this.hashedGHRepositoryName&&a.push({gemini_cli_key:ie.GEMINI_CLI_GH_REPOSITORY_NAME_HASH,value:this.hashedGHRepositoryName}),c&&a.push({gemini_cli_key:ie.GEMINI_CLI_GH_EVENT_NAME,value:c}),u&&a.push({gemini_cli_key:ie.GEMINI_CLI_GH_PR_NUMBER,value:u}),d&&a.push({gemini_cli_key:ie.GEMINI_CLI_GH_ISSUE_NUMBER,value:d}),l&&a.push({gemini_cli_key:ie.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!==Ct.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<zcn||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(Hcn,{method:"POST",body:Mr(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:ie.GEMINI_CLI_START_SESSION_MODEL,value:e.model},{gemini_cli_key:ie.GEMINI_CLI_START_SESSION_EMBEDDING_MODEL,value:e.embedding_model},{gemini_cli_key:ie.GEMINI_CLI_START_SESSION_SANDBOX,value:e.sandbox_enabled.toString()},{gemini_cli_key:ie.GEMINI_CLI_START_SESSION_CORE_TOOLS,value:e.core_tools_enabled},{gemini_cli_key:ie.GEMINI_CLI_START_SESSION_APPROVAL_MODE,value:e.approval_mode},{gemini_cli_key:ie.GEMINI_CLI_START_SESSION_API_KEY_ENABLED,value:e.api_key_enabled.toString()},{gemini_cli_key:ie.GEMINI_CLI_START_SESSION_VERTEX_API_ENABLED,value:e.vertex_ai_enabled.toString()},{gemini_cli_key:ie.GEMINI_CLI_START_SESSION_DEBUG_MODE_ENABLED,value:e.debug_enabled.toString()},{gemini_cli_key:ie.GEMINI_CLI_START_SESSION_VERTEX_API_ENABLED,value:e.vertex_ai_enabled.toString()},{gemini_cli_key:ie.GEMINI_CLI_START_SESSION_MCP_SERVERS,value:e.mcp_servers},{gemini_cli_key:ie.GEMINI_CLI_START_SESSION_VERTEX_API_ENABLED,value:e.vertex_ai_enabled.toString()},{gemini_cli_key:ie.GEMINI_CLI_START_SESSION_TELEMETRY_ENABLED,value:e.telemetry_enabled.toString()},{gemini_cli_key:ie.GEMINI_CLI_START_SESSION_TELEMETRY_LOG_USER_PROMPTS_ENABLED,value:e.telemetry_log_user_prompts_enabled.toString()},{gemini_cli_key:ie.GEMINI_CLI_START_SESSION_MCP_SERVERS_COUNT,value:e.mcp_servers_count?e.mcp_servers_count.toString():""},{gemini_cli_key:ie.GEMINI_CLI_START_SESSION_MCP_TOOLS_COUNT,value:e.mcp_tools_count?.toString()??""},{gemini_cli_key:ie.GEMINI_CLI_START_SESSION_MCP_TOOLS,value:e.mcp_tools?e.mcp_tools:""},{gemini_cli_key:ie.GEMINI_CLI_START_SESSION_EXTENSIONS_COUNT,value:e.extensions_count.toString()},{gemini_cli_key:ie.GEMINI_CLI_START_SESSION_EXTENSION_IDS,value:e.extension_ids.toString()},{gemini_cli_key:ie.GEMINI_CLI_START_SESSION_WORKTREE_ACTIVE,value:e.worktree_active.toString()}],n=UI.cpus();n&&n.length>0&&r.push({gemini_cli_key:ie.GEMINI_CLI_CPU_INFO,value:n[0].model}),r.push({gemini_cli_key:ie.GEMINI_CLI_CPU_CORES,value:UI.availableParallelism().toString()},{gemini_cli_key:ie.GEMINI_CLI_RAM_TOTAL_GB,value:(UI.totalmem()/1024**3).toFixed(2).toString()});let o=await Ycn();r.push({gemini_cli_key:ie.GEMINI_CLI_GPU_INFO,value:o}),this.sessionData=r,this.enqueueLogEventAfterExperimentsLoadAsync(this.createLogEvent(Ct.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:ie.GEMINI_CLI_USER_PROMPT_LENGTH,value:JSON.stringify(e.prompt_length)}];this.enqueueLogEvent(this.createLogEvent(Ct.NEW_PROMPT,r)),this.flushIfNeeded()}logToolCallEvent(e){let r=[{gemini_cli_key:ie.GEMINI_CLI_TOOL_CALL_NAME,value:JSON.stringify(e.function_name)},{gemini_cli_key:ie.GEMINI_CLI_TOOL_CALL_DECISION,value:JSON.stringify(e.decision)},{gemini_cli_key:ie.GEMINI_CLI_TOOL_CALL_SUCCESS,value:JSON.stringify(e.success)},{gemini_cli_key:ie.GEMINI_CLI_TOOL_CALL_DURATION_MS,value:JSON.stringify(e.duration_ms)},{gemini_cli_key:ie.GEMINI_CLI_TOOL_CALL_ERROR_TYPE,value:JSON.stringify(e.error_type)},{gemini_cli_key:ie.GEMINI_CLI_TOOL_TYPE,value:JSON.stringify(e.tool_type)},{gemini_cli_key:ie.GEMINI_CLI_TOOL_CALL_CONTENT_LENGTH,value:JSON.stringify(e.content_length)},{gemini_cli_key:ie.GEMINI_CLI_TOOL_CALL_MCP_SERVER_NAME,value:JSON.stringify(e.mcp_server_name)}];if(e.metadata){let o={model_added_lines:ie.GEMINI_CLI_AI_ADDED_LINES,model_removed_lines:ie.GEMINI_CLI_AI_REMOVED_LINES,model_added_chars:ie.GEMINI_CLI_AI_ADDED_CHARS,model_removed_chars:ie.GEMINI_CLI_AI_REMOVED_CHARS,user_added_lines:ie.GEMINI_CLI_USER_ADDED_LINES,user_removed_lines:ie.GEMINI_CLI_USER_REMOVED_LINES,user_added_chars:ie.GEMINI_CLI_USER_ADDED_CHARS,user_removed_chars:ie.GEMINI_CLI_USER_REMOVED_CHARS};if(e.function_name===Vo&&e.metadata.ask_user){let s=e.metadata.ask_user,c={question_types:ie.GEMINI_CLI_ASK_USER_QUESTION_TYPES,dismissed:ie.GEMINI_CLI_ASK_USER_DISMISSED,empty_submission:ie.GEMINI_CLI_ASK_USER_EMPTY_SUBMISSION,answer_count:ie.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:ie.GEMINI_CLI_EXTENSION_ID,value:e.extension_id});let n=this.createLogEvent(Ct.TOOL_CALL,r);this.enqueueLogEvent(n),this.flushIfNeeded()}logFileOperationEvent(e){let r=[{gemini_cli_key:ie.GEMINI_CLI_TOOL_CALL_NAME,value:JSON.stringify(e.tool_name)},{gemini_cli_key:ie.GEMINI_CLI_FILE_OPERATION_TYPE,value:JSON.stringify(e.operation)},{gemini_cli_key:ie.GEMINI_CLI_FILE_OPERATION_LINES,value:JSON.stringify(e.lines)},{gemini_cli_key:ie.GEMINI_CLI_FILE_OPERATION_MIMETYPE,value:JSON.stringify(e.mimetype)},{gemini_cli_key:ie.GEMINI_CLI_FILE_OPERATION_EXTENSION,value:JSON.stringify(e.extension)}];e.programming_language&&r.push({gemini_cli_key:ie.GEMINI_CLI_PROGRAMMING_LANGUAGE,value:e.programming_language});let n=this.createLogEvent(Ct.FILE_OPERATION,r);this.enqueueLogEvent(n),this.flushIfNeeded()}logApiRequestEvent(e){let r=[{gemini_cli_key:ie.GEMINI_CLI_API_REQUEST_MODEL,value:JSON.stringify(e.model)}];this.enqueueLogEvent(this.createLogEvent(Ct.API_REQUEST,r)),this.flushIfNeeded()}logApiResponseEvent(e){let r=[{gemini_cli_key:ie.GEMINI_CLI_API_RESPONSE_MODEL,value:JSON.stringify(e.model)},{gemini_cli_key:ie.GEMINI_CLI_API_RESPONSE_STATUS_CODE,value:JSON.stringify(e.status_code)},{gemini_cli_key:ie.GEMINI_CLI_API_RESPONSE_DURATION_MS,value:JSON.stringify(e.duration_ms)},{gemini_cli_key:ie.GEMINI_CLI_API_RESPONSE_INPUT_TOKEN_COUNT,value:JSON.stringify(e.usage.input_token_count)},{gemini_cli_key:ie.GEMINI_CLI_API_RESPONSE_OUTPUT_TOKEN_COUNT,value:JSON.stringify(e.usage.output_token_count)},{gemini_cli_key:ie.GEMINI_CLI_API_RESPONSE_CACHED_TOKEN_COUNT,value:JSON.stringify(e.usage.cached_content_token_count)},{gemini_cli_key:ie.GEMINI_CLI_API_RESPONSE_THINKING_TOKEN_COUNT,value:JSON.stringify(e.usage.thoughts_token_count)},{gemini_cli_key:ie.GEMINI_CLI_API_RESPONSE_TOOL_TOKEN_COUNT,value:JSON.stringify(e.usage.tool_token_count)},{gemini_cli_key:ie.GEMINI_CLI_API_RESPONSE_CONTEXT_BREAKDOWN_SYSTEM_INSTRUCTIONS,value:JSON.stringify(e.usage.context_breakdown?.system_instructions??0)},{gemini_cli_key:ie.GEMINI_CLI_API_RESPONSE_CONTEXT_BREAKDOWN_TOOL_DEFINITIONS,value:JSON.stringify(e.usage.context_breakdown?.tool_definitions??0)},{gemini_cli_key:ie.GEMINI_CLI_API_RESPONSE_CONTEXT_BREAKDOWN_HISTORY,value:JSON.stringify(e.usage.context_breakdown?.history??0)},{gemini_cli_key:ie.GEMINI_CLI_API_RESPONSE_CONTEXT_BREAKDOWN_TOOL_CALLS,value:JSON.stringify(e.usage.context_breakdown?.tool_calls??{})},{gemini_cli_key:ie.GEMINI_CLI_API_RESPONSE_CONTEXT_BREAKDOWN_MCP_SERVERS,value:JSON.stringify(e.usage.context_breakdown?.mcp_servers??0)}];this.enqueueLogEvent(this.createLogEvent(Ct.API_RESPONSE,r)),this.flushIfNeeded()}logApiErrorEvent(e){let r=[{gemini_cli_key:ie.GEMINI_CLI_API_ERROR_MODEL,value:JSON.stringify(e.model)},{gemini_cli_key:ie.GEMINI_CLI_API_ERROR_TYPE,value:JSON.stringify(e.error_type)},{gemini_cli_key:ie.GEMINI_CLI_API_ERROR_STATUS_CODE,value:JSON.stringify(e.status_code)},{gemini_cli_key:ie.GEMINI_CLI_API_ERROR_DURATION_MS,value:JSON.stringify(e.duration_ms)}];this.enqueueLogEvent(this.createLogEvent(Ct.API_ERROR,r)),this.flushIfNeeded()}logChatCompressionEvent(e){let r=[{gemini_cli_key:ie.GEMINI_CLI_COMPRESSION_TOKENS_BEFORE,value:`${e.tokens_before}`},{gemini_cli_key:ie.GEMINI_CLI_COMPRESSION_TOKENS_AFTER,value:`${e.tokens_after}`}];this.enqueueLogEvent(this.createLogEvent(Ct.CHAT_COMPRESSION,r))}logFlashFallbackEvent(){this.enqueueLogEvent(this.createLogEvent(Ct.FLASH_FALLBACK,[])),this.flushToClearcut().catch(e=>{B.debug("Error flushing to Clearcut:",e)})}logRipgrepFallbackEvent(){this.enqueueLogEvent(this.createLogEvent(Ct.RIPGREP_FALLBACK,[])),this.flushToClearcut().catch(e=>{B.debug("Error flushing to Clearcut:",e)})}logLoopDetectedEvent(e){let r=[{gemini_cli_key:ie.GEMINI_CLI_LOOP_DETECTED_TYPE,value:JSON.stringify(e.loop_type)}];e.confirmed_by_model&&r.push({gemini_cli_key:ie.GEMINI_CLI_LOOP_DETECTED_CONFIRMED_BY_MODEL,value:e.confirmed_by_model}),this.enqueueLogEvent(this.createLogEvent(Ct.LOOP_DETECTED,r)),this.flushIfNeeded()}logLoopDetectionDisabledEvent(){let e=[];this.enqueueLogEvent(this.createLogEvent(Ct.LOOP_DETECTION_DISABLED,e)),this.flushIfNeeded()}logNextSpeakerCheck(e){let r=[{gemini_cli_key:ie.GEMINI_CLI_RESPONSE_FINISH_REASON,value:JSON.stringify(e.finish_reason)},{gemini_cli_key:ie.GEMINI_CLI_NEXT_SPEAKER_CHECK_RESULT,value:JSON.stringify(e.result)}];this.enqueueLogEvent(this.createLogEvent(Ct.NEXT_SPEAKER_CHECK,r)),this.flushIfNeeded()}logSlashCommandEvent(e){let r=[{gemini_cli_key:ie.GEMINI_CLI_SLASH_COMMAND_NAME,value:JSON.stringify(e.command)}];e.subcommand&&r.push({gemini_cli_key:ie.GEMINI_CLI_SLASH_COMMAND_SUBCOMMAND,value:JSON.stringify(e.subcommand)}),e.status&&r.push({gemini_cli_key:ie.GEMINI_CLI_SLASH_COMMAND_STATUS,value:JSON.stringify(e.status)}),e.extension_id&&r.push({gemini_cli_key:ie.GEMINI_CLI_EXTENSION_ID,value:e.extension_id}),this.enqueueLogEvent(this.createLogEvent(Ct.SLASH_COMMAND,r)),this.flushIfNeeded()}logRewindEvent(e){let r=[{gemini_cli_key:ie.GEMINI_CLI_REWIND_OUTCOME,value:e.outcome}];this.enqueueLogEvent(this.createLogEvent(Ct.REWIND,r)),this.flushIfNeeded()}logMalformedJsonResponseEvent(e){let r=[{gemini_cli_key:ie.GEMINI_CLI_MALFORMED_JSON_RESPONSE_MODEL,value:JSON.stringify(e.model)}];this.enqueueLogEvent(this.createLogEvent(Ct.MALFORMED_JSON_RESPONSE,r)),this.flushIfNeeded()}logIdeConnectionEvent(e){let r=[{gemini_cli_key:ie.GEMINI_CLI_IDE_CONNECTION_TYPE,value:JSON.stringify(e.connection_type)}];this.enqueueLogEventAfterExperimentsLoadAsync(this.createLogEvent(Ct.START_SESSION,r)).then(()=>{this.flushToClearcut().catch(n=>{B.debug("Error flushing to Clearcut:",n)})})}logConversationFinishedEvent(e){let r=[{gemini_cli_key:ie.GEMINI_CLI_SESSION_ID,value:this.config?.getSessionId()??""},{gemini_cli_key:ie.GEMINI_CLI_CONVERSATION_TURN_COUNT,value:JSON.stringify(e.turnCount)},{gemini_cli_key:ie.GEMINI_CLI_APPROVAL_MODE,value:e.approvalMode}];this.enqueueLogEvent(this.createLogEvent(Ct.CONVERSATION_FINISHED,r)),this.flushIfNeeded()}logEndSessionEvent(){this.enqueueLogEvent(this.createLogEvent(Ct.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:ie.GEMINI_CLI_INVALID_CHUNK_ERROR_MESSAGE,value:e.error_message}),this.enqueueLogEvent(this.createLogEvent(Ct.INVALID_CHUNK,r)),this.flushIfNeeded()}logContentRetryEvent(e){let r=[{gemini_cli_key:ie.GEMINI_CLI_CONTENT_RETRY_ATTEMPT_NUMBER,value:String(e.attempt_number)},{gemini_cli_key:ie.GEMINI_CLI_CONTENT_RETRY_ERROR_TYPE,value:e.error_type},{gemini_cli_key:ie.GEMINI_CLI_CONTENT_RETRY_DELAY_MS,value:String(e.retry_delay_ms)},{gemini_cli_key:ie.GEMINI_CLI_API_REQUEST_MODEL,value:e.model}];this.enqueueLogEvent(this.createLogEvent(Ct.CONTENT_RETRY,r)),this.flushIfNeeded()}logContentRetryFailureEvent(e){let r=[{gemini_cli_key:ie.GEMINI_CLI_CONTENT_RETRY_FAILURE_TOTAL_ATTEMPTS,value:String(e.total_attempts)},{gemini_cli_key:ie.GEMINI_CLI_CONTENT_RETRY_FAILURE_FINAL_ERROR_TYPE,value:e.final_error_type},{gemini_cli_key:ie.GEMINI_CLI_API_REQUEST_MODEL,value:e.model}];e.total_duration_ms&&r.push({gemini_cli_key:ie.GEMINI_CLI_CONTENT_RETRY_FAILURE_TOTAL_DURATION_MS,value:String(e.total_duration_ms)}),this.enqueueLogEvent(this.createLogEvent(Ct.CONTENT_RETRY_FAILURE,r)),this.flushIfNeeded()}logNetworkRetryAttemptEvent(e){let r=[{gemini_cli_key:ie.GEMINI_CLI_NETWORK_RETRY_ATTEMPT_NUMBER,value:String(e.attempt)},{gemini_cli_key:ie.GEMINI_CLI_NETWORK_RETRY_DELAY_MS,value:String(e.delay_ms)},{gemini_cli_key:ie.GEMINI_CLI_NETWORK_RETRY_ERROR_TYPE,value:e.error_type},{gemini_cli_key:ie.GEMINI_CLI_API_REQUEST_MODEL,value:e.model}];this.enqueueLogEvent(this.createLogEvent(Ct.RETRY_ATTEMPT,r)),this.flushIfNeeded()}async logExtensionInstallEvent(e){let r=[{gemini_cli_key:ie.GEMINI_CLI_EXTENSION_NAME,value:e.hashed_extension_name},{gemini_cli_key:ie.GEMINI_CLI_EXTENSION_ID,value:e.extension_id},{gemini_cli_key:ie.GEMINI_CLI_EXTENSION_VERSION,value:e.extension_version},{gemini_cli_key:ie.GEMINI_CLI_EXTENSION_SOURCE,value:e.extension_source},{gemini_cli_key:ie.GEMINI_CLI_EXTENSION_INSTALL_STATUS,value:e.status}];this.enqueueLogEvent(this.createBasicLogEvent(Ct.EXTENSION_INSTALL,r)),await this.flushToClearcut().catch(n=>{B.debug("Error flushing to Clearcut:",n)})}async logExtensionUninstallEvent(e){let r=[{gemini_cli_key:ie.GEMINI_CLI_EXTENSION_NAME,value:e.hashed_extension_name},{gemini_cli_key:ie.GEMINI_CLI_EXTENSION_ID,value:e.extension_id},{gemini_cli_key:ie.GEMINI_CLI_EXTENSION_UNINSTALL_STATUS,value:e.status}];this.enqueueLogEvent(this.createBasicLogEvent(Ct.EXTENSION_UNINSTALL,r)),await this.flushToClearcut().catch(n=>{B.debug("Error flushing to Clearcut:",n)})}async logExtensionUpdateEvent(e){let r=[{gemini_cli_key:ie.GEMINI_CLI_EXTENSION_NAME,value:e.hashed_extension_name},{gemini_cli_key:ie.GEMINI_CLI_EXTENSION_ID,value:e.extension_id},{gemini_cli_key:ie.GEMINI_CLI_EXTENSION_VERSION,value:e.extension_version},{gemini_cli_key:ie.GEMINI_CLI_EXTENSION_PREVIOUS_VERSION,value:e.extension_previous_version},{gemini_cli_key:ie.GEMINI_CLI_EXTENSION_SOURCE,value:e.extension_source},{gemini_cli_key:ie.GEMINI_CLI_EXTENSION_UPDATE_STATUS,value:e.status}];this.enqueueLogEvent(this.createBasicLogEvent(Ct.EXTENSION_UPDATE,r)),await this.flushToClearcut().catch(n=>{B.debug("Error flushing to Clearcut:",n)})}logToolOutputTruncatedEvent(e){let r=[{gemini_cli_key:ie.GEMINI_CLI_TOOL_CALL_NAME,value:JSON.stringify(e.tool_name)},{gemini_cli_key:ie.GEMINI_CLI_TOOL_OUTPUT_TRUNCATED_ORIGINAL_LENGTH,value:JSON.stringify(e.original_content_length)},{gemini_cli_key:ie.GEMINI_CLI_TOOL_OUTPUT_TRUNCATED_TRUNCATED_LENGTH,value:JSON.stringify(e.truncated_content_length)},{gemini_cli_key:ie.GEMINI_CLI_TOOL_OUTPUT_TRUNCATED_THRESHOLD,value:JSON.stringify(e.threshold)}],n=this.createLogEvent(Ct.TOOL_OUTPUT_TRUNCATED,r);this.enqueueLogEvent(n),this.flushIfNeeded()}logToolOutputMaskingEvent(e){let r=[{gemini_cli_key:ie.GEMINI_CLI_TOOL_OUTPUT_MASKING_TOKENS_BEFORE,value:e.tokens_before.toString()},{gemini_cli_key:ie.GEMINI_CLI_TOOL_OUTPUT_MASKING_TOKENS_AFTER,value:e.tokens_after.toString()},{gemini_cli_key:ie.GEMINI_CLI_TOOL_OUTPUT_MASKING_MASKED_COUNT,value:e.masked_count.toString()},{gemini_cli_key:ie.GEMINI_CLI_TOOL_OUTPUT_MASKING_TOTAL_PRUNABLE_TOKENS,value:e.total_prunable_tokens.toString()}];this.enqueueLogEvent(this.createLogEvent(Ct.TOOL_OUTPUT_MASKING,r)),this.flushIfNeeded()}logModelRoutingEvent(e){let r=[{gemini_cli_key:ie.GEMINI_CLI_ROUTING_DECISION,value:e.decision_model},{gemini_cli_key:ie.GEMINI_CLI_ROUTING_DECISION_SOURCE,value:e.decision_source},{gemini_cli_key:ie.GEMINI_CLI_ROUTING_LATENCY_MS,value:e.routing_latency_ms.toString()},{gemini_cli_key:ie.GEMINI_CLI_ROUTING_FAILURE,value:e.failed.toString()}];e.error_message&&r.push({gemini_cli_key:ie.GEMINI_CLI_ROUTING_FAILURE_REASON,value:e.error_message}),e.reasoning&&this.config?.getTelemetryLogPromptsEnabled()&&r.push({gemini_cli_key:ie.GEMINI_CLI_ROUTING_REASONING,value:e.reasoning}),e.enable_numerical_routing!==void 0&&r.push({gemini_cli_key:ie.GEMINI_CLI_ROUTING_NUMERICAL_ENABLED,value:e.enable_numerical_routing.toString()}),e.classifier_threshold&&r.push({gemini_cli_key:ie.GEMINI_CLI_ROUTING_CLASSIFIER_THRESHOLD,value:e.classifier_threshold}),this.enqueueLogEvent(this.createLogEvent(Ct.MODEL_ROUTING,r)),this.flushIfNeeded()}async logExtensionEnableEvent(e){let r=[{gemini_cli_key:ie.GEMINI_CLI_EXTENSION_NAME,value:e.hashed_extension_name},{gemini_cli_key:ie.GEMINI_CLI_EXTENSION_ID,value:e.extension_id},{gemini_cli_key:ie.GEMINI_CLI_EXTENSION_ENABLE_SETTING_SCOPE,value:e.setting_scope}];this.enqueueLogEvent(this.createBasicLogEvent(Ct.EXTENSION_ENABLE,r)),await this.flushToClearcut().catch(n=>{B.debug("Error flushing to Clearcut:",n)})}logModelSlashCommandEvent(e){let r=[{gemini_cli_key:ie.GEMINI_CLI_MODEL_SLASH_COMMAND,value:e.model_name}];this.enqueueLogEvent(this.createLogEvent(Ct.MODEL_SLASH_COMMAND,r)),this.flushIfNeeded()}async logExtensionDisableEvent(e){let r=[{gemini_cli_key:ie.GEMINI_CLI_EXTENSION_NAME,value:e.hashed_extension_name},{gemini_cli_key:ie.GEMINI_CLI_EXTENSION_ID,value:e.extension_id},{gemini_cli_key:ie.GEMINI_CLI_EXTENSION_DISABLE_SETTING_SCOPE,value:e.setting_scope}];this.enqueueLogEvent(this.createBasicLogEvent(Ct.EXTENSION_DISABLE,r)),await this.flushToClearcut().catch(n=>{B.debug("Error flushing to Clearcut:",n)})}logEditStrategyEvent(e){let r=[{gemini_cli_key:ie.GEMINI_CLI_EDIT_STRATEGY,value:e.strategy}];this.enqueueLogEvent(this.createLogEvent(Ct.EDIT_STRATEGY,r)),this.flushIfNeeded()}logEditCorrectionEvent(e){let r=[{gemini_cli_key:ie.GEMINI_CLI_EDIT_CORRECTION,value:e.correction}];this.enqueueLogEvent(this.createLogEvent(Ct.EDIT_CORRECTION,r)),this.flushIfNeeded()}logAgentStartEvent(e){let r=[{gemini_cli_key:ie.GEMINI_CLI_AGENT_ID,value:e.agent_id},{gemini_cli_key:ie.GEMINI_CLI_AGENT_NAME,value:e.agent_name}];this.enqueueLogEvent(this.createLogEvent(Ct.AGENT_START,r)),this.flushIfNeeded()}logAgentFinishEvent(e){let r=[{gemini_cli_key:ie.GEMINI_CLI_AGENT_ID,value:e.agent_id},{gemini_cli_key:ie.GEMINI_CLI_AGENT_NAME,value:e.agent_name},{gemini_cli_key:ie.GEMINI_CLI_AGENT_DURATION_MS,value:e.duration_ms.toString()},{gemini_cli_key:ie.GEMINI_CLI_AGENT_TURN_COUNT,value:e.turn_count.toString()},{gemini_cli_key:ie.GEMINI_CLI_AGENT_TERMINATE_REASON,value:e.terminate_reason}];this.enqueueLogEvent(this.createLogEvent(Ct.AGENT_FINISH,r)),this.flushIfNeeded()}logRecoveryAttemptEvent(e){let r=[{gemini_cli_key:ie.GEMINI_CLI_AGENT_ID,value:e.agent_id},{gemini_cli_key:ie.GEMINI_CLI_AGENT_NAME,value:e.agent_name},{gemini_cli_key:ie.GEMINI_CLI_AGENT_RECOVERY_REASON,value:e.reason},{gemini_cli_key:ie.GEMINI_CLI_AGENT_RECOVERY_DURATION_MS,value:e.duration_ms.toString()},{gemini_cli_key:ie.GEMINI_CLI_AGENT_RECOVERY_SUCCESS,value:e.success.toString()},{gemini_cli_key:ie.GEMINI_CLI_AGENT_TURN_COUNT,value:e.turn_count.toString()}];this.enqueueLogEvent(this.createLogEvent(Ct.RECOVERY_ATTEMPT,r)),this.flushIfNeeded()}logWebFetchFallbackAttemptEvent(e){let r=[{gemini_cli_key:ie.GEMINI_CLI_WEB_FETCH_FALLBACK_REASON,value:e.reason}];this.enqueueLogEvent(this.createLogEvent(Ct.WEB_FETCH_FALLBACK_ATTEMPT,r)),this.flushIfNeeded()}logLlmLoopCheckEvent(e){let r=[{gemini_cli_key:ie.GEMINI_CLI_PROMPT_ID,value:e.prompt_id},{gemini_cli_key:ie.GEMINI_CLI_LLM_LOOP_CHECK_FLASH_CONFIDENCE,value:e.flash_confidence.toString()},{gemini_cli_key:ie.GEMINI_CLI_LLM_LOOP_CHECK_MAIN_MODEL,value:e.main_model},{gemini_cli_key:ie.GEMINI_CLI_LLM_LOOP_CHECK_MAIN_MODEL_CONFIDENCE,value:e.main_model_confidence.toString()}];this.enqueueLogEvent(this.createLogEvent(Ct.LLM_LOOP_CHECK,r)),this.flushIfNeeded()}logHookCallEvent(e){let r=[{gemini_cli_key:ie.GEMINI_CLI_HOOK_EVENT_NAME,value:e.hook_event_name},{gemini_cli_key:ie.GEMINI_CLI_HOOK_DURATION_MS,value:e.duration_ms.toString()},{gemini_cli_key:ie.GEMINI_CLI_HOOK_SUCCESS,value:e.success.toString()}];e.exit_code!==void 0&&r.push({gemini_cli_key:ie.GEMINI_CLI_HOOK_EXIT_CODE,value:e.exit_code.toString()}),this.enqueueLogEvent(this.createLogEvent(Ct.HOOK_CALL,r)),this.flushIfNeeded()}logApprovalModeSwitchEvent(e){let r=[{gemini_cli_key:ie.GEMINI_CLI_ACTIVE_APPROVAL_MODE,value:e.from_mode},{gemini_cli_key:ie.GEMINI_CLI_APPROVAL_MODE_TO,value:e.to_mode}];this.enqueueLogEvent(this.createLogEvent(Ct.APPROVAL_MODE_SWITCH,r)),this.flushIfNeeded()}logApprovalModeDurationEvent(e){let r=[{gemini_cli_key:ie.GEMINI_CLI_ACTIVE_APPROVAL_MODE,value:e.mode},{gemini_cli_key:ie.GEMINI_CLI_APPROVAL_MODE_DURATION_MS,value:e.duration_ms.toString()}];this.enqueueLogEvent(this.createLogEvent(Ct.APPROVAL_MODE_DURATION,r)),this.flushIfNeeded()}logPlanExecutionEvent(e){let r=[{gemini_cli_key:ie.GEMINI_CLI_APPROVAL_MODE,value:e.approval_mode}];this.enqueueLogEvent(this.createLogEvent(Ct.PLAN_EXECUTION,r)),this.flushIfNeeded()}logKeychainAvailabilityEvent(e){let r=[{gemini_cli_key:ie.GEMINI_CLI_KEYCHAIN_AVAILABLE,value:JSON.stringify(e.available)}];this.enqueueLogEvent(this.createLogEvent(Ct.KEYCHAIN_AVAILABILITY,r)),this.flushIfNeeded()}logTokenStorageInitializationEvent(e){let r=[{gemini_cli_key:ie.GEMINI_CLI_TOKEN_STORAGE_TYPE,value:e.type},{gemini_cli_key:ie.GEMINI_CLI_TOKEN_STORAGE_FORCED,value:JSON.stringify(e.forced)}];this.enqueueLogEvent(this.createLogEvent(Ct.TOKEN_STORAGE_INITIALIZATION,r)),this.flushIfNeeded()}logOnboardingStartEvent(e){let r=[{gemini_cli_key:ie.GEMINI_CLI_ONBOARDING_START,value:"true"}];this.enqueueLogEvent(this.createLogEvent(Ct.ONBOARDING_START,r)),this.flushIfNeeded()}logOnboardingSuccessEvent(e){let r=[];e.userTier&&r.push({gemini_cli_key:ie.GEMINI_CLI_ONBOARDING_USER_TIER,value:e.userTier}),e.duration_ms!==void 0&&r.push({gemini_cli_key:ie.GEMINI_CLI_ONBOARDING_DURATION_MS,value:e.duration_ms.toString()}),this.enqueueLogEvent(this.createLogEvent(Ct.ONBOARDING_SUCCESS,r)),this.flushIfNeeded()}logStartupStatsEvent(e){let r=[{gemini_cli_key:ie.GEMINI_CLI_STARTUP_PHASES,value:JSON.stringify(e.phases)},{gemini_cli_key:ie.GEMINI_CLI_STARTUP_OS_PLATFORM,value:e.os_platform},{gemini_cli_key:ie.GEMINI_CLI_STARTUP_OS_RELEASE,value:e.os_release},{gemini_cli_key:ie.GEMINI_CLI_STARTUP_IS_DOCKER,value:JSON.stringify(e.is_docker)}];this.enqueueLogEvent(this.createLogEvent(Ct.STARTUP_STATS,r)),this.flushIfNeeded()}logCreditsUsedEvent(e){let r=[{gemini_cli_key:ie.GEMINI_CLI_BILLING_MODEL,value:JSON.stringify(e.model)},{gemini_cli_key:ie.GEMINI_CLI_BILLING_CREDITS_CONSUMED,value:JSON.stringify(e.credits_consumed)},{gemini_cli_key:ie.GEMINI_CLI_BILLING_CREDITS_REMAINING,value:JSON.stringify(e.credits_remaining)}];this.enqueueLogEvent(this.createLogEvent(Ct.CREDITS_USED,r)),this.flushIfNeeded()}logOverageOptionSelectedEvent(e){let r=[{gemini_cli_key:ie.GEMINI_CLI_BILLING_MODEL,value:JSON.stringify(e.model)},{gemini_cli_key:ie.GEMINI_CLI_BILLING_SELECTED_OPTION,value:JSON.stringify(e.selected_option)},{gemini_cli_key:ie.GEMINI_CLI_BILLING_CREDIT_BALANCE,value:JSON.stringify(e.credit_balance)}];this.enqueueLogEvent(this.createLogEvent(Ct.OVERAGE_OPTION_SELECTED,r)),this.flushIfNeeded()}logEmptyWalletMenuShownEvent(e){let r=[{gemini_cli_key:ie.GEMINI_CLI_BILLING_MODEL,value:JSON.stringify(e.model)}];this.enqueueLogEvent(this.createLogEvent(Ct.EMPTY_WALLET_MENU_SHOWN,r)),this.flushIfNeeded()}logCreditPurchaseClickEvent(e){let r=[{gemini_cli_key:ie.GEMINI_CLI_BILLING_MODEL,value:JSON.stringify(e.model)},{gemini_cli_key:ie.GEMINI_CLI_BILLING_PURCHASE_SOURCE,value:JSON.stringify(e.source)}];this.enqueueLogEvent(this.createLogEvent(Ct.CREDIT_PURCHASE_CLICK,r)),this.flushIfNeeded()}addDefaultFields(e,r){let n=[{gemini_cli_key:ie.GEMINI_CLI_SESSION_ID,value:this.config?.getSessionId()??""},{gemini_cli_key:ie.GEMINI_CLI_AUTH_TYPE,value:JSON.stringify(this.config?.getContentGeneratorConfig()?.authType)},{gemini_cli_key:ie.GEMINI_CLI_GOOGLE_ACCOUNTS_COUNT,value:`${r}`},{gemini_cli_key:ie.GEMINI_CLI_PROMPT_ID,value:this.promptId},{gemini_cli_key:ie.GEMINI_CLI_NODE_VERSION,value:process.versions.node},{gemini_cli_key:ie.GEMINI_CLI_USER_SETTINGS,value:this.getConfigJson()},{gemini_cli_key:ie.GEMINI_CLI_INTERACTIVE,value:this.config?.isInteractive().toString()??"false"},{gemini_cli_key:ie.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:ie.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 iOt.HttpsProxyAgent(e);throw new Error("Unsupported proxy type")}}getConfigJson(){return eXe(this.config)}shutdown(){this.logEndSessionEvent()}requeueFailedEvents(e){let r=e.slice(-LZ);e.length>LZ&&this.config?.getDebugMode()&&B.warn(`ClearcutLogger: Dropping ${e.length-LZ} events due to retry queue limit. Total events: ${e.length}, keeping: ${LZ}`);let n=DZ-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>DZ;)this.events.pop();this.config?.getDebugMode()&&B.debug(`ClearcutLogger: Re-queued ${o} events for retry (queue size: ${this.events.size})`)}};var IT=Fe(kt(),1),aOt=Fe(df(),1);import*as sOt from"node:fs";var N4=class{writeStream;constructor(e){this.writeStream=sOt.createWriteStream(e,{flags:"a"})}serialize(e){return Mr(e,2)+`
|
|
1061
|
+
`),B.error("Failed to authenticate with user code:",Se(e)),!1}}async function e4r(t){let e=await t4r(),r=process.env.OAUTH_CALLBACK_HOST||"127.0.0.1",n=`http://127.0.0.1:${e}/oauth2callback`,o=opt.randomBytes(32).toString("hex"),s=t.generateAuthUrl({redirect_uri:n,access_type:"offline",scope:F_e,state:o}),c=new Promise((u,d)=>{let l=ipt.createServer(async(a,p)=>{try{if(a.url.indexOf("/oauth2callback")===-1){p.writeHead(o$,{Location:U_e}),p.end(),d(new Ca("OAuth callback not received. Unexpected request: "+a.url));return}let f=new z6r.URL(a.url,"http://127.0.0.1:3000").searchParams;if(f.get("error")){p.writeHead(o$,{Location:U_e}),p.end();let g=f.get("error"),y=f.get("error_description")||"No additional details provided";d(new Ca(`Google OAuth error: ${g}. ${y}`))}else if(f.get("state")!==o)p.end("State mismatch. Possible CSRF attack"),d(new Ca("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 s$(t)}catch(y){B.warn("Failed to retrieve Google Account ID during authentication:",Se(y))}p.writeHead(o$,{Location:K6r}),p.end(),u()}catch(g){p.writeHead(o$,{Location:U_e}),p.end(),d(new Ca(`Failed to exchange authorization code for tokens: ${Se(g)}`))}else d(new Ca("No authorization code received from Google OAuth. Please try authenticating again."))}catch(f){f instanceof Ca?d(f):d(new Ca(`Unexpected error during OAuth authentication: ${Se(f)}`))}finally{l.close()}});l.listen(e,r,()=>{}),l.on("error",a=>{d(new Ca(`OAuth callback server error: ${Se(a)}`))})});return{authUrl:s,loginCompletePromise:c}}function t4r(){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=spt.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 r4r(){if(j_e())return C2.loadCredentials();let e=[pr.getOAuthCredsPath(),process.env.GOOGLE_APPLICATION_CREDENTIALS].filter(r=>!!r);for(let r of e)try{let n=await xL.readFile(r,"utf-8");return JSON.parse(n)}catch(n){B.debug(`Failed to load credentials from ${r}:`,Se(n))}return null}function n4r(){OL.clear()}async function JBi(){try{j_e()?await C2.clearCredentials():await xL.rm(pr.getOAuthCredsPath(),{force:!0}),await l$.clearCachedGoogleAccount(),n4r()}catch(t){B.warn("Failed to clear cached credentials:",t)}}async function s$(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 l$.cacheGoogleAccount(n.email)}catch(e){B.log("Error retrieving user info:",e)}}function KBi(){OL.clear()}async function i4r(t){let e=pr.getOAuthCredsPath();await xL.mkdir(Y6r.dirname(e),{recursive:!0});let r=JSON.stringify(t,null,2);await xL.writeFile(e,r,{mode:384});try{await xL.chmod(e,384)}catch{}}var c$;(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"})(c$||(c$={}));var x0={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 u$;(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"})(u$||(u$={}));var Mh;(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"})(Mh||(Mh={}));var IL;(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"})(IL||(IL={}));var o4r=Y.object({extensionsEnabled:Y.boolean().optional()}),dpt=Y.object({extensionsSetting:o4r.optional(),unmanagedCapabilitiesEnabled:Y.boolean().optional()}),s4r=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()}),a4r=Y.object({scopes:Y.array(Y.string()).optional(),clientId:Y.string().optional(),clientSecret:Y.string().optional()}),ppt=Y.object({url:Y.string(),type:Y.enum(["sse","http"]),authProviderType:Y.nativeEnum(O0).optional(),oauth:a4r.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()}),Q_e=Y.object({mcpServers:Y.record(s4r).optional(),requiredMcpServers:Y.record(ppt).optional()}),l4r=Y.object({mcpEnabled:Y.boolean().optional(),mcpConfigJson:Y.string().optional()}),t5i=Y.object({strictModeDisabled:Y.boolean().optional(),mcpSetting:Y.object({mcpEnabled:Y.boolean().optional(),mcpConfig:Q_e.optional(),requiredMcpConfig:Y.record(ppt).optional()}).optional(),cliFeatureSetting:dpt.optional()}),fpt=Y.object({secureModeEnabled:Y.boolean().optional(),strictModeDisabled:Y.boolean().optional(),mcpSetting:l4r.optional(),cliFeatureSetting:dpt.optional(),adminControlsApplicable:Y.boolean().optional()});import*as lYt from"node:readline";import{Readable as jHn}from"node:stream";var pS="GOOGLE_ONE_AI",c4r=new Set([Eh,_x,cl]);function hpt(t){return c4r.has(t)}var u4r="https://one.google.com/ai",d4r="https://accounts.google.com/AccountChooser",p4r="gemini_cli",f4r="web";function h4r(t,e){let r=new URLSearchParams({Email:t,continue:e});return`${d4r}?${r.toString()}`}var i5i={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 o5i(t,e,r){let n=`${u4r}/${t}`,o=new URLSearchParams({utm_source:p4r,utm_medium:f4r,utm_campaign:r}),s=`${n}?${o.toString()}`;return h4r(e,s)}function gpt(t){if(!t?.availableCredits)return null;let e=t.availableCredits.filter(r=>r.creditType===pS);return e.length===0?null:e.reduce((r,n)=>{let o=parseInt(n.creditAmount??"0",10);return r+(isNaN(o)?0:o)},0)}var q_e=50;function mpt(t,e){return t==="always"&&e!=null&&e>=q_e}function s5i(t,e){return t==="ask"&&e!=null&&e>=q_e}function a5i(t,e){return t!=="never"&&e!=null&&e<q_e}var Kt=Fe(Fh(),1);qe();var PMt=Fe(fwe(),1),NMt=Fe(gwe(),1),kMt=Fe(bwe(),1),DMt=Fe(Swe(),1),LMt=Fe(wwe(),1),MMt=Fe(t6(),1);Wp();var BMt=Fe(Wwt(),1);hl();var UMt=Fe(G0(),1),$re=Fe($J(),1),Hre=Fe(mJ(),1),kb=Fe(df(),1),FMt=Fe(yCt(),1);var nOt=Fe(h2t(),1),iOt=Fe(TKe(),1);import{createHash as Ucn}from"node:crypto";import*as UI from"node:os";var ie;(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"})(ie||(ie={}));var mIe=Fe(w2t(),1),yIe=Fe(N2t(),1),Z2t=Fe(B2t(),1),vf=Fe(q2t(),1);var AIe=Fe($2t(),1);var OT=Fe(hIe(),1);var Dcn=Fe(J2t(),1),Lcn=Fe(X2t(),1);var HVi=mIe.default.MinFibonacciHeap,zVi=mIe.default.MaxFibonacciHeap,WVi=yIe.default.MinHeap,YVi=yIe.default.MaxHeap,JVi=Z2t.default.GeneralizedSuffixArray,KVi=vf.default.Uint8Vector,XVi=vf.default.Uint8ClampedVector,ZVi=vf.default.Int8Vector,e$i=vf.default.Uint16Vector,t$i=vf.default.Int16Vector,r$i=vf.default.Uint32Vector,n$i=vf.default.Int32Vector,i$i=vf.default.Float32Vector,o$i=vf.default.Float64Vector,s$i=vf.default.PointerVector;var eOt="0dace6f",tOt="0.37.1";var Gr={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 MI(){return!!(process.env.EDITOR_IN_CLOUD_SHELL||process.env.CLOUD_SHELL)}function _Ie(){return!!process.env.TERMINAL_EMULATOR?.toLowerCase().includes("jetbrains")}function BI(){return process.env.ANTIGRAVITY_CLI_ALIAS?Gr.antigravity:process.env.__COG_BASHRC_SOURCED?Gr.devin:process.env.REPLIT_USER?Gr.replit:process.env.CURSOR_TRACE_ID?Gr.cursor:process.env.CODESPACES?Gr.codespaces:MI()?Gr.cloudshell:process.env.TERM_PRODUCT==="Trae"?Gr.trae:process.env.MONOSPACE_ENV?Gr.firebasestudio:process.env.POSITRON==="1"?Gr.positron:process.env.TERM_PROGRAM==="sublime"?Gr.sublimetext:process.env.ZED_SESSION_ID||process.env.TERM_PROGRAM==="Zed"?Gr.zed:process.env.XCODE_VERSION_ACTUAL?Gr.xcode:_Ie()?Gr.jetbrains:Gr.vscode}function Mcn(t,e){return t.name!==Gr.vscode.name?t:!e.command||e.command.toLowerCase().includes("code")?Gr.vscode:Gr.vscodefork}function Bcn(t,e){if(t.name!==Gr.jetbrains.name||!e.command)return t;let r=e.command.toLowerCase(),n=[["idea",Gr.intellijidea],["webstorm",Gr.webstorm],["pycharm",Gr.pycharm],["goland",Gr.goland],["studio",Gr.androidstudio],["clion",Gr.clion],["rustrover",Gr.rustrover],["datagrip",Gr.datagrip],["phpstorm",Gr.phpstorm]];for(let[o,s]of n)if(r.includes(o))return s;return t}function rOt(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&&!_Ie())return;let r=BI();return _Ie()?Bcn(r,t):Mcn(r,t)}var Ct;(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"})(Ct||(Ct={}));function Fcn(){return process.env.SURFACE?process.env.SURFACE:MI()?Gr.cloudshell.name:process.env.GITHUB_SHA?"GitHub":process.env.TERM_PROGRAM==="vscode"?BI().name||Gr.vscode.name:"SURFACE_NOT_SET"}function jcn(){return process.env.GH_WORKFLOW_NAME}function Qcn(){return process.env.GITHUB_REPOSITORY}function qcn(){return process.env.GITHUB_EVENT_NAME}function Gcn(){return process.env.GH_PR_NUMBER}function Vcn(){return process.env.GH_ISSUE_NUMBER}function $cn(){return process.env.GH_CUSTOM_TRACKING_ID}var Hcn="https://play.googleapis.com/log?format=json&hasfast=true",zcn=1e3*60,DZ=1e3,LZ=100,oOt="NA",P4;async function Wcn(){try{let t=await nOt.default.graphics();t.controllers&&t.controllers.length>0?P4=t.controllers.map(e=>e.model).join(", "):P4=oOt}catch(t){P4="FAILED",B.error("Failed to get GPU information for telemetry",Se(t))}}async function Ycn(){return P4||await Wcn(),P4??oOt}var Pt=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 AIe.default(Array,DZ),this.promptId=e?.getSessionId()??"",this.installationManager=new g_,this.userAccountManager=new h_;let r=Qcn();r&&(this.hashedGHRepositoryName=Ucn("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>=DZ;n&&this.events.shift();let o={event_time_ms:Date.now(),source_extension_json:Mr(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:ie.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=Fcn(),s=jcn(),c=qcn(),u=Gcn(),d=Vcn(),l=$cn(),a=[...r,{gemini_cli_key:ie.GEMINI_CLI_SURFACE,value:o},{gemini_cli_key:ie.GEMINI_CLI_VERSION,value:tOt},{gemini_cli_key:ie.GEMINI_CLI_GIT_COMMIT_HASH,value:eOt},{gemini_cli_key:ie.GEMINI_CLI_OS,value:process.platform}];s&&a.push({gemini_cli_key:ie.GEMINI_CLI_GH_WORKFLOW_NAME,value:s}),this.hashedGHRepositoryName&&a.push({gemini_cli_key:ie.GEMINI_CLI_GH_REPOSITORY_NAME_HASH,value:this.hashedGHRepositoryName}),c&&a.push({gemini_cli_key:ie.GEMINI_CLI_GH_EVENT_NAME,value:c}),u&&a.push({gemini_cli_key:ie.GEMINI_CLI_GH_PR_NUMBER,value:u}),d&&a.push({gemini_cli_key:ie.GEMINI_CLI_GH_ISSUE_NUMBER,value:d}),l&&a.push({gemini_cli_key:ie.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!==Ct.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<zcn||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(Hcn,{method:"POST",body:Mr(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:ie.GEMINI_CLI_START_SESSION_MODEL,value:e.model},{gemini_cli_key:ie.GEMINI_CLI_START_SESSION_EMBEDDING_MODEL,value:e.embedding_model},{gemini_cli_key:ie.GEMINI_CLI_START_SESSION_SANDBOX,value:e.sandbox_enabled.toString()},{gemini_cli_key:ie.GEMINI_CLI_START_SESSION_CORE_TOOLS,value:e.core_tools_enabled},{gemini_cli_key:ie.GEMINI_CLI_START_SESSION_APPROVAL_MODE,value:e.approval_mode},{gemini_cli_key:ie.GEMINI_CLI_START_SESSION_API_KEY_ENABLED,value:e.api_key_enabled.toString()},{gemini_cli_key:ie.GEMINI_CLI_START_SESSION_VERTEX_API_ENABLED,value:e.vertex_ai_enabled.toString()},{gemini_cli_key:ie.GEMINI_CLI_START_SESSION_DEBUG_MODE_ENABLED,value:e.debug_enabled.toString()},{gemini_cli_key:ie.GEMINI_CLI_START_SESSION_VERTEX_API_ENABLED,value:e.vertex_ai_enabled.toString()},{gemini_cli_key:ie.GEMINI_CLI_START_SESSION_MCP_SERVERS,value:e.mcp_servers},{gemini_cli_key:ie.GEMINI_CLI_START_SESSION_VERTEX_API_ENABLED,value:e.vertex_ai_enabled.toString()},{gemini_cli_key:ie.GEMINI_CLI_START_SESSION_TELEMETRY_ENABLED,value:e.telemetry_enabled.toString()},{gemini_cli_key:ie.GEMINI_CLI_START_SESSION_TELEMETRY_LOG_USER_PROMPTS_ENABLED,value:e.telemetry_log_user_prompts_enabled.toString()},{gemini_cli_key:ie.GEMINI_CLI_START_SESSION_MCP_SERVERS_COUNT,value:e.mcp_servers_count?e.mcp_servers_count.toString():""},{gemini_cli_key:ie.GEMINI_CLI_START_SESSION_MCP_TOOLS_COUNT,value:e.mcp_tools_count?.toString()??""},{gemini_cli_key:ie.GEMINI_CLI_START_SESSION_MCP_TOOLS,value:e.mcp_tools?e.mcp_tools:""},{gemini_cli_key:ie.GEMINI_CLI_START_SESSION_EXTENSIONS_COUNT,value:e.extensions_count.toString()},{gemini_cli_key:ie.GEMINI_CLI_START_SESSION_EXTENSION_IDS,value:e.extension_ids.toString()},{gemini_cli_key:ie.GEMINI_CLI_START_SESSION_WORKTREE_ACTIVE,value:e.worktree_active.toString()}],n=UI.cpus();n&&n.length>0&&r.push({gemini_cli_key:ie.GEMINI_CLI_CPU_INFO,value:n[0].model}),r.push({gemini_cli_key:ie.GEMINI_CLI_CPU_CORES,value:UI.availableParallelism().toString()},{gemini_cli_key:ie.GEMINI_CLI_RAM_TOTAL_GB,value:(UI.totalmem()/1024**3).toFixed(2).toString()});let o=await Ycn();r.push({gemini_cli_key:ie.GEMINI_CLI_GPU_INFO,value:o}),this.sessionData=r,this.enqueueLogEventAfterExperimentsLoadAsync(this.createLogEvent(Ct.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:ie.GEMINI_CLI_USER_PROMPT_LENGTH,value:JSON.stringify(e.prompt_length)}];this.enqueueLogEvent(this.createLogEvent(Ct.NEW_PROMPT,r)),this.flushIfNeeded()}logToolCallEvent(e){let r=[{gemini_cli_key:ie.GEMINI_CLI_TOOL_CALL_NAME,value:JSON.stringify(e.function_name)},{gemini_cli_key:ie.GEMINI_CLI_TOOL_CALL_DECISION,value:JSON.stringify(e.decision)},{gemini_cli_key:ie.GEMINI_CLI_TOOL_CALL_SUCCESS,value:JSON.stringify(e.success)},{gemini_cli_key:ie.GEMINI_CLI_TOOL_CALL_DURATION_MS,value:JSON.stringify(e.duration_ms)},{gemini_cli_key:ie.GEMINI_CLI_TOOL_CALL_ERROR_TYPE,value:JSON.stringify(e.error_type)},{gemini_cli_key:ie.GEMINI_CLI_TOOL_TYPE,value:JSON.stringify(e.tool_type)},{gemini_cli_key:ie.GEMINI_CLI_TOOL_CALL_CONTENT_LENGTH,value:JSON.stringify(e.content_length)},{gemini_cli_key:ie.GEMINI_CLI_TOOL_CALL_MCP_SERVER_NAME,value:JSON.stringify(e.mcp_server_name)}];if(e.metadata){let o={model_added_lines:ie.GEMINI_CLI_AI_ADDED_LINES,model_removed_lines:ie.GEMINI_CLI_AI_REMOVED_LINES,model_added_chars:ie.GEMINI_CLI_AI_ADDED_CHARS,model_removed_chars:ie.GEMINI_CLI_AI_REMOVED_CHARS,user_added_lines:ie.GEMINI_CLI_USER_ADDED_LINES,user_removed_lines:ie.GEMINI_CLI_USER_REMOVED_LINES,user_added_chars:ie.GEMINI_CLI_USER_ADDED_CHARS,user_removed_chars:ie.GEMINI_CLI_USER_REMOVED_CHARS};if(e.function_name===Vo&&e.metadata.ask_user){let s=e.metadata.ask_user,c={question_types:ie.GEMINI_CLI_ASK_USER_QUESTION_TYPES,dismissed:ie.GEMINI_CLI_ASK_USER_DISMISSED,empty_submission:ie.GEMINI_CLI_ASK_USER_EMPTY_SUBMISSION,answer_count:ie.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:ie.GEMINI_CLI_EXTENSION_ID,value:e.extension_id});let n=this.createLogEvent(Ct.TOOL_CALL,r);this.enqueueLogEvent(n),this.flushIfNeeded()}logFileOperationEvent(e){let r=[{gemini_cli_key:ie.GEMINI_CLI_TOOL_CALL_NAME,value:JSON.stringify(e.tool_name)},{gemini_cli_key:ie.GEMINI_CLI_FILE_OPERATION_TYPE,value:JSON.stringify(e.operation)},{gemini_cli_key:ie.GEMINI_CLI_FILE_OPERATION_LINES,value:JSON.stringify(e.lines)},{gemini_cli_key:ie.GEMINI_CLI_FILE_OPERATION_MIMETYPE,value:JSON.stringify(e.mimetype)},{gemini_cli_key:ie.GEMINI_CLI_FILE_OPERATION_EXTENSION,value:JSON.stringify(e.extension)}];e.programming_language&&r.push({gemini_cli_key:ie.GEMINI_CLI_PROGRAMMING_LANGUAGE,value:e.programming_language});let n=this.createLogEvent(Ct.FILE_OPERATION,r);this.enqueueLogEvent(n),this.flushIfNeeded()}logApiRequestEvent(e){let r=[{gemini_cli_key:ie.GEMINI_CLI_API_REQUEST_MODEL,value:JSON.stringify(e.model)}];this.enqueueLogEvent(this.createLogEvent(Ct.API_REQUEST,r)),this.flushIfNeeded()}logApiResponseEvent(e){let r=[{gemini_cli_key:ie.GEMINI_CLI_API_RESPONSE_MODEL,value:JSON.stringify(e.model)},{gemini_cli_key:ie.GEMINI_CLI_API_RESPONSE_STATUS_CODE,value:JSON.stringify(e.status_code)},{gemini_cli_key:ie.GEMINI_CLI_API_RESPONSE_DURATION_MS,value:JSON.stringify(e.duration_ms)},{gemini_cli_key:ie.GEMINI_CLI_API_RESPONSE_INPUT_TOKEN_COUNT,value:JSON.stringify(e.usage.input_token_count)},{gemini_cli_key:ie.GEMINI_CLI_API_RESPONSE_OUTPUT_TOKEN_COUNT,value:JSON.stringify(e.usage.output_token_count)},{gemini_cli_key:ie.GEMINI_CLI_API_RESPONSE_CACHED_TOKEN_COUNT,value:JSON.stringify(e.usage.cached_content_token_count)},{gemini_cli_key:ie.GEMINI_CLI_API_RESPONSE_THINKING_TOKEN_COUNT,value:JSON.stringify(e.usage.thoughts_token_count)},{gemini_cli_key:ie.GEMINI_CLI_API_RESPONSE_TOOL_TOKEN_COUNT,value:JSON.stringify(e.usage.tool_token_count)},{gemini_cli_key:ie.GEMINI_CLI_API_RESPONSE_CONTEXT_BREAKDOWN_SYSTEM_INSTRUCTIONS,value:JSON.stringify(e.usage.context_breakdown?.system_instructions??0)},{gemini_cli_key:ie.GEMINI_CLI_API_RESPONSE_CONTEXT_BREAKDOWN_TOOL_DEFINITIONS,value:JSON.stringify(e.usage.context_breakdown?.tool_definitions??0)},{gemini_cli_key:ie.GEMINI_CLI_API_RESPONSE_CONTEXT_BREAKDOWN_HISTORY,value:JSON.stringify(e.usage.context_breakdown?.history??0)},{gemini_cli_key:ie.GEMINI_CLI_API_RESPONSE_CONTEXT_BREAKDOWN_TOOL_CALLS,value:JSON.stringify(e.usage.context_breakdown?.tool_calls??{})},{gemini_cli_key:ie.GEMINI_CLI_API_RESPONSE_CONTEXT_BREAKDOWN_MCP_SERVERS,value:JSON.stringify(e.usage.context_breakdown?.mcp_servers??0)}];this.enqueueLogEvent(this.createLogEvent(Ct.API_RESPONSE,r)),this.flushIfNeeded()}logApiErrorEvent(e){let r=[{gemini_cli_key:ie.GEMINI_CLI_API_ERROR_MODEL,value:JSON.stringify(e.model)},{gemini_cli_key:ie.GEMINI_CLI_API_ERROR_TYPE,value:JSON.stringify(e.error_type)},{gemini_cli_key:ie.GEMINI_CLI_API_ERROR_STATUS_CODE,value:JSON.stringify(e.status_code)},{gemini_cli_key:ie.GEMINI_CLI_API_ERROR_DURATION_MS,value:JSON.stringify(e.duration_ms)}];this.enqueueLogEvent(this.createLogEvent(Ct.API_ERROR,r)),this.flushIfNeeded()}logChatCompressionEvent(e){let r=[{gemini_cli_key:ie.GEMINI_CLI_COMPRESSION_TOKENS_BEFORE,value:`${e.tokens_before}`},{gemini_cli_key:ie.GEMINI_CLI_COMPRESSION_TOKENS_AFTER,value:`${e.tokens_after}`}];this.enqueueLogEvent(this.createLogEvent(Ct.CHAT_COMPRESSION,r))}logFlashFallbackEvent(){this.enqueueLogEvent(this.createLogEvent(Ct.FLASH_FALLBACK,[])),this.flushToClearcut().catch(e=>{B.debug("Error flushing to Clearcut:",e)})}logRipgrepFallbackEvent(){this.enqueueLogEvent(this.createLogEvent(Ct.RIPGREP_FALLBACK,[])),this.flushToClearcut().catch(e=>{B.debug("Error flushing to Clearcut:",e)})}logLoopDetectedEvent(e){let r=[{gemini_cli_key:ie.GEMINI_CLI_LOOP_DETECTED_TYPE,value:JSON.stringify(e.loop_type)}];e.confirmed_by_model&&r.push({gemini_cli_key:ie.GEMINI_CLI_LOOP_DETECTED_CONFIRMED_BY_MODEL,value:e.confirmed_by_model}),this.enqueueLogEvent(this.createLogEvent(Ct.LOOP_DETECTED,r)),this.flushIfNeeded()}logLoopDetectionDisabledEvent(){let e=[];this.enqueueLogEvent(this.createLogEvent(Ct.LOOP_DETECTION_DISABLED,e)),this.flushIfNeeded()}logNextSpeakerCheck(e){let r=[{gemini_cli_key:ie.GEMINI_CLI_RESPONSE_FINISH_REASON,value:JSON.stringify(e.finish_reason)},{gemini_cli_key:ie.GEMINI_CLI_NEXT_SPEAKER_CHECK_RESULT,value:JSON.stringify(e.result)}];this.enqueueLogEvent(this.createLogEvent(Ct.NEXT_SPEAKER_CHECK,r)),this.flushIfNeeded()}logSlashCommandEvent(e){let r=[{gemini_cli_key:ie.GEMINI_CLI_SLASH_COMMAND_NAME,value:JSON.stringify(e.command)}];e.subcommand&&r.push({gemini_cli_key:ie.GEMINI_CLI_SLASH_COMMAND_SUBCOMMAND,value:JSON.stringify(e.subcommand)}),e.status&&r.push({gemini_cli_key:ie.GEMINI_CLI_SLASH_COMMAND_STATUS,value:JSON.stringify(e.status)}),e.extension_id&&r.push({gemini_cli_key:ie.GEMINI_CLI_EXTENSION_ID,value:e.extension_id}),this.enqueueLogEvent(this.createLogEvent(Ct.SLASH_COMMAND,r)),this.flushIfNeeded()}logRewindEvent(e){let r=[{gemini_cli_key:ie.GEMINI_CLI_REWIND_OUTCOME,value:e.outcome}];this.enqueueLogEvent(this.createLogEvent(Ct.REWIND,r)),this.flushIfNeeded()}logMalformedJsonResponseEvent(e){let r=[{gemini_cli_key:ie.GEMINI_CLI_MALFORMED_JSON_RESPONSE_MODEL,value:JSON.stringify(e.model)}];this.enqueueLogEvent(this.createLogEvent(Ct.MALFORMED_JSON_RESPONSE,r)),this.flushIfNeeded()}logIdeConnectionEvent(e){let r=[{gemini_cli_key:ie.GEMINI_CLI_IDE_CONNECTION_TYPE,value:JSON.stringify(e.connection_type)}];this.enqueueLogEventAfterExperimentsLoadAsync(this.createLogEvent(Ct.START_SESSION,r)).then(()=>{this.flushToClearcut().catch(n=>{B.debug("Error flushing to Clearcut:",n)})})}logConversationFinishedEvent(e){let r=[{gemini_cli_key:ie.GEMINI_CLI_SESSION_ID,value:this.config?.getSessionId()??""},{gemini_cli_key:ie.GEMINI_CLI_CONVERSATION_TURN_COUNT,value:JSON.stringify(e.turnCount)},{gemini_cli_key:ie.GEMINI_CLI_APPROVAL_MODE,value:e.approvalMode}];this.enqueueLogEvent(this.createLogEvent(Ct.CONVERSATION_FINISHED,r)),this.flushIfNeeded()}logEndSessionEvent(){this.enqueueLogEvent(this.createLogEvent(Ct.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:ie.GEMINI_CLI_INVALID_CHUNK_ERROR_MESSAGE,value:e.error_message}),this.enqueueLogEvent(this.createLogEvent(Ct.INVALID_CHUNK,r)),this.flushIfNeeded()}logContentRetryEvent(e){let r=[{gemini_cli_key:ie.GEMINI_CLI_CONTENT_RETRY_ATTEMPT_NUMBER,value:String(e.attempt_number)},{gemini_cli_key:ie.GEMINI_CLI_CONTENT_RETRY_ERROR_TYPE,value:e.error_type},{gemini_cli_key:ie.GEMINI_CLI_CONTENT_RETRY_DELAY_MS,value:String(e.retry_delay_ms)},{gemini_cli_key:ie.GEMINI_CLI_API_REQUEST_MODEL,value:e.model}];this.enqueueLogEvent(this.createLogEvent(Ct.CONTENT_RETRY,r)),this.flushIfNeeded()}logContentRetryFailureEvent(e){let r=[{gemini_cli_key:ie.GEMINI_CLI_CONTENT_RETRY_FAILURE_TOTAL_ATTEMPTS,value:String(e.total_attempts)},{gemini_cli_key:ie.GEMINI_CLI_CONTENT_RETRY_FAILURE_FINAL_ERROR_TYPE,value:e.final_error_type},{gemini_cli_key:ie.GEMINI_CLI_API_REQUEST_MODEL,value:e.model}];e.total_duration_ms&&r.push({gemini_cli_key:ie.GEMINI_CLI_CONTENT_RETRY_FAILURE_TOTAL_DURATION_MS,value:String(e.total_duration_ms)}),this.enqueueLogEvent(this.createLogEvent(Ct.CONTENT_RETRY_FAILURE,r)),this.flushIfNeeded()}logNetworkRetryAttemptEvent(e){let r=[{gemini_cli_key:ie.GEMINI_CLI_NETWORK_RETRY_ATTEMPT_NUMBER,value:String(e.attempt)},{gemini_cli_key:ie.GEMINI_CLI_NETWORK_RETRY_DELAY_MS,value:String(e.delay_ms)},{gemini_cli_key:ie.GEMINI_CLI_NETWORK_RETRY_ERROR_TYPE,value:e.error_type},{gemini_cli_key:ie.GEMINI_CLI_API_REQUEST_MODEL,value:e.model}];this.enqueueLogEvent(this.createLogEvent(Ct.RETRY_ATTEMPT,r)),this.flushIfNeeded()}async logExtensionInstallEvent(e){let r=[{gemini_cli_key:ie.GEMINI_CLI_EXTENSION_NAME,value:e.hashed_extension_name},{gemini_cli_key:ie.GEMINI_CLI_EXTENSION_ID,value:e.extension_id},{gemini_cli_key:ie.GEMINI_CLI_EXTENSION_VERSION,value:e.extension_version},{gemini_cli_key:ie.GEMINI_CLI_EXTENSION_SOURCE,value:e.extension_source},{gemini_cli_key:ie.GEMINI_CLI_EXTENSION_INSTALL_STATUS,value:e.status}];this.enqueueLogEvent(this.createBasicLogEvent(Ct.EXTENSION_INSTALL,r)),await this.flushToClearcut().catch(n=>{B.debug("Error flushing to Clearcut:",n)})}async logExtensionUninstallEvent(e){let r=[{gemini_cli_key:ie.GEMINI_CLI_EXTENSION_NAME,value:e.hashed_extension_name},{gemini_cli_key:ie.GEMINI_CLI_EXTENSION_ID,value:e.extension_id},{gemini_cli_key:ie.GEMINI_CLI_EXTENSION_UNINSTALL_STATUS,value:e.status}];this.enqueueLogEvent(this.createBasicLogEvent(Ct.EXTENSION_UNINSTALL,r)),await this.flushToClearcut().catch(n=>{B.debug("Error flushing to Clearcut:",n)})}async logExtensionUpdateEvent(e){let r=[{gemini_cli_key:ie.GEMINI_CLI_EXTENSION_NAME,value:e.hashed_extension_name},{gemini_cli_key:ie.GEMINI_CLI_EXTENSION_ID,value:e.extension_id},{gemini_cli_key:ie.GEMINI_CLI_EXTENSION_VERSION,value:e.extension_version},{gemini_cli_key:ie.GEMINI_CLI_EXTENSION_PREVIOUS_VERSION,value:e.extension_previous_version},{gemini_cli_key:ie.GEMINI_CLI_EXTENSION_SOURCE,value:e.extension_source},{gemini_cli_key:ie.GEMINI_CLI_EXTENSION_UPDATE_STATUS,value:e.status}];this.enqueueLogEvent(this.createBasicLogEvent(Ct.EXTENSION_UPDATE,r)),await this.flushToClearcut().catch(n=>{B.debug("Error flushing to Clearcut:",n)})}logToolOutputTruncatedEvent(e){let r=[{gemini_cli_key:ie.GEMINI_CLI_TOOL_CALL_NAME,value:JSON.stringify(e.tool_name)},{gemini_cli_key:ie.GEMINI_CLI_TOOL_OUTPUT_TRUNCATED_ORIGINAL_LENGTH,value:JSON.stringify(e.original_content_length)},{gemini_cli_key:ie.GEMINI_CLI_TOOL_OUTPUT_TRUNCATED_TRUNCATED_LENGTH,value:JSON.stringify(e.truncated_content_length)},{gemini_cli_key:ie.GEMINI_CLI_TOOL_OUTPUT_TRUNCATED_THRESHOLD,value:JSON.stringify(e.threshold)}],n=this.createLogEvent(Ct.TOOL_OUTPUT_TRUNCATED,r);this.enqueueLogEvent(n),this.flushIfNeeded()}logToolOutputMaskingEvent(e){let r=[{gemini_cli_key:ie.GEMINI_CLI_TOOL_OUTPUT_MASKING_TOKENS_BEFORE,value:e.tokens_before.toString()},{gemini_cli_key:ie.GEMINI_CLI_TOOL_OUTPUT_MASKING_TOKENS_AFTER,value:e.tokens_after.toString()},{gemini_cli_key:ie.GEMINI_CLI_TOOL_OUTPUT_MASKING_MASKED_COUNT,value:e.masked_count.toString()},{gemini_cli_key:ie.GEMINI_CLI_TOOL_OUTPUT_MASKING_TOTAL_PRUNABLE_TOKENS,value:e.total_prunable_tokens.toString()}];this.enqueueLogEvent(this.createLogEvent(Ct.TOOL_OUTPUT_MASKING,r)),this.flushIfNeeded()}logModelRoutingEvent(e){let r=[{gemini_cli_key:ie.GEMINI_CLI_ROUTING_DECISION,value:e.decision_model},{gemini_cli_key:ie.GEMINI_CLI_ROUTING_DECISION_SOURCE,value:e.decision_source},{gemini_cli_key:ie.GEMINI_CLI_ROUTING_LATENCY_MS,value:e.routing_latency_ms.toString()},{gemini_cli_key:ie.GEMINI_CLI_ROUTING_FAILURE,value:e.failed.toString()}];e.error_message&&r.push({gemini_cli_key:ie.GEMINI_CLI_ROUTING_FAILURE_REASON,value:e.error_message}),e.reasoning&&this.config?.getTelemetryLogPromptsEnabled()&&r.push({gemini_cli_key:ie.GEMINI_CLI_ROUTING_REASONING,value:e.reasoning}),e.enable_numerical_routing!==void 0&&r.push({gemini_cli_key:ie.GEMINI_CLI_ROUTING_NUMERICAL_ENABLED,value:e.enable_numerical_routing.toString()}),e.classifier_threshold&&r.push({gemini_cli_key:ie.GEMINI_CLI_ROUTING_CLASSIFIER_THRESHOLD,value:e.classifier_threshold}),this.enqueueLogEvent(this.createLogEvent(Ct.MODEL_ROUTING,r)),this.flushIfNeeded()}async logExtensionEnableEvent(e){let r=[{gemini_cli_key:ie.GEMINI_CLI_EXTENSION_NAME,value:e.hashed_extension_name},{gemini_cli_key:ie.GEMINI_CLI_EXTENSION_ID,value:e.extension_id},{gemini_cli_key:ie.GEMINI_CLI_EXTENSION_ENABLE_SETTING_SCOPE,value:e.setting_scope}];this.enqueueLogEvent(this.createBasicLogEvent(Ct.EXTENSION_ENABLE,r)),await this.flushToClearcut().catch(n=>{B.debug("Error flushing to Clearcut:",n)})}logModelSlashCommandEvent(e){let r=[{gemini_cli_key:ie.GEMINI_CLI_MODEL_SLASH_COMMAND,value:e.model_name}];this.enqueueLogEvent(this.createLogEvent(Ct.MODEL_SLASH_COMMAND,r)),this.flushIfNeeded()}async logExtensionDisableEvent(e){let r=[{gemini_cli_key:ie.GEMINI_CLI_EXTENSION_NAME,value:e.hashed_extension_name},{gemini_cli_key:ie.GEMINI_CLI_EXTENSION_ID,value:e.extension_id},{gemini_cli_key:ie.GEMINI_CLI_EXTENSION_DISABLE_SETTING_SCOPE,value:e.setting_scope}];this.enqueueLogEvent(this.createBasicLogEvent(Ct.EXTENSION_DISABLE,r)),await this.flushToClearcut().catch(n=>{B.debug("Error flushing to Clearcut:",n)})}logEditStrategyEvent(e){let r=[{gemini_cli_key:ie.GEMINI_CLI_EDIT_STRATEGY,value:e.strategy}];this.enqueueLogEvent(this.createLogEvent(Ct.EDIT_STRATEGY,r)),this.flushIfNeeded()}logEditCorrectionEvent(e){let r=[{gemini_cli_key:ie.GEMINI_CLI_EDIT_CORRECTION,value:e.correction}];this.enqueueLogEvent(this.createLogEvent(Ct.EDIT_CORRECTION,r)),this.flushIfNeeded()}logAgentStartEvent(e){let r=[{gemini_cli_key:ie.GEMINI_CLI_AGENT_ID,value:e.agent_id},{gemini_cli_key:ie.GEMINI_CLI_AGENT_NAME,value:e.agent_name}];this.enqueueLogEvent(this.createLogEvent(Ct.AGENT_START,r)),this.flushIfNeeded()}logAgentFinishEvent(e){let r=[{gemini_cli_key:ie.GEMINI_CLI_AGENT_ID,value:e.agent_id},{gemini_cli_key:ie.GEMINI_CLI_AGENT_NAME,value:e.agent_name},{gemini_cli_key:ie.GEMINI_CLI_AGENT_DURATION_MS,value:e.duration_ms.toString()},{gemini_cli_key:ie.GEMINI_CLI_AGENT_TURN_COUNT,value:e.turn_count.toString()},{gemini_cli_key:ie.GEMINI_CLI_AGENT_TERMINATE_REASON,value:e.terminate_reason}];this.enqueueLogEvent(this.createLogEvent(Ct.AGENT_FINISH,r)),this.flushIfNeeded()}logRecoveryAttemptEvent(e){let r=[{gemini_cli_key:ie.GEMINI_CLI_AGENT_ID,value:e.agent_id},{gemini_cli_key:ie.GEMINI_CLI_AGENT_NAME,value:e.agent_name},{gemini_cli_key:ie.GEMINI_CLI_AGENT_RECOVERY_REASON,value:e.reason},{gemini_cli_key:ie.GEMINI_CLI_AGENT_RECOVERY_DURATION_MS,value:e.duration_ms.toString()},{gemini_cli_key:ie.GEMINI_CLI_AGENT_RECOVERY_SUCCESS,value:e.success.toString()},{gemini_cli_key:ie.GEMINI_CLI_AGENT_TURN_COUNT,value:e.turn_count.toString()}];this.enqueueLogEvent(this.createLogEvent(Ct.RECOVERY_ATTEMPT,r)),this.flushIfNeeded()}logWebFetchFallbackAttemptEvent(e){let r=[{gemini_cli_key:ie.GEMINI_CLI_WEB_FETCH_FALLBACK_REASON,value:e.reason}];this.enqueueLogEvent(this.createLogEvent(Ct.WEB_FETCH_FALLBACK_ATTEMPT,r)),this.flushIfNeeded()}logLlmLoopCheckEvent(e){let r=[{gemini_cli_key:ie.GEMINI_CLI_PROMPT_ID,value:e.prompt_id},{gemini_cli_key:ie.GEMINI_CLI_LLM_LOOP_CHECK_FLASH_CONFIDENCE,value:e.flash_confidence.toString()},{gemini_cli_key:ie.GEMINI_CLI_LLM_LOOP_CHECK_MAIN_MODEL,value:e.main_model},{gemini_cli_key:ie.GEMINI_CLI_LLM_LOOP_CHECK_MAIN_MODEL_CONFIDENCE,value:e.main_model_confidence.toString()}];this.enqueueLogEvent(this.createLogEvent(Ct.LLM_LOOP_CHECK,r)),this.flushIfNeeded()}logHookCallEvent(e){let r=[{gemini_cli_key:ie.GEMINI_CLI_HOOK_EVENT_NAME,value:e.hook_event_name},{gemini_cli_key:ie.GEMINI_CLI_HOOK_DURATION_MS,value:e.duration_ms.toString()},{gemini_cli_key:ie.GEMINI_CLI_HOOK_SUCCESS,value:e.success.toString()}];e.exit_code!==void 0&&r.push({gemini_cli_key:ie.GEMINI_CLI_HOOK_EXIT_CODE,value:e.exit_code.toString()}),this.enqueueLogEvent(this.createLogEvent(Ct.HOOK_CALL,r)),this.flushIfNeeded()}logApprovalModeSwitchEvent(e){let r=[{gemini_cli_key:ie.GEMINI_CLI_ACTIVE_APPROVAL_MODE,value:e.from_mode},{gemini_cli_key:ie.GEMINI_CLI_APPROVAL_MODE_TO,value:e.to_mode}];this.enqueueLogEvent(this.createLogEvent(Ct.APPROVAL_MODE_SWITCH,r)),this.flushIfNeeded()}logApprovalModeDurationEvent(e){let r=[{gemini_cli_key:ie.GEMINI_CLI_ACTIVE_APPROVAL_MODE,value:e.mode},{gemini_cli_key:ie.GEMINI_CLI_APPROVAL_MODE_DURATION_MS,value:e.duration_ms.toString()}];this.enqueueLogEvent(this.createLogEvent(Ct.APPROVAL_MODE_DURATION,r)),this.flushIfNeeded()}logPlanExecutionEvent(e){let r=[{gemini_cli_key:ie.GEMINI_CLI_APPROVAL_MODE,value:e.approval_mode}];this.enqueueLogEvent(this.createLogEvent(Ct.PLAN_EXECUTION,r)),this.flushIfNeeded()}logKeychainAvailabilityEvent(e){let r=[{gemini_cli_key:ie.GEMINI_CLI_KEYCHAIN_AVAILABLE,value:JSON.stringify(e.available)}];this.enqueueLogEvent(this.createLogEvent(Ct.KEYCHAIN_AVAILABILITY,r)),this.flushIfNeeded()}logTokenStorageInitializationEvent(e){let r=[{gemini_cli_key:ie.GEMINI_CLI_TOKEN_STORAGE_TYPE,value:e.type},{gemini_cli_key:ie.GEMINI_CLI_TOKEN_STORAGE_FORCED,value:JSON.stringify(e.forced)}];this.enqueueLogEvent(this.createLogEvent(Ct.TOKEN_STORAGE_INITIALIZATION,r)),this.flushIfNeeded()}logOnboardingStartEvent(e){let r=[{gemini_cli_key:ie.GEMINI_CLI_ONBOARDING_START,value:"true"}];this.enqueueLogEvent(this.createLogEvent(Ct.ONBOARDING_START,r)),this.flushIfNeeded()}logOnboardingSuccessEvent(e){let r=[];e.userTier&&r.push({gemini_cli_key:ie.GEMINI_CLI_ONBOARDING_USER_TIER,value:e.userTier}),e.duration_ms!==void 0&&r.push({gemini_cli_key:ie.GEMINI_CLI_ONBOARDING_DURATION_MS,value:e.duration_ms.toString()}),this.enqueueLogEvent(this.createLogEvent(Ct.ONBOARDING_SUCCESS,r)),this.flushIfNeeded()}logStartupStatsEvent(e){let r=[{gemini_cli_key:ie.GEMINI_CLI_STARTUP_PHASES,value:JSON.stringify(e.phases)},{gemini_cli_key:ie.GEMINI_CLI_STARTUP_OS_PLATFORM,value:e.os_platform},{gemini_cli_key:ie.GEMINI_CLI_STARTUP_OS_RELEASE,value:e.os_release},{gemini_cli_key:ie.GEMINI_CLI_STARTUP_IS_DOCKER,value:JSON.stringify(e.is_docker)}];this.enqueueLogEvent(this.createLogEvent(Ct.STARTUP_STATS,r)),this.flushIfNeeded()}logCreditsUsedEvent(e){let r=[{gemini_cli_key:ie.GEMINI_CLI_BILLING_MODEL,value:JSON.stringify(e.model)},{gemini_cli_key:ie.GEMINI_CLI_BILLING_CREDITS_CONSUMED,value:JSON.stringify(e.credits_consumed)},{gemini_cli_key:ie.GEMINI_CLI_BILLING_CREDITS_REMAINING,value:JSON.stringify(e.credits_remaining)}];this.enqueueLogEvent(this.createLogEvent(Ct.CREDITS_USED,r)),this.flushIfNeeded()}logOverageOptionSelectedEvent(e){let r=[{gemini_cli_key:ie.GEMINI_CLI_BILLING_MODEL,value:JSON.stringify(e.model)},{gemini_cli_key:ie.GEMINI_CLI_BILLING_SELECTED_OPTION,value:JSON.stringify(e.selected_option)},{gemini_cli_key:ie.GEMINI_CLI_BILLING_CREDIT_BALANCE,value:JSON.stringify(e.credit_balance)}];this.enqueueLogEvent(this.createLogEvent(Ct.OVERAGE_OPTION_SELECTED,r)),this.flushIfNeeded()}logEmptyWalletMenuShownEvent(e){let r=[{gemini_cli_key:ie.GEMINI_CLI_BILLING_MODEL,value:JSON.stringify(e.model)}];this.enqueueLogEvent(this.createLogEvent(Ct.EMPTY_WALLET_MENU_SHOWN,r)),this.flushIfNeeded()}logCreditPurchaseClickEvent(e){let r=[{gemini_cli_key:ie.GEMINI_CLI_BILLING_MODEL,value:JSON.stringify(e.model)},{gemini_cli_key:ie.GEMINI_CLI_BILLING_PURCHASE_SOURCE,value:JSON.stringify(e.source)}];this.enqueueLogEvent(this.createLogEvent(Ct.CREDIT_PURCHASE_CLICK,r)),this.flushIfNeeded()}addDefaultFields(e,r){let n=[{gemini_cli_key:ie.GEMINI_CLI_SESSION_ID,value:this.config?.getSessionId()??""},{gemini_cli_key:ie.GEMINI_CLI_AUTH_TYPE,value:JSON.stringify(this.config?.getContentGeneratorConfig()?.authType)},{gemini_cli_key:ie.GEMINI_CLI_GOOGLE_ACCOUNTS_COUNT,value:`${r}`},{gemini_cli_key:ie.GEMINI_CLI_PROMPT_ID,value:this.promptId},{gemini_cli_key:ie.GEMINI_CLI_NODE_VERSION,value:process.versions.node},{gemini_cli_key:ie.GEMINI_CLI_USER_SETTINGS,value:this.getConfigJson()},{gemini_cli_key:ie.GEMINI_CLI_INTERACTIVE,value:this.config?.isInteractive().toString()??"false"},{gemini_cli_key:ie.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:ie.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 iOt.HttpsProxyAgent(e);throw new Error("Unsupported proxy type")}}getConfigJson(){return eXe(this.config)}shutdown(){this.logEndSessionEvent()}requeueFailedEvents(e){let r=e.slice(-LZ);e.length>LZ&&this.config?.getDebugMode()&&B.warn(`ClearcutLogger: Dropping ${e.length-LZ} events due to retry queue limit. Total events: ${e.length}, keeping: ${LZ}`);let n=DZ-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>DZ;)this.events.pop();this.config?.getDebugMode()&&B.debug(`ClearcutLogger: Re-queued ${o} events for retry (queue size: ${this.events.size})`)}};var IT=Fe(kt(),1),aOt=Fe(df(),1);import*as sOt from"node:fs";var N4=class{writeStream;constructor(e){this.writeStream=sOt.createWriteStream(e,{flags:"a"})}serialize(e){return Mr(e,2)+`
|
|
1062
1062
|
`}shutdown(){return new Promise(e=>{this.writeStream.end(e)})}},MZ=class extends N4{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 N4{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})})}},UZ=class extends N4{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 aOt.AggregationTemporality.CUMULATIVE}async forceFlush(){return Promise.resolve()}};var bJi=Fe(hs(),1),fMt=Fe(KOt(),1),hMt=Fe(HPt(),1),gMt=Fe(pMt(),1),kR=Fe(kt(),1);var i5=class extends fMt.TraceExporter{constructor(e,r){super({projectId:e,credentials:r,resourceFilter:/^gcp\./})}},o5=class extends hMt.MetricExporter{constructor(e,r){super({projectId:e,credentials:r,prefix:"custom.googleapis.com/gemini_cli"})}},s5=class{logging;log;pendingWrites=[];constructor(e,r){this.logging=new gMt.Logging({projectId:e,credentials:r}),this.log=this.logging.log("gemini_cli")}export(e,r){try{let n=e.map(s=>this.log.entry({severity:this.mapSeverityToCloudLogging(s.severityNumber),timestamp:new Date((0,kR.hrTimeToMilliseconds)(s.hrTime)),resource:{type:"global",labels:{project_id:this.logging.projectId}}},{...s.attributes,...s.resource?.attributes,message:s.body})),o=this.log.write(n).then(()=>{r({code:kR.ExportResultCode.SUCCESS})}).catch(s=>{r({code:kR.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:kR.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 a5(t){if(t!==void 0)return t==="true"||t==="1"}function mMt(t){if(t!==void 0){if(t===Jg.LOCAL||t==="local")return Jg.LOCAL;if(t===Jg.GCP||t==="gcp")return Jg.GCP}}async function OSn(t){let e=t.argv??{},r=t.env??{},n=t.settings??{},o=e.telemetry??a5(r.GEMINI_TELEMETRY_ENABLED)??n.enabled,s=e.telemetryTarget??r.GEMINI_TELEMETRY_TARGET??n.target,c=mMt(s);if(s!==void 0&&c===void 0)throw new dme(`Invalid telemetry target: ${String(s)}. Valid values are: local, gcp`);let u=e.telemetryOtlpEndpoint??r.GEMINI_TELEMETRY_OTLP_ENDPOINT??r.OTEL_EXPORTER_OTLP_ENDPOINT??n.otlpEndpoint,d=e.telemetryOtlpProtocol??r.GEMINI_TELEMETRY_OTLP_PROTOCOL??n.otlpProtocol,l=["grpc","http"].find(g=>g===d);if(d!==void 0&&l===void 0)throw new dme(`Invalid telemetry OTLP protocol: ${String(d)}. Valid values are: grpc, http`);let a=e.telemetryLogPrompts??a5(r.GEMINI_TELEMETRY_LOG_PROMPTS)??n.logPrompts,p=e.telemetryOutfile??r.GEMINI_TELEMETRY_OUTFILE??n.outfile,f=a5(r.GEMINI_TELEMETRY_USE_COLLECTOR)??n.useCollector;return{enabled:o,target:c,otlpEndpoint:u,otlpProtocol:l,logPrompts:a,outfile:p,useCollector:f,useCliAuth:a5(r.GEMINI_TELEMETRY_USE_CLI_AUTH)??n.useCliAuth}}var Pke=Fe(Fh(),1);function Nke(t,e){B.debug("Conseca Policy Generation Event:",e);let r=Pt.getInstance(t);if(r){let s=[{gemini_cli_key:ie.CONSECA_USER_PROMPT,value:Mr(e.user_prompt)},{gemini_cli_key:ie.CONSECA_TRUSTED_CONTENT,value:Mr(e.trusted_content)},{gemini_cli_key:ie.CONSECA_GENERATED_POLICY,value:Mr(e.policy)}];e.error&&s.push({gemini_cli_key:ie.CONSECA_ERROR,value:e.error}),r.enqueueLogEvent(r.createLogEvent(Ct.CONSECA_POLICY_GENERATION,s))}if(!Ire())return;let n=Pke.logs.getLogger(Tt),o={body:e.toLogBody(),attributes:e.toOpenTelemetryAttributes(t)};n.emit(o)}function kke(t,e){B.debug("Conseca Verdict Event:",e);let r=Pt.getInstance(t);if(r){let s=[{gemini_cli_key:ie.CONSECA_USER_PROMPT,value:Mr(e.user_prompt)},{gemini_cli_key:ie.CONSECA_GENERATED_POLICY,value:Mr(e.policy)},{gemini_cli_key:ie.GEMINI_CLI_TOOL_CALL_NAME,value:Mr(e.tool_call)},{gemini_cli_key:ie.CONSECA_VERDICT_RESULT,value:Mr(e.verdict)},{gemini_cli_key:ie.CONSECA_VERDICT_RATIONALE,value:e.verdict_rationale}];e.error&&s.push({gemini_cli_key:ie.CONSECA_ERROR,value:e.error}),r.enqueueLogEvent(r.createLogEvent(Ct.CONSECA_VERDICT,s))}if(!Ire())return;let n=Pke.logs.getLogger(Tt),o={body:e.toLogBody(),attributes:e.toOpenTelemetryAttributes(t)};n.emit(o)}qe();hl();import{EventEmitter as NSn}from"node:events";var Dke="**",yMt="**";function Rre(t){let e=t.indexOf(Dke);if(e===-1)return{subject:"",description:t.trim()};let r=t.indexOf(yMt,e+Dke.length);if(r===-1)return{subject:"",description:t.trim()};let n=t.substring(e+Dke.length,r).trim(),o=(t.substring(0,e)+t.substring(r+yMt.length)).trim();return{subject:n,description:o}}import DR from"node:path";import Rb from"node:fs";import*as cy from"node:fs/promises";import Ib from"node:path";var ISn="logs",RSn="tool-outputs";function AMt(t){if(!t||t==="."||t==="..")throw new Error(`Invalid sessionId: ${t}`);let e=Yu(t);if(!e)throw new Error(`Invalid sessionId after sanitization: ${t}`);return e}async function Lke(t,e){try{let r=AMt(t),n=Ib.join(e,ISn),o=Ib.join(n,`session-${r}.jsonl`);await cy.unlink(o).catch(d=>{if(d.code!=="ENOENT")throw d});let s=Ib.join(e,RSn),c=Ib.join(s,`session-${r}`);await cy.rm(c,{recursive:!0,force:!0}).catch(d=>{if(d.code!=="ENOENT")throw d});let u=Ib.join(e,r);await cy.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 _Mt(t,e,r){let n=AMt(t),o=Ib.join(e,n);if(!o.startsWith(e+Ib.sep))throw new Error(`Dangerous subagent directory path: ${o}`);try{let s=await cy.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")){let u=Ib.basename(c.name,".json");await Lke(u,r)}await cy.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 cy.rm(o,{recursive:!0,force:!0}).catch(()=>{})}}import{randomUUID as PSn}from"node:crypto";var l5="session-",EMt="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.",Pre=class{conversationFile=null;cachedLastConvData=null;cachedConversation=null;sessionId;projectHash;kind;queuedThoughts=[];queuedTokens=null;context;constructor(e){this.context=e,this.sessionId=e.promptId,this.projectHash=NKe(e.config.getProjectRoot())}initialize(e,r){try{if(this.kind=r,e)this.conversationFile=e.filePath,this.sessionId=e.conversation.sessionId,this.kind=e.conversation.kind,this.updateConversation(n=>{n.sessionId=this.sessionId}),this.cachedLastConvData=null,this.cachedConversation=null;else{this.sessionId=this.context.promptId;let n=DR.join(this.context.config.storage.getProjectTempDir(),"chats");if(this.kind==="subagent"&&this.context.parentSessionId){let d=Yu(this.context.parentSessionId);if(!d)throw new Error(`Invalid parentSessionId after sanitization: ${this.context.parentSessionId}`);n=DR.join(n,d)}Rb.mkdirSync(n,{recursive:!0});let o=new Date().toISOString().slice(0,16).replace(/:/g,"-"),s=Yu(this.sessionId);if(!s)throw new Error(`Invalid sessionId after sanitization: ${this.sessionId}`);let c;this.kind==="subagent"?c=`${s}.json`:c=`${l5}${o}-${s.slice(0,8)}.json`,this.conversationFile=DR.join(n,c);let u=this.kind==="subagent"?[...this.context.config.getWorkspaceContext()?.getDirectories()??[]]:void 0;this.writeConversation({sessionId:this.sessionId,projectHash:this.projectHash,startTime:new Date().toISOString(),lastUpdated:new Date().toISOString(),messages:[],directories:u,kind:this.kind})}this.queuedThoughts=[],this.queuedTokens=null}catch(n){if(n instanceof Error&&"code"in n&&n.code==="ENOSPC"){this.conversationFile=null,B.warn(EMt);return}throw B.error("Error initializing chat recording service:",n),n}}getLastMessage(e){return e.messages.at(-1)}newMessage(e,r,n){return{id:PSn(),timestamp:new Date().toISOString(),type:e,content:r,displayContent:n}}recordMessage(e){if(this.conversationFile)try{this.updateConversation(r=>{let n=this.newMessage(e.type,e.content,e.displayContent);n.type==="gemini"?(r.messages.push({...n,thoughts:this.queuedThoughts,tokens:this.queuedTokens,model:e.model}),this.queuedThoughts=[],this.queuedTokens=null):r.messages.push(n)})}catch(r){throw B.error("Error saving message to chat history.",r),r}}recordThought(e){if(this.conversationFile)try{this.queuedThoughts.push({...e,timestamp:new Date().toISOString()})}catch(r){throw B.error("Error saving thought to chat history.",r),r}}recordMessageTokens(e){if(this.conversationFile)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.readConversation(),o=this.getLastMessage(n);o&&o.type==="gemini"&&!o.tokens?(o.tokens=r,this.queuedTokens=null,this.writeConversation(n)):this.queuedTokens=r}catch(r){throw B.error("Error updating message tokens in chat history.",r),r}}recordToolCalls(e,r){if(!this.conversationFile)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{this.updateConversation(s=>{let c=this.getLastMessage(s);if(!c||c.type!=="gemini"||this.queuedThoughts.length>0){let u={...this.newMessage("gemini",""),type:"gemini",toolCalls:o,thoughts:this.queuedThoughts,model:e};this.queuedThoughts.length>0&&(u.thoughts=this.queuedThoughts,this.queuedThoughts=[]),this.queuedTokens&&(u.tokens=this.queuedTokens,this.queuedTokens=null),s.messages.push(u)}else{c.toolCalls||(c.toolCalls=[]),c.toolCalls=c.toolCalls.map(u=>{let d=r.find(l=>l.id===u.id);return d?{...u,...d}:u});for(let u of o)c.toolCalls.find(l=>l.id===u.id)||c.toolCalls.push(u)}})}catch(s){throw B.error("Error adding tool call to message in chat history.",s),s}}readConversation(){if(this.cachedConversation)return this.cachedConversation;try{return this.cachedLastConvData=Rb.readFileSync(this.conversationFile,"utf8"),this.cachedConversation=JSON.parse(this.cachedLastConvData),this.cachedConversation||(this.cachedConversation={sessionId:this.sessionId,projectHash:this.projectHash,startTime:new Date().toISOString(),lastUpdated:new Date().toISOString(),messages:[],kind:this.kind}),this.cachedConversation}catch(e){if(e.code!=="ENOENT")throw B.error("Error reading conversation file.",e),e;return this.cachedConversation={sessionId:this.sessionId,projectHash:this.projectHash,startTime:new Date().toISOString(),lastUpdated:new Date().toISOString(),messages:[],kind:this.kind},this.cachedConversation}}writeConversation(e,{allowEmpty:r=!1}={}){try{if(!this.conversationFile||(this.cachedConversation=e,e.messages.length===0&&!r))return;let n=JSON.stringify(e,null,2);if(this.cachedLastConvData===n)return;e.lastUpdated=new Date().toISOString();let o=JSON.stringify(e,null,2);this.cachedLastConvData=o,Rb.mkdirSync(DR.dirname(this.conversationFile),{recursive:!0}),Rb.writeFileSync(this.conversationFile,o)}catch(n){if(n instanceof Error&&"code"in n&&n.code==="ENOSPC"){this.conversationFile=null,this.cachedConversation=null,B.warn(EMt);return}throw B.error("Error writing conversation file.",n),n}}updateConversation(e){let r=this.readConversation();e(r),this.writeConversation(r)}saveSummary(e){if(this.conversationFile)try{this.updateConversation(r=>{r.summary=e})}catch(r){B.error("Error saving summary to chat history.",r)}}recordDirectories(e){if(this.conversationFile)try{this.updateConversation(r=>{r.directories=[...e]})}catch(r){B.error("Error saving directories to chat history.",r)}}getConversation(){if(!this.conversationFile)return null;try{return this.readConversation()}catch(e){return B.error("Error reading conversation for summary.",e),null}}getConversationFilePath(){return this.conversationFile}async deleteSession(e){try{let r=this.context.config.storage.getProjectTempDir(),n=DR.join(r,"chats"),o=this.deriveShortId(e);if(!await Rb.promises.stat(n).catch(()=>null))return;let s=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(l5)){let o=e.replace(".json","").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}getMatchingSessionFiles(e,r){return Rb.readdirSync(e).filter(o=>o.startsWith(l5)&&o.endsWith(`-${r}.json`))}async deleteSessionAndArtifacts(e,r,n){let o=DR.join(e,r);try{let s=await Rb.promises.readFile(o,"utf8"),c=JSON.parse(s),u;if(c&&typeof c=="object"&&"sessionId"in c){let d=c.sessionId;typeof d=="string"&&(u=d)}await Rb.promises.unlink(o),u&&(await Lke(u,n),await _Mt(u,e,n))}catch(s){B.error(`Error deleting associated file ${r}:`,s)}}rewindTo(e){if(!this.conversationFile)return null;let r=this.readConversation(),n=r.messages.findIndex(o=>o.id===e);return n===-1?(B.error("Message to rewind to not found in conversation history"),r):(r.messages=r.messages.slice(0,n),this.writeConversation(r,{allowEmpty:!0}),r)}updateMessagesFromHistory(e){if(this.conversationFile)try{this.updateConversation(r=>{let n=new Map;for(let o of e)if(o.role==="user"&&o.parts){let s=o.parts.map(u=>u.functionResponse?.id).filter(u=>!!u);if(s.length===0)continue;let c=s[0];for(let u of o.parts)u.functionResponse?.id&&(c=u.functionResponse.id),n.has(c)||n.set(c,[]),n.get(c).push(u)}for(let o of r.messages)if(o.type==="gemini"&&o.toolCalls)for(let s of o.toolCalls){let c=n.get(s.id);c!==void 0&&(s.result=c)}})}catch(r){throw B.error("Error updating conversation history from memory.",r),r}}};var bMt=()=>({totalRequests:0,totalErrors:0,totalLatencyMs:0,tokens:{input:0,prompt:0,candidates:0,total:0,cached:0,thoughts:0,tool:0}}),kSn=()=>({api:{totalRequests:0,totalErrors:0,totalLatencyMs:0},tokens:{input:0,prompt:0,candidates:0,total:0,cached:0,thoughts:0,tool:0},roles:{}}),vMt=()=>({models:{},tools:{totalCalls:0,totalSuccess:0,totalFail:0,totalDurationMs:0,totalDecisions:{[to.ACCEPT]:0,[to.REJECT]:0,[to.MODIFY]:0,[to.AUTO_ACCEPT]:0},byName:{}},files:{totalLinesAdded:0,totalLinesRemoved:0}}),Mke=class extends NSn{#e=vMt();#t=0;addEvent(e){switch(e["event.name"]){case bL:this.processApiResponse(e);break;case EL:this.processApiError(e);break;case _L: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=vMt(),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:{[to.ACCEPT]:0,[to.REJECT]:0,[to.MODIFY]:0,[to.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]=kSn()),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]=bMt());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]=bMt());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:{[to.ACCEPT]:0,[to.REJECT]:0,[to.MODIFY]:0,[to.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))}},uy=new Mke;var DSn="gemini_cli.overage_menu_shown",SMt=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{...At(e),"event.name":DSn,"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.`}},LSn="gemini_cli.overage_option_selected",Nre=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{...At(e),"event.name":LSn,"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}.`}},MSn="gemini_cli.empty_wallet_menu_shown",kre=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{...At(e),"event.name":MSn,"event.timestamp":this["event.timestamp"],model:this.model}}toLogBody(){return`Empty wallet menu shown for model ${this.model}.`}},BSn="gemini_cli.credit_purchase_click",Dre=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{...At(e),"event.name":BSn,"event.timestamp":this["event.timestamp"],source:this.source,model:this.model}}toLogBody(){return`Credit purchase clicked from ${this.source} for model ${this.model}.`}},USn="gemini_cli.credits_used",LR=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{...At(e),"event.name":USn,"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.`}},FSn="gemini_cli.api_key_updated",TMt=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{...At(e),"event.name":FSn,"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 d5 from"node:v8";import MR from"node:process";var Pb=t=>t/1048576,wMt=t=>{let e=t/1073741824;return t<1048576?`${(t/1024).toFixed(1)} KB`:t<1073741824?`${Pb(t).toFixed(1)} MB`:`${e.toFixed(2)} GB`};var Lre=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}},Bke=new Lre;function jSn(){return Bke}function QSn(){Bke.recordActivity()}function Uke(){return Bke.isUserActive()}var c5=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 u5=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)}};var Mre=class t{intervalId=null;isRunning=!1;lastSnapshot=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 c5(5),this.rateLimiter=new u5(6e4)}start(e,r=1e4){!_2()||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(!Uke())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=MR.memoryUsage(),o=d5.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 _2()&&(A2(r,s.heapUsed,{memory_type:y_.HEAP_USED,component:e}),A2(r,s.heapTotal,{memory_type:y_.HEAP_TOTAL,component:e}),A2(r,s.external,{memory_type:y_.EXTERNAL,component:e}),A2(r,s.rss,{memory_type:y_.RSS,component:e})),this.lastSnapshot=s,s}takeSnapshotWithoutRecording(e,r){let n=MR.memoryUsage(),o=d5.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=MR.memoryUsage(),r=d5.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 d5.getHeapStatistics()}getHeapSpaceStatistics(){return d5.getHeapSpaceStatistics()}getProcessMetrics(){return{cpuUsage:MR.cpuUsage(),memoryUsage:MR.memoryUsage(),uptime:MR.uptime()}}recordComponentMemoryUsage(e,r,n){return this.takeSnapshot(n?`${r}_${n}`:r,e)}checkMemoryThreshold(e){let r=this.getCurrentMemoryUsage();return Pb(r.heapUsed)>e}getMemoryUsageSummary(){let e=this.getCurrentMemoryUsage();return{heapUsedMB:Math.round(Pb(e.heapUsed)*100)/100,heapTotalMB:Math.round(Pb(e.heapTotal)*100)/100,externalMB:Math.round(Pb(e.external)*100)/100,rssMB:Math.round(Pb(e.rss)*100)/100,heapSizeLimitMB:Math.round(Pb(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()}destroy(){this.stop(),this.rateLimiter.reset(),this.highWaterMarkTracker.resetAllHighWaterMarks()}},BR=null;function Fke(){return BR||(BR=new Mre),BR}function jke(){return BR}function qSn(t,e){return Fke().takeSnapshot(e,t)}function GSn(t,e=1e4){Fke().start(t,e)}function VSn(t){BR&&BR.stop(t)}var dy;(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"})(dy||(dy={}));var $Sn={enabled:!0,snapshotThrottleMs:1e3,maxEventBuffer:100,triggerActivities:[dy.USER_INPUT_START,dy.MESSAGE_ADDED,dy.TOOL_CALL_SCHEDULED,dy.STREAM_START]},Bre=class{listeners=new Set;eventBuffer=[];lastSnapshotTime=0;config;isActive=!1;memoryMonitoringListener=null;constructor(e=$Sn){this.config={...e}}start(e){!_2()||this.isActive||(this.isActive=!0,this.memoryMonitoringListener=r=>{this.handleMemoryMonitoringActivity(r,e)},this.addListener(this.memoryMonitoringListener),this.recordActivity(dy.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=jke();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}},UR=null;function CMt(t){return UR||(UR=new Bre(t)),UR}function HSn(){return UR}function zSn(t,e){CMt(e).start(t)}function WSn(){UR&&UR.stop()}qe();import{randomUUID as xMt}from"node:crypto";var Qke=xMt();function YSn(){return xMt()}var JSn="gemini-cli",KSn="v1";function qke(t,e=1e4){if(typeof t=="string")return nc(t,e,`...[TRUNCATED: original length ${t.length}]`);if(typeof t=="object"&&t!==null){let r=Mr(t);return nc(r,e,`...[TRUNCATED: original length ${r.length}]`)}if(typeof t=="number"||typeof t=="boolean")return t}function XSn(t){return typeof t=="object"&&t!==null&&Symbol.asyncIterator in t}async function xf(t,e){let{operation:r,logPrompts:n,...o}=t;return Lq.getTracer(JSn,KSn).startActiveSpan(r,o,async c=>{let u={name:r,attributes:{[Vnt]:r,[_V]:Tt,[EV]:Gnt,[Jnt]:Qke}},d=()=>{try{if(n!==!1){if(u.input!==void 0){let a=qke(u.input);a!==void 0&&c.setAttribute($nt,a)}if(u.output!==void 0){let a=qke(u.output);a!==void 0&&c.setAttribute(Hnt,a)}}for(let[a,p]of Object.entries(u.attributes)){let f=qke(p);f!==void 0&&c.setAttribute(a,f)}u.error?(c.setStatus({code:_3.ERROR,message:OMt(u.error)}),u.error instanceof Error&&c.recordException(u.error)):c.setStatus({code:_3.OK})}catch(a){Tn.error("Error setting span attributes in endSpan",a),c.setStatus({code:_3.ERROR,message:`Error in endSpan: ${OMt(a)}`})}finally{c.end()}},l=!1;try{let a=await e({metadata:u});if(XSn(a)){l=!0;let p=async function*(){try{yield*a}catch(f){throw u.error=f,f}finally{d()}}();return Object.assign(p,a)}return a}catch(a){throw u.error=a,a}finally{l||d()}})}function OMt(t){return t instanceof Error?t.message:typeof t=="string"?t:Mr(t)}import{performance as Kg}from"node:perf_hooks";import*as Nb from"node:os";import*as Gke from"node:fs";var Ure=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);Kg.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(Kg.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}Kg.mark(o,{detail:r}),Kg.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:Nb.platform(),os_arch:Nb.arch(),os_release:Nb.release(),is_docker:Gke.existsSync("/.dockerenv")},n=Kg.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),u_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((Kg.timeOrigin+c.startTime)*1e3),end_time_usec:Math.round((Kg.timeOrigin+c.startTime+c.duration)*1e3)})}o.length>0&&IMt(e,new qV(o,Nb.platform(),Nb.release(),Gke.existsSync("/.dockerenv")));for(let s of this.phases.keys()){let c=this.getStartMarkName(s),u=this.getEndMarkName(s);Kg.clearMarks(c),Kg.clearMarks(u),Kg.clearMeasures(s)}this.phases.clear()}},Vke=Ure.getInstance();var Jg;(function(t){t.GCP="gcp",t.LOCAL="local"})(Jg||(Jg={}));var $ke=Jg.LOCAL,Hke="http://localhost:4317";var eDe=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)}};Tn.setLogger(new eDe,AXe.INFO);var f5,Gre,Vre,Db=!1,tDe=!1,h5,jR,QR,rDe=[],p5;function Ire(){return Db}function Zt(t){Db?t():rDe.push(t)}async function lTn(){if(Db)for(;rDe.length>0;){let t=rDe.shift();if(t)try{await t()}catch(e){B.error("Error executing buffered telemetry event",e)}}}function cTn(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){Tn.error("Invalid OTLP endpoint URL provided:",r,n);return}}async function Fre(t,e){if(!t.getTelemetryEnabled())return;if(Db){if(e?.client_email&&p5&&e.client_email!==p5){let _=`Telemetry credentials have changed (from ${p5} 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(_)}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){tDe||(tDe=!0,h5=async _=>{t.getTelemetryEnabled()&&t.getTelemetryUseCliAuth()&&(B.log("Telemetry reinit with credentials."),await Fre(t,_))},a$.on("post_auth",h5)),B.log("CLI auth is requested but no credentials, deferring telemetry initialization.");return}let r=(0,UMt.resourceFromAttributes)({[wV.SERVICE_NAME]:Tt,[wV.SERVICE_VERSION]:process.version,"session.id":t.getSessionId()});jR||(jR=_=>{jMt(t,_)},Ee.on(Nr.TelemetryKeychainAvailability,jR)),QR||(QR=_=>{QMt(t,_)},Ee.on(Nr.TelemetryTokenStorageType,QR));let n=t.getTelemetryOtlpEndpoint(),o=t.getTelemetryOtlpProtocol(),s=t.getTelemetryTarget(),c=t.getTelemetryUseCollector(),u=cTn(n,o),d=t.getTelemetryOutfile(),l=!!u&&!d,a=process.env.OTLP_GOOGLE_CLOUD_PROJECT||process.env.GOOGLE_CLOUD_PROJECT,p=s===Jg.GCP&&!c,f,g,y;if(p)B.log("Creating GCP exporters with projectId:",a,"using",e?"provided credentials":"ADC"),f=new i5(a,e),g=new s5(a,e),y=new kb.PeriodicExportingMetricReader({exporter:new o5(a,e),exportIntervalMillis:3e4});else if(l)if(o==="http"){let _=E=>{let b=new URL(u);return b.pathname=[b.pathname.replace(/\/$/,""),E].join("/"),b.href};f=new DMt.OTLPTraceExporter({url:_("v1/traces")}),g=new LMt.OTLPLogExporter({url:_("v1/logs")}),y=new kb.PeriodicExportingMetricReader({exporter:new MMt.OTLPMetricExporter({url:_("v1/metrics")}),exportIntervalMillis:1e4})}else f=new PMt.OTLPTraceExporter({url:u,compression:x_.GZIP}),g=new NMt.OTLPLogExporter({url:u,compression:x_.GZIP}),y=new kb.PeriodicExportingMetricReader({exporter:new kMt.OTLPMetricExporter({url:u,compression:x_.GZIP}),exportIntervalMillis:1e4});else d?(f=new MZ(d),g=new BZ(d),y=new kb.PeriodicExportingMetricReader({exporter:new UZ(d),exportIntervalMillis:1e4})):(f=new $re.ConsoleSpanExporter,g=new Hre.ConsoleLogRecordExporter,y=new kb.PeriodicExportingMetricReader({exporter:new kb.ConsoleMetricExporter,exportIntervalMillis:1e4}));Gre=new $re.BatchSpanProcessor(f),Vre=new Hre.BatchLogRecordProcessor(g),f5=new BMt.NodeSDK({resource:r,spanProcessors:[Gre],logRecordProcessors:[Vre],metricReader:y,instrumentations:[new FMt.HttpInstrumentation]});try{f5.start(),t.getDebugMode()&&B.log("OpenTelemetry SDK started successfully."),p5=e?.client_email,eit(t),Db=!0,lTn()}catch(_){B.error("Error starting OpenTelemetry SDK:",_)}process.on("SIGTERM",()=>{zke(t)}),process.on("SIGINT",()=>{zke(t)})}async function ZSn(t){if(!(!Db||!Gre||!Vre))try{await Promise.all([Gre.forceFlush(),Vre.forceFlush()]),t.getDebugMode()&&B.log("OpenTelemetry SDK flushed successfully.")}catch(e){B.error("Error flushing SDK:",e)}}async function zke(t,e=!0){if(!(!Db||!f5))try{Pt.getInstance()?.shutdown(),await f5.shutdown(),t.getDebugMode()&&e&&B.log("OpenTelemetry SDK shut down successfully.")}catch(r){B.error("Error shutting down SDK:",r)}finally{Db=!1,f5=void 0,Lq.disable(),_Xe.disable(),Dq.disable(),EXe.disable(),Tn.disable(),h5&&(a$.off("post_auth",h5),h5=void 0),jR&&(Ee.off(Nr.TelemetryKeychainAvailability,jR),jR=void 0),QR&&(Ee.off(Nr.TelemetryTokenStorageType,QR),QR=void 0),tDe=!1,p5=void 0}}function eTn(t,e){Pt.getInstance(t)?.logStartSessionEvent(e),Zt(()=>{t.getExperimentsAsync().then(()=>{let r=Kt.logs.getLogger(Tt),n={body:e.toLogBody(),attributes:e.toOpenTelemetryAttributes(t)};r.emit(n)}).catch(r=>{B.error("Failed to log telemetry event",r)})})}function tTn(t,e){Pt.getInstance(t)?.logNewPromptEvent(e),Zt(()=>{let r=Kt.logs.getLogger(Tt),n={body:e.toLogBody(),attributes:e.toOpenTelemetryAttributes(t)};r.emit(n)})}function jre(t,e){let r={...e,"event.name":_L,"event.timestamp":new Date().toISOString()};uy.addEvent(r),Pt.getInstance(t)?.logToolCallEvent(e),Zt(()=>{let n=Kt.logs.getLogger(Tt),o={body:e.toLogBody(),attributes:e.toOpenTelemetryAttributes(t)};if(n.emit(o),t_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&&i_e(t,s,"added",{function_name:e.function_name});let c=e.metadata.model_removed_lines;typeof c=="number"&&c>0&&i_e(t,c,"removed",{function_name:e.function_name})}})}function FR(t,e){Pt.getInstance(t)?.logToolOutputTruncatedEvent(e),Zt(()=>{let r=Kt.logs.getLogger(Tt),n={body:e.toLogBody(),attributes:e.toOpenTelemetryAttributes(t)};r.emit(n)})}function qMt(t,e){Pt.getInstance(t)?.logToolOutputMaskingEvent(e),Zt(()=>{let r=Kt.logs.getLogger(Tt),n={body:e.toLogBody(),attributes:e.toOpenTelemetryAttributes(t)};r.emit(n)})}function qR(t,e){Pt.getInstance(t)?.logFileOperationEvent(e),Zt(()=>{let r=Kt.logs.getLogger(Tt),n={body:e.toLogBody(),attributes:e.toOpenTelemetryAttributes(t)};r.emit(n),n_e(t,{operation:e.operation,lines:e.lines,mimetype:e.mimetype,extension:e.extension,programming_language:e.programming_language})})}function Wke(t,e){Pt.getInstance(t)?.logApiRequestEvent(e),Zt(()=>{let r=Kt.logs.getLogger(Tt);r.emit(e.toLogRecord(t)),r.emit(e.toSemanticLogRecord(t))})}function Yke(t,e){Pt.getInstance(t)?.logFlashFallbackEvent(),Zt(()=>{let r=Kt.logs.getLogger(Tt),n={body:e.toLogBody(),attributes:e.toOpenTelemetryAttributes(t)};r.emit(n)})}function GMt(t,e){Pt.getInstance(t)?.logRipgrepFallbackEvent(),Zt(()=>{let r=Kt.logs.getLogger(Tt),n={body:e.toLogBody(),attributes:e.toOpenTelemetryAttributes(t)};r.emit(n)})}function Jke(t,e){let r={...e,"event.name":EL,"event.timestamp":new Date().toISOString()};uy.addEvent(r),Pt.getInstance(t)?.logApiErrorEvent(e),Zt(()=>{let n=Kt.logs.getLogger(Tt);n.emit(e.toLogRecord(t)),n.emit(e.toSemanticLogRecord(t)),r_e(t,e.duration_ms,{model:e.model,status_code:e.status_code,error_type:e.error_type}),TV(t,e.duration_ms,{model:e.model,status_code:e.status_code,genAiAttributes:{...A_(e),"error.type":e.error_type||"unknown"}})})}function Kke(t,e){let r={...e,"event.name":bL,"event.timestamp":new Date().toISOString()};uy.addEvent(r),Pt.getInstance(t)?.logApiResponseEvent(e),Zt(()=>{let n=Kt.logs.getLogger(Tt);n.emit(e.toLogRecord(t)),n.emit(e.toSemanticLogRecord(t));let o=A_(e);TV(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)d_e(t,c,{model:e.model,type:u,genAiAttributes:o})})}function nDe(t,e){Pt.getInstance(t)?.logLoopDetectedEvent(e),Zt(()=>{let r=Kt.logs.getLogger(Tt),n={body:e.toLogBody(),attributes:e.toOpenTelemetryAttributes(t)};r.emit(n)})}function VMt(t,e){Pt.getInstance(t)?.logLoopDetectionDisabledEvent(),Zt(()=>{let r=Kt.logs.getLogger(Tt),n={body:e.toLogBody(),attributes:e.toOpenTelemetryAttributes(t)};r.emit(n)})}function $Mt(t,e){Pt.getInstance(t)?.logNextSpeakerCheck(e),Zt(()=>{let r=Kt.logs.getLogger(Tt),n={body:e.toLogBody(),attributes:e.toOpenTelemetryAttributes(t)};r.emit(n)})}function rTn(t,e){Pt.getInstance(t)?.logSlashCommandEvent(e),Zt(()=>{let r=Kt.logs.getLogger(Tt),n={body:e.toLogBody(),attributes:e.toOpenTelemetryAttributes(t)};r.emit(n)})}function nTn(t,e){let r={...e,"event.name":k_e,"event.timestamp":new Date().toISOString()};uy.addEvent(r),Pt.getInstance(t)?.logRewindEvent(e),Zt(()=>{let n=Kt.logs.getLogger(Tt),o={body:e.toLogBody(),attributes:e.toOpenTelemetryAttributes(t)};n.emit(o)})}function uTn(t,e){Pt.getInstance(t)?.logIdeConnectionEvent(e),Zt(()=>{let r=Kt.logs.getLogger(Tt),n={body:e.toLogBody(),attributes:e.toOpenTelemetryAttributes(t)};r.emit(n)})}function iTn(t,e){Pt.getInstance(t)?.logConversationFinishedEvent(e),Zt(()=>{let r=Kt.logs.getLogger(Tt),n={body:e.toLogBody(),attributes:e.toOpenTelemetryAttributes(t)};r.emit(n)})}function Qre(t,e){Pt.getInstance(t)?.logChatCompressionEvent(e);let r=Kt.logs.getLogger(Tt),n={body:e.toLogBody(),attributes:e.toOpenTelemetryAttributes(t)};r.emit(n),tit(t,{tokens_before:e.tokens_before,tokens_after:e.tokens_after})}function HMt(t,e){Pt.getInstance(t)?.logMalformedJsonResponseEvent(e),Zt(()=>{let r=Kt.logs.getLogger(Tt),n={body:e.toLogBody(),attributes:e.toOpenTelemetryAttributes(t)};r.emit(n)})}function zMt(t,e){Pt.getInstance(t)?.logInvalidChunkEvent(e),Zt(()=>{let r=Kt.logs.getLogger(Tt),n={body:e.toLogBody(),attributes:e.toOpenTelemetryAttributes(t)};r.emit(n),o_e(t)})}function tw(t,e){Pt.getInstance(t)?.logNetworkRetryAttemptEvent(e),Zt(()=>{let r=Kt.logs.getLogger(Tt),n={body:e.toLogBody(),attributes:e.toOpenTelemetryAttributes(t)};r.emit(n),s_e(t,{model:e.model,attempt:e.attempt})})}function WMt(t,e){Pt.getInstance(t)?.logContentRetryEvent(e),Zt(()=>{let r=Kt.logs.getLogger(Tt),n={body:e.toLogBody(),attributes:e.toOpenTelemetryAttributes(t)};r.emit(n),a_e(t)})}function zre(t,e){Pt.getInstance(t)?.logContentRetryFailureEvent(e),Zt(()=>{let r=Kt.logs.getLogger(Tt),n={body:e.toLogBody(),attributes:e.toOpenTelemetryAttributes(t)};r.emit(n),l_e(t)})}function YMt(t,e){Pt.getInstance(t)?.logModelRoutingEvent(e),Zt(()=>{let r=Kt.logs.getLogger(Tt),n={body:e.toLogBody(),attributes:e.toOpenTelemetryAttributes(t)};r.emit(n),c_e(t,e)})}function dTn(t,e){Pt.getInstance(t)?.logModelSlashCommandEvent(e),Zt(()=>{let r=Kt.logs.getLogger(Tt),n={body:e.toLogBody(),attributes:e.toOpenTelemetryAttributes(t)};r.emit(n),ait(t,e)})}async function oTn(t,e){await Pt.getInstance(t)?.logExtensionInstallEvent(e),Zt(()=>{let r=Kt.logs.getLogger(Tt),n={body:e.toLogBody(),attributes:e.toOpenTelemetryAttributes(t)};r.emit(n)})}async function sTn(t,e){await Pt.getInstance(t)?.logExtensionUninstallEvent(e),Zt(()=>{let r=Kt.logs.getLogger(Tt),n={body:e.toLogBody(),attributes:e.toOpenTelemetryAttributes(t)};r.emit(n)})}async function aTn(t,e){await Pt.getInstance(t)?.logExtensionUpdateEvent(e),Zt(()=>{let r=Kt.logs.getLogger(Tt),n={body:e.toLogBody(),attributes:e.toOpenTelemetryAttributes(t)};r.emit(n)})}async function RMt(t,e){await Pt.getInstance(t)?.logExtensionEnableEvent(e),Zt(()=>{let r=Kt.logs.getLogger(Tt),n={body:e.toLogBody(),attributes:e.toOpenTelemetryAttributes(t)};r.emit(n)})}async function pTn(t,e){await Pt.getInstance(t)?.logExtensionDisableEvent(e),Zt(()=>{let r=Kt.logs.getLogger(Tt),n={body:e.toLogBody(),attributes:e.toOpenTelemetryAttributes(t)};r.emit(n)})}function g5(t,e){Pt.getInstance(t)?.logEditStrategyEvent(e),Zt(()=>{let r=Kt.logs.getLogger(Tt),n={body:e.toLogBody(),attributes:e.toOpenTelemetryAttributes(t)};r.emit(n)})}function iDe(t,e){Pt.getInstance(t)?.logEditCorrectionEvent(e),Zt(()=>{let r=Kt.logs.getLogger(Tt),n={body:e.toLogBody(),attributes:e.toOpenTelemetryAttributes(t)};r.emit(n)})}function JMt(t,e){Pt.getInstance(t)?.logAgentStartEvent(e),Zt(()=>{let r=Kt.logs.getLogger(Tt),n={body:e.toLogBody(),attributes:e.toOpenTelemetryAttributes(t)};r.emit(n)})}function KMt(t,e){Pt.getInstance(t)?.logAgentFinishEvent(e),Zt(()=>{let r=Kt.logs.getLogger(Tt),n={body:e.toLogBody(),attributes:e.toOpenTelemetryAttributes(t)};r.emit(n),lit(t,e)})}function XMt(t,e){Pt.getInstance(t)?.logRecoveryAttemptEvent(e),Zt(()=>{let r=Kt.logs.getLogger(Tt),n={body:e.toLogBody(),attributes:e.toOpenTelemetryAttributes(t)};r.emit(n),cit(t,e)})}function qre(t,e){Pt.getInstance(t)?.logWebFetchFallbackAttemptEvent(e),Zt(()=>{let r=Kt.logs.getLogger(Tt),n={body:e.toLogBody(),attributes:e.toOpenTelemetryAttributes(t)};r.emit(n)})}function oDe(t,e){Pt.getInstance(t)?.logLlmLoopCheckEvent(e),Zt(()=>{let r=Kt.logs.getLogger(Tt),n={body:e.toLogBody(),attributes:e.toOpenTelemetryAttributes(t)};r.emit(n)})}function ZMt(t,e){Pt.getInstance(t)?.logApprovalModeSwitchEvent(e),Zt(()=>{Kt.logs.getLogger(Tt).emit({body:e.toLogBody(),attributes:e.toOpenTelemetryAttributes(t)})})}function e6t(t,e){Pt.getInstance(t)?.logApprovalModeDurationEvent(e),Zt(()=>{Kt.logs.getLogger(Tt).emit({body:e.toLogBody(),attributes:e.toOpenTelemetryAttributes(t)})})}function t6t(t,e){Pt.getInstance(t)?.logPlanExecutionEvent(e),Zt(()=>{Kt.logs.getLogger(Tt).emit({body:e.toLogBody(),attributes:e.toOpenTelemetryAttributes(t)}),sit(t,{approval_mode:e.approval_mode})})}function r6t(t,e){Pt.getInstance(t)?.logHookCallEvent(e),Zt(()=>{let r=Kt.logs.getLogger(Tt),n={body:e.toLogBody(),attributes:e.toOpenTelemetryAttributes(t)};r.emit(n),pit(t,e.hook_event_name,e.hook_name,e.duration_ms,e.success)})}function IMt(t,e){Pt.getInstance(t)?.logStartupStatsEvent(e),Zt(()=>{t.getExperimentsAsync().then(()=>{let r=Kt.logs.getLogger(Tt),n={body:e.toLogBody(),attributes:e.toOpenTelemetryAttributes(t)};r.emit(n)}).catch(r=>{B.error("Failed to log telemetry event",r)})})}function jMt(t,e){Pt.getInstance(t)?.logKeychainAvailabilityEvent(e),Zt(()=>{let r=Kt.logs.getLogger(Tt),n={body:e.toLogBody(),attributes:e.toOpenTelemetryAttributes(t)};r.emit(n),fit(t,e)})}function QMt(t,e){Pt.getInstance(t)?.logTokenStorageInitializationEvent(e),Zt(()=>{let r=Kt.logs.getLogger(Tt),n={body:e.toLogBody(),attributes:e.toOpenTelemetryAttributes(t)};r.emit(n),hit(t,e)})}function Xke(t,e){Pt.getInstance(t)?.logOnboardingStartEvent(e),Zt(()=>{let r=Kt.logs.getLogger(Tt),n={body:e.toLogBody(),attributes:e.toOpenTelemetryAttributes(t)};r.emit(n),iit(t)})}function Zke(t,e){Pt.getInstance(t)?.logOnboardingSuccessEvent(e),Zt(()=>{let r=Kt.logs.getLogger(Tt),n={body:e.toLogBody(),attributes:e.toOpenTelemetryAttributes(t)};r.emit(n),oit(t,e.userTier,e.duration_ms)})}function sDe(t,e){Zt(()=>{let n=Kt.logs.getLogger(Tt),o={body:e.toLogBody(),attributes:e.toOpenTelemetryAttributes(t)};n.emit(o)});let r=Pt.getInstance(t);r&&(e instanceof LR?r.logCreditsUsedEvent(e):e instanceof Nre?r.logOverageOptionSelectedEvent(e):e instanceof kre?r.logEmptyWalletMenuShownEvent(e):e instanceof Dre&&r.logCreditPurchaseClickEvent(e))}function n6t(t){return{request:{model:"models/"+t.model,contents:rw(t.contents)}}}function i6t(t){return t.totalTokens===void 0&&B.warn("Warning: Code Assist API did not return totalTokens. Defaulting to 0."),{totalTokens:t.totalTokens??0}}function lDe(t,e,r,n,o){return{model:t.model,project:r,user_prompt_id:e,request:fTn(t,n),enabled_credit_types:o}}function cDe(t){let e=new d3;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 fTn(t,e){return{contents:rw(t.contents),systemInstruction:hTn(t.config?.systemInstruction),cachedContent:t.config?.cachedContent,tools:t.config?.tools,toolConfig:t.config?.toolConfig,labels:t.config?.labels,safetySettings:t.config?.safetySettings,generationConfig:mTn(t.config),session_id:e}}function rw(t){return Array.isArray(t)?t.map(aDe):[aDe(t)]}function hTn(t){if(t)return aDe(t)}function gTn(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)&&!("parts"in t)&&!("role"in t)}function aDe(t){return Array.isArray(t)?{role:"user",parts:Wre(t)}:typeof t=="string"?{role:"user",parts:[{text:t}]}:gTn(t)?{role:"user",parts:[o6t(t)]}:{...t,parts:t.parts?Wre(t.parts.filter(e=>e!=null)):[]}}function Wre(t){return t.map(o6t)}function o6t(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}
|
|
1063
1063
|
${e}`:e;return{...r,text:c}}return t}function mTn(t){if(t)return{temperature:t.temperature,topP:t.topP,topK:t.topK,candidateCount:t.candidateCount,maxOutputTokens:t.maxOutputTokens,stopSequences:t.stopSequences,responseLogprobs:t.responseLogprobs,logprobs:t.logprobs,presencePenalty:t.presencePenalty,frequencyPenalty:t.frequencyPenalty,seed:t.seed,responseMimeType:t.responseMimeType,responseSchema:t.responseSchema,responseJsonSchema:t.responseJsonSchema,routingConfig:t.routingConfig,modelSelectionConfig:t.modelSelectionConfig,responseModalities:t.responseModalities,mediaResolution:t.mediaResolution,speechConfig:t.speechConfig,audioTimestamp:t.audioTimestamp,thinkingConfig:t.thinkingConfig}}function nw(t,e){if(!t)return"";if(typeof t=="string")return t;if(Array.isArray(t))return t.map(n=>nw(n,e)).join("");let r=t;if(e?.verbose){if(r.videoMetadata!==void 0)return"[Video Metadata]";if(r.thought!==void 0)return`[Thought: ${r.thought}]`;if(r.codeExecutionResult!==void 0)return"[Code Execution Result]";if(r.executableCode!==void 0)return"[Executable Code]";if(r.fileData!==void 0)return"[File Data]";if(r.functionCall!==void 0)return`[Function Call: ${r.functionCall.name}]`;if(r.functionResponse!==void 0)return`[Function Response: ${r.functionResponse.name}]`;if(r.inlineData!==void 0){let n=r.inlineData.mimeType??"unknown",o=r.inlineData.data??"",c=(Math.ceil(o.length*3/4)/1024).toFixed(1);return`[${n.startsWith("audio/")?"Audio":n.startsWith("video/")?"Video":n.startsWith("image/")?"Image":"Media"}: ${n}, ${c} KB]`}}return r.text??""}function bn(t){if(t.candidates&&t.candidates.length>0){let e=t.candidates[0];if(e.content&&e.content.parts&&e.content.parts.length>0)return e.content.parts.filter(r=>r.text&&!r.thought).map(r=>r.text).join("")}return null}async function OXi(t,e){let r=[],n=Array.isArray(t)?t:typeof t=="string"?[{text:t}]:[t];for(let o of n){let s;if(typeof o=="string"?s=o:"text"in o&&(s=o.text),s!==void 0){let c=await e(s);r.push(...c)}else r.push(o)}return r}function IXi(t,e,r=`
|
|
1064
1064
|
|
|
@@ -1212,7 +1212,7 @@ ${R}`);let N=Ix(this.resolvedPath),k=GR(this.resolvedPath),M=S1.extname(this.res
|
|
|
1212
1212
|
`,e-1);return{line:r===-1?0:t.slice(0,r+1).match(/\n/g).length,column:e-r-1}}function yFe(t,e,{oneBased:r=!1}={}){if(typeof t!="string")throw new TypeError("Text parameter should be a string");if(!Number.isInteger(e))throw new TypeError("Index parameter should be an integer");if(e<0||e>t.length)throw new RangeError("Index out of bounds");let n=ZVn(t,e);return r?{line:n.line+1,column:n.column+1}:n}var e$n=t=>`\\u{${t.codePointAt(0).toString(16)}}`,AFe=class t extends Error{name="JSONError";fileName;#e;#t;#r;#n;#o;constructor(e){if(typeof e=="string")super(),this.#r=e;else{let{jsonParseError:r,fileName:n,input:o}=e;super(void 0,{cause:r}),this.#e=o,this.#t=r,this.fileName=n}Error.captureStackTrace?.(this,t)}get message(){this.#r??=`${r$n(this.#t.message)}${this.#e===""?" while parsing empty string":""}`;let{codeFrame:e}=this;return`${this.#r}${this.fileName?` in ${this.fileName}`:""}${e?`
|
|
1213
1213
|
|
|
1214
1214
|
${e}
|
|
1215
|
-
`:""}`}set message(e){this.#r=e}#i(e){if(!this.#t)return;let r=this.#e,n=t$n(r,this.#t.message);if(n)return(0,Gzt.codeFrameColumns)(r,{start:n},{highlightCode:e})}get codeFrame(){return this.#n??=this.#i(!0),this.#n}get rawCodeFrame(){return this.#o??=this.#i(!1),this.#o}},t$n=(t,e)=>{let r=e.match(/in JSON at position (?<index>\d+)(?: \(line (?<line>\d+) column (?<column>\d+)\))?$/);if(!r)return;let{index:n,line:o,column:s}=r.groups;return o&&s?{line:Number(o),column:Number(s)}:yFe(t,Number(n),{oneBased:!0})},r$n=t=>t.replace(/(?<=^Unexpected token )(?<quote>')?(.)\k<quote>/,(e,r,n)=>`"${n}"(${e$n(n)})`);function _Fe(t,e,r){typeof e=="string"&&(r=e,e=void 0);try{return JSON.parse(t,e)}catch(n){throw new AFe({jsonParseError:n,fileName:r,input:t})}}var oYt=Fe(nYt(),1);import{fileURLToPath as wHn}from"node:url";function iYt(t){return t instanceof URL?wHn(t):t}var OHn=t=>xHn.resolve(iYt(t)??".","package.json"),IHn=(t,e)=>{let r=typeof t=="string"?_Fe(t):t;return e&&(0,oYt.default)(r),r};async function sYt({cwd:t,normalize:e=!0}={}){let r=await CHn.readFile(OHn(t),"utf8");return IHn(r,e)}async function aYt(t){let e=await Azt("package.json",t);if(e)return{packageJson:await sYt({...t,cwd:RHn.dirname(e)}),path:e}}async function Aae(t){try{let e=await aYt({cwd:t,normalize:!1});return e?e.packageJson:void 0}catch(e){B.error("Error occurred while reading package.json",e);return}}var x1;(function(t){t.NIGHTLY="nightly",t.PREVIEW="preview",t.STABLE="stable"})(x1||(x1={}));var _ae=new Map;function auo(){_ae.clear()}async function CU(t){if(_ae.has(t))return _ae.get(t);let r=(await Aae(t))?.version??"",n;return r.includes("nightly")||r===""?n=x1.NIGHTLY:r.includes("preview")?n=x1.PREVIEW:n=x1.STABLE,_ae.set(t,n),n}async function luo(t){return await CU(t)===x1.NIGHTLY}async function cuo(t){return await CU(t)===x1.PREVIEW}async function uuo(t){return await CU(t)===x1.STABLE}import{fileURLToPath as LHn}from"node:url";import MHn from"node:path";import{fileURLToPath as PHn}from"node:url";import NHn from"node:path";var kHn=PHn(import.meta.url),DHn=NHn.dirname(kHn),xU;function IN(){return xU||(xU=(async()=>{let t=await Aae(DHn);return"0.37.
|
|
1215
|
+
`:""}`}set message(e){this.#r=e}#i(e){if(!this.#t)return;let r=this.#e,n=t$n(r,this.#t.message);if(n)return(0,Gzt.codeFrameColumns)(r,{start:n},{highlightCode:e})}get codeFrame(){return this.#n??=this.#i(!0),this.#n}get rawCodeFrame(){return this.#o??=this.#i(!1),this.#o}},t$n=(t,e)=>{let r=e.match(/in JSON at position (?<index>\d+)(?: \(line (?<line>\d+) column (?<column>\d+)\))?$/);if(!r)return;let{index:n,line:o,column:s}=r.groups;return o&&s?{line:Number(o),column:Number(s)}:yFe(t,Number(n),{oneBased:!0})},r$n=t=>t.replace(/(?<=^Unexpected token )(?<quote>')?(.)\k<quote>/,(e,r,n)=>`"${n}"(${e$n(n)})`);function _Fe(t,e,r){typeof e=="string"&&(r=e,e=void 0);try{return JSON.parse(t,e)}catch(n){throw new AFe({jsonParseError:n,fileName:r,input:t})}}var oYt=Fe(nYt(),1);import{fileURLToPath as wHn}from"node:url";function iYt(t){return t instanceof URL?wHn(t):t}var OHn=t=>xHn.resolve(iYt(t)??".","package.json"),IHn=(t,e)=>{let r=typeof t=="string"?_Fe(t):t;return e&&(0,oYt.default)(r),r};async function sYt({cwd:t,normalize:e=!0}={}){let r=await CHn.readFile(OHn(t),"utf8");return IHn(r,e)}async function aYt(t){let e=await Azt("package.json",t);if(e)return{packageJson:await sYt({...t,cwd:RHn.dirname(e)}),path:e}}async function Aae(t){try{let e=await aYt({cwd:t,normalize:!1});return e?e.packageJson:void 0}catch(e){B.error("Error occurred while reading package.json",e);return}}var x1;(function(t){t.NIGHTLY="nightly",t.PREVIEW="preview",t.STABLE="stable"})(x1||(x1={}));var _ae=new Map;function auo(){_ae.clear()}async function CU(t){if(_ae.has(t))return _ae.get(t);let r=(await Aae(t))?.version??"",n;return r.includes("nightly")||r===""?n=x1.NIGHTLY:r.includes("preview")?n=x1.PREVIEW:n=x1.STABLE,_ae.set(t,n),n}async function luo(t){return await CU(t)===x1.NIGHTLY}async function cuo(t){return await CU(t)===x1.PREVIEW}async function uuo(t){return await CU(t)===x1.STABLE}import{fileURLToPath as LHn}from"node:url";import MHn from"node:path";import{fileURLToPath as PHn}from"node:url";import NHn from"node:path";var kHn=PHn(import.meta.url),DHn=NHn.dirname(kHn),xU;function IN(){return xU||(xU=(async()=>{let t=await Aae(DHn);return"0.37.1"})(),xU)}function guo(){xU=void 0}var BHn=LHn(import.meta.url),UHn=MHn.dirname(BHn),QFe;function FHn(){let t=process.platform,e=process.arch;return t==="darwin"&&e==="x64"?"DARWIN_AMD64":t==="darwin"&&e==="arm64"?"DARWIN_ARM64":t==="linux"&&e==="x64"?"LINUX_AMD64":t==="linux"&&e==="arm64"?"LINUX_ARM64":t==="win32"&&e==="x64"?"WINDOWS_AMD64":"PLATFORM_UNSPECIFIED"}async function OU(){return QFe||(QFe=(async()=>({ideName:"IDE_UNSPECIFIED",pluginType:"GEMINI",ideVersion:await IN(),platform:FHn(),updateChannel:await CU(UHn)}))()),QFe}var QHn="https://cloudcode-pa.googleapis.com",qHn="v1internal",GHn=1e3,$y=class{client;projectId;httpOptions;sessionId;userTier;userTierName;paidTier;config;constructor(e,r,n={},o,s,c,u,d){this.client=e,this.projectId=r,this.httpOptions=n,this.sessionId=o,this.userTier=s,this.userTierName=c,this.paidTier=u,this.config=d}async generateContentStream(e,r,n){let o=this.config?mpt(this.config.getBillingSettings().overageStrategy,gpt(this.paidTier)):!1,c=hpt(e.model)&&o;c&&!this.config?.getCreditsNotificationShown()&&(this.config?.setCreditsNotificationShown(!0),Ee.emitFeedback("info","Using AI Credits for this request."));let u=c?[pS]:void 0,d=await this.requestStreamingPost("streamGenerateContent",lDe(e,r,this.projectId,this.sessionId,u),e.config?.abortSignal),l={},a=Date.now(),p=!0;return async function*(f){let g=0,y=0;for await(let _ of d){p&&(l.firstMessageLatency=iae(Date.now()-a),p=!1),l.totalLatency=iae(Date.now()-a);let E=cDe(_);if(await uFe(f,_.traceId,E,l,e.config?.abortSignal,f.sessionId),_.consumedCredits)for(let b of _.consumedCredits)b.creditType===pS&&b.creditAmount&&(g+=parseInt(b.creditAmount,10)||0);_.remainingCredits&&(y=_.remainingCredits.reduce((b,v)=>v.creditType===pS&&v.creditAmount?b+(parseInt(v.creditAmount,10)||0):b,0),f.updateCredits(_.remainingCredits)),yield E}g>0&&f.config&&sDe(f.config,new LR(e.model??"unknown",g,y))}(this)}async generateContent(e,r,n){let o=Date.now(),s=await this.requestPost("generateContent",lDe(e,r,this.projectId,this.sessionId,void 0),e.config?.abortSignal,GHn),c=iae(Date.now()-o),u={totalLatency:c,firstMessageLatency:c},d=cDe(s);return await uFe(this,s.traceId,d,u,e.config?.abortSignal,this.sessionId),s.remainingCredits&&this.updateCredits(s.remainingCredits),d}updateCredits(e){if(!this.paidTier)return;let r=(this.paidTier.availableCredits??[]).filter(o=>o.creditType!==pS),n=e.filter(o=>o.creditType===pS);this.paidTier.availableCredits=[...r,...n]}async onboardUser(e){return this.requestPost("onboardUser",e)}async getOperation(e){return this.requestGetOperation(e)}async loadCodeAssist(e){try{return await this.requestPost("loadCodeAssist",e)}catch(r){if($Hn(r))return{currentTier:{id:x0.STANDARD}};throw r}}async refreshAvailableCredits(){if(!this.paidTier)return;let e=await this.loadCodeAssist({cloudaicompanionProject:this.projectId,metadata:{ideType:"IDE_UNSPECIFIED",platform:"PLATFORM_UNSPECIFIED",pluginType:"GEMINI",duetProject:this.projectId},mode:"HEALTH_CHECK"});e.paidTier?.availableCredits&&(this.paidTier.availableCredits=e.paidTier.availableCredits)}async fetchAdminControls(e){return this.requestPost("fetchAdminControls",e)}async getCodeAssistGlobalUserSetting(){return this.requestGet("getCodeAssistGlobalUserSetting")}async setCodeAssistGlobalUserSetting(e){return this.requestPost("setCodeAssistGlobalUserSetting",e)}async countTokens(e){let r=await this.requestPost("countTokens",n6t(e));return i6t(r)}async embedContent(e){throw Error()}async listExperiments(e){if(!this.projectId)throw new Error("projectId is not defined for CodeAssistServer.");let r=this.projectId,n={project:r,metadata:{...e,duetProject:r}};return this.requestPost("listExperiments",n)}async retrieveUserQuota(e){return this.requestPost("retrieveUserQuota",e)}async recordConversationOffered(e){this.projectId&&await this.recordCodeAssistMetrics({project:this.projectId,metadata:await OU(),metrics:[{conversationOffered:e,timestamp:new Date().toISOString()}]})}async recordConversationInteraction(e){this.projectId&&await this.recordCodeAssistMetrics({project:this.projectId,metadata:await OU(),metrics:[{conversationInteraction:e,timestamp:new Date().toISOString()}]})}async recordCodeAssistMetrics(e){return this.requestPost("recordCodeAssistMetrics",e)}async requestPost(e,r,n,o=100){return(await this.client.request({url:this.getMethodUrl(e),method:"POST",headers:{"Content-Type":"application/json",...this.httpOptions.headers},responseType:"json",body:JSON.stringify(r),signal:n,retryConfig:{retryDelay:o,retry:3,noResponseRetries:3,statusCodesToRetry:[[429,429],[499,499],[500,599]]}})).data}async makeGetRequest(e,r){return(await this.client.request({url:e,method:"GET",headers:{"Content-Type":"application/json",...this.httpOptions.headers},responseType:"json",signal:r})).data}async requestGet(e,r){return this.makeGetRequest(this.getMethodUrl(e),r)}async requestGetOperation(e,r){return this.makeGetRequest(this.getOperationUrl(e),r)}async requestStreamingPost(e,r,n){let o=await this.client.request({url:this.getMethodUrl(e),method:"POST",params:{alt:"sse"},headers:{"Content-Type":"application/json",...this.httpOptions.headers},responseType:"stream",body:JSON.stringify(r),signal:n,retry:!1});return async function*(s){let c=lYt.createInterface({input:jHn.from(o.data),crlfDelay:1/0}),u=[];for await(let d of c)if(d.startsWith("data: "))u.push(d.slice(6).trim());else if(d===""){if(u.length===0)continue;let l=u.join(`
|
|
1216
1216
|
`);try{yield JSON.parse(l)}catch{s.config&&zMt(s.config,new UV("Malformed JSON chunk"))}u=[]}}(this)}getBaseUrl(){let e=process.env.CODE_ASSIST_ENDPOINT??QHn,r=process.env.CODE_ASSIST_API_VERSION||qHn;return`${e}/${r}`}getMethodUrl(e){return`${this.getBaseUrl()}:${e}`}getOperationUrl(e){return`${this.getBaseUrl()}/${e}`}};function VHn(t){return!!t&&typeof t=="object"&&"response"in t&&!!t.response&&typeof t.response=="object"&&"data"in t.response&&!!t.response.data&&typeof t.response.data=="object"&&"error"in t.response.data&&!!t.response.data.error&&typeof t.response.data.error=="object"&&"details"in t.response.data.error&&Array.isArray(t.response.data.error.details)}function $Hn(t){return VHn(t)?t.response.data.error.details.some(e=>e&&typeof e=="object"&&"reason"in e&&e.reason==="SECURITY_POLICY_VIOLATED"):!1}var qFe=class{storage;defaultTtl;deleteOnPromiseFailure;constructor(e={}){this.storage=e.storage==="weakmap"?new WeakMap:new Map,this.defaultTtl=e.defaultTtl,this.deleteOnPromiseFailure=e.deleteOnPromiseFailure??!0}get(e){let r=this.storage.get(e);if(!r)return;let n=r.ttl??this.defaultTtl;if(n!==void 0&&Date.now()-r.timestamp>n){this.delete(e);return}return r.value}set(e,r,n){let o={value:r,timestamp:Date.now(),ttl:n};this.storage.set(e,o),this.deleteOnPromiseFailure&&r instanceof Promise&&r.catch(()=>{this.storage.get(e)===o&&this.delete(e)})}getOrCreate(e,r,n){let o=this.get(e);return o===void 0&&(o=r(),this.set(e,o,n)),o}delete(e){this.storage instanceof Map?this.storage.delete(e):this.storage.delete(e)}clear(){if(this.storage instanceof Map)this.storage.clear();else throw new Error("clear() is not supported on WeakMap storage")}};function RN(t={}){return new qFe(t)}var GFe=class extends Error{constructor(){super("This account requires setting the GOOGLE_CLOUD_PROJECT or GOOGLE_CLOUD_PROJECT_ID env var. See https://goo.gle/gemini-cli-auth-docs#workspace-gca"),this.name="ProjectIdRequiredError"}},VFe=class extends Error{constructor(){super("User cancelled account validation"),this.name="ValidationCancelledError"}},$Fe=class extends Error{ineligibleTiers;constructor(e){let r=e.map(n=>n.reasonMessage).join(", ");super(r),this.name="IneligibleTierError",this.ineligibleTiers=e}},uYt=RN({storage:"weakmap"});function Quo(){uYt=RN({storage:"weakmap"})}async function dYt(t,e,r={}){let n=process.env.GOOGLE_CLOUD_PROJECT||process.env.GOOGLE_CLOUD_PROJECT_ID||void 0;return uYt.getOrCreate(t,()=>RN({storage:"map",defaultTtl:3e4})).getOrCreate(n,()=>HHn(t,n,e,r))}async function HHn(t,e,r,n={}){let o=new $y(t,e,n,"",void 0,void 0),s={ideType:"IDE_UNSPECIFIED",platform:"PLATFORM_UNSPECIFIED",pluginType:"GEMINI"},c=r.getValidationHandler(),u;for(;;){u=await o.loadCodeAssist({cloudaicompanionProject:e,metadata:{...s,duetProject:e}});try{WHn(u);break}catch(f){if(f instanceof b1&&c){let g=await c(f.validationLink,f.validationDescription);if(g==="verify")continue;throw g==="change_auth"?new mXe:new VFe}throw f}}if(u.currentTier){if(!u.paidTier?.id&&!u.currentTier.id&&B.warn("Warning: Code Assist API did not return a user tier ID. Defaulting to STANDARD tier."),!u.cloudaicompanionProject){if(e)return{projectId:e,userTier:u.paidTier?.id??u.currentTier.id??x0.STANDARD,userTierName:u.paidTier?.name??u.currentTier.name,paidTier:u.paidTier??void 0,hasOnboardedPreviously:u.currentTier.hasOnboardedPreviously??!0};cYt(u)}return{projectId:u.cloudaicompanionProject,userTier:u.paidTier?.id??u.currentTier.id??x0.STANDARD,userTierName:u.paidTier?.name??u.currentTier.name,paidTier:u.paidTier??void 0,hasOnboardedPreviously:u.currentTier.hasOnboardedPreviously??!0}}let d=zHn(u);d.id||B.warn("Warning: Code Assist API did not return an onboarding tier ID. Defaulting to STANDARD tier.");let l;d.id===x0.FREE?l={tierId:d.id,cloudaicompanionProject:void 0,metadata:s}:l={tierId:d.id,cloudaicompanionProject:e,metadata:{...s,duetProject:e}},Xke(r,new yL);let a=Date.now(),p=await o.onboardUser(l);if(!p.done&&p.name){let f=p.name;for(;!p.done;)await new Promise(g=>setTimeout(g,5e3)),p=await o.getOperation(f)}if(Zke(r,new AL(d.name,Date.now()-a)),!p.response?.cloudaicompanionProject?.id){if(e)return{projectId:e,userTier:d.id??x0.STANDARD,userTierName:d.name,hasOnboardedPreviously:d.hasOnboardedPreviously??!1};cYt(u)}return{projectId:p.response.cloudaicompanionProject.id,userTier:d.id??x0.STANDARD,userTierName:d.name,hasOnboardedPreviously:d.hasOnboardedPreviously??!1}}function cYt(t){throw t.ineligibleTiers&&t.ineligibleTiers.length>0?new $Fe(t.ineligibleTiers):new GFe}function zHn(t){for(let e of t.allowedTiers||[])if(e.isDefault)return e;return{name:"",description:"",id:x0.LEGACY,userDefinedCloudaicompanionProject:!0}}function WHn(t){if(!t)throw new Error("LoadCodeAssist returned empty response");if(!t.currentTier&&t.ineligibleTiers&&t.ineligibleTiers.length>0){let e=t.ineligibleTiers.find(n=>n.validationUrl&&n.reasonCode===c$.VALIDATION_REQUIRED),r=e?.validationUrl;if(e&&r)throw new b1(`Account validation required: ${e.reasonMessage}`,void 0,r,e.reasonMessage)}}function HFe(t){return typeof t=="object"&&t!==null&&"error"in t&&typeof t.error=="object"&&"message"in t.error}function Eae(t){return typeof t=="object"&&t!==null&&"message"in t&&typeof t.message=="string"}var zFe=.25,WFe=1.3,YHn=3e3,JHn=25800,KHn=1e5,XHn=3;function ZHn(t){if(t.length>KHn)return t.length/4;let e=0;for(let r=0;r<t.length;r++)t.charCodeAt(r)<=127?e+=zFe:e+=WFe;return e}function ezn(t){let e="inlineData"in t?t.inlineData:void 0,r="fileData"in t?t.fileData:void 0,n=e?.mimeType||r?.mimeType;if(n?.startsWith("image/"))return YHn;if(n?.startsWith("application/pdf"))return JHn}function tzn(t,e){let r=t.functionResponse;if(!r)return 0;let n=(r.name?.length??0)/4,o=r.response;typeof o=="string"?n+=o.length/4:o!=null&&(n+=JSON.stringify(o).length/4);let s=r.parts;return s&&s.length>0&&(n+=ai(s,e+1)),n}function ai(t,e=0){if(e>XHn)return 0;let r=0;for(let n of t)if(typeof n.text=="string")r+=ZHn(n.text);else if(n.functionResponse)r+=tzn(n,e);else{let o=ezn(n);o!==void 0?r+=o:r+=JSON.stringify(n).length/4}return Math.floor(r)}async function bae(t,e,r){let n=Array.isArray(t)?t.map(s=>typeof s=="string"?{text:s}:s):typeof t=="string"?[{text:t}]:[t];if(n.some(s=>"inlineData"in s||"fileData"in s))try{return(await e.countTokens({model:r,contents:[{role:"user",parts:n}]})).totalTokens??0}catch(s){return B.debug("countTokens API failed:",s),ai(n)}return ai(n)}function YFe(t){return Math.floor(JSON.stringify(t).length/4)}function rzn(t,e){let r=0,n=0,o=0,s=0,c={};if(e?.systemInstruction&&(r+=YFe(e.systemInstruction)),e?.tools)for(let u of e.tools){let d=YFe(u);if(u&&typeof u=="object"&&"functionDeclarations"in u&&u.functionDeclarations){let l=0;for(let a of u.functionDeclarations)a.name&&y0(a.name)&&(l+=YFe(a));s+=l,n+=d-l}else n+=d}for(let u of t)for(let d of u.parts||[])if(d.functionCall){let l=d.functionCall.name||"unknown",a=ai([d]);y0(l)?s+=a:c[l]=(c[l]||0)+a}else if(d.functionResponse){let l=d.functionResponse.name||"unknown",a=ai([d]);y0(l)?s+=a:c[l]=(c[l]||0)+a}else o+=ai([d]);return{system_instructions:r,tool_definitions:n,history:o,tool_calls:c,mcp_servers:s}}var O1=class{wrapped;config;constructor(e,r){this.wrapped=e,this.config=r}getWrapped(){return this.wrapped}get userTier(){return this.wrapped.userTier}get userTierName(){return this.wrapped.userTierName}get paidTier(){return this.wrapped.paidTier}logApiRequest(e,r,n,o,s,c){let u=JSON.stringify(e);Wke(this.config,new aL(r,{prompt_id:n,contents:e,generate_content_config:s,server:c},u,o))}_getEndpointUrl(e,r){if(this.wrapped instanceof $y){let o=new URL(this.wrapped.getMethodUrl(r)),s=o.port?parseInt(o.port,10):o.protocol==="https:"?443:80;return{address:o.hostname,port:s}}if(this.config.getContentGeneratorConfig()?.vertexai){let o=process.env.GOOGLE_CLOUD_LOCATION;return o?{address:`${o}-aiplatform.googleapis.com`,port:443}:{address:"unknown",port:0}}return{address:"generativelanguage.googleapis.com",port:443}}_logApiResponse(e,r,n,o,s,c,u,d,l,a,p){let f=new cL(n,r,{prompt_id:o,contents:e,generate_content_config:a,server:p},{candidates:u,response_id:c},this.config.getContentGeneratorConfig()?.authType,d,l,s);u?.some(y=>y.content?.parts?.some(_=>_.functionCall))||(f.usage.context_breakdown=rzn(e,a)),Kke(this.config,f)}_fixGaxiosErrorData(e){if(typeof e=="object"&&e!==null&&"response"in e&&typeof e.response=="object"&&e.response!==null&&"data"in e.response){let r=e.response,n=r.data;if(typeof n=="string"&&n.includes(","))try{let o=n.split(",").map(Number);o.every(s=>!isNaN(s))&&(r.data=String.fromCharCode(...o))}catch{}}}_logApiError(e,r,n,o,s,c,u,d){if(A0(r))return;let l=r instanceof Error?r.message:String(r),a=gXe(r);Jke(this.config,new lL(n,l,e,{prompt_id:o,contents:s,generate_content_config:u,server:d},this.config.getContentGeneratorConfig()?.authType,a,Eae(r)?r.status:void 0,c))}async generateContent(e,r,n){return xf({operation:id.LLMCall,logPrompts:this.config.getTelemetryLogPromptsEnabled(),attributes:{[bV]:e.model,[tAe]:r,[iAe]:Mr(e.config?.systemInstruction??[]),[oAe]:Mr(e.config?.tools??[])}},async({metadata:o})=>{o.input=e.contents;let s=Date.now(),c=rw(e.contents),u=this._getEndpointUrl(e,"generateContent");this.logApiRequest(c,e.model,r,n,e.config,u);try{let d=await this.wrapped.generateContent(e,r,n);o.output=d.candidates?.[0]?.content??null,o.attributes[rAe]=d.usageMetadata?.promptTokenCount??0,o.attributes[nAe]=d.usageMetadata?.candidatesTokenCount??0;let l=Date.now()-s;return this._logApiResponse(c,l,d.modelVersion||e.model,r,n,d.responseId,d.candidates,d.usageMetadata,JSON.stringify({candidates:d.candidates,usageMetadata:d.usageMetadata,responseId:d.responseId,modelVersion:d.modelVersion,promptFeedback:d.promptFeedback}),e.config,u),this.config.refreshUserQuotaIfStale().catch(a=>B.debug("quota refresh failed",a)),d}catch(d){o.error=d;let l=Date.now()-s;throw this._fixGaxiosErrorData(d),this._logApiError(l,d,e.model,r,c,n,e.config,u),d}})}async generateContentStream(e,r,n){return xf({operation:id.LLMCall,logPrompts:this.config.getTelemetryLogPromptsEnabled(),attributes:{[bV]:e.model,[tAe]:r,[iAe]:Mr(e.config?.systemInstruction??[]),[oAe]:Mr(e.config?.tools??[])}},async({metadata:o})=>{o.input=e.contents;let s=Date.now(),c=this._getEndpointUrl(e,"generateContentStream");/########\d+$/.test(r)&&this.config.setLatestApiRequest(e),this.logApiRequest(rw(e.contents),e.model,r,n,e.config,c);let u;try{u=await this.wrapped.generateContentStream(e,r,n)}catch(d){let l=Date.now()-s;throw this._fixGaxiosErrorData(d),this._logApiError(l,d,e.model,r,rw(e.contents),n,e.config,c),d}return this.loggingStreamWrapper(e,u,s,r,n,o)})}async*loggingStreamWrapper(e,r,n,o,s,c){let u=[],d,l=this._getEndpointUrl(e,"generateContentStream"),a=rw(e.contents);try{for await(let f of r)u.push(f),f.usageMetadata&&(d=f.usageMetadata),yield f;let p=Date.now()-n;this._logApiResponse(a,p,u[0]?.modelVersion||e.model,o,s,u[0]?.responseId,u.flatMap(f=>f.candidates||[]),d,JSON.stringify(u.map(f=>({candidates:f.candidates,usageMetadata:f.usageMetadata,responseId:f.responseId,modelVersion:f.modelVersion,promptFeedback:f.promptFeedback}))),e.config,l),this.config.refreshUserQuotaIfStale().catch(f=>B.debug("quota refresh failed",f)),c.output=u.map(f=>f.candidates?.[0]?.content??null),d&&(c.attributes[rAe]=d.promptTokenCount??0,c.attributes[nAe]=d.candidatesTokenCount??0)}catch(p){c.error=p;let f=Date.now()-n;throw this._logApiError(f,p,u[0]?.modelVersion||e.model,o,a,s,e.config,l),p}}async countTokens(e){return this.wrapped.countTokens(e)}async embedContent(e){return xf({operation:id.LLMCall,logPrompts:this.config.getTelemetryLogPromptsEnabled(),attributes:{[bV]:e.model}},async({metadata:r})=>{r.input=e.contents;let n=await this.wrapped.embedContent(e);return r.output=n,n})}};async function pYt(t,e,r,n){if(e===Vt.LOGIN_WITH_GOOGLE||e===Vt.COMPUTE_ADC){let o=await cpt(e,r),s=await dYt(o,r,t);return new $y(o,s.projectId,t,n,s.userTier,s.userTierName,s.paidTier,r)}throw new Error(`Unsupported authType: ${e}`)}function jf(t){let e=t.getContentGenerator();if(e instanceof O1&&(e=e.getWrapped()),e instanceof $y)return e}var nzn="gemini-cli-api-key",pC="default-api-key",vae=new T_(nzn),Sae=RN({storage:"map",defaultTtl:3e4});function hdo(){Sae.clear()}async function fYt(){return Sae.getOrCreate(pC,async()=>{try{let t=await vae.getCredentials(pC);return t?.token?.accessToken?t.token.accessToken:null}catch(t){return B.error("Failed to load API key from storage:",t),null}})}async function gdo(t){if(Sae.delete(pC),!t||t.trim()===""){try{await vae.deleteCredentials(pC)}catch(r){B.warn("Failed to delete API key from storage:",r)}return}let e={serverName:pC,token:{accessToken:t,tokenType:"ApiKey"},updatedAt:Date.now()};await vae.setCredentials(e)}async function mdo(){Sae.delete(pC);try{await vae.deleteCredentials(pC)}catch(t){B.error("Failed to clear API key from storage:",t)}}import{promises as izn}from"node:fs";var Tae=class t{responses;callCounter=0;userTier;userTierName;paidTier;constructor(e){this.responses=e}static async fromFile(e){let n=(await izn.readFile(e,"utf-8")).split(`
|
|
1217
1217
|
`).filter(o=>o.trim()!=="").map(o=>JSON.parse(o));return new t(n)}getNextResponse(e,r){let n=this.responses[this.callCounter++];if(!n)throw new Error(`No more mock responses for ${e}, got request:
|
|
1218
1218
|
`+Mr(r));if(n.method!==e)throw new Error(`Unexpected response type, next response was for ${n.method} but expected ${e}`);return n.response}async generateContent(e,r,n){return Object.setPrototypeOf(this.getNextResponse("generateContent",e),d3.prototype)}async generateContentStream(e,r,n){let o=this.getNextResponse("generateContentStream",e);async function*s(){for(let c of o)yield Object.setPrototypeOf(c,d3.prototype)}return s()}async countTokens(e){return this.getNextResponse("countTokens",e)}async embedContent(e){return Object.setPrototypeOf(this.getNextResponse("embedContent",e),CKe.prototype)}};function hYt(t){let e={};if(!t)return e;for(let r of t.split(/,(?=\s*[^,:]+:)/)){let n=r.trim();if(!n)continue;let o=n.indexOf(":");if(o===-1)continue;let s=n.slice(0,o).trim(),c=n.slice(o+1).trim();s&&(e[s]=c)}return e}var ozn="terminal";function gYt(){let t=process.env.GEMINI_CLI_SURFACE||process.env.SURFACE;if(t)return t;let e=BI();return e.name!=="vscode"||process.env.TERM_PROGRAM==="vscode"||process.env.VSCODE_PID?e.name:process.env.GITHUB_SHA?"GitHub":ozn}import{appendFileSync as wae}from"node:fs";var Cae=class{realGenerator;filePath;constructor(e,r){this.realGenerator=e,this.filePath=r}get userTier(){return this.realGenerator.userTier}get userTierName(){return this.realGenerator.userTierName}async generateContent(e,r,n){let o=await this.realGenerator.generateContent(e,r,n),s={method:"generateContent",response:{candidates:o.candidates,usageMetadata:o.usageMetadata}};return wae(this.filePath,`${Mr(s)}
|
|
@@ -2895,7 +2895,7 @@ When adding a memory, route it to the right store:
|
|
|
2895
2895
|
# Insufficient context
|
|
2896
2896
|
If you find that you have insufficient context to read or modify the memories as described,
|
|
2897
2897
|
reply with what you need, and exit. Do not search the codebase for the missing context.
|
|
2898
|
-
`.trim();return{kind:"local",name:"save_memory",displayName:"Memory Manager",description:"Writes and reads memory, preferences or facts across ALL future sessions. Use this for recurring instructions like coding styles or tool aliases.",inputConfig:{inputSchema:{type:"object",properties:{request:{type:"string",description:'The memory operation to perform. Examples: "Remember that I prefer tabs over spaces", "Clean up stale memories", "De-duplicate my memories", "Organize my memories".'}},required:["request"]}},outputConfig:{outputName:"result",description:"A summary of the memory operations performed.",schema:REi},modelConfig:{model:Ex},toolConfig:{tools:[Ti,Xl,Kl,bx,Jl,Mi,Vo]},get promptConfig(){return{systemPrompt:n(),query:`${r()}\${request}`}},runConfig:{maxTimeMinutes:5,maxTurns:10}}};var sh=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 _fr=6e4;async function ov(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=YA();try{let{stdout:n}=await tc(r.executable,[...r.argsPrefix,e],{signal:AbortSignal.timeout(_fr),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 ${_fr/1e3} seconds`):n}}return t}function Efr(t){return t.startsWith("$")||t.startsWith("!")}var PEi="X-API-Key",hpe=class extends sh{config;type="apiKey";resolvedKey;headerName;constructor(e){super(),this.config=e,this.headerName=e.name??PEi}async initialize(){Efr(this.config.key)?(this.resolvedKey=await ov(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>=sh.MAX_AUTH_RETRIES))return this.authRetryCount++,B.debug("[ApiKeyAuthProvider] Re-resolving API key after auth failure"),this.resolvedKey=await ov(this.config.key),this.headers()}};var gpe=class extends sh{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 ov(e.token):"username"in e?(this.resolvedUsername=await ov(e.username),this.resolvedPassword=await ov(e.password)):this.resolvedValue=await ov(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>=sh.MAX_AUTH_RETRIES)return;B.debug("[HttpAuthProvider] Re-resolving values after auth failure"),await this.initialize()}return super.shouldRetryWithHeaders(e,r)}};var bfr=Fe(hs(),1);var WC=class extends Error{constructor(e){super(e),this.name="ResourceMismatchError"}},pD=5*60*1e3,Bs=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 WC(`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 WC)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 WC(`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 vfr=/^(.*\.)?run\.app$/,NEi=[/^.+\.googleapis\.com$/,vfr],mpe=class extends sh{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(vfr.test(n)&&(this.useIdToken=!0),this.audience=n,!this.useIdToken&&!NEi.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 bfr.GoogleAuth({scopes:s})}async initialize(){}async headers(){if(this.cachedToken&&this.tokenExpiryTime&&Date.now()<this.tokenExpiryTime-pD)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=Bs.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>=sh.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 sv=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 mpe(n,e.targetUrl);return await s.initialize(),s}case"apiKey":{let s=new hpe(n);return await s.initialize(),s}case"http":{let s=new gpe(n);return await s.initialize(),s}case"oauth2":{let{OAuth2AuthProvider:s}=await import("./oauth2-provider-7WYWCO22.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 zm=class extends Error{userMessage;agentName;constructor(e,r,n,o){super(r,o),this.name="A2AAgentError",this.agentName=e,this.userMessage=n}},$$e=class extends zm{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"}},ype=class extends zm{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}},Ape=class extends zm{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}},_pe=class extends zm{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 kEi(t){return typeof t=="object"&&t!==null}function DEi(t){let e=[],r=t,n=0,o=10;for(;r&&n<o;){if(kEi(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 Sfr(t,e,r){let n=DEi(r);return/\b(ECONNREFUSED|ENOTFOUND|EHOSTUNREACH|ETIMEDOUT)\b/i.test(n)?new _pe(t,e,r):/\b404\b|\bnot[\s_-]?found\b/i.test(n)?new $$e(t,e):/\b401\b|unauthorized/i.test(n)?new ype(t,e,401):/\b403\b|forbidden/i.test(n)?new ype(t,e,403):new _pe(t,e,r)}function H$e(t){return`${t.name}-config`}var Epe=class{config;agents=new Map;allDefinitions=new Map;builtInAgents=new Set;constructor(e){this.config=e}async initialize(){Ee.on(Nr.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(){this.config.getA2AClientManager()?.clearCache(),await this.config.reloadAgents(),this.agents.clear(),this.allDefinitions.clear(),await this.loadAgents(),Ee.emitAgentsRefreshed()}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(Nr.ModelChanged,this.onModelChanged)}async loadAgents(){if(this.agents.clear(),this.allDefinitions.clear(),this.loadBuiltInAgents(),!this.config.isAgentsEnabled())return;let e=pr.getUserAgentsDir(),r=await Q$e(e);for(let s of r.errors)B.warn(`[AgentRegistry] Error loading user agent: ${s.message}`),Ee.emitFeedback("error",`Agent loading error: ${s.message}`);await Promise.allSettled(r.agents.map(async s=>{try{await this.registerAgent(s)}catch(c){B.warn(`[AgentRegistry] Error registering user agent "${s.name}":`,c),Ee.emitFeedback("error",`Error registering user agent "${s.name}": ${c instanceof Error?c.message:String(c)}`)}}));let n=this.config.getFolderTrust(),o=this.config.isTrustedFolder();if(!n||o){let s=this.config.storage.getProjectAgentsDir(),c=await Q$e(s);for(let p of c.errors)Ee.emitFeedback("error",`Agent loading error: ${p.message}`);let u=this.config.getAcknowledgedAgentsService(),d=this.config.getProjectRoot(),l=[],a=[];for(let p of c.agents){if(p.kind==="remote"&&(p.metadata||(p.metadata={}),p.metadata.hash=p.agentCardUrl??(p.agentCardJson?Tfr.createHash("sha256").update(p.agentCardJson).digest("hex"):void 0)),!p.metadata?.hash){a.push(p);continue}await u.isAcknowledged(d,p.name,p.metadata.hash)?a.push(p):l.push(p)}l.length>0&&Ee.emitAgentsDiscovered(l),await Promise.allSettled(a.map(async p=>{try{await this.registerAgent(p)}catch(f){B.warn(`[AgentRegistry] Error registering project agent "${p.name}":`,f),Ee.emitFeedback("error",`Error registering project agent "${p.name}": ${f instanceof Error?f.message:String(f)}`)}}))}else Ee.emitFeedback("info","Skipping project agents due to untrusted folder. To enable, ensure that the project root is trusted.");for(let s of this.config.getExtensions())s.isActive&&s.agents&&await Promise.allSettled(s.agents.map(async c=>{try{await this.registerAgent(c)}catch(u){B.warn(`[AgentRegistry] Error registering extension agent "${c.name}":`,u),Ee.emitFeedback("error",`Error registering extension agent "${c.name}": ${u instanceof Error?u.message:String(u)}`)}}));this.config.getDebugMode()&&B.log(`[AgentRegistry] Loaded with ${this.agents.size} agents.`)}loadBuiltInAgents(){let e=jue(this.config);this.builtInAgents.add(e.name),this.registerLocalAgent(e);let r=hfr(this.config);this.builtInAgents.add(r.name),this.registerLocalAgent(r);let n=gfr(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=fpe(this.config);this.builtInAgents.add(d.name),this.registerLocalAgent(d)}}if(this.config.isMemoryManagerEnabled()){this.registerLocalAgent(Afr(this.config));try{let s=pr.getGlobalGeminiDir();this.config.getWorkspaceContext().addDirectory(s)}catch(s){B.warn("[AgentRegistry] Could not add global .gemini directory to workspace:",s)}}}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){e.kind==="local"?this.registerLocalAgent(e):e.kind==="remote"&&await this.registerRemoteAgent(e)}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}r.removeRulesForTool(e.name,"AgentRegistry (Dynamic)"),r.addRule({toolName:e.name,decision:e.kind==="local"?st.ALLOW:st.ASK_USER,priority:oq,source:"AgentRegistry (Dynamic)"})}}isAgentEnabled(e,r){let o=!(e.experimental===!0);return r&&r.enabled!==void 0&&(o=r.enabled),o}async registerRemoteAgent(e){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 r=this.config.getAgentsSettings().overrides?.[e.name];if(!this.isAgentEnabled(e,r)){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 n=e;n.originalDescription===void 0&&(n.originalDescription=n.description);try{let o=this.config.getA2AClientManager();if(!o){B.warn(`[AgentRegistry] Skipping remote agent '${e.name}': A2AClientManager is not available.`);return}let s=npe(n),c;if(e.auth){let p=await sv.create({authConfig:e.auth,agentName:e.name,targetUrl:s,agentCardUrl:n.agentCardUrl});if(!p)throw new Error(`Failed to create auth provider for agent '${e.name}'`);c=p}let u=await o.loadAgent(n.name,rpe(n),c);if(u.securitySchemes){let p=sv.validateAuthConfig(e.auth,u.securitySchemes);if(!p.valid&&p.diff){let f=sv.describeRequiredAuth(u.securitySchemes),g=new Ape(e.name,f,p.diff.missingConfig);Ee.emitFeedback("warning",`[${e.name}] Agent requires authentication: ${f}`),B.warn(`[AgentRegistry] ${g.message}`)}}let d=n.originalDescription,l=u.description,a=[];if(d?.trim()&&a.push(`User Description: ${d.trim()}`),l?.trim()&&a.push(`Agent Description: ${l.trim()}`),u.skills&&u.skills.length>0){let p=u.skills.map(f=>`${f.name}: ${f.description||"No description provided"}`).join(`
|
|
2898
|
+
`.trim();return{kind:"local",name:"save_memory",displayName:"Memory Manager",description:"Writes and reads memory, preferences or facts across ALL future sessions. Use this for recurring instructions like coding styles or tool aliases.",inputConfig:{inputSchema:{type:"object",properties:{request:{type:"string",description:'The memory operation to perform. Examples: "Remember that I prefer tabs over spaces", "Clean up stale memories", "De-duplicate my memories", "Organize my memories".'}},required:["request"]}},outputConfig:{outputName:"result",description:"A summary of the memory operations performed.",schema:REi},modelConfig:{model:Ex},toolConfig:{tools:[Ti,Xl,Kl,bx,Jl,Mi,Vo]},get promptConfig(){return{systemPrompt:n(),query:`${r()}\${request}`}},runConfig:{maxTimeMinutes:5,maxTurns:10}}};var sh=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 _fr=6e4;async function ov(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=YA();try{let{stdout:n}=await tc(r.executable,[...r.argsPrefix,e],{signal:AbortSignal.timeout(_fr),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 ${_fr/1e3} seconds`):n}}return t}function Efr(t){return t.startsWith("$")||t.startsWith("!")}var PEi="X-API-Key",hpe=class extends sh{config;type="apiKey";resolvedKey;headerName;constructor(e){super(),this.config=e,this.headerName=e.name??PEi}async initialize(){Efr(this.config.key)?(this.resolvedKey=await ov(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>=sh.MAX_AUTH_RETRIES))return this.authRetryCount++,B.debug("[ApiKeyAuthProvider] Re-resolving API key after auth failure"),this.resolvedKey=await ov(this.config.key),this.headers()}};var gpe=class extends sh{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 ov(e.token):"username"in e?(this.resolvedUsername=await ov(e.username),this.resolvedPassword=await ov(e.password)):this.resolvedValue=await ov(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>=sh.MAX_AUTH_RETRIES)return;B.debug("[HttpAuthProvider] Re-resolving values after auth failure"),await this.initialize()}return super.shouldRetryWithHeaders(e,r)}};var bfr=Fe(hs(),1);var WC=class extends Error{constructor(e){super(e),this.name="ResourceMismatchError"}},pD=5*60*1e3,Bs=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 WC(`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 WC)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 WC(`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 vfr=/^(.*\.)?run\.app$/,NEi=[/^.+\.googleapis\.com$/,vfr],mpe=class extends sh{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(vfr.test(n)&&(this.useIdToken=!0),this.audience=n,!this.useIdToken&&!NEi.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 bfr.GoogleAuth({scopes:s})}async initialize(){}async headers(){if(this.cachedToken&&this.tokenExpiryTime&&Date.now()<this.tokenExpiryTime-pD)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=Bs.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>=sh.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 sv=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 mpe(n,e.targetUrl);return await s.initialize(),s}case"apiKey":{let s=new hpe(n);return await s.initialize(),s}case"http":{let s=new gpe(n);return await s.initialize(),s}case"oauth2":{let{OAuth2AuthProvider:s}=await import("./oauth2-provider-HTOFGZYE.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 zm=class extends Error{userMessage;agentName;constructor(e,r,n,o){super(r,o),this.name="A2AAgentError",this.agentName=e,this.userMessage=n}},$$e=class extends zm{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"}},ype=class extends zm{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}},Ape=class extends zm{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}},_pe=class extends zm{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 kEi(t){return typeof t=="object"&&t!==null}function DEi(t){let e=[],r=t,n=0,o=10;for(;r&&n<o;){if(kEi(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 Sfr(t,e,r){let n=DEi(r);return/\b(ECONNREFUSED|ENOTFOUND|EHOSTUNREACH|ETIMEDOUT)\b/i.test(n)?new _pe(t,e,r):/\b404\b|\bnot[\s_-]?found\b/i.test(n)?new $$e(t,e):/\b401\b|unauthorized/i.test(n)?new ype(t,e,401):/\b403\b|forbidden/i.test(n)?new ype(t,e,403):new _pe(t,e,r)}function H$e(t){return`${t.name}-config`}var Epe=class{config;agents=new Map;allDefinitions=new Map;builtInAgents=new Set;constructor(e){this.config=e}async initialize(){Ee.on(Nr.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(){this.config.getA2AClientManager()?.clearCache(),await this.config.reloadAgents(),this.agents.clear(),this.allDefinitions.clear(),await this.loadAgents(),Ee.emitAgentsRefreshed()}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(Nr.ModelChanged,this.onModelChanged)}async loadAgents(){if(this.agents.clear(),this.allDefinitions.clear(),this.loadBuiltInAgents(),!this.config.isAgentsEnabled())return;let e=pr.getUserAgentsDir(),r=await Q$e(e);for(let s of r.errors)B.warn(`[AgentRegistry] Error loading user agent: ${s.message}`),Ee.emitFeedback("error",`Agent loading error: ${s.message}`);await Promise.allSettled(r.agents.map(async s=>{try{await this.registerAgent(s)}catch(c){B.warn(`[AgentRegistry] Error registering user agent "${s.name}":`,c),Ee.emitFeedback("error",`Error registering user agent "${s.name}": ${c instanceof Error?c.message:String(c)}`)}}));let n=this.config.getFolderTrust(),o=this.config.isTrustedFolder();if(!n||o){let s=this.config.storage.getProjectAgentsDir(),c=await Q$e(s);for(let p of c.errors)Ee.emitFeedback("error",`Agent loading error: ${p.message}`);let u=this.config.getAcknowledgedAgentsService(),d=this.config.getProjectRoot(),l=[],a=[];for(let p of c.agents){if(p.kind==="remote"&&(p.metadata||(p.metadata={}),p.metadata.hash=p.agentCardUrl??(p.agentCardJson?Tfr.createHash("sha256").update(p.agentCardJson).digest("hex"):void 0)),!p.metadata?.hash){a.push(p);continue}await u.isAcknowledged(d,p.name,p.metadata.hash)?a.push(p):l.push(p)}l.length>0&&Ee.emitAgentsDiscovered(l),await Promise.allSettled(a.map(async p=>{try{await this.registerAgent(p)}catch(f){B.warn(`[AgentRegistry] Error registering project agent "${p.name}":`,f),Ee.emitFeedback("error",`Error registering project agent "${p.name}": ${f instanceof Error?f.message:String(f)}`)}}))}else Ee.emitFeedback("info","Skipping project agents due to untrusted folder. To enable, ensure that the project root is trusted.");for(let s of this.config.getExtensions())s.isActive&&s.agents&&await Promise.allSettled(s.agents.map(async c=>{try{await this.registerAgent(c)}catch(u){B.warn(`[AgentRegistry] Error registering extension agent "${c.name}":`,u),Ee.emitFeedback("error",`Error registering extension agent "${c.name}": ${u instanceof Error?u.message:String(u)}`)}}));this.config.getDebugMode()&&B.log(`[AgentRegistry] Loaded with ${this.agents.size} agents.`)}loadBuiltInAgents(){let e=jue(this.config);this.builtInAgents.add(e.name),this.registerLocalAgent(e);let r=hfr(this.config);this.builtInAgents.add(r.name),this.registerLocalAgent(r);let n=gfr(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=fpe(this.config);this.builtInAgents.add(d.name),this.registerLocalAgent(d)}}if(this.config.isMemoryManagerEnabled()){this.registerLocalAgent(Afr(this.config));try{let s=pr.getGlobalGeminiDir();this.config.getWorkspaceContext().addDirectory(s)}catch(s){B.warn("[AgentRegistry] Could not add global .gemini directory to workspace:",s)}}}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){e.kind==="local"?this.registerLocalAgent(e):e.kind==="remote"&&await this.registerRemoteAgent(e)}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}r.removeRulesForTool(e.name,"AgentRegistry (Dynamic)"),r.addRule({toolName:e.name,decision:e.kind==="local"?st.ALLOW:st.ASK_USER,priority:oq,source:"AgentRegistry (Dynamic)"})}}isAgentEnabled(e,r){let o=!(e.experimental===!0);return r&&r.enabled!==void 0&&(o=r.enabled),o}async registerRemoteAgent(e){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 r=this.config.getAgentsSettings().overrides?.[e.name];if(!this.isAgentEnabled(e,r)){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 n=e;n.originalDescription===void 0&&(n.originalDescription=n.description);try{let o=this.config.getA2AClientManager();if(!o){B.warn(`[AgentRegistry] Skipping remote agent '${e.name}': A2AClientManager is not available.`);return}let s=npe(n),c;if(e.auth){let p=await sv.create({authConfig:e.auth,agentName:e.name,targetUrl:s,agentCardUrl:n.agentCardUrl});if(!p)throw new Error(`Failed to create auth provider for agent '${e.name}'`);c=p}let u=await o.loadAgent(n.name,rpe(n),c);if(u.securitySchemes){let p=sv.validateAuthConfig(e.auth,u.securitySchemes);if(!p.valid&&p.diff){let f=sv.describeRequiredAuth(u.securitySchemes),g=new Ape(e.name,f,p.diff.missingConfig);Ee.emitFeedback("warning",`[${e.name}] Agent requires authentication: ${f}`),B.warn(`[AgentRegistry] ${g.message}`)}}let d=n.originalDescription,l=u.description,a=[];if(d?.trim()&&a.push(`User Description: ${d.trim()}`),l?.trim()&&a.push(`Agent Description: ${l.trim()}`),u.skills&&u.skills.length>0){let p=u.skills.map(f=>`${f.name}: ${f.description||"No description provided"}`).join(`
|
|
2899
2899
|
`);a.push(`Skills:
|
|
2900
2900
|
${p}`)}a.length>0&&(e.description=a.join(`
|
|
2901
2901
|
`)),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(o){o instanceof zm?Ee.emitFeedback("error",`[${e.name}] ${o.userMessage}`):Ee.emitFeedback("error",`[${e.name}] Failed to load remote agent: ${o instanceof Error?o.message:String(o)}`),B.warn(`[AgentRegistry] Error loading A2A agent "${e.name}":`,o)}}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?nD.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(H$e(e),{modelConfig:o}),o.model&&Vs(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)}};import*as fD from"node:fs/promises";import*as wfr from"node:path";var bpe=class{acknowledgedAgents={};loaded=!1;async load(){if(this.loaded)return;let e=pr.getAcknowledgedAgentsPath();try{let r=await fD.readFile(e,"utf-8");this.acknowledgedAgents=JSON.parse(r)}catch(r){(!Gt(r)||r.code!=="ENOENT")&&B.error("Failed to load acknowledged agents:",Se(r)),this.acknowledgedAgents={}}this.loaded=!0}async save(){let e=pr.getAcknowledgedAgentsPath();try{let r=wfr.dirname(e);await fD.mkdir(r,{recursive:!0}),await fD.writeFile(e,JSON.stringify(this.acknowledgedAgents,null,2),"utf-8")}catch(r){B.error("Failed to save acknowledged agents:",Se(r))}}async isAcknowledged(e,r,n){await this.load();let o=this.acknowledgedAgents[e];return o?o[r]===n:!1}async acknowledge(e,r,n){await this.load(),this.acknowledgedAgents[e]||(this.acknowledgedAgents[e]={}),this.acknowledgedAgents[e][r]=n,await this.save()}};function vpe(t,e){let r=/\$\{(\w+)\}/g,n=new Set(Array.from(t.matchAll(r),c=>c[1])),o=new Set(Object.keys(e)),s=Array.from(n).filter(c=>!o.has(c));if(s.length>0)throw new Error(`Template validation failed: Missing required input parameters: ${s.join(", ")}. Available inputs: ${Object.keys(e).join(", ")}`);return t.replace(r,(c,u)=>String(e[u]))}import{AsyncLocalStorage as LEi}from"node:async_hooks";var Cfr=new LEi;function z$e(t,e){return Cfr.run(t,e)}function Spe(){return Cfr.getStore()}var xfr=Fe(Xse(),1);function Rj(t){return typeof t=="object"&&t!==null&&"callId"in t&&"responseParts"in t}function aBo(t){let{displayName:e,status:r,approvalMode:n,hasResultDisplay:o,parentCallId:s}=t;if(s)return!0;switch(e){case A3:switch(r){case Be.Scheduled:case Be.Validating:case Be.Executing:case Be.AwaitingApproval:return!0;case Be.Error:return!o;default:return!1}case Iq:case Rq:return n===tr.PLAN;default:return!1}}function Pj(t,e,r=3){let n=e.map(c=>({name:c,distance:xfr.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 lBo(t,e,r){let n;aq(t)?n=[t.name,t.constructor.name]:n=[t],n.some(o=>Ch.includes(o))&&(n=[...new Set([...n,...Ch])]);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=>Ch.includes(l))&&(d===u||d.startsWith(u+" ")))return!0}return!1}var Tpe=class{messageBus;schedulerId;onTerminalCall;activeCalls=new Map;queue=[];_completedBatch=[];constructor(e,r=Qnt,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);!o||o.status===Be.Error||(this.activeCalls.set(e,this.patchCall(o,{request:{...o.request,args:r},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===Be.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:Pi.TOOL_CALLS_UPDATE,toolCalls:e,schedulerId:this.schedulerId})}isTerminalCall(e){let{status:r}=e;return r===Be.Success||r===Be.Error||r===Be.Cancelled}transitionCall(e,r,n){switch(r){case Be.Success:{if(!Rj(n))throw new Error(`Invalid data for 'success' transition (callId: ${e.request.callId})`);return this.toSuccess(e,n)}case Be.Error:{if(!Rj(n))throw new Error(`Invalid data for 'error' transition (callId: ${e.request.callId})`);return this.toError(e,n)}case Be.AwaitingApproval:{if(!n)throw new Error(`Missing data for 'awaiting_approval' transition (callId: ${e.request.callId})`);return this.toAwaitingApproval(e,n)}case Be.Scheduled:return this.toScheduled(e);case Be.Cancelled:{if(typeof n!="string"&&!Rj(n))throw new Error(`Invalid reason (string) or response for 'cancelled' transition (callId: ${e.request.callId})`);return this.toCancelled(e,n)}case Be.Validating:return this.toValidating(e);case Be.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,Be.Success);let n="startTime"in e?e.startTime:void 0;return{request:e.request,tool:e.tool,invocation:e.invocation,status:Be.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:Be.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,Be.AwaitingApproval);let n,o;return this.isEventDrivenApprovalData(r)?(o=r.correlationId,n=r.confirmationDetails):n=r,{request:e.request,tool:e.tool,status:Be.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,Be.Scheduled),{request:e.request,tool:e.tool,status:Be.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,Be.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??DKe(u.fileDiff)})}let s;if(e.status===Be.Executing&&e.liveOutput&&(s=e.liveOutput),Rj(r)){let u={...r};return u.resultDisplay||(u.resultDisplay=o??s),{request:e.request,tool:e.tool,invocation:e.invocation,status:Be.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:Be.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===Be.AwaitingApproval}patchCall(e,r){return{...e,...r}}toValidating(e){return this.validateHasToolAndInvocation(e,Be.Validating),{request:e.request,tool:e.tool,status:Be.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,Be.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:Be.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 MEi}from"node:events";import{randomUUID as BEi}from"node:crypto";async function UEi(t,e,r){if(r.aborted)throw new Error("Operation cancelled");try{for await(let[n]of MEi(t,Pi.TOOL_CONFIRMATION_RESPONSE,{signal:r})){let o=n;if(o.correlationId===e)return{outcome:o.outcome??(o.confirmed?Qt.ProceedOnce:Qt.Cancel),payload:o.payload}}}catch(n){throw r.aborted||n.name==="AbortError"?new Error("Operation cancelled"):n}throw new Error("Operation cancelled")}async function W$e(t,e,r){let{state:n,onWaitingForConfirmation:o}=r,s=t.request.callId,c=Qt.ModifyWithEditor,u;for(;c===Qt.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=Qt.ProceedOnce;break}r.systemMessage&&(a.systemMessage=r.systemMessage),await FEi(r,a);let p=BEi(),f=a;u=f;let g="ideConfirmation"in a?a.ideConfirmation:void 0;n.updateStatus(s,Be.AwaitingApproval,{confirmationDetails:f,correlationId:p}),o?.(!0);let y=await qEi(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===Qt.ModifyWithEditor){let _=await jEi(r,t,e);_.error&&Ee.emitFeedback("error",_.error)}else y.payload&&"newContent"in y.payload&&(await QEi(r,t,y.payload,e),c=Qt.ProceedOnce)}return{outcome:c,lastDetails:u}}async function FEi(t,e){t.config.getHookSystem()&&await t.config.getHookSystem()?.fireToolNotificationEvent({...e,onConfirm:async()=>{}})}async function jEi(t,e,r){let{state:n,modifier:o,getPreferredEditor:s}=t,c=s(),u=await A6t(c,r);if(!u)return{error:f6t};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 QEi(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 qEi(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=UEi(t,e,s);if(!n)return await u;let d=n.then(l=>({outcome:l.status==="accepted"?Qt.ProceedOnce:Qt.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 Ofr(t,e){return{errorMessage:`Tool execution denied by policy.${e?.denyMessage?` ${e.denyMessage}`:""}`,errorType:Me.POLICY_VIOLATION}}async function Ifr(t,e,r){let n=t.tool instanceof di?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===st.ASK_USER&&t.request.isClientInitiated&&!t.request.args?.additional_permissions)return{decision:st.ALLOW,rule:s.rule};if(c===st.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 Rfr(t,e,r,n,o,s){if(GEi(t,e)){n.config.setApprovalMode(tr.AUTO_EDIT);return}let c,u,d=n.config.getApprovalMode();if(e===Qt.ProceedAlways||e===Qt.ProceedAlwaysTool||e===Qt.ProceedAlwaysServer||e===Qt.ProceedAlwaysAndSave){let l=Jge.indexOf(d);l!==-1&&(u=Jge.slice(l))}if(e===Qt.ProceedAlwaysAndSave&&(n.config&&n.config.isTrustedFolder()&&n.config.getWorkspacePoliciesDir()!==void 0?c="workspace":c="user"),r?.type==="mcp"){await $Ei(t,e,r,o,c,u);return}await VEi(t,e,r,o,c,s,n.config,u)}function GEi(t,e){return e===Qt.ProceedAlways&&y3.has(t.name)}async function VEi(t,e,r,n,o,s,c,u){if(e===Qt.ProceedAlways||e===Qt.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?Go(r.filePath,c.getTargetDir()):r.filePath;d.argsPattern=Lb(l)}await n.publish({type:Pi.UPDATE_POLICY,toolName:t.name,persist:e===Qt.ProceedAlwaysAndSave,persistScope:o,modes:u,...d})}}async function $Ei(t,e,r,n,o,s){if(!(e===Qt.ProceedAlways||e===Qt.ProceedAlwaysTool||e===Qt.ProceedAlwaysServer||e===Qt.ProceedAlwaysAndSave))return;let u=t.name,d=e===Qt.ProceedAlwaysAndSave;e===Qt.ProceedAlwaysServer&&(u=Qv(r.serverName,"*")),await n.publish({type:Pi.UPDATE_POLICY,toolName:u,mcpName:r.serverName,persist:d,persistScope:o,modes:s})}function Y$e(t,e){if(!(t instanceof tXe))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 Pfr(t,e,r,n,o,s,c,u,d){let l=t.params||{},a=!1,p=[],f=c?Y$e(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:Me.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:Me.EXECUTION_FAILED,message:E.reason}};if(_ instanceof mA){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:Me.INVALID_TOOL_PARAMS,message:String(v)}}}}}}let y=await t.execute(r,o,s);if(a){let _=`
|