@github/copilot-language-server 1.567.0 → 1.567.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/main.js +2 -2
- package/package.json +8 -8
package/dist/main.js
CHANGED
|
@@ -1916,7 +1916,7 @@ ${r}+- `:"";return e+this.description+o}}},kA=class{constructor(e,r,n,o){this.la
|
|
|
1916
1916
|
(using_declaration)
|
|
1917
1917
|
(alias_declaration)
|
|
1918
1918
|
(static_assert_declaration)
|
|
1919
|
-
] @statement`}};var fB=class{constructor(e,r,n){this.languageId=e;this.prefix=r;this.completion=n}static{a(this,"BlockTrimmer")}static isSupported(e){return kA.isSupported(e)}static isTrimmedByDefault(e){return kA.isTrimmedByDefault(e)}async withParsedStatementTree(e){var n=[];try{let r=A5t(n,kA.create(this.languageId,this.prefix+this.completion,this.prefix.length,this.prefix.length+this.completion.length));await r.build();return await e(r)}catch(o){var s=o,c=!0}finally{y5t(n,s,c)}}trimmedCompletion(e){return e===void 0?this.completion:this.completion.substring(0,e)}getStatementAtCursor(e){return e.statementAt(Math.max(this.prefix.length-1,0))??e.statements[0]}getContainingBlockOffset(e){let r;if(e&&this.isCompoundStatement(e))r=e;else if(e){let n=e.parent;for(;n&&!this.isCompoundStatement(n);)n=n.parent;r=n}if(r){let n=this.asCompletionOffset(r.node.endIndex);if(n&&this.completion.substring(n).trim()!=="")return n}}hasNonStatementContentAfter(e){if(!e||!e.nextSibling)return!1;let r=this.asCompletionOffset(e.node.endIndex),n=this.asCompletionOffset(e.nextSibling.node.startIndex);return this.completion.substring(Math.max(0,r??0),Math.max(0,n??0)).trim()!==""}asCompletionOffset(e){return e===void 0?void 0:e-this.prefix.length}isCompoundStatement(e){return e.isCompoundStatementType||e.children.length>0}};var pZe=class extends fB{constructor(r,n,o,s=3,c=7){super(r,n,o);this.lineLimit=s;this.lookAhead=c;let l=[...this.completion.matchAll(/\n/g)],u=this.lineLimit+this.lookAhead;l.length>=this.lineLimit&&this.lineLimit>0&&(this.limitOffset=l[this.lineLimit-1].index),l.length>=u&&u>0&&(this.lookAheadOffset=l[u-1].index)}static{a(this,"TerseBlockTrimmer")}async getCompletionTrimOffset(){return await this.withParsedStatementTree(r=>{let n=r.statementAt(this.stmtStartPos()),o=this.getContainingBlockOffset(n);return o=this.trimAtFirstBlankLine(o),n&&(o=this.trimAtStatementChange(n,o)),this.limitOffset&&this.lookAheadOffset&&(o===void 0||o>this.lookAheadOffset)?this.limitOffset:o})}stmtStartPos(){let r=this.completion.match(/\S/);return r&&r.index!==void 0?this.prefix.length+r.index:Math.max(this.prefix.length-1,0)}trimAtFirstBlankLine(r){let n=[...this.trimmedCompletion(r).matchAll(/\r?\n\s*\r?\n/g)];for(;n.length>0&&(r===void 0||r>n[0].index);){let o=n.shift();if(this.completion.substring(0,o.index).trim()!=="")return o.index}return r}trimAtStatementChange(r,n){let o=this.prefix.length,s=this.prefix.length+(n??this.completion.length);if(r.node.endIndex>o&&this.isCompoundStatement(r))return r.nextSibling&&r.node.endIndex<s?this.asCompletionOffset(r.node.endIndex):n;let c=r,l=r.nextSibling;for(;l&&l.node.endIndex<=s&&!this.hasNonStatementContentAfter(c)&&!this.isCompoundStatement(l);)c=l,l=l.nextSibling;return l&&c.node.endIndex>o&&c.node.endIndex<s?this.asCompletionOffset(c.node.endIndex):n}};async function ISn(t,e){var l=[];try{let r=t.getText();let n=t.offsetAt(e);let o=A5t(l,kA.create(t.detectedLanguageId,r,0,r.length));await o.build();let s=o.statementAt(n);if(!s)return"non-block";if(!s.isCompoundStatementType&&s.children.length===0)return s.parent&&!s.nextSibling&&s.node.endPosition.row<=e.line?"block-end":s.parent?"mid-block":"non-block";if(s.children.length===0)return"empty-block";let c=s.children[s.children.length-1];if(n<c.node.startIndex)return"mid-block";return"block-end"}catch(u){var d=u,f=!0}finally{y5t(l,d,f)}}a(ISn,"getBlockPositionType");h();function kJo(t){return t.HTTPS_PROXY||t.https_proxy||t.HTTP_PROXY||t.http_proxy}a(kJo,"getProxyFromEnvironment");function DJo(t){return t.NODE_TLS_REJECT_UNAUTHORIZED!=="0"}a(DJo,"getRejectUnauthorizedFromEnvironment");var wSn=b.Object({proxy:b.Optional(b.String()),proxyStrictSSL:b.Optional(b.Boolean()),proxyAuthorization:b.Optional(b.String()),proxyKerberosServicePrincipal:b.Optional(b.String()),noProxy:b.Optional(b.Array(b.String()))});function xSn(t){let e=kJo(t),r=gDe({proxy:e,proxyStrictSSL:DJo(t)}),n=t.GH_COPILOT_KERBEROS_SERVICE_PRINCIPAL??t.GITHUB_COPILOT_KERBEROS_SERVICE_PRINCIPAL??t.AGENT_KERBEROS_SERVICE_PRINCIPAL;return n&&(r.proxyKerberosServicePrincipal=n),r}a(xSn,"getHttpSettingsFromEnvironment");function gDe(t){if(!t.proxy)return{...t,proxy:""};try{let{protocol:e,host:r,username:n,password:o,pathname:s,search:c,hash:l}=new URL(t.proxy);return{...t,proxy:`${e}//${r}${s}${c}${l}`,proxyAuthorization:t.proxyAuthorization||MJo(n,o),noProxy:t.noProxy||[]}}catch{return{...t,proxy:""}}}a(gDe,"normalizeHttpSettings");function MJo(t,e){return!t||!e?"":`${decodeURIComponent(t)}:${decodeURIComponent(e)}`}a(MJo,"getAuth");var HZ={};so(HZ,{anthropicClaude:()=>qJo,build:()=>FJo,buildType:()=>UJo,default:()=>VJo,dependencies:()=>$Jo,description:()=>LJo,devDependencies:()=>HJo,displayName:()=>OJo,engines:()=>QJo,name:()=>NJo,overrides:()=>zJo,overridesComments:()=>GJo,scripts:()=>jJo,version:()=>BJo});var NJo="copilot",OJo="GitHub Copilot",LJo="Your AI pair programmer",BJo="1.567.0",FJo="204",UJo="prod",QJo={node:">=22.13.0",npm:">=11.6.0 <12.0.0"},qJo={cliPackageVersion:"2.1.159"},jJo={build:"tsx esbuild.ts",clean:"./script/build/clean.sh",compress:"tsx ./script/compressTokenizer.ts",generate_languages:"tsx script/generateLanguages.ts && prettier --write lib/src/language/generatedLanguages.ts",get_token:"tsx script/deviceFlow.ts --save-as-test-token",lint:'run-p --aggregate-output "lint:*"',"lint:deps":"depcruise -c .dependency-cruiser.js .","lint:eslint":"eslint -f visualstudio --quiet --cache .","lint:gdpr":"tsx script/checkGdprComments.ts","lint:overrides":"tsx script/checkOverridesDocumented.ts","lint:prettier":"prettier --check . 2>&1","lint:types":"tsc --noEmit",manage_auth_db:"tsx script/manageAuthDb.ts",prebuild:"npm install",pretest:"npm run build","pretest:headless":"npm run build","pretest:agent-e2e-full":"npm run build","pretest:agent-e2e":"npm run build","pretest:lsp-client":"npm run build","pretest:lib-e2e":"npm run build",prewatch:"npm run build","prewatch:esbuild":"npm run build",start:"npm run watch",test:'npm-run-all "test:headless --ignore-scripts" lint',"test:headless":'npm-run-all test:lib test:agent test:mcp-int "test:lib-e2e --ignore-scripts" test:prompt "test:lsp-client --ignore-scripts" lint',"test:agent":'mocha "agent/src/**/*.test.{ts,tsx}"',"test:agent-e2e":'mocha "agent/e2e/**/*.test.{ts,tsx}" --exclude "agent/e2e/**/*.daily.test.{ts,tsx}"',"test:agent-e2e-full":'mocha "agent/e2e/**/*.test.{ts,tsx}"',"test:workflow":"node --test .github/workflows/scripts/release-merge-back/release-merge-back.test.mjs","test:lib":'mocha "lib/src/**/*.test.{ts,tsx}" "script/**/*.test.{ts,tsx}" --exclude "lib/src/**/*.int.test.ts"',"test:lib-int":'mocha "lib/src/**/*.int.test.ts"',"test:mcp-int":'mocha "lib/src/mcp/**/*.int.test.ts" "lib/src/mcpGateway/**/*.int.test.ts" "lib/src/backgroundAgent/ide/**/*.int.test.ts"',"test:lib-e2e":'mocha "lib/e2e/src/**/*.test.{ts,tsx}" --exclude "lib/e2e/src/prompt/**/*.test.ts"',"test:lib-e2e-no-ci":'mocha "lib/e2e/no-ci/**/*.test.{ts,tsx}"',"test:lib-prompt-e2e":'mocha "lib/e2e/src/prompt/prompt.test.ts"',"test:lib-prompt-e2e-perf":"INCLUDE_PERFORMANCE=true npm run test:lib-prompt-e2e","test:lsp-client":'mocha "lsp-client/test/*.test.{ts,tsx}"',"test:pkg-runtime":"tsx script/smokeCopilotRuntimePkg.ts","test:prompt":'mocha "prompt/test/**/*.test.{ts,tsx}"',"test:prepare-msbench":"tsx script/setupMsbench.ts","test:run-msbench":"tsx lsp-client/test/msbench/agent/index.ts",watch:'run-p "watch:esbuild --ignore-scripts" "watch:types -- --preserveWatchOutput"',"watch:esbuild":"tsx esbuild.ts --watch","watch:types":"tsc --noEmit --watch"},HJo={"@azure/identity":"^4.13.3","@azure/keyvault-secrets":"^4.11.2","@github/prettier-config":"0.0.6","@limegrass/eslint-plugin-import-alias":"^1.6.1","@microsoft/agent-host-protocol":"^1.0.0","@types/crypto-js":"^4.2.2","@types/diff":"^8.0.0","@types/git-url-parse":"^16.0.2","@types/js-yaml":"^4.0.6","@types/kerberos":"^1.1.2","@types/markdown-it":"^14.2.0","@types/mocha":"^10.0.10","@types/node":"~22.13.0","@types/semver":"^7.8.0","@types/sinon":"^22.0.0","@types/toposort":"^2.0.7","@types/vscode":"1.138.0","@types/which":"^3.0.0","@types/yargs":"^17.0.35","@vscode/tree-sitter-wasm":"0.0.5-php.2","@yao-pkg/pkg":"^6.24.0",boxen:"^8.0.1",chalk:"^5.6.2","dependency-cruiser":"^18.2.0",esbuild:"^0.28.2","esbuild-plugin-copy":"^2.1.1",eslint:"^9.39.5","eslint-formatter-visualstudio":"^9.0.1","eslint-plugin-mocha":"^10.5.0",fflate:"^0.8.2",globals:"^17.12.0","js-yaml":"^4.2.0",mocha:"^11.8.0","mocha-junit-reporter":"^2.2.1","mocha-multi-reporters":"^1.5.2","npm-run-all":"^4.1.5",openai:"^7.20.0",prettier:"^3.5.3","prettier-plugin-organize-imports":"^4.2.0","simple-git":"^4.0.2",sinon:"^22.1.0","tree-sitter-bash":"^0.23.0","tree-sitter-powershell":"0.25.9","ts-dedent":"^2.3.0",tsx:"^4.23.12",typescript:"^5.9.3","typescript-eslint":"^8.39.1","vscode-dts":"^0.3.3"},$Jo={"@adobe/helix-fetch":"github:devm33/helix-fetch#2a08fa939591a0e14f34f611adcc3ed767579e9a","@agentclientprotocol/sdk":"^1.4.0","@anthropic-ai/claude-agent-sdk":"0.3.159","@anthropic-ai/sdk":"^0.98.0","@github/copilot":"1.0.105","@github/copilot-sdk":"1.0.28","@github/keytar":"7.10.6","@github/memoize":"1.1.5","@microsoft/1ds-core-js":"^4.4.3","@microsoft/1ds-post-js":"^4.4.3","@microsoft/applicationinsights-core-js":"^3.4.3","@microsoft/applicationinsights-web-basic":"^3.4.3","@modelcontextprotocol/client":"^2.4.0","@modelcontextprotocol/node":"^2.1.2","@modelcontextprotocol/server":"^2.4.0","@octokit/graphql":"^9.0.5","@octokit/rest":"^22.0.1","@parcel/watcher":"^2.6.0","@sinclair/typebox":"^0.34.52","@vscode/chat-lib":"0.70.0","@vscode/codicons":"^0.0.45","@vscode/deviceid":"github:ghc-jetbrains/vscode-deviceid#f0e5738cd362ef20a09aeb30c3a8be99a9a710f5","@vscode/policy-watcher":"^1.4.0","@vscode/prompt-tsx":"^0.4.0-alpha.9","@vscode/webview-ui-toolkit":"^1.3.1","crypto-js":"^4.2.0",diff:"^9.0.0",dldr:"^0.0.10",events:"^3.3.0","git-url-parse":"^16.1.0",glob:"^11.1.0","jsonc-parser":"^3.3.1",kerberos:"^2.2.0","mac-ca":"^3.1.3","markdown-it":"^15.0.2",minimatch:"^10.2.6",open:"^11.0.4",semver:"^7.8.5",shiki:"~1.15.0","source-map-support":"^0.5.21",toposort:"^2.0.2",undici:"^7.29.1",uuid:"^14.0.0","vscode-languageclient":"^9.0.0","vscode-languageserver":"^9.0.0","vscode-languageserver-protocol":"^3.17","vscode-languageserver-textdocument":"~1.0.14","vscode-uri":"^3.2.0","web-tree-sitter":"^0.23.0",which:"^7.0.0","windows-ca-certs":"^0.2.2",ws:"^8.21.3",yargs:"^18.1.0"},zJo={fsevents:"<0","@github/copilot-linuxmusl-arm64":"<0","@github/copilot-linuxmusl-x64":"<0",bindings:"npm:bundled-bindings@^1.5.0",jws:"^3.2.3",tar:"7.5.21","serialize-javascript":"^7.0.5",uuid:"^14.0.0","ip-address":"^10.1.1","fast-uri":"^3.1.8"},GJo={"//":"Rationale for each entry in `overrides`. Required by `npm run lint:overrides` (script/checkOverridesDocumented.ts). Each value should cover: why (CVE/GHSA or build-hack reason), which direct dep pulls in the vulnerable transitive, and the remove-when condition.",fsevents:"Build hack: macOS-only optional native dep; '<0' is an impossible semver that force-skips install on Linux/Windows pkg builds. Permanent \u2014 keep until @yao-pkg/pkg handles macOS-only optionalDependencies natively. See commit d635096c.","@github/copilot-linuxmusl-arm64":"Build hack: @github/copilot declares a Linux musl optional runtime package, but CLS does not support musl. '<0' prevents npm from installing the unsupported runtime. Drop only if CLS adds musl support.","@github/copilot-linuxmusl-x64":"Build hack: @github/copilot declares a Linux musl optional runtime package, but CLS does not support musl. '<0' prevents npm from installing the unsupported runtime. Drop only if CLS adds musl support.",bindings:"Build hack: alias to bundled-bindings fork that resolves .node native addon paths after pkg/esbuild bundling. Required by kerberos. Drop when upstream `bindings` adopts platform-specific path resolution. See commits c4461665 and b55ece83.",jws:"CVE GHSA-869p-cjfg-cm3x (Improperly Verifies HMAC Signature). Pulled in by jsonwebtoken-family deps. Drop when all transitive consumers pin jws >= 3.2.3. See commit 2b5dc766.",tar:"CVE GHSA-9ppj-qmqm-q256 + GHSA-qffp-2rhf-9h96 (Symlink/Hardlink Path Traversal via Drive-Relative Linkpath), plus the 7.5.12..7.5.20 advisory run: GHSA-23hp-3jrh-7fpw / CVE-2026-59873 (critical, decompression DoS via unlimited input), GHSA-8x88-c5mf-7j5w / CVE-2026-59874 (infinite loop on negative entry size), GHSA-w8wr-v893-vjvp / CVE-2026-59871 (PAX numeric path type confusion), GHSA-gvwx-54wh-qm9j / CVE-2026-59875 (NUL byte in PAX path records), GHSA-vmf3-w455-68vh / CVE-2026-53655 (GNU long-name PAX size override file smuggling), GHSA-r292-9mhp-454m (uncontrolled recursion in mapHas/filesFilter). Pulled in by @yao-pkg/pkg (tar ^7.5.7) and node-gyp / native-build deps. Drop when transitive consumers bump tar >= 7.5.21. Dependabot alerts #170, #169, #179, #171, #168, #146. See commit e2dff0f3.","serialize-javascript":"CVE GHSA-5c6j-r48x-rmvq (RCE via RegExp.flags / Date.toISOString) + GHSA-qj8w-gfj5-8c6v (ReDoS). Pulled in by mocha 11.x (^6.0.2). Dev-only. Drop when mocha bumps to a release that carries serialize-javascript >= 7.0.3. See commit d49f75fd.",uuid:"CVE GHSA-w5hq-g745-h8pq (missing buffer bounds checks in v3/v5/v6). Pulled in by msal-node and @vscode/deviceid as uuid 8.x/9.x. Drop when both upgrade to uuid >= 14. Dependabot alert #128. See commit 6315f3f8.","ip-address":"CVE GHSA-v2v4-37r5-5v8g (XSS in Address6 HTML-emitting methods: group/link/spanAll and AddressError.parseMessage). Pulled in by @anthropic-ai/claude-agent-sdk's v1 MCP peer -> express-rate-limit. Not exploitable here (we don't render HTML or call the affected methods), but the override clears the alert. Drop when express-rate-limit bumps to a release carrying ip-address >= 10.1.1. Dependabot alert #129. See PR #854.","fast-uri":"CVE-2026-6321 GHSA-q3j6-qgpj-74h6 (host confusion via percent-encoded authority delimiters) + CVE-2026-6322 GHSA-v39h-62p7-jpjc (path traversal via percent-encoded dot segments). Pulled in by @anthropic-ai/claude-agent-sdk's v1 MCP peer -> ajv -> fast-uri. Drop when ajv bumps to a release carrying fast-uri >= 3.1.2. Dependabot alerts #132, #133."},VJo={name:NJo,displayName:OJo,description:LJo,version:BJo,build:FJo,buildType:UJo,engines:QJo,anthropicClaude:qJo,scripts:jJo,devDependencies:HJo,dependencies:$Jo,overrides:zJo,overridesComments:GJo};var Ue={Enable:"enable",EnableQuotaThresholdWarning:"quota.enableThresholdWarning",McpGatewayAutoStart:"mcpGateway.autoStart",ShowEditorCompletions:"editor.showEditorCompletions",EnableAutoCompletions:"editor.enableAutoCompletions",DelayCompletions:"editor.delayCompletions",FilterCompletions:"editor.filterCompletions",FetchStrategy:"fetchStrategy",EnableBuiltInGitHubMcpServer:"enableBuiltInGitHubMcpServer",ToolConfirmAutoApprove:"agent.toolConfirmAutoApprove",AutoApproveUnmatchedTerminal:"agent.autoApproveUnmatchedTerminal",AutoApproveUnmatchedFileOp:"agent.autoApproveUnmatchedFileOp",TrustToolAnnotations:"agent.trustToolAnnotations",AutoApproveYoloMode:"agent.autoApproveYoloMode",EditorHandlesAllConfirmation:"agent.editorHandlesAllConfirmation",MaxToolCallingLoop:"agent.maxToolCallingLoop",AutoCompress:"agent.autoCompress",AnthropicThinkingBudgetToken:"agent.anthropicThinkingBudgetToken",EnableSkills:"agent.enableSkills",EnableCloudSandbox:"agent.enableCloudSandbox",EnableOrgSkills:"agent.enableOrgSkills",EnableHooks:"agent.enableHooks",SystemHookTools:"agent.systemHookTools",EnableSandbox:"agent.sandbox.enabled",SandboxAddCurrentWorkingDirectory:"agent.sandbox.addCurrentWorkingDirectory",SandboxAuth:"agent.sandbox.auth",SandboxAllowDevToolAccess:"agent.sandbox.allowDevToolAccess",SandboxAllowBypass:"agent.sandbox.allowBypass",SandboxMcpServers:"agent.sandbox.sandboxMcpServers",SandboxLspServers:"agent.sandbox.sandboxLspServers",SandboxUserPolicy:"agent.sandbox.userPolicy",EnablePlugins:"agent.enablePlugins",EnableEnsemble:"agent.enableEnsemble",EnableCustomAgents:"agent.enableCustomAgents",EnableOrgCustomAgents:"agent.enableOrgCustomAgents",EnableOrgCustomInstructions:"agent.enableOrgCustomInstructions",UseSessionModelForBuiltinSubagents:"agent.useSessionModelForBuiltinSubagents",UseAgentsMd:"agent.useAgentsMdFile",UseNestedAgentsMd:"agent.useNestedAgentsMdFiles",UseClaudeMd:"agent.useClaudeMdFile",UseNestedClaudeMd:"agent.useNestedClaudeMdFiles",CompletionsDelay:"completionsDelay",CompletionsDebounce:"completionsDebounce",EnableThinking:"agent.enableThinking",TranscriptDirectory:"agent.transcriptDirectory",AgentDebugLogsDirectory:"agent.agentDebugLogsDirectory",ClaudeCliPath:"agent.claude.cliPath",CodexCliPath:"agent.codex.cliPath",OtelEnabled:"agent.otel.enabled",OtelEndpoint:"agent.otel.otlpEndpoint",OtelCaptureContent:"agent.otel.captureContent",OtelExporterType:"agent.otel.exporterType",OtelProtocol:"agent.otel.protocol",OtelOutfile:"agent.otel.outfile",OtelServiceName:"agent.otel.serviceName",OtelResourceAttributes:"agent.otel.resourceAttributes",NESExtendedRange:"nextEditSuggestions.extendedRange",NESEagerness:"nextEditSuggestions.eagerness",RelatedFilesVSCodeCSharp:"advanced.relatedFilesVSCodeCSharp",RelatedFilesVSCodeTypeScript:"advanced.relatedFilesVSCodeTypeScript",RelatedFilesVSCode:"advanced.relatedFilesVSCode",ContextProviders:"advanced.contextProviders",DebugOverrideLogLevels:"advanced.debug.overrideLogLevels",DebugFilterLogCategories:"advanced.debug.filterLogCategories",DebugSnippyOverrideUrl:"advanced.debug.codeRefOverrideUrl",DebugUseElectronFetcher:"advanced.debug.useElectronFetcher",DebugUseEditorFetcher:"advanced.debug.useEditorFetcher",UseSubsetMatching:"advanced.useSubsetMatching",ContextProviderTimeBudget:"advanced.contextProviderTimeBudget",DebugOverrideCapiUrl:"internal.capiUrl",DebugOverrideCapiUrlLegacy:"advanced.debug.overrideCapiUrl",DebugTestOverrideCapiUrl:"internal.capiTestUrl",DebugTestOverrideCapiUrlLegacy:"advanced.debug.testOverrideCapiUrl",DebugOverrideProxyUrl:"internal.completionsUrl",DebugOverrideProxyUrlLegacy:"advanced.debug.overrideProxyUrl",DebugTestOverrideProxyUrl:"internal.completionsTestUrl",DebugTestOverrideProxyUrlLegacy:"advanced.debug.testOverrideProxyUrl",DebugOverrideEngine:"internal.completionModel",DebugOverrideEngineLegacy:"advanced.debug.overrideEngine",AlwaysRequestMultiline:"internal.alwaysRequestMultiline",ModelAlwaysTerminatesSingleline:"internal.modelAlwaysTerminatesSingleline",TrimCompletionsAggressively:"internal.trimCompletionsAggressively",UseWorkspaceContextCoordinator:"internal.useWorkspaceContextCoordinator",ShowWorkspaceContextDebugger:"internal.showWorkspaceContextDebugger",IncludeNeighboringFiles:"internal.includeNeighboringFiles",ExcludeRelatedFiles:"internal.excludeRelatedFiles",DebugOverrideCppHeadersEnableSwitch:"internal.cppHeadersEnableSwitch",NESXTab:"internal.useXTab",NESUseExplicitRejection:"internal.nesUseExplicitRejection",NESModelConfiguration:"internal.nesModelConfiguration",UseSplitContextPrompt:"internal.useSplitContextPrompt",UseCompletionsComparisonPanel:"internal.useCompletionsComparisonPanel",ComparisonPanelModelIds:"internal.comparisonPanelModelIds",ComparisonPanelRandomizedMode:"internal.comparisonPanelRandomizedMode",UseFetchFetcher:"internal.useFetchFetcher",UseChatLibCompletions:"internal.useChatLibCompletions",JetBrainsEdgeTasEnabled:"internal.jetbrainsEdgeTasEnabled",ExperimentsOverride:"internal.experimentsOverride",HookErrorOccurredStackTrace:"internal.hookErrorOccurredStackTrace",AppendPromptTokenCache:"internal.appendPromptTokenCache",PromptPersistBasePath:"internal.promptPersistBasePath",AnthropicMessagesEndpoint:"internal.anthropic.messagesEndpoint",UseHelixFetcher:"internal.useHelixFetcher",EnableMapCodeFallback:"internal.enableMapCodeFallback",SearchAgent:"internal.searchAgent",EnsembleEnabledOverride:"internal.ensembleEnabledOverride",PerfEnabled:"internal.perf.enabled",AuthTokenEncryption:"internal.auth.tokenEncryption",EnableWorkspaceIndex:"workspaceIndex.enabled"},lDe=(o=>(o.Parsing="parsing",o.Server="server",o.ParsingAndServer="parsingandserver",o.MoreMultiline="moremultiline",o))(lDe||{});function RSn(t){return["server","parsingandserver"].includes(t)}a(RSn,"shouldDoServerTrimming");var L2=class{static{a(this,"BlockModeConfig")}},Qfe=class extends L2{static{a(this,"ConfigBlockModeConfig")}forLanguage(e,r,n){let o=e.get(or).overrideBlockMode(n);if(o)return C$t(o,r);let s=e.get(or).enableProgressiveReveal(n);return(Ct(e,Ue.AlwaysRequestMultiline)??s)||fB.isTrimmedByDefault(r)?C$t("moremultiline",r):r=="ruby"?"parsing":x1(r)?"parsingandserver":"server"}};function WJo(t){return["parsing","parsingandserver","moremultiline"].includes(t)}a(WJo,"blockModeRequiresTreeSitter");function C$t(t,e){return t==="moremultiline"&&kA.isSupported(e)?t:WJo(t)&&!x1(e)?"server":t}a(C$t,"toApplicableBlockMode");var Dn=class{static{a(this,"ConfigProvider")}getRawConfig(e){return this.getExplicitlySetConfigs().get(e)}requireReady(){return Promise.resolve()}},qfe=class extends Dn{constructor(){super(...arguments);this.onDidChangeCopilotSettings=a(()=>({dispose:a(()=>{},"dispose")}),"onDidChangeCopilotSettings");this.onDidChangeHttpSettings=this.onDidChangeCopilotSettings}static{a(this,"DefaultsOnlyConfigProvider")}getConfig(r){return YJo(r)}getOptionalConfig(r){return KJo(r)}dumpForTelemetry(){return{}}getExplicitlySetConfigs(){return new Map}getHttpSettings(){return{proxy:""}}},$Z=class extends Dn{constructor(r,n){super();this.baseConfigProvider=r;this.overrides=n;this.copilotEmitter=new Yi;this.onDidChangeCopilotSettings=this.copilotEmitter.event;this.didChangeHttpSettingsEmitter=new Yi;this.onDidChangeHttpSettings=this.didChangeHttpSettingsEmitter.event;this.httpSettings=this.baseConfigProvider.getHttpSettings()}static{a(this,"InMemoryConfigProvider")}getOptionalOverride(r){return this.overrides.get(r)}getConfig(r){return this.getOptionalOverride(r)??this.baseConfigProvider.getConfig(r)}getOptionalConfig(r){return this.getOptionalOverride(r)??this.baseConfigProvider.getOptionalConfig(r)}getRawConfig(r){return this.overrides.has(r)?this.overrides.get(r):this.baseConfigProvider.getRawConfig(r)}setConfig(r,n){this.setCopilotSettings({[r]:n})}setCopilotSettings(r){for(let[n,o]of Object.entries(r))o!==void 0?this.overrides.set(n,o):this.overrides.delete(n);this.copilotEmitter.fire(this)}getExplicitlySetConfigs(){let r=new Map(this.baseConfigProvider.getExplicitlySetConfigs());for(let[n,o]of this.overrides)r.set(n,o);return r}getHttpSettings(){return this.httpSettings}setHttpSettings(r){let n=gDe(r);this.httpSettings=n,this.didChangeHttpSettingsEmitter.fire(this.getHttpSettings())}dumpForTelemetry(){let r=this.baseConfigProvider.dumpForTelemetry();for(let n of[Ue.ShowEditorCompletions,Ue.EnableAutoCompletions,Ue.DelayCompletions,Ue.FilterCompletions]){let o=this.overrides.get(n);o!==void 0&&(r[n]=JSON.stringify(o))}return r}};function S$t(t,e){let r=t,n=[];for(let o of e.split(".")){let s=[...n,o].join(".");r&&typeof r=="object"&&s in r?(r=r[s],n.length=0):n.push(o)}if(!(r===void 0||n.length>0))return r}a(S$t,"getConfigKeyRecursively");function YJo(t){if(hZe.has(t))return hZe.get(t);throw new Error(`Missing config default value: ${v5t}.${t}`)}a(YJo,"getConfigDefaultForKey");function KJo(t){return hZe.get(t)}a(KJo,"getOptionalConfigDefaultForKey");function jfe(t){return t.get(Dn).getExplicitlySetConfigs()}a(jfe,"getExplicitlySetConfigs");var JJo={[Ue.DebugOverrideCppHeadersEnableSwitch]:!1,[Ue.RelatedFilesVSCodeCSharp]:!1,[Ue.RelatedFilesVSCodeTypeScript]:!1,[Ue.RelatedFilesVSCode]:!1,[Ue.IncludeNeighboringFiles]:!1,[Ue.ExcludeRelatedFiles]:!1,[Ue.ContextProviders]:[],[Ue.DebugUseEditorFetcher]:null,[Ue.DebugUseElectronFetcher]:null,[Ue.DebugOverrideLogLevels]:{},[Ue.DebugSnippyOverrideUrl]:"",[Ue.AgentDebugLogsDirectory]:void 0,[Ue.ClaudeCliPath]:void 0,[Ue.CodexCliPath]:void 0,[Ue.OtelEnabled]:!1,[Ue.OtelEndpoint]:void 0,[Ue.OtelCaptureContent]:!1,[Ue.OtelExporterType]:"otlp-http",[Ue.OtelProtocol]:"",[Ue.OtelOutfile]:"",[Ue.OtelServiceName]:"",[Ue.OtelResourceAttributes]:{},[Ue.FetchStrategy]:"auto",[Ue.EnableBuiltInGitHubMcpServer]:!1,[Ue.ToolConfirmAutoApprove]:!1,[Ue.AutoApproveUnmatchedTerminal]:void 0,[Ue.AutoApproveUnmatchedFileOp]:void 0,[Ue.TrustToolAnnotations]:!1,[Ue.AutoApproveYoloMode]:!1,[Ue.EditorHandlesAllConfirmation]:!1,[Ue.MaxToolCallingLoop]:25,[Ue.AutoCompress]:!1,[Ue.AnthropicThinkingBudgetToken]:1024,[Ue.EnableSkills]:!1,[Ue.EnableCloudSandbox]:!1,[Ue.EnableOrgSkills]:!0,[Ue.EnableHooks]:!1,[Ue.SystemHookTools]:void 0,[Ue.EnableSandbox]:!1,[Ue.SandboxAddCurrentWorkingDirectory]:void 0,[Ue.SandboxAuth]:void 0,[Ue.SandboxAllowDevToolAccess]:void 0,[Ue.SandboxAllowBypass]:void 0,[Ue.SandboxMcpServers]:void 0,[Ue.SandboxLspServers]:void 0,[Ue.SandboxUserPolicy]:void 0,[Ue.EnablePlugins]:!1,[Ue.EnableEnsemble]:!0,[Ue.EnableCustomAgents]:!0,[Ue.EnableOrgCustomAgents]:!0,[Ue.EnableOrgCustomInstructions]:!0,[Ue.UseSessionModelForBuiltinSubagents]:!1,[Ue.UseAgentsMd]:!1,[Ue.UseNestedAgentsMd]:!1,[Ue.UseClaudeMd]:!1,[Ue.UseNestedClaudeMd]:!1,[Ue.UseSubsetMatching]:null,[Ue.ContextProviderTimeBudget]:void 0,[Ue.DebugOverrideCapiUrl]:"",[Ue.DebugTestOverrideCapiUrl]:"",[Ue.DebugOverrideProxyUrl]:"",[Ue.DebugTestOverrideProxyUrl]:"",[Ue.DebugOverrideEngine]:"",[Ue.AlwaysRequestMultiline]:void 0,[Ue.ModelAlwaysTerminatesSingleline]:void 0,[Ue.TrimCompletionsAggressively]:void 0,[Ue.CompletionsDebounce]:void 0,[Ue.NESXTab]:void 0,[Ue.UseWorkspaceContextCoordinator]:void 0,[Ue.ShowWorkspaceContextDebugger]:!1,[Ue.CompletionsDelay]:void 0,[Ue.UseSplitContextPrompt]:void 0,[Ue.UseCompletionsComparisonPanel]:void 0,[Ue.ComparisonPanelModelIds]:void 0,[Ue.ComparisonPanelRandomizedMode]:void 0,[Ue.UseFetchFetcher]:void 0,[Ue.UseChatLibCompletions]:void 0,[Ue.TranscriptDirectory]:void 0,[Ue.EnableThinking]:!0,[Ue.ShowEditorCompletions]:void 0,[Ue.EnableAutoCompletions]:void 0,[Ue.DelayCompletions]:void 0,[Ue.FilterCompletions]:void 0,[Ue.Enable]:{"*":!0,plaintext:!1,markdown:!1,scminput:!1},[Ue.EnableQuotaThresholdWarning]:!0,[Ue.McpGatewayAutoStart]:!1,[Ue.DebugFilterLogCategories]:[],[Ue.DebugOverrideEngineLegacy]:"",[Ue.DebugTestOverrideProxyUrlLegacy]:"",[Ue.DebugOverrideProxyUrlLegacy]:"",[Ue.DebugTestOverrideCapiUrlLegacy]:"",[Ue.DebugOverrideCapiUrlLegacy]:"",[Ue.HookErrorOccurredStackTrace]:!1,[Ue.NESUseExplicitRejection]:!1,[Ue.NESModelConfiguration]:void 0,[Ue.AppendPromptTokenCache]:"",[Ue.JetBrainsEdgeTasEnabled]:!0,[Ue.ExperimentsOverride]:void 0,[Ue.PromptPersistBasePath]:void 0,[Ue.AnthropicMessagesEndpoint]:"",[Ue.UseHelixFetcher]:"",[Ue.EnableMapCodeFallback]:"enabled",[Ue.SearchAgent]:"",[Ue.EnsembleEnabledOverride]:"",[Ue.PerfEnabled]:"",[Ue.NESExtendedRange]:!1,[Ue.NESEagerness]:"auto",[Ue.AuthTokenEncryption]:"",[Ue.EnableWorkspaceIndex]:!1},hZe=new Map(Object.entries(JJo));for(let t of Object.values(Ue))if(!hZe.has(t))throw new Error(`Missing config default value ${v5t}.${t}`);function Ct(t,e){return t.get(Dn).getConfig(e)}a(Ct,"getConfig");function SC(t){let e=Ct(t,Ue.EnableWorkspaceIndex);return e===!0||e==="true"}a(SC,"isSemanticSearchEnabled");function Sln(t){return t.get(Dn).dumpForTelemetry()}a(Sln,"dumpForTelemetry");var Gs=class{constructor(){this.packageJson=HZ}static{a(this,"BuildInfo")}isProduction(){return this.getBuildType()!=="dev"}getBuildType(){return this.packageJson.buildType}getVersion(){return this.packageJson.version}getDisplayVersion(){return this.getBuildType()==="dev"?`${this.getVersion()}-dev`:this.getVersion()}getBuild(){return this.packageJson.build}getName(){return this.packageJson.name}};function P5t(t){return t.get(Gs).isProduction()}a(P5t,"isProduction");function nhn(t){return t.get(Gs).getBuildType()==="dev"}a(nhn,"isDevBuild");function bq(t){return t.get(Gs).getBuildType()}a(bq,"getBuildType");function bln(t){return t.get(Gs).getBuild()}a(bln,"getBuild");function ZI(t){return t.get(Gs).getVersion()}a(ZI,"getVersion");var ma=class{constructor(e,r,n,o="none",s="desktop"){this.sessionId=e;this.machineId=r;this.devDeviceId=n;this.remoteName=o;this.uiKind=s}static{a(this,"EditorSession")}};function qI({name:t,version:e}){return`${t}/${e}`}a(qI,"formatNameAndVersion");var wr=class{static{a(this,"EditorAndPluginInfo")}getCopilotIntegrationId(){}getEditorPluginSpecificFilters(){return[]}getEditorIdentity(){return AHe({editor:this.getEditorInfo(),plugin:this.getEditorPluginInfo()})}isEditorPluginInfoKnown(){return!0}};function Xpn(t){let e=t.getCopilotIntegrationId();if(e)return e;switch(t.getEditorPluginInfo().name){case"copilot-intellij":return"jetbrains-chat";case"copilot":case"copilot-vs":return;default:return"jetbrains-chat"}}a(Xpn,"getIntegrationId");function Hm(t){let e=t.get(wr);return{"Editor-Version":qI(e.getEditorInfo()),"Editor-Plugin-Version":qI(e.getEditorPluginInfo()),"Copilot-Language-Server-Version":ZI(t)}}a(Hm,"editorVersionHeaders");var PSn="Iv1.b507a08c87ecfe98",ZJo="350ee525b5da0e4a54c6e8e043edc1b99cc02f19",kde="Ov23liV9UpD7Rnfnskm3",XJo="5509a52e4c525cd594a6fba9147ff6cc2388dd9f",eZo={[PSn]:ZJo,[kde]:XJo},em=class{static{a(this,"GitHubAppInfo")}findAppIdToAuthenticate(){return this.githubAppId??PSn}findAppSecretToAuthenticate(){let e=this.findAppIdToAuthenticate(),r=eZo[e];if(!r)throw new Error(`GitHubAppInfo: No app secret found for app ID: ${e}`);return r}};var ir=class{static{a(this,"Fetcher")}getImplementation(){return this}};function zZ(t,e,r,n,o,s,c,l,u,d,f,p,m=!1,g=[]){let A=l?.["x-api-key"],y=m||typeof A=="string"&&A.length>0,v={...l,...y?{}:{Authorization:`Bearer ${r}`},...Hm(t)};d===void 0&&(v["Openai-Organization"]="github-copilot",v["X-Request-Id"]=o,v["VScode-SessionId"]=t.get(ma).sessionId,v["VScode-MachineId"]=t.get(ma).machineId,v["X-GitHub-Api-Version"]="2026-01-09"),n&&(v["OpenAI-Intent"]=n);let E={method:"POST",headers:v,json:s,timeout:u};if(f&&p){let T=[...r?[r]:[],...g,...Object.entries(v).filter(([x,w])=>w.length>0&&_He.has(x.toLowerCase())).map(([,x])=>x)];f.logRequest({timestamp:new Date().toISOString(),requestId:o,method:"POST",url:e,headers:v,messages:p,body:s,sensitiveValues:T})}let _=t.get(ir);if(c){let T=new AbortController;c.onCancellationRequested(()=>{vt(t,"networking.cancelRequest",cr.createAndMarkAsIssued({headerRequestId:o})),T.abort()}),E.signal=T.signal}return _.fetch(e,E).catch(T=>{if(tZo(T))return vt(t,"networking.disconnectAll"),_.disconnectAll().then(()=>_.fetch(e,E));throw T})}a(zZ,"postRequest");function tZo(t){return t instanceof Error?t.message=="ERR_HTTP2_GOAWAY_SESSION"?!0:"code"in t?t.code=="ECONNRESET"||t.code=="ETIMEDOUT"||t.code=="ERR_HTTP2_INVALID_SESSION":!1:!1}a(tZo,"isInterruptedNetworkError");var rZo=new Set(["ERR_WORKER_OUT_OF_MEMORY","ENOMEM"]);function nZo(t){return rZo.has(t.code??"")||t.name==="RangeError"&&t.message==="WebAssembly.Memory(): could not allocate memory"}a(nZo,"isOomError");function GZ(t,e,r,n=an){if(!zh(e)){if(e instanceof Error){let o=e;nZo(o)?t.get(bs).setWarning("cls",{message:"Out of memory"}):o.code==="EMFILE"||o.code==="ENFILE"?t.get(bs).setWarning("cls",{message:"Too many open files"}):o.code==="CopilotPromptLoadFailure"?t.get(bs).setWarning("cls",{message:"Corrupted Copilot installation"}):`${o.code}`.startsWith("CopilotPromptWorkerExit")?t.get(bs).setWarning("cls",{message:"Worker unexpectedly exited"}):o.syscall==="uv_cwd"&&o.code==="ENOENT"&&t.get(bs).setWarning("cls",{message:"Current working directory does not exist"})}n.exception(t,e,r)}}a(GZ,"handleException");function kSn(t){process.addListener("uncaughtException",r=>{GZ(t,r,"uncaughtException")});let e=!1;process.addListener("unhandledRejection",r=>{if(!e)try{e=!0,GZ(t,r,"unhandledRejection")}finally{e=!1}})}a(kSn,"registerDefaultHandlers");function DSn(){jj("o200k_base").catch(()=>{})}a(DSn,"prewarmTokenizers");h();h();h();var i8={abap:{extensions:[".abap"]},aspdotnet:{extensions:[".asax",".ascx",".ashx",".asmx",".aspx",".axd"]},bat:{extensions:[".bat",".cmd"]},bibtex:{extensions:[".bib",".bibtex"]},blade:{extensions:[".blade",".blade.php"]},BluespecSystemVerilog:{extensions:[".bsv"]},c:{extensions:[".c",".cats",".h",".h.in",".idc"]},csharp:{extensions:[".cake",".cs",".cs.pp",".csx",".linq"]},cpp:{extensions:[".c++",".cc",".cp",".cpp",".cppm",".cxx",".h",".h++",".hh",".hpp",".hxx",".idl",".inc",".inl",".ino",".ipp",".ixx",".rc",".re",".tcc",".tpp",".txx",".i"]},cobol:{extensions:[".cbl",".ccp",".cob",".cobol",".cpy"]},css:{extensions:[".css",".wxss"]},clojure:{extensions:[".bb",".boot",".cl2",".clj",".cljc",".cljs",".cljs.hl",".cljscm",".cljx",".edn",".hic"],filenames:["riemann.config"]},ql:{extensions:[".ql",".qll"]},coffeescript:{extensions:["._coffee",".cake",".cjsx",".coffee",".iced"],filenames:["Cakefile"]},cuda:{extensions:[".cu",".cuh"]},dart:{extensions:[".dart"]},dockerfile:{extensions:[".containerfile",".dockerfile"],filenames:["Containerfile","Dockerfile"]},dotenv:{extensions:[".env"],filenames:[".env",".env.ci",".env.dev",".env.development",".env.development.local",".env.example",".env.local",".env.prod",".env.production",".env.sample",".env.staging",".env.test",".env.testing"]},html:{extensions:[".ect",".ejs",".ejs.t",".jst",".hta",".htm",".html",".html.hl",".html5",".inc",".jsp",".njk",".tpl",".twig",".wxml",".xht",".xhtml",".phtml",".liquid"]},elixir:{extensions:[".ex",".exs"],filenames:["mix.lock"]},erlang:{extensions:[".app",".app.src",".erl",".es",".escript",".hrl",".xrl",".yrl"],filenames:["Emakefile","rebar.config","rebar.config.lock","rebar.lock"]},fsharp:{extensions:[".fs",".fsi",".fsx"]},go:{extensions:[".go"]},groovy:{extensions:[".gradle",".groovy",".grt",".gtpl",".gvy",".jenkinsfile"],filenames:["Jenkinsfile","Jenkinsfile"]},graphql:{extensions:[".gql",".graphql",".graphqls"]},terraform:{extensions:[".hcl",".nomad",".tf",".tfvars",".workflow"]},hlsl:{extensions:[".cginc",".fx",".fxh",".hlsl",".hlsli"]},erb:{extensions:[".erb",".erb.deface",".rhtml"]},razor:{extensions:[".cshtml",".razor"]},haml:{extensions:[".haml",".haml.deface"]},handlebars:{extensions:[".handlebars",".hbs"]},haskell:{extensions:[".hs",".hs-boot",".hsc"]},ini:{extensions:[".cfg",".cnf",".dof",".ini",".lektorproject",".prefs",".pro",".properties",".url"],filenames:[".buckconfig",".coveragerc",".flake8",".pylintrc","HOSTS","buildozer.spec","hosts","pylintrc","vlcrc"]},json:{extensions:[".4DForm",".4DProject",".JSON-tmLanguage",".avsc",".geojson",".gltf",".har",".ice",".json",".json.example",".jsonl",".mcmeta",".sarif",".tact",".tfstate",".tfstate.backup",".topojson",".webapp",".webmanifest",".yy",".yyp"],filenames:[".all-contributorsrc",".arcconfig",".auto-changelog",".c8rc",".htmlhintrc",".imgbotconfig",".nycrc",".tern-config",".tern-project",".watchmanconfig","MODULE.bazel.lock","Package.resolved","Pipfile.lock","bun.lock","composer.lock","deno.lock","flake.lock","mcmod.info"]},jsonc:{extensions:[".code-snippets",".code-workspace",".jsonc",".sublime-build",".sublime-color-scheme",".sublime-commands",".sublime-completions",".sublime-keymap",".sublime-macro",".sublime-menu",".sublime-mousemap",".sublime-project",".sublime-settings",".sublime-theme",".sublime-workspace",".sublime_metrics",".sublime_session"],filenames:[".babelrc",".devcontainer.json",".eslintrc.json",".jscsrc",".jshintrc",".jslintrc",".swcrc","api-extractor.json","argv.json","devcontainer.json","extensions.json","jsconfig.json","keybindings.json","language-configuration.json","launch.json","profiles.json","settings.json","tasks.json","tsconfig.json","tslint.json"]},java:{extensions:[".jav",".java",".jsh"]},javascript:{extensions:["._js",".bones",".cjs",".es",".es6",".frag",".gs",".jake",".javascript",".js",".jsb",".jscad",".jsfl",".jslib",".jsm",".jspre",".jss",".mjs",".njs",".pac",".sjs",".ssjs",".xsjs",".xsjslib"],filenames:["Jakefile"]},julia:{extensions:[".jl"]},kotlin:{extensions:[".kt",".ktm",".kts"]},less:{extensions:[".less"]},lua:{extensions:[".fcgi",".lua",".luau",".nse",".p8",".pd_lua",".rbxs",".rockspec",".wlua"],filenames:[".luacheckrc"]},makefile:{extensions:[".d",".mak",".make",".makefile",".mk",".mkfile"],filenames:["BSDmakefile","GNUmakefile","Kbuild","Makefile","Makefile.am","Makefile.boot","Makefile.frag","Makefile.in","Makefile.inc","Makefile.wat","makefile","makefile.sco","mkfile"]},markdown:{extensions:[".livemd",".markdown",".md",".mdown",".mdwn",".mdx",".mkd",".mkdn",".mkdown",".ronn",".scd",".workbook"],filenames:["contents.lr"]},"objective-c":{extensions:[".h",".m"]},"objective-cpp":{extensions:[".mm"]},php:{extensions:[".aw",".ctp",".fcgi",".inc",".install",".module",".php",".php3",".php4",".php5",".phps",".phpt",".theme"],filenames:[".php",".php_cs",".php_cs.dist","Phakefile"]},perl:{extensions:[".al",".cgi",".fcgi",".perl",".ph",".pl",".plx",".pm",".psgi",".t"],filenames:[".latexmkrc","Makefile.PL","Rexfile","ack","cpanfile","latexmkrc"]},powershell:{extensions:[".ps1",".psd1",".psm1"]},pug:{extensions:[".jade",".pug"]},python:{extensions:[".cgi",".codon",".fcgi",".gyp",".gypi",".lmi",".py",".py3",".pyde",".pyi",".pyp",".pyt",".pyw",".rpy",".sage",".spec",".tac",".wsgi",".xpy"],filenames:[".gclient","DEPS","SConscript","SConstruct","wscript"]},r:{extensions:[".r",".rd",".rsx"],filenames:[".Rprofile","expr-dist"]},ruby:{extensions:[".builder",".eye",".fcgi",".gemspec",".god",".jbuilder",".mspec",".pluginspec",".podspec",".prawn",".rabl",".rake",".rb",".rbi",".rbuild",".rbw",".rbx",".ru",".ruby",".spec",".thor",".watchr"],filenames:[".irbrc",".pryrc",".simplecov","Appraisals","Berksfile","Brewfile","Buildfile","Capfile","Dangerfile","Deliverfile","Fastfile","Gemfile","Guardfile","Jarfile","Mavenfile","Podfile","Puppetfile","Rakefile","Snapfile","Steepfile","Thorfile","Vagrantfile","buildfile"]},rust:{extensions:[".rs",".rs.in"]},scss:{extensions:[".scss"]},sql:{extensions:[".cql",".ddl",".inc",".mysql",".prc",".sql",".tab",".udf",".viw"]},sass:{extensions:[".sass"]},scala:{extensions:[".kojo",".sbt",".sc",".scala"]},shellscript:{extensions:[".bash",".bats",".cgi",".command",".fcgi",".fish",".ksh",".sh",".sh.in",".tmux",".tool",".trigger",".zsh",".zsh-theme"],filenames:[".bash_aliases",".bash_functions",".bash_history",".bash_logout",".bash_profile",".bashrc",".cshrc",".envrc",".flaskenv",".kshrc",".login",".profile",".tmux.conf",".zlogin",".zlogout",".zprofile",".zshenv",".zshrc","9fs","PKGBUILD","bash_aliases","bash_logout","bash_profile","bashrc","cshrc","gradlew","kshrc","login","man","profile","tmux.conf","zlogin","zlogout","zprofile","zshenv","zshrc"]},slang:{extensions:[".fxc",".hlsl",".s",".slang",".slangh",".usf",".ush",".vfx"]},slim:{extensions:[".slim"]},solidity:{extensions:[".sol"]},stylus:{extensions:[".styl"]},svelte:{extensions:[".svelte"]},swift:{extensions:[".swift"]},systemverilog:{extensions:[".sv",".svh",".vh"]},typescriptreact:{extensions:[".tsx"]},latex:{extensions:[".aux",".bbx",".cbx",".cls",".dtx",".ins",".lbx",".ltx",".mkii",".mkiv",".mkvi",".sty",".tex",".toc"]},typescript:{extensions:[".cts",".mts",".ts"]},verilog:{extensions:[".v",".veo"]},vim:{extensions:[".vba",".vim",".vimrc",".vmb"],filenames:[".exrc",".gvimrc",".nvimrc",".vimrc","_vimrc","gvimrc","nvimrc","vimrc"]},vb:{extensions:[".vb",".vbhtml",".Dsr",".bas",".cls",".ctl",".frm",".vbs"]},vue:{extensions:[".nvue",".vue"]},xml:{extensions:[".adml",".admx",".ant",".axaml",".axml",".builds",".ccproj",".ccxml",".clixml",".cproject",".cscfg",".csdef",".csl",".csproj",".ct",".depproj",".dita",".ditamap",".ditaval",".dll.config",".dotsettings",".filters",".fsproj",".fxml",".glade",".gml",".gmx",".gpx",".grxml",".gst",".hzp",".iml",".ivy",".jelly",".jsproj",".kml",".launch",".mdpolicy",".mjml",".mod",".mojo",".mxml",".natvis",".ncl",".ndproj",".nproj",".nuspec",".odd",".osm",".pkgproj",".plist",".pluginspec",".proj",".props",".ps1xml",".psc1",".pt",".pubxml",".qhelp",".rdf",".res",".resx",".rss",".sch",".scxml",".sfproj",".shproj",".srdf",".storyboard",".sublime-snippet",".svg",".sw",".targets",".tml",".typ",".ui",".urdf",".ux",".vbproj",".vcxproj",".vsixmanifest",".vssettings",".vstemplate",".vxml",".wixproj",".workflow",".wsdl",".wsf",".wxi",".wxl",".wxs",".x3d",".xacro",".xaml",".xib",".xlf",".xliff",".xmi",".xml",".xml.dist",".xmp",".xproj",".xsd",".xspec",".xul",".zcml"],filenames:[".classpath",".cproject",".project","App.config","NuGet.config","Settings.StyleCop","Web.Debug.config","Web.Release.config","Web.config","packages.config"]},xsl:{extensions:[".xsl",".xslt"]},yaml:{extensions:[".mir",".reek",".rviz",".sublime-syntax",".syntax",".yaml",".yaml-tmlanguage",".yaml.sed",".yml",".yml.mysql"],filenames:[".clang-format",".clang-tidy",".clangd",".gemrc","CITATION.cff","glide.lock","pixi.lock","yarn.lock"]},javascriptreact:{extensions:[".jsx"]},legend:{extensions:[".pure"]}};h();h();var MSn=[".ejs",".erb",".haml",".hbs",".j2",".jinja",".jinja2",".liquid",".mustache",".njk",".php",".pug",".slim",".webc"],NSn={".php":[".blade"]},Gj=Object.keys(i8).flatMap(t=>i8[t].extensions);var b$t=he(require("node:path"));var $fe=class{constructor(e,r,n){this.languageId=e;this.isGuess=r;this.fileExtension=n}static{a(this,"Language")}},ADe=class{static{a(this,"LanguageDetection")}},T$t=new Map,Hfe=new Map;for(let[t,{extensions:e,filenames:r}]of Object.entries(i8)){for(let n of e)T$t.set(n,[...T$t.get(n)??[],t]);for(let n of r??[])Hfe.set(n,[...Hfe.get(n)??[],t])}var I$t=class extends ADe{static{a(this,"FilenameAndExensionLanguageDetection")}detectLanguage(e){let r=To(e.uri),n=b$t.extname(r).toLowerCase(),o=this.extensionWithoutTemplateLanguage(r,n),s=this.detectLanguageId(r,o),c=this.computeFullyQualifiedExtension(n,o);return s?new $fe(s.languageId,s.isGuess,c):new $fe(e.languageId,!0,c)}extensionWithoutTemplateLanguage(e,r){if(MSn.includes(r)){let n=e.substring(0,e.lastIndexOf(".")),o=b$t.extname(n).toLowerCase();if(o.length>0&&Gj.includes(o)&&this.isExtensionValidForTemplateLanguage(r,o))return o}return r}isExtensionValidForTemplateLanguage(e,r){let n=NSn[e];return!n||n.includes(r)}detectLanguageId(e,r){if(Hfe.has(e))return{languageId:Hfe.get(e)[0],isGuess:!1};let n=T$t.get(r)??[];if(n.length>0)return{languageId:n[0],isGuess:n.length>1};for(;e.includes(".");)if(e=e.replace(/\.[^.]*$/,""),Hfe.has(e))return{languageId:Hfe.get(e)[0],isGuess:!1}}computeFullyQualifiedExtension(e,r){return e!==r?r+e:e}},w$t=class extends ADe{constructor(r){super();this.delegate=r}static{a(this,"GroupingLanguageDetection")}detectLanguage(r){let n=this.delegate.detectLanguage(r),o=n.languageId;return o==="c"||o==="cpp"?new $fe("cpp",n.isGuess,n.fileExtension):n}},x$t=class extends ADe{constructor(r){super();this.delegate=r}static{a(this,"ClientProvidedLanguageDetection")}detectLanguage(r){return r.uri.startsWith("untitled:")||r.uri.startsWith("vscode-notebook-cell:")?new $fe(r.languageId,!0,""):this.delegate.detectLanguage(r)}},iZo=new w$t(new x$t(new I$t));function pB({uri:t,languageId:e}){let r=iZo.detectLanguage({uri:t,languageId:"UNKNOWN"});return r.languageId==="UNKNOWN"?e:r.languageId}a(pB,"detectLanguage");h();h();h();h();function ag(t){if(t.isCancellationRequested)throw new mZe}a(ag,"throwIfCancellationRequested");function B2(t){return t instanceof mZe?!0:t instanceof Error&&t.name===R$t&&t.message===R$t}a(B2,"isCancellationError");var mZe=class extends Error{static{a(this,"CancellationError")}constructor(){super(R$t),this.name=this.message}},R$t="Canceled",gZe=class{constructor(){this.items=[]}static{a(this,"Stack")}push(e){this.items.push(e)}pop(){return this.items.pop()}peek(){return this.items[this.items.length-1]}tryPeek(){return this.items.length>0}toArray(){return this.items}};function VZ(t){switch(t){case 0:case 2:case 7:case 8:case 11:case 12:case 13:case 14:return!0;default:return!1}}a(VZ,"isTypeDefinition");var dd=class t{static{a(this,"TextRange")}static{this.empty=new t(0,0)}constructor(e,r){this.start=e,this.length=r}static fromBounds(e,r){return new t(e,r-e)}get end(){return this.start+this.length}contains(e){return this.start<=e&&this.end>=e}containsRange(e){return this.start<=e.start&&this.end>=e.end}equals(e){return this.start===e.start&&this.length===e.length}getText(e){return e.slice(this.start,this.end)}getTextWithIndentation(e,r){let n=[],o=this.start;for(o=LSn(e,e.length,o),OSn(n,r);o<this.end;)e[o]!=="\r"&&e[o]!==`
|
|
1919
|
+
] @statement`}};var fB=class{constructor(e,r,n){this.languageId=e;this.prefix=r;this.completion=n}static{a(this,"BlockTrimmer")}static isSupported(e){return kA.isSupported(e)}static isTrimmedByDefault(e){return kA.isTrimmedByDefault(e)}async withParsedStatementTree(e){var n=[];try{let r=A5t(n,kA.create(this.languageId,this.prefix+this.completion,this.prefix.length,this.prefix.length+this.completion.length));await r.build();return await e(r)}catch(o){var s=o,c=!0}finally{y5t(n,s,c)}}trimmedCompletion(e){return e===void 0?this.completion:this.completion.substring(0,e)}getStatementAtCursor(e){return e.statementAt(Math.max(this.prefix.length-1,0))??e.statements[0]}getContainingBlockOffset(e){let r;if(e&&this.isCompoundStatement(e))r=e;else if(e){let n=e.parent;for(;n&&!this.isCompoundStatement(n);)n=n.parent;r=n}if(r){let n=this.asCompletionOffset(r.node.endIndex);if(n&&this.completion.substring(n).trim()!=="")return n}}hasNonStatementContentAfter(e){if(!e||!e.nextSibling)return!1;let r=this.asCompletionOffset(e.node.endIndex),n=this.asCompletionOffset(e.nextSibling.node.startIndex);return this.completion.substring(Math.max(0,r??0),Math.max(0,n??0)).trim()!==""}asCompletionOffset(e){return e===void 0?void 0:e-this.prefix.length}isCompoundStatement(e){return e.isCompoundStatementType||e.children.length>0}};var pZe=class extends fB{constructor(r,n,o,s=3,c=7){super(r,n,o);this.lineLimit=s;this.lookAhead=c;let l=[...this.completion.matchAll(/\n/g)],u=this.lineLimit+this.lookAhead;l.length>=this.lineLimit&&this.lineLimit>0&&(this.limitOffset=l[this.lineLimit-1].index),l.length>=u&&u>0&&(this.lookAheadOffset=l[u-1].index)}static{a(this,"TerseBlockTrimmer")}async getCompletionTrimOffset(){return await this.withParsedStatementTree(r=>{let n=r.statementAt(this.stmtStartPos()),o=this.getContainingBlockOffset(n);return o=this.trimAtFirstBlankLine(o),n&&(o=this.trimAtStatementChange(n,o)),this.limitOffset&&this.lookAheadOffset&&(o===void 0||o>this.lookAheadOffset)?this.limitOffset:o})}stmtStartPos(){let r=this.completion.match(/\S/);return r&&r.index!==void 0?this.prefix.length+r.index:Math.max(this.prefix.length-1,0)}trimAtFirstBlankLine(r){let n=[...this.trimmedCompletion(r).matchAll(/\r?\n\s*\r?\n/g)];for(;n.length>0&&(r===void 0||r>n[0].index);){let o=n.shift();if(this.completion.substring(0,o.index).trim()!=="")return o.index}return r}trimAtStatementChange(r,n){let o=this.prefix.length,s=this.prefix.length+(n??this.completion.length);if(r.node.endIndex>o&&this.isCompoundStatement(r))return r.nextSibling&&r.node.endIndex<s?this.asCompletionOffset(r.node.endIndex):n;let c=r,l=r.nextSibling;for(;l&&l.node.endIndex<=s&&!this.hasNonStatementContentAfter(c)&&!this.isCompoundStatement(l);)c=l,l=l.nextSibling;return l&&c.node.endIndex>o&&c.node.endIndex<s?this.asCompletionOffset(c.node.endIndex):n}};async function ISn(t,e){var l=[];try{let r=t.getText();let n=t.offsetAt(e);let o=A5t(l,kA.create(t.detectedLanguageId,r,0,r.length));await o.build();let s=o.statementAt(n);if(!s)return"non-block";if(!s.isCompoundStatementType&&s.children.length===0)return s.parent&&!s.nextSibling&&s.node.endPosition.row<=e.line?"block-end":s.parent?"mid-block":"non-block";if(s.children.length===0)return"empty-block";let c=s.children[s.children.length-1];if(n<c.node.startIndex)return"mid-block";return"block-end"}catch(u){var d=u,f=!0}finally{y5t(l,d,f)}}a(ISn,"getBlockPositionType");h();function kJo(t){return t.HTTPS_PROXY||t.https_proxy||t.HTTP_PROXY||t.http_proxy}a(kJo,"getProxyFromEnvironment");function DJo(t){return t.NODE_TLS_REJECT_UNAUTHORIZED!=="0"}a(DJo,"getRejectUnauthorizedFromEnvironment");var wSn=b.Object({proxy:b.Optional(b.String()),proxyStrictSSL:b.Optional(b.Boolean()),proxyAuthorization:b.Optional(b.String()),proxyKerberosServicePrincipal:b.Optional(b.String()),noProxy:b.Optional(b.Array(b.String()))});function xSn(t){let e=kJo(t),r=gDe({proxy:e,proxyStrictSSL:DJo(t)}),n=t.GH_COPILOT_KERBEROS_SERVICE_PRINCIPAL??t.GITHUB_COPILOT_KERBEROS_SERVICE_PRINCIPAL??t.AGENT_KERBEROS_SERVICE_PRINCIPAL;return n&&(r.proxyKerberosServicePrincipal=n),r}a(xSn,"getHttpSettingsFromEnvironment");function gDe(t){if(!t.proxy)return{...t,proxy:""};try{let{protocol:e,host:r,username:n,password:o,pathname:s,search:c,hash:l}=new URL(t.proxy);return{...t,proxy:`${e}//${r}${s}${c}${l}`,proxyAuthorization:t.proxyAuthorization||MJo(n,o),noProxy:t.noProxy||[]}}catch{return{...t,proxy:""}}}a(gDe,"normalizeHttpSettings");function MJo(t,e){return!t||!e?"":`${decodeURIComponent(t)}:${decodeURIComponent(e)}`}a(MJo,"getAuth");var HZ={};so(HZ,{anthropicClaude:()=>qJo,build:()=>FJo,buildType:()=>UJo,default:()=>VJo,dependencies:()=>$Jo,description:()=>LJo,devDependencies:()=>HJo,displayName:()=>OJo,engines:()=>QJo,name:()=>NJo,overrides:()=>zJo,overridesComments:()=>GJo,scripts:()=>jJo,version:()=>BJo});var NJo="copilot",OJo="GitHub Copilot",LJo="Your AI pair programmer",BJo="1.567.1",FJo="207",UJo="prod",QJo={node:">=22.13.0",npm:">=11.6.0 <12.0.0"},qJo={cliPackageVersion:"2.1.159"},jJo={build:"tsx esbuild.ts",clean:"./script/build/clean.sh",compress:"tsx ./script/compressTokenizer.ts",generate_languages:"tsx script/generateLanguages.ts && prettier --write lib/src/language/generatedLanguages.ts",get_token:"tsx script/deviceFlow.ts --save-as-test-token",lint:'run-p --aggregate-output "lint:*"',"lint:deps":"depcruise -c .dependency-cruiser.js .","lint:eslint":"eslint -f visualstudio --quiet --cache .","lint:gdpr":"tsx script/checkGdprComments.ts","lint:overrides":"tsx script/checkOverridesDocumented.ts","lint:prettier":"prettier --check . 2>&1","lint:types":"tsc --noEmit",manage_auth_db:"tsx script/manageAuthDb.ts",prebuild:"npm install",pretest:"npm run build","pretest:headless":"npm run build","pretest:agent-e2e-full":"npm run build","pretest:agent-e2e":"npm run build","pretest:lsp-client":"npm run build","pretest:lib-e2e":"npm run build",prewatch:"npm run build","prewatch:esbuild":"npm run build",start:"npm run watch",test:'npm-run-all "test:headless --ignore-scripts" lint',"test:headless":'npm-run-all test:lib test:agent test:mcp-int "test:lib-e2e --ignore-scripts" test:prompt "test:lsp-client --ignore-scripts" lint',"test:agent":'mocha "agent/src/**/*.test.{ts,tsx}"',"test:agent-e2e":'mocha "agent/e2e/**/*.test.{ts,tsx}" --exclude "agent/e2e/**/*.daily.test.{ts,tsx}"',"test:agent-e2e-full":'mocha "agent/e2e/**/*.test.{ts,tsx}"',"test:workflow":"node --test .github/workflows/scripts/release-merge-back/release-merge-back.test.mjs","test:lib":'mocha "lib/src/**/*.test.{ts,tsx}" "script/**/*.test.{ts,tsx}" --exclude "lib/src/**/*.int.test.ts"',"test:lib-int":'mocha "lib/src/**/*.int.test.ts"',"test:mcp-int":'mocha "lib/src/mcp/**/*.int.test.ts" "lib/src/mcpGateway/**/*.int.test.ts" "lib/src/backgroundAgent/ide/**/*.int.test.ts"',"test:lib-e2e":'mocha "lib/e2e/src/**/*.test.{ts,tsx}" --exclude "lib/e2e/src/prompt/**/*.test.ts"',"test:lib-e2e-no-ci":'mocha "lib/e2e/no-ci/**/*.test.{ts,tsx}"',"test:lib-prompt-e2e":'mocha "lib/e2e/src/prompt/prompt.test.ts"',"test:lib-prompt-e2e-perf":"INCLUDE_PERFORMANCE=true npm run test:lib-prompt-e2e","test:lsp-client":'mocha "lsp-client/test/*.test.{ts,tsx}"',"test:pkg-runtime":"tsx script/smokeCopilotRuntimePkg.ts","test:prompt":'mocha "prompt/test/**/*.test.{ts,tsx}"',"test:prepare-msbench":"tsx script/setupMsbench.ts","test:run-msbench":"tsx lsp-client/test/msbench/agent/index.ts",watch:'run-p "watch:esbuild --ignore-scripts" "watch:types -- --preserveWatchOutput"',"watch:esbuild":"tsx esbuild.ts --watch","watch:types":"tsc --noEmit --watch"},HJo={"@azure/identity":"^4.13.3","@azure/keyvault-secrets":"^4.11.2","@github/prettier-config":"0.0.6","@limegrass/eslint-plugin-import-alias":"^1.6.1","@microsoft/agent-host-protocol":"^1.0.0","@types/crypto-js":"^4.2.2","@types/diff":"^8.0.0","@types/git-url-parse":"^16.0.2","@types/js-yaml":"^4.0.6","@types/kerberos":"^1.1.2","@types/markdown-it":"^14.2.0","@types/mocha":"^10.0.10","@types/node":"~22.13.0","@types/semver":"^7.8.0","@types/sinon":"^22.0.0","@types/toposort":"^2.0.7","@types/vscode":"1.138.0","@types/which":"^3.0.0","@types/yargs":"^17.0.35","@vscode/tree-sitter-wasm":"0.0.5-php.2","@yao-pkg/pkg":"^6.24.0",boxen:"^8.0.1",chalk:"^5.6.2","dependency-cruiser":"^18.2.0",esbuild:"^0.28.2","esbuild-plugin-copy":"^2.1.1",eslint:"^9.39.5","eslint-formatter-visualstudio":"^9.0.1","eslint-plugin-mocha":"^10.5.0",fflate:"^0.8.2",globals:"^17.12.0","js-yaml":"^4.2.0",mocha:"^11.8.0","mocha-junit-reporter":"^2.2.1","mocha-multi-reporters":"^1.5.2","npm-run-all":"^4.1.5",openai:"^7.20.0",prettier:"^3.5.3","prettier-plugin-organize-imports":"^4.2.0","simple-git":"^4.0.2",sinon:"^22.1.0","tree-sitter-bash":"^0.23.0","tree-sitter-powershell":"0.25.9","ts-dedent":"^2.3.0",tsx:"^4.23.12",typescript:"^5.9.3","typescript-eslint":"^8.39.1","vscode-dts":"^0.3.3"},$Jo={"@adobe/helix-fetch":"github:devm33/helix-fetch#2a08fa939591a0e14f34f611adcc3ed767579e9a","@agentclientprotocol/sdk":"^1.4.0","@anthropic-ai/claude-agent-sdk":"0.3.159","@anthropic-ai/sdk":"^0.98.0","@github/copilot":"1.0.105","@github/copilot-sdk":"1.0.28","@github/keytar":"7.10.6","@github/memoize":"1.1.5","@microsoft/1ds-core-js":"^4.4.3","@microsoft/1ds-post-js":"^4.4.3","@microsoft/applicationinsights-core-js":"^3.4.3","@microsoft/applicationinsights-web-basic":"^3.4.3","@modelcontextprotocol/client":"^2.4.0","@modelcontextprotocol/node":"^2.1.2","@modelcontextprotocol/server":"^2.4.0","@octokit/graphql":"^9.0.5","@octokit/rest":"^22.0.1","@parcel/watcher":"^2.6.0","@sinclair/typebox":"^0.34.52","@vscode/chat-lib":"0.70.0","@vscode/codicons":"^0.0.45","@vscode/deviceid":"github:ghc-jetbrains/vscode-deviceid#f0e5738cd362ef20a09aeb30c3a8be99a9a710f5","@vscode/policy-watcher":"^1.4.0","@vscode/prompt-tsx":"^0.4.0-alpha.9","@vscode/webview-ui-toolkit":"^1.3.1","crypto-js":"^4.2.0",diff:"^9.0.0",dldr:"^0.0.10",events:"^3.3.0","git-url-parse":"^16.1.0",glob:"^11.1.0","jsonc-parser":"^3.3.1",kerberos:"^2.2.0","mac-ca":"^3.1.3","markdown-it":"^15.0.2",minimatch:"^10.2.6",open:"^11.0.4",semver:"^7.8.5",shiki:"~1.15.0","source-map-support":"^0.5.21",toposort:"^2.0.2",undici:"^7.29.1",uuid:"^14.0.0","vscode-languageclient":"^9.0.0","vscode-languageserver":"^9.0.0","vscode-languageserver-protocol":"^3.17","vscode-languageserver-textdocument":"~1.0.14","vscode-uri":"^3.2.0","web-tree-sitter":"^0.23.0",which:"^7.0.0","windows-ca-certs":"^0.2.2",ws:"^8.21.3",yargs:"^18.1.0"},zJo={fsevents:"<0","@github/copilot-linuxmusl-arm64":"<0","@github/copilot-linuxmusl-x64":"<0",bindings:"npm:bundled-bindings@^1.5.0",jws:"^3.2.3",tar:"7.5.21","serialize-javascript":"^7.0.5",uuid:"^14.0.0","ip-address":"^10.1.1","fast-uri":"^3.1.8"},GJo={"//":"Rationale for each entry in `overrides`. Required by `npm run lint:overrides` (script/checkOverridesDocumented.ts). Each value should cover: why (CVE/GHSA or build-hack reason), which direct dep pulls in the vulnerable transitive, and the remove-when condition.",fsevents:"Build hack: macOS-only optional native dep; '<0' is an impossible semver that force-skips install on Linux/Windows pkg builds. Permanent \u2014 keep until @yao-pkg/pkg handles macOS-only optionalDependencies natively. See commit d635096c.","@github/copilot-linuxmusl-arm64":"Build hack: @github/copilot declares a Linux musl optional runtime package, but CLS does not support musl. '<0' prevents npm from installing the unsupported runtime. Drop only if CLS adds musl support.","@github/copilot-linuxmusl-x64":"Build hack: @github/copilot declares a Linux musl optional runtime package, but CLS does not support musl. '<0' prevents npm from installing the unsupported runtime. Drop only if CLS adds musl support.",bindings:"Build hack: alias to bundled-bindings fork that resolves .node native addon paths after pkg/esbuild bundling. Required by kerberos. Drop when upstream `bindings` adopts platform-specific path resolution. See commits c4461665 and b55ece83.",jws:"CVE GHSA-869p-cjfg-cm3x (Improperly Verifies HMAC Signature). Pulled in by jsonwebtoken-family deps. Drop when all transitive consumers pin jws >= 3.2.3. See commit 2b5dc766.",tar:"CVE GHSA-9ppj-qmqm-q256 + GHSA-qffp-2rhf-9h96 (Symlink/Hardlink Path Traversal via Drive-Relative Linkpath), plus the 7.5.12..7.5.20 advisory run: GHSA-23hp-3jrh-7fpw / CVE-2026-59873 (critical, decompression DoS via unlimited input), GHSA-8x88-c5mf-7j5w / CVE-2026-59874 (infinite loop on negative entry size), GHSA-w8wr-v893-vjvp / CVE-2026-59871 (PAX numeric path type confusion), GHSA-gvwx-54wh-qm9j / CVE-2026-59875 (NUL byte in PAX path records), GHSA-vmf3-w455-68vh / CVE-2026-53655 (GNU long-name PAX size override file smuggling), GHSA-r292-9mhp-454m (uncontrolled recursion in mapHas/filesFilter). Pulled in by @yao-pkg/pkg (tar ^7.5.7) and node-gyp / native-build deps. Drop when transitive consumers bump tar >= 7.5.21. Dependabot alerts #170, #169, #179, #171, #168, #146. See commit e2dff0f3.","serialize-javascript":"CVE GHSA-5c6j-r48x-rmvq (RCE via RegExp.flags / Date.toISOString) + GHSA-qj8w-gfj5-8c6v (ReDoS). Pulled in by mocha 11.x (^6.0.2). Dev-only. Drop when mocha bumps to a release that carries serialize-javascript >= 7.0.3. See commit d49f75fd.",uuid:"CVE GHSA-w5hq-g745-h8pq (missing buffer bounds checks in v3/v5/v6). Pulled in by msal-node and @vscode/deviceid as uuid 8.x/9.x. Drop when both upgrade to uuid >= 14. Dependabot alert #128. See commit 6315f3f8.","ip-address":"CVE GHSA-v2v4-37r5-5v8g (XSS in Address6 HTML-emitting methods: group/link/spanAll and AddressError.parseMessage). Pulled in by @anthropic-ai/claude-agent-sdk's v1 MCP peer -> express-rate-limit. Not exploitable here (we don't render HTML or call the affected methods), but the override clears the alert. Drop when express-rate-limit bumps to a release carrying ip-address >= 10.1.1. Dependabot alert #129. See PR #854.","fast-uri":"CVE-2026-6321 GHSA-q3j6-qgpj-74h6 (host confusion via percent-encoded authority delimiters) + CVE-2026-6322 GHSA-v39h-62p7-jpjc (path traversal via percent-encoded dot segments). Pulled in by @anthropic-ai/claude-agent-sdk's v1 MCP peer -> ajv -> fast-uri. Drop when ajv bumps to a release carrying fast-uri >= 3.1.2. Dependabot alerts #132, #133."},VJo={name:NJo,displayName:OJo,description:LJo,version:BJo,build:FJo,buildType:UJo,engines:QJo,anthropicClaude:qJo,scripts:jJo,devDependencies:HJo,dependencies:$Jo,overrides:zJo,overridesComments:GJo};var Ue={Enable:"enable",EnableQuotaThresholdWarning:"quota.enableThresholdWarning",McpGatewayAutoStart:"mcpGateway.autoStart",ShowEditorCompletions:"editor.showEditorCompletions",EnableAutoCompletions:"editor.enableAutoCompletions",DelayCompletions:"editor.delayCompletions",FilterCompletions:"editor.filterCompletions",FetchStrategy:"fetchStrategy",EnableBuiltInGitHubMcpServer:"enableBuiltInGitHubMcpServer",ToolConfirmAutoApprove:"agent.toolConfirmAutoApprove",AutoApproveUnmatchedTerminal:"agent.autoApproveUnmatchedTerminal",AutoApproveUnmatchedFileOp:"agent.autoApproveUnmatchedFileOp",TrustToolAnnotations:"agent.trustToolAnnotations",AutoApproveYoloMode:"agent.autoApproveYoloMode",EditorHandlesAllConfirmation:"agent.editorHandlesAllConfirmation",MaxToolCallingLoop:"agent.maxToolCallingLoop",AutoCompress:"agent.autoCompress",AnthropicThinkingBudgetToken:"agent.anthropicThinkingBudgetToken",EnableSkills:"agent.enableSkills",EnableCloudSandbox:"agent.enableCloudSandbox",EnableOrgSkills:"agent.enableOrgSkills",EnableHooks:"agent.enableHooks",SystemHookTools:"agent.systemHookTools",EnableSandbox:"agent.sandbox.enabled",SandboxAddCurrentWorkingDirectory:"agent.sandbox.addCurrentWorkingDirectory",SandboxAuth:"agent.sandbox.auth",SandboxAllowDevToolAccess:"agent.sandbox.allowDevToolAccess",SandboxAllowBypass:"agent.sandbox.allowBypass",SandboxMcpServers:"agent.sandbox.sandboxMcpServers",SandboxLspServers:"agent.sandbox.sandboxLspServers",SandboxUserPolicy:"agent.sandbox.userPolicy",EnablePlugins:"agent.enablePlugins",EnableEnsemble:"agent.enableEnsemble",EnableCustomAgents:"agent.enableCustomAgents",EnableOrgCustomAgents:"agent.enableOrgCustomAgents",EnableOrgCustomInstructions:"agent.enableOrgCustomInstructions",UseSessionModelForBuiltinSubagents:"agent.useSessionModelForBuiltinSubagents",UseAgentsMd:"agent.useAgentsMdFile",UseNestedAgentsMd:"agent.useNestedAgentsMdFiles",UseClaudeMd:"agent.useClaudeMdFile",UseNestedClaudeMd:"agent.useNestedClaudeMdFiles",CompletionsDelay:"completionsDelay",CompletionsDebounce:"completionsDebounce",EnableThinking:"agent.enableThinking",TranscriptDirectory:"agent.transcriptDirectory",AgentDebugLogsDirectory:"agent.agentDebugLogsDirectory",ClaudeCliPath:"agent.claude.cliPath",CodexCliPath:"agent.codex.cliPath",OtelEnabled:"agent.otel.enabled",OtelEndpoint:"agent.otel.otlpEndpoint",OtelCaptureContent:"agent.otel.captureContent",OtelExporterType:"agent.otel.exporterType",OtelProtocol:"agent.otel.protocol",OtelOutfile:"agent.otel.outfile",OtelServiceName:"agent.otel.serviceName",OtelResourceAttributes:"agent.otel.resourceAttributes",NESExtendedRange:"nextEditSuggestions.extendedRange",NESEagerness:"nextEditSuggestions.eagerness",RelatedFilesVSCodeCSharp:"advanced.relatedFilesVSCodeCSharp",RelatedFilesVSCodeTypeScript:"advanced.relatedFilesVSCodeTypeScript",RelatedFilesVSCode:"advanced.relatedFilesVSCode",ContextProviders:"advanced.contextProviders",DebugOverrideLogLevels:"advanced.debug.overrideLogLevels",DebugFilterLogCategories:"advanced.debug.filterLogCategories",DebugSnippyOverrideUrl:"advanced.debug.codeRefOverrideUrl",DebugUseElectronFetcher:"advanced.debug.useElectronFetcher",DebugUseEditorFetcher:"advanced.debug.useEditorFetcher",UseSubsetMatching:"advanced.useSubsetMatching",ContextProviderTimeBudget:"advanced.contextProviderTimeBudget",DebugOverrideCapiUrl:"internal.capiUrl",DebugOverrideCapiUrlLegacy:"advanced.debug.overrideCapiUrl",DebugTestOverrideCapiUrl:"internal.capiTestUrl",DebugTestOverrideCapiUrlLegacy:"advanced.debug.testOverrideCapiUrl",DebugOverrideProxyUrl:"internal.completionsUrl",DebugOverrideProxyUrlLegacy:"advanced.debug.overrideProxyUrl",DebugTestOverrideProxyUrl:"internal.completionsTestUrl",DebugTestOverrideProxyUrlLegacy:"advanced.debug.testOverrideProxyUrl",DebugOverrideEngine:"internal.completionModel",DebugOverrideEngineLegacy:"advanced.debug.overrideEngine",AlwaysRequestMultiline:"internal.alwaysRequestMultiline",ModelAlwaysTerminatesSingleline:"internal.modelAlwaysTerminatesSingleline",TrimCompletionsAggressively:"internal.trimCompletionsAggressively",UseWorkspaceContextCoordinator:"internal.useWorkspaceContextCoordinator",ShowWorkspaceContextDebugger:"internal.showWorkspaceContextDebugger",IncludeNeighboringFiles:"internal.includeNeighboringFiles",ExcludeRelatedFiles:"internal.excludeRelatedFiles",DebugOverrideCppHeadersEnableSwitch:"internal.cppHeadersEnableSwitch",NESXTab:"internal.useXTab",NESUseExplicitRejection:"internal.nesUseExplicitRejection",NESModelConfiguration:"internal.nesModelConfiguration",UseSplitContextPrompt:"internal.useSplitContextPrompt",UseCompletionsComparisonPanel:"internal.useCompletionsComparisonPanel",ComparisonPanelModelIds:"internal.comparisonPanelModelIds",ComparisonPanelRandomizedMode:"internal.comparisonPanelRandomizedMode",UseFetchFetcher:"internal.useFetchFetcher",UseChatLibCompletions:"internal.useChatLibCompletions",JetBrainsEdgeTasEnabled:"internal.jetbrainsEdgeTasEnabled",ExperimentsOverride:"internal.experimentsOverride",HookErrorOccurredStackTrace:"internal.hookErrorOccurredStackTrace",AppendPromptTokenCache:"internal.appendPromptTokenCache",PromptPersistBasePath:"internal.promptPersistBasePath",AnthropicMessagesEndpoint:"internal.anthropic.messagesEndpoint",UseHelixFetcher:"internal.useHelixFetcher",EnableMapCodeFallback:"internal.enableMapCodeFallback",SearchAgent:"internal.searchAgent",EnsembleEnabledOverride:"internal.ensembleEnabledOverride",PerfEnabled:"internal.perf.enabled",AuthTokenEncryption:"internal.auth.tokenEncryption",EnableWorkspaceIndex:"workspaceIndex.enabled"},lDe=(o=>(o.Parsing="parsing",o.Server="server",o.ParsingAndServer="parsingandserver",o.MoreMultiline="moremultiline",o))(lDe||{});function RSn(t){return["server","parsingandserver"].includes(t)}a(RSn,"shouldDoServerTrimming");var L2=class{static{a(this,"BlockModeConfig")}},Qfe=class extends L2{static{a(this,"ConfigBlockModeConfig")}forLanguage(e,r,n){let o=e.get(or).overrideBlockMode(n);if(o)return C$t(o,r);let s=e.get(or).enableProgressiveReveal(n);return(Ct(e,Ue.AlwaysRequestMultiline)??s)||fB.isTrimmedByDefault(r)?C$t("moremultiline",r):r=="ruby"?"parsing":x1(r)?"parsingandserver":"server"}};function WJo(t){return["parsing","parsingandserver","moremultiline"].includes(t)}a(WJo,"blockModeRequiresTreeSitter");function C$t(t,e){return t==="moremultiline"&&kA.isSupported(e)?t:WJo(t)&&!x1(e)?"server":t}a(C$t,"toApplicableBlockMode");var Dn=class{static{a(this,"ConfigProvider")}getRawConfig(e){return this.getExplicitlySetConfigs().get(e)}requireReady(){return Promise.resolve()}},qfe=class extends Dn{constructor(){super(...arguments);this.onDidChangeCopilotSettings=a(()=>({dispose:a(()=>{},"dispose")}),"onDidChangeCopilotSettings");this.onDidChangeHttpSettings=this.onDidChangeCopilotSettings}static{a(this,"DefaultsOnlyConfigProvider")}getConfig(r){return YJo(r)}getOptionalConfig(r){return KJo(r)}dumpForTelemetry(){return{}}getExplicitlySetConfigs(){return new Map}getHttpSettings(){return{proxy:""}}},$Z=class extends Dn{constructor(r,n){super();this.baseConfigProvider=r;this.overrides=n;this.copilotEmitter=new Yi;this.onDidChangeCopilotSettings=this.copilotEmitter.event;this.didChangeHttpSettingsEmitter=new Yi;this.onDidChangeHttpSettings=this.didChangeHttpSettingsEmitter.event;this.httpSettings=this.baseConfigProvider.getHttpSettings()}static{a(this,"InMemoryConfigProvider")}getOptionalOverride(r){return this.overrides.get(r)}getConfig(r){return this.getOptionalOverride(r)??this.baseConfigProvider.getConfig(r)}getOptionalConfig(r){return this.getOptionalOverride(r)??this.baseConfigProvider.getOptionalConfig(r)}getRawConfig(r){return this.overrides.has(r)?this.overrides.get(r):this.baseConfigProvider.getRawConfig(r)}setConfig(r,n){this.setCopilotSettings({[r]:n})}setCopilotSettings(r){for(let[n,o]of Object.entries(r))o!==void 0?this.overrides.set(n,o):this.overrides.delete(n);this.copilotEmitter.fire(this)}getExplicitlySetConfigs(){let r=new Map(this.baseConfigProvider.getExplicitlySetConfigs());for(let[n,o]of this.overrides)r.set(n,o);return r}getHttpSettings(){return this.httpSettings}setHttpSettings(r){let n=gDe(r);this.httpSettings=n,this.didChangeHttpSettingsEmitter.fire(this.getHttpSettings())}dumpForTelemetry(){let r=this.baseConfigProvider.dumpForTelemetry();for(let n of[Ue.ShowEditorCompletions,Ue.EnableAutoCompletions,Ue.DelayCompletions,Ue.FilterCompletions]){let o=this.overrides.get(n);o!==void 0&&(r[n]=JSON.stringify(o))}return r}};function S$t(t,e){let r=t,n=[];for(let o of e.split(".")){let s=[...n,o].join(".");r&&typeof r=="object"&&s in r?(r=r[s],n.length=0):n.push(o)}if(!(r===void 0||n.length>0))return r}a(S$t,"getConfigKeyRecursively");function YJo(t){if(hZe.has(t))return hZe.get(t);throw new Error(`Missing config default value: ${v5t}.${t}`)}a(YJo,"getConfigDefaultForKey");function KJo(t){return hZe.get(t)}a(KJo,"getOptionalConfigDefaultForKey");function jfe(t){return t.get(Dn).getExplicitlySetConfigs()}a(jfe,"getExplicitlySetConfigs");var JJo={[Ue.DebugOverrideCppHeadersEnableSwitch]:!1,[Ue.RelatedFilesVSCodeCSharp]:!1,[Ue.RelatedFilesVSCodeTypeScript]:!1,[Ue.RelatedFilesVSCode]:!1,[Ue.IncludeNeighboringFiles]:!1,[Ue.ExcludeRelatedFiles]:!1,[Ue.ContextProviders]:[],[Ue.DebugUseEditorFetcher]:null,[Ue.DebugUseElectronFetcher]:null,[Ue.DebugOverrideLogLevels]:{},[Ue.DebugSnippyOverrideUrl]:"",[Ue.AgentDebugLogsDirectory]:void 0,[Ue.ClaudeCliPath]:void 0,[Ue.CodexCliPath]:void 0,[Ue.OtelEnabled]:!1,[Ue.OtelEndpoint]:void 0,[Ue.OtelCaptureContent]:!1,[Ue.OtelExporterType]:"otlp-http",[Ue.OtelProtocol]:"",[Ue.OtelOutfile]:"",[Ue.OtelServiceName]:"",[Ue.OtelResourceAttributes]:{},[Ue.FetchStrategy]:"auto",[Ue.EnableBuiltInGitHubMcpServer]:!1,[Ue.ToolConfirmAutoApprove]:!1,[Ue.AutoApproveUnmatchedTerminal]:void 0,[Ue.AutoApproveUnmatchedFileOp]:void 0,[Ue.TrustToolAnnotations]:!1,[Ue.AutoApproveYoloMode]:!1,[Ue.EditorHandlesAllConfirmation]:!1,[Ue.MaxToolCallingLoop]:25,[Ue.AutoCompress]:!1,[Ue.AnthropicThinkingBudgetToken]:1024,[Ue.EnableSkills]:!1,[Ue.EnableCloudSandbox]:!1,[Ue.EnableOrgSkills]:!0,[Ue.EnableHooks]:!1,[Ue.SystemHookTools]:void 0,[Ue.EnableSandbox]:!1,[Ue.SandboxAddCurrentWorkingDirectory]:void 0,[Ue.SandboxAuth]:void 0,[Ue.SandboxAllowDevToolAccess]:void 0,[Ue.SandboxAllowBypass]:void 0,[Ue.SandboxMcpServers]:void 0,[Ue.SandboxLspServers]:void 0,[Ue.SandboxUserPolicy]:void 0,[Ue.EnablePlugins]:!1,[Ue.EnableEnsemble]:!0,[Ue.EnableCustomAgents]:!0,[Ue.EnableOrgCustomAgents]:!0,[Ue.EnableOrgCustomInstructions]:!0,[Ue.UseSessionModelForBuiltinSubagents]:!1,[Ue.UseAgentsMd]:!1,[Ue.UseNestedAgentsMd]:!1,[Ue.UseClaudeMd]:!1,[Ue.UseNestedClaudeMd]:!1,[Ue.UseSubsetMatching]:null,[Ue.ContextProviderTimeBudget]:void 0,[Ue.DebugOverrideCapiUrl]:"",[Ue.DebugTestOverrideCapiUrl]:"",[Ue.DebugOverrideProxyUrl]:"",[Ue.DebugTestOverrideProxyUrl]:"",[Ue.DebugOverrideEngine]:"",[Ue.AlwaysRequestMultiline]:void 0,[Ue.ModelAlwaysTerminatesSingleline]:void 0,[Ue.TrimCompletionsAggressively]:void 0,[Ue.CompletionsDebounce]:void 0,[Ue.NESXTab]:void 0,[Ue.UseWorkspaceContextCoordinator]:void 0,[Ue.ShowWorkspaceContextDebugger]:!1,[Ue.CompletionsDelay]:void 0,[Ue.UseSplitContextPrompt]:void 0,[Ue.UseCompletionsComparisonPanel]:void 0,[Ue.ComparisonPanelModelIds]:void 0,[Ue.ComparisonPanelRandomizedMode]:void 0,[Ue.UseFetchFetcher]:void 0,[Ue.UseChatLibCompletions]:void 0,[Ue.TranscriptDirectory]:void 0,[Ue.EnableThinking]:!0,[Ue.ShowEditorCompletions]:void 0,[Ue.EnableAutoCompletions]:void 0,[Ue.DelayCompletions]:void 0,[Ue.FilterCompletions]:void 0,[Ue.Enable]:{"*":!0,plaintext:!1,markdown:!1,scminput:!1},[Ue.EnableQuotaThresholdWarning]:!0,[Ue.McpGatewayAutoStart]:!1,[Ue.DebugFilterLogCategories]:[],[Ue.DebugOverrideEngineLegacy]:"",[Ue.DebugTestOverrideProxyUrlLegacy]:"",[Ue.DebugOverrideProxyUrlLegacy]:"",[Ue.DebugTestOverrideCapiUrlLegacy]:"",[Ue.DebugOverrideCapiUrlLegacy]:"",[Ue.HookErrorOccurredStackTrace]:!1,[Ue.NESUseExplicitRejection]:!1,[Ue.NESModelConfiguration]:void 0,[Ue.AppendPromptTokenCache]:"",[Ue.JetBrainsEdgeTasEnabled]:!0,[Ue.ExperimentsOverride]:void 0,[Ue.PromptPersistBasePath]:void 0,[Ue.AnthropicMessagesEndpoint]:"",[Ue.UseHelixFetcher]:"",[Ue.EnableMapCodeFallback]:"enabled",[Ue.SearchAgent]:"",[Ue.EnsembleEnabledOverride]:"",[Ue.PerfEnabled]:"",[Ue.NESExtendedRange]:!1,[Ue.NESEagerness]:"auto",[Ue.AuthTokenEncryption]:"",[Ue.EnableWorkspaceIndex]:!1},hZe=new Map(Object.entries(JJo));for(let t of Object.values(Ue))if(!hZe.has(t))throw new Error(`Missing config default value ${v5t}.${t}`);function Ct(t,e){return t.get(Dn).getConfig(e)}a(Ct,"getConfig");function SC(t){let e=Ct(t,Ue.EnableWorkspaceIndex);return e===!0||e==="true"}a(SC,"isSemanticSearchEnabled");function Sln(t){return t.get(Dn).dumpForTelemetry()}a(Sln,"dumpForTelemetry");var Gs=class{constructor(){this.packageJson=HZ}static{a(this,"BuildInfo")}isProduction(){return this.getBuildType()!=="dev"}getBuildType(){return this.packageJson.buildType}getVersion(){return this.packageJson.version}getDisplayVersion(){return this.getBuildType()==="dev"?`${this.getVersion()}-dev`:this.getVersion()}getBuild(){return this.packageJson.build}getName(){return this.packageJson.name}};function P5t(t){return t.get(Gs).isProduction()}a(P5t,"isProduction");function nhn(t){return t.get(Gs).getBuildType()==="dev"}a(nhn,"isDevBuild");function bq(t){return t.get(Gs).getBuildType()}a(bq,"getBuildType");function bln(t){return t.get(Gs).getBuild()}a(bln,"getBuild");function ZI(t){return t.get(Gs).getVersion()}a(ZI,"getVersion");var ma=class{constructor(e,r,n,o="none",s="desktop"){this.sessionId=e;this.machineId=r;this.devDeviceId=n;this.remoteName=o;this.uiKind=s}static{a(this,"EditorSession")}};function qI({name:t,version:e}){return`${t}/${e}`}a(qI,"formatNameAndVersion");var wr=class{static{a(this,"EditorAndPluginInfo")}getCopilotIntegrationId(){}getEditorPluginSpecificFilters(){return[]}getEditorIdentity(){return AHe({editor:this.getEditorInfo(),plugin:this.getEditorPluginInfo()})}isEditorPluginInfoKnown(){return!0}};function Xpn(t){let e=t.getCopilotIntegrationId();if(e)return e;switch(t.getEditorPluginInfo().name){case"copilot-intellij":return"jetbrains-chat";case"copilot":case"copilot-vs":return;default:return"jetbrains-chat"}}a(Xpn,"getIntegrationId");function Hm(t){let e=t.get(wr);return{"Editor-Version":qI(e.getEditorInfo()),"Editor-Plugin-Version":qI(e.getEditorPluginInfo()),"Copilot-Language-Server-Version":ZI(t)}}a(Hm,"editorVersionHeaders");var PSn="Iv1.b507a08c87ecfe98",ZJo="350ee525b5da0e4a54c6e8e043edc1b99cc02f19",kde="Ov23liV9UpD7Rnfnskm3",XJo="5509a52e4c525cd594a6fba9147ff6cc2388dd9f",eZo={[PSn]:ZJo,[kde]:XJo},em=class{static{a(this,"GitHubAppInfo")}findAppIdToAuthenticate(){return this.githubAppId??PSn}findAppSecretToAuthenticate(){let e=this.findAppIdToAuthenticate(),r=eZo[e];if(!r)throw new Error(`GitHubAppInfo: No app secret found for app ID: ${e}`);return r}};var ir=class{static{a(this,"Fetcher")}getImplementation(){return this}};function zZ(t,e,r,n,o,s,c,l,u,d,f,p,m=!1,g=[]){let A=l?.["x-api-key"],y=m||typeof A=="string"&&A.length>0,v={...l,...y?{}:{Authorization:`Bearer ${r}`},...Hm(t)};d===void 0&&(v["Openai-Organization"]="github-copilot",v["X-Request-Id"]=o,v["VScode-SessionId"]=t.get(ma).sessionId,v["VScode-MachineId"]=t.get(ma).machineId,v["X-GitHub-Api-Version"]="2026-01-09"),n&&(v["OpenAI-Intent"]=n);let E={method:"POST",headers:v,json:s,timeout:u};if(f&&p){let T=[...r?[r]:[],...g,...Object.entries(v).filter(([x,w])=>w.length>0&&_He.has(x.toLowerCase())).map(([,x])=>x)];f.logRequest({timestamp:new Date().toISOString(),requestId:o,method:"POST",url:e,headers:v,messages:p,body:s,sensitiveValues:T})}let _=t.get(ir);if(c){let T=new AbortController;c.onCancellationRequested(()=>{vt(t,"networking.cancelRequest",cr.createAndMarkAsIssued({headerRequestId:o})),T.abort()}),E.signal=T.signal}return _.fetch(e,E).catch(T=>{if(tZo(T))return vt(t,"networking.disconnectAll"),_.disconnectAll().then(()=>_.fetch(e,E));throw T})}a(zZ,"postRequest");function tZo(t){return t instanceof Error?t.message=="ERR_HTTP2_GOAWAY_SESSION"?!0:"code"in t?t.code=="ECONNRESET"||t.code=="ETIMEDOUT"||t.code=="ERR_HTTP2_INVALID_SESSION":!1:!1}a(tZo,"isInterruptedNetworkError");var rZo=new Set(["ERR_WORKER_OUT_OF_MEMORY","ENOMEM"]);function nZo(t){return rZo.has(t.code??"")||t.name==="RangeError"&&t.message==="WebAssembly.Memory(): could not allocate memory"}a(nZo,"isOomError");function GZ(t,e,r,n=an){if(!zh(e)){if(e instanceof Error){let o=e;nZo(o)?t.get(bs).setWarning("cls",{message:"Out of memory"}):o.code==="EMFILE"||o.code==="ENFILE"?t.get(bs).setWarning("cls",{message:"Too many open files"}):o.code==="CopilotPromptLoadFailure"?t.get(bs).setWarning("cls",{message:"Corrupted Copilot installation"}):`${o.code}`.startsWith("CopilotPromptWorkerExit")?t.get(bs).setWarning("cls",{message:"Worker unexpectedly exited"}):o.syscall==="uv_cwd"&&o.code==="ENOENT"&&t.get(bs).setWarning("cls",{message:"Current working directory does not exist"})}n.exception(t,e,r)}}a(GZ,"handleException");function kSn(t){process.addListener("uncaughtException",r=>{GZ(t,r,"uncaughtException")});let e=!1;process.addListener("unhandledRejection",r=>{if(!e)try{e=!0,GZ(t,r,"unhandledRejection")}finally{e=!1}})}a(kSn,"registerDefaultHandlers");function DSn(){jj("o200k_base").catch(()=>{})}a(DSn,"prewarmTokenizers");h();h();h();var i8={abap:{extensions:[".abap"]},aspdotnet:{extensions:[".asax",".ascx",".ashx",".asmx",".aspx",".axd"]},bat:{extensions:[".bat",".cmd"]},bibtex:{extensions:[".bib",".bibtex"]},blade:{extensions:[".blade",".blade.php"]},BluespecSystemVerilog:{extensions:[".bsv"]},c:{extensions:[".c",".cats",".h",".h.in",".idc"]},csharp:{extensions:[".cake",".cs",".cs.pp",".csx",".linq"]},cpp:{extensions:[".c++",".cc",".cp",".cpp",".cppm",".cxx",".h",".h++",".hh",".hpp",".hxx",".idl",".inc",".inl",".ino",".ipp",".ixx",".rc",".re",".tcc",".tpp",".txx",".i"]},cobol:{extensions:[".cbl",".ccp",".cob",".cobol",".cpy"]},css:{extensions:[".css",".wxss"]},clojure:{extensions:[".bb",".boot",".cl2",".clj",".cljc",".cljs",".cljs.hl",".cljscm",".cljx",".edn",".hic"],filenames:["riemann.config"]},ql:{extensions:[".ql",".qll"]},coffeescript:{extensions:["._coffee",".cake",".cjsx",".coffee",".iced"],filenames:["Cakefile"]},cuda:{extensions:[".cu",".cuh"]},dart:{extensions:[".dart"]},dockerfile:{extensions:[".containerfile",".dockerfile"],filenames:["Containerfile","Dockerfile"]},dotenv:{extensions:[".env"],filenames:[".env",".env.ci",".env.dev",".env.development",".env.development.local",".env.example",".env.local",".env.prod",".env.production",".env.sample",".env.staging",".env.test",".env.testing"]},html:{extensions:[".ect",".ejs",".ejs.t",".jst",".hta",".htm",".html",".html.hl",".html5",".inc",".jsp",".njk",".tpl",".twig",".wxml",".xht",".xhtml",".phtml",".liquid"]},elixir:{extensions:[".ex",".exs"],filenames:["mix.lock"]},erlang:{extensions:[".app",".app.src",".erl",".es",".escript",".hrl",".xrl",".yrl"],filenames:["Emakefile","rebar.config","rebar.config.lock","rebar.lock"]},fsharp:{extensions:[".fs",".fsi",".fsx"]},go:{extensions:[".go"]},groovy:{extensions:[".gradle",".groovy",".grt",".gtpl",".gvy",".jenkinsfile"],filenames:["Jenkinsfile","Jenkinsfile"]},graphql:{extensions:[".gql",".graphql",".graphqls"]},terraform:{extensions:[".hcl",".nomad",".tf",".tfvars",".workflow"]},hlsl:{extensions:[".cginc",".fx",".fxh",".hlsl",".hlsli"]},erb:{extensions:[".erb",".erb.deface",".rhtml"]},razor:{extensions:[".cshtml",".razor"]},haml:{extensions:[".haml",".haml.deface"]},handlebars:{extensions:[".handlebars",".hbs"]},haskell:{extensions:[".hs",".hs-boot",".hsc"]},ini:{extensions:[".cfg",".cnf",".dof",".ini",".lektorproject",".prefs",".pro",".properties",".url"],filenames:[".buckconfig",".coveragerc",".flake8",".pylintrc","HOSTS","buildozer.spec","hosts","pylintrc","vlcrc"]},json:{extensions:[".4DForm",".4DProject",".JSON-tmLanguage",".avsc",".geojson",".gltf",".har",".ice",".json",".json.example",".jsonl",".mcmeta",".sarif",".tact",".tfstate",".tfstate.backup",".topojson",".webapp",".webmanifest",".yy",".yyp"],filenames:[".all-contributorsrc",".arcconfig",".auto-changelog",".c8rc",".htmlhintrc",".imgbotconfig",".nycrc",".tern-config",".tern-project",".watchmanconfig","MODULE.bazel.lock","Package.resolved","Pipfile.lock","bun.lock","composer.lock","deno.lock","flake.lock","mcmod.info"]},jsonc:{extensions:[".code-snippets",".code-workspace",".jsonc",".sublime-build",".sublime-color-scheme",".sublime-commands",".sublime-completions",".sublime-keymap",".sublime-macro",".sublime-menu",".sublime-mousemap",".sublime-project",".sublime-settings",".sublime-theme",".sublime-workspace",".sublime_metrics",".sublime_session"],filenames:[".babelrc",".devcontainer.json",".eslintrc.json",".jscsrc",".jshintrc",".jslintrc",".swcrc","api-extractor.json","argv.json","devcontainer.json","extensions.json","jsconfig.json","keybindings.json","language-configuration.json","launch.json","profiles.json","settings.json","tasks.json","tsconfig.json","tslint.json"]},java:{extensions:[".jav",".java",".jsh"]},javascript:{extensions:["._js",".bones",".cjs",".es",".es6",".frag",".gs",".jake",".javascript",".js",".jsb",".jscad",".jsfl",".jslib",".jsm",".jspre",".jss",".mjs",".njs",".pac",".sjs",".ssjs",".xsjs",".xsjslib"],filenames:["Jakefile"]},julia:{extensions:[".jl"]},kotlin:{extensions:[".kt",".ktm",".kts"]},less:{extensions:[".less"]},lua:{extensions:[".fcgi",".lua",".luau",".nse",".p8",".pd_lua",".rbxs",".rockspec",".wlua"],filenames:[".luacheckrc"]},makefile:{extensions:[".d",".mak",".make",".makefile",".mk",".mkfile"],filenames:["BSDmakefile","GNUmakefile","Kbuild","Makefile","Makefile.am","Makefile.boot","Makefile.frag","Makefile.in","Makefile.inc","Makefile.wat","makefile","makefile.sco","mkfile"]},markdown:{extensions:[".livemd",".markdown",".md",".mdown",".mdwn",".mdx",".mkd",".mkdn",".mkdown",".ronn",".scd",".workbook"],filenames:["contents.lr"]},"objective-c":{extensions:[".h",".m"]},"objective-cpp":{extensions:[".mm"]},php:{extensions:[".aw",".ctp",".fcgi",".inc",".install",".module",".php",".php3",".php4",".php5",".phps",".phpt",".theme"],filenames:[".php",".php_cs",".php_cs.dist","Phakefile"]},perl:{extensions:[".al",".cgi",".fcgi",".perl",".ph",".pl",".plx",".pm",".psgi",".t"],filenames:[".latexmkrc","Makefile.PL","Rexfile","ack","cpanfile","latexmkrc"]},powershell:{extensions:[".ps1",".psd1",".psm1"]},pug:{extensions:[".jade",".pug"]},python:{extensions:[".cgi",".codon",".fcgi",".gyp",".gypi",".lmi",".py",".py3",".pyde",".pyi",".pyp",".pyt",".pyw",".rpy",".sage",".spec",".tac",".wsgi",".xpy"],filenames:[".gclient","DEPS","SConscript","SConstruct","wscript"]},r:{extensions:[".r",".rd",".rsx"],filenames:[".Rprofile","expr-dist"]},ruby:{extensions:[".builder",".eye",".fcgi",".gemspec",".god",".jbuilder",".mspec",".pluginspec",".podspec",".prawn",".rabl",".rake",".rb",".rbi",".rbuild",".rbw",".rbx",".ru",".ruby",".spec",".thor",".watchr"],filenames:[".irbrc",".pryrc",".simplecov","Appraisals","Berksfile","Brewfile","Buildfile","Capfile","Dangerfile","Deliverfile","Fastfile","Gemfile","Guardfile","Jarfile","Mavenfile","Podfile","Puppetfile","Rakefile","Snapfile","Steepfile","Thorfile","Vagrantfile","buildfile"]},rust:{extensions:[".rs",".rs.in"]},scss:{extensions:[".scss"]},sql:{extensions:[".cql",".ddl",".inc",".mysql",".prc",".sql",".tab",".udf",".viw"]},sass:{extensions:[".sass"]},scala:{extensions:[".kojo",".sbt",".sc",".scala"]},shellscript:{extensions:[".bash",".bats",".cgi",".command",".fcgi",".fish",".ksh",".sh",".sh.in",".tmux",".tool",".trigger",".zsh",".zsh-theme"],filenames:[".bash_aliases",".bash_functions",".bash_history",".bash_logout",".bash_profile",".bashrc",".cshrc",".envrc",".flaskenv",".kshrc",".login",".profile",".tmux.conf",".zlogin",".zlogout",".zprofile",".zshenv",".zshrc","9fs","PKGBUILD","bash_aliases","bash_logout","bash_profile","bashrc","cshrc","gradlew","kshrc","login","man","profile","tmux.conf","zlogin","zlogout","zprofile","zshenv","zshrc"]},slang:{extensions:[".fxc",".hlsl",".s",".slang",".slangh",".usf",".ush",".vfx"]},slim:{extensions:[".slim"]},solidity:{extensions:[".sol"]},stylus:{extensions:[".styl"]},svelte:{extensions:[".svelte"]},swift:{extensions:[".swift"]},systemverilog:{extensions:[".sv",".svh",".vh"]},typescriptreact:{extensions:[".tsx"]},latex:{extensions:[".aux",".bbx",".cbx",".cls",".dtx",".ins",".lbx",".ltx",".mkii",".mkiv",".mkvi",".sty",".tex",".toc"]},typescript:{extensions:[".cts",".mts",".ts"]},verilog:{extensions:[".v",".veo"]},vim:{extensions:[".vba",".vim",".vimrc",".vmb"],filenames:[".exrc",".gvimrc",".nvimrc",".vimrc","_vimrc","gvimrc","nvimrc","vimrc"]},vb:{extensions:[".vb",".vbhtml",".Dsr",".bas",".cls",".ctl",".frm",".vbs"]},vue:{extensions:[".nvue",".vue"]},xml:{extensions:[".adml",".admx",".ant",".axaml",".axml",".builds",".ccproj",".ccxml",".clixml",".cproject",".cscfg",".csdef",".csl",".csproj",".ct",".depproj",".dita",".ditamap",".ditaval",".dll.config",".dotsettings",".filters",".fsproj",".fxml",".glade",".gml",".gmx",".gpx",".grxml",".gst",".hzp",".iml",".ivy",".jelly",".jsproj",".kml",".launch",".mdpolicy",".mjml",".mod",".mojo",".mxml",".natvis",".ncl",".ndproj",".nproj",".nuspec",".odd",".osm",".pkgproj",".plist",".pluginspec",".proj",".props",".ps1xml",".psc1",".pt",".pubxml",".qhelp",".rdf",".res",".resx",".rss",".sch",".scxml",".sfproj",".shproj",".srdf",".storyboard",".sublime-snippet",".svg",".sw",".targets",".tml",".typ",".ui",".urdf",".ux",".vbproj",".vcxproj",".vsixmanifest",".vssettings",".vstemplate",".vxml",".wixproj",".workflow",".wsdl",".wsf",".wxi",".wxl",".wxs",".x3d",".xacro",".xaml",".xib",".xlf",".xliff",".xmi",".xml",".xml.dist",".xmp",".xproj",".xsd",".xspec",".xul",".zcml"],filenames:[".classpath",".cproject",".project","App.config","NuGet.config","Settings.StyleCop","Web.Debug.config","Web.Release.config","Web.config","packages.config"]},xsl:{extensions:[".xsl",".xslt"]},yaml:{extensions:[".mir",".reek",".rviz",".sublime-syntax",".syntax",".yaml",".yaml-tmlanguage",".yaml.sed",".yml",".yml.mysql"],filenames:[".clang-format",".clang-tidy",".clangd",".gemrc","CITATION.cff","glide.lock","pixi.lock","yarn.lock"]},javascriptreact:{extensions:[".jsx"]},legend:{extensions:[".pure"]}};h();h();var MSn=[".ejs",".erb",".haml",".hbs",".j2",".jinja",".jinja2",".liquid",".mustache",".njk",".php",".pug",".slim",".webc"],NSn={".php":[".blade"]},Gj=Object.keys(i8).flatMap(t=>i8[t].extensions);var b$t=he(require("node:path"));var $fe=class{constructor(e,r,n){this.languageId=e;this.isGuess=r;this.fileExtension=n}static{a(this,"Language")}},ADe=class{static{a(this,"LanguageDetection")}},T$t=new Map,Hfe=new Map;for(let[t,{extensions:e,filenames:r}]of Object.entries(i8)){for(let n of e)T$t.set(n,[...T$t.get(n)??[],t]);for(let n of r??[])Hfe.set(n,[...Hfe.get(n)??[],t])}var I$t=class extends ADe{static{a(this,"FilenameAndExensionLanguageDetection")}detectLanguage(e){let r=To(e.uri),n=b$t.extname(r).toLowerCase(),o=this.extensionWithoutTemplateLanguage(r,n),s=this.detectLanguageId(r,o),c=this.computeFullyQualifiedExtension(n,o);return s?new $fe(s.languageId,s.isGuess,c):new $fe(e.languageId,!0,c)}extensionWithoutTemplateLanguage(e,r){if(MSn.includes(r)){let n=e.substring(0,e.lastIndexOf(".")),o=b$t.extname(n).toLowerCase();if(o.length>0&&Gj.includes(o)&&this.isExtensionValidForTemplateLanguage(r,o))return o}return r}isExtensionValidForTemplateLanguage(e,r){let n=NSn[e];return!n||n.includes(r)}detectLanguageId(e,r){if(Hfe.has(e))return{languageId:Hfe.get(e)[0],isGuess:!1};let n=T$t.get(r)??[];if(n.length>0)return{languageId:n[0],isGuess:n.length>1};for(;e.includes(".");)if(e=e.replace(/\.[^.]*$/,""),Hfe.has(e))return{languageId:Hfe.get(e)[0],isGuess:!1}}computeFullyQualifiedExtension(e,r){return e!==r?r+e:e}},w$t=class extends ADe{constructor(r){super();this.delegate=r}static{a(this,"GroupingLanguageDetection")}detectLanguage(r){let n=this.delegate.detectLanguage(r),o=n.languageId;return o==="c"||o==="cpp"?new $fe("cpp",n.isGuess,n.fileExtension):n}},x$t=class extends ADe{constructor(r){super();this.delegate=r}static{a(this,"ClientProvidedLanguageDetection")}detectLanguage(r){return r.uri.startsWith("untitled:")||r.uri.startsWith("vscode-notebook-cell:")?new $fe(r.languageId,!0,""):this.delegate.detectLanguage(r)}},iZo=new w$t(new x$t(new I$t));function pB({uri:t,languageId:e}){let r=iZo.detectLanguage({uri:t,languageId:"UNKNOWN"});return r.languageId==="UNKNOWN"?e:r.languageId}a(pB,"detectLanguage");h();h();h();h();function ag(t){if(t.isCancellationRequested)throw new mZe}a(ag,"throwIfCancellationRequested");function B2(t){return t instanceof mZe?!0:t instanceof Error&&t.name===R$t&&t.message===R$t}a(B2,"isCancellationError");var mZe=class extends Error{static{a(this,"CancellationError")}constructor(){super(R$t),this.name=this.message}},R$t="Canceled",gZe=class{constructor(){this.items=[]}static{a(this,"Stack")}push(e){this.items.push(e)}pop(){return this.items.pop()}peek(){return this.items[this.items.length-1]}tryPeek(){return this.items.length>0}toArray(){return this.items}};function VZ(t){switch(t){case 0:case 2:case 7:case 8:case 11:case 12:case 13:case 14:return!0;default:return!1}}a(VZ,"isTypeDefinition");var dd=class t{static{a(this,"TextRange")}static{this.empty=new t(0,0)}constructor(e,r){this.start=e,this.length=r}static fromBounds(e,r){return new t(e,r-e)}get end(){return this.start+this.length}contains(e){return this.start<=e&&this.end>=e}containsRange(e){return this.start<=e.start&&this.end>=e.end}equals(e){return this.start===e.start&&this.length===e.length}getText(e){return e.slice(this.start,this.end)}getTextWithIndentation(e,r){let n=[],o=this.start;for(o=LSn(e,e.length,o),OSn(n,r);o<this.end;)e[o]!=="\r"&&e[o]!==`
|
|
1920
1920
|
`?n.push(e[o++]):e[o]==="\r"&&o<e.length&&e[o+1]!==`
|
|
1921
1921
|
`||e[o]===`
|
|
1922
1922
|
`?(n.push(`
|
|
@@ -3937,7 +3937,7 @@ ${t}`}a(qha,"buildFormattingPrompt");var Wgt=class{constructor(e){this.ctx=e;thi
|
|
|
3937
3937
|
${E.content}`:E.content).join(`
|
|
3938
3938
|
|
|
3939
3939
|
`)})}let{manager:g,authInfo:A}=await DG(n(()=>{if(f.throwIfAborted(),c!==this.removalGeneration)throw new Lo("cancelled","Code review preparation was invalidated.")}),f),y=await this.run(g,A,m,f,c);return s="completed",y}catch(p){let m=p instanceof Lo?p:new Lo("execution",ol(p));throw s=m.kind,d4e.warn(this.ctx,"Structured review request failed",p),m}finally{clearTimeout(d),u.dispose(),uu(this.ctx,"codeReview.structured",{requestSource:"structuredCodeReview",result:s},{totalTimeMs:performance.now()-o})}}async run(e,r,n,o,s){if(s!==this.removalGeneration)throw new Lo("cancelled","Code review authentication changed during preparation.");o.throwIfAborted();let c=new AbortController,l=a(()=>c.abort(o.reason),"abort");o.addEventListener("abort",l,{once:!0});let u=[Ofi+Lt(),Ofi+Lt()],d={sessionIds:u,controller:c,done:this.execute({manager:e,authInfo:r,model:n.model,controller:c},n,u)};this.active.add(d);try{return await d.done}finally{o.removeEventListener("abort",l),this.active.delete(d)}}async cancelAll(){this.removalGeneration++;let e=[...this.active];for(let r of e)r.controller.abort(new Lo("cancelled","Code review session was closed."));await Promise.allSettled(e.map(r=>r.done))}async execute(e,r,n){let{signal:o}=e.controller,s={agent_type:"code-review",name:"snapshot-code-review",description:"Review IDE code snapshots",mode:"sync",prompt:Uha(r)},c=await this.runSession(e,{kind:"reviewer",sessionId:n[0],taskArguments:s}),l=Qha(c,r),u=await this.runSession(e,{kind:"formatter",sessionId:n[1],prompt:qha(c,r)}),d=y_r(u,r);if(l&&!(0,E_r.isDeepStrictEqual)(d,l))throw new Lo("invalidResult","Code review formatting changed the reviewer findings.");return o.throwIfAborted(),d}async runReviewer(e,r,n){await DG(e.tools.initializeAndValidate(),n),await DG(e.updateSubagentSettings({agents:{"code-review":{model:"inherit"}}}),n);let o=await DG(e.tools.execute({name:"task",arguments:r,toolCallId:Lt()}),n);if(typeof o!="string"&&o.resultType!=="success")throw new Lo("execution",o.error??"The code review task did not complete successfully.");let s=typeof o=="string"?o:o.textResultForLlm;if(!s.trim())throw new Lo("invalidResult","The reviewer returned no report.");return s}async formatReport(e,r,n){let o=await DG(e.sendAndWait({prompt:r,responseSchema:Vgt},Lfi),n);if(!o)throw new Lo("invalidResult","Code review formatting returned no result.");return o.data.content}buildIsolatedSessionOptions(e,r,n){let o=!1;return{sessionId:r.sessionId,authInfo:e.authInfo,model:e.model,workingDirectory:n,configDirectory:v_r.join(n,"config"),availableTools:r.kind==="reviewer"?["task"]:[],excludedTools:r.kind==="reviewer"?[]:["task"],customAgents:[],customAgentsLocalOnly:!0,mcpServers:{},skillDirectories:[],pluginDirectories:[],instructionDirectories:[],enableConfigDiscovery:!1,skipCustomInstructions:!0,enableOnDemandInstructionDiscovery:!1,enableFileHooks:!1,enableHostGitOperations:!1,enableSessionStore:!1,enableSkills:!1,skipEmbeddingRetrieval:!0,embeddingCacheStorage:"in-memory",memory:{enabled:!1},infiniteSessions:{enabled:!1},manageScheduleEnabled:!1,hooks:{preToolUse:[{source:"structured-code-review",handler:a(s=>s.sessionId!==r.sessionId||s.toolName!=="task"||o||r.kind!=="reviewer"||!(0,E_r.isDeepStrictEqual)(s.toolArgs,r.taskArguments)?(d4e.warn(this.ctx,"Rejected structured review tool invocation",{toolName:s.toolName,rootSession:s.sessionId===r.sessionId,taskDispatched:o}),e.controller.abort(new Lo("execution","Code review rejected an unsupported or invalid tool invocation.")),{permissionDecision:"deny",permissionDecisionReason:"Snapshot-only code review."}):(o=!0,{permissionDecision:"allow"}),"handler")}]}}}async runSession(e,r){let{manager:n,controller:o}=e,{sessionId:s}=r,{signal:c}=o,l,u,d,f,p,m,g=a(()=>{u&&!f&&(f=u.abort().catch(A=>{d4e.warn(this.ctx,"Failed to abort structured code review",A),m??=new Lo("execution","Failed to abort the code review session.")}))},"abortSession");c.addEventListener("abort",g,{once:!0});try{l=await(0,Ygt.mkdtemp)(v_r.join((0,Bfi.tmpdir)(),"copilot-code-review-")),c.throwIfAborted(),u=await n.createSession(this.buildIsolatedSessionOptions(e,r,l)),c.aborted&&g(),c.throwIfAborted(),d=u.on(A=>{A.type==="subagent.completed"?(A.data.cancelled||A.data.modelSelectionSource!=="session_inheritance")&&o.abort(new Lo("execution","Code review did not complete with the session model.")):A.type==="session.error"?o.abort(new Lo("execution",A.data.message)):A.type==="subagent.failed"?o.abort(new Lo("execution",A.data.error)):(A.type==="permission.requested"||A.type==="user_input.requested"||A.type==="elicitation.requested"||A.type==="external_tool.requested"||A.type==="exit_plan_mode.requested")&&o.abort(new Lo("execution","Code review failed or requires unsupported interaction."))}),r.kind==="reviewer"?p=await this.runReviewer(u,r.taskArguments,c):p=await this.formatReport(u,r.prompt,c)}catch(A){d4e.warn(this.ctx,"Structured code review did not complete",A),m=A instanceof Lo?A:new Lo("execution",`Failed to execute structured code review: ${ol(A)}`)}finally{c.removeEventListener("abort",g),d?.(),u&&(g(),await f);let A=await Promise.allSettled([n.closeSession(s,u)]);l&&A.push(...await Promise.allSettled([(0,Ygt.rm)(l,{recursive:!0,force:!0})]));let y=A.find(v=>v.status==="rejected");y?.status==="rejected"&&(d4e.error(this.ctx,"Failed to clean up structured code review",y.reason),m??=new Lo("execution","Failed to clean up the code review session."))}if(c.throwIfAborted(),m)throw m;if(p===void 0)throw new Lo("invalidResult","Code review returned no result.");return p}};h();function jha(t){return(t.capabilities.supports?.reasoning_effort?.length??0)<=1?!1:t.supported_endpoints?.includes(UJe.Messages)?t.capabilities.supports?.adaptive_thinking===!0:!0}a(jha,"supportReasoningEffortLevel");function Hha(t){if(t.capabilities.type==="chat"){let e=["chat-panel","inline"];return!Ofe.has(t.capabilities.family)&&t.capabilities.supports?.tool_calls&&(t.capabilities.limits?.max_prompt_tokens??0)>4e4&&e.push("agent-panel"),e}else if(t.capabilities.type==="completion")return["completion"];return[]}a(Hha,"getModelScopes");function $ha(t){return t.capabilities.type==="completion"?!0:t.model_picker_enabled===!0}a($ha,"shouldExposeModel");function zha(t){let e=t.map(r=>r.billing?.auto_discount).filter(r=>r!==void 0);return e.length===0?void 0:Math.round(Math.min(...e)*100)}a(zha,"getAutoModelDiscountPercent");function Kgt(t,e,r){let n=[],o=zha(e);return e.forEach(s=>{!r&&s.capabilities.type!=="chat"||$ha(s)&&n.push({modelFamily:s.capabilities.family,modelName:s.name,modelPolicy:s.policy,scopes:Hha(s),id:s.id,vendor:s.vendor,preview:s.preview??!1,isChatDefault:s.is_chat_default??!1,isChatFallback:s.is_chat_fallback??!1,capabilities:{supports:{vision:s.capabilities.supports?.vision??!1,reasoningEfforts:s.capabilities.supports?.reasoning_effort,supportsReasoningEffortLevel:jha(s)},limits:s.capabilities.limits?{maxContextWindowTokens:s.capabilities.limits.max_context_window_tokens,maxOutputTokens:s.capabilities.limits.max_output_tokens,maxInputTokens:s.capabilities.limits.max_prompt_tokens,maxNonStreamingOutputTokens:s.capabilities.limits.max_non_streaming_output_tokens}:void 0},billing:s.billing?{isPremium:s.billing?.is_premium??!0,multiplier:s.billing?.multiplier??0,tokenBasedBillingEnabled:r?.userInfo?.isTBBEnabled,tokenPrices:s.billing?.token_prices?{batchSize:s.billing.token_prices.batch_size,default:s.billing.token_prices.default?{cachePrice:s.billing.token_prices.default.cache_price,cacheWritePrice:s.billing.token_prices.default.cache_write_price,inputPrice:s.billing.token_prices.default.input_price,outputPrice:s.billing.token_prices.default.output_price,maxContext:s.billing.token_prices.default.context_max}:void 0,longContext:s.billing.token_prices.long_context?{cachePrice:s.billing.token_prices.long_context.cache_price,cacheWritePrice:s.billing.token_prices.long_context.cache_write_price,inputPrice:s.billing.token_prices.long_context.input_price,outputPrice:s.billing.token_prices.long_context.output_price,maxContext:s.billing.token_prices.long_context.context_max}:void 0}:void 0,promo:s.billing?.promo?{id:s.billing.promo.id,discountPercent:s.billing.promo.discount_percent,endsAt:s.billing.promo.ends_at,message:s.billing.promo.message}:void 0}:void 0,customModel:s.custom_model?{keyName:s.custom_model.key_name,ownerName:s.custom_model.owner_name,ownerType:s.custom_model.owner_type,provider:s.custom_model.provider}:void 0,degradationReason:CCn(s),modelPickerCategory:s.model_picker_category,modelPickerPriceCategory:s.model_picker_price_category})}),t.get(hu).getPolicyValue("autoModel.enabled")!==!1&&n.push({modelFamily:av,modelName:Trt,modelPolicy:void 0,scopes:["inline","chat-panel","agent-panel"],id:av,preview:!1,isChatDefault:!1,isChatFallback:!1,capabilities:{supports:{vision:!0,supportsReasoningEffortLevel:!1}},billing:o===void 0?void 0:{discountPercent:o},degradationReason:void 0}),n}a(Kgt,"toCopilotModels");h();var Ufi=require("crypto"),xve=require("fs"),__r=require("path");var Qfi="local-environment.json",Ffi="Invalid local environment publication receipts";async function qfi(t){let e;try{e=await xve.promises.readFile((0,__r.join)(t,Qfi),"utf8")}catch(n){if(n.code==="ENOENT")return[];throw n}let r;try{r=JSON.parse(e)}catch{throw new Error(Ffi)}if(!r||typeof r!="object"||!("publications"in r)||!Array.isArray(r.publications)||!r.publications.every(n=>typeof n=="string"))throw new Error(Ffi);return r.publications}a(qfi,"readLocalEnvironmentPublicationIds");async function jfi(t,e){await xve.promises.mkdir(t,{recursive:!0,mode:448});let r=(0,__r.join)(t,Qfi),n=`${r}.${(0,Ufi.randomUUID)()}.tmp`;try{await xve.promises.writeFile(n,JSON.stringify({publications:e})+`
|
|
3940
|
-
`,{encoding:"utf8",mode:384,flag:"wx",flush:!0}),await xve.promises.rename(n,r)}catch(o){throw await xve.promises.rm(n,{force:!0}).catch(()=>{}),o}}a(jfi,"writeLocalEnvironmentPublicationIds");h();var C_r=require("crypto"),_4=require("fs/promises"),r9=require("path");var Hfi=new fe("BackgroundAgent.LocalEnvironment"),Gha=12e4,Jgt=3e3,Ri=class extends ju{constructor(r){super(`Local environment: ${r}`,{kind:r});this.kind=r;this.name="LocalEnvironmentError"}static{a(this,"LocalEnvironmentError")}};async function $fi(t){await(0,_4.mkdir)(t,{recursive:!0,mode:448});let e=(0,r9.join)(t,"local-environment-id"),r=a(async()=>{let o=(await(0,_4.readFile)(e,"utf8")).trim();if(!/^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/.test(o))throw new Ri("operationFailed");return o},"readId");try{return await r()}catch(o){if(o.code!=="ENOENT")throw o}let n=`${e}.${(0,C_r.randomUUID)()}.tmp`;try{await(0,_4.writeFile)(n,(0,C_r.randomUUID)(),{flag:"wx",mode:384,flush:!0});try{await(0,_4.link)(n,e)}catch(o){if(o.code!=="EEXIST")throw o}return await r()}finally{await(0,_4.rm)(n,{force:!0})}}a($fi,"readLocalEnvironmentComputeId");var Zgt=class{constructor(e,r){this.ctx=e;this.deps=r;this.operations=new H2;this.status={state:"stopped"};this.generation=0;this.startEpoch=0;this.operationRevocation=new AbortController;this.publicationWrites=Promise.resolve()}static{a(this,"LocalEnvironmentService")}isRunning(){return this.desired?.ownerUri!==void 0&&this.host!==void 0&&this.status.state==="running"&&!this.starting?.controller.signal.aborted}requiresRestart(){return this.status.error?.kind==="restartRequired"}captureStartAdmission(){let e=this.startEpoch;return()=>{if(e!==this.startEpoch)throw new Ri("hostNotRunning")}}capturePublicationAdmission(){let e=this.host,r=this.generation,n=this.startEpoch,o=a(()=>{if(this.requiresRestart())throw new Ri("restartRequired");if(!e||this.host!==e||this.generation!==r||this.startEpoch!==n||!this.isRunning())throw new Ri("hostNotRunning");this.deps.assertAllowed()},"validate");return o(),o}captureStartCancellation(){if(!this.starting&&(!this.desired||this.desired.ownerUri!==void 0))return;let e=this.startEpoch,r=this.desired;return()=>{e===this.startEpoch&&r===this.desired&&this.cancelStart()}}cancelStart(){this.desired=void 0,this.invalidateStart()}invalidateStart(e=!1){++this.startEpoch,this.revokeOperations(),e&&this.starting&&(this.starting.hostOnlyCleanup=!0),this.starting?.controller.abort()}workspaceFoldersChanged(e){let r=this.desired;if(!r||r.ownerUri&&e.some(c=>c.uri===r.ownerUri)||this.starting&&!this.starting.hostOnlyCleanup&&r.ownerUri===void 0)return;this.invalidateStart(!0),r.ownerUri=void 0,this.host&&(this.status={...this.status,state:"stopping",publishedSessions:void 0});let n=this.startEpoch,o=a(()=>{if(n!==this.startEpoch||this.desired!==r)throw new Ri("hostNotRunning")},"validate"),s=this.operations.queue(async()=>{try{await this.stopHost(!1)}catch(c){throw this.cancelStart(),c}});return{folders:e.map(c=>({...c})),withdrawn:s,validate:o}}applyWorkspaceSwitch(e){return this.operations.queue(async()=>{e.validate();let r=this.startEpoch;try{if(this.deps.assertAllowed(),!this.desired)throw new Ri("hostNotRunning");if(this.host||this.starting)throw new Ri("hostInUse");await this.startHost(this.desired.name,e.folders,!0)}catch(n){throw r===this.startEpoch&&this.cancelStart(),n}})}start(e,r=this.captureStartAdmission(),n){return this.action(async()=>{if(this.requiresRestart())throw new Ri("restartRequired");if(r(),this.deps.assertAllowed(),this.isRunning()){if(this.status.name!==e)throw new Ri("hostInUse");return n&&(n.isNoop=!0),this.snapshot()}if(this.host||this.starting)throw new Ri("hostInUse");return this.desired={name:e},this.startHost(e,this.deps.workspaceFolders().map(o=>({...o})),!1)})}async startHost(e,r,n){let o={controller:new AbortController,epoch:this.startEpoch,hostOnlyCleanup:n};this.starting=o;let s=setTimeout(()=>o.controller.abort(),Gha),c=++this.generation;this.status={state:"starting",name:e};let l=a(u=>this.waitForStart(o,u),"wait");try{await l(()=>this.changed()),await l(()=>this.publicationWrites);let u=await l(()=>this.deps.resolveWorkspace(r));if(this.validateStart(o),!u){if(!n)throw new Ri("operationFailed");return this.starting=void 0,this.status={state:"stopped"},await this.changed(),this.snapshot()}this.desired.ownerUri=u.ownerUri,this.validateStart(o);let{workspace:d}=u,f=await l(()=>this.deps.computeId()),p=await this.acquireStartHost(o,{authentication:{mode:"github"},computeId:f,workspace:d,localServer:{hostname:"127.0.0.1",port:0,requireConnectionToken:!0},allowCreatingNewSessions:!1});for(let y of await l(()=>this.deps.readPublicationIds()))await l(()=>this.trackPublicationWrite(p.unpublishSession(y)));if((await l(()=>p.listSessions())).sessions.length)throw new Ri("unsupportedSession");await l(()=>this.trackPublicationWrite(o.receiptWrite=this.deps.writePublicationIds([]))),await l(()=>p.dispose()),this.validateStart(o),this.host=void 0;let m=!1,g=await this.acquireStartHost(o,{authentication:{mode:"github"},workspace:d,githubEnvironment:{name:e,computeId:f,requireConnectionBinding:!0},allowCreatingNewSessions:!1,onExit:a(()=>{m=!0,!(o.controller.signal.aborted||o.epoch!==this.startEpoch||this.generation!==c||this.status.state==="stopping")&&(this.cancelStart(),this.status={...this.status,state:"failed",error:{kind:"operationFailed"},publishedSessions:void 0},this.changed())},"onExit")});if(this.validateStart(o),m||!g.environmentId)throw new Ri("operationFailed");this.status={state:"running",name:e,environmentId:g.environmentId};let A=await l(()=>this.refresh(()=>this.validateStart(o)));return this.validateStart(o),this.starting=void 0,A}catch(u){o.controller.abort();let d=!1;try{await this.cleanupStart(o),d=!0}catch{this.cancelStart()}let f=this.requiresRestart()?new Ri("restartRequired"):u instanceof Ri?u:new Ri("operationFailed");throw(o.epoch===this.startEpoch||!d||this.requiresRestart())&&(this.desired=void 0,this.status={state:"failed",error:{kind:f.kind}},await this.changed()),f}finally{clearTimeout(s)}}validateStart(e){if(e.controller.signal.aborted||e.epoch!==this.startEpoch||this.starting!==e)throw new Ri("operationFailed");this.deps.assertAllowed();let r=this.desired?.ownerUri;if(r&&!this.deps.workspaceFolders().some(n=>n.uri===r))throw new Ri("operationFailed")}waitForStart(e,r){let{signal:n}=e.controller;return new Promise((o,s)=>{let c=a(()=>s(new Ri("operationFailed")),"abort");n.addEventListener("abort",c,{once:!0}),Promise.resolve().then(()=>(this.validateStart(e),r())).then(o,s).finally(()=>n.removeEventListener("abort",c))})}revokeOperations(){this.operationRevocation.abort(),this.operationRevocation=new AbortController}waitForRevocation(e,r){return new Promise((n,o)=>{let s=a(()=>o(new Ri("hostNotRunning")),"abort");if(e.aborted){s();return}e.addEventListener("abort",s,{once:!0}),Promise.resolve().then(()=>{if(e.aborted)throw new Ri("hostNotRunning");return r()}).then(n,o).finally(()=>e.removeEventListener("abort",s))})}trackPublicationWrite(e){let r=e.then(()=>{},()=>{});return this.publicationWrites=Promise.all([this.publicationWrites,r]).then(()=>{}),e}async writeReceiptIds(e,r,n){await this.waitForRevocation(r,()=>this.publicationWrites),n(),await this.waitForRevocation(r,()=>(n(),this.trackPublicationWrite(this.deps.writePublicationIds(e))))}async acquireStartHost(e,r){let n=await this.waitForStart(e,()=>(e.pendingHost=this.deps.startHost(r).catch(o=>{throw e.controller.signal.aborted||(e.pendingHost=void 0),o}),e.pendingHost));return this.validateStart(e),this.host=n,e.pendingHost=void 0,n}async cleanupStart(e,r=!e.hostOnlyCleanup){let n=this.host,s=await E0(a(async()=>{let c=n??await e.pendingHost;return c&&await c.dispose(),await e.receiptWrite?.catch(()=>{}),!0},"cleanup")(),Jgt,!1);if(!s&&!r&&!e.runtimeStopRequested)throw new Ri("operationFailed");if(!s||e.runtimeStopRequested){if(this.desired=void 0,e.runtimeStopRequested=!0,!await E0(this.deps.forceStopRuntime().then(()=>!0),Jgt,!1))throw new Ri("operationFailed");this.status={state:"failed",error:{kind:"restartRequired"}}}this.host=void 0,this.starting=void 0,++this.generation}stop(e){return this.cancelStart(),this.operations.queue(()=>(e&&(e.isNoop=!this.host&&!this.starting&&this.status.state==="stopped"),this.stopHost()))}retire(){return this.cancelStart(),this.operations.queue(()=>this.retireHost(!1))}retireForStart(){return this.desired=void 0,this.revokeOperations(),this.starting?.controller.abort(),this.operations.queue(()=>this.retireHost(!1))}getStatus(){return this.operations.queue(async()=>{if(!this.isRunning())return this.snapshot();let e=this.operationRevocation.signal;try{return await this.refresh(void 0,e)}catch(r){if(!e.aborted)throw r;return this.snapshot()}})}setSessionPublished(e,r,n,o,s){let c=this.host,l=this.captureStartAdmission(),u=this.operationRevocation.signal,d=a(()=>{if(l(),u.aborted||!c||this.host!==c||!this.isRunning())throw new Ri("hostNotRunning")},"validateHost");return this.action(async()=>{if(d(),!c)throw new Ri("hostNotRunning");if(n&&s?.(),!n){try{await this.waitForRevocation(u,()=>this.trackPublicationWrite(c.unpublishSession(e))),d()}catch{return this.failPublication(c,d)}return await this.forgetReceipt(e,u,d),d(),this.deps.registry.setLocalEnvironmentPublication(e,void 0),await this.refresh(d,u),d(),{sessionId:e,published:!1}}if(!r)throw new Ri("unsupportedSession");let f=a(()=>{if(d(),this.deps.assertAllowed(),this.deps.registry.get(e)!==r)throw new Ri("unsupportedSession")},"validateBinding"),p=a(async()=>{f(),await this.waitForRevocation(u,async()=>o?.()),f()},"validatePublication");await p();let m=await this.waitForRevocation(u,()=>this.sessionWorkspaceMismatch(e));if(await p(),m)throw new Ri("unsupportedSession");let g=await this.waitForRevocation(u,()=>this.deps.readPublicationIds());await p(),g.includes(e)||await this.writeReceiptIds([...g,e],u,f),await p();let A={session:r};this.deps.registry.setLocalEnvironmentPublication(e,A),this.deps.registry.replaceChild(e,"localEnvironment",{dispose:a(()=>this.operations.queue(async()=>{if(!(this.host!==c||this.deps.registry.getLocalEnvironmentPublication(e)!==A))try{await this.waitForRevocation(u,()=>this.trackPublicationWrite(c.unpublishSession(e))),await this.forgetReceipt(e,u,d),d(),this.deps.registry.setLocalEnvironmentPublication(e,void 0),await this.refresh(d,u)}catch{await this.retirePublicationHost(c,d)}}),"dispose")});let y;try{await p(),y=await this.waitForRevocation(u,()=>this.trackPublicationWrite(c.publishSession(e))),await p(),A.sessionUri=y.sessionUri,await this.refresh(f,u),await p()}catch{return this.failPublication(c,d)}return{sessionId:e,published:!0,sessionUri:y.sessionUri}})}async sessionWorkspaceMismatch(e){let r=this.deps.registry.getWorkingDir(e),n=this.desired?.ownerUri;if(!r||!(0,r9.isAbsolute)(r)||!n)return!1;let o,s;try{[o,s]=await Promise.all([this.deps.realpath(Jn(n).fsPath),this.deps.realpath(r)])}catch{return!1}let c=(0,r9.relative)(o,s);return c===".."||c.startsWith(`..${r9.sep}`)||(0,r9.isAbsolute)(c)}async retirePublicationHost(e,r){try{r()}catch{if(this.host===e)try{await this.stopHost(!1)}catch(n){throw this.cancelStart(),n}return!1}return await this.retireHost(),!0}async failPublication(e,r){let n=await this.retirePublicationHost(e,r);throw new Ri(n?"operationFailed":"hostNotRunning")}async retireHost(e=!0){e&&this.cancelStart();try{await this.stopHost(!0)}catch(r){if(this.starting)throw r;await this.deps.forceStopRuntime(),this.host=void 0,++this.generation,this.status={state:"failed",error:{kind:"restartRequired"}},await this.changed()}}async stopHost(e){if(this.starting&&await this.cleanupStart(this.starting,e),!this.host)return this.status.state==="stopped"||this.requiresRestart()?this.snapshot():(this.status={state:"stopped"},await this.changed(),this.snapshot());this.status={...this.status,state:"stopping",publishedSessions:void 0},await this.changed();try{let r=this.host;if(e===!1){if(!await E0(Promise.resolve().then(()=>r.dispose()).then(()=>!0),Jgt,!1))throw new Ri("operationFailed")}else await r.dispose();return this.host=void 0,++this.generation,this.status={state:"stopped"},await this.changed(),this.snapshot()}catch{throw this.status={state:"failed",error:{kind:"operationFailed"}},await this.changed(),new Ri("operationFailed")}}async refresh(e,r=this.operationRevocation.signal){let n=this.host,o=a(()=>{if(r.aborted||!n||this.host!==n)throw new Ri("hostNotRunning");e?.()},"validateRefresh"),s;try{({sessions:s}=await this.waitForRevocation(r,()=>(o(),n.listSessions())))}catch{return o(),this.status={...this.status,publishedSessions:void 0,error:{kind:"operationFailed"}},await this.changed(),o(),this.snapshot()}return o(),this.status.state!=="running"?this.snapshot():(this.status={state:"running",name:this.status.name,environmentId:this.status.environmentId,publishedSessions:s.map(c=>({sessionUri:c.resource,title:c.title,sessionId:this.deps.registry.localEnvironmentSessionId(c.resource)}))},await this.changed(),o(),this.snapshot())}async forgetReceipt(e,r,n){let o=await this.waitForRevocation(r,()=>this.deps.readPublicationIds());n(),await this.writeReceiptIds(o.filter(s=>s!==e),r,n)}snapshot(){let e=structuredClone(this.status);return this.isRunning()&&(e.workspaceUri=this.desired?.ownerUri),e}async changed(){try{await E0(this.deps.notify(this.snapshot()).then(()=>!0),Jgt,!1)||Hfi.warn(this.ctx,"Could not deliver local environment status")}catch{Hfi.warn(this.ctx,"Could not deliver local environment status")}}action(e){return this.operations.queue(async()=>{try{return await e()}catch(r){throw this.requiresRestart()?new Ri("restartRequired"):r instanceof Ri?r:new Ri("operationFailed")}})}};h();async function Xgt(t,e,r,n){let o=performance.now(),s={stage:"admission",isNoop:!1},c="error",l;try{let u=await n(s);return c="success",u}catch(u){throw l=u instanceof Ri?u.kind:"operationFailed",u}finally{gi(t,"backgroundAgent.localEnvironmentAction",{operation:e,trigger:r??"unknown",result:c,isNoop:String(s.isNoop),...l?{errorKind:l,stage:s.stage}:{}},{durationMs:performance.now()-o})}}a(Xgt,"trackLocalEnvironmentAction");h();var zfi=require("fs/promises"),Gfi=require("path");async function Vfi(t){for(let e of t)try{let r=Jn(e.uri);if(r.scheme==="file"&&(0,Gfi.isAbsolute)(r.fsPath)&&(await(0,zfi.stat)(r.fsPath)).isDirectory())return{ownerUri:e.uri,workspace:r.fsPath}}catch{}}a(Vfi,"resolveLocalEnvironmentWorkspace");h();var Rve=class{constructor(e,r,n){this.ctx=e;this.target=n;this.syncScheduled=!1;this.logger=new fe(r);let o=qgt(e);o&&(this.host=o,this.mountsChangedListener=()=>this.schedule(),o.service.on(hne.MountsChanged,this.mountsChangedListener))}static{a(this,"GatewayMountsSync")}dispose(){this.host&&this.mountsChangedListener&&(this.host.service.off(hne.MountsChanged,this.mountsChangedListener),this.mountsChangedListener=void 0,this.host=void 0)}schedule(){this.syncScheduled||(this.syncScheduled=!0,queueMicrotask(()=>{this.syncScheduled=!1;let e=this.host;e&&this.target.syncToActiveSessions(e).catch(r=>this.onSyncError(r))}))}onSyncError(e){this.logger.warn(this.ctx,"MCP active-session sync failed",{error:e instanceof Error?e.message:String(e)})}};var Jfi=require("fs/promises"),Pve=he(require("node:path")),Zfi=require("os");Bo();var Al=new fe("BackgroundAgent"),aN="backgroundAgent",Vha=new Set(["system.message","hook.start","hook.end"]),qP="auto";function Wfi(t,e){return{...t,model:qP,provider:void 0,capi:t.capi&&{...t.capi,autoTier:void 0},featureFlags:{...t.featureFlags,...Gz},enableExperimentalMode:e}}a(Wfi,"legacyAutoSessionOptions");var Wha=new Set(["gpt-41-copilot","gpt-4.1","gpt-4.1-2025-04-14","gpt-5.4-nano","gemini-2.5-pro","grok-code-fast-1"]);function Yfi(t){return t.model_picker_enabled===!0&&t.capabilities.type==="chat"&&!Wha.has(t.id)}a(Yfi,"isSupportedBackgroundAgentModel");function Kfi(t,e){let r=a(n=>/^[A-Za-z]:[\\/]/.test(n)||/^\\\\/.test(n),"isWindowsPath");return r(t)&&r(e)?Pve.win32.normalize(t).toLowerCase()===Pve.win32.normalize(e).toLowerCase():Pve.posix.normalize(t)===Pve.posix.normalize(e)}a(Kfi,"sessionPathsEqual");function Yha(t){return{status:t.status,...t.effectiveAutoTier!==void 0?{effectiveAutoTier:t.effectiveAutoTier}:{},...t.pendingAutoTier!==void 0?{pendingAutoTier:t.pendingAutoTier}:{},...t.activatingAutoTier!==void 0?{activatingAutoTier:t.activatingAutoTier}:{},...t.supersededAutoTier!==void 0?{supersededAutoTier:t.supersededAutoTier}:{}}}a(Yha,"toSetAutoTierResult");var fo=class{constructor(e,r=new Pht(void 0,()=>e.get(zf).isSkillsEnabled())){this.ctx=e;this.copilotCommandPolicy=r;this.authSequencer=new H2;this.localEnvironmentClosed=!1;this.pendingExternalToolDefs=new Map;this.notificationSender=e.get(zs),this.managerLifecycle=new zht(e),this.authBinding=new Blt(e),this.structuredReviewCoordinator=new Wgt(e),this.registry=new $gt(e,(s,c)=>this.managerLifecycle.closeSession(s,c),()=>this.managerLifecycle.invalidateCommandCatalog()),this.builtinSubagentModelPolicy=new Cht(e,this.registry,(s,c)=>this.managerLifecycle.closeSession(s,c)),this.remoteController=new Vht(e,{registry:this.registry}),this.localEnvironment=new Zgt(e,{registry:this.registry,startHost:a(s=>this.managerLifecycle.startLocalEnvironment(s),"startHost"),forceStopRuntime:a(()=>this.managerLifecycle.forceStop(),"forceStopRuntime"),computeId:a(()=>$fi(e.get($n).directory),"computeId"),workspaceFolders:a(()=>e.get(Mr).getWorkspaceFolders(),"workspaceFolders"),realpath:a(s=>(0,Jfi.realpath)(s),"realpath"),resolveWorkspace:Vfi,readPublicationIds:a(()=>qfi(e.get($n).directory),"readPublicationIds"),writePublicationIds:a(s=>jfi(e.get($n).directory,s),"writePublicationIds"),assertAllowed:a(()=>{if(this.localEnvironmentClosed)throw new Ri("hostNotRunning");if(e.get($u).get().remoteControl?.mode==="disabled")throw new Ri("policyDenied")},"assertAllowed"),notify:a(s=>this.notificationSender.sendLocalEnvironmentDidChange(s),"notify")}),this._localEnvironmentWorkspaceListener=e.get(Mr).onDidChangeWorkspaceFolders(s=>{let c=this.localEnvironment.workspaceFoldersChanged(s.workspaceFolders);c&&this.handleLocalEnvironmentWorkspaceChange(c)}),this.sandboxConfigSync=new Wht(e,this.registry),this.permissionModeController=new Ght(e,this.registry),this.eventRouter=new wht(e,this.registry,this.notificationSender),this.turnDriver=new Ggt(e,this.eventRouter),this.copilotCommandCoordinator=new Rht(e,r,this.registry,this.eventRouter,this.turnDriver,this.sandboxConfigSync,this.permissionModeController,this.notificationSender);let n=new Ult(e,this.registry);this._mcpSync=new Rve(e,"BackgroundAgent.McpSync",n);let o=e.get(Dn);this._commandPolicyListener=o.onDidChangeCopilotSettings(()=>{this.registry.invalidateCommandCatalogs(),this.managerLifecycle.invalidateCommandCatalog()}),o.onDidChangeHttpSettings(()=>{vht(this.ctx)}),oa(e,()=>{this.handleAuthStateChange()});try{this._skillsEnabledListener=this.ctx.get(zf).onDidChangeSkillsEnabled(()=>{this.registry.clearChatMode(),this.registry.invalidateCommandCatalogs(),this.managerLifecycle.invalidateCommandCatalog()})}catch(s){if(!(s instanceof _a))throw s}try{this._organizationInstructionsListener=this.ctx.get(OB).onDidChangeInstructions(s=>this.registry.markOrganizationInstructionsChanged(s))}catch(s){if(!(s instanceof _a))throw s}}static{a(this,"BackgroundAgentService")}async handleAuthStateChange(){let e=this.localEnvironment.captureStartCancellation();if(e)try{let r=await this.authBinding.resolveIdentity();this.managerLifecycle.requiresAuthRestart(r.enterpriseAuth,r.runtimeToken)&&e()}catch{}return this.authSequencer.queue(async()=>{let r;try{r=await this.authBinding.resolveIdentity()}catch(u){Al.warn(this.ctx,"Failed to read GitHub session on auth change; skipping cache invalidation",{error:u instanceof Error?u.message:String(u)});return}let{changed:n,hadPrevious:o,hasCurrent:s,enterpriseAuth:c,runtimeToken:l}=r;n&&(Al.info(this.ctx,"GitHub identity changed, clearing cached sessions",{hadPrevious:o,hasCurrent:s,cachedSessionCount:this.registry.size(),remoteSessionCount:this.remoteController.activeCount()}),await this.clearUserScopedState(),await this.managerLifecycle.disposeIfAuthChanged(c,l)&&Al.info(this.ctx,"Restarting Copilot runtime for GitHub authentication change",{githubHost:c?.githubHost}),r.commit())})}async clearUserScopedState(e=!1){this.pendingExternalToolDefs.clear(),this.managerLifecycle.invalidateCommandCatalog(),await this.structuredReviewCoordinator.cancelAll(),await(e?this.localEnvironment.retireForStart():this.localEnvironment.retire()),await this.registry.removeAll(()=>this.managerLifecycle.closeAllSessions())}reviewCode(e,r){let n=a(async o=>{let s=await this.buildAuthInfo(),c=await this.ensureManager(o);return{authInfo:s,manager:c}},"prepareRuntime");return this.structuredReviewCoordinator.review(e,r,n)}ensureManager(e,r){return this.authSequencer.queue(async()=>{e?.();let n=await this.authBinding.resolveIdentity();if(r!==void 0&&(e?.(),n.runtimeToken!==r||n.enterpriseAuth))throw new Ri("authenticationRequired");let o=n.enterpriseAuth,s=this.managerLifecycle.requiresAuthRestart(o,n.runtimeToken);if(s&&(Al.info(this.ctx,"GitHub authentication changed before manager use, clearing cached sessions",{githubHost:o?.githubHost}),await this.clearUserScopedState(r!==void 0),await this.managerLifecycle.disposeIfAuthChanged(o,n.runtimeToken),r!==void 0)){let l=await this.authBinding.resolveIdentity();if(e?.(),l.runtimeToken!==r||l.enterpriseAuth)throw new Ri("authenticationRequired")}e?.();let c=await this.managerLifecycle.ensureManager(o,n.runtimeToken,e);return(s||o!==void 0)&&n.commit(),c})}get sdk(){return this.managerLifecycle.getSdk()}async handleInteraction(e){let r=performance.now(),n=await this.getOrResumeCurrentSession(e.sessionId),o=await w6n(n,e);return uu(this.ctx,"backgroundAgent.interaction",{requestSource:aN,sessionId:e.sessionId,requestId:e.requestId,interactionType:e.type,resultKind:e.type==="permission"?e.result.kind:""},{totalTimeMs:performance.now()-r}),o}buildAuthInfo(){return this.authBinding.buildAuthInfo()}async detachForReplacement(e,r,n){return this.registry.queueAfterCopilotCommandInvocations(e,async()=>this.registry.getLocalEnvironmentPublication(e)?.session===r&&n&&!n()||(await this.registry.withdrawLocalEnvironmentPublication(e,r),!await this.remoteController.detachForReplacement(e,r,n))?!1:(await this.sandboxConfigSync.drainSession(e),await this.eventRouter.unbind(e,r),!0))}applyChatModeSelection(e,r){return kfi(this.ctx,e,r)}buildSessionOptions(e,r){return wfi(this.ctx,e,r,{buildAuthInfo:a(()=>this.buildAuthInfo(),"buildAuthInfo"),getChatMode:a(()=>this.registry.getChatMode(e),"getChatMode")})}async organizationKeysForBuildParams(e){try{return await this.ctx.get(OB).organizationKeysForWorkspaces(e.sessionWorkspaceFolders??[e.workspaceFolder])}catch(r){return r instanceof _a||Al.warn(this.ctx,"Failed to resolve organization scope for Background Agent session",r),new Set}}rememberSystemMessageBuilder(e,r,n,o){this.registry.setSystemMessageBuilder(e,()=>jgt(this.ctx,e,r,{getChatMode:a(()=>this.registry.getChatMode(e),"getChatMode")})),this.registry.setOrganizationKeys(e,n),this.registry.setAppliedOrganizationInstructionRevision(e,o)}async createSession(e){let r=performance.now();Al.info(this.ctx,"createSession called:",{model:e.model,workspaceFolder:e.workspaceFolder});let n=e.sessionId??Lt();return this.registry.withSessionAdmission(n,async()=>{let o=await BBe(this.ctx,e);return{manager:await this.ensureManager(),resolvedTarget:o}},({manager:o,resolvedTarget:s})=>this.createAdmittedSession(o,n,e,s,r))}async createAdmittedSession(e,r,n,o,s){let c=n.inlineConfinedFile?Wii(2):void 0,l=n.inlineConfinedFile?Yii(n.inlineConfinedFile):void 0;await this.ctx.get(Dn).requireReady();let u={...n,model:o.target.model,provider:o.providerConfig,autoTier:o.autoTier,inlineTurnLimiter:c,inlineConfinementHook:l},d=await this.organizationKeysForBuildParams(u),f=this.registry.organizationInstructionRevision(),p=this.builtinSubagentModelPolicy.prepare(r,await this.buildSessionOptions(r,u)),{options:m}=p,g;try{g=await e.createSession(m)}catch(y){throw Zl(o.target.model)?new lw(`Failed to create Fusion session ${r}: ${ol(y)}`,r,"create"):y}let A=_ht(this.ctx);return await p.apply(g,A,()=>e.closeSession(r,g)),c&&this.registry.setTurnLimiter(r,c),Al.info(this.ctx,"Session created:",r),uu(this.ctx,"backgroundAgent.create",{requestSource:aN,reasoningEffort:n.reasoningEffort??"",sessionId:r,...n.shell?.initScripts?.length&&{shell_options_applied:"true"}},{totalTimeMs:performance.now()-s}),p.publish(),this.registry.setLocalEnvironmentMode(r,g,"agent"),n.sandbox&&this.registry.setDesiredSandboxEnabled(r,n.sandbox.enabled),m.sandboxConfig&&this.registry.setAppliedSandboxConfig(r,m.sandboxConfig),this.registry.replaceChild(r,"sessionEventRouter",this.eventRouter.bind(r,g)),this.registry.setResumeOptions(r,m),this.rememberSystemMessageBuilder(r,u,d,f),this.registry.setProviderModel(r,o.target),this.registry.setWorkingDir(r,Jn(n.workspaceFolder.uri).fsPath),this.registry.setWorkspaceFolderUri(r,n.workspaceFolder.uri),n.mcpDirectory&&this.registry.setMcpDirectory(r,n.mcpDirectory),n.inlineConfinedFile&&this.registry.setConfinedFile(r,n.inlineConfinedFile),n.sandbox&&this.sandboxConfigSync.reportSelection(n.sandbox.enabled),{sessionId:r,workspacePath:g.workspacePath}}registerExternalTools(e,r){r?.length&&(this.pendingExternalToolDefs.set(e,r),Al.info(this.ctx,"Stored pending external tool definitions",{sessionId:e,toolCount:r.length}))}getOrResumeCurrentSession(e){let r=this.registry.get(e);return r?Promise.resolve(r):this.getOrResumeSession(e)}async getOrResumeSession(e,r={},n,o=!1,s,c){c?.();let l=this.registry.get(e),u;return l&&!this.pendingExternalToolDefs.has(e)&&!n&&!this.registry.hasStaleOrganizationInstructions(e)&&(!(Zl(this.registry.getProviderModel(e)?.model)||this.registry.getResumeOptions(e)?.featureFlags?.HYDRAFUSION===!0)||(u=(await H6(this.ctx)).enabled,c?.(),u))?l:this.registry.withSessionAdmission(e,()=>this.ensureManager(c),async d=>{c?.();let f={cleanupArmed:!1};try{let p=await this.getOrResumeAdmittedSession(d,e,r,n,f,o,u,s,c);return o&&this.registry.beginOrdinarySendPreparation(e,p,r.model?.trim()==="ensemble"),p}catch(p){if(f.cleanupArmed){let m=f.exactSession;try{await this.registry.remove(e,m?()=>d.closeSession(e,m):void 0)}catch(g){Al.warn(this.ctx,"Failed to clear an unsafe exact-session transition",{sessionId:e,error:ol(g)})}}throw p}})}async getOrResumeAdmittedSession(e,r,n,o,s,c,l,u,d){let f=!1,p=!1,m=l,g=this.registry.hasStaleOrganizationInstructions(r),A=this.registry.organizationInstructionRevision();await this.ctx.get(Dn).requireReady(),d?.();let v=this.registry.getAppliedBuiltinSubagentSessionModelPolicy(r),E=this.registry.get(r);if(E&&!o&&(Zl(this.registry.getProviderModel(r)?.model)||this.registry.getResumeOptions(r)?.featureFlags?.HYDRAFUSION===!0)&&(m??=(await H6(this.ctx)).enabled,m||(o={target:{model:qP,provider:void 0},providerConfig:void 0})),E){let Y=a(()=>{o&&u?.(E)},"assertTargetPreparationAllowed"),te=a(()=>_ht(this.ctx)!==v&&(n.workspaceFolder!==void 0||c&&!this.registry.hasOrdinarySendPreparation(r,E)&&!this.eventRouter.hasActiveTurn(r,E)&&!this.registry.hasCopilotCommandInvocation(r,E)),"policyChangeRequiresReconnect"),re=te(),j=this.pendingExternalToolDefs.get(r);if(o){let G=this.registry.getProviderModel(r);p=Zl(G?.model)&&!Zl(o.target.model);let L=!koi(G,o.target);if(this.registry.hasOrdinarySendPreparation(r,E)&&(n.model?.trim()==="ensemble"||this.registry.hasEnsembleSendPreparation(r,E)||Zl(G?.model)||Zl(o.target.model)))throw new lw(`Cannot switch session model or Fusion tier during a pending send: ${r}`,r,"update");let M=G!==void 0&&G.provider===void 0&&o.target.provider===void 0&&G.model!==o.target.model,k=!j&&!g&&M&&!re,F=Zl(o.target.model),V=Zl(G?.model)||F,se=a(()=>V&&(L||j!==void 0||g||re),"reconnectingFusion"),ce=a(()=>!this.registry.hasOrdinarySendPreparation(r,E)&&!this.eventRouter.hasActiveTurn(r,E)&&!this.registry.hasCopilotCommandInvocation(r,E),"canTransitionFusion");if(se()&&!ce())throw new lw(`Cannot switch Fusion runtime options during a pending or active turn: ${r}`,r,"update");if(k){Y();try{F&&await E.updateOptions({featureFlags:{...xre},isExperimentalMode:!0}),await E.setModel(o.target.model,{...V?{}:{deferIfModelChangeQueued:!0},...V||n.model?.trim()==="ensemble"?{requireApplied:!0}:{},...o.target.model===qP&&o.autoTier!==void 0?{autoTier:l4e(o.autoTier)}:{}})}catch(ve){throw(V||n.model?.trim()==="ensemble")&&(s.cleanupArmed=!0,s.exactSession=E),o.target.model===qP&&o.autoTier!==void 0?new M0(`Failed to apply Auto tier for session ${r}: ${ol(ve)}`,o.autoTier,"set",r):new lw(`Failed to switch model for session ${r}: ${ol(ve)}`,r,"update")}let W=!Zl(o.target.model)&&(Zl(G?.model)||F),ne=this.registry.getAppliedPermissionMode(r),X=ne?.session===E?ne.mode==="assisted":void 0;if(W)try{await E.updateOptions({featureFlags:{...Gz},...X!==void 0?{isExperimentalMode:X}:{}})}catch(ve){throw s.cleanupArmed=!0,s.exactSession=E,new lw(`Failed to restore legacy Auto runtime options for session ${r}: `+ol(ve),r,"update")}let oe=this.registry.getResumeOptions(r);oe&&this.registry.setResumeOptions(r,{...oe,model:o.target.model,provider:o.providerConfig,...Zl(o.target.model)?{featureFlags:{...oe.featureFlags,...xre},enableExperimentalMode:!0}:W?{featureFlags:{...oe.featureFlags,...Gz},enableExperimentalMode:X}:{}}),this.registry.setProviderModel(r,o.target),Y()}else if(!j&&!L&&!re){if(o.target.provider!==void 0){Y();try{await E.updateOptions({model:o.target.model,provider:o.providerConfig??null})}catch(ne){throw new lw(`Failed to refresh model/provider info for session ${r}: `+ol(ne),r,"update")}let W=this.registry.getResumeOptions(r);W&&this.registry.setResumeOptions(r,{...W,model:o.target.model,provider:o.providerConfig}),this.registry.setProviderModel(r,o.target),Y()}else if(o.target.model===qP&&o.autoTier!==void 0){Y();try{await E.setAutoTier(l4e(o.autoTier))}catch(W){throw new M0(`Failed to switch Auto tier for session ${r}: ${ol(W)}`,o.autoTier,"set",r)}this.registry.setProviderModel(r,o.target),Y()}}if(!j&&!g&&!re&&(k||!L)){if(n.shell?.initScripts?.length){Y(),await E.updateOptions({shell:n.shell});let W=this.registry.getResumeOptions(r);W&&this.registry.setResumeOptions(r,{...W,shell:n.shell}),Y()}if(re=te(),!re){if(n.workspaceFolder!==void 0&&!await this.sandboxConfigSync.alignSession(r,E,"resume",n.sandbox?.enabled))throw new Error(`Session changed while applying sandbox configuration: ${r}`);return E}}let pe=re&&c&&n.workspaceFolder===void 0&&!j&&!g&&(!L||M);re&&!pe&&(s.cleanupArmed=!0,s.exactSession=E);let ye=u!==void 0,ae,z=pe||se()||ye?()=>{try{Y()}catch(W){if(!(W instanceof Cg))throw W;return ae=W,!1}return(!pe||te())&&(!se()||ce())}:void 0;try{let W=await this.detachForReplacement(r,E,z);if(!W&&ae)throw ae;if(!W)return s.cleanupArmed=!1,s.exactSession=void 0,this.getOrResumeAdmittedSession(e,r,n,o,s,!1,void 0,u,d);re&&(s.cleanupArmed=!0,s.exactSession=E),this.registry.deleteChatMode(r),this.registry.deleteAppliedSandboxConfig(r),await e.closeSession(r,E),s.cleanupArmed&&(s.exactSession=void 0)}catch(W){throw W instanceof Cg?(s.cleanupArmed=!1,s.exactSession=void 0,W):L?new lw(`Failed to close session ${r} before applying a new model/provider target: `+ol(W),r,"close"):W}f=L,Al.info(this.ctx,"Reopening cached session with refreshed connection options",{sessionId:r,model:o.target.model,providerName:o.target.provider,pendingExternalToolCount:j?.length??0,organizationInstructionsStale:g})}else if(j||g){let G=Zl(this.registry.getProviderModel(r)?.model)||this.registry.getResumeOptions(r)?.featureFlags?.HYDRAFUSION===!0,L=a(()=>!G||!this.registry.hasOrdinarySendPreparation(r,E)&&!this.eventRouter.hasActiveTurn(r,E)&&!this.registry.hasCopilotCommandInvocation(r,E),"canDetachFusion");if(!L()||!await this.detachForReplacement(r,E,G?L:void 0))return E;this.registry.deleteChatMode(r),this.registry.deleteAppliedSandboxConfig(r),await e.closeSession(r,E),Al.info(this.ctx,"Reopening cached session with refreshed connection options",{sessionId:r,pendingExternalToolCount:j?.length??0,organizationInstructionsStale:g})}else return E;g&&E.getEvents().length===0&&this.registry.requireSessionRecreation(r)}let _=this.pendingExternalToolDefs.get(r),S=this.registry.getResumeOptions(r),T=this.registry.getAppliedPermissionMode(r),x=T===void 0?void 0:T.mode==="assisted";p||=o!==void 0&&!Zl(o.target.model)&&(S?.featureFlags?.HYDRAFUSION===!0||n.model?.trim()==="ensemble"&&o.target.model===qP);let w=n.sandbox?.enabled??this.registry.getDesiredSandboxEnabled(r),I=n.workspaceFolder,R,D,N=!g,O;if(!I&&S){let Y=this.registry.getWorkspaceFolderUri(r);if(!Y)throw new Error(`Cannot resume session ${r}: cached connection options have no workspace URI`);I={uri:Y};let te=g?this.registry.buildSystemMessage(r):void 0,re=te?await te:S.systemMessage,j=f_r(S.capi,o?.autoTier);N||=te!==void 0,O={...S,systemHooks:n.systemHooks??S.systemHooks,...Zl(o?.target.model)?{featureFlags:{...S.featureFlags,...xre},enableExperimentalMode:!0}:p?{featureFlags:{...S.featureFlags,...Gz},enableExperimentalMode:x}:{},systemMessage:re,sessionId:r,...o?{model:o.target.model,provider:o.providerConfig}:{},capi:j,...n.shell?.initScripts?.length?{shell:n.shell}:{},sandboxConfig:oAe(this.ctx,w)??{enabled:!1},externalToolDefinitions:n.externalToolDefinitions??_??S.externalToolDefinitions}}else{if(!I){d?.();let re=await e.getSessionMetadata({sessionId:r});if(!re)throw new Error(`Session not found: ${r}`);let j=re.context?.cwd;if(!j)throw new Error(`Cannot resume session ${r} from disk: persisted metadata is missing working-directory context`);I={uri:Cs(j)},Al.info(this.ctx,"Resuming session from disk via metadata fallback",{sessionId:r})}let Y={...n,sandbox:w===void 0?void 0:{enabled:w},...o?{model:o.target.model,provider:o.providerConfig,autoTier:o.autoTier}:{},externalToolDefinitions:n.externalToolDefinitions??_,workspaceFolder:I};D=await this.organizationKeysForBuildParams(Y);let te=await this.buildSessionOptions(r,Y);N=!0,R=a(()=>jgt(this.ctx,r,Y,{getChatMode:a(()=>this.registry.getChatMode(r),"getChatMode")}),"systemMessageBuilder"),O={...te,...p?{featureFlags:{...te.featureFlags,...Gz},enableExperimentalMode:x}:{},sessionId:r,sandboxConfig:te.sandboxConfig??{enabled:!1}}}!o&&(Zl(O.model)||O.featureFlags?.HYDRAFUSION===!0)&&(m??=(await H6(this.ctx)).enabled,m||(o={target:{model:qP,provider:void 0},providerConfig:void 0},p=!0,O=Wfi(O,x)));let Q=this.builtinSubagentModelPolicy.prepare(r,O);O=Q.options;let $;try{d?.(),$=this.registry.needsSessionRecreation(r)?await e.createSession(O):await e.getSession(O,!0)}catch(Y){throw f||Zl(o?.target.model)?new lw(`Failed to resume session ${r} with the requested model/provider: `+ol(Y),r,"resume"):Y}if(!$)throw f?new lw(`Session not found while applying the requested model/provider target: ${r}`,r,"resume"):new Error(`Session not found: ${r}`);if(!o){let Y=$.getEvents(),te;for(let re=Y.length-1;re>=0;re--){let j=Y[re];if(!("agentId"in j&&j.agentId)){if(j.type==="session.model_change"){te=j.data.newModel;break}if((j.type==="session.start"||j.type==="session.resume")&&j.data.selectedModel){te=j.data.selectedModel;break}}}Zl(te)&&(m??=(await H6(this.ctx)).enabled),Zl(te)&&m===!1&&(o={target:{model:qP,provider:void 0},providerConfig:void 0},p=!0,O=Wfi(O,x))}if(s.cleanupArmed&&(s.exactSession=$),o){let Y=performance.now();try{o.target.provider===void 0?(Zl(o.target.model)&&await $.updateOptions({featureFlags:{...xre},isExperimentalMode:!0}),await $.setModel(o.target.model,{...Zl(o.target.model)||p||n.model?.trim()==="ensemble"?{requireApplied:!0}:{},...o.target.model===qP&&o.autoTier!==void 0?{autoTier:l4e(o.autoTier)}:{}})):await $.updateOptions({model:o.target.model,provider:o.providerConfig??null}),p&&(await $.updateOptions({featureFlags:{...Gz},...x!==void 0?{isExperimentalMode:x}:{}}),O={...O,featureFlags:{...O.featureFlags,...Gz},enableExperimentalMode:x}),O={...O,model:o.target.model,provider:o.providerConfig},p_r(this.ctx,"success",performance.now()-Y)}catch(te){p_r(this.ctx,"failure",performance.now()-Y);try{await e.closeSession(r,$),s.cleanupArmed&&(s.exactSession=void 0)}catch(re){Al.warn(this.ctx,"Failed to close session after target activation failure",{sessionId:r,error:ol(re)})}throw o.target.provider===void 0&&o.target.model===qP&&o.autoTier!==void 0?new M0(`Failed to apply Auto tier for session ${r}: ${ol(te)}`,o.autoTier,"set",r):new lw(`Failed to apply model/provider info after resuming session ${r}: `+ol(te),r,"update")}}let U=_ht(this.ctx);await Q.apply($,U,()=>e.closeSession(r,$),!s.cleanupArmed),_&&this.pendingExternalToolDefs.get(r)===_&&this.pendingExternalToolDefs.delete(r),Q.publish(),this.registry.clearSessionRecreation(r),this.registry.replaceChild(r,"sessionEventRouter",this.eventRouter.bind(r,$)),this.registry.setResumeOptions(r,O),R&&this.registry.setSystemMessageBuilder(r,R),D&&this.registry.setOrganizationKeys(r,D),N&&this.registry.setAppliedOrganizationInstructionRevision(r,A),o&&this.registry.setProviderModel(r,o.target);let H=Array.from($.getEvents()).filter(Y=>Y.type==="user.message").length;H>0&&this.registry.seedTurnIndexIfAbsent(r,H-1),this.registry.deleteChatMode(r),this.registry.setAppliedSandboxConfig(r,O.sandboxConfig);let K=I?.uri?Jn(I.uri).fsPath:void 0;K&&this.registry.setWorkingDir(r,K),I?.uri&&this.registry.setWorkspaceFolderUri(r,I.uri),n.mcpDirectory&&this.registry.setMcpDirectory(r,n.mcpDirectory),s.cleanupArmed=!1,s.exactSession=void 0;try{if(!await this.sandboxConfigSync.alignSession(r,$,"resume",n.sandbox?.enabled))throw new Error(`Session changed while applying sandbox configuration: ${r}`);await this.remoteController.restoreForSession(r,$)}catch(Y){await this.registry.withdrawLocalEnvironmentPublication(r,$);try{await this.remoteController.detachForReplacement(r,$)}catch(te){Al.warn(this.ctx,"Failed to disable Remote after rebind restoration failed",{sessionId:r,error:te instanceof Error?te.message:String(te)}),this.registry.get(r)===$&&this.registry.forgetSession(r)}await this.sandboxConfigSync.drainSession(r),await this.eventRouter.unbind(r,$);try{await e.closeSession(r,$)}catch(te){Al.warn(this.ctx,"Failed to disconnect session after Remote restoration failed",{sessionId:r,error:te instanceof Error?te.message:String(te)})}throw Y}return $}async addWorkspaceFolder(e,r){let n=performance.now(),o="success";try{return await this.updateWorkspaceFolder(e,r,"addWorkspaceFolder"),{added:!0}}catch(s){throw o="failure",s}finally{uu(this.ctx,"backgroundAgent.addWorkspaceFolder",{status_text:o},{totalTimeMs:performance.now()-n})}}async removeWorkspaceFolder(e,r){let n=performance.now(),o="success";try{return await this.updateWorkspaceFolder(e,r,"removeWorkspaceFolder"),{removed:!0}}catch(s){throw o="failure",s}finally{uu(this.ctx,"backgroundAgent.removeWorkspaceFolder",{status_text:o},{totalTimeMs:performance.now()-n})}}updateWorkspaceFolder(e,r,n){return this.registry.withSessionAdmission(e,()=>this.ctx.get(Dn).requireReady(),async()=>{let o=this.registry.get(e);if(!o)throw new Error(`No active Background Agent session found: ${e}`);let s=Jn(r);if(s.scheme!=="file")throw new Error(`Workspace folder must use the file URI scheme: ${r}`);try{await o[n](s.fsPath),await this.reapplyChatModeAfterWorkspaceChange(e,o,{reloadProjectCatalogs:n==="addWorkspaceFolder"})}catch(c){if(n==="removeWorkspaceFolder"&&this.registry.get(e)===o)try{await this.registry.remove(e,()=>this.managerLifecycle.closeSession(e,o))}catch(l){Al.warn(this.ctx,"Failed to close session after workspace folder removal failed",{sessionId:e,error:l instanceof Error?l.message:String(l)})}throw c}})}async reapplyChatModeAfterWorkspaceChange(e,r,n){let o=this.registry.getChatMode(e);if(this.registry.deleteChatMode(e),!!o){if(n.reloadProjectCatalogs){let c=(await Promise.allSettled([r.reloadCustomAgents(),r.reloadSkills()])).find(l=>l.status==="rejected");if(c)throw c.reason}await this.applyChatModeOverride(e,r,{sessionId:e,message:"",chatMode:o})}}async sendMessage(e,r){if(e.copilotCommandInvocationId){if(!this.ctx.get(Rn).getCapabilities().copilotCommands)throw new Cg("invocation_not_admitted",{type:"direct",copilotCommandInvocationId:e.copilotCommandInvocationId});if(e.autoTier!==void 0)throw new M0("Copilot command sends do not support autoTier; use backgroundAgent/setAutoTier on the live Auto session.",e.autoTier,"validate",e.sessionId);if(e.ensembleTier!==void 0)throw new vv("conflictingTier",e.ensembleTier,e.sessionId);let c=e.copilotCommandInvocationId;return this.registry.runCopilotCommandRequest(e.sessionId,l=>this.registry.runSerializedCopilotCommandOperation(e.sessionId,async()=>{let u={type:"direct",copilotCommandInvocationId:c},d=a(()=>new Cg("invocation_not_admitted",u),"commandError"),f=a(()=>{if(l.aborted||r?.isCancellationRequested)throw new mP(u)},"assertNotCancelled"),p=a(v=>{if(this.registry.get(e.sessionId)!==v||this.registry.hasOrdinarySendPreparation(e.sessionId,v)||this.registry.hasCopilotCommandInvocation(e.sessionId,v)||this.eventRouter.hasActiveTurn(e.sessionId,v))throw d()},"assertTargetPreparationAllowed");f();let m=a(async v=>{try{return await v}catch(E){throw f(),E}},"awaitPreparation"),g=this.registry.get(e.sessionId);g&&p(g);let A=await m(BBe(this.ctx,e));f();let y=await m(this.getOrResumeSession(e.sessionId,{...g?{}:{shell:e.shell},sandbox:e.sandbox,systemHooks:e.systemHooks,model:e.model},A,!1,p));return f(),p(y),await this.copilotCommandCoordinator.invokeDirect({sessionId:e.sessionId,message:e.message,copilotCommandInvocationId:c,session:y,sandboxEnabled:e.sandbox?.enabled,permissionMode:e.permissionMode,references:e.references,prepareAgentPromptTurn:a(()=>this.prepareCopilotCommandAgentPromptTurn(y,e),"prepareAgentPromptTurn"),token:r,stopSignal:l}),{}}))}let n=await BBe(this.ctx,e),o={...this.registry.has(e.sessionId)?{}:{shell:e.shell},sandbox:e.sandbox,systemHooks:e.systemHooks,model:e.model,ensembleTier:e.ensembleTier},s=await this.getOrResumeSession(e.sessionId,o,n,!0);try{return await this.sendPreparedMessage(e,s,n,r)}finally{this.registry.endOrdinarySendPreparation(e.sessionId,s,e.model?.trim()==="ensemble")}}async prepareCopilotCommandAgentPromptTurn(e,r){await m_r(e,r),r.chatMode!==void 0&&(r.chatMode!=="agent"&&!Ire(r.chatMode)&&await e.reloadCustomAgents(),await this.applyChatModeOverride(r.sessionId,e,r)),(r.chatMode!==void 0||r.agentMode!==void 0)&&(await this.applyChatModeSelection(e,r),await this.applyAgentModeOverride(e,r))}async sendPreparedMessage(e,r,n,o){let s=e.permissionMode??"default";if(await this.permissionModeController.synchronizeForSend(e.sessionId,r,s),e.chatMode&&e.chatMode!=="agent"&&!Ire(e.chatMode)&&await r.reloadCustomAgents(),await m_r(r,e),await this.applyChatModeOverride(e.sessionId,r,e),!await this.sandboxConfigSync.alignSession(e.sessionId,r,"localSend",e.sandbox?.enabled))throw new Error(`Session changed while applying sandbox configuration: ${e.sessionId}`);e.sandbox&&this.sandboxConfigSync.reportSelection(e.sandbox.enabled);let c=e.message;await this.expandPromptTemplate(e.sessionId,e,e.chatMode),await this.applyChatModeSelection(r,e);let l={prompt:e.message,displayPrompt:c,...e.sendMode?{mode:e.sendMode}:{}};await this.applyAgentModeOverride(r,e);let u=e.chatMode==="inline-ask"||e.chatMode==="inline";if(e.references?.length&&!u){let E=await Flt(e.references,this.ctx);if(this.registry.get(e.sessionId)!==r)throw new Error(`Session changed while preparing attachments: ${e.sessionId}. Retry the message in the current session.`);E.length>0&&(l.attachments=E)}if(u){let E=this.registry.getConfinedFile(e.sessionId);if(E){let _=e.references?.find(T=>T.type==="file"&&T.uri===E),S=await Jii(E,_,this.ctx);if(S.promptFragment&&(l.prompt=`${l.prompt}${S.promptFragment}`),S.isLargeFile){let T=e.chatMode==="inline-ask"?Sht:NAr;await r.updateOptions({availableTools:[...T,"view"]})}}}this.registry.getTurnLimiter(e.sessionId)?.reset();let d=performance.now(),f=this.registry.incrementTurnIndex(e.sessionId),p=e.model?.trim()!=="ensemble"?void 0:n.ensembleTier==="hydrafusion"?"high":n.ensembleTier==="hydrafusion-max"?"max":n.target.model===qP&&n.autoTier==="balance"?"balance":void 0,m=this.turnDriver.wireAndSend(e.sessionId,r,l,f,o,n.target.provider!==void 0,{origin:"ordinary",ensembleTelemetryTier:p}),g=this.registry.getChatMode(e.sessionId)??"agent",A={requestSource:aN,chatMode:g,uiKind:Tre(g),sessionId:e.sessionId,safeModelId:Kha(e.model,e.modelProvider),providerName:e.modelProvider??"",reasoningEffort:e.reasoningEffort??"",contextTier:e.contextTier??"",permissionMode:s,hasReferences:String((e.references?.length??0)>0),turnIndex:String(f)},y={totalTimeMs:performance.now()-d,messageCharLen:e.message.length,referenceCount:e.references?.length??0};return uu(this.ctx,"backgroundAgent.send",A,y),{messageId:await m}}async truncateHistory(e){let r=performance.now(),o=await(await this.getOrResumeCurrentSession(e.sessionId)).history.truncate({eventId:e.eventId});return uu(this.ctx,"backgroundAgent.truncateHistory",{requestSource:aN,providerName:e.providerName,sessionId:e.sessionId,eventId:e.eventId},{totalTimeMs:performance.now()-r,eventsRemoved:o.eventsRemoved}),{eventId:e.eventId,eventsRemoved:o.eventsRemoved}}async previewRewind(e){let r=performance.now(),n="error",o=0;try{let c=await(await this.getOrResumeCurrentSession(e.sessionId)).history.previewRewind({eventId:e.eventId});return n=c.available?"available":c.reason??"unavailable",o=c.fileCount,c}finally{Jt(this.ctx,"backgroundAgent.previewRewind",{requestSource:aN,providerName:e.providerName,status_text:n},{totalTimeMs:performance.now()-r,fileCount:o})}}async rewindHistory(e){let r=performance.now(),n="error",o=0,s=0,c=0;try{let u=await(await this.getOrResumeCurrentSession(e.sessionId)).history.rewind({eventId:e.eventId,mode:e.mode});return n=u.outcome,o=u.eventsRemoved??0,s=u.restoredFiles.length,c=u.skippedFiles.length,u}finally{Jt(this.ctx,"backgroundAgent.rewindHistory",{requestSource:aN,providerName:e.providerName,status_text:n},{totalTimeMs:performance.now()-r,eventsRemoved:o,restoredFileCount:s,skippedFileCount:c})}}async forkSession(e){let r=performance.now(),o=await(await this.ensureManager()).forkSession(e.sessionId,{toEventId:e.toEventId,name:e.name});return uu(this.ctx,"backgroundAgent.fork",{requestSource:aN,providerName:e.providerName},{totalTimeMs:performance.now()-r}),{sessionId:o.sessionId}}applyChatModeOverride(e,r,n){return h_r(this.ctx,e,r,n,this.registry)}applyAgentModeOverride(e,r){return Rfi(e,r)}expandPromptTemplate(e,r,n){return Dfi(this.ctx,e,r,this.registry,()=>this.ctx.get(zf).isSkillsEnabled(),n)}async destroySession(e){try{return await this.registry.withSessionAdmission(e.sessionId,()=>this.ensureManager(),async r=>(this.pendingExternalToolDefs.delete(e.sessionId),await this.registry.remove(e.sessionId,()=>r.deleteSession(e.sessionId)),{success:!0}))}catch(r){return Al.error(this.ctx,`Failed to destroy session ${e.sessionId}:`,r),{success:!1}}}async stopSession(e){let r=performance.now(),n=await this.registry.runCopilotCommandStop(e,async()=>{let o=await this.getOrResumeCurrentSession(e),s=this.registry.hasConfinedFile(e)?this.eventRouter.currentLocalTurn(e,o):void 0;return Al.info(this.ctx,"Stopping session via abort:",e),await o.abortManualCompaction()&&Al.info(this.ctx,"Aborted in-progress manual compaction:",e),await o.clearPendingItems(),await o.abort(),{success:!0,...(s?await this.eventRouter.recoverUnstartedTurn(s):!1)?{recoveredUnstartedTurn:!0}:{}}});return uu(this.ctx,"backgroundAgent.stop",{requestSource:aN,sessionId:e},{totalTimeMs:performance.now()-r}),n}async compactHistory(e){let r=performance.now(),n=await this.getOrResumeCurrentSession(e);Al.info(this.ctx,"Compacting history for session:",e);let o=await n.compactHistory();return uu(this.ctx,"backgroundAgent.compactHistory",{requestSource:aN,sessionId:e},{totalTimeMs:performance.now()-r,tokensRemoved:o.tokensRemoved,messagesRemoved:o.messagesRemoved}),{success:o.success,tokensRemoved:o.tokensRemoved,messagesRemoved:o.messagesRemoved,summaryContent:o.summaryContent,contextWindow:o.contextWindow}}async stopCompactHistory(e){let r=performance.now(),n=await this.getOrResumeCurrentSession(e);Al.info(this.ctx,"Aborting manual compaction for session:",e);let o=await n.abortManualCompaction();return uu(this.ctx,"backgroundAgent.stopCompactHistory",{requestSource:aN,sessionId:e,aborted:String(o)},{totalTimeMs:performance.now()-r}),{aborted:o}}async getPlanPath(e){return await(await this.getOrResumeCurrentSession(e)).getPlanPath()}async resumeSession(e){let r=performance.now();Al.info(this.ctx,"resumeSession called:",e.sessionId);let n=await BBe(this.ctx,e),o=await this.getOrResumeSession(e.sessionId,e,n);this.registry.invalidateCommandCatalog(e.sessionId,o),e.sandbox&&this.sandboxConfigSync.reportSelection(e.sandbox.enabled);let s=Array.from(o.getEvents()),c=await o.isProcessing();Eht(this.ctx,this.notificationSender,e.sessionId,o),uu(this.ctx,"backgroundAgent.resume",{requestSource:aN,reasoningEffort:e.reasoningEffort??"",sessionId:e.sessionId,...e.shell?.initScripts?.length&&{shell_options_applied:"true"}},{totalTimeMs:performance.now()-r});let l=s.filter(u=>!Vha.has(u.type));return{sessionId:e.sessionId,workspacePath:o.workspacePath,events:l,...c===void 0?{}:{status:c.processing?"in_progress":"idle"}}}async commandCompletions(e,r,n){return Olt(async()=>{let o=r===void 0?void 0:this.registry.get(r);if(r!==void 0&&!o)return{items:[]};let s=o&&r!==void 0?await this.readSessionCompletionCatalog(r,o):await this.managerLifecycle.readCommandCatalog(await this.leaseCompletionCatalog());if(!s.isCurrent())throw new Ed("stale");let c=!!(o&&r!==void 0&&(this.eventRouter.hasActiveTurn(r,o)||this.registry.hasCopilotCommandInvocation(r,o)));return{items:Llt(this.copilotCommandPolicy.filterCompletions(s.catalog).commands,e,c)}},n)}async readSessionCompletionCatalog(e,r){let n=this.registry.getCommandCatalog(e,r);if(!n)throw new Ed("stale");let o=n.revision,s=await n.read(()=>r.commands.list({includeBuiltins:!0,includeSkills:!0,includeClientCommands:!1})),c=a(()=>this.registry.getCommandCatalog(e,r)===n&&n.revision===o,"isCurrent");if(!c())throw new Ed("stale");return{catalog:s,isCurrent:c}}async leaseCompletionCatalog(){let e;try{e=await this.ensureManager()}catch{throw new Ed("unavailable")}return this.authSequencer.queue(()=>Promise.resolve(this.managerLifecycle.commandCatalogLease(e)))}async listCommands(e){let r=e.sessionId?await this.listSessionCommands(e.sessionId):await(await this.ensureManager()).listCommands();return this.copilotCommandPolicy.filter(r)}async listSessionCommands(e){return(await this.getOrResumeCurrentSession(e)).commands.list({includeBuiltins:!0,includeSkills:!1,includeClientCommands:!1})}async listSessions(e){let o=(await(await this.ensureManager()).listSessions()).filter(s=>!this.structuredReviewCoordinator.ownsSession(s.sessionId));return e&&(o=o.filter(s=>!(e.cwd&&(!s.context?.cwd||!Kfi(s.context.cwd,e.cwd))||e.gitRoot&&(!s.context?.gitRoot||!Kfi(s.context.gitRoot,e.gitRoot))||e.repository&&s.context?.repository!==e.repository||e.branch&&s.context?.branch!==e.branch))),{sessions:o.map(s=>({sessionId:s.sessionId,startTime:s.startTime instanceof Date?s.startTime.toISOString():String(s.startTime),modifiedTime:s.modifiedTime instanceof Date?s.modifiedTime.toISOString():String(s.modifiedTime),summary:s.summary,isRemote:s.isRemote,context:s.context}))}}async listCLIModels(e){Al.info(this.ctx,"listCLIModels called",{forceRefresh:e});let r=performance.now();try{let n=await this.ctx.get($t).getUserToken(),o=await this.ctx.get(va).getMetadata(e),s=Kgt(this.ctx,o.filter(Yfi),n);for(let p of s)p.id===av&&(p.capabilities.supports.autoTiers=g_r);let l=(await H6(this.ctx,n)).enabled?await jAr(this.ctx,e):void 0,u=Ct(this.ctx,Ue.EnableEnsemble)===!0?l?.candidate:void 0,d=u&&l?Hii(l.serviceMessages,u):void 0,f=$ii(s,u,Zl,d);return Al.info(this.ctx,"listCLIModels succeeded",{modelCount:f.length}),uu(this.ctx,"backgroundAgent.listCLIModels",{status_text:"success"},{duration_ms:performance.now()-r,model_count:f.length}),f}catch(n){let o=Mlt(n);throw Al.error(this.ctx,"listCLIModels failed",{error:n instanceof Error?n.message:String(n),cause:o,stack:n instanceof Error?n.stack:void 0}),Jp(this.ctx,"backgroundAgent.listCLIModels",n,{status_text:"failure",...o?{errorCause:o}:{}},{duration_ms:performance.now()-r}),new Error("Failed to retrieve models",{cause:n})}}async listModels(e){Al.info(this.ctx,"listModels called",{forceRefresh:e}),await this.ensureManager();let r=performance.now();try{let o=(await this.ctx.get(va).getMetadata(e)).filter(Yfi).map($me);o.length===0?Al.warn(this.ctx,"No models available. Check authentication and Copilot subscription status."):Al.info(this.ctx,`Successfully retrieved ${o.length} models`);let s=[];this.ctx.get(hu).getPolicyValue("autoModel.enabled")!==!1&&s.push(this.buildAutoModelEntry());let c=[...s,...o];return Al.debug(this.ctx,"Models retrieved:",c.map(l=>l.id)),uu(this.ctx,"backgroundAgent.listModels",{status_text:"success"},{duration_ms:performance.now()-r,model_count:c.length}),{models:c}}catch(n){let o=n instanceof Error?n.message:String(n),s=Mlt(n);throw Al.error(this.ctx,"listModels failed",{error:o,cause:s,stack:n instanceof Error?n.stack:void 0}),Jp(this.ctx,"backgroundAgent.listModels",n,{status_text:"failure",...s?{errorCause:s}:{}},{duration_ms:performance.now()-r}),new Error("Failed to retrieve models",{cause:n})}}buildAutoModelEntry(){return{id:this.sdk.AUTO_MODEL_ID,name:"Auto",preview:!1,capabilities:{family:this.sdk.AUTO_MODEL_ID,supports:{vision:!0},limits:{max_context_window_tokens:0}}}}async startLocalEnvironment(e,r){return Xgt(this.ctx,"start",r,async n=>{let o=this.localEnvironment.captureStartAdmission(),s=a(()=>{if(o(),this.localEnvironment.requiresRestart())throw new Ri("restartRequired");if(this.localEnvironmentClosed)throw new Ri("hostNotRunning")},"validateAdmission");s(),n.stage="authentication";let c=await this.authBinding.resolveIdentity();if(s(),!c.runtimeToken||c.enterpriseAuth)throw new Ri("authenticationRequired");return n.stage="runtime",await this.ensureManager(s,c.runtimeToken),n.stage="authentication",this.authSequencer.queue(async()=>{s();let l=await this.authBinding.resolveIdentity();if(s(),l.runtimeToken!==c.runtimeToken||l.enterpriseAuth)throw new Ri("authenticationRequired");let u=this.ctx.get(wr),d=AHe({editor:u.getEditorInfo(),plugin:u.getEditorPluginInfo()}),f=e??`Copilot on ${(0,Zfi.hostname)()}`,p=` - ${d.displayName}`;n.stage="start";let m=await this.localEnvironment.start(f.endsWith(p)?f:`${f}${p}`,s,n);return l.commit(),m})})}async handleLocalEnvironmentWorkspaceChange(e){try{await e.withdrawn,await this.authSequencer.queue(async()=>{if(e.validate(),this.localEnvironmentClosed)throw new Ri("hostNotRunning");let r=await this.authBinding.resolveIdentity();if(e.validate(),!r.runtimeToken||r.enterpriseAuth||this.managerLifecycle.requiresAuthRestart(r.enterpriseAuth,r.runtimeToken))throw new Ri("authenticationRequired");await this.localEnvironment.applyWorkspaceSwitch(e)})}catch{try{e.validate(),this.localEnvironment.cancelStart()}catch{}Al.warn(this.ctx,"Local environment workspace switch did not complete")}}stopLocalEnvironment(e){return Xgt(this.ctx,"stop",e,r=>(r.stage="stop",this.localEnvironment.stop(r)))}getLocalEnvironmentStatus(){return this.localEnvironment.getStatus()}async setLocalEnvironmentSessionPublished(e,r,n,o){return Xgt(this.ctx,r?"publish":"unpublish",o,async s=>{if(!r)return s.stage="unpublish",this.registry.cancelLocalEnvironmentPublicationPreparations(e),this.localEnvironment.setSessionPublished(e,void 0,!1);let c=this.registry.beginLocalEnvironmentPublicationPreparation(e);try{let l=this.localEnvironment.capturePublicationAdmission(),u=a(()=>{if(l(),this.localEnvironmentClosed)throw new Ri("hostNotRunning")},"validateHost"),d=a(()=>{if(u(),!c.isCurrent())throw new Ri("unsupportedSession")},"validateAdmission");return s.stage="resume",await this.registry.withSessionAdmission(e,()=>this.getOrResumeSession(e,{},void 0,!1,void 0,d),async f=>{let p=a(()=>{if(u(),this.registry.get(e)!==f||this.registry.hasConfinedFile(e)||this.registry.hasOrdinarySendPreparation(e,f)||n!==void 0&&n!=="agent")throw new Ri("unsupportedSession")},"validateSession");d(),p(),s.stage="authentication";let m=await this.authBinding.resolveIdentity();if(d(),p(),!m.runtimeToken||m.enterpriseAuth||this.managerLifecycle.requiresAuthRestart(m.enterpriseAuth,m.runtimeToken))throw new Ri("authenticationRequired");if(n==="agent"){s.stage="mode";try{await h_r(this.ctx,e,f,{chatMode:n},this.registry)}finally{d(),p()}}let g=a(async()=>{p();let A=await this.authBinding.resolveIdentity();if(p(),A.runtimeToken!==m.runtimeToken||A.enterpriseAuth||this.managerLifecycle.requiresAuthRestart(A.enterpriseAuth,A.runtimeToken))throw new Ri("authenticationRequired");if(this.registry.getLocalEnvironmentMode(e,f)!=="agent")throw new Ri("unsupportedSession")},"validatePublication");return s.stage="authentication",await g(),s.stage="publish",this.localEnvironment.setSessionPublished(e,f,!0,g,()=>{d(),p(),c.dispose()})})}finally{c.dispose()}})}async enableRemote(e,r){let n=await this.getOrResumeSession(e,{sandbox:r});if(!await this.sandboxConfigSync.alignSession(e,n,"remoteEnable",r?.enabled))throw new Error(`Session changed while applying sandbox configuration: ${e}`);return r&&this.sandboxConfigSync.reportSelection(r.enabled),this.remoteController.enableForSession(e,n)}async disableRemote(e){let r=await this.getOrResumeCurrentSession(e);await this.remoteController.disableForSession(r)}getRemoteStatus(e){return this.remoteController.getStatus(e)}setAgentPermissionMode(e,r){return this.permissionModeController.setForLiveSession(e,r)}async setAutoTier(e,r){let n=performance.now(),o="failure";try{let s=this.registry.get(e);if(!s)throw new M0(`Failed to apply Auto tier ${r}: session ${e} is not active`,r,"set",e);let c=await this.registry.withSessionAdmission(e,()=>Promise.resolve(s),async l=>{if(this.assertLiveAutoTierSession(e,l,r),this.registry.hasEnsembleSendPreparation(e,l))throw new M0(`Cannot change Auto tier during a pending Fusion turn: ${e}`,r,"set",e);let u=this.registry.getProviderModel(e);if(!u?.model)throw new M0(`Auto tier '${r}' is only supported when the selected model is '${qP}'.`,r,"validate",e);let d={model:u.model,provider:u.provider};nyr(d,r,e);let f=await l.setAutoTier(l4e(r));return this.assertLiveAutoTierSession(e,l,r),Yha(f)});return o=c.status,c}catch(s){throw s instanceof M0?s:new M0(`Failed to apply Auto tier ${r} to session ${e}: ${ol(s)}`,r,"set",e)}finally{gi(this.ctx,"backgroundAgent.autoTierSelection",{status_text:o,autoTier:r},{duration_ms:performance.now()-n})}}assertLiveAutoTierSession(e,r,n){let o=this.registry.get(e);if(!o)throw new M0(`Failed to apply Auto tier ${n}: session ${e} is not active`,n,"set",e);if(o!==r)throw new M0(`Failed to apply Auto tier ${n}: session ${e} is no longer the active live session`,n,"set",e)}async shutdown(){this.localEnvironmentClosed=!0,this.localEnvironment.cancelStart(),this._mcpSync.dispose(),this.sandboxConfigSync.dispose(),this._localEnvironmentWorkspaceListener?.dispose(),this._localEnvironmentWorkspaceListener=void 0,this._commandPolicyListener?.dispose(),this._commandPolicyListener=void 0,this._skillsEnabledListener?.dispose(),this._skillsEnabledListener=void 0,this._organizationInstructionsListener?.dispose(),this._organizationInstructionsListener=void 0,await this.authSequencer.queue(async()=>{await this.clearUserScopedState(),DAr(),await this.managerLifecycle.dispose()})}forceStopRuntime(){return this.managerLifecycle.forceStop()}};function Kha(t,e){return e?"byok models":t??""}a(Kha,"safeModelId");h();var S_r=["default","assisted","allowAll"];h();h();var T_r=require("crypto"),bT=require("fs/promises"),ST=require("path");var Xfi=1,Jha=".registry",e0t=class{constructor(e){this.entries=new Map;this.ideDirectory=(0,ST.resolve)(e.ideDirectory),this.registryDirectory=(0,ST.join)(this.ideDirectory,Jha),this.ownerPid=e.ownerPid??process.pid,this.registryPath=(0,ST.join)(this.registryDirectory,`${this.ownerPid}-${e.instanceId??(0,T_r.randomUUID)()}.jsonl`),this.isProcessRunning=e.isProcessRunning??tma,this.removeFile=e.removeFile??(r=>(0,bT.rm)(r,{force:!0})),this.onError=e.onError}static{a(this,"IdeLockRegistry")}async reconcile(){let e={status:"success",trackedCount:0,staleCount:0,removedCount:0,failureCount:0},r;try{await(0,bT.mkdir)(this.registryDirectory,{recursive:!0,mode:448}),r=await(0,bT.readdir)(this.registryDirectory)}catch(o){return this.recordFailure(e,"Failed to enumerate IDE lock registries",o),e.status="failed",e}let n=new Map;for(let o of r.filter(s=>s.endsWith(".jsonl"))){let s=(0,ST.join)(this.registryDirectory,o);if(s===this.registryPath)continue;let c;try{c=await Zha(s)}catch(u){this.recordFailure(e,"Failed to read IDE lock registry",u);continue}if(e.trackedCount+=c.length,c.length===0){try{await this.removeFile(s)}catch(u){this.recordFailure(e,`Failed to remove empty IDE lock registry ${o}`,u)}continue}let l=[];for(let u of c){if(!ema(u.lockFileName)){l.push(u),this.recordFailure(e,"Ignored unsafe IDE lock registry entry",new Error("Unsafe lock name"));continue}if(this.ownerIsAlive(u.ownerPid,n)){l.push(u);continue}e.staleCount++;try{await this.removeFile((0,ST.join)(this.ideDirectory,u.lockFileName)),e.removedCount++}catch(d){l.push(u),this.recordFailure(e,"Failed to remove stale IDE lock",d)}}if(l.length!==c.length)try{await b_r(s,l,this.removeFile)}catch(u){this.recordFailure(e,"Failed to update IDE lock registry",u)}}return e.status=e.failureCount===0?"success":e.removedCount>0?"partial":"failed",e}async add(e){let r=this.toLockFileName(e),n={version:Xfi,ownerPid:this.ownerPid,lockFileName:r};this.entries.set(e,n);try{await b_r(this.registryPath,Array.from(this.entries.values()),this.removeFile)}catch(o){throw this.entries.delete(e),o}}async remove(e){let r=this.entries.get(e);if(r){this.entries.delete(e);try{await b_r(this.registryPath,Array.from(this.entries.values()),this.removeFile)}catch(n){throw this.entries.set(e,r),n}}}registryPathForTesting(){return this.registryPath}toLockFileName(e){let r=(0,ST.resolve)(e);if((0,ST.dirname)(r)!==this.ideDirectory||!r.endsWith(".lock"))throw new Error("IDE lock path is outside the IDE directory");return(0,ST.basename)(r)}ownerIsAlive(e,r){let n=r.get(e);if(n!==void 0)return n;let o=this.isProcessRunning(e);return r.set(e,o),o}recordFailure(e,r,n){e.failureCount++,this.onError?.(r,n)}};async function Zha(t){let e=await(0,bT.readFile)(t,"utf8");return e.trim().length===0?[]:e.split(/\r?\n/).filter(r=>r.length>0).map((r,n)=>{let o=JSON.parse(r);if(!Xha(o))throw new Error(`Invalid registry entry at line ${n+1}`);return o})}a(Zha,"readRegistry");async function b_r(t,e,r){if(e.length===0){await r(t);return}await(0,bT.mkdir)((0,ST.dirname)(t),{recursive:!0,mode:448});let n=`${t}.tmp-${(0,T_r.randomUUID)()}`;try{let o=`${e.map(s=>JSON.stringify(s)).join(`
|
|
3940
|
+
`,{encoding:"utf8",mode:384,flag:"wx",flush:!0}),await xve.promises.rename(n,r)}catch(o){throw await xve.promises.rm(n,{force:!0}).catch(()=>{}),o}}a(jfi,"writeLocalEnvironmentPublicationIds");h();var C_r=require("crypto"),_4=require("fs/promises"),r9=require("path");var Hfi=new fe("BackgroundAgent.LocalEnvironment"),Gha=12e4,Jgt=3e3,Ri=class extends ju{constructor(r){super(`Local environment: ${r}`,{kind:r});this.kind=r;this.name="LocalEnvironmentError"}static{a(this,"LocalEnvironmentError")}};async function $fi(t){await(0,_4.mkdir)(t,{recursive:!0,mode:448});let e=(0,r9.join)(t,"local-environment-id"),r=a(async()=>{let o=(await(0,_4.readFile)(e,"utf8")).trim();if(!/^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/.test(o))throw new Ri("operationFailed");return o},"readId");try{return await r()}catch(o){if(o.code!=="ENOENT")throw o}let n=`${e}.${(0,C_r.randomUUID)()}.tmp`;try{await(0,_4.writeFile)(n,(0,C_r.randomUUID)(),{flag:"wx",mode:384,flush:!0});try{await(0,_4.link)(n,e)}catch(o){if(o.code!=="EEXIST")throw o}return await r()}finally{await(0,_4.rm)(n,{force:!0})}}a($fi,"readLocalEnvironmentComputeId");var Zgt=class{constructor(e,r){this.ctx=e;this.deps=r;this.operations=new H2;this.status={state:"stopped"};this.generation=0;this.startEpoch=0;this.operationRevocation=new AbortController;this.publicationWrites=Promise.resolve()}static{a(this,"LocalEnvironmentService")}isRunning(){return this.desired?.ownerUri!==void 0&&this.host!==void 0&&this.status.state==="running"&&!this.starting?.controller.signal.aborted}requiresRestart(){return this.status.error?.kind==="restartRequired"}captureStartAdmission(){let e=this.startEpoch;return()=>{if(e!==this.startEpoch)throw new Ri("hostNotRunning")}}capturePublicationAdmission(){let e=this.host,r=this.generation,n=this.startEpoch,o=a(()=>{if(this.requiresRestart())throw new Ri("restartRequired");if(!e||this.host!==e||this.generation!==r||this.startEpoch!==n||!this.isRunning())throw new Ri("hostNotRunning");this.deps.assertAllowed()},"validate");return o(),o}captureStartCancellation(){if(!this.starting&&(!this.desired||this.desired.ownerUri!==void 0))return;let e=this.startEpoch,r=this.desired;return()=>{e===this.startEpoch&&r===this.desired&&this.cancelStart()}}cancelStart(){this.desired=void 0,this.invalidateStart()}invalidateStart(e=!1){++this.startEpoch,this.revokeOperations(),e&&this.starting&&(this.starting.hostOnlyCleanup=!0),this.starting?.controller.abort()}workspaceFoldersChanged(e){let r=this.desired;if(!r||r.ownerUri&&e.some(c=>c.uri===r.ownerUri)||this.starting&&!this.starting.hostOnlyCleanup&&r.ownerUri===void 0)return;this.invalidateStart(!0),r.ownerUri=void 0,this.host&&(this.status={...this.status,state:"stopping",publishedSessions:void 0});let n=this.startEpoch,o=a(()=>{if(n!==this.startEpoch||this.desired!==r)throw new Ri("hostNotRunning")},"validate"),s=this.operations.queue(async()=>{try{await this.stopHost(!1)}catch(c){throw this.cancelStart(),c}});return{folders:e.map(c=>({...c})),withdrawn:s,validate:o}}applyWorkspaceSwitch(e){return this.operations.queue(async()=>{e.validate();let r=this.startEpoch;try{if(this.deps.assertAllowed(),!this.desired)throw new Ri("hostNotRunning");if(this.host||this.starting)throw new Ri("hostInUse");await this.startHost(this.desired.name,e.folders,!0)}catch(n){throw r===this.startEpoch&&this.cancelStart(),n}})}start(e,r=this.captureStartAdmission(),n){return this.action(async()=>{if(this.requiresRestart())throw new Ri("restartRequired");if(r(),this.deps.assertAllowed(),this.isRunning()){if(this.status.name!==e)throw new Ri("hostInUse");return n&&(n.isNoop=!0),this.snapshot()}if(this.host||this.starting)throw new Ri("hostInUse");return this.desired={name:e},this.startHost(e,this.deps.workspaceFolders().map(o=>({...o})),!1)})}async startHost(e,r,n){let o={controller:new AbortController,epoch:this.startEpoch,hostOnlyCleanup:n};this.starting=o;let s=setTimeout(()=>o.controller.abort(),Gha),c=++this.generation;this.status={state:"starting",name:e};let l=a(u=>this.waitForStart(o,u),"wait");try{await l(()=>this.changed()),await l(()=>this.publicationWrites);let u=await l(()=>this.deps.resolveWorkspace(r));if(this.validateStart(o),!u){if(!n)throw new Ri("operationFailed");return this.starting=void 0,this.status={state:"stopped"},await this.changed(),this.snapshot()}this.desired.ownerUri=u.ownerUri,this.validateStart(o);let{workspace:d}=u,f=await l(()=>this.deps.computeId()),p=await this.acquireStartHost(o,{authentication:{mode:"github"},computeId:f,workspace:d,localServer:{hostname:"127.0.0.1",port:0,requireConnectionToken:!0},allowCreatingNewSessions:!1});for(let y of await l(()=>this.deps.readPublicationIds()))await l(()=>this.trackPublicationWrite(p.unpublishSession(y)));if((await l(()=>p.listSessions())).sessions.length)throw new Ri("unsupportedSession");await l(()=>this.trackPublicationWrite(o.receiptWrite=this.deps.writePublicationIds([]))),await l(()=>p.dispose()),this.validateStart(o),this.host=void 0;let m=!1,g=await this.acquireStartHost(o,{authentication:{mode:"github"},workspace:d,githubEnvironment:{name:e,computeId:f,requireConnectionBinding:!0},allowCreatingNewSessions:!1,onExit:a(()=>{m=!0,!(o.controller.signal.aborted||o.epoch!==this.startEpoch||this.generation!==c||this.status.state==="stopping")&&(this.cancelStart(),this.status={...this.status,state:"failed",error:{kind:"operationFailed"},publishedSessions:void 0},this.changed())},"onExit")});if(this.validateStart(o),m||!g.environmentId)throw new Ri("operationFailed");this.status={state:"running",name:e,environmentId:g.environmentId};let A=await l(()=>this.refresh(()=>this.validateStart(o)));return this.validateStart(o),this.starting=void 0,A}catch(u){o.controller.abort();let d=!1;try{await this.cleanupStart(o),d=!0}catch{this.cancelStart()}let f=this.requiresRestart()?new Ri("restartRequired"):u instanceof Ri?u:new Ri("operationFailed");throw(o.epoch===this.startEpoch||!d||this.requiresRestart())&&(this.desired=void 0,this.status={state:"failed",error:{kind:f.kind}},await this.changed()),f}finally{clearTimeout(s)}}validateStart(e){if(e.controller.signal.aborted||e.epoch!==this.startEpoch||this.starting!==e)throw new Ri("operationFailed");this.deps.assertAllowed();let r=this.desired?.ownerUri;if(r&&!this.deps.workspaceFolders().some(n=>n.uri===r))throw new Ri("operationFailed")}waitForStart(e,r){let{signal:n}=e.controller;return new Promise((o,s)=>{let c=a(()=>s(new Ri("operationFailed")),"abort");n.addEventListener("abort",c,{once:!0}),Promise.resolve().then(()=>(this.validateStart(e),r())).then(o,s).finally(()=>n.removeEventListener("abort",c))})}revokeOperations(){this.operationRevocation.abort(),this.operationRevocation=new AbortController}waitForRevocation(e,r){return new Promise((n,o)=>{let s=a(()=>o(new Ri("hostNotRunning")),"abort");if(e.aborted){s();return}e.addEventListener("abort",s,{once:!0}),Promise.resolve().then(()=>{if(e.aborted)throw new Ri("hostNotRunning");return r()}).then(n,o).finally(()=>e.removeEventListener("abort",s))})}trackPublicationWrite(e){let r=e.then(()=>{},()=>{});return this.publicationWrites=Promise.all([this.publicationWrites,r]).then(()=>{}),e}async writeReceiptIds(e,r,n){await this.waitForRevocation(r,()=>this.publicationWrites),n(),await this.waitForRevocation(r,()=>(n(),this.trackPublicationWrite(this.deps.writePublicationIds(e))))}async acquireStartHost(e,r){let n=await this.waitForStart(e,()=>(e.pendingHost=this.deps.startHost(r).catch(o=>{throw e.controller.signal.aborted||(e.pendingHost=void 0),o}),e.pendingHost));return this.validateStart(e),this.host=n,e.pendingHost=void 0,n}async cleanupStart(e,r=!e.hostOnlyCleanup){let n=this.host,s=await E0(a(async()=>{let c=n??await e.pendingHost;return c&&await c.dispose(),await e.receiptWrite?.catch(()=>{}),!0},"cleanup")(),Jgt,!1);if(!s&&!r&&!e.runtimeStopRequested)throw new Ri("operationFailed");if(!s||e.runtimeStopRequested){if(this.desired=void 0,e.runtimeStopRequested=!0,!await E0(this.deps.forceStopRuntime().then(()=>!0),Jgt,!1))throw new Ri("operationFailed");this.status={state:"failed",error:{kind:"restartRequired"}}}this.host=void 0,this.starting=void 0,++this.generation}stop(e){return this.cancelStart(),this.operations.queue(()=>(e&&(e.isNoop=!this.host&&!this.starting&&this.status.state==="stopped"),this.stopHost()))}retire(){return this.cancelStart(),this.operations.queue(()=>this.retireHost(!1))}retireForStart(){return this.desired=void 0,this.revokeOperations(),this.starting?.controller.abort(),this.operations.queue(()=>this.retireHost(!1))}getStatus(){return this.operations.queue(async()=>{if(!this.isRunning())return this.snapshot();let e=this.operationRevocation.signal;try{return await this.refresh(void 0,e)}catch(r){if(!e.aborted)throw r;return this.snapshot()}})}setSessionPublished(e,r,n,o,s){let c=this.host,l=this.captureStartAdmission(),u=this.operationRevocation.signal,d=a(()=>{if(l(),u.aborted||!c||this.host!==c||!this.isRunning())throw new Ri("hostNotRunning")},"validateHost");return this.action(async()=>{if(d(),!c)throw new Ri("hostNotRunning");if(n&&s?.(),!n){try{await this.waitForRevocation(u,()=>this.trackPublicationWrite(c.unpublishSession(e))),d()}catch{return this.failPublication(c,d)}return await this.forgetReceipt(e,u,d),d(),this.deps.registry.setLocalEnvironmentPublication(e,void 0),await this.refresh(d,u),d(),{sessionId:e,published:!1}}if(!r)throw new Ri("unsupportedSession");let f=a(()=>{if(d(),this.deps.assertAllowed(),this.deps.registry.get(e)!==r)throw new Ri("unsupportedSession")},"validateBinding"),p=a(async()=>{f(),await this.waitForRevocation(u,async()=>o?.()),f()},"validatePublication");await p();let m=await this.waitForRevocation(u,()=>this.sessionWorkspaceMismatch(e));if(await p(),m)throw new Ri("unsupportedSession");let g=await this.waitForRevocation(u,()=>this.deps.readPublicationIds());await p(),g.includes(e)||await this.writeReceiptIds([...g,e],u,f),await p();let A={session:r};this.deps.registry.setLocalEnvironmentPublication(e,A),this.deps.registry.replaceChild(e,"localEnvironment",{dispose:a(()=>this.operations.queue(async()=>{if(!(this.host!==c||this.deps.registry.getLocalEnvironmentPublication(e)!==A))try{await this.waitForRevocation(u,()=>this.trackPublicationWrite(c.unpublishSession(e))),await this.forgetReceipt(e,u,d),d(),this.deps.registry.setLocalEnvironmentPublication(e,void 0),await this.refresh(d,u)}catch{await this.retirePublicationHost(c,d)}}),"dispose")});let y;try{await p(),y=await this.waitForRevocation(u,()=>this.trackPublicationWrite(c.publishSession(e))),await p(),A.sessionUri=y.sessionUri,await this.refresh(f,u),await p()}catch{return this.failPublication(c,d)}return{sessionId:e,published:!0,sessionUri:y.sessionUri}})}async sessionWorkspaceMismatch(e){let r=this.deps.registry.getWorkingDir(e),n=this.desired?.ownerUri;if(!r||!(0,r9.isAbsolute)(r)||!n)return!1;let o,s;try{[o,s]=await Promise.all([this.deps.realpath(Jn(n).fsPath),this.deps.realpath(r)])}catch{return!1}let c=(0,r9.relative)(o,s);return c===".."||c.startsWith(`..${r9.sep}`)||(0,r9.isAbsolute)(c)}async retirePublicationHost(e,r){try{r()}catch{if(this.host===e)try{await this.stopHost(!1)}catch(n){throw this.cancelStart(),n}return!1}return await this.retireHost(),!0}async failPublication(e,r){let n=await this.retirePublicationHost(e,r);throw new Ri(n?"operationFailed":"hostNotRunning")}async retireHost(e=!0){e&&this.cancelStart();try{await this.stopHost(!0)}catch(r){if(this.starting)throw r;await this.deps.forceStopRuntime(),this.host=void 0,++this.generation,this.status={state:"failed",error:{kind:"restartRequired"}},await this.changed()}}async stopHost(e){if(this.starting&&await this.cleanupStart(this.starting,e),!this.host)return this.status.state==="stopped"||this.requiresRestart()?this.snapshot():(this.status={state:"stopped"},await this.changed(),this.snapshot());this.status={...this.status,state:"stopping",publishedSessions:void 0},await this.changed();try{let r=this.host;if(e===!1){if(!await E0(Promise.resolve().then(()=>r.dispose()).then(()=>!0),Jgt,!1))throw new Ri("operationFailed")}else await r.dispose();return this.host=void 0,++this.generation,this.status={state:"stopped"},await this.changed(),this.snapshot()}catch{throw this.status={state:"failed",error:{kind:"operationFailed"}},await this.changed(),new Ri("operationFailed")}}async refresh(e,r=this.operationRevocation.signal){let n=this.host,o=a(()=>{if(r.aborted||!n||this.host!==n)throw new Ri("hostNotRunning");e?.()},"validateRefresh"),s;try{({sessions:s}=await this.waitForRevocation(r,()=>(o(),n.listSessions())))}catch{return o(),this.status={...this.status,publishedSessions:void 0,error:{kind:"operationFailed"}},await this.changed(),o(),this.snapshot()}return o(),this.status.state!=="running"?this.snapshot():(this.status={state:"running",name:this.status.name,environmentId:this.status.environmentId,publishedSessions:s.map(c=>({sessionUri:c.resource,title:c.title,sessionId:this.deps.registry.localEnvironmentSessionId(c.resource)}))},await this.changed(),o(),this.snapshot())}async forgetReceipt(e,r,n){let o=await this.waitForRevocation(r,()=>this.deps.readPublicationIds());n(),await this.writeReceiptIds(o.filter(s=>s!==e),r,n)}snapshot(){let e=structuredClone(this.status);return this.isRunning()&&(e.workspaceUri=this.desired?.ownerUri),e}async changed(){try{await E0(this.deps.notify(this.snapshot()).then(()=>!0),Jgt,!1)||Hfi.warn(this.ctx,"Could not deliver local environment status")}catch{Hfi.warn(this.ctx,"Could not deliver local environment status")}}action(e){return this.operations.queue(async()=>{try{return await e()}catch(r){throw this.requiresRestart()?new Ri("restartRequired"):r instanceof Ri?r:new Ri("operationFailed")}})}};h();async function Xgt(t,e,r,n){let o=performance.now(),s={stage:"admission",isNoop:!1},c="error",l;try{let u=await n(s);return c="success",u}catch(u){throw l=u instanceof Ri?u.kind:"operationFailed",u}finally{gi(t,"backgroundAgent.localEnvironmentAction",{operation:e,trigger:r??"unknown",result:c,isNoop:String(s.isNoop),...l?{errorKind:l,stage:s.stage}:{}},{durationMs:performance.now()-o})}}a(Xgt,"trackLocalEnvironmentAction");h();var zfi=require("fs/promises"),Gfi=require("path");async function Vfi(t){for(let e of t)try{let r=Jn(e.uri);if(r.scheme==="file"&&(0,Gfi.isAbsolute)(r.fsPath)&&(await(0,zfi.stat)(r.fsPath)).isDirectory())return{ownerUri:e.uri,workspace:r.fsPath}}catch{}}a(Vfi,"resolveLocalEnvironmentWorkspace");h();var Rve=class{constructor(e,r,n){this.ctx=e;this.target=n;this.syncScheduled=!1;this.logger=new fe(r);let o=qgt(e);o&&(this.host=o,this.mountsChangedListener=()=>this.schedule(),o.service.on(hne.MountsChanged,this.mountsChangedListener))}static{a(this,"GatewayMountsSync")}dispose(){this.host&&this.mountsChangedListener&&(this.host.service.off(hne.MountsChanged,this.mountsChangedListener),this.mountsChangedListener=void 0,this.host=void 0)}schedule(){this.syncScheduled||(this.syncScheduled=!0,queueMicrotask(()=>{this.syncScheduled=!1;let e=this.host;e&&this.target.syncToActiveSessions(e).catch(r=>this.onSyncError(r))}))}onSyncError(e){this.logger.warn(this.ctx,"MCP active-session sync failed",{error:e instanceof Error?e.message:String(e)})}};var Jfi=require("fs/promises"),Pve=he(require("node:path")),Zfi=require("os");Bo();var Al=new fe("BackgroundAgent"),aN="backgroundAgent",Vha=new Set(["system.message","hook.start","hook.end"]),qP="auto";function Wfi(t,e){return{...t,model:qP,provider:void 0,capi:t.capi&&{...t.capi,autoTier:void 0},featureFlags:{...t.featureFlags,...Gz},enableExperimentalMode:e}}a(Wfi,"legacyAutoSessionOptions");var Wha=new Set(["gpt-41-copilot","gpt-4.1","gpt-4.1-2025-04-14","gpt-5.4-nano","gemini-2.5-pro","grok-code-fast-1"]);function Yfi(t){return t.model_picker_enabled===!0&&t.capabilities.type==="chat"&&!Wha.has(t.id)}a(Yfi,"isSupportedBackgroundAgentModel");function Kfi(t,e){let r=a(n=>/^[A-Za-z]:[\\/]/.test(n)||/^\\\\/.test(n),"isWindowsPath");return r(t)&&r(e)?Pve.win32.normalize(t).toLowerCase()===Pve.win32.normalize(e).toLowerCase():Pve.posix.normalize(t)===Pve.posix.normalize(e)}a(Kfi,"sessionPathsEqual");function Yha(t){return{status:t.status,...t.effectiveAutoTier!==void 0?{effectiveAutoTier:t.effectiveAutoTier}:{},...t.pendingAutoTier!==void 0?{pendingAutoTier:t.pendingAutoTier}:{},...t.activatingAutoTier!==void 0?{activatingAutoTier:t.activatingAutoTier}:{},...t.supersededAutoTier!==void 0?{supersededAutoTier:t.supersededAutoTier}:{}}}a(Yha,"toSetAutoTierResult");var fo=class{constructor(e,r=new Pht(void 0,()=>e.get(zf).isSkillsEnabled())){this.ctx=e;this.copilotCommandPolicy=r;this.authSequencer=new H2;this.localEnvironmentClosed=!1;this.pendingExternalToolDefs=new Map;this.notificationSender=e.get(zs),this.managerLifecycle=new zht(e),this.authBinding=new Blt(e),this.structuredReviewCoordinator=new Wgt(e),this.registry=new $gt(e,(s,c)=>this.managerLifecycle.closeSession(s,c),()=>this.managerLifecycle.invalidateCommandCatalog()),this.builtinSubagentModelPolicy=new Cht(e,this.registry,(s,c)=>this.managerLifecycle.closeSession(s,c)),this.remoteController=new Vht(e,{registry:this.registry}),this.localEnvironment=new Zgt(e,{registry:this.registry,startHost:a(s=>this.managerLifecycle.startLocalEnvironment(s),"startHost"),forceStopRuntime:a(()=>this.managerLifecycle.forceStop(),"forceStopRuntime"),computeId:a(()=>$fi(e.get($n).directory),"computeId"),workspaceFolders:a(()=>e.get(Mr).getWorkspaceFolders(),"workspaceFolders"),realpath:a(s=>(0,Jfi.realpath)(s),"realpath"),resolveWorkspace:Vfi,readPublicationIds:a(()=>qfi(e.get($n).directory),"readPublicationIds"),writePublicationIds:a(s=>jfi(e.get($n).directory,s),"writePublicationIds"),assertAllowed:a(()=>{if(this.localEnvironmentClosed)throw new Ri("hostNotRunning");if(e.get($u).get().remoteControl?.mode==="disabled")throw new Ri("policyDenied")},"assertAllowed"),notify:a(s=>this.notificationSender.sendLocalEnvironmentDidChange(s),"notify")}),this._localEnvironmentWorkspaceListener=e.get(Mr).onDidChangeWorkspaceFolders(s=>{let c=this.localEnvironment.workspaceFoldersChanged(s.workspaceFolders);c&&this.handleLocalEnvironmentWorkspaceChange(c)}),this.sandboxConfigSync=new Wht(e,this.registry),this.permissionModeController=new Ght(e,this.registry),this.eventRouter=new wht(e,this.registry,this.notificationSender),this.turnDriver=new Ggt(e,this.eventRouter),this.copilotCommandCoordinator=new Rht(e,r,this.registry,this.eventRouter,this.turnDriver,this.sandboxConfigSync,this.permissionModeController,this.notificationSender);let n=new Ult(e,this.registry);this._mcpSync=new Rve(e,"BackgroundAgent.McpSync",n);let o=e.get(Dn);this._commandPolicyListener=o.onDidChangeCopilotSettings(()=>{this.registry.invalidateCommandCatalogs(),this.managerLifecycle.invalidateCommandCatalog()}),o.onDidChangeHttpSettings(()=>{vht(this.ctx)}),oa(e,()=>{this.handleAuthStateChange()});try{this._skillsEnabledListener=this.ctx.get(zf).onDidChangeSkillsEnabled(()=>{this.registry.clearChatMode(),this.registry.invalidateCommandCatalogs(),this.managerLifecycle.invalidateCommandCatalog()})}catch(s){if(!(s instanceof _a))throw s}try{this._organizationInstructionsListener=this.ctx.get(OB).onDidChangeInstructions(s=>this.registry.markOrganizationInstructionsChanged(s))}catch(s){if(!(s instanceof _a))throw s}}static{a(this,"BackgroundAgentService")}async handleAuthStateChange(){let e=this.localEnvironment.captureStartCancellation();if(e)try{let r=await this.authBinding.resolveIdentity();this.managerLifecycle.requiresAuthRestart(r.enterpriseAuth,r.runtimeToken)&&e()}catch{}return this.authSequencer.queue(async()=>{let r;try{r=await this.authBinding.resolveIdentity()}catch(u){Al.warn(this.ctx,"Failed to read GitHub session on auth change; skipping cache invalidation",{error:u instanceof Error?u.message:String(u)});return}let{changed:n,hadPrevious:o,hasCurrent:s,enterpriseAuth:c,runtimeToken:l}=r;n&&(Al.info(this.ctx,"GitHub identity changed, clearing cached sessions",{hadPrevious:o,hasCurrent:s,cachedSessionCount:this.registry.size(),remoteSessionCount:this.remoteController.activeCount()}),await this.clearUserScopedState(),await this.managerLifecycle.disposeIfAuthChanged(c,l)&&Al.info(this.ctx,"Restarting Copilot runtime for GitHub authentication change",{githubHost:c?.githubHost}),r.commit())})}async clearUserScopedState(e=!1){this.pendingExternalToolDefs.clear(),this.managerLifecycle.invalidateCommandCatalog(),await this.structuredReviewCoordinator.cancelAll(),await(e?this.localEnvironment.retireForStart():this.localEnvironment.retire()),await this.registry.removeAll(()=>this.managerLifecycle.closeAllSessions())}reviewCode(e,r){let n=a(async o=>{let s=await this.buildAuthInfo(),c=await this.ensureManager(o);return{authInfo:s,manager:c}},"prepareRuntime");return this.structuredReviewCoordinator.review(e,r,n)}ensureManager(e,r){return this.authSequencer.queue(async()=>{e?.();let n=await this.authBinding.resolveIdentity();if(r!==void 0&&(e?.(),n.runtimeToken!==r||n.enterpriseAuth))throw new Ri("authenticationRequired");let o=n.enterpriseAuth,s=this.managerLifecycle.requiresAuthRestart(o,n.runtimeToken);if(s&&(Al.info(this.ctx,"GitHub authentication changed before manager use, clearing cached sessions",{githubHost:o?.githubHost}),await this.clearUserScopedState(r!==void 0),await this.managerLifecycle.disposeIfAuthChanged(o,n.runtimeToken),r!==void 0)){let l=await this.authBinding.resolveIdentity();if(e?.(),l.runtimeToken!==r||l.enterpriseAuth)throw new Ri("authenticationRequired")}e?.();let c=await this.managerLifecycle.ensureManager(o,n.runtimeToken,e);return(s||o!==void 0)&&n.commit(),c})}get sdk(){return this.managerLifecycle.getSdk()}async handleInteraction(e){let r=performance.now(),n=await this.getOrResumeCurrentSession(e.sessionId),o=await w6n(n,e);return uu(this.ctx,"backgroundAgent.interaction",{requestSource:aN,sessionId:e.sessionId,requestId:e.requestId,interactionType:e.type,resultKind:e.type==="permission"?e.result.kind:""},{totalTimeMs:performance.now()-r}),o}buildAuthInfo(){return this.authBinding.buildAuthInfo()}async detachForReplacement(e,r,n){return this.registry.queueAfterCopilotCommandInvocations(e,async()=>this.registry.getLocalEnvironmentPublication(e)?.session===r&&n&&!n()||(await this.registry.withdrawLocalEnvironmentPublication(e,r),!await this.remoteController.detachForReplacement(e,r,n))?!1:(await this.sandboxConfigSync.drainSession(e),await this.eventRouter.unbind(e,r),!0))}applyChatModeSelection(e,r){return kfi(this.ctx,e,r)}buildSessionOptions(e,r){return wfi(this.ctx,e,r,{buildAuthInfo:a(()=>this.buildAuthInfo(),"buildAuthInfo"),getChatMode:a(()=>this.registry.getChatMode(e),"getChatMode")})}async organizationKeysForBuildParams(e){try{return await this.ctx.get(OB).organizationKeysForWorkspaces(e.sessionWorkspaceFolders??[e.workspaceFolder])}catch(r){return r instanceof _a||Al.warn(this.ctx,"Failed to resolve organization scope for Background Agent session",r),new Set}}rememberSystemMessageBuilder(e,r,n,o){this.registry.setSystemMessageBuilder(e,()=>jgt(this.ctx,e,r,{getChatMode:a(()=>this.registry.getChatMode(e),"getChatMode")})),this.registry.setOrganizationKeys(e,n),this.registry.setAppliedOrganizationInstructionRevision(e,o)}async createSession(e){let r=performance.now();Al.info(this.ctx,"createSession called:",{model:e.model,workspaceFolder:e.workspaceFolder});let n=e.sessionId??Lt();return this.registry.withSessionAdmission(n,async()=>{let o=await BBe(this.ctx,e);return{manager:await this.ensureManager(),resolvedTarget:o}},({manager:o,resolvedTarget:s})=>this.createAdmittedSession(o,n,e,s,r))}async createAdmittedSession(e,r,n,o,s){let c=n.inlineConfinedFile?Wii(2):void 0,l=n.inlineConfinedFile?Yii(n.inlineConfinedFile):void 0;await this.ctx.get(Dn).requireReady();let u={...n,model:o.target.model,provider:o.providerConfig,autoTier:o.autoTier,inlineTurnLimiter:c,inlineConfinementHook:l},d=await this.organizationKeysForBuildParams(u),f=this.registry.organizationInstructionRevision(),p=this.builtinSubagentModelPolicy.prepare(r,await this.buildSessionOptions(r,u)),{options:m}=p,g;try{g=await e.createSession(m)}catch(y){throw Zl(o.target.model)?new lw(`Failed to create Fusion session ${r}: ${ol(y)}`,r,"create"):y}let A=_ht(this.ctx);return await p.apply(g,A,()=>e.closeSession(r,g)),c&&this.registry.setTurnLimiter(r,c),Al.info(this.ctx,"Session created:",r),uu(this.ctx,"backgroundAgent.create",{requestSource:aN,reasoningEffort:n.reasoningEffort??"",sessionId:r,...n.shell?.initScripts?.length&&{shell_options_applied:"true"}},{totalTimeMs:performance.now()-s}),p.publish(),this.registry.setLocalEnvironmentMode(r,g,"agent"),n.sandbox&&this.registry.setDesiredSandboxEnabled(r,n.sandbox.enabled),m.sandboxConfig&&this.registry.setAppliedSandboxConfig(r,m.sandboxConfig),this.registry.replaceChild(r,"sessionEventRouter",this.eventRouter.bind(r,g)),this.registry.setResumeOptions(r,m),this.rememberSystemMessageBuilder(r,u,d,f),this.registry.setProviderModel(r,o.target),this.registry.setWorkingDir(r,Jn(n.workspaceFolder.uri).fsPath),this.registry.setWorkspaceFolderUri(r,n.workspaceFolder.uri),n.mcpDirectory&&this.registry.setMcpDirectory(r,n.mcpDirectory),n.inlineConfinedFile&&this.registry.setConfinedFile(r,n.inlineConfinedFile),n.sandbox&&this.sandboxConfigSync.reportSelection(n.sandbox.enabled),{sessionId:r,workspacePath:g.workspacePath}}registerExternalTools(e,r){r?.length&&(this.pendingExternalToolDefs.set(e,r),Al.info(this.ctx,"Stored pending external tool definitions",{sessionId:e,toolCount:r.length}))}getOrResumeCurrentSession(e){let r=this.registry.get(e);return r?Promise.resolve(r):this.getOrResumeSession(e)}async getOrResumeSession(e,r={},n,o=!1,s,c){c?.();let l=this.registry.get(e),u;return l&&!this.pendingExternalToolDefs.has(e)&&!n&&!this.registry.hasStaleOrganizationInstructions(e)&&(!(Zl(this.registry.getProviderModel(e)?.model)||this.registry.getResumeOptions(e)?.featureFlags?.HYDRAFUSION===!0)||(u=(await H6(this.ctx)).enabled,c?.(),u))?l:this.registry.withSessionAdmission(e,()=>this.ensureManager(c),async d=>{c?.();let f={cleanupArmed:!1};try{let p=await this.getOrResumeAdmittedSession(d,e,r,n,f,o,u,s,c);return o&&this.registry.beginOrdinarySendPreparation(e,p,r.model?.trim()==="ensemble"),p}catch(p){if(f.cleanupArmed){let m=f.exactSession;try{await this.registry.remove(e,m?()=>d.closeSession(e,m):void 0)}catch(g){Al.warn(this.ctx,"Failed to clear an unsafe exact-session transition",{sessionId:e,error:ol(g)})}}throw p}})}async getOrResumeAdmittedSession(e,r,n,o,s,c,l,u,d){let f=!1,p=!1,m=l,g=this.registry.hasStaleOrganizationInstructions(r),A=this.registry.organizationInstructionRevision();await this.ctx.get(Dn).requireReady(),d?.();let v=this.registry.getAppliedBuiltinSubagentSessionModelPolicy(r),E=this.registry.get(r);if(E&&!o&&(Zl(this.registry.getProviderModel(r)?.model)||this.registry.getResumeOptions(r)?.featureFlags?.HYDRAFUSION===!0)&&(m??=(await H6(this.ctx)).enabled,m||(o={target:{model:qP,provider:void 0},providerConfig:void 0})),E){let Y=a(()=>{o&&u?.(E)},"assertTargetPreparationAllowed"),te=a(()=>_ht(this.ctx)!==v&&(n.workspaceFolder!==void 0||c&&!this.registry.hasOrdinarySendPreparation(r,E)&&!this.eventRouter.hasActiveTurn(r,E)&&!this.registry.hasCopilotCommandInvocation(r,E)),"policyChangeRequiresReconnect"),re=te(),j=this.pendingExternalToolDefs.get(r);if(o){let G=this.registry.getProviderModel(r);p=Zl(G?.model)&&!Zl(o.target.model);let L=!koi(G,o.target);if(this.registry.hasOrdinarySendPreparation(r,E)&&(n.model?.trim()==="ensemble"||this.registry.hasEnsembleSendPreparation(r,E)||Zl(G?.model)||Zl(o.target.model)))throw new lw(`Cannot switch session model or Fusion tier during a pending send: ${r}`,r,"update");let M=G!==void 0&&G.provider===void 0&&o.target.provider===void 0&&G.model!==o.target.model,k=!j&&!g&&M&&!re,F=Zl(o.target.model),V=Zl(G?.model)||F,se=a(()=>V&&(L||j!==void 0||g||re),"reconnectingFusion"),ce=a(()=>!this.registry.hasOrdinarySendPreparation(r,E)&&!this.eventRouter.hasActiveTurn(r,E)&&!this.registry.hasCopilotCommandInvocation(r,E),"canTransitionFusion");if(se()&&!ce())throw new lw(`Cannot switch Fusion runtime options during a pending or active turn: ${r}`,r,"update");if(k){Y();try{F&&await E.updateOptions({featureFlags:{...xre},isExperimentalMode:!0}),await E.setModel(o.target.model,{...V?{}:{deferIfModelChangeQueued:!0},...V||n.model?.trim()==="ensemble"?{requireApplied:!0}:{},...o.target.model===qP&&o.autoTier!==void 0?{autoTier:l4e(o.autoTier)}:{}})}catch(ve){throw(V||n.model?.trim()==="ensemble")&&(s.cleanupArmed=!0,s.exactSession=E),o.target.model===qP&&o.autoTier!==void 0?new M0(`Failed to apply Auto tier for session ${r}: ${ol(ve)}`,o.autoTier,"set",r):new lw(`Failed to switch model for session ${r}: ${ol(ve)}`,r,"update")}let W=!Zl(o.target.model)&&(Zl(G?.model)||F),ne=this.registry.getAppliedPermissionMode(r),X=ne?.session===E?ne.mode==="assisted":void 0;if(W)try{await E.updateOptions({featureFlags:{...Gz},...X!==void 0?{isExperimentalMode:X}:{}})}catch(ve){throw s.cleanupArmed=!0,s.exactSession=E,new lw(`Failed to restore legacy Auto runtime options for session ${r}: `+ol(ve),r,"update")}let oe=this.registry.getResumeOptions(r);oe&&this.registry.setResumeOptions(r,{...oe,model:o.target.model,provider:o.providerConfig,...Zl(o.target.model)?{featureFlags:{...oe.featureFlags,...xre},enableExperimentalMode:!0}:W?{featureFlags:{...oe.featureFlags,...Gz},enableExperimentalMode:X}:{}}),this.registry.setProviderModel(r,o.target),Y()}else if(!j&&!L&&!re){if(o.target.provider!==void 0){Y();try{await E.updateOptions({model:o.target.model,provider:o.providerConfig??null})}catch(ne){throw new lw(`Failed to refresh model/provider info for session ${r}: `+ol(ne),r,"update")}let W=this.registry.getResumeOptions(r);W&&this.registry.setResumeOptions(r,{...W,model:o.target.model,provider:o.providerConfig}),this.registry.setProviderModel(r,o.target),Y()}else if(o.target.model===qP&&o.autoTier!==void 0){Y();try{await E.setAutoTier(l4e(o.autoTier))}catch(W){throw new M0(`Failed to switch Auto tier for session ${r}: ${ol(W)}`,o.autoTier,"set",r)}this.registry.setProviderModel(r,o.target),Y()}}if(!j&&!g&&!re&&(k||!L)){if(n.shell?.initScripts?.length){Y(),await E.updateOptions({shell:n.shell});let W=this.registry.getResumeOptions(r);W&&this.registry.setResumeOptions(r,{...W,shell:n.shell}),Y()}if(re=te(),!re){if(n.workspaceFolder!==void 0&&!await this.sandboxConfigSync.alignSession(r,E,"resume",n.sandbox?.enabled))throw new Error(`Session changed while applying sandbox configuration: ${r}`);return E}}let pe=re&&c&&n.workspaceFolder===void 0&&!j&&!g&&(!L||M);re&&!pe&&(s.cleanupArmed=!0,s.exactSession=E);let ye=u!==void 0,ae,z=pe||se()||ye?()=>{try{Y()}catch(W){if(!(W instanceof Cg))throw W;return ae=W,!1}return(!pe||te())&&(!se()||ce())}:void 0;try{let W=await this.detachForReplacement(r,E,z);if(!W&&ae)throw ae;if(!W)return s.cleanupArmed=!1,s.exactSession=void 0,this.getOrResumeAdmittedSession(e,r,n,o,s,!1,void 0,u,d);re&&(s.cleanupArmed=!0,s.exactSession=E),this.registry.deleteChatMode(r),this.registry.deleteAppliedSandboxConfig(r),await e.closeSession(r,E),s.cleanupArmed&&(s.exactSession=void 0)}catch(W){throw W instanceof Cg?(s.cleanupArmed=!1,s.exactSession=void 0,W):L?new lw(`Failed to close session ${r} before applying a new model/provider target: `+ol(W),r,"close"):W}f=L,Al.info(this.ctx,"Reopening cached session with refreshed connection options",{sessionId:r,model:o.target.model,providerName:o.target.provider,pendingExternalToolCount:j?.length??0,organizationInstructionsStale:g})}else if(j||g){let G=Zl(this.registry.getProviderModel(r)?.model)||this.registry.getResumeOptions(r)?.featureFlags?.HYDRAFUSION===!0,L=a(()=>!G||!this.registry.hasOrdinarySendPreparation(r,E)&&!this.eventRouter.hasActiveTurn(r,E)&&!this.registry.hasCopilotCommandInvocation(r,E),"canDetachFusion");if(!L()||!await this.detachForReplacement(r,E,G?L:void 0))return E;this.registry.deleteChatMode(r),this.registry.deleteAppliedSandboxConfig(r),await e.closeSession(r,E),Al.info(this.ctx,"Reopening cached session with refreshed connection options",{sessionId:r,pendingExternalToolCount:j?.length??0,organizationInstructionsStale:g})}else return E;g&&E.getEvents().length===0&&this.registry.requireSessionRecreation(r)}let _=this.pendingExternalToolDefs.get(r),S=this.registry.getResumeOptions(r),T=this.registry.getAppliedPermissionMode(r),x=T===void 0?void 0:T.mode==="assisted";p||=o!==void 0&&!Zl(o.target.model)&&(S?.featureFlags?.HYDRAFUSION===!0||n.model?.trim()==="ensemble"&&o.target.model===qP);let w=n.sandbox?.enabled??this.registry.getDesiredSandboxEnabled(r),I=n.workspaceFolder,R,D,N=!g,O;if(!I&&S){let Y=this.registry.getWorkspaceFolderUri(r);if(!Y)throw new Error(`Cannot resume session ${r}: cached connection options have no workspace URI`);I={uri:Y};let te=g?this.registry.buildSystemMessage(r):void 0,re=te?await te:S.systemMessage,j=f_r(S.capi,o?.autoTier);N||=te!==void 0,O={...S,systemHooks:n.systemHooks??S.systemHooks,...Zl(o?.target.model)?{featureFlags:{...S.featureFlags,...xre},enableExperimentalMode:!0}:p?{featureFlags:{...S.featureFlags,...Gz},enableExperimentalMode:x}:{},systemMessage:re,sessionId:r,...o?{model:o.target.model,provider:o.providerConfig}:{},capi:j,...n.shell?.initScripts?.length?{shell:n.shell}:{},sandboxConfig:oAe(this.ctx,w)??{enabled:!1},externalToolDefinitions:n.externalToolDefinitions??_??S.externalToolDefinitions}}else{if(!I){d?.();let re=await e.getSessionMetadata({sessionId:r});if(!re)throw new Error(`Session not found: ${r}`);let j=re.context?.cwd;if(!j)throw new Error(`Cannot resume session ${r} from disk: persisted metadata is missing working-directory context`);I={uri:Cs(j)},Al.info(this.ctx,"Resuming session from disk via metadata fallback",{sessionId:r})}let Y={...n,sandbox:w===void 0?void 0:{enabled:w},...o?{model:o.target.model,provider:o.providerConfig,autoTier:o.autoTier}:{},externalToolDefinitions:n.externalToolDefinitions??_,workspaceFolder:I};D=await this.organizationKeysForBuildParams(Y);let te=await this.buildSessionOptions(r,Y);N=!0,R=a(()=>jgt(this.ctx,r,Y,{getChatMode:a(()=>this.registry.getChatMode(r),"getChatMode")}),"systemMessageBuilder"),O={...te,...p?{featureFlags:{...te.featureFlags,...Gz},enableExperimentalMode:x}:{},sessionId:r,sandboxConfig:te.sandboxConfig??{enabled:!1}}}!o&&(Zl(O.model)||O.featureFlags?.HYDRAFUSION===!0)&&(m??=(await H6(this.ctx)).enabled,m||(o={target:{model:qP,provider:void 0},providerConfig:void 0},p=!0,O=Wfi(O,x)));let Q=this.builtinSubagentModelPolicy.prepare(r,O);O=Q.options;let $;try{d?.(),$=this.registry.needsSessionRecreation(r)?await e.createSession(O):await e.getSession(O,!0)}catch(Y){throw f||Zl(o?.target.model)?new lw(`Failed to resume session ${r} with the requested model/provider: `+ol(Y),r,"resume"):Y}if(!$)throw f?new lw(`Session not found while applying the requested model/provider target: ${r}`,r,"resume"):new Error(`Session not found: ${r}`);if(!o){let Y=$.getEvents(),te;for(let re=Y.length-1;re>=0;re--){let j=Y[re];if(!("agentId"in j&&j.agentId)){if(j.type==="session.model_change"){te=j.data.newModel;break}if((j.type==="session.start"||j.type==="session.resume")&&j.data.selectedModel){te=j.data.selectedModel;break}}}Zl(te)&&(m??=(await H6(this.ctx)).enabled),Zl(te)&&m===!1&&(o={target:{model:qP,provider:void 0},providerConfig:void 0},p=!0,O=Wfi(O,x))}if(s.cleanupArmed&&(s.exactSession=$),o){let Y=performance.now();try{o.target.provider===void 0?(Zl(o.target.model)&&await $.updateOptions({featureFlags:{...xre},isExperimentalMode:!0}),await $.setModel(o.target.model,{...Zl(o.target.model)||p||n.model?.trim()==="ensemble"?{requireApplied:!0}:{},...o.target.model===qP&&o.autoTier!==void 0?{autoTier:l4e(o.autoTier)}:{}})):await $.updateOptions({model:o.target.model,provider:o.providerConfig??null}),p&&(await $.updateOptions({featureFlags:{...Gz},...x!==void 0?{isExperimentalMode:x}:{}}),O={...O,featureFlags:{...O.featureFlags,...Gz},enableExperimentalMode:x}),O={...O,model:o.target.model,provider:o.providerConfig},p_r(this.ctx,"success",performance.now()-Y)}catch(te){p_r(this.ctx,"failure",performance.now()-Y);try{await e.closeSession(r,$),s.cleanupArmed&&(s.exactSession=void 0)}catch(re){Al.warn(this.ctx,"Failed to close session after target activation failure",{sessionId:r,error:ol(re)})}throw o.target.provider===void 0&&o.target.model===qP&&o.autoTier!==void 0?new M0(`Failed to apply Auto tier for session ${r}: ${ol(te)}`,o.autoTier,"set",r):new lw(`Failed to apply model/provider info after resuming session ${r}: `+ol(te),r,"update")}}let U=_ht(this.ctx);await Q.apply($,U,()=>e.closeSession(r,$),!s.cleanupArmed),_&&this.pendingExternalToolDefs.get(r)===_&&this.pendingExternalToolDefs.delete(r),Q.publish(),this.registry.clearSessionRecreation(r),this.registry.replaceChild(r,"sessionEventRouter",this.eventRouter.bind(r,$)),this.registry.setResumeOptions(r,O),R&&this.registry.setSystemMessageBuilder(r,R),D&&this.registry.setOrganizationKeys(r,D),N&&this.registry.setAppliedOrganizationInstructionRevision(r,A),o&&this.registry.setProviderModel(r,o.target);let H=Array.from($.getEvents()).filter(Y=>Y.type==="user.message").length;H>0&&this.registry.seedTurnIndexIfAbsent(r,H-1),this.registry.deleteChatMode(r),this.registry.setAppliedSandboxConfig(r,O.sandboxConfig);let K=I?.uri?Jn(I.uri).fsPath:void 0;K&&this.registry.setWorkingDir(r,K),I?.uri&&this.registry.setWorkspaceFolderUri(r,I.uri),n.mcpDirectory&&this.registry.setMcpDirectory(r,n.mcpDirectory),s.cleanupArmed=!1,s.exactSession=void 0;try{if(!await this.sandboxConfigSync.alignSession(r,$,"resume",n.sandbox?.enabled))throw new Error(`Session changed while applying sandbox configuration: ${r}`);await this.remoteController.restoreForSession(r,$)}catch(Y){await this.registry.withdrawLocalEnvironmentPublication(r,$);try{await this.remoteController.detachForReplacement(r,$)}catch(te){Al.warn(this.ctx,"Failed to disable Remote after rebind restoration failed",{sessionId:r,error:te instanceof Error?te.message:String(te)}),this.registry.get(r)===$&&this.registry.forgetSession(r)}await this.sandboxConfigSync.drainSession(r),await this.eventRouter.unbind(r,$);try{await e.closeSession(r,$)}catch(te){Al.warn(this.ctx,"Failed to disconnect session after Remote restoration failed",{sessionId:r,error:te instanceof Error?te.message:String(te)})}throw Y}return $}async addWorkspaceFolder(e,r){let n=performance.now(),o="success";try{return await this.updateWorkspaceFolder(e,r,"addWorkspaceFolder"),{added:!0}}catch(s){throw o="failure",s}finally{uu(this.ctx,"backgroundAgent.addWorkspaceFolder",{status_text:o},{totalTimeMs:performance.now()-n})}}async removeWorkspaceFolder(e,r){let n=performance.now(),o="success";try{return await this.updateWorkspaceFolder(e,r,"removeWorkspaceFolder"),{removed:!0}}catch(s){throw o="failure",s}finally{uu(this.ctx,"backgroundAgent.removeWorkspaceFolder",{status_text:o},{totalTimeMs:performance.now()-n})}}updateWorkspaceFolder(e,r,n){return this.registry.withSessionAdmission(e,()=>this.ctx.get(Dn).requireReady(),async()=>{let o=this.registry.get(e);if(!o)throw new Error(`No active Background Agent session found: ${e}`);let s=Jn(r);if(s.scheme!=="file")throw new Error(`Workspace folder must use the file URI scheme: ${r}`);try{await o[n](s.fsPath),await this.reapplyChatModeAfterWorkspaceChange(e,o,{reloadProjectCatalogs:n==="addWorkspaceFolder"})}catch(c){if(n==="removeWorkspaceFolder"&&this.registry.get(e)===o)try{await this.registry.remove(e,()=>this.managerLifecycle.closeSession(e,o))}catch(l){Al.warn(this.ctx,"Failed to close session after workspace folder removal failed",{sessionId:e,error:l instanceof Error?l.message:String(l)})}throw c}})}async reapplyChatModeAfterWorkspaceChange(e,r,n){let o=this.registry.getChatMode(e);if(this.registry.deleteChatMode(e),!!o){if(n.reloadProjectCatalogs){let c=(await Promise.allSettled([r.reloadCustomAgents(),r.reloadSkills()])).find(l=>l.status==="rejected");if(c)throw c.reason}await this.applyChatModeOverride(e,r,{sessionId:e,message:"",chatMode:o})}}async sendMessage(e,r){if(e.copilotCommandInvocationId){if(!this.ctx.get(Rn).getCapabilities().copilotCommands)throw new Cg("invocation_not_admitted",{type:"direct",copilotCommandInvocationId:e.copilotCommandInvocationId});if(e.autoTier!==void 0)throw new M0("Copilot command sends do not support autoTier; use backgroundAgent/setAutoTier on the live Auto session.",e.autoTier,"validate",e.sessionId);if(e.ensembleTier!==void 0)throw new vv("conflictingTier",e.ensembleTier,e.sessionId);let c=e.copilotCommandInvocationId;return this.registry.runCopilotCommandRequest(e.sessionId,l=>this.registry.runSerializedCopilotCommandOperation(e.sessionId,async()=>{let u={type:"direct",copilotCommandInvocationId:c},d=a(()=>new Cg("invocation_not_admitted",u),"commandError"),f=a(()=>{if(l.aborted||r?.isCancellationRequested)throw new mP(u)},"assertNotCancelled"),p=a(v=>{if(this.registry.get(e.sessionId)!==v||this.registry.hasOrdinarySendPreparation(e.sessionId,v)||this.registry.hasCopilotCommandInvocation(e.sessionId,v)||this.eventRouter.hasActiveTurn(e.sessionId,v))throw d()},"assertTargetPreparationAllowed");f();let m=a(async v=>{try{return await v}catch(E){throw f(),E}},"awaitPreparation"),g=this.registry.get(e.sessionId);g&&p(g);let A=await m(BBe(this.ctx,e));f();let y=await m(this.getOrResumeSession(e.sessionId,{...g?{}:{shell:e.shell},sandbox:e.sandbox,systemHooks:e.systemHooks,model:e.model},A,!1,p));return f(),p(y),await this.copilotCommandCoordinator.invokeDirect({sessionId:e.sessionId,message:e.message,copilotCommandInvocationId:c,session:y,sandboxEnabled:e.sandbox?.enabled,permissionMode:e.permissionMode,references:e.references,prepareAgentPromptTurn:a(()=>this.prepareCopilotCommandAgentPromptTurn(y,e),"prepareAgentPromptTurn"),token:r,stopSignal:l}),{}}))}let n=await BBe(this.ctx,e),o={...this.registry.has(e.sessionId)?{}:{shell:e.shell},sandbox:e.sandbox,systemHooks:e.systemHooks,model:e.model,ensembleTier:e.ensembleTier},s=await this.getOrResumeSession(e.sessionId,o,n,!0);try{return await this.sendPreparedMessage(e,s,n,r)}finally{this.registry.endOrdinarySendPreparation(e.sessionId,s,e.model?.trim()==="ensemble")}}async prepareCopilotCommandAgentPromptTurn(e,r){await m_r(e,r),r.chatMode!==void 0&&(r.chatMode!=="agent"&&!Ire(r.chatMode)&&await e.reloadCustomAgents(),await this.applyChatModeOverride(r.sessionId,e,r)),(r.chatMode!==void 0||r.agentMode!==void 0)&&(await this.applyChatModeSelection(e,r),await this.applyAgentModeOverride(e,r))}async sendPreparedMessage(e,r,n,o){let s=e.permissionMode??"default";if(await this.permissionModeController.synchronizeForSend(e.sessionId,r,s),e.chatMode&&e.chatMode!=="agent"&&!Ire(e.chatMode)&&await r.reloadCustomAgents(),await m_r(r,e),await this.applyChatModeOverride(e.sessionId,r,e),!await this.sandboxConfigSync.alignSession(e.sessionId,r,"localSend",e.sandbox?.enabled))throw new Error(`Session changed while applying sandbox configuration: ${e.sessionId}`);e.sandbox&&this.sandboxConfigSync.reportSelection(e.sandbox.enabled);let c=e.message;await this.expandPromptTemplate(e.sessionId,e,e.chatMode),await this.applyChatModeSelection(r,e);let l={prompt:e.message,displayPrompt:c,...e.sendMode?{mode:e.sendMode}:{}};await this.applyAgentModeOverride(r,e);let u=e.chatMode==="inline-ask"||e.chatMode==="inline";if(e.references?.length&&!u){let E=await Flt(e.references,this.ctx);if(this.registry.get(e.sessionId)!==r)throw new Error(`Session changed while preparing attachments: ${e.sessionId}. Retry the message in the current session.`);E.length>0&&(l.attachments=E)}if(u){let E=this.registry.getConfinedFile(e.sessionId);if(E){let _=e.references?.find(T=>T.type==="file"&&T.uri===E),S=await Jii(E,_,this.ctx);if(S.promptFragment&&(l.prompt=`${l.prompt}${S.promptFragment}`),S.isLargeFile){let T=e.chatMode==="inline-ask"?Sht:NAr;await r.updateOptions({availableTools:[...T,"view"]})}}}this.registry.getTurnLimiter(e.sessionId)?.reset();let d=performance.now(),f=this.registry.incrementTurnIndex(e.sessionId),p=e.model?.trim()!=="ensemble"?void 0:n.ensembleTier==="hydrafusion"?"high":n.ensembleTier==="hydrafusion-max"?"max":n.target.model===qP&&n.autoTier==="balance"?"balance":void 0,m=this.turnDriver.wireAndSend(e.sessionId,r,l,f,o,n.target.provider!==void 0,{origin:"ordinary",ensembleTelemetryTier:p}),g=this.registry.getChatMode(e.sessionId)??"agent",A={requestSource:aN,chatMode:g,uiKind:Tre(g),sessionId:e.sessionId,safeModelId:Kha(e.model,e.modelProvider),providerName:e.modelProvider??"",reasoningEffort:e.reasoningEffort??"",contextTier:e.contextTier??"",permissionMode:s,hasReferences:String((e.references?.length??0)>0),turnIndex:String(f)},y={totalTimeMs:performance.now()-d,messageCharLen:e.message.length,referenceCount:e.references?.length??0};return uu(this.ctx,"backgroundAgent.send",A,y),{messageId:await m}}async truncateHistory(e){let r=performance.now(),o=await(await this.getOrResumeCurrentSession(e.sessionId)).history.truncate({eventId:e.eventId});return uu(this.ctx,"backgroundAgent.truncateHistory",{requestSource:aN,providerName:e.providerName,sessionId:e.sessionId,eventId:e.eventId},{totalTimeMs:performance.now()-r,eventsRemoved:o.eventsRemoved}),{eventId:e.eventId,eventsRemoved:o.eventsRemoved}}async previewRewind(e){let r=performance.now(),n="error",o=0;try{let c=await(await this.getOrResumeCurrentSession(e.sessionId)).history.previewRewind({eventId:e.eventId});return n=c.available?"available":c.reason??"unavailable",o=c.fileCount,c}finally{Jt(this.ctx,"backgroundAgent.previewRewind",{requestSource:aN,providerName:e.providerName,status_text:n},{totalTimeMs:performance.now()-r,fileCount:o})}}async rewindHistory(e){let r=performance.now(),n="error",o=0,s=0,c=0;try{let u=await(await this.getOrResumeCurrentSession(e.sessionId)).history.rewind({eventId:e.eventId,mode:e.mode});return n=u.outcome,o=u.eventsRemoved??0,s=u.restoredFiles.length,c=u.skippedFiles.length,u}finally{Jt(this.ctx,"backgroundAgent.rewindHistory",{requestSource:aN,providerName:e.providerName,status_text:n},{totalTimeMs:performance.now()-r,eventsRemoved:o,restoredFileCount:s,skippedFileCount:c})}}async forkSession(e){let r=performance.now(),o=await(await this.ensureManager()).forkSession(e.sessionId,{toEventId:e.toEventId,name:e.name});return uu(this.ctx,"backgroundAgent.fork",{requestSource:aN,providerName:e.providerName},{totalTimeMs:performance.now()-r}),{sessionId:o.sessionId}}applyChatModeOverride(e,r,n){return h_r(this.ctx,e,r,n,this.registry)}applyAgentModeOverride(e,r){return Rfi(e,r)}expandPromptTemplate(e,r,n){return Dfi(this.ctx,e,r,this.registry,()=>this.ctx.get(zf).isSkillsEnabled(),n)}async destroySession(e){try{return await this.registry.withSessionAdmission(e.sessionId,()=>this.ensureManager(),async r=>(this.pendingExternalToolDefs.delete(e.sessionId),await this.registry.remove(e.sessionId,()=>r.deleteSession(e.sessionId)),{success:!0}))}catch(r){return Al.error(this.ctx,`Failed to destroy session ${e.sessionId}:`,r),{success:!1}}}async stopSession(e){let r=performance.now(),n=await this.registry.runCopilotCommandStop(e,async()=>{let o=await this.getOrResumeCurrentSession(e),s=this.registry.hasConfinedFile(e)?this.eventRouter.currentLocalTurn(e,o):void 0;return Al.info(this.ctx,"Stopping session via abort:",e),await o.abortManualCompaction()&&Al.info(this.ctx,"Aborted in-progress manual compaction:",e),await o.clearPendingItems(),await o.abort(),{success:!0,...(s?await this.eventRouter.recoverUnstartedTurn(s):!1)?{recoveredUnstartedTurn:!0}:{}}});return uu(this.ctx,"backgroundAgent.stop",{requestSource:aN,sessionId:e},{totalTimeMs:performance.now()-r}),n}async compactHistory(e){let r=performance.now(),n=await this.getOrResumeCurrentSession(e);Al.info(this.ctx,"Compacting history for session:",e);let o=await n.compactHistory();return uu(this.ctx,"backgroundAgent.compactHistory",{requestSource:aN,sessionId:e},{totalTimeMs:performance.now()-r,tokensRemoved:o.tokensRemoved,messagesRemoved:o.messagesRemoved}),{success:o.success,tokensRemoved:o.tokensRemoved,messagesRemoved:o.messagesRemoved,summaryContent:o.summaryContent,contextWindow:o.contextWindow}}async stopCompactHistory(e){let r=performance.now(),n=await this.getOrResumeCurrentSession(e);Al.info(this.ctx,"Aborting manual compaction for session:",e);let o=await n.abortManualCompaction();return uu(this.ctx,"backgroundAgent.stopCompactHistory",{requestSource:aN,sessionId:e,aborted:String(o)},{totalTimeMs:performance.now()-r}),{aborted:o}}async getPlanPath(e){return await(await this.getOrResumeCurrentSession(e)).getPlanPath()}async resumeSession(e){let r=performance.now();Al.info(this.ctx,"resumeSession called:",e.sessionId);let n=await BBe(this.ctx,e),o=await this.getOrResumeSession(e.sessionId,e,n);this.registry.invalidateCommandCatalog(e.sessionId,o),e.sandbox&&this.sandboxConfigSync.reportSelection(e.sandbox.enabled);let s=Array.from(o.getEvents()),c=await o.isProcessing();Eht(this.ctx,this.notificationSender,e.sessionId,o),uu(this.ctx,"backgroundAgent.resume",{requestSource:aN,reasoningEffort:e.reasoningEffort??"",sessionId:e.sessionId,...e.shell?.initScripts?.length&&{shell_options_applied:"true"}},{totalTimeMs:performance.now()-r});let l=s.filter(u=>!Vha.has(u.type));return{sessionId:e.sessionId,workspacePath:o.workspacePath,events:l,...c===void 0?{}:{status:c.processing?"in_progress":"idle"}}}async commandCompletions(e,r,n){return Olt(async()=>{let o=r===void 0?void 0:this.registry.get(r);if(r!==void 0&&!o)return{items:[]};let s=o&&r!==void 0?await this.readSessionCompletionCatalog(r,o):await this.managerLifecycle.readCommandCatalog(await this.leaseCompletionCatalog());if(!s.isCurrent())throw new Ed("stale");let c=!!(o&&r!==void 0&&(this.eventRouter.hasActiveTurn(r,o)||this.registry.hasCopilotCommandInvocation(r,o)));return{items:Llt(this.copilotCommandPolicy.filterCompletions(s.catalog).commands,e,c)}},n)}async readSessionCompletionCatalog(e,r){let n=this.registry.getCommandCatalog(e,r);if(!n)throw new Ed("stale");let o=n.revision,s=await n.read(()=>r.commands.list({includeBuiltins:!0,includeSkills:!0,includeClientCommands:!1})),c=a(()=>this.registry.getCommandCatalog(e,r)===n&&n.revision===o,"isCurrent");if(!c())throw new Ed("stale");return{catalog:s,isCurrent:c}}async leaseCompletionCatalog(){let e;try{e=await this.ensureManager()}catch{throw new Ed("unavailable")}return this.authSequencer.queue(()=>Promise.resolve(this.managerLifecycle.commandCatalogLease(e)))}async listCommands(e){let r=e.sessionId?await this.listSessionCommands(e.sessionId):await(await this.ensureManager()).listCommands();return this.copilotCommandPolicy.filter(r)}async listSessionCommands(e){return(await this.getOrResumeCurrentSession(e)).commands.list({includeBuiltins:!0,includeSkills:!1,includeClientCommands:!1})}async listSessions(e){let o=(await(await this.ensureManager()).listSessions()).filter(s=>!this.structuredReviewCoordinator.ownsSession(s.sessionId));return e&&(o=o.filter(s=>!(e.cwd&&(!s.context?.cwd||!Kfi(s.context.cwd,e.cwd))||e.gitRoot&&(!s.context?.gitRoot||!Kfi(s.context.gitRoot,e.gitRoot))||e.repository&&s.context?.repository!==e.repository||e.branch&&s.context?.branch!==e.branch))),{sessions:o.map(s=>({sessionId:s.sessionId,startTime:s.startTime instanceof Date?s.startTime.toISOString():String(s.startTime),modifiedTime:s.modifiedTime instanceof Date?s.modifiedTime.toISOString():String(s.modifiedTime),summary:s.summary,isRemote:s.isRemote,context:s.context}))}}async listCLIModels(e){Al.info(this.ctx,"listCLIModels called",{forceRefresh:e});let r=performance.now();try{let n=await this.ctx.get($t).getUserToken(),o=await this.ctx.get(va).getMetadata(e),s=Kgt(this.ctx,o.filter(Yfi),n);for(let p of s)p.id===av&&(p.capabilities.supports.autoTiers=g_r);let l=(await H6(this.ctx,n)).enabled?await jAr(this.ctx,e):void 0,u=Ct(this.ctx,Ue.EnableEnsemble)===!0?l?.candidate:void 0,d=u&&l?Hii(l.serviceMessages,u):void 0,f=$ii(s,u,Zl,d);return Al.info(this.ctx,"listCLIModels succeeded",{modelCount:f.length}),uu(this.ctx,"backgroundAgent.listCLIModels",{status_text:"success"},{duration_ms:performance.now()-r,model_count:f.length}),f}catch(n){let o=Mlt(n);throw Al.error(this.ctx,"listCLIModels failed",{error:n instanceof Error?n.message:String(n),cause:o,stack:n instanceof Error?n.stack:void 0}),Jp(this.ctx,"backgroundAgent.listCLIModels",n,{status_text:"failure",...o?{errorCause:o}:{}},{duration_ms:performance.now()-r}),new Error("Failed to retrieve models",{cause:n})}}async listModels(e){Al.info(this.ctx,"listModels called",{forceRefresh:e}),await this.ensureManager();let r=performance.now();try{let o=(await this.ctx.get(va).getMetadata(e)).filter(Yfi).map($me);o.length===0?Al.warn(this.ctx,"No models available. Check authentication and Copilot subscription status."):Al.info(this.ctx,`Successfully retrieved ${o.length} models`);let s=[];this.ctx.get(hu).getPolicyValue("autoModel.enabled")!==!1&&s.push(this.buildAutoModelEntry());let c=[...s,...o];return Al.debug(this.ctx,"Models retrieved:",c.map(l=>l.id)),uu(this.ctx,"backgroundAgent.listModels",{status_text:"success"},{duration_ms:performance.now()-r,model_count:c.length}),{models:c}}catch(n){let o=n instanceof Error?n.message:String(n),s=Mlt(n);throw Al.error(this.ctx,"listModels failed",{error:o,cause:s,stack:n instanceof Error?n.stack:void 0}),Jp(this.ctx,"backgroundAgent.listModels",n,{status_text:"failure",...s?{errorCause:s}:{}},{duration_ms:performance.now()-r}),new Error("Failed to retrieve models",{cause:n})}}buildAutoModelEntry(){return{id:this.sdk.AUTO_MODEL_ID,name:"Auto",preview:!1,capabilities:{family:this.sdk.AUTO_MODEL_ID,supports:{vision:!0},limits:{max_context_window_tokens:0}}}}async startLocalEnvironment(e,r){return Xgt(this.ctx,"start",r,async n=>{let o=this.localEnvironment.captureStartAdmission(),s=a(()=>{if(o(),this.localEnvironment.requiresRestart())throw new Ri("restartRequired");if(this.localEnvironmentClosed)throw new Ri("hostNotRunning")},"validateAdmission");s(),n.stage="authentication";let c=await this.authBinding.resolveIdentity();if(s(),!c.runtimeToken||c.enterpriseAuth)throw new Ri("authenticationRequired");return n.stage="runtime",await this.ensureManager(s,c.runtimeToken),n.stage="authentication",this.authSequencer.queue(async()=>{s();let l=await this.authBinding.resolveIdentity();if(s(),l.runtimeToken!==c.runtimeToken||l.enterpriseAuth)throw new Ri("authenticationRequired");let u=this.ctx.get(wr),d=AHe({editor:u.getEditorInfo(),plugin:u.getEditorPluginInfo()}),f=e??`Copilot on ${(0,Zfi.hostname)()}`,p=` - ${d.displayName}`;n.stage="start";let m=await this.localEnvironment.start(f.endsWith(p)?f:`${f}${p}`,s,n);return l.commit(),m})})}async handleLocalEnvironmentWorkspaceChange(e){try{await e.withdrawn,await this.authSequencer.queue(async()=>{if(e.validate(),this.localEnvironmentClosed)throw new Ri("hostNotRunning");let r=await this.authBinding.resolveIdentity();if(e.validate(),!r.runtimeToken||r.enterpriseAuth||this.managerLifecycle.requiresAuthRestart(r.enterpriseAuth,r.runtimeToken))throw new Ri("authenticationRequired");await this.localEnvironment.applyWorkspaceSwitch(e)})}catch{try{e.validate(),this.localEnvironment.cancelStart()}catch{}Al.warn(this.ctx,"Local environment workspace switch did not complete")}}stopLocalEnvironment(e){return Xgt(this.ctx,"stop",e,r=>(r.stage="stop",this.localEnvironment.stop(r)))}getLocalEnvironmentStatus(){return this.localEnvironment.getStatus()}async setLocalEnvironmentSessionPublished(e,r,n,o){return Xgt(this.ctx,r?"publish":"unpublish",o,async s=>{if(!r)return s.stage="unpublish",this.registry.cancelLocalEnvironmentPublicationPreparations(e),this.localEnvironment.setSessionPublished(e,void 0,!1);let c=this.registry.beginLocalEnvironmentPublicationPreparation(e);try{let l=this.localEnvironment.capturePublicationAdmission(),u=a(()=>{if(l(),this.localEnvironmentClosed)throw new Ri("hostNotRunning")},"validateHost"),d=a(()=>{if(u(),!c.isCurrent())throw new Ri("unsupportedSession")},"validateAdmission");return s.stage="resume",await this.registry.withSessionAdmission(e,()=>this.getOrResumeSession(e,{},void 0,!1,void 0,d),async f=>{let p=a(()=>{if(u(),this.registry.get(e)!==f||this.registry.hasConfinedFile(e)||this.registry.hasOrdinarySendPreparation(e,f)||n!==void 0&&n!=="agent"&&n!=="ask")throw new Ri("unsupportedSession")},"validateSession");d(),p(),s.stage="authentication";let m=await this.authBinding.resolveIdentity();if(d(),p(),!m.runtimeToken||m.enterpriseAuth||this.managerLifecycle.requiresAuthRestart(m.enterpriseAuth,m.runtimeToken))throw new Ri("authenticationRequired");if(n!==void 0){s.stage="mode";try{await h_r(this.ctx,e,f,{chatMode:n},this.registry)}finally{d(),p()}}let g=a(async()=>{p();let A=await this.authBinding.resolveIdentity();if(p(),A.runtimeToken!==m.runtimeToken||A.enterpriseAuth||this.managerLifecycle.requiresAuthRestart(A.enterpriseAuth,A.runtimeToken))throw new Ri("authenticationRequired");if(this.registry.getLocalEnvironmentMode(e,f)!==(n??"agent"))throw new Ri("unsupportedSession")},"validatePublication");return s.stage="authentication",await g(),s.stage="publish",this.localEnvironment.setSessionPublished(e,f,!0,g,()=>{d(),p(),c.dispose()})})}finally{c.dispose()}})}async enableRemote(e,r){let n=await this.getOrResumeSession(e,{sandbox:r});if(!await this.sandboxConfigSync.alignSession(e,n,"remoteEnable",r?.enabled))throw new Error(`Session changed while applying sandbox configuration: ${e}`);return r&&this.sandboxConfigSync.reportSelection(r.enabled),this.remoteController.enableForSession(e,n)}async disableRemote(e){let r=await this.getOrResumeCurrentSession(e);await this.remoteController.disableForSession(r)}getRemoteStatus(e){return this.remoteController.getStatus(e)}setAgentPermissionMode(e,r){return this.permissionModeController.setForLiveSession(e,r)}async setAutoTier(e,r){let n=performance.now(),o="failure";try{let s=this.registry.get(e);if(!s)throw new M0(`Failed to apply Auto tier ${r}: session ${e} is not active`,r,"set",e);let c=await this.registry.withSessionAdmission(e,()=>Promise.resolve(s),async l=>{if(this.assertLiveAutoTierSession(e,l,r),this.registry.hasEnsembleSendPreparation(e,l))throw new M0(`Cannot change Auto tier during a pending Fusion turn: ${e}`,r,"set",e);let u=this.registry.getProviderModel(e);if(!u?.model)throw new M0(`Auto tier '${r}' is only supported when the selected model is '${qP}'.`,r,"validate",e);let d={model:u.model,provider:u.provider};nyr(d,r,e);let f=await l.setAutoTier(l4e(r));return this.assertLiveAutoTierSession(e,l,r),Yha(f)});return o=c.status,c}catch(s){throw s instanceof M0?s:new M0(`Failed to apply Auto tier ${r} to session ${e}: ${ol(s)}`,r,"set",e)}finally{gi(this.ctx,"backgroundAgent.autoTierSelection",{status_text:o,autoTier:r},{duration_ms:performance.now()-n})}}assertLiveAutoTierSession(e,r,n){let o=this.registry.get(e);if(!o)throw new M0(`Failed to apply Auto tier ${n}: session ${e} is not active`,n,"set",e);if(o!==r)throw new M0(`Failed to apply Auto tier ${n}: session ${e} is no longer the active live session`,n,"set",e)}async shutdown(){this.localEnvironmentClosed=!0,this.localEnvironment.cancelStart(),this._mcpSync.dispose(),this.sandboxConfigSync.dispose(),this._localEnvironmentWorkspaceListener?.dispose(),this._localEnvironmentWorkspaceListener=void 0,this._commandPolicyListener?.dispose(),this._commandPolicyListener=void 0,this._skillsEnabledListener?.dispose(),this._skillsEnabledListener=void 0,this._organizationInstructionsListener?.dispose(),this._organizationInstructionsListener=void 0,await this.authSequencer.queue(async()=>{await this.clearUserScopedState(),DAr(),await this.managerLifecycle.dispose()})}forceStopRuntime(){return this.managerLifecycle.forceStop()}};function Kha(t,e){return e?"byok models":t??""}a(Kha,"safeModelId");h();var S_r=["default","assisted","allowAll"];h();h();var T_r=require("crypto"),bT=require("fs/promises"),ST=require("path");var Xfi=1,Jha=".registry",e0t=class{constructor(e){this.entries=new Map;this.ideDirectory=(0,ST.resolve)(e.ideDirectory),this.registryDirectory=(0,ST.join)(this.ideDirectory,Jha),this.ownerPid=e.ownerPid??process.pid,this.registryPath=(0,ST.join)(this.registryDirectory,`${this.ownerPid}-${e.instanceId??(0,T_r.randomUUID)()}.jsonl`),this.isProcessRunning=e.isProcessRunning??tma,this.removeFile=e.removeFile??(r=>(0,bT.rm)(r,{force:!0})),this.onError=e.onError}static{a(this,"IdeLockRegistry")}async reconcile(){let e={status:"success",trackedCount:0,staleCount:0,removedCount:0,failureCount:0},r;try{await(0,bT.mkdir)(this.registryDirectory,{recursive:!0,mode:448}),r=await(0,bT.readdir)(this.registryDirectory)}catch(o){return this.recordFailure(e,"Failed to enumerate IDE lock registries",o),e.status="failed",e}let n=new Map;for(let o of r.filter(s=>s.endsWith(".jsonl"))){let s=(0,ST.join)(this.registryDirectory,o);if(s===this.registryPath)continue;let c;try{c=await Zha(s)}catch(u){this.recordFailure(e,"Failed to read IDE lock registry",u);continue}if(e.trackedCount+=c.length,c.length===0){try{await this.removeFile(s)}catch(u){this.recordFailure(e,`Failed to remove empty IDE lock registry ${o}`,u)}continue}let l=[];for(let u of c){if(!ema(u.lockFileName)){l.push(u),this.recordFailure(e,"Ignored unsafe IDE lock registry entry",new Error("Unsafe lock name"));continue}if(this.ownerIsAlive(u.ownerPid,n)){l.push(u);continue}e.staleCount++;try{await this.removeFile((0,ST.join)(this.ideDirectory,u.lockFileName)),e.removedCount++}catch(d){l.push(u),this.recordFailure(e,"Failed to remove stale IDE lock",d)}}if(l.length!==c.length)try{await b_r(s,l,this.removeFile)}catch(u){this.recordFailure(e,"Failed to update IDE lock registry",u)}}return e.status=e.failureCount===0?"success":e.removedCount>0?"partial":"failed",e}async add(e){let r=this.toLockFileName(e),n={version:Xfi,ownerPid:this.ownerPid,lockFileName:r};this.entries.set(e,n);try{await b_r(this.registryPath,Array.from(this.entries.values()),this.removeFile)}catch(o){throw this.entries.delete(e),o}}async remove(e){let r=this.entries.get(e);if(r){this.entries.delete(e);try{await b_r(this.registryPath,Array.from(this.entries.values()),this.removeFile)}catch(n){throw this.entries.set(e,r),n}}}registryPathForTesting(){return this.registryPath}toLockFileName(e){let r=(0,ST.resolve)(e);if((0,ST.dirname)(r)!==this.ideDirectory||!r.endsWith(".lock"))throw new Error("IDE lock path is outside the IDE directory");return(0,ST.basename)(r)}ownerIsAlive(e,r){let n=r.get(e);if(n!==void 0)return n;let o=this.isProcessRunning(e);return r.set(e,o),o}recordFailure(e,r,n){e.failureCount++,this.onError?.(r,n)}};async function Zha(t){let e=await(0,bT.readFile)(t,"utf8");return e.trim().length===0?[]:e.split(/\r?\n/).filter(r=>r.length>0).map((r,n)=>{let o=JSON.parse(r);if(!Xha(o))throw new Error(`Invalid registry entry at line ${n+1}`);return o})}a(Zha,"readRegistry");async function b_r(t,e,r){if(e.length===0){await r(t);return}await(0,bT.mkdir)((0,ST.dirname)(t),{recursive:!0,mode:448});let n=`${t}.tmp-${(0,T_r.randomUUID)()}`;try{let o=`${e.map(s=>JSON.stringify(s)).join(`
|
|
3941
3941
|
`)}
|
|
3942
3942
|
`;await(0,bT.writeFile)(n,o,{encoding:"utf8",mode:384}),await(0,bT.rename)(n,t)}finally{await(0,bT.rm)(n,{force:!0}).catch(()=>{})}}a(b_r,"writeRegistry");function Xha(t){if(!t||typeof t!="object")return!1;let e=t;return e.version===Xfi&&Number.isInteger(e.ownerPid)&&e.ownerPid>0&&typeof e.lockFileName=="string"}a(Xha,"isRegistryEntry");function ema(t){return(0,ST.basename)(t)===t&&t.endsWith(".lock")}a(ema,"isSafeLockFileName");function tma(t){try{return process.kill(t,0),!0}catch(e){return e.code==="EPERM"}}a(tma,"isProcessRunning");h();h();var p4e=require("http2"),t0t=require("http2"),w_r=require("stream"),opi=he(require("crypto"),1);var yne=class extends Error{static{a(this,"RequestError")}constructor(t,e){super(t,e),this.name="RequestError"}},rma=a(t=>t instanceof yne?t:new yne(t.message,{cause:t}),"toRequestError"),nma=global.Request,f4e=class extends nma{static{a(this,"Request")}constructor(t,e){typeof t=="object"&&Mve in t&&(t=t[Mve]()),typeof e?.body?.getReader<"u"&&(e.duplex??="half"),super(t,e)}},ima=a(t=>{let e=[],r=t.rawHeaders;for(let n=0;n<r.length;n+=2){let{[n]:o,[n+1]:s}=r;o.charCodeAt(0)!==58&&e.push([o,s])}return new Headers(e)},"newHeadersFromIncoming"),rpi=Symbol("wrapBodyStream"),oma=a((t,e,r,n,o)=>{let s={method:t,headers:r,signal:o.signal};if(t==="TRACE"){s.method="GET";let c=new f4e(e,s);return Object.defineProperty(c,"method",{get(){return"TRACE"}}),c}if(!(t==="GET"||t==="HEAD"))if("rawBody"in n&&n.rawBody instanceof Buffer)s.body=new ReadableStream({start(c){c.enqueue(n.rawBody),c.close()}});else if(n[rpi]){let c;s.body=new ReadableStream({async pull(l){try{c||=w_r.Readable.toWeb(n).getReader();let{done:u,value:d}=await c.read();u?l.close():l.enqueue(d)}catch(u){l.error(u)}}})}else s.body=w_r.Readable.toWeb(n);return new f4e(e,s)},"newRequestFromIncoming"),Mve=Symbol("getRequestCache"),sma=Symbol("requestCache"),r0t=Symbol("incomingKey"),n0t=Symbol("urlKey"),ama=Symbol("headersKey"),Dve=Symbol("abortControllerKey"),cma=Symbol("getAbortController"),i0t={get method(){return this[r0t].method||"GET"},get url(){return this[n0t]},get headers(){return this[ama]||=ima(this[r0t])},[cma](){return this[Mve](),this[Dve]},[Mve](){return this[Dve]||=new AbortController,this[sma]||=oma(this.method,this[n0t],this.headers,this[r0t],this[Dve])}};["body","bodyUsed","cache","credentials","destination","integrity","mode","redirect","referrer","referrerPolicy","signal","keepalive"].forEach(t=>{Object.defineProperty(i0t,t,{get(){return this[Mve]()[t]}})});["arrayBuffer","blob","clone","formData","json","text"].forEach(t=>{Object.defineProperty(i0t,t,{value:a(function(){return this[Mve]()[t]()},"value")})});Object.setPrototypeOf(i0t,f4e.prototype);var lma=a((t,e)=>{let r=Object.create(i0t);r[r0t]=t;let n=t.url||"";if(n[0]!=="/"&&(n.startsWith("http://")||n.startsWith("https://"))){if(t instanceof t0t.Http2ServerRequest)throw new yne("Absolute URL for :path is not allowed in HTTP/2");try{let l=new URL(n);r[n0t]=l.href}catch(l){throw new yne("Invalid absolute URL",{cause:l})}return r}let o=(t instanceof t0t.Http2ServerRequest?t.authority:t.headers.host)||e;if(!o)throw new yne("Missing host header");let s;if(t instanceof t0t.Http2ServerRequest){if(s=t.scheme,!(s==="http"||s==="https"))throw new yne("Unsupported scheme")}else s=t.socket&&t.socket.encrypted?"https":"http";let c=new URL(`${s}://${o}${n}`);if(c.hostname.length!==o.length&&c.hostname!==o.replace(/:\d+$/,""))throw new yne("Invalid host header");return r[n0t]=c.href,r},"newRequest"),epi=Symbol("responseCache"),kve=Symbol("getResponseCache"),vne=Symbol("cache"),P_r=global.Response,h4e=class npi{static{a(this,"_Response")}#e;#t;[kve](){return delete this[vne],this[epi]||=new P_r(this.#e,this.#t)}constructor(e,r){let n;if(this.#e=e,r instanceof npi){let o=r[epi];if(o){this.#t=o,this[kve]();return}else this.#t=r.#t,n=new Headers(r.#t.headers)}else this.#t=r;(typeof e=="string"||typeof e?.getReader<"u"||e instanceof Blob||e instanceof Uint8Array)&&(this[vne]=[r?.status||200,e,n||r?.headers])}get headers(){let e=this[vne];return e?(e[2]instanceof Headers||(e[2]=new Headers(e[2]||{"content-type":"text/plain; charset=UTF-8"})),e[2]):this[kve]().headers}get status(){return this[vne]?.[0]??this[kve]().status}get ok(){let e=this.status;return e>=200&&e<300}};["body","bodyUsed","redirected","statusText","trailers","type","url"].forEach(t=>{Object.defineProperty(h4e.prototype,t,{get(){return this[kve]()[t]}})});["arrayBuffer","blob","clone","formData","json","text"].forEach(t=>{Object.defineProperty(h4e.prototype,t,{value:a(function(){return this[kve]()[t]()},"value")})});Object.setPrototypeOf(h4e,P_r);Object.setPrototypeOf(h4e.prototype,P_r.prototype);async function uma(t){return Promise.race([t,Promise.resolve().then(()=>Promise.resolve(void 0))])}a(uma,"readWithoutBlocking");function ipi(t,e,r){let n=a(l=>{t.cancel(l).catch(()=>{})},"cancel");return e.on("close",n),e.on("error",n),(r??t.read()).then(c,o),t.closed.finally(()=>{e.off("close",n),e.off("error",n)});function o(l){l&&e.destroy(l)}a(o,"handleStreamError");function s(){t.read().then(c,o)}a(s,"onDrain");function c({done:l,value:u}){try{if(l)e.end();else if(!e.write(u))e.once("drain",s);else return t.read().then(c,o)}catch(d){o(d)}}a(c,"flow")}a(ipi,"writeFromReadableStreamDefaultReader");function dma(t,e){if(t.locked)throw new TypeError("ReadableStream is locked.");return e.destroyed?void 0:ipi(t.getReader(),e)}a(dma,"writeFromReadableStream");var x_r=a(t=>{let e={};t instanceof Headers||(t=new Headers(t??void 0));let r=[];for(let[n,o]of t)n==="set-cookie"?r.push(o):e[n]=o;return r.length>0&&(e["set-cookie"]=r),e["content-type"]??="text/plain; charset=UTF-8",e},"buildOutgoingHttpHeaders"),fma="x-hono-already-sent";typeof global.crypto>"u"&&(global.crypto=opi.default);var k_r=Symbol("outgoingEnded"),tpi=Symbol("incomingDraining"),pma=500,hma=64*1024*1024,I_r=a(t=>{let e=t;if(t.destroyed||e[tpi])return;if(e[tpi]=!0,t instanceof p4e.Http2ServerRequest){try{t.stream?.close?.(p4e.constants.NGHTTP2_NO_ERROR)}catch{}return}let r=0,n=a(()=>{clearTimeout(s),t.off("data",c),t.off("end",n),t.off("error",n)},"cleanup"),o=a(()=>{n();let l=t.socket;l&&!l.destroyed&&l.destroySoon()},"forceClose"),s=setTimeout(o,pma);s.unref?.();let c=a(l=>{r+=l.length,r>hma&&o()},"onData");t.on("data",c),t.on("end",n),t.on("error",n),t.resume()},"drainIncoming"),mma=a(()=>new Response(null,{status:400}),"handleRequestError"),spi=a(t=>new Response(null,{status:t instanceof Error&&(t.name==="TimeoutError"||t.constructor.name==="TimeoutError")?504:500}),"handleFetchError"),R_r=a((t,e)=>{let r=t instanceof Error?t:new Error("unknown error",{cause:t});r.code==="ERR_STREAM_PREMATURE_CLOSE"?console.info("The user aborted a request."):(console.error(t),e.headersSent||e.writeHead(500,{"Content-Type":"text/plain"}),e.end(`Error: ${r.message}`),e.destroy(r))},"handleResponseError"),api=a(t=>{"flushHeaders"in t&&t.writable&&t.flushHeaders()},"flushHeaders"),cpi=a(async(t,e)=>{let[r,n,o]=t[vne],s=!1;if(!o)o={"content-type":"text/plain; charset=UTF-8"};else if(o instanceof Headers)s=o.has("content-length"),o=x_r(o);else if(Array.isArray(o)){let c=new Headers(o);s=c.has("content-length"),o=x_r(c)}else for(let c in o)if(c.length===14&&c.toLowerCase()==="content-length"){s=!0;break}s||(typeof n=="string"?o["Content-Length"]=Buffer.byteLength(n):n instanceof Uint8Array?o["Content-Length"]=n.byteLength:n instanceof Blob&&(o["Content-Length"]=n.size)),e.writeHead(r,o),typeof n=="string"||n instanceof Uint8Array?e.end(n):n instanceof Blob?e.end(new Uint8Array(await n.arrayBuffer())):(api(e),await dma(n,e)?.catch(c=>R_r(c,e))),e[k_r]?.()},"responseViaCache"),gma=a(t=>typeof t.then=="function","isPromise"),Ama=a(async(t,e,r={})=>{if(gma(t))if(r.errorHandler)try{t=await t}catch(o){let s=await r.errorHandler(o);if(!s)return;t=s}else t=await t.catch(spi);if(vne in t)return cpi(t,e);let n=x_r(t.headers);if(t.body){let o=t.body.getReader(),s=[],c=!1,l;if(n["transfer-encoding"]!=="chunked"){let u=2;for(let d=0;d<u;d++){l||=o.read();let f=await uma(l).catch(p=>{console.error(p),c=!0});if(!f){if(d===1){await new Promise(p=>setTimeout(p)),u=3;continue}break}if(l=void 0,f.value&&s.push(f.value),f.done){c=!0;break}}c&&!("content-length"in n)&&(n["content-length"]=s.reduce((d,f)=>d+f.length,0))}e.writeHead(t.status,n),s.forEach(u=>{e.write(u)}),c?e.end():(s.length===0&&api(e),await ipi(o,e,l))}else n[fma]||(e.writeHead(t.status,n),e.end());e[k_r]?.()},"responseViaResponseObject"),D_r=a((t,e={})=>{let r=e.autoCleanupIncoming??!0;return e.overrideGlobalObjects!==!1&&global.Request!==f4e&&(Object.defineProperty(global,"Request",{value:f4e}),Object.defineProperty(global,"Response",{value:h4e})),async(n,o)=>{let s,c;try{c=lma(n,e.hostname);let l=!r||n.method==="GET"||n.method==="HEAD";if(l||(n[rpi]=!0,n.on("end",()=>{l=!0}),n instanceof p4e.Http2ServerRequest&&(o[k_r]=()=>{l||setTimeout(()=>{l||setTimeout(()=>{I_r(n)})})}),o.on("finish",()=>{l||I_r(n)})),o.on("close",()=>{c[Dve]&&(n.errored?c[Dve].abort(n.errored.toString()):o.writableFinished||c[Dve].abort("Client connection prematurely closed.")),l||setTimeout(()=>{l||setTimeout(()=>{I_r(n)})})}),s=t(c,{incoming:n,outgoing:o}),vne in s)return cpi(s,o)}catch(l){if(s)return R_r(l,o);if(e.errorHandler){if(s=await e.errorHandler(c?l:rma(l)),!s)return}else c?s=spi(l):s=mma()}try{return await Ama(s,o,e)}catch(l){return R_r(l,o)}}},"getRequestListener");var lpi=class{static{a(this,"NodeStreamableHTTPServerTransport")}_webStandardTransport;_requestListener;_requestContext=new WeakMap;constructor(t={}){this._webStandardTransport=new mdi(t),this._requestListener=D_r(async e=>{let r=this._requestContext.get(e);return this._webStandardTransport.handleRequest(e,{authInfo:r?.authInfo,parsedBody:r?.parsedBody})},{overrideGlobalObjects:!1})}get sessionId(){return this._webStandardTransport.sessionId}set onclose(t){this._webStandardTransport.onclose=t}get onclose(){return this._webStandardTransport.onclose}set onerror(t){this._webStandardTransport.onerror=t}get onerror(){return this._webStandardTransport.onerror}set onmessage(t){this._webStandardTransport.onmessage=t}get onmessage(){return this._webStandardTransport.onmessage}async start(){return this._webStandardTransport.start()}async close(){return this._webStandardTransport.close()}async send(t,e){return this._webStandardTransport.send(t,e)}setSupportedProtocolVersions(t){this._webStandardTransport.setSupportedProtocolVersions(t)}setScopeChallengeResolver(t){this._webStandardTransport.setScopeChallengeResolver(t)}async handleRequest(t,e,r){let n=t.auth;await D_r(async o=>this._webStandardTransport.handleRequest(o,{authInfo:n,parsedBody:r}),{overrideGlobalObjects:!1})(t,e)}closeSSEStream(t){this._webStandardTransport.closeSSEStream(t)}closeStandaloneSSEStream(){this._webStandardTransport.closeStandaloneSSEStream()}};var OG=require("crypto"),TT=require("fs/promises"),mpi=require("http"),Nve=require("os"),NG=require("path"),Ove=he(fi());var upi=10*1024*1024,yma=3e4,vma=3e4,Ema=5*6e4,_ma=20,Cma=100,Sma=[50,250,1e3],bma=5e3,Tma="A connection for this session already exists",Ima=new Set(["get_diagnostics","get_selection","open_diff","close_diff","update_session_name"]),MG=new fe("IdeMcpBridge"),wma=new Ove.ProtocolRequestType("copilot/ide/getDiagnostics"),xma=new Ove.ProtocolRequestType("copilot/ide/getSelection"),Rma=new Ove.ProtocolRequestType("copilot/ide/openDiff"),Pma=new Ove.ProtocolRequestType("copilot/ide/closeDiff"),kma=new Ove.ProtocolRequestType("copilot/ide/updateSessionName"),lS=class{constructor(e,r={}){this.ctx=e;this.bridges=new Map;this.nextReferenceStateVersion=0;this.reconciliationTracked=!1;this.mutation=Promise.resolve();this.shuttingDown=!1;this.env=r.env??process.env,this.homeDirectory=r.homeDirectory??(0,Nve.homedir)(),this.osPlatform=r.platform??(0,Nve.platform)(),this.now=r.now??Date.now,this.socketBaseDirectory=r.socketBaseDirectory??(0,Nve.tmpdir)(),this.listenServer=r.listen??Fma,this.client=r.client??new M_r(e),this.telemetryOverride=r.telemetry,this.requestTimeoutMs=r.requestTimeoutMs??yma,this.sessionIdleTimeoutMs=r.sessionIdleTimeoutMs??Ema,this.maxRetainedIdleSessions=r.maxRetainedIdleSessions??_ma,this.sseBackpressureCheckIntervalMs=r.sseBackpressureCheckIntervalMs??Cma,this.isResponseSaturated=r.isResponseSaturated??(n=>n.writableNeedDrain||n.writableEnded||n.destroyed),this.notifyReferenceState=r.notifyReferenceState??(()=>Promise.resolve()),this.referenceStateRetryDelaysMs=r.referenceStateRetryDelaysMs??Sma,this.removeLockFile=r.removeLockFile??(n=>(0,TT.rm)(n,{force:!0})),this.lockRegistry=new e0t({ideDirectory:this.ideDirectory,ownerPid:r.processId,instanceId:r.registryInstanceId,isProcessRunning:r.isProcessRunning,onError:a((n,o)=>MG.warn(this.ctx,n,o),"onError")}),this.reconciliation=this.lockRegistry.reconcile()}static{a(this,"IdeMcpBridgeService")}register(e){return this.enqueue(async()=>{this.assertRunning();let r=this.bridges.get(e.bridgeId);return r?r.disposing?(await this.disposeBridge(r),this.bridges.delete(e.bridgeId),this.referenceStateSnapshot(await this.createBridge(e))):(r.metadata=dpi(e),await this.writeLock(r),this.trackLifecycle("updated",r),this.referenceStateSnapshot(r)):this.referenceStateSnapshot(await this.createBridge(e))})}update(e){return this.register(e)}unregister(e){return this.enqueue(async()=>{let r=this.bridges.get(e);r&&(r.disposing=!0,await this.disposeBridge(r),this.bridges.delete(e),this.trackLifecycle("unregistered",r))})}selectionChanged(e,r){let n=this.bridges.get(e);return n&&(n.latestSelection=r),this.broadcastSelection(e,r)}addFileReference(e,r,n){return this.sendAction(e,"add_file_reference",r,n)}addSelection(e,r,n){return this.sendAction(e,"add_selection",r,n)}shutdown(){return this.enqueue(async()=>{if(this.shuttingDown&&this.bridges.size===0)return;this.shuttingDown=!0;let e=Array.from(this.bridges.entries()),r=[];for(let[n,o]of e)try{o.disposing=!0,await this.disposeBridge(o),this.bridges.delete(n)}catch(s){r.push(s)}if(this.track("lifecycle",{operation:"shutdown"},{bridgeCount:e.length,failureCount:r.length}),r.length>0)throw new AggregateError(r,"Failed to dispose all IDE MCP bridges")})}enqueue(e){let r=this.mutation,n=this.reconciliation.then(o=>{this.reconciliationTracked||(this.reconciliationTracked=!0,this.track("reconcile",{status:o.status},{trackedCount:o.trackedCount,staleCount:o.staleCount,removedCount:o.removedCount,failureCount:o.failureCount}))}).then(()=>r).then(e);return this.mutation=n.then(()=>{},()=>{}),n}trackLifecycle(e,r){this.track("lifecycle",{operation:e,scheme:this.osPlatform==="win32"?"pipe":"unix",trusted:String(r.metadata.isTrusted)},{workspaceFolderCount:r.metadata.workspaceFolders.length,activeBridgeCount:this.bridges.size})}trackSession(e,r,n){this.track("session",{operation:e,scheme:this.osPlatform==="win32"?"pipe":"unix",...n?{reason:n}:{}},{activeSessionCount:r.sessionsByCopilotId.size})}referenceStateSnapshot(e){return{...e.referenceState}}updateReferenceState(e){let r=Array.from(e.sessionsByCopilotId.values()).filter(s=>this.hasAcceptingReferenceStream(s)).map(s=>s.copilotSessionId).sort();if(Dma(r,e.acceptingReferenceSessions))return;let n={canAcceptReferences:r.length>0,stateVersion:this.nextReferenceStateVersion++};e.acceptingReferenceSessions=r,e.referenceState=n;let o={bridgeId:e.metadata.bridgeId,...n};e.referenceStateSendTail=e.referenceStateSendTail.then(()=>this.sendReferenceStateWithRetry(e,o))}async sendReferenceStateWithRetry(e,r){let n=[0,...this.referenceStateRetryDelaysMs];for(let o=0;o<n.length;o++){let s=n[o];if(s>0&&await Lma(s),e.referenceState.stateVersion!==r.stateVersion)return;try{await this.notifyReferenceState(r);return}catch(c){o===n.length-1&&MG.warn(this.ctx,"Failed to notify the IDE about Copilot CLI reference availability",c)}}}hasAcceptingReferenceStream(e){let r=e.standaloneSseResponse;return!e.closing&&e.activeStandaloneSseStreams>0&&r!==void 0&&!e.standaloneSseClosing&&!this.isResponseSaturated(r)}track(e,r,n){try{this.telemetryOverride?this.telemetryOverride.track(e,r,n):vt(this.ctx,`copilot.ideBridge.${e}`,cr.createAndMarkAsIssued(r,n))}catch(o){MG.warn(this.ctx,`Failed to track IDE MCP bridge ${e} telemetry`,o)}}assertRunning(){if(this.shuttingDown)throw new Error("IDE MCP bridge service is shut down")}get ideDirectory(){let e=this.env.COPILOT_HOME;return(0,NG.join)(e&&e.length>0?e:(0,NG.join)(this.homeDirectory,".copilot"),"ide")}async createBridge(e){let r=(0,OG.randomUUID)(),n=this.ideDirectory,o=(0,NG.join)(n,`${r}.lock`),s=this.osPlatform==="win32"?void 0:(0,NG.join)(this.socketBaseDirectory,`.copilot-ide-${r.slice(0,12)}`),c=this.osPlatform==="win32"?`\\\\.\\pipe\\copilot-ide-${r}`:(0,NG.join)(s,"m.sock"),l=`Nonce ${(0,OG.randomBytes)(32).toString("hex")}`;await(0,TT.mkdir)(s??n,{recursive:!0,mode:448});let u={metadata:dpi(e),instanceId:r,nonce:l,socketPath:c,socketDirectory:s,lockPath:o,httpServer:(0,mpi.createServer)(),sockets:new Set,sessionsByCopilotId:new Map,sessionsByMcpId:new Map,acceptingReferenceSessions:[],referenceState:{canAcceptReferences:!1,stateVersion:this.nextReferenceStateVersion++},referenceStateSendTail:Promise.resolve(),disposing:!1,abortController:new AbortController};u.httpServer.on("request",(d,f)=>{this.handleHttpRequest(u,d,f)}),u.httpServer.on("connection",d=>{u.sockets.add(d),d.once("close",()=>u.sockets.delete(d))});try{return await this.listenServer(u.httpServer,c),await this.lockRegistry.add(o),await this.writeLock(u),this.bridges.set(e.bridgeId,u),this.trackLifecycle("registered",u),u}catch(d){throw await this.disposeBridge(u),d}}async writeLock(e){let r={socketPath:e.socketPath,scheme:this.osPlatform==="win32"?"pipe":"unix",headers:{Authorization:e.nonce},pid:e.metadata.ideProcessId,timestamp:this.now(),workspaceFolders:[...e.metadata.workspaceFolders],ideName:e.metadata.ideName,isTrusted:e.metadata.isTrusted};await(0,TT.mkdir)((0,NG.dirname)(e.lockPath),{recursive:!0,mode:448});let n=`${e.lockPath}.tmp-${(0,OG.randomUUID)()}`;try{await(0,TT.writeFile)(n,JSON.stringify(r),{encoding:"utf8",mode:384}),await(0,TT.rename)(n,e.lockPath)}finally{await(0,TT.rm)(n,{force:!0}).catch(()=>{})}}async handleHttpRequest(e,r,n){if(new URL(r.url??"/","http://localhost").pathname!=="/mcp"){n.writeHead(404).end();return}if(!Oma(r.headers.authorization,e.nonce)){n.writeHead(401,{"content-type":"text/plain"}).end("Unauthorized");return}try{if(r.method==="POST"){let o=this.findSession(e,r);if(o){this.cancelSessionIdleExpiry(o),o.activeNonStreamRequests++;try{let l=await hpi(r);await o.transport.handleRequest(r,n,l)}finally{o.activeNonStreamRequests=Math.max(0,o.activeNonStreamRequests-1),await this.handleSessionBecameIdle(e,o)}return}let s=await hpi(r);if(!!s&&typeof s=="object"&&!Array.isArray(s)&&s.method==="initialize"){await this.handleInitialize(e,r,n,s);return}n.writeHead(404,{"content-type":"text/plain"}).end("Session not found");return}if(r.method==="GET"||r.method==="DELETE"){let o=this.findSession(e,r);if(!o){n.writeHead(404,{"content-type":"text/plain"}).end("Session not found");return}if(r.method==="GET"){this.cancelSessionIdleExpiry(o);let s=Bma(n),c="establishing";o.establishingStandaloneSseStreams++,n.once("close",()=>{c!=="closed"&&(c==="establishing"?o.establishingStandaloneSseStreams=Math.max(0,o.establishingStandaloneSseStreams-1):c==="active"&&(o.activeStandaloneSseStreams=Math.max(0,o.activeStandaloneSseStreams-1)),o.standaloneSseResponse===n&&(this.clearSseBackpressureMonitor(o),o.standaloneSseResponse=void 0,o.standaloneSseClosing=!1),c="closed",this.updateReferenceState(e),this.enqueue(()=>this.handleSessionBecameIdle(e,o)).catch(d=>MG.warn(this.ctx,"Failed to retain idle IDE MCP session",d)))});let l=o.transport.handleRequest(r,n);if(await s&&c==="establishing"){if(o.establishingStandaloneSseStreams--,o.activeStandaloneSseStreams++,c="active",o.everHadStandaloneSse=!0,o.standaloneSseResponse=n,o.standaloneSseClosing=!1,this.startSseBackpressureMonitor(e,o,n),this.updateReferenceState(e),e.latestSelection)try{await o.mcpServer.notification({method:"selection_changed",params:e.latestSelection})}catch{MG.warn(this.ctx,"Failed to replay IDE selection after SSE connection")}}else c==="establishing"&&(o.establishingStandaloneSseStreams--,c="closed",await this.handleSessionBecameIdle(e,o));await l;return}try{await o.transport.handleRequest(r,n)}finally{await this.releaseSession(e,o,"delete")}return}n.writeHead(405,{Allow:"POST, GET, DELETE"}).end()}catch(o){if(n.headersSent)n.destroy(o instanceof Error?o:void 0);else{let s=o instanceof A4e?413:400;n.writeHead(s,{"content-type":"text/plain"}).end(Qma(o))}}}async handleInitialize(e,r,n,o){let s=ppi(r.headers["x-copilot-session-id"]);if(!s){n.writeHead(400,{"content-type":"text/plain"}).end("X-Copilot-Session-Id is required");return}let c=e.sessionsByCopilotId.get(s);if(c)if(c.activeStandaloneSseStreams===0&&c.establishingStandaloneSseStreams===0&&(c.everHadStandaloneSse||this.now()-c.createdAt>=vma))await this.releaseSession(e,c,"takeover");else{this.trackSession("duplicateRejected",e),n.writeHead(409,{"content-type":"text/plain"}).end(Tma);return}let l=this.createSession(e,s);e.sessionsByCopilotId.set(s,l);try{if(await l.mcpServer.connect(l.transport),await l.transport.handleRequest(r,n,o),l.mcpSessionId=l.transport.sessionId,!l.mcpSessionId)throw new Error("MCP initialize did not create a session");e.sessionsByMcpId.set(l.mcpSessionId,l),await this.handleSessionBecameIdle(e,l),this.trackSession("initialized",e)}catch(u){throw await this.releaseSession(e,l,"initializeFailed"),u}}createSession(e,r){let n=new GEr({name:"copilot-cli-jetbrains",version:"0.0.1",title:`${e.metadata.ideName} Copilot CLI`},{capabilities:{tools:{listChanged:!0}}}),o={copilotSessionId:r,mcpServer:n,transport:new lpi({sessionIdGenerator:OG.randomUUID}),closing:!1,createdAt:this.now(),establishingStandaloneSseStreams:0,activeStandaloneSseStreams:0,activeNonStreamRequests:0,everHadStandaloneSse:!1,standaloneSseClosing:!1,abortController:new AbortController};return n.setRequestHandler("tools/list",()=>({tools:[m4e("get_diagnostics","Get language diagnostics from the IDE.",{type:"object",properties:{uri:{type:"string"}},additionalProperties:!1}),m4e("get_selection","Get the current IDE selection.",{type:"object",properties:{},additionalProperties:!1}),m4e("open_diff","Open an IDE diff and wait for the user response.",{type:"object",properties:{original_file_path:{type:"string"},new_file_contents:{type:"string"},tab_name:{type:"string"}},required:["original_file_path","new_file_contents","tab_name"],additionalProperties:!1}),m4e("close_diff","Close an IDE diff.",{type:"object",properties:{tab_name:{type:"string"}},required:["tab_name"],additionalProperties:!1}),m4e("update_session_name","Update the IDE display name for the Copilot session.",{type:"object",properties:{name:{type:"string"}},required:["name"],additionalProperties:!1})]})),n.setRequestHandler("tools/call",async s=>{let c=s.params.arguments??{},l=this.now(),u=Mma(s.params.name);try{let d;switch(s.params.name){case"get_diagnostics":d=await this.forwardRequest(e,o,()=>this.client.getDiagnostics({bridgeId:e.metadata.bridgeId,...Nma(c,"uri")}),this.requestTimeoutMs);break;case"get_selection":d=await this.forwardRequest(e,o,()=>this.client.getSelection({bridgeId:e.metadata.bridgeId}),this.requestTimeoutMs);break;case"open_diff":d=await this.forwardRequest(e,o,()=>this.client.openDiff({bridgeId:e.metadata.bridgeId,original_file_path:g4e(c,"original_file_path"),new_file_contents:g4e(c,"new_file_contents"),tab_name:g4e(c,"tab_name")}));break;case"close_diff":d=await this.forwardRequest(e,o,()=>this.client.closeDiff({bridgeId:e.metadata.bridgeId,tab_name:g4e(c,"tab_name")}),this.requestTimeoutMs);break;case"update_session_name":d=await this.forwardRequest(e,o,()=>this.client.updateSessionName({bridgeId:e.metadata.bridgeId,name:g4e(c,"name")}),this.requestTimeoutMs);break;default:throw new Error(`Unknown tool: ${s.params.name}`)}return this.track("toolCall",{toolName:u,status:"success"},{durationMs:Math.max(0,this.now()-l)}),{content:[{type:"text",text:JSON.stringify(d??null)}]}}catch(d){throw this.track("toolCall",{toolName:u,status:"error"},{durationMs:Math.max(0,this.now()-l)}),d}}),o}forwardRequest(e,r,n,o){let s=[e.abortController.signal,r.abortController.signal];return s.some(c=>c.aborted)?Promise.reject(new Error("IDE session was released")):new Promise((c,l)=>{let u=!1,d=a(m=>{u||(u=!0,p&&clearTimeout(p),s.forEach(g=>g.removeEventListener("abort",f)),m())},"finish"),f=a(()=>d(()=>l(new Error("IDE session was released"))),"onAbort"),p=o===void 0?void 0:setTimeout(()=>d(()=>l(new Error(`IDE request timed out after ${o} ms`))),o);p?.unref(),s.forEach(m=>m.addEventListener("abort",f,{once:!0}));try{n().then(m=>d(()=>c(m)),m=>d(()=>l(fpi(m))))}catch(m){d(()=>l(fpi(m)))}})}findSession(e,r){let n=ppi(r.headers["mcp-session-id"]);return n?e.sessionsByMcpId.get(n):void 0}async broadcastSelection(e,r){let n=this.bridges.get(e);n&&await Promise.allSettled(Array.from(n.sessionsByCopilotId.values()).filter(o=>this.canAcceptNotification(n,o)).map(o=>o.mcpServer.notification({method:"selection_changed",params:r})))}async sendAction(e,r,n,o){let s=this.bridges.get(e);if(o!==void 0&&(!s||s.referenceState.stateVersion!==o||!s.referenceState.canAcceptReferences)){this.trackDroppedAction(s,r,n,1);return}let c=s?Array.from(s.sessionsByCopilotId.values()):[],l=s?c.filter(f=>this.canAcceptNotification(s,f)):[],u=c.length-l.length;if(o!==void 0&&(!s||s.referenceState.stateVersion!==o)){this.trackDroppedAction(s,r,n,Math.max(1,u));return}(u>0||l.length===0)&&this.trackDroppedAction(s,r,n,Math.max(1,u)),!(l.length===0||(await Promise.allSettled(l.map(f=>f.mcpServer.notification({method:r,params:n})))).some(f=>f.status==="fulfilled"))&&this.trackDroppedAction(s,r,n,l.length)}trackDroppedAction(e,r,n,o){MG.warn(this.ctx,"Dropped IDE action for a Copilot CLI session without an accepting SSE stream"),this.track("session",{operation:"notificationDropped",scheme:this.osPlatform==="win32"?"pipe":"unix",reason:"streamDisconnected"},{activeSessionCount:e?.sessionsByCopilotId.size??0,droppedNotificationCount:o,droppedNotificationBytes:Buffer.byteLength(JSON.stringify({method:r,params:n}),"utf8")*o})}canAcceptNotification(e,r){let n=r.standaloneSseResponse;return r.activeStandaloneSseStreams===0||!n||r.standaloneSseClosing?!1:this.isResponseSaturated(n)?(this.closeSaturatedSseStream(e,r,n),!1):!0}closeSaturatedSseStream(e,r,n){r.standaloneSseClosing||r.standaloneSseResponse!==n||(r.standaloneSseClosing=!0,this.clearSseBackpressureMonitor(r),this.updateReferenceState(e),MG.warn(this.ctx,"Closing saturated Copilot CLI SSE stream"),this.trackSession("streamClosed",e,"backpressure"),r.transport.closeStandaloneSSEStream(),n.destroy())}startSseBackpressureMonitor(e,r,n){this.clearSseBackpressureMonitor(r);let o=setInterval(()=>{if(r.standaloneSseResponse!==n||r.standaloneSseClosing||r.closing){this.clearSseBackpressureMonitor(r);return}this.isResponseSaturated(n)&&this.closeSaturatedSseStream(e,r,n)},this.sseBackpressureCheckIntervalMs);o.unref(),r.backpressureMonitor=o}clearSseBackpressureMonitor(e){e.backpressureMonitor&&clearInterval(e.backpressureMonitor),e.backpressureMonitor=void 0}cancelSessionIdleExpiry(e){e.idleExpiry&&clearTimeout(e.idleExpiry),e.idleExpiry=void 0,e.idleSince=void 0}scheduleSessionIdleExpiryIfIdle(e,r){if(!this.isSessionIdle(e,r))return;this.cancelSessionIdleExpiry(r),r.idleSince=this.now();let n=setTimeout(()=>{this.enqueue(async()=>{r.idleExpiry!==n||r.closing||r.activeStandaloneSseStreams>0||r.establishingStandaloneSseStreams>0||r.activeNonStreamRequests>0||e.sessionsByCopilotId.get(r.copilotSessionId)!==r||await this.releaseSession(e,r,"idleTimeout")}).catch(o=>MG.warn(this.ctx,"Failed to expire idle IDE MCP session",o))},this.sessionIdleTimeoutMs);n.unref(),r.idleExpiry=n}async handleSessionBecameIdle(e,r){this.scheduleSessionIdleExpiryIfIdle(e,r),await this.enforceRetainedSessionLimit(e)}async enforceRetainedSessionLimit(e){let r=Array.from(e.sessionsByCopilotId.values()).filter(n=>this.isSessionIdle(e,n)&&n.idleSince!==void 0).sort((n,o)=>n.idleSince-o.idleSince);for(let n of r){if(Array.from(e.sessionsByCopilotId.values()).filter(s=>this.isSessionIdle(e,s)&&s.idleSince!==void 0).length<=this.maxRetainedIdleSessions)return;!this.isSessionIdle(e,n)||n.idleSince===void 0||await this.releaseSession(e,n,"capacity")}}isSessionIdle(e,r){return!r.closing&&r.activeStandaloneSseStreams===0&&r.establishingStandaloneSseStreams===0&&r.activeNonStreamRequests===0&&e.sessionsByCopilotId.get(r.copilotSessionId)===r}async releaseSession(e,r,n){r.closing||(r.closing=!0,this.cancelSessionIdleExpiry(r),this.clearSseBackpressureMonitor(r),r.standaloneSseResponse=void 0,r.standaloneSseClosing=!0,r.abortController.abort(),e.sessionsByCopilotId.delete(r.copilotSessionId),r.mcpSessionId&&e.sessionsByMcpId.delete(r.mcpSessionId),this.updateReferenceState(e),await r.mcpServer.close().catch(()=>{}),await r.transport.close().catch(()=>{}),this.trackSession("released",e,n))}async disposeBridge(e){e.abortController.abort(),await Promise.allSettled(Array.from(e.sessionsByCopilotId.values()).map(r=>this.releaseSession(e,r,"bridgeDispose"))),await e.referenceStateSendTail,e.sockets.forEach(r=>r.destroy()),await Uma(e.httpServer),await this.removeLockFile(e.lockPath),this.osPlatform!=="win32"&&(await(0,TT.rm)(e.socketPath,{force:!0}).catch(()=>{}),e.socketDirectory&&await(0,TT.rm)(e.socketDirectory,{recursive:!0,force:!0}).catch(()=>{})),await this.lockRegistry.remove(e.lockPath)}async readLockForTesting(e){let r=this.bridges.get(e);if(r)return JSON.parse(await(0,TT.readFile)(r.lockPath,"utf8"))}lockPathForTesting(e){return this.bridges.get(e)?.lockPath}registryPathForTesting(){return this.lockRegistry.registryPathForTesting()}},M_r=class{constructor(e){this.ctx=e}static{a(this,"DefaultIdeMcpBridgeClient")}getDiagnostics(e){return this.ctx.get(I0).sendRequest(wma,e)}getSelection(e){return this.ctx.get(I0).sendRequest(xma,e)}openDiff(e){return this.ctx.get(I0).sendRequest(Rma,e)}closeDiff(e){return this.ctx.get(I0).sendRequest(Pma,e)}updateSessionName(e){return this.ctx.get(I0).sendRequest(kma,e)}};function dpi(t){return{...t,workspaceFolders:[...t.workspaceFolders]}}a(dpi,"copyMetadata");function Dma(t,e){return t.length===e.length&&t.every((r,n)=>r===e[n])}a(Dma,"arraysEqual");function m4e(t,e,r){return{name:t,description:e,inputSchema:r,execution:{taskSupport:"forbidden"}}}a(m4e,"tool");function Mma(t){return Ima.has(t)?t:"unknown"}a(Mma,"telemetryToolName");function fpi(t){return t instanceof Error?t:new Error(String(t))}a(fpi,"asError");function g4e(t,e){let r=t[e];if(typeof r!="string")throw new Error(`${e} must be a string`);return r}a(g4e,"requiredString");function Nma(t,e){let r=t[e];if(r===void 0)return{};if(typeof r!="string")throw new Error(`${e} must be a string`);return{uri:r}}a(Nma,"optionalString");function ppi(t){return typeof t=="string"&&t.length>0?t:void 0}a(ppi,"singleHeader");function Oma(t,e){if(t===void 0)return!1;let r=Buffer.from(t),n=Buffer.from(e);return r.length===n.length&&(0,OG.timingSafeEqual)(r,n)}a(Oma,"matchesNonce");function Lma(t){return new Promise(e=>{setTimeout(e,t).unref()})}a(Lma,"wait");function Bma(t){return t.headersSent?Promise.resolve(!0):new Promise(e=>{let r=!1,n=a(u=>{r||(r=!0,clearInterval(c),clearTimeout(l),t.off("pipe",o),t.off("close",s),e(u))},"finish"),o=a(()=>n(!0),"onPipe"),s=a(()=>n(!1),"onClose"),c=setInterval(()=>{t.headersSent&&n(!0)},5),l=setTimeout(()=>n(!1),bma);c.unref(),l.unref(),t.once("pipe",o),t.once("close",s)})}a(Bma,"waitForResponseStart");function Fma(t,e){return new Promise((r,n)=>{let o=a(c=>{t.off("listening",s),n(c)},"onError"),s=a(()=>{t.off("error",o),r()},"onListening");t.once("error",o),t.once("listening",s),t.listen(e)})}a(Fma,"listen");function Uma(t){return t.listening?new Promise(e=>t.close(()=>e())):Promise.resolve()}a(Uma,"closeServer");var A4e=class extends Error{static{a(this,"RequestBodyTooLargeError")}};async function hpi(t){let e=Number(t.headers["content-length"]);if(Number.isFinite(e)&&e>upi)throw new A4e("Request body too large");let r=[],n=0;for await(let o of t){let s=Buffer.isBuffer(o)?o:Buffer.from(o);if(n+=s.length,n>upi)throw new A4e("Request body too large");r.push(s)}if(r.length!==0)return JSON.parse(Buffer.concat(r).toString("utf8"))}a(hpi,"readJsonBody");function Qma(t){return t instanceof Error?t.message:"Bad request"}a(Qma,"errorMessage");h();h();async function _m(t,e,r){let n=performance.now(),o={properties:{},measurements:{}};try{let s=await r(o);return gpi(t,e,n,o),s}catch(s){throw o.error??=s,gpi(t,e,n,o),s}}a(_m,"runWithTelemetry");function gpi(t,e,r,n){let s={success:n.error?"false":n.ok??!0?"true":"false",...n.properties},c={totalTimeMs:performance.now()-r,...n.measurements};n.error!==void 0?Jp(t,`${e}.failure`,n.error,s,c):gi(t,e,s,c)}a(gpi,"flushTelemetry");h();var ypi=he(require("path"));h();var N_r=["default","acceptEdits","bypassPermissions","plan","auto"],qma=["acceptEdits","bypassPermissions","auto"];function Api(t,e,r){let n=t??e;return r&&(n===void 0||qma.some(o=>o===n))?"default":t}a(Api,"resolveClaudePermissionMode");function Ene(t,e){if(e!=="CLAUDE")throw new Error(`ClaudeCodeAgentService.${t}: expected agentProvider='CLAUDE', got '${String(e)}'`)}a(Ene,"assertClaudeProvider");function Lve(t,e,r){if(typeof r!="string"||r.length===0)throw new Error(`${t}: ${e} is required`)}a(Lve,"assertNonEmptyString");function jma(t,e,r){if(r===void 0)throw new Error(`${t}: ${e} is required`);try{Jn(r)}catch(n){throw new Error(`${t}: ${e} is not a valid URI: ${r}`,{cause:n})}}a(jma,"assertFsUri");function Hma(t,e,r){if(!ypi.isAbsolute(r))throw new Error(`${t}: ${e} must be an absolute path, got '${r}'`)}a(Hma,"assertAbsolutePath");function $ma(t,e){if(e!==void 0&&!N_r.includes(e))throw new Error(`${t}: agentMode must be one of ${N_r.join(", ")}, got '${e}'`)}a($ma,"assertAllowedAgentMode");async function y4e(t,e){if(e===void 0)return;let n=(await t.get(va).getMetadata()).find(o=>o.id===e);if(!n)throw new Error(`Unknown model id: ${e}`);if(!QJe(n.capabilities.family))throw new Error(`Model ${e} is not a Claude model (family: ${n.capabilities.family})`)}a(y4e,"validateClaudeModel");async function vpi(t,e){Ene("createSession",e.agentProvider),jma("createSession","workspaceFolder.uri",e.workspaceFolder?.uri),await y4e(t,e.model)}a(vpi,"validateAgentCreate");async function Epi(t,e){Ene("resumeSession",e.agentProvider),Lve("resumeSession","sessionId",e.sessionId),await y4e(t,e.model)}a(Epi,"validateAgentResume");async function _pi(t,e){Ene("sendMessage",e.agentProvider),Lve("sendMessage","sessionId",e.sessionId),Lve("sendMessage","message",e.message),$ma("sendMessage",e.agentMode),await y4e(t,e.model)}a(_pi,"validateAgentSend");function Cpi(t,e){Ene("stopSession",e.agentProvider),Lve("stopSession","sessionId",e.sessionId)}a(Cpi,"validateAgentStop");function Spi(t,e){Ene("destroySession",e.agentProvider),Lve("destroySession","sessionId",e.sessionId)}a(Spi,"validateAgentDestroy");function bpi(t,e){Ene("listSessions",e.agentProvider),Lve("listSessions","cwd",e.cwd),Hma("listSessions","cwd",e.cwd)}a(bpi,"validateAgentListSessions");function Tpi(t,e){Ene("listModels",e.agentProvider)}a(Tpi,"validateAgentListModels");h();h();h();var o0t=zd({id:"thirdPartyAgentHarness.allowed",displayName:"Third-party agent harnesses",schema:b.Boolean(),exposeToEditor:!0,inputs:{management:{source:"managed",evaluate:a(t=>{if(t===void 0)return!0;if(typeof t!="object"||t===null||Array.isArray(t))throw new TypeError("Invalid managed settings")},"evaluate")},policy:{source:"policy",key:"thirdPartyAgentHarness.allowWithManagedSettings",evaluate:a(t=>{if(t!==void 0&&typeof t!="boolean")throw new TypeError("Invalid third-party agent harness override");return t===!0},"evaluate")}},strategy:"managed-precedence"});var O_r=class extends ju{static{a(this,"AgentProviderDisabledError")}constructor(e){super(`${e} is disabled by enterprise managed settings.`,{kind:"agentProviderDisabled",provider:e}),this.name="AgentProviderDisabledError"}};function Cm(t,e){if(e!=="CLAUDE"&&e!=="CODEX")return;let r=t.get(hd).get(o0t);if(!(r.status==="ready"&&r.value))throw new O_r(e)}a(Cm,"assertAgentProviderAllowed");h();h();var Rpi=require("child_process"),LG=he(require("path")),Ppi=he(TR()),kpi=require("util");var Ipi=5e3,wpi=200,Bve=class{constructor(e){this.execFile=(0,kpi.promisify)(Rpi.execFile);this.cache=new Map;this.config=e}static{a(this,"BaseCliVersionChecker")}check(e){if(!e)return Promise.resolve({severity:"error",message:this.config.notConfiguredMessage});if(this.config.requireAbsolutePath&&!LG.isAbsolute(e))return Promise.resolve({severity:"error",message:`${this.config.displayName} path must be absolute.`});let r=LG.resolve(e),n=this.cache.get(r);if(n)return n;let o=this.computeStatus(r).then(s=>(s.severity==="error"&&this.cache.delete(r),s));return this.cache.set(r,o),o}clearCache(e){if(e){this.cache.delete(LG.resolve(e));return}this.cache.clear()}async computeStatus(e){let r=this.validateBasename(e);if(r)return{severity:"error",message:r};let n;try{n=(await this.execFile(e,["--version"],{timeout:Ipi,windowsHide:!0})).stdout}catch(l){return{severity:"error",message:this.formatSpawnError(e,l)}}let o=this.config.validateVersionOutput?.(n);if(o)return o;let s=Ppi.coerce(n);if(!s)return{severity:"error",message:`Could not parse ${this.config.displayName} version from the input path --version output: "${xpi(n)}". Cannot verify compatibility.`};let c=this.config.validateVersion(s,e);return c||{severity:"ok"}}validateBasename(e){let r=this.config.allowedBasenames;if(!r||r.length===0)return;let n=LG.basename(e).toLowerCase();if(!r.includes(n))return`${this.config.displayName} at the input path must point at the "${r[0]}" executable, but the basename is "${LG.basename(e)}".`}formatSpawnError(e,r){let n=r;if(n?.code==="ENOENT")return`${this.config.displayName} not found at the input path. Check that the file exists and is executable.`;if(n?.killed&&n?.signal==="SIGTERM")return`${this.config.displayName} at the input path did not respond to --version within ${Ipi/1e3}s.`;let o=typeof n?.stderr=="string"?xpi(n.stderr):"",s="";switch(typeof n?.code){case"number":s=` (exit code ${n.code})`;break;case"string":s=` (error code ${n.code})`;break}let c=o?` stderr: "${o}"`:"",l=n?.message?`: ${n.message}`:"";return`Failed to run "the input path --version"${s}${l}${c}`}};function xpi(t){let e=t.trim();return e.length<=wpi?e:`${e.slice(0,wpi)}\u2026`}a(xpi,"truncate");var s0t=he(TR());function zma(){let t=HZ.anthropicClaude?.cliPackageVersion;return typeof t=="string"?t:""}a(zma,"getExpectedVersionRaw");var L_r=class extends Bve{static{a(this,"ClaudeCliVersionChecker")}constructor(){super({displayName:"Claude Code CLI",allowedBasenames:process.platform==="win32"?["claude.exe"]:["claude"],notConfiguredMessage:"Claude Code CLI path is not configured. Install @anthropic-ai/claude-code (e.g. `npm install -g @anthropic-ai/claude-code`), then open your editor's Copilot settings and set the Claude Code CLI Path field to the absolute path of the `claude` executable.",validateVersion(e){let r=zma(),n=s0t.coerce(r);if(!n)return{severity:"error",message:`Could not parse expected Claude Code CLI version "${r}" from packaged metadata. This is an internal error; please report it.`};if(!s0t.satisfies(e,`~${n.major}.${n.minor}.0`))return{severity:"warning",message:`Claude Code CLI at the input path reports version ${e.version}, but this language server was built against ${n.version}. The session will still start, but SDK behavior may be unstable on protocol drift. Run \`npm install -g @anthropic-ai/claude-code@${n.version}\` to align versions.`}}})}},Fve=new L_r;h();var Uve=class{constructor(){this._entries=new Map}static{a(this,"PendingRequestRegistry")}register(e){if(this._entries.has(e))throw new Error(`PendingRequestRegistry: duplicate key ${e}`);return{promise:new Promise((n,o)=>{this._entries.set(e,{resolve:n,reject:o})}),isSettled:a(()=>!this._entries.has(e),"isSettled")}}respond(e,r){let n=this._entries.get(e);return n?(this._entries.delete(e),n.resolve(r),!0):!1}rejectOne(e,r){let n=this._entries.get(e);return n?(this._entries.delete(e),n.reject(r),!0):!1}has(e){return this._entries.has(e)}respondAll(e){let r=[...this._entries.values()];this._entries.clear();for(let n of r)n.resolve(e)}rejectAll(e){let r=[...this._entries.values()];this._entries.clear();for(let n of r)n.reject(e)}};h();h();function a0t(t){if(!t.startsWith("mcp__"))return;let[e,...r]=t.slice(5).split("__"),n=r.join("__");if(!(!e||!n))return{serverName:e,toolName:n}}a(a0t,"parseClaudeMcpToolName");function Dpi(t,e){let r=t.buildMcpServers(Cs(e),!1),n=Object.create(null);for(let[o,s]of Object.entries(r))n[o]={type:"http",url:s.url};return{servers:n,names:new Set(Object.keys(n))}}a(Dpi,"buildInjectedMcpServers");function Mpi(t,e){if(Object.keys(e).length===0)return;let r=t.service.origin;if(r)return[{serverUrl:`${r}/*`}]}a(Mpi,"buildAllowedMcpServers");function Npi(t,e,r){let n=r.toolUseID,s={intention:r.title??`${t} tool call`,...n!==void 0&&{toolCallId:n}},c=a(l=>typeof l=="string"?l:void 0,"str");switch(t){case"Bash":return{...s,kind:"shell",fullCommandText:c(e.command)??""};case"Write":case"Edit":case"MultiEdit":case"NotebookEdit":return{...s,kind:"write",fileName:c(r.blockedPath)??c(e.file_path)??c(e.notebook_path)??""};case"Read":return{...s,kind:"read",path:c(r.blockedPath)??c(e.file_path)??""};case"WebFetch":return{...s,kind:"url",url:c(e.url)??""};default:{let l=a0t(t);return l?{...s,kind:"mcp",serverName:l.serverName,toolName:l.toolName,args:e}:{...s,kind:"custom-tool",toolName:t,args:e}}}}a(Npi,"buildPermissionRequest");function Opi(t,e){return t.kind==="approve-once"?{behavior:"allow",updatedInput:e}:{behavior:"deny",message:t.feedback?`Permission denied by user: ${t.feedback}`:"Permission denied by user"}}a(Opi,"translatePermissionResult");function Lpi(t){let e=t;if(!Array.isArray(e.questions))return null;let r=[];for(let n of e.questions){if(typeof n?.question!="string"||n.question.length===0)return null;r.push({questionText:n.question,header:typeof n.header=="string"&&n.header.length>0?n.header:void 0,choices:Array.isArray(n.options)?n.options.map(o=>o?.label).filter(o=>typeof o=="string"):void 0})}return r}a(Lpi,"buildPreparedQuestions");function Bpi(t,e){return{question:t.header?`${t.header}
|
|
3943
3943
|
${t.questionText}`:t.questionText,...t.choices!==void 0&&{choices:t.choices},allowFreeform:!0,...e!==void 0&&{toolCallId:e}}}a(Bpi,"buildUserInputRequest");h();var Fpi=require("crypto");var Gma=new fe("ClaudeOTelTracker");function Upi(t){if(t!=null){if(typeof t=="string")return t;try{return JSON.stringify(t)}catch{return}}}a(Upi,"toAttributeString");function Vma(t){if(typeof t=="string")return t;if(Array.isArray(t)){let e=t.filter(r=>{if(typeof r!="object"||r===null)return!1;let n=r;return n.type==="text"&&typeof n.text=="string"}).map(r=>r.text);if(e.length===t.length&&e.length>0)return e.join("")}return Upi(t)}a(Vma,"stringifyToolResult");function B_r(t){return(0,Fpi.randomUUID)().replace(/-/g,"").slice(0,t*2)}a(B_r,"generateHexId");function c0t(){return BigInt(Date.now())*1000000n}a(c0t,"nowNano");var l0t=class{constructor(e,r,n){this._ctx=e;this._sessionId=r;this._persistence=n;this._toolSpans=new Map;this._responseText="";this._inputTokens=0;this._outputTokens=0;this._cacheReadTokens=0;this._cacheCreationTokens=0}static{a(this,"ClaudeOTelTracker")}startRequest(e,r){this._rootSpan&&this._endRootSpan(2,"New request started before previous ended");let n=B_r(16),o=B_r(8);this._rootSpan={traceId:n,spanId:o,name:"invoke_agent claude",startNano:c0t(),attributes:{[Zn.OPERATION_NAME]:V0e.INVOKE_AGENT,[Zn.AGENT_NAME]:"claude",[Zn.SYSTEM]:"anthropic",[Zn.CONVERSATION_ID]:this._sessionId,...e?{[Zn.REQUEST_MODEL]:e,[Zn.RESPONSE_MODEL]:e}:{[Zn.RESPONSE_MODEL]:"unknown"},...r?{[Zn.INPUT_MESSAGES]:j6("user",r)}:{}}},this._inputTokens=0,this._outputTokens=0,this._cacheReadTokens=0,this._cacheCreationTokens=0,this._responseText="",this._toolSpans.clear()}onMessage(e){if(this._rootSpan)switch(e.type){case"assistant":this._onAssistantMessage(e);break;case"user":this._onUserMessage(e);break;case"result":this._onResultMessage(e);break}}endRequest(){this._endRootSpan(1)}endRequestWithError(e){this._endRootSpan(2,e)}_onAssistantMessage(e){if(e.parent_tool_use_id!=null)return;let r=e.message?.content;if(Array.isArray(r))for(let n of r)n.type==="tool_use"?this._startToolSpan(n.id,n.name,n.input):n.type==="text"&&typeof n.text=="string"&&(this._responseText+=n.text)}_onUserMessage(e){let r=e.message?.content;if(Array.isArray(r)){for(let n of r)if(n.type==="tool_result"&&typeof n.tool_use_id=="string"){let o=n.is_error===!0;this._endToolSpan(n.tool_use_id,o,n.content)}}}_onResultMessage(e){if(!this._rootSpan)return;let r=e.usage;r&&(this._inputTokens=r.input_tokens??0,this._outputTokens=r.output_tokens??0,this._cacheReadTokens=r.cache_read_input_tokens??0,this._cacheCreationTokens=r.cache_creation_input_tokens??0),typeof e.num_turns=="number"&&(this._rootSpan.attributes[Zn.TURN_COUNT]=e.num_turns),typeof e.total_cost_usd=="number"&&(this._rootSpan.attributes[Zn.TOTAL_COST_USD]=e.total_cost_usd)}_startToolSpan(e,r,n){if(!this._rootSpan||this._toolSpans.has(e))return;let o={[Zn.OPERATION_NAME]:V0e.EXECUTE_TOOL,[Zn.TOOL_NAME]:r,[Zn.TOOL_CALL_ID]:e,[Zn.CONVERSATION_ID]:this._sessionId},s=Upi(n);s!==void 0&&(o[Zn.TOOL_CALL_ARGUMENTS]=s),this._toolSpans.set(e,{traceId:this._rootSpan.traceId,spanId:B_r(8),parentSpanId:this._rootSpan.spanId,name:`execute_tool ${r}`,startNano:c0t(),attributes:o})}_endToolSpan(e,r,n){let o=this._toolSpans.get(e);if(!o)return;this._toolSpans.delete(e);let s=Vma(n);s!==void 0&&(o.attributes[Zn.TOOL_CALL_RESULT]=s);let c=c0t(),l=this._buildOtlpSpan(o,c,r?2:1,r?"Tool execution error":void 0);this._flush([l])}_endRootSpan(e,r){let n=this._rootSpan;if(!n)return;this._rootSpan=void 0,this._inputTokens>0&&(n.attributes[Zn.USAGE_INPUT_TOKENS]=this._inputTokens),this._outputTokens>0&&(n.attributes[Zn.USAGE_OUTPUT_TOKENS]=this._outputTokens),this._cacheReadTokens>0&&(n.attributes[Zn.USAGE_CACHE_READ_INPUT_TOKENS]=this._cacheReadTokens),this._cacheCreationTokens>0&&(n.attributes[Zn.USAGE_CACHE_CREATION_INPUT_TOKENS]=this._cacheCreationTokens);let o=c0t(),s=[];for(let[,l]of this._toolSpans)s.push(this._buildOtlpSpan(l,o,2,"Tool span orphaned at turn end"));this._toolSpans.clear(),this._responseText&&(n.attributes[Zn.OUTPUT_MESSAGES]=j6("assistant",this._responseText)),this._responseText="";let c=this._buildOtlpSpan(n,o,e,r);this._flush([...s,c])}_buildOtlpSpan(e,r,n,o){let s={traceId:e.traceId,spanId:e.spanId,name:e.name,kind:1,startTimeUnixNano:e.startNano.toString(),endTimeUnixNano:r.toString(),attributes:FP(e.attributes),events:[],status:o?{code:n,message:o}:{code:n}};return e.parentSpanId&&(s.parentSpanId=e.parentSpanId),s}_flush(e){e.length!==0&&this._persistence.appendSpans(e).catch(r=>{Gma.warn(this._ctx,`Failed to persist OTel spans for session=${this._sessionId}: ${r instanceof Error?r.message:String(r)}`)})}};h();var F_r=require("fs"),qpi=he(require("path"));var v4e=new fe("ClaudeCode.ReferenceFormatter"),Wma={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp"},Qpi=5*1024*1024;async function jpi(t,e){if(!t?.length)return[];let r=[],n=[];for(let s of t)switch(s.type){case"file":{let c=Do(s.uri);if(!c){v4e.debug(e,`Skipping reference with non-fs URI: ${s.uri}`);break}let l=Kma(c);if(l){let u=await Yma(c,l,e);u&&r.push(u)}else{let u=s.selection?`:L${s.selection.start.line+1}-L${s.selection.end.line+1}`:"";n.push(`- ${c}${u}`)}break}case"directory":{let c=Do(s.uri);if(!c){v4e.debug(e,`Skipping reference with non-fs URI: ${s.uri}`);break}n.push(`- ${c}/`);break}default:v4e.debug(e,`Skipping unsupported reference type: ${s.type}`);break}let o=[...r];return n.length>0&&o.push({type:"text",text:Jma(n)}),o}a(jpi,"buildReferences");async function Yma(t,e,r){try{let n=await F_r.promises.stat(t);if(n.size>Qpi){v4e.debug(r,`Skipping oversize image reference (${n.size} > ${Qpi} bytes): ${t}`);return}let o=(await F_r.promises.readFile(t)).toString("base64");return{type:"image",source:{type:"base64",media_type:e,data:o}}}catch(n){v4e.debug(r,`Failed to read image reference ${t}: ${n instanceof Error?n.message:String(n)}`);return}}a(Yma,"tryReadImageBlock");function Kma(t){return Wma[qpi.extname(t).toLowerCase()]}a(Kma,"imageMediaTypeForPath");function Jma(t){return`<system-reminder>
|
package/package.json
CHANGED
|
@@ -11,7 +11,7 @@
|
|
|
11
11
|
"url": "git+https://github.com/github/copilot-language-server-release.git"
|
|
12
12
|
},
|
|
13
13
|
"license": "MIT",
|
|
14
|
-
"version": "1.567.
|
|
14
|
+
"version": "1.567.1",
|
|
15
15
|
"bin": {
|
|
16
16
|
"copilot-language-server": "../dist/language-server.js"
|
|
17
17
|
},
|
|
@@ -41,12 +41,12 @@
|
|
|
41
41
|
"vscode-languageserver-protocol": "^3.17.5"
|
|
42
42
|
},
|
|
43
43
|
"optionalDependencies": {
|
|
44
|
-
"@github/copilot-language-server-win32-x64": "1.567.
|
|
45
|
-
"@github/copilot-language-server-win32-arm64": "1.567.
|
|
46
|
-
"@github/copilot-language-server-linux-x64": "1.567.
|
|
47
|
-
"@github/copilot-language-server-linux-arm64": "1.567.
|
|
48
|
-
"@github/copilot-language-server-darwin-x64": "1.567.
|
|
49
|
-
"@github/copilot-language-server-darwin-arm64": "1.567.
|
|
44
|
+
"@github/copilot-language-server-win32-x64": "1.567.1",
|
|
45
|
+
"@github/copilot-language-server-win32-arm64": "1.567.1",
|
|
46
|
+
"@github/copilot-language-server-linux-x64": "1.567.1",
|
|
47
|
+
"@github/copilot-language-server-linux-arm64": "1.567.1",
|
|
48
|
+
"@github/copilot-language-server-darwin-x64": "1.567.1",
|
|
49
|
+
"@github/copilot-language-server-darwin-arm64": "1.567.1",
|
|
50
50
|
"@github/copilot-win32-x64": "1.0.105",
|
|
51
51
|
"@github/copilot-win32-arm64": "1.0.105",
|
|
52
52
|
"@github/copilot-linux-x64": "1.0.105",
|
|
@@ -61,5 +61,5 @@
|
|
|
61
61
|
"@github/copilot-sdk-darwin-arm64": "1.0.28"
|
|
62
62
|
},
|
|
63
63
|
"buildType": "prod",
|
|
64
|
-
"build": "
|
|
64
|
+
"build": "207"
|
|
65
65
|
}
|