@sourcegraph/amp 0.0.1779296280-g014378 → 0.0.1779313683-gf89f27

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 +12 -12
  2. package/package.json +2 -2
package/dist/main.js CHANGED
@@ -914,7 +914,7 @@ Image files are handled as attachments and displayed in the UI.`);let E=D.split(
914
914
  `;$.push(B)}return $.join("")}function IyA(A){if(A.startsWith("/"))return!0;if(A.match(/^[A-Za-z]:[\\]/)||A.match(/^[A-Za-z]:[/]/))return!0;return!1}function HyA(A){return WyA.includes(B1.basename(A))}var WyA;var aK=o(()=>{Q4();p0();RA();XE4();hK();Ip();xQ();mT();bQ();WyA=["yarn.lock","package-lock.json","pnpm-lock.yaml","go.sum","go.mod","Cargo.lock","poetry.lock","Pipfile.lock","composer.lock","Gemfile.lock"]});function oK(A,Q="result"){if(A===null)return`<${Q}>null</${Q}>`;if(A===void 0)return`<${Q}>undefined</${Q}>`;if(typeof A==="string")return`<${Q}>${A}</${Q}>`;if(typeof A==="number"||typeof A==="boolean")return`<${Q}>${A}</${Q}>`;if(Array.isArray(A))return`<${Q}>${JSON.stringify(A)}</${Q}>`;if(typeof A==="object")return Object.entries(A).map(([$,B])=>{if(typeof B==="object"&&B!==null&&!Array.isArray(B)){let D=oK(B,$);return`<${$}>
915
915
  ${D}
916
916
  </${$}>`}return oK(B,$)}).join(`
917
- `);return`<${Q}>${String(A)}</${Q}>`}function al(A){return qyA(A?.["experimental.agentMode"])}function qyA(A){return A??"smart"}function XZ(A,Q){let B=Q.agentMode??hd(Q)??al(A),D=Y44(A,B);return{model:D?D:GK(B),agentMode:B}}var Dk=o(()=>{VK();y5();a4()});function GE4(A){return A+ ++NyA}var NyA=0;function VE4(A){if(!A._regex)try{A._regex=new RegExp(A.pattern,A.caseInsensitive?"gi":"g")}catch(Q){P.warn("Error compiling regex",{pattern:A.id,error:Q}),A._regex=/$^/}return A._regex}var KE4;var zE4=o(()=>{p0();KE4=[{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:"bitbucket-pat",category:"bitbucket",title:"Bitbucket Personal Access Token",pattern:String.raw`(bbpat-[A-Za-z0-9]{20,200})`,keywords:["bbpat-"]},{id:"bitbucket-repo-access-token",category:"bitbucket",title:"Bitbucket Repository Access Token",pattern:String.raw`(bbrat-[A-Za-z0-9]{20,200})`,keywords:["bbrat-"]},{id:"bitbucket-dc-http-token",category:"bitbucket",title:"Bitbucket DC/Server HTTP Access Token",pattern:String.raw`(?:[a-z0-9_ .,-]{0,25}bitbucket[a-z0-9_ .,-]{0,25})(?:=|>|:=|\|\|:|<=|=>|:).{0,5}['"]([A-Za-z0-9+/]{40,80}={0,2})['"]`,keywords:["bitbucket"]},{id:"aws-access-key-id",category:"aws",title:"AWS Access Key ID",pattern:String.raw`((A3T[A-Z0-9]|AKIA|ASIA)[A-Z0-9]{16})`,keywords:["A3T","AKIA","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:"cloudflare-api-token",category:"unknown",title:"Cloudflare API Token",pattern:String.raw`\b(cfut_[A-Za-z0-9]{48})\b`,keywords:["cfut_"]},{id:"e2b-api-key",category:"unknown",title:"E2B API Key",pattern:String.raw`\b(e2b_[a-f0-9]{40})\b`,keywords:["e2b_"]},{id:"google-api-key",category:"google",title:"Google API Key",pattern:String.raw`\b(AIza[0-9A-Za-z_-]{35,40})\b`,keywords:["AIza"]},{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:"secret-value",category:"unknown",title:"Unknown API Key",pattern:String.raw`(?:[a-z0-9_ .,-]{0,25}[-_](?: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))[a-z0-9+/_-]{6,128})['"]?(?=\s|$|[;,\]})'"])`,keywords:["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|string|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 CyA(A){if(!A||typeof A!=="string")return A;let Q=A.replace(wyA,"");if(Q.length!==A.length){let $=A.length-Q.length;P.info("Invisible Unicode tag characters removed during sanitization",{removedCount:$})}return Q}function Bm0(A){if(!A||typeof A!=="string")return A;let Q=z$0.get(A);if(Q!==void 0)return Q;let $=CyA(A);for(let B of KE4){if(!B.keywords.some((J)=>B.caseInsensitive?$.toLowerCase().includes(J.toLowerCase()):$.includes(J)))continue;let D=VE4(B);$=$.replace(D,(J,F)=>{return J.replace(F,`[REDACTED:${B.id}]`)})}if(A.length<=LyA){if(z$0.size>=MyA)z$0.clear();z$0.set(A,$)}return $}function I$0(A,Q){if(!A||typeof A==="number"||typeof A==="boolean")return A;if(typeof A==="string")return Q(A);if(Array.isArray(A))return A.map(($)=>{if(typeof $==="string")return Q($);else if($&&typeof $==="object")return I$0($,Q);return $});if(A&&typeof A==="object"){if("type"in A&&(A.type==="base64"||A.type==="image")&&"data"in A)return{...A};if("isImage"in A&&A.isImage===!0&&"content"in A&&typeof A.content==="string"){let $={};for(let[B,D]of Object.entries(A))if(B==="content")$[B]=D;else $[B]=I$0(D,Q);return $}}return Object.fromEntries(Object.entries(A).map(([$,B])=>[$,I$0(B,Q)]))}function XD(A){return I$0(A,Bm0)}var wyA,MyA=2000,LyA=512000,z$0;var ol=o(()=>{p0();zE4();wyA=/[\uDB40][\uDC00-\uDC7F]/g;z$0=new Map});function OyA(A){return A?A.length>=H$0:!1}function Jk(A){if(A.nextMessageId===void 0)A.nextMessageId=0;return A.nextMessageId++}function jyA(A,Q){let $=Dm0(A["~debug"]?.lastInferenceUsage,Q);if(!$)return;A["~debug"]={...A["~debug"]??{},lastInferenceUsage:$}}function Dm0(A,Q){if(!A)return Q;if(!Q)return A;let $=(D,J)=>Math.max(D,J),B=(D,J)=>{if(J===null)return D;if(D===null)return J;return Math.max(D,J)};return{model:Q.model??A.model,maxInputTokens:$(A.maxInputTokens,Q.maxInputTokens),inputTokens:$(A.inputTokens,Q.inputTokens),outputTokens:$(A.outputTokens,Q.outputTokens),cacheCreationInputTokens:B(A.cacheCreationInputTokens,Q.cacheCreationInputTokens),cacheReadInputTokens:B(A.cacheReadInputTokens,Q.cacheReadInputTokens),totalInputTokens:$(A.totalInputTokens,Q.totalInputTokens),thinkingBudget:Q.thinkingBudget??A.thinkingBudget,timestamp:Q.timestamp??A.timestamp}}function IE4(A,Q=new Date){return($)=>{switch($.v++,A.type){case"cancelled":{W$0($);let B=$.messages.at(-1);if(B?.role==="user"){let D=B.content.findLast((J)=>J.type==="tool_result");if(D)D.run.status="cancelled"}break}case"user:message:interrupt":{let B=$.messages[A.messageIndex];if(B?.role==="user")B.interrupted=!0;break}case"user:message:append-content":{let B=$.messages.find((D)=>D.messageId===A.messageId);if(B?.role==="user")B.content.push(...JA(A.content));break}case"thread:truncate":{if($.messages.splice(A.fromIndex),$.relationships){if($.relationships=$.relationships.filter((B)=>B.messageIndex===void 0||B.messageIndex<A.fromIndex),$.relationships.length===0)$.relationships=void 0}break}case"user:message":{if(W$0($),$.archived)$.archived=!1;let B={role:"user",...A.message,messageId:Jk($),content:A.message.content??[]},D=XD(B);if(A.index!==void 0){if(!$.messages[A.index])throw Error(`user message at index ${A.index} not found`);let J=$.messages[A.index];if($.messages.filter((E)=>E.role==="user")[0]===J&&B.agentMode&&!$.mainThreadID)$.agentMode=B.agentMode;$.messages.splice(A.index,$.messages.length-A.index,D)}else{let J=A5($)===0;if((!$.agentMode||J)&&B.agentMode&&!$.mainThreadID)$.agentMode=B.agentMode;if(J&&A.reasoningEffort!==void 0&&!$.mainThreadID&&C2($.agentMode,A.reasoningEffort))$.reasoningEffort=A.reasoningEffort;if($.messages.push(D),$.draft)$.draft=void 0}break}case"user:message-queue:dequeue":{if(W$0($),!$.queuedMessages)return;let[B,...D]=$.queuedMessages;if(!B)return;$.messages.push(B.queuedMessage),$.queuedMessages=D;break}case"user:tool-input":{if(!E7($,A.toolUse)){P.debug(`Ignoring user:tool-input delta for missing tool use ${A.toolUse} (likely deleted due to thread edit/truncation)`);break}let D=JA(bd($,A.toolUse));if(!D){P.debug(`Ignoring user:tool-input delta for missing tool result block ${A.toolUse} (likely deleted due to thread edit/truncation)`);break}D.userInput=A.value;break}case"tool:data":{if(!zT($,A.toolUse)){P.debug(`Ignoring tool:data delta for missing tool use ${A.toolUse} (likely deleted due to thread edit/truncation)`);break}let D=JA(XD(A.data));WE4($,A.toolUse,D);break}case"tool:processed":{let B=zT($,A.toolUse);if(!B){P.debug(`Ignoring tool:processed delta for missing tool use ${A.toolUse} (likely deleted due to thread edit/truncation)`);break}let D=B.block.input;B.block.input=A.newArgs,B.message.originalToolUseInput={...B.message.originalToolUseInput,[A.toolUse]:D};break}case"assistant:message":{let B=$.messages.findLastIndex((Z)=>Z.role==="assistant"),D=B===-1?void 0:$.messages[B],J=B===$.messages.length-1,F=D?.role==="assistant"?D.content.filter((Z)=>Z.type==="tool_use").map((Z)=>Z.id):[];W$0($);let Y=B===-1?void 0:$.messages[B];if(J&&F.length>0&&Y?.role==="assistant")for(let Z=$.messages.length-1;Z>=0;Z--){let U=$.messages[Z];if(U?.role==="user"){if(U.content=U.content.filter((X)=>{if(X.type==="tool_result"&&F.includes(X.toolUseID))return!1;return!0}),U.content.length===0)$.messages.splice(Z,1)}}let E={...A.message,messageId:Jk($)};$.messages.push(JA(E));break}case"assistant:message-update":{let B=JA(A.message),D=$.messages.at(-1);if(D?.role==="assistant"){let J=Dm0(D.usage,B.usage);$.messages[$.messages.length-1]={...B,messageId:D.messageId,usage:J}}else $.messages.push({...B,messageId:Jk($)});break}case"inference:completed":{if(jyA($,A.usage),!$.env)$.env={initial:{}};if(!$.env.initial.tags)$.env.initial.tags=[];if($.env.initial.tags=$.env.initial.tags.filter((B)=>B!=="model:undefined"),A.model){let B=`model:${A.model}`;if(!$.env.initial.tags.includes(B))$.env.initial.tags=[...$.env.initial.tags,B]}if(A.usage){let B=JA(D9($,"assistant"));if(B){let D=Dm0(B.usage,A.usage);if(D)B.usage=D}}break}case"title":{$.title=A.value||void 0;break}case"max-tokens":{$.maxTokens=A.value||void 0;break}case"main-thread":{$.mainThreadID=A.value||void 0;break}case"agent-mode":{if(A5($)>0)throw Error("(bug) cannot change agentMode after first message");$.agentMode=A.mode;break}case"reasoning-effort":{if(A5($)>0)throw Error("(bug) cannot change reasoningEffort after first message");if(A.effort!==void 0&&$.agentMode===void 0)throw Error("(bug) cannot set reasoningEffort before agentMode");if(A.effort!==void 0&&!C2($.agentMode,A.effort))throw Error(`(bug) reasoningEffort ${A.effort} is not allowed for mode ${$.agentMode}`);$.reasoningEffort=A.effort;break}case"environment":{$.env=JA(A.env);break}case"user:message-queue:enqueue":{if(!$.queuedMessages)$.queuedMessages=[];if(OyA($.queuedMessages))break;let B={role:"user",...A.message,messageId:Jk($),content:A.message.content??[]},D=XD(B);$.queuedMessages.push({id:GE4("queued-"),queuedMessage:JA(D)});break}case"user:message-queue:discard":{if(A.id===void 0){$.queuedMessages=[];break}let B=$.queuedMessages?.findIndex((D)=>D.id===A.id);if(B===void 0)throw Error(`queued message with id ${A.id} not found`);$?.queuedMessages?.splice(B,1);break}case"info:manual-bash-invocation":{$.messages.push({role:"info",messageId:Jk($),content:[{type:"manual_bash_invocation",args:JA(A.args),toolRun:JA(A.toolRun),hidden:A.hidden}]});break}case"clearPendingNavigation":{$.pendingNavigation=void 0;break}case"setPendingNavigation":{$.pendingNavigation=A.threadID;break}case"relationship":{if(!$.relationships)$.relationships=[];if(!$.relationships.some((D)=>D.threadID===A.relationship.threadID&&D.type===A.relationship.type&&D.role===A.relationship.role))$.relationships.push(JA(A.relationship));break}case"draft":{if($.draft=JA(A.content),A.autoSubmit)$.autoSubmitDraft=!0;break}case"trace:start":{PyA($,A.span);break}case"trace:end":{uyA($,A.span,Q);break}case"trace:event":{_yA($,A.span,A.event);break}case"trace:attributes":{TyA($,A.span,A.attributes);break}}}}function W$0(A){let Q=A.messages.findLastIndex((Y)=>Y.role==="assistant"),$=Q===-1?void 0:JA(A.messages[Q]);if(!$)return;if($.role!=="assistant")return;let B=!1;if($.state.type==="streaming")$.state={type:"cancelled"},B=!0;else if($.state.type==="complete"){if($.content.some((E)=>E.type==="tool_use"&&!l5(E)))$.state={type:"cancelled"},B=!0}let D=RyA(A,Q),J=$.content.some((Y)=>Y.type==="tool_use"&&!D.has(Y.id));if(!B&&!J)return;let F=[];for(let Y=0;Y<$.content.length;Y++){let E=$.content[Y];if(E?.type!=="tool_use")continue;if(!l5(E)){P.debug(`Cleaning up incomplete tool_use ${E.id}`,{name:"markPriorStreamingAssistantMessageAsCancelled",threadID:A.id,blockID:E.id});let Z={type:"tool_use",id:E.id,name:E.name,complete:!0,input:E.inputIncomplete??E.input??{}};$.content[Y]=Z}if(!D.has(E.id))F.push(E.id)}for(let Y of F)WE4(A,Y,{status:"cancelled"})}function WE4(A,Q,$){let B,D=zT(A,Q);if(D){let F=D.messageIndex;for(let Y=F+1;Y<A.messages.length;Y++){let E=A.messages[Y];if(E?.role==="user"){B=E;break}}}if(!B)B={role:"user",messageId:Jk(A),content:[]},A.messages.push(B);let J=B?.content.find((F)=>F.type==="tool_result"&&F.toolUseID===Q);if(J){if(f3(J.run.status)&&!f3($.status))return;J.run=JA($)}else J={type:"tool_result",toolUseID:Q,run:JA($)},B.content.push(J)}function RyA(A,Q){let $=new Map;for(let B=Q+1;B<A.messages.length;B++){let D=A.messages[B];if(D?.role!=="user")continue;for(let J of D.content)if(J.type==="tool_result")$.set(J.toolUseID,J);break}return $}function PyA(A,Q){if(!A.meta)A.meta={};if(!A.meta.traces)A.meta.traces=[];let $=A.meta.traces.find((B)=>B.id===Q.id);if($){if($.startTime===void 0)$.startTime=Q.startTime;return}A.meta.traces.push(JA({...Q}))}function uyA(A,Q,$){if(!A.meta)A.meta={};if(!A.meta.traces)A.meta.traces=[];let B=A.meta.traces.find((J)=>J.id===Q.id),D=Q.endTime??$.toISOString();if(B){if(B.endTime===void 0)B.endTime=D}}function _yA(A,Q,$){if(!A.meta?.traces)return;let B=A.meta.traces.find((D)=>D.id===Q);if(!B)return;if(!B.events)B.events=[];B.events.push($)}function TyA(A,Q,$){if(!A.meta?.traces)return;let B=A.meta.traces.find((D)=>D.id===Q);if(!B)return;B.attributes={...B.attributes,...$}}function eL(A){try{return l50(A.replace(/\\+$/,"")+'"')}catch{return l50(A)}}function HE4(A){let Q=i50(A),$;try{$=eL(A)}catch{$=Q}return{input:Q,inputIncomplete:vyA($)?$:Q}}function vyA(A){return typeof A==="object"&&A!==null&&!Array.isArray(A)}var H$0=5;var AO=o(()=>{cQ();p0();a5();ol();a4()});function WY(A){let Q=[];if(A.currentlyVisibleFiles){if(A.currentlyVisibleFiles.length>0)Q.push(`Currently visible files user has open: ${A.currentlyVisibleFiles.map(l3).join(", ")}`)}if(A.runningTerminalCommands&&A.runningTerminalCommands.length>0)Q.push(`Currently running terminal commands:
917
+ `);return`<${Q}>${String(A)}</${Q}>`}function al(A){return qyA(A?.["experimental.agentMode"])}function qyA(A){return A??"smart"}function XZ(A,Q){let B=Q.agentMode??hd(Q)??al(A),D=Y44(A,B);return{model:D?D:GK(B),agentMode:B}}var Dk=o(()=>{VK();y5();a4()});function GE4(A){return A+ ++NyA}var NyA=0;function VE4(A){if(!A._regex)try{A._regex=new RegExp(A.pattern,A.caseInsensitive?"gi":"g")}catch(Q){P.warn("Error compiling regex",{pattern:A.id,error:Q}),A._regex=/$^/}return A._regex}var KE4;var zE4=o(()=>{p0();KE4=[{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:"bitbucket-pat",category:"bitbucket",title:"Bitbucket Personal Access Token",pattern:String.raw`(bbpat-[A-Za-z0-9]{20,200})`,keywords:["bbpat-"]},{id:"bitbucket-repo-access-token",category:"bitbucket",title:"Bitbucket Repository Access Token",pattern:String.raw`(bbrat-[A-Za-z0-9]{20,200})`,keywords:["bbrat-"]},{id:"bitbucket-dc-http-token",category:"bitbucket",title:"Bitbucket DC/Server HTTP Access Token",pattern:String.raw`(?:[a-z0-9_ .,-]{0,25}bitbucket[a-z0-9_ .,-]{0,25})(?:=|>|:=|\|\|:|<=|=>|:).{0,5}['"]([A-Za-z0-9+/]{40,80}={0,2})['"]`,keywords:["bitbucket"]},{id:"aws-access-key-id",category:"aws",title:"AWS Access Key ID",pattern:String.raw`((A3T[A-Z0-9]|AKIA|ASIA)[A-Z0-9]{16})`,keywords:["A3T","AKIA","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:"cloudflare-api-token",category:"unknown",title:"Cloudflare API Token",pattern:String.raw`\b(cfut_[A-Za-z0-9]{48})\b`,keywords:["cfut_"]},{id:"e2b-api-key",category:"unknown",title:"E2B API Key",pattern:String.raw`\b(e2b_[a-f0-9]{40})\b`,keywords:["e2b_"]},{id:"google-api-key",category:"google",title:"Google API Key",pattern:String.raw`\b(AIza[0-9A-Za-z_-]{35,40})\b`,keywords:["AIza"]},{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:"secret-value",category:"unknown",title:"Unknown API Key",pattern:String.raw`(?:[a-z0-9_ .,-]{0,25}[-_](?: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))[a-z0-9+/_-]{6,128})['"]?(?=\s|$|[;,\]})'"])`,keywords:["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|string|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 CyA(A){if(!A||typeof A!=="string")return A;let Q=A.replace(wyA,"");if(Q.length!==A.length){let $=A.length-Q.length;P.info("Invisible Unicode tag characters removed during sanitization",{removedCount:$})}return Q}function Bm0(A){if(!A||typeof A!=="string")return A;let Q=z$0.get(A);if(Q!==void 0)return Q;let $=CyA(A);for(let B of KE4){if(!B.keywords.some((J)=>B.caseInsensitive?$.toLowerCase().includes(J.toLowerCase()):$.includes(J)))continue;let D=VE4(B);$=$.replace(D,(J,F)=>{return J.replace(F,`[REDACTED:${B.id}]`)})}if(A.length<=LyA){if(z$0.size>=MyA)z$0.clear();z$0.set(A,$)}return $}function I$0(A,Q){if(!A||typeof A==="number"||typeof A==="boolean")return A;if(typeof A==="string")return Q(A);if(Array.isArray(A))return A.map(($)=>{if(typeof $==="string")return Q($);else if($&&typeof $==="object")return I$0($,Q);return $});if(A&&typeof A==="object"){if("type"in A&&(A.type==="base64"||A.type==="image")&&"data"in A)return{...A};if("isImage"in A&&A.isImage===!0&&"content"in A&&typeof A.content==="string"){let $={};for(let[B,D]of Object.entries(A))if(B==="content")$[B]=D;else $[B]=I$0(D,Q);return $}}return Object.fromEntries(Object.entries(A).map(([$,B])=>[$,I$0(B,Q)]))}function XD(A){return I$0(A,Bm0)}var wyA,MyA=2000,LyA=512000,z$0;var ol=o(()=>{p0();zE4();wyA=/[\uDB40][\uDC00-\uDC7F]/g;z$0=new Map});function OyA(A){return A?A.length>=H$0:!1}function Jk(A){if(A.nextMessageId===void 0)A.nextMessageId=0;return A.nextMessageId++}function jyA(A,Q){let $=Dm0(A["~debug"]?.lastInferenceUsage,Q);if(!$)return;A["~debug"]={...A["~debug"]??{},lastInferenceUsage:$}}function Dm0(A,Q){if(!A)return Q;if(!Q)return A;let $=(D,J)=>Math.max(D,J),B=(D,J)=>{if(J===null)return D;if(D===null)return J;return Math.max(D,J)};return{model:Q.model??A.model,maxInputTokens:$(A.maxInputTokens,Q.maxInputTokens),inputTokens:$(A.inputTokens,Q.inputTokens),outputTokens:$(A.outputTokens,Q.outputTokens),cacheCreationInputTokens:B(A.cacheCreationInputTokens,Q.cacheCreationInputTokens),cacheReadInputTokens:B(A.cacheReadInputTokens,Q.cacheReadInputTokens),totalInputTokens:$(A.totalInputTokens,Q.totalInputTokens),thinkingBudget:Q.thinkingBudget??A.thinkingBudget,timestamp:Q.timestamp??A.timestamp}}function IE4(A,Q=new Date){return($)=>{switch($.v++,A.type){case"cancelled":{W$0($);let B=$.messages.at(-1);if(B?.role==="user"){let D=B.content.findLast((J)=>J.type==="tool_result");if(D)D.run.status="cancelled"}break}case"user:message:interrupt":{let B=$.messages[A.messageIndex];if(B?.role==="user")B.interrupted=!0;break}case"user:message:append-content":{let B=$.messages.find((D)=>D.messageId===A.messageId);if(B?.role==="user")B.content.push(...JA(A.content));break}case"thread:truncate":{if($.messages.splice(A.fromIndex),$.relationships){if($.relationships=$.relationships.filter((B)=>B.messageIndex===void 0||B.messageIndex<A.fromIndex),$.relationships.length===0)$.relationships=void 0}break}case"user:message":{if(W$0($),$.archived)$.archived=!1;let B={role:"user",...A.message,messageId:Jk($),content:A.message.content??[]},D=XD(B);if(A.index!==void 0){if(!$.messages[A.index])throw Error(`user message at index ${A.index} not found`);let J=$.messages[A.index];if($.messages.filter((E)=>E.role==="user")[0]===J&&B.agentMode&&!$.mainThreadID)$.agentMode=B.agentMode;$.messages.splice(A.index,$.messages.length-A.index,D)}else{let J=A5($)===0;if((!$.agentMode||J)&&B.agentMode&&!$.mainThreadID)$.agentMode=B.agentMode;if(J&&A.reasoningEffort!==void 0&&!$.mainThreadID&&C2($.agentMode,A.reasoningEffort))$.reasoningEffort=A.reasoningEffort;if($.messages.push(D),$.draft)$.draft=void 0}break}case"user:message-queue:dequeue":{if(W$0($),!$.queuedMessages)return;let[B,...D]=$.queuedMessages;if(!B)return;$.messages.push(B.queuedMessage),$.queuedMessages=D;break}case"user:tool-input":{if(!E7($,A.toolUse)){P.debug(`Ignoring user:tool-input delta for missing tool use ${A.toolUse} (likely deleted due to thread edit/truncation)`);break}let D=JA(bd($,A.toolUse));if(!D){P.debug(`Ignoring user:tool-input delta for missing tool result block ${A.toolUse} (likely deleted due to thread edit/truncation)`);break}D.userInput=A.value;break}case"tool:data":{if(!zT($,A.toolUse)){P.debug(`Ignoring tool:data delta for missing tool use ${A.toolUse} (likely deleted due to thread edit/truncation)`);break}let D=JA(XD(A.data));WE4($,A.toolUse,D);break}case"tool:processed":{let B=zT($,A.toolUse);if(!B){P.debug(`Ignoring tool:processed delta for missing tool use ${A.toolUse} (likely deleted due to thread edit/truncation)`);break}let D=B.block.input;B.block.input=A.newArgs,B.message.originalToolUseInput={...B.message.originalToolUseInput,[A.toolUse]:D};break}case"assistant:message":{let B=$.messages.findLastIndex((Z)=>Z.role==="assistant"),D=B===-1?void 0:$.messages[B],J=B===$.messages.length-1,F=D?.role==="assistant"?D.content.filter((Z)=>Z.type==="tool_use").map((Z)=>Z.id):[];W$0($);let Y=B===-1?void 0:$.messages[B];if(J&&F.length>0&&Y?.role==="assistant")for(let Z=$.messages.length-1;Z>=0;Z--){let U=$.messages[Z];if(U?.role==="user"){if(U.content=U.content.filter((X)=>{if(X.type==="tool_result"&&F.includes(X.toolUseID))return!1;return!0}),U.content.length===0)$.messages.splice(Z,1)}}let E={...A.message,messageId:Jk($)};$.messages.push(JA(E));break}case"assistant:message-update":{let B=JA(A.message),D=$.messages.at(-1);if(D?.role==="assistant"){let J=Dm0(D.usage,B.usage);$.messages[$.messages.length-1]={...B,messageId:D.messageId,usage:J}}else $.messages.push({...B,messageId:Jk($)});break}case"inference:completed":{if(jyA($,A.usage),!$.env)$.env={initial:{}};if(!$.env.initial.tags)$.env.initial.tags=[];if($.env.initial.tags=$.env.initial.tags.filter((B)=>B!=="model:undefined"),A.model){let B=`model:${A.model}`;if(!$.env.initial.tags.includes(B))$.env.initial.tags=[...$.env.initial.tags,B]}if(A.usage){let B=JA(D9($,"assistant"));if(B){let D=Dm0(B.usage,A.usage);if(D)B.usage=D}}break}case"title":{$.title=A.value||void 0;break}case"max-tokens":{$.maxTokens=A.value||void 0;break}case"main-thread":{$.mainThreadID=A.value||void 0;break}case"agent-mode":{if(A5($)>0)throw Error("(bug) cannot change agentMode after first message");$.agentMode=A.mode;break}case"reasoning-effort":{if(A5($)>0)throw Error("(bug) cannot change reasoningEffort after first message");if(A.effort!==void 0&&$.agentMode===void 0)throw Error("(bug) cannot set reasoningEffort before agentMode");if(A.effort!==void 0&&!C2($.agentMode,A.effort))throw Error(`(bug) reasoningEffort ${A.effort} is not allowed for mode ${$.agentMode}`);$.reasoningEffort=A.effort;break}case"environment":{$.env=JA(A.env);break}case"user:message-queue:enqueue":{if(!$.queuedMessages)$.queuedMessages=[];if(OyA($.queuedMessages))break;let B={role:"user",...A.message,messageId:Jk($),content:A.message.content??[]},D=XD(B);$.queuedMessages.push({id:GE4("queued-"),queuedMessage:JA(D)});break}case"user:message-queue:discard":{if(A.id===void 0){$.queuedMessages=[];break}let B=$.queuedMessages?.findIndex((D)=>D.id===A.id);if(B===void 0)throw Error(`queued message with id ${A.id} not found`);$?.queuedMessages?.splice(B,1);break}case"info:manual-bash-invocation":{$.messages.push({role:"info",messageId:Jk($),content:[{type:"manual_bash_invocation",args:JA(A.args),toolRun:JA(A.toolRun),hidden:A.hidden}]});break}case"clearPendingNavigation":{$.pendingNavigation=void 0;break}case"setPendingNavigation":{$.pendingNavigation=A.threadID;break}case"relationship":{if(!$.relationships)$.relationships=[];if(!$.relationships.some((D)=>D.threadID===A.relationship.threadID&&D.type===A.relationship.type&&D.role===A.relationship.role))$.relationships.push(JA(A.relationship));break}case"draft":{if($.draft=JA(A.content),A.autoSubmit)$.autoSubmitDraft=!0;break}case"trace:start":{PyA($,A.span);break}case"trace:end":{uyA($,A.span,Q);break}case"trace:event":{_yA($,A.span,A.event);break}case"trace:attributes":{TyA($,A.span,A.attributes);break}}}}function W$0(A){let Q=A.messages.findLastIndex((Y)=>Y.role==="assistant"),$=Q===-1?void 0:JA(A.messages[Q]);if(!$)return;if($.role!=="assistant")return;let B=!1;if($.state.type==="streaming"){if($.content.length===0){A.messages.splice(Q,1);return}$.state={type:"cancelled"},B=!0}else if($.state.type==="complete"){if($.content.some((E)=>E.type==="tool_use"&&!l5(E)))$.state={type:"cancelled"},B=!0}let D=RyA(A,Q),J=$.content.some((Y)=>Y.type==="tool_use"&&!D.has(Y.id));if(!B&&!J)return;let F=[];for(let Y=0;Y<$.content.length;Y++){let E=$.content[Y];if(E?.type!=="tool_use")continue;if(!l5(E)){P.debug(`Cleaning up incomplete tool_use ${E.id}`,{name:"markPriorStreamingAssistantMessageAsCancelled",threadID:A.id,blockID:E.id});let Z={type:"tool_use",id:E.id,name:E.name,complete:!0,input:E.inputIncomplete??E.input??{}};$.content[Y]=Z}if(!D.has(E.id))F.push(E.id)}for(let Y of F)WE4(A,Y,{status:"cancelled"})}function WE4(A,Q,$){let B,D=zT(A,Q);if(D){let F=D.messageIndex;for(let Y=F+1;Y<A.messages.length;Y++){let E=A.messages[Y];if(E?.role==="user"){B=E;break}}}if(!B)B={role:"user",messageId:Jk(A),content:[]},A.messages.push(B);let J=B?.content.find((F)=>F.type==="tool_result"&&F.toolUseID===Q);if(J){if(f3(J.run.status)&&!f3($.status))return;J.run=JA($)}else J={type:"tool_result",toolUseID:Q,run:JA($)},B.content.push(J)}function RyA(A,Q){let $=new Map;for(let B=Q+1;B<A.messages.length;B++){let D=A.messages[B];if(D?.role!=="user")continue;for(let J of D.content)if(J.type==="tool_result")$.set(J.toolUseID,J);break}return $}function PyA(A,Q){if(!A.meta)A.meta={};if(!A.meta.traces)A.meta.traces=[];let $=A.meta.traces.find((B)=>B.id===Q.id);if($){if($.startTime===void 0)$.startTime=Q.startTime;return}A.meta.traces.push(JA({...Q}))}function uyA(A,Q,$){if(!A.meta)A.meta={};if(!A.meta.traces)A.meta.traces=[];let B=A.meta.traces.find((J)=>J.id===Q.id),D=Q.endTime??$.toISOString();if(B){if(B.endTime===void 0)B.endTime=D}}function _yA(A,Q,$){if(!A.meta?.traces)return;let B=A.meta.traces.find((D)=>D.id===Q);if(!B)return;if(!B.events)B.events=[];B.events.push($)}function TyA(A,Q,$){if(!A.meta?.traces)return;let B=A.meta.traces.find((D)=>D.id===Q);if(!B)return;B.attributes={...B.attributes,...$}}function eL(A){try{return l50(A.replace(/\\+$/,"")+'"')}catch{return l50(A)}}function HE4(A){let Q=i50(A),$;try{$=eL(A)}catch{$=Q}return{input:Q,inputIncomplete:vyA($)?$:Q}}function vyA(A){return typeof A==="object"&&A!==null&&!Array.isArray(A)}var H$0=5;var AO=o(()=>{cQ();p0();a5();ol();a4()});function WY(A){let Q=[];if(A.currentlyVisibleFiles){if(A.currentlyVisibleFiles.length>0)Q.push(`Currently visible files user has open: ${A.currentlyVisibleFiles.map(l3).join(", ")}`)}if(A.runningTerminalCommands&&A.runningTerminalCommands.length>0)Q.push(`Currently running terminal commands:
918
918
  ${A.runningTerminalCommands.join(`
919
919
  `)}`);if(A.activeEditor)Q.push(`Currently active editor: ${l3(A.activeEditor)}`);if(A.activeEditor&&!qp(A.activeEditor)){if(A.selectionRange)Q.push(`Selection range: ${A.selectionRange.start.line}:${A.selectionRange.start.column}-${A.selectionRange.end.line}:${A.selectionRange.end.column}`);else if(A.cursorLocation){if(Q.push(`Current cursor location: ${A.cursorLocation.line}:${A.cursorLocation.column}`),A.cursorLocationLine)Q.push(`Contents of line on which cursor is: \`${A.cursorLocationLine}\``)}}if(A.aggmanContext){let $=A.aggmanContext;if(Q.push(`Current URL the user is on: ${$.currentURL}`),$.recentUnreadThreads&&$.recentUnreadThreads.length>0){let B=$.recentUnreadThreads.map((D)=>{let J=D.projectName?.trim();return J?`- ${D.title} [${J}] (${D.threadID})`:`- ${D.title} (${D.threadID})`});Q.push(`Recent unread threads by the user (most recent first):
920
920
  ${B.join(`
@@ -2656,7 +2656,7 @@ Set \`replace_all\` to true to replace all occurrences of \`old_str\` in the fil
2656
2656
  If you need to replace the entire contents of a file, use \`${x2}\` instead, since it requires less tokens for the same action (since you won't have to repeat the contents before replacing).
2657
2657
 
2658
2658
  If you see \`[REDACTED:_____]\` in your inputs and edits fail, Amp's secret redaction may have changed the text; ask the user to manually make the edit.
2659
- `,TO4={spec:{name:N2,description:K33,inputSchema:x.toJSONSchema(aa0),source:"builtin",executionProfile:{resourceKeys:(A)=>{if(A&&typeof A==="object"&&"path"in A&&typeof A.path==="string")return[{key:A.path,mode:"write"}];return[]}}},fn:RO4}});function I33(A){if(A.before===void 0&&A.after===void 0)throw Error("unreachable");if(A.before===null&&A.after===null)throw Error("unreachable")}async function W33(A,Q,$,B){let D={};D.before=await vO4($);let J=await B();return D.after=await vO4($),I33(D),await A.record({toolUse:Q,uri:$,...D}),J}async function UF0(A,Q,$,B,D){await W33(A,Q,$,()=>X7(GA($),B,{encoding:"utf8",signal:D?.signal}))}function iS(A,Q,$,B){return A.record({toolUse:Q,uri:$,...B})}async function vO4(A){try{return await hA(GA(A),{encoding:"utf8"})}catch(Q){if(w5(Q))return null;throw Q}}function oa0(A,Q,$){let B=new Map,D=(F)=>{let Y;for(let[E,Z]of B.entries())for(let[U,X]of Z.entries()){if(!B1.equalURIs(U,F))continue;if(!Y||X.timestamp<Y.timestamp)Y=X}return Y},J=async({filesFilter:F,toolUsesToRevert:Y,pruneRevertedToolUses:E})=>{let Z=new $Q,U=new Map;for(let[V,K]of B.entries()){let I=Y?Y.has(V):!0;for(let[z,W]of K.entries()){if(F&&!F(z))continue;if(W.reverted)continue;let H=Z.get(z)||{changesAfterKeep:[]};if(!I){if(!H.latestKeepChange||W.timestamp>H.latestKeepChange.timestamp)H.latestKeepChange=W}else H.changesAfterKeep.push(W),U.set(W,V);Z.set(z,H)}}let X=Array.from(Z.entries()).filter(([,{changesAfterKeep:V}])=>V.length>0);if(await _Q0(X,H33,async([V,{latestKeepChange:K,changesAfterKeep:I}])=>{try{let z=I.reduce((H,q)=>q.timestamp<H.timestamp?q:H),W=K?K.after:z.isNewFile?null:z.before;await $(V,W);for(let H of I){H.reverted=!0;let q=U.get(H);if(q)try{let N={toolUseID:q,fileChangeID:H.id};await A.store(Q,N,H)}catch(N){P.error(`Error updating backup for file ${V}:`,N)}}}catch(z){P.error(`Error reverting file ${V}:`,z)}}),E&&Y)for(let V of Y)B.delete(V)};return{async getAllRecords(){return B},async record(F){if(!F.toolUse)return;let Y=B.get(F.toolUse);if(!Y)Y=new $Q,B.set(F.toolUse,Y);let E=Y.get(F.uri),Z=D(F.uri),U=E?.before??F.before??"",X=E?.isNewFile??F.before===null,G=Z?SZ(Z.before??"",F.after??"",F.uri):SZ(U,F.after??"",F.uri),V=E?.id??crypto.randomUUID(),K={id:V,uri:t1(F.uri),before:U,after:F.after??"",diff:G,isNewFile:X,reverted:!1,timestamp:Date.now()};Y.set(F.uri,K),await A.store(Q,{toolUseID:F.toolUse,fileChangeID:V},K),P.debug("Recorded file change",{isNewFile:X,isUpdate:!!E,filePath:F.uri.toString(),toolUseID:F.toolUse})},async restoreFromBackups(){let F=await A.list(Q)??[];B.clear();for(let Y of F){let{toolUseID:E}=Y,Z=await A.load(Q,Y);if(!Z)continue;if(!B.has(E))B.set(E,new $Q);B.get(E).set(Z.uri,Z)}return{totalBackups:F.length}},async revertAll(F){let Y=new Set;for(let[E]of B.entries())Y.add(E);await J({filesFilter:F?(E)=>B1.equalURIs(E,F):void 0,toolUsesToRevert:Y,pruneRevertedToolUses:!1})},async revertChanges(F){await J({toolUsesToRevert:F,pruneRevertedToolUses:!0})},getFilesForToolUses(F){let Y=new $Q;for(let[E,Z]of B.entries()){if(!F.has(E))continue;for(let[U,X]of Z.entries()){if(X.reverted)continue;Y.set(U,!0)}}return Array.from(Y.keys()).map(t1)},async cleanupBackups(){await A.cleanup(Q)},async getLastEdit(F){let Y,E,Z=0;for(let[G,V]of B.entries()){let K=V.get(F);if(K&&!K.reverted&&K.timestamp>=Z)Y=K,E=G,Z=K.timestamp}if(!Y||!E)return;let U=Y,X=E;return{oldContent:U.before,newContent:U.after,revert:async()=>{U.reverted=!0,await A.store(Q,{toolUseID:X,fileChangeID:U.id},U)}}},dispose(){B.clear()}}}function XF0(A,Q){async function $(B,D,J){if(D!==null)await X7(B,D,{encoding:"utf8",signal:J});else await HX(B)}return oa0(A.fileChangeTrackerStorage,Q,$)}var H33=4;var Dj=o(()=>{Q4();p0();RA();hK();Bj();TQ0()});function q33(A){if(A.action.type==="redact-tool-input"&&A.on.event!=="tool:post-execute")return"redact-tool-input action can only be used with tool:post-execute event";if(A.action.type==="send-user-message"&&A.on.event!=="tool:pre-execute")return"send-user-message action can only be used with tool:pre-execute event";return null}function ra0(A){if(!A||!Array.isArray(A))return[];return A.filter((Q)=>{if(Q.compatibilityDate!=="2025-05-13")return!1;let $=q33(Q);if($)return P.warn(`Hook "${Q.id}" is invalid: ${$}`),!1;return!0})}var kO4=o(()=>{p0()});function SO4(A,Q){if(!A)return{action:null};A=ra0(A);for(let $ of A){if($.if===!1)continue;if($.on.event==="tool:pre-execute"){if(!(Array.isArray($.on.tool)?$.on.tool:[$.on.tool]).includes(Q.toolUse.name))continue;let D=JSON.stringify(Q.toolUse.input),J=Array.isArray($.on["input.contains"])?$.on["input.contains"]:[$.on["input.contains"]];for(let F of J)if(D.includes(F)){if(P.debug(`Hook triggered: ${$.id}`,{hookID:$.id,threadID:Q.threadID,toolName:Q.toolUse.name,toolUseID:Q.toolUse.id,matchString:F,action:$.action}),$.action.type==="send-user-message")return{hookID:$.id,action:$.action}}}}return{action:null}}function fO4(A,Q){if(!A)return{action:null};A=ra0(A);for(let $ of A){if($.if===!1)continue;if($.on.event==="tool:post-execute"){if(!(Array.isArray($.on.tool)?$.on.tool:[$.on.tool]).includes(Q.toolUse.name))continue;if(P.debug(`Post-execution hook triggered: ${$.id}`,{hookID:$.id,threadID:Q.threadID,toolName:Q.toolUse.name,toolUseID:Q.toolUse.id,action:$.action}),$.action.type==="redact-tool-input")return{hookID:$.id,action:$.action}}}return{action:null}}function yO4(A,Q){if(!A)return{action:null};try{return A(Q.thread)}catch($){return P.error("Error processing assistant end-turn hook",$),{action:null}}}function nS(A,Q,$){if(!Q.action)return{abortOp:!1};switch(Q.action.type){case"send-user-message":{let B={type:"user:message",message:{messageId:0,content:[{type:"text",text:Q.action.message}],source:{type:"hook",hook:Q.hookID}}};return A.updateThread(B),A.onThreadDelta(B),{abortOp:!0}}case"redact-tool-input":{if(!$?.toolUseID)return P.warn("redact-tool-input action requires toolUseID in context"),{abortOp:!1};let B={type:"tool:processed",toolUse:$.toolUseID,newArgs:Q.action.redactedInput};return A.updateThread(B),A.onThreadDelta(B),P.debug("Tool input redacted",{hookID:Q.hookID,toolUseID:$.toolUseID}),{abortOp:!1}}case"handoff":return P.info("Handoff hook triggered",{hookID:Q.hookID,goal:Q.action.goal}),A.executeHandoff(Q.action.goal),{abortOp:!1}}}var sa0=o(()=>{p0();kO4()});function N33(A,Q,$){let B=$.getExecutionProfile(A.name),D=$.getExecutionProfile(Q.name);if(!B||!D)return!0;if(B.serial||D.serial)return!0;let J=B.resourceKeys(A.input??{}),F=D.resourceKeys(Q.input??{});for(let Y of J)for(let E of F)if(Y.key===E.key){if(Y.mode==="write"||E.mode==="write")return!0}return!1}function w33(A,Q,$){for(let B of Q)if(N33(A,B,$))return!0;return!1}function xO4(A,Q){if(A.length===0)return[];let $=[],B=[];for(let D of A){if(w33(D,B,Q)){if(B.length>0)$.push(B),B=[]}B.push(D)}if(B.length>0)$.push(B);return $}class ta0{threadID;toolService;callbacks;processingMutex=new XJ;runningTools=new Map;cancelledToolUses=new Set;toolMessages=new Map;toolCompletionResolvers=new Map;pendingApprovalsSubscription;writtenBlockedToolUseIds=new Set;disposed=!1;constructor(A,Q,$){this.threadID=A;this.toolService=Q;this.callbacks=$;this.pendingApprovalsSubscription=this.toolService.pendingApprovals$.subscribe((B)=>{this.syncPendingApprovalsToThreadState(B)})}syncPendingApprovalsToThreadState(A){let Q=A.filter((B)=>B.threadId===this.threadID);for(let B of Q)if(!this.writtenBlockedToolUseIds.has(B.toolUseId))this.writtenBlockedToolUseIds.add(B.toolUseId),P.debug("Writing blocked-on-user to thread state",{name:"syncPendingApprovalsToThreadState",threadID:this.threadID,toolUseId:B.toolUseId,toolName:B.toolName}),this.callbacks.updateThread({type:"tool:data",toolUse:B.toolUseId,data:{status:"blocked-on-user",reason:B.reason,toAllow:B.toAllow}});let $=new Set(Q.map((B)=>B.toolUseId));for(let B of this.writtenBlockedToolUseIds)if(!$.has(B))this.writtenBlockedToolUseIds.delete(B)}async onResume(){await this.processingMutex.acquire();try{let A=this.callbacks.getThread(),Q=D9(A,"user");if(!Q)return;for(let $ of Q.content){if($.type!=="tool_result")continue;if($.run.status==="blocked-on-user"){let J=this.findToolUseById($.toolUseID);if(!J)continue;P.debug(`restoring blocked-on-user tool ${J.name} to approval queue`,{name:"onResume",threadID:this.threadID,toolUseID:$.toolUseID}),this.toolService.restoreApproval({threadId:this.threadID,toolUseId:$.toolUseID,toolName:J.name,args:J.input??{},reason:$.run.reason,toAllow:$.run.toAllow,context:A.mainThreadID?"subagent":"thread"});continue}if(!(!f3($.run.status)&&!this.runningTools.has($.toolUseID)))continue;let D=this.findToolUseById($.toolUseID);if(!D)continue;if(this.isDangerousToResume(D.name)){P.debug(`cancelling dangerous tool ${D.name} on resume`,{name:"onResume",threadID:this.threadID,toolUseID:$.toolUseID});let J=VL($.run);this.callbacks.updateThread({type:"tool:data",toolUse:$.toolUseID,data:{status:"cancelled",reason:"system:safety",progress:J}});continue}P.debug(`re-invoking tool ${D.name} with ID ${$.toolUseID}`,{name:"onResume",threadID:this.threadID}),await this.invokeTool(D,$.userInput)}}finally{this.processingMutex.release()}await this.callbacks.updateFileChanges()}async onAssistantMessageComplete(A){let Q;await this.processingMutex.acquire();try{this.cancelledToolUses.clear(),Q=this.findToolUsesNeedingInvocation(A),P.debug(`saw ${Q.length} tool uses (${Q.map(($)=>$.name).join(", ")})`,{name:"onAssistantMessageComplete",threadID:this.threadID})}finally{this.processingMutex.release()}if(Q.length>0)await this.executeToolsWithPlan(Q)}async userProvideInput(A,Q){await this.processingMutex.acquire();try{let $=this.findToolUseById(A);if($&&l5($))await this.invokeTool($,Q)}finally{this.processingMutex.release()}}async userCancel(A){await this.cancelTool(A,"user:cancelled")}async onNewUserMessage(){this.markAllActiveToolsCancelled(),this.toolService.clearApprovalsForThread(this.threadID),await this.cancelAll("user:interrupted")}async cancelAll(A){await this.processingMutex.acquire();try{this.markAllActiveToolsCancelled(),this.toolService.clearApprovalsForThread(this.threadID),this.cancelUnstartedTools(A),await this.cancelInProgressTools(A)}finally{this.processingMutex.release()}}async findAndCancelToolRun(A,Q){let $=this.callbacks.getThread();if(!E7($,A))return;await this.cancelTool(A,"user:cancelled",Q)}async cancelToolOnly(A,Q){let $=this.callbacks.getThread();if(!E7($,A))return;let D=this.getCancelDataForToolRun(A,"user:cancelled"),J=this.toolMessages.get(A);if(J){try{J.next({type:"stop-command"})}catch(F){P.warn("Failed to send stop-command",{toolUseID:A,error:F})}J.complete(),this.toolMessages.delete(A)}P.debug(`cancelToolOnly(${A})`),await this.callbacks.handle({type:"tool:data",toolUse:A,data:D},Q)}getRunningToolIds(){return Array.from(this.runningTools.keys())}hasRunningTools(){return this.runningTools.size>0}isCancelled(A){return this.cancelledToolUses.has(A)}markCancelled(A){this.cancelledToolUses.add(A)}clearCancelled(A){this.cancelledToolUses.delete(A)}sendToolMessage(A,Q){let $=this.toolMessages.get(A);if($)return $.next(Q),!0;return!1}resolveToolCompletion(A,Q,$){let B=this.toolCompletionResolvers.get(A);if(B){if(Q)B.resolve();else B.reject($??Error(`Tool failed: ${A}`));this.toolCompletionResolvers.delete(A)}}dispose(){if(this.disposed)return;this.disposed=!0,this.pendingApprovalsSubscription.unsubscribe(),this.toolService.clearApprovalsForThread(this.threadID),this.writtenBlockedToolUseIds.clear();for(let[A,Q]of this.toolCompletionResolvers)try{Q.reject(Error("Orchestrator disposed"))}finally{this.toolCompletionResolvers.delete(A)}for(let[A,Q]of this.toolMessages)try{Q.next({type:"stop-command"}),Q.complete()}catch($){P.warn("Failed to cleanup tool messages during disposal",{id:A,error:$})}this.toolMessages.clear();for(let A of this.runningTools.values())A.abort.abort();this.runningTools.clear(),this.cancelledToolUses.clear()}findToolUsesNeedingInvocation(A){if(A.content.some((Y)=>Y.type==="tool_use"&&!l5(Y)))return[];if(!(A.state?.type==="complete"||A.state?.type==="cancelled"))return[];let B=this.callbacks.getThread(),D=D9(B,"user"),J=D9(B,"assistant"),F=new Set;if(D?.messageId!==void 0&&J?.messageId!==void 0&&D.messageId>J.messageId){for(let Y of D.content)if(Y.type==="tool_result")F.add(Y.toolUseID)}return A.content.filter((Y)=>Y.type==="tool_use").filter((Y)=>!F.has(Y.id)&&!this.cancelledToolUses.has(Y.id))}async executeToolsWithPlan(A){if(A.length===0)return;let Q=xO4(A,this.toolService);P.debug(`executing ${A.length} tools in ${Q.length} batch(es)`,{name:"executeToolsWithPlan",threadID:this.threadID,batches:Q.map(($)=>$.map((B)=>B.name))}),await this.executeToolBatchesSequentially(Q)}async executeToolBatchesSequentially(A){for(let Q of A){let B=(await Promise.allSettled(Q.map((D)=>this.invokeToolAndWait(D,void 0)))).filter((D)=>D.status==="rejected");if(B.length>0)P.warn(`${B.length} tool(s) failed in batch`,{name:"executeToolBatchesSequentially",threadID:this.threadID,errors:B.map((D)=>D.reason)})}}async invokeToolAndWait(A,Q){let $=new Promise((B,D)=>{this.toolCompletionResolvers.set(A.id,{resolve:B,reject:D})});this.invokeTool(A,Q).catch((B)=>{let D=this.toolCompletionResolvers.get(A.id);if(D)P.debug(`Tool invocation setup failed for ${A.id}`,{name:"invokeToolAndWait",threadID:this.threadID,error:String(B)}),D.reject(B),this.toolCompletionResolvers.delete(A.id)}),await $}async invokeTool(A,Q){if(this.runningTools.has(A.id))throw Error(`(bug) tool invocation already in progress: ${A.id}`);if(!l5(A))throw Error(`(bug) tool use is incomplete: ${A.id}`);let $=await this.callbacks.getConfig(),B=SO4($.settings?.hooks,{threadID:this.threadID,toolUse:A}),{abortOp:D}=await this.callbacks.applyHookResult(B);if(D){let E=this.toolCompletionResolvers.get(A.id);if(E)E.resolve(),this.toolCompletionResolvers.delete(A.id);return}let J=A.input;if(this.callbacks.requestPluginToolCall){let E={thread:{id:this.threadID},toolUseID:A.id,tool:A.name,input:A.input??{}},Z=await this.callbacks.requestPluginToolCall(E);if(Z.action==="error"){P.warn("Plugin returned error action",{tool:A.name,message:Z.message,toolUseID:A.id});let U=this.toolCompletionResolvers.get(A.id);if(await this.callbacks.handle({type:"tool:data",toolUse:A.id,data:{status:"error",error:{message:`Plugin error: ${Z.message}`,displayMessage:Z.message}}}),U)U.resolve(),this.toolCompletionResolvers.delete(A.id);return}if(Z.action==="reject-and-continue"){let U=this.toolCompletionResolvers.get(A.id);if(await this.callbacks.handle({type:"tool:data",toolUse:A.id,data:{status:"done",result:`Tool rejected by plugin: ${Z.message}`,isFinal:!1}}),U)U.resolve(),this.toolCompletionResolvers.delete(A.id);return}if(Z.action==="synthesize"){let U=this.toolCompletionResolvers.get(A.id);if(await this.callbacks.handle({type:"tool:data",toolUse:A.id,data:{status:"done",result:Z.result.output,isFinal:!1}}),U)U.resolve(),this.toolCompletionResolvers.delete(A.id);return}if(Z.action==="modify")J=Z.input,await this.callbacks.handle({type:"tool:processed",toolUse:A.id,newArgs:Z.input})}if(this.cancelledToolUses.has(A.id)){this.ensureCancelledToolResult(A.id,"user:interrupted"),this.resolveToolCompletion(A.id,!0);return}let F=new AbortController,Y={abort:F};this.runningTools.set(A.id,Y),this.callbacks.updateThread({type:"tool:data",toolUse:A.id,data:{status:"in-progress"}});try{let E=await this.callbacks.getToolRunEnvironment(A.id,F.signal),Z=new h0((q)=>{this.toolMessages.set(A.id,q)}),U={...E,toolMessages:Z},X=this.toolService.preprocessArgs?.(A.name,J,U);if(X)await this.callbacks.handle({type:"tool:processed",toolUse:A.id,newArgs:X});let G=X??J,V=this.toolService.normalizeToolName(A.name),K=typeof G==="object"&&G!==null?this.toolService.normalizeToolArgs(A.name,G):G,I=typeof K==="object"&&K!==null&&"__isFinal"in K&&typeof K.__isFinal==="boolean"?K.__isFinal:void 0,z=I!==void 0?Object.fromEntries(Object.entries(K).filter(([q])=>q!=="__isFinal")):K,W=this.toolService.invokeTool(V,{args:z,userInput:Q},U).pipe(BK(this.callbacks.getDisposed$()),nW(()=>{this.runningTools.delete(A.id),this.toolMessages.get(A.id)?.complete(),this.toolMessages.delete(A.id)})).subscribe({next:async(q)=>{if(this.cancelledToolUses.has(A.id))return;if(P.debug(`${A.id}, ${q.status}`,{name:"invokeTool",threadID:this.threadID}),f3(q.status)){this.runningTools.delete(A.id),W.unsubscribe();let w=this.toolCompletionResolvers.get(A.id);if(w){if(q.status==="done")w.resolve();else w.reject(Error(`Tool ${q.status}: ${A.id}`));this.toolCompletionResolvers.delete(A.id)}if(q.status==="done"&&A.name.toLowerCase()===n7.toLowerCase())this.callbacks.onSkillToolComplete(A);if($.settings?.hooks){let O=fO4($.settings.hooks,{threadID:this.threadID,toolUse:A});await this.callbacks.applyPostHookResult(O,{toolUseID:A.id})}if(this.callbacks.requestPluginToolResult){let O={thread:{id:this.threadID},toolUseID:A.id,tool:A.name,input:A.input??{},status:q.status,error:q.status==="error"?q.error?.message:void 0,output:q.status==="done"?q.result:void 0};try{let L=await this.callbacks.requestPluginToolResult(O);if(L)q={...q,status:L.status,error:L.status==="error"?{message:L.error??"Plugin error"}:void 0,result:L.output}}catch(L){P.debug("Failed to request plugin tool result",{error:L})}}}await this.callbacks.updateFileChanges();let N=I!==void 0&&q.status==="done"&&q.isFinal===void 0?{...q,isFinal:I}:q;await this.callbacks.handle({type:"tool:data",toolUse:A.id,data:N},F.signal)},error:async(q)=>{let N=this.toolCompletionResolvers.get(A.id);if(N)N.reject(q),this.toolCompletionResolvers.delete(A.id);await this.callbacks.handle({type:"tool:data",toolUse:A.id,data:{status:"error",error:{message:"message"in q?q.message:String(q),displayMessage:"displayMessage"in q?q.displayMessage:void 0}}},F.signal)},complete:()=>{let q=this.toolCompletionResolvers.get(A.id);if(!q)return;let N=this.callbacks.getThread(),w=rF(N).get(A.id)?.run;if(w&&f3(w.status))return;let O;if(this.callbacks.isDisposed())O="Worker disposed";else if(F.signal.aborted)O="Tool aborted";else if(this.cancelledToolUses.has(A.id))O="Tool cancelled";else O="Tool observable completed without terminal state";q.reject(Error(O)),this.toolCompletionResolvers.delete(A.id)}}),H=this.runningTools.get(A.id);if(H)H.subscription=W;QY(F.signal,()=>W.unsubscribe())}catch(E){this.runningTools.delete(A.id);let Z=this.toolCompletionResolvers.get(A.id);if(Z)Z.reject(E),this.toolCompletionResolvers.delete(A.id);throw E}}async cancelTool(A,Q,$){let B=this.getCancelDataForToolRun(A,Q),D=this.toolMessages.get(A);if(D){try{D.next({type:"stop-command"})}catch(J){P.warn("Failed to send stop-command",{toolUseID:A,error:J})}D.complete(),this.toolMessages.delete(A)}P.debug(`cancelTool(${A}, ${Q})`),await this.callbacks.handle({type:"tool:data",toolUse:A,data:B},$),this.resolveToolCompletion(A,!0)}ensureCancelledToolResult(A,Q){let $=this.callbacks.getThread(),B=rF($).get(A)?.run;if(B&&f3(B.status))return;this.callbacks.updateThread({type:"tool:data",toolUse:A,data:{status:"cancelled",reason:Q,progress:B?VL(B):void 0}})}getCancelDataForToolRun(A,Q){let $=this.callbacks.getThread(),B=rF($).get(A)?.run;return{status:"cancelled",progress:B?VL(B):void 0,reason:Q}}markAllActiveToolsCancelled(){let A=this.callbacks.getThread(),Q=D9(A,"assistant");if(Q){let $=D9(A,"user"),B=new Map;if($){for(let D of $.content)if(D.type==="tool_result")B.set(D.toolUseID,D.run)}for(let D of Q.content)if(D.type==="tool_use"&&l5(D)){let J=B.get(D.id);if(!(J?f3(J.status):!1))this.cancelledToolUses.add(D.id)}}}cancelUnstartedTools(A){let Q=this.callbacks.getThread(),$=rF(Q),B=Q.messages.findLastIndex((J)=>U20(J)),D=B===-1?Q.messages:Q.messages.slice(B+1);for(let J of D){if(J.role!=="assistant")continue;for(let F of J.content)if(F.type==="tool_use"&&l5(F)){let Y=$.get(F.id);if(Y?.run.status==="blocked-on-user"&&A==="system:disposed")continue;if(!Y||Y.run.status==="blocked-on-user")this.callbacks.updateThread({type:"tool:data",toolUse:F.id,data:{status:"cancelled",reason:A}})}}}async cancelInProgressTools(A){for(let[Q,$]of this.runningTools)$.abort.abort(),$.subscription?.unsubscribe(),await this.cancelTool(Q,A);this.runningTools.clear()}findToolUseById(A){let Q=this.callbacks.getThread(),$=D9(Q,"assistant");if(!$)return;for(let B of $.content)if(B.type==="tool_use"&&B.id===A)return B;return}isDangerousToResume(A){return A===e6||A===fd||A===i7||A===T8||A===UT}abortToolOp(A){let Q=this.runningTools.get(A);if(Q)Q.abort.abort(),this.runningTools.delete(A)}abortAllTools(){for(let[A,Q]of this.runningTools){let $=this.toolMessages.get(A);if($){try{$.next({type:"stop-command"}),$.complete()}catch(B){P.warn("Failed to send stop-command during disposal",{toolId:A,error:B})}this.toolMessages.delete(A)}Q.abort.abort()}this.runningTools.clear()}}var bO4=o(()=>{P1();$Y();p0();h4();WH();sa0();a4()});function hO4(A){let Q=[],$=/@((?:[^\s@\\,;]|\\.)+)/g,B;while((B=$.exec(A))!==null){let D=B[1],J=C33(D).replace(/[.,;:!?)}\]]+$/,"");Q.push(J)}return{paths:Q}}function C33(A){if(A.match(/^[A-Za-z]:[\\]/))return A.replace(/\\(.)/g,(Q,$)=>{if($===" "||$==="("||$===")"||$==="["||$==="]"||$==="?"||$==="*")return $;return Q});return A.replace(/\\(.)/g,"$1")}function GF0(A){if(!A.connected)return;return mO4(A)}async function gO4(){if(!await o5.isConnected())return;let Q=await k1(o5.status);return mO4(Q)}function mO4(A){let Q=A.selections?.[0],$=j20(Q),B=$&&Q?{line:Q.range.startLine+1,column:Q.range.startCharacter}:void 0;return{currentlyVisibleFiles:A.visibleFiles??[],activeEditor:A.openFile,cursorLocation:B,cursorLocationLine:void 0,selectionRange:!$&&Q?{start:{line:Q?.range.startLine+1,column:Q?.range.startCharacter},end:{line:Q?.range.endLine+1,column:Q?.range.endCharacter}}:void 0}}var VF0=o(()=>{P1();wK();QL()});function dO4(A){for(let Q=A.length-1;Q>=0;Q--){let $=A[Q];if($?.role==="user"&&$.userState!==void 0)return $.userState}return}async function pO4(A,{configService:Q,previousUserState:$}){let B={sentAt:Date.now()},D=w2(A.content),{paths:J}=hO4(D),F=await k1(Q.workspaceRoot);if(!F)return{message:{role:"user",messageId:0,content:A.content,source:A.source,fileMentions:void 0,userState:void 0,agentMode:A.agentMode,meta:B}};let Y=await K$0(J,{searchPaths:[F],shouldIncludeImages:!A.agentMode||cd(A.agentMode)}),E;if(Y?.files&&Y.files.length>0){let G=new Set,V=[];for(let K of Y.files){let I=GA(K.uri),z=await KY(I,F,null,G,void 0);for(let W of z){if(!V.some((H)=>H.uri===W.uri))V.push(W);G.add(W.uri)}}if(V.length>0)E=V}let Z={...await gO4()??qE4},U=$!==void 0&&iF(Z,$)?void 0:Z;return{message:{role:"user",messageId:0,content:Y?.imageBlocks?.length?[...A.content,...Y.imageBlocks]:A.content,source:A.source,fileMentions:Y,userState:U,agentMode:A.agentMode,discoveredGuidanceFiles:E,meta:B}}}var cO4=o(()=>{Q4();P1();M5();y5();aK();a4();tH();VF0()});function M33(A,Q){let $=D9(A,"assistant");if(!$)return{updatedThread:A,uninvoked:[]};let B=$.content.filter((F)=>F.type==="tool_use"),D=Q.items.filter((F)=>!Q.wasInvoked(B,F));if(D.length===0)return{updatedThread:A,uninvoked:[]};return{updatedThread:h8(A,(F)=>{let Y=F.messages.findLast((E)=>E.role==="assistant");if(Y&&Y.role==="assistant"){for(let E of D){let Z=oF();Y.content.push({type:"tool_use",complete:!0,id:Z,name:Q.toolName,input:Q.toToolInput(E)})}if(Y.state.type==="complete"&&Y.state.stopReason==="end_turn")Y.state={...Y.state,stopReason:"tool_use"}}F.v++}),uninvoked:D}}class aS{deps;threadID;async getConfig(A){return k1(this.deps.configService.config,A)}setupSettingsChangeHandlers(){this.setupPermissionsChangeHandler()}setupEphemeralErrorLogging(){this.ephemeralError.pipe(BK(this.disposed$)).subscribe((A)=>{if(A)P.error("ephemeral error",{error:A})})}setupPermissionsChangeHandler(){this.deps.configService.config.pipe(N1((A)=>({permissions:KK(A.settings?.permissions),dangerouslyAllowAll:A.settings?.dangerouslyAllowAll??!1})),T4((A,Q)=>A.dangerouslyAllowAll===Q.dangerouslyAllowAll&&A.permissions===Q.permissions),Qe1(1),BK(this.disposed$)).subscribe(()=>{this.reevaluateBlockedTools()})}reevaluateBlockedTools(){if(this.isDisposed)return;for(let A=this.thread.messages.length-1;A>=0;A--){let Q=this.thread.messages[A];if(!Q||Q.role!=="user")continue;let $=!1;for(let B of Q.content)if(B.type==="tool_result"&&B.run?.status==="blocked-on-user"&&B.toolUseID)$=!0,this.checkAndApproveBlockedTool(B.toolUseID);if(!$)break}}async checkAndApproveBlockedTool(A){try{let Q=E7(this.thread,A);if(!Q){P.warn("Tool use block not found for blocked tool",{toolUseID:A});return}let $=await N80(Q.name,Q.input??{},{configService:this.deps.configService},this.thread.mainThreadID?"subagent":"thread",this.threadID,A);if($.permitted)P.info("Auto-approving previously blocked tool due to permission change",{toolName:Q.name,toolUseID:A,threadID:this.threadID}),this.handle({type:"user:tool-input",toolUse:A,value:{accepted:!0}});else P.debug("Tool remains blocked after permission change",{toolName:Q.name,toolUseID:A,reason:$.reason})}catch(Q){P.warn("Failed to re-evaluate blocked tool",{error:Q,toolUseID:A})}}ops={tools:{},toolMessages:{},inference:null,titleGeneration:null};_state=new a1("initial");state=this._state.pipe(T4(),t6({shouldCountRefs:!0}));handleMutex=new XJ;ephemeralError=new a1(void 0);ephemeralErrorRetryAttempt=0;retryCountdownSeconds=new a1(void 0);retryTimer=null;retrySession=0;_inferenceState=new a1("idle");_turnStartTime=new a1(void 0);_turnElapsedMs=new a1(void 0);fileChanges=new a1({files:[]});get inferenceState(){return this._inferenceState.getValue()}toolCallUpdates=new p4;discoveredGuidanceFileURIs=new Set;fileChangeTracker;cachedFileChanges=[];disposed$=new p4;isDisposed=!1;shouldContinueAfterRejection=!1;_pendingSkills=new a1([]);handoffState=new a1(void 0);pendingSkills=this._pendingSkills.pipe(T4(),t6({shouldCountRefs:!0}));_awaitingSkillInvocation=new a1([]);toolOrchestrator;currentAgentSpan=null;reasoningEffortOverride;currentSpan=null;traceStore;constructor(A,Q){this.deps=A;this.threadID=Q;this.fileChangeTracker=XF0({fileChangeTrackerStorage:this.deps.fileChangeTrackerStorage},Q),this.traceStore={startTrace:($)=>{this.updateThread({type:"trace:start",span:$})},recordTraceEvent:($,B)=>{this.updateThread({type:"trace:event",span:$,event:B})},recordTraceAttributes:($,B)=>{this.updateThread({type:"trace:attributes",span:$,attributes:B})},endTrace:($)=>{this.updateThread({type:"trace:end",span:$})}},this.toolOrchestrator=new ta0(Q,A.toolService,this.createOrchestratorCallbacks())}createTracer(A){return Fb0(this.traceStore,A)}getPluginTracer(){let A=this.currentSpan?.id??this.currentAgentSpan?.span;if(!A)return;return this.createTracer(A)}createOrchestratorCallbacks(){return{getThread:()=>this.thread,updateThread:(A)=>this.updateThread(A),handle:(A,Q)=>this.handle(A,Q),getToolRunEnvironment:(A,Q)=>this.getToolRunEnvironment(A,Q),getHooks:async()=>(await this.getConfig()).settings?.hooks,getConfig:()=>this.getConfig(),updateFileChanges:()=>this.updateFileChanges(),isDisposed:()=>this.isDisposed,getDisposed$:()=>this.disposed$,onSkillToolComplete:(A)=>this.onSkillToolComplete(A),applyHookResult:(A)=>Promise.resolve(nS(this,A)),applyPostHookResult:(A,Q)=>Promise.resolve(nS(this,A,Q)),requestPluginToolCall:this.deps.pluginService?(A)=>this.deps.pluginService.event.toolCall(A,this.getPluginTracer()):void 0,requestPluginToolResult:this.deps.pluginService?(A)=>this.deps.pluginService.event.toolResult(A,this.getPluginTracer()):void 0}}async getToolRunEnvironment(A,Q){let $=await this.getWorkspaceRoot(Q),B=WT(this.thread),D=E7(this.thread,A);return{...this.deps,dir:$,tool:D?.name??"",thread:this.thread,config:await this.getConfig(Q),fileChangeTracker:this.fileChangeTracker,getAllTrackedChanges:this.getAllTrackedChanges.bind(this),toolUseID:A,todos:B,toolMessages:new h0(()=>{}),threadEnvironment:this.thread.env?.initial??await this.deps.getThreadEnvironment(),handleThreadDelta:this.handle.bind(this),agentMode:await this.getSelectedAgentMode(),discoveredGuidanceFileURIs:this.discoveredGuidanceFileURIs}}onSkillToolComplete(A){let Q=A.input;this.thread=h8(this.thread,($)=>{if(!$.activatedSkills)$.activatedSkills=[];if(!$.activatedSkills.some((B)=>B.name===Q.name))$.activatedSkills.push({name:Q.name,arguments:Q.arguments})})}status=this.state.pipe(y4((A)=>A==="active"?jA(this._inferenceState.pipe(T4()),this.fileChanges.pipe(T4()),this.ephemeralError,this.handoffState.pipe(T4()),this.retryCountdownSeconds.pipe(T4()),this._turnStartTime.pipe(T4()),this._turnElapsedMs.pipe(T4()),this.toolCallUpdates.pipe(HA(void 0))).pipe(N1(([Q,$,B,D,J,F,Y])=>({state:A,inferenceState:Q,fileChanges:$,ephemeralError:B?{message:B.message,stack:"stack"in B?B.stack:void 0,error:"error"in B&&B.error&&typeof B.error==="object"&&"error"in B.error?B.error.error:void 0,retryCountdownSeconds:J}:void 0,handoff:D,turnStartTime:F,turnElapsedMs:Y})),BK(this.disposed$)):h0.of({state:A})),t6({shouldCountRefs:!0}));threadReadWriter=null;get thread(){if(!this.threadReadWriter)throw Error(`thread read-writer not initialized for ThreadWorker: ${this.threadID}`);return this.threadReadWriter.read()}set thread(A){if(!this.threadReadWriter)throw Error(`thread read-writer not initialized for ThreadWorker: ${this.threadID}`);this.threadReadWriter.write(A),this.__testing__setThread(A)}updateThread(A){if(!this.threadReadWriter)throw Error(`thread read-writer not initialized for ThreadWorker: ${this.threadID}`);this.threadReadWriter.update(IE4(A,new Date)),this.__testing__setThread(this.threadReadWriter.read())}repairMissingToolResultsForInference(){let A=!1,Q=h8(this.thread,($)=>{for(let B=$.messages.length-1;B>=0;B--){let D=$.messages[B];if(D?.role!=="assistant")continue;if(!(D.state.type==="cancelled"||D.state.type==="complete"&&D.state.stopReason==="tool_use"))continue;if(D.content.some((V)=>V.type==="tool_use"&&!V.complete))continue;let Y=D.content.filter((V)=>V.type==="tool_use"&&V.complete);if(Y.length===0)continue;let E=$.messages[B+1];if(E?.role!=="user")continue;let Z=new Map,U=[];for(let V of E.content)if(V.type==="tool_result"&&Y.some((I)=>I.id===V.toolUseID))Z.set(V.toolUseID,V);else U.push(V);let X=!1,G=[];for(let V of Y){let K=Z.get(V.id);if(K)G.push(JA(K));else G.push(JA({type:"tool_result",toolUseID:V.id,run:{status:"cancelled",reason:"user:interrupted"}})),X=!0,A=!0}if(X)E.content=[...G,...U]}if(A)$.v++});if(A)this.thread=Q}async acquireThread(){if(!this.threadReadWriter)this.threadReadWriter=await this.deps.threadService.exclusiveSyncReadWriter(this.threadID),this._state.next("active")}__testing__setThread(A){}__testing__getDeps(){return this.deps}async resume(){if(this.resumed)return;if(this.resumed=!0,this.handleCalled)throw Error("cannot call ThreadWorker.resume after ThreadWorker.handle");await this.acquireThread(),await this.restoreFileChangesFromBackups();let A=this.thread.messages.at(-1);if(A?.role==="assistant"&&A.state.type==="streaming")this.updateThread({type:"thread:truncate",fromIndex:this.thread.messages.length-1});if(this.triggerTitleGeneration(),!this.shouldResumeFromLastMessage(A))return;await this.toolOrchestrator.onResume(),this.setupSettingsChangeHandlers(),this.setupEphemeralErrorLogging(),this.replayLastCompleteMessage()}resumed=!1;shouldResumeFromLastMessage(A){if(j14(A)||R14(A)&&!this.shouldContinueAfterRejection||U20(A))return this._inferenceState.next("cancelled"),!1;return!0}replayLastCompleteMessage(){let A=this.thread.messages.findLastIndex(($)=>$.role==="user"?P14($):$.role==="assistant"&&$.state.type==="complete");if(A===-1){if(this.thread.messages.length!==0)throw Error(`(bug) invalid thread: ${this.threadID}`);return}let Q=this.thread.messages[A];switch(Q.role){case"user":if(!Q.interrupted)this.onThreadDelta({type:"user:message",message:Q});break;case"assistant":this.onThreadDelta({type:"assistant:message",message:Q});break}}async handle(A,Q){let $=A.type==="user:message"&&A.index!==void 0?A.index:void 0,B=!1;await this.handleMutex.acquire();try{B=await this.innerHandle(A,Q,{deferUserMessageInference:$!==void 0})}finally{this.handleMutex.release()}if($!==void 0&&B){await this.performMessageEditCleanup();let D=this.thread.messages[$];if(D?.role==="user")this.beginInferenceForUserMessage(D)}}async innerHandle(A,Q,$={}){if(this.isDisposed)return P.debug(`Skipping ${A.type} - worker disposed.`,{name:"handle queue",threadID:this.threadID}),!1;if(Q?.aborted)return P.debug(`Skipping ${A.type} - signal aborted.`,{name:"handle queue",threadID:this.threadID}),!1;if(await this.resume(),this.handleCalled=!0,await this.acquireThread(),A.type==="pending-skills"){let J=this._pendingSkills.getValue();return this._pendingSkills.next([...J,...A.skills]),P.info("Pending skills set for injection",{threadID:this.threadID,skillNames:A.skills.map((F)=>F.name)}),!0}let B=A,D=[];if(A.type==="user:message"){let J=dO4(this.thread.messages),F=await pO4(A.message,{configService:this.deps.configService,previousUserState:J});if(D=this._pendingSkills.getValue(),D.length>0)P.info("Pending skills will be injected as info message",{threadID:this.threadID,skillNames:D.map((Y)=>Y.name)}),this._pendingSkills.next([]);B=h8(A,(Y)=>{Y.message=JA(F.message),Q?.throwIfAborted()})}if(B.type==="assistant:message"||B.type==="assistant:message-update")B=this.addNormalizedInputToToolUses(B);try{if(this.ephemeralError.getValue()!==void 0)this.ephemeralError.next(void 0);let J=this.thread;if(this.updateThread(B),this.onThreadDelta(B,J,{deferUserMessageInference:$.deferUserMessageInference}),D.length>0)await this.injectPendingSkills(D,Q);return!0}catch(J){if(!g2(J))P.error("Ephemeral error during handle processing",J,{name:"ThreadWorker",threadID:this.threadID}),this.ephemeralError.next(J instanceof Error?J:Error(String(J)));else P.debug(`AbortError caught during handle processing for ${B.type}.`,{name:"handle queue",threadID:this.threadID});return!1}}handleCalled=!1;addNormalizedInputToToolUses(A){let Q=this.thread.agentMode;if(!A.message.content.some((B)=>B.type==="tool_use"))return A;return h8(A,(B)=>{for(let D of B.message.content)if(D.type==="tool_use"){if(!D.name){P.warn("Skipping tool_use normalization due to missing name",{threadID:this.threadID});continue}let J=this.deps.toolService.normalizeToolName(D.name);if(J!==D.name)D.normalizedName=J;if(D.input&&typeof D.input==="object"){let Y=this.deps.toolService.normalizeToolArgs(D.name,D.input,Q);if(JSON.stringify(Y)!==JSON.stringify(D.input))D.normalizedInput=Y}if((J!==D.name?J:D.name)===UT&&!D.metadata?.handoffThreadID)D.metadata={...D.metadata,handoffThreadID:B9()}}})}onThreadDelta(A,Q,$={}){switch(A.type){case"user:message":{if(this.resetRetryAttempts(),this._turnStartTime.next(Date.now()),this._turnElapsedMs.next(void 0),!$.deferUserMessageInference)this.beginInferenceForLatestUserMessage();break}case"user:message-queue:dequeue":{let B=this.thread.messages.at(-1);if(!B)break;if(B.role!=="user")break;this._turnStartTime.next(Date.now()),this._turnElapsedMs.next(void 0);let D=B.messageId??0,J=w2(B.content);this.startAgentSpan(D),this.beginInference({agentStart:{messageId:D,messageText:J}});break}case"user:tool-input":{this.toolOrchestrator.userProvideInput(A.toolUse,A.value).catch((B)=>{P.error("userProvideInput failed",{name:"ThreadWorker.handleDelta",threadID:this.threadID,toolUse:A.toolUse,error:B instanceof Error?B.message:String(B)})});break}case"tool:data":{if(this.toolOrchestrator.isCancelled(A.toolUse)){let D=rF(this.thread).get(A.toolUse)?.run,J=D?VL(D):void 0;this.updateThread({type:"tool:data",toolUse:A.toolUse,data:{status:"cancelled",reason:"user:interrupted",progress:J}});return}let B=E7(this.thread,A.toolUse);if(A.data.status==="done"&&B?.name===ET){let D=A.data.result;if("task"in D&&D.nextTask){let J=zJ(this.thread),F=this.deps.internalHooks?.onTaskCompleted?.({thread:this.thread,completedTask:D.task,nextTask:D.nextTask,usage:J?{totalInputTokens:J.totalInputTokens,maxInputTokens:J.maxInputTokens}:void 0});if(F)nS(this,F)}}if(f3(A.data.status))this.toolOrchestrator.clearCancelled(A.toolUse),this.toolOrchestrator.resolveToolCompletion(A.toolUse,A.data.status==="done",Error(`Tool ${A.data.status}: ${A.toolUse}`));if(B){let D=L33(this.thread,A.toolUse,this.shouldContinueAfterRejection);P.debug(`updated tool_result${D?" and running inference because all tools completed":""}`,{name:`handleThreadDelta(${A.type}, ${A.toolUse}, ${A.data.status})`,threadID:this.threadID});let J=this.shouldContinueAfterRejection||this._inferenceState.getValue()!=="cancelled";if(D&&J)this.beginInference()}this.toolCallUpdates.next();break}case"assistant:message":{if(A.message.state.type==="complete"&&A.message.state.stopReason==="tool_use"){let D=this.thread.messages.at(-1);(this.currentAgentSpan?this.createTracer(this.currentAgentSpan.span):LX).startActiveSpan("tools",{context:{messageId:D?.messageId}},async()=>{await this.toolOrchestrator.onAssistantMessageComplete(A.message)}).catch((F)=>{P.error("onAssistantMessageComplete failed",{name:"ThreadWorker.handleDelta",threadID:this.threadID,messageState:A.message.state.type,error:F instanceof Error?F.message:String(F)})})}break}case"assistant:message-update":break;case"user:message-queue:enqueue":{let B=this._inferenceState.getValue();if(Li0(this.thread,B)!=="tool-running"){if(B==="cancelled"){this.handle({type:"user:message-queue:dequeue"});break}else if(B==="idle"){let J=this.thread.messages.at(-1);if(J?.role==="assistant"){if(J.state.type==="cancelled"||J.state.type==="error"){this.handle({type:"user:message-queue:dequeue"});break}if(J.state.type==="complete"&&J.state.stopReason!=="tool_use"){this.handle({type:"user:message-queue:dequeue"});break}}else if(J?.role==="info"){this.handle({type:"user:message-queue:dequeue"});break}}}break}case"info:manual-bash-invocation":{this.handle({type:"user:message-queue:dequeue"});break}case"cancelled":{if(this.resetRetryAttempts(),this.currentAgentSpan&&this.currentAgentSpan.messageId!==void 0){let B=this.currentAgentSpan.messageId,D=this.createTracer(this.currentAgentSpan.span);this.stopAgentSpan(this.currentAgentSpan.span),this.deps.pluginService.event.agentEnd({thread:{id:this.threadID},message:this.getMessageText(B),id:B,status:"cancelled",messages:w70(this.getMessagesSince(B))},D).then((J)=>this.handleAgentEndResult(J)).catch((J)=>P.debug("Failed to emit agent.end",{error:J}))}break}case"thread:truncate":{if(this.toolOrchestrator.cancelAll("system:edited").catch((B)=>{P.error("Failed to cancel tools on truncate",B,{name:"ThreadWorker",threadID:this.threadID})}),Q)this.cleanupFileChanges(A.fromIndex).catch((B)=>{P.error("Failed to cleanup file changes on truncate",B,{name:"ThreadWorker",threadID:this.threadID})});break}case"inference:completed":{this.resetRetryAttempts();let B=A.model?.includes("gpt-5")||A.model?.includes("codex"),D=!A.usage||A.usage.totalInputTokens===0||A.usage.outputTokens===0;if(B&&D)P.getChild("thread-worker").warn("Missing token counts in deep mode inference",{threadID:this.threadID,model:A.model,hasUsage:!!A.usage,inputTokens:A.usage?.inputTokens,outputTokens:A.usage?.outputTokens,totalInputTokens:A.usage?.totalInputTokens,cacheReadInputTokens:A.usage?.cacheReadInputTokens,cacheCreationInputTokens:A.usage?.cacheCreationInputTokens});let J=D9(this.thread,"assistant");if(J&&J.state.type==="complete"&&J.state.stopReason==="refusal"){this.ephemeralError.next(Error("The model refused to respond to this request. Please retry with a different prompt."));break}this.checkAndAppendAwaitedSkills();let F=D9(this.thread,"assistant"),Y=F?.state.type==="complete"&&F.state.stopReason==="tool_use";if(F&&Y){let Z=this.currentAgentSpan?this.createTracer(this.currentAgentSpan.span):LX,U=F.messageId;Z.startActiveSpan("tools",{context:{messageId:U}},async()=>{await this.toolOrchestrator.onAssistantMessageComplete(F)}).catch((X)=>{P.error("onAssistantMessageComplete failed after inference",{name:"ThreadWorker.handleDelta",threadID:this.threadID,messageState:F.state.type,error:X instanceof Error?X.message:String(X)})})}if(F&&F.state.type==="complete"&&F.state.stopReason==="end_turn"){let Z=this._turnStartTime.getValue();if(Z!==void 0){let U=Date.now()-Z;this._turnElapsedMs.next(U),this.thread=h8(this.thread,(X)=>{let G=X.messages.findLast((V)=>V.role==="assistant");if(G&&G.role==="assistant")G.turnElapsedMs=U;X.v++})}if(this._turnStartTime.next(void 0),this.thread.queuedMessages&&this.thread.queuedMessages.length>0)this.handle({type:"user:message-queue:dequeue"});else{nS(this,yO4(this.deps.internalHooks?.onAssistantTurnEnd,{thread:this.thread}));let U=zJ(this.thread);if(U&&this.deps.internalHooks?.onInferenceCompleted){let X=this.deps.internalHooks.onInferenceCompleted({thread:this.thread,usage:{totalInputTokens:U.totalInputTokens,maxInputTokens:U.maxInputTokens},isIdle:!0});nS(this,X)}if(this.currentAgentSpan&&this.currentAgentSpan.messageId!==void 0){let X=this.currentAgentSpan.messageId,G=this.createTracer(this.currentAgentSpan.span);this.stopAgentSpan(this.currentAgentSpan.span),this.deps.pluginService.event.agentEnd({thread:{id:this.threadID},message:this.getMessageText(X),id:X,status:"done",messages:w70(this.getMessagesSince(X))},G).then((V)=>this.handleAgentEndResult(V)).catch((V)=>P.debug("Failed to emit agent.end",{error:V}))}}}break}}}getMessageText(A){let Q=this.thread.messages.find(($)=>$.messageId===A);if(Q)return w2(Q.content);return""}getMessagesSince(A){let Q=this.thread.messages.findIndex(($)=>$.messageId===A);if(Q===-1)return[];return this.thread.messages.slice(Q)}startAgentSpan(A){let Q=Jb0();this.currentAgentSpan={span:Q,messageId:A},this.updateThread({type:"trace:start",span:{name:"agent",id:Q,startTime:new Date().toISOString(),context:{messageId:A}}})}stopAgentSpan(A){if(this.updateThread({type:"trace:end",span:{name:"agent",id:A,endTime:new Date().toISOString()}}),this.currentAgentSpan?.span===A)this.currentAgentSpan=null}handleAgentEndResult(A){if(A.action!=="continue"||!A.userMessage)return;this.handle({type:"user:message",message:{content:[{type:"text",text:A.userMessage}]}}).catch((Q)=>{P.debug("Failed to handle plugin agent.end continue",{error:Q})})}triggerTitleGeneration(){if(this.thread.mainThreadID!==void 0||this.thread.title)return;this.ops.titleGeneration?.abort(),this.ops.titleGeneration=new AbortController;let A=this.ops.titleGeneration.signal;this.getConfig(A).then((Q)=>{if(A.aborted)return;let $=Q.settings?.["agent.skipTitleGenerationIfMessageContains"],B=Array.isArray($)?$.filter((J)=>typeof J==="string"):[],D=this.thread.messages.find((J)=>{if(J.role!=="user")return!1;let F=w2(J.content);if(!F)return!1;if(B.length===0)return!0;return!B.some((Y)=>F.includes(Y))});if(P.debug("Checking for message to generate title for",{skipPatterns:B,rawSkipPatterns:$,hasFirstEligibleMessage:D!==void 0,firstEligibleMessageId:D?.messageId}),D)this.deps.generateThreadTitle(D,this.thread.id,this.deps.configService,A).then(({title:J,usage:F})=>{if(A.aborted||this.isDisposed)return;if(J!==void 0&&this.thread.title!==J)this.updateThread({type:"title",value:J,usage:F})}).catch((J)=>{if(!g2(J))P.error("generateThreadTitle error",J,{name:"ThreadWorker",threadID:this.threadID})})}).catch((Q)=>{if(!g2(Q))P.error("ThreadWorker title generation config error",Q)})}setReasoningEffortOverride(A){if(!this.threadReadWriter){this.reasoningEffortOverride=A;return}let Q=this.threadReadWriter.read();if(A5(Q)>0)return;if(A===void 0){this.reasoningEffortOverride=void 0;return}if(Q.agentMode===void 0||!C2(Q.agentMode,A)){this.reasoningEffortOverride=void 0;return}if(this.reasoningEffortOverride=A,Q.reasoningEffort===A)return;this.handle({type:"reasoning-effort",effort:A}).catch(($)=>{P.debug("Failed to persist thread reasoning effort",{error:$,threadID:this.threadID})})}async getWorkspaceRoot(A){let Q=await k1(this.deps.configService.workspaceRoot,A);if(Q)return Q;let $=this.thread.env?.initial?.trees?.find((B)=>B.uri!==void 0)?.uri;return $?A8($):null}beginInferenceForLatestUserMessage(){let A=this.thread.messages.at(-1);if(A?.role!=="user")return;this.beginInferenceForUserMessage(A)}beginInferenceForUserMessage(A){let Q=A.messageId??0,$=w2(A.content);this.startAgentSpan(Q),this.beginInference({agentStart:{messageId:Q,messageText:$}})}beginInference(A){this.runInferenceAndUpdateThread(A).catch((Q)=>{if(this.isDisposed||g2(Q)||Y80(Q))return;P.error("Failed to run inference",Q,{name:"ThreadWorker.runInferenceAndUpdateThread",threadID:this.threadID}),this.ephemeralError.next(Q instanceof Error?Q:Error(String(Q)))})}async runInferenceAndUpdateThread(A){this.abortInferenceOperation();let Q=new AbortController;if(this.ops.inference=Q,await this.deps.pluginService.event.sessionStart({thread:{id:this.threadID}}),Q.signal.aborted)return;if(A?.agentStart){let{messageId:$,messageText:B}=A.agentStart;try{let D=await this.deps.pluginService.event.agentStart({thread:{id:this.threadID},message:B,id:$},this.currentAgentSpan?this.createTracer(this.currentAgentSpan.span):void 0);if(Q.signal.aborted)return;if(D.message)this.updateThread({type:"user:message:append-content",messageId:$,content:[{type:"text",text:D.message.content}]})}catch(D){P.debug("Failed to emit agent.start",{error:D})}}if(Q.signal.aborted)return;return this.doRunInferenceSetup(Q)}async doRunInferenceSetup(A){if(P.debug("runInferenceAndUpdateThread: begin",{threadID:this.threadID,inferenceState:this._inferenceState.getValue(),messageCount:this.thread.messages.length}),A.signal.aborted||this.ops.inference!==A)return;if(this._inferenceState.getValue()==="cancelled")this._inferenceState.next("idle");let Q=this.currentAgentSpan?.span;if(await this.toolOrchestrator.onNewUserMessage(),A.signal.aborted||this.ops.inference!==A)return;await(this.currentAgentSpan?this.createTracer(this.currentAgentSpan.span):LX).startActiveSpan("inference",{context:{messageId:this.currentAgentSpan?.messageId}},()=>this.doRunInferenceAndUpdateThread(A,Q))}async doRunInferenceAndUpdateThread(A,Q){try{await this.doRunInferenceAndUpdateThreadInner(A,Q)}catch($){if(g2($)||Y80($))return;throw $}}async doRunInferenceAndUpdateThreadInner(A,Q){let $=zJ(this.thread);if($&&$.totalInputTokens>=$.maxInputTokens){let z=Error("Context limit reached");this.ephemeralError.next(z);return}let B=this.thread.messages.at(-1);if(this.thread.mainThreadID===void 0&&B?.role==="user"&&this.thread.messages.filter((z)=>z.role==="user").length===1&&this.deps.getThreadEnvironment)try{let z=await this.deps.getThreadEnvironment(A.signal);if(A.signal.aborted||this.ops.inference!==A)return;this.updateThread({type:"environment",env:{initial:{...this.thread.env?.initial,...z}}})}catch(z){if(A.signal.aborted||this.ops.inference!==A||g2(z))return;P.error("Failed to initialize thread environment",z,{threadID:this.threadID})}this.triggerTitleGeneration(),this.repairMissingToolResultsForInference();let J=await this.getConfig(),{model:F,agentMode:Y}=XZ(J.settings,this.thread),E=this.thread.messages.at(-1)?.messageId;P.debug("runInferenceAndUpdateThread: starting inference",{threadID:this.threadID,lastUserMessageId:E,selectedModel:F,agentMode:Y});let Z=this.deps.getServerStatus?await k1(this.deps.getServerStatus().pipe(i3((z)=>z!=="pending")),A.signal):void 0,U=Z&&AA(Z)?Z.user.email:void 0;if(!tM(Y,U))throw Error(`Agent mode '${Y}' is only available for internal users`);let X={toolService:this.deps.toolService,configService:this.deps.configService,skillService:this.deps.skillService,getThreadEnvironment:this.deps.getThreadEnvironment,getEnvironmentData:this.deps.getEnvironmentData,serverStatus:Z},G=await _X({configService:this.deps.configService,threadService:this.deps.threadService},this.thread,A.signal),V,K=0,I=Date.now();try{let z=K20({providerModel:F,serverStatus:Z}),{provider:W,model:H}=rB(z),q=wO4(W,H),{systemPrompt:N,tools:w}=await $q(X,this.thread,{enableTask:!0,enableOracle:!0,enableChart:!1},{model:H,provider:W,agentMode:Y??"smart"},G,A.signal),O=this.thread.reasoningEffort!==void 0&&C2(Y,this.thread.reasoningEffort)?this.thread.reasoningEffort:void 0,L=O===void 0&&this.reasoningEffortOverride!==void 0&&C2(Y,this.reasoningEffortOverride)?this.reasoningEffortOverride:void 0,j=O??L??FF0(z,J.settings,Y),k=q.stream({model:H,agentMode:Y,thread:this.thread,systemPrompt:N,tools:w,configService:this.deps.configService,serverStatus:Z,signal:A.signal,reasoningEffort:j});this._inferenceState.next("running"),I=Date.now(),P.debug("ThreadWorker inference stream started",{threadID:this.threadID,lastUserMessageId:E,selectedModel:z,agentMode:Y});for await(let _ of k){if(A.signal.aborted)return;K++,V=_,await this.handle({type:"assistant:message-update",message:_},A.signal)}if(A.signal.aborted)return;if(P.debug("ThreadWorker inference stream finished",{threadID:this.threadID,streamEventCount:K,durationMs:Date.now()-I,lastMessageState:V?.state.type,lastMessageId:V?.messageId}),V){let _=V.state.type==="streaming",f=V.content.some((h)=>h.type==="tool_use"&&h.complete&&Object.keys(h.input??{}).length===0);if(_||f)P.warn("Stream ended with incomplete message",{name:"ThreadWorker.runInference",threadID:this.threadID,streamEventCount:K,durationMs:Date.now()-I,messageState:V.state.type,stopReason:V.state.type==="complete"?V.state.stopReason:void 0,contentBlocks:V.content.map((h)=>({type:h.type,...h.type==="tool_use"?{name:h.name,complete:h.complete,inputKeys:Object.keys(h.input??{})}:{},...h.type==="text"?{textLength:h.text.length}:{}}))})}await this.handle({type:"inference:completed",model:V?.usage?.model??F,usage:V?.usage},A.signal)}catch(z){if(P.debug("ThreadWorker inference stream error",{threadID:this.threadID,error:z instanceof Error?z.message:String(z),errorName:z instanceof Error?z.name:void 0,streamEventCount:K,durationMs:Date.now()-I,lastMessageState:V?.state.type,lastMessageId:V?.messageId}),!(g2(z)||Y80(z))){let W=z instanceof Error?z:Error(String(z));if(AG({message:W.message})){this.ephemeralError.next(W);return}let H="status"in W&&typeof W.status==="number"?W.status:void 0;if(IS({message:W.message,status:H})){let q=this.getRetryDelaySeconds();if(q!==void 0)this.startRetryCountdown(q)}this.ephemeralError.next(W)}if(V&&V.messageId){let W=await this.deps.pluginService.event.agentEnd({thread:{id:this.threadID},message:w2(V.content),id:V.messageId,status:"error",messages:w70(this.getMessagesSince(V.messageId))},Q?this.createTracer(Q):void 0);if(Q)this.stopAgentSpan(Q);this.handleAgentEndResult(W)}else if(Q)this.stopAgentSpan(Q);return}finally{if(this.ops.inference===A)this.ops.inference=null,this._inferenceState.next("idle")}}async findAndCancelToolRun(A,Q){this.cancelInference(),await this.toolOrchestrator.findAndCancelToolRun(A,Q)}async cancelToolOnly(A,Q){await this.toolOrchestrator.cancelToolOnly(A,Q)}invokeBashTool(A,Q,$){return new h0((B)=>{let D,J,F,E=((U)=>{return QY(U,()=>{if(P.warn("Manual bash abort -> unsubscribe",{threadID:this.threadID}),F?.unsubscribe(),J?.unsubscribe(),B?.complete(),D)this.handleManualBashInvocation(A,{status:"cancelled",progress:VL(D)},$)})})(Q);return(async()=>{try{if(Q.aborted){B.error(Error("Operation was aborted"));return}let U=await this.getWorkspaceRoot(Q),X=await this.getConfig(Q);if(this.isDisposed){B.complete();return}let G={...this.deps,dir:U,tool:e6,thread:this.thread,config:X,fileChangeTracker:this.fileChangeTracker,getAllTrackedChanges:this.getAllTrackedChanges.bind(this),toolUseID:oF(),todos:[],threadEnvironment:this.thread.env?.initial??await this.deps.getThreadEnvironment(),handleThreadDelta:this.handle.bind(this),discoveredGuidanceFileURIs:this.discoveredGuidanceFileURIs,userInitiated:!0};J=this.deps.toolService.invokeTool(e6,{args:A,userInput:{accepted:!0}},G).subscribe({next:(V)=>{D=V,B.next(V)},error:(V)=>{B.error(V)},complete:()=>{if(D)this.handleManualBashInvocation(A,D,$);B.complete()}}),F=this.disposed$.subscribe(()=>{E(),J?.unsubscribe(),B?.complete()})}catch(U){B.error(U)}})(),()=>{E(),J?.unsubscribe(),F?.unsubscribe()}})}async handleManualBashInvocation(A,Q,$){await this.handle({type:"info:manual-bash-invocation",args:A,toolRun:Q,hidden:$})}async cleanupThreadBackups(A){try{await this.fileChangeTracker.cleanupBackups(),P.debug(`Cleaned up backup files for thread ${A}`,{threadID:A})}catch(Q){P.error("Error cleaning up thread backups",Q,{threadID:A})}}async cancel(){P.debug("cancel: aborting inference operation and tools"),this.cancelInference(),await this.toolOrchestrator.cancelAll("user:cancelled"),await this.handle({type:"cancelled"},void 0)}cancelInference(){this.abortInferenceOperation(),this._inferenceState.next("cancelled"),this._turnStartTime.next(void 0),this._turnElapsedMs.next(void 0)}abortInferenceOperation(){if(this.ops.inference)this.ops.inference.abort(Error(SS0.USER_CANCELLED)),this.ops.inference=null}static BASE_RETRY_SECONDS=5;static MAX_RETRY_SECONDS=60;static MAX_AUTO_RETRIES=5;getRetryDelaySeconds(){if(this.ephemeralErrorRetryAttempt>=aS.MAX_AUTO_RETRIES)return;let A=aS.BASE_RETRY_SECONDS*2**this.ephemeralErrorRetryAttempt;return Math.min(A,aS.MAX_RETRY_SECONDS)}async retry(){if(P.debug("retry: retrying inference operation"),this.clearRetryCountdown(),this.ephemeralError.getValue()!==void 0)this.ephemeralErrorRetryAttempt++,this.ephemeralError.next(void 0);if(this.ops.inference)this.ops.inference.abort(),this.ops.inference=null;let A=this.thread.messages.at(-1);if(A?.role==="assistant"&&(A.state.type!=="complete"||A.state.stopReason==="refusal"))this.updateThread({type:"thread:truncate",fromIndex:this.thread.messages.length-1});this._inferenceState.next("idle"),await this.runInferenceAndUpdateThread()}resetRetryAttempts(){this.ephemeralErrorRetryAttempt=0}dismissEphemeralError(){this.clearRetryCountdown(),this.ephemeralError.next(void 0),this.ephemeralErrorRetryAttempt=0}clearRetryCountdown(){if(this.retrySession++,this.retryTimer!==null)clearInterval(this.retryTimer),this.retryTimer=null;this.retryCountdownSeconds.next(void 0)}startRetryCountdown(A){this.clearRetryCountdown();let Q=this.retrySession,$=Date.now()+A*1000;this.retryCountdownSeconds.next(A),this.retryTimer=setInterval(()=>{if(Q!==this.retrySession)return;let B=Math.max(0,Math.ceil(($-Date.now())/1000));if(B<=0)this.clearRetryCountdown(),this.retry().catch((D)=>{P.error("Auto-retry failed",{error:D})});else this.retryCountdownSeconds.next(B)},1000)}addPendingSkill(A){P.debug("addPendingSkill",{threadID:this.threadID,skillName:A.name});let Q=this._pendingSkills.getValue();if(!Q.some(($)=>$.name===A.name))this._pendingSkills.next([...Q,A])}removePendingSkill(A){P.debug("removePendingSkill",{threadID:this.threadID,skillName:A});let Q=this._pendingSkills.getValue();this._pendingSkills.next(Q.filter(($)=>$.name!==A))}clearPendingSkills(){P.debug("clearPendingSkills",{threadID:this.threadID}),this._pendingSkills.next([])}getPendingSkills(){return this._pendingSkills.getValue()}setTestEphemeralError(A){this.ephemeralError.next(A)}async restoreFileChangesFromBackups(){try{let A=await this.fileChangeTracker.restoreFromBackups();P.debug(`Restored ${A.totalBackups} backup files from disk`),await this.updateFileChanges()}catch(A){P.error("Error restoring file changes",A,{threadID:this.threadID})}}async revertFileChanges(A){await this.fileChangeTracker.revertAll(A),await this.updateFileChanges()}async getAllTrackedChanges(){return this.fileChangeTracker.getAllRecords()}async cleanupForkThreads(A=this.thread.messages.length){await this.acquireThread(),this.updateThread({type:"thread:truncate",fromIndex:A})}async getToolUsesToRevert(A=this.thread.messages.length){let Q=new Set;this.thread.messages.slice(0,A).forEach((D)=>{if(D.role==="user"){for(let J of D.content)if(J.type==="tool_result")Q.add(J.toolUseID)}else for(let J of D.content)if(J.type==="tool_use")Q.add(J.id)});let $=new Set,B=await this.fileChangeTracker.getAllRecords();for(let[D]of B.entries())if(!Q.has(D))$.add(D);return $}async getFilesAffectedByTruncation(A){let Q=await this.getToolUsesToRevert(A);return Q.size>0?this.fileChangeTracker.getFilesForToolUses(Q):[]}async cleanupFileChanges(A=this.thread.messages.length){let Q=await this.getToolUsesToRevert(A);if(Q.size===0)return;await this.fileChangeTracker.revertChanges(Q),await this.updateFileChanges()}async performMessageEditCleanup(){await this.toolOrchestrator.cancelAll("system:edited"),await this.cleanupFileChanges(),await this.cleanupForkThreads()}async updateFileChanges(){this.cachedFileChanges=await sF4(this.fileChangeTracker),this.fileChanges.next({files:this.cachedFileChanges})}async injectPendingSkills(A,Q){let $=A.map((B)=>B.name);P.info("Adding info message to prompt skill invocation",{threadID:this.threadID,skillNames:$}),this._awaitingSkillInvocation.next(A),this.thread=h8(this.thread,(B)=>{let D=B.nextMessageId??0;B.nextMessageId=D+1,B.messages.push({role:"info",messageId:D,content:[{type:"text",text:`You MUST call the ${n7} tool to load: ${$.join(", ")}. Do this immediately before responding.`}]}),B.v++})}checkAndAppendAwaitedSkills(){let A=this._awaitingSkillInvocation.getValue();if(A.length===0)return;this._awaitingSkillInvocation.next([]);let{updatedThread:Q,uninvoked:$}=M33(this.thread,{toolName:n7,items:A,wasInvoked:(B,D)=>B.some((J)=>J.name===n7&&J.input.name===D.name),toToolInput:(B)=>({name:B.name,arguments:B.arguments})});if($.length>0)P.info("Skills not invoked by model, appending tool_use blocks",{threadID:this.threadID,uninvokedSkills:$.map((B)=>B.name)}),this.thread=Q}async executeHandoff(A){P.info("Executing handoff",{threadID:this.threadID,goal:A}),this.handoffState.next({goal:A});try{let{threadWorkerService:Q}=await Promise.resolve().then(() => (sq(),iO4)),$={toolService:this.deps.toolService,configService:this.deps.configService,skillService:this.deps.skillService,getThreadEnvironment:this.deps.getThreadEnvironment,getEnvironmentData:this.deps.getEnvironmentData},{threadID:B}=await Q.handoff(this.deps,{threadID:this.threadID,goal:A,images:[],mode:"initial",agentMode:this.thread.agentMode,queuedMessages:this.thread.queuedMessages,clearQueuedMessages:!0,blockIndex:0,buildSystemPromptDeps:$});P.info("Handoff thread created and running in background",{fromThreadID:this.threadID,newThreadID:B,goal:A}),this.handoffState.next({goal:A,result:{newThreadID:B}})}catch(Q){P.error("Handoff failed",Q,{threadID:this.threadID,goal:A}),this.handoffState.next({goal:A,result:{error:Q instanceof Error?Q.message:String(Q)}})}}continueInferenceAfterRejection(A=!0){this.shouldContinueAfterRejection=A}getTurnStartTime(){return this._turnStartTime.getValue()}setTurnStartTime(A){this._turnStartTime.next(A)}async asyncDispose(){if(this.isDisposed)return;if(P.debug("ThreadWorker disposal starting",{name:"ThreadWorker.dispose",threadID:this.threadID,activeToolCount:this.toolOrchestrator.getRunningToolIds().length}),this.isDisposed=!0,await this.toolOrchestrator.cancelAll("system:disposed"),this.disposed$.next(),this.disposed$.complete(),this.clearRetryCountdown(),this._state.complete(),this.ephemeralError.complete(),this._inferenceState.complete(),this.fileChanges.complete(),this.toolCallUpdates.complete(),this.retryCountdownSeconds.complete(),this.toolOrchestrator.dispose(),this.ops.inference)this.ops.inference.abort(),this.ops.inference=null;if(this.ops.titleGeneration)this.ops.titleGeneration.abort(),this.ops.titleGeneration=null;if(this.fileChangeTracker.dispose(),this.threadReadWriter)await this.threadReadWriter.asyncDispose(),this.threadReadWriter=null}async getSelectedAgentMode(){let A=await this.getConfig(),{agentMode:Q}=XZ(A.settings,this.thread);return Q}}function L33(A,Q,$=!1){let B=D9(A,"assistant");if(!B||B.state.type!=="complete"||B.state.stopReason!=="tool_use")return!1;let D=B.content.filter((E)=>E.type==="tool_use").map((E)=>E.id);if(Q&&!D.includes(Q))return P.debug(`tool:data for orphaned tool_use ${Q} - ignoring for inference`,{name:"shouldRunInferenceWithToolData",threadID:A.id}),!1;if(D.length===0)return!1;let J=rF(A);if(!D.every((E)=>{let Z=J.get(E);if(!Z?.run||!f3(Z.run.status))return!1;let U=Z.run.status;if(U==="cancelled"){let X=Z.run.reason;return X?!X.startsWith("user:"):!1}if(U==="rejected-by-user")return $;return!0}))return!1;if(D.every((E)=>{let Z=J.get(E);if(!Z||Z.run.status!=="done")return!1;return Z.run.isFinal===!0}))return!1;return!0}var lO4=o(()=>{Q4();P1();cQ();$Y();p0();M5();a5();ca0();OZ();y5();pT();zK();iE();h4();WH();nh0();Dj();sa0();Dk();Bq();a4();AO();bO4();Yb0();cO4()});var iO4={};C8(iO4,{threadWorkerService:()=>z9});class aO4{threadWorkers=new $v0;async getOrCreateForThread(A,Q){let $=this.threadWorkers.get(Q);if(!$){if($=new aS(A,Q),this.threadWorkers.set(Q,$),this.threadWorkers.size>25)P.info("Many active thread workers detected",{name:"ThreadWorkerService.memoryCheck",threadID:Q,totalWorkerCount:this.threadWorkers.size})}return ea0.record(this.threadWorkers.size),$}async createThreadWorker(A,Q){let $=await this.getOrCreateForThread(A,Q);return await $.resume(),$}async seedThreadMessages(A,Q,$,B){let D=await A.threadService.exclusiveSyncReadWriter(Q),J=B?$.map((E)=>E.role==="user"?{...E,agentMode:B}:E):[...$],F=J.length>0?Math.max(...J.map((E)=>E.messageId))+1:0,Y=D.read();D.write({...Y,agentMode:B??Y.agentMode,messages:J,nextMessageId:F,v:Y.v+1}),await D.asyncDispose()}async applyParentRelationship(A,Q,$,B){let D=Date.now(),{threadID:J,type:F,messageIndex:Y,blockIndex:E,comment:Z}=B;await Q.handle({type:"relationship",relationship:{threadID:J,type:F,role:"child",messageIndex:Y,blockIndex:E,createdAt:D,comment:Z}});let U={threadID:$,type:F,role:"parent",messageIndex:Y,blockIndex:E,createdAt:D,comment:Z},X=this.threadWorkers.get(J);if(X)await X.handle({type:"relationship",relationship:U});else{let G=await A.threadService.exclusiveSyncReadWriter(J);G.update((V)=>{if(!V.relationships)V.relationships=[];if(!V.relationships.some((I)=>I.threadID===U.threadID&&I.type===U.type&&I.role===U.role))V.relationships.push(U)}),await G.asyncDispose()}}async inheritVisibilityIfNeeded(A,Q,$){if(Q.type==="handoff")await UN4(A.threadService,Q.threadID,$)}async sendInitialUserMessage(A,Q){let $=typeof Q==="string"?[{type:"text",text:Q}]:[...Q];await A.handle({type:"user:message",message:{content:$}})}async setDraftContent(A,Q){let $=typeof Q==="string"?Q:[...Q];await A.handle({type:"draft",content:$})}async setPendingNavigation(A,Q){let $=this.threadWorkers.get(A);if($)await $.handle({type:"setPendingNavigation",threadID:Q})}async transferQueuedMessages(A,Q){for(let $ of Q)await A.handle({type:"user:message-queue:enqueue",message:$.queuedMessage})}async createThread(A,Q){let $=Q?.newThreadID??B9(),B=Q?.agentMode,D=!1;if(Q?.seededMessages)await this.seedThreadMessages(A,$,Q.seededMessages,B),D=!0;let J=await this.createThreadWorker(A,$);if(J.thread.messages.length>0&&!D)return P.info("createThread called for existing thread, returning existing worker",{threadID:$,messageCount:J.thread.messages.length}),{threadID:$,worker:J};if(B&&!D)await J.handle({type:"agent-mode",mode:B});if(Q?.parent)await this.applyParentRelationship(A,J,$,Q.parent),await this.inheritVisibilityIfNeeded(A,Q.parent,$);if(Q?.initialUserMessage){if(D)throw Error("initialUserMessage cannot be set when seededMessages is provided");await this.sendInitialUserMessage(J,Q.initialUserMessage)}if(Q?.draftContent){if(D)throw Error("draftContent cannot be set when seededMessages is provided");await this.setDraftContent(J,Q.draftContent)}if(Q?.navigate&&Q?.parent)await this.setPendingNavigation(Q.parent.threadID,$);if(Q?.queuedMessages)await this.transferQueuedMessages(J,Q.queuedMessages);return{threadID:$,worker:J}}async handoff(A,Q){let $=await this.createThreadWorker(A,Q.threadID),B=$.thread,D=Q.images??[],J=Q.signal??new AbortController().signal,{content:F}=await vD0({thread:B,goal:Q.goal,images:D,deps:{configService:A.configService,buildSystemPromptDeps:Q.buildSystemPromptDeps,signal:J,filesystem:Q.filesystem,deadline:Q.deadline}}),Y=typeof F==="string"?F:F.filter((U)=>U.type==="text"||U.type==="image"),E={threadID:Q.threadID,type:"handoff",messageIndex:Q.messageIndex??(B.messages.length?B.messages.length-1:void 0),blockIndex:Q.blockIndex,comment:Q.comment??Q.goal},Z=await this.createThread(A,{newThreadID:Q.newThreadID,agentMode:Q.agentMode??B.agentMode,parent:E,navigate:Q.navigate,queuedMessages:Q.queuedMessages??B.queuedMessages,initialUserMessage:Q.mode==="initial"?Y:void 0,draftContent:Q.mode==="draft"?Y:void 0});if(Q.clearQueuedMessages&&B.queuedMessages?.length)await $.handle({type:"user:message-queue:discard"});return Z}get workers(){return this.threadWorkers.observable}get statuses(){return this.threadWorkers.observable.pipe(y4((A)=>A.size===0?h0.of({}):jA(...Array.from(A.values()).map((Q)=>Q.status.pipe(N1(($)=>[Q.threadID,Q.threadReadWriter?qS(Q.thread,$):void 0])))).pipe(N1((Q)=>Object.fromEntries(Q)))),DK(25),t6())}get(A){return this.threadWorkers.get(A)}prettyPrintToolRun(A,Q){let $=this.threadWorkers.get(A);if(!$)throw Error(`No worker found for thread ${A}`);for(let B of $.thread.messages)for(let D of B.content)if(D.type==="tool_result"&&D.toolUseID===Q)return CZ4(D.run);throw Error(`Tool run not found for thread ${A} and tool use ${Q}`)}async cancelToolOnly(A,Q){await this.threadWorkers.get(A)?.cancelToolOnly(Q)}async cancel(A){await this.threadWorkers.get(A)?.cancel()}async dispose(A){let Q=this.threadWorkers.get(A);if(Q)await Q.cancel(),await Q.asyncDispose(),this.threadWorkers.delete(A),ea0.record(this.threadWorkers.size)}async retry(A){let Q=this.threadWorkers.get(A);if(!Q)throw Error(`No active worker for thread ${A}`);await Q.retry()}async revertFileChanges(A,Q){let $=this.threadWorkers.get(A);if(!$)throw Error(`No active worker for thread ${A}`);await $.revertFileChanges(Q)}async getFilesAffectedByTruncation(A,Q){let $=this.threadWorkers.get(A);if(!$)throw Error(`No active worker for thread ${A}`);return $.getFilesAffectedByTruncation(Q)}async cleanupThreadBackups(A,Q){let $=this.threadWorkers.get(Q);if($)await $.fileChangeTracker.cleanupBackups();else try{await new mL().cleanup(Q),P.debug(`Cleaned up backup files for thread ${Q}`,{threadID:Q})}catch(B){P.error("Error cleaning up thread backups",B,{threadID:Q})}}async disposeAll(){await Promise.all(Array.from(this.threadWorkers.values()).map(async(A)=>await A.asyncDispose())),this.threadWorkers.clear(),ea0.record(0)}}var nO4,O33,ea0,z9;var sq=o(()=>{P1();p0();MZ4();ZN4();Ql();a4();XN4();lO4();nO4=b4(L4(),1),O33=nO4.metrics.getMeter("thread-worker-service"),ea0=O33.createGauge("thread_worker_count",{description:"Number of active thread workers"});z9=new aO4});var Qo0=S((sO4)=>{Object.defineProperty(sO4,"__esModule",{value:!0});sO4.dynamicAnchor=void 0;var Ao0=QA(),j33=EY(),oO4=ap(),R33=U90(),P33={keyword:"$dynamicAnchor",schemaType:"string",code:(A)=>rO4(A,A.schema)};function rO4(A,Q){let{gen:$,it:B}=A;B.schemaEnv.root.dynamicAnchors[Q]=!0;let D=Ao0._`${j33.default.dynamicAnchors}${(0,Ao0.getProperty)(Q)}`,J=B.errSchemaPath==="#"?B.validateName:u33(A);$.if(Ao0._`!${D}`,()=>$.assign(D,J))}sO4.dynamicAnchor=rO4;function u33(A){let{schemaEnv:Q,schema:$,self:B}=A.it,{root:D,baseId:J,localRefs:F,meta:Y}=Q.root,{schemaId:E}=B.opts,Z=new oO4.SchemaEnv({schema:$,schemaId:E,root:D,baseId:J,localRefs:F,meta:Y});return oO4.compileSchema.call(B,Z),(0,R33.getValidate)(A,Z)}sO4.default=P33});var $o0=S(($j4)=>{Object.defineProperty($j4,"__esModule",{value:!0});$j4.dynamicRef=void 0;var eO4=QA(),T33=EY(),Aj4=U90(),v33={keyword:"$dynamicRef",schemaType:"string",code:(A)=>Qj4(A,A.schema)};function Qj4(A,Q){let{gen:$,keyword:B,it:D}=A;if(Q[0]!=="#")throw Error(`"${B}" only supports hash fragment reference`);let J=Q.slice(1);if(D.allErrors)F();else{let E=$.let("valid",!1);F(E),A.ok(E)}function F(E){if(D.schemaEnv.root.dynamicAnchors[J]){let Z=$.let("_v",eO4._`${T33.default.dynamicAnchors}${(0,eO4.getProperty)(J)}`);$.if(Z,Y(Z,E),Y(D.validateName,E))}else Y(D.validateName,E)()}function Y(E,Z){return Z?()=>$.block(()=>{(0,Aj4.callRef)(A,E),$.let(Z,!0)}):()=>(0,Aj4.callRef)(A,E)}}$j4.dynamicRef=Qj4;$j4.default=v33});var Jj4=S((Dj4)=>{Object.defineProperty(Dj4,"__esModule",{value:!0});var S33=Qo0(),f33=gA(),y33={keyword:"$recursiveAnchor",schemaType:"boolean",code(A){if(A.schema)(0,S33.dynamicAnchor)(A,"");else(0,f33.checkStrictMode)(A.it,"$recursiveAnchor: false is ignored")}};Dj4.default=y33});var Yj4=S((Fj4)=>{Object.defineProperty(Fj4,"__esModule",{value:!0});var b33=$o0(),h33={keyword:"$recursiveRef",schemaType:"string",code:(A)=>(0,b33.dynamicRef)(A,A.schema)};Fj4.default=h33});var Zj4=S((Ej4)=>{Object.defineProperty(Ej4,"__esModule",{value:!0});var m33=Qo0(),d33=$o0(),p33=Jj4(),c33=Yj4(),l33=[m33.default,d33.default,p33.default,c33.default];Ej4.default=l33});var Gj4=S((Xj4)=>{Object.defineProperty(Xj4,"__esModule",{value:!0});var Uj4=W90(),n33={keyword:"dependentRequired",type:"object",schemaType:"object",error:Uj4.error,code:(A)=>(0,Uj4.validatePropertyDeps)(A)};Xj4.default=n33});var Kj4=S((Vj4)=>{Object.defineProperty(Vj4,"__esModule",{value:!0});var o33=W90(),r33={keyword:"dependentSchemas",type:"object",schemaType:"object",code:(A)=>(0,o33.validateSchemaDeps)(A)};Vj4.default=r33});var Ij4=S((zj4)=>{Object.defineProperty(zj4,"__esModule",{value:!0});var t33=gA(),e33={keyword:["maxContains","minContains"],type:"array",schemaType:"number",code({keyword:A,parentSchema:Q,it:$}){if(Q.contains===void 0)(0,t33.checkStrictMode)($,`"${A}" without "contains" is ignored`)}};zj4.default=e33});var Hj4=S((Wj4)=>{Object.defineProperty(Wj4,"__esModule",{value:!0});var Q53=Gj4(),$53=Kj4(),B53=Ij4(),D53=[Q53.default,$53.default,B53.default];Wj4.default=D53});var wj4=S((Nj4)=>{Object.defineProperty(Nj4,"__esModule",{value:!0});var tq=QA(),qj4=gA(),F53=EY(),Y53={message:"must NOT have unevaluated properties",params:({params:A})=>tq._`{unevaluatedProperty: ${A.unevaluatedProperty}}`},E53={keyword:"unevaluatedProperties",type:"object",schemaType:["boolean","object"],trackErrors:!0,error:Y53,code(A){let{gen:Q,schema:$,data:B,errsCount:D,it:J}=A;if(!D)throw Error("ajv implementation error");let{allErrors:F,props:Y}=J;if(Y instanceof tq.Name)Q.if(tq._`${Y} !== true`,()=>Q.forIn("key",B,(X)=>Q.if(Z(Y,X),()=>E(X))));else if(Y!==!0)Q.forIn("key",B,(X)=>Y===void 0?E(X):Q.if(U(Y,X),()=>E(X)));J.props=!0,A.ok(tq._`${D} === ${F53.default.errors}`);function E(X){if($===!1){if(A.setParams({unevaluatedProperty:X}),A.error(),!F)Q.break();return}if(!(0,qj4.alwaysValidSchema)(J,$)){let G=Q.name("valid");if(A.subschema({keyword:"unevaluatedProperties",dataProp:X,dataPropType:qj4.Type.Str},G),!F)Q.if((0,tq.not)(G),()=>Q.break())}}function Z(X,G){return tq._`!${X} || !${X}[${G}]`}function U(X,G){let V=[];for(let K in X)if(X[K]===!0)V.push(tq._`${G} !== ${K}`);return(0,tq.and)(...V)}}};Nj4.default=E53});var Lj4=S((Mj4)=>{Object.defineProperty(Mj4,"__esModule",{value:!0});var Fj=QA(),Cj4=gA(),U53={message:({params:{len:A}})=>Fj.str`must NOT have more than ${A} items`,params:({params:{len:A}})=>Fj._`{limit: ${A}}`},X53={keyword:"unevaluatedItems",type:"array",schemaType:["boolean","object"],error:U53,code(A){let{gen:Q,schema:$,data:B,it:D}=A,J=D.items||0;if(J===!0)return;let F=Q.const("len",Fj._`${B}.length`);if($===!1)A.setParams({len:J}),A.fail(Fj._`${F} > ${J}`);else if(typeof $=="object"&&!(0,Cj4.alwaysValidSchema)(D,$)){let E=Q.var("valid",Fj._`${F} <= ${J}`);Q.if((0,Fj.not)(E),()=>Y(E,J)),A.ok(E)}D.items=!0;function Y(E,Z){Q.forRange("i",Z,F,(U)=>{if(A.subschema({keyword:"unevaluatedItems",dataProp:U,dataPropType:Cj4.Type.Num},E),!D.allErrors)Q.if((0,Fj.not)(E),()=>Q.break())})}}};Mj4.default=X53});var jj4=S((Oj4)=>{Object.defineProperty(Oj4,"__esModule",{value:!0});var V53=wj4(),K53=Lj4(),z53=[V53.default,K53.default];Oj4.default=z53});var uj4=S((Pj4)=>{Object.defineProperty(Pj4,"__esModule",{value:!0});var W53=fy0(),H53=by0(),q53=ly0(),N53=Zj4(),w53=Hj4(),C53=jj4(),M53=iy0(),Rj4=ny0(),L53=[N53.default,W53.default,H53.default,(0,q53.default)(!0),M53.default,Rj4.metadataVocabulary,Rj4.contentVocabulary,w53.default,C53.default];Pj4.default=L53});var _j4=S((qQ2,j53)=>{j53.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/schema",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/core":!0,"https://json-schema.org/draft/2020-12/vocab/applicator":!0,"https://json-schema.org/draft/2020-12/vocab/unevaluated":!0,"https://json-schema.org/draft/2020-12/vocab/validation":!0,"https://json-schema.org/draft/2020-12/vocab/meta-data":!0,"https://json-schema.org/draft/2020-12/vocab/format-annotation":!0,"https://json-schema.org/draft/2020-12/vocab/content":!0},$dynamicAnchor:"meta",title:"Core and Validation specifications meta-schema",allOf:[{$ref:"meta/core"},{$ref:"meta/applicator"},{$ref:"meta/unevaluated"},{$ref:"meta/validation"},{$ref:"meta/meta-data"},{$ref:"meta/format-annotation"},{$ref:"meta/content"}],type:["object","boolean"],$comment:"This meta-schema also defines keywords that have appeared in previous drafts in order to prevent incompatible extensions as they remain in common use.",properties:{definitions:{$comment:'"definitions" has been replaced by "$defs".',type:"object",additionalProperties:{$dynamicRef:"#meta"},deprecated:!0,default:{}},dependencies:{$comment:'"dependencies" has been split and replaced by "dependentSchemas" and "dependentRequired" in order to serve their differing semantics.',type:"object",additionalProperties:{anyOf:[{$dynamicRef:"#meta"},{$ref:"meta/validation#/$defs/stringArray"}]},deprecated:!0,default:{}},$recursiveAnchor:{$comment:'"$recursiveAnchor" has been replaced by "$dynamicAnchor".',$ref:"meta/core#/$defs/anchorString",deprecated:!0},$recursiveRef:{$comment:'"$recursiveRef" has been replaced by "$dynamicRef".',$ref:"meta/core#/$defs/uriReferenceString",deprecated:!0}}}});var Tj4=S((NQ2,R53)=>{R53.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/applicator",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/applicator":!0},$dynamicAnchor:"meta",title:"Applicator vocabulary meta-schema",type:["object","boolean"],properties:{prefixItems:{$ref:"#/$defs/schemaArray"},items:{$dynamicRef:"#meta"},contains:{$dynamicRef:"#meta"},additionalProperties:{$dynamicRef:"#meta"},properties:{type:"object",additionalProperties:{$dynamicRef:"#meta"},default:{}},patternProperties:{type:"object",additionalProperties:{$dynamicRef:"#meta"},propertyNames:{format:"regex"},default:{}},dependentSchemas:{type:"object",additionalProperties:{$dynamicRef:"#meta"},default:{}},propertyNames:{$dynamicRef:"#meta"},if:{$dynamicRef:"#meta"},then:{$dynamicRef:"#meta"},else:{$dynamicRef:"#meta"},allOf:{$ref:"#/$defs/schemaArray"},anyOf:{$ref:"#/$defs/schemaArray"},oneOf:{$ref:"#/$defs/schemaArray"},not:{$dynamicRef:"#meta"}},$defs:{schemaArray:{type:"array",minItems:1,items:{$dynamicRef:"#meta"}}}}});var vj4=S((wQ2,P53)=>{P53.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/unevaluated",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/unevaluated":!0},$dynamicAnchor:"meta",title:"Unevaluated applicator vocabulary meta-schema",type:["object","boolean"],properties:{unevaluatedItems:{$dynamicRef:"#meta"},unevaluatedProperties:{$dynamicRef:"#meta"}}}});var kj4=S((CQ2,u53)=>{u53.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/content",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/content":!0},$dynamicAnchor:"meta",title:"Content vocabulary meta-schema",type:["object","boolean"],properties:{contentEncoding:{type:"string"},contentMediaType:{type:"string"},contentSchema:{$dynamicRef:"#meta"}}}});var Sj4=S((MQ2,_53)=>{_53.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/core",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/core":!0},$dynamicAnchor:"meta",title:"Core vocabulary meta-schema",type:["object","boolean"],properties:{$id:{$ref:"#/$defs/uriReferenceString",$comment:"Non-empty fragments not allowed.",pattern:"^[^#]*#?$"},$schema:{$ref:"#/$defs/uriString"},$ref:{$ref:"#/$defs/uriReferenceString"},$anchor:{$ref:"#/$defs/anchorString"},$dynamicRef:{$ref:"#/$defs/uriReferenceString"},$dynamicAnchor:{$ref:"#/$defs/anchorString"},$vocabulary:{type:"object",propertyNames:{$ref:"#/$defs/uriString"},additionalProperties:{type:"boolean"}},$comment:{type:"string"},$defs:{type:"object",additionalProperties:{$dynamicRef:"#meta"}}},$defs:{anchorString:{type:"string",pattern:"^[A-Za-z_][-A-Za-z0-9._]*$"},uriString:{type:"string",format:"uri"},uriReferenceString:{type:"string",format:"uri-reference"}}}});var fj4=S((LQ2,T53)=>{T53.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/format-annotation",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/format-annotation":!0},$dynamicAnchor:"meta",title:"Format vocabulary meta-schema for annotation results",type:["object","boolean"],properties:{format:{type:"string"}}}});var yj4=S((OQ2,v53)=>{v53.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/meta-data",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/meta-data":!0},$dynamicAnchor:"meta",title:"Meta-data vocabulary meta-schema",type:["object","boolean"],properties:{title:{type:"string"},description:{type:"string"},default:!0,deprecated:{type:"boolean",default:!1},readOnly:{type:"boolean",default:!1},writeOnly:{type:"boolean",default:!1},examples:{type:"array",items:!0}}}});var xj4=S((jQ2,k53)=>{k53.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/validation",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/validation":!0},$dynamicAnchor:"meta",title:"Validation vocabulary meta-schema",type:["object","boolean"],properties:{type:{anyOf:[{$ref:"#/$defs/simpleTypes"},{type:"array",items:{$ref:"#/$defs/simpleTypes"},minItems:1,uniqueItems:!0}]},const:!0,enum:{type:"array",items:!0},multipleOf:{type:"number",exclusiveMinimum:0},maximum:{type:"number"},exclusiveMaximum:{type:"number"},minimum:{type:"number"},exclusiveMinimum:{type:"number"},maxLength:{$ref:"#/$defs/nonNegativeInteger"},minLength:{$ref:"#/$defs/nonNegativeIntegerDefault0"},pattern:{type:"string",format:"regex"},maxItems:{$ref:"#/$defs/nonNegativeInteger"},minItems:{$ref:"#/$defs/nonNegativeIntegerDefault0"},uniqueItems:{type:"boolean",default:!1},maxContains:{$ref:"#/$defs/nonNegativeInteger"},minContains:{$ref:"#/$defs/nonNegativeInteger",default:1},maxProperties:{$ref:"#/$defs/nonNegativeInteger"},minProperties:{$ref:"#/$defs/nonNegativeIntegerDefault0"},required:{$ref:"#/$defs/stringArray"},dependentRequired:{type:"object",additionalProperties:{$ref:"#/$defs/stringArray"}}},$defs:{nonNegativeInteger:{type:"integer",minimum:0},nonNegativeIntegerDefault0:{$ref:"#/$defs/nonNegativeInteger",default:0},simpleTypes:{enum:["array","boolean","integer","null","number","object","string"]},stringArray:{type:"array",items:{type:"string"},uniqueItems:!0,default:[]}}}});var hj4=S((bj4)=>{Object.defineProperty(bj4,"__esModule",{value:!0});var S53=_j4(),f53=Tj4(),y53=vj4(),x53=kj4(),b53=Sj4(),h53=fj4(),g53=yj4(),m53=xj4(),d53=["/properties"];function p53(A){return[S53,f53,y53,x53,b53,Q(this,h53),g53,Q(this,m53)].forEach(($)=>this.addMetaSchema($,void 0,!1)),this;function Q($,B){return A?$.$dataMetaSchema(B,d53):B}}bj4.default=p53});var gj4=S((HD,Do0)=>{Object.defineProperty(HD,"__esModule",{value:!0});HD.MissingRefError=HD.ValidationError=HD.CodeGen=HD.Name=HD.nil=HD.stringify=HD.str=HD._=HD.KeywordCxt=HD.Ajv2020=void 0;var l53=Sy0(),i53=uj4(),n53=oy0(),a53=hj4(),Bo0="https://json-schema.org/draft/2020-12/schema";class xa extends l53.default{constructor(A={}){super({...A,dynamicRef:!0,next:!0,unevaluated:!0})}_addVocabularies(){if(super._addVocabularies(),i53.default.forEach((A)=>this.addVocabulary(A)),this.opts.discriminator)this.addKeyword(n53.default)}_addDefaultMetaSchema(){super._addDefaultMetaSchema();let{$data:A,meta:Q}=this.opts;if(!Q)return;a53.default.call(this,A),this.refs["http://json-schema.org/schema"]=Bo0}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(Bo0)?Bo0:void 0)}}HD.Ajv2020=xa;Do0.exports=HD=xa;Do0.exports.Ajv2020=xa;Object.defineProperty(HD,"__esModule",{value:!0});HD.default=xa;var o53=Qv();Object.defineProperty(HD,"KeywordCxt",{enumerable:!0,get:function(){return o53.KeywordCxt}});var oS=QA();Object.defineProperty(HD,"_",{enumerable:!0,get:function(){return oS._}});Object.defineProperty(HD,"str",{enumerable:!0,get:function(){return oS.str}});Object.defineProperty(HD,"stringify",{enumerable:!0,get:function(){return oS.stringify}});Object.defineProperty(HD,"nil",{enumerable:!0,get:function(){return oS.nil}});Object.defineProperty(HD,"Name",{enumerable:!0,get:function(){return oS.Name}});Object.defineProperty(HD,"CodeGen",{enumerable:!0,get:function(){return oS.CodeGen}});var r53=ip();Object.defineProperty(HD,"ValidationError",{enumerable:!0,get:function(){return r53.default}});var s53=$v();Object.defineProperty(HD,"MissingRefError",{enumerable:!0,get:function(){return s53.default}})});var dj4=S((mj4)=>{(()=>{var A={349:(F,Y,E)=>{Object.defineProperty(Y,"__esModule",{value:!0}),Y.CircularList=void 0;let Z=E(460),U=E(844);class X extends U.Disposable{constructor(G){super(),this._maxLength=G,this.onDeleteEmitter=this.register(new Z.EventEmitter),this.onDelete=this.onDeleteEmitter.event,this.onInsertEmitter=this.register(new Z.EventEmitter),this.onInsert=this.onInsertEmitter.event,this.onTrimEmitter=this.register(new Z.EventEmitter),this.onTrim=this.onTrimEmitter.event,this._array=Array(this._maxLength),this._startIndex=0,this._length=0}get maxLength(){return this._maxLength}set maxLength(G){if(this._maxLength===G)return;let V=Array(G);for(let K=0;K<Math.min(G,this.length);K++)V[K]=this._array[this._getCyclicIndex(K)];this._array=V,this._maxLength=G,this._startIndex=0}get length(){return this._length}set length(G){if(G>this._length)for(let V=this._length;V<G;V++)this._array[V]=void 0;this._length=G}get(G){return this._array[this._getCyclicIndex(G)]}set(G,V){this._array[this._getCyclicIndex(G)]=V}push(G){this._array[this._getCyclicIndex(this._length)]=G,this._length===this._maxLength?(this._startIndex=++this._startIndex%this._maxLength,this.onTrimEmitter.fire(1)):this._length++}recycle(){if(this._length!==this._maxLength)throw Error("Can only recycle when the buffer is full");return this._startIndex=++this._startIndex%this._maxLength,this.onTrimEmitter.fire(1),this._array[this._getCyclicIndex(this._length-1)]}get isFull(){return this._length===this._maxLength}pop(){return this._array[this._getCyclicIndex(this._length---1)]}splice(G,V,...K){if(V){for(let I=G;I<this._length-V;I++)this._array[this._getCyclicIndex(I)]=this._array[this._getCyclicIndex(I+V)];this._length-=V,this.onDeleteEmitter.fire({index:G,amount:V})}for(let I=this._length-1;I>=G;I--)this._array[this._getCyclicIndex(I+K.length)]=this._array[this._getCyclicIndex(I)];for(let I=0;I<K.length;I++)this._array[this._getCyclicIndex(G+I)]=K[I];if(K.length&&this.onInsertEmitter.fire({index:G,amount:K.length}),this._length+K.length>this._maxLength){let I=this._length+K.length-this._maxLength;this._startIndex+=I,this._length=this._maxLength,this.onTrimEmitter.fire(I)}else this._length+=K.length}trimStart(G){G>this._length&&(G=this._length),this._startIndex+=G,this._length-=G,this.onTrimEmitter.fire(G)}shiftElements(G,V,K){if(!(V<=0)){if(G<0||G>=this._length)throw Error("start argument out of range");if(G+K<0)throw Error("Cannot shift elements in list beyond index 0");if(K>0){for(let z=V-1;z>=0;z--)this.set(G+z+K,this.get(G+z));let I=G+V+K-this._length;if(I>0)for(this._length+=I;this._length>this._maxLength;)this._length--,this._startIndex++,this.onTrimEmitter.fire(1)}else for(let I=0;I<V;I++)this.set(G+I+K,this.get(G+I))}}_getCyclicIndex(G){return(this._startIndex+G)%this._maxLength}}Y.CircularList=X},439:(F,Y)=>{Object.defineProperty(Y,"__esModule",{value:!0}),Y.clone=void 0,Y.clone=function E(Z,U=5){if(typeof Z!="object")return Z;let X=Array.isArray(Z)?[]:{};for(let G in Z)X[G]=U<=1?Z[G]:Z[G]&&E(Z[G],U-1);return X}},969:(F,Y,E)=>{Object.defineProperty(Y,"__esModule",{value:!0}),Y.CoreTerminal=void 0;let Z=E(844),U=E(585),X=E(348),G=E(866),V=E(744),K=E(302),I=E(83),z=E(460),W=E(753),H=E(480),q=E(994),N=E(282),w=E(435),O=E(981),L=E(660),j=!1;class k extends Z.Disposable{get onScroll(){return this._onScrollApi||(this._onScrollApi=this.register(new z.EventEmitter),this._onScroll.event((_)=>{this._onScrollApi?.fire(_.position)})),this._onScrollApi.event}get cols(){return this._bufferService.cols}get rows(){return this._bufferService.rows}get buffers(){return this._bufferService.buffers}get options(){return this.optionsService.options}set options(_){for(let f in _)this.optionsService.options[f]=_[f]}constructor(_){super(),this._windowsWrappingHeuristics=this.register(new Z.MutableDisposable),this._onBinary=this.register(new z.EventEmitter),this.onBinary=this._onBinary.event,this._onData=this.register(new z.EventEmitter),this.onData=this._onData.event,this._onLineFeed=this.register(new z.EventEmitter),this.onLineFeed=this._onLineFeed.event,this._onResize=this.register(new z.EventEmitter),this.onResize=this._onResize.event,this._onWriteParsed=this.register(new z.EventEmitter),this.onWriteParsed=this._onWriteParsed.event,this._onScroll=this.register(new z.EventEmitter),this._instantiationService=new X.InstantiationService,this.optionsService=this.register(new K.OptionsService(_)),this._instantiationService.setService(U.IOptionsService,this.optionsService),this._bufferService=this.register(this._instantiationService.createInstance(V.BufferService)),this._instantiationService.setService(U.IBufferService,this._bufferService),this._logService=this.register(this._instantiationService.createInstance(G.LogService)),this._instantiationService.setService(U.ILogService,this._logService),this.coreService=this.register(this._instantiationService.createInstance(I.CoreService)),this._instantiationService.setService(U.ICoreService,this.coreService),this.coreMouseService=this.register(this._instantiationService.createInstance(W.CoreMouseService)),this._instantiationService.setService(U.ICoreMouseService,this.coreMouseService),this.unicodeService=this.register(this._instantiationService.createInstance(H.UnicodeService)),this._instantiationService.setService(U.IUnicodeService,this.unicodeService),this._charsetService=this._instantiationService.createInstance(q.CharsetService),this._instantiationService.setService(U.ICharsetService,this._charsetService),this._oscLinkService=this._instantiationService.createInstance(L.OscLinkService),this._instantiationService.setService(U.IOscLinkService,this._oscLinkService),this._inputHandler=this.register(new w.InputHandler(this._bufferService,this._charsetService,this.coreService,this._logService,this.optionsService,this._oscLinkService,this.coreMouseService,this.unicodeService)),this.register((0,z.forwardEvent)(this._inputHandler.onLineFeed,this._onLineFeed)),this.register(this._inputHandler),this.register((0,z.forwardEvent)(this._bufferService.onResize,this._onResize)),this.register((0,z.forwardEvent)(this.coreService.onData,this._onData)),this.register((0,z.forwardEvent)(this.coreService.onBinary,this._onBinary)),this.register(this.coreService.onRequestScrollToBottom(()=>this.scrollToBottom())),this.register(this.coreService.onUserInput(()=>this._writeBuffer.handleUserInput())),this.register(this.optionsService.onMultipleOptionChange(["windowsMode","windowsPty"],()=>this._handleWindowsPtyOptionChange())),this.register(this._bufferService.onScroll((f)=>{this._onScroll.fire({position:this._bufferService.buffer.ydisp,source:0}),this._inputHandler.markRangeDirty(this._bufferService.buffer.scrollTop,this._bufferService.buffer.scrollBottom)})),this.register(this._inputHandler.onScroll((f)=>{this._onScroll.fire({position:this._bufferService.buffer.ydisp,source:0}),this._inputHandler.markRangeDirty(this._bufferService.buffer.scrollTop,this._bufferService.buffer.scrollBottom)})),this._writeBuffer=this.register(new O.WriteBuffer((f,h)=>this._inputHandler.parse(f,h))),this.register((0,z.forwardEvent)(this._writeBuffer.onWriteParsed,this._onWriteParsed))}write(_,f){this._writeBuffer.write(_,f)}writeSync(_,f){this._logService.logLevel<=U.LogLevelEnum.WARN&&!j&&(this._logService.warn("writeSync is unreliable and will be removed soon."),j=!0),this._writeBuffer.writeSync(_,f)}input(_,f=!0){this.coreService.triggerDataEvent(_,f)}resize(_,f){isNaN(_)||isNaN(f)||(_=Math.max(_,V.MINIMUM_COLS),f=Math.max(f,V.MINIMUM_ROWS),this._bufferService.resize(_,f))}scroll(_,f=!1){this._bufferService.scroll(_,f)}scrollLines(_,f,h){this._bufferService.scrollLines(_,f,h)}scrollPages(_){this.scrollLines(_*(this.rows-1))}scrollToTop(){this.scrollLines(-this._bufferService.buffer.ydisp)}scrollToBottom(){this.scrollLines(this._bufferService.buffer.ybase-this._bufferService.buffer.ydisp)}scrollToLine(_){let f=_-this._bufferService.buffer.ydisp;f!==0&&this.scrollLines(f)}registerEscHandler(_,f){return this._inputHandler.registerEscHandler(_,f)}registerDcsHandler(_,f){return this._inputHandler.registerDcsHandler(_,f)}registerCsiHandler(_,f){return this._inputHandler.registerCsiHandler(_,f)}registerOscHandler(_,f){return this._inputHandler.registerOscHandler(_,f)}_setup(){this._handleWindowsPtyOptionChange()}reset(){this._inputHandler.reset(),this._bufferService.reset(),this._charsetService.reset(),this.coreService.reset(),this.coreMouseService.reset()}_handleWindowsPtyOptionChange(){let _=!1,f=this.optionsService.rawOptions.windowsPty;f&&f.buildNumber!==void 0&&f.buildNumber!==void 0?_=f.backend==="conpty"&&f.buildNumber<21376:this.optionsService.rawOptions.windowsMode&&(_=!0),_?this._enableWindowsWrappingHeuristics():this._windowsWrappingHeuristics.clear()}_enableWindowsWrappingHeuristics(){if(!this._windowsWrappingHeuristics.value){let _=[];_.push(this.onLineFeed(N.updateWindowsModeWrappedState.bind(null,this._bufferService))),_.push(this.registerCsiHandler({final:"H"},()=>((0,N.updateWindowsModeWrappedState)(this._bufferService),!1))),this._windowsWrappingHeuristics.value=(0,Z.toDisposable)(()=>{for(let f of _)f.dispose()})}}}Y.CoreTerminal=k},460:(F,Y)=>{Object.defineProperty(Y,"__esModule",{value:!0}),Y.runAndSubscribe=Y.forwardEvent=Y.EventEmitter=void 0,Y.EventEmitter=class{constructor(){this._listeners=[],this._disposed=!1}get event(){return this._event||(this._event=(E)=>{return this._listeners.push(E),{dispose:()=>{if(!this._disposed){for(let U=0;U<this._listeners.length;U++)if(this._listeners[U]===E)return void this._listeners.splice(U,1)}}}}),this._event}fire(E,Z){let U=[];for(let X=0;X<this._listeners.length;X++)U.push(this._listeners[X]);for(let X=0;X<U.length;X++)U[X].call(void 0,E,Z)}dispose(){this.clearListeners(),this._disposed=!0}clearListeners(){this._listeners&&(this._listeners.length=0)}},Y.forwardEvent=function(E,Z){return E((U)=>Z.fire(U))},Y.runAndSubscribe=function(E,Z){return Z(void 0),E((U)=>Z(U))}},435:function(F,Y,E){var Z=this&&this.__decorate||function(g,i,r,A0){var I0,E0=arguments.length,W0=E0<3?i:A0===null?A0=Object.getOwnPropertyDescriptor(i,r):A0;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")W0=Reflect.decorate(g,i,r,A0);else for(var $0=g.length-1;$0>=0;$0--)(I0=g[$0])&&(W0=(E0<3?I0(W0):E0>3?I0(i,r,W0):I0(i,r))||W0);return E0>3&&W0&&Object.defineProperty(i,r,W0),W0},U=this&&this.__param||function(g,i){return function(r,A0){i(r,A0,g)}};Object.defineProperty(Y,"__esModule",{value:!0}),Y.InputHandler=Y.WindowsOptionsReportType=void 0;let X=E(584),G=E(116),V=E(15),K=E(844),I=E(482),z=E(437),W=E(460),H=E(643),q=E(511),N=E(734),w=E(585),O=E(480),L=E(242),j=E(351),k=E(941),_={"(":0,")":1,"*":2,"+":3,"-":1,".":2},f=131072;function h(g,i){if(g>24)return i.setWinLines||!1;switch(g){case 1:return!!i.restoreWin;case 2:return!!i.minimizeWin;case 3:return!!i.setWinPosition;case 4:return!!i.setWinSizePixels;case 5:return!!i.raiseWin;case 6:return!!i.lowerWin;case 7:return!!i.refreshWin;case 8:return!!i.setWinSizeChars;case 9:return!!i.maximizeWin;case 10:return!!i.fullscreenWin;case 11:return!!i.getWinState;case 13:return!!i.getWinPosition;case 14:return!!i.getWinSizePixels;case 15:return!!i.getScreenSizePixels;case 16:return!!i.getCellSizePixels;case 18:return!!i.getWinSizeChars;case 19:return!!i.getScreenSizeChars;case 20:return!!i.getIconTitle;case 21:return!!i.getWinTitle;case 22:return!!i.pushTitle;case 23:return!!i.popTitle;case 24:return!!i.setWinLines}return!1}var b;(function(g){g[g.GET_WIN_SIZE_PIXELS=0]="GET_WIN_SIZE_PIXELS",g[g.GET_CELL_SIZE_PIXELS=1]="GET_CELL_SIZE_PIXELS"})(b||(Y.WindowsOptionsReportType=b={}));let v=0;class y extends K.Disposable{getAttrData(){return this._curAttrData}constructor(g,i,r,A0,I0,E0,W0,$0,j0=new V.EscapeSequenceParser){super(),this._bufferService=g,this._charsetService=i,this._coreService=r,this._logService=A0,this._optionsService=I0,this._oscLinkService=E0,this._coreMouseService=W0,this._unicodeService=$0,this._parser=j0,this._parseBuffer=new Uint32Array(4096),this._stringDecoder=new I.StringToUtf32,this._utf8Decoder=new I.Utf8ToUtf32,this._workCell=new q.CellData,this._windowTitle="",this._iconName="",this._windowTitleStack=[],this._iconNameStack=[],this._curAttrData=z.DEFAULT_ATTR_DATA.clone(),this._eraseAttrDataInternal=z.DEFAULT_ATTR_DATA.clone(),this._onRequestBell=this.register(new W.EventEmitter),this.onRequestBell=this._onRequestBell.event,this._onRequestRefreshRows=this.register(new W.EventEmitter),this.onRequestRefreshRows=this._onRequestRefreshRows.event,this._onRequestReset=this.register(new W.EventEmitter),this.onRequestReset=this._onRequestReset.event,this._onRequestSendFocus=this.register(new W.EventEmitter),this.onRequestSendFocus=this._onRequestSendFocus.event,this._onRequestSyncScrollBar=this.register(new W.EventEmitter),this.onRequestSyncScrollBar=this._onRequestSyncScrollBar.event,this._onRequestWindowsOptionsReport=this.register(new W.EventEmitter),this.onRequestWindowsOptionsReport=this._onRequestWindowsOptionsReport.event,this._onA11yChar=this.register(new W.EventEmitter),this.onA11yChar=this._onA11yChar.event,this._onA11yTab=this.register(new W.EventEmitter),this.onA11yTab=this._onA11yTab.event,this._onCursorMove=this.register(new W.EventEmitter),this.onCursorMove=this._onCursorMove.event,this._onLineFeed=this.register(new W.EventEmitter),this.onLineFeed=this._onLineFeed.event,this._onScroll=this.register(new W.EventEmitter),this.onScroll=this._onScroll.event,this._onTitleChange=this.register(new W.EventEmitter),this.onTitleChange=this._onTitleChange.event,this._onColor=this.register(new W.EventEmitter),this.onColor=this._onColor.event,this._parseStack={paused:!1,cursorStartX:0,cursorStartY:0,decodedLength:0,position:0},this._specialColors=[256,257,258],this.register(this._parser),this._dirtyRowTracker=new p(this._bufferService),this._activeBuffer=this._bufferService.buffer,this.register(this._bufferService.buffers.onBufferActivate((Q0)=>this._activeBuffer=Q0.activeBuffer)),this._parser.setCsiHandlerFallback((Q0,M0)=>{this._logService.debug("Unknown CSI code: ",{identifier:this._parser.identToString(Q0),params:M0.toArray()})}),this._parser.setEscHandlerFallback((Q0)=>{this._logService.debug("Unknown ESC code: ",{identifier:this._parser.identToString(Q0)})}),this._parser.setExecuteHandlerFallback((Q0)=>{this._logService.debug("Unknown EXECUTE code: ",{code:Q0})}),this._parser.setOscHandlerFallback((Q0,M0,n)=>{this._logService.debug("Unknown OSC code: ",{identifier:Q0,action:M0,data:n})}),this._parser.setDcsHandlerFallback((Q0,M0,n)=>{M0==="HOOK"&&(n=n.toArray()),this._logService.debug("Unknown DCS code: ",{identifier:this._parser.identToString(Q0),action:M0,payload:n})}),this._parser.setPrintHandler((Q0,M0,n)=>this.print(Q0,M0,n)),this._parser.registerCsiHandler({final:"@"},(Q0)=>this.insertChars(Q0)),this._parser.registerCsiHandler({intermediates:" ",final:"@"},(Q0)=>this.scrollLeft(Q0)),this._parser.registerCsiHandler({final:"A"},(Q0)=>this.cursorUp(Q0)),this._parser.registerCsiHandler({intermediates:" ",final:"A"},(Q0)=>this.scrollRight(Q0)),this._parser.registerCsiHandler({final:"B"},(Q0)=>this.cursorDown(Q0)),this._parser.registerCsiHandler({final:"C"},(Q0)=>this.cursorForward(Q0)),this._parser.registerCsiHandler({final:"D"},(Q0)=>this.cursorBackward(Q0)),this._parser.registerCsiHandler({final:"E"},(Q0)=>this.cursorNextLine(Q0)),this._parser.registerCsiHandler({final:"F"},(Q0)=>this.cursorPrecedingLine(Q0)),this._parser.registerCsiHandler({final:"G"},(Q0)=>this.cursorCharAbsolute(Q0)),this._parser.registerCsiHandler({final:"H"},(Q0)=>this.cursorPosition(Q0)),this._parser.registerCsiHandler({final:"I"},(Q0)=>this.cursorForwardTab(Q0)),this._parser.registerCsiHandler({final:"J"},(Q0)=>this.eraseInDisplay(Q0,!1)),this._parser.registerCsiHandler({prefix:"?",final:"J"},(Q0)=>this.eraseInDisplay(Q0,!0)),this._parser.registerCsiHandler({final:"K"},(Q0)=>this.eraseInLine(Q0,!1)),this._parser.registerCsiHandler({prefix:"?",final:"K"},(Q0)=>this.eraseInLine(Q0,!0)),this._parser.registerCsiHandler({final:"L"},(Q0)=>this.insertLines(Q0)),this._parser.registerCsiHandler({final:"M"},(Q0)=>this.deleteLines(Q0)),this._parser.registerCsiHandler({final:"P"},(Q0)=>this.deleteChars(Q0)),this._parser.registerCsiHandler({final:"S"},(Q0)=>this.scrollUp(Q0)),this._parser.registerCsiHandler({final:"T"},(Q0)=>this.scrollDown(Q0)),this._parser.registerCsiHandler({final:"X"},(Q0)=>this.eraseChars(Q0)),this._parser.registerCsiHandler({final:"Z"},(Q0)=>this.cursorBackwardTab(Q0)),this._parser.registerCsiHandler({final:"`"},(Q0)=>this.charPosAbsolute(Q0)),this._parser.registerCsiHandler({final:"a"},(Q0)=>this.hPositionRelative(Q0)),this._parser.registerCsiHandler({final:"b"},(Q0)=>this.repeatPrecedingCharacter(Q0)),this._parser.registerCsiHandler({final:"c"},(Q0)=>this.sendDeviceAttributesPrimary(Q0)),this._parser.registerCsiHandler({prefix:">",final:"c"},(Q0)=>this.sendDeviceAttributesSecondary(Q0)),this._parser.registerCsiHandler({final:"d"},(Q0)=>this.linePosAbsolute(Q0)),this._parser.registerCsiHandler({final:"e"},(Q0)=>this.vPositionRelative(Q0)),this._parser.registerCsiHandler({final:"f"},(Q0)=>this.hVPosition(Q0)),this._parser.registerCsiHandler({final:"g"},(Q0)=>this.tabClear(Q0)),this._parser.registerCsiHandler({final:"h"},(Q0)=>this.setMode(Q0)),this._parser.registerCsiHandler({prefix:"?",final:"h"},(Q0)=>this.setModePrivate(Q0)),this._parser.registerCsiHandler({final:"l"},(Q0)=>this.resetMode(Q0)),this._parser.registerCsiHandler({prefix:"?",final:"l"},(Q0)=>this.resetModePrivate(Q0)),this._parser.registerCsiHandler({final:"m"},(Q0)=>this.charAttributes(Q0)),this._parser.registerCsiHandler({final:"n"},(Q0)=>this.deviceStatus(Q0)),this._parser.registerCsiHandler({prefix:"?",final:"n"},(Q0)=>this.deviceStatusPrivate(Q0)),this._parser.registerCsiHandler({intermediates:"!",final:"p"},(Q0)=>this.softReset(Q0)),this._parser.registerCsiHandler({intermediates:" ",final:"q"},(Q0)=>this.setCursorStyle(Q0)),this._parser.registerCsiHandler({final:"r"},(Q0)=>this.setScrollRegion(Q0)),this._parser.registerCsiHandler({final:"s"},(Q0)=>this.saveCursor(Q0)),this._parser.registerCsiHandler({final:"t"},(Q0)=>this.windowOptions(Q0)),this._parser.registerCsiHandler({final:"u"},(Q0)=>this.restoreCursor(Q0)),this._parser.registerCsiHandler({intermediates:"'",final:"}"},(Q0)=>this.insertColumns(Q0)),this._parser.registerCsiHandler({intermediates:"'",final:"~"},(Q0)=>this.deleteColumns(Q0)),this._parser.registerCsiHandler({intermediates:'"',final:"q"},(Q0)=>this.selectProtected(Q0)),this._parser.registerCsiHandler({intermediates:"$",final:"p"},(Q0)=>this.requestMode(Q0,!0)),this._parser.registerCsiHandler({prefix:"?",intermediates:"$",final:"p"},(Q0)=>this.requestMode(Q0,!1)),this._parser.setExecuteHandler(X.C0.BEL,()=>this.bell()),this._parser.setExecuteHandler(X.C0.LF,()=>this.lineFeed()),this._parser.setExecuteHandler(X.C0.VT,()=>this.lineFeed()),this._parser.setExecuteHandler(X.C0.FF,()=>this.lineFeed()),this._parser.setExecuteHandler(X.C0.CR,()=>this.carriageReturn()),this._parser.setExecuteHandler(X.C0.BS,()=>this.backspace()),this._parser.setExecuteHandler(X.C0.HT,()=>this.tab()),this._parser.setExecuteHandler(X.C0.SO,()=>this.shiftOut()),this._parser.setExecuteHandler(X.C0.SI,()=>this.shiftIn()),this._parser.setExecuteHandler(X.C1.IND,()=>this.index()),this._parser.setExecuteHandler(X.C1.NEL,()=>this.nextLine()),this._parser.setExecuteHandler(X.C1.HTS,()=>this.tabSet()),this._parser.registerOscHandler(0,new L.OscHandler((Q0)=>(this.setTitle(Q0),this.setIconName(Q0),!0))),this._parser.registerOscHandler(1,new L.OscHandler((Q0)=>this.setIconName(Q0))),this._parser.registerOscHandler(2,new L.OscHandler((Q0)=>this.setTitle(Q0))),this._parser.registerOscHandler(4,new L.OscHandler((Q0)=>this.setOrReportIndexedColor(Q0))),this._parser.registerOscHandler(8,new L.OscHandler((Q0)=>this.setHyperlink(Q0))),this._parser.registerOscHandler(10,new L.OscHandler((Q0)=>this.setOrReportFgColor(Q0))),this._parser.registerOscHandler(11,new L.OscHandler((Q0)=>this.setOrReportBgColor(Q0))),this._parser.registerOscHandler(12,new L.OscHandler((Q0)=>this.setOrReportCursorColor(Q0))),this._parser.registerOscHandler(104,new L.OscHandler((Q0)=>this.restoreIndexedColor(Q0))),this._parser.registerOscHandler(110,new L.OscHandler((Q0)=>this.restoreFgColor(Q0))),this._parser.registerOscHandler(111,new L.OscHandler((Q0)=>this.restoreBgColor(Q0))),this._parser.registerOscHandler(112,new L.OscHandler((Q0)=>this.restoreCursorColor(Q0))),this._parser.registerEscHandler({final:"7"},()=>this.saveCursor()),this._parser.registerEscHandler({final:"8"},()=>this.restoreCursor()),this._parser.registerEscHandler({final:"D"},()=>this.index()),this._parser.registerEscHandler({final:"E"},()=>this.nextLine()),this._parser.registerEscHandler({final:"H"},()=>this.tabSet()),this._parser.registerEscHandler({final:"M"},()=>this.reverseIndex()),this._parser.registerEscHandler({final:"="},()=>this.keypadApplicationMode()),this._parser.registerEscHandler({final:">"},()=>this.keypadNumericMode()),this._parser.registerEscHandler({final:"c"},()=>this.fullReset()),this._parser.registerEscHandler({final:"n"},()=>this.setgLevel(2)),this._parser.registerEscHandler({final:"o"},()=>this.setgLevel(3)),this._parser.registerEscHandler({final:"|"},()=>this.setgLevel(3)),this._parser.registerEscHandler({final:"}"},()=>this.setgLevel(2)),this._parser.registerEscHandler({final:"~"},()=>this.setgLevel(1)),this._parser.registerEscHandler({intermediates:"%",final:"@"},()=>this.selectDefaultCharset()),this._parser.registerEscHandler({intermediates:"%",final:"G"},()=>this.selectDefaultCharset());for(let Q0 in G.CHARSETS)this._parser.registerEscHandler({intermediates:"(",final:Q0},()=>this.selectCharset("("+Q0)),this._parser.registerEscHandler({intermediates:")",final:Q0},()=>this.selectCharset(")"+Q0)),this._parser.registerEscHandler({intermediates:"*",final:Q0},()=>this.selectCharset("*"+Q0)),this._parser.registerEscHandler({intermediates:"+",final:Q0},()=>this.selectCharset("+"+Q0)),this._parser.registerEscHandler({intermediates:"-",final:Q0},()=>this.selectCharset("-"+Q0)),this._parser.registerEscHandler({intermediates:".",final:Q0},()=>this.selectCharset("."+Q0)),this._parser.registerEscHandler({intermediates:"/",final:Q0},()=>this.selectCharset("/"+Q0));this._parser.registerEscHandler({intermediates:"#",final:"8"},()=>this.screenAlignmentPattern()),this._parser.setErrorHandler((Q0)=>(this._logService.error("Parsing error: ",Q0),Q0)),this._parser.registerDcsHandler({intermediates:"$",final:"q"},new j.DcsHandler((Q0,M0)=>this.requestStatusString(Q0,M0)))}_preserveStack(g,i,r,A0){this._parseStack.paused=!0,this._parseStack.cursorStartX=g,this._parseStack.cursorStartY=i,this._parseStack.decodedLength=r,this._parseStack.position=A0}_logSlowResolvingAsync(g){this._logService.logLevel<=w.LogLevelEnum.WARN&&Promise.race([g,new Promise((i,r)=>setTimeout(()=>r("#SLOW_TIMEOUT"),5000))]).catch((i)=>{if(i!=="#SLOW_TIMEOUT")throw i;console.warn("async parser handler taking longer than 5000 ms")})}_getCurrentLinkId(){return this._curAttrData.extended.urlId}parse(g,i){let r,A0=this._activeBuffer.x,I0=this._activeBuffer.y,E0=0,W0=this._parseStack.paused;if(W0){if(r=this._parser.parse(this._parseBuffer,this._parseStack.decodedLength,i))return this._logSlowResolvingAsync(r),r;A0=this._parseStack.cursorStartX,I0=this._parseStack.cursorStartY,this._parseStack.paused=!1,g.length>f&&(E0=this._parseStack.position+f)}if(this._logService.logLevel<=w.LogLevelEnum.DEBUG&&this._logService.debug("parsing data"+(typeof g=="string"?` "${g}"`:` "${Array.prototype.map.call(g,(Q0)=>String.fromCharCode(Q0)).join("")}"`),typeof g=="string"?g.split("").map((Q0)=>Q0.charCodeAt(0)):g),this._parseBuffer.length<g.length&&this._parseBuffer.length<f&&(this._parseBuffer=new Uint32Array(Math.min(g.length,f))),W0||this._dirtyRowTracker.clearRange(),g.length>f)for(let Q0=E0;Q0<g.length;Q0+=f){let M0=Q0+f<g.length?Q0+f:g.length,n=typeof g=="string"?this._stringDecoder.decode(g.substring(Q0,M0),this._parseBuffer):this._utf8Decoder.decode(g.subarray(Q0,M0),this._parseBuffer);if(r=this._parser.parse(this._parseBuffer,n))return this._preserveStack(A0,I0,n,Q0),this._logSlowResolvingAsync(r),r}else if(!W0){let Q0=typeof g=="string"?this._stringDecoder.decode(g,this._parseBuffer):this._utf8Decoder.decode(g,this._parseBuffer);if(r=this._parser.parse(this._parseBuffer,Q0))return this._preserveStack(A0,I0,Q0,0),this._logSlowResolvingAsync(r),r}this._activeBuffer.x===A0&&this._activeBuffer.y===I0||this._onCursorMove.fire();let $0=this._dirtyRowTracker.end+(this._bufferService.buffer.ybase-this._bufferService.buffer.ydisp),j0=this._dirtyRowTracker.start+(this._bufferService.buffer.ybase-this._bufferService.buffer.ydisp);j0<this._bufferService.rows&&this._onRequestRefreshRows.fire(Math.min(j0,this._bufferService.rows-1),Math.min($0,this._bufferService.rows-1))}print(g,i,r){let A0,I0,E0=this._charsetService.charset,W0=this._optionsService.rawOptions.screenReaderMode,$0=this._bufferService.cols,j0=this._coreService.decPrivateModes.wraparound,Q0=this._coreService.modes.insertMode,M0=this._curAttrData,n=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);this._dirtyRowTracker.markDirty(this._activeBuffer.y),this._activeBuffer.x&&r-i>0&&n.getWidth(this._activeBuffer.x-1)===2&&n.setCellFromCodepoint(this._activeBuffer.x-1,0,1,M0);let a=this._parser.precedingJoinState;for(let t=i;t<r;++t){if(A0=g[t],A0<127&&E0){let w0=E0[String.fromCharCode(A0)];w0&&(A0=w0.charCodeAt(0))}let e=this._unicodeService.charProperties(A0,a);I0=O.UnicodeService.extractWidth(e);let F0=O.UnicodeService.extractShouldJoin(e),J0=F0?O.UnicodeService.extractWidth(a):0;if(a=e,W0&&this._onA11yChar.fire((0,I.stringFromCodePoint)(A0)),this._getCurrentLinkId()&&this._oscLinkService.addLineToLink(this._getCurrentLinkId(),this._activeBuffer.ybase+this._activeBuffer.y),this._activeBuffer.x+I0-J0>$0){if(j0){let w0=n,C0=this._activeBuffer.x-J0;for(this._activeBuffer.x=J0,this._activeBuffer.y++,this._activeBuffer.y===this._activeBuffer.scrollBottom+1?(this._activeBuffer.y--,this._bufferService.scroll(this._eraseAttrData(),!0)):(this._activeBuffer.y>=this._bufferService.rows&&(this._activeBuffer.y=this._bufferService.rows-1),this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y).isWrapped=!0),n=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y),J0>0&&n instanceof z.BufferLine&&n.copyCellsFrom(w0,C0,0,J0,!1);C0<$0;)w0.setCellFromCodepoint(C0++,0,1,M0)}else if(this._activeBuffer.x=$0-1,I0===2)continue}if(F0&&this._activeBuffer.x){let w0=n.getWidth(this._activeBuffer.x-1)?1:2;n.addCodepointToCell(this._activeBuffer.x-w0,A0,I0);for(let C0=I0-J0;--C0>=0;)n.setCellFromCodepoint(this._activeBuffer.x++,0,0,M0)}else if(Q0&&(n.insertCells(this._activeBuffer.x,I0-J0,this._activeBuffer.getNullCell(M0)),n.getWidth($0-1)===2&&n.setCellFromCodepoint($0-1,H.NULL_CELL_CODE,H.NULL_CELL_WIDTH,M0)),n.setCellFromCodepoint(this._activeBuffer.x++,A0,I0,M0),I0>0)for(;--I0;)n.setCellFromCodepoint(this._activeBuffer.x++,0,0,M0)}this._parser.precedingJoinState=a,this._activeBuffer.x<$0&&r-i>0&&n.getWidth(this._activeBuffer.x)===0&&!n.hasContent(this._activeBuffer.x)&&n.setCellFromCodepoint(this._activeBuffer.x,0,1,M0),this._dirtyRowTracker.markDirty(this._activeBuffer.y)}registerCsiHandler(g,i){return g.final!=="t"||g.prefix||g.intermediates?this._parser.registerCsiHandler(g,i):this._parser.registerCsiHandler(g,(r)=>!h(r.params[0],this._optionsService.rawOptions.windowOptions)||i(r))}registerDcsHandler(g,i){return this._parser.registerDcsHandler(g,new j.DcsHandler(i))}registerEscHandler(g,i){return this._parser.registerEscHandler(g,i)}registerOscHandler(g,i){return this._parser.registerOscHandler(g,new L.OscHandler(i))}bell(){return this._onRequestBell.fire(),!0}lineFeed(){return this._dirtyRowTracker.markDirty(this._activeBuffer.y),this._optionsService.rawOptions.convertEol&&(this._activeBuffer.x=0),this._activeBuffer.y++,this._activeBuffer.y===this._activeBuffer.scrollBottom+1?(this._activeBuffer.y--,this._bufferService.scroll(this._eraseAttrData())):this._activeBuffer.y>=this._bufferService.rows?this._activeBuffer.y=this._bufferService.rows-1:this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y).isWrapped=!1,this._activeBuffer.x>=this._bufferService.cols&&this._activeBuffer.x--,this._dirtyRowTracker.markDirty(this._activeBuffer.y),this._onLineFeed.fire(),!0}carriageReturn(){return this._activeBuffer.x=0,!0}backspace(){if(!this._coreService.decPrivateModes.reverseWraparound)return this._restrictCursor(),this._activeBuffer.x>0&&this._activeBuffer.x--,!0;if(this._restrictCursor(this._bufferService.cols),this._activeBuffer.x>0)this._activeBuffer.x--;else if(this._activeBuffer.x===0&&this._activeBuffer.y>this._activeBuffer.scrollTop&&this._activeBuffer.y<=this._activeBuffer.scrollBottom&&this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y)?.isWrapped){this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y).isWrapped=!1,this._activeBuffer.y--,this._activeBuffer.x=this._bufferService.cols-1;let g=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);g.hasWidth(this._activeBuffer.x)&&!g.hasContent(this._activeBuffer.x)&&this._activeBuffer.x--}return this._restrictCursor(),!0}tab(){if(this._activeBuffer.x>=this._bufferService.cols)return!0;let g=this._activeBuffer.x;return this._activeBuffer.x=this._activeBuffer.nextStop(),this._optionsService.rawOptions.screenReaderMode&&this._onA11yTab.fire(this._activeBuffer.x-g),!0}shiftOut(){return this._charsetService.setgLevel(1),!0}shiftIn(){return this._charsetService.setgLevel(0),!0}_restrictCursor(g=this._bufferService.cols-1){this._activeBuffer.x=Math.min(g,Math.max(0,this._activeBuffer.x)),this._activeBuffer.y=this._coreService.decPrivateModes.origin?Math.min(this._activeBuffer.scrollBottom,Math.max(this._activeBuffer.scrollTop,this._activeBuffer.y)):Math.min(this._bufferService.rows-1,Math.max(0,this._activeBuffer.y)),this._dirtyRowTracker.markDirty(this._activeBuffer.y)}_setCursor(g,i){this._dirtyRowTracker.markDirty(this._activeBuffer.y),this._coreService.decPrivateModes.origin?(this._activeBuffer.x=g,this._activeBuffer.y=this._activeBuffer.scrollTop+i):(this._activeBuffer.x=g,this._activeBuffer.y=i),this._restrictCursor(),this._dirtyRowTracker.markDirty(this._activeBuffer.y)}_moveCursor(g,i){this._restrictCursor(),this._setCursor(this._activeBuffer.x+g,this._activeBuffer.y+i)}cursorUp(g){let i=this._activeBuffer.y-this._activeBuffer.scrollTop;return i>=0?this._moveCursor(0,-Math.min(i,g.params[0]||1)):this._moveCursor(0,-(g.params[0]||1)),!0}cursorDown(g){let i=this._activeBuffer.scrollBottom-this._activeBuffer.y;return i>=0?this._moveCursor(0,Math.min(i,g.params[0]||1)):this._moveCursor(0,g.params[0]||1),!0}cursorForward(g){return this._moveCursor(g.params[0]||1,0),!0}cursorBackward(g){return this._moveCursor(-(g.params[0]||1),0),!0}cursorNextLine(g){return this.cursorDown(g),this._activeBuffer.x=0,!0}cursorPrecedingLine(g){return this.cursorUp(g),this._activeBuffer.x=0,!0}cursorCharAbsolute(g){return this._setCursor((g.params[0]||1)-1,this._activeBuffer.y),!0}cursorPosition(g){return this._setCursor(g.length>=2?(g.params[1]||1)-1:0,(g.params[0]||1)-1),!0}charPosAbsolute(g){return this._setCursor((g.params[0]||1)-1,this._activeBuffer.y),!0}hPositionRelative(g){return this._moveCursor(g.params[0]||1,0),!0}linePosAbsolute(g){return this._setCursor(this._activeBuffer.x,(g.params[0]||1)-1),!0}vPositionRelative(g){return this._moveCursor(0,g.params[0]||1),!0}hVPosition(g){return this.cursorPosition(g),!0}tabClear(g){let i=g.params[0];return i===0?delete this._activeBuffer.tabs[this._activeBuffer.x]:i===3&&(this._activeBuffer.tabs={}),!0}cursorForwardTab(g){if(this._activeBuffer.x>=this._bufferService.cols)return!0;let i=g.params[0]||1;for(;i--;)this._activeBuffer.x=this._activeBuffer.nextStop();return!0}cursorBackwardTab(g){if(this._activeBuffer.x>=this._bufferService.cols)return!0;let i=g.params[0]||1;for(;i--;)this._activeBuffer.x=this._activeBuffer.prevStop();return!0}selectProtected(g){let i=g.params[0];return i===1&&(this._curAttrData.bg|=536870912),i!==2&&i!==0||(this._curAttrData.bg&=-536870913),!0}_eraseInBufferLine(g,i,r,A0=!1,I0=!1){let E0=this._activeBuffer.lines.get(this._activeBuffer.ybase+g);E0.replaceCells(i,r,this._activeBuffer.getNullCell(this._eraseAttrData()),I0),A0&&(E0.isWrapped=!1)}_resetBufferLine(g,i=!1){let r=this._activeBuffer.lines.get(this._activeBuffer.ybase+g);r&&(r.fill(this._activeBuffer.getNullCell(this._eraseAttrData()),i),this._bufferService.buffer.clearMarkers(this._activeBuffer.ybase+g),r.isWrapped=!1)}eraseInDisplay(g,i=!1){let r;switch(this._restrictCursor(this._bufferService.cols),g.params[0]){case 0:for(r=this._activeBuffer.y,this._dirtyRowTracker.markDirty(r),this._eraseInBufferLine(r++,this._activeBuffer.x,this._bufferService.cols,this._activeBuffer.x===0,i);r<this._bufferService.rows;r++)this._resetBufferLine(r,i);this._dirtyRowTracker.markDirty(r);break;case 1:for(r=this._activeBuffer.y,this._dirtyRowTracker.markDirty(r),this._eraseInBufferLine(r,0,this._activeBuffer.x+1,!0,i),this._activeBuffer.x+1>=this._bufferService.cols&&(this._activeBuffer.lines.get(r+1).isWrapped=!1);r--;)this._resetBufferLine(r,i);this._dirtyRowTracker.markDirty(0);break;case 2:for(r=this._bufferService.rows,this._dirtyRowTracker.markDirty(r-1);r--;)this._resetBufferLine(r,i);this._dirtyRowTracker.markDirty(0);break;case 3:let A0=this._activeBuffer.lines.length-this._bufferService.rows;A0>0&&(this._activeBuffer.lines.trimStart(A0),this._activeBuffer.ybase=Math.max(this._activeBuffer.ybase-A0,0),this._activeBuffer.ydisp=Math.max(this._activeBuffer.ydisp-A0,0),this._onScroll.fire(0))}return!0}eraseInLine(g,i=!1){switch(this._restrictCursor(this._bufferService.cols),g.params[0]){case 0:this._eraseInBufferLine(this._activeBuffer.y,this._activeBuffer.x,this._bufferService.cols,this._activeBuffer.x===0,i);break;case 1:this._eraseInBufferLine(this._activeBuffer.y,0,this._activeBuffer.x+1,!1,i);break;case 2:this._eraseInBufferLine(this._activeBuffer.y,0,this._bufferService.cols,!0,i)}return this._dirtyRowTracker.markDirty(this._activeBuffer.y),!0}insertLines(g){this._restrictCursor();let i=g.params[0]||1;if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;let r=this._activeBuffer.ybase+this._activeBuffer.y,A0=this._bufferService.rows-1-this._activeBuffer.scrollBottom,I0=this._bufferService.rows-1+this._activeBuffer.ybase-A0+1;for(;i--;)this._activeBuffer.lines.splice(I0-1,1),this._activeBuffer.lines.splice(r,0,this._activeBuffer.getBlankLine(this._eraseAttrData()));return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.y,this._activeBuffer.scrollBottom),this._activeBuffer.x=0,!0}deleteLines(g){this._restrictCursor();let i=g.params[0]||1;if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;let r=this._activeBuffer.ybase+this._activeBuffer.y,A0;for(A0=this._bufferService.rows-1-this._activeBuffer.scrollBottom,A0=this._bufferService.rows-1+this._activeBuffer.ybase-A0;i--;)this._activeBuffer.lines.splice(r,1),this._activeBuffer.lines.splice(A0,0,this._activeBuffer.getBlankLine(this._eraseAttrData()));return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.y,this._activeBuffer.scrollBottom),this._activeBuffer.x=0,!0}insertChars(g){this._restrictCursor();let i=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);return i&&(i.insertCells(this._activeBuffer.x,g.params[0]||1,this._activeBuffer.getNullCell(this._eraseAttrData())),this._dirtyRowTracker.markDirty(this._activeBuffer.y)),!0}deleteChars(g){this._restrictCursor();let i=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);return i&&(i.deleteCells(this._activeBuffer.x,g.params[0]||1,this._activeBuffer.getNullCell(this._eraseAttrData())),this._dirtyRowTracker.markDirty(this._activeBuffer.y)),!0}scrollUp(g){let i=g.params[0]||1;for(;i--;)this._activeBuffer.lines.splice(this._activeBuffer.ybase+this._activeBuffer.scrollTop,1),this._activeBuffer.lines.splice(this._activeBuffer.ybase+this._activeBuffer.scrollBottom,0,this._activeBuffer.getBlankLine(this._eraseAttrData()));return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}scrollDown(g){let i=g.params[0]||1;for(;i--;)this._activeBuffer.lines.splice(this._activeBuffer.ybase+this._activeBuffer.scrollBottom,1),this._activeBuffer.lines.splice(this._activeBuffer.ybase+this._activeBuffer.scrollTop,0,this._activeBuffer.getBlankLine(z.DEFAULT_ATTR_DATA));return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}scrollLeft(g){if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;let i=g.params[0]||1;for(let r=this._activeBuffer.scrollTop;r<=this._activeBuffer.scrollBottom;++r){let A0=this._activeBuffer.lines.get(this._activeBuffer.ybase+r);A0.deleteCells(0,i,this._activeBuffer.getNullCell(this._eraseAttrData())),A0.isWrapped=!1}return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}scrollRight(g){if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;let i=g.params[0]||1;for(let r=this._activeBuffer.scrollTop;r<=this._activeBuffer.scrollBottom;++r){let A0=this._activeBuffer.lines.get(this._activeBuffer.ybase+r);A0.insertCells(0,i,this._activeBuffer.getNullCell(this._eraseAttrData())),A0.isWrapped=!1}return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}insertColumns(g){if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;let i=g.params[0]||1;for(let r=this._activeBuffer.scrollTop;r<=this._activeBuffer.scrollBottom;++r){let A0=this._activeBuffer.lines.get(this._activeBuffer.ybase+r);A0.insertCells(this._activeBuffer.x,i,this._activeBuffer.getNullCell(this._eraseAttrData())),A0.isWrapped=!1}return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}deleteColumns(g){if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;let i=g.params[0]||1;for(let r=this._activeBuffer.scrollTop;r<=this._activeBuffer.scrollBottom;++r){let A0=this._activeBuffer.lines.get(this._activeBuffer.ybase+r);A0.deleteCells(this._activeBuffer.x,i,this._activeBuffer.getNullCell(this._eraseAttrData())),A0.isWrapped=!1}return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}eraseChars(g){this._restrictCursor();let i=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);return i&&(i.replaceCells(this._activeBuffer.x,this._activeBuffer.x+(g.params[0]||1),this._activeBuffer.getNullCell(this._eraseAttrData())),this._dirtyRowTracker.markDirty(this._activeBuffer.y)),!0}repeatPrecedingCharacter(g){let i=this._parser.precedingJoinState;if(!i)return!0;let r=g.params[0]||1,A0=O.UnicodeService.extractWidth(i),I0=this._activeBuffer.x-A0,E0=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y).getString(I0),W0=new Uint32Array(E0.length*r),$0=0;for(let Q0=0;Q0<E0.length;){let M0=E0.codePointAt(Q0)||0;W0[$0++]=M0,Q0+=M0>65535?2:1}let j0=$0;for(let Q0=1;Q0<r;++Q0)W0.copyWithin(j0,0,$0),j0+=$0;return this.print(W0,0,j0),!0}sendDeviceAttributesPrimary(g){return g.params[0]>0||(this._is("xterm")||this._is("rxvt-unicode")||this._is("screen")?this._coreService.triggerDataEvent(X.C0.ESC+"[?1;2c"):this._is("linux")&&this._coreService.triggerDataEvent(X.C0.ESC+"[?6c")),!0}sendDeviceAttributesSecondary(g){return g.params[0]>0||(this._is("xterm")?this._coreService.triggerDataEvent(X.C0.ESC+"[>0;276;0c"):this._is("rxvt-unicode")?this._coreService.triggerDataEvent(X.C0.ESC+"[>85;95;0c"):this._is("linux")?this._coreService.triggerDataEvent(g.params[0]+"c"):this._is("screen")&&this._coreService.triggerDataEvent(X.C0.ESC+"[>83;40003;0c")),!0}_is(g){return(this._optionsService.rawOptions.termName+"").indexOf(g)===0}setMode(g){for(let i=0;i<g.length;i++)switch(g.params[i]){case 4:this._coreService.modes.insertMode=!0;break;case 20:this._optionsService.options.convertEol=!0}return!0}setModePrivate(g){for(let i=0;i<g.length;i++)switch(g.params[i]){case 1:this._coreService.decPrivateModes.applicationCursorKeys=!0;break;case 2:this._charsetService.setgCharset(0,G.DEFAULT_CHARSET),this._charsetService.setgCharset(1,G.DEFAULT_CHARSET),this._charsetService.setgCharset(2,G.DEFAULT_CHARSET),this._charsetService.setgCharset(3,G.DEFAULT_CHARSET);break;case 3:this._optionsService.rawOptions.windowOptions.setWinLines&&(this._bufferService.resize(132,this._bufferService.rows),this._onRequestReset.fire());break;case 6:this._coreService.decPrivateModes.origin=!0,this._setCursor(0,0);break;case 7:this._coreService.decPrivateModes.wraparound=!0;break;case 12:this._optionsService.options.cursorBlink=!0;break;case 45:this._coreService.decPrivateModes.reverseWraparound=!0;break;case 66:this._logService.debug("Serial port requested application keypad."),this._coreService.decPrivateModes.applicationKeypad=!0,this._onRequestSyncScrollBar.fire();break;case 9:this._coreMouseService.activeProtocol="X10";break;case 1000:this._coreMouseService.activeProtocol="VT200";break;case 1002:this._coreMouseService.activeProtocol="DRAG";break;case 1003:this._coreMouseService.activeProtocol="ANY";break;case 1004:this._coreService.decPrivateModes.sendFocus=!0,this._onRequestSendFocus.fire();break;case 1005:this._logService.debug("DECSET 1005 not supported (see #2507)");break;case 1006:this._coreMouseService.activeEncoding="SGR";break;case 1015:this._logService.debug("DECSET 1015 not supported (see #2507)");break;case 1016:this._coreMouseService.activeEncoding="SGR_PIXELS";break;case 25:this._coreService.isCursorHidden=!1;break;case 1048:this.saveCursor();break;case 1049:this.saveCursor();case 47:case 1047:this._bufferService.buffers.activateAltBuffer(this._eraseAttrData()),this._coreService.isCursorInitialized=!0,this._onRequestRefreshRows.fire(0,this._bufferService.rows-1),this._onRequestSyncScrollBar.fire();break;case 2004:this._coreService.decPrivateModes.bracketedPasteMode=!0}return!0}resetMode(g){for(let i=0;i<g.length;i++)switch(g.params[i]){case 4:this._coreService.modes.insertMode=!1;break;case 20:this._optionsService.options.convertEol=!1}return!0}resetModePrivate(g){for(let i=0;i<g.length;i++)switch(g.params[i]){case 1:this._coreService.decPrivateModes.applicationCursorKeys=!1;break;case 3:this._optionsService.rawOptions.windowOptions.setWinLines&&(this._bufferService.resize(80,this._bufferService.rows),this._onRequestReset.fire());break;case 6:this._coreService.decPrivateModes.origin=!1,this._setCursor(0,0);break;case 7:this._coreService.decPrivateModes.wraparound=!1;break;case 12:this._optionsService.options.cursorBlink=!1;break;case 45:this._coreService.decPrivateModes.reverseWraparound=!1;break;case 66:this._logService.debug("Switching back to normal keypad."),this._coreService.decPrivateModes.applicationKeypad=!1,this._onRequestSyncScrollBar.fire();break;case 9:case 1000:case 1002:case 1003:this._coreMouseService.activeProtocol="NONE";break;case 1004:this._coreService.decPrivateModes.sendFocus=!1;break;case 1005:this._logService.debug("DECRST 1005 not supported (see #2507)");break;case 1006:case 1016:this._coreMouseService.activeEncoding="DEFAULT";break;case 1015:this._logService.debug("DECRST 1015 not supported (see #2507)");break;case 25:this._coreService.isCursorHidden=!0;break;case 1048:this.restoreCursor();break;case 1049:case 47:case 1047:this._bufferService.buffers.activateNormalBuffer(),g.params[i]===1049&&this.restoreCursor(),this._coreService.isCursorInitialized=!0,this._onRequestRefreshRows.fire(0,this._bufferService.rows-1),this._onRequestSyncScrollBar.fire();break;case 2004:this._coreService.decPrivateModes.bracketedPasteMode=!1}return!0}requestMode(g,i){let r=this._coreService.decPrivateModes,{activeProtocol:A0,activeEncoding:I0}=this._coreMouseService,E0=this._coreService,{buffers:W0,cols:$0}=this._bufferService,{active:j0,alt:Q0}=W0,M0=this._optionsService.rawOptions,n=(F0)=>F0?1:2,a=g.params[0];return t=a,e=i?a===2?4:a===4?n(E0.modes.insertMode):a===12?3:a===20?n(M0.convertEol):0:a===1?n(r.applicationCursorKeys):a===3?M0.windowOptions.setWinLines?$0===80?2:$0===132?1:0:0:a===6?n(r.origin):a===7?n(r.wraparound):a===8?3:a===9?n(A0==="X10"):a===12?n(M0.cursorBlink):a===25?n(!E0.isCursorHidden):a===45?n(r.reverseWraparound):a===66?n(r.applicationKeypad):a===67?4:a===1000?n(A0==="VT200"):a===1002?n(A0==="DRAG"):a===1003?n(A0==="ANY"):a===1004?n(r.sendFocus):a===1005?4:a===1006?n(I0==="SGR"):a===1015?4:a===1016?n(I0==="SGR_PIXELS"):a===1048?1:a===47||a===1047||a===1049?n(j0===Q0):a===2004?n(r.bracketedPasteMode):0,E0.triggerDataEvent(`${X.C0.ESC}[${i?"":"?"}${t};${e}$y`),!0;var t,e}_updateAttrColor(g,i,r,A0,I0){return i===2?(g|=50331648,g&=-16777216,g|=N.AttributeData.fromColorRGB([r,A0,I0])):i===5&&(g&=-50331904,g|=33554432|255&r),g}_extractColor(g,i,r){let A0=[0,0,-1,0,0,0],I0=0,E0=0;do{if(A0[E0+I0]=g.params[i+E0],g.hasSubParams(i+E0)){let W0=g.getSubParams(i+E0),$0=0;do A0[1]===5&&(I0=1),A0[E0+$0+1+I0]=W0[$0];while(++$0<W0.length&&$0+E0+1+I0<A0.length);break}if(A0[1]===5&&E0+I0>=2||A0[1]===2&&E0+I0>=5)break;A0[1]&&(I0=1)}while(++E0+i<g.length&&E0+I0<A0.length);for(let W0=2;W0<A0.length;++W0)A0[W0]===-1&&(A0[W0]=0);switch(A0[0]){case 38:r.fg=this._updateAttrColor(r.fg,A0[1],A0[3],A0[4],A0[5]);break;case 48:r.bg=this._updateAttrColor(r.bg,A0[1],A0[3],A0[4],A0[5]);break;case 58:r.extended=r.extended.clone(),r.extended.underlineColor=this._updateAttrColor(r.extended.underlineColor,A0[1],A0[3],A0[4],A0[5])}return E0}_processUnderline(g,i){i.extended=i.extended.clone(),(!~g||g>5)&&(g=1),i.extended.underlineStyle=g,i.fg|=268435456,g===0&&(i.fg&=-268435457),i.updateExtended()}_processSGR0(g){g.fg=z.DEFAULT_ATTR_DATA.fg,g.bg=z.DEFAULT_ATTR_DATA.bg,g.extended=g.extended.clone(),g.extended.underlineStyle=0,g.extended.underlineColor&=-67108864,g.updateExtended()}charAttributes(g){if(g.length===1&&g.params[0]===0)return this._processSGR0(this._curAttrData),!0;let i=g.length,r,A0=this._curAttrData;for(let I0=0;I0<i;I0++)r=g.params[I0],r>=30&&r<=37?(A0.fg&=-50331904,A0.fg|=16777216|r-30):r>=40&&r<=47?(A0.bg&=-50331904,A0.bg|=16777216|r-40):r>=90&&r<=97?(A0.fg&=-50331904,A0.fg|=16777224|r-90):r>=100&&r<=107?(A0.bg&=-50331904,A0.bg|=16777224|r-100):r===0?this._processSGR0(A0):r===1?A0.fg|=134217728:r===3?A0.bg|=67108864:r===4?(A0.fg|=268435456,this._processUnderline(g.hasSubParams(I0)?g.getSubParams(I0)[0]:1,A0)):r===5?A0.fg|=536870912:r===7?A0.fg|=67108864:r===8?A0.fg|=1073741824:r===9?A0.fg|=2147483648:r===2?A0.bg|=134217728:r===21?this._processUnderline(2,A0):r===22?(A0.fg&=-134217729,A0.bg&=-134217729):r===23?A0.bg&=-67108865:r===24?(A0.fg&=-268435457,this._processUnderline(0,A0)):r===25?A0.fg&=-536870913:r===27?A0.fg&=-67108865:r===28?A0.fg&=-1073741825:r===29?A0.fg&=2147483647:r===39?(A0.fg&=-67108864,A0.fg|=16777215&z.DEFAULT_ATTR_DATA.fg):r===49?(A0.bg&=-67108864,A0.bg|=16777215&z.DEFAULT_ATTR_DATA.bg):r===38||r===48||r===58?I0+=this._extractColor(g,I0,A0):r===53?A0.bg|=1073741824:r===55?A0.bg&=-1073741825:r===59?(A0.extended=A0.extended.clone(),A0.extended.underlineColor=-1,A0.updateExtended()):r===100?(A0.fg&=-67108864,A0.fg|=16777215&z.DEFAULT_ATTR_DATA.fg,A0.bg&=-67108864,A0.bg|=16777215&z.DEFAULT_ATTR_DATA.bg):this._logService.debug("Unknown SGR attribute: %d.",r);return!0}deviceStatus(g){switch(g.params[0]){case 5:this._coreService.triggerDataEvent(`${X.C0.ESC}[0n`);break;case 6:let i=this._activeBuffer.y+1,r=this._activeBuffer.x+1;this._coreService.triggerDataEvent(`${X.C0.ESC}[${i};${r}R`)}return!0}deviceStatusPrivate(g){if(g.params[0]===6){let i=this._activeBuffer.y+1,r=this._activeBuffer.x+1;this._coreService.triggerDataEvent(`${X.C0.ESC}[?${i};${r}R`)}return!0}softReset(g){return this._coreService.isCursorHidden=!1,this._onRequestSyncScrollBar.fire(),this._activeBuffer.scrollTop=0,this._activeBuffer.scrollBottom=this._bufferService.rows-1,this._curAttrData=z.DEFAULT_ATTR_DATA.clone(),this._coreService.reset(),this._charsetService.reset(),this._activeBuffer.savedX=0,this._activeBuffer.savedY=this._activeBuffer.ybase,this._activeBuffer.savedCurAttrData.fg=this._curAttrData.fg,this._activeBuffer.savedCurAttrData.bg=this._curAttrData.bg,this._activeBuffer.savedCharset=this._charsetService.charset,this._coreService.decPrivateModes.origin=!1,!0}setCursorStyle(g){let i=g.params[0]||1;switch(i){case 1:case 2:this._optionsService.options.cursorStyle="block";break;case 3:case 4:this._optionsService.options.cursorStyle="underline";break;case 5:case 6:this._optionsService.options.cursorStyle="bar"}let r=i%2==1;return this._optionsService.options.cursorBlink=r,!0}setScrollRegion(g){let i=g.params[0]||1,r;return(g.length<2||(r=g.params[1])>this._bufferService.rows||r===0)&&(r=this._bufferService.rows),r>i&&(this._activeBuffer.scrollTop=i-1,this._activeBuffer.scrollBottom=r-1,this._setCursor(0,0)),!0}windowOptions(g){if(!h(g.params[0],this._optionsService.rawOptions.windowOptions))return!0;let i=g.length>1?g.params[1]:0;switch(g.params[0]){case 14:i!==2&&this._onRequestWindowsOptionsReport.fire(b.GET_WIN_SIZE_PIXELS);break;case 16:this._onRequestWindowsOptionsReport.fire(b.GET_CELL_SIZE_PIXELS);break;case 18:this._bufferService&&this._coreService.triggerDataEvent(`${X.C0.ESC}[8;${this._bufferService.rows};${this._bufferService.cols}t`);break;case 22:i!==0&&i!==2||(this._windowTitleStack.push(this._windowTitle),this._windowTitleStack.length>10&&this._windowTitleStack.shift()),i!==0&&i!==1||(this._iconNameStack.push(this._iconName),this._iconNameStack.length>10&&this._iconNameStack.shift());break;case 23:i!==0&&i!==2||this._windowTitleStack.length&&this.setTitle(this._windowTitleStack.pop()),i!==0&&i!==1||this._iconNameStack.length&&this.setIconName(this._iconNameStack.pop())}return!0}saveCursor(g){return this._activeBuffer.savedX=this._activeBuffer.x,this._activeBuffer.savedY=this._activeBuffer.ybase+this._activeBuffer.y,this._activeBuffer.savedCurAttrData.fg=this._curAttrData.fg,this._activeBuffer.savedCurAttrData.bg=this._curAttrData.bg,this._activeBuffer.savedCharset=this._charsetService.charset,!0}restoreCursor(g){return this._activeBuffer.x=this._activeBuffer.savedX||0,this._activeBuffer.y=Math.max(this._activeBuffer.savedY-this._activeBuffer.ybase,0),this._curAttrData.fg=this._activeBuffer.savedCurAttrData.fg,this._curAttrData.bg=this._activeBuffer.savedCurAttrData.bg,this._charsetService.charset=this._savedCharset,this._activeBuffer.savedCharset&&(this._charsetService.charset=this._activeBuffer.savedCharset),this._restrictCursor(),!0}setTitle(g){return this._windowTitle=g,this._onTitleChange.fire(g),!0}setIconName(g){return this._iconName=g,!0}setOrReportIndexedColor(g){let i=[],r=g.split(";");for(;r.length>1;){let A0=r.shift(),I0=r.shift();if(/^\d+$/.exec(A0)){let E0=parseInt(A0);if(c(E0))if(I0==="?")i.push({type:0,index:E0});else{let W0=(0,k.parseColor)(I0);W0&&i.push({type:1,index:E0,color:W0})}}}return i.length&&this._onColor.fire(i),!0}setHyperlink(g){let i=g.split(";");return!(i.length<2)&&(i[1]?this._createHyperlink(i[0],i[1]):!i[0]&&this._finishHyperlink())}_createHyperlink(g,i){this._getCurrentLinkId()&&this._finishHyperlink();let r=g.split(":"),A0,I0=r.findIndex((E0)=>E0.startsWith("id="));return I0!==-1&&(A0=r[I0].slice(3)||void 0),this._curAttrData.extended=this._curAttrData.extended.clone(),this._curAttrData.extended.urlId=this._oscLinkService.registerLink({id:A0,uri:i}),this._curAttrData.updateExtended(),!0}_finishHyperlink(){return this._curAttrData.extended=this._curAttrData.extended.clone(),this._curAttrData.extended.urlId=0,this._curAttrData.updateExtended(),!0}_setOrReportSpecialColor(g,i){let r=g.split(";");for(let A0=0;A0<r.length&&!(i>=this._specialColors.length);++A0,++i)if(r[A0]==="?")this._onColor.fire([{type:0,index:this._specialColors[i]}]);else{let I0=(0,k.parseColor)(r[A0]);I0&&this._onColor.fire([{type:1,index:this._specialColors[i],color:I0}])}return!0}setOrReportFgColor(g){return this._setOrReportSpecialColor(g,0)}setOrReportBgColor(g){return this._setOrReportSpecialColor(g,1)}setOrReportCursorColor(g){return this._setOrReportSpecialColor(g,2)}restoreIndexedColor(g){if(!g)return this._onColor.fire([{type:2}]),!0;let i=[],r=g.split(";");for(let A0=0;A0<r.length;++A0)if(/^\d+$/.exec(r[A0])){let I0=parseInt(r[A0]);c(I0)&&i.push({type:2,index:I0})}return i.length&&this._onColor.fire(i),!0}restoreFgColor(g){return this._onColor.fire([{type:2,index:256}]),!0}restoreBgColor(g){return this._onColor.fire([{type:2,index:257}]),!0}restoreCursorColor(g){return this._onColor.fire([{type:2,index:258}]),!0}nextLine(){return this._activeBuffer.x=0,this.index(),!0}keypadApplicationMode(){return this._logService.debug("Serial port requested application keypad."),this._coreService.decPrivateModes.applicationKeypad=!0,this._onRequestSyncScrollBar.fire(),!0}keypadNumericMode(){return this._logService.debug("Switching back to normal keypad."),this._coreService.decPrivateModes.applicationKeypad=!1,this._onRequestSyncScrollBar.fire(),!0}selectDefaultCharset(){return this._charsetService.setgLevel(0),this._charsetService.setgCharset(0,G.DEFAULT_CHARSET),!0}selectCharset(g){return g.length!==2?(this.selectDefaultCharset(),!0):(g[0]==="/"||this._charsetService.setgCharset(_[g[0]],G.CHARSETS[g[1]]||G.DEFAULT_CHARSET),!0)}index(){return this._restrictCursor(),this._activeBuffer.y++,this._activeBuffer.y===this._activeBuffer.scrollBottom+1?(this._activeBuffer.y--,this._bufferService.scroll(this._eraseAttrData())):this._activeBuffer.y>=this._bufferService.rows&&(this._activeBuffer.y=this._bufferService.rows-1),this._restrictCursor(),!0}tabSet(){return this._activeBuffer.tabs[this._activeBuffer.x]=!0,!0}reverseIndex(){if(this._restrictCursor(),this._activeBuffer.y===this._activeBuffer.scrollTop){let g=this._activeBuffer.scrollBottom-this._activeBuffer.scrollTop;this._activeBuffer.lines.shiftElements(this._activeBuffer.ybase+this._activeBuffer.y,g,1),this._activeBuffer.lines.set(this._activeBuffer.ybase+this._activeBuffer.y,this._activeBuffer.getBlankLine(this._eraseAttrData())),this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom)}else this._activeBuffer.y--,this._restrictCursor();return!0}fullReset(){return this._parser.reset(),this._onRequestReset.fire(),!0}reset(){this._curAttrData=z.DEFAULT_ATTR_DATA.clone(),this._eraseAttrDataInternal=z.DEFAULT_ATTR_DATA.clone()}_eraseAttrData(){return this._eraseAttrDataInternal.bg&=-67108864,this._eraseAttrDataInternal.bg|=67108863&this._curAttrData.bg,this._eraseAttrDataInternal}setgLevel(g){return this._charsetService.setgLevel(g),!0}screenAlignmentPattern(){let g=new q.CellData;g.content=4194373,g.fg=this._curAttrData.fg,g.bg=this._curAttrData.bg,this._setCursor(0,0);for(let i=0;i<this._bufferService.rows;++i){let r=this._activeBuffer.ybase+this._activeBuffer.y+i,A0=this._activeBuffer.lines.get(r);A0&&(A0.fill(g),A0.isWrapped=!1)}return this._dirtyRowTracker.markAllDirty(),this._setCursor(0,0),!0}requestStatusString(g,i){let r=this._bufferService.buffer,A0=this._optionsService.rawOptions;return((I0)=>(this._coreService.triggerDataEvent(`${X.C0.ESC}${I0}${X.C0.ESC}\\`),!0))(g==='"q'?`P1$r${this._curAttrData.isProtected()?1:0}"q`:g==='"p'?'P1$r61;1"p':g==="r"?`P1$r${r.scrollTop+1};${r.scrollBottom+1}r`:g==="m"?"P1$r0m":g===" q"?`P1$r${{block:2,underline:4,bar:6}[A0.cursorStyle]-(A0.cursorBlink?1:0)} q`:"P0$r")}markRangeDirty(g,i){this._dirtyRowTracker.markRangeDirty(g,i)}}Y.InputHandler=y;let p=class{constructor(g){this._bufferService=g,this.clearRange()}clearRange(){this.start=this._bufferService.buffer.y,this.end=this._bufferService.buffer.y}markDirty(g){g<this.start?this.start=g:g>this.end&&(this.end=g)}markRangeDirty(g,i){g>i&&(v=g,g=i,i=v),g<this.start&&(this.start=g),i>this.end&&(this.end=i)}markAllDirty(){this.markRangeDirty(0,this._bufferService.rows-1)}};function c(g){return 0<=g&&g<256}p=Z([U(0,w.IBufferService)],p)},844:(F,Y)=>{function E(Z){for(let U of Z)U.dispose();Z.length=0}Object.defineProperty(Y,"__esModule",{value:!0}),Y.getDisposeArrayDisposable=Y.disposeArray=Y.toDisposable=Y.MutableDisposable=Y.Disposable=void 0,Y.Disposable=class{constructor(){this._disposables=[],this._isDisposed=!1}dispose(){this._isDisposed=!0;for(let Z of this._disposables)Z.dispose();this._disposables.length=0}register(Z){return this._disposables.push(Z),Z}unregister(Z){let U=this._disposables.indexOf(Z);U!==-1&&this._disposables.splice(U,1)}},Y.MutableDisposable=class{constructor(){this._isDisposed=!1}get value(){return this._isDisposed?void 0:this._value}set value(Z){this._isDisposed||Z===this._value||(this._value?.dispose(),this._value=Z)}clear(){this.value=void 0}dispose(){this._isDisposed=!0,this._value?.dispose(),this._value=void 0}},Y.toDisposable=function(Z){return{dispose:Z}},Y.disposeArray=E,Y.getDisposeArrayDisposable=function(Z){return{dispose:()=>E(Z)}}},114:(F,Y)=>{Object.defineProperty(Y,"__esModule",{value:!0}),Y.isChromeOS=Y.isLinux=Y.isWindows=Y.isIphone=Y.isIpad=Y.isMac=Y.getSafariVersion=Y.isSafari=Y.isLegacyEdge=Y.isFirefox=Y.isNode=void 0,Y.isNode=typeof process<"u"&&"title"in process;let E=Y.isNode?"node":navigator.userAgent,Z=Y.isNode?"node":navigator.platform;Y.isFirefox=E.includes("Firefox"),Y.isLegacyEdge=E.includes("Edge"),Y.isSafari=/^((?!chrome|android).)*safari/i.test(E),Y.getSafariVersion=function(){if(!Y.isSafari)return 0;let U=E.match(/Version\/(\d+)/);return U===null||U.length<2?0:parseInt(U[1])},Y.isMac=["Macintosh","MacIntel","MacPPC","Mac68K"].includes(Z),Y.isIpad=Z==="iPad",Y.isIphone=Z==="iPhone",Y.isWindows=["Windows","Win16","Win32","WinCE"].includes(Z),Y.isLinux=Z.indexOf("Linux")>=0,Y.isChromeOS=/\bCrOS\b/.test(E)},226:(F,Y,E)=>{Object.defineProperty(Y,"__esModule",{value:!0}),Y.DebouncedIdleTask=Y.IdleTaskQueue=Y.PriorityTaskQueue=void 0;let Z=E(114);class U{constructor(){this._tasks=[],this._i=0}enqueue(G){this._tasks.push(G),this._start()}flush(){for(;this._i<this._tasks.length;)this._tasks[this._i]()||this._i++;this.clear()}clear(){this._idleCallback&&(this._cancelCallback(this._idleCallback),this._idleCallback=void 0),this._i=0,this._tasks.length=0}_start(){this._idleCallback||(this._idleCallback=this._requestCallback(this._process.bind(this)))}_process(G){this._idleCallback=void 0;let V=0,K=0,I=G.timeRemaining(),z=0;for(;this._i<this._tasks.length;){if(V=Date.now(),this._tasks[this._i]()||this._i++,V=Math.max(1,Date.now()-V),K=Math.max(V,K),z=G.timeRemaining(),1.5*K>z)return I-V<-20&&console.warn(`task queue exceeded allotted deadline by ${Math.abs(Math.round(I-V))}ms`),void this._start();I=z}this.clear()}}class X extends U{_requestCallback(G){return setTimeout(()=>G(this._createDeadline(16)))}_cancelCallback(G){clearTimeout(G)}_createDeadline(G){let V=Date.now()+G;return{timeRemaining:()=>Math.max(0,V-Date.now())}}}Y.PriorityTaskQueue=X,Y.IdleTaskQueue=!Z.isNode&&"requestIdleCallback"in window?class extends U{_requestCallback(G){return requestIdleCallback(G)}_cancelCallback(G){cancelIdleCallback(G)}}:X,Y.DebouncedIdleTask=class{constructor(){this._queue=new Y.IdleTaskQueue}set(G){this._queue.clear(),this._queue.enqueue(G)}flush(){this._queue.flush()}}},282:(F,Y,E)=>{Object.defineProperty(Y,"__esModule",{value:!0}),Y.updateWindowsModeWrappedState=void 0;let Z=E(643);Y.updateWindowsModeWrappedState=function(U){let X=U.buffer.lines.get(U.buffer.ybase+U.buffer.y-1),G=X?.get(U.cols-1),V=U.buffer.lines.get(U.buffer.ybase+U.buffer.y);V&&G&&(V.isWrapped=G[Z.CHAR_DATA_CODE_INDEX]!==Z.NULL_CELL_CODE&&G[Z.CHAR_DATA_CODE_INDEX]!==Z.WHITESPACE_CELL_CODE)}},734:(F,Y)=>{Object.defineProperty(Y,"__esModule",{value:!0}),Y.ExtendedAttrs=Y.AttributeData=void 0;class E{constructor(){this.fg=0,this.bg=0,this.extended=new Z}static toColorRGB(U){return[U>>>16&255,U>>>8&255,255&U]}static fromColorRGB(U){return(255&U[0])<<16|(255&U[1])<<8|255&U[2]}clone(){let U=new E;return U.fg=this.fg,U.bg=this.bg,U.extended=this.extended.clone(),U}isInverse(){return 67108864&this.fg}isBold(){return 134217728&this.fg}isUnderline(){return this.hasExtendedAttrs()&&this.extended.underlineStyle!==0?1:268435456&this.fg}isBlink(){return 536870912&this.fg}isInvisible(){return 1073741824&this.fg}isItalic(){return 67108864&this.bg}isDim(){return 134217728&this.bg}isStrikethrough(){return 2147483648&this.fg}isProtected(){return 536870912&this.bg}isOverline(){return 1073741824&this.bg}getFgColorMode(){return 50331648&this.fg}getBgColorMode(){return 50331648&this.bg}isFgRGB(){return(50331648&this.fg)==50331648}isBgRGB(){return(50331648&this.bg)==50331648}isFgPalette(){return(50331648&this.fg)==16777216||(50331648&this.fg)==33554432}isBgPalette(){return(50331648&this.bg)==16777216||(50331648&this.bg)==33554432}isFgDefault(){return(50331648&this.fg)==0}isBgDefault(){return(50331648&this.bg)==0}isAttributeDefault(){return this.fg===0&&this.bg===0}getFgColor(){switch(50331648&this.fg){case 16777216:case 33554432:return 255&this.fg;case 50331648:return 16777215&this.fg;default:return-1}}getBgColor(){switch(50331648&this.bg){case 16777216:case 33554432:return 255&this.bg;case 50331648:return 16777215&this.bg;default:return-1}}hasExtendedAttrs(){return 268435456&this.bg}updateExtended(){this.extended.isEmpty()?this.bg&=-268435457:this.bg|=268435456}getUnderlineColor(){if(268435456&this.bg&&~this.extended.underlineColor)switch(50331648&this.extended.underlineColor){case 16777216:case 33554432:return 255&this.extended.underlineColor;case 50331648:return 16777215&this.extended.underlineColor;default:return this.getFgColor()}return this.getFgColor()}getUnderlineColorMode(){return 268435456&this.bg&&~this.extended.underlineColor?50331648&this.extended.underlineColor:this.getFgColorMode()}isUnderlineColorRGB(){return 268435456&this.bg&&~this.extended.underlineColor?(50331648&this.extended.underlineColor)==50331648:this.isFgRGB()}isUnderlineColorPalette(){return 268435456&this.bg&&~this.extended.underlineColor?(50331648&this.extended.underlineColor)==16777216||(50331648&this.extended.underlineColor)==33554432:this.isFgPalette()}isUnderlineColorDefault(){return 268435456&this.bg&&~this.extended.underlineColor?(50331648&this.extended.underlineColor)==0:this.isFgDefault()}getUnderlineStyle(){return 268435456&this.fg?268435456&this.bg?this.extended.underlineStyle:1:0}getUnderlineVariantOffset(){return this.extended.underlineVariantOffset}}Y.AttributeData=E;class Z{get ext(){return this._urlId?-469762049&this._ext|this.underlineStyle<<26:this._ext}set ext(U){this._ext=U}get underlineStyle(){return this._urlId?5:(469762048&this._ext)>>26}set underlineStyle(U){this._ext&=-469762049,this._ext|=U<<26&469762048}get underlineColor(){return 67108863&this._ext}set underlineColor(U){this._ext&=-67108864,this._ext|=67108863&U}get urlId(){return this._urlId}set urlId(U){this._urlId=U}get underlineVariantOffset(){let U=(3758096384&this._ext)>>29;return U<0?4294967288^U:U}set underlineVariantOffset(U){this._ext&=536870911,this._ext|=U<<29&3758096384}constructor(U=0,X=0){this._ext=0,this._urlId=0,this._ext=U,this._urlId=X}clone(){return new Z(this._ext,this._urlId)}isEmpty(){return this.underlineStyle===0&&this._urlId===0}}Y.ExtendedAttrs=Z},92:(F,Y,E)=>{Object.defineProperty(Y,"__esModule",{value:!0}),Y.Buffer=Y.MAX_BUFFER_SIZE=void 0;let Z=E(349),U=E(226),X=E(734),G=E(437),V=E(634),K=E(511),I=E(643),z=E(863),W=E(116);Y.MAX_BUFFER_SIZE=4294967295,Y.Buffer=class{constructor(H,q,N){this._hasScrollback=H,this._optionsService=q,this._bufferService=N,this.ydisp=0,this.ybase=0,this.y=0,this.x=0,this.tabs={},this.savedY=0,this.savedX=0,this.savedCurAttrData=G.DEFAULT_ATTR_DATA.clone(),this.savedCharset=W.DEFAULT_CHARSET,this.markers=[],this._nullCell=K.CellData.fromCharData([0,I.NULL_CELL_CHAR,I.NULL_CELL_WIDTH,I.NULL_CELL_CODE]),this._whitespaceCell=K.CellData.fromCharData([0,I.WHITESPACE_CELL_CHAR,I.WHITESPACE_CELL_WIDTH,I.WHITESPACE_CELL_CODE]),this._isClearing=!1,this._memoryCleanupQueue=new U.IdleTaskQueue,this._memoryCleanupPosition=0,this._cols=this._bufferService.cols,this._rows=this._bufferService.rows,this.lines=new Z.CircularList(this._getCorrectBufferLength(this._rows)),this.scrollTop=0,this.scrollBottom=this._rows-1,this.setupTabStops()}getNullCell(H){return H?(this._nullCell.fg=H.fg,this._nullCell.bg=H.bg,this._nullCell.extended=H.extended):(this._nullCell.fg=0,this._nullCell.bg=0,this._nullCell.extended=new X.ExtendedAttrs),this._nullCell}getWhitespaceCell(H){return H?(this._whitespaceCell.fg=H.fg,this._whitespaceCell.bg=H.bg,this._whitespaceCell.extended=H.extended):(this._whitespaceCell.fg=0,this._whitespaceCell.bg=0,this._whitespaceCell.extended=new X.ExtendedAttrs),this._whitespaceCell}getBlankLine(H,q){return new G.BufferLine(this._bufferService.cols,this.getNullCell(H),q)}get hasScrollback(){return this._hasScrollback&&this.lines.maxLength>this._rows}get isCursorInViewport(){let H=this.ybase+this.y-this.ydisp;return H>=0&&H<this._rows}_getCorrectBufferLength(H){if(!this._hasScrollback)return H;let q=H+this._optionsService.rawOptions.scrollback;return q>Y.MAX_BUFFER_SIZE?Y.MAX_BUFFER_SIZE:q}fillViewportRows(H){if(this.lines.length===0){H===void 0&&(H=G.DEFAULT_ATTR_DATA);let q=this._rows;for(;q--;)this.lines.push(this.getBlankLine(H))}}clear(){this.ydisp=0,this.ybase=0,this.y=0,this.x=0,this.lines=new Z.CircularList(this._getCorrectBufferLength(this._rows)),this.scrollTop=0,this.scrollBottom=this._rows-1,this.setupTabStops()}resize(H,q){let N=this.getNullCell(G.DEFAULT_ATTR_DATA),w=0,O=this._getCorrectBufferLength(q);if(O>this.lines.maxLength&&(this.lines.maxLength=O),this.lines.length>0){if(this._cols<H)for(let j=0;j<this.lines.length;j++)w+=+this.lines.get(j).resize(H,N);let L=0;if(this._rows<q)for(let j=this._rows;j<q;j++)this.lines.length<q+this.ybase&&(this._optionsService.rawOptions.windowsMode||this._optionsService.rawOptions.windowsPty.backend!==void 0||this._optionsService.rawOptions.windowsPty.buildNumber!==void 0?this.lines.push(new G.BufferLine(H,N)):this.ybase>0&&this.lines.length<=this.ybase+this.y+L+1?(this.ybase--,L++,this.ydisp>0&&this.ydisp--):this.lines.push(new G.BufferLine(H,N)));else for(let j=this._rows;j>q;j--)this.lines.length>q+this.ybase&&(this.lines.length>this.ybase+this.y+1?this.lines.pop():(this.ybase++,this.ydisp++));if(O<this.lines.maxLength){let j=this.lines.length-O;j>0&&(this.lines.trimStart(j),this.ybase=Math.max(this.ybase-j,0),this.ydisp=Math.max(this.ydisp-j,0),this.savedY=Math.max(this.savedY-j,0)),this.lines.maxLength=O}this.x=Math.min(this.x,H-1),this.y=Math.min(this.y,q-1),L&&(this.y+=L),this.savedX=Math.min(this.savedX,H-1),this.scrollTop=0}if(this.scrollBottom=q-1,this._isReflowEnabled&&(this._reflow(H,q),this._cols>H))for(let L=0;L<this.lines.length;L++)w+=+this.lines.get(L).resize(H,N);this._cols=H,this._rows=q,this._memoryCleanupQueue.clear(),w>0.1*this.lines.length&&(this._memoryCleanupPosition=0,this._memoryCleanupQueue.enqueue(()=>this._batchedMemoryCleanup()))}_batchedMemoryCleanup(){let H=!0;this._memoryCleanupPosition>=this.lines.length&&(this._memoryCleanupPosition=0,H=!1);let q=0;for(;this._memoryCleanupPosition<this.lines.length;)if(q+=this.lines.get(this._memoryCleanupPosition++).cleanupMemory(),q>100)return!0;return H}get _isReflowEnabled(){let H=this._optionsService.rawOptions.windowsPty;return H&&H.buildNumber?this._hasScrollback&&H.backend==="conpty"&&H.buildNumber>=21376:this._hasScrollback&&!this._optionsService.rawOptions.windowsMode}_reflow(H,q){this._cols!==H&&(H>this._cols?this._reflowLarger(H,q):this._reflowSmaller(H,q))}_reflowLarger(H,q){let N=(0,V.reflowLargerGetLinesToRemove)(this.lines,this._cols,H,this.ybase+this.y,this.getNullCell(G.DEFAULT_ATTR_DATA));if(N.length>0){let w=(0,V.reflowLargerCreateNewLayout)(this.lines,N);(0,V.reflowLargerApplyNewLayout)(this.lines,w.layout),this._reflowLargerAdjustViewport(H,q,w.countRemoved)}}_reflowLargerAdjustViewport(H,q,N){let w=this.getNullCell(G.DEFAULT_ATTR_DATA),O=N;for(;O-- >0;)this.ybase===0?(this.y>0&&this.y--,this.lines.length<q&&this.lines.push(new G.BufferLine(H,w))):(this.ydisp===this.ybase&&this.ydisp--,this.ybase--);this.savedY=Math.max(this.savedY-N,0)}_reflowSmaller(H,q){let N=this.getNullCell(G.DEFAULT_ATTR_DATA),w=[],O=0;for(let L=this.lines.length-1;L>=0;L--){let j=this.lines.get(L);if(!j||!j.isWrapped&&j.getTrimmedLength()<=H)continue;let k=[j];for(;j.isWrapped&&L>0;)j=this.lines.get(--L),k.unshift(j);let _=this.ybase+this.y;if(_>=L&&_<L+k.length)continue;let f=k[k.length-1].getTrimmedLength(),h=(0,V.reflowSmallerGetNewLineLengths)(k,this._cols,H),b=h.length-k.length,v;v=this.ybase===0&&this.y!==this.lines.length-1?Math.max(0,this.y-this.lines.maxLength+b):Math.max(0,this.lines.length-this.lines.maxLength+b);let y=[];for(let A0=0;A0<b;A0++){let I0=this.getBlankLine(G.DEFAULT_ATTR_DATA,!0);y.push(I0)}y.length>0&&(w.push({start:L+k.length+O,newLines:y}),O+=y.length),k.push(...y);let p=h.length-1,c=h[p];c===0&&(p--,c=h[p]);let g=k.length-b-1,i=f;for(;g>=0;){let A0=Math.min(i,c);if(k[p]===void 0)break;if(k[p].copyCellsFrom(k[g],i-A0,c-A0,A0,!0),c-=A0,c===0&&(p--,c=h[p]),i-=A0,i===0){g--;let I0=Math.max(g,0);i=(0,V.getWrappedLineTrimmedLength)(k,I0,this._cols)}}for(let A0=0;A0<k.length;A0++)h[A0]<H&&k[A0].setCell(h[A0],N);let r=b-v;for(;r-- >0;)this.ybase===0?this.y<q-1?(this.y++,this.lines.pop()):(this.ybase++,this.ydisp++):this.ybase<Math.min(this.lines.maxLength,this.lines.length+O)-q&&(this.ybase===this.ydisp&&this.ydisp++,this.ybase++);this.savedY=Math.min(this.savedY+b,this.ybase+q-1)}if(w.length>0){let L=[],j=[];for(let p=0;p<this.lines.length;p++)j.push(this.lines.get(p));let k=this.lines.length,_=k-1,f=0,h=w[f];this.lines.length=Math.min(this.lines.maxLength,this.lines.length+O);let b=0;for(let p=Math.min(this.lines.maxLength-1,k+O-1);p>=0;p--)if(h&&h.start>_+b){for(let c=h.newLines.length-1;c>=0;c--)this.lines.set(p--,h.newLines[c]);p++,L.push({index:_+1,amount:h.newLines.length}),b+=h.newLines.length,h=w[++f]}else this.lines.set(p,j[_--]);let v=0;for(let p=L.length-1;p>=0;p--)L[p].index+=v,this.lines.onInsertEmitter.fire(L[p]),v+=L[p].amount;let y=Math.max(0,k+O-this.lines.maxLength);y>0&&this.lines.onTrimEmitter.fire(y)}}translateBufferLineToString(H,q,N=0,w){let O=this.lines.get(H);return O?O.translateToString(q,N,w):""}getWrappedRangeForLine(H){let q=H,N=H;for(;q>0&&this.lines.get(q).isWrapped;)q--;for(;N+1<this.lines.length&&this.lines.get(N+1).isWrapped;)N++;return{first:q,last:N}}setupTabStops(H){for(H!=null?this.tabs[H]||(H=this.prevStop(H)):(this.tabs={},H=0);H<this._cols;H+=this._optionsService.rawOptions.tabStopWidth)this.tabs[H]=!0}prevStop(H){for(H==null&&(H=this.x);!this.tabs[--H]&&H>0;);return H>=this._cols?this._cols-1:H<0?0:H}nextStop(H){for(H==null&&(H=this.x);!this.tabs[++H]&&H<this._cols;);return H>=this._cols?this._cols-1:H<0?0:H}clearMarkers(H){this._isClearing=!0;for(let q=0;q<this.markers.length;q++)this.markers[q].line===H&&(this.markers[q].dispose(),this.markers.splice(q--,1));this._isClearing=!1}clearAllMarkers(){this._isClearing=!0;for(let H=0;H<this.markers.length;H++)this.markers[H].dispose(),this.markers.splice(H--,1);this._isClearing=!1}addMarker(H){let q=new z.Marker(H);return this.markers.push(q),q.register(this.lines.onTrim((N)=>{q.line-=N,q.line<0&&q.dispose()})),q.register(this.lines.onInsert((N)=>{q.line>=N.index&&(q.line+=N.amount)})),q.register(this.lines.onDelete((N)=>{q.line>=N.index&&q.line<N.index+N.amount&&q.dispose(),q.line>N.index&&(q.line-=N.amount)})),q.register(q.onDispose(()=>this._removeMarker(q))),q}_removeMarker(H){this._isClearing||this.markers.splice(this.markers.indexOf(H),1)}}},437:(F,Y,E)=>{Object.defineProperty(Y,"__esModule",{value:!0}),Y.BufferLine=Y.DEFAULT_ATTR_DATA=void 0;let Z=E(734),U=E(511),X=E(643),G=E(482);Y.DEFAULT_ATTR_DATA=Object.freeze(new Z.AttributeData);let V=0;class K{constructor(I,z,W=!1){this.isWrapped=W,this._combined={},this._extendedAttrs={},this._data=new Uint32Array(3*I);let H=z||U.CellData.fromCharData([0,X.NULL_CELL_CHAR,X.NULL_CELL_WIDTH,X.NULL_CELL_CODE]);for(let q=0;q<I;++q)this.setCell(q,H);this.length=I}get(I){let z=this._data[3*I+0],W=2097151&z;return[this._data[3*I+1],2097152&z?this._combined[I]:W?(0,G.stringFromCodePoint)(W):"",z>>22,2097152&z?this._combined[I].charCodeAt(this._combined[I].length-1):W]}set(I,z){this._data[3*I+1]=z[X.CHAR_DATA_ATTR_INDEX],z[X.CHAR_DATA_CHAR_INDEX].length>1?(this._combined[I]=z[1],this._data[3*I+0]=2097152|I|z[X.CHAR_DATA_WIDTH_INDEX]<<22):this._data[3*I+0]=z[X.CHAR_DATA_CHAR_INDEX].charCodeAt(0)|z[X.CHAR_DATA_WIDTH_INDEX]<<22}getWidth(I){return this._data[3*I+0]>>22}hasWidth(I){return 12582912&this._data[3*I+0]}getFg(I){return this._data[3*I+1]}getBg(I){return this._data[3*I+2]}hasContent(I){return 4194303&this._data[3*I+0]}getCodePoint(I){let z=this._data[3*I+0];return 2097152&z?this._combined[I].charCodeAt(this._combined[I].length-1):2097151&z}isCombined(I){return 2097152&this._data[3*I+0]}getString(I){let z=this._data[3*I+0];return 2097152&z?this._combined[I]:2097151&z?(0,G.stringFromCodePoint)(2097151&z):""}isProtected(I){return 536870912&this._data[3*I+2]}loadCell(I,z){return V=3*I,z.content=this._data[V+0],z.fg=this._data[V+1],z.bg=this._data[V+2],2097152&z.content&&(z.combinedData=this._combined[I]),268435456&z.bg&&(z.extended=this._extendedAttrs[I]),z}setCell(I,z){2097152&z.content&&(this._combined[I]=z.combinedData),268435456&z.bg&&(this._extendedAttrs[I]=z.extended),this._data[3*I+0]=z.content,this._data[3*I+1]=z.fg,this._data[3*I+2]=z.bg}setCellFromCodepoint(I,z,W,H){268435456&H.bg&&(this._extendedAttrs[I]=H.extended),this._data[3*I+0]=z|W<<22,this._data[3*I+1]=H.fg,this._data[3*I+2]=H.bg}addCodepointToCell(I,z,W){let H=this._data[3*I+0];2097152&H?this._combined[I]+=(0,G.stringFromCodePoint)(z):2097151&H?(this._combined[I]=(0,G.stringFromCodePoint)(2097151&H)+(0,G.stringFromCodePoint)(z),H&=-2097152,H|=2097152):H=z|4194304,W&&(H&=-12582913,H|=W<<22),this._data[3*I+0]=H}insertCells(I,z,W){if((I%=this.length)&&this.getWidth(I-1)===2&&this.setCellFromCodepoint(I-1,0,1,W),z<this.length-I){let H=new U.CellData;for(let q=this.length-I-z-1;q>=0;--q)this.setCell(I+z+q,this.loadCell(I+q,H));for(let q=0;q<z;++q)this.setCell(I+q,W)}else for(let H=I;H<this.length;++H)this.setCell(H,W);this.getWidth(this.length-1)===2&&this.setCellFromCodepoint(this.length-1,0,1,W)}deleteCells(I,z,W){if(I%=this.length,z<this.length-I){let H=new U.CellData;for(let q=0;q<this.length-I-z;++q)this.setCell(I+q,this.loadCell(I+z+q,H));for(let q=this.length-z;q<this.length;++q)this.setCell(q,W)}else for(let H=I;H<this.length;++H)this.setCell(H,W);I&&this.getWidth(I-1)===2&&this.setCellFromCodepoint(I-1,0,1,W),this.getWidth(I)!==0||this.hasContent(I)||this.setCellFromCodepoint(I,0,1,W)}replaceCells(I,z,W,H=!1){if(H)for(I&&this.getWidth(I-1)===2&&!this.isProtected(I-1)&&this.setCellFromCodepoint(I-1,0,1,W),z<this.length&&this.getWidth(z-1)===2&&!this.isProtected(z)&&this.setCellFromCodepoint(z,0,1,W);I<z&&I<this.length;)this.isProtected(I)||this.setCell(I,W),I++;else for(I&&this.getWidth(I-1)===2&&this.setCellFromCodepoint(I-1,0,1,W),z<this.length&&this.getWidth(z-1)===2&&this.setCellFromCodepoint(z,0,1,W);I<z&&I<this.length;)this.setCell(I++,W)}resize(I,z){if(I===this.length)return 4*this._data.length*2<this._data.buffer.byteLength;let W=3*I;if(I>this.length){if(this._data.buffer.byteLength>=4*W)this._data=new Uint32Array(this._data.buffer,0,W);else{let H=new Uint32Array(W);H.set(this._data),this._data=H}for(let H=this.length;H<I;++H)this.setCell(H,z)}else{this._data=this._data.subarray(0,W);let H=Object.keys(this._combined);for(let N=0;N<H.length;N++){let w=parseInt(H[N],10);w>=I&&delete this._combined[w]}let q=Object.keys(this._extendedAttrs);for(let N=0;N<q.length;N++){let w=parseInt(q[N],10);w>=I&&delete this._extendedAttrs[w]}}return this.length=I,4*W*2<this._data.buffer.byteLength}cleanupMemory(){if(4*this._data.length*2<this._data.buffer.byteLength){let I=new Uint32Array(this._data.length);return I.set(this._data),this._data=I,1}return 0}fill(I,z=!1){if(z)for(let W=0;W<this.length;++W)this.isProtected(W)||this.setCell(W,I);else{this._combined={},this._extendedAttrs={};for(let W=0;W<this.length;++W)this.setCell(W,I)}}copyFrom(I){this.length!==I.length?this._data=new Uint32Array(I._data):this._data.set(I._data),this.length=I.length,this._combined={};for(let z in I._combined)this._combined[z]=I._combined[z];this._extendedAttrs={};for(let z in I._extendedAttrs)this._extendedAttrs[z]=I._extendedAttrs[z];this.isWrapped=I.isWrapped}clone(){let I=new K(0);I._data=new Uint32Array(this._data),I.length=this.length;for(let z in this._combined)I._combined[z]=this._combined[z];for(let z in this._extendedAttrs)I._extendedAttrs[z]=this._extendedAttrs[z];return I.isWrapped=this.isWrapped,I}getTrimmedLength(){for(let I=this.length-1;I>=0;--I)if(4194303&this._data[3*I+0])return I+(this._data[3*I+0]>>22);return 0}getNoBgTrimmedLength(){for(let I=this.length-1;I>=0;--I)if(4194303&this._data[3*I+0]||50331648&this._data[3*I+2])return I+(this._data[3*I+0]>>22);return 0}copyCellsFrom(I,z,W,H,q){let N=I._data;if(q)for(let O=H-1;O>=0;O--){for(let L=0;L<3;L++)this._data[3*(W+O)+L]=N[3*(z+O)+L];268435456&N[3*(z+O)+2]&&(this._extendedAttrs[W+O]=I._extendedAttrs[z+O])}else for(let O=0;O<H;O++){for(let L=0;L<3;L++)this._data[3*(W+O)+L]=N[3*(z+O)+L];268435456&N[3*(z+O)+2]&&(this._extendedAttrs[W+O]=I._extendedAttrs[z+O])}let w=Object.keys(I._combined);for(let O=0;O<w.length;O++){let L=parseInt(w[O],10);L>=z&&(this._combined[L-z+W]=I._combined[L])}}translateToString(I,z,W,H){z=z??0,W=W??this.length,I&&(W=Math.min(W,this.getTrimmedLength())),H&&(H.length=0);let q="";for(;z<W;){let N=this._data[3*z+0],w=2097151&N,O=2097152&N?this._combined[z]:w?(0,G.stringFromCodePoint)(w):X.WHITESPACE_CELL_CHAR;if(q+=O,H)for(let L=0;L<O.length;++L)H.push(z);z+=N>>22||1}return H&&H.push(z),q}}Y.BufferLine=K},634:(F,Y)=>{function E(Z,U,X){if(U===Z.length-1)return Z[U].getTrimmedLength();let G=!Z[U].hasContent(X-1)&&Z[U].getWidth(X-1)===1,V=Z[U+1].getWidth(0)===2;return G&&V?X-1:X}Object.defineProperty(Y,"__esModule",{value:!0}),Y.getWrappedLineTrimmedLength=Y.reflowSmallerGetNewLineLengths=Y.reflowLargerApplyNewLayout=Y.reflowLargerCreateNewLayout=Y.reflowLargerGetLinesToRemove=void 0,Y.reflowLargerGetLinesToRemove=function(Z,U,X,G,V){let K=[];for(let I=0;I<Z.length-1;I++){let z=I,W=Z.get(++z);if(!W.isWrapped)continue;let H=[Z.get(I)];for(;z<Z.length&&W.isWrapped;)H.push(W),W=Z.get(++z);if(G>=I&&G<z){I+=H.length-1;continue}let q=0,N=E(H,q,U),w=1,O=0;for(;w<H.length;){let j=E(H,w,U),k=j-O,_=X-N,f=Math.min(k,_);H[q].copyCellsFrom(H[w],O,N,f,!1),N+=f,N===X&&(q++,N=0),O+=f,O===j&&(w++,O=0),N===0&&q!==0&&H[q-1].getWidth(X-1)===2&&(H[q].copyCellsFrom(H[q-1],X-1,N++,1,!1),H[q-1].setCell(X-1,V))}H[q].replaceCells(N,X,V);let L=0;for(let j=H.length-1;j>0&&(j>q||H[j].getTrimmedLength()===0);j--)L++;L>0&&(K.push(I+H.length-L),K.push(L)),I+=H.length-1}return K},Y.reflowLargerCreateNewLayout=function(Z,U){let X=[],G=0,V=U[G],K=0;for(let I=0;I<Z.length;I++)if(V===I){let z=U[++G];Z.onDeleteEmitter.fire({index:I-K,amount:z}),I+=z-1,K+=z,V=U[++G]}else X.push(I);return{layout:X,countRemoved:K}},Y.reflowLargerApplyNewLayout=function(Z,U){let X=[];for(let G=0;G<U.length;G++)X.push(Z.get(U[G]));for(let G=0;G<X.length;G++)Z.set(G,X[G]);Z.length=U.length},Y.reflowSmallerGetNewLineLengths=function(Z,U,X){let G=[],V=Z.map((W,H)=>E(Z,H,U)).reduce((W,H)=>W+H),K=0,I=0,z=0;for(;z<V;){if(V-z<X){G.push(V-z);break}K+=X;let W=E(Z,I,U);K>W&&(K-=W,I++);let H=Z[I].getWidth(K-1)===2;H&&K--;let q=H?X-1:X;G.push(q),z+=q}return G},Y.getWrappedLineTrimmedLength=E},295:(F,Y,E)=>{Object.defineProperty(Y,"__esModule",{value:!0}),Y.BufferSet=void 0;let Z=E(460),U=E(844),X=E(92);class G extends U.Disposable{constructor(V,K){super(),this._optionsService=V,this._bufferService=K,this._onBufferActivate=this.register(new Z.EventEmitter),this.onBufferActivate=this._onBufferActivate.event,this.reset(),this.register(this._optionsService.onSpecificOptionChange("scrollback",()=>this.resize(this._bufferService.cols,this._bufferService.rows))),this.register(this._optionsService.onSpecificOptionChange("tabStopWidth",()=>this.setupTabStops()))}reset(){this._normal=new X.Buffer(!0,this._optionsService,this._bufferService),this._normal.fillViewportRows(),this._alt=new X.Buffer(!1,this._optionsService,this._bufferService),this._activeBuffer=this._normal,this._onBufferActivate.fire({activeBuffer:this._normal,inactiveBuffer:this._alt}),this.setupTabStops()}get alt(){return this._alt}get active(){return this._activeBuffer}get normal(){return this._normal}activateNormalBuffer(){this._activeBuffer!==this._normal&&(this._normal.x=this._alt.x,this._normal.y=this._alt.y,this._alt.clearAllMarkers(),this._alt.clear(),this._activeBuffer=this._normal,this._onBufferActivate.fire({activeBuffer:this._normal,inactiveBuffer:this._alt}))}activateAltBuffer(V){this._activeBuffer!==this._alt&&(this._alt.fillViewportRows(V),this._alt.x=this._normal.x,this._alt.y=this._normal.y,this._activeBuffer=this._alt,this._onBufferActivate.fire({activeBuffer:this._alt,inactiveBuffer:this._normal}))}resize(V,K){this._normal.resize(V,K),this._alt.resize(V,K),this.setupTabStops(V)}setupTabStops(V){this._normal.setupTabStops(V),this._alt.setupTabStops(V)}}Y.BufferSet=G},511:(F,Y,E)=>{Object.defineProperty(Y,"__esModule",{value:!0}),Y.CellData=void 0;let Z=E(482),U=E(643),X=E(734);class G extends X.AttributeData{constructor(){super(...arguments),this.content=0,this.fg=0,this.bg=0,this.extended=new X.ExtendedAttrs,this.combinedData=""}static fromCharData(V){let K=new G;return K.setFromCharData(V),K}isCombined(){return 2097152&this.content}getWidth(){return this.content>>22}getChars(){return 2097152&this.content?this.combinedData:2097151&this.content?(0,Z.stringFromCodePoint)(2097151&this.content):""}getCode(){return this.isCombined()?this.combinedData.charCodeAt(this.combinedData.length-1):2097151&this.content}setFromCharData(V){this.fg=V[U.CHAR_DATA_ATTR_INDEX],this.bg=0;let K=!1;if(V[U.CHAR_DATA_CHAR_INDEX].length>2)K=!0;else if(V[U.CHAR_DATA_CHAR_INDEX].length===2){let I=V[U.CHAR_DATA_CHAR_INDEX].charCodeAt(0);if(55296<=I&&I<=56319){let z=V[U.CHAR_DATA_CHAR_INDEX].charCodeAt(1);56320<=z&&z<=57343?this.content=1024*(I-55296)+z-56320+65536|V[U.CHAR_DATA_WIDTH_INDEX]<<22:K=!0}else K=!0}else this.content=V[U.CHAR_DATA_CHAR_INDEX].charCodeAt(0)|V[U.CHAR_DATA_WIDTH_INDEX]<<22;K&&(this.combinedData=V[U.CHAR_DATA_CHAR_INDEX],this.content=2097152|V[U.CHAR_DATA_WIDTH_INDEX]<<22)}getAsCharData(){return[this.fg,this.getChars(),this.getWidth(),this.getCode()]}}Y.CellData=G},643:(F,Y)=>{Object.defineProperty(Y,"__esModule",{value:!0}),Y.WHITESPACE_CELL_CODE=Y.WHITESPACE_CELL_WIDTH=Y.WHITESPACE_CELL_CHAR=Y.NULL_CELL_CODE=Y.NULL_CELL_WIDTH=Y.NULL_CELL_CHAR=Y.CHAR_DATA_CODE_INDEX=Y.CHAR_DATA_WIDTH_INDEX=Y.CHAR_DATA_CHAR_INDEX=Y.CHAR_DATA_ATTR_INDEX=Y.DEFAULT_EXT=Y.DEFAULT_ATTR=Y.DEFAULT_COLOR=void 0,Y.DEFAULT_COLOR=0,Y.DEFAULT_ATTR=256|Y.DEFAULT_COLOR<<9,Y.DEFAULT_EXT=0,Y.CHAR_DATA_ATTR_INDEX=0,Y.CHAR_DATA_CHAR_INDEX=1,Y.CHAR_DATA_WIDTH_INDEX=2,Y.CHAR_DATA_CODE_INDEX=3,Y.NULL_CELL_CHAR="",Y.NULL_CELL_WIDTH=1,Y.NULL_CELL_CODE=0,Y.WHITESPACE_CELL_CHAR=" ",Y.WHITESPACE_CELL_WIDTH=1,Y.WHITESPACE_CELL_CODE=32},863:(F,Y,E)=>{Object.defineProperty(Y,"__esModule",{value:!0}),Y.Marker=void 0;let Z=E(460),U=E(844);class X{get id(){return this._id}constructor(G){this.line=G,this.isDisposed=!1,this._disposables=[],this._id=X._nextId++,this._onDispose=this.register(new Z.EventEmitter),this.onDispose=this._onDispose.event}dispose(){this.isDisposed||(this.isDisposed=!0,this.line=-1,this._onDispose.fire(),(0,U.disposeArray)(this._disposables),this._disposables.length=0)}register(G){return this._disposables.push(G),G}}Y.Marker=X,X._nextId=1},116:(F,Y)=>{Object.defineProperty(Y,"__esModule",{value:!0}),Y.DEFAULT_CHARSET=Y.CHARSETS=void 0,Y.CHARSETS={},Y.DEFAULT_CHARSET=Y.CHARSETS.B,Y.CHARSETS[0]={"`":"◆",a:"▒",b:"␉",c:"␌",d:"␍",e:"␊",f:"°",g:"±",h:"␤",i:"␋",j:"┘",k:"┐",l:"┌",m:"└",n:"┼",o:"⎺",p:"⎻",q:"─",r:"⎼",s:"⎽",t:"├",u:"┤",v:"┴",w:"┬",x:"│",y:"≤",z:"≥","{":"π","|":"≠","}":"£","~":"·"},Y.CHARSETS.A={"#":"£"},Y.CHARSETS.B=void 0,Y.CHARSETS[4]={"#":"£","@":"¾","[":"ij","\\":"½","]":"|","{":"¨","|":"f","}":"¼","~":"´"},Y.CHARSETS.C=Y.CHARSETS[5]={"[":"Ä","\\":"Ö","]":"Å","^":"Ü","`":"é","{":"ä","|":"ö","}":"å","~":"ü"},Y.CHARSETS.R={"#":"£","@":"à","[":"°","\\":"ç","]":"§","{":"é","|":"ù","}":"è","~":"¨"},Y.CHARSETS.Q={"@":"à","[":"â","\\":"ç","]":"ê","^":"î","`":"ô","{":"é","|":"ù","}":"è","~":"û"},Y.CHARSETS.K={"@":"§","[":"Ä","\\":"Ö","]":"Ü","{":"ä","|":"ö","}":"ü","~":"ß"},Y.CHARSETS.Y={"#":"£","@":"§","[":"°","\\":"ç","]":"é","`":"ù","{":"à","|":"ò","}":"è","~":"ì"},Y.CHARSETS.E=Y.CHARSETS[6]={"@":"Ä","[":"Æ","\\":"Ø","]":"Å","^":"Ü","`":"ä","{":"æ","|":"ø","}":"å","~":"ü"},Y.CHARSETS.Z={"#":"£","@":"§","[":"¡","\\":"Ñ","]":"¿","{":"°","|":"ñ","}":"ç"},Y.CHARSETS.H=Y.CHARSETS[7]={"@":"É","[":"Ä","\\":"Ö","]":"Å","^":"Ü","`":"é","{":"ä","|":"ö","}":"å","~":"ü"},Y.CHARSETS["="]={"#":"ù","@":"à","[":"é","\\":"ç","]":"ê","^":"î",_:"è","`":"ô","{":"ä","|":"ö","}":"ü","~":"û"}},584:(F,Y)=>{var E,Z,U;Object.defineProperty(Y,"__esModule",{value:!0}),Y.C1_ESCAPED=Y.C1=Y.C0=void 0,function(X){X.NUL="\x00",X.SOH="\x01",X.STX="\x02",X.ETX="\x03",X.EOT="\x04",X.ENQ="\x05",X.ACK="\x06",X.BEL="\x07",X.BS="\b",X.HT="\t",X.LF=`
2659
+ `,TO4={spec:{name:N2,description:K33,inputSchema:x.toJSONSchema(aa0),source:"builtin",executionProfile:{resourceKeys:(A)=>{if(A&&typeof A==="object"&&"path"in A&&typeof A.path==="string")return[{key:A.path,mode:"write"}];return[]}}},fn:RO4}});function I33(A){if(A.before===void 0&&A.after===void 0)throw Error("unreachable");if(A.before===null&&A.after===null)throw Error("unreachable")}async function W33(A,Q,$,B){let D={};D.before=await vO4($);let J=await B();return D.after=await vO4($),I33(D),await A.record({toolUse:Q,uri:$,...D}),J}async function UF0(A,Q,$,B,D){await W33(A,Q,$,()=>X7(GA($),B,{encoding:"utf8",signal:D?.signal}))}function iS(A,Q,$,B){return A.record({toolUse:Q,uri:$,...B})}async function vO4(A){try{return await hA(GA(A),{encoding:"utf8"})}catch(Q){if(w5(Q))return null;throw Q}}function oa0(A,Q,$){let B=new Map,D=(F)=>{let Y;for(let[E,Z]of B.entries())for(let[U,X]of Z.entries()){if(!B1.equalURIs(U,F))continue;if(!Y||X.timestamp<Y.timestamp)Y=X}return Y},J=async({filesFilter:F,toolUsesToRevert:Y,pruneRevertedToolUses:E})=>{let Z=new $Q,U=new Map;for(let[V,K]of B.entries()){let I=Y?Y.has(V):!0;for(let[z,W]of K.entries()){if(F&&!F(z))continue;if(W.reverted)continue;let H=Z.get(z)||{changesAfterKeep:[]};if(!I){if(!H.latestKeepChange||W.timestamp>H.latestKeepChange.timestamp)H.latestKeepChange=W}else H.changesAfterKeep.push(W),U.set(W,V);Z.set(z,H)}}let X=Array.from(Z.entries()).filter(([,{changesAfterKeep:V}])=>V.length>0);if(await _Q0(X,H33,async([V,{latestKeepChange:K,changesAfterKeep:I}])=>{try{let z=I.reduce((H,q)=>q.timestamp<H.timestamp?q:H),W=K?K.after:z.isNewFile?null:z.before;await $(V,W);for(let H of I){H.reverted=!0;let q=U.get(H);if(q)try{let N={toolUseID:q,fileChangeID:H.id};await A.store(Q,N,H)}catch(N){P.error(`Error updating backup for file ${V}:`,N)}}}catch(z){P.error(`Error reverting file ${V}:`,z)}}),E&&Y)for(let V of Y)B.delete(V)};return{async getAllRecords(){return B},async record(F){if(!F.toolUse)return;let Y=B.get(F.toolUse);if(!Y)Y=new $Q,B.set(F.toolUse,Y);let E=Y.get(F.uri),Z=D(F.uri),U=E?.before??F.before??"",X=E?.isNewFile??F.before===null,G=Z?SZ(Z.before??"",F.after??"",F.uri):SZ(U,F.after??"",F.uri),V=E?.id??crypto.randomUUID(),K={id:V,uri:t1(F.uri),before:U,after:F.after??"",diff:G,isNewFile:X,reverted:!1,timestamp:Date.now()};Y.set(F.uri,K),await A.store(Q,{toolUseID:F.toolUse,fileChangeID:V},K),P.debug("Recorded file change",{isNewFile:X,isUpdate:!!E,filePath:F.uri.toString(),toolUseID:F.toolUse})},async restoreFromBackups(){let F=await A.list(Q)??[];B.clear();for(let Y of F){let{toolUseID:E}=Y,Z=await A.load(Q,Y);if(!Z)continue;if(!B.has(E))B.set(E,new $Q);B.get(E).set(Z.uri,Z)}return{totalBackups:F.length}},async revertAll(F){let Y=new Set;for(let[E]of B.entries())Y.add(E);await J({filesFilter:F?(E)=>B1.equalURIs(E,F):void 0,toolUsesToRevert:Y,pruneRevertedToolUses:!1})},async revertChanges(F){await J({toolUsesToRevert:F,pruneRevertedToolUses:!0})},getFilesForToolUses(F){let Y=new $Q;for(let[E,Z]of B.entries()){if(!F.has(E))continue;for(let[U,X]of Z.entries()){if(X.reverted)continue;Y.set(U,!0)}}return Array.from(Y.keys()).map(t1)},async cleanupBackups(){await A.cleanup(Q)},async getLastEdit(F){let Y,E,Z=0;for(let[G,V]of B.entries()){let K=V.get(F);if(K&&!K.reverted&&K.timestamp>=Z)Y=K,E=G,Z=K.timestamp}if(!Y||!E)return;let U=Y,X=E;return{oldContent:U.before,newContent:U.after,revert:async()=>{U.reverted=!0,await A.store(Q,{toolUseID:X,fileChangeID:U.id},U)}}},dispose(){B.clear()}}}function XF0(A,Q){async function $(B,D,J){if(D!==null)await X7(B,D,{encoding:"utf8",signal:J});else await HX(B)}return oa0(A.fileChangeTrackerStorage,Q,$)}var H33=4;var Dj=o(()=>{Q4();p0();RA();hK();Bj();TQ0()});function q33(A){if(A.action.type==="redact-tool-input"&&A.on.event!=="tool:post-execute")return"redact-tool-input action can only be used with tool:post-execute event";if(A.action.type==="send-user-message"&&A.on.event!=="tool:pre-execute")return"send-user-message action can only be used with tool:pre-execute event";return null}function ra0(A){if(!A||!Array.isArray(A))return[];return A.filter((Q)=>{if(Q.compatibilityDate!=="2025-05-13")return!1;let $=q33(Q);if($)return P.warn(`Hook "${Q.id}" is invalid: ${$}`),!1;return!0})}var kO4=o(()=>{p0()});function SO4(A,Q){if(!A)return{action:null};A=ra0(A);for(let $ of A){if($.if===!1)continue;if($.on.event==="tool:pre-execute"){if(!(Array.isArray($.on.tool)?$.on.tool:[$.on.tool]).includes(Q.toolUse.name))continue;let D=JSON.stringify(Q.toolUse.input),J=Array.isArray($.on["input.contains"])?$.on["input.contains"]:[$.on["input.contains"]];for(let F of J)if(D.includes(F)){if(P.debug(`Hook triggered: ${$.id}`,{hookID:$.id,threadID:Q.threadID,toolName:Q.toolUse.name,toolUseID:Q.toolUse.id,matchString:F,action:$.action}),$.action.type==="send-user-message")return{hookID:$.id,action:$.action}}}}return{action:null}}function fO4(A,Q){if(!A)return{action:null};A=ra0(A);for(let $ of A){if($.if===!1)continue;if($.on.event==="tool:post-execute"){if(!(Array.isArray($.on.tool)?$.on.tool:[$.on.tool]).includes(Q.toolUse.name))continue;if(P.debug(`Post-execution hook triggered: ${$.id}`,{hookID:$.id,threadID:Q.threadID,toolName:Q.toolUse.name,toolUseID:Q.toolUse.id,action:$.action}),$.action.type==="redact-tool-input")return{hookID:$.id,action:$.action}}}return{action:null}}function yO4(A,Q){if(!A)return{action:null};try{return A(Q.thread)}catch($){return P.error("Error processing assistant end-turn hook",$),{action:null}}}function nS(A,Q,$){if(!Q.action)return{abortOp:!1};switch(Q.action.type){case"send-user-message":{let B={type:"user:message",message:{messageId:0,content:[{type:"text",text:Q.action.message}],source:{type:"hook",hook:Q.hookID}}};return A.updateThread(B),A.onThreadDelta(B),{abortOp:!0}}case"redact-tool-input":{if(!$?.toolUseID)return P.warn("redact-tool-input action requires toolUseID in context"),{abortOp:!1};let B={type:"tool:processed",toolUse:$.toolUseID,newArgs:Q.action.redactedInput};return A.updateThread(B),A.onThreadDelta(B),P.debug("Tool input redacted",{hookID:Q.hookID,toolUseID:$.toolUseID}),{abortOp:!1}}case"handoff":return P.info("Handoff hook triggered",{hookID:Q.hookID,goal:Q.action.goal}),A.executeHandoff(Q.action.goal),{abortOp:!1}}}var sa0=o(()=>{p0();kO4()});function N33(A,Q,$){let B=$.getExecutionProfile(A.name),D=$.getExecutionProfile(Q.name);if(!B||!D)return!0;if(B.serial||D.serial)return!0;let J=B.resourceKeys(A.input??{}),F=D.resourceKeys(Q.input??{});for(let Y of J)for(let E of F)if(Y.key===E.key){if(Y.mode==="write"||E.mode==="write")return!0}return!1}function w33(A,Q,$){for(let B of Q)if(N33(A,B,$))return!0;return!1}function xO4(A,Q){if(A.length===0)return[];let $=[],B=[];for(let D of A){if(w33(D,B,Q)){if(B.length>0)$.push(B),B=[]}B.push(D)}if(B.length>0)$.push(B);return $}class ta0{threadID;toolService;callbacks;processingMutex=new XJ;runningTools=new Map;cancelledToolUses=new Set;toolMessages=new Map;toolCompletionResolvers=new Map;pendingApprovalsSubscription;writtenBlockedToolUseIds=new Set;disposed=!1;constructor(A,Q,$){this.threadID=A;this.toolService=Q;this.callbacks=$;this.pendingApprovalsSubscription=this.toolService.pendingApprovals$.subscribe((B)=>{this.syncPendingApprovalsToThreadState(B)})}syncPendingApprovalsToThreadState(A){let Q=A.filter((B)=>B.threadId===this.threadID);for(let B of Q)if(!this.writtenBlockedToolUseIds.has(B.toolUseId))this.writtenBlockedToolUseIds.add(B.toolUseId),P.debug("Writing blocked-on-user to thread state",{name:"syncPendingApprovalsToThreadState",threadID:this.threadID,toolUseId:B.toolUseId,toolName:B.toolName}),this.callbacks.updateThread({type:"tool:data",toolUse:B.toolUseId,data:{status:"blocked-on-user",reason:B.reason,toAllow:B.toAllow}});let $=new Set(Q.map((B)=>B.toolUseId));for(let B of this.writtenBlockedToolUseIds)if(!$.has(B))this.writtenBlockedToolUseIds.delete(B)}async onResume(){await this.processingMutex.acquire();try{let A=this.callbacks.getThread(),Q=D9(A,"user");if(!Q)return;for(let $ of Q.content){if($.type!=="tool_result")continue;if($.run.status==="blocked-on-user"){let J=this.findToolUseById($.toolUseID);if(!J)continue;P.debug(`restoring blocked-on-user tool ${J.name} to approval queue`,{name:"onResume",threadID:this.threadID,toolUseID:$.toolUseID}),this.toolService.restoreApproval({threadId:this.threadID,toolUseId:$.toolUseID,toolName:J.name,args:J.input??{},reason:$.run.reason,toAllow:$.run.toAllow,context:A.mainThreadID?"subagent":"thread"});continue}if(!(!f3($.run.status)&&!this.runningTools.has($.toolUseID)))continue;let D=this.findToolUseById($.toolUseID);if(!D)continue;if(this.isDangerousToResume(D.name)){P.debug(`cancelling dangerous tool ${D.name} on resume`,{name:"onResume",threadID:this.threadID,toolUseID:$.toolUseID});let J=VL($.run);this.callbacks.updateThread({type:"tool:data",toolUse:$.toolUseID,data:{status:"cancelled",reason:"system:safety",progress:J}});continue}P.debug(`re-invoking tool ${D.name} with ID ${$.toolUseID}`,{name:"onResume",threadID:this.threadID}),await this.invokeTool(D,$.userInput)}}finally{this.processingMutex.release()}await this.callbacks.updateFileChanges()}async onAssistantMessageComplete(A){let Q;await this.processingMutex.acquire();try{this.cancelledToolUses.clear(),Q=this.findToolUsesNeedingInvocation(A),P.debug(`saw ${Q.length} tool uses (${Q.map(($)=>$.name).join(", ")})`,{name:"onAssistantMessageComplete",threadID:this.threadID})}finally{this.processingMutex.release()}if(Q.length>0)await this.executeToolsWithPlan(Q)}async userProvideInput(A,Q){await this.processingMutex.acquire();try{let $=this.findToolUseById(A);if($&&l5($))await this.invokeTool($,Q)}finally{this.processingMutex.release()}}async userCancel(A){await this.cancelTool(A,"user:cancelled")}async onNewUserMessage(){this.markAllActiveToolsCancelled(),this.toolService.clearApprovalsForThread(this.threadID),await this.cancelAll("user:interrupted")}async cancelAll(A){await this.processingMutex.acquire();try{this.markAllActiveToolsCancelled(),this.toolService.clearApprovalsForThread(this.threadID),this.cancelUnstartedTools(A),await this.cancelInProgressTools(A)}finally{this.processingMutex.release()}}async findAndCancelToolRun(A,Q){let $=this.callbacks.getThread();if(!E7($,A))return;await this.cancelTool(A,"user:cancelled",Q)}async cancelToolOnly(A,Q){let $=this.callbacks.getThread();if(!E7($,A))return;let D=this.getCancelDataForToolRun(A,"user:cancelled"),J=this.toolMessages.get(A);if(J){try{J.next({type:"stop-command"})}catch(F){P.warn("Failed to send stop-command",{toolUseID:A,error:F})}J.complete(),this.toolMessages.delete(A)}P.debug(`cancelToolOnly(${A})`),await this.callbacks.handle({type:"tool:data",toolUse:A,data:D},Q)}getRunningToolIds(){return Array.from(this.runningTools.keys())}hasRunningTools(){return this.runningTools.size>0}isCancelled(A){return this.cancelledToolUses.has(A)}markCancelled(A){this.cancelledToolUses.add(A)}clearCancelled(A){this.cancelledToolUses.delete(A)}sendToolMessage(A,Q){let $=this.toolMessages.get(A);if($)return $.next(Q),!0;return!1}resolveToolCompletion(A,Q,$){let B=this.toolCompletionResolvers.get(A);if(B){if(Q)B.resolve();else B.reject($??Error(`Tool failed: ${A}`));this.toolCompletionResolvers.delete(A)}}dispose(){if(this.disposed)return;this.disposed=!0,this.pendingApprovalsSubscription.unsubscribe(),this.toolService.clearApprovalsForThread(this.threadID),this.writtenBlockedToolUseIds.clear();for(let[A,Q]of this.toolCompletionResolvers)try{Q.reject(Error("Orchestrator disposed"))}finally{this.toolCompletionResolvers.delete(A)}for(let[A,Q]of this.toolMessages)try{Q.next({type:"stop-command"}),Q.complete()}catch($){P.warn("Failed to cleanup tool messages during disposal",{id:A,error:$})}this.toolMessages.clear();for(let A of this.runningTools.values())A.abort.abort();this.runningTools.clear(),this.cancelledToolUses.clear()}findToolUsesNeedingInvocation(A){if(A.content.some((Y)=>Y.type==="tool_use"&&!l5(Y)))return[];if(!(A.state?.type==="complete"||A.state?.type==="cancelled"))return[];let B=this.callbacks.getThread(),D=D9(B,"user"),J=D9(B,"assistant"),F=new Set;if(D?.messageId!==void 0&&J?.messageId!==void 0&&D.messageId>J.messageId){for(let Y of D.content)if(Y.type==="tool_result")F.add(Y.toolUseID)}return A.content.filter((Y)=>Y.type==="tool_use").filter((Y)=>!F.has(Y.id)&&!this.cancelledToolUses.has(Y.id))}async executeToolsWithPlan(A){if(A.length===0)return;let Q=xO4(A,this.toolService);P.debug(`executing ${A.length} tools in ${Q.length} batch(es)`,{name:"executeToolsWithPlan",threadID:this.threadID,batches:Q.map(($)=>$.map((B)=>B.name))}),await this.executeToolBatchesSequentially(Q)}async executeToolBatchesSequentially(A){for(let Q of A){let B=(await Promise.allSettled(Q.map((D)=>this.invokeToolAndWait(D,void 0)))).filter((D)=>D.status==="rejected");if(B.length>0)P.warn(`${B.length} tool(s) failed in batch`,{name:"executeToolBatchesSequentially",threadID:this.threadID,errors:B.map((D)=>D.reason)})}}async invokeToolAndWait(A,Q){let $=new Promise((B,D)=>{this.toolCompletionResolvers.set(A.id,{resolve:B,reject:D})});this.invokeTool(A,Q).catch((B)=>{let D=this.toolCompletionResolvers.get(A.id);if(D)P.debug(`Tool invocation setup failed for ${A.id}`,{name:"invokeToolAndWait",threadID:this.threadID,error:String(B)}),D.reject(B),this.toolCompletionResolvers.delete(A.id)}),await $}async invokeTool(A,Q){if(this.runningTools.has(A.id))throw Error(`(bug) tool invocation already in progress: ${A.id}`);if(!l5(A))throw Error(`(bug) tool use is incomplete: ${A.id}`);let $=await this.callbacks.getConfig(),B=SO4($.settings?.hooks,{threadID:this.threadID,toolUse:A}),{abortOp:D}=await this.callbacks.applyHookResult(B);if(D){let E=this.toolCompletionResolvers.get(A.id);if(E)E.resolve(),this.toolCompletionResolvers.delete(A.id);return}let J=A.input;if(this.callbacks.requestPluginToolCall){let E={thread:{id:this.threadID},toolUseID:A.id,tool:A.name,input:A.input??{}},Z=await this.callbacks.requestPluginToolCall(E);if(Z.action==="error"){P.warn("Plugin returned error action",{tool:A.name,message:Z.message,toolUseID:A.id});let U=this.toolCompletionResolvers.get(A.id);if(await this.callbacks.handle({type:"tool:data",toolUse:A.id,data:{status:"error",error:{message:`Plugin error: ${Z.message}`,displayMessage:Z.message}}}),U)U.resolve(),this.toolCompletionResolvers.delete(A.id);return}if(Z.action==="reject-and-continue"){let U=this.toolCompletionResolvers.get(A.id);if(await this.callbacks.handle({type:"tool:data",toolUse:A.id,data:{status:"done",result:`Tool rejected by plugin: ${Z.message}`,isFinal:!1}}),U)U.resolve(),this.toolCompletionResolvers.delete(A.id);return}if(Z.action==="synthesize"){let U=this.toolCompletionResolvers.get(A.id);if(await this.callbacks.handle({type:"tool:data",toolUse:A.id,data:{status:"done",result:Z.result.output,isFinal:!1}}),U)U.resolve(),this.toolCompletionResolvers.delete(A.id);return}if(Z.action==="modify")J=Z.input,await this.callbacks.handle({type:"tool:processed",toolUse:A.id,newArgs:Z.input})}if(this.cancelledToolUses.has(A.id)){this.ensureCancelledToolResult(A.id,"user:interrupted"),this.resolveToolCompletion(A.id,!0);return}let F=new AbortController,Y={abort:F};this.runningTools.set(A.id,Y),this.callbacks.updateThread({type:"tool:data",toolUse:A.id,data:{status:"in-progress"}});try{let E=await this.callbacks.getToolRunEnvironment(A.id,F.signal),Z=new h0((q)=>{this.toolMessages.set(A.id,q)}),U={...E,toolMessages:Z},X=this.toolService.preprocessArgs?.(A.name,J,U);if(X)await this.callbacks.handle({type:"tool:processed",toolUse:A.id,newArgs:X});let G=X??J,V=this.toolService.normalizeToolName(A.name),K=typeof G==="object"&&G!==null?this.toolService.normalizeToolArgs(A.name,G):G,I=typeof K==="object"&&K!==null&&"__isFinal"in K&&typeof K.__isFinal==="boolean"?K.__isFinal:void 0,z=I!==void 0?Object.fromEntries(Object.entries(K).filter(([q])=>q!=="__isFinal")):K,W=this.toolService.invokeTool(V,{args:z,userInput:Q},U).pipe(BK(this.callbacks.getDisposed$()),nW(()=>{this.runningTools.delete(A.id),this.toolMessages.get(A.id)?.complete(),this.toolMessages.delete(A.id)})).subscribe({next:async(q)=>{if(this.cancelledToolUses.has(A.id))return;if(P.debug(`${A.id}, ${q.status}`,{name:"invokeTool",threadID:this.threadID}),f3(q.status)){this.runningTools.delete(A.id),W.unsubscribe();let w=this.toolCompletionResolvers.get(A.id);if(w){if(q.status==="done")w.resolve();else w.reject(Error(`Tool ${q.status}: ${A.id}`));this.toolCompletionResolvers.delete(A.id)}if(q.status==="done"&&A.name.toLowerCase()===n7.toLowerCase())this.callbacks.onSkillToolComplete(A);if($.settings?.hooks){let O=fO4($.settings.hooks,{threadID:this.threadID,toolUse:A});await this.callbacks.applyPostHookResult(O,{toolUseID:A.id})}if(this.callbacks.requestPluginToolResult){let O={thread:{id:this.threadID},toolUseID:A.id,tool:A.name,input:A.input??{},status:q.status,error:q.status==="error"?q.error?.message:void 0,output:q.status==="done"?q.result:void 0};try{let L=await this.callbacks.requestPluginToolResult(O);if(L)q={...q,status:L.status,error:L.status==="error"?{message:L.error??"Plugin error"}:void 0,result:L.output}}catch(L){P.debug("Failed to request plugin tool result",{error:L})}}}await this.callbacks.updateFileChanges();let N=I!==void 0&&q.status==="done"&&q.isFinal===void 0?{...q,isFinal:I}:q;await this.callbacks.handle({type:"tool:data",toolUse:A.id,data:N},F.signal)},error:async(q)=>{let N=this.toolCompletionResolvers.get(A.id);if(N)N.reject(q),this.toolCompletionResolvers.delete(A.id);await this.callbacks.handle({type:"tool:data",toolUse:A.id,data:{status:"error",error:{message:"message"in q?q.message:String(q),displayMessage:"displayMessage"in q?q.displayMessage:void 0}}},F.signal)},complete:()=>{let q=this.toolCompletionResolvers.get(A.id);if(!q)return;let N=this.callbacks.getThread(),w=rF(N).get(A.id)?.run;if(w&&f3(w.status))return;let O;if(this.callbacks.isDisposed())O="Worker disposed";else if(F.signal.aborted)O="Tool aborted";else if(this.cancelledToolUses.has(A.id))O="Tool cancelled";else O="Tool observable completed without terminal state";q.reject(Error(O)),this.toolCompletionResolvers.delete(A.id)}}),H=this.runningTools.get(A.id);if(H)H.subscription=W;QY(F.signal,()=>W.unsubscribe())}catch(E){this.runningTools.delete(A.id);let Z=this.toolCompletionResolvers.get(A.id);if(Z)Z.reject(E),this.toolCompletionResolvers.delete(A.id);throw E}}async cancelTool(A,Q,$){let B=this.getCancelDataForToolRun(A,Q),D=this.toolMessages.get(A);if(D){try{D.next({type:"stop-command"})}catch(J){P.warn("Failed to send stop-command",{toolUseID:A,error:J})}D.complete(),this.toolMessages.delete(A)}P.debug(`cancelTool(${A}, ${Q})`),await this.callbacks.handle({type:"tool:data",toolUse:A,data:B},$),this.resolveToolCompletion(A,!0)}ensureCancelledToolResult(A,Q){let $=this.callbacks.getThread(),B=rF($).get(A)?.run;if(B&&f3(B.status))return;this.callbacks.updateThread({type:"tool:data",toolUse:A,data:{status:"cancelled",reason:Q,progress:B?VL(B):void 0}})}getCancelDataForToolRun(A,Q){let $=this.callbacks.getThread(),B=rF($).get(A)?.run;return{status:"cancelled",progress:B?VL(B):void 0,reason:Q}}markAllActiveToolsCancelled(){let A=this.callbacks.getThread(),Q=D9(A,"assistant");if(Q){let $=D9(A,"user"),B=new Map;if($){for(let D of $.content)if(D.type==="tool_result")B.set(D.toolUseID,D.run)}for(let D of Q.content)if(D.type==="tool_use"&&l5(D)){let J=B.get(D.id);if(!(J?f3(J.status):!1))this.cancelledToolUses.add(D.id)}}}cancelUnstartedTools(A){let Q=this.callbacks.getThread(),$=rF(Q),B=Q.messages.findLastIndex((J)=>U20(J)),D=B===-1?Q.messages:Q.messages.slice(B+1);for(let J of D){if(J.role!=="assistant")continue;for(let F of J.content)if(F.type==="tool_use"&&l5(F)){let Y=$.get(F.id);if(Y?.run.status==="blocked-on-user"&&A==="system:disposed")continue;if(!Y||Y.run.status==="blocked-on-user")this.callbacks.updateThread({type:"tool:data",toolUse:F.id,data:{status:"cancelled",reason:A}})}}}async cancelInProgressTools(A){for(let[Q,$]of this.runningTools)$.abort.abort(),$.subscription?.unsubscribe(),await this.cancelTool(Q,A);this.runningTools.clear()}findToolUseById(A){let Q=this.callbacks.getThread(),$=D9(Q,"assistant");if(!$)return;for(let B of $.content)if(B.type==="tool_use"&&B.id===A)return B;return}isDangerousToResume(A){return A===e6||A===fd||A===i7||A===T8||A===UT}abortToolOp(A){let Q=this.runningTools.get(A);if(Q)Q.abort.abort(),this.runningTools.delete(A)}abortAllTools(){for(let[A,Q]of this.runningTools){let $=this.toolMessages.get(A);if($){try{$.next({type:"stop-command"}),$.complete()}catch(B){P.warn("Failed to send stop-command during disposal",{toolId:A,error:B})}this.toolMessages.delete(A)}Q.abort.abort()}this.runningTools.clear()}}var bO4=o(()=>{P1();$Y();p0();h4();WH();sa0();a4()});function hO4(A){let Q=[],$=/@((?:[^\s@\\,;]|\\.)+)/g,B;while((B=$.exec(A))!==null){let D=B[1],J=C33(D).replace(/[.,;:!?)}\]]+$/,"");Q.push(J)}return{paths:Q}}function C33(A){if(A.match(/^[A-Za-z]:[\\]/))return A.replace(/\\(.)/g,(Q,$)=>{if($===" "||$==="("||$===")"||$==="["||$==="]"||$==="?"||$==="*")return $;return Q});return A.replace(/\\(.)/g,"$1")}function GF0(A){if(!A.connected)return;return mO4(A)}async function gO4(){if(!await o5.isConnected())return;let Q=await k1(o5.status);return mO4(Q)}function mO4(A){let Q=A.selections?.[0],$=j20(Q),B=$&&Q?{line:Q.range.startLine+1,column:Q.range.startCharacter}:void 0;return{currentlyVisibleFiles:A.visibleFiles??[],activeEditor:A.openFile,cursorLocation:B,cursorLocationLine:void 0,selectionRange:!$&&Q?{start:{line:Q?.range.startLine+1,column:Q?.range.startCharacter},end:{line:Q?.range.endLine+1,column:Q?.range.endCharacter}}:void 0}}var VF0=o(()=>{P1();wK();QL()});function dO4(A){for(let Q=A.length-1;Q>=0;Q--){let $=A[Q];if($?.role==="user"&&$.userState!==void 0)return $.userState}return}async function pO4(A,{configService:Q,previousUserState:$}){let B={sentAt:Date.now()},D=w2(A.content),{paths:J}=hO4(D),F=await k1(Q.workspaceRoot);if(!F)return{message:{role:"user",messageId:0,content:A.content,source:A.source,fileMentions:void 0,userState:void 0,agentMode:A.agentMode,meta:B}};let Y=await K$0(J,{searchPaths:[F],shouldIncludeImages:!A.agentMode||cd(A.agentMode)}),E;if(Y?.files&&Y.files.length>0){let G=new Set,V=[];for(let K of Y.files){let I=GA(K.uri),z=await KY(I,F,null,G,void 0);for(let W of z){if(!V.some((H)=>H.uri===W.uri))V.push(W);G.add(W.uri)}}if(V.length>0)E=V}let Z={...await gO4()??qE4},U=$!==void 0&&iF(Z,$)?void 0:Z;return{message:{role:"user",messageId:0,content:Y?.imageBlocks?.length?[...A.content,...Y.imageBlocks]:A.content,source:A.source,fileMentions:Y,userState:U,agentMode:A.agentMode,discoveredGuidanceFiles:E,meta:B}}}var cO4=o(()=>{Q4();P1();M5();y5();aK();a4();tH();VF0()});function M33(A,Q){let $=D9(A,"assistant");if(!$)return{updatedThread:A,uninvoked:[]};let B=$.content.filter((F)=>F.type==="tool_use"),D=Q.items.filter((F)=>!Q.wasInvoked(B,F));if(D.length===0)return{updatedThread:A,uninvoked:[]};return{updatedThread:h8(A,(F)=>{let Y=F.messages.findLast((E)=>E.role==="assistant");if(Y&&Y.role==="assistant"){for(let E of D){let Z=oF();Y.content.push({type:"tool_use",complete:!0,id:Z,name:Q.toolName,input:Q.toToolInput(E)})}if(Y.state.type==="complete"&&Y.state.stopReason==="end_turn")Y.state={...Y.state,stopReason:"tool_use"}}F.v++}),uninvoked:D}}class aS{deps;threadID;async getConfig(A){return k1(this.deps.configService.config,A)}setupSettingsChangeHandlers(){this.setupPermissionsChangeHandler()}setupEphemeralErrorLogging(){this.ephemeralError.pipe(BK(this.disposed$)).subscribe((A)=>{if(A)P.error("ephemeral error",{error:A})})}setupPermissionsChangeHandler(){this.deps.configService.config.pipe(N1((A)=>({permissions:KK(A.settings?.permissions),dangerouslyAllowAll:A.settings?.dangerouslyAllowAll??!1})),T4((A,Q)=>A.dangerouslyAllowAll===Q.dangerouslyAllowAll&&A.permissions===Q.permissions),Qe1(1),BK(this.disposed$)).subscribe(()=>{this.reevaluateBlockedTools()})}reevaluateBlockedTools(){if(this.isDisposed)return;for(let A=this.thread.messages.length-1;A>=0;A--){let Q=this.thread.messages[A];if(!Q||Q.role!=="user")continue;let $=!1;for(let B of Q.content)if(B.type==="tool_result"&&B.run?.status==="blocked-on-user"&&B.toolUseID)$=!0,this.checkAndApproveBlockedTool(B.toolUseID);if(!$)break}}async checkAndApproveBlockedTool(A){try{let Q=E7(this.thread,A);if(!Q){P.warn("Tool use block not found for blocked tool",{toolUseID:A});return}let $=await N80(Q.name,Q.input??{},{configService:this.deps.configService},this.thread.mainThreadID?"subagent":"thread",this.threadID,A);if($.permitted)P.info("Auto-approving previously blocked tool due to permission change",{toolName:Q.name,toolUseID:A,threadID:this.threadID}),this.handle({type:"user:tool-input",toolUse:A,value:{accepted:!0}});else P.debug("Tool remains blocked after permission change",{toolName:Q.name,toolUseID:A,reason:$.reason})}catch(Q){P.warn("Failed to re-evaluate blocked tool",{error:Q,toolUseID:A})}}ops={tools:{},toolMessages:{},inference:null,titleGeneration:null};_state=new a1("initial");state=this._state.pipe(T4(),t6({shouldCountRefs:!0}));handleMutex=new XJ;ephemeralError=new a1(void 0);ephemeralErrorRetryAttempt=0;retryCountdownSeconds=new a1(void 0);retryTimer=null;retrySession=0;_inferenceState=new a1("idle");_turnStartTime=new a1(void 0);_turnElapsedMs=new a1(void 0);fileChanges=new a1({files:[]});get inferenceState(){return this._inferenceState.getValue()}toolCallUpdates=new p4;discoveredGuidanceFileURIs=new Set;fileChangeTracker;cachedFileChanges=[];disposed$=new p4;isDisposed=!1;shouldContinueAfterRejection=!1;_pendingSkills=new a1([]);handoffState=new a1(void 0);pendingSkills=this._pendingSkills.pipe(T4(),t6({shouldCountRefs:!0}));_awaitingSkillInvocation=new a1([]);toolOrchestrator;currentAgentSpan=null;reasoningEffortOverride;currentSpan=null;traceStore;constructor(A,Q){this.deps=A;this.threadID=Q;this.fileChangeTracker=XF0({fileChangeTrackerStorage:this.deps.fileChangeTrackerStorage},Q),this.traceStore={startTrace:($)=>{this.updateThread({type:"trace:start",span:$})},recordTraceEvent:($,B)=>{this.updateThread({type:"trace:event",span:$,event:B})},recordTraceAttributes:($,B)=>{this.updateThread({type:"trace:attributes",span:$,attributes:B})},endTrace:($)=>{this.updateThread({type:"trace:end",span:$})}},this.toolOrchestrator=new ta0(Q,A.toolService,this.createOrchestratorCallbacks())}createTracer(A){return Fb0(this.traceStore,A)}getPluginTracer(){let A=this.currentSpan?.id??this.currentAgentSpan?.span;if(!A)return;return this.createTracer(A)}createOrchestratorCallbacks(){return{getThread:()=>this.thread,updateThread:(A)=>this.updateThread(A),handle:(A,Q)=>this.handle(A,Q),getToolRunEnvironment:(A,Q)=>this.getToolRunEnvironment(A,Q),getHooks:async()=>(await this.getConfig()).settings?.hooks,getConfig:()=>this.getConfig(),updateFileChanges:()=>this.updateFileChanges(),isDisposed:()=>this.isDisposed,getDisposed$:()=>this.disposed$,onSkillToolComplete:(A)=>this.onSkillToolComplete(A),applyHookResult:(A)=>Promise.resolve(nS(this,A)),applyPostHookResult:(A,Q)=>Promise.resolve(nS(this,A,Q)),requestPluginToolCall:this.deps.pluginService?(A)=>this.deps.pluginService.event.toolCall(A,this.getPluginTracer()):void 0,requestPluginToolResult:this.deps.pluginService?(A)=>this.deps.pluginService.event.toolResult(A,this.getPluginTracer()):void 0}}async getToolRunEnvironment(A,Q){let $=await this.getWorkspaceRoot(Q),B=WT(this.thread),D=E7(this.thread,A);return{...this.deps,dir:$,tool:D?.name??"",thread:this.thread,config:await this.getConfig(Q),fileChangeTracker:this.fileChangeTracker,getAllTrackedChanges:this.getAllTrackedChanges.bind(this),toolUseID:A,todos:B,toolMessages:new h0(()=>{}),threadEnvironment:this.thread.env?.initial??await this.deps.getThreadEnvironment(),handleThreadDelta:this.handle.bind(this),agentMode:await this.getSelectedAgentMode(),discoveredGuidanceFileURIs:this.discoveredGuidanceFileURIs}}onSkillToolComplete(A){let Q=A.input;this.thread=h8(this.thread,($)=>{if(!$.activatedSkills)$.activatedSkills=[];if(!$.activatedSkills.some((B)=>B.name===Q.name))$.activatedSkills.push({name:Q.name,arguments:Q.arguments})})}status=this.state.pipe(y4((A)=>A==="active"?jA(this._inferenceState.pipe(T4()),this.fileChanges.pipe(T4()),this.ephemeralError,this.handoffState.pipe(T4()),this.retryCountdownSeconds.pipe(T4()),this._turnStartTime.pipe(T4()),this._turnElapsedMs.pipe(T4()),this.toolCallUpdates.pipe(HA(void 0))).pipe(N1(([Q,$,B,D,J,F,Y])=>({state:A,inferenceState:Q,fileChanges:$,ephemeralError:B?{message:B.message,stack:"stack"in B?B.stack:void 0,error:"error"in B&&B.error&&typeof B.error==="object"&&"error"in B.error?B.error.error:void 0,retryCountdownSeconds:J}:void 0,handoff:D,turnStartTime:F,turnElapsedMs:Y})),BK(this.disposed$)):h0.of({state:A})),t6({shouldCountRefs:!0}));threadReadWriter=null;get thread(){if(!this.threadReadWriter)throw Error(`thread read-writer not initialized for ThreadWorker: ${this.threadID}`);return this.threadReadWriter.read()}set thread(A){if(!this.threadReadWriter)throw Error(`thread read-writer not initialized for ThreadWorker: ${this.threadID}`);this.threadReadWriter.write(A),this.__testing__setThread(A)}updateThread(A){if(!this.threadReadWriter)throw Error(`thread read-writer not initialized for ThreadWorker: ${this.threadID}`);this.threadReadWriter.update(IE4(A,new Date)),this.__testing__setThread(this.threadReadWriter.read())}repairMissingToolResultsForInference(){let A=!1,Q=h8(this.thread,($)=>{for(let B=$.messages.length-1;B>=0;B--){let D=$.messages[B];if(D?.role!=="assistant")continue;if(!(D.state.type==="cancelled"||D.state.type==="complete"&&D.state.stopReason==="tool_use"))continue;if(D.content.some((V)=>V.type==="tool_use"&&!V.complete))continue;let Y=D.content.filter((V)=>V.type==="tool_use"&&V.complete);if(Y.length===0)continue;let E=$.messages[B+1];if(E?.role!=="user")continue;let Z=new Map,U=[];for(let V of E.content)if(V.type==="tool_result"&&Y.some((I)=>I.id===V.toolUseID))Z.set(V.toolUseID,V);else U.push(V);let X=!1,G=[];for(let V of Y){let K=Z.get(V.id);if(K)G.push(JA(K));else G.push(JA({type:"tool_result",toolUseID:V.id,run:{status:"cancelled",reason:"user:interrupted"}})),X=!0,A=!0}if(X)E.content=[...G,...U]}if(A)$.v++});if(A)this.thread=Q}async acquireThread(){if(!this.threadReadWriter)this.threadReadWriter=await this.deps.threadService.exclusiveSyncReadWriter(this.threadID),this._state.next("active")}__testing__setThread(A){}__testing__getDeps(){return this.deps}async resume(){if(this.resumed)return;if(this.resumed=!0,this.handleCalled)throw Error("cannot call ThreadWorker.resume after ThreadWorker.handle");await this.acquireThread(),await this.restoreFileChangesFromBackups();let A=this.thread.messages.at(-1);if(A?.role==="assistant"&&(A.state.type==="streaming"||A.state.type==="cancelled"&&A.content.length===0))this.updateThread({type:"thread:truncate",fromIndex:this.thread.messages.length-1});if(this.triggerTitleGeneration(),!this.shouldResumeFromLastMessage(A))return;await this.toolOrchestrator.onResume(),this.setupSettingsChangeHandlers(),this.setupEphemeralErrorLogging(),this.replayLastCompleteMessage()}resumed=!1;shouldResumeFromLastMessage(A){if(j14(A)||R14(A)&&!this.shouldContinueAfterRejection||U20(A))return this._inferenceState.next("cancelled"),!1;return!0}replayLastCompleteMessage(){let A=this.thread.messages.findLastIndex(($)=>$.role==="user"?P14($):$.role==="assistant"&&$.state.type==="complete");if(A===-1){if(this.thread.messages.length!==0)throw Error(`(bug) invalid thread: ${this.threadID}`);return}let Q=this.thread.messages[A];switch(Q.role){case"user":if(!Q.interrupted)this.onThreadDelta({type:"user:message",message:Q});break;case"assistant":this.onThreadDelta({type:"assistant:message",message:Q});break}}async handle(A,Q){let $=A.type==="user:message"&&A.index!==void 0?A.index:void 0,B=!1;await this.handleMutex.acquire();try{B=await this.innerHandle(A,Q,{deferUserMessageInference:$!==void 0})}finally{this.handleMutex.release()}if($!==void 0&&B){await this.performMessageEditCleanup();let D=this.thread.messages[$];if(D?.role==="user")this.beginInferenceForUserMessage(D)}}async innerHandle(A,Q,$={}){if(this.isDisposed)return P.debug(`Skipping ${A.type} - worker disposed.`,{name:"handle queue",threadID:this.threadID}),!1;if(Q?.aborted)return P.debug(`Skipping ${A.type} - signal aborted.`,{name:"handle queue",threadID:this.threadID}),!1;if(await this.resume(),this.handleCalled=!0,await this.acquireThread(),A.type==="pending-skills"){let J=this._pendingSkills.getValue();return this._pendingSkills.next([...J,...A.skills]),P.info("Pending skills set for injection",{threadID:this.threadID,skillNames:A.skills.map((F)=>F.name)}),!0}let B=A,D=[];if(A.type==="user:message"){let J=dO4(this.thread.messages),F=await pO4(A.message,{configService:this.deps.configService,previousUserState:J});if(D=this._pendingSkills.getValue(),D.length>0)P.info("Pending skills will be injected as info message",{threadID:this.threadID,skillNames:D.map((Y)=>Y.name)}),this._pendingSkills.next([]);B=h8(A,(Y)=>{Y.message=JA(F.message),Q?.throwIfAborted()})}if(B.type==="assistant:message"||B.type==="assistant:message-update")B=this.addNormalizedInputToToolUses(B);try{if(this.ephemeralError.getValue()!==void 0)this.ephemeralError.next(void 0);let J=this.thread;if(this.updateThread(B),this.onThreadDelta(B,J,{deferUserMessageInference:$.deferUserMessageInference}),D.length>0)await this.injectPendingSkills(D,Q);return!0}catch(J){if(!g2(J))P.error("Ephemeral error during handle processing",J,{name:"ThreadWorker",threadID:this.threadID}),this.ephemeralError.next(J instanceof Error?J:Error(String(J)));else P.debug(`AbortError caught during handle processing for ${B.type}.`,{name:"handle queue",threadID:this.threadID});return!1}}handleCalled=!1;addNormalizedInputToToolUses(A){let Q=this.thread.agentMode;if(!A.message.content.some((B)=>B.type==="tool_use"))return A;return h8(A,(B)=>{for(let D of B.message.content)if(D.type==="tool_use"){if(!D.name){P.warn("Skipping tool_use normalization due to missing name",{threadID:this.threadID});continue}let J=this.deps.toolService.normalizeToolName(D.name);if(J!==D.name)D.normalizedName=J;if(D.input&&typeof D.input==="object"){let Y=this.deps.toolService.normalizeToolArgs(D.name,D.input,Q);if(JSON.stringify(Y)!==JSON.stringify(D.input))D.normalizedInput=Y}if((J!==D.name?J:D.name)===UT&&!D.metadata?.handoffThreadID)D.metadata={...D.metadata,handoffThreadID:B9()}}})}onThreadDelta(A,Q,$={}){switch(A.type){case"user:message":{if(this.resetRetryAttempts(),this._turnStartTime.next(Date.now()),this._turnElapsedMs.next(void 0),!$.deferUserMessageInference)this.beginInferenceForLatestUserMessage();break}case"user:message-queue:dequeue":{let B=this.thread.messages.at(-1);if(!B)break;if(B.role!=="user")break;this._turnStartTime.next(Date.now()),this._turnElapsedMs.next(void 0);let D=B.messageId??0,J=w2(B.content);this.startAgentSpan(D),this.beginInference({agentStart:{messageId:D,messageText:J}});break}case"user:tool-input":{this.toolOrchestrator.userProvideInput(A.toolUse,A.value).catch((B)=>{P.error("userProvideInput failed",{name:"ThreadWorker.handleDelta",threadID:this.threadID,toolUse:A.toolUse,error:B instanceof Error?B.message:String(B)})});break}case"tool:data":{if(this.toolOrchestrator.isCancelled(A.toolUse)){let D=rF(this.thread).get(A.toolUse)?.run,J=D?VL(D):void 0;this.updateThread({type:"tool:data",toolUse:A.toolUse,data:{status:"cancelled",reason:"user:interrupted",progress:J}});return}let B=E7(this.thread,A.toolUse);if(A.data.status==="done"&&B?.name===ET){let D=A.data.result;if("task"in D&&D.nextTask){let J=zJ(this.thread),F=this.deps.internalHooks?.onTaskCompleted?.({thread:this.thread,completedTask:D.task,nextTask:D.nextTask,usage:J?{totalInputTokens:J.totalInputTokens,maxInputTokens:J.maxInputTokens}:void 0});if(F)nS(this,F)}}if(f3(A.data.status))this.toolOrchestrator.clearCancelled(A.toolUse),this.toolOrchestrator.resolveToolCompletion(A.toolUse,A.data.status==="done",Error(`Tool ${A.data.status}: ${A.toolUse}`));if(B){let D=L33(this.thread,A.toolUse,this.shouldContinueAfterRejection);P.debug(`updated tool_result${D?" and running inference because all tools completed":""}`,{name:`handleThreadDelta(${A.type}, ${A.toolUse}, ${A.data.status})`,threadID:this.threadID});let J=this.shouldContinueAfterRejection||this._inferenceState.getValue()!=="cancelled";if(D&&J)this.beginInference()}this.toolCallUpdates.next();break}case"assistant:message":{if(A.message.state.type==="complete"&&A.message.state.stopReason==="tool_use"){let D=this.thread.messages.at(-1);(this.currentAgentSpan?this.createTracer(this.currentAgentSpan.span):LX).startActiveSpan("tools",{context:{messageId:D?.messageId}},async()=>{await this.toolOrchestrator.onAssistantMessageComplete(A.message)}).catch((F)=>{P.error("onAssistantMessageComplete failed",{name:"ThreadWorker.handleDelta",threadID:this.threadID,messageState:A.message.state.type,error:F instanceof Error?F.message:String(F)})})}break}case"assistant:message-update":break;case"user:message-queue:enqueue":{let B=this._inferenceState.getValue();if(Li0(this.thread,B)!=="tool-running"){if(B==="cancelled"){this.handle({type:"user:message-queue:dequeue"});break}else if(B==="idle"){let J=this.thread.messages.at(-1);if(J?.role==="assistant"){if(J.state.type==="cancelled"||J.state.type==="error"){this.handle({type:"user:message-queue:dequeue"});break}if(J.state.type==="complete"&&J.state.stopReason!=="tool_use"){this.handle({type:"user:message-queue:dequeue"});break}}else if(J?.role==="info"){this.handle({type:"user:message-queue:dequeue"});break}}}break}case"info:manual-bash-invocation":{this.handle({type:"user:message-queue:dequeue"});break}case"cancelled":{if(this.resetRetryAttempts(),this.currentAgentSpan&&this.currentAgentSpan.messageId!==void 0){let B=this.currentAgentSpan.messageId,D=this.createTracer(this.currentAgentSpan.span);this.stopAgentSpan(this.currentAgentSpan.span),this.deps.pluginService.event.agentEnd({thread:{id:this.threadID},message:this.getMessageText(B),id:B,status:"cancelled",messages:w70(this.getMessagesSince(B))},D).then((J)=>this.handleAgentEndResult(J)).catch((J)=>P.debug("Failed to emit agent.end",{error:J}))}break}case"thread:truncate":{if(this.toolOrchestrator.cancelAll("system:edited").catch((B)=>{P.error("Failed to cancel tools on truncate",B,{name:"ThreadWorker",threadID:this.threadID})}),Q)this.cleanupFileChanges(A.fromIndex).catch((B)=>{P.error("Failed to cleanup file changes on truncate",B,{name:"ThreadWorker",threadID:this.threadID})});break}case"inference:completed":{this.resetRetryAttempts();let B=A.model?.includes("gpt-5")||A.model?.includes("codex"),D=!A.usage||A.usage.totalInputTokens===0||A.usage.outputTokens===0;if(B&&D)P.getChild("thread-worker").warn("Missing token counts in deep mode inference",{threadID:this.threadID,model:A.model,hasUsage:!!A.usage,inputTokens:A.usage?.inputTokens,outputTokens:A.usage?.outputTokens,totalInputTokens:A.usage?.totalInputTokens,cacheReadInputTokens:A.usage?.cacheReadInputTokens,cacheCreationInputTokens:A.usage?.cacheCreationInputTokens});let J=D9(this.thread,"assistant");if(J&&J.state.type==="complete"&&J.state.stopReason==="refusal"){this.ephemeralError.next(Error("The model refused to respond to this request. Please retry with a different prompt."));break}this.checkAndAppendAwaitedSkills();let F=D9(this.thread,"assistant"),Y=F?.state.type==="complete"&&F.state.stopReason==="tool_use";if(F&&Y){let Z=this.currentAgentSpan?this.createTracer(this.currentAgentSpan.span):LX,U=F.messageId;Z.startActiveSpan("tools",{context:{messageId:U}},async()=>{await this.toolOrchestrator.onAssistantMessageComplete(F)}).catch((X)=>{P.error("onAssistantMessageComplete failed after inference",{name:"ThreadWorker.handleDelta",threadID:this.threadID,messageState:F.state.type,error:X instanceof Error?X.message:String(X)})})}if(F&&F.state.type==="complete"&&F.state.stopReason==="end_turn"){let Z=this._turnStartTime.getValue();if(Z!==void 0){let U=Date.now()-Z;this._turnElapsedMs.next(U),this.thread=h8(this.thread,(X)=>{let G=X.messages.findLast((V)=>V.role==="assistant");if(G&&G.role==="assistant")G.turnElapsedMs=U;X.v++})}if(this._turnStartTime.next(void 0),this.thread.queuedMessages&&this.thread.queuedMessages.length>0)this.handle({type:"user:message-queue:dequeue"});else{nS(this,yO4(this.deps.internalHooks?.onAssistantTurnEnd,{thread:this.thread}));let U=zJ(this.thread);if(U&&this.deps.internalHooks?.onInferenceCompleted){let X=this.deps.internalHooks.onInferenceCompleted({thread:this.thread,usage:{totalInputTokens:U.totalInputTokens,maxInputTokens:U.maxInputTokens},isIdle:!0});nS(this,X)}if(this.currentAgentSpan&&this.currentAgentSpan.messageId!==void 0){let X=this.currentAgentSpan.messageId,G=this.createTracer(this.currentAgentSpan.span);this.stopAgentSpan(this.currentAgentSpan.span),this.deps.pluginService.event.agentEnd({thread:{id:this.threadID},message:this.getMessageText(X),id:X,status:"done",messages:w70(this.getMessagesSince(X))},G).then((V)=>this.handleAgentEndResult(V)).catch((V)=>P.debug("Failed to emit agent.end",{error:V}))}}}break}}}getMessageText(A){let Q=this.thread.messages.find(($)=>$.messageId===A);if(Q)return w2(Q.content);return""}getMessagesSince(A){let Q=this.thread.messages.findIndex(($)=>$.messageId===A);if(Q===-1)return[];return this.thread.messages.slice(Q)}startAgentSpan(A){let Q=Jb0();this.currentAgentSpan={span:Q,messageId:A},this.updateThread({type:"trace:start",span:{name:"agent",id:Q,startTime:new Date().toISOString(),context:{messageId:A}}})}stopAgentSpan(A){if(this.updateThread({type:"trace:end",span:{name:"agent",id:A,endTime:new Date().toISOString()}}),this.currentAgentSpan?.span===A)this.currentAgentSpan=null}handleAgentEndResult(A){if(A.action!=="continue"||!A.userMessage)return;this.handle({type:"user:message",message:{content:[{type:"text",text:A.userMessage}]}}).catch((Q)=>{P.debug("Failed to handle plugin agent.end continue",{error:Q})})}triggerTitleGeneration(){if(this.thread.mainThreadID!==void 0||this.thread.title)return;this.ops.titleGeneration?.abort(),this.ops.titleGeneration=new AbortController;let A=this.ops.titleGeneration.signal;this.getConfig(A).then((Q)=>{if(A.aborted)return;let $=Q.settings?.["agent.skipTitleGenerationIfMessageContains"],B=Array.isArray($)?$.filter((J)=>typeof J==="string"):[],D=this.thread.messages.find((J)=>{if(J.role!=="user")return!1;let F=w2(J.content);if(!F)return!1;if(B.length===0)return!0;return!B.some((Y)=>F.includes(Y))});if(P.debug("Checking for message to generate title for",{skipPatterns:B,rawSkipPatterns:$,hasFirstEligibleMessage:D!==void 0,firstEligibleMessageId:D?.messageId}),D)this.deps.generateThreadTitle(D,this.thread.id,this.deps.configService,A).then(({title:J,usage:F})=>{if(A.aborted||this.isDisposed)return;if(J!==void 0&&this.thread.title!==J)this.updateThread({type:"title",value:J,usage:F})}).catch((J)=>{if(!g2(J))P.error("generateThreadTitle error",J,{name:"ThreadWorker",threadID:this.threadID})})}).catch((Q)=>{if(!g2(Q))P.error("ThreadWorker title generation config error",Q)})}setReasoningEffortOverride(A){if(!this.threadReadWriter){this.reasoningEffortOverride=A;return}let Q=this.threadReadWriter.read();if(A5(Q)>0)return;if(A===void 0){this.reasoningEffortOverride=void 0;return}if(Q.agentMode===void 0||!C2(Q.agentMode,A)){this.reasoningEffortOverride=void 0;return}if(this.reasoningEffortOverride=A,Q.reasoningEffort===A)return;this.handle({type:"reasoning-effort",effort:A}).catch(($)=>{P.debug("Failed to persist thread reasoning effort",{error:$,threadID:this.threadID})})}async getWorkspaceRoot(A){let Q=await k1(this.deps.configService.workspaceRoot,A);if(Q)return Q;let $=this.thread.env?.initial?.trees?.find((B)=>B.uri!==void 0)?.uri;return $?A8($):null}beginInferenceForLatestUserMessage(){let A=this.thread.messages.at(-1);if(A?.role!=="user")return;this.beginInferenceForUserMessage(A)}beginInferenceForUserMessage(A){let Q=A.messageId??0,$=w2(A.content);this.startAgentSpan(Q),this.beginInference({agentStart:{messageId:Q,messageText:$}})}beginInference(A){this.runInferenceAndUpdateThread(A).catch((Q)=>{if(this.isDisposed||g2(Q)||Y80(Q))return;P.error("Failed to run inference",Q,{name:"ThreadWorker.runInferenceAndUpdateThread",threadID:this.threadID}),this.ephemeralError.next(Q instanceof Error?Q:Error(String(Q)))})}async runInferenceAndUpdateThread(A){this.abortInferenceOperation();let Q=new AbortController;if(this.ops.inference=Q,await this.deps.pluginService.event.sessionStart({thread:{id:this.threadID}}),Q.signal.aborted)return;if(A?.agentStart){let{messageId:$,messageText:B}=A.agentStart;try{let D=await this.deps.pluginService.event.agentStart({thread:{id:this.threadID},message:B,id:$},this.currentAgentSpan?this.createTracer(this.currentAgentSpan.span):void 0);if(Q.signal.aborted)return;if(D.message)this.updateThread({type:"user:message:append-content",messageId:$,content:[{type:"text",text:D.message.content}]})}catch(D){P.debug("Failed to emit agent.start",{error:D})}}if(Q.signal.aborted)return;return this.doRunInferenceSetup(Q)}async doRunInferenceSetup(A){if(P.debug("runInferenceAndUpdateThread: begin",{threadID:this.threadID,inferenceState:this._inferenceState.getValue(),messageCount:this.thread.messages.length}),A.signal.aborted||this.ops.inference!==A)return;if(this._inferenceState.getValue()==="cancelled")this._inferenceState.next("idle");let Q=this.currentAgentSpan?.span;if(await this.toolOrchestrator.onNewUserMessage(),A.signal.aborted||this.ops.inference!==A)return;await(this.currentAgentSpan?this.createTracer(this.currentAgentSpan.span):LX).startActiveSpan("inference",{context:{messageId:this.currentAgentSpan?.messageId}},()=>this.doRunInferenceAndUpdateThread(A,Q))}async doRunInferenceAndUpdateThread(A,Q){try{await this.doRunInferenceAndUpdateThreadInner(A,Q)}catch($){if(g2($)||Y80($))return;throw $}}async doRunInferenceAndUpdateThreadInner(A,Q){let $=zJ(this.thread);if($&&$.totalInputTokens>=$.maxInputTokens){let z=Error("Context limit reached");this.ephemeralError.next(z);return}let B=this.thread.messages.at(-1);if(this.thread.mainThreadID===void 0&&B?.role==="user"&&this.thread.messages.filter((z)=>z.role==="user").length===1&&this.deps.getThreadEnvironment)try{let z=await this.deps.getThreadEnvironment(A.signal);if(A.signal.aborted||this.ops.inference!==A)return;this.updateThread({type:"environment",env:{initial:{...this.thread.env?.initial,...z}}})}catch(z){if(A.signal.aborted||this.ops.inference!==A||g2(z))return;P.error("Failed to initialize thread environment",z,{threadID:this.threadID})}this.triggerTitleGeneration(),this.repairMissingToolResultsForInference();let J=await this.getConfig(),{model:F,agentMode:Y}=XZ(J.settings,this.thread),E=this.thread.messages.at(-1)?.messageId;P.debug("runInferenceAndUpdateThread: starting inference",{threadID:this.threadID,lastUserMessageId:E,selectedModel:F,agentMode:Y});let Z=this.deps.getServerStatus?await k1(this.deps.getServerStatus().pipe(i3((z)=>z!=="pending")),A.signal):void 0,U=Z&&AA(Z)?Z.user.email:void 0;if(!tM(Y,U))throw Error(`Agent mode '${Y}' is only available for internal users`);let X={toolService:this.deps.toolService,configService:this.deps.configService,skillService:this.deps.skillService,getThreadEnvironment:this.deps.getThreadEnvironment,getEnvironmentData:this.deps.getEnvironmentData,serverStatus:Z},G=await _X({configService:this.deps.configService,threadService:this.deps.threadService},this.thread,A.signal),V,K=0,I=Date.now();try{let z=K20({providerModel:F,serverStatus:Z}),{provider:W,model:H}=rB(z),q=wO4(W,H),{systemPrompt:N,tools:w}=await $q(X,this.thread,{enableTask:!0,enableOracle:!0,enableChart:!1},{model:H,provider:W,agentMode:Y??"smart"},G,A.signal),O=this.thread.reasoningEffort!==void 0&&C2(Y,this.thread.reasoningEffort)?this.thread.reasoningEffort:void 0,L=O===void 0&&this.reasoningEffortOverride!==void 0&&C2(Y,this.reasoningEffortOverride)?this.reasoningEffortOverride:void 0,j=O??L??FF0(z,J.settings,Y),k=q.stream({model:H,agentMode:Y,thread:this.thread,systemPrompt:N,tools:w,configService:this.deps.configService,serverStatus:Z,signal:A.signal,reasoningEffort:j});this._inferenceState.next("running"),I=Date.now(),P.debug("ThreadWorker inference stream started",{threadID:this.threadID,lastUserMessageId:E,selectedModel:z,agentMode:Y});for await(let _ of k){if(A.signal.aborted)return;K++,V=_,await this.handle({type:"assistant:message-update",message:_},A.signal)}if(A.signal.aborted)return;if(P.debug("ThreadWorker inference stream finished",{threadID:this.threadID,streamEventCount:K,durationMs:Date.now()-I,lastMessageState:V?.state.type,lastMessageId:V?.messageId}),V){let _=V.state.type==="streaming",f=V.content.some((h)=>h.type==="tool_use"&&h.complete&&Object.keys(h.input??{}).length===0);if(_||f)P.warn("Stream ended with incomplete message",{name:"ThreadWorker.runInference",threadID:this.threadID,streamEventCount:K,durationMs:Date.now()-I,messageState:V.state.type,stopReason:V.state.type==="complete"?V.state.stopReason:void 0,contentBlocks:V.content.map((h)=>({type:h.type,...h.type==="tool_use"?{name:h.name,complete:h.complete,inputKeys:Object.keys(h.input??{})}:{},...h.type==="text"?{textLength:h.text.length}:{}}))})}await this.handle({type:"inference:completed",model:V?.usage?.model??F,usage:V?.usage},A.signal)}catch(z){if(P.debug("ThreadWorker inference stream error",{threadID:this.threadID,error:z instanceof Error?z.message:String(z),errorName:z instanceof Error?z.name:void 0,streamEventCount:K,durationMs:Date.now()-I,lastMessageState:V?.state.type,lastMessageId:V?.messageId}),!(g2(z)||Y80(z))){let W=z instanceof Error?z:Error(String(z));if(AG({message:W.message})){this.ephemeralError.next(W);return}let H="status"in W&&typeof W.status==="number"?W.status:void 0;if(IS({message:W.message,status:H})){let q=this.getRetryDelaySeconds();if(q!==void 0)this.startRetryCountdown(q)}this.ephemeralError.next(W)}if(V&&V.messageId){let W=await this.deps.pluginService.event.agentEnd({thread:{id:this.threadID},message:w2(V.content),id:V.messageId,status:"error",messages:w70(this.getMessagesSince(V.messageId))},Q?this.createTracer(Q):void 0);if(Q)this.stopAgentSpan(Q);this.handleAgentEndResult(W)}else if(Q)this.stopAgentSpan(Q);return}finally{if(this.ops.inference===A)this.ops.inference=null,this._inferenceState.next("idle")}}async findAndCancelToolRun(A,Q){this.cancelInference(),await this.toolOrchestrator.findAndCancelToolRun(A,Q)}async cancelToolOnly(A,Q){await this.toolOrchestrator.cancelToolOnly(A,Q)}invokeBashTool(A,Q,$){return new h0((B)=>{let D,J,F,E=((U)=>{return QY(U,()=>{if(P.warn("Manual bash abort -> unsubscribe",{threadID:this.threadID}),F?.unsubscribe(),J?.unsubscribe(),B?.complete(),D)this.handleManualBashInvocation(A,{status:"cancelled",progress:VL(D)},$)})})(Q);return(async()=>{try{if(Q.aborted){B.error(Error("Operation was aborted"));return}let U=await this.getWorkspaceRoot(Q),X=await this.getConfig(Q);if(this.isDisposed){B.complete();return}let G={...this.deps,dir:U,tool:e6,thread:this.thread,config:X,fileChangeTracker:this.fileChangeTracker,getAllTrackedChanges:this.getAllTrackedChanges.bind(this),toolUseID:oF(),todos:[],threadEnvironment:this.thread.env?.initial??await this.deps.getThreadEnvironment(),handleThreadDelta:this.handle.bind(this),discoveredGuidanceFileURIs:this.discoveredGuidanceFileURIs,userInitiated:!0};J=this.deps.toolService.invokeTool(e6,{args:A,userInput:{accepted:!0}},G).subscribe({next:(V)=>{D=V,B.next(V)},error:(V)=>{B.error(V)},complete:()=>{if(D)this.handleManualBashInvocation(A,D,$);B.complete()}}),F=this.disposed$.subscribe(()=>{E(),J?.unsubscribe(),B?.complete()})}catch(U){B.error(U)}})(),()=>{E(),J?.unsubscribe(),F?.unsubscribe()}})}async handleManualBashInvocation(A,Q,$){await this.handle({type:"info:manual-bash-invocation",args:A,toolRun:Q,hidden:$})}async cleanupThreadBackups(A){try{await this.fileChangeTracker.cleanupBackups(),P.debug(`Cleaned up backup files for thread ${A}`,{threadID:A})}catch(Q){P.error("Error cleaning up thread backups",Q,{threadID:A})}}async cancel(){P.debug("cancel: aborting inference operation and tools"),this.cancelInference(),await this.toolOrchestrator.cancelAll("user:cancelled"),await this.handle({type:"cancelled"},void 0)}cancelInference(){this.abortInferenceOperation(),this._inferenceState.next("cancelled"),this._turnStartTime.next(void 0),this._turnElapsedMs.next(void 0)}abortInferenceOperation(){if(this.ops.inference)this.ops.inference.abort(Error(SS0.USER_CANCELLED)),this.ops.inference=null}static BASE_RETRY_SECONDS=5;static MAX_RETRY_SECONDS=60;static MAX_AUTO_RETRIES=5;getRetryDelaySeconds(){if(this.ephemeralErrorRetryAttempt>=aS.MAX_AUTO_RETRIES)return;let A=aS.BASE_RETRY_SECONDS*2**this.ephemeralErrorRetryAttempt;return Math.min(A,aS.MAX_RETRY_SECONDS)}async retry(){if(P.debug("retry: retrying inference operation"),this.clearRetryCountdown(),this.ephemeralError.getValue()!==void 0)this.ephemeralErrorRetryAttempt++,this.ephemeralError.next(void 0);if(this.ops.inference)this.ops.inference.abort(),this.ops.inference=null;let A=this.thread.messages.at(-1);if(A?.role==="assistant"&&(A.state.type!=="complete"||A.state.stopReason==="refusal"))this.updateThread({type:"thread:truncate",fromIndex:this.thread.messages.length-1});this._inferenceState.next("idle"),await this.runInferenceAndUpdateThread()}resetRetryAttempts(){this.ephemeralErrorRetryAttempt=0}dismissEphemeralError(){this.clearRetryCountdown(),this.ephemeralError.next(void 0),this.ephemeralErrorRetryAttempt=0}clearRetryCountdown(){if(this.retrySession++,this.retryTimer!==null)clearInterval(this.retryTimer),this.retryTimer=null;this.retryCountdownSeconds.next(void 0)}startRetryCountdown(A){this.clearRetryCountdown();let Q=this.retrySession,$=Date.now()+A*1000;this.retryCountdownSeconds.next(A),this.retryTimer=setInterval(()=>{if(Q!==this.retrySession)return;let B=Math.max(0,Math.ceil(($-Date.now())/1000));if(B<=0)this.clearRetryCountdown(),this.retry().catch((D)=>{P.error("Auto-retry failed",{error:D})});else this.retryCountdownSeconds.next(B)},1000)}addPendingSkill(A){P.debug("addPendingSkill",{threadID:this.threadID,skillName:A.name});let Q=this._pendingSkills.getValue();if(!Q.some(($)=>$.name===A.name))this._pendingSkills.next([...Q,A])}removePendingSkill(A){P.debug("removePendingSkill",{threadID:this.threadID,skillName:A});let Q=this._pendingSkills.getValue();this._pendingSkills.next(Q.filter(($)=>$.name!==A))}clearPendingSkills(){P.debug("clearPendingSkills",{threadID:this.threadID}),this._pendingSkills.next([])}getPendingSkills(){return this._pendingSkills.getValue()}setTestEphemeralError(A){this.ephemeralError.next(A)}async restoreFileChangesFromBackups(){try{let A=await this.fileChangeTracker.restoreFromBackups();P.debug(`Restored ${A.totalBackups} backup files from disk`),await this.updateFileChanges()}catch(A){P.error("Error restoring file changes",A,{threadID:this.threadID})}}async revertFileChanges(A){await this.fileChangeTracker.revertAll(A),await this.updateFileChanges()}async getAllTrackedChanges(){return this.fileChangeTracker.getAllRecords()}async cleanupForkThreads(A=this.thread.messages.length){await this.acquireThread(),this.updateThread({type:"thread:truncate",fromIndex:A})}async getToolUsesToRevert(A=this.thread.messages.length){let Q=new Set;this.thread.messages.slice(0,A).forEach((D)=>{if(D.role==="user"){for(let J of D.content)if(J.type==="tool_result")Q.add(J.toolUseID)}else for(let J of D.content)if(J.type==="tool_use")Q.add(J.id)});let $=new Set,B=await this.fileChangeTracker.getAllRecords();for(let[D]of B.entries())if(!Q.has(D))$.add(D);return $}async getFilesAffectedByTruncation(A){let Q=await this.getToolUsesToRevert(A);return Q.size>0?this.fileChangeTracker.getFilesForToolUses(Q):[]}async cleanupFileChanges(A=this.thread.messages.length){let Q=await this.getToolUsesToRevert(A);if(Q.size===0)return;await this.fileChangeTracker.revertChanges(Q),await this.updateFileChanges()}async performMessageEditCleanup(){await this.toolOrchestrator.cancelAll("system:edited"),await this.cleanupFileChanges(),await this.cleanupForkThreads()}async updateFileChanges(){this.cachedFileChanges=await sF4(this.fileChangeTracker),this.fileChanges.next({files:this.cachedFileChanges})}async injectPendingSkills(A,Q){let $=A.map((B)=>B.name);P.info("Adding info message to prompt skill invocation",{threadID:this.threadID,skillNames:$}),this._awaitingSkillInvocation.next(A),this.thread=h8(this.thread,(B)=>{let D=B.nextMessageId??0;B.nextMessageId=D+1,B.messages.push({role:"info",messageId:D,content:[{type:"text",text:`You MUST call the ${n7} tool to load: ${$.join(", ")}. Do this immediately before responding.`}]}),B.v++})}checkAndAppendAwaitedSkills(){let A=this._awaitingSkillInvocation.getValue();if(A.length===0)return;this._awaitingSkillInvocation.next([]);let{updatedThread:Q,uninvoked:$}=M33(this.thread,{toolName:n7,items:A,wasInvoked:(B,D)=>B.some((J)=>J.name===n7&&J.input.name===D.name),toToolInput:(B)=>({name:B.name,arguments:B.arguments})});if($.length>0)P.info("Skills not invoked by model, appending tool_use blocks",{threadID:this.threadID,uninvokedSkills:$.map((B)=>B.name)}),this.thread=Q}async executeHandoff(A){P.info("Executing handoff",{threadID:this.threadID,goal:A}),this.handoffState.next({goal:A});try{let{threadWorkerService:Q}=await Promise.resolve().then(() => (sq(),iO4)),$={toolService:this.deps.toolService,configService:this.deps.configService,skillService:this.deps.skillService,getThreadEnvironment:this.deps.getThreadEnvironment,getEnvironmentData:this.deps.getEnvironmentData},{threadID:B}=await Q.handoff(this.deps,{threadID:this.threadID,goal:A,images:[],mode:"initial",agentMode:this.thread.agentMode,queuedMessages:this.thread.queuedMessages,clearQueuedMessages:!0,blockIndex:0,buildSystemPromptDeps:$});P.info("Handoff thread created and running in background",{fromThreadID:this.threadID,newThreadID:B,goal:A}),this.handoffState.next({goal:A,result:{newThreadID:B}})}catch(Q){P.error("Handoff failed",Q,{threadID:this.threadID,goal:A}),this.handoffState.next({goal:A,result:{error:Q instanceof Error?Q.message:String(Q)}})}}continueInferenceAfterRejection(A=!0){this.shouldContinueAfterRejection=A}getTurnStartTime(){return this._turnStartTime.getValue()}setTurnStartTime(A){this._turnStartTime.next(A)}async asyncDispose(){if(this.isDisposed)return;if(P.debug("ThreadWorker disposal starting",{name:"ThreadWorker.dispose",threadID:this.threadID,activeToolCount:this.toolOrchestrator.getRunningToolIds().length}),this.isDisposed=!0,await this.toolOrchestrator.cancelAll("system:disposed"),this.disposed$.next(),this.disposed$.complete(),this.clearRetryCountdown(),this._state.complete(),this.ephemeralError.complete(),this._inferenceState.complete(),this.fileChanges.complete(),this.toolCallUpdates.complete(),this.retryCountdownSeconds.complete(),this.toolOrchestrator.dispose(),this.ops.inference)this.ops.inference.abort(),this.ops.inference=null;if(this.ops.titleGeneration)this.ops.titleGeneration.abort(),this.ops.titleGeneration=null;if(this.fileChangeTracker.dispose(),this.threadReadWriter)await this.threadReadWriter.asyncDispose(),this.threadReadWriter=null}async getSelectedAgentMode(){let A=await this.getConfig(),{agentMode:Q}=XZ(A.settings,this.thread);return Q}}function L33(A,Q,$=!1){let B=D9(A,"assistant");if(!B||B.state.type!=="complete"||B.state.stopReason!=="tool_use")return!1;let D=B.content.filter((E)=>E.type==="tool_use").map((E)=>E.id);if(Q&&!D.includes(Q))return P.debug(`tool:data for orphaned tool_use ${Q} - ignoring for inference`,{name:"shouldRunInferenceWithToolData",threadID:A.id}),!1;if(D.length===0)return!1;let J=rF(A);if(!D.every((E)=>{let Z=J.get(E);if(!Z?.run||!f3(Z.run.status))return!1;let U=Z.run.status;if(U==="cancelled"){let X=Z.run.reason;return X?!X.startsWith("user:"):!1}if(U==="rejected-by-user")return $;return!0}))return!1;if(D.every((E)=>{let Z=J.get(E);if(!Z||Z.run.status!=="done")return!1;return Z.run.isFinal===!0}))return!1;return!0}var lO4=o(()=>{Q4();P1();cQ();$Y();p0();M5();a5();ca0();OZ();y5();pT();zK();iE();h4();WH();nh0();Dj();sa0();Dk();Bq();a4();AO();bO4();Yb0();cO4()});var iO4={};C8(iO4,{threadWorkerService:()=>z9});class aO4{threadWorkers=new $v0;async getOrCreateForThread(A,Q){let $=this.threadWorkers.get(Q);if(!$){if($=new aS(A,Q),this.threadWorkers.set(Q,$),this.threadWorkers.size>25)P.info("Many active thread workers detected",{name:"ThreadWorkerService.memoryCheck",threadID:Q,totalWorkerCount:this.threadWorkers.size})}return ea0.record(this.threadWorkers.size),$}async createThreadWorker(A,Q){let $=await this.getOrCreateForThread(A,Q);return await $.resume(),$}async seedThreadMessages(A,Q,$,B){let D=await A.threadService.exclusiveSyncReadWriter(Q),J=B?$.map((E)=>E.role==="user"?{...E,agentMode:B}:E):[...$],F=J.length>0?Math.max(...J.map((E)=>E.messageId))+1:0,Y=D.read();D.write({...Y,agentMode:B??Y.agentMode,messages:J,nextMessageId:F,v:Y.v+1}),await D.asyncDispose()}async applyParentRelationship(A,Q,$,B){let D=Date.now(),{threadID:J,type:F,messageIndex:Y,blockIndex:E,comment:Z}=B;await Q.handle({type:"relationship",relationship:{threadID:J,type:F,role:"child",messageIndex:Y,blockIndex:E,createdAt:D,comment:Z}});let U={threadID:$,type:F,role:"parent",messageIndex:Y,blockIndex:E,createdAt:D,comment:Z},X=this.threadWorkers.get(J);if(X)await X.handle({type:"relationship",relationship:U});else{let G=await A.threadService.exclusiveSyncReadWriter(J);G.update((V)=>{if(!V.relationships)V.relationships=[];if(!V.relationships.some((I)=>I.threadID===U.threadID&&I.type===U.type&&I.role===U.role))V.relationships.push(U)}),await G.asyncDispose()}}async inheritVisibilityIfNeeded(A,Q,$){if(Q.type==="handoff")await UN4(A.threadService,Q.threadID,$)}async sendInitialUserMessage(A,Q){let $=typeof Q==="string"?[{type:"text",text:Q}]:[...Q];await A.handle({type:"user:message",message:{content:$}})}async setDraftContent(A,Q){let $=typeof Q==="string"?Q:[...Q];await A.handle({type:"draft",content:$})}async setPendingNavigation(A,Q){let $=this.threadWorkers.get(A);if($)await $.handle({type:"setPendingNavigation",threadID:Q})}async transferQueuedMessages(A,Q){for(let $ of Q)await A.handle({type:"user:message-queue:enqueue",message:$.queuedMessage})}async createThread(A,Q){let $=Q?.newThreadID??B9(),B=Q?.agentMode,D=!1;if(Q?.seededMessages)await this.seedThreadMessages(A,$,Q.seededMessages,B),D=!0;let J=await this.createThreadWorker(A,$);if(J.thread.messages.length>0&&!D)return P.info("createThread called for existing thread, returning existing worker",{threadID:$,messageCount:J.thread.messages.length}),{threadID:$,worker:J};if(B&&!D)await J.handle({type:"agent-mode",mode:B});if(Q?.parent)await this.applyParentRelationship(A,J,$,Q.parent),await this.inheritVisibilityIfNeeded(A,Q.parent,$);if(Q?.initialUserMessage){if(D)throw Error("initialUserMessage cannot be set when seededMessages is provided");await this.sendInitialUserMessage(J,Q.initialUserMessage)}if(Q?.draftContent){if(D)throw Error("draftContent cannot be set when seededMessages is provided");await this.setDraftContent(J,Q.draftContent)}if(Q?.navigate&&Q?.parent)await this.setPendingNavigation(Q.parent.threadID,$);if(Q?.queuedMessages)await this.transferQueuedMessages(J,Q.queuedMessages);return{threadID:$,worker:J}}async handoff(A,Q){let $=await this.createThreadWorker(A,Q.threadID),B=$.thread,D=Q.images??[],J=Q.signal??new AbortController().signal,{content:F}=await vD0({thread:B,goal:Q.goal,images:D,deps:{configService:A.configService,buildSystemPromptDeps:Q.buildSystemPromptDeps,signal:J,filesystem:Q.filesystem,deadline:Q.deadline}}),Y=typeof F==="string"?F:F.filter((U)=>U.type==="text"||U.type==="image"),E={threadID:Q.threadID,type:"handoff",messageIndex:Q.messageIndex??(B.messages.length?B.messages.length-1:void 0),blockIndex:Q.blockIndex,comment:Q.comment??Q.goal},Z=await this.createThread(A,{newThreadID:Q.newThreadID,agentMode:Q.agentMode??B.agentMode,parent:E,navigate:Q.navigate,queuedMessages:Q.queuedMessages??B.queuedMessages,initialUserMessage:Q.mode==="initial"?Y:void 0,draftContent:Q.mode==="draft"?Y:void 0});if(Q.clearQueuedMessages&&B.queuedMessages?.length)await $.handle({type:"user:message-queue:discard"});return Z}get workers(){return this.threadWorkers.observable}get statuses(){return this.threadWorkers.observable.pipe(y4((A)=>A.size===0?h0.of({}):jA(...Array.from(A.values()).map((Q)=>Q.status.pipe(N1(($)=>[Q.threadID,Q.threadReadWriter?qS(Q.thread,$):void 0])))).pipe(N1((Q)=>Object.fromEntries(Q)))),DK(25),t6())}get(A){return this.threadWorkers.get(A)}prettyPrintToolRun(A,Q){let $=this.threadWorkers.get(A);if(!$)throw Error(`No worker found for thread ${A}`);for(let B of $.thread.messages)for(let D of B.content)if(D.type==="tool_result"&&D.toolUseID===Q)return CZ4(D.run);throw Error(`Tool run not found for thread ${A} and tool use ${Q}`)}async cancelToolOnly(A,Q){await this.threadWorkers.get(A)?.cancelToolOnly(Q)}async cancel(A){await this.threadWorkers.get(A)?.cancel()}async dispose(A){let Q=this.threadWorkers.get(A);if(Q)await Q.cancel(),await Q.asyncDispose(),this.threadWorkers.delete(A),ea0.record(this.threadWorkers.size)}async retry(A){let Q=this.threadWorkers.get(A);if(!Q)throw Error(`No active worker for thread ${A}`);await Q.retry()}async revertFileChanges(A,Q){let $=this.threadWorkers.get(A);if(!$)throw Error(`No active worker for thread ${A}`);await $.revertFileChanges(Q)}async getFilesAffectedByTruncation(A,Q){let $=this.threadWorkers.get(A);if(!$)throw Error(`No active worker for thread ${A}`);return $.getFilesAffectedByTruncation(Q)}async cleanupThreadBackups(A,Q){let $=this.threadWorkers.get(Q);if($)await $.fileChangeTracker.cleanupBackups();else try{await new mL().cleanup(Q),P.debug(`Cleaned up backup files for thread ${Q}`,{threadID:Q})}catch(B){P.error("Error cleaning up thread backups",B,{threadID:Q})}}async disposeAll(){await Promise.all(Array.from(this.threadWorkers.values()).map(async(A)=>await A.asyncDispose())),this.threadWorkers.clear(),ea0.record(0)}}var nO4,O33,ea0,z9;var sq=o(()=>{P1();p0();MZ4();ZN4();Ql();a4();XN4();lO4();nO4=b4(L4(),1),O33=nO4.metrics.getMeter("thread-worker-service"),ea0=O33.createGauge("thread_worker_count",{description:"Number of active thread workers"});z9=new aO4});var Qo0=S((sO4)=>{Object.defineProperty(sO4,"__esModule",{value:!0});sO4.dynamicAnchor=void 0;var Ao0=QA(),j33=EY(),oO4=ap(),R33=U90(),P33={keyword:"$dynamicAnchor",schemaType:"string",code:(A)=>rO4(A,A.schema)};function rO4(A,Q){let{gen:$,it:B}=A;B.schemaEnv.root.dynamicAnchors[Q]=!0;let D=Ao0._`${j33.default.dynamicAnchors}${(0,Ao0.getProperty)(Q)}`,J=B.errSchemaPath==="#"?B.validateName:u33(A);$.if(Ao0._`!${D}`,()=>$.assign(D,J))}sO4.dynamicAnchor=rO4;function u33(A){let{schemaEnv:Q,schema:$,self:B}=A.it,{root:D,baseId:J,localRefs:F,meta:Y}=Q.root,{schemaId:E}=B.opts,Z=new oO4.SchemaEnv({schema:$,schemaId:E,root:D,baseId:J,localRefs:F,meta:Y});return oO4.compileSchema.call(B,Z),(0,R33.getValidate)(A,Z)}sO4.default=P33});var $o0=S(($j4)=>{Object.defineProperty($j4,"__esModule",{value:!0});$j4.dynamicRef=void 0;var eO4=QA(),T33=EY(),Aj4=U90(),v33={keyword:"$dynamicRef",schemaType:"string",code:(A)=>Qj4(A,A.schema)};function Qj4(A,Q){let{gen:$,keyword:B,it:D}=A;if(Q[0]!=="#")throw Error(`"${B}" only supports hash fragment reference`);let J=Q.slice(1);if(D.allErrors)F();else{let E=$.let("valid",!1);F(E),A.ok(E)}function F(E){if(D.schemaEnv.root.dynamicAnchors[J]){let Z=$.let("_v",eO4._`${T33.default.dynamicAnchors}${(0,eO4.getProperty)(J)}`);$.if(Z,Y(Z,E),Y(D.validateName,E))}else Y(D.validateName,E)()}function Y(E,Z){return Z?()=>$.block(()=>{(0,Aj4.callRef)(A,E),$.let(Z,!0)}):()=>(0,Aj4.callRef)(A,E)}}$j4.dynamicRef=Qj4;$j4.default=v33});var Jj4=S((Dj4)=>{Object.defineProperty(Dj4,"__esModule",{value:!0});var S33=Qo0(),f33=gA(),y33={keyword:"$recursiveAnchor",schemaType:"boolean",code(A){if(A.schema)(0,S33.dynamicAnchor)(A,"");else(0,f33.checkStrictMode)(A.it,"$recursiveAnchor: false is ignored")}};Dj4.default=y33});var Yj4=S((Fj4)=>{Object.defineProperty(Fj4,"__esModule",{value:!0});var b33=$o0(),h33={keyword:"$recursiveRef",schemaType:"string",code:(A)=>(0,b33.dynamicRef)(A,A.schema)};Fj4.default=h33});var Zj4=S((Ej4)=>{Object.defineProperty(Ej4,"__esModule",{value:!0});var m33=Qo0(),d33=$o0(),p33=Jj4(),c33=Yj4(),l33=[m33.default,d33.default,p33.default,c33.default];Ej4.default=l33});var Gj4=S((Xj4)=>{Object.defineProperty(Xj4,"__esModule",{value:!0});var Uj4=W90(),n33={keyword:"dependentRequired",type:"object",schemaType:"object",error:Uj4.error,code:(A)=>(0,Uj4.validatePropertyDeps)(A)};Xj4.default=n33});var Kj4=S((Vj4)=>{Object.defineProperty(Vj4,"__esModule",{value:!0});var o33=W90(),r33={keyword:"dependentSchemas",type:"object",schemaType:"object",code:(A)=>(0,o33.validateSchemaDeps)(A)};Vj4.default=r33});var Ij4=S((zj4)=>{Object.defineProperty(zj4,"__esModule",{value:!0});var t33=gA(),e33={keyword:["maxContains","minContains"],type:"array",schemaType:"number",code({keyword:A,parentSchema:Q,it:$}){if(Q.contains===void 0)(0,t33.checkStrictMode)($,`"${A}" without "contains" is ignored`)}};zj4.default=e33});var Hj4=S((Wj4)=>{Object.defineProperty(Wj4,"__esModule",{value:!0});var Q53=Gj4(),$53=Kj4(),B53=Ij4(),D53=[Q53.default,$53.default,B53.default];Wj4.default=D53});var wj4=S((Nj4)=>{Object.defineProperty(Nj4,"__esModule",{value:!0});var tq=QA(),qj4=gA(),F53=EY(),Y53={message:"must NOT have unevaluated properties",params:({params:A})=>tq._`{unevaluatedProperty: ${A.unevaluatedProperty}}`},E53={keyword:"unevaluatedProperties",type:"object",schemaType:["boolean","object"],trackErrors:!0,error:Y53,code(A){let{gen:Q,schema:$,data:B,errsCount:D,it:J}=A;if(!D)throw Error("ajv implementation error");let{allErrors:F,props:Y}=J;if(Y instanceof tq.Name)Q.if(tq._`${Y} !== true`,()=>Q.forIn("key",B,(X)=>Q.if(Z(Y,X),()=>E(X))));else if(Y!==!0)Q.forIn("key",B,(X)=>Y===void 0?E(X):Q.if(U(Y,X),()=>E(X)));J.props=!0,A.ok(tq._`${D} === ${F53.default.errors}`);function E(X){if($===!1){if(A.setParams({unevaluatedProperty:X}),A.error(),!F)Q.break();return}if(!(0,qj4.alwaysValidSchema)(J,$)){let G=Q.name("valid");if(A.subschema({keyword:"unevaluatedProperties",dataProp:X,dataPropType:qj4.Type.Str},G),!F)Q.if((0,tq.not)(G),()=>Q.break())}}function Z(X,G){return tq._`!${X} || !${X}[${G}]`}function U(X,G){let V=[];for(let K in X)if(X[K]===!0)V.push(tq._`${G} !== ${K}`);return(0,tq.and)(...V)}}};Nj4.default=E53});var Lj4=S((Mj4)=>{Object.defineProperty(Mj4,"__esModule",{value:!0});var Fj=QA(),Cj4=gA(),U53={message:({params:{len:A}})=>Fj.str`must NOT have more than ${A} items`,params:({params:{len:A}})=>Fj._`{limit: ${A}}`},X53={keyword:"unevaluatedItems",type:"array",schemaType:["boolean","object"],error:U53,code(A){let{gen:Q,schema:$,data:B,it:D}=A,J=D.items||0;if(J===!0)return;let F=Q.const("len",Fj._`${B}.length`);if($===!1)A.setParams({len:J}),A.fail(Fj._`${F} > ${J}`);else if(typeof $=="object"&&!(0,Cj4.alwaysValidSchema)(D,$)){let E=Q.var("valid",Fj._`${F} <= ${J}`);Q.if((0,Fj.not)(E),()=>Y(E,J)),A.ok(E)}D.items=!0;function Y(E,Z){Q.forRange("i",Z,F,(U)=>{if(A.subschema({keyword:"unevaluatedItems",dataProp:U,dataPropType:Cj4.Type.Num},E),!D.allErrors)Q.if((0,Fj.not)(E),()=>Q.break())})}}};Mj4.default=X53});var jj4=S((Oj4)=>{Object.defineProperty(Oj4,"__esModule",{value:!0});var V53=wj4(),K53=Lj4(),z53=[V53.default,K53.default];Oj4.default=z53});var uj4=S((Pj4)=>{Object.defineProperty(Pj4,"__esModule",{value:!0});var W53=fy0(),H53=by0(),q53=ly0(),N53=Zj4(),w53=Hj4(),C53=jj4(),M53=iy0(),Rj4=ny0(),L53=[N53.default,W53.default,H53.default,(0,q53.default)(!0),M53.default,Rj4.metadataVocabulary,Rj4.contentVocabulary,w53.default,C53.default];Pj4.default=L53});var _j4=S((qQ2,j53)=>{j53.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/schema",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/core":!0,"https://json-schema.org/draft/2020-12/vocab/applicator":!0,"https://json-schema.org/draft/2020-12/vocab/unevaluated":!0,"https://json-schema.org/draft/2020-12/vocab/validation":!0,"https://json-schema.org/draft/2020-12/vocab/meta-data":!0,"https://json-schema.org/draft/2020-12/vocab/format-annotation":!0,"https://json-schema.org/draft/2020-12/vocab/content":!0},$dynamicAnchor:"meta",title:"Core and Validation specifications meta-schema",allOf:[{$ref:"meta/core"},{$ref:"meta/applicator"},{$ref:"meta/unevaluated"},{$ref:"meta/validation"},{$ref:"meta/meta-data"},{$ref:"meta/format-annotation"},{$ref:"meta/content"}],type:["object","boolean"],$comment:"This meta-schema also defines keywords that have appeared in previous drafts in order to prevent incompatible extensions as they remain in common use.",properties:{definitions:{$comment:'"definitions" has been replaced by "$defs".',type:"object",additionalProperties:{$dynamicRef:"#meta"},deprecated:!0,default:{}},dependencies:{$comment:'"dependencies" has been split and replaced by "dependentSchemas" and "dependentRequired" in order to serve their differing semantics.',type:"object",additionalProperties:{anyOf:[{$dynamicRef:"#meta"},{$ref:"meta/validation#/$defs/stringArray"}]},deprecated:!0,default:{}},$recursiveAnchor:{$comment:'"$recursiveAnchor" has been replaced by "$dynamicAnchor".',$ref:"meta/core#/$defs/anchorString",deprecated:!0},$recursiveRef:{$comment:'"$recursiveRef" has been replaced by "$dynamicRef".',$ref:"meta/core#/$defs/uriReferenceString",deprecated:!0}}}});var Tj4=S((NQ2,R53)=>{R53.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/applicator",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/applicator":!0},$dynamicAnchor:"meta",title:"Applicator vocabulary meta-schema",type:["object","boolean"],properties:{prefixItems:{$ref:"#/$defs/schemaArray"},items:{$dynamicRef:"#meta"},contains:{$dynamicRef:"#meta"},additionalProperties:{$dynamicRef:"#meta"},properties:{type:"object",additionalProperties:{$dynamicRef:"#meta"},default:{}},patternProperties:{type:"object",additionalProperties:{$dynamicRef:"#meta"},propertyNames:{format:"regex"},default:{}},dependentSchemas:{type:"object",additionalProperties:{$dynamicRef:"#meta"},default:{}},propertyNames:{$dynamicRef:"#meta"},if:{$dynamicRef:"#meta"},then:{$dynamicRef:"#meta"},else:{$dynamicRef:"#meta"},allOf:{$ref:"#/$defs/schemaArray"},anyOf:{$ref:"#/$defs/schemaArray"},oneOf:{$ref:"#/$defs/schemaArray"},not:{$dynamicRef:"#meta"}},$defs:{schemaArray:{type:"array",minItems:1,items:{$dynamicRef:"#meta"}}}}});var vj4=S((wQ2,P53)=>{P53.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/unevaluated",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/unevaluated":!0},$dynamicAnchor:"meta",title:"Unevaluated applicator vocabulary meta-schema",type:["object","boolean"],properties:{unevaluatedItems:{$dynamicRef:"#meta"},unevaluatedProperties:{$dynamicRef:"#meta"}}}});var kj4=S((CQ2,u53)=>{u53.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/content",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/content":!0},$dynamicAnchor:"meta",title:"Content vocabulary meta-schema",type:["object","boolean"],properties:{contentEncoding:{type:"string"},contentMediaType:{type:"string"},contentSchema:{$dynamicRef:"#meta"}}}});var Sj4=S((MQ2,_53)=>{_53.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/core",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/core":!0},$dynamicAnchor:"meta",title:"Core vocabulary meta-schema",type:["object","boolean"],properties:{$id:{$ref:"#/$defs/uriReferenceString",$comment:"Non-empty fragments not allowed.",pattern:"^[^#]*#?$"},$schema:{$ref:"#/$defs/uriString"},$ref:{$ref:"#/$defs/uriReferenceString"},$anchor:{$ref:"#/$defs/anchorString"},$dynamicRef:{$ref:"#/$defs/uriReferenceString"},$dynamicAnchor:{$ref:"#/$defs/anchorString"},$vocabulary:{type:"object",propertyNames:{$ref:"#/$defs/uriString"},additionalProperties:{type:"boolean"}},$comment:{type:"string"},$defs:{type:"object",additionalProperties:{$dynamicRef:"#meta"}}},$defs:{anchorString:{type:"string",pattern:"^[A-Za-z_][-A-Za-z0-9._]*$"},uriString:{type:"string",format:"uri"},uriReferenceString:{type:"string",format:"uri-reference"}}}});var fj4=S((LQ2,T53)=>{T53.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/format-annotation",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/format-annotation":!0},$dynamicAnchor:"meta",title:"Format vocabulary meta-schema for annotation results",type:["object","boolean"],properties:{format:{type:"string"}}}});var yj4=S((OQ2,v53)=>{v53.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/meta-data",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/meta-data":!0},$dynamicAnchor:"meta",title:"Meta-data vocabulary meta-schema",type:["object","boolean"],properties:{title:{type:"string"},description:{type:"string"},default:!0,deprecated:{type:"boolean",default:!1},readOnly:{type:"boolean",default:!1},writeOnly:{type:"boolean",default:!1},examples:{type:"array",items:!0}}}});var xj4=S((jQ2,k53)=>{k53.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/validation",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/validation":!0},$dynamicAnchor:"meta",title:"Validation vocabulary meta-schema",type:["object","boolean"],properties:{type:{anyOf:[{$ref:"#/$defs/simpleTypes"},{type:"array",items:{$ref:"#/$defs/simpleTypes"},minItems:1,uniqueItems:!0}]},const:!0,enum:{type:"array",items:!0},multipleOf:{type:"number",exclusiveMinimum:0},maximum:{type:"number"},exclusiveMaximum:{type:"number"},minimum:{type:"number"},exclusiveMinimum:{type:"number"},maxLength:{$ref:"#/$defs/nonNegativeInteger"},minLength:{$ref:"#/$defs/nonNegativeIntegerDefault0"},pattern:{type:"string",format:"regex"},maxItems:{$ref:"#/$defs/nonNegativeInteger"},minItems:{$ref:"#/$defs/nonNegativeIntegerDefault0"},uniqueItems:{type:"boolean",default:!1},maxContains:{$ref:"#/$defs/nonNegativeInteger"},minContains:{$ref:"#/$defs/nonNegativeInteger",default:1},maxProperties:{$ref:"#/$defs/nonNegativeInteger"},minProperties:{$ref:"#/$defs/nonNegativeIntegerDefault0"},required:{$ref:"#/$defs/stringArray"},dependentRequired:{type:"object",additionalProperties:{$ref:"#/$defs/stringArray"}}},$defs:{nonNegativeInteger:{type:"integer",minimum:0},nonNegativeIntegerDefault0:{$ref:"#/$defs/nonNegativeInteger",default:0},simpleTypes:{enum:["array","boolean","integer","null","number","object","string"]},stringArray:{type:"array",items:{type:"string"},uniqueItems:!0,default:[]}}}});var hj4=S((bj4)=>{Object.defineProperty(bj4,"__esModule",{value:!0});var S53=_j4(),f53=Tj4(),y53=vj4(),x53=kj4(),b53=Sj4(),h53=fj4(),g53=yj4(),m53=xj4(),d53=["/properties"];function p53(A){return[S53,f53,y53,x53,b53,Q(this,h53),g53,Q(this,m53)].forEach(($)=>this.addMetaSchema($,void 0,!1)),this;function Q($,B){return A?$.$dataMetaSchema(B,d53):B}}bj4.default=p53});var gj4=S((HD,Do0)=>{Object.defineProperty(HD,"__esModule",{value:!0});HD.MissingRefError=HD.ValidationError=HD.CodeGen=HD.Name=HD.nil=HD.stringify=HD.str=HD._=HD.KeywordCxt=HD.Ajv2020=void 0;var l53=Sy0(),i53=uj4(),n53=oy0(),a53=hj4(),Bo0="https://json-schema.org/draft/2020-12/schema";class xa extends l53.default{constructor(A={}){super({...A,dynamicRef:!0,next:!0,unevaluated:!0})}_addVocabularies(){if(super._addVocabularies(),i53.default.forEach((A)=>this.addVocabulary(A)),this.opts.discriminator)this.addKeyword(n53.default)}_addDefaultMetaSchema(){super._addDefaultMetaSchema();let{$data:A,meta:Q}=this.opts;if(!Q)return;a53.default.call(this,A),this.refs["http://json-schema.org/schema"]=Bo0}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(Bo0)?Bo0:void 0)}}HD.Ajv2020=xa;Do0.exports=HD=xa;Do0.exports.Ajv2020=xa;Object.defineProperty(HD,"__esModule",{value:!0});HD.default=xa;var o53=Qv();Object.defineProperty(HD,"KeywordCxt",{enumerable:!0,get:function(){return o53.KeywordCxt}});var oS=QA();Object.defineProperty(HD,"_",{enumerable:!0,get:function(){return oS._}});Object.defineProperty(HD,"str",{enumerable:!0,get:function(){return oS.str}});Object.defineProperty(HD,"stringify",{enumerable:!0,get:function(){return oS.stringify}});Object.defineProperty(HD,"nil",{enumerable:!0,get:function(){return oS.nil}});Object.defineProperty(HD,"Name",{enumerable:!0,get:function(){return oS.Name}});Object.defineProperty(HD,"CodeGen",{enumerable:!0,get:function(){return oS.CodeGen}});var r53=ip();Object.defineProperty(HD,"ValidationError",{enumerable:!0,get:function(){return r53.default}});var s53=$v();Object.defineProperty(HD,"MissingRefError",{enumerable:!0,get:function(){return s53.default}})});var dj4=S((mj4)=>{(()=>{var A={349:(F,Y,E)=>{Object.defineProperty(Y,"__esModule",{value:!0}),Y.CircularList=void 0;let Z=E(460),U=E(844);class X extends U.Disposable{constructor(G){super(),this._maxLength=G,this.onDeleteEmitter=this.register(new Z.EventEmitter),this.onDelete=this.onDeleteEmitter.event,this.onInsertEmitter=this.register(new Z.EventEmitter),this.onInsert=this.onInsertEmitter.event,this.onTrimEmitter=this.register(new Z.EventEmitter),this.onTrim=this.onTrimEmitter.event,this._array=Array(this._maxLength),this._startIndex=0,this._length=0}get maxLength(){return this._maxLength}set maxLength(G){if(this._maxLength===G)return;let V=Array(G);for(let K=0;K<Math.min(G,this.length);K++)V[K]=this._array[this._getCyclicIndex(K)];this._array=V,this._maxLength=G,this._startIndex=0}get length(){return this._length}set length(G){if(G>this._length)for(let V=this._length;V<G;V++)this._array[V]=void 0;this._length=G}get(G){return this._array[this._getCyclicIndex(G)]}set(G,V){this._array[this._getCyclicIndex(G)]=V}push(G){this._array[this._getCyclicIndex(this._length)]=G,this._length===this._maxLength?(this._startIndex=++this._startIndex%this._maxLength,this.onTrimEmitter.fire(1)):this._length++}recycle(){if(this._length!==this._maxLength)throw Error("Can only recycle when the buffer is full");return this._startIndex=++this._startIndex%this._maxLength,this.onTrimEmitter.fire(1),this._array[this._getCyclicIndex(this._length-1)]}get isFull(){return this._length===this._maxLength}pop(){return this._array[this._getCyclicIndex(this._length---1)]}splice(G,V,...K){if(V){for(let I=G;I<this._length-V;I++)this._array[this._getCyclicIndex(I)]=this._array[this._getCyclicIndex(I+V)];this._length-=V,this.onDeleteEmitter.fire({index:G,amount:V})}for(let I=this._length-1;I>=G;I--)this._array[this._getCyclicIndex(I+K.length)]=this._array[this._getCyclicIndex(I)];for(let I=0;I<K.length;I++)this._array[this._getCyclicIndex(G+I)]=K[I];if(K.length&&this.onInsertEmitter.fire({index:G,amount:K.length}),this._length+K.length>this._maxLength){let I=this._length+K.length-this._maxLength;this._startIndex+=I,this._length=this._maxLength,this.onTrimEmitter.fire(I)}else this._length+=K.length}trimStart(G){G>this._length&&(G=this._length),this._startIndex+=G,this._length-=G,this.onTrimEmitter.fire(G)}shiftElements(G,V,K){if(!(V<=0)){if(G<0||G>=this._length)throw Error("start argument out of range");if(G+K<0)throw Error("Cannot shift elements in list beyond index 0");if(K>0){for(let z=V-1;z>=0;z--)this.set(G+z+K,this.get(G+z));let I=G+V+K-this._length;if(I>0)for(this._length+=I;this._length>this._maxLength;)this._length--,this._startIndex++,this.onTrimEmitter.fire(1)}else for(let I=0;I<V;I++)this.set(G+I+K,this.get(G+I))}}_getCyclicIndex(G){return(this._startIndex+G)%this._maxLength}}Y.CircularList=X},439:(F,Y)=>{Object.defineProperty(Y,"__esModule",{value:!0}),Y.clone=void 0,Y.clone=function E(Z,U=5){if(typeof Z!="object")return Z;let X=Array.isArray(Z)?[]:{};for(let G in Z)X[G]=U<=1?Z[G]:Z[G]&&E(Z[G],U-1);return X}},969:(F,Y,E)=>{Object.defineProperty(Y,"__esModule",{value:!0}),Y.CoreTerminal=void 0;let Z=E(844),U=E(585),X=E(348),G=E(866),V=E(744),K=E(302),I=E(83),z=E(460),W=E(753),H=E(480),q=E(994),N=E(282),w=E(435),O=E(981),L=E(660),j=!1;class k extends Z.Disposable{get onScroll(){return this._onScrollApi||(this._onScrollApi=this.register(new z.EventEmitter),this._onScroll.event((_)=>{this._onScrollApi?.fire(_.position)})),this._onScrollApi.event}get cols(){return this._bufferService.cols}get rows(){return this._bufferService.rows}get buffers(){return this._bufferService.buffers}get options(){return this.optionsService.options}set options(_){for(let f in _)this.optionsService.options[f]=_[f]}constructor(_){super(),this._windowsWrappingHeuristics=this.register(new Z.MutableDisposable),this._onBinary=this.register(new z.EventEmitter),this.onBinary=this._onBinary.event,this._onData=this.register(new z.EventEmitter),this.onData=this._onData.event,this._onLineFeed=this.register(new z.EventEmitter),this.onLineFeed=this._onLineFeed.event,this._onResize=this.register(new z.EventEmitter),this.onResize=this._onResize.event,this._onWriteParsed=this.register(new z.EventEmitter),this.onWriteParsed=this._onWriteParsed.event,this._onScroll=this.register(new z.EventEmitter),this._instantiationService=new X.InstantiationService,this.optionsService=this.register(new K.OptionsService(_)),this._instantiationService.setService(U.IOptionsService,this.optionsService),this._bufferService=this.register(this._instantiationService.createInstance(V.BufferService)),this._instantiationService.setService(U.IBufferService,this._bufferService),this._logService=this.register(this._instantiationService.createInstance(G.LogService)),this._instantiationService.setService(U.ILogService,this._logService),this.coreService=this.register(this._instantiationService.createInstance(I.CoreService)),this._instantiationService.setService(U.ICoreService,this.coreService),this.coreMouseService=this.register(this._instantiationService.createInstance(W.CoreMouseService)),this._instantiationService.setService(U.ICoreMouseService,this.coreMouseService),this.unicodeService=this.register(this._instantiationService.createInstance(H.UnicodeService)),this._instantiationService.setService(U.IUnicodeService,this.unicodeService),this._charsetService=this._instantiationService.createInstance(q.CharsetService),this._instantiationService.setService(U.ICharsetService,this._charsetService),this._oscLinkService=this._instantiationService.createInstance(L.OscLinkService),this._instantiationService.setService(U.IOscLinkService,this._oscLinkService),this._inputHandler=this.register(new w.InputHandler(this._bufferService,this._charsetService,this.coreService,this._logService,this.optionsService,this._oscLinkService,this.coreMouseService,this.unicodeService)),this.register((0,z.forwardEvent)(this._inputHandler.onLineFeed,this._onLineFeed)),this.register(this._inputHandler),this.register((0,z.forwardEvent)(this._bufferService.onResize,this._onResize)),this.register((0,z.forwardEvent)(this.coreService.onData,this._onData)),this.register((0,z.forwardEvent)(this.coreService.onBinary,this._onBinary)),this.register(this.coreService.onRequestScrollToBottom(()=>this.scrollToBottom())),this.register(this.coreService.onUserInput(()=>this._writeBuffer.handleUserInput())),this.register(this.optionsService.onMultipleOptionChange(["windowsMode","windowsPty"],()=>this._handleWindowsPtyOptionChange())),this.register(this._bufferService.onScroll((f)=>{this._onScroll.fire({position:this._bufferService.buffer.ydisp,source:0}),this._inputHandler.markRangeDirty(this._bufferService.buffer.scrollTop,this._bufferService.buffer.scrollBottom)})),this.register(this._inputHandler.onScroll((f)=>{this._onScroll.fire({position:this._bufferService.buffer.ydisp,source:0}),this._inputHandler.markRangeDirty(this._bufferService.buffer.scrollTop,this._bufferService.buffer.scrollBottom)})),this._writeBuffer=this.register(new O.WriteBuffer((f,h)=>this._inputHandler.parse(f,h))),this.register((0,z.forwardEvent)(this._writeBuffer.onWriteParsed,this._onWriteParsed))}write(_,f){this._writeBuffer.write(_,f)}writeSync(_,f){this._logService.logLevel<=U.LogLevelEnum.WARN&&!j&&(this._logService.warn("writeSync is unreliable and will be removed soon."),j=!0),this._writeBuffer.writeSync(_,f)}input(_,f=!0){this.coreService.triggerDataEvent(_,f)}resize(_,f){isNaN(_)||isNaN(f)||(_=Math.max(_,V.MINIMUM_COLS),f=Math.max(f,V.MINIMUM_ROWS),this._bufferService.resize(_,f))}scroll(_,f=!1){this._bufferService.scroll(_,f)}scrollLines(_,f,h){this._bufferService.scrollLines(_,f,h)}scrollPages(_){this.scrollLines(_*(this.rows-1))}scrollToTop(){this.scrollLines(-this._bufferService.buffer.ydisp)}scrollToBottom(){this.scrollLines(this._bufferService.buffer.ybase-this._bufferService.buffer.ydisp)}scrollToLine(_){let f=_-this._bufferService.buffer.ydisp;f!==0&&this.scrollLines(f)}registerEscHandler(_,f){return this._inputHandler.registerEscHandler(_,f)}registerDcsHandler(_,f){return this._inputHandler.registerDcsHandler(_,f)}registerCsiHandler(_,f){return this._inputHandler.registerCsiHandler(_,f)}registerOscHandler(_,f){return this._inputHandler.registerOscHandler(_,f)}_setup(){this._handleWindowsPtyOptionChange()}reset(){this._inputHandler.reset(),this._bufferService.reset(),this._charsetService.reset(),this.coreService.reset(),this.coreMouseService.reset()}_handleWindowsPtyOptionChange(){let _=!1,f=this.optionsService.rawOptions.windowsPty;f&&f.buildNumber!==void 0&&f.buildNumber!==void 0?_=f.backend==="conpty"&&f.buildNumber<21376:this.optionsService.rawOptions.windowsMode&&(_=!0),_?this._enableWindowsWrappingHeuristics():this._windowsWrappingHeuristics.clear()}_enableWindowsWrappingHeuristics(){if(!this._windowsWrappingHeuristics.value){let _=[];_.push(this.onLineFeed(N.updateWindowsModeWrappedState.bind(null,this._bufferService))),_.push(this.registerCsiHandler({final:"H"},()=>((0,N.updateWindowsModeWrappedState)(this._bufferService),!1))),this._windowsWrappingHeuristics.value=(0,Z.toDisposable)(()=>{for(let f of _)f.dispose()})}}}Y.CoreTerminal=k},460:(F,Y)=>{Object.defineProperty(Y,"__esModule",{value:!0}),Y.runAndSubscribe=Y.forwardEvent=Y.EventEmitter=void 0,Y.EventEmitter=class{constructor(){this._listeners=[],this._disposed=!1}get event(){return this._event||(this._event=(E)=>{return this._listeners.push(E),{dispose:()=>{if(!this._disposed){for(let U=0;U<this._listeners.length;U++)if(this._listeners[U]===E)return void this._listeners.splice(U,1)}}}}),this._event}fire(E,Z){let U=[];for(let X=0;X<this._listeners.length;X++)U.push(this._listeners[X]);for(let X=0;X<U.length;X++)U[X].call(void 0,E,Z)}dispose(){this.clearListeners(),this._disposed=!0}clearListeners(){this._listeners&&(this._listeners.length=0)}},Y.forwardEvent=function(E,Z){return E((U)=>Z.fire(U))},Y.runAndSubscribe=function(E,Z){return Z(void 0),E((U)=>Z(U))}},435:function(F,Y,E){var Z=this&&this.__decorate||function(g,i,r,A0){var I0,E0=arguments.length,W0=E0<3?i:A0===null?A0=Object.getOwnPropertyDescriptor(i,r):A0;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")W0=Reflect.decorate(g,i,r,A0);else for(var $0=g.length-1;$0>=0;$0--)(I0=g[$0])&&(W0=(E0<3?I0(W0):E0>3?I0(i,r,W0):I0(i,r))||W0);return E0>3&&W0&&Object.defineProperty(i,r,W0),W0},U=this&&this.__param||function(g,i){return function(r,A0){i(r,A0,g)}};Object.defineProperty(Y,"__esModule",{value:!0}),Y.InputHandler=Y.WindowsOptionsReportType=void 0;let X=E(584),G=E(116),V=E(15),K=E(844),I=E(482),z=E(437),W=E(460),H=E(643),q=E(511),N=E(734),w=E(585),O=E(480),L=E(242),j=E(351),k=E(941),_={"(":0,")":1,"*":2,"+":3,"-":1,".":2},f=131072;function h(g,i){if(g>24)return i.setWinLines||!1;switch(g){case 1:return!!i.restoreWin;case 2:return!!i.minimizeWin;case 3:return!!i.setWinPosition;case 4:return!!i.setWinSizePixels;case 5:return!!i.raiseWin;case 6:return!!i.lowerWin;case 7:return!!i.refreshWin;case 8:return!!i.setWinSizeChars;case 9:return!!i.maximizeWin;case 10:return!!i.fullscreenWin;case 11:return!!i.getWinState;case 13:return!!i.getWinPosition;case 14:return!!i.getWinSizePixels;case 15:return!!i.getScreenSizePixels;case 16:return!!i.getCellSizePixels;case 18:return!!i.getWinSizeChars;case 19:return!!i.getScreenSizeChars;case 20:return!!i.getIconTitle;case 21:return!!i.getWinTitle;case 22:return!!i.pushTitle;case 23:return!!i.popTitle;case 24:return!!i.setWinLines}return!1}var b;(function(g){g[g.GET_WIN_SIZE_PIXELS=0]="GET_WIN_SIZE_PIXELS",g[g.GET_CELL_SIZE_PIXELS=1]="GET_CELL_SIZE_PIXELS"})(b||(Y.WindowsOptionsReportType=b={}));let v=0;class y extends K.Disposable{getAttrData(){return this._curAttrData}constructor(g,i,r,A0,I0,E0,W0,$0,j0=new V.EscapeSequenceParser){super(),this._bufferService=g,this._charsetService=i,this._coreService=r,this._logService=A0,this._optionsService=I0,this._oscLinkService=E0,this._coreMouseService=W0,this._unicodeService=$0,this._parser=j0,this._parseBuffer=new Uint32Array(4096),this._stringDecoder=new I.StringToUtf32,this._utf8Decoder=new I.Utf8ToUtf32,this._workCell=new q.CellData,this._windowTitle="",this._iconName="",this._windowTitleStack=[],this._iconNameStack=[],this._curAttrData=z.DEFAULT_ATTR_DATA.clone(),this._eraseAttrDataInternal=z.DEFAULT_ATTR_DATA.clone(),this._onRequestBell=this.register(new W.EventEmitter),this.onRequestBell=this._onRequestBell.event,this._onRequestRefreshRows=this.register(new W.EventEmitter),this.onRequestRefreshRows=this._onRequestRefreshRows.event,this._onRequestReset=this.register(new W.EventEmitter),this.onRequestReset=this._onRequestReset.event,this._onRequestSendFocus=this.register(new W.EventEmitter),this.onRequestSendFocus=this._onRequestSendFocus.event,this._onRequestSyncScrollBar=this.register(new W.EventEmitter),this.onRequestSyncScrollBar=this._onRequestSyncScrollBar.event,this._onRequestWindowsOptionsReport=this.register(new W.EventEmitter),this.onRequestWindowsOptionsReport=this._onRequestWindowsOptionsReport.event,this._onA11yChar=this.register(new W.EventEmitter),this.onA11yChar=this._onA11yChar.event,this._onA11yTab=this.register(new W.EventEmitter),this.onA11yTab=this._onA11yTab.event,this._onCursorMove=this.register(new W.EventEmitter),this.onCursorMove=this._onCursorMove.event,this._onLineFeed=this.register(new W.EventEmitter),this.onLineFeed=this._onLineFeed.event,this._onScroll=this.register(new W.EventEmitter),this.onScroll=this._onScroll.event,this._onTitleChange=this.register(new W.EventEmitter),this.onTitleChange=this._onTitleChange.event,this._onColor=this.register(new W.EventEmitter),this.onColor=this._onColor.event,this._parseStack={paused:!1,cursorStartX:0,cursorStartY:0,decodedLength:0,position:0},this._specialColors=[256,257,258],this.register(this._parser),this._dirtyRowTracker=new p(this._bufferService),this._activeBuffer=this._bufferService.buffer,this.register(this._bufferService.buffers.onBufferActivate((Q0)=>this._activeBuffer=Q0.activeBuffer)),this._parser.setCsiHandlerFallback((Q0,M0)=>{this._logService.debug("Unknown CSI code: ",{identifier:this._parser.identToString(Q0),params:M0.toArray()})}),this._parser.setEscHandlerFallback((Q0)=>{this._logService.debug("Unknown ESC code: ",{identifier:this._parser.identToString(Q0)})}),this._parser.setExecuteHandlerFallback((Q0)=>{this._logService.debug("Unknown EXECUTE code: ",{code:Q0})}),this._parser.setOscHandlerFallback((Q0,M0,n)=>{this._logService.debug("Unknown OSC code: ",{identifier:Q0,action:M0,data:n})}),this._parser.setDcsHandlerFallback((Q0,M0,n)=>{M0==="HOOK"&&(n=n.toArray()),this._logService.debug("Unknown DCS code: ",{identifier:this._parser.identToString(Q0),action:M0,payload:n})}),this._parser.setPrintHandler((Q0,M0,n)=>this.print(Q0,M0,n)),this._parser.registerCsiHandler({final:"@"},(Q0)=>this.insertChars(Q0)),this._parser.registerCsiHandler({intermediates:" ",final:"@"},(Q0)=>this.scrollLeft(Q0)),this._parser.registerCsiHandler({final:"A"},(Q0)=>this.cursorUp(Q0)),this._parser.registerCsiHandler({intermediates:" ",final:"A"},(Q0)=>this.scrollRight(Q0)),this._parser.registerCsiHandler({final:"B"},(Q0)=>this.cursorDown(Q0)),this._parser.registerCsiHandler({final:"C"},(Q0)=>this.cursorForward(Q0)),this._parser.registerCsiHandler({final:"D"},(Q0)=>this.cursorBackward(Q0)),this._parser.registerCsiHandler({final:"E"},(Q0)=>this.cursorNextLine(Q0)),this._parser.registerCsiHandler({final:"F"},(Q0)=>this.cursorPrecedingLine(Q0)),this._parser.registerCsiHandler({final:"G"},(Q0)=>this.cursorCharAbsolute(Q0)),this._parser.registerCsiHandler({final:"H"},(Q0)=>this.cursorPosition(Q0)),this._parser.registerCsiHandler({final:"I"},(Q0)=>this.cursorForwardTab(Q0)),this._parser.registerCsiHandler({final:"J"},(Q0)=>this.eraseInDisplay(Q0,!1)),this._parser.registerCsiHandler({prefix:"?",final:"J"},(Q0)=>this.eraseInDisplay(Q0,!0)),this._parser.registerCsiHandler({final:"K"},(Q0)=>this.eraseInLine(Q0,!1)),this._parser.registerCsiHandler({prefix:"?",final:"K"},(Q0)=>this.eraseInLine(Q0,!0)),this._parser.registerCsiHandler({final:"L"},(Q0)=>this.insertLines(Q0)),this._parser.registerCsiHandler({final:"M"},(Q0)=>this.deleteLines(Q0)),this._parser.registerCsiHandler({final:"P"},(Q0)=>this.deleteChars(Q0)),this._parser.registerCsiHandler({final:"S"},(Q0)=>this.scrollUp(Q0)),this._parser.registerCsiHandler({final:"T"},(Q0)=>this.scrollDown(Q0)),this._parser.registerCsiHandler({final:"X"},(Q0)=>this.eraseChars(Q0)),this._parser.registerCsiHandler({final:"Z"},(Q0)=>this.cursorBackwardTab(Q0)),this._parser.registerCsiHandler({final:"`"},(Q0)=>this.charPosAbsolute(Q0)),this._parser.registerCsiHandler({final:"a"},(Q0)=>this.hPositionRelative(Q0)),this._parser.registerCsiHandler({final:"b"},(Q0)=>this.repeatPrecedingCharacter(Q0)),this._parser.registerCsiHandler({final:"c"},(Q0)=>this.sendDeviceAttributesPrimary(Q0)),this._parser.registerCsiHandler({prefix:">",final:"c"},(Q0)=>this.sendDeviceAttributesSecondary(Q0)),this._parser.registerCsiHandler({final:"d"},(Q0)=>this.linePosAbsolute(Q0)),this._parser.registerCsiHandler({final:"e"},(Q0)=>this.vPositionRelative(Q0)),this._parser.registerCsiHandler({final:"f"},(Q0)=>this.hVPosition(Q0)),this._parser.registerCsiHandler({final:"g"},(Q0)=>this.tabClear(Q0)),this._parser.registerCsiHandler({final:"h"},(Q0)=>this.setMode(Q0)),this._parser.registerCsiHandler({prefix:"?",final:"h"},(Q0)=>this.setModePrivate(Q0)),this._parser.registerCsiHandler({final:"l"},(Q0)=>this.resetMode(Q0)),this._parser.registerCsiHandler({prefix:"?",final:"l"},(Q0)=>this.resetModePrivate(Q0)),this._parser.registerCsiHandler({final:"m"},(Q0)=>this.charAttributes(Q0)),this._parser.registerCsiHandler({final:"n"},(Q0)=>this.deviceStatus(Q0)),this._parser.registerCsiHandler({prefix:"?",final:"n"},(Q0)=>this.deviceStatusPrivate(Q0)),this._parser.registerCsiHandler({intermediates:"!",final:"p"},(Q0)=>this.softReset(Q0)),this._parser.registerCsiHandler({intermediates:" ",final:"q"},(Q0)=>this.setCursorStyle(Q0)),this._parser.registerCsiHandler({final:"r"},(Q0)=>this.setScrollRegion(Q0)),this._parser.registerCsiHandler({final:"s"},(Q0)=>this.saveCursor(Q0)),this._parser.registerCsiHandler({final:"t"},(Q0)=>this.windowOptions(Q0)),this._parser.registerCsiHandler({final:"u"},(Q0)=>this.restoreCursor(Q0)),this._parser.registerCsiHandler({intermediates:"'",final:"}"},(Q0)=>this.insertColumns(Q0)),this._parser.registerCsiHandler({intermediates:"'",final:"~"},(Q0)=>this.deleteColumns(Q0)),this._parser.registerCsiHandler({intermediates:'"',final:"q"},(Q0)=>this.selectProtected(Q0)),this._parser.registerCsiHandler({intermediates:"$",final:"p"},(Q0)=>this.requestMode(Q0,!0)),this._parser.registerCsiHandler({prefix:"?",intermediates:"$",final:"p"},(Q0)=>this.requestMode(Q0,!1)),this._parser.setExecuteHandler(X.C0.BEL,()=>this.bell()),this._parser.setExecuteHandler(X.C0.LF,()=>this.lineFeed()),this._parser.setExecuteHandler(X.C0.VT,()=>this.lineFeed()),this._parser.setExecuteHandler(X.C0.FF,()=>this.lineFeed()),this._parser.setExecuteHandler(X.C0.CR,()=>this.carriageReturn()),this._parser.setExecuteHandler(X.C0.BS,()=>this.backspace()),this._parser.setExecuteHandler(X.C0.HT,()=>this.tab()),this._parser.setExecuteHandler(X.C0.SO,()=>this.shiftOut()),this._parser.setExecuteHandler(X.C0.SI,()=>this.shiftIn()),this._parser.setExecuteHandler(X.C1.IND,()=>this.index()),this._parser.setExecuteHandler(X.C1.NEL,()=>this.nextLine()),this._parser.setExecuteHandler(X.C1.HTS,()=>this.tabSet()),this._parser.registerOscHandler(0,new L.OscHandler((Q0)=>(this.setTitle(Q0),this.setIconName(Q0),!0))),this._parser.registerOscHandler(1,new L.OscHandler((Q0)=>this.setIconName(Q0))),this._parser.registerOscHandler(2,new L.OscHandler((Q0)=>this.setTitle(Q0))),this._parser.registerOscHandler(4,new L.OscHandler((Q0)=>this.setOrReportIndexedColor(Q0))),this._parser.registerOscHandler(8,new L.OscHandler((Q0)=>this.setHyperlink(Q0))),this._parser.registerOscHandler(10,new L.OscHandler((Q0)=>this.setOrReportFgColor(Q0))),this._parser.registerOscHandler(11,new L.OscHandler((Q0)=>this.setOrReportBgColor(Q0))),this._parser.registerOscHandler(12,new L.OscHandler((Q0)=>this.setOrReportCursorColor(Q0))),this._parser.registerOscHandler(104,new L.OscHandler((Q0)=>this.restoreIndexedColor(Q0))),this._parser.registerOscHandler(110,new L.OscHandler((Q0)=>this.restoreFgColor(Q0))),this._parser.registerOscHandler(111,new L.OscHandler((Q0)=>this.restoreBgColor(Q0))),this._parser.registerOscHandler(112,new L.OscHandler((Q0)=>this.restoreCursorColor(Q0))),this._parser.registerEscHandler({final:"7"},()=>this.saveCursor()),this._parser.registerEscHandler({final:"8"},()=>this.restoreCursor()),this._parser.registerEscHandler({final:"D"},()=>this.index()),this._parser.registerEscHandler({final:"E"},()=>this.nextLine()),this._parser.registerEscHandler({final:"H"},()=>this.tabSet()),this._parser.registerEscHandler({final:"M"},()=>this.reverseIndex()),this._parser.registerEscHandler({final:"="},()=>this.keypadApplicationMode()),this._parser.registerEscHandler({final:">"},()=>this.keypadNumericMode()),this._parser.registerEscHandler({final:"c"},()=>this.fullReset()),this._parser.registerEscHandler({final:"n"},()=>this.setgLevel(2)),this._parser.registerEscHandler({final:"o"},()=>this.setgLevel(3)),this._parser.registerEscHandler({final:"|"},()=>this.setgLevel(3)),this._parser.registerEscHandler({final:"}"},()=>this.setgLevel(2)),this._parser.registerEscHandler({final:"~"},()=>this.setgLevel(1)),this._parser.registerEscHandler({intermediates:"%",final:"@"},()=>this.selectDefaultCharset()),this._parser.registerEscHandler({intermediates:"%",final:"G"},()=>this.selectDefaultCharset());for(let Q0 in G.CHARSETS)this._parser.registerEscHandler({intermediates:"(",final:Q0},()=>this.selectCharset("("+Q0)),this._parser.registerEscHandler({intermediates:")",final:Q0},()=>this.selectCharset(")"+Q0)),this._parser.registerEscHandler({intermediates:"*",final:Q0},()=>this.selectCharset("*"+Q0)),this._parser.registerEscHandler({intermediates:"+",final:Q0},()=>this.selectCharset("+"+Q0)),this._parser.registerEscHandler({intermediates:"-",final:Q0},()=>this.selectCharset("-"+Q0)),this._parser.registerEscHandler({intermediates:".",final:Q0},()=>this.selectCharset("."+Q0)),this._parser.registerEscHandler({intermediates:"/",final:Q0},()=>this.selectCharset("/"+Q0));this._parser.registerEscHandler({intermediates:"#",final:"8"},()=>this.screenAlignmentPattern()),this._parser.setErrorHandler((Q0)=>(this._logService.error("Parsing error: ",Q0),Q0)),this._parser.registerDcsHandler({intermediates:"$",final:"q"},new j.DcsHandler((Q0,M0)=>this.requestStatusString(Q0,M0)))}_preserveStack(g,i,r,A0){this._parseStack.paused=!0,this._parseStack.cursorStartX=g,this._parseStack.cursorStartY=i,this._parseStack.decodedLength=r,this._parseStack.position=A0}_logSlowResolvingAsync(g){this._logService.logLevel<=w.LogLevelEnum.WARN&&Promise.race([g,new Promise((i,r)=>setTimeout(()=>r("#SLOW_TIMEOUT"),5000))]).catch((i)=>{if(i!=="#SLOW_TIMEOUT")throw i;console.warn("async parser handler taking longer than 5000 ms")})}_getCurrentLinkId(){return this._curAttrData.extended.urlId}parse(g,i){let r,A0=this._activeBuffer.x,I0=this._activeBuffer.y,E0=0,W0=this._parseStack.paused;if(W0){if(r=this._parser.parse(this._parseBuffer,this._parseStack.decodedLength,i))return this._logSlowResolvingAsync(r),r;A0=this._parseStack.cursorStartX,I0=this._parseStack.cursorStartY,this._parseStack.paused=!1,g.length>f&&(E0=this._parseStack.position+f)}if(this._logService.logLevel<=w.LogLevelEnum.DEBUG&&this._logService.debug("parsing data"+(typeof g=="string"?` "${g}"`:` "${Array.prototype.map.call(g,(Q0)=>String.fromCharCode(Q0)).join("")}"`),typeof g=="string"?g.split("").map((Q0)=>Q0.charCodeAt(0)):g),this._parseBuffer.length<g.length&&this._parseBuffer.length<f&&(this._parseBuffer=new Uint32Array(Math.min(g.length,f))),W0||this._dirtyRowTracker.clearRange(),g.length>f)for(let Q0=E0;Q0<g.length;Q0+=f){let M0=Q0+f<g.length?Q0+f:g.length,n=typeof g=="string"?this._stringDecoder.decode(g.substring(Q0,M0),this._parseBuffer):this._utf8Decoder.decode(g.subarray(Q0,M0),this._parseBuffer);if(r=this._parser.parse(this._parseBuffer,n))return this._preserveStack(A0,I0,n,Q0),this._logSlowResolvingAsync(r),r}else if(!W0){let Q0=typeof g=="string"?this._stringDecoder.decode(g,this._parseBuffer):this._utf8Decoder.decode(g,this._parseBuffer);if(r=this._parser.parse(this._parseBuffer,Q0))return this._preserveStack(A0,I0,Q0,0),this._logSlowResolvingAsync(r),r}this._activeBuffer.x===A0&&this._activeBuffer.y===I0||this._onCursorMove.fire();let $0=this._dirtyRowTracker.end+(this._bufferService.buffer.ybase-this._bufferService.buffer.ydisp),j0=this._dirtyRowTracker.start+(this._bufferService.buffer.ybase-this._bufferService.buffer.ydisp);j0<this._bufferService.rows&&this._onRequestRefreshRows.fire(Math.min(j0,this._bufferService.rows-1),Math.min($0,this._bufferService.rows-1))}print(g,i,r){let A0,I0,E0=this._charsetService.charset,W0=this._optionsService.rawOptions.screenReaderMode,$0=this._bufferService.cols,j0=this._coreService.decPrivateModes.wraparound,Q0=this._coreService.modes.insertMode,M0=this._curAttrData,n=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);this._dirtyRowTracker.markDirty(this._activeBuffer.y),this._activeBuffer.x&&r-i>0&&n.getWidth(this._activeBuffer.x-1)===2&&n.setCellFromCodepoint(this._activeBuffer.x-1,0,1,M0);let a=this._parser.precedingJoinState;for(let t=i;t<r;++t){if(A0=g[t],A0<127&&E0){let w0=E0[String.fromCharCode(A0)];w0&&(A0=w0.charCodeAt(0))}let e=this._unicodeService.charProperties(A0,a);I0=O.UnicodeService.extractWidth(e);let F0=O.UnicodeService.extractShouldJoin(e),J0=F0?O.UnicodeService.extractWidth(a):0;if(a=e,W0&&this._onA11yChar.fire((0,I.stringFromCodePoint)(A0)),this._getCurrentLinkId()&&this._oscLinkService.addLineToLink(this._getCurrentLinkId(),this._activeBuffer.ybase+this._activeBuffer.y),this._activeBuffer.x+I0-J0>$0){if(j0){let w0=n,C0=this._activeBuffer.x-J0;for(this._activeBuffer.x=J0,this._activeBuffer.y++,this._activeBuffer.y===this._activeBuffer.scrollBottom+1?(this._activeBuffer.y--,this._bufferService.scroll(this._eraseAttrData(),!0)):(this._activeBuffer.y>=this._bufferService.rows&&(this._activeBuffer.y=this._bufferService.rows-1),this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y).isWrapped=!0),n=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y),J0>0&&n instanceof z.BufferLine&&n.copyCellsFrom(w0,C0,0,J0,!1);C0<$0;)w0.setCellFromCodepoint(C0++,0,1,M0)}else if(this._activeBuffer.x=$0-1,I0===2)continue}if(F0&&this._activeBuffer.x){let w0=n.getWidth(this._activeBuffer.x-1)?1:2;n.addCodepointToCell(this._activeBuffer.x-w0,A0,I0);for(let C0=I0-J0;--C0>=0;)n.setCellFromCodepoint(this._activeBuffer.x++,0,0,M0)}else if(Q0&&(n.insertCells(this._activeBuffer.x,I0-J0,this._activeBuffer.getNullCell(M0)),n.getWidth($0-1)===2&&n.setCellFromCodepoint($0-1,H.NULL_CELL_CODE,H.NULL_CELL_WIDTH,M0)),n.setCellFromCodepoint(this._activeBuffer.x++,A0,I0,M0),I0>0)for(;--I0;)n.setCellFromCodepoint(this._activeBuffer.x++,0,0,M0)}this._parser.precedingJoinState=a,this._activeBuffer.x<$0&&r-i>0&&n.getWidth(this._activeBuffer.x)===0&&!n.hasContent(this._activeBuffer.x)&&n.setCellFromCodepoint(this._activeBuffer.x,0,1,M0),this._dirtyRowTracker.markDirty(this._activeBuffer.y)}registerCsiHandler(g,i){return g.final!=="t"||g.prefix||g.intermediates?this._parser.registerCsiHandler(g,i):this._parser.registerCsiHandler(g,(r)=>!h(r.params[0],this._optionsService.rawOptions.windowOptions)||i(r))}registerDcsHandler(g,i){return this._parser.registerDcsHandler(g,new j.DcsHandler(i))}registerEscHandler(g,i){return this._parser.registerEscHandler(g,i)}registerOscHandler(g,i){return this._parser.registerOscHandler(g,new L.OscHandler(i))}bell(){return this._onRequestBell.fire(),!0}lineFeed(){return this._dirtyRowTracker.markDirty(this._activeBuffer.y),this._optionsService.rawOptions.convertEol&&(this._activeBuffer.x=0),this._activeBuffer.y++,this._activeBuffer.y===this._activeBuffer.scrollBottom+1?(this._activeBuffer.y--,this._bufferService.scroll(this._eraseAttrData())):this._activeBuffer.y>=this._bufferService.rows?this._activeBuffer.y=this._bufferService.rows-1:this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y).isWrapped=!1,this._activeBuffer.x>=this._bufferService.cols&&this._activeBuffer.x--,this._dirtyRowTracker.markDirty(this._activeBuffer.y),this._onLineFeed.fire(),!0}carriageReturn(){return this._activeBuffer.x=0,!0}backspace(){if(!this._coreService.decPrivateModes.reverseWraparound)return this._restrictCursor(),this._activeBuffer.x>0&&this._activeBuffer.x--,!0;if(this._restrictCursor(this._bufferService.cols),this._activeBuffer.x>0)this._activeBuffer.x--;else if(this._activeBuffer.x===0&&this._activeBuffer.y>this._activeBuffer.scrollTop&&this._activeBuffer.y<=this._activeBuffer.scrollBottom&&this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y)?.isWrapped){this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y).isWrapped=!1,this._activeBuffer.y--,this._activeBuffer.x=this._bufferService.cols-1;let g=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);g.hasWidth(this._activeBuffer.x)&&!g.hasContent(this._activeBuffer.x)&&this._activeBuffer.x--}return this._restrictCursor(),!0}tab(){if(this._activeBuffer.x>=this._bufferService.cols)return!0;let g=this._activeBuffer.x;return this._activeBuffer.x=this._activeBuffer.nextStop(),this._optionsService.rawOptions.screenReaderMode&&this._onA11yTab.fire(this._activeBuffer.x-g),!0}shiftOut(){return this._charsetService.setgLevel(1),!0}shiftIn(){return this._charsetService.setgLevel(0),!0}_restrictCursor(g=this._bufferService.cols-1){this._activeBuffer.x=Math.min(g,Math.max(0,this._activeBuffer.x)),this._activeBuffer.y=this._coreService.decPrivateModes.origin?Math.min(this._activeBuffer.scrollBottom,Math.max(this._activeBuffer.scrollTop,this._activeBuffer.y)):Math.min(this._bufferService.rows-1,Math.max(0,this._activeBuffer.y)),this._dirtyRowTracker.markDirty(this._activeBuffer.y)}_setCursor(g,i){this._dirtyRowTracker.markDirty(this._activeBuffer.y),this._coreService.decPrivateModes.origin?(this._activeBuffer.x=g,this._activeBuffer.y=this._activeBuffer.scrollTop+i):(this._activeBuffer.x=g,this._activeBuffer.y=i),this._restrictCursor(),this._dirtyRowTracker.markDirty(this._activeBuffer.y)}_moveCursor(g,i){this._restrictCursor(),this._setCursor(this._activeBuffer.x+g,this._activeBuffer.y+i)}cursorUp(g){let i=this._activeBuffer.y-this._activeBuffer.scrollTop;return i>=0?this._moveCursor(0,-Math.min(i,g.params[0]||1)):this._moveCursor(0,-(g.params[0]||1)),!0}cursorDown(g){let i=this._activeBuffer.scrollBottom-this._activeBuffer.y;return i>=0?this._moveCursor(0,Math.min(i,g.params[0]||1)):this._moveCursor(0,g.params[0]||1),!0}cursorForward(g){return this._moveCursor(g.params[0]||1,0),!0}cursorBackward(g){return this._moveCursor(-(g.params[0]||1),0),!0}cursorNextLine(g){return this.cursorDown(g),this._activeBuffer.x=0,!0}cursorPrecedingLine(g){return this.cursorUp(g),this._activeBuffer.x=0,!0}cursorCharAbsolute(g){return this._setCursor((g.params[0]||1)-1,this._activeBuffer.y),!0}cursorPosition(g){return this._setCursor(g.length>=2?(g.params[1]||1)-1:0,(g.params[0]||1)-1),!0}charPosAbsolute(g){return this._setCursor((g.params[0]||1)-1,this._activeBuffer.y),!0}hPositionRelative(g){return this._moveCursor(g.params[0]||1,0),!0}linePosAbsolute(g){return this._setCursor(this._activeBuffer.x,(g.params[0]||1)-1),!0}vPositionRelative(g){return this._moveCursor(0,g.params[0]||1),!0}hVPosition(g){return this.cursorPosition(g),!0}tabClear(g){let i=g.params[0];return i===0?delete this._activeBuffer.tabs[this._activeBuffer.x]:i===3&&(this._activeBuffer.tabs={}),!0}cursorForwardTab(g){if(this._activeBuffer.x>=this._bufferService.cols)return!0;let i=g.params[0]||1;for(;i--;)this._activeBuffer.x=this._activeBuffer.nextStop();return!0}cursorBackwardTab(g){if(this._activeBuffer.x>=this._bufferService.cols)return!0;let i=g.params[0]||1;for(;i--;)this._activeBuffer.x=this._activeBuffer.prevStop();return!0}selectProtected(g){let i=g.params[0];return i===1&&(this._curAttrData.bg|=536870912),i!==2&&i!==0||(this._curAttrData.bg&=-536870913),!0}_eraseInBufferLine(g,i,r,A0=!1,I0=!1){let E0=this._activeBuffer.lines.get(this._activeBuffer.ybase+g);E0.replaceCells(i,r,this._activeBuffer.getNullCell(this._eraseAttrData()),I0),A0&&(E0.isWrapped=!1)}_resetBufferLine(g,i=!1){let r=this._activeBuffer.lines.get(this._activeBuffer.ybase+g);r&&(r.fill(this._activeBuffer.getNullCell(this._eraseAttrData()),i),this._bufferService.buffer.clearMarkers(this._activeBuffer.ybase+g),r.isWrapped=!1)}eraseInDisplay(g,i=!1){let r;switch(this._restrictCursor(this._bufferService.cols),g.params[0]){case 0:for(r=this._activeBuffer.y,this._dirtyRowTracker.markDirty(r),this._eraseInBufferLine(r++,this._activeBuffer.x,this._bufferService.cols,this._activeBuffer.x===0,i);r<this._bufferService.rows;r++)this._resetBufferLine(r,i);this._dirtyRowTracker.markDirty(r);break;case 1:for(r=this._activeBuffer.y,this._dirtyRowTracker.markDirty(r),this._eraseInBufferLine(r,0,this._activeBuffer.x+1,!0,i),this._activeBuffer.x+1>=this._bufferService.cols&&(this._activeBuffer.lines.get(r+1).isWrapped=!1);r--;)this._resetBufferLine(r,i);this._dirtyRowTracker.markDirty(0);break;case 2:for(r=this._bufferService.rows,this._dirtyRowTracker.markDirty(r-1);r--;)this._resetBufferLine(r,i);this._dirtyRowTracker.markDirty(0);break;case 3:let A0=this._activeBuffer.lines.length-this._bufferService.rows;A0>0&&(this._activeBuffer.lines.trimStart(A0),this._activeBuffer.ybase=Math.max(this._activeBuffer.ybase-A0,0),this._activeBuffer.ydisp=Math.max(this._activeBuffer.ydisp-A0,0),this._onScroll.fire(0))}return!0}eraseInLine(g,i=!1){switch(this._restrictCursor(this._bufferService.cols),g.params[0]){case 0:this._eraseInBufferLine(this._activeBuffer.y,this._activeBuffer.x,this._bufferService.cols,this._activeBuffer.x===0,i);break;case 1:this._eraseInBufferLine(this._activeBuffer.y,0,this._activeBuffer.x+1,!1,i);break;case 2:this._eraseInBufferLine(this._activeBuffer.y,0,this._bufferService.cols,!0,i)}return this._dirtyRowTracker.markDirty(this._activeBuffer.y),!0}insertLines(g){this._restrictCursor();let i=g.params[0]||1;if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;let r=this._activeBuffer.ybase+this._activeBuffer.y,A0=this._bufferService.rows-1-this._activeBuffer.scrollBottom,I0=this._bufferService.rows-1+this._activeBuffer.ybase-A0+1;for(;i--;)this._activeBuffer.lines.splice(I0-1,1),this._activeBuffer.lines.splice(r,0,this._activeBuffer.getBlankLine(this._eraseAttrData()));return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.y,this._activeBuffer.scrollBottom),this._activeBuffer.x=0,!0}deleteLines(g){this._restrictCursor();let i=g.params[0]||1;if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;let r=this._activeBuffer.ybase+this._activeBuffer.y,A0;for(A0=this._bufferService.rows-1-this._activeBuffer.scrollBottom,A0=this._bufferService.rows-1+this._activeBuffer.ybase-A0;i--;)this._activeBuffer.lines.splice(r,1),this._activeBuffer.lines.splice(A0,0,this._activeBuffer.getBlankLine(this._eraseAttrData()));return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.y,this._activeBuffer.scrollBottom),this._activeBuffer.x=0,!0}insertChars(g){this._restrictCursor();let i=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);return i&&(i.insertCells(this._activeBuffer.x,g.params[0]||1,this._activeBuffer.getNullCell(this._eraseAttrData())),this._dirtyRowTracker.markDirty(this._activeBuffer.y)),!0}deleteChars(g){this._restrictCursor();let i=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);return i&&(i.deleteCells(this._activeBuffer.x,g.params[0]||1,this._activeBuffer.getNullCell(this._eraseAttrData())),this._dirtyRowTracker.markDirty(this._activeBuffer.y)),!0}scrollUp(g){let i=g.params[0]||1;for(;i--;)this._activeBuffer.lines.splice(this._activeBuffer.ybase+this._activeBuffer.scrollTop,1),this._activeBuffer.lines.splice(this._activeBuffer.ybase+this._activeBuffer.scrollBottom,0,this._activeBuffer.getBlankLine(this._eraseAttrData()));return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}scrollDown(g){let i=g.params[0]||1;for(;i--;)this._activeBuffer.lines.splice(this._activeBuffer.ybase+this._activeBuffer.scrollBottom,1),this._activeBuffer.lines.splice(this._activeBuffer.ybase+this._activeBuffer.scrollTop,0,this._activeBuffer.getBlankLine(z.DEFAULT_ATTR_DATA));return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}scrollLeft(g){if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;let i=g.params[0]||1;for(let r=this._activeBuffer.scrollTop;r<=this._activeBuffer.scrollBottom;++r){let A0=this._activeBuffer.lines.get(this._activeBuffer.ybase+r);A0.deleteCells(0,i,this._activeBuffer.getNullCell(this._eraseAttrData())),A0.isWrapped=!1}return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}scrollRight(g){if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;let i=g.params[0]||1;for(let r=this._activeBuffer.scrollTop;r<=this._activeBuffer.scrollBottom;++r){let A0=this._activeBuffer.lines.get(this._activeBuffer.ybase+r);A0.insertCells(0,i,this._activeBuffer.getNullCell(this._eraseAttrData())),A0.isWrapped=!1}return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}insertColumns(g){if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;let i=g.params[0]||1;for(let r=this._activeBuffer.scrollTop;r<=this._activeBuffer.scrollBottom;++r){let A0=this._activeBuffer.lines.get(this._activeBuffer.ybase+r);A0.insertCells(this._activeBuffer.x,i,this._activeBuffer.getNullCell(this._eraseAttrData())),A0.isWrapped=!1}return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}deleteColumns(g){if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;let i=g.params[0]||1;for(let r=this._activeBuffer.scrollTop;r<=this._activeBuffer.scrollBottom;++r){let A0=this._activeBuffer.lines.get(this._activeBuffer.ybase+r);A0.deleteCells(this._activeBuffer.x,i,this._activeBuffer.getNullCell(this._eraseAttrData())),A0.isWrapped=!1}return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}eraseChars(g){this._restrictCursor();let i=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);return i&&(i.replaceCells(this._activeBuffer.x,this._activeBuffer.x+(g.params[0]||1),this._activeBuffer.getNullCell(this._eraseAttrData())),this._dirtyRowTracker.markDirty(this._activeBuffer.y)),!0}repeatPrecedingCharacter(g){let i=this._parser.precedingJoinState;if(!i)return!0;let r=g.params[0]||1,A0=O.UnicodeService.extractWidth(i),I0=this._activeBuffer.x-A0,E0=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y).getString(I0),W0=new Uint32Array(E0.length*r),$0=0;for(let Q0=0;Q0<E0.length;){let M0=E0.codePointAt(Q0)||0;W0[$0++]=M0,Q0+=M0>65535?2:1}let j0=$0;for(let Q0=1;Q0<r;++Q0)W0.copyWithin(j0,0,$0),j0+=$0;return this.print(W0,0,j0),!0}sendDeviceAttributesPrimary(g){return g.params[0]>0||(this._is("xterm")||this._is("rxvt-unicode")||this._is("screen")?this._coreService.triggerDataEvent(X.C0.ESC+"[?1;2c"):this._is("linux")&&this._coreService.triggerDataEvent(X.C0.ESC+"[?6c")),!0}sendDeviceAttributesSecondary(g){return g.params[0]>0||(this._is("xterm")?this._coreService.triggerDataEvent(X.C0.ESC+"[>0;276;0c"):this._is("rxvt-unicode")?this._coreService.triggerDataEvent(X.C0.ESC+"[>85;95;0c"):this._is("linux")?this._coreService.triggerDataEvent(g.params[0]+"c"):this._is("screen")&&this._coreService.triggerDataEvent(X.C0.ESC+"[>83;40003;0c")),!0}_is(g){return(this._optionsService.rawOptions.termName+"").indexOf(g)===0}setMode(g){for(let i=0;i<g.length;i++)switch(g.params[i]){case 4:this._coreService.modes.insertMode=!0;break;case 20:this._optionsService.options.convertEol=!0}return!0}setModePrivate(g){for(let i=0;i<g.length;i++)switch(g.params[i]){case 1:this._coreService.decPrivateModes.applicationCursorKeys=!0;break;case 2:this._charsetService.setgCharset(0,G.DEFAULT_CHARSET),this._charsetService.setgCharset(1,G.DEFAULT_CHARSET),this._charsetService.setgCharset(2,G.DEFAULT_CHARSET),this._charsetService.setgCharset(3,G.DEFAULT_CHARSET);break;case 3:this._optionsService.rawOptions.windowOptions.setWinLines&&(this._bufferService.resize(132,this._bufferService.rows),this._onRequestReset.fire());break;case 6:this._coreService.decPrivateModes.origin=!0,this._setCursor(0,0);break;case 7:this._coreService.decPrivateModes.wraparound=!0;break;case 12:this._optionsService.options.cursorBlink=!0;break;case 45:this._coreService.decPrivateModes.reverseWraparound=!0;break;case 66:this._logService.debug("Serial port requested application keypad."),this._coreService.decPrivateModes.applicationKeypad=!0,this._onRequestSyncScrollBar.fire();break;case 9:this._coreMouseService.activeProtocol="X10";break;case 1000:this._coreMouseService.activeProtocol="VT200";break;case 1002:this._coreMouseService.activeProtocol="DRAG";break;case 1003:this._coreMouseService.activeProtocol="ANY";break;case 1004:this._coreService.decPrivateModes.sendFocus=!0,this._onRequestSendFocus.fire();break;case 1005:this._logService.debug("DECSET 1005 not supported (see #2507)");break;case 1006:this._coreMouseService.activeEncoding="SGR";break;case 1015:this._logService.debug("DECSET 1015 not supported (see #2507)");break;case 1016:this._coreMouseService.activeEncoding="SGR_PIXELS";break;case 25:this._coreService.isCursorHidden=!1;break;case 1048:this.saveCursor();break;case 1049:this.saveCursor();case 47:case 1047:this._bufferService.buffers.activateAltBuffer(this._eraseAttrData()),this._coreService.isCursorInitialized=!0,this._onRequestRefreshRows.fire(0,this._bufferService.rows-1),this._onRequestSyncScrollBar.fire();break;case 2004:this._coreService.decPrivateModes.bracketedPasteMode=!0}return!0}resetMode(g){for(let i=0;i<g.length;i++)switch(g.params[i]){case 4:this._coreService.modes.insertMode=!1;break;case 20:this._optionsService.options.convertEol=!1}return!0}resetModePrivate(g){for(let i=0;i<g.length;i++)switch(g.params[i]){case 1:this._coreService.decPrivateModes.applicationCursorKeys=!1;break;case 3:this._optionsService.rawOptions.windowOptions.setWinLines&&(this._bufferService.resize(80,this._bufferService.rows),this._onRequestReset.fire());break;case 6:this._coreService.decPrivateModes.origin=!1,this._setCursor(0,0);break;case 7:this._coreService.decPrivateModes.wraparound=!1;break;case 12:this._optionsService.options.cursorBlink=!1;break;case 45:this._coreService.decPrivateModes.reverseWraparound=!1;break;case 66:this._logService.debug("Switching back to normal keypad."),this._coreService.decPrivateModes.applicationKeypad=!1,this._onRequestSyncScrollBar.fire();break;case 9:case 1000:case 1002:case 1003:this._coreMouseService.activeProtocol="NONE";break;case 1004:this._coreService.decPrivateModes.sendFocus=!1;break;case 1005:this._logService.debug("DECRST 1005 not supported (see #2507)");break;case 1006:case 1016:this._coreMouseService.activeEncoding="DEFAULT";break;case 1015:this._logService.debug("DECRST 1015 not supported (see #2507)");break;case 25:this._coreService.isCursorHidden=!0;break;case 1048:this.restoreCursor();break;case 1049:case 47:case 1047:this._bufferService.buffers.activateNormalBuffer(),g.params[i]===1049&&this.restoreCursor(),this._coreService.isCursorInitialized=!0,this._onRequestRefreshRows.fire(0,this._bufferService.rows-1),this._onRequestSyncScrollBar.fire();break;case 2004:this._coreService.decPrivateModes.bracketedPasteMode=!1}return!0}requestMode(g,i){let r=this._coreService.decPrivateModes,{activeProtocol:A0,activeEncoding:I0}=this._coreMouseService,E0=this._coreService,{buffers:W0,cols:$0}=this._bufferService,{active:j0,alt:Q0}=W0,M0=this._optionsService.rawOptions,n=(F0)=>F0?1:2,a=g.params[0];return t=a,e=i?a===2?4:a===4?n(E0.modes.insertMode):a===12?3:a===20?n(M0.convertEol):0:a===1?n(r.applicationCursorKeys):a===3?M0.windowOptions.setWinLines?$0===80?2:$0===132?1:0:0:a===6?n(r.origin):a===7?n(r.wraparound):a===8?3:a===9?n(A0==="X10"):a===12?n(M0.cursorBlink):a===25?n(!E0.isCursorHidden):a===45?n(r.reverseWraparound):a===66?n(r.applicationKeypad):a===67?4:a===1000?n(A0==="VT200"):a===1002?n(A0==="DRAG"):a===1003?n(A0==="ANY"):a===1004?n(r.sendFocus):a===1005?4:a===1006?n(I0==="SGR"):a===1015?4:a===1016?n(I0==="SGR_PIXELS"):a===1048?1:a===47||a===1047||a===1049?n(j0===Q0):a===2004?n(r.bracketedPasteMode):0,E0.triggerDataEvent(`${X.C0.ESC}[${i?"":"?"}${t};${e}$y`),!0;var t,e}_updateAttrColor(g,i,r,A0,I0){return i===2?(g|=50331648,g&=-16777216,g|=N.AttributeData.fromColorRGB([r,A0,I0])):i===5&&(g&=-50331904,g|=33554432|255&r),g}_extractColor(g,i,r){let A0=[0,0,-1,0,0,0],I0=0,E0=0;do{if(A0[E0+I0]=g.params[i+E0],g.hasSubParams(i+E0)){let W0=g.getSubParams(i+E0),$0=0;do A0[1]===5&&(I0=1),A0[E0+$0+1+I0]=W0[$0];while(++$0<W0.length&&$0+E0+1+I0<A0.length);break}if(A0[1]===5&&E0+I0>=2||A0[1]===2&&E0+I0>=5)break;A0[1]&&(I0=1)}while(++E0+i<g.length&&E0+I0<A0.length);for(let W0=2;W0<A0.length;++W0)A0[W0]===-1&&(A0[W0]=0);switch(A0[0]){case 38:r.fg=this._updateAttrColor(r.fg,A0[1],A0[3],A0[4],A0[5]);break;case 48:r.bg=this._updateAttrColor(r.bg,A0[1],A0[3],A0[4],A0[5]);break;case 58:r.extended=r.extended.clone(),r.extended.underlineColor=this._updateAttrColor(r.extended.underlineColor,A0[1],A0[3],A0[4],A0[5])}return E0}_processUnderline(g,i){i.extended=i.extended.clone(),(!~g||g>5)&&(g=1),i.extended.underlineStyle=g,i.fg|=268435456,g===0&&(i.fg&=-268435457),i.updateExtended()}_processSGR0(g){g.fg=z.DEFAULT_ATTR_DATA.fg,g.bg=z.DEFAULT_ATTR_DATA.bg,g.extended=g.extended.clone(),g.extended.underlineStyle=0,g.extended.underlineColor&=-67108864,g.updateExtended()}charAttributes(g){if(g.length===1&&g.params[0]===0)return this._processSGR0(this._curAttrData),!0;let i=g.length,r,A0=this._curAttrData;for(let I0=0;I0<i;I0++)r=g.params[I0],r>=30&&r<=37?(A0.fg&=-50331904,A0.fg|=16777216|r-30):r>=40&&r<=47?(A0.bg&=-50331904,A0.bg|=16777216|r-40):r>=90&&r<=97?(A0.fg&=-50331904,A0.fg|=16777224|r-90):r>=100&&r<=107?(A0.bg&=-50331904,A0.bg|=16777224|r-100):r===0?this._processSGR0(A0):r===1?A0.fg|=134217728:r===3?A0.bg|=67108864:r===4?(A0.fg|=268435456,this._processUnderline(g.hasSubParams(I0)?g.getSubParams(I0)[0]:1,A0)):r===5?A0.fg|=536870912:r===7?A0.fg|=67108864:r===8?A0.fg|=1073741824:r===9?A0.fg|=2147483648:r===2?A0.bg|=134217728:r===21?this._processUnderline(2,A0):r===22?(A0.fg&=-134217729,A0.bg&=-134217729):r===23?A0.bg&=-67108865:r===24?(A0.fg&=-268435457,this._processUnderline(0,A0)):r===25?A0.fg&=-536870913:r===27?A0.fg&=-67108865:r===28?A0.fg&=-1073741825:r===29?A0.fg&=2147483647:r===39?(A0.fg&=-67108864,A0.fg|=16777215&z.DEFAULT_ATTR_DATA.fg):r===49?(A0.bg&=-67108864,A0.bg|=16777215&z.DEFAULT_ATTR_DATA.bg):r===38||r===48||r===58?I0+=this._extractColor(g,I0,A0):r===53?A0.bg|=1073741824:r===55?A0.bg&=-1073741825:r===59?(A0.extended=A0.extended.clone(),A0.extended.underlineColor=-1,A0.updateExtended()):r===100?(A0.fg&=-67108864,A0.fg|=16777215&z.DEFAULT_ATTR_DATA.fg,A0.bg&=-67108864,A0.bg|=16777215&z.DEFAULT_ATTR_DATA.bg):this._logService.debug("Unknown SGR attribute: %d.",r);return!0}deviceStatus(g){switch(g.params[0]){case 5:this._coreService.triggerDataEvent(`${X.C0.ESC}[0n`);break;case 6:let i=this._activeBuffer.y+1,r=this._activeBuffer.x+1;this._coreService.triggerDataEvent(`${X.C0.ESC}[${i};${r}R`)}return!0}deviceStatusPrivate(g){if(g.params[0]===6){let i=this._activeBuffer.y+1,r=this._activeBuffer.x+1;this._coreService.triggerDataEvent(`${X.C0.ESC}[?${i};${r}R`)}return!0}softReset(g){return this._coreService.isCursorHidden=!1,this._onRequestSyncScrollBar.fire(),this._activeBuffer.scrollTop=0,this._activeBuffer.scrollBottom=this._bufferService.rows-1,this._curAttrData=z.DEFAULT_ATTR_DATA.clone(),this._coreService.reset(),this._charsetService.reset(),this._activeBuffer.savedX=0,this._activeBuffer.savedY=this._activeBuffer.ybase,this._activeBuffer.savedCurAttrData.fg=this._curAttrData.fg,this._activeBuffer.savedCurAttrData.bg=this._curAttrData.bg,this._activeBuffer.savedCharset=this._charsetService.charset,this._coreService.decPrivateModes.origin=!1,!0}setCursorStyle(g){let i=g.params[0]||1;switch(i){case 1:case 2:this._optionsService.options.cursorStyle="block";break;case 3:case 4:this._optionsService.options.cursorStyle="underline";break;case 5:case 6:this._optionsService.options.cursorStyle="bar"}let r=i%2==1;return this._optionsService.options.cursorBlink=r,!0}setScrollRegion(g){let i=g.params[0]||1,r;return(g.length<2||(r=g.params[1])>this._bufferService.rows||r===0)&&(r=this._bufferService.rows),r>i&&(this._activeBuffer.scrollTop=i-1,this._activeBuffer.scrollBottom=r-1,this._setCursor(0,0)),!0}windowOptions(g){if(!h(g.params[0],this._optionsService.rawOptions.windowOptions))return!0;let i=g.length>1?g.params[1]:0;switch(g.params[0]){case 14:i!==2&&this._onRequestWindowsOptionsReport.fire(b.GET_WIN_SIZE_PIXELS);break;case 16:this._onRequestWindowsOptionsReport.fire(b.GET_CELL_SIZE_PIXELS);break;case 18:this._bufferService&&this._coreService.triggerDataEvent(`${X.C0.ESC}[8;${this._bufferService.rows};${this._bufferService.cols}t`);break;case 22:i!==0&&i!==2||(this._windowTitleStack.push(this._windowTitle),this._windowTitleStack.length>10&&this._windowTitleStack.shift()),i!==0&&i!==1||(this._iconNameStack.push(this._iconName),this._iconNameStack.length>10&&this._iconNameStack.shift());break;case 23:i!==0&&i!==2||this._windowTitleStack.length&&this.setTitle(this._windowTitleStack.pop()),i!==0&&i!==1||this._iconNameStack.length&&this.setIconName(this._iconNameStack.pop())}return!0}saveCursor(g){return this._activeBuffer.savedX=this._activeBuffer.x,this._activeBuffer.savedY=this._activeBuffer.ybase+this._activeBuffer.y,this._activeBuffer.savedCurAttrData.fg=this._curAttrData.fg,this._activeBuffer.savedCurAttrData.bg=this._curAttrData.bg,this._activeBuffer.savedCharset=this._charsetService.charset,!0}restoreCursor(g){return this._activeBuffer.x=this._activeBuffer.savedX||0,this._activeBuffer.y=Math.max(this._activeBuffer.savedY-this._activeBuffer.ybase,0),this._curAttrData.fg=this._activeBuffer.savedCurAttrData.fg,this._curAttrData.bg=this._activeBuffer.savedCurAttrData.bg,this._charsetService.charset=this._savedCharset,this._activeBuffer.savedCharset&&(this._charsetService.charset=this._activeBuffer.savedCharset),this._restrictCursor(),!0}setTitle(g){return this._windowTitle=g,this._onTitleChange.fire(g),!0}setIconName(g){return this._iconName=g,!0}setOrReportIndexedColor(g){let i=[],r=g.split(";");for(;r.length>1;){let A0=r.shift(),I0=r.shift();if(/^\d+$/.exec(A0)){let E0=parseInt(A0);if(c(E0))if(I0==="?")i.push({type:0,index:E0});else{let W0=(0,k.parseColor)(I0);W0&&i.push({type:1,index:E0,color:W0})}}}return i.length&&this._onColor.fire(i),!0}setHyperlink(g){let i=g.split(";");return!(i.length<2)&&(i[1]?this._createHyperlink(i[0],i[1]):!i[0]&&this._finishHyperlink())}_createHyperlink(g,i){this._getCurrentLinkId()&&this._finishHyperlink();let r=g.split(":"),A0,I0=r.findIndex((E0)=>E0.startsWith("id="));return I0!==-1&&(A0=r[I0].slice(3)||void 0),this._curAttrData.extended=this._curAttrData.extended.clone(),this._curAttrData.extended.urlId=this._oscLinkService.registerLink({id:A0,uri:i}),this._curAttrData.updateExtended(),!0}_finishHyperlink(){return this._curAttrData.extended=this._curAttrData.extended.clone(),this._curAttrData.extended.urlId=0,this._curAttrData.updateExtended(),!0}_setOrReportSpecialColor(g,i){let r=g.split(";");for(let A0=0;A0<r.length&&!(i>=this._specialColors.length);++A0,++i)if(r[A0]==="?")this._onColor.fire([{type:0,index:this._specialColors[i]}]);else{let I0=(0,k.parseColor)(r[A0]);I0&&this._onColor.fire([{type:1,index:this._specialColors[i],color:I0}])}return!0}setOrReportFgColor(g){return this._setOrReportSpecialColor(g,0)}setOrReportBgColor(g){return this._setOrReportSpecialColor(g,1)}setOrReportCursorColor(g){return this._setOrReportSpecialColor(g,2)}restoreIndexedColor(g){if(!g)return this._onColor.fire([{type:2}]),!0;let i=[],r=g.split(";");for(let A0=0;A0<r.length;++A0)if(/^\d+$/.exec(r[A0])){let I0=parseInt(r[A0]);c(I0)&&i.push({type:2,index:I0})}return i.length&&this._onColor.fire(i),!0}restoreFgColor(g){return this._onColor.fire([{type:2,index:256}]),!0}restoreBgColor(g){return this._onColor.fire([{type:2,index:257}]),!0}restoreCursorColor(g){return this._onColor.fire([{type:2,index:258}]),!0}nextLine(){return this._activeBuffer.x=0,this.index(),!0}keypadApplicationMode(){return this._logService.debug("Serial port requested application keypad."),this._coreService.decPrivateModes.applicationKeypad=!0,this._onRequestSyncScrollBar.fire(),!0}keypadNumericMode(){return this._logService.debug("Switching back to normal keypad."),this._coreService.decPrivateModes.applicationKeypad=!1,this._onRequestSyncScrollBar.fire(),!0}selectDefaultCharset(){return this._charsetService.setgLevel(0),this._charsetService.setgCharset(0,G.DEFAULT_CHARSET),!0}selectCharset(g){return g.length!==2?(this.selectDefaultCharset(),!0):(g[0]==="/"||this._charsetService.setgCharset(_[g[0]],G.CHARSETS[g[1]]||G.DEFAULT_CHARSET),!0)}index(){return this._restrictCursor(),this._activeBuffer.y++,this._activeBuffer.y===this._activeBuffer.scrollBottom+1?(this._activeBuffer.y--,this._bufferService.scroll(this._eraseAttrData())):this._activeBuffer.y>=this._bufferService.rows&&(this._activeBuffer.y=this._bufferService.rows-1),this._restrictCursor(),!0}tabSet(){return this._activeBuffer.tabs[this._activeBuffer.x]=!0,!0}reverseIndex(){if(this._restrictCursor(),this._activeBuffer.y===this._activeBuffer.scrollTop){let g=this._activeBuffer.scrollBottom-this._activeBuffer.scrollTop;this._activeBuffer.lines.shiftElements(this._activeBuffer.ybase+this._activeBuffer.y,g,1),this._activeBuffer.lines.set(this._activeBuffer.ybase+this._activeBuffer.y,this._activeBuffer.getBlankLine(this._eraseAttrData())),this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom)}else this._activeBuffer.y--,this._restrictCursor();return!0}fullReset(){return this._parser.reset(),this._onRequestReset.fire(),!0}reset(){this._curAttrData=z.DEFAULT_ATTR_DATA.clone(),this._eraseAttrDataInternal=z.DEFAULT_ATTR_DATA.clone()}_eraseAttrData(){return this._eraseAttrDataInternal.bg&=-67108864,this._eraseAttrDataInternal.bg|=67108863&this._curAttrData.bg,this._eraseAttrDataInternal}setgLevel(g){return this._charsetService.setgLevel(g),!0}screenAlignmentPattern(){let g=new q.CellData;g.content=4194373,g.fg=this._curAttrData.fg,g.bg=this._curAttrData.bg,this._setCursor(0,0);for(let i=0;i<this._bufferService.rows;++i){let r=this._activeBuffer.ybase+this._activeBuffer.y+i,A0=this._activeBuffer.lines.get(r);A0&&(A0.fill(g),A0.isWrapped=!1)}return this._dirtyRowTracker.markAllDirty(),this._setCursor(0,0),!0}requestStatusString(g,i){let r=this._bufferService.buffer,A0=this._optionsService.rawOptions;return((I0)=>(this._coreService.triggerDataEvent(`${X.C0.ESC}${I0}${X.C0.ESC}\\`),!0))(g==='"q'?`P1$r${this._curAttrData.isProtected()?1:0}"q`:g==='"p'?'P1$r61;1"p':g==="r"?`P1$r${r.scrollTop+1};${r.scrollBottom+1}r`:g==="m"?"P1$r0m":g===" q"?`P1$r${{block:2,underline:4,bar:6}[A0.cursorStyle]-(A0.cursorBlink?1:0)} q`:"P0$r")}markRangeDirty(g,i){this._dirtyRowTracker.markRangeDirty(g,i)}}Y.InputHandler=y;let p=class{constructor(g){this._bufferService=g,this.clearRange()}clearRange(){this.start=this._bufferService.buffer.y,this.end=this._bufferService.buffer.y}markDirty(g){g<this.start?this.start=g:g>this.end&&(this.end=g)}markRangeDirty(g,i){g>i&&(v=g,g=i,i=v),g<this.start&&(this.start=g),i>this.end&&(this.end=i)}markAllDirty(){this.markRangeDirty(0,this._bufferService.rows-1)}};function c(g){return 0<=g&&g<256}p=Z([U(0,w.IBufferService)],p)},844:(F,Y)=>{function E(Z){for(let U of Z)U.dispose();Z.length=0}Object.defineProperty(Y,"__esModule",{value:!0}),Y.getDisposeArrayDisposable=Y.disposeArray=Y.toDisposable=Y.MutableDisposable=Y.Disposable=void 0,Y.Disposable=class{constructor(){this._disposables=[],this._isDisposed=!1}dispose(){this._isDisposed=!0;for(let Z of this._disposables)Z.dispose();this._disposables.length=0}register(Z){return this._disposables.push(Z),Z}unregister(Z){let U=this._disposables.indexOf(Z);U!==-1&&this._disposables.splice(U,1)}},Y.MutableDisposable=class{constructor(){this._isDisposed=!1}get value(){return this._isDisposed?void 0:this._value}set value(Z){this._isDisposed||Z===this._value||(this._value?.dispose(),this._value=Z)}clear(){this.value=void 0}dispose(){this._isDisposed=!0,this._value?.dispose(),this._value=void 0}},Y.toDisposable=function(Z){return{dispose:Z}},Y.disposeArray=E,Y.getDisposeArrayDisposable=function(Z){return{dispose:()=>E(Z)}}},114:(F,Y)=>{Object.defineProperty(Y,"__esModule",{value:!0}),Y.isChromeOS=Y.isLinux=Y.isWindows=Y.isIphone=Y.isIpad=Y.isMac=Y.getSafariVersion=Y.isSafari=Y.isLegacyEdge=Y.isFirefox=Y.isNode=void 0,Y.isNode=typeof process<"u"&&"title"in process;let E=Y.isNode?"node":navigator.userAgent,Z=Y.isNode?"node":navigator.platform;Y.isFirefox=E.includes("Firefox"),Y.isLegacyEdge=E.includes("Edge"),Y.isSafari=/^((?!chrome|android).)*safari/i.test(E),Y.getSafariVersion=function(){if(!Y.isSafari)return 0;let U=E.match(/Version\/(\d+)/);return U===null||U.length<2?0:parseInt(U[1])},Y.isMac=["Macintosh","MacIntel","MacPPC","Mac68K"].includes(Z),Y.isIpad=Z==="iPad",Y.isIphone=Z==="iPhone",Y.isWindows=["Windows","Win16","Win32","WinCE"].includes(Z),Y.isLinux=Z.indexOf("Linux")>=0,Y.isChromeOS=/\bCrOS\b/.test(E)},226:(F,Y,E)=>{Object.defineProperty(Y,"__esModule",{value:!0}),Y.DebouncedIdleTask=Y.IdleTaskQueue=Y.PriorityTaskQueue=void 0;let Z=E(114);class U{constructor(){this._tasks=[],this._i=0}enqueue(G){this._tasks.push(G),this._start()}flush(){for(;this._i<this._tasks.length;)this._tasks[this._i]()||this._i++;this.clear()}clear(){this._idleCallback&&(this._cancelCallback(this._idleCallback),this._idleCallback=void 0),this._i=0,this._tasks.length=0}_start(){this._idleCallback||(this._idleCallback=this._requestCallback(this._process.bind(this)))}_process(G){this._idleCallback=void 0;let V=0,K=0,I=G.timeRemaining(),z=0;for(;this._i<this._tasks.length;){if(V=Date.now(),this._tasks[this._i]()||this._i++,V=Math.max(1,Date.now()-V),K=Math.max(V,K),z=G.timeRemaining(),1.5*K>z)return I-V<-20&&console.warn(`task queue exceeded allotted deadline by ${Math.abs(Math.round(I-V))}ms`),void this._start();I=z}this.clear()}}class X extends U{_requestCallback(G){return setTimeout(()=>G(this._createDeadline(16)))}_cancelCallback(G){clearTimeout(G)}_createDeadline(G){let V=Date.now()+G;return{timeRemaining:()=>Math.max(0,V-Date.now())}}}Y.PriorityTaskQueue=X,Y.IdleTaskQueue=!Z.isNode&&"requestIdleCallback"in window?class extends U{_requestCallback(G){return requestIdleCallback(G)}_cancelCallback(G){cancelIdleCallback(G)}}:X,Y.DebouncedIdleTask=class{constructor(){this._queue=new Y.IdleTaskQueue}set(G){this._queue.clear(),this._queue.enqueue(G)}flush(){this._queue.flush()}}},282:(F,Y,E)=>{Object.defineProperty(Y,"__esModule",{value:!0}),Y.updateWindowsModeWrappedState=void 0;let Z=E(643);Y.updateWindowsModeWrappedState=function(U){let X=U.buffer.lines.get(U.buffer.ybase+U.buffer.y-1),G=X?.get(U.cols-1),V=U.buffer.lines.get(U.buffer.ybase+U.buffer.y);V&&G&&(V.isWrapped=G[Z.CHAR_DATA_CODE_INDEX]!==Z.NULL_CELL_CODE&&G[Z.CHAR_DATA_CODE_INDEX]!==Z.WHITESPACE_CELL_CODE)}},734:(F,Y)=>{Object.defineProperty(Y,"__esModule",{value:!0}),Y.ExtendedAttrs=Y.AttributeData=void 0;class E{constructor(){this.fg=0,this.bg=0,this.extended=new Z}static toColorRGB(U){return[U>>>16&255,U>>>8&255,255&U]}static fromColorRGB(U){return(255&U[0])<<16|(255&U[1])<<8|255&U[2]}clone(){let U=new E;return U.fg=this.fg,U.bg=this.bg,U.extended=this.extended.clone(),U}isInverse(){return 67108864&this.fg}isBold(){return 134217728&this.fg}isUnderline(){return this.hasExtendedAttrs()&&this.extended.underlineStyle!==0?1:268435456&this.fg}isBlink(){return 536870912&this.fg}isInvisible(){return 1073741824&this.fg}isItalic(){return 67108864&this.bg}isDim(){return 134217728&this.bg}isStrikethrough(){return 2147483648&this.fg}isProtected(){return 536870912&this.bg}isOverline(){return 1073741824&this.bg}getFgColorMode(){return 50331648&this.fg}getBgColorMode(){return 50331648&this.bg}isFgRGB(){return(50331648&this.fg)==50331648}isBgRGB(){return(50331648&this.bg)==50331648}isFgPalette(){return(50331648&this.fg)==16777216||(50331648&this.fg)==33554432}isBgPalette(){return(50331648&this.bg)==16777216||(50331648&this.bg)==33554432}isFgDefault(){return(50331648&this.fg)==0}isBgDefault(){return(50331648&this.bg)==0}isAttributeDefault(){return this.fg===0&&this.bg===0}getFgColor(){switch(50331648&this.fg){case 16777216:case 33554432:return 255&this.fg;case 50331648:return 16777215&this.fg;default:return-1}}getBgColor(){switch(50331648&this.bg){case 16777216:case 33554432:return 255&this.bg;case 50331648:return 16777215&this.bg;default:return-1}}hasExtendedAttrs(){return 268435456&this.bg}updateExtended(){this.extended.isEmpty()?this.bg&=-268435457:this.bg|=268435456}getUnderlineColor(){if(268435456&this.bg&&~this.extended.underlineColor)switch(50331648&this.extended.underlineColor){case 16777216:case 33554432:return 255&this.extended.underlineColor;case 50331648:return 16777215&this.extended.underlineColor;default:return this.getFgColor()}return this.getFgColor()}getUnderlineColorMode(){return 268435456&this.bg&&~this.extended.underlineColor?50331648&this.extended.underlineColor:this.getFgColorMode()}isUnderlineColorRGB(){return 268435456&this.bg&&~this.extended.underlineColor?(50331648&this.extended.underlineColor)==50331648:this.isFgRGB()}isUnderlineColorPalette(){return 268435456&this.bg&&~this.extended.underlineColor?(50331648&this.extended.underlineColor)==16777216||(50331648&this.extended.underlineColor)==33554432:this.isFgPalette()}isUnderlineColorDefault(){return 268435456&this.bg&&~this.extended.underlineColor?(50331648&this.extended.underlineColor)==0:this.isFgDefault()}getUnderlineStyle(){return 268435456&this.fg?268435456&this.bg?this.extended.underlineStyle:1:0}getUnderlineVariantOffset(){return this.extended.underlineVariantOffset}}Y.AttributeData=E;class Z{get ext(){return this._urlId?-469762049&this._ext|this.underlineStyle<<26:this._ext}set ext(U){this._ext=U}get underlineStyle(){return this._urlId?5:(469762048&this._ext)>>26}set underlineStyle(U){this._ext&=-469762049,this._ext|=U<<26&469762048}get underlineColor(){return 67108863&this._ext}set underlineColor(U){this._ext&=-67108864,this._ext|=67108863&U}get urlId(){return this._urlId}set urlId(U){this._urlId=U}get underlineVariantOffset(){let U=(3758096384&this._ext)>>29;return U<0?4294967288^U:U}set underlineVariantOffset(U){this._ext&=536870911,this._ext|=U<<29&3758096384}constructor(U=0,X=0){this._ext=0,this._urlId=0,this._ext=U,this._urlId=X}clone(){return new Z(this._ext,this._urlId)}isEmpty(){return this.underlineStyle===0&&this._urlId===0}}Y.ExtendedAttrs=Z},92:(F,Y,E)=>{Object.defineProperty(Y,"__esModule",{value:!0}),Y.Buffer=Y.MAX_BUFFER_SIZE=void 0;let Z=E(349),U=E(226),X=E(734),G=E(437),V=E(634),K=E(511),I=E(643),z=E(863),W=E(116);Y.MAX_BUFFER_SIZE=4294967295,Y.Buffer=class{constructor(H,q,N){this._hasScrollback=H,this._optionsService=q,this._bufferService=N,this.ydisp=0,this.ybase=0,this.y=0,this.x=0,this.tabs={},this.savedY=0,this.savedX=0,this.savedCurAttrData=G.DEFAULT_ATTR_DATA.clone(),this.savedCharset=W.DEFAULT_CHARSET,this.markers=[],this._nullCell=K.CellData.fromCharData([0,I.NULL_CELL_CHAR,I.NULL_CELL_WIDTH,I.NULL_CELL_CODE]),this._whitespaceCell=K.CellData.fromCharData([0,I.WHITESPACE_CELL_CHAR,I.WHITESPACE_CELL_WIDTH,I.WHITESPACE_CELL_CODE]),this._isClearing=!1,this._memoryCleanupQueue=new U.IdleTaskQueue,this._memoryCleanupPosition=0,this._cols=this._bufferService.cols,this._rows=this._bufferService.rows,this.lines=new Z.CircularList(this._getCorrectBufferLength(this._rows)),this.scrollTop=0,this.scrollBottom=this._rows-1,this.setupTabStops()}getNullCell(H){return H?(this._nullCell.fg=H.fg,this._nullCell.bg=H.bg,this._nullCell.extended=H.extended):(this._nullCell.fg=0,this._nullCell.bg=0,this._nullCell.extended=new X.ExtendedAttrs),this._nullCell}getWhitespaceCell(H){return H?(this._whitespaceCell.fg=H.fg,this._whitespaceCell.bg=H.bg,this._whitespaceCell.extended=H.extended):(this._whitespaceCell.fg=0,this._whitespaceCell.bg=0,this._whitespaceCell.extended=new X.ExtendedAttrs),this._whitespaceCell}getBlankLine(H,q){return new G.BufferLine(this._bufferService.cols,this.getNullCell(H),q)}get hasScrollback(){return this._hasScrollback&&this.lines.maxLength>this._rows}get isCursorInViewport(){let H=this.ybase+this.y-this.ydisp;return H>=0&&H<this._rows}_getCorrectBufferLength(H){if(!this._hasScrollback)return H;let q=H+this._optionsService.rawOptions.scrollback;return q>Y.MAX_BUFFER_SIZE?Y.MAX_BUFFER_SIZE:q}fillViewportRows(H){if(this.lines.length===0){H===void 0&&(H=G.DEFAULT_ATTR_DATA);let q=this._rows;for(;q--;)this.lines.push(this.getBlankLine(H))}}clear(){this.ydisp=0,this.ybase=0,this.y=0,this.x=0,this.lines=new Z.CircularList(this._getCorrectBufferLength(this._rows)),this.scrollTop=0,this.scrollBottom=this._rows-1,this.setupTabStops()}resize(H,q){let N=this.getNullCell(G.DEFAULT_ATTR_DATA),w=0,O=this._getCorrectBufferLength(q);if(O>this.lines.maxLength&&(this.lines.maxLength=O),this.lines.length>0){if(this._cols<H)for(let j=0;j<this.lines.length;j++)w+=+this.lines.get(j).resize(H,N);let L=0;if(this._rows<q)for(let j=this._rows;j<q;j++)this.lines.length<q+this.ybase&&(this._optionsService.rawOptions.windowsMode||this._optionsService.rawOptions.windowsPty.backend!==void 0||this._optionsService.rawOptions.windowsPty.buildNumber!==void 0?this.lines.push(new G.BufferLine(H,N)):this.ybase>0&&this.lines.length<=this.ybase+this.y+L+1?(this.ybase--,L++,this.ydisp>0&&this.ydisp--):this.lines.push(new G.BufferLine(H,N)));else for(let j=this._rows;j>q;j--)this.lines.length>q+this.ybase&&(this.lines.length>this.ybase+this.y+1?this.lines.pop():(this.ybase++,this.ydisp++));if(O<this.lines.maxLength){let j=this.lines.length-O;j>0&&(this.lines.trimStart(j),this.ybase=Math.max(this.ybase-j,0),this.ydisp=Math.max(this.ydisp-j,0),this.savedY=Math.max(this.savedY-j,0)),this.lines.maxLength=O}this.x=Math.min(this.x,H-1),this.y=Math.min(this.y,q-1),L&&(this.y+=L),this.savedX=Math.min(this.savedX,H-1),this.scrollTop=0}if(this.scrollBottom=q-1,this._isReflowEnabled&&(this._reflow(H,q),this._cols>H))for(let L=0;L<this.lines.length;L++)w+=+this.lines.get(L).resize(H,N);this._cols=H,this._rows=q,this._memoryCleanupQueue.clear(),w>0.1*this.lines.length&&(this._memoryCleanupPosition=0,this._memoryCleanupQueue.enqueue(()=>this._batchedMemoryCleanup()))}_batchedMemoryCleanup(){let H=!0;this._memoryCleanupPosition>=this.lines.length&&(this._memoryCleanupPosition=0,H=!1);let q=0;for(;this._memoryCleanupPosition<this.lines.length;)if(q+=this.lines.get(this._memoryCleanupPosition++).cleanupMemory(),q>100)return!0;return H}get _isReflowEnabled(){let H=this._optionsService.rawOptions.windowsPty;return H&&H.buildNumber?this._hasScrollback&&H.backend==="conpty"&&H.buildNumber>=21376:this._hasScrollback&&!this._optionsService.rawOptions.windowsMode}_reflow(H,q){this._cols!==H&&(H>this._cols?this._reflowLarger(H,q):this._reflowSmaller(H,q))}_reflowLarger(H,q){let N=(0,V.reflowLargerGetLinesToRemove)(this.lines,this._cols,H,this.ybase+this.y,this.getNullCell(G.DEFAULT_ATTR_DATA));if(N.length>0){let w=(0,V.reflowLargerCreateNewLayout)(this.lines,N);(0,V.reflowLargerApplyNewLayout)(this.lines,w.layout),this._reflowLargerAdjustViewport(H,q,w.countRemoved)}}_reflowLargerAdjustViewport(H,q,N){let w=this.getNullCell(G.DEFAULT_ATTR_DATA),O=N;for(;O-- >0;)this.ybase===0?(this.y>0&&this.y--,this.lines.length<q&&this.lines.push(new G.BufferLine(H,w))):(this.ydisp===this.ybase&&this.ydisp--,this.ybase--);this.savedY=Math.max(this.savedY-N,0)}_reflowSmaller(H,q){let N=this.getNullCell(G.DEFAULT_ATTR_DATA),w=[],O=0;for(let L=this.lines.length-1;L>=0;L--){let j=this.lines.get(L);if(!j||!j.isWrapped&&j.getTrimmedLength()<=H)continue;let k=[j];for(;j.isWrapped&&L>0;)j=this.lines.get(--L),k.unshift(j);let _=this.ybase+this.y;if(_>=L&&_<L+k.length)continue;let f=k[k.length-1].getTrimmedLength(),h=(0,V.reflowSmallerGetNewLineLengths)(k,this._cols,H),b=h.length-k.length,v;v=this.ybase===0&&this.y!==this.lines.length-1?Math.max(0,this.y-this.lines.maxLength+b):Math.max(0,this.lines.length-this.lines.maxLength+b);let y=[];for(let A0=0;A0<b;A0++){let I0=this.getBlankLine(G.DEFAULT_ATTR_DATA,!0);y.push(I0)}y.length>0&&(w.push({start:L+k.length+O,newLines:y}),O+=y.length),k.push(...y);let p=h.length-1,c=h[p];c===0&&(p--,c=h[p]);let g=k.length-b-1,i=f;for(;g>=0;){let A0=Math.min(i,c);if(k[p]===void 0)break;if(k[p].copyCellsFrom(k[g],i-A0,c-A0,A0,!0),c-=A0,c===0&&(p--,c=h[p]),i-=A0,i===0){g--;let I0=Math.max(g,0);i=(0,V.getWrappedLineTrimmedLength)(k,I0,this._cols)}}for(let A0=0;A0<k.length;A0++)h[A0]<H&&k[A0].setCell(h[A0],N);let r=b-v;for(;r-- >0;)this.ybase===0?this.y<q-1?(this.y++,this.lines.pop()):(this.ybase++,this.ydisp++):this.ybase<Math.min(this.lines.maxLength,this.lines.length+O)-q&&(this.ybase===this.ydisp&&this.ydisp++,this.ybase++);this.savedY=Math.min(this.savedY+b,this.ybase+q-1)}if(w.length>0){let L=[],j=[];for(let p=0;p<this.lines.length;p++)j.push(this.lines.get(p));let k=this.lines.length,_=k-1,f=0,h=w[f];this.lines.length=Math.min(this.lines.maxLength,this.lines.length+O);let b=0;for(let p=Math.min(this.lines.maxLength-1,k+O-1);p>=0;p--)if(h&&h.start>_+b){for(let c=h.newLines.length-1;c>=0;c--)this.lines.set(p--,h.newLines[c]);p++,L.push({index:_+1,amount:h.newLines.length}),b+=h.newLines.length,h=w[++f]}else this.lines.set(p,j[_--]);let v=0;for(let p=L.length-1;p>=0;p--)L[p].index+=v,this.lines.onInsertEmitter.fire(L[p]),v+=L[p].amount;let y=Math.max(0,k+O-this.lines.maxLength);y>0&&this.lines.onTrimEmitter.fire(y)}}translateBufferLineToString(H,q,N=0,w){let O=this.lines.get(H);return O?O.translateToString(q,N,w):""}getWrappedRangeForLine(H){let q=H,N=H;for(;q>0&&this.lines.get(q).isWrapped;)q--;for(;N+1<this.lines.length&&this.lines.get(N+1).isWrapped;)N++;return{first:q,last:N}}setupTabStops(H){for(H!=null?this.tabs[H]||(H=this.prevStop(H)):(this.tabs={},H=0);H<this._cols;H+=this._optionsService.rawOptions.tabStopWidth)this.tabs[H]=!0}prevStop(H){for(H==null&&(H=this.x);!this.tabs[--H]&&H>0;);return H>=this._cols?this._cols-1:H<0?0:H}nextStop(H){for(H==null&&(H=this.x);!this.tabs[++H]&&H<this._cols;);return H>=this._cols?this._cols-1:H<0?0:H}clearMarkers(H){this._isClearing=!0;for(let q=0;q<this.markers.length;q++)this.markers[q].line===H&&(this.markers[q].dispose(),this.markers.splice(q--,1));this._isClearing=!1}clearAllMarkers(){this._isClearing=!0;for(let H=0;H<this.markers.length;H++)this.markers[H].dispose(),this.markers.splice(H--,1);this._isClearing=!1}addMarker(H){let q=new z.Marker(H);return this.markers.push(q),q.register(this.lines.onTrim((N)=>{q.line-=N,q.line<0&&q.dispose()})),q.register(this.lines.onInsert((N)=>{q.line>=N.index&&(q.line+=N.amount)})),q.register(this.lines.onDelete((N)=>{q.line>=N.index&&q.line<N.index+N.amount&&q.dispose(),q.line>N.index&&(q.line-=N.amount)})),q.register(q.onDispose(()=>this._removeMarker(q))),q}_removeMarker(H){this._isClearing||this.markers.splice(this.markers.indexOf(H),1)}}},437:(F,Y,E)=>{Object.defineProperty(Y,"__esModule",{value:!0}),Y.BufferLine=Y.DEFAULT_ATTR_DATA=void 0;let Z=E(734),U=E(511),X=E(643),G=E(482);Y.DEFAULT_ATTR_DATA=Object.freeze(new Z.AttributeData);let V=0;class K{constructor(I,z,W=!1){this.isWrapped=W,this._combined={},this._extendedAttrs={},this._data=new Uint32Array(3*I);let H=z||U.CellData.fromCharData([0,X.NULL_CELL_CHAR,X.NULL_CELL_WIDTH,X.NULL_CELL_CODE]);for(let q=0;q<I;++q)this.setCell(q,H);this.length=I}get(I){let z=this._data[3*I+0],W=2097151&z;return[this._data[3*I+1],2097152&z?this._combined[I]:W?(0,G.stringFromCodePoint)(W):"",z>>22,2097152&z?this._combined[I].charCodeAt(this._combined[I].length-1):W]}set(I,z){this._data[3*I+1]=z[X.CHAR_DATA_ATTR_INDEX],z[X.CHAR_DATA_CHAR_INDEX].length>1?(this._combined[I]=z[1],this._data[3*I+0]=2097152|I|z[X.CHAR_DATA_WIDTH_INDEX]<<22):this._data[3*I+0]=z[X.CHAR_DATA_CHAR_INDEX].charCodeAt(0)|z[X.CHAR_DATA_WIDTH_INDEX]<<22}getWidth(I){return this._data[3*I+0]>>22}hasWidth(I){return 12582912&this._data[3*I+0]}getFg(I){return this._data[3*I+1]}getBg(I){return this._data[3*I+2]}hasContent(I){return 4194303&this._data[3*I+0]}getCodePoint(I){let z=this._data[3*I+0];return 2097152&z?this._combined[I].charCodeAt(this._combined[I].length-1):2097151&z}isCombined(I){return 2097152&this._data[3*I+0]}getString(I){let z=this._data[3*I+0];return 2097152&z?this._combined[I]:2097151&z?(0,G.stringFromCodePoint)(2097151&z):""}isProtected(I){return 536870912&this._data[3*I+2]}loadCell(I,z){return V=3*I,z.content=this._data[V+0],z.fg=this._data[V+1],z.bg=this._data[V+2],2097152&z.content&&(z.combinedData=this._combined[I]),268435456&z.bg&&(z.extended=this._extendedAttrs[I]),z}setCell(I,z){2097152&z.content&&(this._combined[I]=z.combinedData),268435456&z.bg&&(this._extendedAttrs[I]=z.extended),this._data[3*I+0]=z.content,this._data[3*I+1]=z.fg,this._data[3*I+2]=z.bg}setCellFromCodepoint(I,z,W,H){268435456&H.bg&&(this._extendedAttrs[I]=H.extended),this._data[3*I+0]=z|W<<22,this._data[3*I+1]=H.fg,this._data[3*I+2]=H.bg}addCodepointToCell(I,z,W){let H=this._data[3*I+0];2097152&H?this._combined[I]+=(0,G.stringFromCodePoint)(z):2097151&H?(this._combined[I]=(0,G.stringFromCodePoint)(2097151&H)+(0,G.stringFromCodePoint)(z),H&=-2097152,H|=2097152):H=z|4194304,W&&(H&=-12582913,H|=W<<22),this._data[3*I+0]=H}insertCells(I,z,W){if((I%=this.length)&&this.getWidth(I-1)===2&&this.setCellFromCodepoint(I-1,0,1,W),z<this.length-I){let H=new U.CellData;for(let q=this.length-I-z-1;q>=0;--q)this.setCell(I+z+q,this.loadCell(I+q,H));for(let q=0;q<z;++q)this.setCell(I+q,W)}else for(let H=I;H<this.length;++H)this.setCell(H,W);this.getWidth(this.length-1)===2&&this.setCellFromCodepoint(this.length-1,0,1,W)}deleteCells(I,z,W){if(I%=this.length,z<this.length-I){let H=new U.CellData;for(let q=0;q<this.length-I-z;++q)this.setCell(I+q,this.loadCell(I+z+q,H));for(let q=this.length-z;q<this.length;++q)this.setCell(q,W)}else for(let H=I;H<this.length;++H)this.setCell(H,W);I&&this.getWidth(I-1)===2&&this.setCellFromCodepoint(I-1,0,1,W),this.getWidth(I)!==0||this.hasContent(I)||this.setCellFromCodepoint(I,0,1,W)}replaceCells(I,z,W,H=!1){if(H)for(I&&this.getWidth(I-1)===2&&!this.isProtected(I-1)&&this.setCellFromCodepoint(I-1,0,1,W),z<this.length&&this.getWidth(z-1)===2&&!this.isProtected(z)&&this.setCellFromCodepoint(z,0,1,W);I<z&&I<this.length;)this.isProtected(I)||this.setCell(I,W),I++;else for(I&&this.getWidth(I-1)===2&&this.setCellFromCodepoint(I-1,0,1,W),z<this.length&&this.getWidth(z-1)===2&&this.setCellFromCodepoint(z,0,1,W);I<z&&I<this.length;)this.setCell(I++,W)}resize(I,z){if(I===this.length)return 4*this._data.length*2<this._data.buffer.byteLength;let W=3*I;if(I>this.length){if(this._data.buffer.byteLength>=4*W)this._data=new Uint32Array(this._data.buffer,0,W);else{let H=new Uint32Array(W);H.set(this._data),this._data=H}for(let H=this.length;H<I;++H)this.setCell(H,z)}else{this._data=this._data.subarray(0,W);let H=Object.keys(this._combined);for(let N=0;N<H.length;N++){let w=parseInt(H[N],10);w>=I&&delete this._combined[w]}let q=Object.keys(this._extendedAttrs);for(let N=0;N<q.length;N++){let w=parseInt(q[N],10);w>=I&&delete this._extendedAttrs[w]}}return this.length=I,4*W*2<this._data.buffer.byteLength}cleanupMemory(){if(4*this._data.length*2<this._data.buffer.byteLength){let I=new Uint32Array(this._data.length);return I.set(this._data),this._data=I,1}return 0}fill(I,z=!1){if(z)for(let W=0;W<this.length;++W)this.isProtected(W)||this.setCell(W,I);else{this._combined={},this._extendedAttrs={};for(let W=0;W<this.length;++W)this.setCell(W,I)}}copyFrom(I){this.length!==I.length?this._data=new Uint32Array(I._data):this._data.set(I._data),this.length=I.length,this._combined={};for(let z in I._combined)this._combined[z]=I._combined[z];this._extendedAttrs={};for(let z in I._extendedAttrs)this._extendedAttrs[z]=I._extendedAttrs[z];this.isWrapped=I.isWrapped}clone(){let I=new K(0);I._data=new Uint32Array(this._data),I.length=this.length;for(let z in this._combined)I._combined[z]=this._combined[z];for(let z in this._extendedAttrs)I._extendedAttrs[z]=this._extendedAttrs[z];return I.isWrapped=this.isWrapped,I}getTrimmedLength(){for(let I=this.length-1;I>=0;--I)if(4194303&this._data[3*I+0])return I+(this._data[3*I+0]>>22);return 0}getNoBgTrimmedLength(){for(let I=this.length-1;I>=0;--I)if(4194303&this._data[3*I+0]||50331648&this._data[3*I+2])return I+(this._data[3*I+0]>>22);return 0}copyCellsFrom(I,z,W,H,q){let N=I._data;if(q)for(let O=H-1;O>=0;O--){for(let L=0;L<3;L++)this._data[3*(W+O)+L]=N[3*(z+O)+L];268435456&N[3*(z+O)+2]&&(this._extendedAttrs[W+O]=I._extendedAttrs[z+O])}else for(let O=0;O<H;O++){for(let L=0;L<3;L++)this._data[3*(W+O)+L]=N[3*(z+O)+L];268435456&N[3*(z+O)+2]&&(this._extendedAttrs[W+O]=I._extendedAttrs[z+O])}let w=Object.keys(I._combined);for(let O=0;O<w.length;O++){let L=parseInt(w[O],10);L>=z&&(this._combined[L-z+W]=I._combined[L])}}translateToString(I,z,W,H){z=z??0,W=W??this.length,I&&(W=Math.min(W,this.getTrimmedLength())),H&&(H.length=0);let q="";for(;z<W;){let N=this._data[3*z+0],w=2097151&N,O=2097152&N?this._combined[z]:w?(0,G.stringFromCodePoint)(w):X.WHITESPACE_CELL_CHAR;if(q+=O,H)for(let L=0;L<O.length;++L)H.push(z);z+=N>>22||1}return H&&H.push(z),q}}Y.BufferLine=K},634:(F,Y)=>{function E(Z,U,X){if(U===Z.length-1)return Z[U].getTrimmedLength();let G=!Z[U].hasContent(X-1)&&Z[U].getWidth(X-1)===1,V=Z[U+1].getWidth(0)===2;return G&&V?X-1:X}Object.defineProperty(Y,"__esModule",{value:!0}),Y.getWrappedLineTrimmedLength=Y.reflowSmallerGetNewLineLengths=Y.reflowLargerApplyNewLayout=Y.reflowLargerCreateNewLayout=Y.reflowLargerGetLinesToRemove=void 0,Y.reflowLargerGetLinesToRemove=function(Z,U,X,G,V){let K=[];for(let I=0;I<Z.length-1;I++){let z=I,W=Z.get(++z);if(!W.isWrapped)continue;let H=[Z.get(I)];for(;z<Z.length&&W.isWrapped;)H.push(W),W=Z.get(++z);if(G>=I&&G<z){I+=H.length-1;continue}let q=0,N=E(H,q,U),w=1,O=0;for(;w<H.length;){let j=E(H,w,U),k=j-O,_=X-N,f=Math.min(k,_);H[q].copyCellsFrom(H[w],O,N,f,!1),N+=f,N===X&&(q++,N=0),O+=f,O===j&&(w++,O=0),N===0&&q!==0&&H[q-1].getWidth(X-1)===2&&(H[q].copyCellsFrom(H[q-1],X-1,N++,1,!1),H[q-1].setCell(X-1,V))}H[q].replaceCells(N,X,V);let L=0;for(let j=H.length-1;j>0&&(j>q||H[j].getTrimmedLength()===0);j--)L++;L>0&&(K.push(I+H.length-L),K.push(L)),I+=H.length-1}return K},Y.reflowLargerCreateNewLayout=function(Z,U){let X=[],G=0,V=U[G],K=0;for(let I=0;I<Z.length;I++)if(V===I){let z=U[++G];Z.onDeleteEmitter.fire({index:I-K,amount:z}),I+=z-1,K+=z,V=U[++G]}else X.push(I);return{layout:X,countRemoved:K}},Y.reflowLargerApplyNewLayout=function(Z,U){let X=[];for(let G=0;G<U.length;G++)X.push(Z.get(U[G]));for(let G=0;G<X.length;G++)Z.set(G,X[G]);Z.length=U.length},Y.reflowSmallerGetNewLineLengths=function(Z,U,X){let G=[],V=Z.map((W,H)=>E(Z,H,U)).reduce((W,H)=>W+H),K=0,I=0,z=0;for(;z<V;){if(V-z<X){G.push(V-z);break}K+=X;let W=E(Z,I,U);K>W&&(K-=W,I++);let H=Z[I].getWidth(K-1)===2;H&&K--;let q=H?X-1:X;G.push(q),z+=q}return G},Y.getWrappedLineTrimmedLength=E},295:(F,Y,E)=>{Object.defineProperty(Y,"__esModule",{value:!0}),Y.BufferSet=void 0;let Z=E(460),U=E(844),X=E(92);class G extends U.Disposable{constructor(V,K){super(),this._optionsService=V,this._bufferService=K,this._onBufferActivate=this.register(new Z.EventEmitter),this.onBufferActivate=this._onBufferActivate.event,this.reset(),this.register(this._optionsService.onSpecificOptionChange("scrollback",()=>this.resize(this._bufferService.cols,this._bufferService.rows))),this.register(this._optionsService.onSpecificOptionChange("tabStopWidth",()=>this.setupTabStops()))}reset(){this._normal=new X.Buffer(!0,this._optionsService,this._bufferService),this._normal.fillViewportRows(),this._alt=new X.Buffer(!1,this._optionsService,this._bufferService),this._activeBuffer=this._normal,this._onBufferActivate.fire({activeBuffer:this._normal,inactiveBuffer:this._alt}),this.setupTabStops()}get alt(){return this._alt}get active(){return this._activeBuffer}get normal(){return this._normal}activateNormalBuffer(){this._activeBuffer!==this._normal&&(this._normal.x=this._alt.x,this._normal.y=this._alt.y,this._alt.clearAllMarkers(),this._alt.clear(),this._activeBuffer=this._normal,this._onBufferActivate.fire({activeBuffer:this._normal,inactiveBuffer:this._alt}))}activateAltBuffer(V){this._activeBuffer!==this._alt&&(this._alt.fillViewportRows(V),this._alt.x=this._normal.x,this._alt.y=this._normal.y,this._activeBuffer=this._alt,this._onBufferActivate.fire({activeBuffer:this._alt,inactiveBuffer:this._normal}))}resize(V,K){this._normal.resize(V,K),this._alt.resize(V,K),this.setupTabStops(V)}setupTabStops(V){this._normal.setupTabStops(V),this._alt.setupTabStops(V)}}Y.BufferSet=G},511:(F,Y,E)=>{Object.defineProperty(Y,"__esModule",{value:!0}),Y.CellData=void 0;let Z=E(482),U=E(643),X=E(734);class G extends X.AttributeData{constructor(){super(...arguments),this.content=0,this.fg=0,this.bg=0,this.extended=new X.ExtendedAttrs,this.combinedData=""}static fromCharData(V){let K=new G;return K.setFromCharData(V),K}isCombined(){return 2097152&this.content}getWidth(){return this.content>>22}getChars(){return 2097152&this.content?this.combinedData:2097151&this.content?(0,Z.stringFromCodePoint)(2097151&this.content):""}getCode(){return this.isCombined()?this.combinedData.charCodeAt(this.combinedData.length-1):2097151&this.content}setFromCharData(V){this.fg=V[U.CHAR_DATA_ATTR_INDEX],this.bg=0;let K=!1;if(V[U.CHAR_DATA_CHAR_INDEX].length>2)K=!0;else if(V[U.CHAR_DATA_CHAR_INDEX].length===2){let I=V[U.CHAR_DATA_CHAR_INDEX].charCodeAt(0);if(55296<=I&&I<=56319){let z=V[U.CHAR_DATA_CHAR_INDEX].charCodeAt(1);56320<=z&&z<=57343?this.content=1024*(I-55296)+z-56320+65536|V[U.CHAR_DATA_WIDTH_INDEX]<<22:K=!0}else K=!0}else this.content=V[U.CHAR_DATA_CHAR_INDEX].charCodeAt(0)|V[U.CHAR_DATA_WIDTH_INDEX]<<22;K&&(this.combinedData=V[U.CHAR_DATA_CHAR_INDEX],this.content=2097152|V[U.CHAR_DATA_WIDTH_INDEX]<<22)}getAsCharData(){return[this.fg,this.getChars(),this.getWidth(),this.getCode()]}}Y.CellData=G},643:(F,Y)=>{Object.defineProperty(Y,"__esModule",{value:!0}),Y.WHITESPACE_CELL_CODE=Y.WHITESPACE_CELL_WIDTH=Y.WHITESPACE_CELL_CHAR=Y.NULL_CELL_CODE=Y.NULL_CELL_WIDTH=Y.NULL_CELL_CHAR=Y.CHAR_DATA_CODE_INDEX=Y.CHAR_DATA_WIDTH_INDEX=Y.CHAR_DATA_CHAR_INDEX=Y.CHAR_DATA_ATTR_INDEX=Y.DEFAULT_EXT=Y.DEFAULT_ATTR=Y.DEFAULT_COLOR=void 0,Y.DEFAULT_COLOR=0,Y.DEFAULT_ATTR=256|Y.DEFAULT_COLOR<<9,Y.DEFAULT_EXT=0,Y.CHAR_DATA_ATTR_INDEX=0,Y.CHAR_DATA_CHAR_INDEX=1,Y.CHAR_DATA_WIDTH_INDEX=2,Y.CHAR_DATA_CODE_INDEX=3,Y.NULL_CELL_CHAR="",Y.NULL_CELL_WIDTH=1,Y.NULL_CELL_CODE=0,Y.WHITESPACE_CELL_CHAR=" ",Y.WHITESPACE_CELL_WIDTH=1,Y.WHITESPACE_CELL_CODE=32},863:(F,Y,E)=>{Object.defineProperty(Y,"__esModule",{value:!0}),Y.Marker=void 0;let Z=E(460),U=E(844);class X{get id(){return this._id}constructor(G){this.line=G,this.isDisposed=!1,this._disposables=[],this._id=X._nextId++,this._onDispose=this.register(new Z.EventEmitter),this.onDispose=this._onDispose.event}dispose(){this.isDisposed||(this.isDisposed=!0,this.line=-1,this._onDispose.fire(),(0,U.disposeArray)(this._disposables),this._disposables.length=0)}register(G){return this._disposables.push(G),G}}Y.Marker=X,X._nextId=1},116:(F,Y)=>{Object.defineProperty(Y,"__esModule",{value:!0}),Y.DEFAULT_CHARSET=Y.CHARSETS=void 0,Y.CHARSETS={},Y.DEFAULT_CHARSET=Y.CHARSETS.B,Y.CHARSETS[0]={"`":"◆",a:"▒",b:"␉",c:"␌",d:"␍",e:"␊",f:"°",g:"±",h:"␤",i:"␋",j:"┘",k:"┐",l:"┌",m:"└",n:"┼",o:"⎺",p:"⎻",q:"─",r:"⎼",s:"⎽",t:"├",u:"┤",v:"┴",w:"┬",x:"│",y:"≤",z:"≥","{":"π","|":"≠","}":"£","~":"·"},Y.CHARSETS.A={"#":"£"},Y.CHARSETS.B=void 0,Y.CHARSETS[4]={"#":"£","@":"¾","[":"ij","\\":"½","]":"|","{":"¨","|":"f","}":"¼","~":"´"},Y.CHARSETS.C=Y.CHARSETS[5]={"[":"Ä","\\":"Ö","]":"Å","^":"Ü","`":"é","{":"ä","|":"ö","}":"å","~":"ü"},Y.CHARSETS.R={"#":"£","@":"à","[":"°","\\":"ç","]":"§","{":"é","|":"ù","}":"è","~":"¨"},Y.CHARSETS.Q={"@":"à","[":"â","\\":"ç","]":"ê","^":"î","`":"ô","{":"é","|":"ù","}":"è","~":"û"},Y.CHARSETS.K={"@":"§","[":"Ä","\\":"Ö","]":"Ü","{":"ä","|":"ö","}":"ü","~":"ß"},Y.CHARSETS.Y={"#":"£","@":"§","[":"°","\\":"ç","]":"é","`":"ù","{":"à","|":"ò","}":"è","~":"ì"},Y.CHARSETS.E=Y.CHARSETS[6]={"@":"Ä","[":"Æ","\\":"Ø","]":"Å","^":"Ü","`":"ä","{":"æ","|":"ø","}":"å","~":"ü"},Y.CHARSETS.Z={"#":"£","@":"§","[":"¡","\\":"Ñ","]":"¿","{":"°","|":"ñ","}":"ç"},Y.CHARSETS.H=Y.CHARSETS[7]={"@":"É","[":"Ä","\\":"Ö","]":"Å","^":"Ü","`":"é","{":"ä","|":"ö","}":"å","~":"ü"},Y.CHARSETS["="]={"#":"ù","@":"à","[":"é","\\":"ç","]":"ê","^":"î",_:"è","`":"ô","{":"ä","|":"ö","}":"ü","~":"û"}},584:(F,Y)=>{var E,Z,U;Object.defineProperty(Y,"__esModule",{value:!0}),Y.C1_ESCAPED=Y.C1=Y.C0=void 0,function(X){X.NUL="\x00",X.SOH="\x01",X.STX="\x02",X.ETX="\x03",X.EOT="\x04",X.ENQ="\x05",X.ACK="\x06",X.BEL="\x07",X.BS="\b",X.HT="\t",X.LF=`
2660
2660
  `,X.VT="\v",X.FF="\f",X.CR="\r",X.SO="\x0E",X.SI="\x0F",X.DLE="\x10",X.DC1="\x11",X.DC2="\x12",X.DC3="\x13",X.DC4="\x14",X.NAK="\x15",X.SYN="\x16",X.ETB="\x17",X.CAN="\x18",X.EM="\x19",X.SUB="\x1A",X.ESC="\x1B",X.FS="\x1C",X.GS="\x1D",X.RS="\x1E",X.US="\x1F",X.SP=" ",X.DEL=""}(E||(Y.C0=E={})),function(X){X.PAD="€",X.HOP="",X.BPH="‚",X.NBH="ƒ",X.IND="„",X.NEL="…",X.SSA="†",X.ESA="‡",X.HTS="ˆ",X.HTJ="‰",X.VTS="Š",X.PLD="‹",X.PLU="Œ",X.RI="",X.SS2="Ž",X.SS3="",X.DCS="",X.PU1="‘",X.PU2="’",X.STS="“",X.CCH="”",X.MW="•",X.SPA="–",X.EPA="—",X.SOS="˜",X.SGCI="™",X.SCI="š",X.CSI="›",X.ST="œ",X.OSC="",X.PM="ž",X.APC="Ÿ"}(Z||(Y.C1=Z={})),function(X){X.ST=`${E.ESC}\\`}(U||(Y.C1_ESCAPED=U={}))},482:(F,Y)=>{Object.defineProperty(Y,"__esModule",{value:!0}),Y.Utf8ToUtf32=Y.StringToUtf32=Y.utf32ToString=Y.stringFromCodePoint=void 0,Y.stringFromCodePoint=function(E){return E>65535?(E-=65536,String.fromCharCode(55296+(E>>10))+String.fromCharCode(E%1024+56320)):String.fromCharCode(E)},Y.utf32ToString=function(E,Z=0,U=E.length){let X="";for(let G=Z;G<U;++G){let V=E[G];V>65535?(V-=65536,X+=String.fromCharCode(55296+(V>>10))+String.fromCharCode(V%1024+56320)):X+=String.fromCharCode(V)}return X},Y.StringToUtf32=class{constructor(){this._interim=0}clear(){this._interim=0}decode(E,Z){let U=E.length;if(!U)return 0;let X=0,G=0;if(this._interim){let V=E.charCodeAt(G++);56320<=V&&V<=57343?Z[X++]=1024*(this._interim-55296)+V-56320+65536:(Z[X++]=this._interim,Z[X++]=V),this._interim=0}for(let V=G;V<U;++V){let K=E.charCodeAt(V);if(55296<=K&&K<=56319){if(++V>=U)return this._interim=K,X;let I=E.charCodeAt(V);56320<=I&&I<=57343?Z[X++]=1024*(K-55296)+I-56320+65536:(Z[X++]=K,Z[X++]=I)}else K!==65279&&(Z[X++]=K)}return X}},Y.Utf8ToUtf32=class{constructor(){this.interim=new Uint8Array(3)}clear(){this.interim.fill(0)}decode(E,Z){let U=E.length;if(!U)return 0;let X,G,V,K,I=0,z=0,W=0;if(this.interim[0]){let N=!1,w=this.interim[0];w&=(224&w)==192?31:(240&w)==224?15:7;let O,L=0;for(;(O=63&this.interim[++L])&&L<4;)w<<=6,w|=O;let j=(224&this.interim[0])==192?2:(240&this.interim[0])==224?3:4,k=j-L;for(;W<k;){if(W>=U)return 0;if(O=E[W++],(192&O)!=128){W--,N=!0;break}this.interim[L++]=O,w<<=6,w|=63&O}N||(j===2?w<128?W--:Z[I++]=w:j===3?w<2048||w>=55296&&w<=57343||w===65279||(Z[I++]=w):w<65536||w>1114111||(Z[I++]=w)),this.interim.fill(0)}let H=U-4,q=W;for(;q<U;){for(;!(!(q<H)||128&(X=E[q])||128&(G=E[q+1])||128&(V=E[q+2])||128&(K=E[q+3]));)Z[I++]=X,Z[I++]=G,Z[I++]=V,Z[I++]=K,q+=4;if(X=E[q++],X<128)Z[I++]=X;else if((224&X)==192){if(q>=U)return this.interim[0]=X,I;if(G=E[q++],(192&G)!=128){q--;continue}if(z=(31&X)<<6|63&G,z<128){q--;continue}Z[I++]=z}else if((240&X)==224){if(q>=U)return this.interim[0]=X,I;if(G=E[q++],(192&G)!=128){q--;continue}if(q>=U)return this.interim[0]=X,this.interim[1]=G,I;if(V=E[q++],(192&V)!=128){q--;continue}if(z=(15&X)<<12|(63&G)<<6|63&V,z<2048||z>=55296&&z<=57343||z===65279)continue;Z[I++]=z}else if((248&X)==240){if(q>=U)return this.interim[0]=X,I;if(G=E[q++],(192&G)!=128){q--;continue}if(q>=U)return this.interim[0]=X,this.interim[1]=G,I;if(V=E[q++],(192&V)!=128){q--;continue}if(q>=U)return this.interim[0]=X,this.interim[1]=G,this.interim[2]=V,I;if(K=E[q++],(192&K)!=128){q--;continue}if(z=(7&X)<<18|(63&G)<<12|(63&V)<<6|63&K,z<65536||z>1114111)continue;Z[I++]=z}}return I}}},225:(F,Y,E)=>{Object.defineProperty(Y,"__esModule",{value:!0}),Y.UnicodeV6=void 0;let Z=E(480),U=[[768,879],[1155,1158],[1160,1161],[1425,1469],[1471,1471],[1473,1474],[1476,1477],[1479,1479],[1536,1539],[1552,1557],[1611,1630],[1648,1648],[1750,1764],[1767,1768],[1770,1773],[1807,1807],[1809,1809],[1840,1866],[1958,1968],[2027,2035],[2305,2306],[2364,2364],[2369,2376],[2381,2381],[2385,2388],[2402,2403],[2433,2433],[2492,2492],[2497,2500],[2509,2509],[2530,2531],[2561,2562],[2620,2620],[2625,2626],[2631,2632],[2635,2637],[2672,2673],[2689,2690],[2748,2748],[2753,2757],[2759,2760],[2765,2765],[2786,2787],[2817,2817],[2876,2876],[2879,2879],[2881,2883],[2893,2893],[2902,2902],[2946,2946],[3008,3008],[3021,3021],[3134,3136],[3142,3144],[3146,3149],[3157,3158],[3260,3260],[3263,3263],[3270,3270],[3276,3277],[3298,3299],[3393,3395],[3405,3405],[3530,3530],[3538,3540],[3542,3542],[3633,3633],[3636,3642],[3655,3662],[3761,3761],[3764,3769],[3771,3772],[3784,3789],[3864,3865],[3893,3893],[3895,3895],[3897,3897],[3953,3966],[3968,3972],[3974,3975],[3984,3991],[3993,4028],[4038,4038],[4141,4144],[4146,4146],[4150,4151],[4153,4153],[4184,4185],[4448,4607],[4959,4959],[5906,5908],[5938,5940],[5970,5971],[6002,6003],[6068,6069],[6071,6077],[6086,6086],[6089,6099],[6109,6109],[6155,6157],[6313,6313],[6432,6434],[6439,6440],[6450,6450],[6457,6459],[6679,6680],[6912,6915],[6964,6964],[6966,6970],[6972,6972],[6978,6978],[7019,7027],[7616,7626],[7678,7679],[8203,8207],[8234,8238],[8288,8291],[8298,8303],[8400,8431],[12330,12335],[12441,12442],[43014,43014],[43019,43019],[43045,43046],[64286,64286],[65024,65039],[65056,65059],[65279,65279],[65529,65531]],X=[[68097,68099],[68101,68102],[68108,68111],[68152,68154],[68159,68159],[119143,119145],[119155,119170],[119173,119179],[119210,119213],[119362,119364],[917505,917505],[917536,917631],[917760,917999]],G;Y.UnicodeV6=class{constructor(){if(this.version="6",!G){G=new Uint8Array(65536),G.fill(1),G[0]=0,G.fill(0,1,32),G.fill(0,127,160),G.fill(2,4352,4448),G[9001]=2,G[9002]=2,G.fill(2,11904,42192),G[12351]=1,G.fill(2,44032,55204),G.fill(2,63744,64256),G.fill(2,65040,65050),G.fill(2,65072,65136),G.fill(2,65280,65377),G.fill(2,65504,65511);for(let V=0;V<U.length;++V)G.fill(0,U[V][0],U[V][1]+1)}}wcwidth(V){return V<32?0:V<127?1:V<65536?G[V]:function(K,I){let z,W=0,H=I.length-1;if(K<I[0][0]||K>I[H][1])return!1;for(;H>=W;)if(z=W+H>>1,K>I[z][1])W=z+1;else{if(!(K<I[z][0]))return!0;H=z-1}return!1}(V,X)?0:V>=131072&&V<=196605||V>=196608&&V<=262141?2:1}charProperties(V,K){let I=this.wcwidth(V),z=I===0&&K!==0;if(z){let W=Z.UnicodeService.extractWidth(K);W===0?z=!1:W>I&&(I=W)}return Z.UnicodeService.createPropertyValue(0,I,z)}}},981:(F,Y,E)=>{Object.defineProperty(Y,"__esModule",{value:!0}),Y.WriteBuffer=void 0;let Z=E(460),U=E(844);class X extends U.Disposable{constructor(G){super(),this._action=G,this._writeBuffer=[],this._callbacks=[],this._pendingData=0,this._bufferOffset=0,this._isSyncWriting=!1,this._syncCalls=0,this._didUserInput=!1,this._onWriteParsed=this.register(new Z.EventEmitter),this.onWriteParsed=this._onWriteParsed.event}handleUserInput(){this._didUserInput=!0}writeSync(G,V){if(V!==void 0&&this._syncCalls>V)return void(this._syncCalls=0);if(this._pendingData+=G.length,this._writeBuffer.push(G),this._callbacks.push(void 0),this._syncCalls++,this._isSyncWriting)return;let K;for(this._isSyncWriting=!0;K=this._writeBuffer.shift();){this._action(K);let I=this._callbacks.shift();I&&I()}this._pendingData=0,this._bufferOffset=2147483647,this._isSyncWriting=!1,this._syncCalls=0}write(G,V){if(this._pendingData>50000000)throw Error("write data discarded, use flow control to avoid losing data");if(!this._writeBuffer.length){if(this._bufferOffset=0,this._didUserInput)return this._didUserInput=!1,this._pendingData+=G.length,this._writeBuffer.push(G),this._callbacks.push(V),void this._innerWrite();setTimeout(()=>this._innerWrite())}this._pendingData+=G.length,this._writeBuffer.push(G),this._callbacks.push(V)}_innerWrite(G=0,V=!0){let K=G||Date.now();for(;this._writeBuffer.length>this._bufferOffset;){let I=this._writeBuffer[this._bufferOffset],z=this._action(I,V);if(z){let H=(q)=>Date.now()-K>=12?setTimeout(()=>this._innerWrite(0,q)):this._innerWrite(K,q);return void z.catch((q)=>(queueMicrotask(()=>{throw q}),Promise.resolve(!1))).then(H)}let W=this._callbacks[this._bufferOffset];if(W&&W(),this._bufferOffset++,this._pendingData-=I.length,Date.now()-K>=12)break}this._writeBuffer.length>this._bufferOffset?(this._bufferOffset>50&&(this._writeBuffer=this._writeBuffer.slice(this._bufferOffset),this._callbacks=this._callbacks.slice(this._bufferOffset),this._bufferOffset=0),setTimeout(()=>this._innerWrite())):(this._writeBuffer.length=0,this._callbacks.length=0,this._pendingData=0,this._bufferOffset=0),this._onWriteParsed.fire()}}Y.WriteBuffer=X},941:(F,Y)=>{Object.defineProperty(Y,"__esModule",{value:!0}),Y.toRgbString=Y.parseColor=void 0;let E=/^([\da-f])\/([\da-f])\/([\da-f])$|^([\da-f]{2})\/([\da-f]{2})\/([\da-f]{2})$|^([\da-f]{3})\/([\da-f]{3})\/([\da-f]{3})$|^([\da-f]{4})\/([\da-f]{4})\/([\da-f]{4})$/,Z=/^[\da-f]+$/;function U(X,G){let V=X.toString(16),K=V.length<2?"0"+V:V;switch(G){case 4:return V[0];case 8:return K;case 12:return(K+K).slice(0,3);default:return K+K}}Y.parseColor=function(X){if(!X)return;let G=X.toLowerCase();if(G.indexOf("rgb:")===0){G=G.slice(4);let V=E.exec(G);if(V){let K=V[1]?15:V[4]?255:V[7]?4095:65535;return[Math.round(parseInt(V[1]||V[4]||V[7]||V[10],16)/K*255),Math.round(parseInt(V[2]||V[5]||V[8]||V[11],16)/K*255),Math.round(parseInt(V[3]||V[6]||V[9]||V[12],16)/K*255)]}}else if(G.indexOf("#")===0&&(G=G.slice(1),Z.exec(G)&&[3,6,9,12].includes(G.length))){let V=G.length/3,K=[0,0,0];for(let I=0;I<3;++I){let z=parseInt(G.slice(V*I,V*I+V),16);K[I]=V===1?z<<4:V===2?z:V===3?z>>4:z>>8}return K}},Y.toRgbString=function(X,G=16){let[V,K,I]=X;return`rgb:${U(V,G)}/${U(K,G)}/${U(I,G)}`}},770:(F,Y)=>{Object.defineProperty(Y,"__esModule",{value:!0}),Y.PAYLOAD_LIMIT=void 0,Y.PAYLOAD_LIMIT=1e7},351:(F,Y,E)=>{Object.defineProperty(Y,"__esModule",{value:!0}),Y.DcsHandler=Y.DcsParser=void 0;let Z=E(482),U=E(742),X=E(770),G=[];Y.DcsParser=class{constructor(){this._handlers=Object.create(null),this._active=G,this._ident=0,this._handlerFb=()=>{},this._stack={paused:!1,loopPosition:0,fallThrough:!1}}dispose(){this._handlers=Object.create(null),this._handlerFb=()=>{},this._active=G}registerHandler(K,I){this._handlers[K]===void 0&&(this._handlers[K]=[]);let z=this._handlers[K];return z.push(I),{dispose:()=>{let W=z.indexOf(I);W!==-1&&z.splice(W,1)}}}clearHandler(K){this._handlers[K]&&delete this._handlers[K]}setHandlerFallback(K){this._handlerFb=K}reset(){if(this._active.length)for(let K=this._stack.paused?this._stack.loopPosition-1:this._active.length-1;K>=0;--K)this._active[K].unhook(!1);this._stack.paused=!1,this._active=G,this._ident=0}hook(K,I){if(this.reset(),this._ident=K,this._active=this._handlers[K]||G,this._active.length)for(let z=this._active.length-1;z>=0;z--)this._active[z].hook(I);else this._handlerFb(this._ident,"HOOK",I)}put(K,I,z){if(this._active.length)for(let W=this._active.length-1;W>=0;W--)this._active[W].put(K,I,z);else this._handlerFb(this._ident,"PUT",(0,Z.utf32ToString)(K,I,z))}unhook(K,I=!0){if(this._active.length){let z=!1,W=this._active.length-1,H=!1;if(this._stack.paused&&(W=this._stack.loopPosition-1,z=I,H=this._stack.fallThrough,this._stack.paused=!1),!H&&z===!1){for(;W>=0&&(z=this._active[W].unhook(K),z!==!0);W--)if(z instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=W,this._stack.fallThrough=!1,z;W--}for(;W>=0;W--)if(z=this._active[W].unhook(!1),z instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=W,this._stack.fallThrough=!0,z}else this._handlerFb(this._ident,"UNHOOK",K);this._active=G,this._ident=0}};let V=new U.Params;V.addParam(0),Y.DcsHandler=class{constructor(K){this._handler=K,this._data="",this._params=V,this._hitLimit=!1}hook(K){this._params=K.length>1||K.params[0]?K.clone():V,this._data="",this._hitLimit=!1}put(K,I,z){this._hitLimit||(this._data+=(0,Z.utf32ToString)(K,I,z),this._data.length>X.PAYLOAD_LIMIT&&(this._data="",this._hitLimit=!0))}unhook(K){let I=!1;if(this._hitLimit)I=!1;else if(K&&(I=this._handler(this._data,this._params),I instanceof Promise))return I.then((z)=>(this._params=V,this._data="",this._hitLimit=!1,z));return this._params=V,this._data="",this._hitLimit=!1,I}}},15:(F,Y,E)=>{Object.defineProperty(Y,"__esModule",{value:!0}),Y.EscapeSequenceParser=Y.VT500_TRANSITION_TABLE=Y.TransitionTable=void 0;let Z=E(844),U=E(742),X=E(242),G=E(351);class V{constructor(z){this.table=new Uint8Array(z)}setDefault(z,W){this.table.fill(z<<4|W)}add(z,W,H,q){this.table[W<<8|z]=H<<4|q}addMany(z,W,H,q){for(let N=0;N<z.length;N++)this.table[W<<8|z[N]]=H<<4|q}}Y.TransitionTable=V;let K=160;Y.VT500_TRANSITION_TABLE=function(){let z=new V(4095),W=Array.apply(null,Array(256)).map((L,j)=>j),H=(L,j)=>W.slice(L,j),q=H(32,127),N=H(0,24);N.push(25),N.push.apply(N,H(28,32));let w=H(0,14),O;for(O in z.setDefault(1,0),z.addMany(q,0,2,0),w)z.addMany([24,26,153,154],O,3,0),z.addMany(H(128,144),O,3,0),z.addMany(H(144,152),O,3,0),z.add(156,O,0,0),z.add(27,O,11,1),z.add(157,O,4,8),z.addMany([152,158,159],O,0,7),z.add(155,O,11,3),z.add(144,O,11,9);return z.addMany(N,0,3,0),z.addMany(N,1,3,1),z.add(127,1,0,1),z.addMany(N,8,0,8),z.addMany(N,3,3,3),z.add(127,3,0,3),z.addMany(N,4,3,4),z.add(127,4,0,4),z.addMany(N,6,3,6),z.addMany(N,5,3,5),z.add(127,5,0,5),z.addMany(N,2,3,2),z.add(127,2,0,2),z.add(93,1,4,8),z.addMany(q,8,5,8),z.add(127,8,5,8),z.addMany([156,27,24,26,7],8,6,0),z.addMany(H(28,32),8,0,8),z.addMany([88,94,95],1,0,7),z.addMany(q,7,0,7),z.addMany(N,7,0,7),z.add(156,7,0,0),z.add(127,7,0,7),z.add(91,1,11,3),z.addMany(H(64,127),3,7,0),z.addMany(H(48,60),3,8,4),z.addMany([60,61,62,63],3,9,4),z.addMany(H(48,60),4,8,4),z.addMany(H(64,127),4,7,0),z.addMany([60,61,62,63],4,0,6),z.addMany(H(32,64),6,0,6),z.add(127,6,0,6),z.addMany(H(64,127),6,0,0),z.addMany(H(32,48),3,9,5),z.addMany(H(32,48),5,9,5),z.addMany(H(48,64),5,0,6),z.addMany(H(64,127),5,7,0),z.addMany(H(32,48),4,9,5),z.addMany(H(32,48),1,9,2),z.addMany(H(32,48),2,9,2),z.addMany(H(48,127),2,10,0),z.addMany(H(48,80),1,10,0),z.addMany(H(81,88),1,10,0),z.addMany([89,90,92],1,10,0),z.addMany(H(96,127),1,10,0),z.add(80,1,11,9),z.addMany(N,9,0,9),z.add(127,9,0,9),z.addMany(H(28,32),9,0,9),z.addMany(H(32,48),9,9,12),z.addMany(H(48,60),9,8,10),z.addMany([60,61,62,63],9,9,10),z.addMany(N,11,0,11),z.addMany(H(32,128),11,0,11),z.addMany(H(28,32),11,0,11),z.addMany(N,10,0,10),z.add(127,10,0,10),z.addMany(H(28,32),10,0,10),z.addMany(H(48,60),10,8,10),z.addMany([60,61,62,63],10,0,11),z.addMany(H(32,48),10,9,12),z.addMany(N,12,0,12),z.add(127,12,0,12),z.addMany(H(28,32),12,0,12),z.addMany(H(32,48),12,9,12),z.addMany(H(48,64),12,0,11),z.addMany(H(64,127),12,12,13),z.addMany(H(64,127),10,12,13),z.addMany(H(64,127),9,12,13),z.addMany(N,13,13,13),z.addMany(q,13,13,13),z.add(127,13,0,13),z.addMany([27,156,24,26],13,14,0),z.add(K,0,2,0),z.add(K,8,5,8),z.add(K,6,0,6),z.add(K,11,0,11),z.add(K,13,13,13),z}();class I extends Z.Disposable{constructor(z=Y.VT500_TRANSITION_TABLE){super(),this._transitions=z,this._parseStack={state:0,handlers:[],handlerPos:0,transition:0,chunkPos:0},this.initialState=0,this.currentState=this.initialState,this._params=new U.Params,this._params.addParam(0),this._collect=0,this.precedingJoinState=0,this._printHandlerFb=(W,H,q)=>{},this._executeHandlerFb=(W)=>{},this._csiHandlerFb=(W,H)=>{},this._escHandlerFb=(W)=>{},this._errorHandlerFb=(W)=>W,this._printHandler=this._printHandlerFb,this._executeHandlers=Object.create(null),this._csiHandlers=Object.create(null),this._escHandlers=Object.create(null),this.register((0,Z.toDisposable)(()=>{this._csiHandlers=Object.create(null),this._executeHandlers=Object.create(null),this._escHandlers=Object.create(null)})),this._oscParser=this.register(new X.OscParser),this._dcsParser=this.register(new G.DcsParser),this._errorHandler=this._errorHandlerFb,this.registerEscHandler({final:"\\"},()=>!0)}_identifier(z,W=[64,126]){let H=0;if(z.prefix){if(z.prefix.length>1)throw Error("only one byte as prefix supported");if(H=z.prefix.charCodeAt(0),H&&60>H||H>63)throw Error("prefix must be in range 0x3c .. 0x3f")}if(z.intermediates){if(z.intermediates.length>2)throw Error("only two bytes as intermediates are supported");for(let N=0;N<z.intermediates.length;++N){let w=z.intermediates.charCodeAt(N);if(32>w||w>47)throw Error("intermediate must be in range 0x20 .. 0x2f");H<<=8,H|=w}}if(z.final.length!==1)throw Error("final must be a single byte");let q=z.final.charCodeAt(0);if(W[0]>q||q>W[1])throw Error(`final must be in range ${W[0]} .. ${W[1]}`);return H<<=8,H|=q,H}identToString(z){let W=[];for(;z;)W.push(String.fromCharCode(255&z)),z>>=8;return W.reverse().join("")}setPrintHandler(z){this._printHandler=z}clearPrintHandler(){this._printHandler=this._printHandlerFb}registerEscHandler(z,W){let H=this._identifier(z,[48,126]);this._escHandlers[H]===void 0&&(this._escHandlers[H]=[]);let q=this._escHandlers[H];return q.push(W),{dispose:()=>{let N=q.indexOf(W);N!==-1&&q.splice(N,1)}}}clearEscHandler(z){this._escHandlers[this._identifier(z,[48,126])]&&delete this._escHandlers[this._identifier(z,[48,126])]}setEscHandlerFallback(z){this._escHandlerFb=z}setExecuteHandler(z,W){this._executeHandlers[z.charCodeAt(0)]=W}clearExecuteHandler(z){this._executeHandlers[z.charCodeAt(0)]&&delete this._executeHandlers[z.charCodeAt(0)]}setExecuteHandlerFallback(z){this._executeHandlerFb=z}registerCsiHandler(z,W){let H=this._identifier(z);this._csiHandlers[H]===void 0&&(this._csiHandlers[H]=[]);let q=this._csiHandlers[H];return q.push(W),{dispose:()=>{let N=q.indexOf(W);N!==-1&&q.splice(N,1)}}}clearCsiHandler(z){this._csiHandlers[this._identifier(z)]&&delete this._csiHandlers[this._identifier(z)]}setCsiHandlerFallback(z){this._csiHandlerFb=z}registerDcsHandler(z,W){return this._dcsParser.registerHandler(this._identifier(z),W)}clearDcsHandler(z){this._dcsParser.clearHandler(this._identifier(z))}setDcsHandlerFallback(z){this._dcsParser.setHandlerFallback(z)}registerOscHandler(z,W){return this._oscParser.registerHandler(z,W)}clearOscHandler(z){this._oscParser.clearHandler(z)}setOscHandlerFallback(z){this._oscParser.setHandlerFallback(z)}setErrorHandler(z){this._errorHandler=z}clearErrorHandler(){this._errorHandler=this._errorHandlerFb}reset(){this.currentState=this.initialState,this._oscParser.reset(),this._dcsParser.reset(),this._params.reset(),this._params.addParam(0),this._collect=0,this.precedingJoinState=0,this._parseStack.state!==0&&(this._parseStack.state=2,this._parseStack.handlers=[])}_preserveStack(z,W,H,q,N){this._parseStack.state=z,this._parseStack.handlers=W,this._parseStack.handlerPos=H,this._parseStack.transition=q,this._parseStack.chunkPos=N}parse(z,W,H){let q,N=0,w=0,O=0;if(this._parseStack.state)if(this._parseStack.state===2)this._parseStack.state=0,O=this._parseStack.chunkPos+1;else{if(H===void 0||this._parseStack.state===1)throw this._parseStack.state=1,Error("improper continuation due to previous async handler, giving up parsing");let L=this._parseStack.handlers,j=this._parseStack.handlerPos-1;switch(this._parseStack.state){case 3:if(H===!1&&j>-1){for(;j>=0&&(q=L[j](this._params),q!==!0);j--)if(q instanceof Promise)return this._parseStack.handlerPos=j,q}this._parseStack.handlers=[];break;case 4:if(H===!1&&j>-1){for(;j>=0&&(q=L[j](),q!==!0);j--)if(q instanceof Promise)return this._parseStack.handlerPos=j,q}this._parseStack.handlers=[];break;case 6:if(N=z[this._parseStack.chunkPos],q=this._dcsParser.unhook(N!==24&&N!==26,H),q)return q;N===27&&(this._parseStack.transition|=1),this._params.reset(),this._params.addParam(0),this._collect=0;break;case 5:if(N=z[this._parseStack.chunkPos],q=this._oscParser.end(N!==24&&N!==26,H),q)return q;N===27&&(this._parseStack.transition|=1),this._params.reset(),this._params.addParam(0),this._collect=0}this._parseStack.state=0,O=this._parseStack.chunkPos+1,this.precedingJoinState=0,this.currentState=15&this._parseStack.transition}for(let L=O;L<W;++L){switch(N=z[L],w=this._transitions.table[this.currentState<<8|(N<160?N:K)],w>>4){case 2:for(let h=L+1;;++h){if(h>=W||(N=z[h])<32||N>126&&N<K){this._printHandler(z,L,h),L=h-1;break}if(++h>=W||(N=z[h])<32||N>126&&N<K){this._printHandler(z,L,h),L=h-1;break}if(++h>=W||(N=z[h])<32||N>126&&N<K){this._printHandler(z,L,h),L=h-1;break}if(++h>=W||(N=z[h])<32||N>126&&N<K){this._printHandler(z,L,h),L=h-1;break}}break;case 3:this._executeHandlers[N]?this._executeHandlers[N]():this._executeHandlerFb(N),this.precedingJoinState=0;break;case 0:break;case 1:if(this._errorHandler({position:L,code:N,currentState:this.currentState,collect:this._collect,params:this._params,abort:!1}).abort)return;break;case 7:let j=this._csiHandlers[this._collect<<8|N],k=j?j.length-1:-1;for(;k>=0&&(q=j[k](this._params),q!==!0);k--)if(q instanceof Promise)return this._preserveStack(3,j,k,w,L),q;k<0&&this._csiHandlerFb(this._collect<<8|N,this._params),this.precedingJoinState=0;break;case 8:do switch(N){case 59:this._params.addParam(0);break;case 58:this._params.addSubParam(-1);break;default:this._params.addDigit(N-48)}while(++L<W&&(N=z[L])>47&&N<60);L--;break;case 9:this._collect<<=8,this._collect|=N;break;case 10:let _=this._escHandlers[this._collect<<8|N],f=_?_.length-1:-1;for(;f>=0&&(q=_[f](),q!==!0);f--)if(q instanceof Promise)return this._preserveStack(4,_,f,w,L),q;f<0&&this._escHandlerFb(this._collect<<8|N),this.precedingJoinState=0;break;case 11:this._params.reset(),this._params.addParam(0),this._collect=0;break;case 12:this._dcsParser.hook(this._collect<<8|N,this._params);break;case 13:for(let h=L+1;;++h)if(h>=W||(N=z[h])===24||N===26||N===27||N>127&&N<K){this._dcsParser.put(z,L,h),L=h-1;break}break;case 14:if(q=this._dcsParser.unhook(N!==24&&N!==26),q)return this._preserveStack(6,[],0,w,L),q;N===27&&(w|=1),this._params.reset(),this._params.addParam(0),this._collect=0,this.precedingJoinState=0;break;case 4:this._oscParser.start();break;case 5:for(let h=L+1;;h++)if(h>=W||(N=z[h])<32||N>127&&N<K){this._oscParser.put(z,L,h),L=h-1;break}break;case 6:if(q=this._oscParser.end(N!==24&&N!==26),q)return this._preserveStack(5,[],0,w,L),q;N===27&&(w|=1),this._params.reset(),this._params.addParam(0),this._collect=0,this.precedingJoinState=0}this.currentState=15&w}}}Y.EscapeSequenceParser=I},242:(F,Y,E)=>{Object.defineProperty(Y,"__esModule",{value:!0}),Y.OscHandler=Y.OscParser=void 0;let Z=E(770),U=E(482),X=[];Y.OscParser=class{constructor(){this._state=0,this._active=X,this._id=-1,this._handlers=Object.create(null),this._handlerFb=()=>{},this._stack={paused:!1,loopPosition:0,fallThrough:!1}}registerHandler(G,V){this._handlers[G]===void 0&&(this._handlers[G]=[]);let K=this._handlers[G];return K.push(V),{dispose:()=>{let I=K.indexOf(V);I!==-1&&K.splice(I,1)}}}clearHandler(G){this._handlers[G]&&delete this._handlers[G]}setHandlerFallback(G){this._handlerFb=G}dispose(){this._handlers=Object.create(null),this._handlerFb=()=>{},this._active=X}reset(){if(this._state===2)for(let G=this._stack.paused?this._stack.loopPosition-1:this._active.length-1;G>=0;--G)this._active[G].end(!1);this._stack.paused=!1,this._active=X,this._id=-1,this._state=0}_start(){if(this._active=this._handlers[this._id]||X,this._active.length)for(let G=this._active.length-1;G>=0;G--)this._active[G].start();else this._handlerFb(this._id,"START")}_put(G,V,K){if(this._active.length)for(let I=this._active.length-1;I>=0;I--)this._active[I].put(G,V,K);else this._handlerFb(this._id,"PUT",(0,U.utf32ToString)(G,V,K))}start(){this.reset(),this._state=1}put(G,V,K){if(this._state!==3){if(this._state===1)for(;V<K;){let I=G[V++];if(I===59){this._state=2,this._start();break}if(I<48||57<I)return void(this._state=3);this._id===-1&&(this._id=0),this._id=10*this._id+I-48}this._state===2&&K-V>0&&this._put(G,V,K)}}end(G,V=!0){if(this._state!==0){if(this._state!==3)if(this._state===1&&this._start(),this._active.length){let K=!1,I=this._active.length-1,z=!1;if(this._stack.paused&&(I=this._stack.loopPosition-1,K=V,z=this._stack.fallThrough,this._stack.paused=!1),!z&&K===!1){for(;I>=0&&(K=this._active[I].end(G),K!==!0);I--)if(K instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=I,this._stack.fallThrough=!1,K;I--}for(;I>=0;I--)if(K=this._active[I].end(!1),K instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=I,this._stack.fallThrough=!0,K}else this._handlerFb(this._id,"END",G);this._active=X,this._id=-1,this._state=0}}},Y.OscHandler=class{constructor(G){this._handler=G,this._data="",this._hitLimit=!1}start(){this._data="",this._hitLimit=!1}put(G,V,K){this._hitLimit||(this._data+=(0,U.utf32ToString)(G,V,K),this._data.length>Z.PAYLOAD_LIMIT&&(this._data="",this._hitLimit=!0))}end(G){let V=!1;if(this._hitLimit)V=!1;else if(G&&(V=this._handler(this._data),V instanceof Promise))return V.then((K)=>(this._data="",this._hitLimit=!1,K));return this._data="",this._hitLimit=!1,V}}},742:(F,Y)=>{Object.defineProperty(Y,"__esModule",{value:!0}),Y.Params=void 0;let E=2147483647;class Z{static fromArray(U){let X=new Z;if(!U.length)return X;for(let G=Array.isArray(U[0])?1:0;G<U.length;++G){let V=U[G];if(Array.isArray(V))for(let K=0;K<V.length;++K)X.addSubParam(V[K]);else X.addParam(V)}return X}constructor(U=32,X=32){if(this.maxLength=U,this.maxSubParamsLength=X,X>256)throw Error("maxSubParamsLength must not be greater than 256");this.params=new Int32Array(U),this.length=0,this._subParams=new Int32Array(X),this._subParamsLength=0,this._subParamsIdx=new Uint16Array(U),this._rejectDigits=!1,this._rejectSubDigits=!1,this._digitIsSub=!1}clone(){let U=new Z(this.maxLength,this.maxSubParamsLength);return U.params.set(this.params),U.length=this.length,U._subParams.set(this._subParams),U._subParamsLength=this._subParamsLength,U._subParamsIdx.set(this._subParamsIdx),U._rejectDigits=this._rejectDigits,U._rejectSubDigits=this._rejectSubDigits,U._digitIsSub=this._digitIsSub,U}toArray(){let U=[];for(let X=0;X<this.length;++X){U.push(this.params[X]);let G=this._subParamsIdx[X]>>8,V=255&this._subParamsIdx[X];V-G>0&&U.push(Array.prototype.slice.call(this._subParams,G,V))}return U}reset(){this.length=0,this._subParamsLength=0,this._rejectDigits=!1,this._rejectSubDigits=!1,this._digitIsSub=!1}addParam(U){if(this._digitIsSub=!1,this.length>=this.maxLength)this._rejectDigits=!0;else{if(U<-1)throw Error("values lesser than -1 are not allowed");this._subParamsIdx[this.length]=this._subParamsLength<<8|this._subParamsLength,this.params[this.length++]=U>E?E:U}}addSubParam(U){if(this._digitIsSub=!0,this.length)if(this._rejectDigits||this._subParamsLength>=this.maxSubParamsLength)this._rejectSubDigits=!0;else{if(U<-1)throw Error("values lesser than -1 are not allowed");this._subParams[this._subParamsLength++]=U>E?E:U,this._subParamsIdx[this.length-1]++}}hasSubParams(U){return(255&this._subParamsIdx[U])-(this._subParamsIdx[U]>>8)>0}getSubParams(U){let X=this._subParamsIdx[U]>>8,G=255&this._subParamsIdx[U];return G-X>0?this._subParams.subarray(X,G):null}getSubParamsAll(){let U={};for(let X=0;X<this.length;++X){let G=this._subParamsIdx[X]>>8,V=255&this._subParamsIdx[X];V-G>0&&(U[X]=this._subParams.slice(G,V))}return U}addDigit(U){let X;if(this._rejectDigits||!(X=this._digitIsSub?this._subParamsLength:this.length)||this._digitIsSub&&this._rejectSubDigits)return;let G=this._digitIsSub?this._subParams:this.params,V=G[X-1];G[X-1]=~V?Math.min(10*V+U,E):U}}Y.Params=Z},741:(F,Y)=>{Object.defineProperty(Y,"__esModule",{value:!0}),Y.AddonManager=void 0,Y.AddonManager=class{constructor(){this._addons=[]}dispose(){for(let E=this._addons.length-1;E>=0;E--)this._addons[E].instance.dispose()}loadAddon(E,Z){let U={instance:Z,dispose:Z.dispose,isDisposed:!1};this._addons.push(U),Z.dispose=()=>this._wrappedAddonDispose(U),Z.activate(E)}_wrappedAddonDispose(E){if(E.isDisposed)return;let Z=-1;for(let U=0;U<this._addons.length;U++)if(this._addons[U]===E){Z=U;break}if(Z===-1)throw Error("Could not dispose an addon that has not been loaded");E.isDisposed=!0,E.dispose.apply(E.instance),this._addons.splice(Z,1)}}},771:(F,Y,E)=>{Object.defineProperty(Y,"__esModule",{value:!0}),Y.BufferApiView=void 0;let Z=E(785),U=E(511);Y.BufferApiView=class{constructor(X,G){this._buffer=X,this.type=G}init(X){return this._buffer=X,this}get cursorY(){return this._buffer.y}get cursorX(){return this._buffer.x}get viewportY(){return this._buffer.ydisp}get baseY(){return this._buffer.ybase}get length(){return this._buffer.lines.length}getLine(X){let G=this._buffer.lines.get(X);if(G)return new Z.BufferLineApiView(G)}getNullCell(){return new U.CellData}}},785:(F,Y,E)=>{Object.defineProperty(Y,"__esModule",{value:!0}),Y.BufferLineApiView=void 0;let Z=E(511);Y.BufferLineApiView=class{constructor(U){this._line=U}get isWrapped(){return this._line.isWrapped}get length(){return this._line.length}getCell(U,X){if(!(U<0||U>=this._line.length))return X?(this._line.loadCell(U,X),X):this._line.loadCell(U,new Z.CellData)}translateToString(U,X,G){return this._line.translateToString(U,X,G)}}},285:(F,Y,E)=>{Object.defineProperty(Y,"__esModule",{value:!0}),Y.BufferNamespaceApi=void 0;let Z=E(771),U=E(460),X=E(844);class G extends X.Disposable{constructor(V){super(),this._core=V,this._onBufferChange=this.register(new U.EventEmitter),this.onBufferChange=this._onBufferChange.event,this._normal=new Z.BufferApiView(this._core.buffers.normal,"normal"),this._alternate=new Z.BufferApiView(this._core.buffers.alt,"alternate"),this._core.buffers.onBufferActivate(()=>this._onBufferChange.fire(this.active))}get active(){if(this._core.buffers.active===this._core.buffers.normal)return this.normal;if(this._core.buffers.active===this._core.buffers.alt)return this.alternate;throw Error("Active buffer is neither normal nor alternate")}get normal(){return this._normal.init(this._core.buffers.normal)}get alternate(){return this._alternate.init(this._core.buffers.alt)}}Y.BufferNamespaceApi=G},975:(F,Y)=>{Object.defineProperty(Y,"__esModule",{value:!0}),Y.ParserApi=void 0,Y.ParserApi=class{constructor(E){this._core=E}registerCsiHandler(E,Z){return this._core.registerCsiHandler(E,(U)=>Z(U.toArray()))}addCsiHandler(E,Z){return this.registerCsiHandler(E,Z)}registerDcsHandler(E,Z){return this._core.registerDcsHandler(E,(U,X)=>Z(U,X.toArray()))}addDcsHandler(E,Z){return this.registerDcsHandler(E,Z)}registerEscHandler(E,Z){return this._core.registerEscHandler(E,Z)}addEscHandler(E,Z){return this.registerEscHandler(E,Z)}registerOscHandler(E,Z){return this._core.registerOscHandler(E,Z)}addOscHandler(E,Z){return this.registerOscHandler(E,Z)}}},90:(F,Y)=>{Object.defineProperty(Y,"__esModule",{value:!0}),Y.UnicodeApi=void 0,Y.UnicodeApi=class{constructor(E){this._core=E}register(E){this._core.unicodeService.register(E)}get versions(){return this._core.unicodeService.versions}get activeVersion(){return this._core.unicodeService.activeVersion}set activeVersion(E){this._core.unicodeService.activeVersion=E}}},744:function(F,Y,E){var Z=this&&this.__decorate||function(z,W,H,q){var N,w=arguments.length,O=w<3?W:q===null?q=Object.getOwnPropertyDescriptor(W,H):q;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")O=Reflect.decorate(z,W,H,q);else for(var L=z.length-1;L>=0;L--)(N=z[L])&&(O=(w<3?N(O):w>3?N(W,H,O):N(W,H))||O);return w>3&&O&&Object.defineProperty(W,H,O),O},U=this&&this.__param||function(z,W){return function(H,q){W(H,q,z)}};Object.defineProperty(Y,"__esModule",{value:!0}),Y.BufferService=Y.MINIMUM_ROWS=Y.MINIMUM_COLS=void 0;let X=E(460),G=E(844),V=E(295),K=E(585);Y.MINIMUM_COLS=2,Y.MINIMUM_ROWS=1;let I=Y.BufferService=class extends G.Disposable{get buffer(){return this.buffers.active}constructor(z){super(),this.isUserScrolling=!1,this._onResize=this.register(new X.EventEmitter),this.onResize=this._onResize.event,this._onScroll=this.register(new X.EventEmitter),this.onScroll=this._onScroll.event,this.cols=Math.max(z.rawOptions.cols||0,Y.MINIMUM_COLS),this.rows=Math.max(z.rawOptions.rows||0,Y.MINIMUM_ROWS),this.buffers=this.register(new V.BufferSet(z,this))}resize(z,W){this.cols=z,this.rows=W,this.buffers.resize(z,W),this._onResize.fire({cols:z,rows:W})}reset(){this.buffers.reset(),this.isUserScrolling=!1}scroll(z,W=!1){let H=this.buffer,q;q=this._cachedBlankLine,q&&q.length===this.cols&&q.getFg(0)===z.fg&&q.getBg(0)===z.bg||(q=H.getBlankLine(z,W),this._cachedBlankLine=q),q.isWrapped=W;let N=H.ybase+H.scrollTop,w=H.ybase+H.scrollBottom;if(H.scrollTop===0){let O=H.lines.isFull;w===H.lines.length-1?O?H.lines.recycle().copyFrom(q):H.lines.push(q.clone()):H.lines.splice(w+1,0,q.clone()),O?this.isUserScrolling&&(H.ydisp=Math.max(H.ydisp-1,0)):(H.ybase++,this.isUserScrolling||H.ydisp++)}else{let O=w-N+1;H.lines.shiftElements(N+1,O-1,-1),H.lines.set(w,q.clone())}this.isUserScrolling||(H.ydisp=H.ybase),this._onScroll.fire(H.ydisp)}scrollLines(z,W,H){let q=this.buffer;if(z<0){if(q.ydisp===0)return;this.isUserScrolling=!0}else z+q.ydisp>=q.ybase&&(this.isUserScrolling=!1);let N=q.ydisp;q.ydisp=Math.max(Math.min(q.ydisp+z,q.ybase),0),N!==q.ydisp&&(W||this._onScroll.fire(q.ydisp))}};Y.BufferService=I=Z([U(0,K.IOptionsService)],I)},994:(F,Y)=>{Object.defineProperty(Y,"__esModule",{value:!0}),Y.CharsetService=void 0,Y.CharsetService=class{constructor(){this.glevel=0,this._charsets=[]}reset(){this.charset=void 0,this._charsets=[],this.glevel=0}setgLevel(E){this.glevel=E,this.charset=this._charsets[E]}setgCharset(E,Z){this._charsets[E]=Z,this.glevel===E&&(this.charset=Z)}}},753:function(F,Y,E){var Z=this&&this.__decorate||function(q,N,w,O){var L,j=arguments.length,k=j<3?N:O===null?O=Object.getOwnPropertyDescriptor(N,w):O;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")k=Reflect.decorate(q,N,w,O);else for(var _=q.length-1;_>=0;_--)(L=q[_])&&(k=(j<3?L(k):j>3?L(N,w,k):L(N,w))||k);return j>3&&k&&Object.defineProperty(N,w,k),k},U=this&&this.__param||function(q,N){return function(w,O){N(w,O,q)}};Object.defineProperty(Y,"__esModule",{value:!0}),Y.CoreMouseService=void 0;let X=E(585),G=E(460),V=E(844),K={NONE:{events:0,restrict:()=>!1},X10:{events:1,restrict:(q)=>q.button!==4&&q.action===1&&(q.ctrl=!1,q.alt=!1,q.shift=!1,!0)},VT200:{events:19,restrict:(q)=>q.action!==32},DRAG:{events:23,restrict:(q)=>q.action!==32||q.button!==3},ANY:{events:31,restrict:(q)=>!0}};function I(q,N){let w=(q.ctrl?16:0)|(q.shift?4:0)|(q.alt?8:0);return q.button===4?(w|=64,w|=q.action):(w|=3&q.button,4&q.button&&(w|=64),8&q.button&&(w|=128),q.action===32?w|=32:q.action!==0||N||(w|=3)),w}let z=String.fromCharCode,W={DEFAULT:(q)=>{let N=[I(q,!1)+32,q.col+32,q.row+32];return N[0]>255||N[1]>255||N[2]>255?"":`\x1B[M${z(N[0])}${z(N[1])}${z(N[2])}`},SGR:(q)=>{let N=q.action===0&&q.button!==4?"m":"M";return`\x1B[<${I(q,!0)};${q.col};${q.row}${N}`},SGR_PIXELS:(q)=>{let N=q.action===0&&q.button!==4?"m":"M";return`\x1B[<${I(q,!0)};${q.x};${q.y}${N}`}},H=Y.CoreMouseService=class extends V.Disposable{constructor(q,N){super(),this._bufferService=q,this._coreService=N,this._protocols={},this._encodings={},this._activeProtocol="",this._activeEncoding="",this._lastEvent=null,this._onProtocolChange=this.register(new G.EventEmitter),this.onProtocolChange=this._onProtocolChange.event;for(let w of Object.keys(K))this.addProtocol(w,K[w]);for(let w of Object.keys(W))this.addEncoding(w,W[w]);this.reset()}addProtocol(q,N){this._protocols[q]=N}addEncoding(q,N){this._encodings[q]=N}get activeProtocol(){return this._activeProtocol}get areMouseEventsActive(){return this._protocols[this._activeProtocol].events!==0}set activeProtocol(q){if(!this._protocols[q])throw Error(`unknown protocol "${q}"`);this._activeProtocol=q,this._onProtocolChange.fire(this._protocols[q].events)}get activeEncoding(){return this._activeEncoding}set activeEncoding(q){if(!this._encodings[q])throw Error(`unknown encoding "${q}"`);this._activeEncoding=q}reset(){this.activeProtocol="NONE",this.activeEncoding="DEFAULT",this._lastEvent=null}triggerMouseEvent(q){if(q.col<0||q.col>=this._bufferService.cols||q.row<0||q.row>=this._bufferService.rows)return!1;if(q.button===4&&q.action===32)return!1;if(q.button===3&&q.action!==32)return!1;if(q.button!==4&&(q.action===2||q.action===3))return!1;if(q.col++,q.row++,q.action===32&&this._lastEvent&&this._equalEvents(this._lastEvent,q,this._activeEncoding==="SGR_PIXELS"))return!1;if(!this._protocols[this._activeProtocol].restrict(q))return!1;let N=this._encodings[this._activeEncoding](q);return N&&(this._activeEncoding==="DEFAULT"?this._coreService.triggerBinaryEvent(N):this._coreService.triggerDataEvent(N,!0)),this._lastEvent=q,!0}explainEvents(q){return{down:!!(1&q),up:!!(2&q),drag:!!(4&q),move:!!(8&q),wheel:!!(16&q)}}_equalEvents(q,N,w){if(w){if(q.x!==N.x)return!1;if(q.y!==N.y)return!1}else{if(q.col!==N.col)return!1;if(q.row!==N.row)return!1}return q.button===N.button&&q.action===N.action&&q.ctrl===N.ctrl&&q.alt===N.alt&&q.shift===N.shift}};Y.CoreMouseService=H=Z([U(0,X.IBufferService),U(1,X.ICoreService)],H)},83:function(F,Y,E){var Z=this&&this.__decorate||function(H,q,N,w){var O,L=arguments.length,j=L<3?q:w===null?w=Object.getOwnPropertyDescriptor(q,N):w;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")j=Reflect.decorate(H,q,N,w);else for(var k=H.length-1;k>=0;k--)(O=H[k])&&(j=(L<3?O(j):L>3?O(q,N,j):O(q,N))||j);return L>3&&j&&Object.defineProperty(q,N,j),j},U=this&&this.__param||function(H,q){return function(N,w){q(N,w,H)}};Object.defineProperty(Y,"__esModule",{value:!0}),Y.CoreService=void 0;let X=E(439),G=E(460),V=E(844),K=E(585),I=Object.freeze({insertMode:!1}),z=Object.freeze({applicationCursorKeys:!1,applicationKeypad:!1,bracketedPasteMode:!1,origin:!1,reverseWraparound:!1,sendFocus:!1,wraparound:!0}),W=Y.CoreService=class extends V.Disposable{constructor(H,q,N){super(),this._bufferService=H,this._logService=q,this._optionsService=N,this.isCursorInitialized=!1,this.isCursorHidden=!1,this._onData=this.register(new G.EventEmitter),this.onData=this._onData.event,this._onUserInput=this.register(new G.EventEmitter),this.onUserInput=this._onUserInput.event,this._onBinary=this.register(new G.EventEmitter),this.onBinary=this._onBinary.event,this._onRequestScrollToBottom=this.register(new G.EventEmitter),this.onRequestScrollToBottom=this._onRequestScrollToBottom.event,this.modes=(0,X.clone)(I),this.decPrivateModes=(0,X.clone)(z)}reset(){this.modes=(0,X.clone)(I),this.decPrivateModes=(0,X.clone)(z)}triggerDataEvent(H,q=!1){if(this._optionsService.rawOptions.disableStdin)return;let N=this._bufferService.buffer;q&&this._optionsService.rawOptions.scrollOnUserInput&&N.ybase!==N.ydisp&&this._onRequestScrollToBottom.fire(),q&&this._onUserInput.fire(),this._logService.debug(`sending data "${H}"`,()=>H.split("").map((w)=>w.charCodeAt(0))),this._onData.fire(H)}triggerBinaryEvent(H){this._optionsService.rawOptions.disableStdin||(this._logService.debug(`sending binary "${H}"`,()=>H.split("").map((q)=>q.charCodeAt(0))),this._onBinary.fire(H))}};Y.CoreService=W=Z([U(0,K.IBufferService),U(1,K.ILogService),U(2,K.IOptionsService)],W)},348:(F,Y,E)=>{Object.defineProperty(Y,"__esModule",{value:!0}),Y.InstantiationService=Y.ServiceCollection=void 0;let Z=E(585),U=E(343);class X{constructor(...G){this._entries=new Map;for(let[V,K]of G)this.set(V,K)}set(G,V){let K=this._entries.get(G);return this._entries.set(G,V),K}forEach(G){for(let[V,K]of this._entries.entries())G(V,K)}has(G){return this._entries.has(G)}get(G){return this._entries.get(G)}}Y.ServiceCollection=X,Y.InstantiationService=class{constructor(){this._services=new X,this._services.set(Z.IInstantiationService,this)}setService(G,V){this._services.set(G,V)}getService(G){return this._services.get(G)}createInstance(G,...V){let K=(0,U.getServiceDependencies)(G).sort((W,H)=>W.index-H.index),I=[];for(let W of K){let H=this._services.get(W.id);if(!H)throw Error(`[createInstance] ${G.name} depends on UNKNOWN service ${W.id}.`);I.push(H)}let z=K.length>0?K[0].index:V.length;if(V.length!==z)throw Error(`[createInstance] First service dependency of ${G.name} at position ${z+1} conflicts with ${V.length} static arguments`);return new G(...[...V,...I])}}},866:function(F,Y,E){var Z=this&&this.__decorate||function(z,W,H,q){var N,w=arguments.length,O=w<3?W:q===null?q=Object.getOwnPropertyDescriptor(W,H):q;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")O=Reflect.decorate(z,W,H,q);else for(var L=z.length-1;L>=0;L--)(N=z[L])&&(O=(w<3?N(O):w>3?N(W,H,O):N(W,H))||O);return w>3&&O&&Object.defineProperty(W,H,O),O},U=this&&this.__param||function(z,W){return function(H,q){W(H,q,z)}};Object.defineProperty(Y,"__esModule",{value:!0}),Y.traceCall=Y.setTraceLogger=Y.LogService=void 0;let X=E(844),G=E(585),V={trace:G.LogLevelEnum.TRACE,debug:G.LogLevelEnum.DEBUG,info:G.LogLevelEnum.INFO,warn:G.LogLevelEnum.WARN,error:G.LogLevelEnum.ERROR,off:G.LogLevelEnum.OFF},K,I=Y.LogService=class extends X.Disposable{get logLevel(){return this._logLevel}constructor(z){super(),this._optionsService=z,this._logLevel=G.LogLevelEnum.OFF,this._updateLogLevel(),this.register(this._optionsService.onSpecificOptionChange("logLevel",()=>this._updateLogLevel())),K=this}_updateLogLevel(){this._logLevel=V[this._optionsService.rawOptions.logLevel]}_evalLazyOptionalParams(z){for(let W=0;W<z.length;W++)typeof z[W]=="function"&&(z[W]=z[W]())}_log(z,W,H){this._evalLazyOptionalParams(H),z.call(console,(this._optionsService.options.logger?"":"xterm.js: ")+W,...H)}trace(z,...W){this._logLevel<=G.LogLevelEnum.TRACE&&this._log(this._optionsService.options.logger?.trace.bind(this._optionsService.options.logger)??console.log,z,W)}debug(z,...W){this._logLevel<=G.LogLevelEnum.DEBUG&&this._log(this._optionsService.options.logger?.debug.bind(this._optionsService.options.logger)??console.log,z,W)}info(z,...W){this._logLevel<=G.LogLevelEnum.INFO&&this._log(this._optionsService.options.logger?.info.bind(this._optionsService.options.logger)??console.info,z,W)}warn(z,...W){this._logLevel<=G.LogLevelEnum.WARN&&this._log(this._optionsService.options.logger?.warn.bind(this._optionsService.options.logger)??console.warn,z,W)}error(z,...W){this._logLevel<=G.LogLevelEnum.ERROR&&this._log(this._optionsService.options.logger?.error.bind(this._optionsService.options.logger)??console.error,z,W)}};Y.LogService=I=Z([U(0,G.IOptionsService)],I),Y.setTraceLogger=function(z){K=z},Y.traceCall=function(z,W,H){if(typeof H.value!="function")throw Error("not supported");let q=H.value;H.value=function(...N){if(K.logLevel!==G.LogLevelEnum.TRACE)return q.apply(this,N);K.trace(`GlyphRenderer#${q.name}(${N.map((O)=>JSON.stringify(O)).join(", ")})`);let w=q.apply(this,N);return K.trace(`GlyphRenderer#${q.name} return`,w),w}}},302:(F,Y,E)=>{Object.defineProperty(Y,"__esModule",{value:!0}),Y.OptionsService=Y.DEFAULT_OPTIONS=void 0;let Z=E(460),U=E(844),X=E(114);Y.DEFAULT_OPTIONS={cols:80,rows:24,cursorBlink:!1,cursorStyle:"block",cursorWidth:1,cursorInactiveStyle:"outline",customGlyphs:!0,drawBoldTextInBrightColors:!0,documentOverride:null,fastScrollModifier:"alt",fastScrollSensitivity:5,fontFamily:"courier-new, courier, monospace",fontSize:15,fontWeight:"normal",fontWeightBold:"bold",ignoreBracketedPasteMode:!1,lineHeight:1,letterSpacing:0,linkHandler:null,logLevel:"info",logger:null,scrollback:1000,scrollOnUserInput:!0,scrollSensitivity:1,screenReaderMode:!1,smoothScrollDuration:0,macOptionIsMeta:!1,macOptionClickForcesSelection:!1,minimumContrastRatio:1,disableStdin:!1,allowProposedApi:!1,allowTransparency:!1,tabStopWidth:8,theme:{},rescaleOverlappingGlyphs:!1,rightClickSelectsWord:X.isMac,windowOptions:{},windowsMode:!1,windowsPty:{},wordSeparator:" ()[]{}',\"`",altClickMovesCursor:!0,convertEol:!1,termName:"xterm",cancelEvents:!1,overviewRulerWidth:0};let G=["normal","bold","100","200","300","400","500","600","700","800","900"];class V extends U.Disposable{constructor(K){super(),this._onOptionChange=this.register(new Z.EventEmitter),this.onOptionChange=this._onOptionChange.event;let I={...Y.DEFAULT_OPTIONS};for(let z in K)if(z in I)try{let W=K[z];I[z]=this._sanitizeAndValidateOption(z,W)}catch(W){console.error(W)}this.rawOptions=I,this.options={...I},this._setupOptions(),this.register((0,U.toDisposable)(()=>{this.rawOptions.linkHandler=null,this.rawOptions.documentOverride=null}))}onSpecificOptionChange(K,I){return this.onOptionChange((z)=>{z===K&&I(this.rawOptions[K])})}onMultipleOptionChange(K,I){return this.onOptionChange((z)=>{K.indexOf(z)!==-1&&I()})}_setupOptions(){let K=(z)=>{if(!(z in Y.DEFAULT_OPTIONS))throw Error(`No option with key "${z}"`);return this.rawOptions[z]},I=(z,W)=>{if(!(z in Y.DEFAULT_OPTIONS))throw Error(`No option with key "${z}"`);W=this._sanitizeAndValidateOption(z,W),this.rawOptions[z]!==W&&(this.rawOptions[z]=W,this._onOptionChange.fire(z))};for(let z in this.rawOptions){let W={get:K.bind(this,z),set:I.bind(this,z)};Object.defineProperty(this.options,z,W)}}_sanitizeAndValidateOption(K,I){switch(K){case"cursorStyle":if(I||(I=Y.DEFAULT_OPTIONS[K]),!function(z){return z==="block"||z==="underline"||z==="bar"}(I))throw Error(`"${I}" is not a valid value for ${K}`);break;case"wordSeparator":I||(I=Y.DEFAULT_OPTIONS[K]);break;case"fontWeight":case"fontWeightBold":if(typeof I=="number"&&1<=I&&I<=1000)break;I=G.includes(I)?I:Y.DEFAULT_OPTIONS[K];break;case"cursorWidth":I=Math.floor(I);case"lineHeight":case"tabStopWidth":if(I<1)throw Error(`${K} cannot be less than 1, value: ${I}`);break;case"minimumContrastRatio":I=Math.max(1,Math.min(21,Math.round(10*I)/10));break;case"scrollback":if((I=Math.min(I,4294967295))<0)throw Error(`${K} cannot be less than 0, value: ${I}`);break;case"fastScrollSensitivity":case"scrollSensitivity":if(I<=0)throw Error(`${K} cannot be less than or equal to 0, value: ${I}`);break;case"rows":case"cols":if(!I&&I!==0)throw Error(`${K} must be numeric, value: ${I}`);break;case"windowsPty":I=I??{}}return I}}Y.OptionsService=V},660:function(F,Y,E){var Z=this&&this.__decorate||function(V,K,I,z){var W,H=arguments.length,q=H<3?K:z===null?z=Object.getOwnPropertyDescriptor(K,I):z;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")q=Reflect.decorate(V,K,I,z);else for(var N=V.length-1;N>=0;N--)(W=V[N])&&(q=(H<3?W(q):H>3?W(K,I,q):W(K,I))||q);return H>3&&q&&Object.defineProperty(K,I,q),q},U=this&&this.__param||function(V,K){return function(I,z){K(I,z,V)}};Object.defineProperty(Y,"__esModule",{value:!0}),Y.OscLinkService=void 0;let X=E(585),G=Y.OscLinkService=class{constructor(V){this._bufferService=V,this._nextId=1,this._entriesWithId=new Map,this._dataByLinkId=new Map}registerLink(V){let K=this._bufferService.buffer;if(V.id===void 0){let N=K.addMarker(K.ybase+K.y),w={data:V,id:this._nextId++,lines:[N]};return N.onDispose(()=>this._removeMarkerFromLink(w,N)),this._dataByLinkId.set(w.id,w),w.id}let I=V,z=this._getEntryIdKey(I),W=this._entriesWithId.get(z);if(W)return this.addLineToLink(W.id,K.ybase+K.y),W.id;let H=K.addMarker(K.ybase+K.y),q={id:this._nextId++,key:this._getEntryIdKey(I),data:I,lines:[H]};return H.onDispose(()=>this._removeMarkerFromLink(q,H)),this._entriesWithId.set(q.key,q),this._dataByLinkId.set(q.id,q),q.id}addLineToLink(V,K){let I=this._dataByLinkId.get(V);if(I&&I.lines.every((z)=>z.line!==K)){let z=this._bufferService.buffer.addMarker(K);I.lines.push(z),z.onDispose(()=>this._removeMarkerFromLink(I,z))}}getLinkData(V){return this._dataByLinkId.get(V)?.data}_getEntryIdKey(V){return`${V.id};;${V.uri}`}_removeMarkerFromLink(V,K){let I=V.lines.indexOf(K);I!==-1&&(V.lines.splice(I,1),V.lines.length===0&&(V.data.id!==void 0&&this._entriesWithId.delete(V.key),this._dataByLinkId.delete(V.id)))}};Y.OscLinkService=G=Z([U(0,X.IBufferService)],G)},343:(F,Y)=>{Object.defineProperty(Y,"__esModule",{value:!0}),Y.createDecorator=Y.getServiceDependencies=Y.serviceRegistry=void 0;let E="di$target",Z="di$dependencies";Y.serviceRegistry=new Map,Y.getServiceDependencies=function(U){return U[Z]||[]},Y.createDecorator=function(U){if(Y.serviceRegistry.has(U))return Y.serviceRegistry.get(U);let X=function(G,V,K){if(arguments.length!==3)throw Error("@IServiceName-decorator can only be used to decorate a parameter");(function(I,z,W){z[E]===z?z[Z].push({id:I,index:W}):(z[Z]=[{id:I,index:W}],z[E]=z)})(X,G,K)};return X.toString=()=>U,Y.serviceRegistry.set(U,X),X}},585:(F,Y,E)=>{Object.defineProperty(Y,"__esModule",{value:!0}),Y.IDecorationService=Y.IUnicodeService=Y.IOscLinkService=Y.IOptionsService=Y.ILogService=Y.LogLevelEnum=Y.IInstantiationService=Y.ICharsetService=Y.ICoreService=Y.ICoreMouseService=Y.IBufferService=void 0;let Z=E(343);var U;Y.IBufferService=(0,Z.createDecorator)("BufferService"),Y.ICoreMouseService=(0,Z.createDecorator)("CoreMouseService"),Y.ICoreService=(0,Z.createDecorator)("CoreService"),Y.ICharsetService=(0,Z.createDecorator)("CharsetService"),Y.IInstantiationService=(0,Z.createDecorator)("InstantiationService"),function(X){X[X.TRACE=0]="TRACE",X[X.DEBUG=1]="DEBUG",X[X.INFO=2]="INFO",X[X.WARN=3]="WARN",X[X.ERROR=4]="ERROR",X[X.OFF=5]="OFF"}(U||(Y.LogLevelEnum=U={})),Y.ILogService=(0,Z.createDecorator)("LogService"),Y.IOptionsService=(0,Z.createDecorator)("OptionsService"),Y.IOscLinkService=(0,Z.createDecorator)("OscLinkService"),Y.IUnicodeService=(0,Z.createDecorator)("UnicodeService"),Y.IDecorationService=(0,Z.createDecorator)("DecorationService")},480:(F,Y,E)=>{Object.defineProperty(Y,"__esModule",{value:!0}),Y.UnicodeService=void 0;let Z=E(460),U=E(225);class X{static extractShouldJoin(G){return(1&G)!=0}static extractWidth(G){return G>>1&3}static extractCharKind(G){return G>>3}static createPropertyValue(G,V,K=!1){return(16777215&G)<<3|(3&V)<<1|(K?1:0)}constructor(){this._providers=Object.create(null),this._active="",this._onChange=new Z.EventEmitter,this.onChange=this._onChange.event;let G=new U.UnicodeV6;this.register(G),this._active=G.version,this._activeProvider=G}dispose(){this._onChange.dispose()}get versions(){return Object.keys(this._providers)}get activeVersion(){return this._active}set activeVersion(G){if(!this._providers[G])throw Error(`unknown Unicode version "${G}"`);this._active=G,this._activeProvider=this._providers[G],this._onChange.fire(G)}register(G){this._providers[G.version]=G}wcwidth(G){return this._activeProvider.wcwidth(G)}getStringCellWidth(G){let V=0,K=0,I=G.length;for(let z=0;z<I;++z){let W=G.charCodeAt(z);if(55296<=W&&W<=56319){if(++z>=I)return V+this.wcwidth(W);let N=G.charCodeAt(z);56320<=N&&N<=57343?W=1024*(W-55296)+N-56320+65536:V+=this.wcwidth(N)}let H=this.charProperties(W,K),q=X.extractWidth(H);X.extractShouldJoin(H)&&(q-=X.extractWidth(K)),V+=q,K=H}return V}charProperties(G,V){return this._activeProvider.charProperties(G,V)}}Y.UnicodeService=X},781:(F,Y,E)=>{Object.defineProperty(Y,"__esModule",{value:!0}),Y.Terminal=void 0;let Z=E(437),U=E(969),X=E(460);class G extends U.CoreTerminal{constructor(V={}){super(V),this._onBell=this.register(new X.EventEmitter),this.onBell=this._onBell.event,this._onCursorMove=this.register(new X.EventEmitter),this.onCursorMove=this._onCursorMove.event,this._onTitleChange=this.register(new X.EventEmitter),this.onTitleChange=this._onTitleChange.event,this._onA11yCharEmitter=this.register(new X.EventEmitter),this.onA11yChar=this._onA11yCharEmitter.event,this._onA11yTabEmitter=this.register(new X.EventEmitter),this.onA11yTab=this._onA11yTabEmitter.event,this._setup(),this.register(this._inputHandler.onRequestBell(()=>this.bell())),this.register(this._inputHandler.onRequestReset(()=>this.reset())),this.register((0,X.forwardEvent)(this._inputHandler.onCursorMove,this._onCursorMove)),this.register((0,X.forwardEvent)(this._inputHandler.onTitleChange,this._onTitleChange)),this.register((0,X.forwardEvent)(this._inputHandler.onA11yChar,this._onA11yCharEmitter)),this.register((0,X.forwardEvent)(this._inputHandler.onA11yTab,this._onA11yTabEmitter))}get buffer(){return this.buffers.active}get markers(){return this.buffer.markers}addMarker(V){if(this.buffer===this.buffers.normal)return this.buffer.addMarker(this.buffer.ybase+this.buffer.y+V)}bell(){this._onBell.fire()}input(V,K=!0){this.coreService.triggerDataEvent(V,K)}resize(V,K){V===this.cols&&K===this.rows||super.resize(V,K)}clear(){if(this.buffer.ybase!==0||this.buffer.y!==0){this.buffer.lines.set(0,this.buffer.lines.get(this.buffer.ybase+this.buffer.y)),this.buffer.lines.length=1,this.buffer.ydisp=0,this.buffer.ybase=0,this.buffer.y=0;for(let V=1;V<this.rows;V++)this.buffer.lines.push(this.buffer.getBlankLine(Z.DEFAULT_ATTR_DATA));this._onScroll.fire({position:this.buffer.ydisp,source:0})}}reset(){this.options.rows=this.rows,this.options.cols=this.cols,this._setup(),super.reset()}}Y.Terminal=G}},Q={};function $(F){var Y=Q[F];if(Y!==void 0)return Y.exports;var E=Q[F]={exports:{}};return A[F].call(E.exports,E,E.exports,$),E.exports}var B={};(()=>{var F=B;Object.defineProperty(F,"__esModule",{value:!0}),F.Terminal=void 0;let Y=$(285),E=$(975),Z=$(90),U=$(781),X=$(741),G=$(844),V=["cols","rows"];class K extends G.Disposable{constructor(I){super(),this._core=this.register(new U.Terminal(I)),this._addonManager=this.register(new X.AddonManager),this._publicOptions={...this._core.options};let z=(H)=>this._core.options[H],W=(H,q)=>{this._checkReadonlyOptions(H),this._core.options[H]=q};for(let H in this._core.options){Object.defineProperty(this._publicOptions,H,{get:()=>this._core.options[H],set:(N)=>{this._checkReadonlyOptions(H),this._core.options[H]=N}});let q={get:z.bind(this,H),set:W.bind(this,H)};Object.defineProperty(this._publicOptions,H,q)}}_checkReadonlyOptions(I){if(V.includes(I))throw Error(`Option "${I}" can only be set in the constructor`)}_checkProposedApi(){if(!this._core.optionsService.options.allowProposedApi)throw Error("You must set the allowProposedApi option to true to use proposed API")}get onBell(){return this._core.onBell}get onBinary(){return this._core.onBinary}get onCursorMove(){return this._core.onCursorMove}get onData(){return this._core.onData}get onLineFeed(){return this._core.onLineFeed}get onResize(){return this._core.onResize}get onScroll(){return this._core.onScroll}get onTitleChange(){return this._core.onTitleChange}get parser(){return this._checkProposedApi(),this._parser||(this._parser=new E.ParserApi(this._core)),this._parser}get unicode(){return this._checkProposedApi(),new Z.UnicodeApi(this._core)}get rows(){return this._core.rows}get cols(){return this._core.cols}get buffer(){return this._checkProposedApi(),this._buffer||(this._buffer=this.register(new Y.BufferNamespaceApi(this._core))),this._buffer}get markers(){return this._checkProposedApi(),this._core.markers}get modes(){let I=this._core.coreService.decPrivateModes,z="none";switch(this._core.coreMouseService.activeProtocol){case"X10":z="x10";break;case"VT200":z="vt200";break;case"DRAG":z="drag";break;case"ANY":z="any"}return{applicationCursorKeysMode:I.applicationCursorKeys,applicationKeypadMode:I.applicationKeypad,bracketedPasteMode:I.bracketedPasteMode,insertMode:this._core.coreService.modes.insertMode,mouseTrackingMode:z,originMode:I.origin,reverseWraparoundMode:I.reverseWraparound,sendFocusMode:I.sendFocus,wraparoundMode:I.wraparound}}get options(){return this._publicOptions}set options(I){for(let z in I)this._publicOptions[z]=I[z]}input(I,z=!0){this._core.input(I,z)}resize(I,z){this._verifyIntegers(I,z),this._core.resize(I,z)}registerMarker(I=0){return this._checkProposedApi(),this._verifyIntegers(I),this._core.addMarker(I)}addMarker(I){return this.registerMarker(I)}dispose(){super.dispose()}scrollLines(I){this._verifyIntegers(I),this._core.scrollLines(I)}scrollPages(I){this._verifyIntegers(I),this._core.scrollPages(I)}scrollToTop(){this._core.scrollToTop()}scrollToBottom(){this._core.scrollToBottom()}scrollToLine(I){this._verifyIntegers(I),this._core.scrollToLine(I)}clear(){this._core.clear()}write(I,z){this._core.write(I,z)}writeln(I,z){this._core.write(I),this._core.write(`\r
2661
2661
  `,z)}reset(){this._core.reset()}loadAddon(I){this._addonManager.loadAddon(this,I)}_verifyIntegers(...I){for(let z of I)if(z===1/0||isNaN(z)||z%1!=0)throw Error("This API only accepts integers")}}F.Terminal=K})();var D=mj4;for(var J in B)D[J]=B[J];B.__esModule&&Object.defineProperty(D,"__esModule",{value:!0})})()});function g23(A){return`${A.description}
2662
2662
  \`\`\`json
@@ -4795,13 +4795,13 @@ ${I}`))}},error:(K)=>{if(!V)V=!0,Z(Error(`Failed to spawn brew: ${K.message}`))}
4795
4795
  ${I}`;if(F==="pnpm"&&I.includes("Unable to find the global bin directory"))z+=`
4796
4796
 
4797
4797
  Hint: Try running "pnpm setup" to configure pnpm global directory, or use npm instead:
4798
- npm install -g ${J}`;Z(Error(z))}},error:(K)=>{if(!G)G=!0,Z(Error(`Failed to spawn ${F}: ${K.message}`))},complete:()=>{if(!G)G=!0,E()}})})}p0();p0();Iz();var iC3="@ampcode/cli";async function gE0(A,Q,$=iC3){let D=`${Q||"https://registry.npmjs.org"}/${$}/latest`,J=new AbortController,F=setTimeout(()=>J.abort(),5000);try{let Y=await fetch(D,{signal:J.signal});if(!Y.ok)return{hasUpdate:!1,currentVersion:A,source:"npm"};let E=await Y.json(),Z=E.version??E["dist-tags"]?.latest;if(!Z)return{hasUpdate:!1,currentVersion:A,source:"npm"};let U=eo(A,Z),X=U<0,G,V;if(E.time){let K=E.time[A],I=E.time[Z],z=Date.now();if(K)G=Math.floor((z-new Date(K).getTime())/3600000);if(I)V=Math.floor((z-new Date(I).getTime())/3600000)}return P.info("NPM version comparison",{currentVersion:A,latestVersion:Z,compareResult:U,hasUpdate:X,currentVersionAge:G,latestVersionAge:V}),{hasUpdate:X,latestVersion:Z,currentVersion:A,currentVersionAge:G,latestVersionAge:V,source:"npm"}}catch(Y){return P.debug("Error checking npm version",{error:Y}),{hasUpdate:!1,currentVersion:A,source:"npm"}}finally{clearTimeout(F)}}var nC3="https://static.ampcode.com/cli/cli-version.txt";async function mE0(A){let Q=new AbortController,$=setTimeout(()=>Q.abort(),5000);try{let B=await fetch(`${nC3}?t=${Date.now()}`,{signal:Q.signal,cache:"no-store"});if(!B.ok)return{hasUpdate:!1,currentVersion:A,source:"bin"};let D=(await B.text()).trim();if(!D||!/^\d+\.\d+\.\d+/.test(D))return{hasUpdate:!1,currentVersion:A,source:"bin"};let J=eo(A,D),F=J<0;return P.info("Bin version comparison",{currentVersion:A,latestVersion:D,compareResult:J,hasUpdate:F}),{hasUpdate:F,latestVersion:D,currentVersion:A,source:"bin"}}catch(B){return P.debug("Error checking bin version",{error:B}),{hasUpdate:!1,currentVersion:A,source:"bin"}}finally{clearTimeout($)}}var aC3=604800000;function db4(A){if(!A)return null;let Q=typeof A==="number"?A:new Date(A).getTime();if(isNaN(Q))return null;let $=Date.now()-Q;if($>aC3)return{ageMs:$};return null}function eo(A,Q){let $=(F)=>{let[Y,E]=F.split("-");return{parts:Y?.split(".").map(Number)||[],label:E}},B=$(A),D=$(Q),J=Math.max(B.parts.length,D.parts.length);for(let F=0;F<J;F++){let Y=B.parts[F]||0,E=D.parts[F]||0;if(Y<E)return-1;if(Y>E)return 1}if(B.label===D.label)return 0;if(!B.label&&D.label)return 1;if(B.label&&!D.label)return-1;if(B.label&&D.label)return B.label<D.label?-1:1;return 0}function Ar(A){try{let Q=A.match(/^0\.0\.(\d+)(?:-(.+))?/);if(!Q)return null;let $=parseInt(Q[1],10),B=$!==0?$*1000:void 0,J=Q[2]?.match(/^g?([a-f0-9]+)$/)?.[1],F=B!==void 0?uY(B):void 0;return{sha:J,timestamp:B,age:F}}catch{return null}}P1();p0();import{readFile as oC3,realpath as rC3}from"node:fs/promises";import{dirname as pb4,join as sC3}from"node:path";async function cb4(A){switch(A){case"binary":case"brew":return tC3(so());case"npm":case"pnpm":case"yarn":case"bun":return eC3()}}async function tC3(A){let Q=await MN(A,["--version"],5000);if(Q.reason!=="success")return P.debug("failed to read version from binary",{binaryPath:A,result:Q}),null;return Q.output.trim().split(/\s+/)[0]||null}async function eC3(){try{let A=process.argv[1];if(!A)return null;let Q=await rC3(A),$=pb4(pb4(Q));return await AM3(sC3($,"package.json"))}catch(A){return P.debug("failed to read installed version from package.json",{error:A}),null}}async function AM3(A){let Q=await oC3(A,"utf8"),$=JSON.parse(Q);if(!$.name||!ee0($.name))return P.debug("package.json name mismatch",{pkgJsonPath:A,name:$.name}),null;return $.version||null}p0();import{spawn as QM3}from"node:child_process";function F01(A){if(A=A.replace(/\/$/,""),!A.startsWith("http://")&&!A.startsWith("https://"))A=`https://${A}`;try{return new URL(A),A}catch{return P.warn(`Invalid registry URL: ${A}, falling back to npmjs.org`),"https://registry.npmjs.org"}}var dE0=null,Qr=null;function lb4(A){return new Promise((Q)=>{let $=QM3("npm",["config","get",A],{stdio:["ignore","pipe","ignore"],timeout:5000,shell:process.platform==="win32"}),B="";$.stdout.on("data",(D)=>{B+=D.toString()}),$.on("close",(D,J)=>{if(D!==0||J==="SIGTERM"){Q(null);return}let F=B.trim();Q(F&&F!=="undefined"?F:null)}),$.on("error",()=>{Q(null)})})}async function pE0(){if(dE0)return dE0;if(Qr)return Qr;Qr=(async()=>{let A=process.env.NPM_CONFIG_REGISTRY??process.env.npm_config_registry;if(A)return F01(A);let Q=await lb4("@sourcegraph:registry");if(Q)return F01(Q);let $=await lb4("registry");if($)return F01($);return"https://registry.npmjs.org"})();try{return dE0=await Qr,dE0}finally{Qr=null}}var $M3=3600000,BM3=5000;function cE0(A,Q,$={}){let B=new p4,D=B.pipe(t6({shouldCountRefs:!1})),J=$.startDelayMs??0,F=$.checkIntervalMs??$M3,Y=!1,E=()=>{Y=!0};return setImmediate(async()=>{let Z=P.getChild("update");if(J>0){if(await BG(J),Y)return}let U=D.subscribe({next:(G)=>{Z.debug("emit new state",G)}}),X=A;try{while(!Y){let G=await DM3(X,Q,Z,B);if(G.stop)return;if(G.updatedTo)X=G.updatedTo;if(G.emittedVisibleState){if(await BG(BM3),Y)return;B.next("hidden")}if(F<=0)return;let V=1000,K=F;while(K>0&&!Y){let I=Math.min(V,K);await BG(I),K-=I}}}finally{U.unsubscribe(),B.complete()}}),{state:D,dispose:E}}async function DM3(A,Q,$,B){let D={stop:!1,emittedVisibleState:!1};try{if(process.env.AMP_SKIP_UPDATE_CHECK==="1")return $.debug("checking disabled via AMP_SKIP_UPDATE_CHECK environment variable"),D.stop=!0,D;let J=await Q.get("updates.mode");if(J==="disabled")return $.debug("checking disabled"),D.stop=!0,D;let F=await kG(),Y=F==="binary"||F==="brew",E=Y?void 0:await LN();$.debug("checking",{currentVersion:A,mode:J,packageManager:F,isBinaryDistribution:Y,npmPackageName:E});let Z;if(Y)Z=await mE0(A);else{let G=await pE0();Z=await gE0(A,G,E)}if(!(Z.latestVersion&&Z.hasUpdate))return $.debug("no update available"),D;let U=(G)=>{B.next(G),D.emittedVisibleState=!0};if(F){let G=await cb4(F);if(G&&eo(G,Z.latestVersion)>=0){if($.debug("on-disk version already up to date",{currentVersion:A,installedVersion:G,latestVersion:Z.latestVersion}),D.updatedTo=G,eo(A,G)<0){let V=await pz(G),K={from:A,to:G,externallyUpdated:!0,...V};if(V.status==="same")$.info("on-disk already updated by another instance",K),U("updated");else $.warn("on-disk already updated by another instance, with PATH warning",K),U("updated-with-warning")}return D}}let X=()=>{if(Z.currentVersionAge!==void 0&&Z.latestVersionAge!==void 0){let G=Z.currentVersionAge-Z.latestVersionAge,V=0.5;if(Math.abs(G)<0.5)return $.debug("versions too close together, suppressing update warning",{currentVersionAge:Z.currentVersionAge,latestVersionAge:Z.latestVersionAge,ageDifferenceHours:G}),!0}return!1};if(!J)J=F==="pnpm"?"warn":"auto",$.debug("no configured update mode; selected default based on package manager",{packageManager:F,mode:J});if(F==="brew"){if(!X())U("update-available-brew");return D}if(F==="binary"&&process.execPath!==so()){if($.debug("non-standard binary path, showing warning"),!X())U("update-available-unrecognized-path");return D}if(J==="warn"){if(!X())U("update-available");return D}if(!F){if($.debug("auto-update not supported, falling back to warn mode"),!X())U("update-available");return D}try{await to(Z.latestVersion,F),D.updatedTo=Z.latestVersion;let G=await pz(Z.latestVersion),V={from:Z.currentVersion,to:Z.latestVersion,...G};if(G.status==="same")$.info("success",V),U("updated");else $.warn("success with warning",V),U("updated-with-warning")}catch(G){U("update-error")}return D}catch(J){return $.debug("check failed",{error:J}),D}}Iz();import{stderr as aY}from"node:process";function ib4(A){let Q=new DN().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(B)=>{await se0(B.force||!1,B.verbose||!1,"0.0.1779296280-g014378"),process.exit()});A.addCommand(Q,{hidden:!0});let $=new DN("update").alias("up").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(B)=>{await YM3(B.targetVersion)});A.addCommand($)}function JM3(A){let Q=Boolean(A.isTTY),$=0,B=!1;function D(){if(!Q||!B)return;A.write(`
4798
+ npm install -g ${J}`;Z(Error(z))}},error:(K)=>{if(!G)G=!0,Z(Error(`Failed to spawn ${F}: ${K.message}`))},complete:()=>{if(!G)G=!0,E()}})})}p0();p0();Iz();var iC3="@ampcode/cli";async function gE0(A,Q,$=iC3){let D=`${Q||"https://registry.npmjs.org"}/${$}/latest`,J=new AbortController,F=setTimeout(()=>J.abort(),5000);try{let Y=await fetch(D,{signal:J.signal});if(!Y.ok)return{hasUpdate:!1,currentVersion:A,source:"npm"};let E=await Y.json(),Z=E.version??E["dist-tags"]?.latest;if(!Z)return{hasUpdate:!1,currentVersion:A,source:"npm"};let U=eo(A,Z),X=U<0,G,V;if(E.time){let K=E.time[A],I=E.time[Z],z=Date.now();if(K)G=Math.floor((z-new Date(K).getTime())/3600000);if(I)V=Math.floor((z-new Date(I).getTime())/3600000)}return P.info("NPM version comparison",{currentVersion:A,latestVersion:Z,compareResult:U,hasUpdate:X,currentVersionAge:G,latestVersionAge:V}),{hasUpdate:X,latestVersion:Z,currentVersion:A,currentVersionAge:G,latestVersionAge:V,source:"npm"}}catch(Y){return P.debug("Error checking npm version",{error:Y}),{hasUpdate:!1,currentVersion:A,source:"npm"}}finally{clearTimeout(F)}}var nC3="https://static.ampcode.com/cli/cli-version.txt";async function mE0(A){let Q=new AbortController,$=setTimeout(()=>Q.abort(),5000);try{let B=await fetch(`${nC3}?t=${Date.now()}`,{signal:Q.signal,cache:"no-store"});if(!B.ok)return{hasUpdate:!1,currentVersion:A,source:"bin"};let D=(await B.text()).trim();if(!D||!/^\d+\.\d+\.\d+/.test(D))return{hasUpdate:!1,currentVersion:A,source:"bin"};let J=eo(A,D),F=J<0;return P.info("Bin version comparison",{currentVersion:A,latestVersion:D,compareResult:J,hasUpdate:F}),{hasUpdate:F,latestVersion:D,currentVersion:A,source:"bin"}}catch(B){return P.debug("Error checking bin version",{error:B}),{hasUpdate:!1,currentVersion:A,source:"bin"}}finally{clearTimeout($)}}var aC3=604800000;function db4(A){if(!A)return null;let Q=typeof A==="number"?A:new Date(A).getTime();if(isNaN(Q))return null;let $=Date.now()-Q;if($>aC3)return{ageMs:$};return null}function eo(A,Q){let $=(F)=>{let[Y,E]=F.split("-");return{parts:Y?.split(".").map(Number)||[],label:E}},B=$(A),D=$(Q),J=Math.max(B.parts.length,D.parts.length);for(let F=0;F<J;F++){let Y=B.parts[F]||0,E=D.parts[F]||0;if(Y<E)return-1;if(Y>E)return 1}if(B.label===D.label)return 0;if(!B.label&&D.label)return 1;if(B.label&&!D.label)return-1;if(B.label&&D.label)return B.label<D.label?-1:1;return 0}function Ar(A){try{let Q=A.match(/^0\.0\.(\d+)(?:-(.+))?/);if(!Q)return null;let $=parseInt(Q[1],10),B=$!==0?$*1000:void 0,J=Q[2]?.match(/^g?([a-f0-9]+)$/)?.[1],F=B!==void 0?uY(B):void 0;return{sha:J,timestamp:B,age:F}}catch{return null}}P1();p0();import{readFile as oC3,realpath as rC3}from"node:fs/promises";import{dirname as pb4,join as sC3}from"node:path";async function cb4(A){switch(A){case"binary":case"brew":return tC3(so());case"npm":case"pnpm":case"yarn":case"bun":return eC3()}}async function tC3(A){let Q=await MN(A,["--version"],5000);if(Q.reason!=="success")return P.debug("failed to read version from binary",{binaryPath:A,result:Q}),null;return Q.output.trim().split(/\s+/)[0]||null}async function eC3(){try{let A=process.argv[1];if(!A)return null;let Q=await rC3(A),$=pb4(pb4(Q));return await AM3(sC3($,"package.json"))}catch(A){return P.debug("failed to read installed version from package.json",{error:A}),null}}async function AM3(A){let Q=await oC3(A,"utf8"),$=JSON.parse(Q);if(!$.name||!ee0($.name))return P.debug("package.json name mismatch",{pkgJsonPath:A,name:$.name}),null;return $.version||null}p0();import{spawn as QM3}from"node:child_process";function F01(A){if(A=A.replace(/\/$/,""),!A.startsWith("http://")&&!A.startsWith("https://"))A=`https://${A}`;try{return new URL(A),A}catch{return P.warn(`Invalid registry URL: ${A}, falling back to npmjs.org`),"https://registry.npmjs.org"}}var dE0=null,Qr=null;function lb4(A){return new Promise((Q)=>{let $=QM3("npm",["config","get",A],{stdio:["ignore","pipe","ignore"],timeout:5000,shell:process.platform==="win32"}),B="";$.stdout.on("data",(D)=>{B+=D.toString()}),$.on("close",(D,J)=>{if(D!==0||J==="SIGTERM"){Q(null);return}let F=B.trim();Q(F&&F!=="undefined"?F:null)}),$.on("error",()=>{Q(null)})})}async function pE0(){if(dE0)return dE0;if(Qr)return Qr;Qr=(async()=>{let A=process.env.NPM_CONFIG_REGISTRY??process.env.npm_config_registry;if(A)return F01(A);let Q=await lb4("@sourcegraph:registry");if(Q)return F01(Q);let $=await lb4("registry");if($)return F01($);return"https://registry.npmjs.org"})();try{return dE0=await Qr,dE0}finally{Qr=null}}var $M3=3600000,BM3=5000;function cE0(A,Q,$={}){let B=new p4,D=B.pipe(t6({shouldCountRefs:!1})),J=$.startDelayMs??0,F=$.checkIntervalMs??$M3,Y=!1,E=()=>{Y=!0};return setImmediate(async()=>{let Z=P.getChild("update");if(J>0){if(await BG(J),Y)return}let U=D.subscribe({next:(G)=>{Z.debug("emit new state",G)}}),X=A;try{while(!Y){let G=await DM3(X,Q,Z,B);if(G.stop)return;if(G.updatedTo)X=G.updatedTo;if(G.emittedVisibleState){if(await BG(BM3),Y)return;B.next("hidden")}if(F<=0)return;let V=1000,K=F;while(K>0&&!Y){let I=Math.min(V,K);await BG(I),K-=I}}}finally{U.unsubscribe(),B.complete()}}),{state:D,dispose:E}}async function DM3(A,Q,$,B){let D={stop:!1,emittedVisibleState:!1};try{if(process.env.AMP_SKIP_UPDATE_CHECK==="1")return $.debug("checking disabled via AMP_SKIP_UPDATE_CHECK environment variable"),D.stop=!0,D;let J=await Q.get("updates.mode");if(J==="disabled")return $.debug("checking disabled"),D.stop=!0,D;let F=await kG(),Y=F==="binary"||F==="brew",E=Y?void 0:await LN();$.debug("checking",{currentVersion:A,mode:J,packageManager:F,isBinaryDistribution:Y,npmPackageName:E});let Z;if(Y)Z=await mE0(A);else{let G=await pE0();Z=await gE0(A,G,E)}if(!(Z.latestVersion&&Z.hasUpdate))return $.debug("no update available"),D;let U=(G)=>{B.next(G),D.emittedVisibleState=!0};if(F){let G=await cb4(F);if(G&&eo(G,Z.latestVersion)>=0){if($.debug("on-disk version already up to date",{currentVersion:A,installedVersion:G,latestVersion:Z.latestVersion}),D.updatedTo=G,eo(A,G)<0){let V=await pz(G),K={from:A,to:G,externallyUpdated:!0,...V};if(V.status==="same")$.info("on-disk already updated by another instance",K),U("updated");else $.warn("on-disk already updated by another instance, with PATH warning",K),U("updated-with-warning")}return D}}let X=()=>{if(Z.currentVersionAge!==void 0&&Z.latestVersionAge!==void 0){let G=Z.currentVersionAge-Z.latestVersionAge,V=0.5;if(Math.abs(G)<0.5)return $.debug("versions too close together, suppressing update warning",{currentVersionAge:Z.currentVersionAge,latestVersionAge:Z.latestVersionAge,ageDifferenceHours:G}),!0}return!1};if(!J)J=F==="pnpm"?"warn":"auto",$.debug("no configured update mode; selected default based on package manager",{packageManager:F,mode:J});if(F==="brew"){if(!X())U("update-available-brew");return D}if(F==="binary"&&process.execPath!==so()){if($.debug("non-standard binary path, showing warning"),!X())U("update-available-unrecognized-path");return D}if(J==="warn"){if(!X())U("update-available");return D}if(!F){if($.debug("auto-update not supported, falling back to warn mode"),!X())U("update-available");return D}try{await to(Z.latestVersion,F),D.updatedTo=Z.latestVersion;let G=await pz(Z.latestVersion),V={from:Z.currentVersion,to:Z.latestVersion,...G};if(G.status==="same")$.info("success",V),U("updated");else $.warn("success with warning",V),U("updated-with-warning")}catch(G){U("update-error")}return D}catch(J){return $.debug("check failed",{error:J}),D}}Iz();import{stderr as aY}from"node:process";function ib4(A){let Q=new DN().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(B)=>{await se0(B.force||!1,B.verbose||!1,"0.0.1779313683-gf89f27"),process.exit()});A.addCommand(Q,{hidden:!0});let $=new DN("update").alias("up").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(B)=>{await YM3(B.targetVersion)});A.addCommand($)}function JM3(A){let Q=Boolean(A.isTTY),$=0,B=!1;function D(){if(!Q||!B)return;A.write(`
4799
4799
  `),B=!1,$=0}function J(F){if(!Q)return;let Y=F.padEnd($," ");A.write(`\r${Y}`),B=!0,$=Y.length}return{flushProgressLine:D,renderProgress:J}}function FM3(A){if(A.source==="npm"&&A.latestVersionAge!==void 0&&A.latestVersionAge>36)aY.write(t0.yellow(`The latest Amp CLI version reported by npm is older than expected. Be aware that you may be using an npm proxy with a corporate policy to delay package updates.
4800
4800
  `))}async function YM3(A){let $=process.platform==="win32"&&yj()?{currentExecutablePath:process.execPath}:void 0,{flushProgressLine:B,renderProgress:D}=JM3(aY);if(process.env.AMP_SKIP_UPDATE_CHECK==="1")aY.write(t0.yellow(`Note: AMP_SKIP_UPDATE_CHECK=1 is set, which disables automatic update checking. Manual updates will still work.
4801
4801
 
4802
4802
  `));try{if(!A){aY.write(t0.blue(`Checking for updates...
4803
- `));let Y=!1,E;if(yj()){let Z=await mE0("0.0.1779296280-g014378");Y=Z.hasUpdate,E=Z.latestVersion}else{let Z=await pE0(),U=await LN(),X=await gE0("0.0.1779296280-g014378",Z,U);FM3(X),Y=X.hasUpdate,E=X.latestVersion}if(!Y){let Z=Ar("0.0.1779296280-g014378"),U=Z?.age?`released ${Z.age} ago`:`built ${uY(new Date("2026-05-20T17:03:06.980Z"))} ago`;aY.write(t0.green(`✓ Amp is already up to date on version ${"0.0.1779296280-g014378"} (${U})
4804
- `));let X=await pz("0.0.1779296280-g014378",$);if(X.warning)aY.write(`
4803
+ `));let Y=!1,E;if(yj()){let Z=await mE0("0.0.1779313683-gf89f27");Y=Z.hasUpdate,E=Z.latestVersion}else{let Z=await pE0(),U=await LN(),X=await gE0("0.0.1779313683-gf89f27",Z,U);FM3(X),Y=X.hasUpdate,E=X.latestVersion}if(!Y){let Z=Ar("0.0.1779313683-gf89f27"),U=Z?.age?`released ${Z.age} ago`:`built ${uY(new Date("2026-05-20T21:52:35.567Z"))} ago`;aY.write(t0.green(`✓ Amp is already up to date on version ${"0.0.1779313683-gf89f27"} (${U})
4804
+ `));let X=await pz("0.0.1779313683-gf89f27",$);if(X.warning)aY.write(`
4805
4805
  `+t0.yellow(X.warning)+`
4806
4806
  `);process.exit(0)}if(!E)aY.write(t0.yellow("[WARN] could not find latest version")),process.exit(0);A=E}aY.write(t0.blue(`Updating to version ${A}...
4807
4807
  `)),await to(A,void 0,(Y)=>{B(),aY.write(t0.dim(`Running: ${Y}
@@ -5230,7 +5230,7 @@ ${B}`).join(`
5230
5230
  `).length,D=new d({text:new C(A,new T({color:$}))});if(B<=IX0)return D;return new X0({width:1/0,height:IX0,child:new i8({autofocus:!1,controller:Q,child:D})})}function Nb3(){return new Map([[G1.key("PageUp"),new WX0],[G1.key("PageDown"),new a61],[G1.ctrl("u"),new WX0],[G1.shift("Home"),new o61],[G1.shift("End"),new r61]])}function wb3(A,Q,$){return Math.max(Q,Math.min(A,$))}var s61=8,da4=1,pa4=s61-1;class t61 extends V4{}class e61 extends V4{}class HX0 extends V4{}class qX0 extends V4{}class AA1 extends V4{}class QA1 extends V4{}class $A1 extends P0{props;constructor(A){super(A.key===void 0?{}:{key:A.key});this.props=A}createState(){return new ca4}}class ca4 extends R0{messageScroll=new v6;initState(){super.initState(),this.messageScroll.followMode=!1,this.messageScroll.jumpTo(0)}dispose(){this.messageScroll.dispose(),super.dispose()}build(A){let Q=this.widget.props,$=Cb3(Q,this.messageScroll),B=Mb3(Q.options.message),D=B?new x4({actions:this.buildScrollActions(),child:new kA({debugLabel:"NeoSelectDialogScrollShortcuts",shortcuts:Ob3(),child:$})}):$,J=[{keys:["↑/↓","j/k"],label:"move"},{keys:["Enter"],label:"select"}];if(B)J.push({keys:["Ctrl+E","Ctrl+Y"],label:"scroll"});return J.push({keys:["Esc"],label:"cancel"}),new w6({header:Q.options.title,minWidth:64,maxWidth:80,footer:J,autofocus:!1,onDismiss:Q.onCancel,child:D})}buildScrollActions(){let A=(Q)=>{let $=jb3(this.messageScroll.offset+Q,0,this.messageScroll.maxScrollExtent);this.messageScroll.jumpTo($)};return new Map([[t61,new T1(()=>A(-da4))],[e61,new T1(()=>A(da4))],[HX0,new T1(()=>A(-pa4))],[qX0,new T1(()=>A(pa4))],[AA1,new T1(()=>this.messageScroll.jumpTo(0))],[QA1,new T1(()=>this.messageScroll.jumpTo(this.messageScroll.maxScrollExtent))]])}}function Cb3(A,Q){let $=A.options.options.map((D)=>({value:D,label:D})),B=Math.max(0,$.findIndex((D)=>D.value===A.options.initialValue));return new I8({options:$,selectedIndex:B,body:Lb3(A.options.message,Q),onSelect:(D)=>{if(D===null){A.onCancel();return}A.onSelect(D)},padding:V0.all(0),showBorder:!1,showDismissalMessage:!1,enableMouseInteraction:!0,wrapOptions:!0})}function Mb3(A){if(A===void 0)return!1;return A.split(`
5231
5231
  `).length>s61}function Lb3(A,Q){if(A===void 0)return;let $=A.split(`
5232
5232
  `).length,B=Math.min($,s61);return new X0({width:1/0,height:B,child:new i8({autofocus:!1,controller:Q,child:new d({text:new C(A)})})})}function Ob3(){return new Map([[G1.key("PageUp"),new HX0],[G1.key("PageDown"),new qX0],[G1.ctrl("u"),new HX0],[G1.ctrl("d"),new qX0],[G1.ctrl("y"),new t61],[G1.ctrl("e"),new e61],[G1.shift("Home"),new AA1],[G1.shift("End"),new QA1]])}function jb3(A,Q,$){return Math.max(Q,Math.min(A,$))}var Rb3=3,Pb3=new m6("NeoPluginDialogOverlay");function la4(A,Q,$){if($!==void 0)return{type:"response",id:A,error:$};if(Q===void 0)return{type:"response",id:A};return{type:"response",id:A,result:Q}}class BA1{options;unregisterPluginCommands=null;pluginCommandSubscriptions=[];pluginErrorToastKeys=new Set;activeDialog=null;queuedDialogs=[];resolvingDialog=null;pendingOwnerUIRequests=new Map;pendingActorUIRequests=new Map;stateBackedRequestIDs=new Set;pluginUIRespondRequestCounter=0;statusItems=new Map;disposed=!1;constructor(A){this.options=A}init(){this.disposed=!1,this.configurePluginPlatform(),this.subscribePluginCommands()}dispose(){this.disposed=!0,this.unregisterPluginCommands?.(),this.unregisterPluginCommands=null;for(let A of this.pluginCommandSubscriptions)A.unsubscribe();this.pluginCommandSubscriptions=[],this.cancelOwnerUIRequests(),this.cancelPendingDialogs(),this.statusItems.clear(),this.clearPluginPlatformStatusHandlers()}handlePluginMessage(A,Q){let $=A.message;if($.type==="response"){this.cancelOwnerUIRequest($.id),this.cancelActorUIRequest($.id);return}if($.type==="event"){if(this.handlePluginUIStateEvent($,Q))return;this.handlePluginEvent($);return}if(this.stateBackedRequestIDs.has($.id))return;if(!dY0($.method))return;this.handleOwnerUIRequest($,Q)}cancelOwnerUIRequests(){let A=[...this.pendingOwnerUIRequests.values(),...this.pendingActorUIRequests.values()];this.pendingOwnerUIRequests.clear(),this.pendingActorUIRequests.clear(),this.stateBackedRequestIDs.clear();for(let Q of A)Q.abort()}hasBlockingDialog(){return this.activeDialog!==null}buildDialogLayers(){let A=this.activeDialog;if(!A)return[];return[new k4({key:Pb3,debugLabel:"PluginDialogOverlay",autofocus:!1,canRequestFocus:!0,child:this.buildActiveDialog(A)})]}buildActiveDialog(A){switch(A.kind){case"input":return new ps({key:new nz(A),header:A.options.title??"Input",helpText:A.options.helpText,initialValue:A.options.initialValue,isRequired:!1,onSubmit:(Q)=>this.resolveInputDialog(A,Q),onDismiss:()=>this.resolveInputDialog(A,void 0)});case"confirm":return new n61({key:new nz(A),options:A.options,onConfirm:()=>this.resolveConfirmDialog(A,!0),onCancel:()=>this.resolveConfirmDialog(A,!1)});case"select":return new $A1({key:new nz(A),options:A.options,onSelect:(Q)=>this.resolveSelectDialog(A,Q),onCancel:()=>this.resolveSelectDialog(A,void 0)})}}getStatusItems(){return[...this.statusItems.values()].flatMap((A)=>A.value===void 0?[]:[{pluginURI:A.pluginURI,id:A.id,value:A.value}])}configurePluginPlatform(){let A=this.options.neoContext.pluginPlatform;if(!A)return;A.showToast=(Q)=>this.options.toastController.show(Q,"success"),A.showOpenedURLToast=(Q)=>{this.options.toastController.show(`Opened URL: ${Q}`,"success",8000)},A.appendToThreadHandler=this.options.neoContext.observerOnly?async()=>{throw Error("thread.append is only available from an executor-owned plugin runtime")}:this.options.appendToThread,A.showInputDialog=this.showInputDialog,A.showConfirmDialog=this.showConfirmDialog,A.showSelectDialog=this.showSelectDialog,A.createStatusItemHandler=this.createStatusItem,A.updateStatusItemHandler=this.updateStatusItem,A.removeStatusItemHandler=this.removeStatusItem}handlePluginEvent(A){if(A.event!=="ui.notify")return;let Q=A.data;if(typeof Q.message==="string")this.options.toastController.show(Q.message,"success")}async handleOwnerUIRequest(A,Q){let $=new AbortController;this.pendingOwnerUIRequests.set(A.id,$);try{let B=await this.dispatchOwnerUIRequest(A,$.signal);if(this.pendingOwnerUIRequests.get(A.id)!==$)return;this.pendingOwnerUIRequests.delete(A.id),Q(la4(A.id,B))}catch(B){if(this.pendingOwnerUIRequests.get(A.id)!==$)return;this.pendingOwnerUIRequests.delete(A.id),Q(la4(A.id,void 0,B instanceof Error?B.message:String(B)))}}dispatchOwnerUIRequest(A,Q){switch(A.method){case"ui.input":return this.showInputDialog(A.params.options,Q);case"ui.confirm":return this.showConfirmDialog(A.params.options,Q);case"ui.select":return this.showSelectDialog(A.params.options,Q);default:throw Error(`Unknown owner UI request method: ${A.method}`)}}cancelOwnerUIRequest(A){let Q=this.pendingOwnerUIRequests.get(A);if(!Q)return;this.pendingOwnerUIRequests.delete(A),Q.abort()}cancelActorUIRequest(A){let Q=this.pendingActorUIRequests.get(A);if(!Q)return;this.pendingActorUIRequests.delete(A),Q.abort()}buildPluginUIRespondRequest(A,Q,$){this.pluginUIRespondRequestCounter+=1;let B={requestId:A};if($!==void 0)B.error=$;else if(Q!==void 0)B.result=Q;return{type:"request",id:`plugin-ui-respond-${A}-${this.pluginUIRespondRequestCounter}`,method:"plugin.ui.respond",params:B}}async handleActorUIRequest(A,Q){let $=new AbortController;this.pendingActorUIRequests.set(A.requestId,$);let B={type:"request",id:A.requestId,method:A.method,params:A.params};try{let D=await this.dispatchOwnerUIRequest(B,$.signal);if(this.pendingActorUIRequests.get(A.requestId)!==$)return;this.pendingActorUIRequests.delete(A.requestId),Q(this.buildPluginUIRespondRequest(A.requestId,D))}catch(D){if(this.pendingActorUIRequests.get(A.requestId)!==$)return;this.pendingActorUIRequests.delete(A.requestId),Q(this.buildPluginUIRespondRequest(A.requestId,void 0,D instanceof Error?D.message:String(D)))}}upsertActorUIState(A,Q){if(this.stateBackedRequestIDs.add(A.requestId),A.status!=="pending"){this.cancelActorUIRequest(A.requestId);return}if(this.pendingActorUIRequests.has(A.requestId))return;this.handleActorUIRequest(A,Q)}handlePluginUISnapshot(A,Q){let $=new Set(A.requests.map((B)=>B.requestId));for(let B of this.pendingActorUIRequests.keys())if(!$.has(B))this.cancelActorUIRequest(B);for(let B of this.stateBackedRequestIDs)if(!$.has(B))this.stateBackedRequestIDs.delete(B);for(let B of A.requests)this.upsertActorUIState(B,Q)}handlePluginUIRequestAdded(A,Q){this.upsertActorUIState(A.request,Q)}handlePluginUIRequestSettled(A,Q){this.upsertActorUIState(A.request,Q)}handlePluginUIRequestRemoved(A){this.cancelActorUIRequest(A.requestId),this.stateBackedRequestIDs.delete(A.requestId)}handlePluginUIStateEvent(A,Q){if(A.event==="plugin.ui.snapshot"){let $=Rk4.safeParse(A.data);if($.success)this.handlePluginUISnapshot($.data,Q);return!0}if(A.event==="plugin.ui.request_added"){let $=Pk4.safeParse(A.data);if($.success)this.handlePluginUIRequestAdded($.data,Q);return!0}if(A.event==="plugin.ui.request_settled"){let $=uk4.safeParse(A.data);if($.success)this.handlePluginUIRequestSettled($.data,Q);return!0}if(A.event==="plugin.ui.request_removed"){let $=_k4.safeParse(A.data);if($.success)this.handlePluginUIRequestRemoved($.data);return!0}return!1}clearPluginPlatformStatusHandlers(){let A=this.options.neoContext.pluginPlatform;if(!A)return;if(A.createStatusItemHandler===this.createStatusItem)A.createStatusItemHandler=null;if(A.updateStatusItemHandler===this.updateStatusItem)A.updateStatusItemHandler=null;if(A.removeStatusItemHandler===this.removeStatusItem)A.removeStatusItemHandler=null}subscribePluginCommands(){let A=this.options.neoContext.pluginService;if(!A)return;this.refreshPluginCommands(A.commands.list()),this.pluginCommandSubscriptions=[A.plugins.subscribe((Q)=>{this.removeInactivePluginStatusItems(Q),this.showNewPluginErrorToasts(Q),this.refreshPluginCommands(A.commands.list())}),A.commands.changed.subscribe(()=>{this.refreshPluginCommands(A.commands.list())})]}refreshPluginCommands(A){this.unregisterPluginCommands?.();let $=A.map((B)=>this.createPluginCommand(B)).map((B)=>this.options.commandRegistry.register(B));this.unregisterPluginCommands=()=>{for(let B of $)B()}}showNewPluginErrorToasts(A){let Q=new Set;for(let $ of A){if($.status!=="error")continue;if(Cc($.errorMessage))continue;let B=`${$.uri.toString()}
5233
- ${$.errorMessage??""}`;if(Q.add(B),this.pluginErrorToastKeys.has(B))continue;this.options.toastController.show(this.formatPluginErrorToast($),"error",8000)}this.pluginErrorToastKeys=Q}removeInactivePluginStatusItems(A){let Q=new Set(A.filter((B)=>B.status==="active").map((B)=>B.uri.toString())),$=[];for(let[B,D]of this.statusItems){if(Q.has(D.pluginURI))continue;$.push(B)}if($.length===0)return;this.updateStatusItemState(()=>{for(let B of $)this.statusItems.delete(B)})}formatPluginErrorToast(A){let Q=A.uri.toString();return`Plugin failed: ${Q.split("/").pop()??Q}. See logs: ${this.options.neoContext.logFilePath}`}createPluginCommand(A){return{id:A.id,noun:A.category,verb:A.title,description:A.description??`Run plugin command ${A.category}: ${A.title}`,keywords:["plugin",A.pluginName,A.id],status:A.availability,run:async(Q,$,B)=>{B();try{await this.options.neoContext.pluginService?.commands.execute(A.pluginName,A.id,{threadID:this.options.getActiveThreadID()})}catch(D){P.error("Neo plugin command failed",{error:D,command:A}),this.options.toastController.show(D instanceof Error?D.message:String(D),"error",5000)}}}}showInputDialog=(A,Q)=>{return new Promise(($)=>{if(this.disposed||!this.options.state.mounted||Q?.aborted){$(void 0);return}let B={kind:"input",options:A,resolve:$,abortUnsubscribe:()=>{}};B.abortUnsubscribe=QY(Q,()=>this.abortDialog(B)),this.enqueueDialog(B)})};showConfirmDialog=(A,Q)=>{return new Promise(($)=>{if(this.disposed||!this.options.state.mounted||Q?.aborted){$(!1);return}let B={kind:"confirm",options:A,resolve:$,abortUnsubscribe:()=>{}};B.abortUnsubscribe=QY(Q,()=>this.abortDialog(B)),this.enqueueDialog(B)})};showSelectDialog=(A,Q)=>{return new Promise(($)=>{if(this.disposed||!this.options.state.mounted||Q?.aborted){$(void 0);return}let B={kind:"select",options:A,resolve:$,abortUnsubscribe:()=>{}};B.abortUnsubscribe=QY(Q,()=>this.abortDialog(B)),this.enqueueDialog(B)})};createStatusItem=(A,Q,$)=>{if(this.disposed)return;this.updateStatusItemState(()=>{let B=this.statusItemKey(A,Q),D={pluginURI:A,id:Q};if($!==void 0)D.value=$;this.statusItems.set(B,D)})};updateStatusItem=(A,Q,$)=>{if(this.disposed)return;this.updateStatusItemState(()=>{this.statusItems.set(this.statusItemKey(A,Q),{pluginURI:A,id:Q,value:$})})};removeStatusItem=(A,Q)=>{if(this.disposed)return;this.updateStatusItemState(()=>{this.statusItems.delete(this.statusItemKey(A,Q))})};updateStatusItemState(A){if(this.options.state.mounted)this.options.state.setState(A);else A()}statusItemKey(A,Q){return`${A}\x00${Q}`}cancelPendingDialogs(){let A=[];if(this.activeDialog)A.push(this.activeDialog);A.push(...this.queuedDialogs),this.activeDialog=null,this.queuedDialogs=[],this.resolvingDialog=null;for(let Q of A)this.cancelDialog(Q)}cancelDialog(A){switch(A.abortUnsubscribe(),A.kind){case"input":A.resolve(void 0);return;case"confirm":A.resolve(!1);return;case"select":A.resolve(void 0);return}}abortDialog(A){if(this.activeDialog===A){this.advanceDialog(),this.cancelDialog(A);return}let Q=this.queuedDialogs.indexOf(A);if(Q===-1)return;this.updateDialogState(()=>{this.queuedDialogs.splice(Q,1)}),this.cancelDialog(A)}enqueueDialog(A){if(this.activeDialog){if(this.queuedDialogs.push(A),this.resolvingDialog===this.activeDialog)this.advanceResolvingDialog(this.activeDialog);return}this.options.commandPalette.disable(),this.options.state.setState(()=>{this.activeDialog=A})}resolveInputDialog(A,Q){this.resolveDialog(A,()=>A.resolve(Q))}resolveConfirmDialog(A,Q){this.resolveDialog(A,()=>A.resolve(Q))}resolveSelectDialog(A,Q){this.resolveDialog(A,()=>A.resolve(Q))}resolveDialog(A,Q){if(this.activeDialog!==A||this.resolvingDialog===A)return;this.resolvingDialog=A,A.abortUnsubscribe(),Q(),this.scheduleResolvingDialogAdvance(A,Rb3)}scheduleResolvingDialogAdvance(A,Q){i6.instance.addPostFrameCallback(()=>{if(this.activeDialog!==A)return;if(this.queuedDialogs.length>0||Q<=1){this.advanceResolvingDialog(A);return}this.scheduleResolvingDialogAdvance(A,Q-1)},"NeoPluginIntegration.advanceDialog")}advanceResolvingDialog(A){if(this.resolvingDialog===A)this.resolvingDialog=null;if(this.activeDialog!==A)return;this.advanceDialog()}advanceDialog(){this.updateDialogState(()=>{this.activeDialog=this.queuedDialogs.shift()??null})}updateDialogState(A){if(this.options.state.mounted)this.options.state.setState(A);else A()}}var ub3=48;class DA1{visible=!1;onClick=void 0;listeners=new Set;show(A){this.visible=!0,this.onClick=A,this.notifyListeners()}activate(){this.onClick?.()}get isVisible(){return this.visible}dismiss(){this.visible=!1,this.onClick=void 0,this.notifyListeners()}addListener(A){this.listeners.add(A)}removeListener(A){this.listeners.delete(A)}buildComplexToast(){if(!this.visible||!this.onClick)return null;return new hs({width:ub3,title:"Relaunch to Update Amp",message:"Your threads will resume.",variant:"success",mouseBehavior:"click-anywhere",action:{keyboardShortcut:"Ctrl+O",command:"amp: relaunch",confirmShortcut:"Enter",label:"relaunch",onAction:()=>this.activate()}})}notifyListeners(){for(let A of this.listeners)A()}}p0();import{spawnSync as _b3}from"node:child_process";import YI from"node:process";var ia4={options:new Set(["settings-file","log-level","log-file","mcp-config"]),booleans:new Set(["color","dangerously-allow-all","ide","jetbrains","neo-orb","notifications"])};function cs(A){let Q=A.getRelaunchThreadIDs();if(A.onRelaunchRequested?.(Q),A.stop)A.stop();else K4.instance.stop()}function na4(A){return{noun:"amp",verb:"Relaunch (Quit, then Reopen & Resume Thread)",description:"Quit, reopen Amp, and resume active threads",keywords:["restart","update","resume","reopen"],shortcut:YI.env.NODE_ENV==="development"&&YI.platform==="darwin"?G1.meta("r"):void 0,status:{type:"enabled"},sortBoost:90,run:(Q,$,B)=>{B(),cs(A)}}}function Tb3(A,Q){P.info("Relaunching Amp; threads will be resumed",{threadIDs:A});let{command:$,args:B}=vb3(A),D=_b3($,B,{cwd:Q,env:YI.env,stdio:"inherit"});if(D.error)return P.error("Failed to relaunch Amp",{error:D.error}),1;return D.status??1}class JA1{relaunchRequested=!1;requestedThreadIDs=[];request=(A)=>{P.info("Relaunch requested; threads will be resumed",{threadIDs:A}),this.relaunchRequested=!0,this.requestedThreadIDs=A};get shouldShowExitSummary(){return!this.relaunchRequested}relaunchIfRequested(A){if(!this.relaunchRequested)return;return Tb3(this.requestedThreadIDs,A)}}function vb3(A){let Q=A.length>0?["threads","continue",...A]:[],$=kb3(YI.argv),B=fb3();if(B)return{command:B.command,args:[...B.args,...$,...Q]};let D=YI.argv[1],J=D&&Sb3(D)?[D]:[];return{command:YI.execPath,args:[...J,...$,...Q]}}function kb3(A){let Q=[],$=A.slice(2);for(let B=0;B<$.length;B+=1){let D=$[B];if(!D?.startsWith("--"))continue;let[J,F]=D.split("=",2);if(!J)continue;let Y=J.slice(2),E=Y.startsWith("no-")?Y.slice(3):Y;if(ia4.booleans.has(E)){Q.push(D);continue}if(!ia4.options.has(Y))continue;if(F!==void 0){Q.push(D);continue}let Z=$[B+1];if(Z===void 0||Z.startsWith("--"))continue;Q.push(D,Z),B+=1}return Q}function Sb3(A){return A!==YI.execPath&&!A.startsWith("/$bunfs/")}function fb3(){if(YI.env.NODE_ENV!=="development")return null;let A=YI.env.AMP_DEV_RELAUNCH_COMMAND?.trim();if(!A)return null;let Q=yb3(A),$=Q[0];if(!$)return null;return{command:$,args:Q.slice(1)}}function yb3(A){if(A.startsWith("["))try{let Q=JSON.parse(A);if(Array.isArray(Q)&&Q.every(($)=>typeof $==="string"))return Q}catch{return[]}return A.split(/\s+/).filter(Boolean)}var xb3=18000000;class FA1{options;subscription=null;relaunchNotificationShown=!1;relaunchNotificationPending=!1;relaunchNotificationTimer=null;openedAt=Date.now();constructor(A){this.options=A}init(){if(this.subscription=this.options.updateService?.state.subscribe((A)=>{this.handleUpdateState(A)})??null,process.env.DEV_SHOW_RELAUNCH_NOTIF_ON_STARTUP==="1")this.showUpdateRelaunchNotification(!0)}dispose(){if(this.subscription?.unsubscribe(),this.subscription=null,this.relaunchNotificationTimer)clearTimeout(this.relaunchNotificationTimer),this.relaunchNotificationTimer=null}handleUpdateState(A){if(A!=="updated")return;this.showUpdateRelaunchNotification()}showUpdateRelaunchNotification(A=!1){if(this.relaunchNotificationShown)return;let $=(this.options.minimumOpenDurationMs??xb3)-(Date.now()-this.openedAt);if($>0&&!A){if(this.relaunchNotificationPending=!0,!this.relaunchNotificationTimer)this.relaunchNotificationTimer=setTimeout(()=>{if(this.relaunchNotificationTimer=null,!this.relaunchNotificationPending)return;this.relaunchNotificationPending=!1,this.showUpdateRelaunchNotification()},$),this.relaunchNotificationTimer.unref();return}this.relaunchNotificationPending=!1,this.relaunchNotificationShown=!0,this.options.relaunchNotificationController.show(()=>cs(this.options))}}ol();$8();import{readFile as bb3}from"node:fs/promises";import YA1 from"node:os";function hb3(A=new Date){return A.toISOString().replaceAll("-","").replaceAll(":","").slice(0,15)+"Z"}async function aa4(A,Q){try{return{path:Q,contents:Bm0(await bb3(A,"utf8"))}}catch{return null}}async function NX0(A,Q){let $=[],B=hb3(),D=await t4.getThread({thread:Q},{config:A.configService}),J=D.ok?D.result.thread.data:null;$.push({path:`${B}/thread.json`,contents:JSON.stringify(XD(J),null,2)});let F=await aa4(If(Q),`${B}/logs/${Q}.log`);if(F)$.push(F);let Y=await aa4(A.settingsFilePath,`${B}/settings/global.json`);if(Y)$.push(Y);let E=await kG()??"unknown",Z=await t4.sendReport({threadID:Q,files:$,metadata:{clientVersion:"0.0.1779296280-g014378",clientOS:`${YA1.platform()} ${YA1.release()} ${YA1.arch()}`,installMethod:E}},{config:A.configService});if(!Z.ok)throw Error(`Failed to submit report: ${Z.error.message}`);return Z.result.reportID}class EA1{backStack=[];forwardStack=[];canNavigateBack(){return this.backStack.length>0}canNavigateForward(){return this.forwardStack.length>0}recordNavigation(A){if(!A)return;this.backStack.push(A),this.forwardStack.length=0}startBackNavigation(A){let Q=this.backStack.pop();if(!Q)return null;let $=Boolean(A);if(A)this.forwardStack.push(A);return{targetThreadID:Q,rollback:()=>{if($)this.forwardStack.pop();this.backStack.push(Q)}}}startForwardNavigation(A){let Q=this.forwardStack.pop();if(!Q)return null;let $=Boolean(A);if(A)this.backStack.push(A);return{targetThreadID:Q,rollback:()=>{if($)this.backStack.pop();this.forwardStack.push(Q)}}}}class wX0 extends g3{offstage;constructor({key:A,offstage:Q=!0,child:$}){super({key:A,child:$});this.offstage=Q}createRenderObject(){return new ZA1(this.offstage)}updateRenderObject(A){if(A instanceof ZA1)A.offstage=this.offstage}}class ZA1 extends p1{_offstage;constructor(A){super();this._offstage=A}get offstage(){return this._offstage}set offstage(A){if(A===this._offstage)return;this._offstage=A,this.markNeedsLayout()}getMinIntrinsicWidth(A){if(this._offstage)return 0;return this.children[0]?.getMinIntrinsicWidth(A)??0}getMaxIntrinsicWidth(A){if(this._offstage)return 0;return this.children[0]?.getMaxIntrinsicWidth(A)??0}getMinIntrinsicHeight(A){if(this._offstage)return 0;return this.children[0]?.getMinIntrinsicHeight(A)??0}getMaxIntrinsicHeight(A){if(this._offstage)return 0;return this.children[0]?.getMaxIntrinsicHeight(A)??0}performLayout(){let A=this._lastConstraints;q4(!!A,"performLayout called without constraints");let Q=this.children[0];if(this._offstage){if(this.setSize(0,0),Q)Q.layout(A),Q.setOffset(0,0)}else if(Q){Q.layout(A);let $=A.constrain(Q.size.width,Q.size.height);this.setSize($.width,$.height),Q.setOffset(0,0)}else{let $=A.smallest;this.setSize($.width,$.height)}super.performLayout()}paint(A,Q,$){if(this._offstage)return;super.paint(A,Q,$)}hitTest(A,Q,$,B){if(this._offstage)return!1;return super.hitTest(A,Q,$,B)}}class ls{_state=null;_attach(A){this._state=A}_detach(){this._state=null}push(A){this._state?.push(A)}pushWithDismiss(A){this._state?.pushWithDismiss(A)}pop(){return this._state?.pop()??!1}get canPop(){return this._state?.canPop??!1}}class UA1 extends P0{root;controller;constructor(A){super();this.root=A.root,this.controller=A.controller}createState(){return new oa4}}class oa4 extends R0{entries=[];initState(){this.widget.controller._attach(this)}didUpdateWidget(A){if(A.controller!==this.widget.controller)A.controller._detach(),this.widget.controller._attach(this)}dispose(){this.widget.controller._detach(),super.dispose()}push(A){let Q=new dj,$=this.makeScopedDismiss(Q);this.setState(()=>{this.entries.push({key:Q,widget:A,dismiss:$})})}pushWithDismiss(A){let Q=new dj,$=this.makeScopedDismiss(Q),B=A($);this.setState(()=>{this.entries.push({key:Q,widget:B,dismiss:$})})}pop(){if(this.entries.length===0)return!1;return this.setState(()=>{this.entries.pop()}),!0}get canPop(){return this.entries.length>0}makeScopedDismiss(A){return()=>{if(!this.mounted)return;let Q=this.entries[this.entries.length-1];if(!Q||Q.key!==A)return;this.setState(()=>{this.entries.pop()})}}build(A){let Q=[];Q.push(new wX0({offstage:this.entries.length>0,child:this.widget.root}));for(let $=0;$<this.entries.length;$++){let B=this.entries[$],D=$===this.entries.length-1,J=D?new k4({autofocus:!0,debugLabel:`ModalStackEntry[${$}]`,onKey:(F)=>{if(F.key!=="Escape")return"ignored";return B.dismiss(),"handled"},child:B.widget}):B.widget;Q.push(new wX0({key:B.key,offstage:!D,child:J}))}return new i4({fit:"expand",children:Q})}}import ra4 from"node:process";class GA1 extends H1{props;constructor(A){super();this.props=A}build(A){let Q=this.props.commands.filter((B)=>B.status.type!=="hidden"),$=gb3(Q);return new w6({header:"Command Palette",autofocus:!1,barrierOpaque:!1,chromePadding:V0.only({left:1,top:1,right:1}),footer:"none",onDismiss:this.props.onDismiss,child:new lA({items:Q,showBorder:!1,getLabel:(B)=>{let D=XA1(B);return B.keywords&&B.keywords.length>0?`${D} ${B.keywords.join(" ").toLowerCase()}`:D},sortItems:(B,D,J)=>{if(J===""){let U=B.item.status.type==="disabled"?1:0,X=D.item.status.type==="disabled"?1:0;if(U!==X)return U-X;let G=B.item.sortBoost??0,V=D.item.sortBoost??0;if(G!==V)return V-G;let K=B.item.noun?.toLowerCase()??"",I=D.item.noun?.toLowerCase()??"";if(K!==I)return K<I?-1:1;return 0}let F=ER(B.item.verb.toLowerCase(),J),Y=ER(D.item.verb.toLowerCase(),J);if(F!==Y)return Y-F;let E=ER(XA1(B.item),J),Z=ER(XA1(D.item),J);if(E!==Z)return Z-E;return D.score-B.score},isItemDisabled:(B)=>B.status.type==="disabled",buildDisabledReasonWidget:(B,D)=>{if(B.status.type!=="disabled")return;let{colors:J}=O0.of(D);return new d({text:new C(B.status.reason,new T({color:J.mutedForeground,dim:!0})),textAlign:"center"})},renderItem:(B,D,J,F)=>new sa4({command:B,isSelected:D,isDisabled:J,categoryWidth:$,buildContext:F}),onAccept:(B)=>{this.props.onAccept(B)},onDismiss:this.props.onDismiss})})}}class sa4 extends H1{props;constructor(A){super();this.props=A}build(A){let{command:Q,isSelected:$,isDisabled:B,categoryWidth:D,buildContext:J}=this.props,F=O0.of(J),{colors:Y,app:E}=F,Z=$?E.selectionBackground:void 0,U=$?E.selectionForeground:Y.foreground,X=$?U:Y.mutedForeground,G=new d({text:new C(Q.noun?.toLowerCase()??"",new T({color:X,dim:B||!$})),textAlign:"right"}),V=[new C(Q.verb.toLowerCase(),new T({color:U,bold:!0,dim:B}))];if(B)V.push(new C(" (unavailable)",new T({color:U,dim:!0})));let K=d.spans(V),I=[{child:G,fixedWidth:D},{child:K,expanded:!0}];if(Q.shortcut)I.push({child:mb3(Q.shortcut,F,B)});return new ta4({columns:I,padding:V0.horizontal(1),backgroundColor:Z})}}function XA1(A){return A.noun?`${A.noun.toLowerCase()} ${A.verb.toLowerCase()}`:A.verb.toLowerCase()}function gb3(A){return A.reduce((Q,$)=>{return $.noun?Math.max(Q,J4($.noun)):Q},0)}function mb3(A,Q,$){let{colors:B,app:D}=Q,J=new T({color:B.mutedForeground,dim:$}),F=[];for(let Y of A.modifiers()){if(F.length>0)F.push(new C(" ",J));F.push(new C(db3(Y),new T({color:D.keybind,bold:!0,dim:$})))}if(F.length>0)F.push(new C(" ",J));return F.push(new C(pb3(A),new T({color:D.keybind,bold:!0,dim:$}))),d.spans(F)}function db3(A){return A==="Meta"&&ra4.platform==="darwin"?"Cmd":A}function pb3(A){return A.meta&&ra4.platform==="darwin"?A.key.toUpperCase():A.key}class ta4 extends H1{props;constructor(A){super();this.props=A}build(A){let{columns:Q,gap:$=2,padding:B,backgroundColor:D}=this.props,J=[];for(let Y=0;Y<Q.length;Y++){let E=Q[Y];if(Y>0&&$>0)J.push(new X0({width:$}));if(E.fixedWidth!==void 0)J.push(new X0({width:E.fixedWidth,child:E.child}));else if(E.expanded)J.push(new R1({child:E.child}));else J.push(E.child)}let F=new r0({crossAxisAlignment:"start",children:J});if(!B&&!D)return F;return new b0({decoration:D?{color:D}:void 0,padding:B,child:F})}}class VA1{#A=[];#Q=new Set;get commands(){return this.#A}register(A){return this.#A.push(A),this.#$(),()=>{let Q=this.#A.indexOf(A);if(Q===-1)return;this.#A.splice(Q,1),this.#$()}}findByID(A){return this.#A.find((Q)=>Q.id===A)}runByID(A,Q){let $=this.findByID(A);if(!$||$.status.type!=="enabled")return!1;return $.run(new ls,Q,()=>{}),!0}addListener(A){this.#Q.add(A)}removeListener(A){this.#Q.delete(A)}#$(){for(let A of this.#Q)A()}}class M9 extends KA{commandRegistry;constructor({commandRegistry:A,child:Q}){super({child:Q});this.commandRegistry=A}updateShouldNotify(A){return!1}static of(A){let Q=M9.maybeOf(A);if(!Q)throw Error("No NeoCommandRegistryProvider found in widget tree");return Q}static maybeOf(A){return A.dependOnInheritedWidgetOfExactType(M9)?.commandRegistry??null}}class KA1 extends P0{onDismiss;constructor(A){super();this.onDismiss=A.onDismiss}createState(){return new ea4}}class ea4 extends R0{modalStack=new ls;commandRegistry=null;initState(){super.initState(),queueMicrotask(()=>{if(!this.mounted)return;let A=M9.of(this.context);this.commandRegistry=A,A.addListener(this.onCommandsChanged)})}dispose(){this.commandRegistry?.removeListener(this.onCommandsChanged),this.commandRegistry=null,super.dispose()}onCommandsChanged=()=>{this.setState()};build(A){let Q=M9.of(A).commands,$=new GA1({commands:Q,onAccept:(B)=>{B.run(this.modalStack,A,this.widget.onDismiss)},onDismiss:()=>{if(this.modalStack.canPop)this.modalStack.pop();else this.widget.onDismiss()}});return new UA1({root:$,controller:this.modalStack})}}var zA1=[{description:"Move cursor up/down",methods:[{keys:["↑"]},{keys:["↓"]}]},{description:"Move cursor left/right",methods:[{keys:["←"]},{keys:["→"]},{input:"B",keys:["Ctrl"]},{input:"F",keys:["Ctrl"]}]},{description:"Insert newline",methods:[{keys:["Shift","Enter"]},{keys:["Alt","Enter"]},{input:"J",keys:["Ctrl"]}],submitOnEnterOnly:!0},{description:"Insert newline",methods:[{keys:["Enter"]},{keys:["Shift","Enter"]},{keys:["Alt","Enter"]},{input:"J",keys:["Ctrl"]}],submitOnEnterOnly:!1},{description:"Submit message",methods:[{keys:["Enter"]}],submitOnEnterOnly:!0},{description:"Submit message",methods:[{keys:["Ctrl/Cmd","Enter"]}],submitOnEnterOnly:!1},{description:"Clear input",methods:[{keys:["Escape"]}]},{description:"Edit prompt in $EDITOR",methods:[{input:"G",keys:["Ctrl"]}]},{description:"Navigate history (previous/next)",methods:[{input:"P",keys:["Ctrl"]},{input:"N",keys:["Ctrl"]}]},{description:"Jump to start of line",methods:[{keys:["Cmd","←"]},{input:"A",keys:["Ctrl"]}]},{description:"Jump to end of line",methods:[{keys:["Cmd","→"]},{input:"E",keys:["Ctrl"]}]},{description:"Jump to previous word",methods:[{keys:["Alt","←"]},{keys:["Ctrl","←"]},{input:"B",keys:["Alt"]}]},{description:"Jump to next word",methods:[{keys:["Alt","→"]},{keys:["Ctrl","→"]},{input:"F",keys:["Alt"]}]},{description:"Delete character backward",methods:[{keys:["Backspace"]},{input:"H",keys:["Ctrl"]}]},{description:"Delete word backward",methods:[{keys:["Alt","Backspace"]},{input:"W",keys:["Ctrl"]}]},{description:"Delete character forward",methods:[{keys:["Delete"]},{input:"D",keys:["Ctrl"]}]},{description:"Delete to start of line",methods:[{keys:["Cmd","Backspace"]},{input:"U",keys:["Ctrl"]}]},{description:"Delete to end of line",methods:[{input:"K",keys:["Ctrl"]}]},{description:"Yank (paste deleted text)",methods:[{input:"Y",keys:["Ctrl"]}]},{description:"Paste image from clipboard",methods:[{input:"V",keys:["Ctrl"]}]},{description:"Switch agent mode",methods:[{input:"S",keys:["Ctrl"]}]},{description:"Toggle reasoning effort",methods:[{input:"D",keys:["Alt"]}]},{description:"Open command palette",methods:[{input:"O",keys:["Ctrl"]}]},{description:"Mention files",methods:[{keys:["@"]}]},{description:"Mention threads",methods:[{keys:["@@"]}]},{description:"Show prompt history",methods:[{input:"R",keys:["Ctrl"]}]},{description:"Toggle inline shortcuts help",methods:[{keys:["?"]}]},{description:"Toggle thinking/dense view",methods:[{input:"T",keys:["Alt"]}]}],IA1=[{description:"Page scroll",methods:[{keys:["Pg Up"]},{keys:["Pg Down"]}]},{description:"Half-page scroll",methods:[{input:"K",keys:["Alt"]},{input:"J",keys:["Alt"]}]},{description:"Mouse wheel scroll",methods:[{keys:["Mouse Wheel"]}]},{description:"Jump to first message",methods:[{keys:["Home"]}]},{description:"Jump to bottom of screen",methods:[{keys:["End"]}]},{description:"Navigate to previous messages",methods:[{keys:["Tab"]},{keys:["Shift","Tab"]}]}];class CX0 extends H1{items;renderRow;constructor({items:A,renderRow:Q}){super();this.items=A,this.renderRow=Q}build(A){let $=c1.of(A).size.width,B=50,D=$<50,J=[];for(let F of this.items){let[Y,E]=this.renderRow(F),Z;if(D)Z=new S0({crossAxisAlignment:"start",mainAxisSize:"min",children:[Y,new f0({padding:V0.only({left:4}),child:E})]});else Z=new r0({crossAxisAlignment:"start",children:[new R1({flex:1,child:Y}),new X0({width:1}),new R1({flex:1,child:E})]});J.push(new f0({padding:V0.horizontal(6),child:Z}))}return new S0({crossAxisAlignment:"start",mainAxisSize:"min",children:J})}}class WA1 extends P0{commands;submitOnEnter;constructor({key:A,commands:Q,submitOnEnter:$}){super(A?{key:A}:{});this.commands=Q,this.submitOnEnter=$??!0}createState(){return new Ao4}}class Ao4 extends R0{scrollController;initState(){this.scrollController=new v6,this.scrollController.disableFollowMode(),this.scrollController.jumpTo(0)}dispose(){}build(A){let $=L1.of(A).colorScheme,D=O0.of(A).app,J=c1.of(A),F=new T({color:$.primary,bold:!0}),Y=new T({color:$.secondary,bold:!0}),E=new T({color:D.keybind}),Z=new T({color:D.command}),U=new T({color:$.foreground}),X=new T({color:$.foreground}),G=J.size.width,V=J.size.height,K=G-4,I=V-4,z=Math.max(40,Math.min(80,K)),W=new Set(["permissions-disable"]),q=[...this.widget.commands.filter((L)=>{let j=L.noun?.toLowerCase();return j!=="dev"&&j!=="debug"&&!L.id.startsWith("debug-")&&!W.has(L.id)})].sort((L,j)=>{let k=(L.noun??"").toLowerCase(),_=(j.noun??"").toLowerCase(),f=k.localeCompare(_);if(f!==0)return f;let h=L.verb.toLowerCase(),b=j.verb.toLowerCase(),v=h.localeCompare(b);if(v!==0)return v;return L.id.localeCompare(j.id)}),N=new k6({autofocus:!0,controller:this.scrollController,child:new b0({constraints:new C1(z,z,0,Number.POSITIVE_INFINITY),child:new S0({crossAxisAlignment:"start",mainAxisSize:"min",children:[new $4({child:new d({text:new C(`Amp CLI - Help & Keyboard Shortcuts
5233
+ ${$.errorMessage??""}`;if(Q.add(B),this.pluginErrorToastKeys.has(B))continue;this.options.toastController.show(this.formatPluginErrorToast($),"error",8000)}this.pluginErrorToastKeys=Q}removeInactivePluginStatusItems(A){let Q=new Set(A.filter((B)=>B.status==="active").map((B)=>B.uri.toString())),$=[];for(let[B,D]of this.statusItems){if(Q.has(D.pluginURI))continue;$.push(B)}if($.length===0)return;this.updateStatusItemState(()=>{for(let B of $)this.statusItems.delete(B)})}formatPluginErrorToast(A){let Q=A.uri.toString();return`Plugin failed: ${Q.split("/").pop()??Q}. See logs: ${this.options.neoContext.logFilePath}`}createPluginCommand(A){return{id:A.id,noun:A.category,verb:A.title,description:A.description??`Run plugin command ${A.category}: ${A.title}`,keywords:["plugin",A.pluginName,A.id],status:A.availability,run:async(Q,$,B)=>{B();try{await this.options.neoContext.pluginService?.commands.execute(A.pluginName,A.id,{threadID:this.options.getActiveThreadID()})}catch(D){P.error("Neo plugin command failed",{error:D,command:A}),this.options.toastController.show(D instanceof Error?D.message:String(D),"error",5000)}}}}showInputDialog=(A,Q)=>{return new Promise(($)=>{if(this.disposed||!this.options.state.mounted||Q?.aborted){$(void 0);return}let B={kind:"input",options:A,resolve:$,abortUnsubscribe:()=>{}};B.abortUnsubscribe=QY(Q,()=>this.abortDialog(B)),this.enqueueDialog(B)})};showConfirmDialog=(A,Q)=>{return new Promise(($)=>{if(this.disposed||!this.options.state.mounted||Q?.aborted){$(!1);return}let B={kind:"confirm",options:A,resolve:$,abortUnsubscribe:()=>{}};B.abortUnsubscribe=QY(Q,()=>this.abortDialog(B)),this.enqueueDialog(B)})};showSelectDialog=(A,Q)=>{return new Promise(($)=>{if(this.disposed||!this.options.state.mounted||Q?.aborted){$(void 0);return}let B={kind:"select",options:A,resolve:$,abortUnsubscribe:()=>{}};B.abortUnsubscribe=QY(Q,()=>this.abortDialog(B)),this.enqueueDialog(B)})};createStatusItem=(A,Q,$)=>{if(this.disposed)return;this.updateStatusItemState(()=>{let B=this.statusItemKey(A,Q),D={pluginURI:A,id:Q};if($!==void 0)D.value=$;this.statusItems.set(B,D)})};updateStatusItem=(A,Q,$)=>{if(this.disposed)return;this.updateStatusItemState(()=>{this.statusItems.set(this.statusItemKey(A,Q),{pluginURI:A,id:Q,value:$})})};removeStatusItem=(A,Q)=>{if(this.disposed)return;this.updateStatusItemState(()=>{this.statusItems.delete(this.statusItemKey(A,Q))})};updateStatusItemState(A){if(this.options.state.mounted)this.options.state.setState(A);else A()}statusItemKey(A,Q){return`${A}\x00${Q}`}cancelPendingDialogs(){let A=[];if(this.activeDialog)A.push(this.activeDialog);A.push(...this.queuedDialogs),this.activeDialog=null,this.queuedDialogs=[],this.resolvingDialog=null;for(let Q of A)this.cancelDialog(Q)}cancelDialog(A){switch(A.abortUnsubscribe(),A.kind){case"input":A.resolve(void 0);return;case"confirm":A.resolve(!1);return;case"select":A.resolve(void 0);return}}abortDialog(A){if(this.activeDialog===A){this.advanceDialog(),this.cancelDialog(A);return}let Q=this.queuedDialogs.indexOf(A);if(Q===-1)return;this.updateDialogState(()=>{this.queuedDialogs.splice(Q,1)}),this.cancelDialog(A)}enqueueDialog(A){if(this.activeDialog){if(this.queuedDialogs.push(A),this.resolvingDialog===this.activeDialog)this.advanceResolvingDialog(this.activeDialog);return}this.options.commandPalette.disable(),this.options.state.setState(()=>{this.activeDialog=A})}resolveInputDialog(A,Q){this.resolveDialog(A,()=>A.resolve(Q))}resolveConfirmDialog(A,Q){this.resolveDialog(A,()=>A.resolve(Q))}resolveSelectDialog(A,Q){this.resolveDialog(A,()=>A.resolve(Q))}resolveDialog(A,Q){if(this.activeDialog!==A||this.resolvingDialog===A)return;this.resolvingDialog=A,A.abortUnsubscribe(),Q(),this.scheduleResolvingDialogAdvance(A,Rb3)}scheduleResolvingDialogAdvance(A,Q){i6.instance.addPostFrameCallback(()=>{if(this.activeDialog!==A)return;if(this.queuedDialogs.length>0||Q<=1){this.advanceResolvingDialog(A);return}this.scheduleResolvingDialogAdvance(A,Q-1)},"NeoPluginIntegration.advanceDialog")}advanceResolvingDialog(A){if(this.resolvingDialog===A)this.resolvingDialog=null;if(this.activeDialog!==A)return;this.advanceDialog()}advanceDialog(){this.updateDialogState(()=>{this.activeDialog=this.queuedDialogs.shift()??null})}updateDialogState(A){if(this.options.state.mounted)this.options.state.setState(A);else A()}}var ub3=48;class DA1{visible=!1;onClick=void 0;listeners=new Set;show(A){this.visible=!0,this.onClick=A,this.notifyListeners()}activate(){this.onClick?.()}get isVisible(){return this.visible}dismiss(){this.visible=!1,this.onClick=void 0,this.notifyListeners()}addListener(A){this.listeners.add(A)}removeListener(A){this.listeners.delete(A)}buildComplexToast(){if(!this.visible||!this.onClick)return null;return new hs({width:ub3,title:"Relaunch to Update Amp",message:"Your threads will resume.",variant:"success",mouseBehavior:"click-anywhere",action:{keyboardShortcut:"Ctrl+O",command:"amp: relaunch",confirmShortcut:"Enter",label:"relaunch",onAction:()=>this.activate()}})}notifyListeners(){for(let A of this.listeners)A()}}p0();import{spawnSync as _b3}from"node:child_process";import YI from"node:process";var ia4={options:new Set(["settings-file","log-level","log-file","mcp-config"]),booleans:new Set(["color","dangerously-allow-all","ide","jetbrains","neo-orb","notifications"])};function cs(A){let Q=A.getRelaunchThreadIDs();if(A.onRelaunchRequested?.(Q),A.stop)A.stop();else K4.instance.stop()}function na4(A){return{noun:"amp",verb:"Relaunch (Quit, then Reopen & Resume Thread)",description:"Quit, reopen Amp, and resume active threads",keywords:["restart","update","resume","reopen"],shortcut:YI.env.NODE_ENV==="development"&&YI.platform==="darwin"?G1.meta("r"):void 0,status:{type:"enabled"},sortBoost:90,run:(Q,$,B)=>{B(),cs(A)}}}function Tb3(A,Q){P.info("Relaunching Amp; threads will be resumed",{threadIDs:A});let{command:$,args:B}=vb3(A),D=_b3($,B,{cwd:Q,env:YI.env,stdio:"inherit"});if(D.error)return P.error("Failed to relaunch Amp",{error:D.error}),1;return D.status??1}class JA1{relaunchRequested=!1;requestedThreadIDs=[];request=(A)=>{P.info("Relaunch requested; threads will be resumed",{threadIDs:A}),this.relaunchRequested=!0,this.requestedThreadIDs=A};get shouldShowExitSummary(){return!this.relaunchRequested}relaunchIfRequested(A){if(!this.relaunchRequested)return;return Tb3(this.requestedThreadIDs,A)}}function vb3(A){let Q=A.length>0?["threads","continue",...A]:[],$=kb3(YI.argv),B=fb3();if(B)return{command:B.command,args:[...B.args,...$,...Q]};let D=YI.argv[1],J=D&&Sb3(D)?[D]:[];return{command:YI.execPath,args:[...J,...$,...Q]}}function kb3(A){let Q=[],$=A.slice(2);for(let B=0;B<$.length;B+=1){let D=$[B];if(!D?.startsWith("--"))continue;let[J,F]=D.split("=",2);if(!J)continue;let Y=J.slice(2),E=Y.startsWith("no-")?Y.slice(3):Y;if(ia4.booleans.has(E)){Q.push(D);continue}if(!ia4.options.has(Y))continue;if(F!==void 0){Q.push(D);continue}let Z=$[B+1];if(Z===void 0||Z.startsWith("--"))continue;Q.push(D,Z),B+=1}return Q}function Sb3(A){return A!==YI.execPath&&!A.startsWith("/$bunfs/")}function fb3(){if(YI.env.NODE_ENV!=="development")return null;let A=YI.env.AMP_DEV_RELAUNCH_COMMAND?.trim();if(!A)return null;let Q=yb3(A),$=Q[0];if(!$)return null;return{command:$,args:Q.slice(1)}}function yb3(A){if(A.startsWith("["))try{let Q=JSON.parse(A);if(Array.isArray(Q)&&Q.every(($)=>typeof $==="string"))return Q}catch{return[]}return A.split(/\s+/).filter(Boolean)}var xb3=18000000;class FA1{options;subscription=null;relaunchNotificationShown=!1;relaunchNotificationPending=!1;relaunchNotificationTimer=null;openedAt=Date.now();constructor(A){this.options=A}init(){if(this.subscription=this.options.updateService?.state.subscribe((A)=>{this.handleUpdateState(A)})??null,process.env.DEV_SHOW_RELAUNCH_NOTIF_ON_STARTUP==="1")this.showUpdateRelaunchNotification(!0)}dispose(){if(this.subscription?.unsubscribe(),this.subscription=null,this.relaunchNotificationTimer)clearTimeout(this.relaunchNotificationTimer),this.relaunchNotificationTimer=null}handleUpdateState(A){if(A!=="updated")return;this.showUpdateRelaunchNotification()}showUpdateRelaunchNotification(A=!1){if(this.relaunchNotificationShown)return;let $=(this.options.minimumOpenDurationMs??xb3)-(Date.now()-this.openedAt);if($>0&&!A){if(this.relaunchNotificationPending=!0,!this.relaunchNotificationTimer)this.relaunchNotificationTimer=setTimeout(()=>{if(this.relaunchNotificationTimer=null,!this.relaunchNotificationPending)return;this.relaunchNotificationPending=!1,this.showUpdateRelaunchNotification()},$),this.relaunchNotificationTimer.unref();return}this.relaunchNotificationPending=!1,this.relaunchNotificationShown=!0,this.options.relaunchNotificationController.show(()=>cs(this.options))}}ol();$8();import{readFile as bb3}from"node:fs/promises";import YA1 from"node:os";function hb3(A=new Date){return A.toISOString().replaceAll("-","").replaceAll(":","").slice(0,15)+"Z"}async function aa4(A,Q){try{return{path:Q,contents:Bm0(await bb3(A,"utf8"))}}catch{return null}}async function NX0(A,Q){let $=[],B=hb3(),D=await t4.getThread({thread:Q},{config:A.configService}),J=D.ok?D.result.thread.data:null;$.push({path:`${B}/thread.json`,contents:JSON.stringify(XD(J),null,2)});let F=await aa4(If(Q),`${B}/logs/${Q}.log`);if(F)$.push(F);let Y=await aa4(A.settingsFilePath,`${B}/settings/global.json`);if(Y)$.push(Y);let E=await kG()??"unknown",Z=await t4.sendReport({threadID:Q,files:$,metadata:{clientVersion:"0.0.1779313683-gf89f27",clientOS:`${YA1.platform()} ${YA1.release()} ${YA1.arch()}`,installMethod:E}},{config:A.configService});if(!Z.ok)throw Error(`Failed to submit report: ${Z.error.message}`);return Z.result.reportID}class EA1{backStack=[];forwardStack=[];canNavigateBack(){return this.backStack.length>0}canNavigateForward(){return this.forwardStack.length>0}recordNavigation(A){if(!A)return;this.backStack.push(A),this.forwardStack.length=0}startBackNavigation(A){let Q=this.backStack.pop();if(!Q)return null;let $=Boolean(A);if(A)this.forwardStack.push(A);return{targetThreadID:Q,rollback:()=>{if($)this.forwardStack.pop();this.backStack.push(Q)}}}startForwardNavigation(A){let Q=this.forwardStack.pop();if(!Q)return null;let $=Boolean(A);if(A)this.backStack.push(A);return{targetThreadID:Q,rollback:()=>{if($)this.backStack.pop();this.forwardStack.push(Q)}}}}class wX0 extends g3{offstage;constructor({key:A,offstage:Q=!0,child:$}){super({key:A,child:$});this.offstage=Q}createRenderObject(){return new ZA1(this.offstage)}updateRenderObject(A){if(A instanceof ZA1)A.offstage=this.offstage}}class ZA1 extends p1{_offstage;constructor(A){super();this._offstage=A}get offstage(){return this._offstage}set offstage(A){if(A===this._offstage)return;this._offstage=A,this.markNeedsLayout()}getMinIntrinsicWidth(A){if(this._offstage)return 0;return this.children[0]?.getMinIntrinsicWidth(A)??0}getMaxIntrinsicWidth(A){if(this._offstage)return 0;return this.children[0]?.getMaxIntrinsicWidth(A)??0}getMinIntrinsicHeight(A){if(this._offstage)return 0;return this.children[0]?.getMinIntrinsicHeight(A)??0}getMaxIntrinsicHeight(A){if(this._offstage)return 0;return this.children[0]?.getMaxIntrinsicHeight(A)??0}performLayout(){let A=this._lastConstraints;q4(!!A,"performLayout called without constraints");let Q=this.children[0];if(this._offstage){if(this.setSize(0,0),Q)Q.layout(A),Q.setOffset(0,0)}else if(Q){Q.layout(A);let $=A.constrain(Q.size.width,Q.size.height);this.setSize($.width,$.height),Q.setOffset(0,0)}else{let $=A.smallest;this.setSize($.width,$.height)}super.performLayout()}paint(A,Q,$){if(this._offstage)return;super.paint(A,Q,$)}hitTest(A,Q,$,B){if(this._offstage)return!1;return super.hitTest(A,Q,$,B)}}class ls{_state=null;_attach(A){this._state=A}_detach(){this._state=null}push(A){this._state?.push(A)}pushWithDismiss(A){this._state?.pushWithDismiss(A)}pop(){return this._state?.pop()??!1}get canPop(){return this._state?.canPop??!1}}class UA1 extends P0{root;controller;constructor(A){super();this.root=A.root,this.controller=A.controller}createState(){return new oa4}}class oa4 extends R0{entries=[];initState(){this.widget.controller._attach(this)}didUpdateWidget(A){if(A.controller!==this.widget.controller)A.controller._detach(),this.widget.controller._attach(this)}dispose(){this.widget.controller._detach(),super.dispose()}push(A){let Q=new dj,$=this.makeScopedDismiss(Q);this.setState(()=>{this.entries.push({key:Q,widget:A,dismiss:$})})}pushWithDismiss(A){let Q=new dj,$=this.makeScopedDismiss(Q),B=A($);this.setState(()=>{this.entries.push({key:Q,widget:B,dismiss:$})})}pop(){if(this.entries.length===0)return!1;return this.setState(()=>{this.entries.pop()}),!0}get canPop(){return this.entries.length>0}makeScopedDismiss(A){return()=>{if(!this.mounted)return;let Q=this.entries[this.entries.length-1];if(!Q||Q.key!==A)return;this.setState(()=>{this.entries.pop()})}}build(A){let Q=[];Q.push(new wX0({offstage:this.entries.length>0,child:this.widget.root}));for(let $=0;$<this.entries.length;$++){let B=this.entries[$],D=$===this.entries.length-1,J=D?new k4({autofocus:!0,debugLabel:`ModalStackEntry[${$}]`,onKey:(F)=>{if(F.key!=="Escape")return"ignored";return B.dismiss(),"handled"},child:B.widget}):B.widget;Q.push(new wX0({key:B.key,offstage:!D,child:J}))}return new i4({fit:"expand",children:Q})}}import ra4 from"node:process";class GA1 extends H1{props;constructor(A){super();this.props=A}build(A){let Q=this.props.commands.filter((B)=>B.status.type!=="hidden"),$=gb3(Q);return new w6({header:"Command Palette",autofocus:!1,barrierOpaque:!1,chromePadding:V0.only({left:1,top:1,right:1}),footer:"none",onDismiss:this.props.onDismiss,child:new lA({items:Q,showBorder:!1,getLabel:(B)=>{let D=XA1(B);return B.keywords&&B.keywords.length>0?`${D} ${B.keywords.join(" ").toLowerCase()}`:D},sortItems:(B,D,J)=>{if(J===""){let U=B.item.status.type==="disabled"?1:0,X=D.item.status.type==="disabled"?1:0;if(U!==X)return U-X;let G=B.item.sortBoost??0,V=D.item.sortBoost??0;if(G!==V)return V-G;let K=B.item.noun?.toLowerCase()??"",I=D.item.noun?.toLowerCase()??"";if(K!==I)return K<I?-1:1;return 0}let F=ER(B.item.verb.toLowerCase(),J),Y=ER(D.item.verb.toLowerCase(),J);if(F!==Y)return Y-F;let E=ER(XA1(B.item),J),Z=ER(XA1(D.item),J);if(E!==Z)return Z-E;return D.score-B.score},isItemDisabled:(B)=>B.status.type==="disabled",buildDisabledReasonWidget:(B,D)=>{if(B.status.type!=="disabled")return;let{colors:J}=O0.of(D);return new d({text:new C(B.status.reason,new T({color:J.mutedForeground,dim:!0})),textAlign:"center"})},renderItem:(B,D,J,F)=>new sa4({command:B,isSelected:D,isDisabled:J,categoryWidth:$,buildContext:F}),onAccept:(B)=>{this.props.onAccept(B)},onDismiss:this.props.onDismiss})})}}class sa4 extends H1{props;constructor(A){super();this.props=A}build(A){let{command:Q,isSelected:$,isDisabled:B,categoryWidth:D,buildContext:J}=this.props,F=O0.of(J),{colors:Y,app:E}=F,Z=$?E.selectionBackground:void 0,U=$?E.selectionForeground:Y.foreground,X=$?U:Y.mutedForeground,G=new d({text:new C(Q.noun?.toLowerCase()??"",new T({color:X,dim:B||!$})),textAlign:"right"}),V=[new C(Q.verb.toLowerCase(),new T({color:U,bold:!0,dim:B}))];if(B)V.push(new C(" (unavailable)",new T({color:U,dim:!0})));let K=d.spans(V),I=[{child:G,fixedWidth:D},{child:K,expanded:!0}];if(Q.shortcut)I.push({child:mb3(Q.shortcut,F,B)});return new ta4({columns:I,padding:V0.horizontal(1),backgroundColor:Z})}}function XA1(A){return A.noun?`${A.noun.toLowerCase()} ${A.verb.toLowerCase()}`:A.verb.toLowerCase()}function gb3(A){return A.reduce((Q,$)=>{return $.noun?Math.max(Q,J4($.noun)):Q},0)}function mb3(A,Q,$){let{colors:B,app:D}=Q,J=new T({color:B.mutedForeground,dim:$}),F=[];for(let Y of A.modifiers()){if(F.length>0)F.push(new C(" ",J));F.push(new C(db3(Y),new T({color:D.keybind,bold:!0,dim:$})))}if(F.length>0)F.push(new C(" ",J));return F.push(new C(pb3(A),new T({color:D.keybind,bold:!0,dim:$}))),d.spans(F)}function db3(A){return A==="Meta"&&ra4.platform==="darwin"?"Cmd":A}function pb3(A){return A.meta&&ra4.platform==="darwin"?A.key.toUpperCase():A.key}class ta4 extends H1{props;constructor(A){super();this.props=A}build(A){let{columns:Q,gap:$=2,padding:B,backgroundColor:D}=this.props,J=[];for(let Y=0;Y<Q.length;Y++){let E=Q[Y];if(Y>0&&$>0)J.push(new X0({width:$}));if(E.fixedWidth!==void 0)J.push(new X0({width:E.fixedWidth,child:E.child}));else if(E.expanded)J.push(new R1({child:E.child}));else J.push(E.child)}let F=new r0({crossAxisAlignment:"start",children:J});if(!B&&!D)return F;return new b0({decoration:D?{color:D}:void 0,padding:B,child:F})}}class VA1{#A=[];#Q=new Set;get commands(){return this.#A}register(A){return this.#A.push(A),this.#$(),()=>{let Q=this.#A.indexOf(A);if(Q===-1)return;this.#A.splice(Q,1),this.#$()}}findByID(A){return this.#A.find((Q)=>Q.id===A)}runByID(A,Q){let $=this.findByID(A);if(!$||$.status.type!=="enabled")return!1;return $.run(new ls,Q,()=>{}),!0}addListener(A){this.#Q.add(A)}removeListener(A){this.#Q.delete(A)}#$(){for(let A of this.#Q)A()}}class M9 extends KA{commandRegistry;constructor({commandRegistry:A,child:Q}){super({child:Q});this.commandRegistry=A}updateShouldNotify(A){return!1}static of(A){let Q=M9.maybeOf(A);if(!Q)throw Error("No NeoCommandRegistryProvider found in widget tree");return Q}static maybeOf(A){return A.dependOnInheritedWidgetOfExactType(M9)?.commandRegistry??null}}class KA1 extends P0{onDismiss;constructor(A){super();this.onDismiss=A.onDismiss}createState(){return new ea4}}class ea4 extends R0{modalStack=new ls;commandRegistry=null;initState(){super.initState(),queueMicrotask(()=>{if(!this.mounted)return;let A=M9.of(this.context);this.commandRegistry=A,A.addListener(this.onCommandsChanged)})}dispose(){this.commandRegistry?.removeListener(this.onCommandsChanged),this.commandRegistry=null,super.dispose()}onCommandsChanged=()=>{this.setState()};build(A){let Q=M9.of(A).commands,$=new GA1({commands:Q,onAccept:(B)=>{B.run(this.modalStack,A,this.widget.onDismiss)},onDismiss:()=>{if(this.modalStack.canPop)this.modalStack.pop();else this.widget.onDismiss()}});return new UA1({root:$,controller:this.modalStack})}}var zA1=[{description:"Move cursor up/down",methods:[{keys:["↑"]},{keys:["↓"]}]},{description:"Move cursor left/right",methods:[{keys:["←"]},{keys:["→"]},{input:"B",keys:["Ctrl"]},{input:"F",keys:["Ctrl"]}]},{description:"Insert newline",methods:[{keys:["Shift","Enter"]},{keys:["Alt","Enter"]},{input:"J",keys:["Ctrl"]}],submitOnEnterOnly:!0},{description:"Insert newline",methods:[{keys:["Enter"]},{keys:["Shift","Enter"]},{keys:["Alt","Enter"]},{input:"J",keys:["Ctrl"]}],submitOnEnterOnly:!1},{description:"Submit message",methods:[{keys:["Enter"]}],submitOnEnterOnly:!0},{description:"Submit message",methods:[{keys:["Ctrl/Cmd","Enter"]}],submitOnEnterOnly:!1},{description:"Clear input",methods:[{keys:["Escape"]}]},{description:"Edit prompt in $EDITOR",methods:[{input:"G",keys:["Ctrl"]}]},{description:"Navigate history (previous/next)",methods:[{input:"P",keys:["Ctrl"]},{input:"N",keys:["Ctrl"]}]},{description:"Jump to start of line",methods:[{keys:["Cmd","←"]},{input:"A",keys:["Ctrl"]}]},{description:"Jump to end of line",methods:[{keys:["Cmd","→"]},{input:"E",keys:["Ctrl"]}]},{description:"Jump to previous word",methods:[{keys:["Alt","←"]},{keys:["Ctrl","←"]},{input:"B",keys:["Alt"]}]},{description:"Jump to next word",methods:[{keys:["Alt","→"]},{keys:["Ctrl","→"]},{input:"F",keys:["Alt"]}]},{description:"Delete character backward",methods:[{keys:["Backspace"]},{input:"H",keys:["Ctrl"]}]},{description:"Delete word backward",methods:[{keys:["Alt","Backspace"]},{input:"W",keys:["Ctrl"]}]},{description:"Delete character forward",methods:[{keys:["Delete"]},{input:"D",keys:["Ctrl"]}]},{description:"Delete to start of line",methods:[{keys:["Cmd","Backspace"]},{input:"U",keys:["Ctrl"]}]},{description:"Delete to end of line",methods:[{input:"K",keys:["Ctrl"]}]},{description:"Yank (paste deleted text)",methods:[{input:"Y",keys:["Ctrl"]}]},{description:"Paste image from clipboard",methods:[{input:"V",keys:["Ctrl"]}]},{description:"Switch agent mode",methods:[{input:"S",keys:["Ctrl"]}]},{description:"Toggle reasoning effort",methods:[{input:"D",keys:["Alt"]}]},{description:"Open command palette",methods:[{input:"O",keys:["Ctrl"]}]},{description:"Mention files",methods:[{keys:["@"]}]},{description:"Mention threads",methods:[{keys:["@@"]}]},{description:"Show prompt history",methods:[{input:"R",keys:["Ctrl"]}]},{description:"Toggle inline shortcuts help",methods:[{keys:["?"]}]},{description:"Toggle thinking/dense view",methods:[{input:"T",keys:["Alt"]}]}],IA1=[{description:"Page scroll",methods:[{keys:["Pg Up"]},{keys:["Pg Down"]}]},{description:"Half-page scroll",methods:[{input:"K",keys:["Alt"]},{input:"J",keys:["Alt"]}]},{description:"Mouse wheel scroll",methods:[{keys:["Mouse Wheel"]}]},{description:"Jump to first message",methods:[{keys:["Home"]}]},{description:"Jump to bottom of screen",methods:[{keys:["End"]}]},{description:"Navigate to previous messages",methods:[{keys:["Tab"]},{keys:["Shift","Tab"]}]}];class CX0 extends H1{items;renderRow;constructor({items:A,renderRow:Q}){super();this.items=A,this.renderRow=Q}build(A){let $=c1.of(A).size.width,B=50,D=$<50,J=[];for(let F of this.items){let[Y,E]=this.renderRow(F),Z;if(D)Z=new S0({crossAxisAlignment:"start",mainAxisSize:"min",children:[Y,new f0({padding:V0.only({left:4}),child:E})]});else Z=new r0({crossAxisAlignment:"start",children:[new R1({flex:1,child:Y}),new X0({width:1}),new R1({flex:1,child:E})]});J.push(new f0({padding:V0.horizontal(6),child:Z}))}return new S0({crossAxisAlignment:"start",mainAxisSize:"min",children:J})}}class WA1 extends P0{commands;submitOnEnter;constructor({key:A,commands:Q,submitOnEnter:$}){super(A?{key:A}:{});this.commands=Q,this.submitOnEnter=$??!0}createState(){return new Ao4}}class Ao4 extends R0{scrollController;initState(){this.scrollController=new v6,this.scrollController.disableFollowMode(),this.scrollController.jumpTo(0)}dispose(){}build(A){let $=L1.of(A).colorScheme,D=O0.of(A).app,J=c1.of(A),F=new T({color:$.primary,bold:!0}),Y=new T({color:$.secondary,bold:!0}),E=new T({color:D.keybind}),Z=new T({color:D.command}),U=new T({color:$.foreground}),X=new T({color:$.foreground}),G=J.size.width,V=J.size.height,K=G-4,I=V-4,z=Math.max(40,Math.min(80,K)),W=new Set(["permissions-disable"]),q=[...this.widget.commands.filter((L)=>{let j=L.noun?.toLowerCase();return j!=="dev"&&j!=="debug"&&!L.id.startsWith("debug-")&&!W.has(L.id)})].sort((L,j)=>{let k=(L.noun??"").toLowerCase(),_=(j.noun??"").toLowerCase(),f=k.localeCompare(_);if(f!==0)return f;let h=L.verb.toLowerCase(),b=j.verb.toLowerCase(),v=h.localeCompare(b);if(v!==0)return v;return L.id.localeCompare(j.id)}),N=new k6({autofocus:!0,controller:this.scrollController,child:new b0({constraints:new C1(z,z,0,Number.POSITIVE_INFINITY),child:new S0({crossAxisAlignment:"start",mainAxisSize:"min",children:[new $4({child:new d({text:new C(`Amp CLI - Help & Keyboard Shortcuts
5234
5234
  `,F)})}),new X0({height:1}),new f0({padding:V0.horizontal(2),child:new d({text:new C(`Editor Shortcuts
5235
5235
  `,Y)})}),new CX0({items:zA1.filter((L)=>L.submitOnEnterOnly===void 0||L.submitOnEnterOnly===this.widget.submitOnEnter),renderRow:(L)=>{let j=[];for(let _ of L.methods){let f=this.buildCleanKeyCombination(_);j.push(f)}let k=j.join(", ");return[new d({text:new C(k,E)}),new d({text:new C(L.description,U)})]}}),new X0({height:1}),new f0({padding:V0.horizontal(2),child:new d({text:new C(`Scrolling & Navigation
5236
5236
  `,Y)})}),new CX0({items:IA1,renderRow:(L)=>{let j=[];for(let _ of L.methods){let f=this.buildCleanKeyCombination(_);j.push(f)}let k=j.join(", ");return[new d({text:new C(k,E)}),new d({text:new C(L.description,U)})]}}),new X0({height:1}),new f0({padding:V0.horizontal(2),child:new d({text:new C(`Command Palette Commands
@@ -5320,7 +5320,7 @@ Ctrl-X, Y, Z to unlock`;if(this.widget.centerContent)h=this.widget.centerContent
5320
5320
  `))}return F}function $i3(A,Q,$){let{colors:B,app:D}=$,J=Bi3(Q.status,$);if(A.push(new C(` ${J.icon} `,new T({color:J.color}))),A.push(new C(Q.name,new T({color:Q.status==="pending"?B.warning:D.command}))),Q.status==="pending")A.push(new C(" discovering...",new T({color:B.foreground,dim:!0})));else if(Q.description)A.push(new C(` ${ve4(Q.description,50)}`,new T({color:B.foreground,dim:!0})));if(Q.error)A.push(new C(` ${ve4(Q.error,40)}`,new T({color:D.toolError})));A.push(new C(`
5321
5321
  `))}function Bi3(A,Q){let{colors:$,app:B}=Q;switch(A){case"pending":return{icon:"◌",color:$.warning};case"registered":return{icon:"•",color:$.mutedForeground};case"failed":return{icon:"✗",color:B.toolError};case"duplicate":return{icon:"◇",color:$.warning};default:return{icon:"?",color:$.foreground}}}function ve4(A,Q){let $=A.replace(/\s+/g," ").trim();if(J4($)<=Q)return $;let B="...",D=J4(B);if(Q<=D)return VQ(B,Q);return`${VQ($,Q-D,!0,"")}${B}`}var u51="https://ampcode.com/news/neo",_51=[{title:"Meet the new Amp CLI",body:[]},{title:"Rebuilt From The Ground Up",body:["Same close-up terminal workflow. Completely different underneath."]},{title:"Just Keep Typing",body:["Context is summarized automatically at ~90%.","No handoff flow. No context percentage to babysit."]},{title:"Queueing and Steering",body:["Sending a message now queues by default instead of cancelling tools.","Use steering when you want the agent to see something sooner."]},{title:"Remote Control",body:["Start a thread in the CLI, then keep going from ampcode.com.","Watch live updates and queue follow-ups from any device."]},{title:"Customize Amp with Amp",body:[{text:"Amp now has a ",linkText:"complete plugin API",href:"https://ampcode.com/manual/plugin-api",textAfter:"."},"Add tools, commands, control UI, and hook into events."]},{title:"Permissions",body:[{text:"By default (when no ",highlightText:"amp.permissions",textAfterHighlight:" setting is present), Amp no longer asks for confirmation before running any tools and commands. And you can now implement your own custom permission logic with ",linkText:"plugins",href:"https://ampcode.com/manual/plugin-api",textAfter:"."}]},{title:null,body:["Check out the full news post for more:",{text:u51,href:u51},"","",{text:"Need old Amp for a bit? Use ",keybind:"amp --take-me-back"}]}];function Di3(A){return[{title:"Upgrade your Amp CLI",body:[{text:"This npm-based distribution of Amp CLI has been deprecated. To use the ",linkText:"new Amp CLI",href:u51,textAfter:" you'll need to switch to the binary install:",linkWidget:!0},"",{codeBlock:["npm uninstall -g @sourcegraph/amp",A]}]}]}function Ji3(){if(process.platform==="win32")return'powershell -c "irm https://ampcode.com/install.ps1 | iex"';return"curl -fsSL https://ampcode.com/install.sh | bash"}var Yx=50,TR=40,R51=1000,Fi3=420,Yi3=760,Ei3=-250,Zi3=1100,HG0=33,ye4=0.999,Ui3=2.1,Xi3=720,Gi3=420,ce4="Meet the new",le4="Amp",ie4="CLI",T51=Z4(ce4).length,Vi3=Z4(le4).length,Ki3=Z4(ie4).length,qG0={primary:{r:140,g:38,b:0},secondary:{r:255,g:225,b:102}},xe4={primary:{r:10,g:42,b:18},secondary:{r:200,g:230,b:68}},be4={primary:{r:18,g:0,b:107},secondary:{r:103,g:255,b:168}},he4=[qG0,xe4,be4,qG0,xe4,be4,qG0],zi3=qG0;class v51 extends P0{onDismiss;onQuit;animationProgress;animationsEnabled;variant;binaryInstallCommand;introStages;dismissible;constructor(A){super();this.onDismiss=A.onDismiss,this.onQuit=A.onQuit,this.animationProgress=A.animationProgress,this.animationsEnabled=A.animationsEnabled??!0,this.variant=A.variant??"intro",this.binaryInstallCommand=A.binaryInstallCommand??Ji3(),this.introStages=this.variant==="npm-migration"?Di3(this.binaryInstallCommand):_51,this.dismissible=this.variant!=="npm-migration"}createState(){return new ne4}}class ne4 extends R0{startedAt=performance.now();animationTimer=null;stageTransitionTimer=null;firstStageTitleTimer=null;firstStageHintTimer=null;firstStageRevealTimer=null;firstStageTitleRevealStartedAt=null;firstStageHintRevealStartedAt=null;stageTransitionStartedAt=performance.now();animationStartProgress=0;animationTargetProgress=1;animationDurationMs=R51;onAnimationComplete=null;animationProgress=0;introStage=0;previousIntroStage=null;stageTransitionProgress=1;stageTransitionDirection=1;firstStageTitleVisible=!1;firstStageHintVisible=!1;firstStageTitleRevealProgress=0;firstStageHintRevealProgress=0;dismissTimer=null;dismissStartedAt=performance.now();dismissProgress=0;isDismissing=!1;splashOrbGlow=new a9(42);initState(){super.initState(),this.startAnimationIfNeeded()}didUpdateWidget(A){if(super.didUpdateWidget(A),A.animationProgress!==this.widget.animationProgress||A.animationsEnabled!==this.widget.animationsEnabled)this.startAnimationIfNeeded()}dispose(){this.stopAnimation(),this.stopStageTransitionTimer(),this.stopFirstStageRevealTimers(),this.stopDismissAnimation(),super.dispose()}startAnimationIfNeeded(){if(this.stopAnimation(),this.stopFirstStageRevealTimers(),this.widget.animationProgress!==void 0){this.animationProgress=YF(this.widget.animationProgress),this.firstStageTitleVisible=this.animationProgress>=ye4,this.firstStageHintVisible=this.animationProgress>=ye4,this.firstStageTitleRevealProgress=this.firstStageTitleVisible?1:0,this.firstStageHintRevealProgress=this.firstStageHintVisible?1:0;return}if(!this.widget.animationsEnabled){this.stopStageTransitionTimer(),this.stopDismissAnimation(),this.animationProgress=1,this.isDismissing=!1,this.dismissProgress=0,this.firstStageTitleVisible=!0,this.firstStageHintVisible=!0,this.firstStageTitleRevealProgress=1,this.firstStageHintRevealProgress=1,this.previousIntroStage=null,this.stageTransitionProgress=1;return}if(this.firstStageTitleVisible=!1,this.firstStageHintVisible=!1,this.firstStageTitleRevealProgress=0,this.firstStageHintRevealProgress=0,this.startProgressAnimation({from:0,to:1,durationMs:R51,onComplete:()=>{if(!this.widget.dismissible)this.setState(()=>{this.firstStageTitleVisible=!0,this.firstStageHintVisible=!0,this.firstStageTitleRevealProgress=1,this.firstStageHintRevealProgress=1})}}),this.widget.dismissible)this.startFirstStageRevealSequence()}startDismissAnimation(){if(this.isDismissing)return;if(!this.widget.animationsEnabled){this.widget.onDismiss();return}this.stopFirstStageRevealTimers(),this.stopStageTransitionTimer(),this.dismissStartedAt=performance.now(),this.setState(()=>{this.isDismissing=!0,this.dismissProgress=0}),this.dismissTimer=setInterval(()=>{let A=performance.now()-this.dismissStartedAt,Q=YF(A/Yi3);if(this.setState(()=>{this.dismissProgress=Q}),Q>=1)this.stopDismissAnimation(),this.widget.onDismiss()},HG0)}canNavigateIntroStage(){if(this.isDismissing)return!1;if(!this.firstStageHintVisible)return!1;if(this.introStage===0&&this.firstStageHintRevealProgress<1)return!1;return!0}advanceIntroStage(){if(!this.canNavigateIntroStage())return;if(this.isFinalIntroStage()){if(this.widget.dismissible)this.startDismissAnimation();return}this.moveIntroStage(1)}dismissFromFinalIntroStage(){if(!this.widget.dismissible||!this.canNavigateIntroStage()||!this.isFinalIntroStage())return!1;return this.startDismissAnimation(),!0}nextIntroStage(){if(!this.canNavigateIntroStage()||this.isFinalIntroStage())return;this.moveIntroStage(1)}goToPreviousIntroStage(){if(!this.canNavigateIntroStage()||this.introStage<=0)return;this.moveIntroStage(-1)}isFinalIntroStage(){return this.introStage>=this.widget.introStages.length-1}moveIntroStage(A){let Q=this.introStage+A;if(this.stopStageTransitionTimer(),this.stageTransitionStartedAt=performance.now(),this.setState(()=>{this.previousIntroStage=this.introStage,this.introStage=Q,this.stageTransitionDirection=A}),this.widget.animationProgress!==void 0||!this.widget.animationsEnabled){this.setState(()=>{this.previousIntroStage=null,this.stageTransitionProgress=1});return}this.setState(()=>{this.stageTransitionProgress=0}),this.stageTransitionTimer=setInterval(()=>{let $=performance.now()-this.stageTransitionStartedAt,B=YF($/Fi3);if(this.setState(()=>{if(this.stageTransitionProgress=B,B>=1)this.previousIntroStage=null}),B>=1)this.stopStageTransitionTimer()},HG0)}startProgressAnimation({from:A,to:Q,durationMs:$,onComplete:B}){this.stopAnimation(),this.startedAt=performance.now(),this.animationStartProgress=A,this.animationTargetProgress=Q,this.animationDurationMs=$,this.onAnimationComplete=B,this.animationProgress=A,this.animationTimer=setInterval(()=>{let D=performance.now()-this.startedAt,J=YF(D/this.animationDurationMs),F=this.animationStartProgress+(this.animationTargetProgress-this.animationStartProgress)*Ex(J);if(this.setState(()=>{this.animationProgress=F}),J>=1)this.stopAnimation(),this.onAnimationComplete?.(),this.onAnimationComplete=null},HG0)}stopAnimation(){if(this.animationTimer)clearInterval(this.animationTimer),this.animationTimer=null}stopStageTransitionTimer(){if(this.stageTransitionTimer)clearInterval(this.stageTransitionTimer),this.stageTransitionTimer=null}startFirstStageRevealSequence(){if(this.stopFirstStageRevealTimers(),!this.widget.animationsEnabled){this.setState(()=>{this.firstStageTitleVisible=!0,this.firstStageHintVisible=!0,this.firstStageTitleRevealProgress=1,this.firstStageHintRevealProgress=1});return}this.setState(()=>{this.firstStageTitleVisible=!1,this.firstStageHintVisible=!1,this.firstStageTitleRevealProgress=0,this.firstStageHintRevealProgress=0});let A=Math.max(0,R51+Ei3),Q=A+Zi3;this.firstStageTitleTimer=setTimeout(()=>{this.firstStageTitleRevealStartedAt=performance.now(),this.setState(()=>{this.firstStageTitleVisible=!0,this.firstStageTitleRevealProgress=0}),this.startFirstStageRevealTimer()},A),this.firstStageHintTimer=setTimeout(()=>{this.firstStageHintRevealStartedAt=performance.now(),this.setState(()=>{this.firstStageHintVisible=!0,this.firstStageHintRevealProgress=0}),this.startFirstStageRevealTimer()},Q)}startFirstStageRevealTimer(){if(this.firstStageRevealTimer)return;this.firstStageRevealTimer=setInterval(()=>{let A=performance.now(),Q=this.firstStageTitleRevealStartedAt?YF((A-this.firstStageTitleRevealStartedAt)/Xi3):this.firstStageTitleRevealProgress,$=this.firstStageHintRevealStartedAt?YF((A-this.firstStageHintRevealStartedAt)/Gi3):this.firstStageHintRevealProgress;if(this.setState(()=>{this.firstStageTitleRevealProgress=Q,this.firstStageHintRevealProgress=$}),Q>=1&&$>=1)this.stopFirstStageRevealTimer()},HG0)}stopFirstStageRevealTimers(){if(this.stopFirstStageRevealTimer(),this.firstStageTitleRevealStartedAt=null,this.firstStageHintRevealStartedAt=null,this.firstStageTitleTimer)clearTimeout(this.firstStageTitleTimer),this.firstStageTitleTimer=null;if(this.firstStageHintTimer)clearTimeout(this.firstStageHintTimer),this.firstStageHintTimer=null}stopFirstStageRevealTimer(){if(this.firstStageRevealTimer)clearInterval(this.firstStageRevealTimer),this.firstStageRevealTimer=null}stopDismissAnimation(){if(this.dismissTimer)clearInterval(this.dismissTimer),this.dismissTimer=null}currentOrbPalette(){let A=ge4(this.introStage),Q=this.previousIntroStage===null||this.stageTransitionProgress>=1?A:me4(ge4(this.previousIntroStage),A,Ex(this.stageTransitionProgress));return this.dismissProgress>0?me4(Q,zi3,Ex(this.dismissProgress)):Q}build(A){let Q=L1.of(A).colorScheme,$=O0.of(A),B=this.currentOrbPalette(),D=J$(1,"frontier",B),J=c1.of(A).size,Y=this.widget.animationProgress??this.animationProgress,E=Math.max(J.width/Yx,J.height/TR)*Ui3,Z=E+(1-E)*Y,U=Ex(this.dismissProgress),X=Math.max(Yx,Math.round(Yx*Z)),G=Math.max(TR,Math.round(TR*Z)),V=Math.round((J.width-X)/2),K=Math.round((J.height-G)/2),I=Math.max(0,Math.floor((J.width-Yx)/2)),z=-Math.floor(TR/2),W=Math.round(V+(I-V)*Y),H=Math.round(K+(z-K)*Y),q=W+X/2,N=H+G/2,w=Ii3({dismissProgress:this.dismissProgress,easedDismissProgress:U,introOrbScale:Z,normalOrbCenterX:q,normalOrbCenterY:N,size:J}),O=Math.max(Yx,Math.round(Yx*w.orbScale)),L=Math.max(TR,Math.round(TR*w.orbScale)),j=w.orbCenterX,k=w.orbCenterY,_=Math.round(j-O/2),f=Math.round(k-L/2),h=Math.max(3,Math.min(J.height-5,Math.floor(TR/2)+2)),b=Math.max(h+3,J.height-3),v=w.textDissolveProgress,y=this.isFinalIntroStage()?w.backdropDissolveProgress:0,p=this.firstStageTitleVisible&&v<1,c=p&&this.firstStageHintVisible,g=c&&this.widget.dismissible&&this.introStage>0&&!this.isFinalIntroStage(),i=this.introStage===0?this.firstStageTitleRevealProgress:1,r=this.introStage===0?this.firstStageHintRevealProgress:1,A0=Math.max(24,Math.min(74,J.width-4)),I0=Math.min(12,Math.max(8,J.height-h-6)),E0=Math.max(0,Math.floor((J.width-A0)/2)),W0=Math.max(0,Math.min(J.height-I0,Math.floor(J.height*0.55-I0/2))),j0=this.widget.animationProgress!==void 0||!this.widget.animationsEnabled?new uN({width:O,height:L,agentMode:"frontier",visualStyle:"neo",neoGlyphSet:"dotField",backgroundColor:Q.background,primaryColor:B.primary,secondaryColor:B.secondary,glow:this.splashOrbGlow,seed:42,fps:0,onClick:()=>{}}):new uN({width:O,height:L,agentMode:"frontier",visualStyle:"neo",neoGlyphSet:"dotField",backgroundColor:Q.background,primaryColor:B.primary,secondaryColor:B.secondary,glow:this.splashOrbGlow,onClick:()=>{}});return new k4({autofocus:!0,canRequestFocus:!0,debugLabel:"NeoWelcomeTakeover",onKey:(Q0)=>{if(Q0.key==="Enter")return this.advanceIntroStage(),"handled";if(!this.widget.dismissible&&Q0.key==="c"&&Q0.ctrlKey)return this.widget.onQuit?.(),"handled";if(!this.widget.dismissible&&Q0.key==="q")return this.widget.onQuit?.(),"handled";if((Q0.key===" "||Q0.key==="Space")&&!this.isFinalIntroStage())return this.advanceIntroStage(),"handled";if(Q0.key==="Escape"||Q0.key==="Esc"){if(!this.widget.dismissible)return this.widget.onQuit?.(),"handled";return this.dismissFromFinalIntroStage()?"handled":"ignored"}if(Q0.key==="ArrowRight")return this.nextIntroStage(),"handled";if(Q0.key==="ArrowLeft")return this.goToPreviousIntroStage(),"handled";return"ignored"},child:new i4({fit:"expand",children:[new ae4({color:Q.background,dissolveProgress:y}),new i4({fit:"expand",children:[new O1({onClick:()=>{},child:X0.expand()}),new o4({left:_,top:f,width:O,height:L,child:j0}),...p?[new o4({left:E0,top:W0,width:A0,height:I0,child:Hi3({introStages:this.widget.introStages,stage:this.introStage,previousStage:this.previousIntroStage,progress:this.stageTransitionProgress,direction:this.stageTransitionDirection,width:A0,height:I0,foreground:Q.foreground,mutedForeground:Q.mutedForeground,accent:D,link:$.app.link,keybind:$.app.keybind,titleRevealProgress:i,dissolveProgress:v,context:A})})]:[],...c?[...g?[new o4({left:E0,top:Math.max(0,b-1),width:A0,height:1,child:new d({text:Li3({stage:this.introStage,featureStageCount:Math.max(0,this.widget.introStages.length-2),foreground:Q.mutedForeground,dissolveProgress:v}),textAlign:"center"})})]:[],new o4({left:E0,top:b,width:A0,height:1,child:ji3({finalStage:this.isFinalIntroStage(),dismissible:this.widget.dismissible,foreground:Q.mutedForeground,keybind:$.app.keybind,revealProgress:r,dissolveProgress:v,context:A})})]:[]]})]})})}}class ae4 extends R5{color;dissolveProgress;constructor({color:A,dissolveProgress:Q}){super();this.color=A,this.dissolveProgress=Q}createRenderObject(){return new oe4(this.color,this.dissolveProgress)}updateRenderObject(A){A.update(this.color,this.dissolveProgress)}}class oe4 extends p1{color;dissolveProgress;constructor(A,Q){super();this.color=A,this.dissolveProgress=Q}update(A,Q){this.color=A,this.dissolveProgress=Q,this.markNeedsPaint()}performLayout(){let A=this._lastConstraints;q4(!!A,"performLayout called without constraints");let Q=A.constrain(A.biggest.width,A.biggest.height);this.setSize(Q.width,Q.height),super.performLayout()}paint(A,Q=0,$=0){let B=Math.floor(Q+this.offset.x),D=Math.floor($+this.offset.y),J=Math.floor(this.size.width),F=Math.floor(this.size.height),Y={bg:this.color},E=YF(this.dissolveProgress);if(E<=0){A.fill(B,D,J,F," ",Y);return}if(E>=1)return;for(let Z=0;Z<F;Z++)for(let U=0;U<J;U++)if(!Wi3(U,Z,J,F,E))A.fill(B+U,D+Z,1,1," ",Y)}}function YF(A){return Math.min(1,Math.max(0,A))}function Ex(A){return 1-(1-A)**3}function ge4(A){return he4[A]??he4[0]}function me4(A,Q,$){return{primary:cj(A.primary,Q.primary,$),secondary:cj(A.secondary,Q.secondary,$)}}function Ii3({dismissProgress:A,easedDismissProgress:Q,introOrbScale:$,normalOrbCenterX:B,normalOrbCenterY:D,size:J}){return{orbScale:$+($*0.86-$)*Q,orbCenterX:B+(J.width*0.54-B)*Q,orbCenterY:D-J.height*0.44*Q,textDissolveProgress:YF(A/0.52),backdropDissolveProgress:Ex(YF((A-0.12)/0.88))}}function Wi3(A,Q,$,B,D){let J=B<=1?0:Q/(B-1),F=re4(A+Q*Math.max(1,$));return(1-J)*0.72+F*0.28<D}function Hi3({introStages:A,stage:Q,previousStage:$,progress:B,direction:D,width:J,height:F,foreground:Y,mutedForeground:E,accent:Z,link:U,keybind:X,titleRevealProgress:G,dissolveProgress:V,context:K}){if($===null||B>=1)return P51({introStages:A,stage:Q,foreground:Y,mutedForeground:E,accent:Z,link:U,keybind:X,titleRevealProgress:G,dissolveProgress:V,context:K});let I=Ex(B),z=D*Math.round((1-I)*J),W=-D*Math.round(I*J);return new sz(new i4({fit:"expand",children:[new o4({left:W,top:0,width:J,height:F,child:P51({introStages:A,stage:$,foreground:Y,mutedForeground:E,accent:Z,link:U,keybind:X,titleRevealProgress:$===0?1:G,dissolveProgress:V,context:K})}),new o4({left:z,top:0,width:J,height:F,child:P51({introStages:A,stage:Q,foreground:Y,mutedForeground:E,accent:Z,link:U,keybind:X,titleRevealProgress:G,dissolveProgress:V,context:K})})]}))}function P51({introStages:A,stage:Q,foreground:$,mutedForeground:B,accent:D,link:J,keybind:F,titleRevealProgress:Y,dissolveProgress:E,context:Z}){let U=A[Q]??A[0]??_51[0],X=new T({color:D,bold:!0}),G=new T({color:$}),V=A===_51&&Q===0,K=[...U.title===null?[]:[new d({text:V?NG0(wi3({progress:Y,foreground:D,pulseColor:D}),E):new C(zB(U.title,E),X),textAlign:"center"})],...U.body.length>0?[qi3()]:[],...U.body.map((I)=>Ni3(I,G,B,J,F,E,Z))];return new $4({child:new f0({padding:V0.horizontal(1),child:new S0({crossAxisAlignment:"stretch",mainAxisAlignment:"center",mainAxisSize:"min",children:K})})})}function qi3(){return X0.height(1)}function Ni3(A,Q,$,B,D,J,F){if(typeof A==="string")return new d({text:new C(zB(A,J),Q),textAlign:"center"});if("codeBlock"in A)return new X5({onCopy:(Y,E)=>{if(E)L3.success(F,"Copied to clipboard",2000)},child:new S0({mainAxisSize:"min",children:A.codeBlock.map((Y)=>new d({text:new C(zB(Y,J),new T({color:D})),textAlign:"center",selectable:!0}))})});if("keybind"in A){let Y=new d({text:new C("",void 0,[new C(zB(A.text,J),new T({color:$,dim:!0})),new C(zB(A.keybind,J,Z4(A.text).length),new T({color:D}))]),textAlign:"center",selectable:"selectable"in A?A.selectable:!1});if("selectable"in A)return new $4({child:new X5({child:Y})});return Y}if("highlightText"in A){let Y=u6.createSpan(A.href,A.linkText,new T({color:B,underline:!0})),E=eZ.of(F),Z=new C("",void 0,[new C(A.text,Q),new C(A.highlightText,new T({color:D})),new C(A.textAfterHighlight,Q),new C(Y.text,Y.style,Y.children,Y.hyperlink,()=>{n6(F,A.href,{forceExternal:!1,onShowImagePreview:E})}),new C(A.textAfter,Q)]);return new d({text:NG0(Z,J),textAlign:"center"})}if("linkText"in A){if(A.linkWidget)return new S0({mainAxisSize:"min",children:[new d({text:new C(zB(A.text,J),Q),textAlign:"center"}),new $4({child:new r0({mainAxisSize:"min",children:[u6.createWidget(F,A.href,zB(A.linkText,J),new T({color:B,underline:!0})),new d({text:new C(zB(A.textAfter,J),Q)})]})})]});let Y=u6.createSpan(A.href,A.linkText,new T({color:B,underline:!0})),E=eZ.of(F),Z=new C("",void 0,[new C(A.text,Q),new C(Y.text,Y.style,Y.children,Y.hyperlink,()=>{n6(F,A.href,{forceExternal:!1,onShowImagePreview:E})}),new C(A.textAfter,Q)]);return new d({text:NG0(Z,J),textAlign:"center"})}if(J>0)return new d({text:new C(zB(A.text,J),new T({color:B,underline:!0})),textAlign:"center"});return new $4({child:u6.createWidget(F,A.href,A.text,new T({color:B,underline:!0}))})}function wi3({progress:A,foreground:Q,pulseColor:$}){let B=new T({color:Q,bold:!0}),D=new T({color:Mi3({progress:A,foreground:Q,pulseColor:$}),bold:!0});return new C("",void 0,[new C(Ci3(A).padEnd(T51," "),B),new C(" ",B),new C(de4(le4,Vi3,A,0.72),B),new C(" ",B),new C(de4(ie4,Ki3,A,0.88),D)])}function Ci3(A){let Q=Z4(ce4),$=Math.min(T51,Math.ceil(YF(A/0.62)*T51));return Q.slice(0,$).join("")}function de4(A,Q,$,B){return $>=B?A:"".padEnd(Q," ")}function Mi3({progress:A,foreground:Q,pulseColor:$}){if(A<0.88||A>=1)return Q;let B=YF((A-0.88)/0.12);return Math.cos(B*Math.PI*4)*(1-B)>0.12?$:Q}function Li3({stage:A,featureStageCount:Q,foreground:$,dissolveProgress:B}){return new C(zB(`${A}/${Q}`,B),new T({color:$,dim:!0}))}function Oi3({finalStage:A,dismissible:Q,foreground:$,keybind:B,revealProgress:D,dissolveProgress:J}){let F=new T({color:B}),Y=new T({color:$,dim:!0}),E=Q?A?"Enter":"Space":"Esc",Z=Q?A?" to get started":" to continue":" to quit, or use ",U=Q?"":"amp --take-me-back",X=Q?"":" to use the old version",G=`${Z}${U}${X}`;if(!Q)return new C("",void 0,[new C(E,F),new C(Z,Y),new C(U,F),new C(X,Y)]);let V=pe4(E,D),K=pe4(G,YF((D*(Z4(E).length+Z4(G).length)-Z4(E).length)/Z4(G).length));return new C("",void 0,[new C(zB(V,J),F),new C(zB(K.slice(0,Z.length),J),Y),new C(zB(K.slice(Z.length,Z.length+U.length),J),F),new C(zB(K.slice(Z.length+U.length),J),Y)])}function ji3({finalStage:A,dismissible:Q,foreground:$,keybind:B,revealProgress:D,dissolveProgress:J,context:F}){if(Q)return new d({text:Oi3({finalStage:A,dismissible:Q,foreground:$,keybind:B,revealProgress:D,dissolveProgress:J}),textAlign:"center"});let Y=new T({color:B}),E=new T({color:$,dim:!0});return new X5({onCopy:(Z,U)=>{if(U)L3.success(F,"Copied to clipboard",2000)},child:new d({text:new C("",void 0,[new C("q",Y),new C(" to quit, or use ",E),new C("amp --take-me-back",Y),new C(" to use the old version",E)]),textAlign:"center",selectable:!0})})}function pe4(A,Q){let $=Z4(A),B=Math.min($.length,Math.ceil(YF(Q)*$.length));return $.slice(0,B).join("").padEnd($.length," ")}function NG0(A,Q,$=0){if(Q<=0)return A;let B=$+Z4(A.text??"").length,D=A.children?.map((J)=>{let F=NG0(J,Q,B);return B+=Z4(J.toPlainText()).length,F});return new C(A.text?zB(A.text,Q,$):A.text,A.style,D,A.hyperlink,A.onClick)}function zB(A,Q,$=0){if(Q<=0)return A;return Z4(A).map((D,J)=>{if(D.trim()==="")return D;return re4($+J)<Q?" ":D}).join("")}function re4(A){let Q=Math.sin((A+1)*12.9898)*43758.5453;return Q-Math.floor(Q)}p0();$8();function Xw(A,Q){let{colors:$,dim:B}=Q,D=[];if(A.totalCostUSD===null)return D;let J=A.costBreakdown,F=J?.freeUSD??0,Y=J?.paidUSD??0;if(F===0&&Y===0)return D;let Z={decimalPlaces:"more-if-tiny",intent:"cost"};if(Y===0)D.push(new C(eG(F,Z),new T({color:$.foreground,dim:B}))),D.push(new C(" (free)",new T({color:$.foreground,dim:B})));else if(F>0)D.push(new C(eG(F,Z),new T({color:$.foreground,dim:B}))),D.push(new C(" (free)",new T({color:$.foreground,dim:B}))),D.push(new C(" + ",new T({color:$.foreground,dim:B}))),D.push(new C(eG(Y,Z),new T({color:$.foreground,dim:B,bold:!B})));else D.push(new C(eG(Y,Z),new T({color:$.foreground,dim:B,bold:!B})));return D}class k51 extends V4{}class S51 extends V4{}function Ri3(A,Q){if(Q.code==="auth-required")return"You must be logged in to view thread usage. Run `amp login` first.";if(Q.code==="thread-not-found")return`Thread ${A} not found.`;return`Failed to load thread usage: ${Q.message??Q.code}`}function Pi3(A,Q){let $=O0.of(Q),{colors:B}=$,D=Xw(A,{colors:{foreground:B.foreground}}),J=[];if(D.length>0)J.push(new C("Total: ",new T({color:B.mutedForeground}))),J.push(...D);else if(A.totalCostUSD===null)J.push(new C("Usage information is currently unavailable."));else J.push(new C("No usage recorded for this thread yet."));if(A.costBreakdownURL)J.push(new C(`
5322
5322
 
5323
- `)),J.push(new C("Details: ",new T({color:B.mutedForeground}))),J.push(new C(A.costBreakdownURL,new T({color:$.app.link})));return new d({text:new C("",void 0,J)})}function ui3(A,Q,$){let B=Pi3(A,Q);if(!A.costBreakdownURL)return new w6({header:"Thread Cost",minWidth:80,maxWidth:100,onDismiss:$,child:B});let D=A.costBreakdownURL,J=new T1(()=>{return x4.maybeInvoke(Q,new H8(D,"Cost breakdown URL copied to clipboard","Failed to copy cost breakdown URL")),"handled"}),F=new T1(()=>{return n6(Q,D),"handled"});return new w6({header:"Thread Cost",minWidth:80,maxWidth:100,autofocus:!1,footer:[{keys:["Esc"],label:"close"},{keys:["o"],label:"open in browser"},{keys:["y"],label:"copy url"}],onDismiss:$,child:new x4({actions:new Map([[k51,J],[S51,F]]),child:new kA({debugLabel:"ThreadCostShortcuts",shortcuts:new Map([[G1.key("o"),new S51],[G1.key("y"),new k51]]),child:new v4({autofocus:!0,debugLabel:"ThreadCostBody",child:B})})})})}function se4(A){return{noun:"thread",verb:"show cost",description:"Show usage cost for the active thread",keywords:["usage","credits","billing","spend"],get status(){return A.getActiveThreadID()?{type:"enabled"}:{type:"disabled",reason:"No active thread"}},run:async(Q,$,B)=>{let D=A.getActiveThreadID();if(!D)return;try{let J=await t4.threadDisplayCostInfo({threadID:D},{config:A.configService});if(!J.ok){A.toastController.show(Ri3(D,J.error),"error",5000),B();return}Q.push(ui3(J.result,$,B))}catch(J){P.error("Failed to load Neo thread cost",{error:J,threadID:D}),A.toastController.show(`Failed to show thread cost: ${J instanceof Error?J.message:String(J)}`,"error",5000),B()}}}}p0();u9();Q4();class XI extends V4{direction;constructor(A){super();this.direction=A}}class wG0 extends V4{}class zt extends V4{}class CG0 extends V4{index;constructor(A){super();this.index=A}}function f51(A){return A.length+2}class y51 extends P0{props;constructor(A){super();this.props=A}createState(){return new te4}}class te4 extends R0{selectedIndex=0;initState(){super.initState(),this.selectedIndex=this.findSelectableIndex(this.widget.props.initialSelectedIndex??0)}didUpdateWidget(A){this.selectedIndex=this.findSelectableIndex(this.selectedIndex)}isSelectable(A){let Q=this.widget.props.entries[A];return Q?.type==="item"&&(Q.enabled??!0)}findSelectableIndex(A){let{entries:Q}=this.widget.props;if(Q.length===0)return 0;let $=Math.max(0,Math.min(A,Q.length-1));if(this.isSelectable($))return $;for(let B=1;B<Q.length;B++){let D=$+B;if(D<Q.length&&this.isSelectable(D))return D;let J=$-B;if(J>=0&&this.isSelectable(J))return J}return 0}moveSelection(A){let Q=this.findNextSelectableIndex(A);if(Q===this.selectedIndex)return;this.setState(()=>{this.selectedIndex=Q})}findNextSelectableIndex(A){let{entries:Q}=this.widget.props;for(let $=this.selectedIndex+A;$>=0&&$<Q.length;$+=A)if(this.isSelectable($))return $;return this.selectedIndex}acceptIndex(A){let Q=this.widget.props.entries[A];if(Q?.type!=="item"||!(Q.enabled??!0))return;this.setState(()=>{this.selectedIndex=A}),this.widget.props.onAccept(Q.value)}invoke=(A)=>{if(A instanceof XI)return this.moveSelection(A.direction),"handled";if(A instanceof wG0)return this.acceptIndex(this.selectedIndex),"handled";if(A instanceof zt)return this.widget.props.onDismiss(),"handled";if(A instanceof CG0)return this.acceptIndex(A.index),"handled";return"ignored"};buildShortcuts(){let A=new Map([[G1.key("ArrowDown"),new XI(1)],[G1.key("j"),new XI(1)],[G1.ctrl("n"),new XI(1)],[G1.key("ArrowUp"),new XI(-1)],[G1.key("k"),new XI(-1)],[G1.ctrl("p"),new XI(-1)],[G1.key("Enter"),new wG0],[G1.key("Escape"),new zt],[G1.ctrl("."),new zt]]);return this.widget.props.entries.forEach((Q,$)=>{if(Q.type==="item"&&Q.shortcut)A.set(Q.shortcut,new CG0($))}),A}buildActions(){return new Map([[XI,new T1(this.invoke)],[wG0,new T1(this.invoke)],[zt,new T1(this.invoke)],[CG0,new T1(this.invoke)]])}build(A){let Q=O0.of(A),$=_i3(this.widget.props.entries,c1.of(A).supportsEmojiWidth);return new b0({width:this.widget.props.width,height:f51(this.widget.props.entries),decoration:new R4(Q.colors.background,m1.all(new d1(Q.colors.border,1,"solid"))),child:new x4({actions:this.buildActions(),child:new kA({debugLabel:"NeoContextPickerShortcuts",shortcuts:this.buildShortcuts(),child:new v4({autofocus:!0,debugLabel:"NeoContextPicker",child:new S0({mainAxisSize:"min",crossAxisAlignment:"stretch",children:this.widget.props.entries.map((B,D)=>this.buildEntry(B,D,$,Q))})})})})})}buildEntry(A,Q,$,B){if(A.type==="separator")return new b0({height:1,decoration:{border:new m1(new d1(B.colors.border,1,"solid"))}});let D=Q===this.selectedIndex,J=A.enabled??!0,F=new T({color:D?B.app.selectionForeground:B.colors.foreground,dim:!J}),Y=new T({color:D?B.app.selectionForeground:B.app.keybind,bold:!0,dim:!J});return new O1({onClick:()=>this.acceptIndex(Q),child:new b0({padding:V0.symmetric(1,0),decoration:D?new R4(B.app.selectionBackground):void 0,child:new r0({crossAxisAlignment:"start",children:[new R1({child:new d({text:new C(A.label,F),maxLines:1,overflow:"ellipsis"})}),new X0({width:1}),new X0({width:$,child:new d({text:new C(ee4(A),Y),textAlign:"right",maxLines:1,overflow:"ellipsis"})})]})})})}}function _i3(A,Q){return A.reduce(($,B)=>{return B.type==="item"?Math.max($,J4(ee4(B),Q)):$},0)}function ee4(A){return A.shortcutLabel??A.shortcut?.toString().toLowerCase()??""}var Ti3=36,vi3=24,ki3=72;class A06 extends P0{child;onContext;constructor(A,Q){super();this.child=A;this.onContext=Q}createState(){return new Q06}}class Q06 extends R0{build(A){return this.widget.onContext(A),this.widget.child}}function $06(A){return A.replace(/ ago$/,"")}function MG0(A){return A.reduce((Q,$)=>Math.max(Q,J4($06($.description.timeAgo))),0)}function B06(A){return Math.max(vi3,Math.min(A,ki3))}class x51 extends V4{}class b51 extends V4{}class h51{options;visibility;width=Ti3;constructor(A){this.options=A;this.visibility=new xr(A.state)}isVisible(){return this.visibility.isEnabled()}buildBody(A){return new r0({crossAxisAlignment:"stretch",children:[this.buildSlot(),new R1({child:A})]})}buildSlot(){if(!this.options.isAvailable()||this.visibility.isDisabled())return new X0({width:0});return new X0({width:this.width,child:new k4({debugLabel:"ThreadListSidebar",child:new D06({activeThreadID:this.options.getActiveThreadID(),currentWorkspaceURI:t1(i0.file(this.options.getWorkspaceRoot())),width:this.width,loadThreads:this.options.loadThreads,onSelectThread:this.options.onSelectThread,onDismiss:this.close,onResizeWidth:this.resize})})})}commands(){if(!this.options.isAvailable())return[];return[{noun:"thread",verb:"toggle sidebar",description:"Show or hide the thread sidebar",keywords:["sidebar","recent","history","threads"],shortcut:G1.alt("s"),status:{type:"enabled"},run:(A,Q,$)=>{$(),this.toggle()}}]}shortcutEntries(){return this.options.isAvailable()?[[G1.alt("s"),new EX0]]:[]}actionEntries(){if(!this.options.isAvailable())return[];return[[EX0,new T1(()=>this.toggle())]]}toggle=()=>{if(!this.options.isAvailable())return"ignored";if(this.visibility.isDisabled()&&this.options.isBlocked())return"ignored";return this.visibility.toggle(),"handled"};close=()=>{this.visibility.disable()};resize=(A)=>{let Q=B06(A);if(Q===this.width)return;this.options.state.setState(()=>{this.width=Q})}}class D06 extends P0{props;constructor(A){super();this.props=A}createState(){return new J06}}class J06 extends R0{threads=[];isLoading=!0;isSwitchingThread=!1;hasError=!1;filterByWorkspace=!0;timeColWidth=0;contextMenu=null;pendingThreadMutations=new Map;resizeSession=null;isResizeHandleHovered=!1;pickerController=new Qs;threadItemContexts=new Map;shortcuts=new Map([[G1.alt("w"),new x51],[G1.ctrl("."),new b51]]);actions=new Map([[x51,new T1(()=>{return this.setState(()=>{this.filterByWorkspace=!this.filterByWorkspace,this.contextMenu=null}),"handled"})],[b51,new T1(()=>this.openContextMenu())]]);get isBusy(){return this.isLoading||this.isSwitchingThread}get isResizeActive(){return this.resizeSession!==null||this.isResizeHandleHovered}didUpdateWidget(A){if(this.contextMenu&&(A.props.width!==this.widget.props.width||A.props.currentWorkspaceURI!==this.widget.props.currentWorkspaceURI))this.contextMenu=null}initState(){super.initState(),this.loadThreadSummaries()}async loadThreadSummaries(){try{let A=await this.widget.props.loadThreads(),Q=j31(A);if(!this.mounted)return;this.setState(()=>{this.pickerController.selectedItem=Q.find(($)=>$.id===this.widget.props.activeThreadID)??null,this.threads=Q,this.timeColWidth=MG0(Q),this.isLoading=!1,this.hasError=!1})}catch(A){if(P.error("Failed to load threads for Neo sidebar",{error:A}),!this.mounted)return;this.setState(()=>{this.isLoading=!1,this.hasError=!0})}}handleSelectThread=async(A)=>{if(this.isSwitchingThread)return;this.setState(()=>{this.isSwitchingThread=!0});try{await this.widget.props.onSelectThread(A),this.widget.props.onDismiss()}catch(Q){P.error("Failed to switch thread from Neo sidebar",{error:Q,threadID:A})}finally{if(this.mounted)this.setState(()=>{this.isSwitchingThread=!1})}};getOptimisticThreads(){return this.threads.flatMap((A)=>{if(this.pendingThreadMutations.get(A.id)?.kind==="archive")return[];return[A]})}getThreadsForDisplay(){let A=this.getOptimisticThreads();return this.filterByWorkspace?A.filter((Q)=>!Q.workspaceURI||Q.workspaceURI===this.widget.props.currentWorkspaceURI):A}buildContextMenuEntries(){return[{type:"item",value:"archive",label:"Archive Thread",shortcut:G1.key("a"),shortcutLabel:"a"},{type:"separator"},{type:"item",value:"copy-id",label:"Copy ID",shortcut:G1.ctrl("c"),shortcutLabel:"ctrl+c"},{type:"item",value:"copy-url",label:"Copy URL",shortcut:new G1("c",{shift:!0,ctrl:!0}),shortcutLabel:"shift+ctrl+c"}]}openContextMenu(){let A=this.pickerController.selectedItem;if(!A||this.isBusy||this.hasError)return"ignored";let Q=this.buildContextMenuEntries(),$=f51(Q),B=this.getContextMenuWidth(),D=this.getContextMenuPosition(A.id,$,B);return this.setState(()=>{this.contextMenu={threadID:A.id,left:D.left,top:D.top,width:B,height:$}}),"handled"}getContextMenuWidth(){let A=Math.max(24,this.widget.props.width-3);return Math.max(1,Math.min(A,this.widget.props.width-2))}getContextMenuPosition(A,Q,$){let B=Math.max(0,Math.min(2,this.widget.props.width-$)),D=1,J=this.threadItemContexts.get(A)?.findRenderObject(),F=this.context.findRenderObject();if(!(J instanceof p1)||!(F instanceof p1))return{left:B,top:1};let Y=J.localToGlobal({x:0,y:0}),E=F.localToGlobal({x:0,y:0}),Z=Y.y-E.y,U=Z+J.size.height,X=c1.sizeOf(this.context).height,G=Math.max(1,Math.min(F.size.height,X-E.y)),I=G-U>=Q||Z<G/2?U:Z-Q,z=Math.max(0,G-Q);return{left:B,top:Math.max(0,Math.min(I,z))}}closeContextMenu=()=>{if(!this.contextMenu)return;this.setState(()=>{this.contextMenu=null})};handleContextMenuAccept=(A)=>{let Q=this.contextMenu?.threadID;if(!Q)return;if(this.closeContextMenu(),A==="archive"){this.archiveContextMenuThread(Q);return}if(A==="copy-id"){x4.maybeInvoke(this.context,new H8(Q,"Thread ID copied to clipboard","Failed to copy thread ID"));return}x4.maybeInvoke(this.context,new H8(this.getThreadURL(Q),"Thread URL copied to clipboard","Failed to copy thread URL"))};beginOptimisticArchive(A){if(this.pendingThreadMutations.has(A))return!1;if(!this.threads.some(($)=>$.id===A))return!1;let Q={kind:"archive",fallbackSelectedThreadID:null};return this.setState(()=>{this.pendingThreadMutations.set(A,Q),this.timeColWidth=MG0(this.getOptimisticThreads())}),i6.instance.addPostFrameCallback(()=>{if(!this.mounted)return;let $=this.pendingThreadMutations.get(A);if($?.kind!=="archive")return;$.fallbackSelectedThreadID=this.pickerController.selectedItem?.id??null}),!0}commitOptimisticArchive(A){if(this.pendingThreadMutations.get(A)?.kind!=="archive")return;this.pendingThreadMutations.delete(A),this.threads=this.threads.filter(($)=>$.id!==A),this.timeColWidth=MG0(this.getOptimisticThreads())}rollbackOptimisticArchive(A){let Q=this.pendingThreadMutations.get(A);if(Q?.kind!=="archive")return;let $=this.threads.find((B)=>B.id===A);if(!$){this.pendingThreadMutations.delete(A);return}this.setState(()=>{this.pendingThreadMutations.delete(A),this.timeColWidth=MG0(this.getOptimisticThreads());let B=this.pickerController.selectedItem?.id??null;if(B===null||B===Q.fallbackSelectedThreadID)this.pickerController.selectedItem=$})}async archiveContextMenuThread(A){let Q=L3.maybeOf(this.context),{configService:$}=V5.of(this.context);if(!this.beginOptimisticArchive(A))return;try{let B=await GU0({configService:$},A);if(!this.mounted)return;if(B){this.rollbackOptimisticArchive(A),Q?.show(B.message,"error");return}this.commitOptimisticArchive(A)}catch(B){if(P.error("Failed to archive thread from Neo sidebar context menu",{error:B,threadID:A}),!this.mounted)return;this.rollbackOptimisticArchive(A),Q?.show("Failed to archive thread","error")}}getThreadURL(A){return y$(new URL(V5.of(this.context).ampURL),A).toString()}buildContextMenuOverlay(){let A=this.contextMenu;if(!A||!this.getThreadsForDisplay().some((Q)=>Q.id===A.threadID))return null;return new o4({left:A.left,top:A.top,width:A.width,height:A.height,child:new k4({debugLabel:"ThreadListSidebarContextMenu",onFocusChange:(Q)=>{if(!Q)this.closeContextMenu()},child:new y51({entries:this.buildContextMenuEntries(),width:A.width,onAccept:this.handleContextMenuAccept,onDismiss:this.closeContextMenu})})})}buildContextMenuBackdrop(){return new o4({left:0,top:0,right:0,bottom:0,child:new O1({onClick:()=>this.closeContextMenu(),child:X0.expand()})})}buildThreadItem(A,Q,$,B){let D=O0.of(B),{app:J,colors:F}=D,Y=!Q,E=Q?J.selectionForeground:F.foreground,Z=Q?J.selectionForeground:F.mutedForeground,X=A.id===this.widget.props.activeThreadID?new d({text:new C("*",new T({color:Q?J.selectionForeground:F.success,dim:Y}))}):void 0,G=$06(A.description.timeAgo);return new A06(new b0({padding:V0.symmetric(1,0),child:new r0({children:[new X0({width:2,child:X}),new R1({child:new d({text:new C(A.title,new T({color:E,dim:Y})),overflow:"ellipsis",maxLines:1})}),new X0({width:2}),new X0({width:$,child:r0.end([new d({text:new C(G,new T({color:Z,dim:Y}))})])})]})}),(V)=>{this.threadItemContexts.set(A.id,V)})}handleResizeHandlePress=(A)=>{if(A.button!=="left")return;this.setState(()=>{this.resizeSession={baseWidthColumns:this.widget.props.width,startColumn:Math.floor(A.position.x)}})};handleResizeHandleDrag=(A)=>{if(A.button!=="left"||this.resizeSession===null)return;let Q=Math.floor(A.position.x)-this.resizeSession.startColumn,$=B06(this.resizeSession.baseWidthColumns+Q);if($!==this.widget.props.width)this.widget.props.onResizeWidth($)};handleResizeHandleRelease=(A)=>{if(A.button!=="left"||this.resizeSession===null)return;this.setState(()=>{this.resizeSession=null})};handleResizeHandleEnter=()=>{if(this.isResizeHandleHovered)return;this.setState(()=>{this.isResizeHandleHovered=!0})};handleResizeHandleExit=()=>{if(!this.isResizeHandleHovered)return;this.setState(()=>{this.isResizeHandleHovered=!1})};buildResizeHandle(){return new o4({top:0,right:0,bottom:0,width:1,child:new O1({cursor:ZA.EW_RESIZE,onClick:this.handleResizeHandlePress,onDrag:this.handleResizeHandleDrag,onRelease:this.handleResizeHandleRelease,onEnter:this.handleResizeHandleEnter,onExit:this.handleResizeHandleExit,child:new X0({width:1})})})}build(A){let Q=O0.of(A),$=this.getThreadsForDisplay(),B=this.hasError?[]:$;this.threadItemContexts.clear();let D=this.isSwitchingThread?"Switching thread...":"Loading threads...",J=this.hasError?"Failed to load threads":"No threads match your filter",F=this.isResizeActive?2:1,Y=new m1(void 0,new d1(Q.colors.border,F),void 0,void 0),E=this.buildContextMenuOverlay(),Z=[new b0({decoration:new R4(Q.colors.background,Y),child:new x4({actions:this.actions,child:new kA({shortcuts:this.shortcuts,debugLabel:"ThreadListSidebarFilter",child:new lA({items:B,getLabel:(U)=>`${U.title} ${U.id}`,controller:this.pickerController,onAccept:(U)=>void this.handleSelectThread(U.id),onDismiss:this.widget.props.onDismiss,renderItem:(U,X,G,V)=>this.buildThreadItem(U,X,this.timeColWidth,V),enabled:!this.isBusy,isLoading:this.isBusy,hidePromptWhenLoading:!0,loadingText:D,emptyStateText:J,maxRenderItems:200,showBorder:!1})})})}),this.buildResizeHandle()];if(E)Z.push(this.buildContextMenuBackdrop()),Z.push(E);return new b0({width:this.widget.props.width,child:new i4({fit:"expand",children:Z})})}}class g51 extends P0{listSkillsForThread;clientPool;completionBuilder;history;ideManager;configService;updateService;initialThreadIDs;showNeoWelcome;neoWelcomeVariant;onNeoWelcomeDismissed;notificationService;mcpTrustHandler;onThreadArchived;onActiveThreadChange;onRelaunchRequested;onFirstFrame;initialUserInput;getDefaultNewThreadVisibility;openThreadPickerOnStart;workspaceSettingsFilePath;neoContext;constructor(A){super();this.listSkillsForThread=A.listSkillsForThread,this.clientPool=A.clientPool,this.completionBuilder=A.completionBuilder,this.history=A.history,this.ideManager=A.ideManager,this.configService=A.configService,this.updateService=A.updateService,this.initialThreadIDs=A.initialThreadIDs??[],this.showNeoWelcome=A.showNeoWelcome??!1,this.neoWelcomeVariant=A.neoWelcomeVariant??"intro",this.onNeoWelcomeDismissed=A.onNeoWelcomeDismissed,this.notificationService=A.notificationService,this.mcpTrustHandler=A.mcpTrustHandler,this.onThreadArchived=A.onThreadArchived,this.onActiveThreadChange=A.onActiveThreadChange,this.onRelaunchRequested=A.onRelaunchRequested,this.onFirstFrame=A.onFirstFrame,this.initialUserInput=A.initialUserInput,this.getDefaultNewThreadVisibility=A.getDefaultNewThreadVisibility,this.openThreadPickerOnStart=A.openThreadPickerOnStart??!1,this.workspaceSettingsFilePath=A.workspaceSettingsFilePath,this.neoContext=A.neoContext}createState(){return new Y06}}class Y06 extends R0{editorController=new T2;commandPalette=new xr(this);commandRegistry=new VA1;toastController=new u11;relaunchNotificationController=new DA1;exitHintTimer=new yr(this,1000);ideStatus=new z8(this,{});threadNavigationHistory=new EA1;draftThreadSettings={};draftThreadSettingsSeed={};hasDraftThreadSettingsSeed=!1;draftThreadSettingsInitPromise=null;activeThreadContext=null;activeThreadIDSubscription=null;activePluginMessageSubscription=null;activePluginUIRequestsSubscription=null;connectionErrorsSubscription=null;configSubscription=null;connectingToThreadID=null;executorAlreadyConnectedDialog=null;switchThreadPickerVisible=!1;neoWelcomeVisible=!1;endCreditsVisible=!1;neoInvadersHighScore=0;debugOverlayVisible=!1;focusDebugVisible=!1;unregisterCommands=null;pluginIntegration=null;mcpTrustIntegration=null;updateRelaunchIntegration=null;noticesPollingTimeout=null;notices;loadThreads=async()=>{return this.widget.neoContext.listThreads()};analyzeContextForThread=async(A,Q)=>{return Md4({ampURL:this.widget.neoContext.ampURL,configService:this.widget.configService,threadID:A,signal:Q})};onSwitchThread=(A)=>{return this.connectToExistingThread(A,{recordNavigation:!0,rethrowError:!0})};threadListSidebar=new h51({state:this,isAvailable:()=>this.widget.neoContext.isInternalUser,isBlocked:()=>this.commandPalette.isEnabled()||this.hasBlockingTopLevelModal(),getActiveThreadID:()=>this.activeThreadContext?.client.getThreadId()??null,getWorkspaceRoot:()=>this.widget.neoContext.workspaceRoot,loadThreads:this.loadThreads,onSelectThread:this.onSwitchThread});sendFeedbackReport=async(A)=>NX0({configService:this.widget.configService,settingsFilePath:this.widget.neoContext.settingsFilePath},A);archiveThread=async(A)=>{let Q=await GU0({configService:this.widget.configService},A);if(Q===null)this.widget.onThreadArchived?.(A);return Q};addThreadLabel=async(A,Q)=>{let $=await Tl4({configService:this.widget.configService},A,Q);if($ instanceof Error)return $;return this.toastController.show($.message,$.type,2000),null};removeThreadLabel=async(A,Q)=>{let $=await vl4({configService:this.widget.configService},A,Q);if($ instanceof Error)return $;return this.toastController.show($.message,$.type,2000),null};initState(){if(YB.getInstance().interceptConsole(),this.neoInvadersHighScore=this.widget.neoContext.neoInvadersHighScore??0,this.notices=new c61(this.widget.configService,($)=>this.setState($)),i6.instance.addPostFrameCallback(()=>{setTimeout(()=>this.widget.onFirstFrame?.(),0),this.noticesPollingTimeout=setTimeout(()=>{this.noticesPollingTimeout=null,this.notices.startPolling()},500)},"Neo notices polling"),this.widget.showNeoWelcome)this.neoWelcomeVisible=!0;if(this.connectionErrorsSubscription=this.widget.clientPool.connectionErrors$.subscribe(({threadID:$,error:B})=>{if(P.error("Neo failed to connect to thread",{threadID:$,error:B}),!$)this.toastController.show(`Connection failed: ${B.message}`,"error",4000)}),this.configSubscription=this.widget.configService.config.subscribe(($)=>{this.applyDraftThreadSettingsSeed(this.applySessionDefaultsToThreadSettings(W20($.settings)))}),this.updateRelaunchIntegration=new FA1({getRelaunchThreadIDs:this.getRelaunchThreadIDs,onRelaunchRequested:this.widget.onRelaunchRequested,relaunchNotificationController:this.relaunchNotificationController,updateService:this.widget.updateService}),this.updateRelaunchIntegration.init(),this.ideStatus.subscribe(this.widget.ideManager.status),this.widget.openThreadPickerOnStart)this.switchThreadPickerVisible=!0;this.ensureDraftThreadSettingsInitialized();let A=this.widget.initialUserInput,Q=this.widget.initialThreadIDs[0];if(Q){let $={};if(A)$.initialUserInput=A;this.connectToInitialThreads(Q,$)}else if(A)this.onNewThread([{type:"text",text:A}],this.widget.neoContext.sessionAgentMode);this.pluginIntegration=new BA1({state:this,commandPalette:this.commandPalette,commandRegistry:this.commandRegistry,toastController:this.toastController,neoContext:this.widget.neoContext,getActiveThreadID:this.getActiveThreadID,appendToThread:this.appendPluginMessagesToThread}),this.pluginIntegration.init(),this.mcpTrustIntegration=new p61({state:this,mcpTrustHandler:this.widget.mcpTrustHandler,toastController:this.toastController,workspaceSettingsFilePath:this.widget.workspaceSettingsFilePath}),this.mcpTrustIntegration.init(),this.unregisterCommands=this.registerAppCommands(),queueMicrotask(()=>{if(!this.mounted)return;this.replayEarlyInputToEditor()})}replayEarlyInputToEditor(){let A=K4.instance.tuiInstance.getEarlyInputText();if(!A)return;this.editorController.insertText(A)}registerAppCommands(){let A=this,Q=this.widget.neoContext.pluginService?ba4({pluginService:this.widget.neoContext.pluginService,workspaceRoot:this.widget.neoContext.workspaceRoot,logFilePath:this.widget.neoContext.logFilePath,toastController:this.toastController}):[],B=[na4({getRelaunchThreadIDs:this.getRelaunchThreadIDs,onRelaunchRequested:this.widget.onRelaunchRequested}),{noun:"thread",verb:"switch",description:"Switch to existing thread",keywords:["recent","history","open","resume","change"],status:{type:"enabled"},sortBoost:100,run:(D,J,F)=>{D.pushWithDismiss((Y)=>R31({activeThreadID:this.activeThreadContext?.client.getThreadId()??null,loadThreads:this.loadThreads,onSelectThread:this.onSwitchThread,onDismiss:Y,onThreadSelected:F}))}},...this.threadListSidebar.commands(),{noun:"thread",verb:"switch to previous",description:"Switch to previous thread",keywords:["back"],get status(){return A.threadNavigationHistory.canNavigateBack()?{type:"enabled"}:{type:"disabled",reason:"Cannot use thread: switch to previous with no previous thread"}},run:(D,J,F)=>{A.navigateBack(),F()}},se4({configService:this.widget.configService,getActiveThreadID:()=>this.activeThreadContext?.client.getThreadId()??void 0,toastController:this.toastController}),{noun:"thread",verb:"switch to next",description:"Switch to next thread",keywords:["forward"],get status(){return A.threadNavigationHistory.canNavigateForward()?{type:"enabled"}:{type:"disabled",reason:"Cannot use thread: switch to next with no next thread"}},run:(D,J,F)=>{A.navigateForward(),F()}},{noun:"mcp",verb:"info",description:"Show MCP servers and tools",keywords:["servers","tools","plugins","integrations"],status:{type:"enabled"},run:(D,J,F)=>{D.push(new rA1({mcpServers:this.widget.neoContext.mcpServers,onDismiss:F}))}},{noun:"toolbox",verb:"list",description:"List all toolboxes and their tools",keywords:["tools","toolbox"],status:{type:"enabled"},run:(D)=>{D.pushWithDismiss((J)=>new j51({toolboxes:this.widget.neoContext.toolboxes,onDismiss:J}))}},{noun:"news",verb:"open",description:"Open Amp Chronicle in browser",keywords:["chronicle","updates","blog","announcements"],status:{type:"enabled"},run:async(D,J,F)=>{try{await n6(J,"https://ampcode.com/chronicle")}finally{F()}}},{noun:"settings",verb:"open in editor",description:"Open CLI settings in $EDITOR",keywords:["config","preferences","edit"],status:{type:"enabled"},run:()=>{F$(this.widget.neoContext.settingsFilePath).catch((D)=>{P.error("Failed to open settings file in editor",{error:D})})}},{noun:"IDE",verb:"connect",description:"Connect to an IDE",keywords:["vscode","cursor","jetbrains","editor","attach"],status:{type:"enabled"},run:(D,J,F)=>{D.pushWithDismiss((Y)=>new aA1({onCancel:Y,onSelect:(E)=>{this.handleIdeSelection(E),F()}}))}},{noun:"amp",verb:"help",description:"Show help & keyboard shortcuts",keywords:["shortcuts","keybindings","docs","manual","?"],status:{type:"enabled"},run:(D,J,F)=>{D.push(new HA1({commands:M9.of(J).commands,onDismiss:F}))}},{noun:"amp",verb:"show welcome",description:"Show the welcome message again",keywords:["intro","onboarding","getting started"],status:{type:"enabled"},run:(D,J,F)=>{F(),A.showNeoWelcome()}},{noun:"amp",verb:"end credits",description:"Roll the full-screen Amp credits",keywords:["team","contributors","movie","credits","easter egg"],status:{type:"enabled"},run:(D,J,F)=>{F(),A.showEndCredits()}},{noun:"amp",verb:"show version",description:"Show current Amp version",keywords:["about","release","build"],status:{type:"enabled"},run:(D,J,F)=>{D.push(new w6({header:"Amp Version",maxWidth:72,onDismiss:F,child:new d({text:new C(hZ0({version:"0.0.1779296280-g014378",buildTimestamp:"2026-05-20T17:03:06.980Z",buildType:"release"}))})}))}},{noun:"amp",verb:"quit",description:"Exit application",keywords:["exit","close","leave","bye"],shortcut:G1.ctrl("c"),status:{type:"enabled"},run:(D,J)=>{x4.maybeInvoke(J,new gy)}},...Q,...Na4(this.widget.neoContext.logFilePath)].map((D)=>this.commandRegistry.register(D));return()=>{for(let D of B)D()}}build(A){let Q=this.buildHints(),$=this.ideStatus.getValue(),B=this.notices.current,D=new O51({initialAgentMode:this.widget.neoContext.sessionAgentMode,analyzeContextForThread:this.analyzeContextForThread,listSkillsForThread:this.widget.listSkillsForThread,threadContext:this.activeThreadContext,draftThreadSettings:this.draftThreadSettings,editorController:this.editorController,history:this.widget.history,updateDraftThreadSettings:this.updateDraftThreadSettings,onNewThread:this.onNewThread,sendFeedbackReport:this.sendFeedbackReport,archiveThread:this.archiveThread,addThreadLabel:this.addThreadLabel,removeThreadLabel:this.removeThreadLabel,configService:this.widget.configService,hints:Q,ideStatus:$,statusItems:this.pluginIntegration?.getStatusItems()??[],notificationService:this.widget.notificationService,notice:this.activeThreadContext||this.neoWelcomeVisible?null:B,onDismissNotice:(U)=>this.notices.dismiss(U)}),J=c1.of(A),F=J.capabilities.animationSupport!=="disabled",E=[new b0({constraints:C1.tight(J.size.width,J.size.height),child:this.threadListSidebar.buildBody(D)})];if(this.commandPalette.isEnabled())E.push(new k4({debugLabel:"CommandPaletteOverlay",onFocusChange:this.closeCommandPaletteOnFocusLoss,child:new KA1({onDismiss:this.commandPalette.disable})}));if(this.switchThreadPickerVisible&&!this.neoWelcomeVisible)E.push(R31({activeThreadID:this.activeThreadContext?.client.getThreadId()??null,loadThreads:this.loadThreads,onSelectThread:this.onSwitchThread,onDismiss:this.closeSwitchThreadPicker,onThreadSelected:this.closeSwitchThreadPicker}));if(this.neoWelcomeVisible)E.push(new k4({debugLabel:"NeoWelcomeDialogOverlay",child:new v51({onDismiss:this.dismissNeoWelcome,onQuit:()=>K4.instance.stop(),animationsEnabled:F,variant:this.widget.neoWelcomeVariant})}));let Z=this.executorAlreadyConnectedDialog;if(Z)E.push(new k4({debugLabel:"NeoExecutorAlreadyConnectedDialogOverlay",child:new iA1({existingExecutorPid:Z.existingExecutorPid,onChoice:this.handleExecutorAlreadyConnectedChoice})}));if(E.push(...this.mcpTrustIntegration?.buildDialogLayers()??[]),E.push(...this.pluginIntegration?.buildDialogLayers()??[]),this.widget.neoContext.isInternalUser)E.push(new NA1({top:this.focusDebugVisible?33:1,visible:this.debugOverlayVisible,pid:LG0.pid,activeThreadID:this.activeThreadContext?.client.getThreadId()??null,connectionInfo$:this.activeThreadContext?.observer.connectionInfo()??null}));if(this.focusDebugVisible)E.push(new nA1);if(this.endCreditsVisible)E.push(new gA1({onComplete:this.completeEndCredits,highScore:this.neoInvadersHighScore,onHighScoreChange:this.updateNeoInvadersHighScore}));return new V5({neoContext:this.widget.neoContext,child:new M9({commandRegistry:this.commandRegistry,child:new py({completionBuilder:this.widget.completionBuilder,child:new L3({controller:this.toastController,child:new x4({actions:this.buildActions(),child:new kA({debugLabel:"NeoAppShortcuts",shortcuts:this.buildShortcuts(),child:new v4({debugLabel:"AppShellFocus",child:new _11({controller:this.toastController,complexToastControllers:[this.relaunchNotificationController,...B&&this.activeThreadContext&&!this.neoWelcomeVisible?[this.notices]:[]],child:new qA1({configReloadEvents:this.widget.configService.configReloadEvents,toastController:this.toastController,child:new i4({children:E})})})})})})})})})})}buildShortcuts(){let A=new Map([[G1.ctrl("c"),new BX0],[G1.ctrl("o"),new JX0],[G1.alt("i"),new YX0],[G1.alt("p"),new fN],[G1.ctrl("."),new UX0],[G1.ctrl("t"),new VX0],...this.threadListSidebar.shortcutEntries()]);if(LG0.env.NODE_ENV==="development"&&LG0.platform==="darwin")A.set(G1.meta("r"),new DX0);return A}buildActions(){let A=new T1(()=>{if(jD.hasAnyCopyableSelection())return jD.tryCopyAnyActiveSelection(),"handled";return this.onExitPressed(),"handled"}),Q=new T1(()=>{if(!this.commandPalette.isEnabled()&&this.hasBlockingTopLevelModal())return"ignored";return this.commandPalette.toggle(),"handled"}),$=new T1(()=>{if(this.commandPalette.isEnabled()||this.hasBlockingTopLevelModal())return"ignored";return this.commandPalette.enable(),"handled"}),B=new T1(()=>{return this.startNewDraftThread(),"handled"}),D=new T1(()=>{return K4.instance.stop(),"handled"}),J=new T1(()=>{return cs({getRelaunchThreadIDs:this.getRelaunchThreadIDs,onRelaunchRequested:this.widget.onRelaunchRequested}),"handled"}),F=new T1((G)=>{if(!G.text)return"ignored";return K4.instance.tuiInstance.clipboard.writeText(G.text).then((V)=>{if(V.ok)this.toastController.show(G.successMessage,"success",2000);else this.toastController.show(`${G.failureMessage}: ${V.userFacingErrorMessage}`,"error",4000)}).catch((V)=>{P.error("Failed to copy Neo text to clipboard",{error:V}),this.toastController.show(G.failureMessage,"error",2000)}),"handled"}),Y=new T1(()=>{return K4.instance.toggleFrameStatsOverlay(),"handled"}),E=new T1(()=>this.notices.dismissCurrent()?"handled":"ignored"),Z=new T1(()=>{if(!this.widget.neoContext.isInternalUser)return"ignored";return this.setState(()=>{this.debugOverlayVisible=!this.debugOverlayVisible}),"handled"}),U=Do4({getActiveThreadID:()=>this.activeThreadContext?.client.getThreadId()??null,neoContext:this.widget.neoContext,toastController:this.toastController,startNewDraftThread:this.startNewDraftThread,sendFeedbackReport:this.sendFeedbackReport}),X=new T1(()=>{return this.setState(()=>{this.focusDebugVisible=!this.focusDebugVisible}),"handled"});return new Map([[BX0,A],[Ss,B],[gy,D],[DX0,J],[H8,F],[bs,$],[JX0,Q],[YX0,Z],...this.threadListSidebar.actionEntries(),[UX0,E],...U,[fN,Y],[VX0,X]])}startNewDraftThread(A={}){let Q=this.activeThreadContext?.client.getThreadId();if(this.commandPalette.disable(),this.threadNavigationHistory.recordNavigation(Q),this.setState(()=>{if(this.activeThreadIDSubscription?.unsubscribe(),this.activeThreadIDSubscription=null,this.activePluginMessageSubscription?.unsubscribe(),this.activePluginMessageSubscription=null,this.activePluginUIRequestsSubscription?.unsubscribe(),this.activePluginUIRequestsSubscription=null,this.pluginIntegration?.cancelOwnerUIRequests(),this.activeThreadContext=null,this.connectingToThreadID=null,A.hideDebugOverlay)this.debugOverlayVisible=!1}),this.widget.onActiveThreadChange?.(null),A.prompt!==void 0)this.editorController.text=A.prompt}closeCommandPaletteOnFocusLoss=(A)=>{if(A||!this.commandPalette.isEnabled())return;this.commandPalette.disable()};ensureDraftThreadSettingsInitialized(){if(this.hasDraftThreadSettingsSeed)return Promise.resolve();if(!this.draftThreadSettingsInitPromise)this.draftThreadSettingsInitPromise=this.initDraftThreadSettings();return this.draftThreadSettingsInitPromise}async initDraftThreadSettings(){try{let A=this.applySessionDefaultsToThreadSettings(await By(this.widget.configService));this.applyDraftThreadSettingsSeed(A)}catch(A){P.warn("Failed to initialize Neo draft thread settings",{error:A instanceof Error?A.message:String(A)})}}applySessionDefaultsToThreadSettings(A){let Q=this.widget.neoContext.sessionAgentMode,$=A,B=EB(Q),D=OZ0(this.widget.neoContext,Q);if(B!==void 0&&D!==void 0)$={...$,[B]:D};return LZ0($,{agentMode:Q,explicitEffort:this.widget.neoContext.explicitReasoningEffort,sessionState:this.widget.neoContext})}applyDraftThreadSettingsSeed(A){if(!this.mounted)return;if(!this.hasDraftThreadSettingsSeed){this.setState(()=>{this.hasDraftThreadSettingsSeed=!0,this.draftThreadSettings=F06(this.draftThreadSettings,{},A),this.draftThreadSettingsSeed={...A}});return}if(iF(this.draftThreadSettingsSeed,A))return;this.setState(()=>{this.draftThreadSettings=F06(this.draftThreadSettings,this.draftThreadSettingsSeed,A),this.draftThreadSettingsSeed={...A}})}buildHints(){let A=new Set;if(this.connectingToThreadID)A.add(eN);if(this.exitHintTimer.isActive())A.add(fy);return A}onExitPressed=()=>{if(this.exitHintTimer.isActive())this.exitHintTimer.clear(),K4.instance.stop();else this.exitHintTimer.activate()};dismissNeoWelcome=()=>{if(!this.neoWelcomeVisible)return;this.setState(()=>{this.neoWelcomeVisible=!1}),this.widget.onNeoWelcomeDismissed?.()};updateNeoInvadersHighScore=(A)=>{if(A<=this.neoInvadersHighScore)return;this.setState(()=>{this.neoInvadersHighScore=A}),zQ((Q)=>({...Q,neoInvadersHighScore:Math.max(Q.neoInvadersHighScore,A)})).catch((Q)=>{P.warn("Failed to save Neo Invaders high score",{error:Q instanceof Error?Q.message:String(Q)})})};showNeoWelcome=()=>{if(this.neoWelcomeVisible)return;this.setState(()=>{this.neoWelcomeVisible=!0})};showEndCredits=()=>{if(this.endCreditsVisible)return;this.setState(()=>{this.endCreditsVisible=!0})};completeEndCredits=()=>{if(!this.endCreditsVisible)return;this.setState(()=>{this.endCreditsVisible=!1})};promptExecutorAlreadyConnected(A){return new Promise((Q)=>{this.setState(()=>{this.executorAlreadyConnectedDialog={existingExecutorPid:A.existingExecutorPid,resolve:($)=>{Q($==="watch"?"observe":"disconnect")}}})})}handleExecutorAlreadyConnectedChoice=(A)=>{if(this.resolveExecutorAlreadyConnectedDialog(A),A==="exit")K4.instance.stop()};resolveExecutorAlreadyConnectedDialog(A){let Q=this.executorAlreadyConnectedDialog;if(!Q)return;this.setState(()=>{this.executorAlreadyConnectedDialog=null}),Q.resolve(A)}closeSwitchThreadPicker=()=>{if(!this.switchThreadPickerVisible)return;this.setState(()=>{this.switchThreadPickerVisible=!1})};updateDraftThreadSettings=(A)=>{this.setState(()=>{this.draftThreadSettings=A(this.draftThreadSettings)})};onNewThread=async(A,Q,$=null,B)=>{await this.ensureDraftThreadSettingsInitialized();let D=this.activeThreadContext?.client.getThreadId(),J=A.find(E20);if(J)this.widget.history.add(J.text,LG0.cwd()),this.widget.history.reset();let F=$?void 0:await this.widget.getDefaultNewThreadVisibility?.(),Y=$??F??null,E=this.widget.clientPool.createNewThread(Q,this.draftThreadSettings,Y??void 0);this.sendUserMessage(E,A,Q,B),this.rememberSessionDefaultsForNewMessage(Q,this.draftThreadSettings),this.threadNavigationHistory.recordNavigation(D),this.setActiveClient(E)};rememberSessionDefaultsForNewMessage(A,Q){this.widget.neoContext.sessionAgentMode=A;let $=Q["reasoning.effort"];if($!==void 0)this.widget.neoContext.lastReasoningEffortByMode={...this.widget.neoContext.lastReasoningEffortByMode??{},[A]:$};let B=EB(A),D=B?Q[B]:void 0;if(D!==void 0)this.widget.neoContext.lastSpeedByMode={...this.widget.neoContext.lastSpeedByMode??{},[A]:D};zQ((J)=>{let F={...J,agentMode:A};if($!==void 0)F={...F,lastReasoningEffortByMode:{...F.lastReasoningEffortByMode??{},[A]:$}};if(D!==void 0)F={...F,lastSpeedByMode:{...F.lastSpeedByMode??{},[A]:D}};return F}).catch((J)=>{P.warn("Failed to persist Neo session defaults for new message",{error:J instanceof Error?J.message:String(J)})})}sendUserMessage(A,Q,$,B){let D=GF0(this.ideStatus.getValue());if(B===void 0){A.client.sendUserMessage(Q,$,{userState:D});return}A.client.sendUserMessage(Q,$,{reasoningEffort:B,userState:D})}getActiveThreadID=()=>{return this.activeThreadContext?.client.getThreadId()??void 0};getRelaunchThreadIDs=()=>{let A=new Set,Q=this.getActiveThreadID();if(Q)A.add(Q);for(let $ of this.widget.clientPool.activeThreadIDs)A.add($);return[...A]};appendPluginMessagesToThread=async(A,Q)=>{let $=this.activeThreadContext;if(!$)throw Error("appendToThread is not available - no active thread");let B=$.client.getThreadId();if(Q&&B!==Q)throw Error("thread.append is only available for the active executor thread");for(let D of A)this.sendUserMessage($,[{type:"text",text:D.content}])};async connectToExistingThread(A,Q={}){let $=this.activeThreadContext?.client.getThreadId();this.setState(()=>{this.connectingToThreadID=A});try{let B=await this.widget.clientPool.connectToThread(A,{observerOnly:this.widget.neoContext.observerOnly,onExecutorAlreadyConnected:(D)=>this.promptExecutorAlreadyConnected(D)});if(this.setActiveClient(B),Q.recordNavigation&&$!==A)this.threadNavigationHistory.recordNavigation($);if(Q.initialUserInput)this.sendUserMessage(B,[{type:"text",text:Q.initialUserInput}])}catch(B){if(P.error("Failed to load thread",{error:B,threadID:A}),this.toastController.show(`Failed to load ${A}: ${B instanceof Error?B.message:String(B)}`,"error",4000),Q.rethrowError)throw B}finally{this.setState(()=>{this.connectingToThreadID=null})}}async connectToInitialThreads(A,Q={}){await this.connectToExistingThread(A,Q);let $=this.widget.initialThreadIDs.filter((B)=>B!==A);await Promise.all($.map((B)=>this.resumeBackgroundThread(B)))}async resumeBackgroundThread(A){try{await this.widget.clientPool.connectToThread(A,{observerOnly:this.widget.neoContext.observerOnly,onExecutorAlreadyConnected:async()=>"observe"})}catch(Q){P.error("Failed to resume background thread",{error:Q,threadID:A}),this.toastController.show(`Failed to resume ${A}: ${Q instanceof Error?Q.message:String(Q)}`,"error",4000)}}async navigateBack(){let A=this.threadNavigationHistory.startBackNavigation(this.activeThreadContext?.client.getThreadId());if(!A)return;await this.navigateToThread(A)}async navigateForward(){let A=this.threadNavigationHistory.startForwardNavigation(this.activeThreadContext?.client.getThreadId());if(!A)return;await this.navigateToThread(A)}async navigateToThread(A){try{await this.connectToExistingThread(A.targetThreadID,{rethrowError:!0})}catch{A.rollback()}}setActiveClient({client:A,observer:Q}){this.setState(()=>{this.activeThreadContext={client:A,observer:Q}}),this.activeThreadIDSubscription?.unsubscribe(),this.activeThreadIDSubscription=Q.threadID().subscribe(($)=>{this.widget.onActiveThreadChange?.($)}),this.activePluginMessageSubscription?.unsubscribe(),this.activePluginUIRequestsSubscription?.unsubscribe(),this.pluginIntegration?.cancelOwnerUIRequests(),this.activePluginMessageSubscription=Q.pluginMessages().subscribe(($)=>{this.pluginIntegration?.handlePluginMessage($,(B)=>{A.sendPluginMessage(B)})}),this.activePluginUIRequestsSubscription=Q.pluginUIRequests().subscribe(($)=>{this.pluginIntegration?.handlePluginMessage({type:"plugin_message",message:{type:"event",event:"plugin.ui.snapshot",data:{requests:[...$]}}},(B)=>{A.sendPluginMessage(B)})})}handleIdeSelection=async(A)=>{try{await this.widget.ideManager.connect(A)}catch(Q){P.error("Failed to connect to IDE",{error:Q});let $=Q instanceof Error?Q.message:String(Q);this.toastController.show(`IDE connection failed: ${$}`,"error",4000)}};dispose(){if(this.unregisterCommands?.(),this.unregisterCommands=null,this.activePluginMessageSubscription?.unsubscribe(),this.activePluginMessageSubscription=null,this.activePluginUIRequestsSubscription?.unsubscribe(),this.activePluginUIRequestsSubscription=null,this.pluginIntegration?.dispose(),this.pluginIntegration=null,this.mcpTrustIntegration?.dispose(),this.mcpTrustIntegration=null,this.updateRelaunchIntegration?.dispose(),this.updateRelaunchIntegration=null,this.activeThreadIDSubscription?.unsubscribe(),this.activeThreadIDSubscription=null,this.noticesPollingTimeout)clearTimeout(this.noticesPollingTimeout),this.noticesPollingTimeout=null;this.connectionErrorsSubscription?.unsubscribe(),this.configSubscription?.unsubscribe(),this.configSubscription=null,this.notices.dispose(),this.widget.notificationService.detach(),this.toastController.dispose(),super.dispose()}hasBlockingTopLevelModal(){return this.switchThreadPickerVisible||this.executorAlreadyConnectedDialog!==null||this.neoWelcomeVisible||(this.mcpTrustIntegration?.hasBlockingDialog()??!1)||this.endCreditsVisible||(this.pluginIntegration?.hasBlockingDialog()??!1)}}function F06(A,Q,$){let B={...A};for(let D of Si3(Q,$)){if(!iF(A[D],Q[D]))continue;let J=$[D];if(J===void 0)delete B[D];else B[D]=J}return B}function Si3(...A){return Array.from(new Set(A.flatMap((Q)=>Object.keys(Q))))}a4();function E06(A,Q,$,B){let D=IT(A),J="\x1B[0m",F="\x1B[34m",Y="\x1B[90m",E="\x1B[2m",Z=[];if(A.archived)Z.push("\x1B[90m\x1B[2mArchived\x1B[0m");Z.push(`${D}`),Z.push(`\x1B[34m${Q}\x1B[0m`),Z.push(`\x1B[90mamp threads continue ${A.id}\x1B[0m`);let U=14,X=7,G=new tJ(U,X),V=new a9(42),K=new _N(U,X,U,X,U,X,0,A.agentMode??"smart","intensity","classic","braille",void 0,void 0,K0.default(),V);K.layout(C1.tight(U,X)),K.paint(G,0,0);let I=G.getBuffer().getCells(),z=0;for(let j=0;j<X;j++)if(I[j].some((k)=>k.char!==" ")){z=j;break}let W=X-1;for(let j=X-1;j>=0;j--)if(I[j].some((k)=>k.char!==" ")){W=j;break}function H(j,k){if(!j)return"";if(j.type==="rgb"){let{r:_,g:f,b:h}=j.value;if($.getColorDepth()>=24)return`\x1B[${k?38:48};2;${_};${f};${h}m`;let b=gj(_,f,h);return`\x1B[${k?38:48};5;${b}m`}return""}let q=[];if(W>=z)for(let j=z;j<=W;j++){let k="";for(let _=0;_<U;_++){let f=I[j][_],h=f.char,b=H(f.style.fg,!0);k+=b+h+"\x1B[0m"}q.push(k)}let N=q.length,w=Math.max(N,Z.length),O=Math.floor((w-N)/2),L=Math.floor((w-Z.length)/2);for(let j=0;j<w;j++){let k=" ".repeat(U);if(j>=O&&j<O+N)k=q[j-O];let _=" ",f="";if(j>=L&&j<L+Z.length)f=Z[j-L];$.write(k+_+f+`
5323
+ `)),J.push(new C("Details: ",new T({color:B.mutedForeground}))),J.push(new C(A.costBreakdownURL,new T({color:$.app.link})));return new d({text:new C("",void 0,J)})}function ui3(A,Q,$){let B=Pi3(A,Q);if(!A.costBreakdownURL)return new w6({header:"Thread Cost",minWidth:80,maxWidth:100,onDismiss:$,child:B});let D=A.costBreakdownURL,J=new T1(()=>{return x4.maybeInvoke(Q,new H8(D,"Cost breakdown URL copied to clipboard","Failed to copy cost breakdown URL")),"handled"}),F=new T1(()=>{return n6(Q,D),"handled"});return new w6({header:"Thread Cost",minWidth:80,maxWidth:100,autofocus:!1,footer:[{keys:["Esc"],label:"close"},{keys:["o"],label:"open in browser"},{keys:["y"],label:"copy url"}],onDismiss:$,child:new x4({actions:new Map([[k51,J],[S51,F]]),child:new kA({debugLabel:"ThreadCostShortcuts",shortcuts:new Map([[G1.key("o"),new S51],[G1.key("y"),new k51]]),child:new v4({autofocus:!0,debugLabel:"ThreadCostBody",child:B})})})})}function se4(A){return{noun:"thread",verb:"show cost",description:"Show usage cost for the active thread",keywords:["usage","credits","billing","spend"],get status(){return A.getActiveThreadID()?{type:"enabled"}:{type:"disabled",reason:"No active thread"}},run:async(Q,$,B)=>{let D=A.getActiveThreadID();if(!D)return;try{let J=await t4.threadDisplayCostInfo({threadID:D},{config:A.configService});if(!J.ok){A.toastController.show(Ri3(D,J.error),"error",5000),B();return}Q.push(ui3(J.result,$,B))}catch(J){P.error("Failed to load Neo thread cost",{error:J,threadID:D}),A.toastController.show(`Failed to show thread cost: ${J instanceof Error?J.message:String(J)}`,"error",5000),B()}}}}p0();u9();Q4();class XI extends V4{direction;constructor(A){super();this.direction=A}}class wG0 extends V4{}class zt extends V4{}class CG0 extends V4{index;constructor(A){super();this.index=A}}function f51(A){return A.length+2}class y51 extends P0{props;constructor(A){super();this.props=A}createState(){return new te4}}class te4 extends R0{selectedIndex=0;initState(){super.initState(),this.selectedIndex=this.findSelectableIndex(this.widget.props.initialSelectedIndex??0)}didUpdateWidget(A){this.selectedIndex=this.findSelectableIndex(this.selectedIndex)}isSelectable(A){let Q=this.widget.props.entries[A];return Q?.type==="item"&&(Q.enabled??!0)}findSelectableIndex(A){let{entries:Q}=this.widget.props;if(Q.length===0)return 0;let $=Math.max(0,Math.min(A,Q.length-1));if(this.isSelectable($))return $;for(let B=1;B<Q.length;B++){let D=$+B;if(D<Q.length&&this.isSelectable(D))return D;let J=$-B;if(J>=0&&this.isSelectable(J))return J}return 0}moveSelection(A){let Q=this.findNextSelectableIndex(A);if(Q===this.selectedIndex)return;this.setState(()=>{this.selectedIndex=Q})}findNextSelectableIndex(A){let{entries:Q}=this.widget.props;for(let $=this.selectedIndex+A;$>=0&&$<Q.length;$+=A)if(this.isSelectable($))return $;return this.selectedIndex}acceptIndex(A){let Q=this.widget.props.entries[A];if(Q?.type!=="item"||!(Q.enabled??!0))return;this.setState(()=>{this.selectedIndex=A}),this.widget.props.onAccept(Q.value)}invoke=(A)=>{if(A instanceof XI)return this.moveSelection(A.direction),"handled";if(A instanceof wG0)return this.acceptIndex(this.selectedIndex),"handled";if(A instanceof zt)return this.widget.props.onDismiss(),"handled";if(A instanceof CG0)return this.acceptIndex(A.index),"handled";return"ignored"};buildShortcuts(){let A=new Map([[G1.key("ArrowDown"),new XI(1)],[G1.key("j"),new XI(1)],[G1.ctrl("n"),new XI(1)],[G1.key("ArrowUp"),new XI(-1)],[G1.key("k"),new XI(-1)],[G1.ctrl("p"),new XI(-1)],[G1.key("Enter"),new wG0],[G1.key("Escape"),new zt],[G1.ctrl("."),new zt]]);return this.widget.props.entries.forEach((Q,$)=>{if(Q.type==="item"&&Q.shortcut)A.set(Q.shortcut,new CG0($))}),A}buildActions(){return new Map([[XI,new T1(this.invoke)],[wG0,new T1(this.invoke)],[zt,new T1(this.invoke)],[CG0,new T1(this.invoke)]])}build(A){let Q=O0.of(A),$=_i3(this.widget.props.entries,c1.of(A).supportsEmojiWidth);return new b0({width:this.widget.props.width,height:f51(this.widget.props.entries),decoration:new R4(Q.colors.background,m1.all(new d1(Q.colors.border,1,"solid"))),child:new x4({actions:this.buildActions(),child:new kA({debugLabel:"NeoContextPickerShortcuts",shortcuts:this.buildShortcuts(),child:new v4({autofocus:!0,debugLabel:"NeoContextPicker",child:new S0({mainAxisSize:"min",crossAxisAlignment:"stretch",children:this.widget.props.entries.map((B,D)=>this.buildEntry(B,D,$,Q))})})})})})}buildEntry(A,Q,$,B){if(A.type==="separator")return new b0({height:1,decoration:{border:new m1(new d1(B.colors.border,1,"solid"))}});let D=Q===this.selectedIndex,J=A.enabled??!0,F=new T({color:D?B.app.selectionForeground:B.colors.foreground,dim:!J}),Y=new T({color:D?B.app.selectionForeground:B.app.keybind,bold:!0,dim:!J});return new O1({onClick:()=>this.acceptIndex(Q),child:new b0({padding:V0.symmetric(1,0),decoration:D?new R4(B.app.selectionBackground):void 0,child:new r0({crossAxisAlignment:"start",children:[new R1({child:new d({text:new C(A.label,F),maxLines:1,overflow:"ellipsis"})}),new X0({width:1}),new X0({width:$,child:new d({text:new C(ee4(A),Y),textAlign:"right",maxLines:1,overflow:"ellipsis"})})]})})})}}function _i3(A,Q){return A.reduce(($,B)=>{return B.type==="item"?Math.max($,J4(ee4(B),Q)):$},0)}function ee4(A){return A.shortcutLabel??A.shortcut?.toString().toLowerCase()??""}var Ti3=36,vi3=24,ki3=72;class A06 extends P0{child;onContext;constructor(A,Q){super();this.child=A;this.onContext=Q}createState(){return new Q06}}class Q06 extends R0{build(A){return this.widget.onContext(A),this.widget.child}}function $06(A){return A.replace(/ ago$/,"")}function MG0(A){return A.reduce((Q,$)=>Math.max(Q,J4($06($.description.timeAgo))),0)}function B06(A){return Math.max(vi3,Math.min(A,ki3))}class x51 extends V4{}class b51 extends V4{}class h51{options;visibility;width=Ti3;constructor(A){this.options=A;this.visibility=new xr(A.state)}isVisible(){return this.visibility.isEnabled()}buildBody(A){return new r0({crossAxisAlignment:"stretch",children:[this.buildSlot(),new R1({child:A})]})}buildSlot(){if(!this.options.isAvailable()||this.visibility.isDisabled())return new X0({width:0});return new X0({width:this.width,child:new k4({debugLabel:"ThreadListSidebar",child:new D06({activeThreadID:this.options.getActiveThreadID(),currentWorkspaceURI:t1(i0.file(this.options.getWorkspaceRoot())),width:this.width,loadThreads:this.options.loadThreads,onSelectThread:this.options.onSelectThread,onDismiss:this.close,onResizeWidth:this.resize})})})}commands(){if(!this.options.isAvailable())return[];return[{noun:"thread",verb:"toggle sidebar",description:"Show or hide the thread sidebar",keywords:["sidebar","recent","history","threads"],shortcut:G1.alt("s"),status:{type:"enabled"},run:(A,Q,$)=>{$(),this.toggle()}}]}shortcutEntries(){return this.options.isAvailable()?[[G1.alt("s"),new EX0]]:[]}actionEntries(){if(!this.options.isAvailable())return[];return[[EX0,new T1(()=>this.toggle())]]}toggle=()=>{if(!this.options.isAvailable())return"ignored";if(this.visibility.isDisabled()&&this.options.isBlocked())return"ignored";return this.visibility.toggle(),"handled"};close=()=>{this.visibility.disable()};resize=(A)=>{let Q=B06(A);if(Q===this.width)return;this.options.state.setState(()=>{this.width=Q})}}class D06 extends P0{props;constructor(A){super();this.props=A}createState(){return new J06}}class J06 extends R0{threads=[];isLoading=!0;isSwitchingThread=!1;hasError=!1;filterByWorkspace=!0;timeColWidth=0;contextMenu=null;pendingThreadMutations=new Map;resizeSession=null;isResizeHandleHovered=!1;pickerController=new Qs;threadItemContexts=new Map;shortcuts=new Map([[G1.alt("w"),new x51],[G1.ctrl("."),new b51]]);actions=new Map([[x51,new T1(()=>{return this.setState(()=>{this.filterByWorkspace=!this.filterByWorkspace,this.contextMenu=null}),"handled"})],[b51,new T1(()=>this.openContextMenu())]]);get isBusy(){return this.isLoading||this.isSwitchingThread}get isResizeActive(){return this.resizeSession!==null||this.isResizeHandleHovered}didUpdateWidget(A){if(this.contextMenu&&(A.props.width!==this.widget.props.width||A.props.currentWorkspaceURI!==this.widget.props.currentWorkspaceURI))this.contextMenu=null}initState(){super.initState(),this.loadThreadSummaries()}async loadThreadSummaries(){try{let A=await this.widget.props.loadThreads(),Q=j31(A);if(!this.mounted)return;this.setState(()=>{this.pickerController.selectedItem=Q.find(($)=>$.id===this.widget.props.activeThreadID)??null,this.threads=Q,this.timeColWidth=MG0(Q),this.isLoading=!1,this.hasError=!1})}catch(A){if(P.error("Failed to load threads for Neo sidebar",{error:A}),!this.mounted)return;this.setState(()=>{this.isLoading=!1,this.hasError=!0})}}handleSelectThread=async(A)=>{if(this.isSwitchingThread)return;this.setState(()=>{this.isSwitchingThread=!0});try{await this.widget.props.onSelectThread(A),this.widget.props.onDismiss()}catch(Q){P.error("Failed to switch thread from Neo sidebar",{error:Q,threadID:A})}finally{if(this.mounted)this.setState(()=>{this.isSwitchingThread=!1})}};getOptimisticThreads(){return this.threads.flatMap((A)=>{if(this.pendingThreadMutations.get(A.id)?.kind==="archive")return[];return[A]})}getThreadsForDisplay(){let A=this.getOptimisticThreads();return this.filterByWorkspace?A.filter((Q)=>!Q.workspaceURI||Q.workspaceURI===this.widget.props.currentWorkspaceURI):A}buildContextMenuEntries(){return[{type:"item",value:"archive",label:"Archive Thread",shortcut:G1.key("a"),shortcutLabel:"a"},{type:"separator"},{type:"item",value:"copy-id",label:"Copy ID",shortcut:G1.ctrl("c"),shortcutLabel:"ctrl+c"},{type:"item",value:"copy-url",label:"Copy URL",shortcut:new G1("c",{shift:!0,ctrl:!0}),shortcutLabel:"shift+ctrl+c"}]}openContextMenu(){let A=this.pickerController.selectedItem;if(!A||this.isBusy||this.hasError)return"ignored";let Q=this.buildContextMenuEntries(),$=f51(Q),B=this.getContextMenuWidth(),D=this.getContextMenuPosition(A.id,$,B);return this.setState(()=>{this.contextMenu={threadID:A.id,left:D.left,top:D.top,width:B,height:$}}),"handled"}getContextMenuWidth(){let A=Math.max(24,this.widget.props.width-3);return Math.max(1,Math.min(A,this.widget.props.width-2))}getContextMenuPosition(A,Q,$){let B=Math.max(0,Math.min(2,this.widget.props.width-$)),D=1,J=this.threadItemContexts.get(A)?.findRenderObject(),F=this.context.findRenderObject();if(!(J instanceof p1)||!(F instanceof p1))return{left:B,top:1};let Y=J.localToGlobal({x:0,y:0}),E=F.localToGlobal({x:0,y:0}),Z=Y.y-E.y,U=Z+J.size.height,X=c1.sizeOf(this.context).height,G=Math.max(1,Math.min(F.size.height,X-E.y)),I=G-U>=Q||Z<G/2?U:Z-Q,z=Math.max(0,G-Q);return{left:B,top:Math.max(0,Math.min(I,z))}}closeContextMenu=()=>{if(!this.contextMenu)return;this.setState(()=>{this.contextMenu=null})};handleContextMenuAccept=(A)=>{let Q=this.contextMenu?.threadID;if(!Q)return;if(this.closeContextMenu(),A==="archive"){this.archiveContextMenuThread(Q);return}if(A==="copy-id"){x4.maybeInvoke(this.context,new H8(Q,"Thread ID copied to clipboard","Failed to copy thread ID"));return}x4.maybeInvoke(this.context,new H8(this.getThreadURL(Q),"Thread URL copied to clipboard","Failed to copy thread URL"))};beginOptimisticArchive(A){if(this.pendingThreadMutations.has(A))return!1;if(!this.threads.some(($)=>$.id===A))return!1;let Q={kind:"archive",fallbackSelectedThreadID:null};return this.setState(()=>{this.pendingThreadMutations.set(A,Q),this.timeColWidth=MG0(this.getOptimisticThreads())}),i6.instance.addPostFrameCallback(()=>{if(!this.mounted)return;let $=this.pendingThreadMutations.get(A);if($?.kind!=="archive")return;$.fallbackSelectedThreadID=this.pickerController.selectedItem?.id??null}),!0}commitOptimisticArchive(A){if(this.pendingThreadMutations.get(A)?.kind!=="archive")return;this.pendingThreadMutations.delete(A),this.threads=this.threads.filter(($)=>$.id!==A),this.timeColWidth=MG0(this.getOptimisticThreads())}rollbackOptimisticArchive(A){let Q=this.pendingThreadMutations.get(A);if(Q?.kind!=="archive")return;let $=this.threads.find((B)=>B.id===A);if(!$){this.pendingThreadMutations.delete(A);return}this.setState(()=>{this.pendingThreadMutations.delete(A),this.timeColWidth=MG0(this.getOptimisticThreads());let B=this.pickerController.selectedItem?.id??null;if(B===null||B===Q.fallbackSelectedThreadID)this.pickerController.selectedItem=$})}async archiveContextMenuThread(A){let Q=L3.maybeOf(this.context),{configService:$}=V5.of(this.context);if(!this.beginOptimisticArchive(A))return;try{let B=await GU0({configService:$},A);if(!this.mounted)return;if(B){this.rollbackOptimisticArchive(A),Q?.show(B.message,"error");return}this.commitOptimisticArchive(A)}catch(B){if(P.error("Failed to archive thread from Neo sidebar context menu",{error:B,threadID:A}),!this.mounted)return;this.rollbackOptimisticArchive(A),Q?.show("Failed to archive thread","error")}}getThreadURL(A){return y$(new URL(V5.of(this.context).ampURL),A).toString()}buildContextMenuOverlay(){let A=this.contextMenu;if(!A||!this.getThreadsForDisplay().some((Q)=>Q.id===A.threadID))return null;return new o4({left:A.left,top:A.top,width:A.width,height:A.height,child:new k4({debugLabel:"ThreadListSidebarContextMenu",onFocusChange:(Q)=>{if(!Q)this.closeContextMenu()},child:new y51({entries:this.buildContextMenuEntries(),width:A.width,onAccept:this.handleContextMenuAccept,onDismiss:this.closeContextMenu})})})}buildContextMenuBackdrop(){return new o4({left:0,top:0,right:0,bottom:0,child:new O1({onClick:()=>this.closeContextMenu(),child:X0.expand()})})}buildThreadItem(A,Q,$,B){let D=O0.of(B),{app:J,colors:F}=D,Y=!Q,E=Q?J.selectionForeground:F.foreground,Z=Q?J.selectionForeground:F.mutedForeground,X=A.id===this.widget.props.activeThreadID?new d({text:new C("*",new T({color:Q?J.selectionForeground:F.success,dim:Y}))}):void 0,G=$06(A.description.timeAgo);return new A06(new b0({padding:V0.symmetric(1,0),child:new r0({children:[new X0({width:2,child:X}),new R1({child:new d({text:new C(A.title,new T({color:E,dim:Y})),overflow:"ellipsis",maxLines:1})}),new X0({width:2}),new X0({width:$,child:r0.end([new d({text:new C(G,new T({color:Z,dim:Y}))})])})]})}),(V)=>{this.threadItemContexts.set(A.id,V)})}handleResizeHandlePress=(A)=>{if(A.button!=="left")return;this.setState(()=>{this.resizeSession={baseWidthColumns:this.widget.props.width,startColumn:Math.floor(A.position.x)}})};handleResizeHandleDrag=(A)=>{if(A.button!=="left"||this.resizeSession===null)return;let Q=Math.floor(A.position.x)-this.resizeSession.startColumn,$=B06(this.resizeSession.baseWidthColumns+Q);if($!==this.widget.props.width)this.widget.props.onResizeWidth($)};handleResizeHandleRelease=(A)=>{if(A.button!=="left"||this.resizeSession===null)return;this.setState(()=>{this.resizeSession=null})};handleResizeHandleEnter=()=>{if(this.isResizeHandleHovered)return;this.setState(()=>{this.isResizeHandleHovered=!0})};handleResizeHandleExit=()=>{if(!this.isResizeHandleHovered)return;this.setState(()=>{this.isResizeHandleHovered=!1})};buildResizeHandle(){return new o4({top:0,right:0,bottom:0,width:1,child:new O1({cursor:ZA.EW_RESIZE,onClick:this.handleResizeHandlePress,onDrag:this.handleResizeHandleDrag,onRelease:this.handleResizeHandleRelease,onEnter:this.handleResizeHandleEnter,onExit:this.handleResizeHandleExit,child:new X0({width:1})})})}build(A){let Q=O0.of(A),$=this.getThreadsForDisplay(),B=this.hasError?[]:$;this.threadItemContexts.clear();let D=this.isSwitchingThread?"Switching thread...":"Loading threads...",J=this.hasError?"Failed to load threads":"No threads match your filter",F=this.isResizeActive?2:1,Y=new m1(void 0,new d1(Q.colors.border,F),void 0,void 0),E=this.buildContextMenuOverlay(),Z=[new b0({decoration:new R4(Q.colors.background,Y),child:new x4({actions:this.actions,child:new kA({shortcuts:this.shortcuts,debugLabel:"ThreadListSidebarFilter",child:new lA({items:B,getLabel:(U)=>`${U.title} ${U.id}`,controller:this.pickerController,onAccept:(U)=>void this.handleSelectThread(U.id),onDismiss:this.widget.props.onDismiss,renderItem:(U,X,G,V)=>this.buildThreadItem(U,X,this.timeColWidth,V),enabled:!this.isBusy,isLoading:this.isBusy,hidePromptWhenLoading:!0,loadingText:D,emptyStateText:J,maxRenderItems:200,showBorder:!1})})})}),this.buildResizeHandle()];if(E)Z.push(this.buildContextMenuBackdrop()),Z.push(E);return new b0({width:this.widget.props.width,child:new i4({fit:"expand",children:Z})})}}class g51 extends P0{listSkillsForThread;clientPool;completionBuilder;history;ideManager;configService;updateService;initialThreadIDs;showNeoWelcome;neoWelcomeVariant;onNeoWelcomeDismissed;notificationService;mcpTrustHandler;onThreadArchived;onActiveThreadChange;onRelaunchRequested;onFirstFrame;initialUserInput;getDefaultNewThreadVisibility;openThreadPickerOnStart;workspaceSettingsFilePath;neoContext;constructor(A){super();this.listSkillsForThread=A.listSkillsForThread,this.clientPool=A.clientPool,this.completionBuilder=A.completionBuilder,this.history=A.history,this.ideManager=A.ideManager,this.configService=A.configService,this.updateService=A.updateService,this.initialThreadIDs=A.initialThreadIDs??[],this.showNeoWelcome=A.showNeoWelcome??!1,this.neoWelcomeVariant=A.neoWelcomeVariant??"intro",this.onNeoWelcomeDismissed=A.onNeoWelcomeDismissed,this.notificationService=A.notificationService,this.mcpTrustHandler=A.mcpTrustHandler,this.onThreadArchived=A.onThreadArchived,this.onActiveThreadChange=A.onActiveThreadChange,this.onRelaunchRequested=A.onRelaunchRequested,this.onFirstFrame=A.onFirstFrame,this.initialUserInput=A.initialUserInput,this.getDefaultNewThreadVisibility=A.getDefaultNewThreadVisibility,this.openThreadPickerOnStart=A.openThreadPickerOnStart??!1,this.workspaceSettingsFilePath=A.workspaceSettingsFilePath,this.neoContext=A.neoContext}createState(){return new Y06}}class Y06 extends R0{editorController=new T2;commandPalette=new xr(this);commandRegistry=new VA1;toastController=new u11;relaunchNotificationController=new DA1;exitHintTimer=new yr(this,1000);ideStatus=new z8(this,{});threadNavigationHistory=new EA1;draftThreadSettings={};draftThreadSettingsSeed={};hasDraftThreadSettingsSeed=!1;draftThreadSettingsInitPromise=null;activeThreadContext=null;activeThreadIDSubscription=null;activePluginMessageSubscription=null;activePluginUIRequestsSubscription=null;connectionErrorsSubscription=null;configSubscription=null;connectingToThreadID=null;executorAlreadyConnectedDialog=null;switchThreadPickerVisible=!1;neoWelcomeVisible=!1;endCreditsVisible=!1;neoInvadersHighScore=0;debugOverlayVisible=!1;focusDebugVisible=!1;unregisterCommands=null;pluginIntegration=null;mcpTrustIntegration=null;updateRelaunchIntegration=null;noticesPollingTimeout=null;notices;loadThreads=async()=>{return this.widget.neoContext.listThreads()};analyzeContextForThread=async(A,Q)=>{return Md4({ampURL:this.widget.neoContext.ampURL,configService:this.widget.configService,threadID:A,signal:Q})};onSwitchThread=(A)=>{return this.connectToExistingThread(A,{recordNavigation:!0,rethrowError:!0})};threadListSidebar=new h51({state:this,isAvailable:()=>this.widget.neoContext.isInternalUser,isBlocked:()=>this.commandPalette.isEnabled()||this.hasBlockingTopLevelModal(),getActiveThreadID:()=>this.activeThreadContext?.client.getThreadId()??null,getWorkspaceRoot:()=>this.widget.neoContext.workspaceRoot,loadThreads:this.loadThreads,onSelectThread:this.onSwitchThread});sendFeedbackReport=async(A)=>NX0({configService:this.widget.configService,settingsFilePath:this.widget.neoContext.settingsFilePath},A);archiveThread=async(A)=>{let Q=await GU0({configService:this.widget.configService},A);if(Q===null)this.widget.onThreadArchived?.(A);return Q};addThreadLabel=async(A,Q)=>{let $=await Tl4({configService:this.widget.configService},A,Q);if($ instanceof Error)return $;return this.toastController.show($.message,$.type,2000),null};removeThreadLabel=async(A,Q)=>{let $=await vl4({configService:this.widget.configService},A,Q);if($ instanceof Error)return $;return this.toastController.show($.message,$.type,2000),null};initState(){if(YB.getInstance().interceptConsole(),this.neoInvadersHighScore=this.widget.neoContext.neoInvadersHighScore??0,this.notices=new c61(this.widget.configService,($)=>this.setState($)),i6.instance.addPostFrameCallback(()=>{setTimeout(()=>this.widget.onFirstFrame?.(),0),this.noticesPollingTimeout=setTimeout(()=>{this.noticesPollingTimeout=null,this.notices.startPolling()},500)},"Neo notices polling"),this.widget.showNeoWelcome)this.neoWelcomeVisible=!0;if(this.connectionErrorsSubscription=this.widget.clientPool.connectionErrors$.subscribe(({threadID:$,error:B})=>{if(P.error("Neo failed to connect to thread",{threadID:$,error:B}),!$)this.toastController.show(`Connection failed: ${B.message}`,"error",4000)}),this.configSubscription=this.widget.configService.config.subscribe(($)=>{this.applyDraftThreadSettingsSeed(this.applySessionDefaultsToThreadSettings(W20($.settings)))}),this.updateRelaunchIntegration=new FA1({getRelaunchThreadIDs:this.getRelaunchThreadIDs,onRelaunchRequested:this.widget.onRelaunchRequested,relaunchNotificationController:this.relaunchNotificationController,updateService:this.widget.updateService}),this.updateRelaunchIntegration.init(),this.ideStatus.subscribe(this.widget.ideManager.status),this.widget.openThreadPickerOnStart)this.switchThreadPickerVisible=!0;this.ensureDraftThreadSettingsInitialized();let A=this.widget.initialUserInput,Q=this.widget.initialThreadIDs[0];if(Q){let $={};if(A)$.initialUserInput=A;this.connectToInitialThreads(Q,$)}else if(A)this.onNewThread([{type:"text",text:A}],this.widget.neoContext.sessionAgentMode);this.pluginIntegration=new BA1({state:this,commandPalette:this.commandPalette,commandRegistry:this.commandRegistry,toastController:this.toastController,neoContext:this.widget.neoContext,getActiveThreadID:this.getActiveThreadID,appendToThread:this.appendPluginMessagesToThread}),this.pluginIntegration.init(),this.mcpTrustIntegration=new p61({state:this,mcpTrustHandler:this.widget.mcpTrustHandler,toastController:this.toastController,workspaceSettingsFilePath:this.widget.workspaceSettingsFilePath}),this.mcpTrustIntegration.init(),this.unregisterCommands=this.registerAppCommands(),queueMicrotask(()=>{if(!this.mounted)return;this.replayEarlyInputToEditor()})}replayEarlyInputToEditor(){let A=K4.instance.tuiInstance.getEarlyInputText();if(!A)return;this.editorController.insertText(A)}registerAppCommands(){let A=this,Q=this.widget.neoContext.pluginService?ba4({pluginService:this.widget.neoContext.pluginService,workspaceRoot:this.widget.neoContext.workspaceRoot,logFilePath:this.widget.neoContext.logFilePath,toastController:this.toastController}):[],B=[na4({getRelaunchThreadIDs:this.getRelaunchThreadIDs,onRelaunchRequested:this.widget.onRelaunchRequested}),{noun:"thread",verb:"switch",description:"Switch to existing thread",keywords:["recent","history","open","resume","change"],status:{type:"enabled"},sortBoost:100,run:(D,J,F)=>{D.pushWithDismiss((Y)=>R31({activeThreadID:this.activeThreadContext?.client.getThreadId()??null,loadThreads:this.loadThreads,onSelectThread:this.onSwitchThread,onDismiss:Y,onThreadSelected:F}))}},...this.threadListSidebar.commands(),{noun:"thread",verb:"switch to previous",description:"Switch to previous thread",keywords:["back"],get status(){return A.threadNavigationHistory.canNavigateBack()?{type:"enabled"}:{type:"disabled",reason:"Cannot use thread: switch to previous with no previous thread"}},run:(D,J,F)=>{A.navigateBack(),F()}},se4({configService:this.widget.configService,getActiveThreadID:()=>this.activeThreadContext?.client.getThreadId()??void 0,toastController:this.toastController}),{noun:"thread",verb:"switch to next",description:"Switch to next thread",keywords:["forward"],get status(){return A.threadNavigationHistory.canNavigateForward()?{type:"enabled"}:{type:"disabled",reason:"Cannot use thread: switch to next with no next thread"}},run:(D,J,F)=>{A.navigateForward(),F()}},{noun:"mcp",verb:"info",description:"Show MCP servers and tools",keywords:["servers","tools","plugins","integrations"],status:{type:"enabled"},run:(D,J,F)=>{D.push(new rA1({mcpServers:this.widget.neoContext.mcpServers,onDismiss:F}))}},{noun:"toolbox",verb:"list",description:"List all toolboxes and their tools",keywords:["tools","toolbox"],status:{type:"enabled"},run:(D)=>{D.pushWithDismiss((J)=>new j51({toolboxes:this.widget.neoContext.toolboxes,onDismiss:J}))}},{noun:"news",verb:"open",description:"Open Amp Chronicle in browser",keywords:["chronicle","updates","blog","announcements"],status:{type:"enabled"},run:async(D,J,F)=>{try{await n6(J,"https://ampcode.com/chronicle")}finally{F()}}},{noun:"settings",verb:"open in editor",description:"Open CLI settings in $EDITOR",keywords:["config","preferences","edit"],status:{type:"enabled"},run:()=>{F$(this.widget.neoContext.settingsFilePath).catch((D)=>{P.error("Failed to open settings file in editor",{error:D})})}},{noun:"IDE",verb:"connect",description:"Connect to an IDE",keywords:["vscode","cursor","jetbrains","editor","attach"],status:{type:"enabled"},run:(D,J,F)=>{D.pushWithDismiss((Y)=>new aA1({onCancel:Y,onSelect:(E)=>{this.handleIdeSelection(E),F()}}))}},{noun:"amp",verb:"help",description:"Show help & keyboard shortcuts",keywords:["shortcuts","keybindings","docs","manual","?"],status:{type:"enabled"},run:(D,J,F)=>{D.push(new HA1({commands:M9.of(J).commands,onDismiss:F}))}},{noun:"amp",verb:"show welcome",description:"Show the welcome message again",keywords:["intro","onboarding","getting started"],status:{type:"enabled"},run:(D,J,F)=>{F(),A.showNeoWelcome()}},{noun:"amp",verb:"end credits",description:"Roll the full-screen Amp credits",keywords:["team","contributors","movie","credits","easter egg"],status:{type:"enabled"},run:(D,J,F)=>{F(),A.showEndCredits()}},{noun:"amp",verb:"show version",description:"Show current Amp version",keywords:["about","release","build"],status:{type:"enabled"},run:(D,J,F)=>{D.push(new w6({header:"Amp Version",maxWidth:72,onDismiss:F,child:new d({text:new C(hZ0({version:"0.0.1779313683-gf89f27",buildTimestamp:"2026-05-20T21:52:35.567Z",buildType:"release"}))})}))}},{noun:"amp",verb:"quit",description:"Exit application",keywords:["exit","close","leave","bye"],shortcut:G1.ctrl("c"),status:{type:"enabled"},run:(D,J)=>{x4.maybeInvoke(J,new gy)}},...Q,...Na4(this.widget.neoContext.logFilePath)].map((D)=>this.commandRegistry.register(D));return()=>{for(let D of B)D()}}build(A){let Q=this.buildHints(),$=this.ideStatus.getValue(),B=this.notices.current,D=new O51({initialAgentMode:this.widget.neoContext.sessionAgentMode,analyzeContextForThread:this.analyzeContextForThread,listSkillsForThread:this.widget.listSkillsForThread,threadContext:this.activeThreadContext,draftThreadSettings:this.draftThreadSettings,editorController:this.editorController,history:this.widget.history,updateDraftThreadSettings:this.updateDraftThreadSettings,onNewThread:this.onNewThread,sendFeedbackReport:this.sendFeedbackReport,archiveThread:this.archiveThread,addThreadLabel:this.addThreadLabel,removeThreadLabel:this.removeThreadLabel,configService:this.widget.configService,hints:Q,ideStatus:$,statusItems:this.pluginIntegration?.getStatusItems()??[],notificationService:this.widget.notificationService,notice:this.activeThreadContext||this.neoWelcomeVisible?null:B,onDismissNotice:(U)=>this.notices.dismiss(U)}),J=c1.of(A),F=J.capabilities.animationSupport!=="disabled",E=[new b0({constraints:C1.tight(J.size.width,J.size.height),child:this.threadListSidebar.buildBody(D)})];if(this.commandPalette.isEnabled())E.push(new k4({debugLabel:"CommandPaletteOverlay",onFocusChange:this.closeCommandPaletteOnFocusLoss,child:new KA1({onDismiss:this.commandPalette.disable})}));if(this.switchThreadPickerVisible&&!this.neoWelcomeVisible)E.push(R31({activeThreadID:this.activeThreadContext?.client.getThreadId()??null,loadThreads:this.loadThreads,onSelectThread:this.onSwitchThread,onDismiss:this.closeSwitchThreadPicker,onThreadSelected:this.closeSwitchThreadPicker}));if(this.neoWelcomeVisible)E.push(new k4({debugLabel:"NeoWelcomeDialogOverlay",child:new v51({onDismiss:this.dismissNeoWelcome,onQuit:()=>K4.instance.stop(),animationsEnabled:F,variant:this.widget.neoWelcomeVariant})}));let Z=this.executorAlreadyConnectedDialog;if(Z)E.push(new k4({debugLabel:"NeoExecutorAlreadyConnectedDialogOverlay",child:new iA1({existingExecutorPid:Z.existingExecutorPid,onChoice:this.handleExecutorAlreadyConnectedChoice})}));if(E.push(...this.mcpTrustIntegration?.buildDialogLayers()??[]),E.push(...this.pluginIntegration?.buildDialogLayers()??[]),this.widget.neoContext.isInternalUser)E.push(new NA1({top:this.focusDebugVisible?33:1,visible:this.debugOverlayVisible,pid:LG0.pid,activeThreadID:this.activeThreadContext?.client.getThreadId()??null,connectionInfo$:this.activeThreadContext?.observer.connectionInfo()??null}));if(this.focusDebugVisible)E.push(new nA1);if(this.endCreditsVisible)E.push(new gA1({onComplete:this.completeEndCredits,highScore:this.neoInvadersHighScore,onHighScoreChange:this.updateNeoInvadersHighScore}));return new V5({neoContext:this.widget.neoContext,child:new M9({commandRegistry:this.commandRegistry,child:new py({completionBuilder:this.widget.completionBuilder,child:new L3({controller:this.toastController,child:new x4({actions:this.buildActions(),child:new kA({debugLabel:"NeoAppShortcuts",shortcuts:this.buildShortcuts(),child:new v4({debugLabel:"AppShellFocus",child:new _11({controller:this.toastController,complexToastControllers:[this.relaunchNotificationController,...B&&this.activeThreadContext&&!this.neoWelcomeVisible?[this.notices]:[]],child:new qA1({configReloadEvents:this.widget.configService.configReloadEvents,toastController:this.toastController,child:new i4({children:E})})})})})})})})})})}buildShortcuts(){let A=new Map([[G1.ctrl("c"),new BX0],[G1.ctrl("o"),new JX0],[G1.alt("i"),new YX0],[G1.alt("p"),new fN],[G1.ctrl("."),new UX0],[G1.ctrl("t"),new VX0],...this.threadListSidebar.shortcutEntries()]);if(LG0.env.NODE_ENV==="development"&&LG0.platform==="darwin")A.set(G1.meta("r"),new DX0);return A}buildActions(){let A=new T1(()=>{if(jD.hasAnyCopyableSelection())return jD.tryCopyAnyActiveSelection(),"handled";return this.onExitPressed(),"handled"}),Q=new T1(()=>{if(!this.commandPalette.isEnabled()&&this.hasBlockingTopLevelModal())return"ignored";return this.commandPalette.toggle(),"handled"}),$=new T1(()=>{if(this.commandPalette.isEnabled()||this.hasBlockingTopLevelModal())return"ignored";return this.commandPalette.enable(),"handled"}),B=new T1(()=>{return this.startNewDraftThread(),"handled"}),D=new T1(()=>{return K4.instance.stop(),"handled"}),J=new T1(()=>{return cs({getRelaunchThreadIDs:this.getRelaunchThreadIDs,onRelaunchRequested:this.widget.onRelaunchRequested}),"handled"}),F=new T1((G)=>{if(!G.text)return"ignored";return K4.instance.tuiInstance.clipboard.writeText(G.text).then((V)=>{if(V.ok)this.toastController.show(G.successMessage,"success",2000);else this.toastController.show(`${G.failureMessage}: ${V.userFacingErrorMessage}`,"error",4000)}).catch((V)=>{P.error("Failed to copy Neo text to clipboard",{error:V}),this.toastController.show(G.failureMessage,"error",2000)}),"handled"}),Y=new T1(()=>{return K4.instance.toggleFrameStatsOverlay(),"handled"}),E=new T1(()=>this.notices.dismissCurrent()?"handled":"ignored"),Z=new T1(()=>{if(!this.widget.neoContext.isInternalUser)return"ignored";return this.setState(()=>{this.debugOverlayVisible=!this.debugOverlayVisible}),"handled"}),U=Do4({getActiveThreadID:()=>this.activeThreadContext?.client.getThreadId()??null,neoContext:this.widget.neoContext,toastController:this.toastController,startNewDraftThread:this.startNewDraftThread,sendFeedbackReport:this.sendFeedbackReport}),X=new T1(()=>{return this.setState(()=>{this.focusDebugVisible=!this.focusDebugVisible}),"handled"});return new Map([[BX0,A],[Ss,B],[gy,D],[DX0,J],[H8,F],[bs,$],[JX0,Q],[YX0,Z],...this.threadListSidebar.actionEntries(),[UX0,E],...U,[fN,Y],[VX0,X]])}startNewDraftThread(A={}){let Q=this.activeThreadContext?.client.getThreadId();if(this.commandPalette.disable(),this.threadNavigationHistory.recordNavigation(Q),this.setState(()=>{if(this.activeThreadIDSubscription?.unsubscribe(),this.activeThreadIDSubscription=null,this.activePluginMessageSubscription?.unsubscribe(),this.activePluginMessageSubscription=null,this.activePluginUIRequestsSubscription?.unsubscribe(),this.activePluginUIRequestsSubscription=null,this.pluginIntegration?.cancelOwnerUIRequests(),this.activeThreadContext=null,this.connectingToThreadID=null,A.hideDebugOverlay)this.debugOverlayVisible=!1}),this.widget.onActiveThreadChange?.(null),A.prompt!==void 0)this.editorController.text=A.prompt}closeCommandPaletteOnFocusLoss=(A)=>{if(A||!this.commandPalette.isEnabled())return;this.commandPalette.disable()};ensureDraftThreadSettingsInitialized(){if(this.hasDraftThreadSettingsSeed)return Promise.resolve();if(!this.draftThreadSettingsInitPromise)this.draftThreadSettingsInitPromise=this.initDraftThreadSettings();return this.draftThreadSettingsInitPromise}async initDraftThreadSettings(){try{let A=this.applySessionDefaultsToThreadSettings(await By(this.widget.configService));this.applyDraftThreadSettingsSeed(A)}catch(A){P.warn("Failed to initialize Neo draft thread settings",{error:A instanceof Error?A.message:String(A)})}}applySessionDefaultsToThreadSettings(A){let Q=this.widget.neoContext.sessionAgentMode,$=A,B=EB(Q),D=OZ0(this.widget.neoContext,Q);if(B!==void 0&&D!==void 0)$={...$,[B]:D};return LZ0($,{agentMode:Q,explicitEffort:this.widget.neoContext.explicitReasoningEffort,sessionState:this.widget.neoContext})}applyDraftThreadSettingsSeed(A){if(!this.mounted)return;if(!this.hasDraftThreadSettingsSeed){this.setState(()=>{this.hasDraftThreadSettingsSeed=!0,this.draftThreadSettings=F06(this.draftThreadSettings,{},A),this.draftThreadSettingsSeed={...A}});return}if(iF(this.draftThreadSettingsSeed,A))return;this.setState(()=>{this.draftThreadSettings=F06(this.draftThreadSettings,this.draftThreadSettingsSeed,A),this.draftThreadSettingsSeed={...A}})}buildHints(){let A=new Set;if(this.connectingToThreadID)A.add(eN);if(this.exitHintTimer.isActive())A.add(fy);return A}onExitPressed=()=>{if(this.exitHintTimer.isActive())this.exitHintTimer.clear(),K4.instance.stop();else this.exitHintTimer.activate()};dismissNeoWelcome=()=>{if(!this.neoWelcomeVisible)return;this.setState(()=>{this.neoWelcomeVisible=!1}),this.widget.onNeoWelcomeDismissed?.()};updateNeoInvadersHighScore=(A)=>{if(A<=this.neoInvadersHighScore)return;this.setState(()=>{this.neoInvadersHighScore=A}),zQ((Q)=>({...Q,neoInvadersHighScore:Math.max(Q.neoInvadersHighScore,A)})).catch((Q)=>{P.warn("Failed to save Neo Invaders high score",{error:Q instanceof Error?Q.message:String(Q)})})};showNeoWelcome=()=>{if(this.neoWelcomeVisible)return;this.setState(()=>{this.neoWelcomeVisible=!0})};showEndCredits=()=>{if(this.endCreditsVisible)return;this.setState(()=>{this.endCreditsVisible=!0})};completeEndCredits=()=>{if(!this.endCreditsVisible)return;this.setState(()=>{this.endCreditsVisible=!1})};promptExecutorAlreadyConnected(A){return new Promise((Q)=>{this.setState(()=>{this.executorAlreadyConnectedDialog={existingExecutorPid:A.existingExecutorPid,resolve:($)=>{Q($==="watch"?"observe":"disconnect")}}})})}handleExecutorAlreadyConnectedChoice=(A)=>{if(this.resolveExecutorAlreadyConnectedDialog(A),A==="exit")K4.instance.stop()};resolveExecutorAlreadyConnectedDialog(A){let Q=this.executorAlreadyConnectedDialog;if(!Q)return;this.setState(()=>{this.executorAlreadyConnectedDialog=null}),Q.resolve(A)}closeSwitchThreadPicker=()=>{if(!this.switchThreadPickerVisible)return;this.setState(()=>{this.switchThreadPickerVisible=!1})};updateDraftThreadSettings=(A)=>{this.setState(()=>{this.draftThreadSettings=A(this.draftThreadSettings)})};onNewThread=async(A,Q,$=null,B)=>{await this.ensureDraftThreadSettingsInitialized();let D=this.activeThreadContext?.client.getThreadId(),J=A.find(E20);if(J)this.widget.history.add(J.text,LG0.cwd()),this.widget.history.reset();let F=$?void 0:await this.widget.getDefaultNewThreadVisibility?.(),Y=$??F??null,E=this.widget.clientPool.createNewThread(Q,this.draftThreadSettings,Y??void 0);this.sendUserMessage(E,A,Q,B),this.rememberSessionDefaultsForNewMessage(Q,this.draftThreadSettings),this.threadNavigationHistory.recordNavigation(D),this.setActiveClient(E)};rememberSessionDefaultsForNewMessage(A,Q){this.widget.neoContext.sessionAgentMode=A;let $=Q["reasoning.effort"];if($!==void 0)this.widget.neoContext.lastReasoningEffortByMode={...this.widget.neoContext.lastReasoningEffortByMode??{},[A]:$};let B=EB(A),D=B?Q[B]:void 0;if(D!==void 0)this.widget.neoContext.lastSpeedByMode={...this.widget.neoContext.lastSpeedByMode??{},[A]:D};zQ((J)=>{let F={...J,agentMode:A};if($!==void 0)F={...F,lastReasoningEffortByMode:{...F.lastReasoningEffortByMode??{},[A]:$}};if(D!==void 0)F={...F,lastSpeedByMode:{...F.lastSpeedByMode??{},[A]:D}};return F}).catch((J)=>{P.warn("Failed to persist Neo session defaults for new message",{error:J instanceof Error?J.message:String(J)})})}sendUserMessage(A,Q,$,B){let D=GF0(this.ideStatus.getValue());if(B===void 0){A.client.sendUserMessage(Q,$,{userState:D});return}A.client.sendUserMessage(Q,$,{reasoningEffort:B,userState:D})}getActiveThreadID=()=>{return this.activeThreadContext?.client.getThreadId()??void 0};getRelaunchThreadIDs=()=>{let A=new Set,Q=this.getActiveThreadID();if(Q)A.add(Q);for(let $ of this.widget.clientPool.activeThreadIDs)A.add($);return[...A]};appendPluginMessagesToThread=async(A,Q)=>{let $=this.activeThreadContext;if(!$)throw Error("appendToThread is not available - no active thread");let B=$.client.getThreadId();if(Q&&B!==Q)throw Error("thread.append is only available for the active executor thread");for(let D of A)this.sendUserMessage($,[{type:"text",text:D.content}])};async connectToExistingThread(A,Q={}){let $=this.activeThreadContext?.client.getThreadId();this.setState(()=>{this.connectingToThreadID=A});try{let B=await this.widget.clientPool.connectToThread(A,{observerOnly:this.widget.neoContext.observerOnly,onExecutorAlreadyConnected:(D)=>this.promptExecutorAlreadyConnected(D)});if(this.setActiveClient(B),Q.recordNavigation&&$!==A)this.threadNavigationHistory.recordNavigation($);if(Q.initialUserInput)this.sendUserMessage(B,[{type:"text",text:Q.initialUserInput}])}catch(B){if(P.error("Failed to load thread",{error:B,threadID:A}),this.toastController.show(`Failed to load ${A}: ${B instanceof Error?B.message:String(B)}`,"error",4000),Q.rethrowError)throw B}finally{this.setState(()=>{this.connectingToThreadID=null})}}async connectToInitialThreads(A,Q={}){await this.connectToExistingThread(A,Q);let $=this.widget.initialThreadIDs.filter((B)=>B!==A);await Promise.all($.map((B)=>this.resumeBackgroundThread(B)))}async resumeBackgroundThread(A){try{await this.widget.clientPool.connectToThread(A,{observerOnly:this.widget.neoContext.observerOnly,onExecutorAlreadyConnected:async()=>"observe"})}catch(Q){P.error("Failed to resume background thread",{error:Q,threadID:A}),this.toastController.show(`Failed to resume ${A}: ${Q instanceof Error?Q.message:String(Q)}`,"error",4000)}}async navigateBack(){let A=this.threadNavigationHistory.startBackNavigation(this.activeThreadContext?.client.getThreadId());if(!A)return;await this.navigateToThread(A)}async navigateForward(){let A=this.threadNavigationHistory.startForwardNavigation(this.activeThreadContext?.client.getThreadId());if(!A)return;await this.navigateToThread(A)}async navigateToThread(A){try{await this.connectToExistingThread(A.targetThreadID,{rethrowError:!0})}catch{A.rollback()}}setActiveClient({client:A,observer:Q}){this.setState(()=>{this.activeThreadContext={client:A,observer:Q}}),this.activeThreadIDSubscription?.unsubscribe(),this.activeThreadIDSubscription=Q.threadID().subscribe(($)=>{this.widget.onActiveThreadChange?.($)}),this.activePluginMessageSubscription?.unsubscribe(),this.activePluginUIRequestsSubscription?.unsubscribe(),this.pluginIntegration?.cancelOwnerUIRequests(),this.activePluginMessageSubscription=Q.pluginMessages().subscribe(($)=>{this.pluginIntegration?.handlePluginMessage($,(B)=>{A.sendPluginMessage(B)})}),this.activePluginUIRequestsSubscription=Q.pluginUIRequests().subscribe(($)=>{this.pluginIntegration?.handlePluginMessage({type:"plugin_message",message:{type:"event",event:"plugin.ui.snapshot",data:{requests:[...$]}}},(B)=>{A.sendPluginMessage(B)})})}handleIdeSelection=async(A)=>{try{await this.widget.ideManager.connect(A)}catch(Q){P.error("Failed to connect to IDE",{error:Q});let $=Q instanceof Error?Q.message:String(Q);this.toastController.show(`IDE connection failed: ${$}`,"error",4000)}};dispose(){if(this.unregisterCommands?.(),this.unregisterCommands=null,this.activePluginMessageSubscription?.unsubscribe(),this.activePluginMessageSubscription=null,this.activePluginUIRequestsSubscription?.unsubscribe(),this.activePluginUIRequestsSubscription=null,this.pluginIntegration?.dispose(),this.pluginIntegration=null,this.mcpTrustIntegration?.dispose(),this.mcpTrustIntegration=null,this.updateRelaunchIntegration?.dispose(),this.updateRelaunchIntegration=null,this.activeThreadIDSubscription?.unsubscribe(),this.activeThreadIDSubscription=null,this.noticesPollingTimeout)clearTimeout(this.noticesPollingTimeout),this.noticesPollingTimeout=null;this.connectionErrorsSubscription?.unsubscribe(),this.configSubscription?.unsubscribe(),this.configSubscription=null,this.notices.dispose(),this.widget.notificationService.detach(),this.toastController.dispose(),super.dispose()}hasBlockingTopLevelModal(){return this.switchThreadPickerVisible||this.executorAlreadyConnectedDialog!==null||this.neoWelcomeVisible||(this.mcpTrustIntegration?.hasBlockingDialog()??!1)||this.endCreditsVisible||(this.pluginIntegration?.hasBlockingDialog()??!1)}}function F06(A,Q,$){let B={...A};for(let D of Si3(Q,$)){if(!iF(A[D],Q[D]))continue;let J=$[D];if(J===void 0)delete B[D];else B[D]=J}return B}function Si3(...A){return Array.from(new Set(A.flatMap((Q)=>Object.keys(Q))))}a4();function E06(A,Q,$,B){let D=IT(A),J="\x1B[0m",F="\x1B[34m",Y="\x1B[90m",E="\x1B[2m",Z=[];if(A.archived)Z.push("\x1B[90m\x1B[2mArchived\x1B[0m");Z.push(`${D}`),Z.push(`\x1B[34m${Q}\x1B[0m`),Z.push(`\x1B[90mamp threads continue ${A.id}\x1B[0m`);let U=14,X=7,G=new tJ(U,X),V=new a9(42),K=new _N(U,X,U,X,U,X,0,A.agentMode??"smart","intensity","classic","braille",void 0,void 0,K0.default(),V);K.layout(C1.tight(U,X)),K.paint(G,0,0);let I=G.getBuffer().getCells(),z=0;for(let j=0;j<X;j++)if(I[j].some((k)=>k.char!==" ")){z=j;break}let W=X-1;for(let j=X-1;j>=0;j--)if(I[j].some((k)=>k.char!==" ")){W=j;break}function H(j,k){if(!j)return"";if(j.type==="rgb"){let{r:_,g:f,b:h}=j.value;if($.getColorDepth()>=24)return`\x1B[${k?38:48};2;${_};${f};${h}m`;let b=gj(_,f,h);return`\x1B[${k?38:48};5;${b}m`}return""}let q=[];if(W>=z)for(let j=z;j<=W;j++){let k="";for(let _=0;_<U;_++){let f=I[j][_],h=f.char,b=H(f.style.fg,!0);k+=b+h+"\x1B[0m"}q.push(k)}let N=q.length,w=Math.max(N,Z.length),O=Math.floor((w-N)/2),L=Math.floor((w-Z.length)/2);for(let j=0;j<w;j++){let k=" ".repeat(U);if(j>=O&&j<O+N)k=q[j-O];let _=" ",f="";if(j>=L&&j<L+Z.length)f=Z[j-L];$.write(k+_+f+`
5324
5324
  `)}if(B)$.write(`
5325
5325
  \x1B[90m${B}\x1B[0m
5326
5326
  `)}p0();p0();import{exec as vR}from"node:child_process";function OG0(A="idle"){try{if(A==="idle"){if(process.platform==="darwin")vR("afplay /System/Library/Sounds/Submarine.aiff");else if(process.platform==="win32")vR("powershell [console]::beep(800,200)");else if(process.platform==="linux")vR("paplay /usr/share/sounds/freedesktop/stereo/message.oga || beep")}else if(A==="idle-review"){if(process.platform==="darwin")vR("afplay /System/Library/Sounds/Glass.aiff")}else if(A==="requires-user-input"){if(process.platform==="darwin")vR("afplay /System/Library/Sounds/Ping.aiff");else if(process.platform==="win32")vR("powershell [console]::beep(1000,300)");else if(process.platform==="linux")vR("paplay /usr/share/sounds/freedesktop/stereo/dialog-information.oga || beep -f 1000 -l 100")}}catch(Q){P.error(`Failed to play notification sound (${A}):`,Q)}}fZ0();var fi3=2000,yi3="Agent is ready",xi3="Waiting for approval";function Z06(A){let Q=!0,$=!0,B=A.configService.config.subscribe((W)=>{Q=W.settings["notifications.enabled"]??!0,$=W.settings["notifications.system.enabled"]!==!1}),D=0,J=()=>{let W=V?.prepareTerminalTitleForNotification();if(W!==void 0)process.stdout.write(AZ0(W))},F=(W)=>{if(!Q)return;let H=Date.now();if(H-D<fi3)return;if(D=H,aj())return;if(kE0())J(),setTimeout(SE0,Ur);else OG0(W)},Y=()=>{F("idle"),K(yi3)},E=()=>{F("requires-user-input"),K(xi3)},Z=(W)=>W?.attempt===void 0||W.attempt===0,U=null,X=null,G=null,V,K=(W)=>{if(!Q||!$)return;if(aj()&&!ur()&&!af())return;J(),setTimeout(()=>{process.stdout.write(Xr(W))},Ur)},I=()=>{U?.unsubscribe(),X?.unsubscribe(),U=null,X=null,G=null,V=void 0};return{attach:(W,H,q)=>{if(I(),V=q,H)X=H.subscribe({next:(N)=>{if(N===null)return;if(!Z(N))return;Y()},error:(N)=>{P.debug("Neo notification active error stream errored",{error:N})}});U=W.subscribe({next:(N)=>{try{let w=G!==null&&tQ(G),O=G==="awaiting_approval",L=w||O;if(N==="awaiting_approval"&&!O)E();else if(N==="idle"&&L)Y()}catch(w){P.debug("Neo notification handling failed",{error:w})}finally{G=N}},error:(N)=>{P.debug("Neo notification agent state stream errored",{error:N})}})},detach:I,unsubscribe(){I(),B.unsubscribe()}}}function bi3({initialUserInput:A,showNeoWelcome:Q,hideNeoWelcome:$,neoWelcomeVariant:B,neoWelcomeDismissed:D}){if($)return{show:!1,markDismissedOnDismiss:!1};if(B==="npm-migration")return{show:!0,markDismissedOnDismiss:!1};if(Q)return{show:!0,markDismissedOnDismiss:!0};let J=!A&&!D;return{show:J,markDismissedOnDismiss:J}}async function hi3(A){await zQ((Q)=>Fy(Q,A,"interactive"))}async function U06(A,Q={}){let{initialThreadIDs:$=[],initialUserInput:B,getDefaultNewThreadVisibility:D,openThreadPickerOnStart:J=!1,observerOnly:F=!1,initialAgentMode:Y,initialReasoningEffort:E,onFirstFrame:Z,showNeoWelcome:U=!1,hideNeoWelcome:X=!1,neoWelcomeVariant:G="intro"}=Q,V=G==="npm-migration";if($.length>1)P.info("Resuming multiple initial threads",{threadIDs:$});let K=async(_)=>{let f=await A.getThreadFromServer(_);if(!f)return null;return wE0(f)},I=async(_)=>{let f=await A.getThreadFromServer(_);if(!f)throw Error(`Thread ${_} not found`);let h=await l9(_,A.configService,A.apiKey,{usesThreadActors:!0}),b=TG({endpoint:A.rivetEndpoint,poolName:h.poolName}),v={wsToken:h.wsToken,transport:"amp-rpc"},p=await b.threadActor.getOrCreate([_],{params:v,createWithInput:{threadId:h.threadId,threadVersion:h.threadVersion,ownerUserId:h.ownerUserId,...h.agentMode?{agentMode:h.agentMode}:{}}}).fetch("/import",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({thread:my4(f)}),skipReadyWait:!0});if(!p.ok&&p.status!==409)throw Error(`Thread import failed (${p.status}): ${await p.text()}`);try{await Ix4(_,A.configService,A.apiKey,{executorType:"local-client"})}catch(c){P.warn("failed to mark thread as imported on server",{threadID:_,error:c instanceof Error?c.message:String(c)})}},z=new $11(A.rivetEndpoint,A.apiKey,A.configService,{clientID:ZN.parse(`neo-${crypto.randomUUID()}`),toolService:A.toolService,skillService:A.skillService,requestPluginToolCall:(_)=>A.pluginService.event.toolCall(_),requestPluginToolResult:(_)=>A.pluginService.event.toolResult(_),pluginService:A.pluginService,pluginPlatform:A.pluginPlatform,invokeTool:async(_,f)=>{let h=typeof f.args==="object"&&f.args!==null?f.args:{},b=await wN({toolName:f.toolName,configService:A.configService,toolService:A.toolService,mcpService:A.mcpService,skillService:A.skillService,toolUseID:f.toolCallId,threadId:_});return A.toolService.invokeTool(f.toolName,{args:h},b)},persistLastThreadID:hi3,readFileSystemDirectory:A.readFileSystemDirectory},K,I),W=await rz(),H=bi3({initialUserInput:B,showNeoWelcome:U,hideNeoWelcome:X,neoWelcomeVariant:G,neoWelcomeDismissed:W.neoWelcomeDismissed}),q={ampURL:A.ampURL,configService:A.configService,getThreadMarkdown:async(_)=>{let f=await A.getThreadFromServer(_);return f?bX(f):null},isInternalUser:A.isInternalUser,listThreads:A.listThreads,logFilePath:Ao,mcpServers:A.mcpService.servers,pluginPlatform:A.pluginPlatform,pluginService:A.pluginService,toolboxes:A.toolboxes,observerOnly:V?!1:F,neoInvadersHighScore:W.neoInvadersHighScore,sessionAgentMode:Y??W.agentMode,explicitReasoningEffort:E,lastReasoningEffortByMode:W.lastReasoningEffortByMode,lastSpeedByMode:W.lastSpeedByMode,settingsFilePath:A.settingsFilePath,splashOrbVisualStyle:Q.splashOrbVisualStyle??"neo",workspaceRoot:A.workspaceRoot},N=(_,f)=>{return _m4({ampURL:A.ampURL,configService:A.configService,threadID:_,signal:f})},w=new M11,O=Z06({configService:A.configService}),L=await A.configService.getLatest();K4.instance.tuiInstance.setOptions({queryOptions:{animationDisabled:L.settings["terminal.animation"]===!1}});let j=new Set,k=new JA1;try{await _r(new g51({clientPool:z,listSkillsForThread:N,completionBuilder:A.completionBuilder,history:new mo,ideManager:w,configService:A.configService,updateService:A.updateService,initialThreadIDs:V?[]:$,notificationService:O,mcpTrustHandler:A.mcpTrustHandler,initialUserInput:V?void 0:B,getDefaultNewThreadVisibility:D,openThreadPickerOnStart:V?!1:J,workspaceSettingsFilePath:A.workspaceSettingsFilePath,neoContext:q,showNeoWelcome:H.show,neoWelcomeVariant:G,onActiveThreadChange:A.setActiveThreadID,onRelaunchRequested:k.request,onNeoWelcomeDismissed:H.markDismissedOnDismiss?()=>{zQ(km4).catch((f)=>{P.warn("Failed to mark Neo welcome as dismissed",{error:f})})}:void 0,onThreadArchived:(f)=>{j.add(f)},onFirstFrame:Z}));let _=z.lastActiveObservingClient;if(_&&k.shouldShowExitSummary){let{client:f,observer:h}=_,b=f.getThreadId();if(b){let v={id:b,title:h.title().getValue(),agentMode:h.agentMode,archived:j.has(b)},y=`${A.ampURL.replace(/\/$/,"")}/threads/${b}`;E06(v,y,process.stdout)}}}finally{process.stdout.write(jN("")),O.unsubscribe(),z.dispose(),await A.dispose?.()}process.exit(k.relaunchIfRequested(A.workspaceRoot)??0)}Z5();function Zx(A){let Q=[],$={meta:{visibility:"private",sharedGroupIDs:[]}};if(A.workspace?.disablePrivateThreads)$.disabledReason="Disabled by workspace policy";if(Q.push($),A.workspace?.groups&&A.workspace.groups.length>0){let F={meta:{visibility:"private",shareWithAllCreatorGroups:!0}};if(A.creatorIsViewer===!1)F.disabledReason="Can only be set by thread creator";Q.push(F)}if(A.workspace)Q.push({meta:{visibility:"thread_workspace_shared"}});let B=A.workspace?.disablePublicSharing?"Disabled by workspace policy":void 0,D={meta:{visibility:"public_unlisted"}},J={meta:{visibility:"public_discoverable"}};if(B)D.disabledReason=B,J.disabledReason=B;return Q.push(D,J),Q}function X06(A){if(A.visibility!=="private")return!0;if("shareWithAllCreatorGroups"in A&&A.shareWithAllCreatorGroups)return!0;return"sharedGroupIDs"in A&&A.sharedGroupIDs.length>0}function kR(A,Q={}){switch(A.visibility){case"thread_workspace_shared":return{text:"Workspace",description:"Visible to all members of the workspace"};case"public_discoverable":return{text:"Public",description:"Visible on public profile & publicly searchable"};case"public_unlisted":return{text:"Unlisted",description:"Visible to anyone on the Internet who has the link"};case"private":{let $="shareWithAllCreatorGroups"in A&&A.shareWithAllCreatorGroups,D=($?Q.workspace?.groups.map((J)=>J.id)??[]:("sharedGroupIDs"in A)?A.sharedGroupIDs:[]).reduce((J,F)=>{let Y=Q.workspace?.groups.find((E)=>E.id===F)?.name;if(Y)J.push(`'${Y}'`);return J},[]);if(D.length>0)return{text:"Group",description:`Shared with ${X4(D.length,"group")} ${D.join(", ")} and workspace admins`};if($)return{text:"Group",description:"Shared with creator groups and workspace admins"};return{text:"Private",description:Q.workspace?"Only visible to you and workspace admins":"Only you can see this thread"}}}}function jG0(A){if(A.visibility==="private")return"shareWithAllCreatorGroups"in A?"group":"private";if(A.visibility==="thread_workspace_shared")return"workspace";if(A.visibility==="public_unlisted")return"unlisted";return"public"}function Ux(A,Q=null){let $=A!==null&&typeof A==="object"&&"visibility"in A?A.visibility:void 0;if(!$||typeof $!=="string")return;let D=Zx({workspace:Q?.team??void 0}).filter((J)=>!J.disabledReason).map((J)=>jG0(J.meta));if(D.includes($))return gi3($);if($==="group"&&!D.includes("group")){if(Q?.team?.groups!==void 0)return Error(`Group visibility is not available. You are not a member of any group in this workspace.
@@ -7082,7 +7082,7 @@ ${D}`,Q);this.line=$,this.column=B,this.codeblock=D}}/*!
7082
7082
  `),J=[];for(let F=0;F<D.length;F++){let Z=D[F].replace(/\b(SELECT|FROM|WHERE|GROUP BY|ORDER BY|HAVING|LIMIT|JOIN|LEFT JOIN|RIGHT JOIN|INNER JOIN|ON|AND|OR|AS|IN|NOT|NULL|IS|BETWEEN|LIKE|EXISTS|UNION|DISTINCT|COUNT|SUM|AVG|MIN|MAX|DATE|TIMESTAMP_TRUNC|TIMESTAMP_SUB|CURRENT_TIMESTAMP|INTERVAL|CASE|WHEN|THEN|ELSE|END|WITH|INSERT|UPDATE|DELETE|SET|VALUES|INTO|CREATE|ALTER|DROP|TRUE|FALSE|ASC|DESC)\b/gi,"\x00$1\x01").split(/(\x00[^\x01]+\x01)/);for(let U of Z)if(U.startsWith("\x00")&&U.endsWith("\x01"))J.push(new C(U.slice(1,-1),new T({color:B.app.keybind,bold:!0})));else J.push(new C(U,new T({color:$.colorScheme.foreground})));if(F<D.length-1)J.push(new C(`
7083
7083
  `))}return new b0({decoration:{color:$.colorScheme.background,border:m1.all(new d1(B.app.keybind,1,"rounded"))},child:new f0({padding:V0.symmetric(0,1),child:new d({text:new C(void 0,void 0,J)})})})}}class r21 extends R5{chartData;highlightIndex;showAxes;colors;constructor({key:A,chartData:Q,highlightIndex:$=null,showAxes:B=!0,colors:D=dV0}){super(A?{key:A}:{});this.chartData=Q,this.highlightIndex=$,this.showAxes=B,this.colors=D}createRenderObject(){return new a21({chartData:this.chartData,highlightIndex:this.highlightIndex,showAxes:this.showAxes,colors:this.colors})}updateRenderObject(A){let Q=A;Q.chartData=this.chartData,Q.highlightIndex=this.highlightIndex,Q.showAxes=this.showAxes,Q.colors=this.colors,Q.markNeedsLayout()}}function l66(A,Q,$,B,D,J,F){if(J<=0)return null;switch(A){case"horizontal-bar":{let Y=$;return Y>=0&&Y<J?Y:null}case"bar":case"stacked-bar":{let Y=F?a2:0,E=B-Y;if(E<=0)return null;let Z=Q-Y;if(Z<0||Z>=E)return null;let U=Math.max(1,Math.floor(E/J)),X=Math.floor(Z/U);return X>=0&&X<J?X:null}case"line":case"sparkline":case"stacked-area":{let Y=F?a2:0,E=B-Y;if(E<=0)return null;let Z=Math.max(0,Math.min(E-1,Q-Y));if(J===1)return 0;let U=E/(J-1),X=Math.round(Z/U);return Math.max(0,Math.min(J-1,X))}default:return null}}function Xe3(A,Q,$,B,D,J,F,Y){if(D<=0||Q<0||Q>=D)return null;let E=2;switch(A){case"horizontal-bar":return{x:Math.floor($/2),y:Q};case"bar":case"stacked-bar":{let Z=J?a2:0,U=$-Z,X=B-(J?E:0);if(U<=0||X<=0)return null;let G=Math.max(1,Math.floor(U/D)),V=Z+Q*G+Math.floor(G/2),K=Y>0?F/Y:0,I=Math.round((1-K)*(X-1));return{x:V,y:I}}case"line":case"sparkline":case"stacked-area":{let Z=J?a2:0,U=$-Z,X=B-(J?E:0);if(U<=0||X<=0)return null;let G=D>1?Z+Math.round(Q/(D-1)*(U-1)):Z+Math.floor(U/2),V=Y>0?F/Y:0,K=Math.round((1-V)*(X-1));return{x:G,y:K}}default:return null}}function Ge3(A){let Q=0;for(let $ of A)for(let B of $.points)if(B.value>Q)Q=B.value;return Q||1}function Ve3(A,Q,$,B,D){if($.length<=1){let Y=B(A.value),E=A.meta?` (${A.meta})`:"";return A.label.length+2+Y.length+E.length}let J=A.label.length,F=0;for(let Y of $){let E=Y.points[Q];if(!E)continue;F+=E.value;let Z=2+Y.name.length+2+B(E.value).length;J=Math.max(J,Z)}if(D){let Y=9+B(F).length;J=Math.max(J,Y)}return J}function Ke3(A,Q,$,B,D,J,F){let Y;try{let K=L1.of(A),I=O0.of(A);Y={foreground:K.colorScheme.foreground,background:K.colorScheme.background,border:I.app.keybind}}catch{Y={foreground:{type:"index",value:15},background:{type:"index",value:0},border:{type:"index",value:7}}}let E=new T({color:Y.foreground,bold:!0}),Z=new T({color:Y.foreground}),U=new T({color:Y.foreground,dim:!0}),X=[],G=new T({color:Y.foreground,underline:!0}),V=(K,I)=>new C(I,G,void 0,lz(K),()=>{n6(A,K)});if(B.length<=1){if(X.push(new C(`${Q.label}: `,E)),Q.link)X.push(V(Q.link,J(Q.value)));else X.push(new C(J(Q.value),Z));if(Q.meta)X.push(new C(` (${Q.meta})`,U))}else{let K=F==="stacked-bar"||F==="stacked-area";X.push(new C(`${Q.label}
7084
7084
  `,E));let I=0;for(let z=0;z<B.length;z++){let W=B[z],H=W.points[$];if(!H)continue;I+=H.value;let q=W.color??D[z%D.length]??Y.foreground;if(X.push(new C("● ",new T({color:q}))),X.push(new C(`${W.name}: `,U)),H.link)X.push(V(H.link,J(H.value)));else X.push(new C(J(H.value),Z));if(z<B.length-1||K)X.push(new C(`
7085
- `))}if(K)X.push(new C(" ",U)),X.push(new C("Total: ",U)),X.push(new C(J(I),Z))}return new b0({decoration:{color:Y.background,border:m1.all(new d1(Y.border,1,"rounded"))},child:new d({text:new C(void 0,void 0,X)})})}p0();function i66(A){return A.length===0?A:A[0].toLowerCase()+A.slice(1)}Z5();a5();y5();h$();u9();$8();xQ();Bq();a4();Zk();y_();P1();p0();u9();class s21{enabled;configService;commandCounts=new Map;timer=null;bufferTimeMs=1e4;constructor(A,Q){this.enabled=A;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 A=Array.from(this.commandCounts.entries()).map(([Q,$])=>({feature:"cli.command",action:Q,source:{client:"cli",clientVersion:"0.0.1779296280-g014378"},parameters:{metadata:{count:$}},timestamp:Date.now()*1000}));this.commandCounts.clear();try{let Q=JSON.stringify(A);await G20(Q,this.configService)}catch(Q){P.error("Failed to export command telemetry events",Q)}}async submit(A){if(!await this.enabled()||this.timer===null)return;let Q=this.commandCounts.get(A)||0;this.commandCounts.set(A,Q+1)}async dispose(){if(await this.flushEvents(),this.timer!==null)clearInterval(this.timer),this.timer=null}}class Lw extends P0{props;constructor(A){super();this.props=A}createState(){return new n66}}class n66 extends R0{_state;initState(){super.initState(),this._state=this.widget.props.initialState}build(A){let Q=($)=>{this.setState(()=>{this._state=$(this._state)})};return this.widget.props.builder(A,Q,this._state)}}class a66 extends R0{controller=new T2;focusNode=new r6({debugLabel:"CommandArgumentPrompt",onKey:(A)=>{if(A.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(A){let Q=O0.of(A),{colors:$,app:B}=Q,D=this.widget.props.isRequiredArg??!0,J=this.controller.text.trim().length>0,F=!D||J,Y=m1.all(new d1($.foreground,1,"solid")),E=new UB({controller:this.controller,focusNode:this.focusNode,placeholder:this.widget.props.placeholder??"Enter command argument...",onSubmitted:(V)=>{let K=V.trim();if(D&&K.length===0)return;this.widget.props.onSubmit(K)},autofocus:!0,style:{textColor:$.foreground,border:null},maxLines:1}),Z=new r0({children:[new b0({decoration:{color:$.background},child:new d({text:new C(">",new T({color:$.foreground}))})}),new R1({child:E})]}),U=new b0({padding:V0.symmetric(1,0),child:new d({text:this.widget.props.title?new C(this.widget.props.title,new T({color:B.command,bold:!0})):new C("",void 0,[new C("Command: ",new T({color:$.foreground})),new C(this.widget.props.commandName,new T({color:B.command,bold:!0}))])})}),X=[];if(F)X.push(new C("Enter",new T({color:B.keybind}))),X.push(new C(" to submit, ",new T({color:$.foreground,dim:!0})));X.push(new C("Esc",new T({color:B.keybind}))),X.push(new C(" to cancel",new T({color:$.foreground,dim:!0})));let G=new b0({padding:V0.symmetric(1,0),child:new d({text:new C("",void 0,X)})});return new b0({decoration:{border:Y,color:$.background},padding:V0.all(1),child:new S0({children:[U,new X0({height:1}),Z,new X3,G]})})}}class St extends P0{props;constructor(A){super();this.props=A}createState(){return new a66}}xQ();class o66 extends R0{controller=new T2;imageAttachments=[];imagePaths=[];isConfirmingClearInput=!1;clearInputConfirmTimeout=null;focusNode=new r6({debugLabel:"CommandMultilinePrompt",onKey:(A)=>{if(A.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=async(A)=>{if(this.imageAttachments.length>=T9)return!1;let Q=await rG(A);if(typeof Q==="object")return this.setState(()=>{this.imageAttachments=[...this.imageAttachments,Q],this.imagePaths=[...this.imagePaths,A]}),!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(A){let Q=O0.of(A),{colors:$,app:B}=Q,J=c1.of(A).size.height,F=Math.max(Math.floor(J*0.5),10),Y=new ZI({controller:this.controller,triggers:[new YE],completionBuilder:this.widget.props.completionBuilder,onSubmitted:(V)=>{this.widget.props.onSubmit(V.trim(),this.imageAttachments)},theme:$,placeholder:this.widget.props.placeholder||"Enter your message...",enabled:this.widget.props.enabled??!0,autofocus:!0,clipboard:K4.instance.tuiInstance.clipboard,autoOverlayPosition:!0,onInsertImage:this.widget.props.onInsertImage??this._handleInsertImage,imageAttachments:this.imageAttachments,popImage:this._handlePopImage}),E=new v4({debugLabel:"CommandMultilinePrompt",focusNode:this.focusNode,child:Y}),Z=new b0({constraints:new C1({maxHeight:F}),padding:V0.symmetric(1,0),child:E}),U=new b0({padding:V0.symmetric(1,0),child:new d({text:new C("",void 0,[new C("Command: ",new T({color:$.foreground})),new C(this.widget.props.commandName,new T({color:B.command,bold:!0}))])})}),X=new b0({padding:V0.symmetric(1,0),child:new d({text:this.isConfirmingClearInput?new C("",void 0,[new C("Esc",new T({color:B.keybind})),new C(" again to clear input",new T({color:$.foreground,dim:!0}))]):new C("",void 0,[new C("Press ",new T({color:$.foreground,dim:!0})),new C("Enter",new T({color:B.keybind})),new C(" to submit, ",new T({color:$.foreground,dim:!0})),new C("Esc",new T({color:B.keybind})),new C(" to clear",new T({color:$.foreground,dim:!0}))])})}),G=[U,new X0({height:1}),new R1({child:Z}),new X0({height:1}),X];return new b0({decoration:{border:m1.all(new d1($.foreground,1,"solid")),color:$.background},padding:V0.all(1),child:new S0({children:G})})}}class t21 extends P0{props;constructor(A){super();this.props=A}createState(){return new o66}}function r66(A){let $=new Date().getTime()-A.getTime(),B=Math.floor($/60000),D=Math.floor($/3600000),J=Math.floor($/86400000);if(B<1)return"just now";if(B<60)return`${B}m ago`;if(D<24)return`${D}h ago`;if(J<7)return`${J}d ago`;return A.toLocaleDateString()}class e21 extends H1{props;debugLabel="NewsFeedPicker";constructor(A){super();this.props=A}build(A){let Q=[...this.props.entries].sort((D,J)=>J.pubDate.getTime()-D.pubDate.getTime()),$=Math.max(0,...Q.map((D)=>r66(D.pubDate).length));return new lA({items:Q,getLabel:(D)=>D.title,onAccept:(D)=>this.props.onSelect?.(D),onDismiss:this.props.onDismiss,title:this.props.title,emptyStateText:"No news entries available",maxRenderItems:100,renderItem:(D,J,F,Y)=>{let E=O0.of(Y),{colors:Z}=E,U=E.app,X=J?U.selectionBackground:void 0,G=J?U.selectionForeground:Z.foreground,V=Z.mutedForeground,K=(I,z)=>new X0({width:z,child:r0.end([new d({text:new C(I,new T({color:V}))})])});return new b0({decoration:X?{color:X}:void 0,padding:V0.symmetric(2,0),child:new r0({children:[new R1({child:new d({text:new C(D.title,new T({color:G})),overflow:"ellipsis",maxLines:1})}),new X0({width:2}),K(r66(D.pubDate),$)]})})}})}}class W${static _instance=null;_allExpanded=!1;_listeners=new Set;static get instance(){if(!W$._instance)W$._instance=new W$;return W$._instance}get allExpanded(){return this._allExpanded}setAllExpanded(A){if(this._allExpanded===A)return;this._allExpanded=A,this._notifyListeners()}toggleAll(){this.setAllExpanded(!this._allExpanded)}addListener(A){return this._listeners.add(A),()=>this.removeListener(A)}removeListener(A){this._listeners.delete(A)}_notifyListeners(){for(let A of this._listeners)A()}}p0();class s66 extends R0{labels=[];isLoading=!0;currentQuery="";initState(){this.loadLabels()}async loadLabels(){try{let A=await this.widget.props.internalAPIClient.getUserLabels({query:""},{config:this.widget.props.configService});if(!A.ok){P.error("Failed to load labels",A.error),this.isLoading=!1,this.labels=[],this.setState();return}this.labels=A.result,this.isLoading=!1,this.setState()}catch(A){P.error("Failed to load labels",A),this.isLoading=!1,this.labels=[],this.setState()}}getValidationError(A){let Q=A.trim().toLowerCase();if(Q.length===0)return null;if(Q.length>32)return"Label name cannot exceed 32 characters";if(!/^[a-z0-9][a-z0-9-]*$/.test(Q))return"Label must be alphanumeric with hyphens, starting with a letter or number";return null}isValidLabelName(A){return this.getValidationError(A)===null&&A.length>0}getAvailableLabels(){let A=this.widget.props.currentLabels||[];return this.labels.filter((Q)=>!A.includes(Q.name))}shouldShowCreateMarker(A){if(A.length===0||this.isLoading)return!1;let Q=A.trim().toLowerCase();if(!this.isValidLabelName(Q))return!1;let $=this.widget.props.currentLabels||[],B=this.labels.some((J)=>J.name===Q),D=$.includes(Q);return!B&&!D}build(A){let Q=O0.of(A),{app:$,colors:B}=Q,D=this.currentQuery.trim().toLowerCase(),J=D.length>0?this.getValidationError(D):null,F=this.getAvailableLabels(),E=[{id:"__create__",name:"__create_placeholder__",createdAt:"",__isCreateMarker:!0},...F];return new lA({title:"Add Label",items:E,getLabel:(Z)=>{if("__isCreateMarker"in Z)return this.currentQuery.trim().toLowerCase();return Z.name},onAccept:(Z)=>{if("__isCreateMarker"in Z)this.widget.props.onSelect(this.currentQuery.trim().toLowerCase());else this.widget.props.onSelect(Z.name)},onDismiss:this.widget.props.onDismiss,isLoading:this.isLoading,loadingText:"Loading labels...",emptyStateText:J||"Type to create a new label",renderItem:(Z,U,X,G)=>{let V=U?$.selectionBackground:void 0,K=U?$.selectionForeground:B.foreground;if("__isCreateMarker"in Z&&Z.__isCreateMarker){let z=this.currentQuery.trim().toLowerCase();return new b0({decoration:V?{color:V}:void 0,padding:V0.symmetric(2,0),child:new d({text:new C("",void 0,[new C("Create new label: ",new T({color:K})),new C(z,new T({color:K,bold:!0}))])})})}return new b0({decoration:V?{color:V}:void 0,padding:V0.symmetric(2,0),child:new d({text:new C(Z.name,new T({color:K}))})})},filterItem:(Z,U)=>{if(this.currentQuery!==U)this.currentQuery=U,setTimeout(()=>this.setState(),0);if("__isCreateMarker"in Z&&Z.__isCreateMarker)return this.shouldShowCreateMarker(U);let G=U.trim().toLowerCase();return G.length===0||Z.name.includes(G)},sortItems:(Z,U,X)=>{let G="__isCreateMarker"in Z.item&&Z.item.__isCreateMarker,V="__isCreateMarker"in U.item&&U.item.__isCreateMarker;if(G&&!V)return-1;if(!G&&V)return 1;return U.score-Z.score}})}}class A81 extends P0{props;constructor(A){super();this.props=A}createState(){return new s66}}class DU extends P0{props;constructor(A){super();this.props=A}createState(){return new t66}}class t66 extends R0{_spinner=new NA;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(A){let Q=O0.of(A),{colors:$,app:B}=Q,D=m1.all(new d1($.foreground,1,"solid")),J=this._spinner.toBraille(),F=new d({textAlign:"center",text:new C("",void 0,[new C(J,new T({color:B.processing})),new C(" ",void 0),new C(this.widget.props.message,new T({color:$.foreground}))])}),E=[new R1({child:new S0({mainAxisAlignment:"center",crossAxisAlignment:"center",children:[F]})})];if(this.widget.props.onAbort)E.push(new X0({height:2,child:new b0({padding:V0.symmetric(2,0),child:new d({text:new C("",new T({dim:!0}),[new C("Press ",new T({color:$.foreground})),new C("Esc",new T({color:$.info})),new C(" to cancel",new T({color:$.foreground}))])})})}));let Z=new b0({decoration:new R4($.background,D),child:new X0({width:60,height:7,child:new S0({mainAxisAlignment:"start",children:E})})});if(this.widget.props.onAbort)return new k4({debugLabel:"LoadingDialog",child:new v4({debugLabel:"LoadingDialog",autofocus:!0,onKey:(U)=>{if(U.key==="Escape")return this.widget.props.onAbort?.(),"handled";return"ignored"},child:Z})});return Z}}class $V extends P0{props;constructor(A){super();this.props=A}createState(){return new e66}}class e66 extends R0{scrollController=new v6;scrollAreaKey=new G8("message-dialog-scroll-area");viewportHeight=20;initState(){super.initState(),this.scrollController.followMode=!1,this.scrollController.addListener(()=>{this.setState()})}dispose(){this.scrollController.dispose(),super.dispose()}isWidgetMessage(A){return A instanceof l8}resolveFooterStyle(A){if(this.isWidgetMessage(A))return A.footerStyle;return"default"}getViewportHeight(){let Q=this.scrollAreaKey.currentElement?.renderObject;if(Q&&"size"in Q){let $=Q.size;if(typeof $.height==="number"&&$.height>0)return this.viewportHeight=$.height,$.height}return this.viewportHeight}build(A){let Q=O0.of(A),$=this.widget.props.message,B=(()=>{if(this.isWidgetMessage($))return{title:$.title,type:$.type};if($ instanceof Error&&$.name==="CommandCancelledError")return{title:"Cancelled",type:"info",description:$.message};if($ instanceof Error&&$.name==="CommandTimeoutError")return{title:"Timeout",type:"error",description:$.message};let U=WU0($);return{title:U.title,type:U.type,description:U.description}})(),D=B.type==="error"?Q.app.toolError:Q.app.command,J=m1.all(new d1(Q.colors.border,1,"solid")),F=new b0({padding:V0.symmetric(1,0),child:new d({text:new C(B.title,new T({color:D,bold:!0}))})}),Y=this.isWidgetMessage($)?$.widget:new d({text:new C(B.description,new T({color:Q.colors.foreground})),selectable:!0}),E=new R1({child:new X5({child:new b0({padding:V0.symmetric(1,0),child:new r0({key:this.scrollAreaKey,crossAxisAlignment:"stretch",children:[new R1({child:new k6({controller:this.scrollController,autofocus:!0,child:Y})}),new q8({controller:this.scrollController,thumbColor:Q.app.scrollbarThumb,trackColor:Q.app.scrollbarTrack,getScrollInfo:()=>{let U=this.scrollController.maxScrollExtent,X=this.scrollController.offset,G=this.getViewportHeight(),V=U+G;return{totalContentHeight:Math.max(V,0),viewportHeight:Math.max(G,1),scrollOffset:Math.max(X,0)}}})]})})})}),Z=new b0({padding:V0.symmetric(1,0),child:new d({text:(()=>{if(this.widget.props.onRetry)return new C("",void 0,[new C("Press ",new T({color:Q.colors.foreground,dim:!0})),new C("R",new T({color:Q.app.keybind})),new C(" to retry, ",new T({color:Q.colors.foreground,dim:!0})),new C("Esc",new T({color:Q.app.keybind})),new C(" to cancel",new T({color:Q.colors.foreground,dim:!0}))]);let U=this.resolveFooterStyle(this.widget.props.message);if(U==="none")return new C("",new T({color:Q.colors.foreground,dim:!0}));if(U==="help"){let X=new T({color:Q.app.keybind}),G=new T({color:Q.colors.foreground,dim:!0});return new C("",G,[new C("Press ",G),new C("Escape",X),new C(" to close • Use ",G),new C("↑↓",X),new C(" or ",G),new C("j/k",X),new C(" to scroll",G)])}return new C("Press any key to close",new T({color:Q.colors.foreground,dim:!0,italic:!0}))})()})});return new k4({debugLabel:"MessageDialog",child:new i4({fit:"expand",children:[new O1({onClick:()=>{},child:new X0}),new v4({onKey:(U)=>{if(this.widget.props.onRetry&&U.key==="r")return this.widget.props.onRetry(),"handled";if(U.key==="Escape")return this.widget.props.onDismiss(),"handled";if(!this.widget.props.onRetry)return this.widget.props.onDismiss(),"handled";return"ignored"},autofocus:!1,child:new b0({decoration:{border:J,color:Q.colors.background},padding:V0.all(1),child:new S0({mainAxisAlignment:"center",children:[F,new X0({height:1}),E,Z]})})})]})})}}Z5();Q4();class AA6 extends P0{props;constructor(A){super();this.props=A}createState(){return new QA6}}class QA6 extends R0{plugins=[];subscription=null;initState(){this.subscription=this.widget.props.pluginService.plugins.subscribe((A)=>{this.plugins=A,this.setState(()=>{})})}dispose(){this.subscription?.unsubscribe(),super.dispose()}getRelativePath(A){let Q=i0.file(this.widget.props.cwd),$=B1.relativePath(Q,GA(A));if($!==null&&$!==""&&$!==".."&&!$.startsWith("../"))return $;return l3(A)}statusIcon(A){let Q=l2.default(),{colors:$,app:B}=Q;switch(A){case"loading":return{icon:"◌",color:$.warning};case"active":return{icon:"✓",color:B.toolSuccess};case"error":return{icon:"✗",color:B.toolError}}}build(A){let Q=O0.of(A),{app:$}=Q;if(this.plugins.length===0)return new d({text:new C("No plugins found.",new T({dim:!0}))});let B=[],D=this.plugins.length,J=this.plugins.filter((E)=>E.status==="active").length,F=this.plugins.reduce((E,Z)=>E+Z.registeredCommands.length,0),Y=this.plugins.reduce((E,Z)=>E+Z.registeredTools.length,0);if(B.push(new C(`${J}/${D} ${X4(D,"plugin")} active`,new T({bold:!0}))),F>0||Y>0)B.push(new C(` (${F} ${X4(F,"command")}, ${Y} ${X4(Y,"tool")})`,new T({dim:!0})));B.push(new C(`
7085
+ `))}if(K)X.push(new C(" ",U)),X.push(new C("Total: ",U)),X.push(new C(J(I),Z))}return new b0({decoration:{color:Y.background,border:m1.all(new d1(Y.border,1,"rounded"))},child:new d({text:new C(void 0,void 0,X)})})}p0();function i66(A){return A.length===0?A:A[0].toLowerCase()+A.slice(1)}Z5();a5();y5();h$();u9();$8();xQ();Bq();a4();Zk();y_();P1();p0();u9();class s21{enabled;configService;commandCounts=new Map;timer=null;bufferTimeMs=1e4;constructor(A,Q){this.enabled=A;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 A=Array.from(this.commandCounts.entries()).map(([Q,$])=>({feature:"cli.command",action:Q,source:{client:"cli",clientVersion:"0.0.1779313683-gf89f27"},parameters:{metadata:{count:$}},timestamp:Date.now()*1000}));this.commandCounts.clear();try{let Q=JSON.stringify(A);await G20(Q,this.configService)}catch(Q){P.error("Failed to export command telemetry events",Q)}}async submit(A){if(!await this.enabled()||this.timer===null)return;let Q=this.commandCounts.get(A)||0;this.commandCounts.set(A,Q+1)}async dispose(){if(await this.flushEvents(),this.timer!==null)clearInterval(this.timer),this.timer=null}}class Lw extends P0{props;constructor(A){super();this.props=A}createState(){return new n66}}class n66 extends R0{_state;initState(){super.initState(),this._state=this.widget.props.initialState}build(A){let Q=($)=>{this.setState(()=>{this._state=$(this._state)})};return this.widget.props.builder(A,Q,this._state)}}class a66 extends R0{controller=new T2;focusNode=new r6({debugLabel:"CommandArgumentPrompt",onKey:(A)=>{if(A.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(A){let Q=O0.of(A),{colors:$,app:B}=Q,D=this.widget.props.isRequiredArg??!0,J=this.controller.text.trim().length>0,F=!D||J,Y=m1.all(new d1($.foreground,1,"solid")),E=new UB({controller:this.controller,focusNode:this.focusNode,placeholder:this.widget.props.placeholder??"Enter command argument...",onSubmitted:(V)=>{let K=V.trim();if(D&&K.length===0)return;this.widget.props.onSubmit(K)},autofocus:!0,style:{textColor:$.foreground,border:null},maxLines:1}),Z=new r0({children:[new b0({decoration:{color:$.background},child:new d({text:new C(">",new T({color:$.foreground}))})}),new R1({child:E})]}),U=new b0({padding:V0.symmetric(1,0),child:new d({text:this.widget.props.title?new C(this.widget.props.title,new T({color:B.command,bold:!0})):new C("",void 0,[new C("Command: ",new T({color:$.foreground})),new C(this.widget.props.commandName,new T({color:B.command,bold:!0}))])})}),X=[];if(F)X.push(new C("Enter",new T({color:B.keybind}))),X.push(new C(" to submit, ",new T({color:$.foreground,dim:!0})));X.push(new C("Esc",new T({color:B.keybind}))),X.push(new C(" to cancel",new T({color:$.foreground,dim:!0})));let G=new b0({padding:V0.symmetric(1,0),child:new d({text:new C("",void 0,X)})});return new b0({decoration:{border:Y,color:$.background},padding:V0.all(1),child:new S0({children:[U,new X0({height:1}),Z,new X3,G]})})}}class St extends P0{props;constructor(A){super();this.props=A}createState(){return new a66}}xQ();class o66 extends R0{controller=new T2;imageAttachments=[];imagePaths=[];isConfirmingClearInput=!1;clearInputConfirmTimeout=null;focusNode=new r6({debugLabel:"CommandMultilinePrompt",onKey:(A)=>{if(A.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=async(A)=>{if(this.imageAttachments.length>=T9)return!1;let Q=await rG(A);if(typeof Q==="object")return this.setState(()=>{this.imageAttachments=[...this.imageAttachments,Q],this.imagePaths=[...this.imagePaths,A]}),!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(A){let Q=O0.of(A),{colors:$,app:B}=Q,J=c1.of(A).size.height,F=Math.max(Math.floor(J*0.5),10),Y=new ZI({controller:this.controller,triggers:[new YE],completionBuilder:this.widget.props.completionBuilder,onSubmitted:(V)=>{this.widget.props.onSubmit(V.trim(),this.imageAttachments)},theme:$,placeholder:this.widget.props.placeholder||"Enter your message...",enabled:this.widget.props.enabled??!0,autofocus:!0,clipboard:K4.instance.tuiInstance.clipboard,autoOverlayPosition:!0,onInsertImage:this.widget.props.onInsertImage??this._handleInsertImage,imageAttachments:this.imageAttachments,popImage:this._handlePopImage}),E=new v4({debugLabel:"CommandMultilinePrompt",focusNode:this.focusNode,child:Y}),Z=new b0({constraints:new C1({maxHeight:F}),padding:V0.symmetric(1,0),child:E}),U=new b0({padding:V0.symmetric(1,0),child:new d({text:new C("",void 0,[new C("Command: ",new T({color:$.foreground})),new C(this.widget.props.commandName,new T({color:B.command,bold:!0}))])})}),X=new b0({padding:V0.symmetric(1,0),child:new d({text:this.isConfirmingClearInput?new C("",void 0,[new C("Esc",new T({color:B.keybind})),new C(" again to clear input",new T({color:$.foreground,dim:!0}))]):new C("",void 0,[new C("Press ",new T({color:$.foreground,dim:!0})),new C("Enter",new T({color:B.keybind})),new C(" to submit, ",new T({color:$.foreground,dim:!0})),new C("Esc",new T({color:B.keybind})),new C(" to clear",new T({color:$.foreground,dim:!0}))])})}),G=[U,new X0({height:1}),new R1({child:Z}),new X0({height:1}),X];return new b0({decoration:{border:m1.all(new d1($.foreground,1,"solid")),color:$.background},padding:V0.all(1),child:new S0({children:G})})}}class t21 extends P0{props;constructor(A){super();this.props=A}createState(){return new o66}}function r66(A){let $=new Date().getTime()-A.getTime(),B=Math.floor($/60000),D=Math.floor($/3600000),J=Math.floor($/86400000);if(B<1)return"just now";if(B<60)return`${B}m ago`;if(D<24)return`${D}h ago`;if(J<7)return`${J}d ago`;return A.toLocaleDateString()}class e21 extends H1{props;debugLabel="NewsFeedPicker";constructor(A){super();this.props=A}build(A){let Q=[...this.props.entries].sort((D,J)=>J.pubDate.getTime()-D.pubDate.getTime()),$=Math.max(0,...Q.map((D)=>r66(D.pubDate).length));return new lA({items:Q,getLabel:(D)=>D.title,onAccept:(D)=>this.props.onSelect?.(D),onDismiss:this.props.onDismiss,title:this.props.title,emptyStateText:"No news entries available",maxRenderItems:100,renderItem:(D,J,F,Y)=>{let E=O0.of(Y),{colors:Z}=E,U=E.app,X=J?U.selectionBackground:void 0,G=J?U.selectionForeground:Z.foreground,V=Z.mutedForeground,K=(I,z)=>new X0({width:z,child:r0.end([new d({text:new C(I,new T({color:V}))})])});return new b0({decoration:X?{color:X}:void 0,padding:V0.symmetric(2,0),child:new r0({children:[new R1({child:new d({text:new C(D.title,new T({color:G})),overflow:"ellipsis",maxLines:1})}),new X0({width:2}),K(r66(D.pubDate),$)]})})}})}}class W${static _instance=null;_allExpanded=!1;_listeners=new Set;static get instance(){if(!W$._instance)W$._instance=new W$;return W$._instance}get allExpanded(){return this._allExpanded}setAllExpanded(A){if(this._allExpanded===A)return;this._allExpanded=A,this._notifyListeners()}toggleAll(){this.setAllExpanded(!this._allExpanded)}addListener(A){return this._listeners.add(A),()=>this.removeListener(A)}removeListener(A){this._listeners.delete(A)}_notifyListeners(){for(let A of this._listeners)A()}}p0();class s66 extends R0{labels=[];isLoading=!0;currentQuery="";initState(){this.loadLabels()}async loadLabels(){try{let A=await this.widget.props.internalAPIClient.getUserLabels({query:""},{config:this.widget.props.configService});if(!A.ok){P.error("Failed to load labels",A.error),this.isLoading=!1,this.labels=[],this.setState();return}this.labels=A.result,this.isLoading=!1,this.setState()}catch(A){P.error("Failed to load labels",A),this.isLoading=!1,this.labels=[],this.setState()}}getValidationError(A){let Q=A.trim().toLowerCase();if(Q.length===0)return null;if(Q.length>32)return"Label name cannot exceed 32 characters";if(!/^[a-z0-9][a-z0-9-]*$/.test(Q))return"Label must be alphanumeric with hyphens, starting with a letter or number";return null}isValidLabelName(A){return this.getValidationError(A)===null&&A.length>0}getAvailableLabels(){let A=this.widget.props.currentLabels||[];return this.labels.filter((Q)=>!A.includes(Q.name))}shouldShowCreateMarker(A){if(A.length===0||this.isLoading)return!1;let Q=A.trim().toLowerCase();if(!this.isValidLabelName(Q))return!1;let $=this.widget.props.currentLabels||[],B=this.labels.some((J)=>J.name===Q),D=$.includes(Q);return!B&&!D}build(A){let Q=O0.of(A),{app:$,colors:B}=Q,D=this.currentQuery.trim().toLowerCase(),J=D.length>0?this.getValidationError(D):null,F=this.getAvailableLabels(),E=[{id:"__create__",name:"__create_placeholder__",createdAt:"",__isCreateMarker:!0},...F];return new lA({title:"Add Label",items:E,getLabel:(Z)=>{if("__isCreateMarker"in Z)return this.currentQuery.trim().toLowerCase();return Z.name},onAccept:(Z)=>{if("__isCreateMarker"in Z)this.widget.props.onSelect(this.currentQuery.trim().toLowerCase());else this.widget.props.onSelect(Z.name)},onDismiss:this.widget.props.onDismiss,isLoading:this.isLoading,loadingText:"Loading labels...",emptyStateText:J||"Type to create a new label",renderItem:(Z,U,X,G)=>{let V=U?$.selectionBackground:void 0,K=U?$.selectionForeground:B.foreground;if("__isCreateMarker"in Z&&Z.__isCreateMarker){let z=this.currentQuery.trim().toLowerCase();return new b0({decoration:V?{color:V}:void 0,padding:V0.symmetric(2,0),child:new d({text:new C("",void 0,[new C("Create new label: ",new T({color:K})),new C(z,new T({color:K,bold:!0}))])})})}return new b0({decoration:V?{color:V}:void 0,padding:V0.symmetric(2,0),child:new d({text:new C(Z.name,new T({color:K}))})})},filterItem:(Z,U)=>{if(this.currentQuery!==U)this.currentQuery=U,setTimeout(()=>this.setState(),0);if("__isCreateMarker"in Z&&Z.__isCreateMarker)return this.shouldShowCreateMarker(U);let G=U.trim().toLowerCase();return G.length===0||Z.name.includes(G)},sortItems:(Z,U,X)=>{let G="__isCreateMarker"in Z.item&&Z.item.__isCreateMarker,V="__isCreateMarker"in U.item&&U.item.__isCreateMarker;if(G&&!V)return-1;if(!G&&V)return 1;return U.score-Z.score}})}}class A81 extends P0{props;constructor(A){super();this.props=A}createState(){return new s66}}class DU extends P0{props;constructor(A){super();this.props=A}createState(){return new t66}}class t66 extends R0{_spinner=new NA;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(A){let Q=O0.of(A),{colors:$,app:B}=Q,D=m1.all(new d1($.foreground,1,"solid")),J=this._spinner.toBraille(),F=new d({textAlign:"center",text:new C("",void 0,[new C(J,new T({color:B.processing})),new C(" ",void 0),new C(this.widget.props.message,new T({color:$.foreground}))])}),E=[new R1({child:new S0({mainAxisAlignment:"center",crossAxisAlignment:"center",children:[F]})})];if(this.widget.props.onAbort)E.push(new X0({height:2,child:new b0({padding:V0.symmetric(2,0),child:new d({text:new C("",new T({dim:!0}),[new C("Press ",new T({color:$.foreground})),new C("Esc",new T({color:$.info})),new C(" to cancel",new T({color:$.foreground}))])})})}));let Z=new b0({decoration:new R4($.background,D),child:new X0({width:60,height:7,child:new S0({mainAxisAlignment:"start",children:E})})});if(this.widget.props.onAbort)return new k4({debugLabel:"LoadingDialog",child:new v4({debugLabel:"LoadingDialog",autofocus:!0,onKey:(U)=>{if(U.key==="Escape")return this.widget.props.onAbort?.(),"handled";return"ignored"},child:Z})});return Z}}class $V extends P0{props;constructor(A){super();this.props=A}createState(){return new e66}}class e66 extends R0{scrollController=new v6;scrollAreaKey=new G8("message-dialog-scroll-area");viewportHeight=20;initState(){super.initState(),this.scrollController.followMode=!1,this.scrollController.addListener(()=>{this.setState()})}dispose(){this.scrollController.dispose(),super.dispose()}isWidgetMessage(A){return A instanceof l8}resolveFooterStyle(A){if(this.isWidgetMessage(A))return A.footerStyle;return"default"}getViewportHeight(){let Q=this.scrollAreaKey.currentElement?.renderObject;if(Q&&"size"in Q){let $=Q.size;if(typeof $.height==="number"&&$.height>0)return this.viewportHeight=$.height,$.height}return this.viewportHeight}build(A){let Q=O0.of(A),$=this.widget.props.message,B=(()=>{if(this.isWidgetMessage($))return{title:$.title,type:$.type};if($ instanceof Error&&$.name==="CommandCancelledError")return{title:"Cancelled",type:"info",description:$.message};if($ instanceof Error&&$.name==="CommandTimeoutError")return{title:"Timeout",type:"error",description:$.message};let U=WU0($);return{title:U.title,type:U.type,description:U.description}})(),D=B.type==="error"?Q.app.toolError:Q.app.command,J=m1.all(new d1(Q.colors.border,1,"solid")),F=new b0({padding:V0.symmetric(1,0),child:new d({text:new C(B.title,new T({color:D,bold:!0}))})}),Y=this.isWidgetMessage($)?$.widget:new d({text:new C(B.description,new T({color:Q.colors.foreground})),selectable:!0}),E=new R1({child:new X5({child:new b0({padding:V0.symmetric(1,0),child:new r0({key:this.scrollAreaKey,crossAxisAlignment:"stretch",children:[new R1({child:new k6({controller:this.scrollController,autofocus:!0,child:Y})}),new q8({controller:this.scrollController,thumbColor:Q.app.scrollbarThumb,trackColor:Q.app.scrollbarTrack,getScrollInfo:()=>{let U=this.scrollController.maxScrollExtent,X=this.scrollController.offset,G=this.getViewportHeight(),V=U+G;return{totalContentHeight:Math.max(V,0),viewportHeight:Math.max(G,1),scrollOffset:Math.max(X,0)}}})]})})})}),Z=new b0({padding:V0.symmetric(1,0),child:new d({text:(()=>{if(this.widget.props.onRetry)return new C("",void 0,[new C("Press ",new T({color:Q.colors.foreground,dim:!0})),new C("R",new T({color:Q.app.keybind})),new C(" to retry, ",new T({color:Q.colors.foreground,dim:!0})),new C("Esc",new T({color:Q.app.keybind})),new C(" to cancel",new T({color:Q.colors.foreground,dim:!0}))]);let U=this.resolveFooterStyle(this.widget.props.message);if(U==="none")return new C("",new T({color:Q.colors.foreground,dim:!0}));if(U==="help"){let X=new T({color:Q.app.keybind}),G=new T({color:Q.colors.foreground,dim:!0});return new C("",G,[new C("Press ",G),new C("Escape",X),new C(" to close • Use ",G),new C("↑↓",X),new C(" or ",G),new C("j/k",X),new C(" to scroll",G)])}return new C("Press any key to close",new T({color:Q.colors.foreground,dim:!0,italic:!0}))})()})});return new k4({debugLabel:"MessageDialog",child:new i4({fit:"expand",children:[new O1({onClick:()=>{},child:new X0}),new v4({onKey:(U)=>{if(this.widget.props.onRetry&&U.key==="r")return this.widget.props.onRetry(),"handled";if(U.key==="Escape")return this.widget.props.onDismiss(),"handled";if(!this.widget.props.onRetry)return this.widget.props.onDismiss(),"handled";return"ignored"},autofocus:!1,child:new b0({decoration:{border:J,color:Q.colors.background},padding:V0.all(1),child:new S0({mainAxisAlignment:"center",children:[F,new X0({height:1}),E,Z]})})})]})})}}Z5();Q4();class AA6 extends P0{props;constructor(A){super();this.props=A}createState(){return new QA6}}class QA6 extends R0{plugins=[];subscription=null;initState(){this.subscription=this.widget.props.pluginService.plugins.subscribe((A)=>{this.plugins=A,this.setState(()=>{})})}dispose(){this.subscription?.unsubscribe(),super.dispose()}getRelativePath(A){let Q=i0.file(this.widget.props.cwd),$=B1.relativePath(Q,GA(A));if($!==null&&$!==""&&$!==".."&&!$.startsWith("../"))return $;return l3(A)}statusIcon(A){let Q=l2.default(),{colors:$,app:B}=Q;switch(A){case"loading":return{icon:"◌",color:$.warning};case"active":return{icon:"✓",color:B.toolSuccess};case"error":return{icon:"✗",color:B.toolError}}}build(A){let Q=O0.of(A),{app:$}=Q;if(this.plugins.length===0)return new d({text:new C("No plugins found.",new T({dim:!0}))});let B=[],D=this.plugins.length,J=this.plugins.filter((E)=>E.status==="active").length,F=this.plugins.reduce((E,Z)=>E+Z.registeredCommands.length,0),Y=this.plugins.reduce((E,Z)=>E+Z.registeredTools.length,0);if(B.push(new C(`${J}/${D} ${X4(D,"plugin")} active`,new T({bold:!0}))),F>0||Y>0)B.push(new C(` (${F} ${X4(F,"command")}, ${Y} ${X4(Y,"tool")})`,new T({dim:!0})));B.push(new C(`
7086
7086
 
7087
7087
  `));for(let E of this.plugins){let{icon:Z,color:U}=this.statusIcon(E.status),X=this.getRelativePath(E.uri);if(B.push(new C(`${Z} `,new T({color:U}))),B.push(new C(X,new T({bold:!0}))),B.push(new C(` ${E.status}`,new T({dim:!0}))),B.push(new C(`
7088
7088
  `)),E.status==="active"&&E.registeredEvents.length>0)B.push(new C(" Events: ",new T({dim:!0}))),B.push(new C(E.registeredEvents.join(", "),new T({color:$.link}))),B.push(new C(`
@@ -7260,7 +7260,7 @@ ${t.content||""}`:t.content||"",y0=[],d0=t.baseDir.startsWith("file://")?IK0(t.b
7260
7260
  `)}function y56(A,Q){A.command("usage").description("Show your current Amp usage and credit balance").action(async($,B)=>{let D=B.optsWithGlobals(),J=await Q(D),F=await J.settings.get("proxy"),Y=I44({settings:{url:J.ampURL,proxy:F},secrets:{getToken:(Z,U)=>J.secrets.get(Z,U)}}),E=await t4.userDisplayBalanceInfo({},{config:Y});if(!E.ok){if(E.error.code==="auth-required")process.stderr.write(t0.red("Error: ")+"You must be logged in to view usage. Run `amp login` first.\n"),process.exit(1);process.stderr.write(t0.red("Error: ")+E.error.message+`
7261
7261
  `),process.exit(1)}process.stdout.write(await S45(E.result.displayText)+`
7262
7262
  `),process.exit(0)})}var $25=He.join(lB,"logs","headless.log"),BQ1=He.join(id,"device-id.json"),B25=`cli-tui-${U76(16).toString("hex")}`;async function D25(){let A=await Promise.all($L.map(async(Q)=>{try{return{query:Q,hasConfigs:(await Q.listConfigs()).length>0}}catch($){return P.debug("Failed to detect query-based IDE integration",{ideName:Q.ideName,error:$}),{query:Q,hasConfigs:!1}}}));for(let Q of A)if(Q.hasConfigs)return Q.query;return}function G76(){D25().then((A)=>{if(A){let Q=k20(A.ideName);if(Q)oM(Q)}})}try{if(process.platform==="win32")await Promise.resolve().then(() => b4(Ab(),1))}catch{}if(process.env.AMP_PWD)try{process.chdir(process.env.AMP_PWD),delete process.env.AMP_PWD}catch(A){H$.write(`Failed to change directory to ${process.env.AMP_PWD}: ${A}
7263
- `)}function J25(A){process.emitWarning=(Q,$,B,D)=>{let J=typeof Q==="string"?Q:Q.message||String(Q),F=$||"Warning",Y=!1;A.warn(J,{name:F,code:B})}}function r8(A,Q){if(A.getOptionValueSourceWithGlobals("dangerouslyAllowAll")==="cli")WJ("dangerouslyAllowAll",Q.dangerouslyAllowAll);if(A.getOptionValueSourceWithGlobals("mode")==="cli")WJ("experimental.agentMode",Q.mode);if(A.getOptionValueSourceWithGlobals("model")==="cli"&&Q.model)WJ("internal.model",E25(Q.model))}function B76(A){let Q=A.indexOf(":");if(Q===-1)throw new n1(`Invalid model format "${A}". Expected "provider:model" (e.g., "anthropic:claude-sonnet-4-20250514").`,1);let $=A.slice(0,Q).trim(),B=A.slice(Q+1).trim();if(!$||!B)throw new n1(`Invalid model format "${A}". Both provider and model must be non-empty (e.g., "anthropic:claude-sonnet-4-20250514").`,1)}function F25(A){if(A===void 0)return;let Q=A.trim();if(o14(Q))return Q;throw new n1(`Invalid effort "${A}". Expected one of: none, minimal, low, medium, high, xhigh, max.`,1)}function Y25(A,Q){if(C2(A,Q))return;let $=tB(A)?.levels,B=$?` Allowed for ${A}: ${$.join(", ")}.`:"";throw new n1(`Reasoning effort "${Q}" is not available for ${A} mode.${B}`,1)}function E25(A){if(!A.includes("="))return B76(A),A;let Q={};for(let $ of A.split(",")){let B=$.trim();if(!B)continue;let D=B.indexOf("=");if(D===-1)throw new n1(`Invalid mode-specific model entry "${B}". Expected "mode=provider:model" (e.g., "smart=anthropic:claude-sonnet-4-20250514").`,1);let J=B.slice(0,D).trim(),F=B.slice(D+1).trim();if(!J)throw new n1(`Missing mode name in "${B}". Expected "mode=provider:model".`,1);if(!F)throw new n1(`Missing model value for mode "${J}". Expected "${J}=provider:model".`,1);B76(F),Q[J]=F}if(Object.keys(Q).length===0)throw new n1("No valid model overrides found in --model flag value.",1);return Q}function Z25(A,Q){if(A.getOptionValueSourceWithGlobals("sp")==="cli"&&Q.sp)return Q.sp;if(A.getOptionValueSourceWithGlobals("systemPrompt")==="cli"&&Q.systemPrompt)return Q.systemPrompt;return}async function U25(A){try{return await X76(A,"utf-8")}catch{return A}}async function DQ1(A,Q,$){let B=Z25(A,Q);if(!B)return;let D=AA($)?$.features:[],J=AA($)?$.user.email:void 0;if(!we(D,S$.HARNESS_SYSTEM_PROMPT)&&!(J&&p7(J)))throw new n1("You are not allowed to do this.",1);WJ("systemPrompt",await U25(B))}function we(A,Q){return A?.some(($)=>$.name===Q&&$.enabled)??!1}function X25(A){return A!=="pending"}function TI(A){if(!AA(A))return null;return{...A.user,features:A.features??[],team:A.workspace??void 0}}function G25(A){let Q=TI(A);if(Q)return Q.id;if(lE(A))throw Error(A.error.message);throw Error("unreachable")}function V25(A){try{let Q=new URL(A);return Q.hostname==="localhost"||Q.hostname==="127.0.0.1"}catch{return A.includes("localhost")||A.includes("127.0.0.1")}}function K25(A){let B=V25(A)?"Run `pnpm dev` to start the local server, then try again.":"Check your network connection or the server URL and try again.";return new n1(`Couldn't connect to the Amp server at ${A}.`,1,B)}function qe(A,Q){let $=Ks0(Error(A.error.message));if($.message===d9.networkOffline||$.message===d9.networkTimeout)return K25(Q);if($.message!==d9.internalBug)return new n1($.message,1,$.suggestion);return new n1(A.error.message.replace(/^Error: /,""),1)}async function z25(){if(process.versions.bun)return!1;try{return await kG()==="npm"}catch(A){return P.debug("Failed to detect package manager for Neo npm migration welcome",{error:A}),!1}}var D76=[{name:"notifications",long:"notifications",type:"flag",description:(A)=>`${A?"Enable":"Disable"} notification alerts (audio locally, terminal bell over SSH or with AMP_FORCE_BEL; enabled by default when not in execute mode)`},{name:"color",long:"color",type:"flag",description:(A)=>`${A?"Enable":"Disable"} color output (enabled by default if stdout and stderr are sent to a TTY)`},{name:"settingsFile",long:"settings-file",type:"option",default:process.env.AMP_SETTINGS_FILE??nE,description:`Custom settings file path (overrides the default location ${nE})`},{name:"logLevel",long:"log-level",type:"option",description:`Set log level (${Object.keys(P).join(", ")})`},{name:"logFile",long:"log-file",type:"option",description:`Set log file location (overrides the default location ${Ao})`},{name:"format",long:"format",type:"option",description:"output using the standard or new-ui. Options: `ui`, `new-ui`",choices:["ui","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:w9(),description:(A)=>A?"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:(A)=>A?"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:(A)=>A?"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:"mode",long:"mode",short:"m",type:"option",default:eM.SMART.key,description:`Set the agent mode (${sB({}).map((A)=>A.mode).join(", ")}) — controls the model, system prompt, and tool selection`,choices:Array.from(new Set(sB().map((A)=>A.mode))),hiddenChoices:["frontier"]},{name:"effort",long:"effort",type:"option",description:"Set reasoning effort for the new thread, when supported by the selected mode",choices:["none","minimal","low","medium","high","xhigh","max"]},{name:"takeMeBack",long:"take-me-back",type:"switch",description:"Disable thread-actors mode and use the legacy worker runtime",hidden:!0},{name:"neoOrb",long:"neo-orb",type:"switch",description:"Use the experimental Neo splash orb",hidden:!0},{name:"hideWelcome",long:"hide-welcome",type:"switch",description:"Skip the welcome experience on startup",hidden:!0},{name:"showWelcome",long:"show-welcome",type:"switch",description:"Show the welcome experience on startup",hidden:!0},{name:"observe",long:"observe",type:"option",description:"Open the Neo TUI as an observer of an existing thread (thread ID or URL)",hidden:!0},{name:"headless",long:"headless",type:"optional-option",description:"Run headless thread-actor executor (no TUI). Optionally provide a thread ID to connect to existing thread, otherwise create one.",hidden:!0},{name:"sp",long:"sp",type:"option",description:"Custom system prompt text or file path",hidden:!0},{name:"systemPrompt",long:"system-prompt",type:"option",description:"Custom system prompt text",hidden:!0},{name:"model",long:"model",type:"option",description:'Override the model. Use "provider:model" for all modes, or "mode=provider:model,mode=provider:model" for mode-specific overrides',hidden:!0}],J76=(A)=>("deprecated"in A)&&A.deprecated===!0,I25=(A)=>("hidden"in A)&&A.hidden===!0,W25=(A)=>("default"in A),H25=(A)=>("default"in A)?A.default:void 0;function Jz0(A,Q){if(A.getOptionValueSourceWithGlobals("effort")!=="cli")return;let $=F25(Q.effort);if($!==void 0)Y25(Q.mode,$);return $}function q25(A,Q){let $=Q.args[0],B=Q.commands.map((J)=>J.name());if($&&!$.includes(" ")&&$.length<30&&!/[./\\]/.test($)){let J=B.filter((Y)=>$.includes(Y)||Y.includes($)),F="Run amp --help for a list of available commands.";if(J.length>0)F=`Did you mean: ${J.join(", ")}? Or run amp --help for all commands.`;throw new n1(d9.unknownCommand($),1,F)}}async function Ez0(A){return{...A,getThreadEnvironment:kz,getEnvironmentData:(Q,$)=>sK(Q,$),skillService:A.skillService,fileChangeTrackerStorage:new mL,generateThreadTitle:NZ4,deleteThread:(Q)=>A.threadService.delete(Q),getServerStatus:()=>sF(A.configService),pluginService:A.pluginService}}function V76(A){return{toolService:A.toolService,configService:A.configService,skillService:A.skillService,getThreadEnvironment:kz,getEnvironmentData:(Q,$)=>sK(Q,$)}}var Fz0=i0.file(Q25.homedir()),JQ1=process.env.XDG_CONFIG_HOME?i0.file(process.env.XDG_CONFIG_HOME):B1.joinPath(Fz0,".config");async function o2(A,Q,$){let B=$?.deferAuth??!1,D=$?.skipToolProviders??!1;g14("0.0.1779296280-g014378");let J=O20({storage:A.settings,secretStorage:A.secrets,workspaceRoot:h0.of(i0.file(process.cwd())),defaultAmpURL:A.ampURL,homeDir:Fz0,userConfigDir:JQ1}),F=A.secrets.get("apiKey",A.ampURL),Y=sF(J),E=null,Z=()=>{return},U=new Promise((Q0)=>{Z=Q0}),X=F.then(async(Q0)=>{if(!Q0&&!B)await U;return E??=Y.subscribe(()=>{}),k1(Y.pipe(i3(X25)))});X.catch(()=>{return}),i06(J);let G=await J.getLatest();P.debug("Global configuration initialized",{settingsKeys:Object.keys(G.settings)});let V=!1;{let Q0=await F;if(V=Boolean(Q0),P.info("API key lookup before login",{found:Boolean(Q0),ampURL:A.ampURL,deferAuth:B}),!Q0)if(B)P.info("No API key found, continuing startup with deferred auth");else{$3.write(`No API key found. Starting login flow...
7263
+ `)}function J25(A){process.emitWarning=(Q,$,B,D)=>{let J=typeof Q==="string"?Q:Q.message||String(Q),F=$||"Warning",Y=!1;A.warn(J,{name:F,code:B})}}function r8(A,Q){if(A.getOptionValueSourceWithGlobals("dangerouslyAllowAll")==="cli")WJ("dangerouslyAllowAll",Q.dangerouslyAllowAll);if(A.getOptionValueSourceWithGlobals("mode")==="cli")WJ("experimental.agentMode",Q.mode);if(A.getOptionValueSourceWithGlobals("model")==="cli"&&Q.model)WJ("internal.model",E25(Q.model))}function B76(A){let Q=A.indexOf(":");if(Q===-1)throw new n1(`Invalid model format "${A}". Expected "provider:model" (e.g., "anthropic:claude-sonnet-4-20250514").`,1);let $=A.slice(0,Q).trim(),B=A.slice(Q+1).trim();if(!$||!B)throw new n1(`Invalid model format "${A}". Both provider and model must be non-empty (e.g., "anthropic:claude-sonnet-4-20250514").`,1)}function F25(A){if(A===void 0)return;let Q=A.trim();if(o14(Q))return Q;throw new n1(`Invalid effort "${A}". Expected one of: none, minimal, low, medium, high, xhigh, max.`,1)}function Y25(A,Q){if(C2(A,Q))return;let $=tB(A)?.levels,B=$?` Allowed for ${A}: ${$.join(", ")}.`:"";throw new n1(`Reasoning effort "${Q}" is not available for ${A} mode.${B}`,1)}function E25(A){if(!A.includes("="))return B76(A),A;let Q={};for(let $ of A.split(",")){let B=$.trim();if(!B)continue;let D=B.indexOf("=");if(D===-1)throw new n1(`Invalid mode-specific model entry "${B}". Expected "mode=provider:model" (e.g., "smart=anthropic:claude-sonnet-4-20250514").`,1);let J=B.slice(0,D).trim(),F=B.slice(D+1).trim();if(!J)throw new n1(`Missing mode name in "${B}". Expected "mode=provider:model".`,1);if(!F)throw new n1(`Missing model value for mode "${J}". Expected "${J}=provider:model".`,1);B76(F),Q[J]=F}if(Object.keys(Q).length===0)throw new n1("No valid model overrides found in --model flag value.",1);return Q}function Z25(A,Q){if(A.getOptionValueSourceWithGlobals("sp")==="cli"&&Q.sp)return Q.sp;if(A.getOptionValueSourceWithGlobals("systemPrompt")==="cli"&&Q.systemPrompt)return Q.systemPrompt;return}async function U25(A){try{return await X76(A,"utf-8")}catch{return A}}async function DQ1(A,Q,$){let B=Z25(A,Q);if(!B)return;let D=AA($)?$.features:[],J=AA($)?$.user.email:void 0;if(!we(D,S$.HARNESS_SYSTEM_PROMPT)&&!(J&&p7(J)))throw new n1("You are not allowed to do this.",1);WJ("systemPrompt",await U25(B))}function we(A,Q){return A?.some(($)=>$.name===Q&&$.enabled)??!1}function X25(A){return A!=="pending"}function TI(A){if(!AA(A))return null;return{...A.user,features:A.features??[],team:A.workspace??void 0}}function G25(A){let Q=TI(A);if(Q)return Q.id;if(lE(A))throw Error(A.error.message);throw Error("unreachable")}function V25(A){try{let Q=new URL(A);return Q.hostname==="localhost"||Q.hostname==="127.0.0.1"}catch{return A.includes("localhost")||A.includes("127.0.0.1")}}function K25(A){let B=V25(A)?"Run `pnpm dev` to start the local server, then try again.":"Check your network connection or the server URL and try again.";return new n1(`Couldn't connect to the Amp server at ${A}.`,1,B)}function qe(A,Q){let $=Ks0(Error(A.error.message));if($.message===d9.networkOffline||$.message===d9.networkTimeout)return K25(Q);if($.message!==d9.internalBug)return new n1($.message,1,$.suggestion);return new n1(A.error.message.replace(/^Error: /,""),1)}async function z25(){if(process.versions.bun)return!1;try{return await kG()==="npm"}catch(A){return P.debug("Failed to detect package manager for Neo npm migration welcome",{error:A}),!1}}var D76=[{name:"notifications",long:"notifications",type:"flag",description:(A)=>`${A?"Enable":"Disable"} notification alerts (audio locally, terminal bell over SSH or with AMP_FORCE_BEL; enabled by default when not in execute mode)`},{name:"color",long:"color",type:"flag",description:(A)=>`${A?"Enable":"Disable"} color output (enabled by default if stdout and stderr are sent to a TTY)`},{name:"settingsFile",long:"settings-file",type:"option",default:process.env.AMP_SETTINGS_FILE??nE,description:`Custom settings file path (overrides the default location ${nE})`},{name:"logLevel",long:"log-level",type:"option",description:`Set log level (${Object.keys(P).join(", ")})`},{name:"logFile",long:"log-file",type:"option",description:`Set log file location (overrides the default location ${Ao})`},{name:"format",long:"format",type:"option",description:"output using the standard or new-ui. Options: `ui`, `new-ui`",choices:["ui","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:w9(),description:(A)=>A?"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:(A)=>A?"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:(A)=>A?"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:"mode",long:"mode",short:"m",type:"option",default:eM.SMART.key,description:`Set the agent mode (${sB({}).map((A)=>A.mode).join(", ")}) — controls the model, system prompt, and tool selection`,choices:Array.from(new Set(sB().map((A)=>A.mode))),hiddenChoices:["frontier"]},{name:"effort",long:"effort",type:"option",description:"Set reasoning effort for the new thread, when supported by the selected mode",choices:["none","minimal","low","medium","high","xhigh","max"]},{name:"takeMeBack",long:"take-me-back",type:"switch",description:"Disable thread-actors mode and use the legacy worker runtime",hidden:!0},{name:"neoOrb",long:"neo-orb",type:"switch",description:"Use the experimental Neo splash orb",hidden:!0},{name:"hideWelcome",long:"hide-welcome",type:"switch",description:"Skip the welcome experience on startup",hidden:!0},{name:"showWelcome",long:"show-welcome",type:"switch",description:"Show the welcome experience on startup",hidden:!0},{name:"observe",long:"observe",type:"option",description:"Open the Neo TUI as an observer of an existing thread (thread ID or URL)",hidden:!0},{name:"headless",long:"headless",type:"optional-option",description:"Run headless thread-actor executor (no TUI). Optionally provide a thread ID to connect to existing thread, otherwise create one.",hidden:!0},{name:"sp",long:"sp",type:"option",description:"Custom system prompt text or file path",hidden:!0},{name:"systemPrompt",long:"system-prompt",type:"option",description:"Custom system prompt text",hidden:!0},{name:"model",long:"model",type:"option",description:'Override the model. Use "provider:model" for all modes, or "mode=provider:model,mode=provider:model" for mode-specific overrides',hidden:!0}],J76=(A)=>("deprecated"in A)&&A.deprecated===!0,I25=(A)=>("hidden"in A)&&A.hidden===!0,W25=(A)=>("default"in A),H25=(A)=>("default"in A)?A.default:void 0;function Jz0(A,Q){if(A.getOptionValueSourceWithGlobals("effort")!=="cli")return;let $=F25(Q.effort);if($!==void 0)Y25(Q.mode,$);return $}function q25(A,Q){let $=Q.args[0],B=Q.commands.map((J)=>J.name());if($&&!$.includes(" ")&&$.length<30&&!/[./\\]/.test($)){let J=B.filter((Y)=>$.includes(Y)||Y.includes($)),F="Run amp --help for a list of available commands.";if(J.length>0)F=`Did you mean: ${J.join(", ")}? Or run amp --help for all commands.`;throw new n1(d9.unknownCommand($),1,F)}}async function Ez0(A){return{...A,getThreadEnvironment:kz,getEnvironmentData:(Q,$)=>sK(Q,$),skillService:A.skillService,fileChangeTrackerStorage:new mL,generateThreadTitle:NZ4,deleteThread:(Q)=>A.threadService.delete(Q),getServerStatus:()=>sF(A.configService),pluginService:A.pluginService}}function V76(A){return{toolService:A.toolService,configService:A.configService,skillService:A.skillService,getThreadEnvironment:kz,getEnvironmentData:(Q,$)=>sK(Q,$)}}var Fz0=i0.file(Q25.homedir()),JQ1=process.env.XDG_CONFIG_HOME?i0.file(process.env.XDG_CONFIG_HOME):B1.joinPath(Fz0,".config");async function o2(A,Q,$){let B=$?.deferAuth??!1,D=$?.skipToolProviders??!1;g14("0.0.1779313683-gf89f27");let J=O20({storage:A.settings,secretStorage:A.secrets,workspaceRoot:h0.of(i0.file(process.cwd())),defaultAmpURL:A.ampURL,homeDir:Fz0,userConfigDir:JQ1}),F=A.secrets.get("apiKey",A.ampURL),Y=sF(J),E=null,Z=()=>{return},U=new Promise((Q0)=>{Z=Q0}),X=F.then(async(Q0)=>{if(!Q0&&!B)await U;return E??=Y.subscribe(()=>{}),k1(Y.pipe(i3(X25)))});X.catch(()=>{return}),i06(J);let G=await J.getLatest();P.debug("Global configuration initialized",{settingsKeys:Object.keys(G.settings)});let V=!1;{let Q0=await F;if(V=Boolean(Q0),P.info("API key lookup before login",{found:Boolean(Q0),ampURL:A.ampURL,deferAuth:B}),!Q0)if(B)P.info("No API key found, continuing startup with deferred auth");else{$3.write(`No API key found. Starting login flow...
7264
7264
  `);let M0=await N25(A),n=await A.secrets.get("apiKey",A.ampURL);if(P.info("Login flow completed",{success:M0,storedKeyPresent:Boolean(n),ampURL:A.ampURL}),!M0)await vz(),process.exit(1);V=!0,Z()}}{let Q0=await J.getLatest(),M0=Q0.settings.url,n=Q0.secrets.isSet?.[M0];P.info("Config secrets state after login",{configURL:M0,apiKeySet:n?.apiKey??!1})}let K=B?"pending":await X;if(!B)P.info("Server status resolved",{status:"ready",isAuthenticated:AA(K),isError:lE(K),errorMessage:lE(K)?K.error.message:void 0});let I=X.then((Q0)=>G25(Q0));I.catch(()=>{return});let z=!Q.takeMeBack&&AA(K)&&we(K.features,S$.THREAD_ACTORS_TUI),W=!1;if(process.env.AMP_DISABLE_PLUGINS==="1")P.warn("Ignoring AMP_DISABLE_PLUGINS outside development");let H=W?"off":z?"all":process.env.PLUGINS??"permissions",{toolService:q,dispose:N}=_u4({configService:J}),w=new Map,O=()=>w.clear(),L=new Bb0(J,A.settings.getWorkspaceRootPath()),j=oF4({configService:J}),k=v$4({configService:J,trustStore:L,skillMCPServers:j.skillMCPServers,uploadImageAttachments:z,createOAuthProvider:async(Q0,M0,n)=>{let a=`${Q0}:${M0}`,t=w.get(a);if(t)return P.debug("Reusing existing OAuth provider for server",{serverName:Q0,serverUrl:M0}),t;P.debug("Creating OAuth provider for server",{serverName:Q0,serverUrl:M0});let e=(async()=>{let F0=new EL(A.secrets),J0=await F0.getClientInfo(Q0,M0),w0=n?.scopes??J0?.scopes,C0=ix4();P.info("OAuth headless mode check",{useHeadless:C0,executeMode:A.executeMode,envVar:process.env.AMP_HEADLESS_OAUTH,isTTY:$3.isTTY});let _0;if(C0)_0=A.executeMode?lx4():cx4(Q0);let U0=new VS0({storage:F0,serverName:Q0,serverUrl:M0,clientId:n?.clientId??J0?.clientId,clientSecret:n?.clientSecret??J0?.clientSecret,authUrl:n?.authUrl??J0?.authUrl,tokenUrl:n?.tokenUrl??J0?.tokenUrl,scopes:w0,headlessAuthHandler:_0});return P.debug("OAuth provider created",{serverName:Q0,serverUrl:M0,hasManualClientId:!!(n?.clientId??J0?.clientId),willUseDCR:!(n?.clientId??J0?.clientId),scopes:w0,headlessMode:C0,executeMode:A.executeMode}),U0})();return w.set(a,e),e}}),_=Jo0({configService:J,spawn:WF0}),f=Q.headless?H06():void 0,h=f??new RG0({configService:J}),b=h instanceof RG0?h:void 0;if(b)b.pluginExecutorKind="local";let v=new a1(null),y=null,p=z&&!W?[...w06(G.settings)?[{name:"permissions",entryPoint:c51}]:[],{name:"thread-visibility",entryPoint:L06(J,()=>X.then(TI),()=>y,(Q0)=>{y=Q0}),alwaysLoad:!0}]:[],c=Hb0({configService:J,platform:h,loadGlobalPlugins:ke0(J),pluginFilter:H,activeThread$:v,internalPlugins:p}),g=OB4(c),i=[k,_,g],r;if(D)r=new Map;else if(A.executeMode){let Q0=await qR4({toolService:q,providers:i,initialTimeout:15000});r=Q0.registrations;for(let[M0,n]of Q0.initErrors)P.warn(`${M0} provider initialization slow or failed:`,n)}else r=Fo0({toolService:q,providers:i});if(Q.jetbrains)oM("JetBrains");else if(Q.ide&&Wb4())oM("VS Code");else if(Q.ide&&Hb4())oM("Neovim");else if(Q.ide&&(!z||A.executeMode||Q.takeMeBack))G76();if(A.executeMode)m14(!0);let A0,I0=o5.status.pipe(N1((Q0)=>Boolean(Q0.connected&&Q0.authenticated&&Q0.ideName&&l44(Q0.ideName))),T4()).subscribe((Q0)=>{if(Q0){if(!A0)A0=q.registerTool(HR4)}else A0?.dispose(),A0=void 0}),E0;if(!A.executeMode){let Q0=await A.settings.get("fuzzy.alwaysIncludePaths")??[];E0=new _E0(process.cwd(),{alwaysIncludePaths:Q0},!0)}else E0=new class extends _E0{async start(){}async query(){return[]}async queryCompletions(){return[]}getStats(){return{state:"unstarted",stats:[]}}dispose(){}};let W0=new Nm0(Ji(J,{usesThreadActors:!1}),{maxThreads:200});P.info("Starting Amp background services");let $0=new r51,j0={configService:J,toolService:q,mcpService:k,skillService:j,toolboxService:_,trustStore:L,threadService:W0,secretStorage:A.secrets,settingsStorage:A.settings,fuzzyServer:E0,terminal:$0,pluginService:c,pluginPlatform:b,headlessPluginPlatform:f,activeThread$:v,serverStatus:K,serverStatusPromise:X,viewerUserIDPromise:I,hasAPIKeyAtStartup:V,consumeDraftNewThreadVisibility:()=>{let Q0=y;return y=null,Q0}};return{...j0,async asyncDispose(){if(j0.mcpService.hasAuthenticatingClients())P.info("Waiting for OAuth authentication to complete before exit..."),await j0.mcpService.waitForAuthentication();for(let Q0 of r.values())Q0.dispose();await j0.mcpService.dispose(),O(),await j0.threadService.asyncDispose(),j0.configService.unsubscribe(),E?.unsubscribe(),N(),j0.fuzzyServer.dispose(),j0.settingsStorage[Symbol.dispose](),I0.unsubscribe(),A0?.dispose(),await j0.pluginService.dispose()}}}async function N25(A){if(!A.executeMode){if(!await wZ0("Would you like to log in to Amp? [(y)es, (n)o]: "))return $3.write(`Login cancelled. Run the command again to retry.
7265
7265
  `),!1}return await K76(A)}async function K76(A){let Q=U76(32).toString("hex"),$=await $y(A.ampURL,Q),B=new AbortController;try{await pE($,B.signal)}catch(J){P.error("Error opening browser",{error:J})}let D=await $y(A.ampURL,Q,!1);$3.write(`If your browser does not open automatically, visit:
7266
7266
 
@@ -7268,7 +7268,7 @@ ${t0.blue.bold(D)}
7268
7268
 
7269
7269
  `);try{return await kg4(A.ampURL,Q,A.secrets,B),$3.write("\nLogin successful! Run `amp` to get started.\n"),!0}catch(J){return P.error("Login failed",{error:J}),H$.write(`
7270
7270
  Login failed: ${J instanceof Error?J.message:String(J)}
7271
- `),!1}}async function w25(A,Q,$){let B=await Q.get("apiKey",A);if(!B)throw new n1("No Amp API key found. Run `amp login` first.",1);let D=t55("curl",["-H",`Authorization: Bearer ${B}`,...$],{stdio:"inherit"});process.exitCode=await new Promise((J,F)=>{D.on("error",F),D.on("close",(Y)=>J(Y??1))})}function C25(A){let Q=new DN().name("amp").description("AI-powered coding assistant").option("--visibility <visibility>","Set thread visibility (private, public, workspace, group)").configureOutput({writeErr:()=>{}});Q.exitOverride((z)=>{if(z.code==="commander.help"||z.code==="commander.version"||z.exitCode===0)zj(),process.exit(0);let W=z.originalError??z;rv4(W)}),Od4(Q,{version:"0.0.1779296280-g014378",buildTimestamp:"2026-05-20T17:03:06.980Z",buildType:"release"}),Q.addHelpText("after",Kb4()),Q.configureHelp({formatHelp:zb4}),Q.command("logout").description("Log out by removing stored API key").action(async(z,W)=>{let H=W.optsWithGlobals(),q=await d3(H);await v25(q)}),Q.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(z,W)=>{let H=W.optsWithGlobals(),q=await d3(H);await T25(q,await i51(H,q.settings))}),nv4(Q,d3);let B=Q.command("internal",{hidden:!0}).description("Internal commands").command("curl [args...]").description("Internal: run curl with the current Amp API key as a bearer token").allowUnknownOption(!0).allowExcessArguments(!0).action(async(...z)=>{let W=z.find((w)=>typeof w==="object"&&w!==null&&typeof w.optsWithGlobals==="function")??B,H=z.filter((w)=>w!==W).flatMap((w)=>Array.isArray(w)?w:typeof w==="string"?[w]:[]),q=W.optsWithGlobals(),N=await d3(q);await w25(N.ampURL,N.secrets,H),process.exit(process.exitCode??0)});Q.command("git-credential-helper [action]",{hidden:!0}).summary("Git credential helper for GitHub").description("Internal: implements the git credential helper protocol. Used inside sandboxes to authenticate git operations with GitHub.").action(async(z,W,H)=>{let q=H.optsWithGlobals(),N=await d3(q);await yx4(z??"get",N.ampURL,N.secrets),process.exit(process.exitCode??0)}),Q.command("sign-commit",{hidden:!0}).summary("Git commit signing helper").description("Internal: implements the gpg signing interface for git commit signing. Used inside sandboxes as gpg.program.").allowUnknownOption().action(async(z,W)=>{let H=W.optsWithGlobals(),q=await d3(H);await xx4(q.ampURL,q.secrets),process.exit(process.exitCode??0)}),Q.command("keyboard-tester",{hidden:!0}).summary("Keyboard input tester").description("Internal: stream parsed terminal input events as JSONL.").option("--raw","Log raw incoming terminal bytes before parsing").action(async(z)=>{await vh4({raw:z.raw===!0}),process.exit(process.exitCode??0)}),Q.command("live-sync [threadIDOrURL]",{hidden:!0}).summary("Mirror live DTW thread changes into the current checkout").description("Experimental: watch a v2 thread URL or ID and mirror its live working-tree changes into your local checkout, or apply the current snapshot once and exit.").addHelpText("after",["","Examples:"," amp live-sync T-5928a90d-d53b-488f-a829-4e36442142ee"," amp live-sync --apply T-5928a90d-d53b-488f-a829-4e36442142ee"," amp live-sync https://ampcode.com/threads/T-5928a90d-d53b-488f-a829-4e36442142ee"].join(`
7271
+ `),!1}}async function w25(A,Q,$){let B=await Q.get("apiKey",A);if(!B)throw new n1("No Amp API key found. Run `amp login` first.",1);let D=t55("curl",["-H",`Authorization: Bearer ${B}`,...$],{stdio:"inherit"});process.exitCode=await new Promise((J,F)=>{D.on("error",F),D.on("close",(Y)=>J(Y??1))})}function C25(A){let Q=new DN().name("amp").description("AI-powered coding assistant").option("--visibility <visibility>","Set thread visibility (private, public, workspace, group)").configureOutput({writeErr:()=>{}});Q.exitOverride((z)=>{if(z.code==="commander.help"||z.code==="commander.version"||z.exitCode===0)zj(),process.exit(0);let W=z.originalError??z;rv4(W)}),Od4(Q,{version:"0.0.1779313683-gf89f27",buildTimestamp:"2026-05-20T21:52:35.567Z",buildType:"release"}),Q.addHelpText("after",Kb4()),Q.configureHelp({formatHelp:zb4}),Q.command("logout").description("Log out by removing stored API key").action(async(z,W)=>{let H=W.optsWithGlobals(),q=await d3(H);await v25(q)}),Q.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(z,W)=>{let H=W.optsWithGlobals(),q=await d3(H);await T25(q,await i51(H,q.settings))}),nv4(Q,d3);let B=Q.command("internal",{hidden:!0}).description("Internal commands").command("curl [args...]").description("Internal: run curl with the current Amp API key as a bearer token").allowUnknownOption(!0).allowExcessArguments(!0).action(async(...z)=>{let W=z.find((w)=>typeof w==="object"&&w!==null&&typeof w.optsWithGlobals==="function")??B,H=z.filter((w)=>w!==W).flatMap((w)=>Array.isArray(w)?w:typeof w==="string"?[w]:[]),q=W.optsWithGlobals(),N=await d3(q);await w25(N.ampURL,N.secrets,H),process.exit(process.exitCode??0)});Q.command("git-credential-helper [action]",{hidden:!0}).summary("Git credential helper for GitHub").description("Internal: implements the git credential helper protocol. Used inside sandboxes to authenticate git operations with GitHub.").action(async(z,W,H)=>{let q=H.optsWithGlobals(),N=await d3(q);await yx4(z??"get",N.ampURL,N.secrets),process.exit(process.exitCode??0)}),Q.command("sign-commit",{hidden:!0}).summary("Git commit signing helper").description("Internal: implements the gpg signing interface for git commit signing. Used inside sandboxes as gpg.program.").allowUnknownOption().action(async(z,W)=>{let H=W.optsWithGlobals(),q=await d3(H);await xx4(q.ampURL,q.secrets),process.exit(process.exitCode??0)}),Q.command("keyboard-tester",{hidden:!0}).summary("Keyboard input tester").description("Internal: stream parsed terminal input events as JSONL.").option("--raw","Log raw incoming terminal bytes before parsing").action(async(z)=>{await vh4({raw:z.raw===!0}),process.exit(process.exitCode??0)}),Q.command("live-sync [threadIDOrURL]",{hidden:!0}).summary("Mirror live DTW thread changes into the current checkout").description("Experimental: watch a v2 thread URL or ID and mirror its live working-tree changes into your local checkout, or apply the current snapshot once and exit.").addHelpText("after",["","Examples:"," amp live-sync T-5928a90d-d53b-488f-a829-4e36442142ee"," amp live-sync --apply T-5928a90d-d53b-488f-a829-4e36442142ee"," amp live-sync https://ampcode.com/threads/T-5928a90d-d53b-488f-a829-4e36442142ee"].join(`
7272
7272
  `)).option("--apply <threadIDOrURL>","Apply the current DTW thread snapshot once and exit").option("--checkout","Automatically check out the thread commit when it differs").option("--skip-checkout","Skip the startup checkout prompt when commits differ").action(async(z,W,H)=>{if(z&&W.apply)throw new n1("Choose either a positional thread ID/URL or --apply <thread-id>, not both.",1);let q=W.apply??z;if(!q||q.trim().length===0)$3.write(`live-sync watches a v2 thread and mirrors its live changes locally. Use --apply <thread-id> to materialize the current snapshot once and exit.
7273
7273
 
7274
7274
  `),H.outputHelp(),process.exit(0);let N=k8(q)??DB(q),w=H.optsWithGlobals(),O=await d3(w);r8(H,w);let L=await o2(O,w),j=!1;try{if(W.checkout&&W.skipCheckout)throw new n1("Choose either --checkout or --skip-checkout, not both.",1);if(lE(L.serverStatus))throw qe(L.serverStatus,O.ampURL);let k=AA(L.serverStatus)?L.serverStatus.features:void 0;if(!we(k,S$.V2))throw new n1("live-sync is not enabled for your user",1);await Cg4({ampURL:O.ampURL,threadId:N,configService:L.configService,threadService:L.threadService,apiKey:process.env.AMP_API_KEY,applyOnce:typeof W.apply==="string",checkoutMode:W.checkout?"always":W.skipCheckout?"never":"prompt",promptForYesNo:wZ0}),j=!0}finally{if(await L.asyncDispose(),j)process.exit(0)}});let D=async(z,W,H)=>{O20({storage:W.settings,secretStorage:W.secrets,workspaceRoot:h0.of(i0.file(process.cwd())),defaultAmpURL:W.ampURL,homeDir:Fz0,userConfigDir:JQ1});let q={...W,executeMode:!1};await Yz0(q,{...z,openThreadSwitcher:!0},H,A)},J=Q.command("threads").alias("t").alias("thread").summary("Manage threads").description("Thread management commands. When no subcommand is provided, defaults to listing threads.").option("--include-archived","Include archived threads in the list").action(async(z,W)=>{let H=W.optsWithGlobals(),q=await d3(H);await Z76(H,q,W)});J.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(z,W)=>{let H=W.optsWithGlobals(),q=await d3(H);await l25(H,q,W)}),J.command("continue [threadIDOrURLs...]").alias("c").summary("Continue an existing thread").description("Continue an existing thread by resuming the conversation. By default, interactive mode shows a picker. Use --last to continue the last thread for the current mode directly. When multiple thread are given, all are resumed and the first is shown in the foreground.").option("--last","Continue the last thread for the current mode directly").option("--pick","Pick a thread interactively from a list (DEPRECATED: picker is now the default)").action(async(z,W,H)=>{let q=H.optsWithGlobals(),N=await d3(q),w=Array.isArray(z)?z:[];if(W.pick)H$.write(`${t0.yellow("Warning:")} The --pick flag is deprecated. The picker is now shown by default.
@@ -7301,8 +7301,8 @@ ${O}
7301
7301
  `))}),W.args.length>0)q25(q,W);await Yz0(q,H,W,A)}),ib4(Q),Q}async function Ne(A,Q){await zQ(($)=>Fy($,A,Q))}async function F76(A,Q,$){let B=Date.now(),[D,J]=await Promise.all([t4.getThreadLinkInfo({thread:A},{config:Q}),$]);if(P.getChild("fetchAndStartThread").info(`Ownership check in ${Date.now()-B}ms`),D.ok){let F=D.result.creatorUserID;if(F&&F!==J&&!process.env.AMP_RESUME_OTHER_USER_THREADS_INSECURE)throw new n1(`Cannot resume thread created by another user.
7302
7302
 
7303
7303
  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.`)}}async function z76(A){if(A.streamJsonInput)return{userInput:"",stdinInput:null};if(typeof A.execute==="string"){let Q=(await vG0()).trimEnd();return{userInput:A.execute,stdinInput:Q||null}}return{userInput:(await vG0()).trimEnd(),stdinInput:null}}function I76(A,Q,$){if(A.streamJson&&!Q)throw new n1("The --stream-json flag requires --execute mode",1,'Use: amp --execute "your message" --stream-json');if(A.streamJsonInput&&!Q)throw new n1("The --stream-json-input flag requires --execute mode",1,"Use: amp --execute --stream-json --stream-json-input");if(A.streamJsonInput&&!A.streamJson)throw new n1("The --stream-json-input flag requires --stream-json",1,"Use: amp --execute --stream-json --stream-json-input");if(A.stats&&A.streamJson)throw new n1("The --stats and --stream-json flags are mutually exclusive output formats",1,'Use one or the other: amp --execute "your message" --stats OR amp --execute "your message" --stream-json');if(A.stats&&!Q)throw new n1("The --stats flag requires --execute mode",1,'Use: amp --execute "your message" --stats');if(A.archive&&!Q)throw new n1("The --archive flag requires --execute mode",1,'Use: amp --execute "your message" --archive');if(A.streamJsonInput&&typeof A.execute==="string"&&A.execute.trim()!=="")throw new n1("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"},{"type":"image","source":{"type":"base64","media_type":"image/png","data":"..."}}]}}' | amp --execute --stream-json --stream-json-input`);if(Q&&$===""&&!A.streamJsonInput&&!A.headless)throw new n1("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"
7304
- Or pipe via stdin: echo "your message" | amp --execute`)}function M25(){b34([C20.parse({tool:"*",action:"allow"})]),X34({bypass:!0})}function L25(A){if(A.threadId&&!P9(A.threadId))delete A.threadId}async function Yz0(A,Q,$,B){if(Q.headless)return O25(A,Q,$);let D=await o2(A,Q),J=await D.serverStatusPromise,F=AA(J)&&we(J.features,S$.THREAD_ACTORS_TUI),Y=F&&!Q.takeMeBack;if(Q.showWelcome&&Q.hideWelcome)throw await D.asyncDispose(),new n1("Cannot use --show-welcome and --hide-welcome together",1);if(Q.showWelcome&&!F)throw await D.asyncDispose(),new n1("--show-welcome is only available with the new Amp CLI feature flag",1);if(Y){let E=!A.executeMode&&await z25();return M25(),L25(Q),j25(A,Q,$,D,{showNpmMigrationWelcome:E})}else{if(Q.threadId&&P9(Q.threadId)){let E=await t4.getThreadLinkInfo({thread:Q.threadId},{config:D.configService}).catch(()=>null);if(E?.ok&&E.result.usesThreadActors)throw await D.asyncDispose(),new n1(`Thread ${Q.threadId} was created with the Neo TUI and cannot be continued in the legacy CLI.`,1,"Re-run without --take-me-back to continue this thread.")}return R25(A,Q,$,B,{dependencies:D})}}async function O25(A,Q,$){let B=(W,H)=>{let q=Number(process.hrtime.bigint()-H)/1e6,N=Ds0();P.info("Startup phase",{phase:W,phaseMs:Math.round(q),sinceMainMs:N===null?void 0:Math.round(N)})};r8($,Q);let D=process.hrtime.bigint(),J=await o2(A,Q);B("runMainThread:createThreadDependencies",D);let{serverStatus:F}=J;if(lE(F))throw qe(F,A.ampURL);let Y=AA(F)?F:null,E=Y?.user.email;await DQ1($,Q,F);let Z=TI(F),U=Ux(Q,Z);if(U instanceof Error)P3(U.message);if(Y&&!tM(Q.mode,E))throw new n1(`Agent mode '${Q.mode}' is only available for Amp employees`,1);if(process.env.AMP_EXECUTOR!=="1"&&(!E||!p7(E)))throw new n1("Headless executor mode is only available for Amp employees",1);uY0();let G=await J.secretStorage.get("apiKey",A.ampURL);if(!G)throw new n1("API key required for headless mode. Please run `amp login` first.",1);let V=typeof Q.headless==="string"&&Q.headless!=="true"?Q.headless:void 0;if(V&&!P9(V))throw new n1(`Invalid thread ID: ${V}`,1);let K=V?void 0:await p25({dependencies:J,apiKey:G,visibility:U??void 0}),I=V??K?.threadId;if(!I)throw new n1("Failed to resolve headless thread ID",1);let z=await rx4(I);if(z.status==="already-running")await J.asyncDispose(),await vz(),process.exit(0);try{await mx4({ampURL:A.ampURL,apiKey:G,workspaceRoot:process.cwd(),threadId:I,ownerUserId:K?.ownerUserId,threadVersion:K?.threadVersion,agentMode:K?.agentMode,initialToolDiscovery:Promise.all([J.mcpService.initialized,J.toolboxService.initialized,J.pluginService.initialized]).then(()=>{return}),configService:J.configService,mcpService:J.mcpService,toolService:J.toolService,skillService:J.skillService,pluginService:J.pluginService,pluginPlatform:J.headlessPluginPlatform})}finally{await z.release(),await J.asyncDispose()}await vz(),process.exit(0)}async function j25(A,Q,$,B,D){let{userInput:J,stdinInput:F}=await z76(Q),Y=!!Q.streamJson||!!Q.streamJsonThinking;I76({...Q,streamJson:Y},A.executeMode,J),r8($,Q),Sv4(),uY0();let E=Q.threadId,Z=Q.resumeThreadIDs??(E?[E]:[]),U=Q.observe?k8(Q.observe)??DB(Q.observe):void 0,X=await B.serverStatusPromise;if(lE(X))throw qe(X,A.ampURL);let G=TI(X),V=Ux(Q,G);if(V instanceof Error)P3(V.message);let K=null,I=async()=>{let H=B.consumeDraftNewThreadVisibility();if(H!==null)return H;return K??=(async()=>{let q=await Qo(A.settings,process.cwd(),G,V);if(q instanceof Error)P3(q.message);return q})(),K},z=await B.secretStorage.get("apiKey",A.ampURL);if(!z)throw new n1("API key required. Please run `amp login` first.",1);let W=AA(X)&&p7(X.user.email);if(A.executeMode){if(Z.length>1)throw new n1("Execute mode can only resume one thread.",1);g01(B.mcpService,A.settings);try{let H=Jz0($,Q),q=await rz(),N=E?H:MZ0({agentMode:Q.mode,explicitEffort:H,sessionState:q}),w=E?void 0:LZ0(await By(B.configService),{agentMode:Q.mode,explicitEffort:H,sessionState:q}),O=E?void 0:await I(),L=await Mx4({apiKey:z,ampURL:A.ampURL,workspaceRoot:process.cwd(),dependencies:B,userInput:J,stdinInput:F,stats:!!Q.stats,streamJson:Y,streamJsonThinking:!!Q.streamJsonThinking,streamJsonInput:!!Q.streamJsonInput,stdin:process.stdin,agentMode:Q.mode,reasoningEffort:N,labels:Q.label,initialThreadID:E,initialThreadMeta:O,initialSettings:w});if(await Ne(L,"execute"),Q.archive)await B.threadService.archive(L,!0)}finally{await B.asyncDispose()}await vz(),process.exit(0)}else{let H=Jz0($,Q),q=D.showNpmMigrationWelcome?"npm-migration":"intro",N=cE0("0.0.1779296280-g014378",B.settingsStorage,{startDelayMs:3000}),w=new CZ0(B.mcpService,A.settings.getWorkspaceRootPath()),O=Ji(B.configService),L=new ft(B.fuzzyServer),j=process.cwd();await U06({ampURL:A.ampURL,apiKey:z,rivetEndpoint:process.env.RIVET_PUBLIC_ENDPOINT??rJ(A.ampURL),configService:B.configService,toolService:B.toolService,pluginPlatform:B.pluginPlatform,pluginService:B.pluginService,skillService:B.skillService,mcpService:B.mcpService,readFileSystemDirectory:({uri:k})=>bf({workspaceRoot:j},k),completionBuilder:L,updateService:N,workspaceRoot:j,listThreads:()=>O.listThreads(),getThreadFromServer:(k)=>O.getThread(k),toolboxes:B.toolboxService.toolboxes,isInternalUser:W,settingsFilePath:B.settingsStorage.getSettingsFilePath(),workspaceSettingsFilePath:B.settingsStorage.getWorkspaceSettingsPath(),mcpTrustHandler:w,setActiveThreadID:(k)=>B.activeThread$.next(k),dispose:()=>{return w.dispose(),N.dispose(),B.asyncDispose()}},{initialThreadIDs:U?[U]:Z,initialUserInput:J||void 0,getDefaultNewThreadVisibility:I,onFirstFrame:Q.ide?G76:void 0,openThreadPickerOnStart:Q.openThreadSwitcher,observerOnly:!!U,splashOrbVisualStyle:"neo",hideNeoWelcome:!!Q.hideWelcome,showNeoWelcome:Q.showWelcome,neoWelcomeVariant:q,initialAgentMode:$.getOptionValueSourceWithGlobals("mode")==="cli"?Q.mode:void 0,initialReasoningEffort:H}),process.exit(0)}}async function R25(A,Q,$,B,D){let J=process.hrtime.bigint(),F=($0,j0)=>{let Q0=Number(process.hrtime.bigint()-j0)/1e6,M0=Ds0();P.info("Startup phase",{phase:$0,phaseMs:Math.round(Q0),sinceMainMs:M0===null?void 0:Math.round(M0)})},{userInput:Y,stdinInput:E}=await z76(Q),Z=!!Q.streamJson||!!Q.streamJsonThinking;I76({...Q,streamJson:Z},A.executeMode,Y),r8($,Q);let U=process.hrtime.bigint(),X=D?.dependencies??await o2(A,Q),G=X.hasAPIKeyAtStartup,V=X.serverStatus==="pending";if(P.info("Interactive auth startup mode",{deferInteractiveAuth:V,hasAPIKeyAtStartup:G,executeMode:A.executeMode,headless:Boolean(Q.headless)}),!D)F("runMainThread:createThreadDependencies",U);let{serverStatus:K}=X;if(!V&&lE(K))throw qe(K,A.ampURL);let I=AA(K)?K:null,z=I?.user.email,W=!!(z&&p7(z));if(W)uY0();if(!V)await DQ1($,Q,K);let H=TI(K),q=H?.features??[],N=H?.team??null,w=Ux(Q,H);if(w instanceof Error)P3(w.message);if(I&&!tM(Q.mode,z))throw new n1(`Agent mode '${Q.mode}' is only available for Amp employees`,1);let O=Q.threadId&&P9(Q.threadId)?Q.threadId:void 0;U=process.hrtime.bigint();let L=await Ez0(X);F("runMainThread:createWorkerDeps",U);let j=A.executeMode?void 0:async($0)=>Ne($0,"interactive"),k={threadService:X.threadService,workerDeps:L,createThread:async($0)=>{let j0=V?await X.serverStatusPromise:K,Q0=await Qo(A.settings,process.cwd(),TI(j0),w);if(Q0 instanceof Error)P3(Q0.message);return _91(L,{threadMeta:Q0,agentMode:$0??Q.mode,onFirstAssistantMessage:j})},validateThreadOwnership:async($0,j0)=>{if(j0?.nonBlockingOwnershipCheck){F76($0,X.configService,X.viewerUserIDPromise).catch((Q0)=>{if(Q0 instanceof n1){if(j0.onOwnershipError){j0.onOwnershipError(Q0,$0);return}Sz(Q0,$0);return}P.warn("Failed to validate thread ownership in CLI, allowing to open",{error:Q0})});return}try{await F76($0,X.configService,X.viewerUserIDPromise)}catch(Q0){if(Q0 instanceof n1)throw Q0;P.warn("Failed to validate thread ownership in CLI, allowing to open",{error:Q0})}},switchThreadVisibility:w,switchThreadAgentMode:Q.mode,onFirstAssistantMessage:j,handleError:Sz},_=async()=>{try{return v56(k,Q.threadId,{nonBlockingOwnershipCheck:Q.nonBlockingThreadOwnershipCheck})}catch($0){if($0 instanceof n1)throw $0;throw await Sz($0,Q.threadId),Error("handleError should have called process.exit()")}},f=(async()=>{if(V){P.info("Skipping initial free tier status fetch until auth is complete");return}try{let $0=await X.configService.getLatest(),j0=Yd($0),Q0=await t4.getUserFreeTierStatus({},{config:X.configService,signal:AbortSignal.timeout(j0)});if(Q0.ok)return P.info("User free tier status:",Q0),Q0.result;return}catch($0){P.error("Failed to fetch free tier status:",$0);return}})(),b=!A.executeMode?new Q21:null,v,y=null;if(b)v=b,y=(async()=>{let $0=V?await X.serverStatusPromise:X.serverStatus;if(lE($0))throw qe($0,A.ampURL);await DQ1($,Q,$0);let j0=process.hrtime.bigint(),Q0=await _();if(F("runMainThread:createThreadPool",j0),b.attach(Q0),Y){let M0=await k1(Q0.threadHandles$);if(!M0)throw new n1("No active thread is available yet.",1);await M0.sendMessage({content:[{type:"text",text:Y}]})}})(),y.catch(async($0)=>{let j0=$0 instanceof Error?$0:Error(String($0));b.setInitError(j0),await Sz($0,Q.threadId)});else U=process.hrtime.bigint(),v=await _(),F("runMainThread:createThreadPool",U);let p=Q.notifications!==void 0?Q.notifications:!A.executeMode;U=process.hrtime.bigint();let c=await X.configService.getLatest();if(F("runMainThread:configService.getLatest",U),U=process.hrtime.bigint(),H16({configService:X.configService,threadService:X.threadService,threadPool:v,config:c,useNotifications:p}),F("runMainThread:createLegacyTuiNotificationService",U),A.executeMode){g01(X.mcpService,A.settings);let $0=Jz0($,Q),j0=await rz(),Q0=O?$0:MZ0({agentMode:Q.mode,explicitEffort:$0,sessionState:j0}),M0={userInput:Y,stdinInput:E,dependencies:X,streamJson:Z,streamJsonInput:!!Q.streamJsonInput,streamJsonThinking:!!Q.streamJsonThinking,stats:!!Q.stats,ampURL:A.ampURL,isInternalUser:W,agentMode:Q.mode,reasoningEffort:Q0,labels:Q.label},n=await Wk4({threadPool:v,...M0});if(await Ne(n,"execute"),Q.archive)await X.threadService.archive(n,!0);await X.asyncDispose(),process.exit(0)}let g=!1,i=!1;if(Q.jetbrains||Q.ide){await f20();let $0=await oE({jetbrainsOnly:Q.jetbrains});if($0.length===0){if(Q.jetbrains)g=!await X.configService.get("jetbrains.skipInstall")}else if($0.length===1){let j0=$0[0];if(j0)o5.selectConfig(j0)}else i=!0}U=process.hrtime.bigint();let r=cE0("0.0.1779296280-g014378",X.settingsStorage,{startDelayMs:3000});F("runMainThread:createUpdateService",U),U=process.hrtime.bigint();let A0=new CZ0(X.mcpService,A.settings.getWorkspaceRootPath());if(F("runMainThread:createMcpTrustHandler",U),Y&&A.executeMode){let $0=await k1(v.threadHandles$);if(!$0)throw new n1("No active thread is available yet.",1);await $0.sendMessage({content:[{type:"text",text:Y}]})}U=process.hrtime.bigint();let I0=await rz();F("runMainThread:loadSessionState",U),P.info("Loaded session state:",I0);let E0=Jz0($,Q),W0={...I0,launchCount:I0.launchCount+1,lastReasoningEffortByMode:E0?{...I0.lastReasoningEffortByMode,[Q.mode]:E0}:I0.lastReasoningEffortByMode};zQ(($0)=>({...$0,launchCount:$0.launchCount+1}));try{if(U=process.hrtime.bigint(),await l16({history:new mo,fuzzyServer:X.fuzzyServer,settingsStorage:X.settingsStorage,threadService:X.threadService,skillService:X.skillService,configService:X.configService,secretStorage:X.secretStorage,internalAPIClient:t4,threadPool:v,createSystemPromptDeps:async()=>V76(X),ideClient:o5,mcpService:X.mcpService,toolboxService:X.toolboxService,mcpTrustHandler:A0,updateService:r,pluginPlatform:X.pluginPlatform,pluginService:X.pluginService},{initialServerStatus:X.serverStatus,stdout:process.stdout,hasAPIKeyAtStartup:X.hasAPIKeyAtStartup,ampURL:A.ampURL,startupThreadID:O,showJetBrainsInstaller:g,showIdePickerHint:i,openThreadSwitcher:Q.openThreadSwitcher,jetbrainsMode:Q.jetbrains,clientId:B25,logFile:{path:B},sessionState:W0,freeTierStatusPromise:f,workspace:N??null,features:q,isInternalUser:W,initialAgentMode:$.getOptionValueSourceWithGlobals("mode")==="cli"?Q.mode:void 0,splashOrbVisualStyle:Q.neoOrb?"neo":"classic",buildTimestamp:"2026-05-20T17:03:06.980Z"},($0)=>new E21({...$0,threadPool:$0.threadPool},(j0)=>new P91({...j0,threadState:j0.threadState}))),F("runMainThread:mountApp-returned",U),y)await y}finally{await v.dispose().catch(($0)=>{P.error("Failed to dispose thread pool during shutdown",$0)})}await X.asyncDispose(),F("runMainThread:dependencies.asyncDispose",J),process.exit(0)}async function d3(A){if(P.info("Initializing CLI context",{argv:process.argv,nodeEnv:"production",hasAmpURL:Boolean(process.env.AMP_URL),hasAmpAPIKey:Boolean(process.env.AMP_API_KEY),hasSettingsFile:Boolean(process.env.AMP_SETTINGS_FILE)}),A.interactive)H$.write(`Warning: --interactive flag is deprecated. Interactive mode is now the default unless --execute is used or output is redirected.
7305
- `);let Q=!!A.execute||!process.stdout.isTTY&&!A.streamJson,$=process.stdout.isTTY&&process.stderr.isTTY;P.info("Execution mode resolved",{executeMode:Q,stdoutTTY:process.stdout.isTTY,stderrTTY:process.stderr.isTTY,streamJson:A.streamJson,executeFlag:A.execute});let B=await x$4({get:async(Y)=>{if(Y!==Kc)return;try{let E=await X76(BQ1,"utf-8");return JSON.parse(E).installationID}catch{return}},set:async(Y,E)=>{if(Y!==Kc)return;await e55(He.dirname(BQ1),{recursive:!0}),await A25(BQ1,JSON.stringify({installationID:E},null,2),{mode:384})}},{clientType:"cli",platform:e90()});d14(B);let D=await d06({...A,workspaceTrust:{current:!0,changes:Ed},getHook:process.env.AMP_URL?(Y,E)=>{if(Y==="url")return Promise.resolve(process.env.AMP_URL);return E()}:void 0});if(A.mcpConfig){let Y=await pg4(A.mcpConfig);D=cg4(D,Y)}let J=He.dirname(D.getSettingsFilePath());Su4(id,J),D=Ie1(D);let F=await D.get("url","admin")??await D.get("url","global");if(!F)F=a7;if(P.info("Resolved Amp URL",{ampURL:F,settingsFile:D.getSettingsFilePath(),workspaceRoot:D.getWorkspaceRootPath()}),!BH(F))P.info("Targeting custom Amp server",{ampURL:F});return{executeMode:Q,isTTY:$,ampURL:F,settings:D,secrets:y06(await i51(A,D))}}function P25(A){let Q={};for(let $=0;$<A.length;$++){let B=A[$];if(B?.startsWith("--")){let J=B.slice(2).replace(/-([a-z])/g,(Y,E)=>E.toUpperCase()),F=A[$+1];if(F&&!F.startsWith("--"))Q[J]=F,$++}}return Q}function u25(A,Q){let $=A.includes("--headless")||A.some((D)=>D.startsWith("--headless=")),B=He.resolve(Q.logFile??process.env.AMP_LOG_FILE??($?$25:Ao));return{logLevel:Q.logLevel??process.env.AMP_LOG_LEVEL??"info",logFile:B}}async function _25(){Pv4();let A=P25(process.argv),Q=u25(process.argv,A),$=fv4(Q);wY0("silent");let B=process.argv.includes("--no-color"),D=process.argv.includes("--color"),J=process.stdout.isTTY&&process.stderr.isTTY;if(B||!D&&!J)t0.level=0;if(J25(P),P.info("Starting Amp CLI.",{version:"0.0.1779296280-g014378",buildTimestamp:"2026-05-20T17:03:06.980Z"}),process.platform==="win32"&&yj())gb4();if(parseInt(process.version.slice(1).split(".")[0]??"")<20)throw new n1(d9.nodeVersion(process.version),1,"Please upgrade your Node.js installation from https://nodejs.org");await C25($).parseAsync(process.argv)}vu4().startActiveSpan("main",async(A)=>{process.on("exit",()=>A.end()),await _25().catch(Sz)});async function T25(A,Q){let $=A.ampURL.includes("localhost")||A.ampURL.includes("127.0.0.1");if(process.env.AMP_URL&&!$)await A.settings.set("url",process.env.AMP_URL,"global"),$3.write(`Saving custom server URL to settings: ${process.env.AMP_URL}
7304
+ Or pipe via stdin: echo "your message" | amp --execute`)}function M25(){b34([C20.parse({tool:"*",action:"allow"})]),X34({bypass:!0})}function L25(A){if(A.threadId&&!P9(A.threadId))delete A.threadId}async function Yz0(A,Q,$,B){if(Q.headless)return O25(A,Q,$);let D=await o2(A,Q),J=await D.serverStatusPromise,F=AA(J)&&we(J.features,S$.THREAD_ACTORS_TUI),Y=F&&!Q.takeMeBack;if(Q.showWelcome&&Q.hideWelcome)throw await D.asyncDispose(),new n1("Cannot use --show-welcome and --hide-welcome together",1);if(Q.showWelcome&&!F)throw await D.asyncDispose(),new n1("--show-welcome is only available with the new Amp CLI feature flag",1);if(Y){let E=!A.executeMode&&await z25();return M25(),L25(Q),j25(A,Q,$,D,{showNpmMigrationWelcome:E})}else{if(Q.threadId&&P9(Q.threadId)){let E=await t4.getThreadLinkInfo({thread:Q.threadId},{config:D.configService}).catch(()=>null);if(E?.ok&&E.result.usesThreadActors)throw await D.asyncDispose(),new n1(`Thread ${Q.threadId} was created with the Neo TUI and cannot be continued in the legacy CLI.`,1,"Re-run without --take-me-back to continue this thread.")}return R25(A,Q,$,B,{dependencies:D})}}async function O25(A,Q,$){let B=(W,H)=>{let q=Number(process.hrtime.bigint()-H)/1e6,N=Ds0();P.info("Startup phase",{phase:W,phaseMs:Math.round(q),sinceMainMs:N===null?void 0:Math.round(N)})};r8($,Q);let D=process.hrtime.bigint(),J=await o2(A,Q);B("runMainThread:createThreadDependencies",D);let{serverStatus:F}=J;if(lE(F))throw qe(F,A.ampURL);let Y=AA(F)?F:null,E=Y?.user.email;await DQ1($,Q,F);let Z=TI(F),U=Ux(Q,Z);if(U instanceof Error)P3(U.message);if(Y&&!tM(Q.mode,E))throw new n1(`Agent mode '${Q.mode}' is only available for Amp employees`,1);if(process.env.AMP_EXECUTOR!=="1"&&(!E||!p7(E)))throw new n1("Headless executor mode is only available for Amp employees",1);uY0();let G=await J.secretStorage.get("apiKey",A.ampURL);if(!G)throw new n1("API key required for headless mode. Please run `amp login` first.",1);let V=typeof Q.headless==="string"&&Q.headless!=="true"?Q.headless:void 0;if(V&&!P9(V))throw new n1(`Invalid thread ID: ${V}`,1);let K=V?void 0:await p25({dependencies:J,apiKey:G,visibility:U??void 0}),I=V??K?.threadId;if(!I)throw new n1("Failed to resolve headless thread ID",1);let z=await rx4(I);if(z.status==="already-running")await J.asyncDispose(),await vz(),process.exit(0);try{await mx4({ampURL:A.ampURL,apiKey:G,workspaceRoot:process.cwd(),threadId:I,ownerUserId:K?.ownerUserId,threadVersion:K?.threadVersion,agentMode:K?.agentMode,initialToolDiscovery:Promise.all([J.mcpService.initialized,J.toolboxService.initialized,J.pluginService.initialized]).then(()=>{return}),configService:J.configService,mcpService:J.mcpService,toolService:J.toolService,skillService:J.skillService,pluginService:J.pluginService,pluginPlatform:J.headlessPluginPlatform})}finally{await z.release(),await J.asyncDispose()}await vz(),process.exit(0)}async function j25(A,Q,$,B,D){let{userInput:J,stdinInput:F}=await z76(Q),Y=!!Q.streamJson||!!Q.streamJsonThinking;I76({...Q,streamJson:Y},A.executeMode,J),r8($,Q),Sv4(),uY0();let E=Q.threadId,Z=Q.resumeThreadIDs??(E?[E]:[]),U=Q.observe?k8(Q.observe)??DB(Q.observe):void 0,X=await B.serverStatusPromise;if(lE(X))throw qe(X,A.ampURL);let G=TI(X),V=Ux(Q,G);if(V instanceof Error)P3(V.message);let K=null,I=async()=>{let H=B.consumeDraftNewThreadVisibility();if(H!==null)return H;return K??=(async()=>{let q=await Qo(A.settings,process.cwd(),G,V);if(q instanceof Error)P3(q.message);return q})(),K},z=await B.secretStorage.get("apiKey",A.ampURL);if(!z)throw new n1("API key required. Please run `amp login` first.",1);let W=AA(X)&&p7(X.user.email);if(A.executeMode){if(Z.length>1)throw new n1("Execute mode can only resume one thread.",1);g01(B.mcpService,A.settings);try{let H=Jz0($,Q),q=await rz(),N=E?H:MZ0({agentMode:Q.mode,explicitEffort:H,sessionState:q}),w=E?void 0:LZ0(await By(B.configService),{agentMode:Q.mode,explicitEffort:H,sessionState:q}),O=E?void 0:await I(),L=await Mx4({apiKey:z,ampURL:A.ampURL,workspaceRoot:process.cwd(),dependencies:B,userInput:J,stdinInput:F,stats:!!Q.stats,streamJson:Y,streamJsonThinking:!!Q.streamJsonThinking,streamJsonInput:!!Q.streamJsonInput,stdin:process.stdin,agentMode:Q.mode,reasoningEffort:N,labels:Q.label,initialThreadID:E,initialThreadMeta:O,initialSettings:w});if(await Ne(L,"execute"),Q.archive)await B.threadService.archive(L,!0)}finally{await B.asyncDispose()}await vz(),process.exit(0)}else{let H=Jz0($,Q),q=D.showNpmMigrationWelcome?"npm-migration":"intro",N=cE0("0.0.1779313683-gf89f27",B.settingsStorage,{startDelayMs:3000}),w=new CZ0(B.mcpService,A.settings.getWorkspaceRootPath()),O=Ji(B.configService),L=new ft(B.fuzzyServer),j=process.cwd();await U06({ampURL:A.ampURL,apiKey:z,rivetEndpoint:process.env.RIVET_PUBLIC_ENDPOINT??rJ(A.ampURL),configService:B.configService,toolService:B.toolService,pluginPlatform:B.pluginPlatform,pluginService:B.pluginService,skillService:B.skillService,mcpService:B.mcpService,readFileSystemDirectory:({uri:k})=>bf({workspaceRoot:j},k),completionBuilder:L,updateService:N,workspaceRoot:j,listThreads:()=>O.listThreads(),getThreadFromServer:(k)=>O.getThread(k),toolboxes:B.toolboxService.toolboxes,isInternalUser:W,settingsFilePath:B.settingsStorage.getSettingsFilePath(),workspaceSettingsFilePath:B.settingsStorage.getWorkspaceSettingsPath(),mcpTrustHandler:w,setActiveThreadID:(k)=>B.activeThread$.next(k),dispose:()=>{return w.dispose(),N.dispose(),B.asyncDispose()}},{initialThreadIDs:U?[U]:Z,initialUserInput:J||void 0,getDefaultNewThreadVisibility:I,onFirstFrame:Q.ide?G76:void 0,openThreadPickerOnStart:Q.openThreadSwitcher,observerOnly:!!U,splashOrbVisualStyle:"neo",hideNeoWelcome:!!Q.hideWelcome,showNeoWelcome:Q.showWelcome,neoWelcomeVariant:q,initialAgentMode:$.getOptionValueSourceWithGlobals("mode")==="cli"?Q.mode:void 0,initialReasoningEffort:H}),process.exit(0)}}async function R25(A,Q,$,B,D){let J=process.hrtime.bigint(),F=($0,j0)=>{let Q0=Number(process.hrtime.bigint()-j0)/1e6,M0=Ds0();P.info("Startup phase",{phase:$0,phaseMs:Math.round(Q0),sinceMainMs:M0===null?void 0:Math.round(M0)})},{userInput:Y,stdinInput:E}=await z76(Q),Z=!!Q.streamJson||!!Q.streamJsonThinking;I76({...Q,streamJson:Z},A.executeMode,Y),r8($,Q);let U=process.hrtime.bigint(),X=D?.dependencies??await o2(A,Q),G=X.hasAPIKeyAtStartup,V=X.serverStatus==="pending";if(P.info("Interactive auth startup mode",{deferInteractiveAuth:V,hasAPIKeyAtStartup:G,executeMode:A.executeMode,headless:Boolean(Q.headless)}),!D)F("runMainThread:createThreadDependencies",U);let{serverStatus:K}=X;if(!V&&lE(K))throw qe(K,A.ampURL);let I=AA(K)?K:null,z=I?.user.email,W=!!(z&&p7(z));if(W)uY0();if(!V)await DQ1($,Q,K);let H=TI(K),q=H?.features??[],N=H?.team??null,w=Ux(Q,H);if(w instanceof Error)P3(w.message);if(I&&!tM(Q.mode,z))throw new n1(`Agent mode '${Q.mode}' is only available for Amp employees`,1);let O=Q.threadId&&P9(Q.threadId)?Q.threadId:void 0;U=process.hrtime.bigint();let L=await Ez0(X);F("runMainThread:createWorkerDeps",U);let j=A.executeMode?void 0:async($0)=>Ne($0,"interactive"),k={threadService:X.threadService,workerDeps:L,createThread:async($0)=>{let j0=V?await X.serverStatusPromise:K,Q0=await Qo(A.settings,process.cwd(),TI(j0),w);if(Q0 instanceof Error)P3(Q0.message);return _91(L,{threadMeta:Q0,agentMode:$0??Q.mode,onFirstAssistantMessage:j})},validateThreadOwnership:async($0,j0)=>{if(j0?.nonBlockingOwnershipCheck){F76($0,X.configService,X.viewerUserIDPromise).catch((Q0)=>{if(Q0 instanceof n1){if(j0.onOwnershipError){j0.onOwnershipError(Q0,$0);return}Sz(Q0,$0);return}P.warn("Failed to validate thread ownership in CLI, allowing to open",{error:Q0})});return}try{await F76($0,X.configService,X.viewerUserIDPromise)}catch(Q0){if(Q0 instanceof n1)throw Q0;P.warn("Failed to validate thread ownership in CLI, allowing to open",{error:Q0})}},switchThreadVisibility:w,switchThreadAgentMode:Q.mode,onFirstAssistantMessage:j,handleError:Sz},_=async()=>{try{return v56(k,Q.threadId,{nonBlockingOwnershipCheck:Q.nonBlockingThreadOwnershipCheck})}catch($0){if($0 instanceof n1)throw $0;throw await Sz($0,Q.threadId),Error("handleError should have called process.exit()")}},f=(async()=>{if(V){P.info("Skipping initial free tier status fetch until auth is complete");return}try{let $0=await X.configService.getLatest(),j0=Yd($0),Q0=await t4.getUserFreeTierStatus({},{config:X.configService,signal:AbortSignal.timeout(j0)});if(Q0.ok)return P.info("User free tier status:",Q0),Q0.result;return}catch($0){P.error("Failed to fetch free tier status:",$0);return}})(),b=!A.executeMode?new Q21:null,v,y=null;if(b)v=b,y=(async()=>{let $0=V?await X.serverStatusPromise:X.serverStatus;if(lE($0))throw qe($0,A.ampURL);await DQ1($,Q,$0);let j0=process.hrtime.bigint(),Q0=await _();if(F("runMainThread:createThreadPool",j0),b.attach(Q0),Y){let M0=await k1(Q0.threadHandles$);if(!M0)throw new n1("No active thread is available yet.",1);await M0.sendMessage({content:[{type:"text",text:Y}]})}})(),y.catch(async($0)=>{let j0=$0 instanceof Error?$0:Error(String($0));b.setInitError(j0),await Sz($0,Q.threadId)});else U=process.hrtime.bigint(),v=await _(),F("runMainThread:createThreadPool",U);let p=Q.notifications!==void 0?Q.notifications:!A.executeMode;U=process.hrtime.bigint();let c=await X.configService.getLatest();if(F("runMainThread:configService.getLatest",U),U=process.hrtime.bigint(),H16({configService:X.configService,threadService:X.threadService,threadPool:v,config:c,useNotifications:p}),F("runMainThread:createLegacyTuiNotificationService",U),A.executeMode){g01(X.mcpService,A.settings);let $0=Jz0($,Q),j0=await rz(),Q0=O?$0:MZ0({agentMode:Q.mode,explicitEffort:$0,sessionState:j0}),M0={userInput:Y,stdinInput:E,dependencies:X,streamJson:Z,streamJsonInput:!!Q.streamJsonInput,streamJsonThinking:!!Q.streamJsonThinking,stats:!!Q.stats,ampURL:A.ampURL,isInternalUser:W,agentMode:Q.mode,reasoningEffort:Q0,labels:Q.label},n=await Wk4({threadPool:v,...M0});if(await Ne(n,"execute"),Q.archive)await X.threadService.archive(n,!0);await X.asyncDispose(),process.exit(0)}let g=!1,i=!1;if(Q.jetbrains||Q.ide){await f20();let $0=await oE({jetbrainsOnly:Q.jetbrains});if($0.length===0){if(Q.jetbrains)g=!await X.configService.get("jetbrains.skipInstall")}else if($0.length===1){let j0=$0[0];if(j0)o5.selectConfig(j0)}else i=!0}U=process.hrtime.bigint();let r=cE0("0.0.1779313683-gf89f27",X.settingsStorage,{startDelayMs:3000});F("runMainThread:createUpdateService",U),U=process.hrtime.bigint();let A0=new CZ0(X.mcpService,A.settings.getWorkspaceRootPath());if(F("runMainThread:createMcpTrustHandler",U),Y&&A.executeMode){let $0=await k1(v.threadHandles$);if(!$0)throw new n1("No active thread is available yet.",1);await $0.sendMessage({content:[{type:"text",text:Y}]})}U=process.hrtime.bigint();let I0=await rz();F("runMainThread:loadSessionState",U),P.info("Loaded session state:",I0);let E0=Jz0($,Q),W0={...I0,launchCount:I0.launchCount+1,lastReasoningEffortByMode:E0?{...I0.lastReasoningEffortByMode,[Q.mode]:E0}:I0.lastReasoningEffortByMode};zQ(($0)=>({...$0,launchCount:$0.launchCount+1}));try{if(U=process.hrtime.bigint(),await l16({history:new mo,fuzzyServer:X.fuzzyServer,settingsStorage:X.settingsStorage,threadService:X.threadService,skillService:X.skillService,configService:X.configService,secretStorage:X.secretStorage,internalAPIClient:t4,threadPool:v,createSystemPromptDeps:async()=>V76(X),ideClient:o5,mcpService:X.mcpService,toolboxService:X.toolboxService,mcpTrustHandler:A0,updateService:r,pluginPlatform:X.pluginPlatform,pluginService:X.pluginService},{initialServerStatus:X.serverStatus,stdout:process.stdout,hasAPIKeyAtStartup:X.hasAPIKeyAtStartup,ampURL:A.ampURL,startupThreadID:O,showJetBrainsInstaller:g,showIdePickerHint:i,openThreadSwitcher:Q.openThreadSwitcher,jetbrainsMode:Q.jetbrains,clientId:B25,logFile:{path:B},sessionState:W0,freeTierStatusPromise:f,workspace:N??null,features:q,isInternalUser:W,initialAgentMode:$.getOptionValueSourceWithGlobals("mode")==="cli"?Q.mode:void 0,splashOrbVisualStyle:Q.neoOrb?"neo":"classic",buildTimestamp:"2026-05-20T21:52:35.567Z"},($0)=>new E21({...$0,threadPool:$0.threadPool},(j0)=>new P91({...j0,threadState:j0.threadState}))),F("runMainThread:mountApp-returned",U),y)await y}finally{await v.dispose().catch(($0)=>{P.error("Failed to dispose thread pool during shutdown",$0)})}await X.asyncDispose(),F("runMainThread:dependencies.asyncDispose",J),process.exit(0)}async function d3(A){if(P.info("Initializing CLI context",{argv:process.argv,nodeEnv:"production",hasAmpURL:Boolean(process.env.AMP_URL),hasAmpAPIKey:Boolean(process.env.AMP_API_KEY),hasSettingsFile:Boolean(process.env.AMP_SETTINGS_FILE)}),A.interactive)H$.write(`Warning: --interactive flag is deprecated. Interactive mode is now the default unless --execute is used or output is redirected.
7305
+ `);let Q=!!A.execute||!process.stdout.isTTY&&!A.streamJson,$=process.stdout.isTTY&&process.stderr.isTTY;P.info("Execution mode resolved",{executeMode:Q,stdoutTTY:process.stdout.isTTY,stderrTTY:process.stderr.isTTY,streamJson:A.streamJson,executeFlag:A.execute});let B=await x$4({get:async(Y)=>{if(Y!==Kc)return;try{let E=await X76(BQ1,"utf-8");return JSON.parse(E).installationID}catch{return}},set:async(Y,E)=>{if(Y!==Kc)return;await e55(He.dirname(BQ1),{recursive:!0}),await A25(BQ1,JSON.stringify({installationID:E},null,2),{mode:384})}},{clientType:"cli",platform:e90()});d14(B);let D=await d06({...A,workspaceTrust:{current:!0,changes:Ed},getHook:process.env.AMP_URL?(Y,E)=>{if(Y==="url")return Promise.resolve(process.env.AMP_URL);return E()}:void 0});if(A.mcpConfig){let Y=await pg4(A.mcpConfig);D=cg4(D,Y)}let J=He.dirname(D.getSettingsFilePath());Su4(id,J),D=Ie1(D);let F=await D.get("url","admin")??await D.get("url","global");if(!F)F=a7;if(P.info("Resolved Amp URL",{ampURL:F,settingsFile:D.getSettingsFilePath(),workspaceRoot:D.getWorkspaceRootPath()}),!BH(F))P.info("Targeting custom Amp server",{ampURL:F});return{executeMode:Q,isTTY:$,ampURL:F,settings:D,secrets:y06(await i51(A,D))}}function P25(A){let Q={};for(let $=0;$<A.length;$++){let B=A[$];if(B?.startsWith("--")){let J=B.slice(2).replace(/-([a-z])/g,(Y,E)=>E.toUpperCase()),F=A[$+1];if(F&&!F.startsWith("--"))Q[J]=F,$++}}return Q}function u25(A,Q){let $=A.includes("--headless")||A.some((D)=>D.startsWith("--headless=")),B=He.resolve(Q.logFile??process.env.AMP_LOG_FILE??($?$25:Ao));return{logLevel:Q.logLevel??process.env.AMP_LOG_LEVEL??"info",logFile:B}}async function _25(){Pv4();let A=P25(process.argv),Q=u25(process.argv,A),$=fv4(Q);wY0("silent");let B=process.argv.includes("--no-color"),D=process.argv.includes("--color"),J=process.stdout.isTTY&&process.stderr.isTTY;if(B||!D&&!J)t0.level=0;if(J25(P),P.info("Starting Amp CLI.",{version:"0.0.1779313683-gf89f27",buildTimestamp:"2026-05-20T21:52:35.567Z"}),process.platform==="win32"&&yj())gb4();if(parseInt(process.version.slice(1).split(".")[0]??"")<20)throw new n1(d9.nodeVersion(process.version),1,"Please upgrade your Node.js installation from https://nodejs.org");await C25($).parseAsync(process.argv)}vu4().startActiveSpan("main",async(A)=>{process.on("exit",()=>A.end()),await _25().catch(Sz)});async function T25(A,Q){let $=A.ampURL.includes("localhost")||A.ampURL.includes("127.0.0.1");if(process.env.AMP_URL&&!$)await A.settings.set("url",process.env.AMP_URL,"global"),$3.write(`Saving custom server URL to settings: ${process.env.AMP_URL}
7306
7306
  `);else if(!BH(A.ampURL))$3.write(`Logging in to ${new URL(A.ampURL).hostname}
7307
7307
  `);let B=process.env.AMP_API_KEY;if(B)$3.write(`API key found in environment variable, storing...
7308
7308
  `),await Q.set("apiKey",B,A.ampURL),$3.write(`API key successfully stored.