@sourcegraph/amp 0.0.1764115312-g9a6608 → 0.0.1764129854-ge5da8d

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/main.js +10 -10
  2. package/package.json +1 -1
package/dist/main.js CHANGED
@@ -2228,7 +2228,7 @@ IMPORTANT: Always use the ${z7} tool to plan and track tasks throughout the conv
2228
2228
 
2229
2229
  `});class FM1{async*stream({model:J,thread:Q,buildSystemPromptDeps:Y,signal:X,agentMode:G,clientRequestId:Z}){let{systemPrompt:q,tools:V}=await WQ(Y,Q,{enableTodos:!0,enableTask:!0,enableOracle:!0},{model:J,provider:"vertexai",agentMode:G??"smart"},X),K=V.map((U)=>c7(J,U)),W=UM1(Q),H=NM1(J,W,K,q.map((U)=>U.text).join(`
2230
2230
 
2231
- `),Q,{configService:Y.configService},X,bV(Q)?.messageId,Z),z;for await(let U of H)if(z=hb4(z,U),z)yield bb4(z)}}function UM1(J){let{summaryBlock:Q,index:Y}=eG(J)??{summaryBlock:void 0,index:0},X=[];if(Q&&Q.summary.type==="message")X.push({role:"model",parts:[{text:Q.summary.summary.trimEnd()}]});for(let G=Y+(Q?1:0);G<J.messages.length;G++){let Z=J.messages[G];if(!Z)continue;switch(Z.role){case"user":{let q=vb4(Z,J);if(q.length===0)continue;X.push({role:"user",parts:q});break}case"assistant":{let q=Z.content.filter((W)=>{if(W.type==="tool_use"&&!W.complete)return!1;return!0}),V=$Q(J);for(let W of q)if(W.type==="tool_use"){if(!V.get(W.id)?.run)throw Error(`(bug) corresponding tool_result not found for tool_use (id=${W.id}, name=${W.name})`)}if(Z.nativeMessage?.type==="vertexai"){let W=Z.nativeMessage.message.candidates?.[0]?.content,H={role:W?.role??"model",parts:W?.parts??[]};X.push(c8(H));break}if(q.length===0)break;let K=fb4(q);if(K.length>0)X.push({role:"model",parts:K});break}case"info":{let q=[];for(let V of Z.content)if(V.type==="manual_bash_invocation"){let K=oU(V);q.push(...K.map((W)=>({text:W.text})))}else if(V.type==="text"&&V.text.trim().length>0)q.push({text:V.text});if(q.length>0)X.push({role:"user",parts:q});break}}}return X}function BM1(J){let Q=Object.values(z8).find((Y)=>Y.provider===l8.VERTEXAI&&Y.name===J);if(Q===void 0)return x.warn(`Unknown gemini model ${J}`),{...z8.GEMINI_2_5_PRO,name:J,displayName:J};return Q}async function*NM1(J,Q,Y,X,G,Z,q,V,K){let W=BM1(J),H=await Z.configService.getLatest(q),z=await tx0(H,{threadMeta:G,messageId:V,clientRequestId:K}),U={model:W.name,contents:c8(Q),config:{seed:Date.now()%1e4,tools:sx0(Y),systemInstruction:X,maxOutputTokens:W.maxOutputTokens,temperature:1,thinkingConfig:{includeThoughts:!0,thinkingLevel:H.settings["gemini.thinkingLevel"]==="low"?mx.LOW:H.settings["gemini.thinkingLevel"]==="high"?mx.HIGH:void 0},abortSignal:q}},N=await z.models.generateContentStream(U),M;for await(let L of N)M=L,yield L;return{model:J,"~debugParamsUsed":{model:W,streamParams:U},"~debugUsage":{model:J,maxInputTokens:W.contextWindow-W.maxOutputTokens,inputTokens:0,outputTokens:(M?.usageMetadata?.candidatesTokenCount??0)+(M?.usageMetadata?.thoughtsTokenCount??0),totalInputTokens:M?.usageMetadata?.promptTokenCount??0,cacheCreationInputTokens:(M?.usageMetadata?.promptTokenCount??0)-(M?.usageMetadata?.cachedContentTokenCount??0),cacheReadInputTokens:M?.usageMetadata?.cachedContentTokenCount??0,credits:0}}}async function Rs(J,Q,Y,X,G,Z,q,V){let K=BM1(J),H=await(await tx0(G,{threadMeta:X,clientRequestId:V})).models.generateContent({model:K.name,contents:c8(Q),config:{tools:sx0(Y),seed:Date.now()%1e4,temperature:0.1,maxOutputTokens:K.maxOutputTokens,abortSignal:Z,...q}});return{message:H,"~debugUsage":{model:K.name,maxInputTokens:K.contextWindow-K.maxOutputTokens,inputTokens:0,outputTokens:(H.usageMetadata?.candidatesTokenCount??0)+(H.usageMetadata?.thoughtsTokenCount??0),totalInputTokens:H.usageMetadata?.promptTokenCount??0,cacheCreationInputTokens:(H.usageMetadata?.promptTokenCount??0)-(H.usageMetadata?.cachedContentTokenCount??0),cacheReadInputTokens:H.usageMetadata?.cachedContentTokenCount??0,credits:0}}}function sx0(J){if(J.length===0)return[];return[{functionDeclarations:[...J.map(yb4)]}]}function yb4(J){return{name:J.name,description:J.description??"",parameters:zM1(J.inputSchema)}}function zM1(J){let Q={},Y=xb4[J.type??"any"];if(Y)Q.type=Y;if(J.description)Q.description=J.description;if(J.required)Q.required=J.required;let X=J.examples;if(Array.isArray(X)&&X.length>0)Q.example=X[0];if(J.properties)Q.properties=Object.fromEntries(Object.entries(J.properties).map(([G,Z])=>[G,zM1(Z)]));if(J.items)Q.items=zM1(J.items);return Q}async function tx0(J,Q){let{settings:Y,secrets:X}=J,{url:G}=Y,Z=await X.getToken("apiKey",G);if(!Z)throw Error("API key not found. You must provide an API key in settings.");let q={GOOGLE_CLOUD_PROJECT:process.env.GOOGLE_CLOUD_PROJECT,GCLOUD_PROJECT:process.env.GCLOUD_PROJECT,GOOGLE_APPLICATION_CREDENTIALS:process.env.GOOGLE_APPLICATION_CREDENTIALS};delete process.env.GOOGLE_CLOUD_PROJECT,delete process.env.GCLOUD_PROJECT,delete process.env.GOOGLE_APPLICATION_CREDENTIALS;let V=new FB1({apiKey:"placeholder",vertexai:!0,googleAuthOptions:{},httpOptions:{baseUrl:new URL("/api/provider/google",G).toString(),headers:{Authorization:"Bearer "+Z,[RY]:"amp.chat",...Q?.messageId!=null?{[JZ]:String(Q.messageId)}:{},...Q?.clientRequestId!=null?{[CY]:Q.clientRequestId}:{},...jY(Q?.threadMeta)}}});for(let[K,W]of Object.entries(q))if(W!==void 0)process.env[K]=W;return V}function vb4(J,Q){let Y=[];if(J.fileMentions&&J.fileMentions.files.length>0)Y.push({text:HZ(J.fileMentions)});if(J.userState)Y.push({text:WK(J.userState)});for(let X of J.content)if(X.type==="text")Y.push({text:X.text});else if(X.type==="image"){if(X.source.type==="base64"&&"mediaType"in X.source&&"data"in X.source)Y.push({inlineData:{mimeType:X.source.mediaType,data:X.source.data}});else if(X.source.type==="url"&&"url"in X.source)Y.push({text:`[Image URL: ${X.source.url}]`})}else if(X.type==="tool_result"){let G={};if(X.run.status==="done")G.output=X.run.result;else if(X.run.status==="error")G.error=X.run.error?.message??"Error executing tool";else G.error=`Tool status: ${X.run.status}`;let Z,[,q]=X.toolUseID.split("__");if(q)Z=q;else for(let K of Q.messages)if(K.role==="assistant"){for(let W of K.content)if(W.type==="tool_use"&&W.id===X.toolUseID){Z=W.name;break}if(Z)break}if(!Z)throw Error(`Could not find tool name for tool_result with ID: ${X.toolUseID}`);let V={name:Z,response:G};Y.push({functionResponse:V})}return Y}function fb4(J){let Q=[];for(let Y of J)if(Y.type==="text")Q.push({text:Y.text});else if(Y.type==="tool_use")Q.push({functionCall:{name:Y.name,args:Y.input??{}}});else if(Y.type==="thinking")Q.push({text:Y.thinking,thought:!0,thoughtSignature:Y.signature});else if(Y.type==="redacted_thinking")Q.push({text:"[Redacted thinking]"});return Q}function hb4(J,Q){if(!J)return Q;let Y=J.candidates&&Q.candidates?J.candidates.map((G,Z)=>{let q=Q.candidates?.[Z];if(!q)return G;return{...q,content:{role:q.content?.role??G.content?.role??"model",parts:[...G.content?.parts??[],...q.content?.parts??[]]}}}):Q.candidates,X=new RU;return Object.assign(X,{...Q,candidates:Y}),X}function bb4(J){function Q(){let G=[];for(let Z of J.candidates?.at(0)?.content?.parts??[])if(Z.text&&Z.thought){let q=G.at(-1);if(q?.type==="thinking")G[G.length-1]={type:"thinking",thinking:q.thinking+Z.text,signature:"",provider:"vertexai"};else G.push({type:"thinking",thinking:Z.text,signature:"",provider:"vertexai"})}else if(Z.text){let q=G.at(-1);if(q?.type==="text")G[G.length-1]={type:"text",text:q.text+Z.text};else G.push({type:"text",text:Z.text})}else if(Z.functionCall)G.push({type:"tool_use",complete:!0,id:Z.functionCall.id??_M(),name:Z.functionCall.name??"",input:Z.functionCall.args??{}});return G}function Y(){if(!J.usageMetadata)return;let G=BM1(J.modelVersion??"");return{model:G.name,maxInputTokens:G.contextWindow-G.maxOutputTokens,inputTokens:0,cacheReadInputTokens:J.usageMetadata?.cachedContentTokenCount??0,cacheCreationInputTokens:(J.usageMetadata?.promptTokenCount??0)-(J.usageMetadata?.cachedContentTokenCount??0),outputTokens:(J.usageMetadata?.totalTokenCount??0)-(J.usageMetadata?.promptTokenCount??0),totalInputTokens:J.usageMetadata?.promptTokenCount??0,credits:0}}function X(){let G=J.candidates?.at(0)?.finishReason,Z=J.candidates?.at(0)?.finishMessage;switch(G){case m3.STOP:{if(J.candidates?.at(0)?.content?.parts?.some((V)=>V.functionCall!==void 0))return{type:"complete",stopReason:"tool_use"};return{type:"complete",stopReason:"end_turn"}}case m3.MAX_TOKENS:return{type:"complete",stopReason:"max_tokens"};case m3.BLOCKLIST:case m3.SAFETY:case m3.RECITATION:case m3.LANGUAGE:case m3.PROHIBITED_CONTENT:case m3.IMAGE_PROHIBITED_CONTENT:case m3.IMAGE_SAFETY:case m3.SPII:case m3.OTHER:case m3.FINISH_REASON_UNSPECIFIED:case m3.NO_IMAGE:return{type:"error",error:{message:`provider refused to continue with code '${G}': ${Z}`}};case m3.UNEXPECTED_TOOL_CALL:case m3.MALFORMED_FUNCTION_CALL:return{type:"error",error:{message:`provider failed with code '${G}': ${Z}`}};case void 0:return{type:"streaming"}}}return{role:"assistant",content:Q(),state:X(),usage:Y(),nativeMessage:{type:"vertexai",message:J}}}var g99,m99,rx0,u99,xb4;var Mf=Z1(()=>{lo();lo();PY();U0();_U();gV();vH();M9();RL();D5();b5();sv();g99=z8.GEMINI_2_5_PRO.name,m99=z8.GEMINI_2_5_FLASH_LITE.name,rx0=z8.GEMINI_2_5_FLASH_LITE_PREVIEW_09_2025.name,u99=z8.GEMINI_2_5_FLASH_PREVIEW_09_2025.name;xb4={string:hQ.STRING,number:hQ.NUMBER,integer:hQ.INTEGER,boolean:hQ.BOOLEAN,object:hQ.OBJECT,array:hQ.ARRAY}});function ex0(J){return J+ ++gb4}var gb4=0;function Jv0(J){if(!J._regex)try{J._regex=new RegExp(J.pattern,J.caseInsensitive?"gi":"g")}catch(Q){x.warn("Error compiling regex",{pattern:J.id,error:Q}),J._regex=new RegExp("$^")}return J._regex}var Qv0;var Yv0=Z1(()=>{U0();Qv0=[{id:"sourcegraph-access-token-v3",category:"sourcegraph",title:"Sourcegraph Access Token (v3)",pattern:String.raw`(sgp_(?:[a-fA-F0-9]{16}|local)_[a-fA-F0-9]{40})`,keywords:["sgp_"]},{id:"sourcegraph-access-token-v2",category:"sourcegraph",title:"Sourcegraph Access Token (v2, deprecated)",pattern:String.raw`(sgp_[a-fA-F0-9]{40})`,keywords:["sgp_"]},{id:"sourcegraph-dotcom-user-gateway",category:"sourcegraph",title:"Sourcegraph Dotcom User Gateway Access Token",pattern:String.raw`(sgd_[a-fA-F0-9]{64})`,keywords:["sgd_"]},{id:"sourcegraph-license-key",category:"sourcegraph",title:"Sourcegraph License Key Token",pattern:String.raw`(slk_[a-fA-F0-9]{64})`,keywords:["slk_"]},{id:"sourcegraph-enterprise-subscription",category:"sourcegraph",title:"Sourcegraph Enterprise subscription Token",pattern:String.raw`(sgs_[a-fA-F0-9]{64})`,keywords:["sgs_"]},{id:"sourcegraph-amp",category:"sourcegraph",title:"Sourcegraph Amp Access Token",pattern:String.raw`(sgamp_user_[A-Z0-9]{26}_[a-f0-9]{64})`,keywords:["sgamp_user_"]},{id:"sourcegraph-amp-auth-bypass",category:"sourcegraph",title:"Sourcegraph Amp Auth Bypass Token",pattern:String.raw`(sgamp_user_auth-bypass_[a-zA-Z0-9_-]+)`,keywords:["sgamp_user_auth-bypass_"]},{id:"sourcegraph-workspace-token",category:"sourcegraph",title:"Sourcegraph Workspace Access Token",pattern:String.raw`(sgp_ws[a-fA-F0-9]{32}_[a-fA-F0-9]{40})`,keywords:["sgp_ws"]},{id:"github-pat",category:"github",title:"GitHub Personal Access Token",pattern:String.raw`(ghp_[0-9a-zA-Z]{36})`,keywords:["ghp_"]},{id:"github-oauth",category:"github",title:"GitHub OAuth Access Token",pattern:String.raw`(gho_[0-9a-zA-Z]{36})`,keywords:["gho_"]},{id:"github-app-token",category:"github",title:"GitHub App Token",pattern:String.raw`((ghu|ghs)_[0-9a-zA-Z]{36})`,keywords:["ghu_","ghs_"]},{id:"github-refresh-token",category:"github",title:"GitHub Refresh Token",pattern:String.raw`(ghr_[0-9a-zA-Z]{76})`,keywords:["ghr_"]},{id:"github-fine-grained-pat",category:"github",title:"GitHub Fine-grained personal access tokens",pattern:String.raw`(github_pat_[a-zA-Z0-9]{22}_[a-zA-Z0-9]{59})`,keywords:["github_pat_"]},{id:"gitlab-pat",category:"gitlab",title:"GitLab Personal Access Token",pattern:String.raw`(glpat-[0-9a-zA-Z_-]{20})`,keywords:["glpat-"]},{id:"aws-access-key-id",category:"aws",title:"AWS Access Key ID",pattern:String.raw`((A3T[A-Z0-9]|AKIA|AGPA|AIDA|AROA|AIPA|ANPA|ANVA|ASIA)[A-Z0-9]{16})`,keywords:["AKIA","AGPA","AIDA","AROA","AIPA","ANPA","ANVA","ASIA"]},{id:"hugging-face-access-token",category:"huggingface",title:"Hugging Face Access Token",pattern:String.raw`(hf_[A-Za-z0-9]{34,40})`,keywords:["hf_"]},{id:"private-key",category:"asymmetric-private-key",title:"Asymmetric Private Key",pattern:String.raw`-----\s*?BEGIN[ A-Z0-9_-]*?PRIVATE KEY( BLOCK)?\s*?-----[\s]*?([A-Za-z0-9=+/\\\\r\n][A-Za-z0-9=+/\\\\s]+)[\s]*?-----\s*?END[ A-Z0-9_-]*? PRIVATE KEY( BLOCK)?\s*?-----`,keywords:["-----"],caseInsensitive:!0},{id:"shopify-token",category:"shopify",title:"Shopify token",pattern:String.raw`(shp(ss|at|ca|pa)_[a-fA-F0-9]{32})`,keywords:["shpss_","shpat_","shpca_","shppa_"]},{id:"slack-access-token",category:"slack",title:"Slack token",pattern:String.raw`((xox[baoprs]-|xapp-|xwfp-)([0-9a-zA-Z-]{10,100}))`,keywords:["xoxb-","xoxa-","xoxp-","xoxr-","xoxs-","xoxo-","xapp-","xwfp-"]},{id:"slack-config-refresh-token",category:"slack",title:"Slack config refresh token",pattern:String.raw`(xoxe-\d-[a-zA-Z0-9]{146})`,caseInsensitive:!0,keywords:["xoxe-"]},{id:"slack-config-access-token",category:"slack",title:"Slack config access token",pattern:String.raw`(xoxe.xox[bp]-\d-[A-Z0-9]{163,166})`,caseInsensitive:!0,keywords:["xoxe.xoxb-","xoxe.xoxp-"]},{id:"slack-web-hook",category:"slack",title:"Slack Webhook",pattern:String.raw`(https:\/\/hooks\.slack\.com\/(services|triggers|workflows)\/[A-Za-z0-9+\/]{43,56})`,caseInsensitive:!0,keywords:["hooks.slack.com"]},{id:"stripe-secret-token",category:"stripe",title:"Stripe Secret Key",pattern:String.raw`(sk_(test|live)_[0-9a-z]{10,99})`,keywords:["sk_test_","sk_live_"],caseInsensitive:!0},{id:"supabase-service-key",category:"supabase",title:"Supabase Service Key",pattern:String.raw`(sbp_[a-fA-F0-9]{40})`,keywords:["sbp_"]},{id:"pypi-upload-token",category:"pypi",title:"PyPI upload token",pattern:String.raw`(pypi-AgEIcHlwaS5vcmc[A-Za-z0-9_-]{50,1000})`,keywords:["pypi-AgEIcHlwaS5vcmc"]},{id:"gcp-service-account",category:"google",title:"Google (GCP) Service-account",pattern:String.raw`("type": "service_account")`,keywords:['"type": "service_account"']},{id:"heroku-api-key",category:"heroku",title:"Heroku API Key",pattern:String.raw`(?:heroku[a-z0-9_ .,-]{0,25})(?:=|>|:=|\|\|:|<=|=>|:).{0,5}['"](\d[0-9A-F]{8}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{12})['"]`,keywords:["heroku"],caseInsensitive:!0},{id:"twilio-api-key",category:"twilio",title:"Twilio API Key",pattern:String.raw`(SK[0-9a-fA-F]{32})`,keywords:["SK"]},{id:"age-secret-key",category:"age",title:"Age secret key",pattern:String.raw`(AGE-SECRET-KEY-1[QPZRY9X8GF2TVDW0S3JN54KHCE6MUA7L]{58})`,keywords:["AGE-SECRET-KEY-1"]},{id:"jwt-token",category:"jwt",title:"JWT token",pattern:String.raw`(ey[a-zA-Z0-9]{17,}\.ey[a-zA-Z0-9/\\_-]{17,}\.(?:[a-zA-Z0-9/\\_-]{10,}={0,2})?)`,keywords:[".eyJ"]},{id:"npm-access-token",category:"npm",title:"npm access token",pattern:String.raw`(npm_[a-z0-9]{36})`,keywords:["npm_"],caseInsensitive:!0},{id:"sendgrid-api-token",category:"sendgrid",title:"SendGrid API token",pattern:String.raw`(SG\.[a-z0-9_.-]{66})`,keywords:["SG."],caseInsensitive:!0},{id:"aws-secret-access-key",category:"aws",title:"AWS Secret Access Key",pattern:String.raw`(aws[_-]secret[_-]access[_-]key[_-][A-Za-z0-9/+=]{40})`,keywords:["key"],caseInsensitive:!0},{id:"dockerconfig-secret",category:"docker",title:"Dockerconfig secret exposed",pattern:String.raw`((\.dockerconfigjson|dockercfg):\s*\|*\s*((ey|ew)+[A-Za-z0-9/+=]+))`,keywords:["dockerc"],caseInsensitive:!0},{id:"linear-api-token",category:"linear",title:"Linear API token",pattern:String.raw`(lin_api_[a-z0-9]{40})`,keywords:["lin_api_"],caseInsensitive:!0},{id:"sendinblue-api-token",category:"sendinblue",title:"Sendinblue API token",pattern:String.raw`(xkeysib-[a-f0-9]{64}-[a-z0-9]{16})`,keywords:["xkeysib-"],caseInsensitive:!0},{id:"planetscale-api-token",category:"planetscale",title:"PlanetScale API token",pattern:String.raw`(pscale_tkn_[a-z0-9_.-]{43})`,keywords:["pscale_tkn_"],caseInsensitive:!0},{id:"doppler-api-token",category:"doppler",title:"Doppler API token",pattern:String.raw`(dp\.pt\.[a-z0-9]{43})`,keywords:["dp.pt."],caseInsensitive:!0},{id:"discord-api-token",category:"discord",title:"Discord API key",pattern:String.raw`(?:discord[a-z0-9_ .,-]{0,25})(?:=|>|:=|\|\|:|<=|=>|:).{0,5}['"]([a-h0-9]{64})['"]`,keywords:["discord"],caseInsensitive:!0},{id:"pulumi-api-token",category:"pulumi",title:"Pulumi API token",pattern:String.raw`(pul-[a-f0-9]{40})`,keywords:["pul-"]},{id:"postman-api-token",category:"postman",title:"Postman API token",pattern:String.raw`(PMAK-[a-f0-9]{24}-[a-f0-9]{34})`,keywords:["PMAK-"],caseInsensitive:!0},{id:"facebook-token",category:"facebook",title:"Facebook token",pattern:String.raw`(?:facebook[a-z0-9_ .,-]{0,25})(?:=|>|:=|\|\|:|<=|=>|:).{0,5}['"]([a-f0-9]{32})['"]`,keywords:["facebook"],caseInsensitive:!0},{id:"twitter-token",category:"twitter",title:"Twitter token",pattern:String.raw`(?:twitter[a-z0-9_ .,-]{0,25})(?:=|>|:=|\|\|:|<=|=>|:).{0,5}['"]([a-f0-9]{35,44})['"]`,keywords:["twitter"],caseInsensitive:!0},{id:"adobe-client-id",category:"adobe",title:"Adobe Client ID (Oauth Web)",pattern:String.raw`(?:adobe[a-z0-9_ .,-]{0,25})(?:=|>|:=|\|\|:|<=|=>|:).{0,5}['"]([a-f0-9]{32})['"]`,keywords:["adobe"],caseInsensitive:!0},{id:"adobe-client-secret",category:"adobe",title:"Adobe Client Secret",pattern:String.raw`(p8e-[a-z0-9]{32})`,keywords:["p8e-"],caseInsensitive:!0},{id:"alibaba-access-key-id",category:"alibaba",title:"Alibaba AccessKey ID",pattern:String.raw`((LTAI)[a-z0-9]{20})`,keywords:["LTAI"],caseInsensitive:!0},{id:"alibaba-secret-key",category:"alibaba",title:"Alibaba Secret Key",pattern:String.raw`(?:alibaba[a-z0-9_ .,-]{0,25})(?:=|>|:=|\|\|:|<=|=>|:).{0,5}['"]([a-z0-9]{30})['"]`,keywords:["alibaba"],caseInsensitive:!0},{id:"asana-client-id",category:"asana",title:"Asana Client ID",pattern:String.raw`(?:asana[a-z0-9_ .,-]{0,25})(?:=|>|:=|\|\|:|<=|=>|:).{0,5}['"]([0-9]{16})['"]`,keywords:["asana"],caseInsensitive:!0},{id:"asana-client-secret",category:"asana",title:"Asana Client Secret",pattern:String.raw`(?:asana[a-z0-9_ .,-]{0,25})(?:=|>|:=|\|\|:|<=|=>|:).{0,5}['"]([a-z0-9]{32})['"]`,keywords:["asana"],caseInsensitive:!0},{id:"atlassian-api-token",category:"atlassian",title:"Atlassian API token",pattern:String.raw`(?:atlassian[a-z0-9_ .,-]{0,25})(?:=|>|:=|\|\|:|<=|=>|:).{0,5}['"]([a-z0-9]{24})['"]`,keywords:["atlassian"],caseInsensitive:!0},{id:"beamer-api-token",category:"beamer",title:"Beamer API token",pattern:String.raw`(?:beamer[a-z0-9_ .,-]{0,25})(?:=|>|:=|\|\|:|<=|=>|:).{0,5}['"](b_[a-z0-9=_-]{44})['"]`,keywords:["beamer"],caseInsensitive:!0},{id:"buildkite-agent-token",category:"buildkite",title:"Buildkite API Token V2",pattern:String.raw`(bkua_[a-fA-F0-9]{40})`,keywords:["bkua_"]},{id:"clojars-api-token",category:"clojars",title:"Clojars API token",pattern:String.raw`(CLOJARS_[a-z0-9]{60})`,keywords:["CLOJARS_"],caseInsensitive:!0},{id:"contentful-delivery-api-token",category:"contentful-delivery",title:"Contentful delivery API token",pattern:String.raw`(?:contentful[a-z0-9_ .,-]{0,25})(?:=|>|:=|\|\|:|<=|=>|:).{0,5}['"]([a-z0-9=_-]{43})['"]`,keywords:["contentful"],caseInsensitive:!0},{id:"databricks-api-token",category:"databricks",title:"Databricks API token",pattern:String.raw`(dapi[a-h0-9]{32})`,keywords:["dapi"]},{id:"discord-client-id",category:"discord",title:"Discord client ID",pattern:String.raw`(?:discord[a-z0-9_ .,-]{0,25})(?:=|>|:=|\|\|:|<=|=>|:).{0,5}['"]([0-9]{18})['"]`,keywords:["discord"],caseInsensitive:!0},{id:"discord-client-secret",category:"discord",title:"Discord client secret",pattern:String.raw`(?:discord[a-z0-9_ .,-]{0,25})(?:=|>|:=|\|\|:|<=|=>|:).{0,5}['"]([a-z0-9=_-]{32})['"]`,keywords:["discord"],caseInsensitive:!0},{id:"dropbox-api-secret",category:"dropbox",title:"Dropbox API secret/key",pattern:String.raw`(?:dropbox[a-z0-9_ .,-]{0,25})(?:=|>|:=|\|\|:|<=|=>|:).{0,5}['"]([a-z0-9]{15})['"]`,keywords:["dropbox"],caseInsensitive:!0},{id:"dropbox-short-lived-api-token",category:"dropbox",title:"Dropbox short lived API token",pattern:String.raw`(?:dropbox[a-z0-9_ .,-]{0,25})(?:=|>|:=|\|\|:|<=|=>|:).{0,5}['"](sl\.[a-z0-9=_-]{135})['"]`,keywords:["dropbox"],caseInsensitive:!0},{id:"dropbox-long-lived-api-token",category:"dropbox",title:"Dropbox long lived API token",pattern:String.raw`(?:dropbox[a-z0-9_ .,-]{0,25})(?:=|>|:=|\|\|:|<=|=>|:).{0,5}['"]([a-z0-9]{11}(AAAAAAAAAA)[a-z0-9_=-]{43})['"]`,keywords:["dropbox"],caseInsensitive:!0},{id:"duffel-api-token",category:"duffel",title:"Duffel API token",pattern:String.raw`(duffel_(test|live)_[a-z0-9_-]{43})`,keywords:["duffel_test_","duffel_live_"],caseInsensitive:!0},{id:"dynatrace-api-token",category:"dynatrace",title:"Dynatrace API token",pattern:String.raw`(dt0c01\.[a-z0-9]{24}\.[a-z0-9]{64})`,keywords:["dt0c01."],caseInsensitive:!0},{id:"easypost-api-token",category:"easypost",title:"EasyPost API token",pattern:String.raw`(EZ[AT]K[a-z0-9]{54})`,keywords:["EZAK","EZAT"],caseInsensitive:!0},{id:"fastly-api-token",category:"fastly",title:"Fastly API token",pattern:String.raw`(?:fastly[a-z0-9_ .,-]{0,25})(?:=|>|:=|\|\|:|<=|=>|:).{0,5}['"]([a-z0-9=_-]{32})['"]`,keywords:["fastly"],caseInsensitive:!0},{id:"finicity-client-secret",category:"finicity",title:"Finicity client secret",pattern:String.raw`(?:finicity[a-z0-9_ .,-]{0,25})(?:=|>|:=|\|\|:|<=|=>|:).{0,5}['"]([a-z0-9]{20})['"]`,keywords:["finicity"],caseInsensitive:!0},{id:"finicity-api-token",category:"finicity",title:"Finicity API token",pattern:String.raw`(?:finicity[a-z0-9_ .,-]{0,25})(?:=|>|:=|\|\|:|<=|=>|:).{0,5}['"]([a-f0-9]{32})['"]`,keywords:["finicity"],caseInsensitive:!0},{id:"flutterwave-public-key",category:"flutterwave",title:"Flutterwave public/secret key",pattern:String.raw`(FLW(PUB|SEC)K_TEST-[a-h0-9]{32}-X)`,keywords:["FLWSECK_TEST-","FLWPUBK_TEST-"],caseInsensitive:!0},{id:"flutterwave-enc-key",category:"flutterwave",title:"Flutterwave encrypted key",pattern:String.raw`(FLWSECK_TEST[a-h0-9]{12})`,keywords:["FLWSECK_TEST"]},{id:"frameio-api-token",category:"frameio",title:"Frame.io API token",pattern:String.raw`(fio-u-[a-z0-9_=-]{64})`,keywords:["fio-u-"],caseInsensitive:!0},{id:"gocardless-api-token",category:"gocardless",title:"GoCardless API token",pattern:String.raw`(live_[a-z0-9_=-]{40})`,keywords:["live_"],caseInsensitive:!0},{id:"grafana-api-token",category:"grafana",title:"Grafana API token",pattern:String.raw`(eyJrIjoi[a-z0-9_=-]{72,92})`,keywords:["eyJrIjoi"],caseInsensitive:!0},{id:"hashicorp-tf-api-token",category:"hashicorp",title:"HashiCorp Terraform user/org API token",pattern:String.raw`([a-z0-9]{14}\.atlasv1\.[a-z0-9_=-]{60,70})`,keywords:["atlasv1."],caseInsensitive:!0},{id:"hubspot-api-token",category:"hubspot",title:"HubSpot API token",pattern:String.raw`(?:hubspot[a-z0-9_ .,-]{0,25})(?:=|>|:=|\|\|:|<=|=>|:).{0,5}['"]([a-h0-9]{8}-[a-h0-9]{4}-[a-h0-9]{4}-[a-h0-9]{4}-[a-h0-9]{12})['"]`,keywords:["hubspot"],caseInsensitive:!0},{id:"intercom-api-token",category:"intercom",title:"Intercom API token",pattern:String.raw`(?:intercom[a-z0-9_ .,-]{0,25})(?:=|>|:=|\|\|:|<=|=>|:).{0,5}['"]([a-z0-9=_]{60})['"]`,keywords:["intercom"],caseInsensitive:!0},{id:"intercom-client-secret",category:"intercom",title:"Intercom client secret/ID",pattern:String.raw`(?:intercom[a-z0-9_ .,-]{0,25})(?:=|>|:=|\|\|:|<=|=>|:).{0,5}['"]([a-h0-9]{8}-[a-h0-9]{4}-[a-h0-9]{4}-[a-h0-9]{4}-[a-h0-9]{12})['"]`,keywords:["intercom"],caseInsensitive:!0},{id:"ionic-api-token",category:"ionic",title:"Ionic API token",pattern:String.raw`(?:ionic[a-z0-9_ .,-]{0,25})(?:=|>|:=|\|\|:|<=|=>|:).{0,5}['"](ion_[a-z0-9]{42})['"]`,keywords:["ionic"],caseInsensitive:!0},{id:"linear-client-secret",category:"linear",title:"Linear client secret/ID",pattern:String.raw`(?:linear[a-z0-9_ .,-]{0,25})(?:=|>|:=|\|\|:|<=|=>|:).{0,5}['"]([a-f0-9]{32})['"]`,keywords:["linear"],caseInsensitive:!0},{id:"lob-api-key",category:"lob",title:"Lob API Key",pattern:String.raw`(?:lob[a-z0-9_ .,-]{0,25})(?:=|>|:=|\|\|:|<=|=>|:).{0,5}['"]((live|test)_[a-f0-9]{35})['"]`,keywords:["lob"],caseInsensitive:!0},{id:"mailchimp-api-key",category:"mailchimp",title:"Mailchimp API key",pattern:String.raw`(?:mailchimp[a-z0-9_ .,-]{0,25})(?:=|>|:=|\|\|:|<=|=>|:).{0,5}['"]([a-f0-9]{32}-us20)['"]`,keywords:["mailchimp"],caseInsensitive:!0},{id:"mailgun-token",category:"mailgun",title:"Mailgun private API token",pattern:String.raw`(?:mailgun[a-z0-9_ .,-]{0,25})(?:=|>|:=|\|\|:|<=|=>|:).{0,5}['"]((pub)?key-[a-f0-9]{32})['"]`,keywords:["mailgun"],caseInsensitive:!0},{id:"mailgun-signing-key",category:"mailgun",title:"Mailgun webhook signing key",pattern:String.raw`(?:mailgun[a-z0-9_ .,-]{0,25})(?:=|>|:=|\|\|:|<=|=>|:).{0,5}['"]([a-h0-9]{32}-[a-h0-9]{8}-[a-h0-9]{8})['"]`,keywords:["mailgun"],caseInsensitive:!0},{id:"mapbox-api-token",category:"mapbox",title:"Mapbox API token",pattern:String.raw`(pk\.[a-z0-9]{60}\.[a-z0-9]{22})`,keywords:["pk."],caseInsensitive:!0},{id:"messagebird-api-token",category:"messagebird",title:"MessageBird API token",pattern:String.raw`(?:messagebird[a-z0-9_ .,-]{0,25})(?:=|>|:=|\|\|:|<=|=>|:).{0,5}['"]([a-z0-9]{25})['"]`,keywords:["messagebird"],caseInsensitive:!0},{id:"messagebird-client-id",category:"messagebird",title:"MessageBird API client ID",pattern:String.raw`(?:messagebird[a-z0-9_ .,-]{0,25})(?:=|>|:=|\|\|:|<=|=>|:).{0,5}['"]([a-h0-9]{8}-[a-h0-9]{4}-[a-h0-9]{4}-[a-h0-9]{4}-[a-h0-9]{12})['"]`,keywords:["messagebird"],caseInsensitive:!0},{id:"new-relic-user-api-key",category:"newrelic",title:"New Relic user API Key",pattern:String.raw`(NRAK-[A-Z0-9]{27})`,keywords:["NRAK-"]},{id:"new-relic-user-api-id",category:"newrelic",title:"New Relic user API ID",pattern:String.raw`(?:newrelic[a-z0-9_ .,-]{0,25})(?:=|>|:=|\|\|:|<=|=>|:).{0,5}['"]([A-Z0-9]{64})['"]`,keywords:["newrelic"],caseInsensitive:!0},{id:"new-relic-browser-api-token",category:"newrelic",title:"New Relic ingest browser API token",pattern:String.raw`(NRJS-[a-f0-9]{19})`,keywords:["NRJS-"]},{id:"planetscale-password",category:"planetscale",title:"PlanetScale password",pattern:String.raw`(pscale_pw_[a-z0-9_.-]{43})`,keywords:["pscale_pw_"],caseInsensitive:!0},{id:"private-packagist-token",category:"private-packagist",title:"Private Packagist token",pattern:String.raw`(packagist_[ou][ru]t_[a-f0-9]{68})`,keywords:["packagist_uut_","packagist_ort_","packagist_out_"],caseInsensitive:!0},{id:"rubygems-api-token",category:"rubygems",title:"Rubygem API token",pattern:String.raw`(rubygems_[a-f0-9]{48})`,keywords:["rubygems_"]},{id:"shippo-api-token",category:"shippo",title:"Shippo API token",pattern:String.raw`(shippo_(live|test)_[a-f0-9]{40})`,keywords:["shippo_live_","shippo_test_"]},{id:"linkedin-client-secret",category:"linkedin",title:"LinkedIn Client secret",pattern:String.raw`(?:linkedin[a-z0-9_ .,-]{0,25})(?:=|>|:=|\|\|:|<=|=>|:).{0,5}['"]([a-z]{16})['"]`,keywords:["linkedin"],caseInsensitive:!0},{id:"linkedin-client-id",category:"linkedin",title:"LinkedIn Client ID",pattern:String.raw`(?:linkedin[a-z0-9_ .,-]{0,25})(?:=|>|:=|\|\|:|<=|=>|:).{0,5}['"]([a-z0-9]{14})['"]`,keywords:["linkedin"],caseInsensitive:!0},{id:"twitch-api-token",category:"twitch",title:"Twitch API token",pattern:String.raw`(?:twitch[a-z0-9_ .,-]{0,25})(?:=|>|:=|\|\|:|<=|=>|:).{0,5}['"]([a-z0-9]{30})['"]`,keywords:["twitch"],caseInsensitive:!0},{id:"typeform-api-token",category:"typeform",title:"Typeform API token",pattern:String.raw`(?:typeform[a-z0-9_ .,-]{0,25})(?:=|>|:=|\|\|:|<=|=>|:).{0,5}(tfp_[a-z0-9_.=-]{59})`,keywords:["typeform"],caseInsensitive:!0},{id:"todoist-api-token",category:"todoist",title:"Todoist API token",pattern:String.raw`(?:todoist[a-z0-9_ .,-]{0,25})(?:=|>|:=|\|\|:|<=|=>|:)[\s'"]{0,3}([0-9a-f]{40})`,keywords:["todoist"],caseInsensitive:!0},{id:"openai-api-key",category:"openai",title:"OpenAI API Key",pattern:String.raw`(sk-[a-zA-Z0-9]{50})`,caseInsensitive:!1,keywords:["sk-"]},{id:"openai-api-key-project",category:"openai",title:"OpenAI Project-scoped API Key",pattern:String.raw`(sk-proj-[A-Za-z0-9]{24}-[A-Za-z0-9]{40,128})`,caseInsensitive:!0,keywords:["sk-proj-"]},{id:"openai-api-key-env",category:"openai",title:"OpenAI Environment-scoped API Key",pattern:String.raw`(sk-(?:live|test)-[A-Za-z0-9]{24}-[A-Za-z0-9]{40,128})`,caseInsensitive:!0,keywords:["sk-live-","sk-test-"]},{id:"anthropic-api-key",category:"anthropic",title:"Anthropic API Key",pattern:String.raw`(sk-ant-([a-zA-Z0-9]{1,10}-)?[a-zA-Z0-9_-]{32,128})`,caseInsensitive:!1,keywords:["sk-ant-"]},{id:"canva-token",category:"canva",title:"Canva Token",pattern:String.raw`\b(cnv[a-z0-9]{2}[A-Za-z0-9_=-]+[a-f0-9]{8})\b`,caseInsensitive:!1,keywords:["cnv"]},{id:"api-key",category:"unknown",title:"Unknown API Key",pattern:String.raw`(?:[a-z0-9_ .,-]{0,25}api[-_](?:key|token)(?!length|count|max|min|maxlength|_length|_count|_min|_maxlength)[a-z0-9_ .,-]{0,25})\s*(?:=|>|:=|\|\|:|<=|=>|:)\s*['"]?((?!.*(?:api|key|secret|foo|example|dummy|password|12345|abcde|placeholder|fake|token))[a-z0-9+/_-]{6,128})['"]?(?=\s|$|[;,\]})'"])`,keywords:["api-key","api_key","api-token","api_token"],caseInsensitive:!0},{id:"webhook-secret",category:"unknown",title:"Unknown Webhook Secret",pattern:String.raw`(?:[a-z0-9_ .,-]{0,25}webhook[-_]secret(?!length|count|max|min|maxlength|_length|_count|_min|_maxlength)[a-z0-9_ .,-]{0,25})\s*(?:=|>|:=|\|\|:|<=|=>|:)\s*['"]?((?!.*(?:api|key|secret|foo|example|dummy|password|12345|abcde|placeholder|fake|token|webhook))[a-z0-9+/=_-]{6,128})['"]?(?=\s|$|[;,\]})'"])`,keywords:["webhook-secret","webhook_secret"],caseInsensitive:!0},{id:"password",category:"unknown",title:"Unknown Password",pattern:String.raw`(?:[a-z0-9_ .,-]{0,25}password(?!length|count|max|min|maxlength|_length|_count|_min|_maxlength)[a-z0-9_ .,-]{0,25})\s*(?:=|>|:=|\|\|:|<=|=>|:)\s*['"]?((?!.*(?:api|key|secret|foo|example|dummy|password|12345|abcde|placeholder|fake|token|password|pass|pwd))[a-z0-9+/=_-]{6,128})['"]?(?=\s|$|[;,\]})'"])`,keywords:["password"],caseInsensitive:!0},{id:"sk-secret",category:"unknown",title:"Unknown SK Secret",pattern:String.raw`(?:^|['"\s])(sk(?:[-_][a-z0-9]{1,10})?[-_][a-z0-9]{10,99})(?:$|['"\s])`,caseInsensitive:!0,keywords:["sk-","sk_"]}]});function ub4(J){if(!J||typeof J!=="string")return J;let Q=J.replace(mb4,"");if(Q.length!==J.length){let Y=J.length-Q.length;x.info("Invisible Unicode tag characters removed during sanitization",{removedCount:Y})}return Q}function pb4(J){if(!J||typeof J!=="string")return J;let Q=ub4(J);for(let Y of Qv0){if(!Y.keywords.some((G)=>Y.caseInsensitive?Q.toLowerCase().includes(G.toLowerCase()):Q.includes(G)))continue;let X=Jv0(Y);Q=Q.replace(X,(G,Z)=>{return G.replace(Z,`[REDACTED:${Y.id}]`)})}return Q}function Cs(J,Q){if(!J||typeof J==="number"||typeof J==="boolean")return J;if(typeof J==="string")return Q(J);if(Array.isArray(J))return J.map((Y)=>{if(typeof Y==="string")return Q(Y);else if(Y&&typeof Y==="object")return Cs(Y,Q);return Y});if(J&&typeof J==="object"){if("type"in J&&(J.type==="base64"||J.type==="image")&&"data"in J)return{...J};if("isImage"in J&&J.isImage===!0&&"content"in J&&typeof J.content==="string"){let Y={};for(let[X,G]of Object.entries(J))if(X==="content")Y[X]=G;else Y[X]=Cs(G,Q);return Y}}return Object.fromEntries(Object.entries(J).map(([Y,X])=>[Y,Cs(X,Q)]))}function js(J){return Cs(J,pb4)}var mb4;var Xv0=Z1(()=>{U0();Yv0();mb4=/[\uDB40][\uDC00-\uDC7F]/g});function db4(J){return{[Y7]:"oracle",[zJ]:"subagent",[V9]:"codebase-search",[WI]:"codebase-search",[HI]:"codebase-search",[YU]:"codebase-search",[zI]:"codebase-search",[QU]:"codebase-search"}[J]||null}function cb4(J,Q){let Y=J["~debug"];if(!Y)return null;x.debug("Extracting usage from tool debug info",{operationType:Q,debugInfoKeys:Object.keys(Y),hasUsage:!!Y.usage,hasInferences:Array.isArray(Y.inferences),inferenceCount:Array.isArray(Y.inferences)?Y.inferences.length:0});let X=[];if(Q==="subagent"){if(Y.usage)X=[{usage:Y.usage}];else if(Array.isArray(Y.inferences))X=Y.inferences}else X=Array.isArray(Y.inferences)?Y.inferences:[];if(X.length===0)return x.debug("No inferences found in tool debug",{operationType:Q}),null;let G=lb4(X);return x.debug("Aggregated tool usage from inferences",{operationType:Q,inferenceCount:X.length,totalCredits:G.credits}),G}function lb4(J){let Q=J.reduce((X,G)=>({inputTokens:X.inputTokens+(G.usage?.inputTokens??0),outputTokens:X.outputTokens+(G.usage?.outputTokens??0),cacheCreationInputTokens:X.cacheCreationInputTokens+(G.usage?.cacheCreationInputTokens??0),cacheReadInputTokens:X.cacheReadInputTokens+(G.usage?.cacheReadInputTokens??0),credits:X.credits+(G.usage?.credits??0)}),{inputTokens:0,outputTokens:0,cacheCreationInputTokens:0,cacheReadInputTokens:0,credits:0}),Y=J[J.length-1]?.usage;return{model:Y?.model,maxInputTokens:Y?.maxInputTokens??0,inputTokens:Q.inputTokens,outputTokens:Q.outputTokens,totalInputTokens:Q.inputTokens+Q.cacheCreationInputTokens+Q.cacheReadInputTokens,cacheCreationInputTokens:Q.cacheCreationInputTokens,cacheReadInputTokens:Q.cacheReadInputTokens,credits:Q.credits}}function ib4(J,Q){if(Q==="subagent")return J["~debug"]?.threadID||J.threadID;return}function nb4(J){let Q,Y=-1;for(let G=J.length-1;G>=0;G--){let Z=J[G];if(Z?.role==="assistant"){Q=Z.messageId,Y=G;break}}if(Y===-1)return{fromMessageId:void 0,toMessageId:Q};let X;for(let G=Y-1;G>=0;G--){let Z=J[G];if(Z?.role==="user"){X=Z.messageId;break}}return{fromMessageId:X,toMessageId:Q}}function Gv0(J,Q,Y){let X=LI(J,Q);if(!X?.block?.name){x.debug("Tool block not found for ledger extraction",{toolUse:Q});return}let G=db4(X.block.name);if(x.debug("Processing tool completion for ledger",{toolName:X.block.name,toolUse:Q,operationType:G,hasDebugInfo:!!Y["~debug"],debugKeys:Y["~debug"]?Object.keys(Y["~debug"]):[]}),!G)return;let Z=cb4(Y,G);if(!Z){x.debug("No usage extracted from tool debug info",{toolName:X.block.name,operationType:G,hasDebug:!!Y["~debug"]});return}let q=ib4(Y,G),V;for(let K of J.messages)if(K.role==="assistant"&&Array.isArray(K.content)){for(let W of K.content)if(W.type==="tool_use"&&W.id===Q){V=K.messageId;break}if(V!==void 0)break}x.debug("Adding tool usage to thread ledger",{toolName:X.block.name,operationType:G,credits:Z.credits,subagentThreadID:q,triggeringMessageId:V}),Lf(J,Z,G,q,V,Q)}function Lf(J,Q,Y="inference",X,G,Z){if(!J.usageLedger)J.usageLedger={events:[]};let q,V;if(Y==="inference"&&J.messages){let H=nb4(J.messages);q=H.fromMessageId,V=H.toMessageId}else if(G!==void 0)q=G,V=G;let K={id:crypto.randomUUID(),timestamp:new Date().toISOString(),model:Q.model,credits:Q.credits??0,tokens:{input:Q.inputTokens??0,output:Q.outputTokens??0},operationType:Y,subagentThreadID:X,fromMessageId:q,toMessageId:V,toolUseID:Z};J.usageLedger.events.push(K);let W=J.usageLedger.events.reduce((H,z)=>H+z.credits,0);x.debug("usage-ledger:event",{threadId:J.id,operationType:Y,eventId:K.id,toolUseID:Z,addedCredits:K.credits,totalCredits:W,eventCount:J.usageLedger.events.length,fromMessageId:q,toMessageId:V})}function Zv0(J){return J.usageLedger?.events.reduce((Q,Y)=>Q+Y.credits,0)??0}function $v0(J,Q){let Y=J.usageLedger?.events??[],X=new Map;for(let Z of Y){let q=Z.model?.trim()||"unknown",V=`${q}|${Z.operationType}`,K=X.get(V)??{model:q,operationType:Z.operationType,credits:0,tokensIn:0,tokensOut:0};K.credits+=Z.credits||0,K.tokensIn+=Z.tokens?.input||0,K.tokensOut+=Z.tokens?.output||0,X.set(V,K)}let G=Array.from(X.values());if(!Q?.includeZero)G=G.filter((Z)=>Z.credits>0);return G.sort((Z,q)=>q.credits-Z.credits||Z.model.localeCompare(q.model)||Z.operationType.localeCompare(q.operationType)),G}function qv0(J){let Q=new Map,Y=0,X=0,G=0;for(let q of J){let V=Q.get(q.model);if(!V)V={model:q.model,totalCredits:0,totalTokensIn:0,totalTokensOut:0,rows:[]},Q.set(q.model,V);V.rows.push({operationType:q.operationType,credits:q.credits,tokensIn:q.tokensIn,tokensOut:q.tokensOut}),V.totalCredits+=q.credits,V.totalTokensIn+=q.tokensIn,V.totalTokensOut+=q.tokensOut,Y+=q.credits,X+=q.tokensIn,G+=q.tokensOut}let Z=Array.from(Q.values());Z.sort((q,V)=>V.totalCredits-q.totalCredits||q.model.localeCompare(V.model));for(let q of Z)q.rows.sort((V,K)=>K.credits-V.credits||V.operationType.localeCompare(K.operationType));return{models:Z,grandTotal:{credits:Y,tokensIn:X,tokensOut:G}}}function Ss(J,Q){return J.usageLedger?.events.filter((Y)=>Y.toolUseID===Q).reduce((Y,X)=>Y+X.credits,0)??0}function DM1(J){if(J?.role!=="user")return!1;let Q=Array.isArray(J.content)?J.content:[];if(Q.length===0)return!1;return Q.every((Y)=>Y&&Y.type==="tool_result")}function ab4(J,Q){for(let Y=J.length-1;Y>=0;Y--){let X=J[Y];if(X?.messageId===Q){if(X.role==="user"&&!DM1(X))return Q;if(X.role==="user"&&DM1(X))for(let G=Y-1;G>=0;G--){let Z=J[G];if(Z?.role==="user"&&!DM1(Z))return Z.messageId}break}}return Q}function Vv0(J){if(!J.usageLedger?.events.length||!J.messages)return 0;let Q=J.usageLedger.events.filter((G)=>G.operationType==="inference");if(!Q.length)return 0;let Y=Q[Q.length-1];if(!Y||Y.fromMessageId===void 0)return Y?.credits??0;let X=ab4(J.messages,Y.fromMessageId);return J.usageLedger.events.filter((G)=>G.fromMessageId!==void 0&&G.fromMessageId>=X).reduce((G,Z)=>G+Z.credits,0)}var ZT=Z1(()=>{U0();z4();M9()});function rb4(J){return J?J.length>=ob4:!1}function gH(J){if(J.nextMessageId===void 0)J.nextMessageId=0;return J.nextMessageId++}function sb4(J,Q){J["~debug"]={...J["~debug"]??{},...Q.usage?{lastInferenceUsage:Q.usage}:{}}}function Kv0(J){return(Q)=>{switch(Q.v++,J.type){case"cancelled":{_s(Q);let Y=Q.messages.at(-1);if(Y?.role==="user"){let X=Y.content.findLast((G)=>G.type==="tool_result");if(X)X.run.status="cancelled"}break}case"user:message:interrupt":{let Y=Q.messages[J.messageIndex];if(Y?.role==="user")Y.interrupted=!0;break}case"artifact:update":{if(!Q.artifacts)Q.artifacts={};let Y=Q.artifacts[J.artifactId];Q.artifacts[J.artifactId]={type:"plan",content:J.content,created:Y?.created??Date.now(),updated:Date.now(),version:J.version??(Y?.version??0)+1};break}case"summary:created":{if(J.summary.type==="external"){if(!Q.summaryThreads)Q.summaryThreads=[];Q.summaryThreads.push(J.summary.summaryThreadID),Q.messages.push({role:"info",messageId:gH(Q),content:[{type:"summary",summary:{type:"thread",thread:J.summary.summaryThreadID}}]})}else if(J.summary.type==="internal"){let Y=gH(Q);if(Q.messages.push({role:"info",messageId:Y,content:[{type:"summary",summary:{type:"message",summary:J.summary.summary}}]}),J.summary.usage)x.debug("summary:created delta handler: adding usage to ledger",{usage:{...J.summary.usage},messageId:Y,threadId:Q.id}),Lf(Q,J.summary.usage,"summarization",void 0,Y);else x.warn("summary:created delta handler: no usage in internal summary")}break}case"fork:created":{if(!Q.forkThreads)Q.forkThreads={};let Y=Q.forkThreads[J.fromMessageIndex]||[];Q.forkThreads={...Q.forkThreads,[J.fromMessageIndex]:[...Y,J.forkThreadID]},Q.v++;break}case"thread:truncate":{if(Q.messages.splice(J.fromIndex),Q.forkThreads){let Y=[];for(let X in Q.forkThreads){let G=Number(X);if(G>=J.fromIndex)Y.push(G)}for(let X of Y)delete Q.forkThreads[X];if(Object.keys(Q.forkThreads).length===0)Q.forkThreads=void 0}break}case"user:message":{_s(Q);let Y={role:"user",messageId:gH(Q),...J.message,content:J.message.content??[]},X=js(Y);if(J.index!==void 0){if(!Q.messages[J.index])throw Error(`user message at index ${J.index} not found`);let G=Q.messages[J.index];if(Q.messages.filter((V)=>V.role==="user")[0]===G&&Y.agentMode&&!Q.mainThreadID)Q.agentMode=Y.agentMode;Q.messages.splice(J.index,Q.messages.length-J.index,X)}else{let G=d$(Q)===0;if((!Q.agentMode||G)&&Y.agentMode&&!Q.mainThreadID)Q.agentMode=Y.agentMode;if(Q.messages.push(X),Y.agentMode==="plan"&&Q.messages.length===1&&!Q.artifacts?.plan){if(!Q.artifacts)Q.artifacts={};let Z=Date.now();Q.artifacts.plan={type:"plan",content:i$,created:Z,version:0,updated:Z}}if(Q.draft)Q.draft=void 0}break}case"user:message-queue:dequeue":{if(_s(Q),!Q.queuedMessages)return;let[Y,...X]=Q.queuedMessages;if(!Y)return;Q.messages.push(Y.queuedMessage),Q.queuedMessages=X;break}case"user:tool-input":{if(!CX(Q,J.toolUse)){x.debug(`Ignoring user:tool-input delta for missing tool use ${J.toolUse} (likely deleted due to thread edit/truncation)`);break}let X=c8(GU(Q,J.toolUse));if(!X){x.debug(`Ignoring user:tool-input delta for missing tool result block ${J.toolUse} (likely deleted due to thread edit/truncation)`);break}X.userInput=J.value;break}case"tool:data":{if(!LI(Q,J.toolUse)){x.debug(`Ignoring tool:data delta for missing tool use ${J.toolUse} (likely deleted due to thread edit/truncation)`);break}let X=c8(js(J.data));if(Wv0(Q,J.toolUse,X),X&&"status"in X&&X.status==="done"){if(Gv0(Q,J.toolUse,X),X.result&&typeof X.result==="object"&&"artifact"in X.result&&X.result.artifact&&typeof X.result.artifact==="object"&&"id"in X.result.artifact&&"content"in X.result.artifact){let{id:G,content:Z}=X.result.artifact;if(!Q.artifacts)Q.artifacts={};let q=Q.artifacts[G],V=q?.created??Date.now(),K=q?.version??0;Q.artifacts[G]={type:"plan",content:Z,created:V,updated:Date.now(),version:K+1}}}break}case"tool:processed":{let Y=LI(Q,J.toolUse);if(!Y){x.debug(`Ignoring tool:processed delta for missing tool use ${J.toolUse} (likely deleted due to thread edit/truncation)`);break}let X=Y.block.input;Y.block.input=J.newArgs,Y.message.originalToolUseInput={...Y.message.originalToolUseInput,[J.toolUse]:X};break}case"assistant:message":{let Y=FJ(Q,"assistant"),X=Y?.content.filter((Z)=>Z.type==="tool_use").map((Z)=>Z.id)||[];if(_s(Q),Y?.state.type==="cancelled"){for(let Z of Q.messages)if(Z.role==="user")Z.content=Z.content.filter((q)=>{if(q.type==="tool_result"&&X.includes(q.toolUseID))return!1;return!0})}let G={...J.message,messageId:gH(Q)};Q.messages.push(c8(G));break}case"assistant:message-update":{let Y=c8(J.message),X=Q.messages.at(-1);if(X?.role==="assistant")Q.messages[Q.messages.length-1]={...Y,messageId:X?.messageId};else Q.messages.push({...Y,messageId:gH(Q)});break}case"inference:completed":{if(sb4(Q,{usage:J.usage}),!Q.env)Q.env={initial:{}};if(!Q.env.initial.tags)Q.env.initial.tags=[];let Y=`model:${J.model}`;if(!Q.env.initial.tags.includes(Y))Q.env.initial.tags=[...Q.env.initial.tags,Y];if(J.usage){let X=c8(FJ(Q,"assistant"));if(Lf(Q,J.usage,"inference"),X){let G=Vv0(Q);X.usage={...J.usage,creditsSinceLastUserMessage:G}}}break}case"title":{if(Q.title=J.value||void 0,J.usage)Lf(Q,J.usage,"title-generation",void 0,0);break}case"max-tokens":{Q.maxTokens=J.value||void 0;break}case"main-thread":{Q.mainThreadID=J.value||void 0;break}case"agent-mode":{if(d$(Q)>0)throw Error("(bug) cannot change agentMode after first message");Q.agentMode=J.mode;break}case"environment":{Q.env=c8(J.env);break}case"user:message-queue:enqueue":{if(!Q.queuedMessages)Q.queuedMessages=[];if(rb4(Q.queuedMessages))break;let Y={role:"user",messageId:gH(Q),...J.message,content:J.message.content??[]},X=js(Y);Q.queuedMessages.push({id:ex0("queued-"),queuedMessage:c8(X)});break}case"user:message-queue:discard":{if(J.id===void 0){Q.queuedMessages=[];break}let Y=Q.queuedMessages?.findIndex((X)=>X.id===J.id);if(Y===void 0)throw Error(`queued message with id ${J.id} not found`);Q?.queuedMessages?.splice(Y,1);break}case"info:manual-bash-invocation":{Q.messages.push({role:"info",messageId:gH(Q),content:[{type:"manual_bash_invocation",args:c8(J.args),toolRun:c8(J.toolRun),hidden:J.hidden}]});break}case"info:skill-injection":{Q.messages.push({role:"info",messageId:gH(Q),content:[{type:"text",text:J.content}]});break}}}}function _s(J){let Q=c8(FJ(J,"assistant"));if(!Q)return;let Y=!1,X=[];if(Q.state.type==="streaming")Q.state={type:"cancelled"},Y=!0;else if(Q.state.type==="complete"){if(Q.content.some((Z)=>Z.type==="tool_use"&&!d2(Z)))Q.state={type:"cancelled"},Y=!0}if(Y){for(let Z=0;Z<Q.content.length;Z++){let q=Q.content[Z];if(q?.type==="tool_use"&&!d2(q)){X.push(q.id),x.debug(`Cleaning up incomplete tool_use ${q.id}`,{name:"markPriorStreamingAssistantMessageAsCancelled",threadID:J.id,blockID:q.id});let V={type:"tool_use",id:q.id,name:q.name,complete:!0,input:q.inputIncomplete??q.input??{}};Q.content[Z]=V}}let G=$Q(J);for(let Z of X)if(!G.has(Z))Wv0(J,Z,{status:"cancelled"})}}function Wv0(J,Q,Y){let X,G=LI(J,Q);if(G){let q=G.messageIndex;for(let V=q+1;V<J.messages.length;V++){let K=J.messages[V];if(K?.role==="user"){X=K;break}}}if(!X)X={role:"user",messageId:gH(J),content:[]},J.messages.push(X);let Z=GU(J,Q);if(Z)Z.run=c8(Y);else Z={type:"tool_result",toolUseID:Q,run:c8(Y)},X.content.push(Z)}function ks(J){try{return tG(J.replace(/\\+$/,"")+'"')}catch{return tG(J)}}var ob4=5;var ys=Z1(()=>{wM();PY();U0();Xv0();M9();ZT()});function j4(J,Q,Y,X,G){if(X==="m")throw TypeError("Private method is not writable");if(X==="a"&&!G)throw TypeError("Private accessor was defined without a setter");if(typeof Q==="function"?J!==Q||!G:!Q.has(J))throw TypeError("Cannot write private member to an object whose class did not declare it");return X==="a"?G.call(J,Y):G?G.value=Y:Q.set(J,Y),Y}function E0(J,Q,Y,X){if(Y==="a"&&!X)throw TypeError("Private accessor was defined without a getter");if(typeof Q==="function"?J!==Q||!X:!Q.has(J))throw TypeError("Cannot read private member from an object whose class did not declare it");return Y==="m"?X:Y==="a"?X.call(J):X?X.value:Q.get(J)}var AZ=()=>{};var MM1=function(){let{crypto:J}=globalThis;if(J?.randomUUID)return MM1=J.randomUUID.bind(J),J.randomUUID();let Q=new Uint8Array(1),Y=J?()=>J.getRandomValues(Q)[0]:()=>Math.random()*255&255;return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,(X)=>(+X^Y()&15>>+X/4).toString(16))};function Of(J){return typeof J==="object"&&J!==null&&(("name"in J)&&J.name==="AbortError"||("message"in J)&&String(J.message).includes("FetchRequestCanceledException"))}var Af=(J)=>{if(J instanceof Error)return J;if(typeof J==="object"&&J!==null){try{if(Object.prototype.toString.call(J)==="[object Error]"){let Q=Error(J.message,J.cause?{cause:J.cause}:{});if(J.stack)Q.stack=J.stack;if(J.cause&&!Q.cause)Q.cause=J.cause;if(J.name)Q.name=J.name;return Q}}catch{}try{return Error(JSON.stringify(J))}catch{}}return Error(J)};var G4,a2,N3,hL,bL,wf,Ef,If,Pf,Tf,Rf,Cf,jf,Sf,_f,mH;var NK=Z1(()=>{G4=class G4 extends Error{};a2=class a2 extends G4{constructor(J,Q,Y,X){super(`${a2.makeMessage(J,Q,Y)}`);this.status=J,this.headers=X,this.requestID=X?.get("x-request-id"),this.error=Q;let G=Q;this.code=G?.code,this.param=G?.param,this.type=G?.type}static makeMessage(J,Q,Y){let X=Q?.message?typeof Q.message==="string"?Q.message:JSON.stringify(Q.message):Q?JSON.stringify(Q):Y;if(J&&X)return`${J} ${X}`;if(J)return`${J} status code (no body)`;if(X)return X;return"(no status code or body)"}static generate(J,Q,Y,X){if(!J||!X)return new hL({message:Y,cause:Af(Q)});let G=Q?.error;if(J===400)return new wf(J,G,Y,X);if(J===401)return new Ef(J,G,Y,X);if(J===403)return new If(J,G,Y,X);if(J===404)return new Pf(J,G,Y,X);if(J===409)return new Tf(J,G,Y,X);if(J===422)return new Rf(J,G,Y,X);if(J===429)return new Cf(J,G,Y,X);if(J>=500)return new jf(J,G,Y,X);return new a2(J,G,Y,X)}};N3=class N3 extends a2{constructor({message:J}={}){super(void 0,void 0,J||"Request was aborted.",void 0)}};hL=class hL extends a2{constructor({message:J,cause:Q}){super(void 0,void 0,J||"Connection error.",void 0);if(Q)this.cause=Q}};bL=class bL extends hL{constructor({message:J}={}){super({message:J??"Request timed out."})}};wf=class wf extends a2{};Ef=class Ef extends a2{};If=class If extends a2{};Pf=class Pf extends a2{};Tf=class Tf extends a2{};Rf=class Rf extends a2{};Cf=class Cf extends a2{};jf=class jf extends a2{};Sf=class Sf extends G4{constructor(){super("Could not parse response content as the length limit was reached")}};_f=class _f extends G4{constructor(){super("Could not parse response content as the request was rejected by the content filter")}};mH=class mH extends Error{constructor(J){super(J)}}});function OM1(J){if(typeof J!=="object")return{};return J??{}}function zv0(J){if(!J)return!0;for(let Q in J)return!1;return!0}function Fv0(J,Q){return Object.prototype.hasOwnProperty.call(J,Q)}function kf(J){return J!=null&&typeof J==="object"&&!Array.isArray(J)}var eb4,Hv0=(J)=>{return eb4.test(J)},HQ=(J)=>(HQ=Array.isArray,HQ(J)),LM1,Uv0=(J,Q)=>{if(typeof Q!=="number"||!Number.isInteger(Q))throw new G4(`${J} must be an integer`);if(Q<0)throw new G4(`${J} must be a positive integer`);return Q},Bv0=(J)=>{try{return JSON.parse(J)}catch(Q){return}};var uH=Z1(()=>{NK();eb4=/^[a-z][a-z0-9+.-]*:/i,LM1=HQ});var DK=(J)=>new Promise((Q)=>setTimeout(Q,J));var QB="6.7.0";function Jg4(){if(typeof Deno<"u"&&Deno.build!=null)return"deno";if(typeof EdgeRuntime<"u")return"edge";if(Object.prototype.toString.call(typeof globalThis.process<"u"?globalThis.process:0)==="[object process]")return"node";return"unknown"}function Yg4(){if(typeof navigator>"u"||!navigator)return null;let J=[{key:"edge",pattern:/Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"chrome",pattern:/Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"firefox",pattern:/Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"safari",pattern:/(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/}];for(let{key:Q,pattern:Y}of J){let X=Y.exec(navigator.userAgent);if(X){let G=X[1]||0,Z=X[2]||0,q=X[3]||0;return{browser:Q,version:`${G}.${Z}.${q}`}}}return null}var Lv0=()=>{return typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u"},Qg4=()=>{let J=Jg4();if(J==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":QB,"X-Stainless-OS":Dv0(Deno.build.os),"X-Stainless-Arch":Nv0(Deno.build.arch),"X-Stainless-Runtime":"deno","X-Stainless-Runtime-Version":typeof Deno.version==="string"?Deno.version:Deno.version?.deno??"unknown"};if(typeof EdgeRuntime<"u")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":QB,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":globalThis.process.version};if(J==="node")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":QB,"X-Stainless-OS":Dv0(globalThis.process.platform??"unknown"),"X-Stainless-Arch":Nv0(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};let Q=Yg4();if(Q)return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":QB,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":`browser:${Q.browser}`,"X-Stainless-Runtime-Version":Q.version};return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":QB,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}},Nv0=(J)=>{if(J==="x32")return"x32";if(J==="x86_64"||J==="x64")return"x64";if(J==="arm")return"arm";if(J==="aarch64"||J==="arm64")return"arm64";if(J)return`other:${J}`;return"unknown"},Dv0=(J)=>{if(J=J.toLowerCase(),J.includes("ios"))return"iOS";if(J==="android")return"Android";if(J==="darwin")return"MacOS";if(J==="win32")return"Windows";if(J==="freebsd")return"FreeBSD";if(J==="openbsd")return"OpenBSD";if(J==="linux")return"Linux";if(J)return`Other:${J}`;return"Unknown"},Mv0,Ov0=()=>{return Mv0??(Mv0=Qg4())};var AM1=()=>{};function Av0(){if(typeof fetch<"u")return fetch;throw Error("`fetch` is not defined as a global; Either pass `fetch` to the client, `new OpenAI({ fetch })` or polyfill the global, `globalThis.fetch = fetch`")}function wM1(...J){let Q=globalThis.ReadableStream;if(typeof Q>"u")throw Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");return new Q(...J)}function xs(J){let Q=Symbol.asyncIterator in J?J[Symbol.asyncIterator]():J[Symbol.iterator]();return wM1({start(){},async pull(Y){let{done:X,value:G}=await Q.next();if(X)Y.close();else Y.enqueue(G)},async cancel(){await Q.return?.()}})}function EM1(J){if(J[Symbol.asyncIterator])return J;let Q=J.getReader();return{async next(){try{let Y=await Q.read();if(Y?.done)Q.releaseLock();return Y}catch(Y){throw Q.releaseLock(),Y}},async return(){let Y=Q.cancel();return Q.releaseLock(),await Y,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}async function wv0(J){if(J===null||typeof J!=="object")return;if(J[Symbol.asyncIterator]){await J[Symbol.asyncIterator]().return?.();return}let Q=J.getReader(),Y=Q.cancel();Q.releaseLock(),await Y}var Ev0=({headers:J,body:Q})=>{return{bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(Q)}};var vs="RFC3986",IM1=(J)=>String(J),fs,PM1="RFC1738";var hs=Z1(()=>{fs={RFC1738:(J)=>String(J).replace(/%20/g,"+"),RFC3986:IM1}});function Pv0(J){if(!J||typeof J!=="object")return!1;return!!(J.constructor&&J.constructor.isBuffer&&J.constructor.isBuffer(J))}function RM1(J,Q){if(HQ(J)){let Y=[];for(let X=0;X<J.length;X+=1)Y.push(Q(J[X]));return Y}return Q(J)}var bs=(J,Q)=>(bs=Object.hasOwn??Function.prototype.call.bind(Object.prototype.hasOwnProperty),bs(J,Q)),MK,TM1=1024,Iv0=(J,Q,Y,X,G)=>{if(J.length===0)return J;let Z=J;if(typeof J==="symbol")Z=Symbol.prototype.toString.call(J);else if(typeof J!=="string")Z=String(J);if(Y==="iso-8859-1")return escape(Z).replace(/%u[0-9a-f]{4}/gi,function(V){return"%26%23"+parseInt(V.slice(2),16)+"%3B"});let q="";for(let V=0;V<Z.length;V+=TM1){let K=Z.length>=TM1?Z.slice(V,V+TM1):Z,W=[];for(let H=0;H<K.length;++H){let z=K.charCodeAt(H);if(z===45||z===46||z===95||z===126||z>=48&&z<=57||z>=65&&z<=90||z>=97&&z<=122||G===PM1&&(z===40||z===41)){W[W.length]=K.charAt(H);continue}if(z<128){W[W.length]=MK[z];continue}if(z<2048){W[W.length]=MK[192|z>>6]+MK[128|z&63];continue}if(z<55296||z>=57344){W[W.length]=MK[224|z>>12]+MK[128|z>>6&63]+MK[128|z&63];continue}H+=1,z=65536+((z&1023)<<10|K.charCodeAt(H)&1023),W[W.length]=MK[240|z>>18]+MK[128|z>>12&63]+MK[128|z>>6&63]+MK[128|z&63]}q+=W.join("")}return q};var Tv0=Z1(()=>{hs();uH();MK=(()=>{let J=[];for(let Q=0;Q<256;++Q)J.push("%"+((Q<16?"0":"")+Q.toString(16)).toUpperCase());return J})()});function Zg4(J){return typeof J==="string"||typeof J==="number"||typeof J==="boolean"||typeof J==="symbol"||typeof J==="bigint"}function Sv0(J,Q,Y,X,G,Z,q,V,K,W,H,z,U,N,M,L,O,E){let I=J,P=E,R=0,S=!1;while((P=P.get(CM1))!==void 0&&!S){let b=P.get(J);if(R+=1,typeof b<"u")if(b===R)throw RangeError("Cyclic object value");else S=!0;if(typeof P.get(CM1)>"u")R=0}if(typeof W==="function")I=W(Q,I);else if(I instanceof Date)I=U?.(I);else if(Y==="comma"&&HQ(I))I=RM1(I,function(b){if(b instanceof Date)return U?.(b);return b});if(I===null){if(Z)return K&&!L?K(Q,D3.encoder,O,"key",N):Q;I=""}if(Zg4(I)||Pv0(I)){if(K){let b=L?Q:K(Q,D3.encoder,O,"key",N);return[M?.(b)+"="+M?.(K(I,D3.encoder,O,"value",N))]}return[M?.(Q)+"="+M?.(String(I))]}let y=[];if(typeof I>"u")return y;let f;if(Y==="comma"&&HQ(I)){if(L&&K)I=RM1(I,K);f=[{value:I.length>0?I.join(",")||null:void 0}]}else if(HQ(W))f=W;else{let b=Object.keys(I);f=H?b.sort(H):b}let m=V?String(Q).replace(/\./g,"%2E"):String(Q),p=X&&HQ(I)&&I.length===1?m+"[]":m;if(G&&HQ(I)&&I.length===0)return p+"[]";for(let b=0;b<f.length;++b){let i=f[b],J1=typeof i==="object"&&typeof i.value<"u"?i.value:I[i];if(q&&J1===null)continue;let n=z&&V?i.replace(/\./g,"%2E"):i,u=HQ(I)?typeof Y==="function"?Y(p,n):p:p+(z?"."+n:"["+n+"]");E.set(J,R);let s=new WeakMap;s.set(CM1,E),jv0(y,Sv0(J1,u,Y,X,G,Z,q,V,Y==="comma"&&L&&HQ(I)?null:K,W,H,z,U,N,M,L,O,s))}return y}function $g4(J=D3){if(typeof J.allowEmptyArrays<"u"&&typeof J.allowEmptyArrays!=="boolean")throw TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");if(typeof J.encodeDotInKeys<"u"&&typeof J.encodeDotInKeys!=="boolean")throw TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided");if(J.encoder!==null&&typeof J.encoder<"u"&&typeof J.encoder!=="function")throw TypeError("Encoder has to be a function.");let Q=J.charset||D3.charset;if(typeof J.charset<"u"&&J.charset!=="utf-8"&&J.charset!=="iso-8859-1")throw TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");let Y=vs;if(typeof J.format<"u"){if(!bs(fs,J.format))throw TypeError("Unknown format option provided.");Y=J.format}let X=fs[Y],G=D3.filter;if(typeof J.filter==="function"||HQ(J.filter))G=J.filter;let Z;if(J.arrayFormat&&J.arrayFormat in Cv0)Z=J.arrayFormat;else if("indices"in J)Z=J.indices?"indices":"repeat";else Z=D3.arrayFormat;if("commaRoundTrip"in J&&typeof J.commaRoundTrip!=="boolean")throw TypeError("`commaRoundTrip` must be a boolean, or absent");let q=typeof J.allowDots>"u"?!!J.encodeDotInKeys===!0?!0:D3.allowDots:!!J.allowDots;return{addQueryPrefix:typeof J.addQueryPrefix==="boolean"?J.addQueryPrefix:D3.addQueryPrefix,allowDots:q,allowEmptyArrays:typeof J.allowEmptyArrays==="boolean"?!!J.allowEmptyArrays:D3.allowEmptyArrays,arrayFormat:Z,charset:Q,charsetSentinel:typeof J.charsetSentinel==="boolean"?J.charsetSentinel:D3.charsetSentinel,commaRoundTrip:!!J.commaRoundTrip,delimiter:typeof J.delimiter>"u"?D3.delimiter:J.delimiter,encode:typeof J.encode==="boolean"?J.encode:D3.encode,encodeDotInKeys:typeof J.encodeDotInKeys==="boolean"?J.encodeDotInKeys:D3.encodeDotInKeys,encoder:typeof J.encoder==="function"?J.encoder:D3.encoder,encodeValuesOnly:typeof J.encodeValuesOnly==="boolean"?J.encodeValuesOnly:D3.encodeValuesOnly,filter:G,format:Y,formatter:X,serializeDate:typeof J.serializeDate==="function"?J.serializeDate:D3.serializeDate,skipNulls:typeof J.skipNulls==="boolean"?J.skipNulls:D3.skipNulls,sort:typeof J.sort==="function"?J.sort:null,strictNullHandling:typeof J.strictNullHandling==="boolean"?J.strictNullHandling:D3.strictNullHandling}}function jM1(J,Q={}){let Y=J,X=$g4(Q),G,Z;if(typeof X.filter==="function")Z=X.filter,Y=Z("",Y);else if(HQ(X.filter))Z=X.filter,G=Z;let q=[];if(typeof Y!=="object"||Y===null)return"";let V=Cv0[X.arrayFormat],K=V==="comma"&&X.commaRoundTrip;if(!G)G=Object.keys(Y);if(X.sort)G.sort(X.sort);let W=new WeakMap;for(let U=0;U<G.length;++U){let N=G[U];if(X.skipNulls&&Y[N]===null)continue;jv0(q,Sv0(Y[N],N,V,K,X.allowEmptyArrays,X.strictNullHandling,X.skipNulls,X.encodeDotInKeys,X.encode?X.encoder:null,X.filter,X.sort,X.allowDots,X.serializeDate,X.format,X.formatter,X.encodeValuesOnly,X.charset,W))}let H=q.join(X.delimiter),z=X.addQueryPrefix===!0?"?":"";if(X.charsetSentinel)if(X.charset==="iso-8859-1")z+="utf8=%26%2310003%3B&";else z+="utf8=%E2%9C%93&";return H.length>0?z+H:""}var Cv0,jv0=function(J,Q){Array.prototype.push.apply(J,HQ(Q)?Q:[Q])},Rv0,D3,CM1;var _v0=Z1(()=>{Tv0();hs();uH();Cv0={brackets(J){return String(J)+"[]"},comma:"comma",indices(J,Q){return String(J)+"["+Q+"]"},repeat(J){return String(J)}},D3={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:Iv0,encodeValuesOnly:!1,format:vs,formatter:IM1,indices:!1,serializeDate(J){return(Rv0??(Rv0=Function.prototype.call.bind(Date.prototype.toISOString)))(J)},skipNulls:!1,strictNullHandling:!1};CM1={}});var kv0=Z1(()=>{hs();_v0()});function vv0(J){let Q=0;for(let G of J)Q+=G.length;let Y=new Uint8Array(Q),X=0;for(let G of J)Y.set(G,X),X+=G.length;return Y}function $T(J){let Q;return(yv0??(Q=new globalThis.TextEncoder,yv0=Q.encode.bind(Q)))(J)}function SM1(J){let Q;return(xv0??(Q=new globalThis.TextDecoder,xv0=Q.decode.bind(Q)))(J)}var yv0,xv0;class qT{constructor(){sX.set(this,void 0),tX.set(this,void 0),j4(this,sX,new Uint8Array,"f"),j4(this,tX,null,"f")}decode(J){if(J==null)return[];let Q=J instanceof ArrayBuffer?new Uint8Array(J):typeof J==="string"?$T(J):J;j4(this,sX,vv0([E0(this,sX,"f"),Q]),"f");let Y=[],X;while((X=Vg4(E0(this,sX,"f"),E0(this,tX,"f")))!=null){if(X.carriage&&E0(this,tX,"f")==null){j4(this,tX,X.index,"f");continue}if(E0(this,tX,"f")!=null&&(X.index!==E0(this,tX,"f")+1||X.carriage)){Y.push(SM1(E0(this,sX,"f").subarray(0,E0(this,tX,"f")-1))),j4(this,sX,E0(this,sX,"f").subarray(E0(this,tX,"f")),"f"),j4(this,tX,null,"f");continue}let G=E0(this,tX,"f")!==null?X.preceding-1:X.preceding,Z=SM1(E0(this,sX,"f").subarray(0,G));Y.push(Z),j4(this,sX,E0(this,sX,"f").subarray(X.index),"f"),j4(this,tX,null,"f")}return Y}flush(){if(!E0(this,sX,"f").length)return[];return this.decode(`
2231
+ `),Q,{configService:Y.configService},X,bV(Q)?.messageId,Z),z;for await(let U of H)if(z=hb4(z,U),z)yield bb4(z)}}function UM1(J){let{summaryBlock:Q,index:Y}=eG(J)??{summaryBlock:void 0,index:0},X=[];if(Q&&Q.summary.type==="message")X.push({role:"model",parts:[{text:Q.summary.summary.trimEnd()}]});for(let G=Y+(Q?1:0);G<J.messages.length;G++){let Z=J.messages[G];if(!Z)continue;switch(Z.role){case"user":{let q=vb4(Z,J);if(q.length===0)continue;X.push({role:"user",parts:q});break}case"assistant":{let q=Z.content.filter((W)=>{if(W.type==="tool_use"&&!W.complete)return!1;return!0}),V=$Q(J);for(let W of q)if(W.type==="tool_use"){if(!V.get(W.id)?.run)throw Error(`(bug) corresponding tool_result not found for tool_use (id=${W.id}, name=${W.name})`)}if(Z.nativeMessage?.type==="vertexai"){let W=Z.nativeMessage.message.candidates?.[0]?.content,H={role:W?.role??"model",parts:W?.parts??[]};X.push(c8(H));break}if(q.length===0)break;let K=fb4(q);if(K.length>0)X.push({role:"model",parts:K});break}case"info":{let q=[];for(let V of Z.content)if(V.type==="manual_bash_invocation"){let K=oU(V);q.push(...K.map((W)=>({text:W.text})))}else if(V.type==="text"&&V.text.trim().length>0)q.push({text:V.text});if(q.length>0)X.push({role:"user",parts:q});break}}}return X}function BM1(J){let Q=Object.values(z8).find((Y)=>Y.provider===l8.VERTEXAI&&Y.name===J);if(Q===void 0)return x.warn(`Unknown gemini model ${J}`),{...z8.GEMINI_2_5_PRO,name:J,displayName:J};return Q}async function*NM1(J,Q,Y,X,G,Z,q,V,K){let W=BM1(J),H=await Z.configService.getLatest(q),z=await tx0(H,{threadMeta:G,messageId:V,clientRequestId:K}),U={model:W.name,contents:c8(Q),config:{seed:Date.now()%1e4,tools:sx0(Y),systemInstruction:X,maxOutputTokens:W.maxOutputTokens,temperature:1,thinkingConfig:{includeThoughts:!0,thinkingLevel:H.settings["gemini.thinkingLevel"]==="low"?mx.LOW:H.settings["gemini.thinkingLevel"]==="high"?mx.HIGH:void 0},abortSignal:q}},N=await z.models.generateContentStream(U),M;for await(let L of N)M=L,yield L;return{model:J,"~debugParamsUsed":{model:W,streamParams:U},"~debugUsage":{model:J,maxInputTokens:W.contextWindow-W.maxOutputTokens,inputTokens:0,outputTokens:(M?.usageMetadata?.candidatesTokenCount??0)+(M?.usageMetadata?.thoughtsTokenCount??0),totalInputTokens:M?.usageMetadata?.promptTokenCount??0,cacheCreationInputTokens:(M?.usageMetadata?.promptTokenCount??0)-(M?.usageMetadata?.cachedContentTokenCount??0),cacheReadInputTokens:M?.usageMetadata?.cachedContentTokenCount??0,credits:0}}}async function Rs(J,Q,Y,X,G,Z,q,V){let K=BM1(J),H=await(await tx0(G,{threadMeta:X,clientRequestId:V})).models.generateContent({model:K.name,contents:c8(Q),config:{tools:sx0(Y),seed:Date.now()%1e4,temperature:0.1,maxOutputTokens:K.maxOutputTokens,abortSignal:Z,...q}});return{message:H,"~debugUsage":{model:K.name,maxInputTokens:K.contextWindow-K.maxOutputTokens,inputTokens:0,outputTokens:(H.usageMetadata?.candidatesTokenCount??0)+(H.usageMetadata?.thoughtsTokenCount??0),totalInputTokens:H.usageMetadata?.promptTokenCount??0,cacheCreationInputTokens:(H.usageMetadata?.promptTokenCount??0)-(H.usageMetadata?.cachedContentTokenCount??0),cacheReadInputTokens:H.usageMetadata?.cachedContentTokenCount??0,credits:0}}}function sx0(J){if(J.length===0)return[];return[{functionDeclarations:[...J.map(yb4)]}]}function yb4(J){return{name:J.name,description:J.description??"",parameters:zM1(J.inputSchema)}}function zM1(J){let Q={},Y=xb4[J.type??"any"];if(Y)Q.type=Y;if(J.description)Q.description=J.description;if(J.required)Q.required=J.required;let X=J.examples;if(Array.isArray(X)&&X.length>0)Q.example=X[0];if(J.properties)Q.properties=Object.fromEntries(Object.entries(J.properties).map(([G,Z])=>[G,zM1(Z)]));if(J.items)Q.items=zM1(J.items);return Q}async function tx0(J,Q){let{settings:Y,secrets:X}=J,{url:G}=Y,Z=await X.getToken("apiKey",G);if(!Z)throw Error("API key not found. You must provide an API key in settings.");let q={GOOGLE_CLOUD_PROJECT:process.env.GOOGLE_CLOUD_PROJECT,GCLOUD_PROJECT:process.env.GCLOUD_PROJECT,GOOGLE_APPLICATION_CREDENTIALS:process.env.GOOGLE_APPLICATION_CREDENTIALS};delete process.env.GOOGLE_CLOUD_PROJECT,delete process.env.GCLOUD_PROJECT,delete process.env.GOOGLE_APPLICATION_CREDENTIALS;let V=new FB1({apiKey:"placeholder",vertexai:!0,googleAuthOptions:{},httpOptions:{baseUrl:new URL("/api/provider/google",G).toString(),headers:{Authorization:"Bearer "+Z,[RY]:"amp.chat",...Q?.messageId!=null?{[JZ]:String(Q.messageId)}:{},...Q?.clientRequestId!=null?{[CY]:Q.clientRequestId}:{},...jY(Q?.threadMeta)}}});for(let[K,W]of Object.entries(q))if(W!==void 0)process.env[K]=W;return V}function vb4(J,Q){let Y=[];if(J.fileMentions&&J.fileMentions.files.length>0)Y.push({text:HZ(J.fileMentions)});if(J.userState)Y.push({text:WK(J.userState)});for(let X of J.content)if(X.type==="text")Y.push({text:X.text});else if(X.type==="image"){if(X.source.type==="base64"&&"mediaType"in X.source&&"data"in X.source)Y.push({inlineData:{mimeType:X.source.mediaType,data:X.source.data}});else if(X.source.type==="url"&&"url"in X.source)Y.push({text:`[Image URL: ${X.source.url}]`})}else if(X.type==="tool_result"){let G={};if(X.run.status==="done")G.output=X.run.result;else if(X.run.status==="error")G.error=X.run.error?.message??"Error executing tool";else G.error=`Tool status: ${X.run.status}`;let Z,[,q]=X.toolUseID.split("__");if(q)Z=q;else for(let K of Q.messages)if(K.role==="assistant"){for(let W of K.content)if(W.type==="tool_use"&&W.id===X.toolUseID){Z=W.name;break}if(Z)break}if(!Z)throw Error(`Could not find tool name for tool_result with ID: ${X.toolUseID}`);let V={name:Z,response:G};Y.push({functionResponse:V})}return Y}function fb4(J){let Q=[];for(let Y of J)if(Y.type==="text")Q.push({text:Y.text});else if(Y.type==="tool_use")Q.push({functionCall:{name:Y.name,args:Y.input??{}}});else if(Y.type==="thinking")Q.push({text:Y.thinking,thought:!0,thoughtSignature:Y.signature});else if(Y.type==="redacted_thinking")Q.push({text:"[Redacted thinking]"});return Q}function hb4(J,Q){if(!J)return Q;let Y=J.candidates&&Q.candidates?J.candidates.map((G,Z)=>{let q=Q.candidates?.[Z];if(!q)return G;return{...q,content:{role:q.content?.role??G.content?.role??"model",parts:[...G.content?.parts??[],...q.content?.parts??[]]}}}):Q.candidates,X=new RU;return Object.assign(X,{...Q,candidates:Y}),X}function bb4(J){function Q(){let G=[];for(let Z of J.candidates?.at(0)?.content?.parts??[])if(Z.text&&Z.thought){let q=G.at(-1);if(q?.type==="thinking")G[G.length-1]={type:"thinking",thinking:q.thinking+Z.text,signature:"",provider:"vertexai"};else G.push({type:"thinking",thinking:Z.text,signature:"",provider:"vertexai"})}else if(Z.text){let q=G.at(-1);if(q?.type==="text")G[G.length-1]={type:"text",text:q.text+Z.text};else G.push({type:"text",text:Z.text})}else if(Z.functionCall)G.push({type:"tool_use",complete:!0,id:Z.functionCall.id??_M(),name:Z.functionCall.name??"",input:Z.functionCall.args??{}});return G}function Y(){if(!J.usageMetadata)return;let G=BM1(J.modelVersion??"");return{model:G.name,maxInputTokens:G.contextWindow-G.maxOutputTokens,inputTokens:0,cacheReadInputTokens:J.usageMetadata?.cachedContentTokenCount??0,cacheCreationInputTokens:(J.usageMetadata?.promptTokenCount??0)-(J.usageMetadata?.cachedContentTokenCount??0),outputTokens:(J.usageMetadata?.totalTokenCount??0)-(J.usageMetadata?.promptTokenCount??0),totalInputTokens:J.usageMetadata?.promptTokenCount??0,credits:0}}function X(){let G=J.candidates?.at(0)?.finishReason,Z=J.candidates?.at(0)?.finishMessage;switch(G){case m3.STOP:{if(J.candidates?.at(0)?.content?.parts?.some((V)=>V.functionCall!==void 0))return{type:"complete",stopReason:"tool_use"};return{type:"complete",stopReason:"end_turn"}}case m3.MAX_TOKENS:return{type:"complete",stopReason:"max_tokens"};case m3.BLOCKLIST:case m3.SAFETY:case m3.RECITATION:case m3.LANGUAGE:case m3.PROHIBITED_CONTENT:case m3.IMAGE_PROHIBITED_CONTENT:case m3.IMAGE_SAFETY:case m3.SPII:case m3.OTHER:case m3.FINISH_REASON_UNSPECIFIED:case m3.NO_IMAGE:return{type:"error",error:{message:`provider refused to continue with code '${G}': ${Z}`}};case m3.UNEXPECTED_TOOL_CALL:case m3.MALFORMED_FUNCTION_CALL:return{type:"error",error:{message:`provider failed with code '${G}': ${Z}`}};case void 0:return{type:"streaming"}}}return{role:"assistant",content:Q(),state:X(),usage:Y(),nativeMessage:{type:"vertexai",message:J}}}var g99,m99,rx0,u99,xb4;var Mf=Z1(()=>{lo();lo();PY();U0();_U();gV();vH();M9();RL();D5();b5();sv();g99=z8.GEMINI_2_5_PRO.name,m99=z8.GEMINI_2_5_FLASH_LITE.name,rx0=z8.GEMINI_2_5_FLASH_LITE_PREVIEW_09_2025.name,u99=z8.GEMINI_2_5_FLASH_PREVIEW_09_2025.name;xb4={string:hQ.STRING,number:hQ.NUMBER,integer:hQ.INTEGER,boolean:hQ.BOOLEAN,object:hQ.OBJECT,array:hQ.ARRAY}});function ex0(J){return J+ ++gb4}var gb4=0;function Jv0(J){if(!J._regex)try{J._regex=new RegExp(J.pattern,J.caseInsensitive?"gi":"g")}catch(Q){x.warn("Error compiling regex",{pattern:J.id,error:Q}),J._regex=new RegExp("$^")}return J._regex}var Qv0;var Yv0=Z1(()=>{U0();Qv0=[{id:"sourcegraph-access-token-v3",category:"sourcegraph",title:"Sourcegraph Access Token (v3)",pattern:String.raw`(sgp_(?:[a-fA-F0-9]{16}|local)_[a-fA-F0-9]{40})`,keywords:["sgp_"]},{id:"sourcegraph-access-token-v2",category:"sourcegraph",title:"Sourcegraph Access Token (v2, deprecated)",pattern:String.raw`(sgp_[a-fA-F0-9]{40})`,keywords:["sgp_"]},{id:"sourcegraph-dotcom-user-gateway",category:"sourcegraph",title:"Sourcegraph Dotcom User Gateway Access Token",pattern:String.raw`(sgd_[a-fA-F0-9]{64})`,keywords:["sgd_"]},{id:"sourcegraph-license-key",category:"sourcegraph",title:"Sourcegraph License Key Token",pattern:String.raw`(slk_[a-fA-F0-9]{64})`,keywords:["slk_"]},{id:"sourcegraph-enterprise-subscription",category:"sourcegraph",title:"Sourcegraph Enterprise subscription Token",pattern:String.raw`(sgs_[a-fA-F0-9]{64})`,keywords:["sgs_"]},{id:"sourcegraph-amp",category:"sourcegraph",title:"Sourcegraph Amp Access Token",pattern:String.raw`(sgamp_user_[A-Z0-9]{26}_[a-f0-9]{64})`,keywords:["sgamp_user_"]},{id:"sourcegraph-amp-auth-bypass",category:"sourcegraph",title:"Sourcegraph Amp Auth Bypass Token",pattern:String.raw`(sgamp_user_auth-bypass_[a-zA-Z0-9_-]+)`,keywords:["sgamp_user_auth-bypass_"]},{id:"sourcegraph-workspace-token",category:"sourcegraph",title:"Sourcegraph Workspace Access Token",pattern:String.raw`(sgp_ws[a-fA-F0-9]{32}_[a-fA-F0-9]{40})`,keywords:["sgp_ws"]},{id:"github-pat",category:"github",title:"GitHub Personal Access Token",pattern:String.raw`(ghp_[0-9a-zA-Z]{36})`,keywords:["ghp_"]},{id:"github-oauth",category:"github",title:"GitHub OAuth Access Token",pattern:String.raw`(gho_[0-9a-zA-Z]{36})`,keywords:["gho_"]},{id:"github-app-token",category:"github",title:"GitHub App Token",pattern:String.raw`((ghu|ghs)_[0-9a-zA-Z]{36})`,keywords:["ghu_","ghs_"]},{id:"github-refresh-token",category:"github",title:"GitHub Refresh Token",pattern:String.raw`(ghr_[0-9a-zA-Z]{76})`,keywords:["ghr_"]},{id:"github-fine-grained-pat",category:"github",title:"GitHub Fine-grained personal access tokens",pattern:String.raw`(github_pat_[a-zA-Z0-9]{22}_[a-zA-Z0-9]{59})`,keywords:["github_pat_"]},{id:"gitlab-pat",category:"gitlab",title:"GitLab Personal Access Token",pattern:String.raw`(glpat-[0-9a-zA-Z_-]{20})`,keywords:["glpat-"]},{id:"aws-access-key-id",category:"aws",title:"AWS Access Key ID",pattern:String.raw`((A3T[A-Z0-9]|AKIA|AGPA|AIDA|AROA|AIPA|ANPA|ANVA|ASIA)[A-Z0-9]{16})`,keywords:["AKIA","AGPA","AIDA","AROA","AIPA","ANPA","ANVA","ASIA"]},{id:"hugging-face-access-token",category:"huggingface",title:"Hugging Face Access Token",pattern:String.raw`(hf_[A-Za-z0-9]{34,40})`,keywords:["hf_"]},{id:"private-key",category:"asymmetric-private-key",title:"Asymmetric Private Key",pattern:String.raw`-----\s*?BEGIN[ A-Z0-9_-]*?PRIVATE KEY(?: BLOCK)?\s*?-----\s*([A-Za-z0-9=+/\s]+)\s*-----\s*?END[ A-Z0-9_-]*? PRIVATE KEY(?: BLOCK)?\s*?-----`,keywords:["-----"],caseInsensitive:!0},{id:"shopify-token",category:"shopify",title:"Shopify token",pattern:String.raw`(shp(ss|at|ca|pa)_[a-fA-F0-9]{32})`,keywords:["shpss_","shpat_","shpca_","shppa_"]},{id:"slack-access-token",category:"slack",title:"Slack token",pattern:String.raw`((xox[baoprs]-|xapp-|xwfp-)([0-9a-zA-Z-]{10,100}))`,keywords:["xoxb-","xoxa-","xoxp-","xoxr-","xoxs-","xoxo-","xapp-","xwfp-"]},{id:"slack-config-refresh-token",category:"slack",title:"Slack config refresh token",pattern:String.raw`(xoxe-\d-[a-zA-Z0-9]{146})`,caseInsensitive:!0,keywords:["xoxe-"]},{id:"slack-config-access-token",category:"slack",title:"Slack config access token",pattern:String.raw`(xoxe.xox[bp]-\d-[A-Z0-9]{163,166})`,caseInsensitive:!0,keywords:["xoxe.xoxb-","xoxe.xoxp-"]},{id:"slack-web-hook",category:"slack",title:"Slack Webhook",pattern:String.raw`(https:\/\/hooks\.slack\.com\/(services|triggers|workflows)\/[A-Za-z0-9+\/]{43,56})`,caseInsensitive:!0,keywords:["hooks.slack.com"]},{id:"stripe-secret-token",category:"stripe",title:"Stripe Secret Key",pattern:String.raw`(sk_(test|live)_[0-9a-z]{10,99})`,keywords:["sk_test_","sk_live_"],caseInsensitive:!0},{id:"supabase-service-key",category:"supabase",title:"Supabase Service Key",pattern:String.raw`(sbp_[a-fA-F0-9]{40})`,keywords:["sbp_"]},{id:"pypi-upload-token",category:"pypi",title:"PyPI upload token",pattern:String.raw`(pypi-AgEIcHlwaS5vcmc[A-Za-z0-9_-]{50,1000})`,keywords:["pypi-AgEIcHlwaS5vcmc"]},{id:"gcp-service-account",category:"google",title:"Google (GCP) Service-account",pattern:String.raw`("type": "service_account")`,keywords:['"type": "service_account"']},{id:"heroku-api-key",category:"heroku",title:"Heroku API Key",pattern:String.raw`(?:heroku[a-z0-9_ .,-]{0,25})(?:=|>|:=|\|\|:|<=|=>|:).{0,5}['"](\d[0-9A-F]{8}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{12})['"]`,keywords:["heroku"],caseInsensitive:!0},{id:"twilio-api-key",category:"twilio",title:"Twilio API Key",pattern:String.raw`(SK[0-9a-fA-F]{32})`,keywords:["SK"]},{id:"age-secret-key",category:"age",title:"Age secret key",pattern:String.raw`(AGE-SECRET-KEY-1[QPZRY9X8GF2TVDW0S3JN54KHCE6MUA7L]{58})`,keywords:["AGE-SECRET-KEY-1"]},{id:"jwt-token",category:"jwt",title:"JWT token",pattern:String.raw`(ey[a-zA-Z0-9]{17,}\.ey[a-zA-Z0-9/\\_-]{17,}\.(?:[a-zA-Z0-9/\\_-]{10,}={0,2})?)`,keywords:[".eyJ"]},{id:"npm-access-token",category:"npm",title:"npm access token",pattern:String.raw`(npm_[a-z0-9]{36})`,keywords:["npm_"],caseInsensitive:!0},{id:"sendgrid-api-token",category:"sendgrid",title:"SendGrid API token",pattern:String.raw`(SG\.[a-z0-9_.-]{66})`,keywords:["SG."],caseInsensitive:!0},{id:"aws-secret-access-key",category:"aws",title:"AWS Secret Access Key",pattern:String.raw`(aws[_-]secret[_-]access[_-]key[_-][A-Za-z0-9/+=]{40})`,keywords:["key"],caseInsensitive:!0},{id:"dockerconfig-secret",category:"docker",title:"Dockerconfig secret exposed",pattern:String.raw`((\.dockerconfigjson|dockercfg):\s*\|*\s*((ey|ew)+[A-Za-z0-9/+=]+))`,keywords:["dockerc"],caseInsensitive:!0},{id:"linear-api-token",category:"linear",title:"Linear API token",pattern:String.raw`(lin_api_[a-z0-9]{40})`,keywords:["lin_api_"],caseInsensitive:!0},{id:"sendinblue-api-token",category:"sendinblue",title:"Sendinblue API token",pattern:String.raw`(xkeysib-[a-f0-9]{64}-[a-z0-9]{16})`,keywords:["xkeysib-"],caseInsensitive:!0},{id:"planetscale-api-token",category:"planetscale",title:"PlanetScale API token",pattern:String.raw`(pscale_tkn_[a-z0-9_.-]{43})`,keywords:["pscale_tkn_"],caseInsensitive:!0},{id:"doppler-api-token",category:"doppler",title:"Doppler API token",pattern:String.raw`(dp\.pt\.[a-z0-9]{43})`,keywords:["dp.pt."],caseInsensitive:!0},{id:"discord-api-token",category:"discord",title:"Discord API key",pattern:String.raw`(?:discord[a-z0-9_ .,-]{0,25})(?:=|>|:=|\|\|:|<=|=>|:).{0,5}['"]([a-h0-9]{64})['"]`,keywords:["discord"],caseInsensitive:!0},{id:"pulumi-api-token",category:"pulumi",title:"Pulumi API token",pattern:String.raw`(pul-[a-f0-9]{40})`,keywords:["pul-"]},{id:"postman-api-token",category:"postman",title:"Postman API token",pattern:String.raw`(PMAK-[a-f0-9]{24}-[a-f0-9]{34})`,keywords:["PMAK-"],caseInsensitive:!0},{id:"facebook-token",category:"facebook",title:"Facebook token",pattern:String.raw`(?:facebook[a-z0-9_ .,-]{0,25})(?:=|>|:=|\|\|:|<=|=>|:).{0,5}['"]([a-f0-9]{32})['"]`,keywords:["facebook"],caseInsensitive:!0},{id:"twitter-token",category:"twitter",title:"Twitter token",pattern:String.raw`(?:twitter[a-z0-9_ .,-]{0,25})(?:=|>|:=|\|\|:|<=|=>|:).{0,5}['"]([a-f0-9]{35,44})['"]`,keywords:["twitter"],caseInsensitive:!0},{id:"adobe-client-id",category:"adobe",title:"Adobe Client ID (Oauth Web)",pattern:String.raw`(?:adobe[a-z0-9_ .,-]{0,25})(?:=|>|:=|\|\|:|<=|=>|:).{0,5}['"]([a-f0-9]{32})['"]`,keywords:["adobe"],caseInsensitive:!0},{id:"adobe-client-secret",category:"adobe",title:"Adobe Client Secret",pattern:String.raw`(p8e-[a-z0-9]{32})`,keywords:["p8e-"],caseInsensitive:!0},{id:"alibaba-access-key-id",category:"alibaba",title:"Alibaba AccessKey ID",pattern:String.raw`((LTAI)[a-z0-9]{20})`,keywords:["LTAI"],caseInsensitive:!0},{id:"alibaba-secret-key",category:"alibaba",title:"Alibaba Secret Key",pattern:String.raw`(?:alibaba[a-z0-9_ .,-]{0,25})(?:=|>|:=|\|\|:|<=|=>|:).{0,5}['"]([a-z0-9]{30})['"]`,keywords:["alibaba"],caseInsensitive:!0},{id:"asana-client-id",category:"asana",title:"Asana Client ID",pattern:String.raw`(?:asana[a-z0-9_ .,-]{0,25})(?:=|>|:=|\|\|:|<=|=>|:).{0,5}['"]([0-9]{16})['"]`,keywords:["asana"],caseInsensitive:!0},{id:"asana-client-secret",category:"asana",title:"Asana Client Secret",pattern:String.raw`(?:asana[a-z0-9_ .,-]{0,25})(?:=|>|:=|\|\|:|<=|=>|:).{0,5}['"]([a-z0-9]{32})['"]`,keywords:["asana"],caseInsensitive:!0},{id:"atlassian-api-token",category:"atlassian",title:"Atlassian API token",pattern:String.raw`(?:atlassian[a-z0-9_ .,-]{0,25})(?:=|>|:=|\|\|:|<=|=>|:).{0,5}['"]([a-z0-9]{24})['"]`,keywords:["atlassian"],caseInsensitive:!0},{id:"beamer-api-token",category:"beamer",title:"Beamer API token",pattern:String.raw`(?:beamer[a-z0-9_ .,-]{0,25})(?:=|>|:=|\|\|:|<=|=>|:).{0,5}['"](b_[a-z0-9=_-]{44})['"]`,keywords:["beamer"],caseInsensitive:!0},{id:"buildkite-agent-token",category:"buildkite",title:"Buildkite API Token V2",pattern:String.raw`(bkua_[a-fA-F0-9]{40})`,keywords:["bkua_"]},{id:"clojars-api-token",category:"clojars",title:"Clojars API token",pattern:String.raw`(CLOJARS_[a-z0-9]{60})`,keywords:["CLOJARS_"],caseInsensitive:!0},{id:"contentful-delivery-api-token",category:"contentful-delivery",title:"Contentful delivery API token",pattern:String.raw`(?:contentful[a-z0-9_ .,-]{0,25})(?:=|>|:=|\|\|:|<=|=>|:).{0,5}['"]([a-z0-9=_-]{43})['"]`,keywords:["contentful"],caseInsensitive:!0},{id:"databricks-api-token",category:"databricks",title:"Databricks API token",pattern:String.raw`(dapi[a-h0-9]{32})`,keywords:["dapi"]},{id:"discord-client-id",category:"discord",title:"Discord client ID",pattern:String.raw`(?:discord[a-z0-9_ .,-]{0,25})(?:=|>|:=|\|\|:|<=|=>|:).{0,5}['"]([0-9]{18})['"]`,keywords:["discord"],caseInsensitive:!0},{id:"discord-client-secret",category:"discord",title:"Discord client secret",pattern:String.raw`(?:discord[a-z0-9_ .,-]{0,25})(?:=|>|:=|\|\|:|<=|=>|:).{0,5}['"]([a-z0-9=_-]{32})['"]`,keywords:["discord"],caseInsensitive:!0},{id:"dropbox-api-secret",category:"dropbox",title:"Dropbox API secret/key",pattern:String.raw`(?:dropbox[a-z0-9_ .,-]{0,25})(?:=|>|:=|\|\|:|<=|=>|:).{0,5}['"]([a-z0-9]{15})['"]`,keywords:["dropbox"],caseInsensitive:!0},{id:"dropbox-short-lived-api-token",category:"dropbox",title:"Dropbox short lived API token",pattern:String.raw`(?:dropbox[a-z0-9_ .,-]{0,25})(?:=|>|:=|\|\|:|<=|=>|:).{0,5}['"](sl\.[a-z0-9=_-]{135})['"]`,keywords:["dropbox"],caseInsensitive:!0},{id:"dropbox-long-lived-api-token",category:"dropbox",title:"Dropbox long lived API token",pattern:String.raw`(?:dropbox[a-z0-9_ .,-]{0,25})(?:=|>|:=|\|\|:|<=|=>|:).{0,5}['"]([a-z0-9]{11}(AAAAAAAAAA)[a-z0-9_=-]{43})['"]`,keywords:["dropbox"],caseInsensitive:!0},{id:"duffel-api-token",category:"duffel",title:"Duffel API token",pattern:String.raw`(duffel_(test|live)_[a-z0-9_-]{43})`,keywords:["duffel_test_","duffel_live_"],caseInsensitive:!0},{id:"dynatrace-api-token",category:"dynatrace",title:"Dynatrace API token",pattern:String.raw`(dt0c01\.[a-z0-9]{24}\.[a-z0-9]{64})`,keywords:["dt0c01."],caseInsensitive:!0},{id:"easypost-api-token",category:"easypost",title:"EasyPost API token",pattern:String.raw`(EZ[AT]K[a-z0-9]{54})`,keywords:["EZAK","EZAT"],caseInsensitive:!0},{id:"fastly-api-token",category:"fastly",title:"Fastly API token",pattern:String.raw`(?:fastly[a-z0-9_ .,-]{0,25})(?:=|>|:=|\|\|:|<=|=>|:).{0,5}['"]([a-z0-9=_-]{32})['"]`,keywords:["fastly"],caseInsensitive:!0},{id:"finicity-client-secret",category:"finicity",title:"Finicity client secret",pattern:String.raw`(?:finicity[a-z0-9_ .,-]{0,25})(?:=|>|:=|\|\|:|<=|=>|:).{0,5}['"]([a-z0-9]{20})['"]`,keywords:["finicity"],caseInsensitive:!0},{id:"finicity-api-token",category:"finicity",title:"Finicity API token",pattern:String.raw`(?:finicity[a-z0-9_ .,-]{0,25})(?:=|>|:=|\|\|:|<=|=>|:).{0,5}['"]([a-f0-9]{32})['"]`,keywords:["finicity"],caseInsensitive:!0},{id:"flutterwave-public-key",category:"flutterwave",title:"Flutterwave public/secret key",pattern:String.raw`(FLW(PUB|SEC)K_TEST-[a-h0-9]{32}-X)`,keywords:["FLWSECK_TEST-","FLWPUBK_TEST-"],caseInsensitive:!0},{id:"flutterwave-enc-key",category:"flutterwave",title:"Flutterwave encrypted key",pattern:String.raw`(FLWSECK_TEST[a-h0-9]{12})`,keywords:["FLWSECK_TEST"]},{id:"frameio-api-token",category:"frameio",title:"Frame.io API token",pattern:String.raw`(fio-u-[a-z0-9_=-]{64})`,keywords:["fio-u-"],caseInsensitive:!0},{id:"gocardless-api-token",category:"gocardless",title:"GoCardless API token",pattern:String.raw`(live_[a-z0-9_=-]{40})`,keywords:["live_"],caseInsensitive:!0},{id:"grafana-api-token",category:"grafana",title:"Grafana API token",pattern:String.raw`(eyJrIjoi[a-z0-9_=-]{72,92})`,keywords:["eyJrIjoi"],caseInsensitive:!0},{id:"hashicorp-tf-api-token",category:"hashicorp",title:"HashiCorp Terraform user/org API token",pattern:String.raw`([a-z0-9]{14}\.atlasv1\.[a-z0-9_=-]{60,70})`,keywords:["atlasv1."],caseInsensitive:!0},{id:"hubspot-api-token",category:"hubspot",title:"HubSpot API token",pattern:String.raw`(?:hubspot[a-z0-9_ .,-]{0,25})(?:=|>|:=|\|\|:|<=|=>|:).{0,5}['"]([a-h0-9]{8}-[a-h0-9]{4}-[a-h0-9]{4}-[a-h0-9]{4}-[a-h0-9]{12})['"]`,keywords:["hubspot"],caseInsensitive:!0},{id:"intercom-api-token",category:"intercom",title:"Intercom API token",pattern:String.raw`(?:intercom[a-z0-9_ .,-]{0,25})(?:=|>|:=|\|\|:|<=|=>|:).{0,5}['"]([a-z0-9=_]{60})['"]`,keywords:["intercom"],caseInsensitive:!0},{id:"intercom-client-secret",category:"intercom",title:"Intercom client secret/ID",pattern:String.raw`(?:intercom[a-z0-9_ .,-]{0,25})(?:=|>|:=|\|\|:|<=|=>|:).{0,5}['"]([a-h0-9]{8}-[a-h0-9]{4}-[a-h0-9]{4}-[a-h0-9]{4}-[a-h0-9]{12})['"]`,keywords:["intercom"],caseInsensitive:!0},{id:"ionic-api-token",category:"ionic",title:"Ionic API token",pattern:String.raw`(?:ionic[a-z0-9_ .,-]{0,25})(?:=|>|:=|\|\|:|<=|=>|:).{0,5}['"](ion_[a-z0-9]{42})['"]`,keywords:["ionic"],caseInsensitive:!0},{id:"linear-client-secret",category:"linear",title:"Linear client secret/ID",pattern:String.raw`(?:linear[a-z0-9_ .,-]{0,25})(?:=|>|:=|\|\|:|<=|=>|:).{0,5}['"]([a-f0-9]{32})['"]`,keywords:["linear"],caseInsensitive:!0},{id:"lob-api-key",category:"lob",title:"Lob API Key",pattern:String.raw`(?:lob[a-z0-9_ .,-]{0,25})(?:=|>|:=|\|\|:|<=|=>|:).{0,5}['"]((live|test)_[a-f0-9]{35})['"]`,keywords:["lob"],caseInsensitive:!0},{id:"mailchimp-api-key",category:"mailchimp",title:"Mailchimp API key",pattern:String.raw`(?:mailchimp[a-z0-9_ .,-]{0,25})(?:=|>|:=|\|\|:|<=|=>|:).{0,5}['"]([a-f0-9]{32}-us20)['"]`,keywords:["mailchimp"],caseInsensitive:!0},{id:"mailgun-token",category:"mailgun",title:"Mailgun private API token",pattern:String.raw`(?:mailgun[a-z0-9_ .,-]{0,25})(?:=|>|:=|\|\|:|<=|=>|:).{0,5}['"]((pub)?key-[a-f0-9]{32})['"]`,keywords:["mailgun"],caseInsensitive:!0},{id:"mailgun-signing-key",category:"mailgun",title:"Mailgun webhook signing key",pattern:String.raw`(?:mailgun[a-z0-9_ .,-]{0,25})(?:=|>|:=|\|\|:|<=|=>|:).{0,5}['"]([a-h0-9]{32}-[a-h0-9]{8}-[a-h0-9]{8})['"]`,keywords:["mailgun"],caseInsensitive:!0},{id:"mapbox-api-token",category:"mapbox",title:"Mapbox API token",pattern:String.raw`(pk\.[a-z0-9]{60}\.[a-z0-9]{22})`,keywords:["pk."],caseInsensitive:!0},{id:"messagebird-api-token",category:"messagebird",title:"MessageBird API token",pattern:String.raw`(?:messagebird[a-z0-9_ .,-]{0,25})(?:=|>|:=|\|\|:|<=|=>|:).{0,5}['"]([a-z0-9]{25})['"]`,keywords:["messagebird"],caseInsensitive:!0},{id:"messagebird-client-id",category:"messagebird",title:"MessageBird API client ID",pattern:String.raw`(?:messagebird[a-z0-9_ .,-]{0,25})(?:=|>|:=|\|\|:|<=|=>|:).{0,5}['"]([a-h0-9]{8}-[a-h0-9]{4}-[a-h0-9]{4}-[a-h0-9]{4}-[a-h0-9]{12})['"]`,keywords:["messagebird"],caseInsensitive:!0},{id:"new-relic-user-api-key",category:"newrelic",title:"New Relic user API Key",pattern:String.raw`(NRAK-[A-Z0-9]{27})`,keywords:["NRAK-"]},{id:"new-relic-user-api-id",category:"newrelic",title:"New Relic user API ID",pattern:String.raw`(?:newrelic[a-z0-9_ .,-]{0,25})(?:=|>|:=|\|\|:|<=|=>|:).{0,5}['"]([A-Z0-9]{64})['"]`,keywords:["newrelic"],caseInsensitive:!0},{id:"new-relic-browser-api-token",category:"newrelic",title:"New Relic ingest browser API token",pattern:String.raw`(NRJS-[a-f0-9]{19})`,keywords:["NRJS-"]},{id:"planetscale-password",category:"planetscale",title:"PlanetScale password",pattern:String.raw`(pscale_pw_[a-z0-9_.-]{43})`,keywords:["pscale_pw_"],caseInsensitive:!0},{id:"private-packagist-token",category:"private-packagist",title:"Private Packagist token",pattern:String.raw`(packagist_[ou][ru]t_[a-f0-9]{68})`,keywords:["packagist_uut_","packagist_ort_","packagist_out_"],caseInsensitive:!0},{id:"rubygems-api-token",category:"rubygems",title:"Rubygem API token",pattern:String.raw`(rubygems_[a-f0-9]{48})`,keywords:["rubygems_"]},{id:"shippo-api-token",category:"shippo",title:"Shippo API token",pattern:String.raw`(shippo_(live|test)_[a-f0-9]{40})`,keywords:["shippo_live_","shippo_test_"]},{id:"linkedin-client-secret",category:"linkedin",title:"LinkedIn Client secret",pattern:String.raw`(?:linkedin[a-z0-9_ .,-]{0,25})(?:=|>|:=|\|\|:|<=|=>|:).{0,5}['"]([a-z]{16})['"]`,keywords:["linkedin"],caseInsensitive:!0},{id:"linkedin-client-id",category:"linkedin",title:"LinkedIn Client ID",pattern:String.raw`(?:linkedin[a-z0-9_ .,-]{0,25})(?:=|>|:=|\|\|:|<=|=>|:).{0,5}['"]([a-z0-9]{14})['"]`,keywords:["linkedin"],caseInsensitive:!0},{id:"twitch-api-token",category:"twitch",title:"Twitch API token",pattern:String.raw`(?:twitch[a-z0-9_ .,-]{0,25})(?:=|>|:=|\|\|:|<=|=>|:).{0,5}['"]([a-z0-9]{30})['"]`,keywords:["twitch"],caseInsensitive:!0},{id:"typeform-api-token",category:"typeform",title:"Typeform API token",pattern:String.raw`(?:typeform[a-z0-9_ .,-]{0,25})(?:=|>|:=|\|\|:|<=|=>|:).{0,5}(tfp_[a-z0-9_.=-]{59})`,keywords:["typeform"],caseInsensitive:!0},{id:"todoist-api-token",category:"todoist",title:"Todoist API token",pattern:String.raw`(?:todoist[a-z0-9_ .,-]{0,25})(?:=|>|:=|\|\|:|<=|=>|:)[\s'"]{0,3}([0-9a-f]{40})`,keywords:["todoist"],caseInsensitive:!0},{id:"openai-api-key",category:"openai",title:"OpenAI API Key",pattern:String.raw`(sk-[a-zA-Z0-9]{50})`,caseInsensitive:!1,keywords:["sk-"]},{id:"openai-api-key-project",category:"openai",title:"OpenAI Project-scoped API Key",pattern:String.raw`(sk-proj-[A-Za-z0-9]{24}-[A-Za-z0-9]{40,128})`,caseInsensitive:!0,keywords:["sk-proj-"]},{id:"openai-api-key-env",category:"openai",title:"OpenAI Environment-scoped API Key",pattern:String.raw`(sk-(?:live|test)-[A-Za-z0-9]{24}-[A-Za-z0-9]{40,128})`,caseInsensitive:!0,keywords:["sk-live-","sk-test-"]},{id:"anthropic-api-key",category:"anthropic",title:"Anthropic API Key",pattern:String.raw`(sk-ant-([a-zA-Z0-9]{1,10}-)?[a-zA-Z0-9_-]{32,128})`,caseInsensitive:!1,keywords:["sk-ant-"]},{id:"canva-token",category:"canva",title:"Canva Token",pattern:String.raw`\b(cnv[a-z0-9]{2}[A-Za-z0-9_=-]+[a-f0-9]{8})\b`,caseInsensitive:!1,keywords:["cnv"]},{id:"api-key",category:"unknown",title:"Unknown API Key",pattern:String.raw`(?:[a-z0-9_ .,-]{0,25}api[-_](?:key|token)(?!length|count|max|min|maxlength|_length|_count|_min|_maxlength)[a-z0-9_ .,-]{0,25})\s*(?:=|>|:=|\|\|:|<=|=>|:)\s*['"]?((?!.*(?:api|key|secret|foo|example|dummy|password|12345|abcde|placeholder|fake|token))[a-z0-9+/_-]{6,128})['"]?(?=\s|$|[;,\]})'"])`,keywords:["api-key","api_key","api-token","api_token"],caseInsensitive:!0},{id:"webhook-secret",category:"unknown",title:"Unknown Webhook Secret",pattern:String.raw`(?:[a-z0-9_ .,-]{0,25}webhook[-_]secret(?!length|count|max|min|maxlength|_length|_count|_min|_maxlength)[a-z0-9_ .,-]{0,25})\s*(?:=|>|:=|\|\|:|<=|=>|:)\s*['"]?((?!.*(?:api|key|secret|foo|example|dummy|password|12345|abcde|placeholder|fake|token|webhook))[a-z0-9+/=_-]{6,128})['"]?(?=\s|$|[;,\]})'"])`,keywords:["webhook-secret","webhook_secret"],caseInsensitive:!0},{id:"password",category:"unknown",title:"Unknown Password",pattern:String.raw`(?:[a-z0-9_ .,-]{0,25}password(?!length|count|max|min|maxlength|_length|_count|_min|_maxlength)[a-z0-9_ .,-]{0,25})\s*(?:=|>|:=|\|\|:|<=|=>|:)\s*['"]?((?!.*(?:api|key|secret|foo|example|dummy|password|12345|abcde|placeholder|fake|token|password|pass|pwd))[a-z0-9+/=_-]{6,128})['"]?(?=\s|$|[;,\]})'"])`,keywords:["password"],caseInsensitive:!0},{id:"sk-secret",category:"unknown",title:"Unknown SK Secret",pattern:String.raw`(?:^|['"\s])(sk(?:[-_][a-z0-9]{1,10})?[-_][a-z0-9]{10,99})(?:$|['"\s])`,caseInsensitive:!0,keywords:["sk-","sk_"]}]});function ub4(J){if(!J||typeof J!=="string")return J;let Q=J.replace(mb4,"");if(Q.length!==J.length){let Y=J.length-Q.length;x.info("Invisible Unicode tag characters removed during sanitization",{removedCount:Y})}return Q}function pb4(J){if(!J||typeof J!=="string")return J;let Q=ub4(J);for(let Y of Qv0){if(!Y.keywords.some((G)=>Y.caseInsensitive?Q.toLowerCase().includes(G.toLowerCase()):Q.includes(G)))continue;let X=Jv0(Y);Q=Q.replace(X,(G,Z)=>{return G.replace(Z,`[REDACTED:${Y.id}]`)})}return Q}function Cs(J,Q){if(!J||typeof J==="number"||typeof J==="boolean")return J;if(typeof J==="string")return Q(J);if(Array.isArray(J))return J.map((Y)=>{if(typeof Y==="string")return Q(Y);else if(Y&&typeof Y==="object")return Cs(Y,Q);return Y});if(J&&typeof J==="object"){if("type"in J&&(J.type==="base64"||J.type==="image")&&"data"in J)return{...J};if("isImage"in J&&J.isImage===!0&&"content"in J&&typeof J.content==="string"){let Y={};for(let[X,G]of Object.entries(J))if(X==="content")Y[X]=G;else Y[X]=Cs(G,Q);return Y}}return Object.fromEntries(Object.entries(J).map(([Y,X])=>[Y,Cs(X,Q)]))}function js(J){return Cs(J,pb4)}var mb4;var Xv0=Z1(()=>{U0();Yv0();mb4=/[\uDB40][\uDC00-\uDC7F]/g});function db4(J){return{[Y7]:"oracle",[zJ]:"subagent",[V9]:"codebase-search",[WI]:"codebase-search",[HI]:"codebase-search",[YU]:"codebase-search",[zI]:"codebase-search",[QU]:"codebase-search"}[J]||null}function cb4(J,Q){let Y=J["~debug"];if(!Y)return null;x.debug("Extracting usage from tool debug info",{operationType:Q,debugInfoKeys:Object.keys(Y),hasUsage:!!Y.usage,hasInferences:Array.isArray(Y.inferences),inferenceCount:Array.isArray(Y.inferences)?Y.inferences.length:0});let X=[];if(Q==="subagent"){if(Y.usage)X=[{usage:Y.usage}];else if(Array.isArray(Y.inferences))X=Y.inferences}else X=Array.isArray(Y.inferences)?Y.inferences:[];if(X.length===0)return x.debug("No inferences found in tool debug",{operationType:Q}),null;let G=lb4(X);return x.debug("Aggregated tool usage from inferences",{operationType:Q,inferenceCount:X.length,totalCredits:G.credits}),G}function lb4(J){let Q=J.reduce((X,G)=>({inputTokens:X.inputTokens+(G.usage?.inputTokens??0),outputTokens:X.outputTokens+(G.usage?.outputTokens??0),cacheCreationInputTokens:X.cacheCreationInputTokens+(G.usage?.cacheCreationInputTokens??0),cacheReadInputTokens:X.cacheReadInputTokens+(G.usage?.cacheReadInputTokens??0),credits:X.credits+(G.usage?.credits??0)}),{inputTokens:0,outputTokens:0,cacheCreationInputTokens:0,cacheReadInputTokens:0,credits:0}),Y=J[J.length-1]?.usage;return{model:Y?.model,maxInputTokens:Y?.maxInputTokens??0,inputTokens:Q.inputTokens,outputTokens:Q.outputTokens,totalInputTokens:Q.inputTokens+Q.cacheCreationInputTokens+Q.cacheReadInputTokens,cacheCreationInputTokens:Q.cacheCreationInputTokens,cacheReadInputTokens:Q.cacheReadInputTokens,credits:Q.credits}}function ib4(J,Q){if(Q==="subagent")return J["~debug"]?.threadID||J.threadID;return}function nb4(J){let Q,Y=-1;for(let G=J.length-1;G>=0;G--){let Z=J[G];if(Z?.role==="assistant"){Q=Z.messageId,Y=G;break}}if(Y===-1)return{fromMessageId:void 0,toMessageId:Q};let X;for(let G=Y-1;G>=0;G--){let Z=J[G];if(Z?.role==="user"){X=Z.messageId;break}}return{fromMessageId:X,toMessageId:Q}}function Gv0(J,Q,Y){let X=LI(J,Q);if(!X?.block?.name){x.debug("Tool block not found for ledger extraction",{toolUse:Q});return}let G=db4(X.block.name);if(x.debug("Processing tool completion for ledger",{toolName:X.block.name,toolUse:Q,operationType:G,hasDebugInfo:!!Y["~debug"],debugKeys:Y["~debug"]?Object.keys(Y["~debug"]):[]}),!G)return;let Z=cb4(Y,G);if(!Z){x.debug("No usage extracted from tool debug info",{toolName:X.block.name,operationType:G,hasDebug:!!Y["~debug"]});return}let q=ib4(Y,G),V;for(let K of J.messages)if(K.role==="assistant"&&Array.isArray(K.content)){for(let W of K.content)if(W.type==="tool_use"&&W.id===Q){V=K.messageId;break}if(V!==void 0)break}x.debug("Adding tool usage to thread ledger",{toolName:X.block.name,operationType:G,credits:Z.credits,subagentThreadID:q,triggeringMessageId:V}),Lf(J,Z,G,q,V,Q)}function Lf(J,Q,Y="inference",X,G,Z){if(!J.usageLedger)J.usageLedger={events:[]};let q,V;if(Y==="inference"&&J.messages){let H=nb4(J.messages);q=H.fromMessageId,V=H.toMessageId}else if(G!==void 0)q=G,V=G;let K={id:crypto.randomUUID(),timestamp:new Date().toISOString(),model:Q.model,credits:Q.credits??0,tokens:{input:Q.inputTokens??0,output:Q.outputTokens??0},operationType:Y,subagentThreadID:X,fromMessageId:q,toMessageId:V,toolUseID:Z};J.usageLedger.events.push(K);let W=J.usageLedger.events.reduce((H,z)=>H+z.credits,0);x.debug("usage-ledger:event",{threadId:J.id,operationType:Y,eventId:K.id,toolUseID:Z,addedCredits:K.credits,totalCredits:W,eventCount:J.usageLedger.events.length,fromMessageId:q,toMessageId:V})}function Zv0(J){return J.usageLedger?.events.reduce((Q,Y)=>Q+Y.credits,0)??0}function $v0(J,Q){let Y=J.usageLedger?.events??[],X=new Map;for(let Z of Y){let q=Z.model?.trim()||"unknown",V=`${q}|${Z.operationType}`,K=X.get(V)??{model:q,operationType:Z.operationType,credits:0,tokensIn:0,tokensOut:0};K.credits+=Z.credits||0,K.tokensIn+=Z.tokens?.input||0,K.tokensOut+=Z.tokens?.output||0,X.set(V,K)}let G=Array.from(X.values());if(!Q?.includeZero)G=G.filter((Z)=>Z.credits>0);return G.sort((Z,q)=>q.credits-Z.credits||Z.model.localeCompare(q.model)||Z.operationType.localeCompare(q.operationType)),G}function qv0(J){let Q=new Map,Y=0,X=0,G=0;for(let q of J){let V=Q.get(q.model);if(!V)V={model:q.model,totalCredits:0,totalTokensIn:0,totalTokensOut:0,rows:[]},Q.set(q.model,V);V.rows.push({operationType:q.operationType,credits:q.credits,tokensIn:q.tokensIn,tokensOut:q.tokensOut}),V.totalCredits+=q.credits,V.totalTokensIn+=q.tokensIn,V.totalTokensOut+=q.tokensOut,Y+=q.credits,X+=q.tokensIn,G+=q.tokensOut}let Z=Array.from(Q.values());Z.sort((q,V)=>V.totalCredits-q.totalCredits||q.model.localeCompare(V.model));for(let q of Z)q.rows.sort((V,K)=>K.credits-V.credits||V.operationType.localeCompare(K.operationType));return{models:Z,grandTotal:{credits:Y,tokensIn:X,tokensOut:G}}}function Ss(J,Q){return J.usageLedger?.events.filter((Y)=>Y.toolUseID===Q).reduce((Y,X)=>Y+X.credits,0)??0}function DM1(J){if(J?.role!=="user")return!1;let Q=Array.isArray(J.content)?J.content:[];if(Q.length===0)return!1;return Q.every((Y)=>Y&&Y.type==="tool_result")}function ab4(J,Q){for(let Y=J.length-1;Y>=0;Y--){let X=J[Y];if(X?.messageId===Q){if(X.role==="user"&&!DM1(X))return Q;if(X.role==="user"&&DM1(X))for(let G=Y-1;G>=0;G--){let Z=J[G];if(Z?.role==="user"&&!DM1(Z))return Z.messageId}break}}return Q}function Vv0(J){if(!J.usageLedger?.events.length||!J.messages)return 0;let Q=J.usageLedger.events.filter((G)=>G.operationType==="inference");if(!Q.length)return 0;let Y=Q[Q.length-1];if(!Y||Y.fromMessageId===void 0)return Y?.credits??0;let X=ab4(J.messages,Y.fromMessageId);return J.usageLedger.events.filter((G)=>G.fromMessageId!==void 0&&G.fromMessageId>=X).reduce((G,Z)=>G+Z.credits,0)}var ZT=Z1(()=>{U0();z4();M9()});function rb4(J){return J?J.length>=ob4:!1}function gH(J){if(J.nextMessageId===void 0)J.nextMessageId=0;return J.nextMessageId++}function sb4(J,Q){J["~debug"]={...J["~debug"]??{},...Q.usage?{lastInferenceUsage:Q.usage}:{}}}function Kv0(J){return(Q)=>{switch(Q.v++,J.type){case"cancelled":{_s(Q);let Y=Q.messages.at(-1);if(Y?.role==="user"){let X=Y.content.findLast((G)=>G.type==="tool_result");if(X)X.run.status="cancelled"}break}case"user:message:interrupt":{let Y=Q.messages[J.messageIndex];if(Y?.role==="user")Y.interrupted=!0;break}case"artifact:update":{if(!Q.artifacts)Q.artifacts={};let Y=Q.artifacts[J.artifactId];Q.artifacts[J.artifactId]={type:"plan",content:J.content,created:Y?.created??Date.now(),updated:Date.now(),version:J.version??(Y?.version??0)+1};break}case"summary:created":{if(J.summary.type==="external"){if(!Q.summaryThreads)Q.summaryThreads=[];Q.summaryThreads.push(J.summary.summaryThreadID),Q.messages.push({role:"info",messageId:gH(Q),content:[{type:"summary",summary:{type:"thread",thread:J.summary.summaryThreadID}}]})}else if(J.summary.type==="internal"){let Y=gH(Q);if(Q.messages.push({role:"info",messageId:Y,content:[{type:"summary",summary:{type:"message",summary:J.summary.summary}}]}),J.summary.usage)x.debug("summary:created delta handler: adding usage to ledger",{usage:{...J.summary.usage},messageId:Y,threadId:Q.id}),Lf(Q,J.summary.usage,"summarization",void 0,Y);else x.warn("summary:created delta handler: no usage in internal summary")}break}case"fork:created":{if(!Q.forkThreads)Q.forkThreads={};let Y=Q.forkThreads[J.fromMessageIndex]||[];Q.forkThreads={...Q.forkThreads,[J.fromMessageIndex]:[...Y,J.forkThreadID]},Q.v++;break}case"thread:truncate":{if(Q.messages.splice(J.fromIndex),Q.forkThreads){let Y=[];for(let X in Q.forkThreads){let G=Number(X);if(G>=J.fromIndex)Y.push(G)}for(let X of Y)delete Q.forkThreads[X];if(Object.keys(Q.forkThreads).length===0)Q.forkThreads=void 0}break}case"user:message":{_s(Q);let Y={role:"user",messageId:gH(Q),...J.message,content:J.message.content??[]},X=js(Y);if(J.index!==void 0){if(!Q.messages[J.index])throw Error(`user message at index ${J.index} not found`);let G=Q.messages[J.index];if(Q.messages.filter((V)=>V.role==="user")[0]===G&&Y.agentMode&&!Q.mainThreadID)Q.agentMode=Y.agentMode;Q.messages.splice(J.index,Q.messages.length-J.index,X)}else{let G=d$(Q)===0;if((!Q.agentMode||G)&&Y.agentMode&&!Q.mainThreadID)Q.agentMode=Y.agentMode;if(Q.messages.push(X),Y.agentMode==="plan"&&Q.messages.length===1&&!Q.artifacts?.plan){if(!Q.artifacts)Q.artifacts={};let Z=Date.now();Q.artifacts.plan={type:"plan",content:i$,created:Z,version:0,updated:Z}}if(Q.draft)Q.draft=void 0}break}case"user:message-queue:dequeue":{if(_s(Q),!Q.queuedMessages)return;let[Y,...X]=Q.queuedMessages;if(!Y)return;Q.messages.push(Y.queuedMessage),Q.queuedMessages=X;break}case"user:tool-input":{if(!CX(Q,J.toolUse)){x.debug(`Ignoring user:tool-input delta for missing tool use ${J.toolUse} (likely deleted due to thread edit/truncation)`);break}let X=c8(GU(Q,J.toolUse));if(!X){x.debug(`Ignoring user:tool-input delta for missing tool result block ${J.toolUse} (likely deleted due to thread edit/truncation)`);break}X.userInput=J.value;break}case"tool:data":{if(!LI(Q,J.toolUse)){x.debug(`Ignoring tool:data delta for missing tool use ${J.toolUse} (likely deleted due to thread edit/truncation)`);break}let X=c8(js(J.data));if(Wv0(Q,J.toolUse,X),X&&"status"in X&&X.status==="done"){if(Gv0(Q,J.toolUse,X),X.result&&typeof X.result==="object"&&"artifact"in X.result&&X.result.artifact&&typeof X.result.artifact==="object"&&"id"in X.result.artifact&&"content"in X.result.artifact){let{id:G,content:Z}=X.result.artifact;if(!Q.artifacts)Q.artifacts={};let q=Q.artifacts[G],V=q?.created??Date.now(),K=q?.version??0;Q.artifacts[G]={type:"plan",content:Z,created:V,updated:Date.now(),version:K+1}}}break}case"tool:processed":{let Y=LI(Q,J.toolUse);if(!Y){x.debug(`Ignoring tool:processed delta for missing tool use ${J.toolUse} (likely deleted due to thread edit/truncation)`);break}let X=Y.block.input;Y.block.input=J.newArgs,Y.message.originalToolUseInput={...Y.message.originalToolUseInput,[J.toolUse]:X};break}case"assistant:message":{let Y=FJ(Q,"assistant"),X=Y?.content.filter((Z)=>Z.type==="tool_use").map((Z)=>Z.id)||[];if(_s(Q),Y?.state.type==="cancelled"){for(let Z of Q.messages)if(Z.role==="user")Z.content=Z.content.filter((q)=>{if(q.type==="tool_result"&&X.includes(q.toolUseID))return!1;return!0})}let G={...J.message,messageId:gH(Q)};Q.messages.push(c8(G));break}case"assistant:message-update":{let Y=c8(J.message),X=Q.messages.at(-1);if(X?.role==="assistant")Q.messages[Q.messages.length-1]={...Y,messageId:X?.messageId};else Q.messages.push({...Y,messageId:gH(Q)});break}case"inference:completed":{if(sb4(Q,{usage:J.usage}),!Q.env)Q.env={initial:{}};if(!Q.env.initial.tags)Q.env.initial.tags=[];let Y=`model:${J.model}`;if(!Q.env.initial.tags.includes(Y))Q.env.initial.tags=[...Q.env.initial.tags,Y];if(J.usage){let X=c8(FJ(Q,"assistant"));if(Lf(Q,J.usage,"inference"),X){let G=Vv0(Q);X.usage={...J.usage,creditsSinceLastUserMessage:G}}}break}case"title":{if(Q.title=J.value||void 0,J.usage)Lf(Q,J.usage,"title-generation",void 0,0);break}case"max-tokens":{Q.maxTokens=J.value||void 0;break}case"main-thread":{Q.mainThreadID=J.value||void 0;break}case"agent-mode":{if(d$(Q)>0)throw Error("(bug) cannot change agentMode after first message");Q.agentMode=J.mode;break}case"environment":{Q.env=c8(J.env);break}case"user:message-queue:enqueue":{if(!Q.queuedMessages)Q.queuedMessages=[];if(rb4(Q.queuedMessages))break;let Y={role:"user",messageId:gH(Q),...J.message,content:J.message.content??[]},X=js(Y);Q.queuedMessages.push({id:ex0("queued-"),queuedMessage:c8(X)});break}case"user:message-queue:discard":{if(J.id===void 0){Q.queuedMessages=[];break}let Y=Q.queuedMessages?.findIndex((X)=>X.id===J.id);if(Y===void 0)throw Error(`queued message with id ${J.id} not found`);Q?.queuedMessages?.splice(Y,1);break}case"info:manual-bash-invocation":{Q.messages.push({role:"info",messageId:gH(Q),content:[{type:"manual_bash_invocation",args:c8(J.args),toolRun:c8(J.toolRun),hidden:J.hidden}]});break}case"info:skill-injection":{Q.messages.push({role:"info",messageId:gH(Q),content:[{type:"text",text:J.content}]});break}}}}function _s(J){let Q=c8(FJ(J,"assistant"));if(!Q)return;let Y=!1,X=[];if(Q.state.type==="streaming")Q.state={type:"cancelled"},Y=!0;else if(Q.state.type==="complete"){if(Q.content.some((Z)=>Z.type==="tool_use"&&!d2(Z)))Q.state={type:"cancelled"},Y=!0}if(Y){for(let Z=0;Z<Q.content.length;Z++){let q=Q.content[Z];if(q?.type==="tool_use"&&!d2(q)){X.push(q.id),x.debug(`Cleaning up incomplete tool_use ${q.id}`,{name:"markPriorStreamingAssistantMessageAsCancelled",threadID:J.id,blockID:q.id});let V={type:"tool_use",id:q.id,name:q.name,complete:!0,input:q.inputIncomplete??q.input??{}};Q.content[Z]=V}}let G=$Q(J);for(let Z of X)if(!G.has(Z))Wv0(J,Z,{status:"cancelled"})}}function Wv0(J,Q,Y){let X,G=LI(J,Q);if(G){let q=G.messageIndex;for(let V=q+1;V<J.messages.length;V++){let K=J.messages[V];if(K?.role==="user"){X=K;break}}}if(!X)X={role:"user",messageId:gH(J),content:[]},J.messages.push(X);let Z=GU(J,Q);if(Z)Z.run=c8(Y);else Z={type:"tool_result",toolUseID:Q,run:c8(Y)},X.content.push(Z)}function ks(J){try{return tG(J.replace(/\\+$/,"")+'"')}catch{return tG(J)}}var ob4=5;var ys=Z1(()=>{wM();PY();U0();Xv0();M9();ZT()});function j4(J,Q,Y,X,G){if(X==="m")throw TypeError("Private method is not writable");if(X==="a"&&!G)throw TypeError("Private accessor was defined without a setter");if(typeof Q==="function"?J!==Q||!G:!Q.has(J))throw TypeError("Cannot write private member to an object whose class did not declare it");return X==="a"?G.call(J,Y):G?G.value=Y:Q.set(J,Y),Y}function E0(J,Q,Y,X){if(Y==="a"&&!X)throw TypeError("Private accessor was defined without a getter");if(typeof Q==="function"?J!==Q||!X:!Q.has(J))throw TypeError("Cannot read private member from an object whose class did not declare it");return Y==="m"?X:Y==="a"?X.call(J):X?X.value:Q.get(J)}var AZ=()=>{};var MM1=function(){let{crypto:J}=globalThis;if(J?.randomUUID)return MM1=J.randomUUID.bind(J),J.randomUUID();let Q=new Uint8Array(1),Y=J?()=>J.getRandomValues(Q)[0]:()=>Math.random()*255&255;return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,(X)=>(+X^Y()&15>>+X/4).toString(16))};function Of(J){return typeof J==="object"&&J!==null&&(("name"in J)&&J.name==="AbortError"||("message"in J)&&String(J.message).includes("FetchRequestCanceledException"))}var Af=(J)=>{if(J instanceof Error)return J;if(typeof J==="object"&&J!==null){try{if(Object.prototype.toString.call(J)==="[object Error]"){let Q=Error(J.message,J.cause?{cause:J.cause}:{});if(J.stack)Q.stack=J.stack;if(J.cause&&!Q.cause)Q.cause=J.cause;if(J.name)Q.name=J.name;return Q}}catch{}try{return Error(JSON.stringify(J))}catch{}}return Error(J)};var G4,a2,N3,hL,bL,wf,Ef,If,Pf,Tf,Rf,Cf,jf,Sf,_f,mH;var NK=Z1(()=>{G4=class G4 extends Error{};a2=class a2 extends G4{constructor(J,Q,Y,X){super(`${a2.makeMessage(J,Q,Y)}`);this.status=J,this.headers=X,this.requestID=X?.get("x-request-id"),this.error=Q;let G=Q;this.code=G?.code,this.param=G?.param,this.type=G?.type}static makeMessage(J,Q,Y){let X=Q?.message?typeof Q.message==="string"?Q.message:JSON.stringify(Q.message):Q?JSON.stringify(Q):Y;if(J&&X)return`${J} ${X}`;if(J)return`${J} status code (no body)`;if(X)return X;return"(no status code or body)"}static generate(J,Q,Y,X){if(!J||!X)return new hL({message:Y,cause:Af(Q)});let G=Q?.error;if(J===400)return new wf(J,G,Y,X);if(J===401)return new Ef(J,G,Y,X);if(J===403)return new If(J,G,Y,X);if(J===404)return new Pf(J,G,Y,X);if(J===409)return new Tf(J,G,Y,X);if(J===422)return new Rf(J,G,Y,X);if(J===429)return new Cf(J,G,Y,X);if(J>=500)return new jf(J,G,Y,X);return new a2(J,G,Y,X)}};N3=class N3 extends a2{constructor({message:J}={}){super(void 0,void 0,J||"Request was aborted.",void 0)}};hL=class hL extends a2{constructor({message:J,cause:Q}){super(void 0,void 0,J||"Connection error.",void 0);if(Q)this.cause=Q}};bL=class bL extends hL{constructor({message:J}={}){super({message:J??"Request timed out."})}};wf=class wf extends a2{};Ef=class Ef extends a2{};If=class If extends a2{};Pf=class Pf extends a2{};Tf=class Tf extends a2{};Rf=class Rf extends a2{};Cf=class Cf extends a2{};jf=class jf extends a2{};Sf=class Sf extends G4{constructor(){super("Could not parse response content as the length limit was reached")}};_f=class _f extends G4{constructor(){super("Could not parse response content as the request was rejected by the content filter")}};mH=class mH extends Error{constructor(J){super(J)}}});function OM1(J){if(typeof J!=="object")return{};return J??{}}function zv0(J){if(!J)return!0;for(let Q in J)return!1;return!0}function Fv0(J,Q){return Object.prototype.hasOwnProperty.call(J,Q)}function kf(J){return J!=null&&typeof J==="object"&&!Array.isArray(J)}var eb4,Hv0=(J)=>{return eb4.test(J)},HQ=(J)=>(HQ=Array.isArray,HQ(J)),LM1,Uv0=(J,Q)=>{if(typeof Q!=="number"||!Number.isInteger(Q))throw new G4(`${J} must be an integer`);if(Q<0)throw new G4(`${J} must be a positive integer`);return Q},Bv0=(J)=>{try{return JSON.parse(J)}catch(Q){return}};var uH=Z1(()=>{NK();eb4=/^[a-z][a-z0-9+.-]*:/i,LM1=HQ});var DK=(J)=>new Promise((Q)=>setTimeout(Q,J));var QB="6.7.0";function Jg4(){if(typeof Deno<"u"&&Deno.build!=null)return"deno";if(typeof EdgeRuntime<"u")return"edge";if(Object.prototype.toString.call(typeof globalThis.process<"u"?globalThis.process:0)==="[object process]")return"node";return"unknown"}function Yg4(){if(typeof navigator>"u"||!navigator)return null;let J=[{key:"edge",pattern:/Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"chrome",pattern:/Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"firefox",pattern:/Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"safari",pattern:/(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/}];for(let{key:Q,pattern:Y}of J){let X=Y.exec(navigator.userAgent);if(X){let G=X[1]||0,Z=X[2]||0,q=X[3]||0;return{browser:Q,version:`${G}.${Z}.${q}`}}}return null}var Lv0=()=>{return typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u"},Qg4=()=>{let J=Jg4();if(J==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":QB,"X-Stainless-OS":Dv0(Deno.build.os),"X-Stainless-Arch":Nv0(Deno.build.arch),"X-Stainless-Runtime":"deno","X-Stainless-Runtime-Version":typeof Deno.version==="string"?Deno.version:Deno.version?.deno??"unknown"};if(typeof EdgeRuntime<"u")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":QB,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":globalThis.process.version};if(J==="node")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":QB,"X-Stainless-OS":Dv0(globalThis.process.platform??"unknown"),"X-Stainless-Arch":Nv0(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};let Q=Yg4();if(Q)return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":QB,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":`browser:${Q.browser}`,"X-Stainless-Runtime-Version":Q.version};return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":QB,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}},Nv0=(J)=>{if(J==="x32")return"x32";if(J==="x86_64"||J==="x64")return"x64";if(J==="arm")return"arm";if(J==="aarch64"||J==="arm64")return"arm64";if(J)return`other:${J}`;return"unknown"},Dv0=(J)=>{if(J=J.toLowerCase(),J.includes("ios"))return"iOS";if(J==="android")return"Android";if(J==="darwin")return"MacOS";if(J==="win32")return"Windows";if(J==="freebsd")return"FreeBSD";if(J==="openbsd")return"OpenBSD";if(J==="linux")return"Linux";if(J)return`Other:${J}`;return"Unknown"},Mv0,Ov0=()=>{return Mv0??(Mv0=Qg4())};var AM1=()=>{};function Av0(){if(typeof fetch<"u")return fetch;throw Error("`fetch` is not defined as a global; Either pass `fetch` to the client, `new OpenAI({ fetch })` or polyfill the global, `globalThis.fetch = fetch`")}function wM1(...J){let Q=globalThis.ReadableStream;if(typeof Q>"u")throw Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");return new Q(...J)}function xs(J){let Q=Symbol.asyncIterator in J?J[Symbol.asyncIterator]():J[Symbol.iterator]();return wM1({start(){},async pull(Y){let{done:X,value:G}=await Q.next();if(X)Y.close();else Y.enqueue(G)},async cancel(){await Q.return?.()}})}function EM1(J){if(J[Symbol.asyncIterator])return J;let Q=J.getReader();return{async next(){try{let Y=await Q.read();if(Y?.done)Q.releaseLock();return Y}catch(Y){throw Q.releaseLock(),Y}},async return(){let Y=Q.cancel();return Q.releaseLock(),await Y,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}async function wv0(J){if(J===null||typeof J!=="object")return;if(J[Symbol.asyncIterator]){await J[Symbol.asyncIterator]().return?.();return}let Q=J.getReader(),Y=Q.cancel();Q.releaseLock(),await Y}var Ev0=({headers:J,body:Q})=>{return{bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(Q)}};var vs="RFC3986",IM1=(J)=>String(J),fs,PM1="RFC1738";var hs=Z1(()=>{fs={RFC1738:(J)=>String(J).replace(/%20/g,"+"),RFC3986:IM1}});function Pv0(J){if(!J||typeof J!=="object")return!1;return!!(J.constructor&&J.constructor.isBuffer&&J.constructor.isBuffer(J))}function RM1(J,Q){if(HQ(J)){let Y=[];for(let X=0;X<J.length;X+=1)Y.push(Q(J[X]));return Y}return Q(J)}var bs=(J,Q)=>(bs=Object.hasOwn??Function.prototype.call.bind(Object.prototype.hasOwnProperty),bs(J,Q)),MK,TM1=1024,Iv0=(J,Q,Y,X,G)=>{if(J.length===0)return J;let Z=J;if(typeof J==="symbol")Z=Symbol.prototype.toString.call(J);else if(typeof J!=="string")Z=String(J);if(Y==="iso-8859-1")return escape(Z).replace(/%u[0-9a-f]{4}/gi,function(V){return"%26%23"+parseInt(V.slice(2),16)+"%3B"});let q="";for(let V=0;V<Z.length;V+=TM1){let K=Z.length>=TM1?Z.slice(V,V+TM1):Z,W=[];for(let H=0;H<K.length;++H){let z=K.charCodeAt(H);if(z===45||z===46||z===95||z===126||z>=48&&z<=57||z>=65&&z<=90||z>=97&&z<=122||G===PM1&&(z===40||z===41)){W[W.length]=K.charAt(H);continue}if(z<128){W[W.length]=MK[z];continue}if(z<2048){W[W.length]=MK[192|z>>6]+MK[128|z&63];continue}if(z<55296||z>=57344){W[W.length]=MK[224|z>>12]+MK[128|z>>6&63]+MK[128|z&63];continue}H+=1,z=65536+((z&1023)<<10|K.charCodeAt(H)&1023),W[W.length]=MK[240|z>>18]+MK[128|z>>12&63]+MK[128|z>>6&63]+MK[128|z&63]}q+=W.join("")}return q};var Tv0=Z1(()=>{hs();uH();MK=(()=>{let J=[];for(let Q=0;Q<256;++Q)J.push("%"+((Q<16?"0":"")+Q.toString(16)).toUpperCase());return J})()});function Zg4(J){return typeof J==="string"||typeof J==="number"||typeof J==="boolean"||typeof J==="symbol"||typeof J==="bigint"}function Sv0(J,Q,Y,X,G,Z,q,V,K,W,H,z,U,N,M,L,O,E){let I=J,P=E,R=0,S=!1;while((P=P.get(CM1))!==void 0&&!S){let b=P.get(J);if(R+=1,typeof b<"u")if(b===R)throw RangeError("Cyclic object value");else S=!0;if(typeof P.get(CM1)>"u")R=0}if(typeof W==="function")I=W(Q,I);else if(I instanceof Date)I=U?.(I);else if(Y==="comma"&&HQ(I))I=RM1(I,function(b){if(b instanceof Date)return U?.(b);return b});if(I===null){if(Z)return K&&!L?K(Q,D3.encoder,O,"key",N):Q;I=""}if(Zg4(I)||Pv0(I)){if(K){let b=L?Q:K(Q,D3.encoder,O,"key",N);return[M?.(b)+"="+M?.(K(I,D3.encoder,O,"value",N))]}return[M?.(Q)+"="+M?.(String(I))]}let y=[];if(typeof I>"u")return y;let f;if(Y==="comma"&&HQ(I)){if(L&&K)I=RM1(I,K);f=[{value:I.length>0?I.join(",")||null:void 0}]}else if(HQ(W))f=W;else{let b=Object.keys(I);f=H?b.sort(H):b}let m=V?String(Q).replace(/\./g,"%2E"):String(Q),p=X&&HQ(I)&&I.length===1?m+"[]":m;if(G&&HQ(I)&&I.length===0)return p+"[]";for(let b=0;b<f.length;++b){let i=f[b],J1=typeof i==="object"&&typeof i.value<"u"?i.value:I[i];if(q&&J1===null)continue;let n=z&&V?i.replace(/\./g,"%2E"):i,u=HQ(I)?typeof Y==="function"?Y(p,n):p:p+(z?"."+n:"["+n+"]");E.set(J,R);let s=new WeakMap;s.set(CM1,E),jv0(y,Sv0(J1,u,Y,X,G,Z,q,V,Y==="comma"&&L&&HQ(I)?null:K,W,H,z,U,N,M,L,O,s))}return y}function $g4(J=D3){if(typeof J.allowEmptyArrays<"u"&&typeof J.allowEmptyArrays!=="boolean")throw TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");if(typeof J.encodeDotInKeys<"u"&&typeof J.encodeDotInKeys!=="boolean")throw TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided");if(J.encoder!==null&&typeof J.encoder<"u"&&typeof J.encoder!=="function")throw TypeError("Encoder has to be a function.");let Q=J.charset||D3.charset;if(typeof J.charset<"u"&&J.charset!=="utf-8"&&J.charset!=="iso-8859-1")throw TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");let Y=vs;if(typeof J.format<"u"){if(!bs(fs,J.format))throw TypeError("Unknown format option provided.");Y=J.format}let X=fs[Y],G=D3.filter;if(typeof J.filter==="function"||HQ(J.filter))G=J.filter;let Z;if(J.arrayFormat&&J.arrayFormat in Cv0)Z=J.arrayFormat;else if("indices"in J)Z=J.indices?"indices":"repeat";else Z=D3.arrayFormat;if("commaRoundTrip"in J&&typeof J.commaRoundTrip!=="boolean")throw TypeError("`commaRoundTrip` must be a boolean, or absent");let q=typeof J.allowDots>"u"?!!J.encodeDotInKeys===!0?!0:D3.allowDots:!!J.allowDots;return{addQueryPrefix:typeof J.addQueryPrefix==="boolean"?J.addQueryPrefix:D3.addQueryPrefix,allowDots:q,allowEmptyArrays:typeof J.allowEmptyArrays==="boolean"?!!J.allowEmptyArrays:D3.allowEmptyArrays,arrayFormat:Z,charset:Q,charsetSentinel:typeof J.charsetSentinel==="boolean"?J.charsetSentinel:D3.charsetSentinel,commaRoundTrip:!!J.commaRoundTrip,delimiter:typeof J.delimiter>"u"?D3.delimiter:J.delimiter,encode:typeof J.encode==="boolean"?J.encode:D3.encode,encodeDotInKeys:typeof J.encodeDotInKeys==="boolean"?J.encodeDotInKeys:D3.encodeDotInKeys,encoder:typeof J.encoder==="function"?J.encoder:D3.encoder,encodeValuesOnly:typeof J.encodeValuesOnly==="boolean"?J.encodeValuesOnly:D3.encodeValuesOnly,filter:G,format:Y,formatter:X,serializeDate:typeof J.serializeDate==="function"?J.serializeDate:D3.serializeDate,skipNulls:typeof J.skipNulls==="boolean"?J.skipNulls:D3.skipNulls,sort:typeof J.sort==="function"?J.sort:null,strictNullHandling:typeof J.strictNullHandling==="boolean"?J.strictNullHandling:D3.strictNullHandling}}function jM1(J,Q={}){let Y=J,X=$g4(Q),G,Z;if(typeof X.filter==="function")Z=X.filter,Y=Z("",Y);else if(HQ(X.filter))Z=X.filter,G=Z;let q=[];if(typeof Y!=="object"||Y===null)return"";let V=Cv0[X.arrayFormat],K=V==="comma"&&X.commaRoundTrip;if(!G)G=Object.keys(Y);if(X.sort)G.sort(X.sort);let W=new WeakMap;for(let U=0;U<G.length;++U){let N=G[U];if(X.skipNulls&&Y[N]===null)continue;jv0(q,Sv0(Y[N],N,V,K,X.allowEmptyArrays,X.strictNullHandling,X.skipNulls,X.encodeDotInKeys,X.encode?X.encoder:null,X.filter,X.sort,X.allowDots,X.serializeDate,X.format,X.formatter,X.encodeValuesOnly,X.charset,W))}let H=q.join(X.delimiter),z=X.addQueryPrefix===!0?"?":"";if(X.charsetSentinel)if(X.charset==="iso-8859-1")z+="utf8=%26%2310003%3B&";else z+="utf8=%E2%9C%93&";return H.length>0?z+H:""}var Cv0,jv0=function(J,Q){Array.prototype.push.apply(J,HQ(Q)?Q:[Q])},Rv0,D3,CM1;var _v0=Z1(()=>{Tv0();hs();uH();Cv0={brackets(J){return String(J)+"[]"},comma:"comma",indices(J,Q){return String(J)+"["+Q+"]"},repeat(J){return String(J)}},D3={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:Iv0,encodeValuesOnly:!1,format:vs,formatter:IM1,indices:!1,serializeDate(J){return(Rv0??(Rv0=Function.prototype.call.bind(Date.prototype.toISOString)))(J)},skipNulls:!1,strictNullHandling:!1};CM1={}});var kv0=Z1(()=>{hs();_v0()});function vv0(J){let Q=0;for(let G of J)Q+=G.length;let Y=new Uint8Array(Q),X=0;for(let G of J)Y.set(G,X),X+=G.length;return Y}function $T(J){let Q;return(yv0??(Q=new globalThis.TextEncoder,yv0=Q.encode.bind(Q)))(J)}function SM1(J){let Q;return(xv0??(Q=new globalThis.TextDecoder,xv0=Q.decode.bind(Q)))(J)}var yv0,xv0;class qT{constructor(){sX.set(this,void 0),tX.set(this,void 0),j4(this,sX,new Uint8Array,"f"),j4(this,tX,null,"f")}decode(J){if(J==null)return[];let Q=J instanceof ArrayBuffer?new Uint8Array(J):typeof J==="string"?$T(J):J;j4(this,sX,vv0([E0(this,sX,"f"),Q]),"f");let Y=[],X;while((X=Vg4(E0(this,sX,"f"),E0(this,tX,"f")))!=null){if(X.carriage&&E0(this,tX,"f")==null){j4(this,tX,X.index,"f");continue}if(E0(this,tX,"f")!=null&&(X.index!==E0(this,tX,"f")+1||X.carriage)){Y.push(SM1(E0(this,sX,"f").subarray(0,E0(this,tX,"f")-1))),j4(this,sX,E0(this,sX,"f").subarray(E0(this,tX,"f")),"f"),j4(this,tX,null,"f");continue}let G=E0(this,tX,"f")!==null?X.preceding-1:X.preceding,Z=SM1(E0(this,sX,"f").subarray(0,G));Y.push(Z),j4(this,sX,E0(this,sX,"f").subarray(X.index),"f"),j4(this,tX,null,"f")}return Y}flush(){if(!E0(this,sX,"f").length)return[];return this.decode(`
2232
2232
  `)}}function Vg4(J,Q){for(let G=Q??0;G<J.length;G++){if(J[G]===10)return{preceding:G,index:G+1,carriage:!1};if(J[G]===13)return{preceding:G,index:G+1,carriage:!0}}return null}function fv0(J){for(let X=0;X<J.length-1;X++){if(J[X]===10&&J[X+1]===10)return X+2;if(J[X]===13&&J[X+1]===13)return X+2;if(J[X]===13&&J[X+1]===10&&X+3<J.length&&J[X+2]===13&&J[X+3]===10)return X+4}return-1}var sX,tX;var hv0=Z1(()=>{AZ();sX=new WeakMap,tX=new WeakMap;qT.NEWLINE_CHARS=new Set([`
2233
2233
  `,"\r"]);qT.NEWLINE_REGEXP=/\r\n|[\n\r]/g});function yf(){}function gs(J,Q,Y){if(!Q||ms[J]>ms[Y])return yf;else return Q[J].bind(Q)}function w2(J){let Q=J.logger,Y=J.logLevel??"off";if(!Q)return Kg4;let X=bv0.get(Q);if(X&&X[0]===Y)return X[1];let G={error:gs("error",Q,Y),warn:gs("warn",Q,Y),info:gs("info",Q,Y),debug:gs("debug",Q,Y)};return bv0.set(Q,[Y,G]),G}var ms,_M1=(J,Q,Y)=>{if(!J)return;if(Fv0(ms,J))return J;w2(Y).warn(`${Q} was set to ${JSON.stringify(J)}, expected one of ${JSON.stringify(Object.keys(ms))}`);return},Kg4,bv0,pH=(J)=>{if(J.options)J.options={...J.options},delete J.options.headers;if(J.headers)J.headers=Object.fromEntries((J.headers instanceof Headers?[...J.headers]:Object.entries(J.headers)).map(([Q,Y])=>[Q,Q.toLowerCase()==="authorization"||Q.toLowerCase()==="cookie"||Q.toLowerCase()==="set-cookie"?"***":Y]));if("retryOfRequestLogID"in J){if(J.retryOfRequestLogID)J.retryOf=J.retryOfRequestLogID;delete J.retryOfRequestLogID}return J};var xf=Z1(()=>{uH();ms={off:0,error:200,warn:300,info:400,debug:500};Kg4={error:yf,warn:yf,info:yf,debug:yf},bv0=new WeakMap});async function*Wg4(J,Q){if(!J.body){if(Q.abort(),typeof globalThis.navigator<"u"&&globalThis.navigator.product==="ReactNative")throw new G4("The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api");throw new G4("Attempted to iterate over a response with no body")}let Y=new gv0,X=new qT,G=EM1(J.body);for await(let Z of Hg4(G))for(let q of X.decode(Z)){let V=Y.decode(q);if(V)yield V}for(let Z of X.flush()){let q=Y.decode(Z);if(q)yield q}}async function*Hg4(J){let Q=new Uint8Array;for await(let Y of J){if(Y==null)continue;let X=Y instanceof ArrayBuffer?new Uint8Array(Y):typeof Y==="string"?$T(Y):Y,G=new Uint8Array(Q.length+X.length);G.set(Q),G.set(X,Q.length),Q=G;let Z;while((Z=fv0(Q))!==-1)yield Q.slice(0,Z),Q=Q.slice(Z)}if(Q.length>0)yield Q}class gv0{constructor(){this.event=null,this.data=[],this.chunks=[]}decode(J){if(J.endsWith("\r"))J=J.substring(0,J.length-1);if(!J){if(!this.event&&!this.data.length)return null;let G={event:this.event,data:this.data.join(`
2234
2234
  `),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],G}if(this.chunks.push(J),J.startsWith(":"))return null;let[Q,Y,X]=zg4(J,":");if(X.startsWith(" "))X=X.substring(1);if(Q==="event")this.event=X;else if(Q==="data")this.data.push(X);return null}}function zg4(J,Q){let Y=J.indexOf(Q);if(Y!==-1)return[J.substring(0,Y),Q,J.substring(Y+Q.length)];return[J,"",""]}var vf,eX;var kM1=Z1(()=>{AZ();NK();hv0();xf();NK();eX=class eX{constructor(J,Q,Y){this.iterator=J,vf.set(this,void 0),this.controller=Q,j4(this,vf,Y,"f")}static fromSSEResponse(J,Q,Y){let X=!1,G=Y?w2(Y):console;async function*Z(){if(X)throw new G4("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");X=!0;let q=!1;try{for await(let V of Wg4(J,Q)){if(q)continue;if(V.data.startsWith("[DONE]")){q=!0;continue}if(V.event===null||!V.event.startsWith("thread.")){let K;try{K=JSON.parse(V.data)}catch(W){throw G.error("Could not parse message into JSON:",V.data),G.error("From chunk:",V.raw),W}if(K&&K.error)throw new a2(void 0,K.error,void 0,J.headers);yield K}else{let K;try{K=JSON.parse(V.data)}catch(W){throw console.error("Could not parse message into JSON:",V.data),console.error("From chunk:",V.raw),W}if(V.event=="error")throw new a2(void 0,K.error,K.message,void 0);yield{event:V.event,data:K}}}q=!0}catch(V){if(Of(V))return;throw V}finally{if(!q)Q.abort()}}return new eX(Z,Q,Y)}static fromReadableStream(J,Q,Y){let X=!1;async function*G(){let q=new qT,V=EM1(J);for await(let K of V)for(let W of q.decode(K))yield W;for(let K of q.flush())yield K}async function*Z(){if(X)throw new G4("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");X=!0;let q=!1;try{for await(let V of G()){if(q)continue;if(V)yield JSON.parse(V)}q=!0}catch(V){if(Of(V))return;throw V}finally{if(!q)Q.abort()}}return new eX(Z,Q,Y)}[(vf=new WeakMap,Symbol.asyncIterator)](){return this.iterator()}tee(){let J=[],Q=[],Y=this.iterator(),X=(G)=>{return{next:()=>{if(G.length===0){let Z=Y.next();J.push(Z),Q.push(Z)}return G.shift()}}};return[new eX(()=>X(J),this.controller,E0(this,vf,"f")),new eX(()=>X(Q),this.controller,E0(this,vf,"f"))]}toReadableStream(){let J=this,Q;return wM1({async start(){Q=J[Symbol.asyncIterator]()},async pull(Y){try{let{value:X,done:G}=await Q.next();if(G)return Y.close();let Z=$T(JSON.stringify(X)+`
@@ -4397,11 +4397,11 @@ Actual: ${G}`)}async function HV8(J,Q,Y){let{execSync:X}=await import("node:ch
4397
4397
  ${N}`;if(G==="pnpm"&&N.includes("Unable to find the global bin directory"))M+=`
4398
4398
 
4399
4399
  Hint: Try running "pnpm setup" to configure pnpm global directory, or use npm instead:
4400
- npm install -g @sourcegraph/amp`;V(Error(M))}},error:(U)=>{if(!H)H=!0,V(Error(`Failed to spawn ${G}: ${U.message}`))},complete:()=>{if(!H)H=!0,q()}})})}U0();U0();async function S41(J,Q){let X=Q||"https://registry.npmjs.org";try{let G=new AbortController,Z=setTimeout(()=>G.abort(),5000),q=await fetch(`${X}/@sourcegraph/amp`,{signal:G.signal});if(clearTimeout(Z),!q.ok)return{hasUpdate:!1,currentVersion:J,source:"npm"};let V=await q.json(),K=V["dist-tags"]?.latest;if(!K)return{hasUpdate:!1,currentVersion:J,source:"npm"};let W=NV8(J,K),H=W<0,z,U;if(V.time){let N=V.time[J],M=V.time[K],L=Date.now();if(N)z=Math.floor((L-new Date(N).getTime())/3600000);if(M)U=Math.floor((L-new Date(M).getTime())/3600000)}return x.info("NPM version comparison",{currentVersion:J,latestVersion:K,compareResult:W,hasUpdate:H,currentVersionAge:z,latestVersionAge:U}),{hasUpdate:H,latestVersion:K,currentVersion:J,currentVersionAge:z,latestVersionAge:U,source:"npm"}}catch(G){return x.debug("Error checking npm version",{error:G}),{hasUpdate:!1,currentVersion:J,source:"npm"}}}function NV8(J,Q){let Y=(q)=>{let[V,K]=q.split("-");return{parts:V?.split(".").map(Number)||[],label:K}},X=Y(J),G=Y(Q),Z=Math.max(X.parts.length,G.parts.length);for(let q=0;q<Z;q++){let V=X.parts[q]||0,K=G.parts[q]||0;if(V<K)return-1;if(V>K)return 1}if(X.label===G.label)return 0;if(!X.label&&G.label)return 1;if(X.label&&!G.label)return-1;if(X.label&&G.label)return X.label<G.label?-1:1;return 0}d0();function _41(J,Q){let Y=new y4,X=Y.pipe(t8({shouldCountRefs:!1}));return setImmediate(async()=>{let G=new _V().scoped("update"),Z=X.subscribe({next:(q)=>{G.debug("emit new state",q)}});try{let q=process.env.AMP_TEST_UPDATE_STATUS;if(q){G.debug("using fake update status for testing",{status:q}),await aU(500),Y.next(q);return}if(process.env.AMP_SKIP_UPDATE_CHECK==="1"){G.debug("checking disabled via AMP_SKIP_UPDATE_CHECK environment variable");return}let V=await Q.get("updates.mode");if(V==="disabled"){G.debug("checking disabled");return}G.debug("checking",{currentVersion:J,mode:V});let K=WA(),W=await S41(J,K);if(!(W.latestVersion&&W.hasUpdate)){G.debug("no update available");return}let H=()=>{if(W.currentVersionAge!==void 0&&W.latestVersionAge!==void 0){let U=W.currentVersionAge-W.latestVersionAge,N=0.5;if(Math.abs(U)<0.5)return G.debug("versions too close together, suppressing update warning",{currentVersionAge:W.currentVersionAge,latestVersionAge:W.latestVersionAge,ageDifferenceHours:U}),!0}return!1},z=await j41();if(!V)V=z==="pnpm"?"warn":"auto",G.debug("no configured update mode; selected default based on package manager",{packageManager:z,mode:V});if(V==="warn"){if(!H())Y.next("update-available");return}if(!z){if(G.debug("auto-update not supported, falling back to warn mode"),!H())Y.next("update-available");return}try{await $m(W.latestVersion,z);let U=await $N(W.latestVersion),N={from:W.currentVersion,to:W.latestVersion,...U};if(U.status==="same")G.info("success",N),Y.next("updated");else G.warn("success with warning",N),Y.next("updated-with-warning")}catch(U){Y.next("update-error")}}catch(q){G.debug("check failed",{error:q})}finally{await aU(5000),Y.next("hidden"),Z.unsubscribe(),Y.complete()}}),{state:X}}import{stderr as cK}from"node:process";function j76(J){let Q=new rO().name("install").description("Install required tools like ripgrep to $AMP_HOME/bin").option("--force","Force reinstallation even if already installed").option("--verbose","Show installation progress and results").action(async(X)=>{await cC1(X.force||!1,X.verbose||!1,"0.0.1764115312-g9a6608"),process.exit()});J.addCommand(Q,{hidden:!0});let Y=new rO("update").summary("Update Amp CLI").description("Update Amp CLI to the latest version. You can specify a particular version to install, or leave blank to get the latest stable release.").option("--target-version <version>","Update to a specific version").allowUnknownOption(!1).action(async(X)=>{await DV8(X.targetVersion)});J.addCommand(Y)}async function DV8(J){if(process.env.AMP_SKIP_UPDATE_CHECK==="1")cK.write(h4.yellow(`Note: AMP_SKIP_UPDATE_CHECK=1 is set, which disables automatic update checking. Manual updates will still work.
4400
+ npm install -g @sourcegraph/amp`;V(Error(M))}},error:(U)=>{if(!H)H=!0,V(Error(`Failed to spawn ${G}: ${U.message}`))},complete:()=>{if(!H)H=!0,q()}})})}U0();U0();async function S41(J,Q){let X=Q||"https://registry.npmjs.org";try{let G=new AbortController,Z=setTimeout(()=>G.abort(),5000),q=await fetch(`${X}/@sourcegraph/amp`,{signal:G.signal});if(clearTimeout(Z),!q.ok)return{hasUpdate:!1,currentVersion:J,source:"npm"};let V=await q.json(),K=V["dist-tags"]?.latest;if(!K)return{hasUpdate:!1,currentVersion:J,source:"npm"};let W=NV8(J,K),H=W<0,z,U;if(V.time){let N=V.time[J],M=V.time[K],L=Date.now();if(N)z=Math.floor((L-new Date(N).getTime())/3600000);if(M)U=Math.floor((L-new Date(M).getTime())/3600000)}return x.info("NPM version comparison",{currentVersion:J,latestVersion:K,compareResult:W,hasUpdate:H,currentVersionAge:z,latestVersionAge:U}),{hasUpdate:H,latestVersion:K,currentVersion:J,currentVersionAge:z,latestVersionAge:U,source:"npm"}}catch(G){return x.debug("Error checking npm version",{error:G}),{hasUpdate:!1,currentVersion:J,source:"npm"}}}function NV8(J,Q){let Y=(q)=>{let[V,K]=q.split("-");return{parts:V?.split(".").map(Number)||[],label:K}},X=Y(J),G=Y(Q),Z=Math.max(X.parts.length,G.parts.length);for(let q=0;q<Z;q++){let V=X.parts[q]||0,K=G.parts[q]||0;if(V<K)return-1;if(V>K)return 1}if(X.label===G.label)return 0;if(!X.label&&G.label)return 1;if(X.label&&!G.label)return-1;if(X.label&&G.label)return X.label<G.label?-1:1;return 0}d0();function _41(J,Q){let Y=new y4,X=Y.pipe(t8({shouldCountRefs:!1}));return setImmediate(async()=>{let G=new _V().scoped("update"),Z=X.subscribe({next:(q)=>{G.debug("emit new state",q)}});try{let q=process.env.AMP_TEST_UPDATE_STATUS;if(q){G.debug("using fake update status for testing",{status:q}),await aU(500),Y.next(q);return}if(process.env.AMP_SKIP_UPDATE_CHECK==="1"){G.debug("checking disabled via AMP_SKIP_UPDATE_CHECK environment variable");return}let V=await Q.get("updates.mode");if(V==="disabled"){G.debug("checking disabled");return}G.debug("checking",{currentVersion:J,mode:V});let K=WA(),W=await S41(J,K);if(!(W.latestVersion&&W.hasUpdate)){G.debug("no update available");return}let H=()=>{if(W.currentVersionAge!==void 0&&W.latestVersionAge!==void 0){let U=W.currentVersionAge-W.latestVersionAge,N=0.5;if(Math.abs(U)<0.5)return G.debug("versions too close together, suppressing update warning",{currentVersionAge:W.currentVersionAge,latestVersionAge:W.latestVersionAge,ageDifferenceHours:U}),!0}return!1},z=await j41();if(!V)V=z==="pnpm"?"warn":"auto",G.debug("no configured update mode; selected default based on package manager",{packageManager:z,mode:V});if(V==="warn"){if(!H())Y.next("update-available");return}if(!z){if(G.debug("auto-update not supported, falling back to warn mode"),!H())Y.next("update-available");return}try{await $m(W.latestVersion,z);let U=await $N(W.latestVersion),N={from:W.currentVersion,to:W.latestVersion,...U};if(U.status==="same")G.info("success",N),Y.next("updated");else G.warn("success with warning",N),Y.next("updated-with-warning")}catch(U){Y.next("update-error")}}catch(q){G.debug("check failed",{error:q})}finally{await aU(5000),Y.next("hidden"),Z.unsubscribe(),Y.complete()}}),{state:X}}import{stderr as cK}from"node:process";function j76(J){let Q=new rO().name("install").description("Install required tools like ripgrep to $AMP_HOME/bin").option("--force","Force reinstallation even if already installed").option("--verbose","Show installation progress and results").action(async(X)=>{await cC1(X.force||!1,X.verbose||!1,"0.0.1764129854-ge5da8d"),process.exit()});J.addCommand(Q,{hidden:!0});let Y=new rO("update").summary("Update Amp CLI").description("Update Amp CLI to the latest version. You can specify a particular version to install, or leave blank to get the latest stable release.").option("--target-version <version>","Update to a specific version").allowUnknownOption(!1).action(async(X)=>{await DV8(X.targetVersion)});J.addCommand(Y)}async function DV8(J){if(process.env.AMP_SKIP_UPDATE_CHECK==="1")cK.write(h4.yellow(`Note: AMP_SKIP_UPDATE_CHECK=1 is set, which disables automatic update checking. Manual updates will still work.
4401
4401
 
4402
4402
  `));try{if(!J){cK.write(h4.blue(`Checking for updates...
4403
- `));let Y=WA(),{hasUpdate:X,latestVersion:G}=await S41("0.0.1764115312-g9a6608",Y);if(!X){cK.write(h4.green(`✓ Amp CLI is already up to date.
4404
- `));let Z=await $N("0.0.1764115312-g9a6608");if(Z.warning)cK.write(`
4403
+ `));let Y=WA(),{hasUpdate:X,latestVersion:G}=await S41("0.0.1764129854-ge5da8d",Y);if(!X){cK.write(h4.green(`✓ Amp CLI is already up to date.
4404
+ `));let Z=await $N("0.0.1764129854-ge5da8d");if(Z.warning)cK.write(`
4405
4405
  `+h4.yellow(Z.warning)+`
4406
4406
  `);process.exit(0)}if(!G)cK.write(h4.yellow("[WARN] could not find latest version")),process.exit(0);J=G}cK.write(h4.blue(`Updating to version ${J}...
4407
4407
  `)),await $m(J,void 0,(Y)=>{cK.write(h4.dim(`Running: ${Y}
@@ -5026,7 +5026,7 @@ exit code: ${Z}`,new F1({color:X.foreground,dim:!0,italic:!0})));if(q)V.push(new
5026
5026
  `,M),...L],E=[new l1({text:new Q1("",void 0,O)})];if(W.url){let P=W.url.replace(/^https?:\/\//,"");E.push(new V4({children:[new l1({text:new Q1("See more: ",M)}),new J3({uri:W.url,text:P,style:new F1({color:Y.secondary,underline:!0})})]}))}let I=new s0({crossAxisAlignment:"stretch",mainAxisSize:"min",children:E});return H8.child(new X6({constraints:new s6(40,120,0,1/0),child:new V4({mainAxisAlignment:"center",crossAxisAlignment:"center",children:[new B4({flex:1,child:new VS1({width:40,height:40,agentMode:this.agentMode,...V&&{primaryColor:{r:100,g:20,b:20},secondaryColor:{r:255,g:60,b:70}},fps:q==="fast"?60:q==="slow"?15:0,...q==="disabled"&&{seed:42,t:3}})}),new L0({width:1}),new B4({flex:2,child:I})]})}))}}U0();M9();z4();D5();M9();d0();function bM8(J,Q){return`${J}:${Q}`}class fk1{threadService;workers=new Map;threadsMap=new Map;subthreadsMap=new Map;mainThreadSubs=new Map;subthreadsSubs=new Map;workerStatusSubs=new Map;subthreadPatchSubs=new Map;mainThreadObservable;subthreadObservable;workerStatusObservable;emitMainThread=null;emitSubthread=null;emitWorkerStatus=null;constructor(J){this.threadService=J;this.mainThreadObservable=new Q0((Q)=>{return this.emitMainThread=(Y)=>Q.next(Y),()=>{this.emitMainThread=null}}),this.subthreadObservable=new Q0((Q)=>{return this.emitSubthread=(Y)=>Q.next(Y),()=>{this.emitSubthread=null}}),this.workerStatusObservable=new Q0((Q)=>{return this.emitWorkerStatus=(Y)=>Q.next(Y),()=>{this.emitWorkerStatus=null}})}registerWorker(J){let Q=J.thread.id;if(this.workers.has(Q))this.unregisterWorker(Q);this.threadsMap.set(Q,J.thread),this.subthreadsMap.set(Q,[]),this.workers.set(Q,{state:"initial"});let Y=this.threadService.observePatches(Q).pipe(kM()).subscribe((Z)=>{this.threadsMap.set(Q,Z);let q=this.subthreadsMap.get(Q)||[],V=this.workers.get(Q)||{state:"initial"};if(this.emitMainThread)this.emitMainThread({threadID:Q,mainThread:Z,subthreads:q,workerStatus:V})});this.mainThreadSubs.set(Q,Y);let X=J.status.subscribe((Z)=>{if(this.workers.set(Q,Z),this.emitWorkerStatus)this.emitWorkerStatus({threadID:Q,status:Z})});this.workerStatusSubs.set(Q,X);let G=J.subthreads.subscribe((Z)=>{this.subthreadsMap.set(Q,Z);for(let q of Z){let V=bM8(Q,q.toolUse.id);if(this.subthreadPatchSubs.has(V))continue;let K=this.threadService.observePatches(q.threadID).pipe(kM()).subscribe((W)=>{if(this.emitSubthread)this.emitSubthread({threadID:Q,thread:W,subthread:q})});this.subthreadPatchSubs.set(V,K)}});this.subthreadsSubs.set(Q,G)}unregisterWorker(J){let Q=this.mainThreadSubs.get(J);if(Q)Q.unsubscribe(),this.mainThreadSubs.delete(J);let Y=this.workerStatusSubs.get(J);if(Y)Y.unsubscribe(),this.workerStatusSubs.delete(J);let X=this.subthreadsSubs.get(J);if(X)X.unsubscribe(),this.subthreadsSubs.delete(J);for(let[G,Z]of this.subthreadPatchSubs.entries())if(G.startsWith(`${J}:`))Z.unsubscribe(),this.subthreadPatchSubs.delete(G);this.workers.delete(J),this.threadsMap.delete(J),this.subthreadsMap.delete(J)}observeThread(J){return{mainThread:new Q0((Q)=>{return this.mainThreadObservable.subscribe((Y)=>{if(Y.threadID===J)Q.next(Y)})}),subthreads:new Q0((Q)=>{return this.subthreadObservable.subscribe((Y)=>{if(Y.threadID===J)Q.next(Y)})}),workerStatus:new Q0((Q)=>{return this.workerStatusObservable.subscribe((Y)=>{if(Y.threadID===J)Q.next(Y)})})}}get threadViewStates(){let J={};for(let[Q,Y]of this.threadsMap){let X=this.workers.get(Q);if(X)J[Q]=kO(Y,X)}return J}dispose(){for(let J of this.mainThreadSubs.values())J.unsubscribe();for(let J of this.subthreadsSubs.values())J.unsubscribe();for(let J of this.workerStatusSubs.values())J.unsubscribe();for(let J of this.subthreadPatchSubs.values())J.unsubscribe();this.mainThreadSubs.clear(),this.subthreadsSubs.clear(),this.workerStatusSubs.clear(),this.subthreadPatchSubs.clear(),this.workers.clear(),this.threadsMap.clear(),this.subthreadsMap.clear()}}function gM8(J,Q){switch(Q.type){case"subthread-patch":{let{thread:Y,subthread:X}=Q,G=J.subagents[X.threadID];if(!G){if(G={subThreadID:Y.id,parentToolID:X.toolUse.id,taskDescription:X.toolUse.input.description||"Task",isCompleted:!1,agentState:{type:"idle"}},J.mainThread){let W=$Q(J.mainThread);G.isCompleted=GG6(W,X.toolUse.id)}}let Z=mM8(Y,G.agentState),q=G.agentState===Z?G:{...G,agentState:Z},V={...J.tools},K=Yj(Y).items.filter((W)=>W.type==="toolResult");for(let W of K)V[W.id]={id:W.id,subthreadID:Y.id,toolRun:W.toolResult.run,toolUse:W.toolUse};return{subagents:{...J.subagents,[X.threadID]:q},tools:V,items:J.items,viewState:J.viewState,todosList:J.todosList,mainThread:J.mainThread}}case"main-thread-patch":{let{thread:Y,subthreads:X,workerStatus:G}=Q,Z=$Q(Y),q={...J.subagents};for(let z of X){let U=q[z.threadID];if(!U)continue;let N=GG6(Z,z.toolUse.id);q[z.threadID]={...U,isCompleted:N}}let{items:V}=Yj(Y),K=kO(Y,G),W=AI({messages:Y.messages}),H=Array.isArray(W)?W:[];return{...J,subagents:q,items:V,viewState:K,todosList:H,mainThread:Y}}case"worker-status-change":{if(!J.mainThread)return J;let Y=kO(J.mainThread,Q.workerStatus);if(Y===J.viewState)return J;return{...J,viewState:Y}}default:return J}}function Yj(J){let Q=[],Y=new Map,X=new Set;for(let[G,Z]of J.messages.entries()){let q=`${Z.role}-${G}`;switch(Z.role){case"assistant":{let V=Z.state.type==="streaming";for(let W of Z.content)if(W.type==="tool_use"){if(Y.set(W.id,W),V)X.add(W.id)}if(Z.content.some((W)=>W.type==="text"&&W.text.trim()||W.type==="thinking"))Q.push({type:"message",id:q,message:Z});for(let W of Z.content)if(W.type==="tool_use"){let H=!1;for(let z=G+1;z<J.messages.length;z++){let U=J.messages[z];if(U){for(let N of U.content)if(N.type==="tool_result"&&N.toolUseID===W.id){H=!0;break}}if(H)break}if(!H)Q.push({type:"toolResult",id:W.id,toolUse:W,toolResult:{type:"tool_result",toolUseID:W.id,run:{status:V?"in-progress":"queued"}}})}break}case"info":Q.push({type:"message",id:q,message:Z});break;case"user":{if(Z.content.some((K)=>K.type==="text"&&K.text.trim()||K.type==="image"))Q.push({type:"message",id:q,message:Z});for(let K of Z.content)if(K.type==="tool_result"){let W=Y.get(K.toolUseID)??CX(J,K.toolUseID);if(!W)throw Error(`(bug) tool use ${K.toolUseID} not found`);Q.push({type:"toolResult",id:K.toolUseID,toolUse:W,toolResult:K})}break}}}return{items:Q}}function GG6(J,Q){let Y=J.get(Q);return(Y&&M2(Y.run))??!1}function mM8(J,Q){let Y=J.messages.at(-1);if(Y?.content.some((G)=>G.type==="tool_result"&&G.run.status==="blocked-on-user"))return x.info("Subagent status: idle (blocked-on-user)",{threadID:J.id}),{type:"idle"};if(Yj(J).items.some((G)=>G.type==="toolResult"&&G.toolResult.run.status==="in-progress")){let G=Q?.type==="running-tools"?Q.startTime:Date.now();return x.info("Subagent status: running-tools",{threadID:J.id,startTime:G,hasStartTime:!!G}),{type:"running-tools",startTime:G}}if(Y&&Y.role==="assistant"&&Y.state.type==="streaming")switch(Y.content.at(-1)?.type){case"text":return x.info("Subagent status: streaming-text",{threadID:J.id}),{type:"streaming-text"};case"thinking":return x.info("Subagent status: streaming-thinking",{threadID:J.id}),{type:"streaming-thinking"};case"tool_use":{let Z=Q?.type==="running-tools"?Q.startTime:Date.now();return x.info("Subagent status: running-tools (streaming tool_use)",{threadID:J.id,startTime:Z,hasStartTime:!!Z}),{type:"running-tools",startTime:Z}}default:return x.info("Subagent status: streaming-text (default)",{threadID:J.id}),{type:"streaming-text"}}return x.info("Subagent status: idle (default)",{threadID:J.id}),{type:"idle"}}class hk1 extends q6{props;constructor(J){super();this.props=J}createState(){return new ZG6}}class ZG6 extends $6{state={subagents:{},tools:{},items:[],viewState:{state:"initial",interactionState:!1,toolState:{running:0,blocked:0}},todosList:[],mainThread:null};workerController;subscriptions=[];recentThreadIDs=[];currentWorker;constructor(){super();this.workerController=null,this.currentWorker=null}addToRecentThreads(J){this.setState(()=>{let Q=this.recentThreadIDs.indexOf(J);if(Q!==-1)this.recentThreadIDs.splice(Q,1);if(this.recentThreadIDs.unshift(J),this.recentThreadIDs.length>50)this.recentThreadIDs.pop()})}initState(){let{threadService:J,worker:Q}=this.widget.props;this.workerController=new fk1(J),this.currentWorker=Q,this.setupSubscriptions(Q),this.addToRecentThreads(Q.thread.id)}dispose(){this.cleanup()}didUpdateWidget(J){if(J.props.threadService!==this.widget.props.threadService||J.props.worker!==this.widget.props.worker)this.cleanup(),this.setupSubscriptions(this.widget.props.worker)}setupSubscriptions(J){this.workerController.registerWorker(J);let Q=this.workerController.observeThread(J.thread.id),Y=Q.mainThread.subscribe((Z)=>{this.dispatch({type:"main-thread-patch",thread:Z.mainThread,subthreads:Z.subthreads,workerStatus:Z.workerStatus})});this.subscriptions.push(Y);let X=Q.subthreads.subscribe((Z)=>{this.dispatch({type:"subthread-patch",thread:Z.thread,subthread:Z.subthread})});this.subscriptions.push(X);let G=Q.workerStatus.subscribe((Z)=>{this.dispatch({type:"worker-status-change",workerStatus:Z.status})});this.subscriptions.push(G)}cleanup(){this.subscriptions.forEach((J)=>J.unsubscribe()),this.subscriptions=[]}switchWorker(J){this.cleanup(),this.setState(()=>{this.currentWorker=J}),this.setState(()=>{this.state={subagents:{},tools:{},items:[],viewState:{state:"initial",interactionState:!1,toolState:{running:0,blocked:0}},todosList:[],mainThread:null}}),this.setupSubscriptions(J),this.addToRecentThreads(J.thread.id)}dispatch(J){this.setState(()=>{this.state=gM8(this.state,J)})}getThreadData(){let J=Object.values(this.state.tools).map((Z)=>({toolUse:Z.toolUse,toolRun:Z.toolRun,subthreadID:Z.subthreadID})),Q={};for(let Z of Object.values(this.state.subagents)){let q=J.filter((V)=>V.subthreadID===Z.subThreadID);Q[Z.parentToolID]=q}let Y=(Z)=>Z===Y7||Z===V9||Z===WI||Z===QU||Z===YU||Z===HI||Z===zI||Z===RX,X=new Map;for(let Z of this.state.items)if(Z.type==="toolResult"&&Y(Z.toolUse.name))X.set(Z.toolUse.id,{toolUseId:Z.toolUse.id,toolName:Z.toolUse.name,toolRun:Z.toolResult.run});let G=Array.from(X.values());for(let{toolUseId:Z,toolRun:q}of G){let V=[],K;if(q.status==="in-progress"||q.status==="done"||q.status==="error"||q.status==="cancelled")K=q.progress;if(K){let W=0;for(let H of K)if(H.tool_uses)for(let z of H.tool_uses){let U=`${Z}:progress:${W++}`;V.push({toolUse:MI(z.tool_name,z.input,U),toolRun:{status:z.status}})}}Q[Z]=V}return{...this.state,subagents:Object.values(this.state.subagents),subagentActiveTools:J,subagentToolsByParentID:Q}}build(J){let Q=this.getThreadData();return this.widget.props.builder(J,Q,this.workerController,(Y)=>this.switchWorker(Y),()=>this.currentWorker,this.recentThreadIDs)}}class bk1 extends q6{props;constructor(J){super({key:J.key});this.props=J}createState(){return new $G6}}class $G6 extends $6{build(J){let Y=b6.of(J).colors,{todos:X,title:G="TODOs"}=this.widget.props;if(!Array.isArray(X)||X.length===0)return new L0({width:0,height:0});let Z=X.map((q)=>this.buildTodoItem(q,Y));return new X6({child:new i6({padding:f0.symmetric(1,0),child:new s0({crossAxisAlignment:"stretch",mainAxisSize:"min",children:[new l1({text:new Q1(G,new F1({bold:!0,color:Y.foreground}))}),...Z]})})})}buildTodoItem(J,Q){let Y=this.getStatusIcon(J.status),X=J.status==="completed",G=new F1({bold:J.status==="in-progress",color:Q.foreground,dim:X}),Z=new F1({bold:J.status==="in-progress",strikethrough:J.status==="completed",color:Q.foreground,dim:X});return new V4({crossAxisAlignment:"start",children:[new l1({text:new Q1(Y,G)}),new L0({width:1}),new B4({child:new l1({text:new Q1(J.content,Z)})})]})}getStatusIcon(J){return J==="completed"?"✓":"•"}}class gk1 extends j6{ad;onDismiss;onButtonClick;constructor({key:J,ad:Q,onDismiss:Y,onButtonClick:X}){super({key:J});this.ad=Q,this.onDismiss=Y,this.onButtonClick=X}build(J){let Q=b6.of(J),Y=Q.colors.primary,X=Q.colors.foreground;return new X6({decoration:new E8(void 0,new d4(new P4(Y,1,"rounded"),new P4(Y,1,"rounded"),void 0,new P4(Y,1,"rounded"))),child:new i6({padding:f0.horizontal(1),child:new s0({children:[new V4({crossAxisAlignment:"start",children:[new B4({child:new l1({text:new Q1(this.ad.content,new F1({color:X}))})}),new L0({width:4}),new J3({uri:"https://ampcode.com/free",text:"Ad",style:new F1({color:X,dim:!0}),onError:(G)=>{}})]}),new V4({crossAxisAlignment:"start",children:[new OS1({text:this.ad.buttonLabel,onPressed:()=>this.onButtonClick?.(),padding:f0.horizontal(1),color:Y,reverse:!0}),new L0({width:2}),new l1({text:new Q1(this.ad.destinationUrlHostname,new F1({color:X,dim:!0}))})]})]})})})}}class mk1 extends q6{props;constructor(J){super();this.props=J}createState(){return new qG6(this.props.autofocus??!0)}}class qG6 extends $6{autofocus;constructor(J){super();this.autofocus=J}build(J){let Q=(V)=>{if(V.key==="Enter"&&this.widget.props.showCopyOption)return this.widget.props.onSelect("copy"),"handled";if(V.ctrlKey&&V.key==="c"||V.key==="Escape")return this.widget.props.onSelect(null),"handled";return"ignored"},Y=B8.sizeOf(J),X=Math.min(60,Y.width-4),G=Y.height-4,Z=[];if(this.widget.props.title)Z.push(new l1({text:new Q1(this.widget.props.title,new F1({bold:!0,color:A1.blue}))}),new L0({height:1}));if(this.widget.props.message)Z.push(new l1({text:new Q1(this.widget.props.message,void 0,void 0,{uri:this.widget.props.message,id:"ad-link"})}));if(this.widget.props.message)Z.push(new L0({height:1}));let q=[];if(this.widget.props.showCopyOption)q.push(new l1({text:new Q1("Enter to copy",new F1({dim:!0}))}));return q.push(new l1({text:new Q1("Escape to close",new F1({dim:!0}))})),Z.push(new V4({children:q.flatMap((V,K)=>K<q.length-1?[V,new L0({width:1}),new l1({text:new Q1("•",new F1({dim:!0}))}),new L0({width:1})]:[V]),mainAxisSize:"min"})),new H8({child:new X6({constraints:new s6(X,X,0,G),decoration:new E8(A1.default(),new d4(new P4(A1.blue,1,"rounded"),new P4(A1.blue,1,"rounded"),new P4(A1.blue,1,"rounded"),new P4(A1.blue,1,"rounded"))),padding:new f0(2,2,2,2),child:new G9({autofocus:this.autofocus,onKey:Q,child:new s0({children:Z,mainAxisSize:"min"})})})})}}class o91 extends Error{constructor(J="Command timed out"){super(J);this.name="CommandTimeoutError",Object.setPrototypeOf(this,o91.prototype)}}class r91 extends Error{constructor(J){let Q=`${J.noun}: ${J.verb} command cancelled`;super(Q);this.name="CommandCancelledError",Object.setPrototypeOf(this,r91.prototype)}}function uk1(J){let Q=J.match(/"([^"]*)"|'([^']*)'|([^\s"']+)/g);if(!Q)return[];return Q.map((Y)=>{if(Y.startsWith('"')&&Y.endsWith('"')||Y.startsWith("'")&&Y.endsWith("'"))return Y.slice(1,-1);return Y})}VU();U0();import{spawn as uM8}from"node:child_process";import{promises as pM8}from"node:fs";function VG6(J){return J.kind==="executable"}function KG6(J){return J.kind==="markdown"}var kz=50000,WG6=300000;async function pk1(J,Q,Y,X={}){let{timeoutMs:G=WG6,signal:Z,source:q}=X;try{let V=await Y.getCommand(J,q);if(!V)return{success:!1,output:"",error:`Command '${J}' not found`};if(!await Y.isCommandAvailable(J,q))return{success:!1,output:"",error:`Command '${J}' is not available for execution`};if(x.debug("Executing command",{commandName:J,filePath:V.filePath,args:Q}),KG6(V))return await dM8(V,Q);else if(VG6(V))return await cM8(V,Q,G,Z);else return{success:!1,output:"",error:"Unsupported command type"}}catch(V){return x.error("Failed to execute command",{commandName:J,error:V}),{success:!1,output:"",error:V instanceof Error?V.message:"Unknown error occurred"}}}async function dM8(J,Q){try{if(Q.length>0)return{success:!1,output:"",error:"Markdown commands do not accept arguments"};let Y=await pM8.readFile(J.filePath,"utf8");return{success:!0,output:(Y.length>kz?Y.slice(0,kz)+`
5027
5027
  ... (output truncated at ${kz} characters)`:Y).trim(),exitCode:0}}catch(Y){return{success:!1,output:"",error:Y instanceof Error?Y.message:"Failed to read markdown file"}}}async function cM8(J,Q,Y=WG6,X){return new Promise((G)=>{let[Z,q]=lM8(J,Q);x.debug("Spawning command",{spawnCommand:Z,spawnArgs:q.slice(0,10),filePath:J.filePath,timeoutMs:Y});let V=CM0(X),K=!1,W=setTimeout(()=>{K=!0,V.abort(),x.warn("Command execution timed out",{commandName:J.name,timeoutMs:Y})},Y),H=uM8(Z,q,{stdio:["pipe","pipe","pipe"],signal:V.signal,detached:!0}),z=[],U=[],N=0;H.stdout?.on("data",(M)=>{let L=M.toString();if(N+=L.length,N<=kz)z.push(L);else{let O=kz-(N-L.length);if(O>0)z.push(L.slice(0,O))}}),H.stderr?.on("data",(M)=>{let L=M.toString();if(N+=L.length,N<=kz)U.push(L);else{let O=kz-(N-L.length);if(O>0)U.push(L.slice(0,O))}}),H.on("close",(M)=>{if(clearTimeout(W),K){G({success:!1,output:z.join(""),error:`Command timed out after ${Y}ms`,exitCode:void 0});return}if(V.signal.aborted){G({success:!1,output:z.join(""),error:"The command was aborted",exitCode:M??void 0});return}let L=M===0||M===1,O=z.join(""),E=U.join(""),I=O;if(!L&&!O.trim()&&E.trim())I=E;else if(E.trim())I+=O?`
5028
5028
  ${E}`:E;if(N>kz)I+=`
5029
- ... (output truncated at ${kz} characters)`;G({success:L,output:I.trim(),error:!L?E.trim()||"Command failed":void 0,exitCode:M??void 0})}),H.on("error",(M)=>{clearTimeout(W);let L=M.message;if(K)L=`Command timed out after ${Y}ms`;else if(M.message.includes("operation was aborted")||M.name==="AbortError")L="The command was aborted";G({success:!1,output:z.join(""),error:L})})})}function lM8(J,Q){let{filePath:Y,interpreter:X,extension:G}=J;if(process.platform==="win32")return nM8(Y,X?[...X]:null,G,Q);else return iM8(Y,X?[...X]:null,G,Q)}function iM8(J,Q,Y,X){if(Q&&Q.length>0&&Q[0])return[Q[0],[...Q.slice(1),J,...X]];else return[J,X]}function nM8(J,Q,Y,X){if(Q&&Q.length>0&&Q[0])return[Q[0],[...Q.slice(1),J,...X]];switch(Y.toLowerCase()){case".bat":case".cmd":return["cmd.exe",["/c",J,...X]];case".ps1":return["powershell.exe",["-ExecutionPolicy","Bypass","-File",J,...X]];case".exe":return[J,X];default:return[J,X]}}U0();Hq();b5();eW();OZ();Wq();dV();vH();H11();D5();Mk();d0();var LG6=z6(uU(),1);import{writeFile as NG6}from"fs/promises";import DG6 from"path";U0();OZ();class dk1{enabled;configService;commandCounts=new Map;timer=null;bufferTimeMs=1e4;constructor(J,Q){this.enabled=J;this.configService=Q;this.startTimer()}startTimer(){this.timer=setInterval(()=>{this.flushEvents()},this.bufferTimeMs)}async flushEvents(){if(this.commandCounts.size===0||!await this.enabled())return;let J=Array.from(this.commandCounts.entries()).map(([Q,Y])=>({feature:"cli.command",action:Q,source:{client:"cli",clientVersion:"0.0.1764115312-g9a6608"},parameters:{metadata:{count:Y}},timestamp:Date.now()*1000}));this.commandCounts.clear();try{let Q=JSON.stringify(J);await Ts(Q,this.configService)}catch(Q){x.error("Failed to export command telemetry events",Q)}}async submit(J){if(!await this.enabled()||this.timer===null)return;let Q=this.commandCounts.get(J)||0;this.commandCounts.set(J,Q+1)}async dispose(){if(await this.flushEvents(),this.timer!==null)clearInterval(this.timer),this.timer=null}}class ck1 extends q6{props;constructor(J){super();this.props=J}createState(){return new HG6}}class HG6 extends $6{_state;initState(){super.initState(),this._state=this.widget.props.initialState}build(J){let Q=(Y)=>{this.setState(()=>{this._state=Y(this._state)})};return this.widget.props.builder(J,Q,this._state)}}class zG6 extends $6{controller=new rZ;focusNode=new a8({debugLabel:"CommandArgumentPrompt",onKey:(J)=>{if(J.key==="Escape")return this.widget.props.onDismiss(),"handled";return"ignored"}});_textListener=()=>{this.setState(()=>{})};initState(){this.focusNode.requestFocus(),this.controller.addListener(this._textListener)}dispose(){this.controller.removeListener(this._textListener),this.focusNode.dispose()}build(J){let Q=b6.of(J),{colors:Y,app:X}=Q,G=this.widget.props.isRequiredArg??!0,Z=this.controller.text.trim().length>0,q=!G||Z,V=d4.all(new P4(Y.foreground,1,"solid")),K=new IA({controller:this.controller,focusNode:this.focusNode,placeholder:this.widget.props.placeholder??"Enter command argument...",onSubmitted:(N)=>{let M=N.trim();if(G&&M.length===0)return;this.widget.props.onSubmit(M)},autofocus:!0,style:{textColor:Y.foreground,border:null},maxLines:1}),W=new V4({children:[new X6({decoration:{color:A1.default()},child:new l1({text:new Q1(">",new F1({color:Y.foreground}))})}),new B4({child:K})]}),H=new X6({padding:f0.symmetric(1,0),child:new l1({text:new Q1("",void 0,[new Q1("Command: ",new F1({color:Y.foreground})),new Q1(this.widget.props.commandName,new F1({color:A1.yellow,bold:!0}))])})}),z=[];if(q)z.push(new Q1("Enter",new F1({color:X.keybind}))),z.push(new Q1(" to submit, ",new F1({color:Y.foreground,dim:!0})));z.push(new Q1("Esc",new F1({color:X.keybind}))),z.push(new Q1(" to cancel",new F1({color:Y.foreground,dim:!0})));let U=new X6({padding:f0.symmetric(1,0),child:new l1({text:new Q1("",void 0,z)})});return new X6({decoration:{border:V,color:A1.default()},padding:f0.all(1),child:new s0({children:[H,new L0({height:1}),W,new s5,U]})})}}class s91 extends q6{props;constructor(J){super();this.props=J}createState(){return new zG6}}dV();class FG6 extends $6{controller=new rZ;imageAttachments=[];imagePaths=[];isConfirmingClearInput=!1;clearInputConfirmTimeout=null;focusNode=new a8({debugLabel:"CommandMultilinePrompt",onKey:(J)=>{if(J.key==="Escape"){if(this.isConfirmingClearInput){if(this.controller.clear(),this.setState(()=>{this.isConfirmingClearInput=!1,this.imageAttachments=[],this.imagePaths=[]}),this.clearInputConfirmTimeout)clearTimeout(this.clearInputConfirmTimeout),this.clearInputConfirmTimeout=null;return"handled"}if(this.controller.text.trim()!==""||this.imageAttachments.length>0){if(this.setState(()=>{this.isConfirmingClearInput=!0}),this.clearInputConfirmTimeout)clearTimeout(this.clearInputConfirmTimeout);return this.clearInputConfirmTimeout=setTimeout(()=>{this.setState(()=>{this.isConfirmingClearInput=!1}),this.clearInputConfirmTimeout=null},1000),"handled"}return this.widget.props.onDismiss(),"handled"}return"ignored"}});initState(){if(this.widget.props.initialText)this.controller.text=this.widget.props.initialText;if(this.widget.props.initialImages)this.imageAttachments=[...this.widget.props.initialImages];this.focusNode.requestFocus()}_handleInsertImage=(J)=>{if(this.imageAttachments.length>=WU)return!1;let Q=gC(J);if(typeof Q==="object")return this.setState(()=>{this.imageAttachments=[...this.imageAttachments,Q],this.imagePaths=[...this.imagePaths,J]}),!1;return!1};_handlePopImage=()=>{if(this.imageAttachments.length>0)this.setState(()=>{this.imageAttachments=this.imageAttachments.slice(0,-1),this.imagePaths=this.imagePaths.slice(0,-1)})};dispose(){if(this.clearInputConfirmTimeout)clearTimeout(this.clearInputConfirmTimeout),this.clearInputConfirmTimeout=null;this.focusNode.dispose(),this.controller.dispose()}build(J){let Q=b6.of(J),{colors:Y,app:X}=Q,Z=B8.of(J).size.height,q=Math.max(Math.floor(Z*0.5),10),V=new gA({controller:this.controller,triggers:[new PN],completionBuilder:this.widget.props.completionBuilder,ampURL:this.widget.props.ampURL,onSubmitted:(N)=>{this.widget.props.onSubmit(N.trim(),this.imageAttachments)},theme:Y,placeholder:this.widget.props.placeholder||"Enter your message...",enabled:this.widget.props.enabled??!0,autofocus:!0,clipboard:T9.instance.tuiInstance.clipboard,showMenuBelow:!0,onInsertImage:this.widget.props.onInsertImage??this._handleInsertImage,imageAttachments:this.imageAttachments,popImage:this._handlePopImage}),K=new G9({focusNode:this.focusNode,child:V}),W=new X6({constraints:new s6({maxHeight:q}),padding:f0.symmetric(1,0),child:K}),H=new X6({padding:f0.symmetric(1,0),child:new l1({text:new Q1("",void 0,[new Q1("Command: ",new F1({color:Y.foreground})),new Q1(this.widget.props.commandName,new F1({color:A1.yellow,bold:!0}))])})}),z=new X6({padding:f0.symmetric(1,0),child:new l1({text:this.isConfirmingClearInput?new Q1("",void 0,[new Q1("Esc",new F1({color:X.keybind})),new Q1(" again to clear input",new F1({color:Y.foreground,dim:!0}))]):new Q1("",void 0,[new Q1("Press ",new F1({color:Y.foreground,dim:!0})),new Q1("Enter",new F1({color:X.keybind})),new Q1(" to submit, ",new F1({color:Y.foreground,dim:!0})),new Q1("Esc",new F1({color:X.keybind})),new Q1(" to clear",new F1({color:Y.foreground,dim:!0}))])})}),U=[H,new L0({height:1}),new B4({child:W}),new L0({height:1}),z];return new X6({decoration:{border:d4.all(new P4(Y.foreground,1,"solid")),color:A1.default()},padding:f0.all(1),child:new s0({children:U})})}}class mA extends q6{props;constructor(J){super();this.props=J}createState(){return new FG6}}class lk1 extends j6{props;constructor(J){super();this.props=J}build(){return new H8({child:new l1({text:new Q1("",void 0,[new Q1(`Forked to new thread:
5029
+ ... (output truncated at ${kz} characters)`;G({success:L,output:I.trim(),error:!L?E.trim()||"Command failed":void 0,exitCode:M??void 0})}),H.on("error",(M)=>{clearTimeout(W);let L=M.message;if(K)L=`Command timed out after ${Y}ms`;else if(M.message.includes("operation was aborted")||M.name==="AbortError")L="The command was aborted";G({success:!1,output:z.join(""),error:L})})})}function lM8(J,Q){let{filePath:Y,interpreter:X,extension:G}=J;if(process.platform==="win32")return nM8(Y,X?[...X]:null,G,Q);else return iM8(Y,X?[...X]:null,G,Q)}function iM8(J,Q,Y,X){if(Q&&Q.length>0&&Q[0])return[Q[0],[...Q.slice(1),J,...X]];else return[J,X]}function nM8(J,Q,Y,X){if(Q&&Q.length>0&&Q[0])return[Q[0],[...Q.slice(1),J,...X]];switch(Y.toLowerCase()){case".bat":case".cmd":return["cmd.exe",["/c",J,...X]];case".ps1":return["powershell.exe",["-ExecutionPolicy","Bypass","-File",J,...X]];case".exe":return[J,X];default:return[J,X]}}U0();Hq();b5();eW();OZ();Wq();dV();vH();H11();D5();Mk();d0();var LG6=z6(uU(),1);import{writeFile as NG6}from"fs/promises";import DG6 from"path";U0();OZ();class dk1{enabled;configService;commandCounts=new Map;timer=null;bufferTimeMs=1e4;constructor(J,Q){this.enabled=J;this.configService=Q;this.startTimer()}startTimer(){this.timer=setInterval(()=>{this.flushEvents()},this.bufferTimeMs)}async flushEvents(){if(this.commandCounts.size===0||!await this.enabled())return;let J=Array.from(this.commandCounts.entries()).map(([Q,Y])=>({feature:"cli.command",action:Q,source:{client:"cli",clientVersion:"0.0.1764129854-ge5da8d"},parameters:{metadata:{count:Y}},timestamp:Date.now()*1000}));this.commandCounts.clear();try{let Q=JSON.stringify(J);await Ts(Q,this.configService)}catch(Q){x.error("Failed to export command telemetry events",Q)}}async submit(J){if(!await this.enabled()||this.timer===null)return;let Q=this.commandCounts.get(J)||0;this.commandCounts.set(J,Q+1)}async dispose(){if(await this.flushEvents(),this.timer!==null)clearInterval(this.timer),this.timer=null}}class ck1 extends q6{props;constructor(J){super();this.props=J}createState(){return new HG6}}class HG6 extends $6{_state;initState(){super.initState(),this._state=this.widget.props.initialState}build(J){let Q=(Y)=>{this.setState(()=>{this._state=Y(this._state)})};return this.widget.props.builder(J,Q,this._state)}}class zG6 extends $6{controller=new rZ;focusNode=new a8({debugLabel:"CommandArgumentPrompt",onKey:(J)=>{if(J.key==="Escape")return this.widget.props.onDismiss(),"handled";return"ignored"}});_textListener=()=>{this.setState(()=>{})};initState(){this.focusNode.requestFocus(),this.controller.addListener(this._textListener)}dispose(){this.controller.removeListener(this._textListener),this.focusNode.dispose()}build(J){let Q=b6.of(J),{colors:Y,app:X}=Q,G=this.widget.props.isRequiredArg??!0,Z=this.controller.text.trim().length>0,q=!G||Z,V=d4.all(new P4(Y.foreground,1,"solid")),K=new IA({controller:this.controller,focusNode:this.focusNode,placeholder:this.widget.props.placeholder??"Enter command argument...",onSubmitted:(N)=>{let M=N.trim();if(G&&M.length===0)return;this.widget.props.onSubmit(M)},autofocus:!0,style:{textColor:Y.foreground,border:null},maxLines:1}),W=new V4({children:[new X6({decoration:{color:A1.default()},child:new l1({text:new Q1(">",new F1({color:Y.foreground}))})}),new B4({child:K})]}),H=new X6({padding:f0.symmetric(1,0),child:new l1({text:new Q1("",void 0,[new Q1("Command: ",new F1({color:Y.foreground})),new Q1(this.widget.props.commandName,new F1({color:A1.yellow,bold:!0}))])})}),z=[];if(q)z.push(new Q1("Enter",new F1({color:X.keybind}))),z.push(new Q1(" to submit, ",new F1({color:Y.foreground,dim:!0})));z.push(new Q1("Esc",new F1({color:X.keybind}))),z.push(new Q1(" to cancel",new F1({color:Y.foreground,dim:!0})));let U=new X6({padding:f0.symmetric(1,0),child:new l1({text:new Q1("",void 0,z)})});return new X6({decoration:{border:V,color:A1.default()},padding:f0.all(1),child:new s0({children:[H,new L0({height:1}),W,new s5,U]})})}}class s91 extends q6{props;constructor(J){super();this.props=J}createState(){return new zG6}}dV();class FG6 extends $6{controller=new rZ;imageAttachments=[];imagePaths=[];isConfirmingClearInput=!1;clearInputConfirmTimeout=null;focusNode=new a8({debugLabel:"CommandMultilinePrompt",onKey:(J)=>{if(J.key==="Escape"){if(this.isConfirmingClearInput){if(this.controller.clear(),this.setState(()=>{this.isConfirmingClearInput=!1,this.imageAttachments=[],this.imagePaths=[]}),this.clearInputConfirmTimeout)clearTimeout(this.clearInputConfirmTimeout),this.clearInputConfirmTimeout=null;return"handled"}if(this.controller.text.trim()!==""||this.imageAttachments.length>0){if(this.setState(()=>{this.isConfirmingClearInput=!0}),this.clearInputConfirmTimeout)clearTimeout(this.clearInputConfirmTimeout);return this.clearInputConfirmTimeout=setTimeout(()=>{this.setState(()=>{this.isConfirmingClearInput=!1}),this.clearInputConfirmTimeout=null},1000),"handled"}return this.widget.props.onDismiss(),"handled"}return"ignored"}});initState(){if(this.widget.props.initialText)this.controller.text=this.widget.props.initialText;if(this.widget.props.initialImages)this.imageAttachments=[...this.widget.props.initialImages];this.focusNode.requestFocus()}_handleInsertImage=(J)=>{if(this.imageAttachments.length>=WU)return!1;let Q=gC(J);if(typeof Q==="object")return this.setState(()=>{this.imageAttachments=[...this.imageAttachments,Q],this.imagePaths=[...this.imagePaths,J]}),!1;return!1};_handlePopImage=()=>{if(this.imageAttachments.length>0)this.setState(()=>{this.imageAttachments=this.imageAttachments.slice(0,-1),this.imagePaths=this.imagePaths.slice(0,-1)})};dispose(){if(this.clearInputConfirmTimeout)clearTimeout(this.clearInputConfirmTimeout),this.clearInputConfirmTimeout=null;this.focusNode.dispose(),this.controller.dispose()}build(J){let Q=b6.of(J),{colors:Y,app:X}=Q,Z=B8.of(J).size.height,q=Math.max(Math.floor(Z*0.5),10),V=new gA({controller:this.controller,triggers:[new PN],completionBuilder:this.widget.props.completionBuilder,ampURL:this.widget.props.ampURL,onSubmitted:(N)=>{this.widget.props.onSubmit(N.trim(),this.imageAttachments)},theme:Y,placeholder:this.widget.props.placeholder||"Enter your message...",enabled:this.widget.props.enabled??!0,autofocus:!0,clipboard:T9.instance.tuiInstance.clipboard,showMenuBelow:!0,onInsertImage:this.widget.props.onInsertImage??this._handleInsertImage,imageAttachments:this.imageAttachments,popImage:this._handlePopImage}),K=new G9({focusNode:this.focusNode,child:V}),W=new X6({constraints:new s6({maxHeight:q}),padding:f0.symmetric(1,0),child:K}),H=new X6({padding:f0.symmetric(1,0),child:new l1({text:new Q1("",void 0,[new Q1("Command: ",new F1({color:Y.foreground})),new Q1(this.widget.props.commandName,new F1({color:A1.yellow,bold:!0}))])})}),z=new X6({padding:f0.symmetric(1,0),child:new l1({text:this.isConfirmingClearInput?new Q1("",void 0,[new Q1("Esc",new F1({color:X.keybind})),new Q1(" again to clear input",new F1({color:Y.foreground,dim:!0}))]):new Q1("",void 0,[new Q1("Press ",new F1({color:Y.foreground,dim:!0})),new Q1("Enter",new F1({color:X.keybind})),new Q1(" to submit, ",new F1({color:Y.foreground,dim:!0})),new Q1("Esc",new F1({color:X.keybind})),new Q1(" to clear",new F1({color:Y.foreground,dim:!0}))])})}),U=[H,new L0({height:1}),new B4({child:W}),new L0({height:1}),z];return new X6({decoration:{border:d4.all(new P4(Y.foreground,1,"solid")),color:A1.default()},padding:f0.all(1),child:new s0({children:U})})}}class mA extends q6{props;constructor(J){super();this.props=J}createState(){return new FG6}}class lk1 extends j6{props;constructor(J){super();this.props=J}build(){return new H8({child:new l1({text:new Q1("",void 0,[new Q1(`Forked to new thread:
5030
5030
 
5031
5031
  `,new F1({color:A1.white,dim:!0})),new Q1(`"${this.props.newThreadTitle||"Untitled"}"`,new F1({color:A1.white}))]),textAlign:"center"})})}}class yz extends q6{props;constructor(J){super();this.props=J}createState(){return new UG6}}class UG6 extends $6{_spinner=new JW;animationInterval=null;initState(){super.initState(),this.animationInterval=setInterval(()=>{this._spinner.step(),this.setState(()=>{})},100)}dispose(){if(this.animationInterval)clearInterval(this.animationInterval),this.animationInterval=null;super.dispose()}build(J){let Q=b6.of(J),{colors:Y}=Q,X=d4.all(new P4(Y.foreground,1,"solid")),G=this._spinner.toBraille(),Z=new l1({textAlign:"center",text:new Q1("",void 0,[new Q1(G,new F1({color:A1.yellow})),new Q1(" ",void 0),new Q1(this.widget.props.message,new F1({color:Y.foreground}))])}),V=[new B4({child:new s0({mainAxisAlignment:"center",crossAxisAlignment:"center",children:[Z]})})];if(this.widget.props.onAbort)V.push(new L0({height:2,child:new X6({padding:f0.symmetric(2,0),child:new l1({text:new Q1("",new F1({dim:!0}),[new Q1("Press ",new F1({color:Y.foreground})),new Q1("Esc",new F1({color:Y.info})),new Q1(" to cancel",new F1({color:Y.foreground}))])})})}));let K=new X6({decoration:new E8(A1.default(),X),child:new L0({width:60,height:7,child:new s0({mainAxisAlignment:"start",children:V})})});if(this.widget.props.onAbort)return new G9({debugLabel:"LoadingDialog",autofocus:!0,onKey:(W)=>{if(W.key==="Escape")return this.widget.props.onAbort?.(),"handled";return"ignored"},child:K});return K}}class xz extends q6{props;constructor(J){super();this.props=J}createState(){return new BG6}}class BG6 extends $6{dispose(){super.dispose()}isWidgetMessage(J){return J instanceof rK}build(J){let Q=this.widget.props.message,Y=(()=>{if(this.isWidgetMessage(Q))return{title:Q.title,type:Q.type};if(Q instanceof Error&&Q.name==="CommandCancelledError")return{title:"Cancelled",type:"info",description:Q.message};if(Q instanceof Error&&Q.name==="CommandTimeoutError")return{title:"Timeout",type:"error",description:Q.message};let W=X91(Q);return{title:W.title,type:W.type,description:W.description}})(),X=Y.type==="error"?A1.red:A1.yellow,G=d4.all(new P4(A1.default(),1,"solid")),Z=new X6({padding:f0.symmetric(1,0),child:new l1({text:new Q1(Y.title,new F1({color:X,bold:!0}))})}),q=this.isWidgetMessage(Q)?Q.widget:new l1({text:new Q1(Y.description,new F1({color:A1.default()})),selectable:!0}),V=new B4({child:new AA({child:new X6({padding:f0.symmetric(1,0),child:q})})}),K=new X6({padding:f0.symmetric(1,0),child:new l1({text:this.widget.props.onRetry?new Q1("",void 0,[new Q1("Press ",new F1({color:A1.default(),dim:!0})),new Q1("R",new F1({color:A1.yellow})),new Q1(" to retry, ",new F1({color:A1.default(),dim:!0})),new Q1("Esc",new F1({color:A1.yellow})),new Q1(" to cancel",new F1({color:A1.default(),dim:!0}))]):new Q1("Press any key to close",new F1({color:A1.default(),dim:!0,italic:!0}))})});return new G9({onKey:(W)=>{if(this.widget.props.onRetry&&W.key==="r")return this.widget.props.onRetry(),"handled";if(W.key==="Escape")return this.widget.props.onDismiss(),"handled";if(!this.widget.props.onRetry)return this.widget.props.onDismiss(),"handled";return"ignored"},autofocus:!0,child:new X6({decoration:{border:G,color:A1.default()},padding:f0.all(1),child:new s0({mainAxisAlignment:"center",children:[Z,new L0({height:1}),V,K]})})})}}class ik1 extends j6{build(){return new H8({child:new l1({text:new Q1("",void 0,[new Q1(`✓ Thread Shared
5032
5032
 
@@ -5112,7 +5112,7 @@ https://www.jetbrains.com/help/idea/managing-plugins.html#install_plugin_from_di
5112
5112
  `)?`${V}...`:G,W=new F1({color:A1.index(8)}),H=[new Q1(K,W)];if(q>0){let z=new F1({color:Y.success});for(let U=1;U<=q;U++)H.push(new Q1(" ")),H.push(new Q1(`[${U}]`,z))}return new i6({padding:f0.only({bottom:0}),child:new V4({crossAxisAlignment:"start",children:[new i6({padding:f0.only({right:1}),child:new l1({text:new Q1("•",new F1({color:A1.index(8)}))})}),new B4({child:new l1({text:new Q1("",void 0,H)})})]})})}}class wy1 extends q6{createState(){return new HZ6}}class HZ6 extends $6{_animationTimer;_visible=!0;initState(){super.initState(),this._startAnimation()}dispose(){this._stopAnimation(),super.dispose()}_startAnimation(){this._animationTimer=setInterval(()=>{this.setState(()=>{this._visible=!this._visible})},500)}_stopAnimation(){if(this._animationTimer)clearInterval(this._animationTimer),this._animationTimer=void 0}build(J){let Q=new F1({color:A1.red}),Y=new F1({color:this._visible?A1.red:A1.transparent()});return new V4({children:[new l1({text:new Q1("⏺",Y)}),new L0({width:1}),new l1({text:new Q1("Replay",Q)})]})}}class Ey1 extends j6{entry;constructor({key:J,entry:Q}){super({key:J});this.entry=Q}build(J){let Q=b6.of(J),Y=Q.colors.secondary,X=Q.colors.foreground,G=this.entry.authors.map((Z)=>Z.name).join(", ");return new X6({decoration:new E8(void 0,new d4(new P4(Y,1,"rounded"),new P4(Y,1,"rounded"),void 0,new P4(Y,1,"rounded"))),child:new i6({padding:f0.horizontal(1),child:new s0({children:[new V4({crossAxisAlignment:"start",children:[new B4({child:new l1({text:new Q1(this.entry.title,new F1({color:X,bold:!0}))})}),new L0({width:4}),new l1({text:new Q1(G||"Community",new F1({color:X,dim:!0}))})]}),new V4({crossAxisAlignment:"start",children:[new B4({child:new L0({})}),new J3({uri:this.entry.link,text:"View Thread",style:new F1({color:Y,underline:!0}),onError:(Z)=>{}})]})]})})})}}d0();function XO8(J){let Y=new Date().getTime()-J.getTime(),X=Math.floor(Y/3600000),G=Math.floor(X/24),Z=Math.floor(G/7),q=Math.floor(G/30);if(X<1)return"Just now";if(X<24)return`${X}h ago`;if(G<7)return`${G}d ago`;if(Z<=4)return`${Z}w ago`;return`${q}mo ago`}class Iy1{threadHistoryService;constructor(J){this.threadHistoryService=J}async fetchThreadSummaries(J=""){try{let Q=await new Promise((Y)=>{let X=this.threadHistoryService.observeThreadList().subscribe((G)=>{X.unsubscribe(),Y(G)})});return{ok:!0,threads:this.formatThreadSummaries(Q,J)}}catch(Q){return{ok:!1,errorMsg:Q instanceof Error?Q.message:"An unexpected error occurred"}}}observeThreadSummaries(J=""){return this.threadHistoryService.observeHistory().pipe(Y6((Q)=>this.formatThreadSummaries(Q,J)))}formatThreadSummaries(J,Q){return J.filter((X)=>{if(!Q.trim())return!0;let G=X.title?.toLowerCase()||"untitled",Z=X.id.toLowerCase(),q=Q.toLowerCase();return G.includes(q)||Z.includes(q)}).map((X)=>{let G=new Date(X.userLastInteractedAt),Z=XO8(G),q=X.id.slice(-8),V=X.env?.initial.trees?.[0]?.uri;return{id:X.id,title:X.title||"Untitled",updatedAt:new Date(X.userLastInteractedAt).toISOString(),description:{timeAgo:Z,title:X.title||"Untitled",shortThreadID:q},diffStats:X.summaryStats?.diffStats,workspaceURI:V,parentRelationships:X.parentRelationships}})}}U0();M9();class Py1{currentId=null;current=null;subscribeTimer=null;subscription=null;listeners=[];threadService=null;scrollController=new r3;constructor(){}setThreadService(J){this.threadService=J}async select(J){if(!this.threadService){x.error("TUI assert failed: ThreadService used before being set");return}if(this.currentId===J)return;this.cancelTimerAndSubscription(),this.currentId=J;let Q=await this.threadService.get(J);if(Q){if(this.currentId===J)this.current=Q,this.notifyListeners()}this.subscribeTimer=setTimeout(()=>{this.subscribeLive(J)},1000)}clear(){this.cancelTimerAndSubscription(),this.currentId=null,this.current=null,this.notifyListeners()}addListener(J){this.listeners.push(J)}removeListener(J){let Q=this.listeners.indexOf(J);if(Q!==-1)this.listeners.splice(Q,1)}dispose(){this.cancelTimerAndSubscription(),this.scrollController.dispose(),this.listeners=[]}subscribeLive(J){if(!this.threadService){x.error("TUI assert failed: ThreadService used before being set");return}if(this.currentId!==J)return;this.subscription=this.threadService.observePatches(J).pipe(kM()).subscribe((Q)=>{if(this.currentId===J)this.current=Q,this.notifyListeners()})}cancelTimerAndSubscription(){if(this.subscribeTimer)clearTimeout(this.subscribeTimer),this.subscribeTimer=null;if(this.subscription)this.subscription.unsubscribe(),this.subscription=null}notifyListeners(){for(let J of this.listeners)J(this.current)}}function zZ6(J,Q){switch(J){case"update-available":return[new Q1("A newer Amp is available. Run ",new F1({color:Q.foreground,dim:!0})),new Q1("amp update",new F1({color:Q.warning}))];case"updated":return null;case"updated-with-warning":return[new Q1("Update complete, run ",new F1({color:Q.foreground,dim:!0})),new Q1("amp update",new F1({color:Q.warning})),new Q1(" to see warnings",new F1({color:Q.foreground,dim:!0}))];case"update-error":return[new Q1("Update failed, run ",new F1({color:Q.foreground,dim:!0})),new Q1("amp update",new F1({color:Q.warning})),new Q1(" to see warnings",new F1({color:Q.foreground,dim:!0}))];case"hidden":return null}}async function VO8(J){return new Promise((Q)=>{ZO8("git",["branch","--show-current"],{cwd:J},(Y,X)=>{if(Y){Q(null);return}let G=X.trim();Q(G||null)})})}class NZ6 extends q6{dependencies;constructor(J){super();this.dependencies=J}createState(){return new DZ6}}class DZ6 extends $6{themeColors=null;themeApp=null;selectionListener=null;ideStatus=null;connectedClientsStatus=null;connectedClientsStatusExpanded=!1;randomAd=null;adSubscription=null;threadLoadSubscription=null;lastAdImpressionId=null;lastUserInteractionTime=Date.now();isConfirmingExit=!1;isExiting=!1;isConfirmingClearInput=!1;isConfirmingCancelProcessing=!1;copyMessageTimer=null;isShowingHelp=!1;isShowingConsoleOverlay=!1;isShowingConfirmationOverlay=!1;isShowingFileChangesOverlay=!1;isShowingCostBreakdownOverlay=!1;confirmationOverlayContent="";exitConfirmTimeout=null;clearInputConfirmTimeout=null;cancelProcessingConfirmTimeout=null;historyIndex=-1;historyDraft=null;bashInvocations=[];dismissedEphemeralErrorKey=null;currentTitle=void 0;currentShellModeStatus=void 0;imageAttachments=[];displayMessage=null;executingCommand=null;isShowingJetBrainsInstaller=!1;isShowingIdePicker=!1;isShowingPalette=!1;threadsForPicker=[];isLoadingThreads=!1;threadPreviewController=new Py1;previewThread=null;planScrollController=(()=>{let J=new r3;return J.followMode=!1,J})();todoScrollController=(()=>{let J=new r3;return J.followMode=!1,J})();showingSelectionCopiedHint=!1;isShowingStandaloneThreadPicker=!1;filterThreadPickerByWorkspace=!0;agentModePulseSeq=0;currentGitBranch=null;messageViewFocusNode=new a8({debugLabel:"MessageViewFocus"});autocompleteFocusNode=new a8({debugLabel:"AutocompleteFocus"});isTextfieldAndAutocompleteFocused=!1;submitDisabledHint=null;submitDisabledHintTimer=null;showingCannotToggleMessage=null;showImageUnsupportedHint=!1;imageUnsupportedHintTimer=null;adActionModal=null;threadFeedReader=null;currentThreadFeedEntry=null;threadFeedEntries=[];threadFeedSubscription=null;threadFeedRotationTimer=null;currentUserInfo=null;bottomGridUserHeight=void 0;bottomGridDragStartY=null;bottomGridDragStartHeight=null;pendingMCPServers=[];mcpTrustSubscription=null;agentModeSubscription=null;currentAgentMode="smart";hasToggledAgentMode=!1;inMemoryAgentModeOverride=null;cachedVisibleModes=yZ();freeTierStatus=void 0;tryOpus=!1;updateState="hidden";updateServiceSubscription=null;isMessageViewInSelectionMode=!1;threadBackStack=[];threadForwardStack=[];replayDisplayedMessages=[];replayAbortController=new AbortController;replayTypingTimer=null;async initThreadFeed(){let Q=(await N6(this.widget.dependencies.configService.config)).settings.url,Y=Q.includes("localhost")||Q.includes("127.0.0.1");try{let q=await this.widget.dependencies.internalAPIClient.getUserInfo({},{config:this.widget.dependencies.configService});if(q.ok){let V=q.result,K="user"in V?V.user:V;this.currentUserInfo={username:K.username??void 0,displayName:K.displayName??void 0};let W="ffe10a0c-6c42-41ce-a3a6-38990fd6caf8";if(!Y&&V.team?.id!==W)return}else return}catch(q){x.debug("Failed to fetch user info for thread feed filtering",q);return}let X="/threads.rss",G=async(q,V)=>{let K=q instanceof Request?q.url:q.toString();return gQ(K,V,this.widget.dependencies.configService)},Z=t16();Z.get("entries").then((q)=>{if(q){let V=this.filterEntries(q);if(this.threadFeedEntries=V,V.length>0&&!this.currentThreadFeedEntry)this.setState(()=>{this.currentThreadFeedEntry=this.getRandomEntry(V)})}}),this.threadFeedReader=new lj1(Z,G,{url:X}),this.threadFeedSubscription=this.threadFeedReader.stream().subscribe({next:(q)=>{try{let V=this.filterEntries(q);if(V.length>0)this.threadFeedEntries=[...V,...this.threadFeedEntries],this.setState(()=>{this.currentThreadFeedEntry=V[0]}),this.resetThreadFeedRotation()}catch(V){x.error("Thread feed: error in next handler",V)}},error:(q)=>{x.error("Thread feed error:",q)}}),this.resetThreadFeedRotation()}filterEntries(J){if(!this.currentUserInfo)return J;let{username:Q,displayName:Y}=this.currentUserInfo;return J.filter((X)=>{return!X.authors.some((G)=>{let Z=G.name;if(!Z)return!1;return Q&&Z===Q||Y&&Z===Y||Q&&Z.includes(Q)})})}rotateThreadFeed(){if(this.threadFeedRotationTimer)clearInterval(this.threadFeedRotationTimer);this.threadFeedRotationTimer=setInterval(()=>{if(this.threadFeedEntries.length>0)this.setState(()=>{this.currentThreadFeedEntry=this.getRandomEntry(this.threadFeedEntries)})},30000)}resetThreadFeedRotation(){this.rotateThreadFeed()}getRandomEntry(J){let Y=[...J].sort((X,G)=>G.pubDate.getTime()-X.pubDate.getTime()).slice(0,5);return Y[Math.floor(Math.random()*Y.length)]}recordNavigation(J){this.threadBackStack.push(J),this.threadForwardStack=[]}navigateBack=async()=>{if(this.threadBackStack.length===0)return;let J=this.widget.dependencies.worker.thread.id,Q=this.threadBackStack.pop();this.threadForwardStack.push(J),await this.switchToExistingThread(Q,{recordInNavigationHistory:!1})};navigateForward=async()=>{if(this.threadForwardStack.length===0)return;let J=this.widget.dependencies.worker.thread.id,Q=this.threadForwardStack.pop();this.threadBackStack.push(J),await this.switchToExistingThread(Q,{recordInNavigationHistory:!1})};startAndSwitchToNewThread=async()=>{let J=this.widget.dependencies.worker.thread.id;this.recordNavigation(J);let Q=await this.widget.dependencies.startNewThread();return this.widget.dependencies.worker=Q,this.widget.dependencies.threadID=Q.thread.id,this.widget.dependencies.switchWorker(Q),this.setState(()=>{this.isMessageViewInSelectionMode=!1}),Q};async startReplay(){let J=this.widget.dependencies.replayMode;if(!J)return;let{thread:Q,typingEnabled:Y,baseWpm:X}=J,G=Q.messages;for(let Z=0;Z<G.length;Z++){if(this.replayAbortController.signal.aborted)break;let q=G[Z];if(!q)continue;if(Z>0)await this.replaySleep(J.messageDelayMs);if(q.role==="user"&&Y){let W=q.content.filter((H)=>H.type==="text").map((H)=>H.text).join(`
5113
5113
  `);if(W)await this.replayTypeMessage(W,X)}if(q.role==="assistant"){let W=q.content.some((U)=>U.type==="tool_use"),H=G[Z+1],z=H?.role==="user"&&H.content.some((U)=>U.type==="tool_result");if(W&&z){let U={...q,state:{type:"streaming"}};this.setState(()=>{this.replayDisplayedMessages=[...this.replayDisplayedMessages,U],this.textController.clear()});let N=J.thread.id;this.getMessageScrollController(N).scrollToBottom(),await this.replaySleep(J.toolProgressDelayMs),this.setState(()=>{this.replayDisplayedMessages=[...this.replayDisplayedMessages.slice(0,-1),q]});continue}}this.setState(()=>{this.replayDisplayedMessages=[...this.replayDisplayedMessages,q],this.textController.clear()});let V=J.thread.id;this.getMessageScrollController(V).scrollToBottom()}await this.replaySleep(J.exitDelayMs),T9.instance.stop()}async replayTypeMessage(J,Q){this.textController.clear();let Y=J.split(/(?<=\s)/),X=60000/Q;for(let G of Y){if(this.replayAbortController.signal.aborted)break;let Z=X/G.length;for(let q of G){this.textController.text=this.textController.text+q,this.textController.cursorPosition=this.textController.text.length,this.setState(()=>{});let V=0.8+Math.random()*0.4,K=Z*V;await this.replaySleep(K)}}}replaySleep(J){return new Promise((Q)=>{this.replayTypingTimer=setTimeout(Q,J)})}getEffectiveAgentMode(){return j81(this.widget.dependencies.worker.thread,this.inMemoryAgentModeOverride?{agentMode:this.inMemoryAgentModeOverride}:null,this.freeTierStatus,{"experimental.agentMode":this.currentAgentMode})}isProcessing(){let{threadState:J}=this.widget.dependencies;if(!J.mainThread)return!1;if(J.viewState.state!=="active")return!1;if(Boolean(J.viewState.inferenceState==="running"))return!0;let Y=J.items.filter((Z)=>Z.type==="toolResult").filter((Z)=>Z.toolResult.run.status==="in-progress"||Z.toolResult.run.status==="queued"),X=J.subagentActiveTools.filter((Z)=>Z.toolRun.status==="in-progress"||Z.toolRun.status==="queued");return[...Y,...X].length>0}showSubmitDisabledHint(J){if(this.submitDisabledHintTimer)clearTimeout(this.submitDisabledHintTimer);this.setState(()=>{this.submitDisabledHint=J}),this.submitDisabledHintTimer=setTimeout(()=>{this.setState(()=>{this.submitDisabledHint=null}),this.submitDisabledHintTimer=null},3000)}getUIHint(){let J=this.themeColors?.colorScheme;if(!J)return null;let Q=this.themeApp;if(!Q)return null;if(this.submitDisabledHint)return new Q1(this.submitDisabledHint,new F1({color:J.foreground,dim:!0}));if(this.isExiting)return new Q1("Exiting...",new F1({color:J.foreground,dim:!0}));if(this.isConfirmingExit)return new Q1("",void 0,[new Q1("Ctrl+C",new F1({color:Q.keybind})),new Q1(" again to exit",new F1({color:J.foreground,dim:!0}))]);if(this.isConfirmingClearInput)return new Q1("",void 0,[new Q1("Esc",new F1({color:Q.keybind})),new Q1(" again to clear input",new F1({color:J.foreground,dim:!0}))]);if(this.isShowingHelp)return new Q1("",void 0,[new Q1("Escape",new F1({color:Q.keybind})),new Q1(" to close help",new F1({color:J.foreground,dim:!0}))]);if(this.showImageUnsupportedHint){let G=this.getEffectiveAgentMode(),Z=jy1(G,this.tryOpus);return new Q1("",void 0,[new Q1("Images aren't supported in ",new F1({color:J.warning,dim:!1})),new Q1(G,new F1({color:Z})),new Q1(" mode.",new F1({color:J.warning,dim:!1}))])}if(this.isProcessing()||this.bashInvocations.length>0){if(this.isConfirmingCancelProcessing)return new Q1("",void 0,[new Q1("Esc",new F1({color:Q.keybind})),new Q1(" again to cancel",new F1({color:J.foreground,dim:!0}))]);return new Q1("",void 0,[new Q1("Esc",new F1({color:Q.keybind})),new Q1(" to cancel",new F1({color:J.foreground,dim:!0}))])}if(this.showingSelectionCopiedHint)return new Q1("Selection copied to clipboard",new F1({color:J.foreground,dim:!0}));if(this.showingCannotToggleMessage)return new Q1(this.showingCannotToggleMessage,new F1({color:J.warning,dim:!1}));let Y=zZ6(this.updateState,J);if(Y)return new Q1("",void 0,Y);let X=this.widget.dependencies.worker.thread;if(X.agentMode==="plan"&&FA(X))return new Q1("",void 0,[new Q1("Ctrl+O",new F1({color:Q.keybind})),new Q1(" → Execute Plan",new F1({color:J.foreground,dim:!0}))]);return null}isTranscriptEmpty(){let{threadState:J}=this.widget.dependencies;return J.items.length===0}handleMessageRestoreSubmit=async(J)=>{let{threadState:Q,worker:Y}=this.widget.dependencies;if(!Q.mainThread?.id)return;let G=Q.mainThread?.messages.findIndex((Z)=>Z===J);if(G===void 0||G===-1)return;try{this.cancelBashInvocations(),await Y.cancel(),await Y.handle({type:"thread:truncate",fromIndex:G}),this.scrollMessageViewToBottom(),this.setState(()=>{this.imageAttachments=[]})}catch(Z){x.error("Failed to edit message:",Z)}};forkMessage=async(J)=>{let{threadState:Q,workerDeps:Y,threadSyncService:X}=this.widget.dependencies,G=Q.mainThread?.id;if(!G)return;let Z=Q.mainThread?.messages.findIndex((q)=>q===J);if(Z===void 0||Z<=0)return;try{let q=await A3.getOrCreateForThread(Y,G),V=await rR(q,X,Z-1);await this.switchToExistingThread(V)}catch(q){x.error("Failed to fork thread:",q),this.showErrorMessage(`Failed to fork thread: ${q}`)}};handleMessageEditSubmit=async(J,Q)=>{let{threadState:Y,worker:X}=this.widget.dependencies,G=Y.mainThread;if(!G)return;let Z=G.messages.findIndex((q)=>q.messageId!==void 0&&q.messageId===J.messageId);if(Z===-1)return;try{this.cancelBashInvocations(),await X.cancel(),this.widget.dependencies.history.add(Q);let q=DN(Q);if(q)await X.handle({type:"thread:truncate",fromIndex:Z}),this.invokeBashCommand(q.cmd,{visibility:q.visibility});else{let V=[{type:"text",text:Q}];if(this.imageAttachments.length>0)V.push(...this.imageAttachments);let K={content:V,agentMode:G.agentMode},W=Z===0;if(G.agentMode&&!W&&K.agentMode!==G.agentMode){x.error(`Cannot edit message: This thread uses ${G.agentMode} mode. To change mode, create a new thread.`);return}await X.handle({type:"user:message",message:K,index:Z})}this.scrollMessageViewToBottom(),this.setState(()=>{this.imageAttachments=[]})}catch(q){x.error("Failed to edit message:",q)}};getAffectedFiles=async(J)=>{let{worker:Q}=this.widget.dependencies;try{return(await Q.getFilesAffectedByTruncation(J)).map(VJ)}catch(Y){return x.error("Failed to get affected files:",Y),[]}};textController=new rZ;messageScrollControllers=new Map;getMessageScrollController(J){if(!this.messageScrollControllers.has(J))this.messageScrollControllers.set(J,new r3);return this.messageScrollControllers.get(J)}scrollMessageViewToBottom(){let{threadState:J}=this.widget.dependencies,Q=J.mainThread?.id;if(!Q)return;this.getMessageScrollController(Q).scrollToBottom()}findElementByKey(J){return this.searchElementTreeByKey(this.context.element,J)}searchElementTreeByKey(J,Q){if(!J)return null;if(J?.widget?.key?.value===Q)return J;if(J?.child){let X=this.searchElementTreeByKey(J.child,Q);if(X)return X}if(J?.children)for(let X of J.children){let G=this.searchElementTreeByKey(X,Q);if(G)return G}return null}setupSelectionListener(){let J=this.findElementByKey("message-view-selection-area");if(J?.state){let Q=J.state;if(Q?.controller&&!this.selectionListener)this.selectionListener=()=>{this.setState(()=>{})},Q.controller.addListener(this.selectionListener),Q.controller.onSelectionCopied=()=>{if(this.copyMessageTimer)clearTimeout(this.copyMessageTimer);this.setState(()=>{this.showingSelectionCopiedHint=!0}),this.copyMessageTimer=setTimeout(()=>{this.setState(()=>{this.showingSelectionCopiedHint=!1}),this.copyMessageTimer=null},2000)}}}updateTerminalTitle(){let{threadState:J}=this.widget.dependencies,Q=J.mainThread?.title;if(Q!==this.currentTitle){this.currentTitle=Q;let Y=process.cwd().replace(process.env.HOME||"","~"),X=Q?`amp - ${Q} - ${Y}`:"";process.stdout.write(Zj1(X))}}_handleTextCopy(J){if(J&&J.length>0){if(this.setState(()=>{this.showingSelectionCopiedHint=!0}),this.copyMessageTimer)clearTimeout(this.copyMessageTimer);this.copyMessageTimer=setTimeout(()=>{this.setState(()=>{this.showingSelectionCopiedHint=!1}),this.copyMessageTimer=null},2000)}}textFieldKey=new e7("text-field");ideStatusSubscription=null;ideMessageSubscription=null;ideAppendToPromptSubscription=null;connectedClientsStatusSubscription=null;paletteCommands=null;completionBuilder=null;textChangeListener=()=>{let J=this.textController.text;if(J==="/"){this.showCommandPalette(),this.textController.clear();return}let Y=DN(J)?.visibility;if(Y!==this.currentShellModeStatus)this.currentShellModeStatus=Y,this.setState(()=>{})};navigateHistoryPrevious=()=>{let J=this.widget.dependencies.history.previous();if(J!==null){if(this.historyIndex===-1)this.historyDraft=this.textController.text;this.historyIndex++,this.textController.text=J,this.textController.moveCursorToStart()}};navigateHistoryNext=()=>{let J=this.widget.dependencies.history.next();if(J!==null)this.historyIndex--,this.textController.text=J,this.textController.moveCursorToEnd();else if(this.historyIndex>-1)this.historyIndex=-1,this.textController.text=this.historyDraft||"",this.textController.moveCursorToEnd(),this.historyDraft=null};resetHistory=()=>{this.widget.dependencies.history.reset(),this.historyIndex=-1,this.historyDraft=null};openJetBrainsInstaller=()=>{this.setState(()=>{this.isShowingJetBrainsInstaller=!0})};dismissJetBrainsInstaller=()=>{this.setState(()=>{this.isShowingJetBrainsInstaller=!1})};openIdePicker=()=>{this.setState(()=>{this.isShowingIdePicker=!0})};dismissIdePicker=()=>{this.setState(()=>{this.isShowingIdePicker=!1}),P9.instance.addPostFrameCallback(()=>{this.autocompleteFocusNode.requestFocus()})};handleIdeSelection=async(J,Q)=>{if(this.widget.dependencies.ideClient.getSelectedConfig()?.pid===J.pid){this.dismissIdePicker();return}try{await this.connectToSelectedIde(J,Q)}catch(Y){let X=Y instanceof Error?Y.message:String(Y);this.setState(()=>{this.displayMessage=Error(`Failed to connect to IDE: ${X}`)})}this.widget.dependencies.ideClient.selectConfig(J),this.dismissIdePicker()};async connectToSelectedIde(J,Q){await this.widget.dependencies.ideClient.start(J,!0,Q)}previewControllerListener=(J)=>{this.setState(()=>{this.previewThread=J})};showStandaloneThreadPicker=()=>{this.loadThreadsForPicker(),this.setState(()=>{this.isShowingStandaloneThreadPicker=!0})};dismissStandaloneThreadPicker=()=>{this.exitApplication()};handleStandaloneThreadSelect=async(J)=>{try{await this.switchToExistingThread(J,{recordInNavigationHistory:!1}),this.threadPreviewController.clear(),this.setState(()=>{this.isShowingStandaloneThreadPicker=!1}),P9.instance.addPostFrameCallback(()=>{if(!this.isMessageViewInSelectionMode&&!this.isShowingPalette&&!this.isShowingStandaloneThreadPicker)this.autocompleteFocusNode.requestFocus()})}catch(Q){x.error("Failed to switch thread:",Q),this.showErrorMessage(`Failed to switch thread: ${Q}`)}};toggleThreadPickerWorkspaceFilter=()=>{this.setState(()=>{this.filterThreadPickerByWorkspace=!this.filterThreadPickerByWorkspace})};showCommandPalette(){if(this.setState(()=>{this.isShowingPalette=!this.isShowingPalette}),this.isShowingPalette)this.loadThreadsForPicker()}getPaletteCommands(){if(!this.paletteCommands)this.paletteCommands=new ak1(this.widget.dependencies.configService,this.widget.dependencies.commandRegistry,(J)=>{this.setState(()=>{this.executingCommand=J})},()=>{this.setState(()=>{this.executingCommand=null})},this.widget.dependencies.isDogfooding);return this.paletteCommands}getCompletionBuilder(){if(!this.completionBuilder)this.completionBuilder=new sk1(this.widget.dependencies.fuzzyServer,this.widget.dependencies.threadFuzzyIndexer);return this.completionBuilder}dismissPalette=()=>{this.setState(()=>{this.isShowingPalette=!1})};getCommandPaletteContext=()=>{let{threadState:J,recentThreadIDs:Q}=this.widget.dependencies;if(!J.mainThread)return null;let Y=a0.file(process.cwd()),X=M6(Y);return{recentThreadIDs:Q,currentThreadID:J.mainThread.id,worker:this.widget.dependencies.worker,editorState:this.textController,isProcessing:this.isProcessing(),thread:J.mainThread,ampURL:this.widget.dependencies.ampURL,threadSyncService:this.widget.dependencies.threadSyncService,configService:this.widget.dependencies.configService,openInEditor:this.openInEditor,takeImageAttachments:()=>{let G=this.imageAttachments;return this.setState(()=>{this.imageAttachments=[]}),G},setImageAttachments:(G)=>{this.setState(()=>{this.imageAttachments=G})},editorDispatch:(G)=>{switch(G.type){case"set-input":this.textController.clear(),this.textController.insertText(G.input);break;case"insert-text":this.textController.insertText(G.text);break;case"clear":this.textController.clear();break}},submitMessage:(G)=>{return this.proceedWithUserMessage(G)},exitApp:this.exitApplication,openHelp:()=>{this.setState(()=>{this.isShowingHelp=!0})},settingsStorage:this.widget.dependencies.settingsStorage,clientId:this.widget.dependencies.clientId,connectedClientsService:this.widget.dependencies.connectedClientsService,mcpService:this.widget.dependencies.mcpService,startNewThread:async()=>{await this.startAndSwitchToNewThread()},navigateBack:this.navigateBack,navigateForward:this.navigateForward,canNavigateBack:this.threadBackStack.length>0,canNavigateForward:this.threadForwardStack.length>0,canUseAmpFree:this.widget.dependencies.freeTierStatus?.canUseAmpFree??!1,switchToThread:async(G)=>{return await this.switchToExistingThread(G),this.setState(()=>{this.isMessageViewInSelectionMode=!1}),this.widget.dependencies.worker},generateHandoffPrompt:async(G,Z,q)=>{let V=this.widget.dependencies.threadState.mainThread?.id;if(!V)throw Error("No active thread");let K=setTimeout(()=>{q.throwIfAborted()},60000);try{let W=await this.widget.dependencies.threadService.generateHandoffPrompt(V,G,Z,this.widget.dependencies.configService,q);return clearTimeout(K),W}catch(W){throw clearTimeout(K),W}},handleHandoff:async(G,Z)=>{let{goal:q,generatedPrompt:V,images:K}=Z;if(!q&&!V)return{ok:!1,error:Error("Either goal or generatedPrompt required")};try{let W=this.widget.dependencies.threadState.mainThread?.id;if(!W)return{ok:!1,error:Error("No active thread")};let H=setTimeout(()=>G.abort(new o91("Handoff took too long and was aborted (timeout: 60s)")),60000);try{let z=await this.widget.dependencies.threadService.createHandoffThread(W,{goal:q,generatedPrompt:V,images:K},this.widget.dependencies.configService,G.signal);return clearTimeout(H),await this.switchToExistingThread(z),{ok:!0}}catch(z){if(clearTimeout(H),z instanceof Error&&(z.name==="AbortError"||z.message.includes("aborted")))throw G.signal.reason;throw z}}catch(W){return x.error("Failed to create handoff thread",W),{ok:!1,error:W instanceof Error?W:Error(String(W))}}},getGuidanceFiles:async(G)=>{if(!J.mainThread)return[];return(await hr({filesystem:this.widget.dependencies.worker.fs.fileSystemReader(),configService:this.widget.dependencies.configService,threadService:this.widget.dependencies.threadService},J.mainThread,G)).map((q)=>({uri:q.uri,type:q.type}))},openIdePicker:()=>{this.openIdePicker()},getInMemoryAgentModeOverride:()=>{return this.inMemoryAgentModeOverride},setInMemoryAgentModeOverride:(G)=>{this.setState(()=>{this.inMemoryAgentModeOverride=G,this.hasToggledAgentMode=!0})},toggleAgentMode:this.toggleAgentMode,getEffectiveAgentMode:()=>this.getEffectiveAgentMode(),getEditorText:()=>this.textController.text,workspace:this.widget.dependencies.workspace??null,handleExecutePlan:async()=>{try{let G=J.mainThread?.id;if(!G){this.setState(()=>{this.displayMessage=Error("No active thread")});return}let Z=await this.widget.dependencies.threadService.createPlanExecutionThread(G,"smart");await this.switchToExistingThread(Z)}catch(G){x.error("Failed to execute plan",G),this.setState(()=>{this.displayMessage=Error(`Failed to execute plan: ${G instanceof Error?G.message:String(G)}`)})}},planFileManager:this.widget.dependencies.planFileManager,completionBuilder:this.getCompletionBuilder(),threads:this.threadsForPicker,previewController:this.threadPreviewController,isLoadingThreads:this.isLoadingThreads,filterByWorkspace:this.filterThreadPickerByWorkspace,currentWorkspace:X,threadViewStates:this.widget.dependencies.workerController.threadViewStates,currentThreadFeedEntry:this.currentThreadFeedEntry}};loadThreadsForPicker(){if(this.threadLoadSubscription)return;this.setState(()=>{this.isLoadingThreads=!0});let J=new Iy1(this.widget.dependencies.threadHistoryService);this.threadLoadSubscription=J.observeThreadSummaries("").subscribe({next:(Q)=>{this.setState(()=>{this.threadsForPicker=Q,this.isLoadingThreads=!1})},error:()=>{this.setState(()=>{this.isLoadingThreads=!1})}})}updateGitBranch=async()=>{let J=await VO8(process.cwd());this.setState(()=>{this.currentGitBranch=J})};removeBashInvocation=(J)=>{this.setState(()=>{this.bashInvocations=this.bashInvocations.filter((Q)=>Q.id!==J)})};invokeBashCommand=(J,{visibility:Q})=>{let Y=Date.now(),X=`bash-${Y}-${Math.random().toString(36).substring(7)}`,G={cmd:J},Z=new AbortController;this.widget.dependencies.worker.invokeBashTool(G,Z.signal,Q===NN).subscribe({next:(q)=>{this.setState(()=>{if(this.bashInvocations.find((K)=>K.id===X))this.bashInvocations=this.bashInvocations.map((K)=>K.id===X?{...K,toolRun:q}:K);else{let K={id:X,args:G,toolRun:q,startTime:Y,abortController:Z,hidden:Q===NN};this.bashInvocations=[...this.bashInvocations,K]}})},error:()=>this.removeBashInvocation(X),complete:()=>this.removeBashInvocation(X)})};cancelBashInvocations=()=>{let J=this.bashInvocations.find((Q)=>Q.toolRun.status==="in-progress");if(J)J.abortController.abort()};toggleConnectedClientsStatus=()=>{this.setState(()=>{this.connectedClientsStatusExpanded=!this.connectedClientsStatusExpanded})};toggleAgentMode=()=>{let J=this.widget.dependencies.getCurrentWorker()||this.widget.dependencies.worker;if(d$(J.thread)>0)return;if(this.freeTierStatus?.canUseAmpFree){let X=this.getEffectiveAgentMode(),G=Xg(X,this.cachedVisibleModes);if(G!==X)this.setState(()=>{this.hasToggledAgentMode=!0,this.inMemoryAgentModeOverride=G,this.agentModePulseSeq++,this.showingCannotToggleMessage=null,this.showImageUnsupportedHint=!1});return}let Q=this.getEffectiveAgentMode(),Y=Xg(Q,this.cachedVisibleModes);if(Y===Q)return;if(this.setState(()=>{this.hasToggledAgentMode=!0,this.inMemoryAgentModeOverride=Y,this.agentModePulseSeq++,this.showingCannotToggleMessage=null,this.showImageUnsupportedHint=!1}),M5(Y))this.checkAndShowFreeModeModal()};checkAndShowFreeModeModal=()=>{if(this.freeTierStatus?.canUseAmpFree)return;if(this.freeTierStatus){if(!this.freeTierStatus.eligible){this.setState(()=>{this.showingCannotToggleMessage="Amp Free is unavailable. Switch to another mode."}),setTimeout(()=>{this.setState(()=>{this.showingCannotToggleMessage=null})},3000);return}else if(!this.freeTierStatus.workspaceAllowsAmpFree){this.setState(()=>{this.showingCannotToggleMessage="Your workspace does not allow Amp Free. Switch to another mode."}),setTimeout(()=>{this.setState(()=>{this.showingCannotToggleMessage=null})},3000);return}}};isInRestrictedFreeMode(){if(this.getEffectiveAgentMode()!=="free")return!1;if(this.freeTierStatus?.canUseAmpFree)return!1;return!0}handleInsertImage=(J)=>{let Q=this.getEffectiveAgentMode();if(!jb(Q)){if(this.imageUnsupportedHintTimer)clearTimeout(this.imageUnsupportedHintTimer);return this.setState(()=>{this.showImageUnsupportedHint=!0}),this.imageUnsupportedHintTimer=setTimeout(()=>{this.setState(()=>{this.showImageUnsupportedHint=!1}),this.imageUnsupportedHintTimer=null},5000),!1}if(this.imageAttachments.length>=WU)return!1;let Y=gC(J);if(typeof Y==="object")return this.setState(()=>{this.imageAttachments=[...this.imageAttachments,Y]}),!1;return this.setState(()=>{this.displayMessage=Error(`Failed to attach image: ${Y}`)}),!1};handlePopImage=()=>{if(this.imageAttachments.length>0)this.setState(()=>{this.imageAttachments=this.imageAttachments.slice(0,-1)})};openInEditor=async(J)=>{let{mkdtemp:Q,readFile:Y,unlink:X,rmdir:G,writeFile:Z}=await import("node:fs/promises"),{tmpdir:q}=await import("node:os"),V=await import("node:path");try{let K=await Q(V.join(q(),"amp-edit-")),W=V.join(K,"message.amp.md");await Z(W,J,"utf-8"),await Pz(W);try{let H=await Y(W,"utf-8");this.textController.text=H}catch(H){if(H?.code!=="ENOENT")x.error("Failed to read temporary file",H)}try{await X(W),await G(K)}catch(H){x.warn("Failed to clean up temporary file",H)}}catch(K){x.error("Error opening editor:",K)}};onTextSubmitted=async(J)=>{if(!J.trim())return;let Q=DN(J);if(Q)if(!Q.cmd){this.showSubmitDisabledHint("No command provided");return}else if(this.isProcessing()){this.showSubmitDisabledHint("Unable to use shell mode while agent is active");return}else{this.invokeBashCommand(Q.cmd,{visibility:Q.visibility}),this.widget.dependencies.history.add(J),this.textController.clear(),this.resetHistory();return}this.textController.clear(),this.resetHistory(),await this.updateGitBranch(),await this.sendUserMessage(J)};initState(){if(KG.getInstance().interceptConsole(),this.threadPreviewController.setThreadService(this.widget.dependencies.threadService),this.threadPreviewController.addListener(this.previewControllerListener),this.widget.dependencies.openThreadSwitcher)this.showStandaloneThreadPicker();T9.instance.on("key",()=>{this.lastUserInteractionTime=Date.now()}),T9.instance.on("mouse",()=>{this.lastUserInteractionTime=Date.now()}),T9.instance.on("paste",()=>{this.lastUserInteractionTime=Date.now()}),this.autocompleteFocusNode.addListener((Y)=>{P9.instance.addPostFrameCallback(()=>{this.setState(()=>{this.isTextfieldAndAutocompleteFocused=Y.hasFocus})})}),this.freeTierStatus=this.widget.dependencies.freeTierStatus,N6(this.widget.dependencies.configService.config).then((Y)=>{let X=j81(this.widget.dependencies.worker.thread,this.widget.dependencies.sessionState??null,this.freeTierStatus,Y.settings);if(x.info(`[initState] Resolved agentMode: ${X}`),this.widget.dependencies.sessionState?.agentMode)this.setState(()=>{this.inMemoryAgentModeOverride=X})}),this.updateGitBranch(),this.adSubscription=Pj1(this.widget.dependencies.internalAPIClient,this.widget.dependencies.configService,()=>{return(this.inMemoryAgentModeOverride&&M5(this.inMemoryAgentModeOverride)||this.randomAd===null)&&Ij1(this.lastUserInteractionTime)}).subscribe({next:(Y)=>{if(Y){let X=$O8(16).toString("hex");this.lastAdImpressionId=X,Promise.resolve().then(() => (N51(),B51)).then(({recordAdEvent:G})=>{let Z=this.widget.dependencies.worker.thread,q=Z.messages[Z.messages.length-1];G("viewed",{adId:Y.id,advertiserId:Y.advertiserId,threadId:Z.id,messageId:q?.messageId,impressionId:X,placement:"tui",matchType:Y.metadata?.matchType,matchedPatterns:Y.metadata?.matchedPatterns,candidateAdPoolCount:Y.metadata?.candidateAdPoolCount,clientRegion:Y.metadata?.clientRegion})})}this.setState(()=>{this.randomAd=Y}),P9.instance.addPostFrameCallback(()=>{if(!this.isMessageViewInSelectionMode&&!this.isShowingPalette&&!this.isShowingStandaloneThreadPicker&&!this.isShowingIdePicker)this.autocompleteFocusNode.requestFocus()})}});let{mcpTrustHandler:J}=this.widget.dependencies;this.mcpTrustSubscription=J.pendingServers$.subscribe((Y)=>{this.setState(()=>{this.pendingMCPServers=Y})}),this.ideStatusSubscription=this.widget.dependencies.ideClient.status.subscribe((Y)=>{this.setState(()=>{this.ideStatus=Y})}),this.ideMessageSubscription=this.widget.dependencies.ideClient.messages.subscribe(async(Y)=>{let X=this.widget.dependencies.getCurrentWorker();if(!X){x.warn("No active thread worker found to handle IDE message");return}await new Promise((G)=>setTimeout(G,50)),await X.handle({type:"user:message",message:{content:[{type:"text",text:Y}]}}),x.debug("Message sent from IDE to agent",{message:Y.slice(0,100)})}),this.ideAppendToPromptSubscription=this.widget.dependencies.ideClient.appendToPrompt.subscribe((Y)=>{this.textController.insertText(Y),x.debug("Appended text to CLI prompt from IDE",{text:Y.slice(0,100)})}),this.connectedClientsStatusSubscription=this.widget.dependencies.connectedClientsService.status.subscribe((Y)=>{this.setState(()=>{this.connectedClientsStatus=Y})}),this.updateServiceSubscription=this.widget.dependencies.updateService.state.subscribe((Y)=>{this.setState(()=>{this.updateState=Y})}),this.agentModeSubscription=this.widget.dependencies.configService.config.subscribe((Y)=>{let X=yZ(Y.settings,this.freeTierStatus?.canUseAmpFree);this.setState(()=>{this.cachedVisibleModes=X,this.tryOpus=Y.settings.tryOpus??!1})}),this.textController.addListener(this.textChangeListener),this.updateTerminalTitle();let Q=this.widget.dependencies.ideClient.getSelectedConfig();if(Q)this.connectToSelectedIde(Q,"auto-startup").catch((Y)=>{let X=Y instanceof Error?Y.message:String(Y);this.setState(()=>{this.displayMessage=Error(`Failed to connect to IDE: ${X}`)})});else if(this.widget.dependencies.showIdePicker)this.openIdePicker();else if(this.widget.dependencies.showJetBrainsInstaller)this.openJetBrainsInstaller();if(this.widget.dependencies.replayMode)setTimeout(()=>this.startReplay(),100);this.initThreadFeed()}didUpdateWidget(J){super.didUpdateWidget(J),this.setupSelectionListener()}dispose(){if(this.replayAbortController.abort(),this.replayTypingTimer)clearTimeout(this.replayTypingTimer);if(this.ideStatusSubscription)this.ideStatusSubscription.unsubscribe();if(this.ideMessageSubscription)this.ideMessageSubscription.unsubscribe();if(this.ideAppendToPromptSubscription)this.ideAppendToPromptSubscription.unsubscribe();if(this.connectedClientsStatusSubscription)this.connectedClientsStatusSubscription.unsubscribe();if(this.updateServiceSubscription)this.updateServiceSubscription.unsubscribe();if(this.agentModeSubscription)this.agentModeSubscription.unsubscribe();if(this.adSubscription)this.adSubscription.unsubscribe();if(this.mcpTrustSubscription)this.mcpTrustSubscription.unsubscribe();if(this.threadLoadSubscription)this.threadLoadSubscription.unsubscribe();if(this.threadFeedSubscription)this.threadFeedSubscription.unsubscribe();if(this.threadFeedRotationTimer)clearInterval(this.threadFeedRotationTimer);if(this.threadPreviewController.removeListener(this.previewControllerListener),this.threadPreviewController.dispose(),this.exitConfirmTimeout)clearTimeout(this.exitConfirmTimeout),this.exitConfirmTimeout=null;if(this.clearInputConfirmTimeout)clearTimeout(this.clearInputConfirmTimeout),this.clearInputConfirmTimeout=null;this.textController.removeListener(this.textChangeListener);for(let J of this.messageScrollControllers.values())J.dispose();if(this.messageScrollControllers.clear(),process.stdout.write(Zj1("")),this.shouldUseProgressBar())process.stdout.write(M26())}getCurrentConfirmation(){let{threadState:J}=this.widget.dependencies,X=[...J.items.filter((V)=>V.type==="toolResult").map((V)=>({toolUse:V.toolUse,toolRun:V.toolResult.run,subthreadID:void 0})),...J.subagentActiveTools].filter((V)=>V.toolRun.status==="blocked-on-user");if(X.length===0)return null;let G=X[0],Z=G.toolRun.status==="blocked-on-user"?G.toolRun.toAllow??[]:[],q=G.toolRun.status==="blocked-on-user"?G.toolRun.reason:void 0;return{type:"tool-use",tools:[{useBlock:G.toolUse,toAllow:Z}],subthreadID:G.subthreadID,reason:q}}shouldUseProgressBar(){return!1}updateProgressBar(){}onConfirmationResponse=async(J)=>{let Q=this.getCurrentConfirmation();if(!Q||Q.type!=="tool-use"){x.error("No current tool confirmation found");return}let Y=Q.tools[0]?.useBlock;if(!Y){x.error("No tool use block found in confirmation");return}if(J==="allow-all-session")sG("dangerouslyAllowAll",!0);if(J==="allow-all-persistent")try{await this.widget.dependencies.settingsStorage.set("dangerouslyAllowAll",!0,"global")}catch(G){if(G&&G instanceof Error)this.setState(()=>{this.displayMessage=G});else x.error("Failed to write dangerouslyAllowAll setting:",G);return}if(J==="always-guarded"){let G=Q.tools[0]?.toAllow??[],Z=await this.widget.dependencies.settingsStorage.get("guardedFiles.allowlist")||[],q=[...G,...Z];await this.widget.dependencies.settingsStorage.set("guardedFiles.allowlist",q,"global")}if(J==="connect-github"){let G=new URL("/settings#code-host-connections",this.widget.dependencies.ampURL).toString();try{await WJ(G)}catch(Z){x.error("Failed to open settings page:",Z),await this.showErrorMessage(`Cannot open browser. Please go to ${G} to connect to GitHub`)}return}if(J==="disable-librarian"){let G=await this.widget.dependencies.settingsStorage.get("tools.disable")??[];if(!G.includes(RX))await this.widget.dependencies.settingsStorage.set("tools.disable",[...G,RX],"global")}let X=J!==null&&["yes","allow-all-session","allow-all-persistent","always-guarded"].includes(J);try{let G={type:"user:tool-input",toolUse:Y.id,value:{accepted:X}};if(Q.subthreadID)await(await A3.getOrCreateForThread(this.widget.dependencies.workerDeps,Q.subthreadID)).handle(G);else await this.widget.dependencies.worker.handle(G)}catch(G){x.error("Failed to send tool confirmation:",G)}};showConfirmationOverlay=(J)=>{this.setState(()=>{this.isShowingConfirmationOverlay=!0,this.confirmationOverlayContent=J})};getErrorKey(J){return`${J.constructor.name}:${J.message}`}getCurrentEphemeralError(){let{threadState:J}=this.widget.dependencies,Q=J.viewState;if(Q.state!=="active"||!Q.ephemeralError)return null;let Y=this.getErrorKey(Q.ephemeralError);if(this.dismissedEphemeralErrorKey===Y)return null;return Q.ephemeralError}handleEphemeralErrorResponse=async(J)=>{let Q=this.getCurrentEphemeralError(),Y=this.widget.dependencies.worker;switch(J){case"retry":this.dismissedEphemeralErrorKey=null,await Y.retry();break;case"dismiss":if(Q)this.dismissedEphemeralErrorKey=this.getErrorKey(Q);break;case"new-thread":{this.setState(()=>{this.dismissedEphemeralErrorKey=null}),await this.startAndSwitchToNewThread();break}case"new-smart-thread":{this.setState(()=>{this.inMemoryAgentModeOverride="smart",this.dismissedEphemeralErrorKey=null}),f41({agentMode:"smart"}),await this.startAndSwitchToNewThread();break}}this.setState(()=>{})};handleDisplayMessageDismiss=()=>{this.setState(()=>{this.displayMessage=null})};handleMCPTrustOpenSettings=async()=>{let{mcpTrustHandler:J,settingsStorage:Q}=this.widget.dependencies;await J.deny();try{await Pz(Q.getSettingsFilePath())}catch(Y){let X=Y instanceof Error?Y.message:String(Y);await this.showErrorMessage(`Failed to open settings: ${X}`)}};cancelStreamingMessage=async()=>{await A3.cancel(this.widget.dependencies.threadID)};markLastUserMessageAsInterrupted=async()=>{let J=this.widget.dependencies.threadState.mainThread;if(!J)return;for(let Q=J.messages.length-1;Q>=0;Q--){let Y=J.messages[Q];if(Y?.role==="user"&&!Y.interrupted){await this.widget.dependencies.worker.handle({type:"user:message:interrupt",messageIndex:Q});break}}};switchToExistingThread=async(J,Q={})=>{let{recordInNavigationHistory:Y=!0}=Q;if(Y){let X=this.widget.dependencies.worker.thread.id;if(X!==J)this.recordNavigation(X)}try{x.info(`[switchToExistingThread] Switching to thread: ${J}`);let X=await this.widget.dependencies.switchToThread(J);x.info(`[switchToExistingThread] Got worker for thread ${J}, thread.agentMode: ${X.thread.agentMode}`);let G=await this.widget.dependencies.configService.getLatest(),Z=j81(X.thread,this.widget.dependencies.sessionState??null,this.freeTierStatus,G.settings);if(x.info(`[switchToExistingThread] Thread ${J} resolved agentMode: ${Z}`),this.widget.dependencies.worker=X,this.widget.dependencies.threadID=X.thread.id,this.widget.dependencies.switchWorker(X),this.setState(()=>{x.info("[switchToExistingThread] Clearing inMemoryAgentModeOverride"),this.inMemoryAgentModeOverride=null}),X.thread.draft)if(x.info("[switchToExistingThread] Loading draft content into text controller"),this.textController.clear(),typeof X.thread.draft==="string")this.textController.insertText(X.thread.draft);else{let q=X.thread.draft.filter((W)=>W.type==="text"),V=X.thread.draft.filter((W)=>W.type==="image"),K=q.map((W)=>W.text).join(`
5114
5114
  `);if(K)this.textController.insertText(K);if(V.length>0)this.setState(()=>{this.imageAttachments=V})}}catch(X){throw x.error("Failed to switch to thread:",J,X),Error(`Failed to switch to thread: ${J}`)}};sendUserMessage=async(J)=>{await this.proceedWithUserMessage(J)};proceedWithUserMessage=async(J)=>{this.cancelBashInvocations(),this.widget.dependencies.history.add(J);let Q=this.widget.dependencies.getCurrentWorker()||this.widget.dependencies.worker,Y=d$(Q.thread)===0,X=this.getEffectiveAgentMode();if(Q.thread.agentMode&&!Y&&X!==Q.thread.agentMode){await this.showErrorMessage(`This thread uses ${Q.thread.agentMode} mode. To change mode, edit the first message or create a new thread.`);return}let G=[{type:"text",text:J}];if(this.imageAttachments.length>0)G.push(...this.imageAttachments);if(await Q.handle({type:"user:message",message:{content:G,agentMode:X}}),Y)f41({agentMode:X});this.scrollMessageViewToBottom(),this.setState(()=>{this.imageAttachments=[]}),P9.instance.addPostFrameCallback(()=>{if(!this.isMessageViewInSelectionMode&&!this.isShowingPalette&&!this.isShowingStandaloneThreadPicker&&!this.isShowingIdePicker)this.autocompleteFocusNode.requestFocus()})};async showErrorMessage(J){this.setState(()=>{this.displayMessage=Error(J)})}exitApplication=async()=>{this.setState(()=>{this.isExiting=!0});let J=this.widget.dependencies.threadState.mainThread;if(J?.messages.length===0){if(J.relationships?.find((X)=>X.type==="handoff"&&X.role==="child"))await this.widget.dependencies.threadService.discardHandoffThread(J.id).catch(()=>{})}let Q=this.getEffectiveAgentMode();f41({agentMode:Q}).catch((Y)=>{x.warn("Failed to save session state on exit:",Y)}).finally(()=>{T9.instance.stop()})};onExitPressed=()=>{if(this.isConfirmingExit){if(this.exitConfirmTimeout)clearTimeout(this.exitConfirmTimeout),this.exitConfirmTimeout=null;this.exitApplication()}else{if(this.setState(()=>{this.isConfirmingExit=!0}),this.exitConfirmTimeout)clearTimeout(this.exitConfirmTimeout);this.exitConfirmTimeout=setTimeout(()=>{this.setState(()=>{this.isConfirmingExit=!1}),this.exitConfirmTimeout=null},1000)}};toHomeRelative(J){let Q=qO8();if(J===Q)return"~";if(J.startsWith(Q+Xu.sep))return"~"+J.slice(Q.length);return J}shorten(J){let Q=J.split(Xu.sep).filter(Boolean);if(Q.length<=5)return J;return[Q.slice(0,2).join(Xu.sep),"…",Q.slice(-2).join(Xu.sep)].join(Xu.sep)}build(J){let Q=B8.of(J),Y=b6.of(J),X=Y.base;this.themeColors=X;let{colors:G,app:Z}=Y;this.themeApp=Z;let q=this.widget.dependencies.getCurrentWorker()||this.widget.dependencies.worker,V=q.thread.agentMode&&M5(q.thread.agentMode),K=V&&this.randomAd!==null,W=!V&&this.currentThreadFeedEntry!==null,H=K||W,{threadState:z}=this.widget.dependencies;this.updateTerminalTitle(),this.updateProgressBar();let U=this.getCurrentConfirmation(),N=this.widget.dependencies.replayMode,M=Boolean(N),L=z.items,O=z.mainThread||void 0,E=z.subagentToolsByParentID,I=z.todosList;if(M){let c6={...N.thread,messages:this.replayDisplayedMessages};L=Yj(c6).items,O=c6,E={};let _4=AI({messages:this.replayDisplayedMessages});I=Array.isArray(_4)?_4:[]}let P=O?.id,R=O,S=M?this.replayDisplayedMessages.length===0:this.isTranscriptEmpty(),y=(c6)=>new i91({key:new e7(`preview-message-view-${c6.id}`),items:Yj(c6).items,controller:this.threadPreviewController.scrollController,autofocus:!1,thread:c6,focusNode:new a8({debugLabel:"PreviewFocus"})}),f=this.previewThread,m=f?f.messages.length>2000?new s0({mainAxisSize:"max",children:[new B4({child:new L0}),new i6({padding:f0.all(2),child:new H8({child:new l1({text:new Q1("Thread too long for preview",new F1({color:G.mutedForeground,dim:!0}))})})})]}):y(f):S?new a91({agentMode:this.getEffectiveAgentMode(),tryOpus:this.tryOpus}):new i91({key:P?new e7(`message-view-${P}`):void 0,items:L,subagentToolsByParentID:E,controller:P?this.getMessageScrollController(P):new r3,autofocus:!1,onCopy:M?void 0:this._handleTextCopy.bind(this),thread:R,onMessageEditSubmit:M?void 0:this.handleMessageEditSubmit,onMessageRestoreSubmit:M?void 0:this.handleMessageRestoreSubmit,onMessageForkSubmit:M?void 0:this.forkMessage,getAffectedFiles:M?void 0:this.getAffectedFiles,focusNode:this.messageViewFocusNode,onDismissFocus:()=>{if(this.setState(()=>{this.isMessageViewInSelectionMode=!1}),!this.isShowingIdePicker)this.autocompleteFocusNode.requestFocus()},isInSelectionMode:this.isMessageViewInSelectionMode}),p=Math.max(Math.floor(Q.size.height*0.4),12),b=this.getCurrentEphemeralError(),i=this.buildBottomWidget(b,U,G,Y,z,I,p,H,M),J1=Q.size.width<40,n=z.mainThread?QN0(z.mainThread):void 0,u=new V91({threadViewState:z.viewState,threadTokenUsage:n,threadID:P??null,thread:z.mainThread??void 0,onFileChangesClick:()=>{this.setState(()=>{this.isShowingFileChangesOverlay=!this.isShowingFileChangesOverlay})},onCostBreakdownClick:()=>{this.setState(()=>{this.isShowingCostBreakdownOverlay=!this.isShowingCostBreakdownOverlay})},onShowIdePicker:this.openIdePicker,ideStatus:this.ideStatus,connectedClientsStatus:this.connectedClientsStatus,isNarrow:J1,uiHint:this.getUIHint()??void 0,waitingForConfirmation:!!U,showingEphemeralError:Boolean(z.viewState.state==="active"&&z.viewState.ephemeralError),runningBashInvocations:this.bashInvocations.length>0,executingCommand:this.executingCommand?.name??null,executingCommandMessage:this.executingCommand?.statusMessage??null}),s=new q91({bashInvocations:this.bashInvocations}),V1=[],H1=this.getEffectiveAgentMode(),o=this.currentShellModeStatus,r=jy1(H1,this.tryOpus),l=!o?H1.length+1:0,U1=Q.capabilities.animationSupport,y1=U1==="disabled"?0:U1==="slow"?30:60,t=yK(H1)?.uiHints?.fasterAnimation?3:1,f1=y1>0&&this.agentModePulseSeq>0?new $7({children:[i,new o3({top:0,left:1,right:1,height:1,child:new Ly1({color:r,trigger:this.agentModePulseSeq,fps:y1,speed:t,leftOffset:l})})]}):i;V1.push(new B4({child:m}),s);let j1=new $7({children:[new s0({mainAxisSize:"min",children:[K?new gk1({ad:this.randomAd,onButtonClick:async()=>{let c6=this.randomAd;if(this.lastAdImpressionId)Promise.resolve().then(() => (N51(),B51)).then(({recordAdEvent:_4})=>{let i4=this.widget.dependencies.worker.thread,u4=i4.messages[i4.messages.length-1];_4("clicked",{adId:c6.id,advertiserId:c6.advertiserId,threadId:i4.id,messageId:u4?.messageId,impressionId:this.lastAdImpressionId,placement:"tui",actionType:"link_to",matchType:c6.metadata?.matchType,matchedPatterns:c6.metadata?.matchedPatterns,candidateAdPoolCount:c6.metadata?.candidateAdPoolCount,clientRegion:c6.metadata?.clientRegion})});try{await WJ(c6.shortDestinationUrl)}catch(_4){let u4=T9.instance.tuiInstance.clipboard.isOsc52Supported();this.setState(()=>{this.adActionModal={showCopyOption:u4,url:c6.shortDestinationUrl}})}}}):W?new Ey1({entry:this.currentThreadFeedEntry}):new L0({height:0}),new X6({constraints:new s6(0,Q.size.width,0,p),child:f1})]}),H?new o3({top:0,left:0,right:0,child:new OZ6({userHeight:this.bottomGridUserHeight,maxHeight:p,onInitializeHeight:(c6)=>{this.setState(()=>{this.bottomGridUserHeight=Math.min(c6,p)})},onDrag:(c6)=>{if(this.bottomGridDragStartY===null)this.bottomGridDragStartY=Math.floor(c6.localPosition.y),this.bottomGridDragStartHeight=this.bottomGridUserHeight;let _4=Math.floor(c6.localPosition.y)-this.bottomGridDragStartY,i4=Math.max(4,this.bottomGridDragStartHeight-_4),u4=Math.min(i4,p),w4=Math.floor(u4);if(this.bottomGridUserHeight!==w4)this.setState(()=>{this.bottomGridUserHeight=w4})},onRelease:()=>{this.bottomGridDragStartY=null,this.bottomGridDragStartHeight=null}})}):new L0({height:0})]});V1.push(j1,new L0({height:1,child:new i6({padding:f0.horizontal(1),child:u})}));let w0=new s0({crossAxisAlignment:"stretch",mainAxisSize:"max",children:V1}),C1=M?new $7({children:[w0,new o3({top:0,left:0,child:new wy1})]}):w0,s1=new X9(()=>{if(this.isShowingPalette)return this.dismissPalette(),"handled";if(this.pendingMCPServers.length>0)return this.widget.dependencies.mcpTrustHandler.deny(),"handled";if(this.getCurrentEphemeralError())return this.handleEphemeralErrorResponse("dismiss"),"handled";if(this.displayMessage)return this.handleDisplayMessageDismiss(),"handled";if(this.isShowingHelp)return this.setState(()=>{this.isShowingHelp=!1}),"handled";if(this.isShowingFileChangesOverlay)return this.setState(()=>{this.isShowingFileChangesOverlay=!1}),"handled";if(this.isShowingCostBreakdownOverlay)return this.setState(()=>{this.isShowingCostBreakdownOverlay=!1}),"handled";if(this.isShowingIdePicker)return this.dismissIdePicker(),"handled";if(this.isShowingJetBrainsInstaller)return this.dismissJetBrainsInstaller(),"handled";if(this.isShowingConfirmationOverlay)return this.setState(()=>{this.isShowingConfirmationOverlay=!1,this.confirmationOverlayContent=""}),"handled";if(this.isShowingConsoleOverlay)return this.setState(()=>{this.isShowingConsoleOverlay=!1}),"handled";if(this.textController.hasSelection)return this.textController.clearSelection(),"handled";if(this.isConfirmingClearInput){if(this.textController.clear(),this.setState(()=>{this.isConfirmingClearInput=!1,this.imageAttachments=[]}),this.clearInputConfirmTimeout)clearTimeout(this.clearInputConfirmTimeout),this.clearInputConfirmTimeout=null;return"handled"}if(this.isConfirmingCancelProcessing){if(this.bashInvocations.length>0)this.cancelBashInvocations();if(this.isProcessing())this.markLastUserMessageAsInterrupted().catch((_4)=>{x.error("Failed to mark message as interrupted:",_4)}),this.cancelStreamingMessage().catch((_4)=>{x.error("Failed to cancel streaming message:",_4)});if(this.setState(()=>{this.isConfirmingCancelProcessing=!1}),this.cancelProcessingConfirmTimeout)clearTimeout(this.cancelProcessingConfirmTimeout),this.cancelProcessingConfirmTimeout=null;return"handled"}if(this.executingCommand)return x.info("Canceling executing command:",this.executingCommand.name),this.executingCommand.abortController.abort(),"handled";if(this.bashInvocations.length>0||this.isProcessing()){if(this.setState(()=>{this.isConfirmingCancelProcessing=!0}),this.cancelProcessingConfirmTimeout)clearTimeout(this.cancelProcessingConfirmTimeout);return this.cancelProcessingConfirmTimeout=setTimeout(()=>{this.setState(()=>{this.isConfirmingCancelProcessing=!1}),this.cancelProcessingConfirmTimeout=null},1000),"handled"}if(this.textController.text.trim()!==""||this.imageAttachments.length>0){if(this.setState(()=>{this.isConfirmingClearInput=!0}),this.clearInputConfirmTimeout)clearTimeout(this.clearInputConfirmTimeout);return this.clearInputConfirmTimeout=setTimeout(()=>{this.setState(()=>{this.isConfirmingClearInput=!1}),this.clearInputConfirmTimeout=null},1000),"handled"}return"ignored"}),B1=new X9(()=>{return this.onExitPressed(),"handled"}),Y1=new X9(()=>{return this.setState(()=>{this.isShowingConsoleOverlay=!this.isShowingConsoleOverlay}),"handled"}),O1=new X9(()=>{return kJ.instance.toggleAll(),"handled"}),w1=new X9(()=>{return this.widget.dependencies.configService.getLatest().then((c6)=>{sG("internal.showCost",!(c6.settings["internal.showCost"]??!0))}),"handled"}),I1=new X9(()=>{return T9.instance.toggleFrameStatsOverlay(),"handled"}),E1=new X9(()=>{return T9.instance.tuiInstance.getScreen().markForRefresh(),P9.instance.requestFrame(),"handled"}),p1=new X9(()=>{return this.toggleAgentMode(),"handled"}),h1=new X9(()=>{let _4=this.isShowingPalette&&this.previewThread?this.threadPreviewController.scrollController:(()=>{let{threadState:i4}=this.widget.dependencies,u4=i4.mainThread?.id;return u4?this.getMessageScrollController(u4):null})();if(_4){let i4=Math.max(Math.floor(Q.size.height*0.4),10),u4=Q.size.height-i4;_4.animatePageUp(u4,100)}return"handled"}),r1=new X9(()=>{let _4=this.isShowingPalette&&this.previewThread?this.threadPreviewController.scrollController:(()=>{let{threadState:i4}=this.widget.dependencies,u4=i4.mainThread?.id;return u4?this.getMessageScrollController(u4):null})();if(_4){let i4=Math.max(Math.floor(Q.size.height*0.4),10),u4=Q.size.height-i4;_4.animatePageDown(u4,100)}return"handled"}),$0=new X9(()=>{let _4=this.isShowingPalette&&this.previewThread?this.threadPreviewController.scrollController:(()=>{let{threadState:i4}=this.widget.dependencies,u4=i4.mainThread?.id;return u4?this.getMessageScrollController(u4):null})();if(_4)_4.animateTo(0,100);return"handled"}),G0=new X9(()=>{let _4=this.isShowingPalette&&this.previewThread?this.threadPreviewController.scrollController:(()=>{let{threadState:i4}=this.widget.dependencies,u4=i4.mainThread?.id;return u4?this.getMessageScrollController(u4):null})();if(_4)_4.animateTo(Number.MAX_SAFE_INTEGER,100);return"handled"}),R0=new X9(()=>{if(!this.isTextfieldAndAutocompleteFocused)return"ignored";let{threadState:c6}=this.widget.dependencies;if(!c6.mainThread?.messages.some((i4)=>i4.role==="user"||OI(i4)))return"ignored";return this.setState(()=>{this.isMessageViewInSelectionMode=!0}),"handled"}),U6=new X9((c6)=>{if(c6.direction==="previous")this.navigateHistoryPrevious();else this.navigateHistoryNext();return"handled"}),L6=new X9(()=>{if(!this.isTextfieldAndAutocompleteFocused)return"ignored";return Y91().then(async(c6)=>{if(c6)try{this.handleInsertImage(c6)}finally{try{let{unlink:_4}=await import("node:fs/promises");await _4(c6)}catch{}}}),"handled"}),D4=new Map([[N4.ctrl("c"),new _m],[N4.ctrl("l"),new fm],[N4.ctrl("o"),new i81],[N4.ctrl("v"),new jm],[N4.alt("s"),new uC],[N4.ctrl("s"),new uC],[N4.alt("p"),new vm],[N4.ctrl("r"),new ym],[N4.alt("d"),new xm],[N4.ctrl("t"),new hm],[N4.key("PageUp"),new p81],[N4.key("PageDown"),new d81],[N4.key("Home"),new c81],[N4.key("End"),new l81],[N4.key("Escape"),new Sm],[N4.ctrl("p"),new pC("previous")],[N4.ctrl("n"),new pC("next")],[N4.key("Tab"),new bm]]);if(!t2())D4.set(N4.key("ArrowUp"),new bm);if(!1)D4.set(N4.alt("c"),new km);let k9=new X9(()=>{if(this.isShowingStandaloneThreadPicker)return"handled";return this.showCommandPalette(),"handled"}),I0=new X9(()=>{return this.toggleThreadPickerWorkspaceFilter(),"handled"}),u0=new Map([[Sm,s1],[fm,E1],[uC,p1],[i81,k9],[jm,L6],[km,Y1],[ym,O1],[xm,w1],[vm,I1],[hm,I0],[_m,B1],[p81,h1],[d81,r1],[c81,$0],[l81,G0],[bm,R0],[pC,U6]]),_6=[C1];if(this.isShowingConsoleOverlay)_6.push(new Jy1);if(this.isShowingHelp){let c6=this.getPaletteCommands().getAllCommands();_6.push(new Xy1({commands:c6}))}if(this.adActionModal)_6.push(new mk1({title:"Failed to open browser",message:this.adActionModal.url,showCopyOption:this.adActionModal.showCopyOption,onSelect:async(c6)=>{let _4=this.adActionModal.url;if(c6==="copy")try{await T9.instance.tuiInstance.clipboard.writeText(_4),this.setState(()=>{this.displayMessage=new BG("Link copied to clipboard")})}catch(i4){x.error("Failed to copy to clipboard",{error:i4}),this.setState(()=>{this.displayMessage=Error("Failed to copy to clipboard")})}this.setState(()=>{this.adActionModal=null})}}));if(this.pendingMCPServers.length>0){let{mcpTrustHandler:c6}=this.widget.dependencies;_6.push(new Oy1({servers:this.pendingMCPServers,onAlwaysTrust:c6.trustAlways.bind(c6),onTrustOnce:c6.trustOnce.bind(c6),onOpenSettings:this.handleMCPTrustOpenSettings,onDismiss:c6.deny.bind(c6)}))}if(this.isShowingFileChangesOverlay)_6.push(new uS1({threadData:z}));if(this.isShowingCostBreakdownOverlay&&z.mainThread)_6.push(new Qy1({thread:z.mainThread}));if(this.isShowingConfirmationOverlay)_6.push(new tk1({details:this.confirmationOverlayContent}));let Q8=this.getCommandPaletteContext();if(Q8&&this.isShowingPalette)_6.push(new H8({child:new X6({constraints:s6.loose(80,20),child:new rk1({commandContext:Q8,mainThread:z.mainThread,commands:this.getPaletteCommands(),onDismiss:this.dismissPalette})})}));if(this.isShowingIdePicker)_6.push(new Zy1({onCancel:this.dismissIdePicker,onSelect:this.handleIdeSelection,jetbrainsMode:this.widget.dependencies.jetbrainsMode}));if(this.isShowingStandaloneThreadPicker){let c6=a0.file(process.cwd()),_4=M6(c6);_6.push(new H8({child:new X6({constraints:s6.loose(80,20),child:new nC({threads:this.threadsForPicker,title:"Continue Thread",onSelect:this.handleStandaloneThreadSelect,onDismiss:this.dismissStandaloneThreadPicker,previewController:this.threadPreviewController,isLoading:this.isLoadingThreads,currentWorkspaceURI:_4,filterByWorkspace:this.filterThreadPickerByWorkspace,threadViewStates:this.widget.dependencies.workerController.threadViewStates,recentThreadIDs:this.widget.dependencies.recentThreadIDs,currentThreadID:this.widget.dependencies.threadState.mainThread?.id})})}))}let x8=new $7({children:_6});if(this.isShowingJetBrainsInstaller)return new EA({child:new QY({actions:u0,child:new hq({shortcuts:D4,debugLabel:"jetbrains-installer-shortcuts",child:new My1({configService:this.widget.dependencies.configService,ideClient:this.widget.dependencies.ideClient,onExit:()=>process.exit(0),onContinue:this.dismissJetBrainsInstaller})})})});let A5=new MN({onError:(c6)=>{this.showErrorMessage(c6.message)},child:x8});return new EA({child:new QY({actions:u0,child:new hq({shortcuts:D4,debugLabel:"main-app-shortcuts",child:A5})})})}buildScrollableTodoList(J,Q,Y){return new MZ6({todos:J,enabled:Q,controller:this.todoScrollController,appTheme:Y})}buildBottomWidget(J,Q,Y,X,G,Z,q,V,K){if(J)return new Yy1({error:J,ampURL:this.widget.dependencies.ampURL,onResponse:this.handleEphemeralErrorResponse});if(Q){if(this.displayMessage)this.handleDisplayMessageDismiss();return new ek1({confirmationRequest:Q,onResponse:this.onConfirmationResponse,onShowOverlay:this.showConfirmationOverlay})}if(this.displayMessage)return new Ay1({message:this.displayMessage,onDismiss:this.handleDisplayMessageDismiss});let W=X.app,H=$91(X),z=this.isInRestrictedFreeMode(),U=new gA({key:this.textFieldKey,controller:this.textController,triggers:K?[]:[new PN],completionBuilder:K?void 0:this.getCompletionBuilder(),ampURL:this.widget.dependencies.ampURL,onSubmitted:K?void 0:this.onTextSubmitted,theme:Y,placeholder:K?"Press Ctrl+C to exit":z?"Amp Free is not enabled. Press Ctrl+S to switch modes.":void 0,enabled:this.isTextfieldAndAutocompleteFocused&&!z&&!this.isShowingStandaloneThreadPicker,shellPromptRules:H,focusNode:this.autocompleteFocusNode,autofocus:!this.isMessageViewInSelectionMode&&!this.isShowingStandaloneThreadPicker&&!this.isShowingIdePicker,clipboard:T9.instance.tuiInstance.clipboard,onCopy:this._handleTextCopy.bind(this),onInsertImage:this.handleInsertImage,imageAttachments:this.imageAttachments,popImage:this.handlePopImage}),N=G.mainThread?.queuedMessages??[],M=Array.isArray(Z)&&Z.length>0,L=Array.isArray(N)&&N.length>0,O=G.mainThread?.agentMode==="plan"&&FA(G.mainThread),E,I;if(O){if(E=new WS1(new n91({thread:G.mainThread,onExecute:async()=>{let b=this.getCommandPaletteContext();if(b)await this.getPaletteCommands().execute("execute-plan",b,void 0,new AbortController)},onEdit:async()=>{try{let b=process.env.EDITOR||process.env.VISUAL||"nano",{filePath:i}=await this.widget.dependencies.planFileManager.ensureSync(G.mainThread.id);T9.instance.tuiInstance.suspend();let{execSync:J1}=await import("child_process");J1(`${b} "${i}"`,{stdio:"inherit"}),T9.instance.tuiInstance.resume()}catch(b){x.error("Failed to edit plan",b),this.setState(()=>{this.displayMessage=Error("Failed to edit plan")})}},controller:this.planScrollController,appTheme:X}),{clipBehavior:"antiAlias"}),L)I=new U51({queuedMessages:N});else if(M)I=this.buildScrollableTodoList(Z,this.isTextfieldAndAutocompleteFocused&&!z,X)}else E=L?new U51({queuedMessages:N}):void 0,I=M?this.buildScrollableTodoList(Z,this.isTextfieldAndAutocompleteFocused&&!z,X):void 0;let P=[],R=this.currentShellModeStatus;if(R)P.push({text:new Q1(R==="hidden"?"shell mode (incognito)":"shell mode",new F1({color:R==="hidden"?X.app.shellModeHidden:X.app.shellMode})),position:"top-left"});if(!R&&this.cachedVisibleModes.length>1){let b=this.previewThread,i=b?b.agentMode??this.getEffectiveAgentMode():this.getEffectiveAgentMode(),J1=jy1(i,this.tryOpus);if(b)P.push({text:new Q1(i,new F1({color:J1})),position:"top-left",offsetY:0});else{let u=Xg(i,this.cachedVisibleModes)!==i,s=this.widget.dependencies.getCurrentWorker()||this.widget.dependencies.worker,V1=d$(s.thread)===0,o=z||!this.hasToggledAgentMode&&u&&V1?new Q1("",void 0,[new Q1(i,new F1({color:J1})),new Q1(" (click or ",new F1({color:Y.foreground,dim:!0})),new Q1("Ctrl+S",new F1({color:W.keybind})),new Q1(" to switch)",new F1({color:Y.foreground,dim:!0}))]):new Q1(i,new F1({color:J1}));P.push({text:o,position:"top-left",offsetY:0,onClick:V1?this.toggleAgentMode:void 0})}}if(this.connectedClientsStatus&&this.connectedClientsStatus.enabled){let b=this.connectedClientsStatus,i=b.mode||"disconnected",J1=!!b.errorMessage,n=b.clientID||"unknown",u,s;if(J1)u="●",s=A1.red;else if(i==="presence")u="○",s=A1.yellow;else if(i==="connected"&&b.connected)u="●",s=A1.green;else u="○",s=A1.yellow;let V1=this.connectedClientsStatusExpanded?`${n} ${u}`:u;P.push({text:new Q1(V1,new F1({color:s})),position:"top-right",offsetX:-2,offsetY:0,onClick:this.toggleConnectedClientsStatus})}let S=K?this.widget.dependencies.replayMode.thread.env?.initial.trees?.[0]?.uri:G.mainThread?.env?.initial.trees?.[0]?.uri,y;if(S)y=a0.parse(S).fsPath;else y=process.cwd();let f=this.toHomeRelative(y),m=this.shorten(f),p=!K&&this.currentGitBranch?`${m} (${this.currentGitBranch})`:m;return P.push({text:new Q1(p,new F1({color:Y.foreground,dim:!0})),position:"bottom-right"}),new kS1({leftChild:new B4({child:U}),rightChild1:E,rightChild2:I,maxHeight:q,overlayTexts:P,borderColor:z||!this.isTextfieldAndAutocompleteFocused?A1.index(8):void 0,hasBanner:V,userHeight:this.bottomGridUserHeight,onInitializeHeight:(b)=>{this.setState(()=>{this.bottomGridUserHeight=Math.min(b,q)})},onDrag:(b)=>{if(this.bottomGridDragStartY===null)this.bottomGridDragStartY=Math.floor(b.localPosition.y),this.bottomGridDragStartHeight=this.bottomGridUserHeight;let i=Math.floor(b.localPosition.y)-this.bottomGridDragStartY,J1=Math.max(4,this.bottomGridDragStartHeight-i),n=Math.min(J1,q),u=Math.floor(n);if(this.bottomGridUserHeight!==u)this.setState(()=>{this.bottomGridUserHeight=u})},onDragRelease:()=>{this.bottomGridDragStartY=null,this.bottomGridDragStartHeight=null},enableResize:!V})}}async function Sy1(J){if((await J.configService.getLatest()).settings["terminal.animation"]===!1)T9.instance.tuiInstance.setOptions({queryOptions:{animationDisabled:!0}});let X=()=>null,Z=!1,q=new Mz(Z,1000,J.inspectorPort),V=J.features?.find((O)=>O.name==="amp-connect")?.enabled??!1,K=new hk1({threadService:J.threadService,worker:J.worker,builder:(O,E,I,P,R,S)=>{if(X=R,J.threadDependencies&&V)oj1(J.threadDependencies,J.configService,R,P,J.connectedClientsService,J.startNewThread,J.switchToThread,J.clientId).catch((m)=>{x.error("Failed to start automatic presence:",m)});let y=R(),f={...J,worker:y,threadID:y.thread.id};return new NZ6({...f,threadState:E,workerController:I,switchWorker:P,getCurrentWorker:R,recentThreadIDs:S})}}),W=new hS1({configService:J.configService,child:K}),H=new xS1({configService:J.configService,child:W}),z=new AS1(H),U=new b6({data:cC.fromBaseTheme(oZ.default()),child:z});try{await Oj1(U,{onRootElementMounted:(O)=>{if(x.info("TUI input ready for user interaction"),Z)q.start(O)}})}finally{if(Z)q.stop();if(J.threadDependencies&&V){let{stopGlobalSession:O}=await Promise.resolve().then(() => (rj1(),DJ6));O()}}let M=X()?.thread.id||J.threadID,L=await J.threadService.get(M);if(L&&L.messages.length>0){let O=`${J.ampURL.replace(/\/$/,"")}/threads/${M}`;gJ6(L,O,J.stdout)}}function jy1(J,Q){return J==="smart"?Q?A1.rgb(255,60,70):A1.rgb(145,119,199):J==="rush"?A1.rgb(228,180,2):M5(J)?A1.rgb(0,184,255):J==="plan"?A1.rgb(153,102,255):KO8(J)}class MZ6 extends q6{props;constructor(J){super();this.props=J}createState(){return new LZ6}}class LZ6 extends $6{viewportHeight=1;scrollListenerAttached=!1;initState(){if(!this.scrollListenerAttached)this.widget.props.controller.addListener(()=>{this.updateViewportHeight()}),this.scrollListenerAttached=!0}build(J){let{todos:Q,controller:Y,appTheme:X}=this.widget.props;return new V4({crossAxisAlignment:"stretch",children:[new B4({child:new S2({controller:Y,autofocus:!1,child:new bk1({todos:Q})})}),new DG({controller:Y,thumbColor:X.app.scrollbarThumb,trackColor:X.app.scrollbarTrack,getScrollInfo:()=>{let{maxScrollExtent:G,offset:Z}=Y,q=this.viewportHeight,V=G+q;return{totalContentHeight:Math.max(V,0),viewportHeight:Math.max(q,1),scrollOffset:Math.max(Z,0)}}})]})}updateViewportHeight(){let J=this.getViewportHeight();if(J!==this.viewportHeight)this.viewportHeight=J}getViewportHeight(){let J=this.context.findRenderObject();if(!J)return this.viewportHeight;let Q=(X,G=0)=>{if(X&&"size"in X&&"children"in X){let Z=X.children||[];for(let q of Z){if(q&&"size"in q){let K=q.size;if(typeof K?.height==="number"&&K.height>0)return K.height}let V=Q(q,G+1);if(V>0)return V}}return 0},Y=Q(J);if(Y>0)return Y;if("size"in J){let X=J.size;if(typeof X?.height==="number"&&X.height>0)return X.height}return this.viewportHeight}}class OZ6 extends j6{props;constructor(J){super();this.props=J}build(J){return new y8({child:new L0({height:1}),cursor:a9.NS_RESIZE,onDrag:(Q)=>{if(this.props.userHeight===void 0){let X=J.findRenderObject()?.size.height??0;if(X>0){this.props.onInitializeHeight(X);return}}this.props.onDrag(Q)},onRelease:this.props.onRelease})}}function KO8(J){let Q=0;for(let G=0;G<J.length;G++){let Z=J.charCodeAt(G);Q=(Q<<5)-Q+Z,Q=Q&Q}let Y=[9,10,11,12,13,14,15,208,209,210,211,212,213,214,215],X=Math.abs(Q)%Y.length;return A1.index(Y[X])}Lj1();try{if(process.platform==="win32")await Promise.resolve().then(() => z6(Aj(),1))}catch{}if(process.env.AMP_PWD)try{process.chdir(process.env.AMP_PWD),delete process.env.AMP_PWD}catch(J){Z$.write(`Failed to change directory to ${process.env.AMP_PWD}: ${J}
5115
- `)}var Zv1=Gv1.join(vF0||Gv1.join(process.env.HOME||process.cwd(),".local","state"),"amp","last-thread-id");function kI8(J){process.emitWarning=function(Q,Y,X,G){let Z=typeof Q==="string"?Q:Q.message||String(Q),q=Y||"Warning",V=!1;J.warn(Z,{name:q,code:X})}}function dq(J,Q){if(J.getOptionValueSourceWithGlobals("dangerouslyAllowAll")==="cli")sG("dangerouslyAllowAll",Q.dangerouslyAllowAll);if(J.getOptionValueSourceWithGlobals("mode")==="cli")sG("experimental.agentMode",Q.mode);if(J.getOptionValueSourceWithGlobals("tryOpus")==="cli"&&Q.tryOpus)sG("tryOpus",!0);if(J.getOptionValueSourceWithGlobals("useSonnet")==="cli")sG("model.sonnet",Q.useSonnet)}async function qv1(J){try{await jI8(Gv1.dirname(Zv1),{recursive:!0}),await SI8(Zv1,J,"utf-8")}catch(Q){x.debug("Failed to save last thread ID",Q)}}async function yI8(){try{return(await iV6(Zv1,"utf-8")).trim()}catch(J){return null}}var dV6=[{name:"notifications",long:"notifications",type:"flag",description:(J)=>`${J?"Enable":"Disable"} sound notifications (enabled by default when not in execute mode)`},{name:"color",long:"color",type:"flag",description:(J)=>`${J?"Enable":"Disable"} color output (enabled by default if stdout and stderr are sent to a TTY)`,deprecated:!0},{name:"settingsFile",long:"settings-file",type:"option",default:process.env.AMP_SETTINGS_FILE??dZ,description:`Custom settings file path (overrides the default location ${dZ})`},{name:"logLevel",long:"log-level",type:"option",description:`Set log level (${Object.keys(x).join(", ")})`},{name:"logFile",long:"log-file",type:"option",description:`Set log file location (overrides the default location ${IC1})`},{name:"format",long:"format",type:"option",description:"output using the standard or new-ui. Options: `ui`, `new-ui`",choices:["ui","jsonl","new-ui"],hidden:!0,deprecated:!0},{name:"dangerouslyAllowAll",long:"dangerously-allow-all",type:"switch",default:!1,description:"Disable all command confirmation prompts (agent will execute all commands without asking)"},{name:"jetbrains",long:"jetbrains",type:"flag",default:t2(),description:(J)=>J?"Enable JetBrains integration. When enabled, Amp automatically includes your open JetBrains file and text selection with every message.":"Disable JetBrains integration"},{name:"ide",long:"ide",type:"flag",default:!0,description:(J)=>J?"Enable IDE connection (default). When enabled, Amp automatically includes your open IDE's file and text selection with every message.":"Disable IDE connection"},{name:"interactive",long:"interactive",type:"flag",description:(J)=>J?"Enable interactive mode. This will enable the interactive UI.":"Disable interactive mode. This will disable the interactive UI.",hidden:!0,deprecated:!0},{name:"mcpConfig",long:"mcp-config",type:"option",description:"JSON configuration or file path for MCP servers to merge with existing settings"},{name:"useSonnet",long:"use-sonnet",type:"flag",description:(J)=>J?"Use Claude Sonnet 4.5 instead of Gemini 3":"Use default model (Gemini 3)"},{name:"tryOpus",long:"try-opus",type:"switch",default:!1,description:"Try Claude Opus 4.5 in Amp's smart mode",hidden:!1},{name:"mode",long:"mode",short:"m",type:"option",default:kR.SMART.key,description:`Set the agent mode (${yZ().map((J)=>J.mode).join(", ")}) — controls the model, system prompt, and tool selection`,choices:yZ().map((J)=>J.mode)}],cV6=(J)=>("deprecated"in J)&&J.deprecated===!0,xI8=(J)=>("hidden"in J)&&J.hidden===!0,vI8=(J)=>("default"in J),fI8=(J)=>("default"in J)?J.default:void 0;function hI8(J,Q){let Y=Q.args[0],X=Q.commands.map((Z)=>Z.name());if(Y&&!Y.includes(" ")&&Y.length<30&&!/[./\\]/.test(Y)){let Z=X.filter((V)=>Y.includes(V)||V.includes(Y)),q="Run amp --help for a list of available commands.";if(Z.length>0)q=`Did you mean: ${Z.join(", ")}? Or run amp --help for all commands.`;throw new _8(pZ.unknownCommand(Y),1,q)}}var nV6=null;function oM5(){return nV6}function Tu(J){return{...J,getThreadEnvironment:H41,vfs:rM0({os:J.fileSystem},J.configService.config),fileChangeTrackerStorage:new Ib(J.fileSystem),generateThreadTitle:G06,deleteThread:(Q)=>J.threadService.delete(Q)}}var Vv1=a0.file(_I8.homedir()),aV6=process.env.XDG_CONFIG_HOME?a0.file(process.env.XDG_CONFIG_HOME):Z6.joinPath(Vv1,".config");async function cq(J,Q){FN0("0.0.1764115312-g9a6608");let Y=lI1({storage:J.settings,secretStorage:J.secrets,workspaceRoots:Q0.of([a0.file(process.cwd())]),defaultAmpURL:J.ampURL,homeDir:Vv1,userConfigDir:aV6}),{initializeCLITelemetry:X}=await Promise.resolve().then(() => (N51(),B51));X(Y);let G=await Y.getLatest();x.debug("Global configuration initialized",{settingsKeys:Object.keys(G.settings)});let Z=new _O({configService:Y}),q=new Map,V=()=>q.clear(),K=new LT1(Y,J.settings.getWorkspaceRootPath()),W=x16({configService:Y,trustStore:K,createOAuthProvider:async(J1)=>{let n=q.get(J1);if(n)return x.debug("Reusing existing OAuth provider for server",{serverName:J1}),n;x.debug("Creating OAuth provider for server",{serverName:J1});let u=(async()=>{let s=new aO(J.secrets),V1=await s.getClientInfo(J1),H1=new XT1({storage:s,serverName:J1,clientId:V1?.clientId,clientSecret:V1?.clientSecret,scopes:V1?.scopes});return x.debug("OAuth provider created",{serverName:J1,hasManualClientId:!!V1?.clientId,willUseDCR:!V1?.clientId}),H1})();return q.set(J1,u),u}}),H=P01({configService:Y,filesystem:L5,spawn:dO}),{initializeToolProviders:z}=await Promise.resolve().then(() => (pV6(),uV6)),{registrations:U,initErrors:N}=await z({toolServices:Z,providers:[W,H],initialTimeout:J.executeMode?15000:5000});for(let[J1,n]of N)x.warn(`${J1} provider initialization slow or failed:`,n);if(Q.jetbrains)EI("JetBrains");else if(Q.ide&&z76())EI("VS Code");else if(Q.ide&&F76())EI("Neovim");if(J.executeMode)UN0(!0);let M,L=I2.status.pipe(Y6((J1)=>Boolean(J1.connected&&J1.authenticated)),x4()).subscribe((J1)=>{if(J1){if(!M)M=Z.registerTool(gT)}else M?.dispose(),M=void 0}),O;if(!J.executeMode)O=new w41(process.cwd(),{},!0);else O=new class extends w41{async start(){}async query(){return[]}getStats(){return{state:"unstarted",stats:[]}}dispose(){}};if(!await J.secrets.get("apiKey",J.ampURL)){if(e5.write(`No API key found. Starting login flow...
5115
+ `)}var Zv1=Gv1.join(vF0||Gv1.join(process.env.HOME||process.cwd(),".local","state"),"amp","last-thread-id");function kI8(J){process.emitWarning=function(Q,Y,X,G){let Z=typeof Q==="string"?Q:Q.message||String(Q),q=Y||"Warning",V=!1;J.warn(Z,{name:q,code:X})}}function dq(J,Q){if(J.getOptionValueSourceWithGlobals("dangerouslyAllowAll")==="cli")sG("dangerouslyAllowAll",Q.dangerouslyAllowAll);if(J.getOptionValueSourceWithGlobals("mode")==="cli")sG("experimental.agentMode",Q.mode);if(J.getOptionValueSourceWithGlobals("tryOpus")==="cli"&&Q.tryOpus)sG("tryOpus",!0);if(J.getOptionValueSourceWithGlobals("useSonnet")==="cli")sG("model.sonnet",Q.useSonnet)}async function qv1(J){try{await jI8(Gv1.dirname(Zv1),{recursive:!0}),await SI8(Zv1,J,"utf-8")}catch(Q){x.debug("Failed to save last thread ID",Q)}}async function yI8(){try{return(await iV6(Zv1,"utf-8")).trim()}catch(J){return null}}var dV6=[{name:"notifications",long:"notifications",type:"flag",description:(J)=>`${J?"Enable":"Disable"} sound notifications (enabled by default when not in execute mode)`},{name:"color",long:"color",type:"flag",description:(J)=>`${J?"Enable":"Disable"} color output (enabled by default if stdout and stderr are sent to a TTY)`,deprecated:!0},{name:"settingsFile",long:"settings-file",type:"option",default:process.env.AMP_SETTINGS_FILE??dZ,description:`Custom settings file path (overrides the default location ${dZ})`},{name:"logLevel",long:"log-level",type:"option",description:`Set log level (${Object.keys(x).join(", ")})`},{name:"logFile",long:"log-file",type:"option",description:`Set log file location (overrides the default location ${IC1})`},{name:"format",long:"format",type:"option",description:"output using the standard or new-ui. Options: `ui`, `new-ui`",choices:["ui","jsonl","new-ui"],hidden:!0,deprecated:!0},{name:"dangerouslyAllowAll",long:"dangerously-allow-all",type:"switch",default:!1,description:"Disable all command confirmation prompts (agent will execute all commands without asking)"},{name:"jetbrains",long:"jetbrains",type:"flag",default:t2(),description:(J)=>J?"Enable JetBrains integration. When enabled, Amp automatically includes your open JetBrains file and text selection with every message.":"Disable JetBrains integration"},{name:"ide",long:"ide",type:"flag",default:!0,description:(J)=>J?"Enable IDE connection (default). When enabled, Amp automatically includes your open IDE's file and text selection with every message.":"Disable IDE connection"},{name:"interactive",long:"interactive",type:"flag",description:(J)=>J?"Enable interactive mode. This will enable the interactive UI.":"Disable interactive mode. This will disable the interactive UI.",hidden:!0,deprecated:!0},{name:"mcpConfig",long:"mcp-config",type:"option",description:"JSON configuration or file path for MCP servers to merge with existing settings"},{name:"useSonnet",long:"use-sonnet",type:"flag",description:(J)=>J?"Use Claude Sonnet 4.5 instead of Gemini 3":"Use default model (Gemini 3)"},{name:"tryOpus",long:"try-opus",type:"switch",default:!1,description:"Try Claude Opus 4.5 in Amp's smart mode",hidden:!1},{name:"mode",long:"mode",short:"m",type:"option",default:kR.SMART.key,description:`Set the agent mode (${yZ().map((J)=>J.mode).join(", ")}) — controls the model, system prompt, and tool selection`,choices:yZ().map((J)=>J.mode)}],cV6=(J)=>("deprecated"in J)&&J.deprecated===!0,xI8=(J)=>("hidden"in J)&&J.hidden===!0,vI8=(J)=>("default"in J),fI8=(J)=>("default"in J)?J.default:void 0;function hI8(J,Q){let Y=Q.args[0],X=Q.commands.map((Z)=>Z.name());if(Y&&!Y.includes(" ")&&Y.length<30&&!/[./\\]/.test(Y)){let Z=X.filter((V)=>Y.includes(V)||V.includes(Y)),q="Run amp --help for a list of available commands.";if(Z.length>0)q=`Did you mean: ${Z.join(", ")}? Or run amp --help for all commands.`;throw new _8(pZ.unknownCommand(Y),1,q)}}var nV6=null;function oM5(){return nV6}function Tu(J){return{...J,getThreadEnvironment:H41,vfs:rM0({os:J.fileSystem},J.configService.config),fileChangeTrackerStorage:new Ib(J.fileSystem),generateThreadTitle:G06,deleteThread:(Q)=>J.threadService.delete(Q)}}var Vv1=a0.file(_I8.homedir()),aV6=process.env.XDG_CONFIG_HOME?a0.file(process.env.XDG_CONFIG_HOME):Z6.joinPath(Vv1,".config");async function cq(J,Q){FN0("0.0.1764129854-ge5da8d");let Y=lI1({storage:J.settings,secretStorage:J.secrets,workspaceRoots:Q0.of([a0.file(process.cwd())]),defaultAmpURL:J.ampURL,homeDir:Vv1,userConfigDir:aV6}),{initializeCLITelemetry:X}=await Promise.resolve().then(() => (N51(),B51));X(Y);let G=await Y.getLatest();x.debug("Global configuration initialized",{settingsKeys:Object.keys(G.settings)});let Z=new _O({configService:Y}),q=new Map,V=()=>q.clear(),K=new LT1(Y,J.settings.getWorkspaceRootPath()),W=x16({configService:Y,trustStore:K,createOAuthProvider:async(J1)=>{let n=q.get(J1);if(n)return x.debug("Reusing existing OAuth provider for server",{serverName:J1}),n;x.debug("Creating OAuth provider for server",{serverName:J1});let u=(async()=>{let s=new aO(J.secrets),V1=await s.getClientInfo(J1),H1=new XT1({storage:s,serverName:J1,clientId:V1?.clientId,clientSecret:V1?.clientSecret,scopes:V1?.scopes});return x.debug("OAuth provider created",{serverName:J1,hasManualClientId:!!V1?.clientId,willUseDCR:!V1?.clientId}),H1})();return q.set(J1,u),u}}),H=P01({configService:Y,filesystem:L5,spawn:dO}),{initializeToolProviders:z}=await Promise.resolve().then(() => (pV6(),uV6)),{registrations:U,initErrors:N}=await z({toolServices:Z,providers:[W,H],initialTimeout:J.executeMode?15000:5000});for(let[J1,n]of N)x.warn(`${J1} provider initialization slow or failed:`,n);if(Q.jetbrains)EI("JetBrains");else if(Q.ide&&z76())EI("VS Code");else if(Q.ide&&F76())EI("Neovim");if(J.executeMode)UN0(!0);let M,L=I2.status.pipe(Y6((J1)=>Boolean(J1.connected&&J1.authenticated)),x4()).subscribe((J1)=>{if(J1){if(!M)M=Z.registerTool(gT)}else M?.dispose(),M=void 0}),O;if(!J.executeMode)O=new w41(process.cwd(),{},!0);else O=new class extends w41{async start(){}async query(){return[]}getStats(){return{state:"unstarted",stats:[]}}dispose(){}};if(!await J.secrets.get("apiKey",J.ampURL)){if(e5.write(`No API key found. Starting login flow...
5116
5116
  `),!await bI8(J))await VA(),process.exit(1)}let E=await o16({isDevelopment:!1}),I=new PT1(E,Y),P=new wT1(E,{lazy:!0}),R=new OT1(I,(J1,n)=>{let u=A3.get(J1);if(u)u.handle(n).catch((s)=>{x.error("Failed to apply artifact delta",s)})}),S=Q.notifications!==void 0?Q.notifications:!J.executeMode,y=H06({playNotificationSound:async(J1)=>{if(S){W06(J1);let n=Dj1(),u=Mj1();if((!n||u)&&G.settings["notifications.system.enabled"]!==!1){if(J1==="idle")process.stdout.write("\x1B]777;notify;Amp;Agent is ready\x1B\\");else if(J1==="requires-user-input")process.stdout.write("\x1B]777;notify;Amp;Waiting for approval\x1B\\")}}},windowFocused:()=>Promise.resolve(!1),threadService:I,configService:Y});x.info("Starting Amp background services");let f=$06({threadService:I,threadHistoryService:P,configService:Y,isExtensionDevelopment:!1}),m;I2.status.subscribe((J1)=>{m=J1});let p=new G$1({workspaceRoots:[a0.file(process.cwd())],getCurrentFile:()=>{if(!m?.openFile)return;try{return a0.parse(m.openFile)}catch(J1){x.warn("Failed to parse current file URI",{uri:m.openFile,error:J1});return}},getOpenFiles:()=>{if(!m?.visibleFiles?.length)return[];let J1=m.openFile;return m.visibleFiles.filter((n)=>n!==J1).map((n)=>{try{return a0.parse(n)}catch(u){return x.warn("Failed to parse visible file URI",{uri:n,error:u}),null}}).filter((n)=>n!==null)}}),b=new Aj1,i={codebaseContextService:p,configService:Y,toolServices:Z,mcpService:W,trustStore:K,threadService:I,threadHistoryService:P,threadSyncService:f,planFileManager:R,threadStorage:E,secretStorage:J.secrets,settingsStorage:J.settings,fuzzyServer:O,notificationService:y,fileSystem:Q.jetbrains||Q.ide?d16:L5,terminal:b};return{...i,async asyncDispose(){for(let J1 of U.values())J1.dispose();await i.mcpService.dispose(),V(),await i.threadService.asyncDispose(),i.configService.unsubscribe(),i.toolServices.dispose(),i.fuzzyServer.dispose(),i.threadSyncService.dispose(),i.settingsStorage[Symbol.dispose](),L.unsubscribe(),M?.dispose()}}}async function bI8(J){if(!J.executeMode){if(!await oC1("Would you like to log in to Amp? [(y)es, (n)o]: "))return e5.write(`Login cancelled. Run the command again to retry.
5117
5117
  `),!1}return await oV6(J)}async function oV6(J){let Q=CI8(32).toString("hex"),Y=await aC1(J.ampURL,Q),X=new AbortController;try{await WJ(Y,X.signal)}catch(Z){x.error("Error opening browser",{error:Z})}let G=await aC1(J.ampURL,Q,!1);e5.write(`If your browser does not open automatically, visit:
5118
5118
 
@@ -5122,15 +5122,15 @@ ${h4.blue.bold(G)}
5122
5122
  Login successful! You can now use the Amp CLI.
5123
5123
  `),!0}catch(Z){return x.error("Login failed",{error:Z}),Z$.write(`
5124
5124
  Login failed: ${Z instanceof Error?Z.message:String(Z)}
5125
- `),!1}}function gI8(){let J=new rO().name("amp").description("AI-powered coding assistant").option("--visibility <visibility>","Set thread visibility (private, public, workspace, group)").configureOutput({writeErr:()=>{}});J.exitOverride((H)=>{if(H.code==="commander.help"||H.code==="commander.version"||H.exitCode===0)WC(),process.exit(0);let z=H.originalError??H;q56(z)}),J.option("-V, --version","Print the version number and exit",()=>{e5.write(`0.0.1764115312-g9a6608 (released 2025-11-26T00:07:01.147Z)
5125
+ `),!1}}function gI8(){let J=new rO().name("amp").description("AI-powered coding assistant").option("--visibility <visibility>","Set thread visibility (private, public, workspace, group)").configureOutput({writeErr:()=>{}});J.exitOverride((H)=>{if(H.code==="commander.help"||H.code==="commander.version"||H.exitCode===0)WC(),process.exit(0);let z=H.originalError??H;q56(z)}),J.option("-V, --version","Print the version number and exit",()=>{e5.write(`0.0.1764129854-ge5da8d (released 2025-11-26T04:09:43.233Z)
5126
5126
  `),process.exit(0)}),J.addHelpText("after",K76()),J.configureHelp({formatHelp:W76}),J.command("logout").description("Log out by removing stored API key").action(async(H,z)=>{let U=z.optsWithGlobals(),N=await KY(U);await dI8(N)}),J.command("login").description("Log in to Amp").addHelpText("after","If AMP_URL is set during login, it will be persisted to global settings for future CLI invocations, though AMP_URL will continue to take precedence.").action(async(H,z)=>{let U=z.optsWithGlobals(),N=await KY(U);await pI8(N,await hC1(U,N.settings))});let Q=async(H,z,U)=>{lI1({storage:z.settings,secretStorage:z.secrets,workspaceRoots:Q0.of([a0.file(process.cwd())]),defaultAmpURL:z.ampURL,homeDir:Vv1,userConfigDir:aV6});let N={...z,executeMode:!1};await $v1(N,{...H,openThreadSwitcher:!0},U)},Y=J.command("threads").alias("t").alias("thread").summary("Manage threads").description("Thread management commands. When no subcommand is provided, defaults to listing threads.").action(async(H,z)=>{let U=z.optsWithGlobals(),N=await KY(U);await lV6(U,N,z)});Y.command("new").alias("n").summary("Create a new thread").description("Create a new thread and print its ID. The thread will be empty. You can set the visibility using the --visibility option.").option("--visibility <visibility>","Set thread visibility (private, public, workspace, group)").action(async(H,z)=>{let U=z.optsWithGlobals(),N=await KY(U);await rI8(U,N,z)}),Y.command("continue [threadId]").alias("c").summary("Continue an existing thread").description("Continue an existing thread by resuming the conversation. By default, shows an interactive picker with the most recently used thread at the top. Use --last to continue the last thread directly without the picker.").option("--last","Continue the last thread directly without showing the picker").option("--pick","Pick a thread interactively from a list (DEPRECATED: picker is now the default)").action(async(H,z,U)=>{let N=U.optsWithGlobals(),M=await KY(N);if(z.pick)Z$.write(`${h4.yellow("Warning:")} The --pick flag is deprecated. The picker is now shown by default.
5127
5127
  `);if(z.last||H||M.executeMode)await oI8(N,M,H,U);else await Q(N,M,U)}),Y.command("fork [threadId]").alias("f").summary("Fork an existing thread").description("Create a new thread by forking an existing one. This copies the conversation history up to the current point and creates a new thread where you can explore different directions. If no thread ID is provided, the most recently used thread will be forked.").action(async(H,z,U)=>{let N=U.optsWithGlobals(),M=await KY(N);await aI8(N,M,H,U)}),Y.command("list").alias("l").alias("ls").summary("List all threads").description("List all your threads with their IDs, names, and last modified times.").action(async(H,z)=>{let U=z.optsWithGlobals(),N=await KY(U);await lV6(U,N,z)}),Y.command("share <threadId>").summary("Share a thread").description("Change thread visibility (private, public, unlisted, workspace, group) or share with Amp support for debugging. Use --visibility to change who can access the thread, or --support to share with the Amp team for troubleshooting.").alias("s").option("--visibility <visibility>","Set thread visibility (private, public, unlisted, workspace, group)").option("--support [message]","Share thread with Amp support for debugging").action(async(H,z,U)=>{let N=U.optsWithGlobals(),M=await KY(N);await nI8(N,M,H,U,z.support)}),Y.command("rename <threadId> <newName>").alias("r").summary("Rename a thread").description('Change the title of a thread. Quote names with spaces: amp threads rename T-123 "New thread name"').action(async(H,z,U,N)=>{let M=N.optsWithGlobals(),L=await KY(M);await cI8(M,L,H,z,N)}),Y.command("markdown <threadId>").alias("md").summary("Render thread as markdown").description("Render a thread as markdown. This outputs the entire conversation history in a readable markdown format.").action(async(H,z,U)=>{let N=U.optsWithGlobals(),M=await KY(N);await lI8(N,M,H,U)}),Y.command("replay <threadId>").alias("p").summary("Replay a thread").description("Replay a thread by downloading it and playing through all interactions. User messages are simulated with variable typing speed.").option("--wpm <wpm>","Typing speed in words per minute (default: 120)","120").option("--no-typing","Disable typing simulation and display messages instantly").option("--message-delay <ms>","Delay between messages in milliseconds (default: 1000)","1000").option("--tool-progress-delay <ms>","Delay to show tool in-progress state in milliseconds (default: 800)","800").option("--exit-delay <seconds>","Delay in seconds before exiting after replay completes (default: 3)","3").option("--no-indicator","Hide the replay progress indicator").action(async(H,z,U)=>{let N=U.optsWithGlobals(),M=await KY(N);await iI8(N,M,H,z,U)}),Z36(J,async(H,z)=>{let U=await KY(z);dq(H,z);let N=await cq(U,z);return{context:U,mcpService:N.mcpService,toolService:N.toolServices,toolServices:N.toolServices,configService:N.configService,cleanupTerminal:WC,asyncDispose:N.asyncDispose.bind(N)}}),n76(J,async(H)=>{let z=H.optsWithGlobals();return await KY(z)}),h76(J,async(H)=>{let z=await KY(H);return{settings:z.settings,secretStorage:z.secrets,getThreadDeps:async(U)=>{dq(U,H);let N=await cq(z,H);return{mcpService:N.mcpService,settings:z.settings,asyncDispose:N.asyncDispose.bind(N)}}}});function G(H,z,U){let M=typeof H.description==="string"?H.description:U===void 0?H.description(!0):H.description(U),L=new sB(z,M),O=fI8(H);if(O)L.default(O);if(L.hidden=xI8(H)||cV6(H),"choices"in H)L.choices([...H.choices]);return L}for(let H of dV6)switch(H.type){case"flag":{J.addOption(G(H,`--${H.long}`)),J.addOption(G(H,`--no-${H.long}`,!1));break}case"switch":{J.addOption(G(H,`--${H.long}`,!0));break}default:{J.addOption(G(H,`${"short"in H?`-${H.short}, `:""}--${H.long} <value>`));break}}let Z=new sB("-x, --execute [message]","Use execute mode, optionally with user message. In execute mode, agent will execute provided prompt (either as argument, or via stdin). Only last assistant message is printed. Enabled automatically when redirecting stdout.").default(!1);J.addOption(Z);let q=new sB("-r, --remote","When used with -x/--execute, execute in an async agent on the Amp server.").default(!1).hideHelp();J.addOption(q);let V=new sB("--stream-json","When used with --execute, output in Claude Code-compatible stream JSON format instead of plain text.").default(!1);J.addOption(V);let K=new sB("--stream-json-input","Read JSON Lines user messages from stdin. Requires both --execute and --stream-json.").default(!1);J.addOption(K);let W=new sB("--stats","When used with --execute, output JSON with both result and token usage data (for /evals).").default(!1).hideHelp(!0);if(J.addOption(W),process.env.AMP_CONNECT==="1"){let H=new sB("--client-id <clientId>","Override the client ID for connect functionality (default: amp-<pid>@<hostname>)");J.addOption(H)}return J.action(async(H,z)=>{let U=H,N=await KY(U);if(Object.keys(U).forEach((M)=>{let L=dV6.find((O)=>O.name===M);if(L&&cV6(L)&&!vI8(L))Z$.write(h4.yellow(`Warning: '--${M}' flag is deprecated
5128
5128
  `))}),z.args.length>0)hI8(N,z);await $v1(N,U,z)}),j76(J),J}async function G71(J,Q){let{thread:Y,visibility:X}=Q,G=Y?.id??u$(),Z=Tu(J);if(Y)await J.threadStorage.set(G,Y);let q=await A3.getOrCreateForThread(Z,G),V=await J.threadStorage.get(G);if(Q.agentMode&&!V?.agentMode&&d$(q.thread)===0)await q.handle({type:"agent-mode",mode:Q.agentMode});if(X)await J.threadSyncService.updateThreadMeta(G,x41(X));let K=J.threadService.observe(G).subscribe(async(W)=>{if(FJ(W,"assistant"))await qv1(G),K.unsubscribe()});return await q.resume(),q}async function $v1(J,Q,Y){let X=y41(Q);if(X instanceof Error)G$(X.message);let G,Z=null;if(Q.streamJsonInput)G="";else if(typeof Q.execute==="string"){G=Q.execute;let i=(await rC1()).trimEnd();if(i)Z=i}else G=(await rC1()).trimEnd();if(Q.remote&&!J.executeMode)throw new _8("The -r/--remote flag currently only works with --execute mode",1,'Use: amp --remote --execute "your message"');if(Q.streamJson&&!J.executeMode)throw new _8("The --stream-json flag requires --execute mode",1,'Use: amp --execute "your message" --stream-json');if(Q.streamJsonInput&&!J.executeMode)throw new _8("The --stream-json-input flag requires --execute mode",1,"Use: amp --execute --stream-json --stream-json-input");if(Q.streamJsonInput&&!Q.streamJson)throw new _8("The --stream-json-input flag requires --stream-json",1,"Use: amp --execute --stream-json --stream-json-input");if((J.executeMode||Q.streamJson)&&M5(Q.mode))throw new _8(`Execute mode is not permitted with --mode '${Q.mode}'`,1);if(Q.stats&&!J.executeMode)throw new _8("The --stats flag requires --execute mode",1,'Use: amp --execute "your message" --stats');if(Q.streamJsonInput&&typeof Q.execute==="string"&&Q.execute.trim()!=="")throw new _8("Do not provide a message argument when using --stream-json-input",1,`Supply messages via stdin JSONL instead: echo '{"type":"user","message":{"role":"user","content":[{"type":"text","text":"your message"}]}}' | amp --execute --stream-json --stream-json-input`);if(J.executeMode&&G===""&&!Q.streamJsonInput)throw new _8("User message must be provided through stdin or as argument when using execute mode",1,`Either pass a message as an argument: amp --execute "your message"
5129
5129
  Or pipe via stdin: echo "your message" | amp --execute`);dq(Y,Q);let q=await cq(J,Q);nV6=q;let V=Tu(q),K=async(i)=>{let J1=await iV6(i,"utf-8"),n=JSON.parse(J1);if(!p$(n.id))throw new _8(pZ.invalidThreadId);return G71(q,{visibility:X,agentMode:Q.mode,thread:n})},W=async(i)=>{if(!p$(i))throw new _8(pZ.invalidThreadId);try{let[n,u]=await Promise.all([C5.getThreadLinkInfo({thread:i},{config:q.configService}),C5.getUserInfo({},{config:q.configService})]);if(n.ok&&u.ok){let s=n.result.creatorUserID,V1=u.result.id;if(s&&s!==V1&&!process.env.AMP_RESUME_OTHER_USER_THREADS_INSECURE)throw new _8(`Cannot resume thread created by another user.
5130
5130
 
5131
5131
  This thread belongs to a different user and cannot be continued for security reasons. Set AMP_RESUME_OTHER_USER_THREADS_INSECURE=1 to bypass this check.`)}}catch(n){if(n instanceof _8)throw n;x.warn("Failed to validate thread ownership in CLI, allowing to open",{error:n})}let J1=await q.threadService.get(i)??void 0;return x.info(`[fetchAndStartThread] Loaded thread ${i}, agentMode: ${J1?.agentMode??"undefined"}`),G71(q,{visibility:X,agentMode:J1?void 0:Q.mode,thread:J1})},H=async()=>{try{if(Q.threadId)return W(Q.threadId);else return G71(q,{visibility:X})}catch(i){if(i instanceof _8)throw i;throw await ag(i,Q.threadId),Error("handleError should have called process.exit()")}},z=async()=>{return G71(q,{visibility:X})};if(Q.format==="jsonl")Z$.write(`jsonl format is deprecated. Version "0.0.1752148945-gd8844f" or earlier is required to use jsonl format.
5132
- `),await VA(),process.exit(1);if(J.executeMode&&Q.remote)await a76(G,Z,q.configService),await q.asyncDispose(),process.exit(0);let U=await H();if(J.executeMode)m76(q.mcpService,J.settings),await A56(U,U.threadID,G,Z,q,!!Q.streamJson,!!Q.streamJsonInput,!!Q.stats,J.ampURL),await q.asyncDispose(),process.exit(0);let N=!1,M=!1;if(Q.jetbrains||Q.ide){await Ah0();let i=bT({jetbrainsOnly:Q.jetbrains});if(i.length===0){if(Q.jetbrains)M=!await q.configService.get("jetbrains.skipInstall")}else if(i.length===1){let J1=i[0];if(J1)I2.selectConfig(J1)}else N=!0}let L=_41("0.0.1764115312-g9a6608",q.settingsStorage),O=new k61(q.threadStorage),E=Q0.of([a0.file(process.cwd())]),I=B$1(void 0,E),P=new k41(q.mcpService,J.settings.getWorkspaceRootPath());if(G)U.handle({type:"user:message",message:{content:[{type:"text",text:G}]}});let R=(async()=>{try{let i=await C5.getUserFreeTierStatus({},{config:q.configService,signal:AbortSignal.timeout(5000)});if(i.ok)return x.info("User free tier status:",i),i.result}catch(i){x.error("Failed to fetch free tier status:",i)}})(),S=(async()=>{try{let i=await C5.getUserInfo({},{config:q.configService});if(i.ok)return i.result}catch(i){x.debug("Failed to fetch user workspace info:",i)}})(),[y,f]=await Promise.all([R,S]),m=f?.email,p=m&&(m.endsWith("@sourcegraph.com")||m.endsWith("@ampcode.com")||m==="auth-bypass-user@example.com");if(p)q.toolServices.registerTool(K06);let b=await t76();x.info("Loaded session state:",b),await Sy1({codebaseContextService:q.codebaseContextService,stdout:process.stdout,history:new B41,fuzzyServer:q.fuzzyServer,settingsStorage:q.settingsStorage,threadService:q.threadService,threadHistoryService:q.threadHistoryService,threadSyncService:q.threadSyncService,planFileManager:q.planFileManager,threadID:U.threadID,threadFuzzyIndexer:O,worker:U,workerDeps:V,configService:q.configService,internalAPIClient:C5,ampURL:J.ampURL,startNewThread:z,switchToThread:W,ideClient:I2,connectedClientsService:new _01,commandRegistry:I,mcpService:q.mcpService,mcpTrustHandler:P,showJetBrainsInstaller:M,showIdePicker:N,openThreadSwitcher:Q.openThreadSwitcher,updateService:L,inspector:Q.inspector,inspectorPort:Q.inspectorPort,jetbrainsMode:Q.jetbrains,clientId:Q.clientId,sessionState:b,freeTierStatus:y,workspace:f?.team??null,features:f?.features??[],isDogfooding:p||!1,threadDependencies:q}),await q.asyncDispose(),process.exit(0)}async function KY(J){if(J.interactive)Z$.write(`Warning: --interactive flag is deprecated. Interactive mode is now the default unless --execute is used or output is redirected.
5133
- `);let Q=!!J.execute||!process.stdout.isTTY&&!J.streamJson,Y=process.stdout.isTTY&&process.stderr.isTTY,X=await n56({...J,workspaceTrust:{current:!0,changes:Ok},getHook:process.env.AMP_URL?(Z,q)=>{if(Z==="url")return Promise.resolve(process.env.AMP_URL);return q()}:void 0});if(J.mcpConfig){let Z=await b76(J.mcpConfig);X=g76(X,Z)}let G=await X.get("url","global");if(!G)G=EY;if(!cF(G))x.info("Targeting custom Amp server",{ampURL:G});return X=yU0(X),{executeMode:Q,isTTY:Y,ampURL:G,settings:X,secrets:o76(await hC1(J,X))}}function mI8(J){let Q={};for(let Y=0;Y<J.length;Y++){let X=J[Y];if(X?.startsWith("--")){let Z=X.slice(2).replace(/-([a-z])/g,(V,K)=>K.toUpperCase()),q=J[Y+1];if(q&&!q.startsWith("--"))Q[Z]=q,Y++}}return Q}async function uI8(){let J=mI8(process.argv);if(t96({logLevel:J.logLevel||process.env.AMP_LOG_LEVEL,logFile:J.logFile||process.env.AMP_LOG_FILE}),kI8(x),x.info("Starting Amp CLI.",{version:"0.0.1764115312-g9a6608",buildTimestamp:"2025-11-26T00:07:01.147Z"}),parseInt(process.version.slice(1).split(".")[0]??"")<20)throw new _8(pZ.nodeVersion(process.version),1,"Please upgrade your Node.js installation from https://nodejs.org");await gI8().parseAsync(process.argv)}LE1().startActiveSpan("main",async(J)=>{process.on("exit",()=>J.end()),await uI8().catch(ag)});async function pI8(J,Q){if(process.env.AMP_URL)await J.settings.set("url",process.env.AMP_URL,"global"),e5.write(`Saving custom server URL to settings: ${process.env.AMP_URL}
5132
+ `),await VA(),process.exit(1);if(J.executeMode&&Q.remote)await a76(G,Z,q.configService),await q.asyncDispose(),process.exit(0);let U=await H();if(J.executeMode)m76(q.mcpService,J.settings),await A56(U,U.threadID,G,Z,q,!!Q.streamJson,!!Q.streamJsonInput,!!Q.stats,J.ampURL),await q.asyncDispose(),process.exit(0);let N=!1,M=!1;if(Q.jetbrains||Q.ide){await Ah0();let i=bT({jetbrainsOnly:Q.jetbrains});if(i.length===0){if(Q.jetbrains)M=!await q.configService.get("jetbrains.skipInstall")}else if(i.length===1){let J1=i[0];if(J1)I2.selectConfig(J1)}else N=!0}let L=_41("0.0.1764129854-ge5da8d",q.settingsStorage),O=new k61(q.threadStorage),E=Q0.of([a0.file(process.cwd())]),I=B$1(void 0,E),P=new k41(q.mcpService,J.settings.getWorkspaceRootPath());if(G)U.handle({type:"user:message",message:{content:[{type:"text",text:G}]}});let R=(async()=>{try{let i=await C5.getUserFreeTierStatus({},{config:q.configService,signal:AbortSignal.timeout(5000)});if(i.ok)return x.info("User free tier status:",i),i.result}catch(i){x.error("Failed to fetch free tier status:",i)}})(),S=(async()=>{try{let i=await C5.getUserInfo({},{config:q.configService});if(i.ok)return i.result}catch(i){x.debug("Failed to fetch user workspace info:",i)}})(),[y,f]=await Promise.all([R,S]),m=f?.email,p=m&&(m.endsWith("@sourcegraph.com")||m.endsWith("@ampcode.com")||m==="auth-bypass-user@example.com");if(p)q.toolServices.registerTool(K06);let b=await t76();x.info("Loaded session state:",b),await Sy1({codebaseContextService:q.codebaseContextService,stdout:process.stdout,history:new B41,fuzzyServer:q.fuzzyServer,settingsStorage:q.settingsStorage,threadService:q.threadService,threadHistoryService:q.threadHistoryService,threadSyncService:q.threadSyncService,planFileManager:q.planFileManager,threadID:U.threadID,threadFuzzyIndexer:O,worker:U,workerDeps:V,configService:q.configService,internalAPIClient:C5,ampURL:J.ampURL,startNewThread:z,switchToThread:W,ideClient:I2,connectedClientsService:new _01,commandRegistry:I,mcpService:q.mcpService,mcpTrustHandler:P,showJetBrainsInstaller:M,showIdePicker:N,openThreadSwitcher:Q.openThreadSwitcher,updateService:L,inspector:Q.inspector,inspectorPort:Q.inspectorPort,jetbrainsMode:Q.jetbrains,clientId:Q.clientId,sessionState:b,freeTierStatus:y,workspace:f?.team??null,features:f?.features??[],isDogfooding:p||!1,threadDependencies:q}),await q.asyncDispose(),process.exit(0)}async function KY(J){if(J.interactive)Z$.write(`Warning: --interactive flag is deprecated. Interactive mode is now the default unless --execute is used or output is redirected.
5133
+ `);let Q=!!J.execute||!process.stdout.isTTY&&!J.streamJson,Y=process.stdout.isTTY&&process.stderr.isTTY,X=await n56({...J,workspaceTrust:{current:!0,changes:Ok},getHook:process.env.AMP_URL?(Z,q)=>{if(Z==="url")return Promise.resolve(process.env.AMP_URL);return q()}:void 0});if(J.mcpConfig){let Z=await b76(J.mcpConfig);X=g76(X,Z)}let G=await X.get("url","global");if(!G)G=EY;if(!cF(G))x.info("Targeting custom Amp server",{ampURL:G});return X=yU0(X),{executeMode:Q,isTTY:Y,ampURL:G,settings:X,secrets:o76(await hC1(J,X))}}function mI8(J){let Q={};for(let Y=0;Y<J.length;Y++){let X=J[Y];if(X?.startsWith("--")){let Z=X.slice(2).replace(/-([a-z])/g,(V,K)=>K.toUpperCase()),q=J[Y+1];if(q&&!q.startsWith("--"))Q[Z]=q,Y++}}return Q}async function uI8(){let J=mI8(process.argv);if(t96({logLevel:J.logLevel||process.env.AMP_LOG_LEVEL,logFile:J.logFile||process.env.AMP_LOG_FILE}),kI8(x),x.info("Starting Amp CLI.",{version:"0.0.1764129854-ge5da8d",buildTimestamp:"2025-11-26T04:09:43.233Z"}),parseInt(process.version.slice(1).split(".")[0]??"")<20)throw new _8(pZ.nodeVersion(process.version),1,"Please upgrade your Node.js installation from https://nodejs.org");await gI8().parseAsync(process.argv)}LE1().startActiveSpan("main",async(J)=>{process.on("exit",()=>J.end()),await uI8().catch(ag)});async function pI8(J,Q){if(process.env.AMP_URL)await J.settings.set("url",process.env.AMP_URL,"global"),e5.write(`Saving custom server URL to settings: ${process.env.AMP_URL}
5134
5134
  `);else if(!cF(J.ampURL))e5.write(`Logging in to ${new URL(J.ampURL).hostname}
5135
5135
  `);let Y=process.env.AMP_API_KEY;if(Y)e5.write(`API key found in environment variable, storing...
5136
5136
  `),await Q.set("apiKey",Y,J.ampURL),e5.write(`API key successfully stored.
@@ -5143,7 +5143,7 @@ This thread belongs to a different user and cannot be continued for security rea
5143
5143
  `);else e5.write(`Successfully logged out from ${new URL(J.ampURL).hostname}.
5144
5144
  `);process.exit(0)}async function cI8(J,Q,Y,X,G){dq(G,J);let Z=await cq(Q,J);try{let q=Z71(Y);if(!q)$71(Y);let V=q,K=X.trim();if(K.length===0)G$("Thread name cannot be empty");if(K.length>256)G$("Thread name cannot exceed 256 characters");if(!(await wj(V,Z)).messages.length)G$("Cannot rename an empty thread.");let H=Tu(Z);await(await A3.getOrCreateForThread(H,V)).handle({type:"title",value:K}),x.info("GOT HERE"),await Z.threadSyncService.sync(),x.info("GOT THERE"),e5.write(h4.green(`✓ Thread ${V} renamed to "${K}"
5145
5145
  `)),await Z.asyncDispose(),process.exit(0)}catch(q){await Z.asyncDispose();let V=`Failed to rename thread: ${q instanceof Error?q.message:String(q)}`;G$(V)}}async function lI8(J,Q,Y,X){dq(X,J);let G=await cq(Q,J);try{let Z=Z71(Y);if(!Z)$71(Y);let V=await wj(Z,G),K=KR(V);e5.write(K+`
5146
- `),await G.asyncDispose(),process.exit(0)}catch(Z){await G.asyncDispose();let q=`Failed to render thread as markdown: ${Z instanceof Error?Z.message:String(Z)}`;G$(q)}}async function iI8(J,Q,Y,X,G){dq(G,J);let Z=await cq(Q,J);try{let q=await Kv1(Y),V=await wj(q,Z),K=X.typing!==!1,W=parseInt(X.wpm||"120",10),H=parseInt(X.messageDelay||"1000",10),z=parseInt(X.toolProgressDelay||"800",10),U=parseInt(X.exitDelay||"3",10)*1000,N=X.indicator!==!1,M=Tu(Z),L=V.id;await Z.threadStorage.set(L,V);let O=await A3.getOrCreateForThread(M,L);await O.resume();let E=_61.fromWorker(O),I=new k61(Z.threadStorage),P=Q0.of([a0.file(process.cwd())]),R=B$1(void 0,P),S=new k41(Z.mcpService,Q.settings.getWorkspaceRootPath()),y=_41("0.0.1764115312-g9a6608",Z.settingsStorage);await Sy1({codebaseContextService:Z.codebaseContextService,stdout:process.stdout,history:new B41,fuzzyServer:Z.fuzzyServer,settingsStorage:Z.settingsStorage,threadService:Z.threadService,threadHistoryService:Z.threadHistoryService,threadSyncService:Z.threadSyncService,planFileManager:Z.planFileManager,threadID:L,threadFuzzyIndexer:I,worker:E,workerDeps:M,configService:Z.configService,internalAPIClient:C5,ampURL:Q.ampURL,startNewThread:async()=>E,switchToThread:async()=>E,ideClient:I2,connectedClientsService:new _01,commandRegistry:R,mcpService:Z.mcpService,mcpTrustHandler:S,showJetBrainsInstaller:!1,updateService:y,isDogfooding:!1,replayMode:{thread:V,typingEnabled:K,baseWpm:W,messageDelayMs:H,toolProgressDelayMs:z,exitDelayMs:U,showIndicator:N}}),await Z.asyncDispose(),process.exit(0)}catch(q){await Z.asyncDispose(),await ag(q,Y)}}async function nI8(J,Q,Y,X,G){dq(X,J);let Z=await cq(Q,J);try{let q=Z71(Y);if(!q)$71(Y);let V=q,K=await C5.getUserInfo({},{config:Z.configService}),W=K.ok?K.result:null,H=y41(J,W);if(!H&&!G)G$("Must specify either --visibility or --support");if(H&&G)G$("Cannot specify both --visibility and --support at the same time");if(H instanceof Error)G$(H.message);if(H)await Z.threadSyncService.updateThreadMeta(V,x41(H)),e5.write(h4.green("✓ ")+`Thread ${V} visibility changed to ${H}.
5146
+ `),await G.asyncDispose(),process.exit(0)}catch(Z){await G.asyncDispose();let q=`Failed to render thread as markdown: ${Z instanceof Error?Z.message:String(Z)}`;G$(q)}}async function iI8(J,Q,Y,X,G){dq(G,J);let Z=await cq(Q,J);try{let q=await Kv1(Y),V=await wj(q,Z),K=X.typing!==!1,W=parseInt(X.wpm||"120",10),H=parseInt(X.messageDelay||"1000",10),z=parseInt(X.toolProgressDelay||"800",10),U=parseInt(X.exitDelay||"3",10)*1000,N=X.indicator!==!1,M=Tu(Z),L=V.id;await Z.threadStorage.set(L,V);let O=await A3.getOrCreateForThread(M,L);await O.resume();let E=_61.fromWorker(O),I=new k61(Z.threadStorage),P=Q0.of([a0.file(process.cwd())]),R=B$1(void 0,P),S=new k41(Z.mcpService,Q.settings.getWorkspaceRootPath()),y=_41("0.0.1764129854-ge5da8d",Z.settingsStorage);await Sy1({codebaseContextService:Z.codebaseContextService,stdout:process.stdout,history:new B41,fuzzyServer:Z.fuzzyServer,settingsStorage:Z.settingsStorage,threadService:Z.threadService,threadHistoryService:Z.threadHistoryService,threadSyncService:Z.threadSyncService,planFileManager:Z.planFileManager,threadID:L,threadFuzzyIndexer:I,worker:E,workerDeps:M,configService:Z.configService,internalAPIClient:C5,ampURL:Q.ampURL,startNewThread:async()=>E,switchToThread:async()=>E,ideClient:I2,connectedClientsService:new _01,commandRegistry:R,mcpService:Z.mcpService,mcpTrustHandler:S,showJetBrainsInstaller:!1,updateService:y,isDogfooding:!1,replayMode:{thread:V,typingEnabled:K,baseWpm:W,messageDelayMs:H,toolProgressDelayMs:z,exitDelayMs:U,showIndicator:N}}),await Z.asyncDispose(),process.exit(0)}catch(q){await Z.asyncDispose(),await ag(q,Y)}}async function nI8(J,Q,Y,X,G){dq(X,J);let Z=await cq(Q,J);try{let q=Z71(Y);if(!q)$71(Y);let V=q,K=await C5.getUserInfo({},{config:Z.configService}),W=K.ok?K.result:null,H=y41(J,W);if(!H&&!G)G$("Must specify either --visibility or --support");if(H&&G)G$("Cannot specify both --visibility and --support at the same time");if(H instanceof Error)G$(H.message);if(H)await Z.threadSyncService.updateThreadMeta(V,x41(H)),e5.write(h4.green("✓ ")+`Thread ${V} visibility changed to ${H}.
5147
5147
  `);if(G){await wj(V,Z);let z=typeof G==="string"?G:void 0;await Mx0(Z.threadService,V,Z.configService,z),e5.write(h4.green("✓ ")+`Thread ${V} has been shared with Amp support. These thread reports will be aggregated and analysed.
5148
5148
  `)}await Z.asyncDispose(),process.exit(0)}catch(q){await Z.asyncDispose(),G$(`Failed to update thread: ${q instanceof Error?q.message:String(q)}`)}}async function aI8(J,Q,Y,X){dq(X,J);let G=await cq(Q,J),Z=Tu(G);try{let q=await Kv1(Y),K=(await wj(q,G)).messages.length-1,W=await A3.getOrCreateForThread(Z,q),H=await rR(W,G.threadSyncService,K);await Promise.all([G.threadSyncService.uploadThread(q),G.threadSyncService.uploadThread(H)]),await qv1(H),e5.write(`${H}
5149
5149
  `),await G.asyncDispose(),process.exit(0)}catch(q){Z$.write(`Error forking thread: ${q instanceof Error?q.message:String(q)}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sourcegraph/amp",
3
- "version": "0.0.1764115312-g9a6608",
3
+ "version": "0.0.1764129854-ge5da8d",
4
4
  "description": "CLI for Amp, the frontier coding agent from Sourcegraph.",
5
5
  "homepage": "https://ampcode.com/",
6
6
  "author": {