forked from microsoft/vscode-python
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathconfigurePythonEnvTool.ts
More file actions
178 lines (167 loc) · 7.33 KB
/
Copy pathconfigurePythonEnvTool.ts
File metadata and controls
178 lines (167 loc) · 7.33 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
import {
CancellationToken,
LanguageModelTool,
LanguageModelToolInvocationOptions,
LanguageModelToolInvocationPrepareOptions,
LanguageModelToolResult,
PreparedToolInvocation,
Uri,
workspace,
lm,
} from 'vscode';
import { PythonExtension } from '../api/types';
import { IServiceContainer } from '../ioc/types';
import { ICodeExecutionService } from '../terminals/types';
import { TerminalCodeExecutionProvider } from '../terminals/codeExecution/terminalCodeExecution';
import {
getEnvDetailsForResponse,
getEnvTypeForTelemetry,
getToolResponseIfNotebook,
IResourceReference,
isCancellationError,
raceCancellationError,
setEnvironmentDirectlyByPath,
} from './utils';
import { ITerminalHelper } from '../common/terminal/types';
import { IRecommendedEnvironmentService } from '../interpreter/configuration/types';
import { CreateVirtualEnvTool } from './createVirtualEnvTool';
import { ISelectPythonEnvToolArguments, SelectPythonEnvTool } from './selectEnvTool';
import { BaseTool } from './baseTool';
import { traceVerbose } from '../logging';
import { ErrorWithTelemetrySafeReason } from '../common/errors/errorUtils';
export interface IConfigurePythonEnvToolArguments extends IResourceReference {
/**
* Optional path to a Python interpreter. When provided, the tool sets this
* interpreter directly without any user interaction (no Quick Pick, no
* create-venv prompt). This is the recommended way for Copilot to call
* the tool in autopilot / bypass-approvals mode.
*/
pythonPath?: string;
}
export class ConfigurePythonEnvTool extends BaseTool<IConfigurePythonEnvToolArguments>
implements LanguageModelTool<IConfigurePythonEnvToolArguments> {
private readonly terminalExecutionService: TerminalCodeExecutionProvider;
private readonly terminalHelper: ITerminalHelper;
private readonly recommendedEnvService: IRecommendedEnvironmentService;
public static readonly toolName = 'configure_python_environment';
constructor(
private readonly api: PythonExtension['environments'],
private readonly serviceContainer: IServiceContainer,
private readonly createEnvTool: CreateVirtualEnvTool,
) {
super(ConfigurePythonEnvTool.toolName);
this.terminalExecutionService = this.serviceContainer.get<TerminalCodeExecutionProvider>(
ICodeExecutionService,
'standard',
);
this.terminalHelper = this.serviceContainer.get<ITerminalHelper>(ITerminalHelper);
this.recommendedEnvService = this.serviceContainer.get<IRecommendedEnvironmentService>(
IRecommendedEnvironmentService,
);
}
async invokeImpl(
options: LanguageModelToolInvocationOptions<IConfigurePythonEnvToolArguments>,
resource: Uri | undefined,
token: CancellationToken,
): Promise<LanguageModelToolResult> {
const notebookResponse = getToolResponseIfNotebook(resource);
if (notebookResponse) {
this.extraTelemetryProperties.resolveOutcome = 'notebook';
return notebookResponse;
}
// Fast path: if the caller provided a pythonPath, set it directly without any UI.
if (options.input.pythonPath) {
return this.setEnvironmentDirectly(options.input.pythonPath, resource, token);
}
const workspaceSpecificEnv = await raceCancellationError(
this.hasAlreadyGotAWorkspaceSpecificEnvironment(resource),
token,
);
if (workspaceSpecificEnv) {
this.extraTelemetryProperties.resolveOutcome = 'existingWorkspaceEnv';
this.extraTelemetryProperties.envType = getEnvTypeForTelemetry(workspaceSpecificEnv);
return getEnvDetailsForResponse(
workspaceSpecificEnv,
this.api,
this.terminalExecutionService,
this.terminalHelper,
resource,
token,
);
}
if (await this.createEnvTool.shouldCreateNewVirtualEnv(resource, token)) {
try {
const result = await lm.invokeTool(CreateVirtualEnvTool.toolName, options, token);
this.extraTelemetryProperties.resolveOutcome = 'createdVirtualEnv';
return result;
} catch (ex) {
if (isCancellationError(ex)) {
const input: ISelectPythonEnvToolArguments = {
...options.input,
reason: 'cancelled',
};
// If the user cancelled the tool, then we should invoke the select env tool.
this.extraTelemetryProperties.resolveOutcome = 'selectedEnvAfterCancelledCreate';
return lm.invokeTool(SelectPythonEnvTool.toolName, { ...options, input }, token);
}
throw ex;
}
} else {
const input: ISelectPythonEnvToolArguments = {
...options.input,
};
this.extraTelemetryProperties.resolveOutcome = 'selectedEnv';
return lm.invokeTool(SelectPythonEnvTool.toolName, { ...options, input }, token);
}
}
/**
* Sets the given interpreter path directly without user interaction, then
* resolves and returns the environment details.
*/
private async setEnvironmentDirectly(
pythonPath: string,
resource: Uri | undefined,
token: CancellationToken,
): Promise<LanguageModelToolResult> {
traceVerbose(`${ConfigurePythonEnvTool.toolName}: setting environment directly from pythonPath: ${pythonPath}`);
const result = await setEnvironmentDirectlyByPath(pythonPath, this.api, resource, token);
if (result) {
this.extraTelemetryProperties.resolveOutcome = 'providedEnv';
this.extraTelemetryProperties.envType = getEnvTypeForTelemetry(result);
return getEnvDetailsForResponse(
result,
this.api,
this.terminalExecutionService,
this.terminalHelper,
resource,
token,
);
}
throw new ErrorWithTelemetrySafeReason(
`No environment found for the provided pythonPath '${pythonPath}'.`,
'noEnvFound',
);
}
async prepareInvocationImpl(
_options: LanguageModelToolInvocationPrepareOptions<IConfigurePythonEnvToolArguments>,
_resource: Uri | undefined,
_token: CancellationToken,
): Promise<PreparedToolInvocation> {
return {
invocationMessage: 'Configuring a Python Environment',
};
}
async hasAlreadyGotAWorkspaceSpecificEnvironment(resource: Uri | undefined) {
const recommededEnv = await this.recommendedEnvService.getRecommededEnvironment(resource);
// Already selected workspace env, hence nothing to do.
if (recommededEnv?.reason === 'workspaceUserSelected' && workspace.workspaceFolders?.length) {
return recommededEnv.environment;
}
// No workspace folders, and the user selected a global environment.
if (recommededEnv?.reason === 'globalUserSelected' && !workspace.workspaceFolders?.length) {
return recommededEnv.environment;
}
}
}