instruction
stringclasses 1
value | input
stringlengths 67
168
| output
stringlengths 46
67k
|
---|---|---|
You are a code assistant | Definition of 'isClientFlagEnabled' in file src/common/feature_flags.ts in project gitlab-lsp | Definition:
isClientFlagEnabled(name: ClientFeatureFlags): boolean;
}
@Injectable(FeatureFlagService, [GitLabApiClient, ConfigService])
export class DefaultFeatureFlagService {
#api: GitLabApiClient;
#configService: ConfigService;
#featureFlags: Map<string, boolean> = new Map();
constructor(api: GitLabApiClient, configService: ConfigService) {
this.#api = api;
this.#featureFlags = new Map();
this.#configService = configService;
this.#api.onApiReconfigured(async ({ isInValidState }) => {
if (!isInValidState) return;
await this.#updateInstanceFeatureFlags();
});
}
/**
* Fetches the feature flags from the gitlab instance
* and updates the internal state.
*/
async #fetchFeatureFlag(name: string): Promise<boolean> {
try {
const result = await this.#api.fetchFromApi<{ featureFlagEnabled: boolean }>({
type: 'graphql',
query: INSTANCE_FEATURE_FLAG_QUERY,
variables: { name },
});
log.debug(`FeatureFlagService: feature flag ${name} is ${result.featureFlagEnabled}`);
return result.featureFlagEnabled;
} catch (e) {
// FIXME: we need to properly handle graphql errors
// https://gitlab.com/gitlab-org/editor-extensions/gitlab-lsp/-/issues/250
if (e instanceof ClientError) {
const fieldDoesntExistError = e.message.match(/field '([^']+)' doesn't exist on type/i);
if (fieldDoesntExistError) {
// we expect graphql-request to throw an error when the query doesn't exist (eg. GitLab 16.9)
// so we debug to reduce noise
log.debug(`FeatureFlagService: query doesn't exist`, e.message);
} else {
log.error(`FeatureFlagService: error fetching feature flag ${name}`, e);
}
}
return false;
}
}
/**
* Fetches the feature flags from the gitlab instance
* and updates the internal state.
*/
async #updateInstanceFeatureFlags(): Promise<void> {
log.debug('FeatureFlagService: populating feature flags');
for (const flag of Object.values(InstanceFeatureFlags)) {
// eslint-disable-next-line no-await-in-loop
this.#featureFlags.set(flag, await this.#fetchFeatureFlag(flag));
}
}
/**
* Checks if a feature flag is enabled on the GitLab instance.
* @see `GitLabApiClient` for how the instance is determined.
* @requires `updateInstanceFeatureFlags` to be called first.
*/
isInstanceFlagEnabled(name: InstanceFeatureFlags): boolean {
return this.#featureFlags.get(name) ?? false;
}
/**
* Checks if a feature flag is enabled on the client.
* @see `ConfigService` for client configuration.
*/
isClientFlagEnabled(name: ClientFeatureFlags): boolean {
const value = this.#configService.get('client.featureFlags')?.[name];
return value ?? false;
}
}
References: |
You are a code assistant | Definition of 'DEFAULT_INITIALIZE_PARAMS' in file src/tests/int/lsp_client.ts in project gitlab-lsp | Definition:
export const DEFAULT_INITIALIZE_PARAMS = createFakePartial<CustomInitializeParams>({
processId: process.pid,
capabilities: {
textDocument: {
completion: {
completionItem: {
documentationFormat: [MarkupKind.PlainText],
insertReplaceSupport: false,
},
completionItemKind: {
valueSet: [1], // text
},
contextSupport: false,
insertTextMode: 2, // adjust indentation
},
},
},
clientInfo: {
name: 'lsp_client',
version: '0.0.1',
},
workspaceFolders: [
{
name: 'test',
uri: WORKSPACE_FOLDER_URI,
},
],
initializationOptions: {
ide: {
name: 'lsp_client',
version: '0.0.1',
vendor: 'gitlab',
},
},
});
/**
* Low level language server client for integration tests
*/
export class LspClient {
#childProcess: ChildProcessWithoutNullStreams;
#connection: MessageConnection;
#gitlabToken: string;
#gitlabBaseUrl: string = 'https://gitlab.com';
public childProcessConsole: string[] = [];
/**
* Spawn language server and create an RPC connection.
*
* @param gitlabToken GitLab PAT to use for code suggestions
*/
constructor(gitlabToken: string) {
this.#gitlabToken = gitlabToken;
const command = process.env.LSP_COMMAND ?? 'node';
const args = process.env.LSP_ARGS?.split(' ') ?? ['./out/node/main-bundle.js', '--stdio'];
console.log(`Running LSP using command \`${command} ${args.join(' ')}\` `);
const file = command === 'node' ? args[0] : command;
expect(file).not.toBe(undefined);
expect({ file, exists: fs.existsSync(file) }).toEqual({ file, exists: true });
this.#childProcess = spawn(command, args);
this.#childProcess.stderr.on('data', (chunk: Buffer | string) => {
const chunkString = chunk.toString('utf8');
this.childProcessConsole = this.childProcessConsole.concat(chunkString.split('\n'));
process.stderr.write(chunk);
});
// Use stdin and stdout for communication:
this.#connection = createMessageConnection(
new StreamMessageReader(this.#childProcess.stdout),
new StreamMessageWriter(this.#childProcess.stdin),
);
this.#connection.listen();
this.#connection.onError(function (err) {
console.error(err);
expect(err).not.toBeTruthy();
});
}
/**
* Make sure to call this method to shutdown the LS rpc connection
*/
public dispose() {
this.#connection.end();
}
/**
* Send the LSP 'initialize' message.
*
* @param initializeParams Provide custom values that override defaults. Merged with defaults.
* @returns InitializeResponse object
*/
public async sendInitialize(
initializeParams?: CustomInitializeParams,
): Promise<InitializeResult> {
const params = { ...DEFAULT_INITIALIZE_PARAMS, ...initializeParams };
const request = new RequestType<InitializeParams, InitializeResult, InitializeError>(
'initialize',
);
const response = await this.#connection.sendRequest(request, params);
return response;
}
/**
* Send the LSP 'initialized' notification
*/
public async sendInitialized(options?: InitializedParams | undefined): Promise<void> {
const defaults = {};
const params = { ...defaults, ...options };
const request = new NotificationType<InitializedParams>('initialized');
await this.#connection.sendNotification(request, params);
}
/**
* Send the LSP 'workspace/didChangeConfiguration' notification
*/
public async sendDidChangeConfiguration(
options?: ChangeConfigOptions | undefined,
): Promise<void> {
const defaults = createFakePartial<ChangeConfigOptions>({
settings: {
token: this.#gitlabToken,
baseUrl: this.#gitlabBaseUrl,
codeCompletion: {
enableSecretRedaction: true,
},
telemetry: {
enabled: false,
},
},
});
const params = { ...defaults, ...options };
const request = new NotificationType<DidChangeConfigurationParams>(
'workspace/didChangeConfiguration',
);
await this.#connection.sendNotification(request, params);
}
public async sendTextDocumentDidOpen(
uri: string,
languageId: string,
version: number,
text: string,
): Promise<void> {
const params = {
textDocument: {
uri,
languageId,
version,
text,
},
};
const request = new NotificationType<DidOpenTextDocumentParams>('textDocument/didOpen');
await this.#connection.sendNotification(request, params);
}
public async sendTextDocumentDidClose(uri: string): Promise<void> {
const params = {
textDocument: {
uri,
},
};
const request = new NotificationType<DidCloseTextDocumentParams>('textDocument/didClose');
await this.#connection.sendNotification(request, params);
}
/**
* Send LSP 'textDocument/didChange' using Full sync method notification
*
* @param uri File URL. Should include the workspace path in the url
* @param version Change version (incrementing from 0)
* @param text Full contents of the file
*/
public async sendTextDocumentDidChangeFull(
uri: string,
version: number,
text: string,
): Promise<void> {
const params = {
textDocument: {
uri,
version,
},
contentChanges: [{ text }],
};
const request = new NotificationType<DidChangeTextDocumentParams>('textDocument/didChange');
await this.#connection.sendNotification(request, params);
}
public async sendTextDocumentCompletion(
uri: string,
line: number,
character: number,
): Promise<CompletionItem[] | CompletionList | null> {
const params: CompletionParams = {
textDocument: {
uri,
},
position: {
line,
character,
},
context: {
triggerKind: 1, // invoked
},
};
const request = new RequestType1<
CompletionParams,
CompletionItem[] | CompletionList | null,
void
>('textDocument/completion');
const result = await this.#connection.sendRequest(request, params);
return result;
}
public async sendDidChangeDocumentInActiveEditor(uri: string): Promise<void> {
await this.#connection.sendNotification(DidChangeDocumentInActiveEditor, uri);
}
public async getWebviewMetadata(): Promise<WebviewMetadata[]> {
const result = await this.#connection.sendRequest<WebviewMetadata[]>(
'$/gitlab/webview-metadata',
);
return result;
}
}
References: |
You are a code assistant | Definition of 'updateSuggestionState' in file src/common/tracking/multi_tracker.ts in project gitlab-lsp | Definition:
updateSuggestionState(uniqueTrackingId: string, newState: TRACKING_EVENTS) {
this.#enabledTrackers.forEach((t) => t.updateSuggestionState(uniqueTrackingId, newState));
}
rejectOpenedSuggestions() {
this.#enabledTrackers.forEach((t) => t.rejectOpenedSuggestions());
}
}
References: |
You are a code assistant | Definition of 'FailedResponse' in file packages/lib_webview/src/events/webview_runtime_message_bus.ts in project gitlab-lsp | Definition:
export type FailedResponse = WebviewAddress & {
requestId: string;
success: false;
reason: string;
type: string;
};
export type ResponseMessage = SuccessfulResponse | FailedResponse;
export type Messages = {
'webview:connect': WebviewAddress;
'webview:disconnect': WebviewAddress;
'webview:notification': NotificationMessage;
'webview:request': RequestMessage;
'webview:response': ResponseMessage;
'plugin:notification': NotificationMessage;
'plugin:request': RequestMessage;
'plugin:response': ResponseMessage;
};
export class WebviewRuntimeMessageBus extends MessageBus<Messages> {}
References: |
You are a code assistant | Definition of 'SocketNotificationMessage' in file packages/lib_webview_transport_socket_io/src/utils/message_utils.ts in project gitlab-lsp | Definition:
export type SocketNotificationMessage = {
type: string;
payload: unknown;
};
export type SocketIoRequestMessage = {
requestId: string;
type: string;
payload: unknown;
};
export type SocketResponseMessage = {
requestId: string;
type: string;
payload: unknown;
success: boolean;
reason?: string | undefined;
};
export function isSocketNotificationMessage(
message: unknown,
): message is SocketNotificationMessage {
return (
typeof message === 'object' &&
message !== null &&
'type' in message &&
typeof message.type === 'string'
);
}
export function isSocketRequestMessage(message: unknown): message is SocketIoRequestMessage {
return (
typeof message === 'object' &&
message !== null &&
'requestId' in message &&
typeof message.requestId === 'string' &&
'type' in message &&
typeof message.type === 'string'
);
}
export function isSocketResponseMessage(message: unknown): message is SocketResponseMessage {
return (
typeof message === 'object' &&
message !== null &&
'requestId' in message &&
typeof message.requestId === 'string'
);
}
References: |
You are a code assistant | Definition of 'IClientContext' in file src/common/tracking/tracking_types.ts in project gitlab-lsp | Definition:
export interface IClientContext {
ide?: IIDEInfo;
extension?: IClientInfo;
}
export interface ITelemetryOptions {
enabled?: boolean;
baseUrl?: string;
trackingUrl?: string;
actions?: Array<{ action: TRACKING_EVENTS }>;
ide?: IIDEInfo;
extension?: IClientInfo;
}
export interface ICodeSuggestionModel {
lang: string;
engine: string;
name: string;
tokens_consumption_metadata?: {
input_tokens?: number;
output_tokens?: number;
context_tokens_sent?: number;
context_tokens_used?: number;
};
}
export interface TelemetryTracker {
isEnabled(): boolean;
setCodeSuggestionsContext(
uniqueTrackingId: string,
context: Partial<ICodeSuggestionContextUpdate>,
): void;
updateCodeSuggestionsContext(
uniqueTrackingId: string,
contextUpdate: Partial<ICodeSuggestionContextUpdate>,
): void;
rejectOpenedSuggestions(): void;
updateSuggestionState(uniqueTrackingId: string, newState: TRACKING_EVENTS): void;
}
export const TelemetryTracker = createInterfaceId<TelemetryTracker>('TelemetryTracker');
References:
- src/common/tracking/snowplow_tracker.test.ts:206
- src/common/tracking/snowplow_tracker.ts:229
- src/common/suggestion/suggestion_service.ts:71
- src/common/message_handler.ts:28
- src/tests/int/snowplow_tracker.test.ts:10 |
You are a code assistant | Definition of 'greet6' in file src/tests/fixtures/intent/empty_function/javascript.js in project gitlab-lsp | Definition:
const greet6 = (name) => {
console.log(name);
};
class Greet {
constructor(name) {}
greet() {}
}
class Greet2 {
constructor(name) {
this.name = name;
}
greet() {
console.log(`Hello ${this.name}`);
}
}
class Greet3 {}
function* generateGreetings() {}
function* greetGenerator() {
yield 'Hello';
}
References:
- src/tests/fixtures/intent/empty_function/ruby.rb:14 |
You are a code assistant | Definition of 'isAllowed' in file src/common/ai_context_management_2/policies/duo_project_policy.ts in project gitlab-lsp | Definition:
isAllowed(aiProviderItem: AiContextProviderItem): Promise<{ allowed: boolean; reason?: string }> {
const { providerType } = aiProviderItem;
switch (providerType) {
case 'file': {
const { repositoryFile } = aiProviderItem;
if (!repositoryFile) {
return Promise.resolve({ allowed: true });
}
const duoProjectStatus = this.duoProjectAccessChecker.checkProjectStatus(
repositoryFile.uri.toString(),
repositoryFile.workspaceFolder,
);
const enabled =
duoProjectStatus === DuoProjectStatus.DuoEnabled ||
duoProjectStatus === DuoProjectStatus.NonGitlabProject;
if (!enabled) {
return Promise.resolve({ allowed: false, reason: 'Duo is not enabled for this project' });
}
return Promise.resolve({ allowed: true });
}
default: {
throw new Error(`Unknown provider type ${providerType}`);
}
}
}
}
References: |
You are a code assistant | Definition of 'FetchBase' in file src/common/fetch.ts in project gitlab-lsp | Definition:
export class FetchBase implements LsFetch {
updateRequestInit(method: string, init?: RequestInit): RequestInit {
if (typeof init === 'undefined') {
// eslint-disable-next-line no-param-reassign
init = { method };
} else {
// eslint-disable-next-line no-param-reassign
init.method = method;
}
return init;
}
async initialize(): Promise<void> {}
async destroy(): Promise<void> {}
async fetch(input: RequestInfo | URL, init?: RequestInit): Promise<Response> {
return fetch(input, init);
}
async *streamFetch(
/* eslint-disable @typescript-eslint/no-unused-vars */
_url: string,
_body: string,
_headers: FetchHeaders,
/* eslint-enable @typescript-eslint/no-unused-vars */
): AsyncGenerator<string, void, void> {
// Stub. Should delegate to the node or browser fetch implementations
throw new Error('Not implemented');
yield '';
}
async delete(input: RequestInfo | URL, init?: RequestInit): Promise<Response> {
return this.fetch(input, this.updateRequestInit('DELETE', init));
}
async get(input: RequestInfo | URL, init?: RequestInit): Promise<Response> {
return this.fetch(input, this.updateRequestInit('GET', init));
}
async post(input: RequestInfo | URL, init?: RequestInit): Promise<Response> {
return this.fetch(input, this.updateRequestInit('POST', init));
}
async put(input: RequestInfo | URL, init?: RequestInit): Promise<Response> {
return this.fetch(input, this.updateRequestInit('PUT', init));
}
async fetchBase(input: RequestInfo | URL, init?: RequestInit): Promise<Response> {
// eslint-disable-next-line no-underscore-dangle, no-restricted-globals
const _global = typeof global === 'undefined' ? self : global;
return _global.fetch(input, init);
}
// eslint-disable-next-line @typescript-eslint/no-unused-vars
updateAgentOptions(_opts: FetchAgentOptions): void {}
}
References:
- src/common/api.test.ts:34
- src/common/tracking/snowplow_tracker.test.ts:86 |
You are a code assistant | Definition of 'TRACKING_EVENTS' in file src/common/tracking/constants.ts in project gitlab-lsp | Definition:
export enum TRACKING_EVENTS {
REQUESTED = 'suggestion_requested',
LOADED = 'suggestion_loaded',
NOT_PROVIDED = 'suggestion_not_provided',
SHOWN = 'suggestion_shown',
ERRORED = 'suggestion_error',
ACCEPTED = 'suggestion_accepted',
REJECTED = 'suggestion_rejected',
CANCELLED = 'suggestion_cancelled',
STREAM_STARTED = 'suggestion_stream_started',
STREAM_COMPLETED = 'suggestion_stream_completed',
}
const END_STATE_NO_TRANSITIONS_ALLOWED: TRACKING_EVENTS[] = [];
const endStatesGraph = new Map<TRACKING_EVENTS, TRACKING_EVENTS[]>([
[TRACKING_EVENTS.ERRORED, END_STATE_NO_TRANSITIONS_ALLOWED],
[TRACKING_EVENTS.CANCELLED, END_STATE_NO_TRANSITIONS_ALLOWED],
[TRACKING_EVENTS.NOT_PROVIDED, END_STATE_NO_TRANSITIONS_ALLOWED],
[TRACKING_EVENTS.REJECTED, END_STATE_NO_TRANSITIONS_ALLOWED],
[TRACKING_EVENTS.ACCEPTED, END_STATE_NO_TRANSITIONS_ALLOWED],
]);
export const nonStreamingSuggestionStateGraph = new Map<TRACKING_EVENTS, TRACKING_EVENTS[]>([
[TRACKING_EVENTS.REQUESTED, [TRACKING_EVENTS.LOADED, TRACKING_EVENTS.ERRORED]],
[
TRACKING_EVENTS.LOADED,
[TRACKING_EVENTS.SHOWN, TRACKING_EVENTS.CANCELLED, TRACKING_EVENTS.NOT_PROVIDED],
],
[TRACKING_EVENTS.SHOWN, [TRACKING_EVENTS.ACCEPTED, TRACKING_EVENTS.REJECTED]],
...endStatesGraph,
]);
export const streamingSuggestionStateGraph = new Map<TRACKING_EVENTS, TRACKING_EVENTS[]>([
[
TRACKING_EVENTS.REQUESTED,
[TRACKING_EVENTS.STREAM_STARTED, TRACKING_EVENTS.ERRORED, TRACKING_EVENTS.CANCELLED],
],
[
TRACKING_EVENTS.STREAM_STARTED,
[TRACKING_EVENTS.SHOWN, TRACKING_EVENTS.ERRORED, TRACKING_EVENTS.STREAM_COMPLETED],
],
[
TRACKING_EVENTS.SHOWN,
[
TRACKING_EVENTS.ERRORED,
TRACKING_EVENTS.STREAM_COMPLETED,
TRACKING_EVENTS.ACCEPTED,
TRACKING_EVENTS.REJECTED,
],
],
[
TRACKING_EVENTS.STREAM_COMPLETED,
[TRACKING_EVENTS.ACCEPTED, TRACKING_EVENTS.REJECTED, TRACKING_EVENTS.NOT_PROVIDED],
],
...endStatesGraph,
]);
export const endStates = [...endStatesGraph].map(([state]) => state);
export const SAAS_INSTANCE_URL = 'https://gitlab.com';
export const TELEMETRY_NOTIFICATION = '$/gitlab/telemetry';
export const CODE_SUGGESTIONS_CATEGORY = 'code_suggestions';
export const GC_TIME = 60000;
export const INSTANCE_TRACKING_EVENTS_MAP = {
[TRACKING_EVENTS.REQUESTED]: null,
[TRACKING_EVENTS.LOADED]: null,
[TRACKING_EVENTS.NOT_PROVIDED]: null,
[TRACKING_EVENTS.SHOWN]: 'code_suggestion_shown_in_ide',
[TRACKING_EVENTS.ERRORED]: null,
[TRACKING_EVENTS.ACCEPTED]: 'code_suggestion_accepted_in_ide',
[TRACKING_EVENTS.REJECTED]: 'code_suggestion_rejected_in_ide',
[TRACKING_EVENTS.CANCELLED]: null,
[TRACKING_EVENTS.STREAM_STARTED]: null,
[TRACKING_EVENTS.STREAM_COMPLETED]: null,
};
// FIXME: once we remove the default from ConfigService, we can move this back to the SnowplowTracker
export const DEFAULT_TRACKING_ENDPOINT = 'https://snowplow.trx.gitlab.net';
export const TELEMETRY_DISABLED_WARNING_MSG =
'GitLab Duo Code Suggestions telemetry is disabled. Please consider enabling telemetry to help improve our service.';
export const TELEMETRY_ENABLED_MSG = 'GitLab Duo Code Suggestions telemetry is enabled.';
References:
- src/common/suggestion/suggestion_service.ts:89
- src/common/tracking/multi_tracker.ts:35
- src/common/tracking/utils.ts:5
- src/common/message_handler.test.ts:153
- src/common/tracking/instance_tracker.ts:203
- src/common/tracking/snowplow_tracker.ts:410
- src/common/tracking/utils.ts:6
- src/common/tracking/tracking_types.ts:85
- src/common/message_handler.ts:45
- src/common/tracking/tracking_types.ts:54
- src/common/tracking/instance_tracker.ts:157
- src/common/tracking/snowplow_tracker.ts:366 |
You are a code assistant | Definition of 'ResponseHandler' in file packages/lib_webview/src/setup/plugin/webview_instance_message_bus.ts in project gitlab-lsp | Definition:
type ResponseHandler = (message: ResponseMessage) => void;
export class WebviewInstanceMessageBus<T extends MessageMap = MessageMap>
implements WebviewMessageBus<T>, Disposable
{
#address: WebviewAddress;
#runtimeMessageBus: WebviewRuntimeMessageBus;
#eventSubscriptions = new CompositeDisposable();
#notificationEvents = new SimpleRegistry<NotificationHandler>();
#requestEvents = new SimpleRegistry<RequestHandler>();
#pendingResponseEvents = new SimpleRegistry<ResponseHandler>();
#logger: Logger;
constructor(
webviewAddress: WebviewAddress,
runtimeMessageBus: WebviewRuntimeMessageBus,
logger: Logger,
) {
this.#address = webviewAddress;
this.#runtimeMessageBus = runtimeMessageBus;
this.#logger = withPrefix(
logger,
`[WebviewInstanceMessageBus:${webviewAddress.webviewId}:${webviewAddress.webviewInstanceId}]`,
);
this.#logger.debug('initializing');
const eventFilter = buildWebviewAddressFilter(webviewAddress);
this.#eventSubscriptions.add(
this.#runtimeMessageBus.subscribe(
'webview:notification',
async (message) => {
try {
await this.#notificationEvents.handle(message.type, message.payload);
} catch (error) {
this.#logger.debug(
`Failed to handle webview instance notification: ${message.type}`,
error instanceof Error ? error : undefined,
);
}
},
eventFilter,
),
this.#runtimeMessageBus.subscribe(
'webview:request',
async (message) => {
try {
await this.#requestEvents.handle(message.type, message.requestId, message.payload);
} catch (error) {
this.#logger.error(error as Error);
}
},
eventFilter,
),
this.#runtimeMessageBus.subscribe(
'webview:response',
async (message) => {
try {
await this.#pendingResponseEvents.handle(message.requestId, message);
} catch (error) {
this.#logger.error(error as Error);
}
},
eventFilter,
),
);
this.#logger.debug('initialized');
}
sendNotification(type: Method, payload?: unknown): void {
this.#logger.debug(`Sending notification: ${type}`);
this.#runtimeMessageBus.publish('plugin:notification', {
...this.#address,
type,
payload,
});
}
onNotification(type: Method, handler: Handler): Disposable {
return this.#notificationEvents.register(type, handler);
}
async sendRequest(type: Method, payload?: unknown): Promise<never> {
const requestId = generateRequestId();
this.#logger.debug(`Sending request: ${type}, ID: ${requestId}`);
let timeout: NodeJS.Timeout | undefined;
return new Promise((resolve, reject) => {
const pendingRequestHandle = this.#pendingResponseEvents.register(
requestId,
(message: ResponseMessage) => {
if (message.success) {
resolve(message.payload as PromiseLike<never>);
} else {
reject(new Error(message.reason));
}
clearTimeout(timeout);
pendingRequestHandle.dispose();
},
);
this.#runtimeMessageBus.publish('plugin:request', {
...this.#address,
requestId,
type,
payload,
});
timeout = setTimeout(() => {
pendingRequestHandle.dispose();
this.#logger.debug(`Request with ID: ${requestId} timed out`);
reject(new Error('Request timed out'));
}, 10000);
});
}
onRequest(type: Method, handler: Handler): Disposable {
return this.#requestEvents.register(type, (requestId: RequestId, payload: unknown) => {
try {
const result = handler(payload);
this.#runtimeMessageBus.publish('plugin:response', {
...this.#address,
requestId,
type,
success: true,
payload: result,
});
} catch (error) {
this.#logger.error(`Error handling request of type ${type}:`, error as Error);
this.#runtimeMessageBus.publish('plugin:response', {
...this.#address,
requestId,
type,
success: false,
reason: (error as Error).message,
});
}
});
}
dispose(): void {
this.#eventSubscriptions.dispose();
this.#notificationEvents.dispose();
this.#requestEvents.dispose();
this.#pendingResponseEvents.dispose();
}
}
References: |
You are a code assistant | Definition of 'TimeoutError' in file src/common/fetch_error.ts in project gitlab-lsp | Definition:
export class TimeoutError extends Error {
constructor(url: URL | RequestInfo) {
const timeoutInSeconds = Math.round(REQUEST_TIMEOUT_MILLISECONDS / 1000);
super(
`Request to ${extractURL(url)} timed out after ${timeoutInSeconds} second${timeoutInSeconds === 1 ? '' : 's'}`,
);
}
}
export class InvalidInstanceVersionError extends Error {}
References:
- src/node/fetch.ts:114 |
You are a code assistant | Definition of 'updateAgentOptions' in file src/node/fetch.ts in project gitlab-lsp | Definition:
updateAgentOptions({ ignoreCertificateErrors, ca, cert, certKey }: FetchAgentOptions): void {
let fileOptions = {};
try {
fileOptions = {
...(ca ? { ca: fs.readFileSync(ca) } : {}),
...(cert ? { cert: fs.readFileSync(cert) } : {}),
...(certKey ? { key: fs.readFileSync(certKey) } : {}),
};
} catch (err) {
log.error('Error reading https agent options from file', err);
}
const newOptions: LsAgentOptions = {
rejectUnauthorized: !ignoreCertificateErrors,
...fileOptions,
};
if (isEqual(newOptions, this.#agentOptions)) {
// new and old options are the same, nothing to do
return;
}
this.#agentOptions = newOptions;
this.#httpsAgent = this.#createHttpsAgent();
if (this.#proxy) {
this.#proxy = this.#createProxyAgent();
}
}
async *streamFetch(
url: string,
body: string,
headers: FetchHeaders,
): AsyncGenerator<string, void, void> {
let buffer = '';
const decoder = new TextDecoder();
async function* readStream(
stream: ReadableStream<Uint8Array>,
): AsyncGenerator<string, void, void> {
for await (const chunk of stream) {
buffer += decoder.decode(chunk);
yield buffer;
}
}
const response: Response = await this.fetch(url, {
method: 'POST',
headers,
body,
});
await handleFetchError(response, 'Code Suggestions Streaming');
if (response.body) {
// Note: Using (node:stream).ReadableStream as it supports async iterators
yield* readStream(response.body as ReadableStream);
}
}
#createHttpsAgent(): https.Agent {
const agentOptions = {
...this.#agentOptions,
keepAlive: true,
};
log.debug(
`fetch: https agent with options initialized ${JSON.stringify(
this.#sanitizeAgentOptions(agentOptions),
)}.`,
);
return new https.Agent(agentOptions);
}
#createProxyAgent(): ProxyAgent {
log.debug(
`fetch: proxy agent with options initialized ${JSON.stringify(
this.#sanitizeAgentOptions(this.#agentOptions),
)}.`,
);
return new ProxyAgent(this.#agentOptions);
}
async #fetchLogged(input: RequestInfo | URL, init: LsRequestInit): Promise<Response> {
const start = Date.now();
const url = this.#extractURL(input);
if (init.agent === httpAgent) {
log.debug(`fetch: request for ${url} made with http agent.`);
} else {
const type = init.agent === this.#proxy ? 'proxy' : 'https';
log.debug(`fetch: request for ${url} made with ${type} agent.`);
}
try {
const resp = await fetch(input, init);
const duration = Date.now() - start;
log.debug(`fetch: request to ${url} returned HTTP ${resp.status} after ${duration} ms`);
return resp;
} catch (e) {
const duration = Date.now() - start;
log.debug(`fetch: request to ${url} threw an exception after ${duration} ms`);
log.error(`fetch: request to ${url} failed with:`, e);
throw e;
}
}
#getAgent(input: RequestInfo | URL): ProxyAgent | https.Agent | http.Agent {
if (this.#proxy) {
return this.#proxy;
}
if (input.toString().startsWith('https://')) {
return this.#httpsAgent;
}
return httpAgent;
}
#extractURL(input: RequestInfo | URL): string {
if (input instanceof URL) {
return input.toString();
}
if (typeof input === 'string') {
return input;
}
return input.url;
}
#sanitizeAgentOptions(agentOptions: LsAgentOptions) {
const { ca, cert, key, ...options } = agentOptions;
return {
...options,
...(ca ? { ca: '<hidden>' } : {}),
...(cert ? { cert: '<hidden>' } : {}),
...(key ? { key: '<hidden>' } : {}),
};
}
}
References: |
You are a code assistant | Definition of 'LangGraphCheckpoint' in file packages/webview_duo_workflow/src/types.ts in project gitlab-lsp | Definition:
export type LangGraphCheckpoint = {
checkpoint: string;
};
export type DuoWorkflowEvents = {
nodes: LangGraphCheckpoint[];
};
export type DuoWorkflowEventConnectionType = {
duoWorkflowEvents: DuoWorkflowEvents;
};
References:
- src/common/graphql/workflow/service.ts:37
- src/common/graphql/workflow/service.ts:28 |
You are a code assistant | Definition of 'DefaultSuggestionClient' in file src/common/suggestion_client/default_suggestion_client.ts in project gitlab-lsp | Definition:
export class DefaultSuggestionClient implements SuggestionClient {
readonly #api: GitLabApiClient;
constructor(api: GitLabApiClient) {
this.#api = api;
}
async getSuggestions(
suggestionContext: SuggestionContext,
): Promise<SuggestionResponse | undefined> {
const response = await this.#api.getCodeSuggestions(createV2Request(suggestionContext));
return response && { ...response, isDirectConnection: false };
}
}
References:
- src/common/suggestion/suggestion_service.ts:162
- src/common/suggestion_client/default_suggestion_client.test.ts:21
- src/common/suggestion_client/default_suggestion_client.test.ts:28 |
You are a code assistant | Definition of 'isEnabled' in file src/common/tracking/snowplow_tracker.ts in project gitlab-lsp | Definition:
isEnabled(): boolean {
return Boolean(this.#options.enabled);
}
async #reconfigure(config: IConfig) {
const { baseUrl } = config.client;
const trackingUrl = config.client.telemetry?.trackingUrl;
const enabled = config.client.telemetry?.enabled;
const actions = config.client.telemetry?.actions;
if (typeof enabled !== 'undefined') {
this.#options.enabled = enabled;
if (enabled === false) {
log.warn(`Snowplow Telemetry: ${TELEMETRY_DISABLED_WARNING_MSG}`);
} else if (enabled === true) {
log.info(`Snowplow Telemetry: ${TELEMETRY_ENABLED_MSG}`);
}
}
if (baseUrl) {
this.#options.baseUrl = baseUrl;
this.#gitlabRealm = baseUrl.endsWith(SAAS_INSTANCE_URL)
? GitlabRealm.saas
: GitlabRealm.selfManaged;
}
if (trackingUrl && this.#options.trackingUrl !== trackingUrl) {
await this.#snowplow.stop();
this.#snowplow.destroy();
this.#snowplow = Snowplow.getInstance(this.#lsFetch, {
...DEFAULT_SNOWPLOW_OPTIONS,
endpoint: trackingUrl,
enabled: this.isEnabled.bind(this),
});
}
if (actions) {
this.#options.actions = actions;
}
this.#setClientContext({
extension: config.client.telemetry?.extension,
ide: config.client.telemetry?.ide,
});
}
#setClientContext(context: IClientContext) {
this.#clientContext.data = {
ide_name: context?.ide?.name ?? null,
ide_vendor: context?.ide?.vendor ?? null,
ide_version: context?.ide?.version ?? null,
extension_name: context?.extension?.name ?? null,
extension_version: context?.extension?.version ?? null,
language_server_version: lsVersion ?? null,
};
}
public setCodeSuggestionsContext(
uniqueTrackingId: string,
context: Partial<ICodeSuggestionContextUpdate>,
) {
const {
documentContext,
source = SuggestionSource.network,
language,
isStreaming,
triggerKind,
optionsCount,
additionalContexts,
isDirectConnection,
} = context;
const {
gitlab_instance_id,
gitlab_global_user_id,
gitlab_host_name,
gitlab_saas_duo_pro_namespace_ids,
} = this.#configService.get('client.snowplowTrackerOptions') ?? {};
if (source === SuggestionSource.cache) {
log.debug(`Snowplow Telemetry: Retrieved suggestion from cache`);
} else {
log.debug(`Snowplow Telemetry: Received request to create a new suggestion`);
}
// Only auto-reject if client is set up to track accepted and not rejected events.
if (
canClientTrackEvent(this.#options.actions, TRACKING_EVENTS.ACCEPTED) &&
!canClientTrackEvent(this.#options.actions, TRACKING_EVENTS.REJECTED)
) {
this.rejectOpenedSuggestions();
}
setTimeout(() => {
if (this.#codeSuggestionsContextMap.has(uniqueTrackingId)) {
this.#codeSuggestionsContextMap.delete(uniqueTrackingId);
this.#codeSuggestionStates.delete(uniqueTrackingId);
}
}, GC_TIME);
const advancedContextData = this.#getAdvancedContextData({
additionalContexts,
documentContext,
});
this.#codeSuggestionsContextMap.set(uniqueTrackingId, {
schema: 'iglu:com.gitlab/code_suggestions_context/jsonschema/3-5-0',
data: {
suffix_length: documentContext?.suffix.length ?? 0,
prefix_length: documentContext?.prefix.length ?? 0,
gitlab_realm: this.#gitlabRealm,
model_engine: null,
model_name: null,
language: language ?? null,
api_status_code: null,
debounce_interval: source === SuggestionSource.cache ? 0 : SUGGESTIONS_DEBOUNCE_INTERVAL_MS,
suggestion_source: source,
gitlab_global_user_id: gitlab_global_user_id ?? null,
gitlab_host_name: gitlab_host_name ?? null,
gitlab_instance_id: gitlab_instance_id ?? null,
gitlab_saas_duo_pro_namespace_ids: gitlab_saas_duo_pro_namespace_ids ?? null,
gitlab_instance_version: this.#api.instanceVersion ?? null,
is_streaming: isStreaming ?? false,
is_invoked: SnowplowTracker.#isCompletionInvoked(triggerKind),
options_count: optionsCount ?? null,
has_advanced_context: advancedContextData.hasAdvancedContext,
is_direct_connection: isDirectConnection ?? null,
total_context_size_bytes: advancedContextData.totalContextSizeBytes,
content_above_cursor_size_bytes: advancedContextData.contentAboveCursorSizeBytes,
content_below_cursor_size_bytes: advancedContextData.contentBelowCursorSizeBytes,
context_items: advancedContextData.contextItems,
},
});
this.#codeSuggestionStates.set(uniqueTrackingId, TRACKING_EVENTS.REQUESTED);
this.#trackCodeSuggestionsEvent(TRACKING_EVENTS.REQUESTED, uniqueTrackingId).catch((e) =>
log.warn('Snowplow Telemetry: Could not track telemetry', e),
);
log.debug(`Snowplow Telemetry: New suggestion ${uniqueTrackingId} has been requested`);
}
// FIXME: the set and update context methods have similar logic and they should have to grow linearly with each new attribute
// the solution might be some generic update method used by both
public updateCodeSuggestionsContext(
uniqueTrackingId: string,
contextUpdate: Partial<ICodeSuggestionContextUpdate>,
) {
const context = this.#codeSuggestionsContextMap.get(uniqueTrackingId);
const { model, status, optionsCount, acceptedOption, isDirectConnection } = contextUpdate;
if (context) {
if (model) {
context.data.language = model.lang ?? null;
context.data.model_engine = model.engine ?? null;
context.data.model_name = model.name ?? null;
context.data.input_tokens = model?.tokens_consumption_metadata?.input_tokens ?? null;
context.data.output_tokens = model.tokens_consumption_metadata?.output_tokens ?? null;
context.data.context_tokens_sent =
model.tokens_consumption_metadata?.context_tokens_sent ?? null;
context.data.context_tokens_used =
model.tokens_consumption_metadata?.context_tokens_used ?? null;
}
if (status) {
context.data.api_status_code = status;
}
if (optionsCount) {
context.data.options_count = optionsCount;
}
if (isDirectConnection !== undefined) {
context.data.is_direct_connection = isDirectConnection;
}
if (acceptedOption) {
context.data.accepted_option = acceptedOption;
}
this.#codeSuggestionsContextMap.set(uniqueTrackingId, context);
}
}
async #trackCodeSuggestionsEvent(eventType: TRACKING_EVENTS, uniqueTrackingId: string) {
if (!this.isEnabled()) {
return;
}
const event: StructuredEvent = {
category: CODE_SUGGESTIONS_CATEGORY,
action: eventType,
label: uniqueTrackingId,
};
try {
const contexts: SelfDescribingJson[] = [this.#clientContext];
const codeSuggestionContext = this.#codeSuggestionsContextMap.get(uniqueTrackingId);
if (codeSuggestionContext) {
contexts.push(codeSuggestionContext);
}
const suggestionContextValid = this.#ajv.validate(
CodeSuggestionContextSchema,
codeSuggestionContext?.data,
);
if (!suggestionContextValid) {
log.warn(EVENT_VALIDATION_ERROR_MSG);
log.debug(JSON.stringify(this.#ajv.errors, null, 2));
return;
}
const ideExtensionContextValid = this.#ajv.validate(
IdeExtensionContextSchema,
this.#clientContext?.data,
);
if (!ideExtensionContextValid) {
log.warn(EVENT_VALIDATION_ERROR_MSG);
log.debug(JSON.stringify(this.#ajv.errors, null, 2));
return;
}
await this.#snowplow.trackStructEvent(event, contexts);
} catch (error) {
log.warn(`Snowplow Telemetry: Failed to track telemetry event: ${eventType}`, error);
}
}
public updateSuggestionState(uniqueTrackingId: string, newState: TRACKING_EVENTS): void {
const state = this.#codeSuggestionStates.get(uniqueTrackingId);
if (!state) {
log.debug(`Snowplow Telemetry: The suggestion with ${uniqueTrackingId} can't be found`);
return;
}
const isStreaming = Boolean(
this.#codeSuggestionsContextMap.get(uniqueTrackingId)?.data.is_streaming,
);
const allowedTransitions = isStreaming
? streamingSuggestionStateGraph.get(state)
: nonStreamingSuggestionStateGraph.get(state);
if (!allowedTransitions) {
log.debug(
`Snowplow Telemetry: The suggestion's ${uniqueTrackingId} state ${state} can't be found in state graph`,
);
return;
}
if (!allowedTransitions.includes(newState)) {
log.debug(
`Snowplow Telemetry: Unexpected transition from ${state} into ${newState} for ${uniqueTrackingId}`,
);
// Allow state to update to ACCEPTED despite 'allowed transitions' constraint.
if (newState !== TRACKING_EVENTS.ACCEPTED) {
return;
}
log.debug(
`Snowplow Telemetry: Conditionally allowing transition to accepted state for ${uniqueTrackingId}`,
);
}
this.#codeSuggestionStates.set(uniqueTrackingId, newState);
this.#trackCodeSuggestionsEvent(newState, uniqueTrackingId).catch((e) =>
log.warn('Snowplow Telemetry: Could not track telemetry', e),
);
log.debug(`Snowplow Telemetry: ${uniqueTrackingId} transisted from ${state} to ${newState}`);
}
rejectOpenedSuggestions() {
log.debug(`Snowplow Telemetry: Reject all opened suggestions`);
this.#codeSuggestionStates.forEach((state, uniqueTrackingId) => {
if (endStates.includes(state)) {
return;
}
this.updateSuggestionState(uniqueTrackingId, TRACKING_EVENTS.REJECTED);
});
}
#hasAdvancedContext(advancedContexts?: AdditionalContext[]): boolean | null {
const advancedContextFeatureFlagsEnabled = shouldUseAdvancedContext(
this.#featureFlagService,
this.#configService,
);
if (advancedContextFeatureFlagsEnabled) {
return Boolean(advancedContexts?.length);
}
return null;
}
#getAdvancedContextData({
additionalContexts,
documentContext,
}: {
additionalContexts?: AdditionalContext[];
documentContext?: IDocContext;
}) {
const hasAdvancedContext = this.#hasAdvancedContext(additionalContexts);
const contentAboveCursorSizeBytes = documentContext?.prefix
? getByteSize(documentContext.prefix)
: 0;
const contentBelowCursorSizeBytes = documentContext?.suffix
? getByteSize(documentContext.suffix)
: 0;
const contextItems: ContextItem[] | null =
additionalContexts?.map((item) => ({
file_extension: item.name.split('.').pop() || '',
type: item.type,
resolution_strategy: item.resolution_strategy,
byte_size: item?.content ? getByteSize(item.content) : 0,
})) ?? null;
const totalContextSizeBytes =
contextItems?.reduce((total, item) => total + item.byte_size, 0) ?? 0;
return {
totalContextSizeBytes,
contentAboveCursorSizeBytes,
contentBelowCursorSizeBytes,
contextItems,
hasAdvancedContext,
};
}
static #isCompletionInvoked(triggerKind?: InlineCompletionTriggerKind): boolean | null {
let isInvoked = null;
if (triggerKind === InlineCompletionTriggerKind.Invoked) {
isInvoked = true;
} else if (triggerKind === InlineCompletionTriggerKind.Automatic) {
isInvoked = false;
}
return isInvoked;
}
}
References: |
You are a code assistant | Definition of 'setCodeSuggestionsContext' in file src/common/tracking/multi_tracker.ts in project gitlab-lsp | Definition:
setCodeSuggestionsContext(
uniqueTrackingId: string,
context: Partial<ICodeSuggestionContextUpdate>,
) {
this.#enabledTrackers.forEach((t) => t.setCodeSuggestionsContext(uniqueTrackingId, context));
}
updateCodeSuggestionsContext(
uniqueTrackingId: string,
contextUpdate: Partial<ICodeSuggestionContextUpdate>,
) {
this.#enabledTrackers.forEach((t) =>
t.updateCodeSuggestionsContext(uniqueTrackingId, contextUpdate),
);
}
updateSuggestionState(uniqueTrackingId: string, newState: TRACKING_EVENTS) {
this.#enabledTrackers.forEach((t) => t.updateSuggestionState(uniqueTrackingId, newState));
}
rejectOpenedSuggestions() {
this.#enabledTrackers.forEach((t) => t.rejectOpenedSuggestions());
}
}
References: |
You are a code assistant | Definition of 'onNotification' in file src/common/webview/extension/extension_connection_message_bus.ts in project gitlab-lsp | Definition:
onNotification<T extends keyof TMessageMap['inbound']['notifications'] & string>(
type: T,
handler: (payload: TMessageMap['inbound']['notifications'][T]) => void,
): Disposable {
return this.#handlers.notification.register({ webviewId: this.#webviewId, type }, handler);
}
sendRequest<T extends keyof TMessageMap['outbound']['requests'] & string>(
type: T,
payload?: TMessageMap['outbound']['requests'][T]['params'],
): Promise<ExtractRequestResult<TMessageMap['outbound']['requests'][T]>> {
return this.#connection.sendRequest(this.#rpcMethods.request, {
webviewId: this.#webviewId,
type,
payload,
});
}
async sendNotification<T extends keyof TMessageMap['outbound']['notifications'] & string>(
type: T,
payload?: TMessageMap['outbound']['notifications'][T],
): Promise<void> {
await this.#connection.sendNotification(this.#rpcMethods.notification, {
webviewId: this.#webviewId,
type,
payload,
});
}
}
References: |
You are a code assistant | Definition of 'SendEventCallback' in file src/common/tracking/snowplow/emitter.ts in project gitlab-lsp | Definition:
export type SendEventCallback = (events: PayloadBuilder[]) => Promise<void>;
enum EmitterState {
STARTED,
STOPPING,
STOPPED,
}
export class Emitter {
#trackingQueue: PayloadBuilder[] = [];
#callback: SendEventCallback;
#timeInterval: number;
#maxItems: number;
#currentState: EmitterState;
#timeout: NodeJS.Timeout | undefined;
constructor(timeInterval: number, maxItems: number, callback: SendEventCallback) {
this.#maxItems = maxItems;
this.#timeInterval = timeInterval;
this.#callback = callback;
this.#currentState = EmitterState.STOPPED;
}
add(data: PayloadBuilder) {
this.#trackingQueue.push(data);
if (this.#trackingQueue.length >= this.#maxItems) {
this.#drainQueue().catch(() => {});
}
}
async #drainQueue(): Promise<void> {
if (this.#trackingQueue.length > 0) {
const copyOfTrackingQueue = this.#trackingQueue.map((e) => e);
this.#trackingQueue = [];
await this.#callback(copyOfTrackingQueue);
}
}
start() {
this.#timeout = setTimeout(async () => {
await this.#drainQueue();
if (this.#currentState !== EmitterState.STOPPING) {
this.start();
}
}, this.#timeInterval);
this.#currentState = EmitterState.STARTED;
}
async stop() {
this.#currentState = EmitterState.STOPPING;
if (this.#timeout) {
clearTimeout(this.#timeout);
}
this.#timeout = undefined;
await this.#drainQueue();
}
}
References:
- src/common/tracking/snowplow/emitter.ts:24
- src/common/tracking/snowplow/emitter.ts:14 |
You are a code assistant | Definition of 'registerStaticPluginSafely' in file src/node/http/utils/register_static_plugin_safely.ts in project gitlab-lsp | Definition:
export const registerStaticPluginSafely = async (
fastify: FastifyInstance,
options: Omit<FastifyStaticOptions, 'decorateReply'>,
) => {
// Check if 'sendFile' is already decorated on the reply object
if (!fastify.hasReplyDecorator('sendFile')) {
await fastify.register(FastifyStatic, {
...options,
decorateReply: true,
});
} else {
// Register the plugin without adding the decoration again
await fastify.register(FastifyStatic, {
...options,
decorateReply: false,
});
}
};
References:
- src/node/webview/routes/webview_routes.ts:26 |
You are a code assistant | Definition of 'publish' in file packages/lib_webview/src/events/message_bus.ts in project gitlab-lsp | Definition:
public publish<K extends keyof TMessageMap>(messageType: K, data: TMessageMap[K]): void {
const targetSubscriptions = this.#subscriptions.get(messageType);
if (targetSubscriptions) {
Array.from(targetSubscriptions).forEach((subscription) => {
const { listener, filter } = subscription as Subscription<TMessageMap[K]>;
if (!filter || filter(data)) {
listener(data);
}
});
}
}
public hasListeners<K extends keyof TMessageMap>(messageType: K): boolean {
return this.#subscriptions.has(messageType);
}
public listenerCount<K extends keyof TMessageMap>(messageType: K): number {
return this.#subscriptions.get(messageType)?.size ?? 0;
}
public clear(): void {
this.#subscriptions.clear();
}
public dispose(): void {
this.clear();
}
}
References: |
You are a code assistant | Definition of 'ConnectionService' in file src/common/connection_service.ts in project gitlab-lsp | Definition:
export interface ConnectionService {}
export const ConnectionService = createInterfaceId<ConnectionService>('ConnectionService');
const createNotifyFn =
<T>(c: LsConnection, method: NotificationType<T>) =>
(param: T) =>
c.sendNotification(method, param);
const createDiagnosticsPublisherFn = (c: LsConnection) => (param: PublishDiagnosticsParams) =>
c.sendDiagnostics(param);
@Injectable(ConnectionService, [
LsConnection,
TokenCheckNotifier,
InitializeHandler,
DidChangeWorkspaceFoldersHandler,
SecurityDiagnosticsPublisher,
DocumentService,
AiContextAggregator,
AiContextManager,
FeatureStateManager,
])
export class DefaultConnectionService implements ConnectionService {
#connection: LsConnection;
#aiContextAggregator: AiContextAggregator;
#aiContextManager: AiContextManager;
constructor(
connection: LsConnection,
tokenCheckNotifier: TokenCheckNotifier,
initializeHandler: InitializeHandler,
didChangeWorkspaceFoldersHandler: DidChangeWorkspaceFoldersHandler,
securityDiagnosticsPublisher: SecurityDiagnosticsPublisher,
documentService: DocumentService,
aiContextAggregator: AiContextAggregator,
aiContextManager: AiContextManager,
featureStateManager: FeatureStateManager,
) {
this.#connection = connection;
this.#aiContextAggregator = aiContextAggregator;
this.#aiContextManager = aiContextManager;
// request handlers
connection.onInitialize(initializeHandler.requestHandler);
// notifiers
this.#initializeNotifier(TokenCheckNotificationType, tokenCheckNotifier);
this.#initializeNotifier(FeatureStateChangeNotificationType, featureStateManager);
// notification handlers
connection.onNotification(DidChangeDocumentInActiveEditor, documentService.notificationHandler);
connection.onNotification(
DidChangeWorkspaceFoldersNotification.method,
didChangeWorkspaceFoldersHandler.notificationHandler,
);
// diagnostics publishers
this.#initializeDiagnosticsPublisher(securityDiagnosticsPublisher);
// custom handlers
this.#setupAiContextHandlers();
}
#initializeNotifier<T>(method: NotificationType<T>, notifier: Notifier<T>) {
notifier.init(createNotifyFn(this.#connection, method));
}
#initializeDiagnosticsPublisher(publisher: DiagnosticsPublisher) {
publisher.init(createDiagnosticsPublisherFn(this.#connection));
}
#setupAiContextHandlers() {
this.#connection.onRequest('$/gitlab/ai-context/query', async (query: AiContextQuery) => {
log.info(`recieved search query ${JSON.stringify(query)}`);
const results = await this.#aiContextAggregator.getContextForQuery(query);
log.info(`got back ${results.length}`);
return results;
});
this.#connection.onRequest('$/gitlab/ai-context/add', async (item: AiContextItem) => {
log.info(`recieved context item add request ${JSON.stringify(item)}`);
return this.#aiContextManager.addItem(item);
});
this.#connection.onRequest('$/gitlab/ai-context/remove', async (id: string) => {
log.info(`recieved context item add request ${JSON.stringify(id)}`);
return this.#aiContextManager.removeItem(id);
});
this.#connection.onRequest('$/gitlab/ai-context/current-items', async () => {
const currentItems = this.#aiContextManager.currentItems();
log.info(`returning ${currentItems.length} current items`);
return currentItems;
});
this.#connection.onRequest('$/gitlab/ai-context/retrieve', async () => {
const items = await this.#aiContextManager.retrieveItems();
log.info(`retrieved ${items.length} current items`);
return items;
});
}
}
References: |
You are a code assistant | Definition of 'getTreeAndTestFile' in file src/tests/unit/tree_sitter/test_utils.ts in project gitlab-lsp | Definition:
export const getTreeAndTestFile = async ({
fixturePath,
position,
languageId,
}: {
fixturePath: string;
position: Position;
languageId: LanguageServerLanguageId;
}) => {
const parser = new DesktopTreeSitterParser();
const fullText = await readFile(fixturePath, 'utf8');
const { prefix, suffix } = splitTextFileForPosition(fullText, position);
const documentContext = {
uri: fsPathToUri(fixturePath),
prefix,
suffix,
position,
languageId,
fileRelativePath: resolve(cwd(), fixturePath),
workspaceFolder: {
uri: 'file:///',
name: 'test',
},
} satisfies IDocContext;
const treeAndLanguage = await parser.parseFile(documentContext);
if (!treeAndLanguage) {
throw new Error('Failed to parse file');
}
return { prefix, suffix, fullText, treeAndLanguage };
};
/**
* Mimics the "prefix" and "suffix" according
* to the position in the text file.
*/
export const splitTextFileForPosition = (text: string, position: Position) => {
const lines = text.split('\n');
// Ensure the position is within bounds
const maxRow = lines.length - 1;
const row = Math.min(position.line, maxRow);
const maxColumn = lines[row]?.length || 0;
const column = Math.min(position.character, maxColumn);
// Get the part of the current line before the cursor and after the cursor
const prefixLine = lines[row].slice(0, column);
const suffixLine = lines[row].slice(column);
// Combine lines before the current row for the prefix
const prefixLines = lines.slice(0, row).concat(prefixLine);
const prefix = prefixLines.join('\n');
// Combine lines after the current row for the suffix
const suffixLines = [suffixLine].concat(lines.slice(row + 1));
const suffix = suffixLines.join('\n');
return { prefix, suffix };
};
References:
- src/tests/unit/tree_sitter/intent_resolver.test.ts:665
- src/tests/unit/tree_sitter/intent_resolver.test.ts:28
- src/tests/unit/tree_sitter/intent_resolver.test.ts:395
- src/tests/unit/tree_sitter/intent_resolver.test.ts:15 |
You are a code assistant | Definition of 'AImpl2' in file packages/lib_di/src/index.test.ts in project gitlab-lsp | Definition:
class AImpl2 implements A {
a = () => 'hello';
}
expect(() => container.instantiate(AImpl, AImpl2)).toThrow(
/The following interface IDs were used multiple times 'A' \(classes: AImpl,AImpl2\)/,
);
});
it('detects duplicate id with pre-existing instance', () => {
const aInstance = new AImpl();
const a = brandInstance(A, aInstance);
container.addInstances(a);
expect(() => container.instantiate(AImpl)).toThrow(/classes are clashing/);
});
it('detects missing dependencies', () => {
expect(() => container.instantiate(BImpl)).toThrow(
/Class BImpl \(interface B\) depends on interfaces \[A]/,
);
});
it('it uses existing instances as dependencies', () => {
const aInstance = new AImpl();
const a = brandInstance(A, aInstance);
container.addInstances(a);
container.instantiate(BImpl);
expect(container.get(B).b()).toBe('B(a)');
});
it("detects classes what aren't decorated with @Injectable", () => {
class AImpl2 implements A {
a = () => 'hello';
}
expect(() => container.instantiate(AImpl2)).toThrow(
/Classes \[AImpl2] are not decorated with @Injectable/,
);
});
it('detects circular dependencies', () => {
@Injectable(A, [C])
class ACircular implements A {
a = () => 'hello';
constructor(c: C) {
// eslint-disable-next-line no-unused-expressions
c;
}
}
expect(() => container.instantiate(ACircular, BImpl, CImpl)).toThrow(
/Circular dependency detected between interfaces \(A,C\), starting with 'A' \(class: ACircular\)./,
);
});
// this test ensures that we don't store any references to the classes and we instantiate them only once
it('does not instantiate classes from previous instantiate call', () => {
let globCount = 0;
@Injectable(A, [])
class Counter implements A {
counter = globCount;
constructor() {
globCount++;
}
a = () => this.counter.toString();
}
container.instantiate(Counter);
container.instantiate(BImpl);
expect(container.get(A).a()).toBe('0');
});
});
describe('get', () => {
it('returns an instance of the interfaceId', () => {
container.instantiate(AImpl);
expect(container.get(A)).toBeInstanceOf(AImpl);
});
it('throws an error for missing dependency', () => {
container.instantiate();
expect(() => container.get(A)).toThrow(/Instance for interface 'A' is not in the container/);
});
});
});
References: |
You are a code assistant | Definition of 'FixedTimeCircuitBreaker' in file src/common/circuit_breaker/fixed_time_circuit_breaker.ts in project gitlab-lsp | Definition:
export class FixedTimeCircuitBreaker implements CircuitBreaker {
#name: string;
#state: CircuitBreakerState = CircuitBreakerState.CLOSED;
readonly #maxErrorsBeforeBreaking: number;
readonly #breakTimeMs: number;
#errorCount = 0;
#eventEmitter = new EventEmitter();
#timeoutId: NodeJS.Timeout | null = null;
/**
* @param name identifier of the circuit breaker that will appear in the logs
* */
constructor(
name: string,
maxErrorsBeforeBreaking: number = MAX_ERRORS_BEFORE_CIRCUIT_BREAK,
breakTimeMs: number = CIRCUIT_BREAK_INTERVAL_MS,
) {
this.#name = name;
this.#maxErrorsBeforeBreaking = maxErrorsBeforeBreaking;
this.#breakTimeMs = breakTimeMs;
}
error() {
this.#errorCount += 1;
if (this.#errorCount >= this.#maxErrorsBeforeBreaking) {
this.#open();
}
}
#open() {
this.#state = CircuitBreakerState.OPEN;
log.warn(
`Excess errors detected, opening '${this.#name}' circuit breaker for ${this.#breakTimeMs / 1000} second(s).`,
);
this.#timeoutId = setTimeout(() => this.#close(), this.#breakTimeMs);
this.#eventEmitter.emit('open');
}
isOpen() {
return this.#state === CircuitBreakerState.OPEN;
}
#close() {
if (this.#state === CircuitBreakerState.CLOSED) {
return;
}
if (this.#timeoutId) {
clearTimeout(this.#timeoutId);
}
this.#state = CircuitBreakerState.CLOSED;
this.#eventEmitter.emit('close');
}
success() {
this.#errorCount = 0;
this.#close();
}
onOpen(listener: () => void): Disposable {
this.#eventEmitter.on('open', listener);
return { dispose: () => this.#eventEmitter.removeListener('open', listener) };
}
onClose(listener: () => void): Disposable {
this.#eventEmitter.on('close', listener);
return { dispose: () => this.#eventEmitter.removeListener('close', listener) };
}
}
References:
- src/common/circuit_breaker/fixed_time_circuit_breaker.test.ts:61
- src/common/circuit_breaker/fixed_time_circuit_breaker.test.ts:20
- src/common/message_handler.ts:77
- src/common/circuit_breaker/fixed_time_circuit_breaker.test.ts:12
- src/common/circuit_breaker/fixed_time_circuit_breaker.test.ts:37
- src/common/circuit_breaker/fixed_time_circuit_breaker.test.ts:7
- src/common/tracking/instance_tracker.ts:35
- src/common/circuit_breaker/fixed_time_circuit_breaker.test.ts:49
- src/common/circuit_breaker/fixed_time_circuit_breaker.test.ts:28
- src/common/suggestion/suggestion_service.ts:127 |
You are a code assistant | Definition of 'GraphQLRequest' in file packages/webview_duo_chat/src/plugin/types.ts in project gitlab-lsp | Definition:
interface GraphQLRequest<_TReturnType> {
type: 'graphql';
query: string;
/** Options passed to the GraphQL query */
variables: Record<string, unknown>;
supportedSinceInstanceVersion?: SupportedSinceInstanceVersion;
}
interface PostRequest<_TReturnType> extends BaseRestRequest<_TReturnType> {
method: 'POST';
body?: unknown;
}
/**
* The response body is parsed as JSON and it's up to the client to ensure it
* matches the TReturnType
*/
interface GetRequest<_TReturnType> extends BaseRestRequest<_TReturnType> {
method: 'GET';
searchParams?: Record<string, string>;
supportedSinceInstanceVersion?: SupportedSinceInstanceVersion;
}
export type ApiRequest<_TReturnType> =
| GetRequest<_TReturnType>
| PostRequest<_TReturnType>
| GraphQLRequest<_TReturnType>;
export interface GitLabApiClient {
fetchFromApi<TReturnType>(request: ApiRequest<TReturnType>): Promise<TReturnType>;
connectToCable(): Promise<Cable>;
}
References: |
You are a code assistant | Definition of 'UnhandledHandlerError' in file packages/lib_handler_registry/src/errors/unhandled_handler_error.ts in project gitlab-lsp | Definition:
export class UnhandledHandlerError extends Error {
readonly type = 'UnhandledHandlerError';
originalError: Error;
constructor(handlerId: string, originalError: Error) {
super(`Unhandled error in handler '${handlerId}': ${originalError.message}`);
this.name = 'UnhandledHandlerError';
this.originalError = originalError;
this.stack = originalError.stack;
}
}
References:
- packages/lib_handler_registry/src/registry/simple_registry.ts:39 |
You are a code assistant | Definition of 'ChangeConfigOptions' in file src/common/message_handler.ts in project gitlab-lsp | Definition:
export type ChangeConfigOptions = { settings: IClientConfig };
export type CustomInitializeParams = InitializeParams & {
initializationOptions?: IClientContext;
};
export const WORKFLOW_MESSAGE_NOTIFICATION = '$/gitlab/workflowMessage';
export interface MessageHandlerOptions {
telemetryTracker: TelemetryTracker;
configService: ConfigService;
connection: Connection;
featureFlagService: FeatureFlagService;
duoProjectAccessCache: DuoProjectAccessCache;
virtualFileSystemService: VirtualFileSystemService;
workflowAPI: WorkflowAPI | undefined;
}
export interface ITelemetryNotificationParams {
category: 'code_suggestions';
action: TRACKING_EVENTS;
context: {
trackingId: string;
optionId?: number;
};
}
export interface IStartWorkflowParams {
goal: string;
image: string;
}
export const waitMs = (msToWait: number) =>
new Promise((resolve) => {
setTimeout(resolve, msToWait);
});
/* CompletionRequest represents LS client's request for either completion or inlineCompletion */
export interface CompletionRequest {
textDocument: TextDocumentIdentifier;
position: Position;
token: CancellationToken;
inlineCompletionContext?: InlineCompletionContext;
}
export class MessageHandler {
#configService: ConfigService;
#tracker: TelemetryTracker;
#connection: Connection;
#circuitBreaker = new FixedTimeCircuitBreaker('Code Suggestion Requests');
#subscriptions: Disposable[] = [];
#duoProjectAccessCache: DuoProjectAccessCache;
#featureFlagService: FeatureFlagService;
#workflowAPI: WorkflowAPI | undefined;
#virtualFileSystemService: VirtualFileSystemService;
constructor({
telemetryTracker,
configService,
connection,
featureFlagService,
duoProjectAccessCache,
virtualFileSystemService,
workflowAPI = undefined,
}: MessageHandlerOptions) {
this.#configService = configService;
this.#tracker = telemetryTracker;
this.#connection = connection;
this.#featureFlagService = featureFlagService;
this.#workflowAPI = workflowAPI;
this.#subscribeToCircuitBreakerEvents();
this.#virtualFileSystemService = virtualFileSystemService;
this.#duoProjectAccessCache = duoProjectAccessCache;
}
didChangeConfigurationHandler = async (
{ settings }: ChangeConfigOptions = { settings: {} },
): Promise<void> => {
this.#configService.merge({
client: settings,
});
// update Duo project access cache
await this.#duoProjectAccessCache.updateCache({
baseUrl: this.#configService.get('client.baseUrl') ?? '',
workspaceFolders: this.#configService.get('client.workspaceFolders') ?? [],
});
await this.#virtualFileSystemService.initialize(
this.#configService.get('client.workspaceFolders') ?? [],
);
};
telemetryNotificationHandler = async ({
category,
action,
context,
}: ITelemetryNotificationParams) => {
if (category === CODE_SUGGESTIONS_CATEGORY) {
const { trackingId, optionId } = context;
if (
trackingId &&
canClientTrackEvent(this.#configService.get('client.telemetry.actions'), action)
) {
switch (action) {
case TRACKING_EVENTS.ACCEPTED:
if (optionId) {
this.#tracker.updateCodeSuggestionsContext(trackingId, { acceptedOption: optionId });
}
this.#tracker.updateSuggestionState(trackingId, TRACKING_EVENTS.ACCEPTED);
break;
case TRACKING_EVENTS.REJECTED:
this.#tracker.updateSuggestionState(trackingId, TRACKING_EVENTS.REJECTED);
break;
case TRACKING_EVENTS.CANCELLED:
this.#tracker.updateSuggestionState(trackingId, TRACKING_EVENTS.CANCELLED);
break;
case TRACKING_EVENTS.SHOWN:
this.#tracker.updateSuggestionState(trackingId, TRACKING_EVENTS.SHOWN);
break;
case TRACKING_EVENTS.NOT_PROVIDED:
this.#tracker.updateSuggestionState(trackingId, TRACKING_EVENTS.NOT_PROVIDED);
break;
default:
break;
}
}
}
};
onShutdownHandler = () => {
this.#subscriptions.forEach((subscription) => subscription?.dispose());
};
#subscribeToCircuitBreakerEvents() {
this.#subscriptions.push(
this.#circuitBreaker.onOpen(() => this.#connection.sendNotification(API_ERROR_NOTIFICATION)),
);
this.#subscriptions.push(
this.#circuitBreaker.onClose(() =>
this.#connection.sendNotification(API_RECOVERY_NOTIFICATION),
),
);
}
async #sendWorkflowErrorNotification(message: string) {
await this.#connection.sendNotification(WORKFLOW_MESSAGE_NOTIFICATION, {
message,
type: 'error',
});
}
startWorkflowNotificationHandler = async ({ goal, image }: IStartWorkflowParams) => {
const duoWorkflow = this.#featureFlagService.isClientFlagEnabled(
ClientFeatureFlags.DuoWorkflow,
);
if (!duoWorkflow) {
await this.#sendWorkflowErrorNotification(`The Duo Workflow feature is not enabled`);
return;
}
if (!this.#workflowAPI) {
await this.#sendWorkflowErrorNotification('Workflow API is not configured for the LSP');
return;
}
try {
await this.#workflowAPI?.runWorkflow(goal, image);
} catch (e) {
log.error('Error in running workflow', e);
await this.#sendWorkflowErrorNotification(`Error occurred while running workflow ${e}`);
}
};
}
References:
- src/common/message_handler.ts:111 |
You are a code assistant | Definition of 'AiContextPolicyManager' in file src/common/ai_context_management_2/ai_policy_management.ts in project gitlab-lsp | Definition:
export interface AiContextPolicyManager extends DefaultAiPolicyManager {}
export const AiContextPolicyManager =
createInterfaceId<AiContextPolicyManager>('AiContextAggregator');
export type AiContextQuery = {
query: string;
providerType: 'file';
textDocument?: TextDocument;
workspaceFolders: WorkspaceFolder[];
};
@Injectable(AiContextPolicyManager, [DuoProjectPolicy])
export class DefaultAiPolicyManager {
#policies: AiContextPolicy[] = [];
constructor(duoProjectPolicy: DuoProjectPolicy) {
this.#policies.push(duoProjectPolicy);
}
async runPolicies(aiContextProviderItem: AiContextProviderItem) {
const results = await Promise.all(
this.#policies.map(async (policy) => {
return policy.isAllowed(aiContextProviderItem);
}),
);
const disallowedResults = results.filter((result) => !result.allowed);
if (disallowedResults.length > 0) {
const reasons = disallowedResults.map((result) => result.reason).filter(Boolean);
return { allowed: false, reasons: reasons as string[] };
}
return { allowed: true };
}
}
References:
- src/common/ai_context_management_2/ai_context_aggregator.ts:26
- src/common/ai_context_management_2/ai_context_aggregator.ts:30 |
You are a code assistant | Definition of 'ifVersionGte' in file packages/webview_duo_chat/src/plugin/port/utils/if_version_gte.ts in project gitlab-lsp | Definition:
export function ifVersionGte<T>(
current: string | undefined,
minimumRequiredVersion: string,
then: () => T,
otherwise: () => T,
): T {
if (!valid(minimumRequiredVersion)) {
throw new Error(`minimumRequiredVersion argument ${minimumRequiredVersion} isn't valid`);
}
const parsedCurrent = coerce(current);
if (!parsedCurrent) {
log.warn(
`Could not parse version from "${current}", running logic for the latest GitLab version`,
);
return then();
}
if (gte(parsedCurrent, minimumRequiredVersion)) return then();
return otherwise();
}
References:
- packages/webview_duo_chat/src/plugin/port/chat/gitlab_chat_api.ts:260
- packages/webview_duo_chat/src/plugin/port/utils/if_version_gte.test.ts:27
- packages/webview_duo_chat/src/plugin/port/utils/if_version_gte.test.ts:7
- packages/webview_duo_chat/src/plugin/port/utils/if_version_gte.test.ts:12
- packages/webview_duo_chat/src/plugin/port/utils/if_version_gte.test.ts:17
- packages/webview_duo_chat/src/plugin/port/utils/if_version_gte.test.ts:22 |
You are a code assistant | Definition of 'syntaxHighlight' in file packages/webview_duo_chat/src/app/render_gfm.ts in project gitlab-lsp | Definition:
function syntaxHighlight(els: HTMLElement[]) {
if (!els || els.length === 0) return;
els.forEach((el) => {
if (el.classList && el.classList.contains('js-syntax-highlight') && !el.dataset.highlighted) {
hljs.highlightElement(el);
// This is how the dom elements are designed to be manipulated
el.dataset.highlighted = 'true';
}
});
}
// this is a partial implementation of `renderGFM` concerned only with syntax highlighting.
// for all possible renderers, check
// https://gitlab.com/gitlab-org/gitlab/-/blob/774ecc1f2b15a581e8eab6441de33585c9691c82/app/assets/javascripts/behaviors/markdown/render_gfm.js#L18-40
export function renderGFM(element: HTMLElement) {
if (!element) {
return;
}
const highlightEls = Array.from(
element.querySelectorAll('.js-syntax-highlight'),
) as HTMLElement[];
syntaxHighlight(highlightEls);
}
References:
- packages/webview_duo_chat/src/app/render_gfm.ts:35 |
You are a code assistant | Definition of 'fetch' in file src/common/fetch.ts in project gitlab-lsp | Definition:
fetch(input: RequestInfo | URL, init?: RequestInit): Promise<Response>;
fetchBase(input: RequestInfo | URL, init?: RequestInit): Promise<Response>;
delete(input: RequestInfo | URL, init?: RequestInit): Promise<Response>;
get(input: RequestInfo | URL, init?: RequestInit): Promise<Response>;
post(input: RequestInfo | URL, init?: RequestInit): Promise<Response>;
put(input: RequestInfo | URL, init?: RequestInit): Promise<Response>;
updateAgentOptions(options: FetchAgentOptions): void;
streamFetch(url: string, body: string, headers: FetchHeaders): AsyncGenerator<string, void, void>;
}
export const LsFetch = createInterfaceId<LsFetch>('LsFetch');
export class FetchBase implements LsFetch {
updateRequestInit(method: string, init?: RequestInit): RequestInit {
if (typeof init === 'undefined') {
// eslint-disable-next-line no-param-reassign
init = { method };
} else {
// eslint-disable-next-line no-param-reassign
init.method = method;
}
return init;
}
async initialize(): Promise<void> {}
async destroy(): Promise<void> {}
async fetch(input: RequestInfo | URL, init?: RequestInit): Promise<Response> {
return fetch(input, init);
}
async *streamFetch(
/* eslint-disable @typescript-eslint/no-unused-vars */
_url: string,
_body: string,
_headers: FetchHeaders,
/* eslint-enable @typescript-eslint/no-unused-vars */
): AsyncGenerator<string, void, void> {
// Stub. Should delegate to the node or browser fetch implementations
throw new Error('Not implemented');
yield '';
}
async delete(input: RequestInfo | URL, init?: RequestInit): Promise<Response> {
return this.fetch(input, this.updateRequestInit('DELETE', init));
}
async get(input: RequestInfo | URL, init?: RequestInit): Promise<Response> {
return this.fetch(input, this.updateRequestInit('GET', init));
}
async post(input: RequestInfo | URL, init?: RequestInit): Promise<Response> {
return this.fetch(input, this.updateRequestInit('POST', init));
}
async put(input: RequestInfo | URL, init?: RequestInit): Promise<Response> {
return this.fetch(input, this.updateRequestInit('PUT', init));
}
async fetchBase(input: RequestInfo | URL, init?: RequestInit): Promise<Response> {
// eslint-disable-next-line no-underscore-dangle, no-restricted-globals
const _global = typeof global === 'undefined' ? self : global;
return _global.fetch(input, init);
}
// eslint-disable-next-line @typescript-eslint/no-unused-vars
updateAgentOptions(_opts: FetchAgentOptions): void {}
}
References:
- src/common/security_diagnostics_publisher.ts:101
- src/node/fetch.ts:214
- src/common/suggestion_client/direct_connection_client.ts:104
- src/common/fetch.ts:48 |
You are a code assistant | Definition of 'ConfigService' in file src/common/config_service.ts in project gitlab-lsp | Definition:
export const ConfigService = createInterfaceId<ConfigService>('ConfigService');
@Injectable(ConfigService, [])
export class DefaultConfigService implements ConfigService {
#config: IConfig;
#eventEmitter = new EventEmitter();
constructor() {
this.#config = {
client: {
baseUrl: GITLAB_API_BASE_URL,
codeCompletion: {
enableSecretRedaction: true,
},
telemetry: {
enabled: true,
},
logLevel: LOG_LEVEL.INFO,
ignoreCertificateErrors: false,
httpAgentOptions: {},
},
};
}
get: TypedGetter<IConfig> = (key?: string) => {
return key ? get(this.#config, key) : this.#config;
};
set: TypedSetter<IConfig> = (key: string, value: unknown) => {
set(this.#config, key, value);
this.#triggerChange();
};
onConfigChange(listener: (config: IConfig) => void): Disposable {
this.#eventEmitter.on('configChange', listener);
return { dispose: () => this.#eventEmitter.removeListener('configChange', listener) };
}
#triggerChange() {
this.#eventEmitter.emit('configChange', this.#config);
}
merge(newConfig: Partial<IConfig>) {
mergeWith(this.#config, newConfig, (target, src) => (isArray(target) ? src : undefined));
this.#triggerChange();
}
}
References:
- src/node/duo_workflow/desktop_workflow_runner.test.ts:15
- src/common/api.ts:135
- src/common/core/handlers/did_change_workspace_folders_handler.test.ts:13
- src/common/tracking/snowplow_tracker.ts:131
- src/common/secret_redaction/index.ts:17
- src/common/tracking/instance_tracker.ts:51
- src/common/suggestion/suggestions_cache.ts:50
- src/browser/tree_sitter/index.ts:13
- src/browser/tree_sitter/index.test.ts:12
- src/common/secret_redaction/index.ts:19
- src/node/duo_workflow/desktop_workflow_runner.ts:53
- src/common/core/handlers/did_change_workspace_folders_handler.ts:16
- src/common/suggestion/suggestion_service.test.ts:177
- src/common/secret_redaction/redactor.test.ts:21
- src/common/log.ts:65
- src/common/suggestion/suggestion_service.ts:117
- src/common/feature_flags.test.ts:14
- src/common/security_diagnostics_publisher.ts:41
- src/common/suggestion/supported_languages_service.test.ts:8
- src/common/api.test.ts:38
- src/common/suggestion/suggestion_service.ts:78
- src/common/message_handler.ts:35
- src/common/feature_flags.ts:45
- src/common/message_handler.test.ts:202
- src/common/advanced_context/helpers.ts:22
- src/common/tracking/instance_tracker.ts:37
- src/common/suggestion/suggestion_service.test.ts:439
- src/common/message_handler.test.ts:85
- src/common/feature_state/project_duo_acces_check.ts:42
- src/common/core/handlers/initialize_handler.test.ts:15
- src/common/connection.ts:25
- src/common/suggestion/supported_languages_service.ts:34
- src/common/security_diagnostics_publisher.test.ts:18
- src/common/suggestion/suggestions_cache.ts:52
- src/common/advanced_context/advanced_context_service.ts:26
- src/common/core/handlers/initialize_handler.ts:19
- src/common/suggestion_client/direct_connection_client.test.ts:26
- src/common/message_handler.ts:71
- src/common/suggestion_client/direct_connection_client.ts:32
- src/common/core/handlers/did_change_workspace_folders_handler.ts:14
- src/common/feature_flags.ts:49
- src/common/tracking/snowplow_tracker.ts:160
- src/common/advanced_context/advanced_context_service.ts:33
- src/browser/tree_sitter/index.ts:11
- src/common/api.ts:131
- src/common/core/handlers/initialize_handler.ts:21
- src/common/suggestion_client/direct_connection_client.ts:54
- src/common/suggestion/supported_languages_service.ts:38
- src/common/feature_state/project_duo_acces_check.ts:34 |
You are a code assistant | Definition of 'SecretRedactor' in file src/common/secret_redaction/index.ts in project gitlab-lsp | Definition:
export interface SecretRedactor extends IDocTransformer {
redactSecrets(raw: string): string;
}
export const SecretRedactor = createInterfaceId<SecretRedactor>('SecretRedactor');
@Injectable(SecretRedactor, [ConfigService])
export class DefaultSecretRedactor implements SecretRedactor {
#rules: IGitleaksRule[] = [];
#configService: ConfigService;
constructor(configService: ConfigService) {
this.#rules = rules.map((rule) => ({
...rule,
compiledRegex: new RegExp(convertToJavaScriptRegex(rule.regex), 'gmi'),
}));
this.#configService = configService;
}
transform(context: IDocContext): IDocContext {
if (this.#configService.get('client.codeCompletion.enableSecretRedaction')) {
return {
prefix: this.redactSecrets(context.prefix),
suffix: this.redactSecrets(context.suffix),
fileRelativePath: context.fileRelativePath,
position: context.position,
uri: context.uri,
languageId: context.languageId,
workspaceFolder: context.workspaceFolder,
};
}
return context;
}
redactSecrets(raw: string): string {
return this.#rules.reduce((redacted: string, rule: IGitleaksRule) => {
return this.#redactRuleSecret(redacted, rule);
}, raw);
}
#redactRuleSecret(str: string, rule: IGitleaksRule): string {
if (!rule.compiledRegex) return str;
if (!this.#keywordHit(rule, str)) {
return str;
}
const matches = [...str.matchAll(rule.compiledRegex)];
return matches.reduce((redacted: string, match: RegExpMatchArray) => {
const secret = match[rule.secretGroup ?? 0];
return redacted.replace(secret, '*'.repeat(secret.length));
}, str);
}
#keywordHit(rule: IGitleaksRule, raw: string) {
if (!rule.keywords?.length) {
return true;
}
for (const keyword of rule.keywords) {
if (raw.toLowerCase().includes(keyword)) {
return true;
}
}
return false;
}
}
References:
- src/common/ai_context_management_2/retrievers/ai_file_context_retriever.ts:18
- src/common/document_transformer_service.ts:81
- src/common/secret_redaction/redactor.test.ts:20 |
You are a code assistant | Definition of 'FileSystemEventListener' in file src/common/services/fs/virtual_file_service.ts in project gitlab-lsp | Definition:
export interface FileSystemEventListener {
<T extends VirtualFileSystemEvents>(eventType: T, data: FileSystemEventMap[T]): void;
}
export type VirtualFileSystemService = typeof DefaultVirtualFileSystemService.prototype;
export const VirtualFileSystemService = createInterfaceId<VirtualFileSystemService>(
'VirtualFileSystemService',
);
@Injectable(VirtualFileSystemService, [DirectoryWalker])
export class DefaultVirtualFileSystemService {
#directoryWalker: DirectoryWalker;
#emitter = new EventEmitter();
constructor(directoryWalker: DirectoryWalker) {
this.#directoryWalker = directoryWalker;
}
#handleFileChange: FileChangeHandler = (event, workspaceFolder, filePath) => {
const fileUri = fsPathToUri(filePath);
this.#emitFileSystemEvent(VirtualFileSystemEvents.WorkspaceFileUpdate, {
event,
fileUri,
workspaceFolder,
});
};
async initialize(workspaceFolders: WorkspaceFolder[]): Promise<void> {
await Promise.all(
workspaceFolders.map(async (workspaceFolder) => {
const files = await this.#directoryWalker.findFilesForDirectory({
directoryUri: workspaceFolder.uri,
});
this.#emitFileSystemEvent(VirtualFileSystemEvents.WorkspaceFilesUpdate, {
files,
workspaceFolder,
});
this.#directoryWalker.setupFileWatcher(workspaceFolder, this.#handleFileChange);
}),
);
}
#emitFileSystemEvent<T extends VirtualFileSystemEvents>(
eventType: T,
data: FileSystemEventMap[T],
) {
this.#emitter.emit(FILE_SYSTEM_EVENT_NAME, eventType, data);
}
onFileSystemEvent(listener: FileSystemEventListener) {
this.#emitter.on(FILE_SYSTEM_EVENT_NAME, listener);
return {
dispose: () => this.#emitter.removeListener(FILE_SYSTEM_EVENT_NAME, listener),
};
}
}
References:
- src/common/services/fs/virtual_file_service.ts:82 |
You are a code assistant | Definition of 'BrowserTreeSitterParser' in file src/browser/tree_sitter/index.ts in project gitlab-lsp | Definition:
export class BrowserTreeSitterParser extends TreeSitterParser {
#configService: ConfigService;
constructor(configService: ConfigService) {
super({ languages: [] });
this.#configService = configService;
}
getLanguages() {
return this.languages;
}
getLoadState() {
return this.loadState;
}
async init(): Promise<void> {
const baseAssetsUrl = this.#configService.get('client.baseAssetsUrl');
this.languages = this.buildTreeSitterInfoByExtMap([
{
name: 'bash',
extensions: ['.sh', '.bash', '.bashrc', '.bash_profile'],
wasmPath: resolveGrammarAbsoluteUrl('vendor/grammars/tree-sitter-c.wasm', baseAssetsUrl),
nodeModulesPath: 'tree-sitter-c',
},
{
name: 'c',
extensions: ['.c'],
wasmPath: resolveGrammarAbsoluteUrl('vendor/grammars/tree-sitter-c.wasm', baseAssetsUrl),
nodeModulesPath: 'tree-sitter-c',
},
{
name: 'cpp',
extensions: ['.cpp'],
wasmPath: resolveGrammarAbsoluteUrl('vendor/grammars/tree-sitter-cpp.wasm', baseAssetsUrl),
nodeModulesPath: 'tree-sitter-cpp',
},
{
name: 'c_sharp',
extensions: ['.cs'],
wasmPath: resolveGrammarAbsoluteUrl(
'vendor/grammars/tree-sitter-c_sharp.wasm',
baseAssetsUrl,
),
nodeModulesPath: 'tree-sitter-c-sharp',
},
{
name: 'css',
extensions: ['.css'],
wasmPath: resolveGrammarAbsoluteUrl('vendor/grammars/tree-sitter-css.wasm', baseAssetsUrl),
nodeModulesPath: 'tree-sitter-css',
},
{
name: 'go',
extensions: ['.go'],
wasmPath: resolveGrammarAbsoluteUrl('vendor/grammars/tree-sitter-go.wasm', baseAssetsUrl),
nodeModulesPath: 'tree-sitter-go',
},
{
name: 'html',
extensions: ['.html'],
wasmPath: resolveGrammarAbsoluteUrl('vendor/grammars/tree-sitter-html.wasm', baseAssetsUrl),
nodeModulesPath: 'tree-sitter-html',
},
{
name: 'java',
extensions: ['.java'],
wasmPath: resolveGrammarAbsoluteUrl('vendor/grammars/tree-sitter-java.wasm', baseAssetsUrl),
nodeModulesPath: 'tree-sitter-java',
},
{
name: 'javascript',
extensions: ['.js'],
wasmPath: resolveGrammarAbsoluteUrl(
'vendor/grammars/tree-sitter-javascript.wasm',
baseAssetsUrl,
),
nodeModulesPath: 'tree-sitter-javascript',
},
{
name: 'powershell',
extensions: ['.ps1'],
wasmPath: resolveGrammarAbsoluteUrl(
'vendor/grammars/tree-sitter-powershell.wasm',
baseAssetsUrl,
),
nodeModulesPath: 'tree-sitter-powershell',
},
{
name: 'python',
extensions: ['.py'],
wasmPath: resolveGrammarAbsoluteUrl(
'vendor/grammars/tree-sitter-python.wasm',
baseAssetsUrl,
),
nodeModulesPath: 'tree-sitter-python',
},
{
name: 'ruby',
extensions: ['.rb'],
wasmPath: resolveGrammarAbsoluteUrl('vendor/grammars/tree-sitter-ruby.wasm', baseAssetsUrl),
nodeModulesPath: 'tree-sitter-ruby',
},
// TODO: Parse throws an error - investigate separately
// {
// name: 'sql',
// extensions: ['.sql'],
// wasmPath: resolveGrammarAbsoluteUrl('vendor/grammars/tree-sitter-sql.wasm', baseAssetsUrl),
// nodeModulesPath: 'tree-sitter-sql',
// },
{
name: 'scala',
extensions: ['.scala'],
wasmPath: resolveGrammarAbsoluteUrl(
'vendor/grammars/tree-sitter-scala.wasm',
baseAssetsUrl,
),
nodeModulesPath: 'tree-sitter-scala',
},
{
name: 'typescript',
extensions: ['.ts'],
wasmPath: resolveGrammarAbsoluteUrl(
'vendor/grammars/tree-sitter-typescript.wasm',
baseAssetsUrl,
),
nodeModulesPath: 'tree-sitter-typescript/typescript',
},
// TODO: Parse throws an error - investigate separately
// {
// name: 'hcl', // terraform, terragrunt
// extensions: ['.tf', '.hcl'],
// wasmPath: resolveGrammarAbsoluteUrl(
// 'vendor/grammars/tree-sitter-hcl.wasm',
// baseAssetsUrl,
// ),
// nodeModulesPath: 'tree-sitter-hcl',
// },
{
name: 'json',
extensions: ['.json'],
wasmPath: resolveGrammarAbsoluteUrl('vendor/grammars/tree-sitter-json.wasm', baseAssetsUrl),
nodeModulesPath: 'tree-sitter-json',
},
]);
try {
await Parser.init({
locateFile(scriptName: string) {
return resolveGrammarAbsoluteUrl(`node/${scriptName}`, baseAssetsUrl);
},
});
log.debug('BrowserTreeSitterParser: Initialized tree-sitter parser.');
this.loadState = TreeSitterParserLoadState.READY;
} catch (err) {
log.warn('BrowserTreeSitterParser: Error initializing tree-sitter parsers.', err);
this.loadState = TreeSitterParserLoadState.ERRORED;
}
}
}
References:
- src/browser/tree_sitter/index.test.ts:11
- src/browser/main.ts:114
- src/browser/tree_sitter/index.test.ts:20 |
You are a code assistant | Definition of 'loadIgnoreFiles' in file src/common/git/ignore_manager.ts in project gitlab-lsp | Definition:
async loadIgnoreFiles(files: string[]): Promise<void> {
await this.#loadRootGitignore();
const gitignoreFiles = files.filter(
(file) => path.basename(file) === '.gitignore' && file !== '.gitignore',
);
await Promise.all(gitignoreFiles.map((file) => this.#loadGitignore(file)));
}
async #loadRootGitignore(): Promise<void> {
const rootGitignorePath = path.join(this.repoUri, '.gitignore');
try {
const content = await fs.readFile(rootGitignorePath, 'utf-8');
this.#addPatternsToTrie([], content);
} catch (error) {
if ((error as NodeJS.ErrnoException).code !== 'ENOENT') {
console.warn(`Failed to read root .gitignore file: ${rootGitignorePath}`, error);
}
}
}
async #loadGitignore(filePath: string): Promise<void> {
try {
const content = await fs.readFile(filePath, 'utf-8');
const relativePath = path.relative(this.repoUri, path.dirname(filePath));
const pathParts = relativePath.split(path.sep);
this.#addPatternsToTrie(pathParts, content);
} catch (error) {
console.warn(`Failed to read .gitignore file: ${filePath}`, error);
}
}
#addPatternsToTrie(pathParts: string[], content: string): void {
const patterns = content
.split('\n')
.map((rule) => rule.trim())
.filter((rule) => rule && !rule.startsWith('#'));
for (const pattern of patterns) {
this.#ignoreTrie.addPattern(pathParts, pattern);
}
}
isIgnored(filePath: string): boolean {
const relativePath = path.relative(this.repoUri, filePath);
const pathParts = relativePath.split(path.sep);
return this.#ignoreTrie.isIgnored(pathParts);
}
dispose(): void {
this.#ignoreTrie.dispose();
}
}
References: |
You are a code assistant | Definition of 'constructor' in file src/common/document_transformer_service.ts in project gitlab-lsp | Definition:
constructor(documents: LsTextDocuments, secretRedactor: SecretRedactor) {
this.#documents = documents;
this.#transformers.push(secretRedactor);
}
get(uri: string) {
return this.#documents.get(uri);
}
getContext(
uri: string,
position: Position,
workspaceFolders: WorkspaceFolder[],
completionContext?: InlineCompletionContext,
): IDocContext | undefined {
const doc = this.get(uri);
if (doc === undefined) {
return undefined;
}
return this.transform(getDocContext(doc, position, workspaceFolders, completionContext));
}
transform(context: IDocContext): IDocContext {
return this.#transformers.reduce((ctx, transformer) => transformer.transform(ctx), context);
}
}
export function getDocContext(
document: TextDocument,
position: Position,
workspaceFolders: WorkspaceFolder[],
completionContext?: InlineCompletionContext,
): IDocContext {
let prefix: string;
if (completionContext?.selectedCompletionInfo) {
const { selectedCompletionInfo } = completionContext;
const range = sanitizeRange(selectedCompletionInfo.range);
prefix = `${document.getText({
start: document.positionAt(0),
end: range.start,
})}${selectedCompletionInfo.text}`;
} else {
prefix = document.getText({ start: document.positionAt(0), end: position });
}
const suffix = document.getText({
start: position,
end: document.positionAt(document.getText().length),
});
const workspaceFolder = getMatchingWorkspaceFolder(document.uri, workspaceFolders);
const fileRelativePath = getRelativePath(document.uri, workspaceFolder);
return {
prefix,
suffix,
fileRelativePath,
position,
uri: document.uri,
languageId: document.languageId,
workspaceFolder,
};
}
References: |
You are a code assistant | Definition of 'on' in file packages/lib_webview_transport_socket_io/src/socket_io_webview_transport.ts in project gitlab-lsp | Definition:
on<K extends keyof MessagesToServer>(
type: K,
callback: TransportMessageHandler<MessagesToServer[K]>,
): Disposable {
this.#messageEmitter.on(type, callback as WebviewTransportEventEmitterMessages[K]);
return {
dispose: () =>
this.#messageEmitter.off(type, callback as WebviewTransportEventEmitterMessages[K]),
};
}
dispose() {
this.#messageEmitter.removeAllListeners();
for (const connection of this.#connections.values()) {
connection.disconnect();
}
this.#connections.clear();
}
}
References: |
You are a code assistant | Definition of 'extractURL' in file src/common/utils/extract_url.ts in project gitlab-lsp | Definition:
export function extractURL(input: RequestInfo | URL): string {
if (input instanceof URL) {
return input.toString();
}
if (typeof input === 'string') {
return input;
}
return input.url;
}
References:
- src/common/fetch_error.ts:82 |
You are a code assistant | Definition of 'fetch' in file src/node/fetch.ts in project gitlab-lsp | Definition:
async fetch(input: RequestInfo | URL, init?: RequestInit): Promise<Response> {
if (!this.#initialized) {
throw new Error('LsFetch not initialized. Make sure LsFetch.initialize() was called.');
}
try {
return await this.#fetchLogged(input, {
signal: AbortSignal.timeout(REQUEST_TIMEOUT_MILLISECONDS),
...init,
agent: this.#getAgent(input),
});
} catch (e) {
if (hasName(e) && e.name === 'AbortError') {
throw new TimeoutError(input);
}
throw e;
}
}
updateAgentOptions({ ignoreCertificateErrors, ca, cert, certKey }: FetchAgentOptions): void {
let fileOptions = {};
try {
fileOptions = {
...(ca ? { ca: fs.readFileSync(ca) } : {}),
...(cert ? { cert: fs.readFileSync(cert) } : {}),
...(certKey ? { key: fs.readFileSync(certKey) } : {}),
};
} catch (err) {
log.error('Error reading https agent options from file', err);
}
const newOptions: LsAgentOptions = {
rejectUnauthorized: !ignoreCertificateErrors,
...fileOptions,
};
if (isEqual(newOptions, this.#agentOptions)) {
// new and old options are the same, nothing to do
return;
}
this.#agentOptions = newOptions;
this.#httpsAgent = this.#createHttpsAgent();
if (this.#proxy) {
this.#proxy = this.#createProxyAgent();
}
}
async *streamFetch(
url: string,
body: string,
headers: FetchHeaders,
): AsyncGenerator<string, void, void> {
let buffer = '';
const decoder = new TextDecoder();
async function* readStream(
stream: ReadableStream<Uint8Array>,
): AsyncGenerator<string, void, void> {
for await (const chunk of stream) {
buffer += decoder.decode(chunk);
yield buffer;
}
}
const response: Response = await this.fetch(url, {
method: 'POST',
headers,
body,
});
await handleFetchError(response, 'Code Suggestions Streaming');
if (response.body) {
// Note: Using (node:stream).ReadableStream as it supports async iterators
yield* readStream(response.body as ReadableStream);
}
}
#createHttpsAgent(): https.Agent {
const agentOptions = {
...this.#agentOptions,
keepAlive: true,
};
log.debug(
`fetch: https agent with options initialized ${JSON.stringify(
this.#sanitizeAgentOptions(agentOptions),
)}.`,
);
return new https.Agent(agentOptions);
}
#createProxyAgent(): ProxyAgent {
log.debug(
`fetch: proxy agent with options initialized ${JSON.stringify(
this.#sanitizeAgentOptions(this.#agentOptions),
)}.`,
);
return new ProxyAgent(this.#agentOptions);
}
async #fetchLogged(input: RequestInfo | URL, init: LsRequestInit): Promise<Response> {
const start = Date.now();
const url = this.#extractURL(input);
if (init.agent === httpAgent) {
log.debug(`fetch: request for ${url} made with http agent.`);
} else {
const type = init.agent === this.#proxy ? 'proxy' : 'https';
log.debug(`fetch: request for ${url} made with ${type} agent.`);
}
try {
const resp = await fetch(input, init);
const duration = Date.now() - start;
log.debug(`fetch: request to ${url} returned HTTP ${resp.status} after ${duration} ms`);
return resp;
} catch (e) {
const duration = Date.now() - start;
log.debug(`fetch: request to ${url} threw an exception after ${duration} ms`);
log.error(`fetch: request to ${url} failed with:`, e);
throw e;
}
}
#getAgent(input: RequestInfo | URL): ProxyAgent | https.Agent | http.Agent {
if (this.#proxy) {
return this.#proxy;
}
if (input.toString().startsWith('https://')) {
return this.#httpsAgent;
}
return httpAgent;
}
#extractURL(input: RequestInfo | URL): string {
if (input instanceof URL) {
return input.toString();
}
if (typeof input === 'string') {
return input;
}
return input.url;
}
#sanitizeAgentOptions(agentOptions: LsAgentOptions) {
const { ca, cert, key, ...options } = agentOptions;
return {
...options,
...(ca ? { ca: '<hidden>' } : {}),
...(cert ? { cert: '<hidden>' } : {}),
...(key ? { key: '<hidden>' } : {}),
};
}
}
References:
- src/common/security_diagnostics_publisher.ts:101
- src/node/fetch.ts:214
- src/common/suggestion_client/direct_connection_client.ts:104
- src/common/fetch.ts:48 |
You are a code assistant | Definition of 'WorkspaceFileUpdate' in file src/common/services/fs/virtual_file_service.ts in project gitlab-lsp | Definition:
export type WorkspaceFileUpdate = {
fileUri: URI;
event: 'add' | 'change' | 'unlink';
workspaceFolder: WorkspaceFolder;
};
export type WorkspaceFilesUpdate = {
files: URI[];
workspaceFolder: WorkspaceFolder;
};
export enum VirtualFileSystemEvents {
WorkspaceFileUpdate = 'workspaceFileUpdate',
WorkspaceFilesUpdate = 'workspaceFilesUpdate',
}
const FILE_SYSTEM_EVENT_NAME = 'fileSystemEvent';
export interface FileSystemEventMap {
[VirtualFileSystemEvents.WorkspaceFileUpdate]: WorkspaceFileUpdate;
[VirtualFileSystemEvents.WorkspaceFilesUpdate]: WorkspaceFilesUpdate;
}
export interface FileSystemEventListener {
<T extends VirtualFileSystemEvents>(eventType: T, data: FileSystemEventMap[T]): void;
}
export type VirtualFileSystemService = typeof DefaultVirtualFileSystemService.prototype;
export const VirtualFileSystemService = createInterfaceId<VirtualFileSystemService>(
'VirtualFileSystemService',
);
@Injectable(VirtualFileSystemService, [DirectoryWalker])
export class DefaultVirtualFileSystemService {
#directoryWalker: DirectoryWalker;
#emitter = new EventEmitter();
constructor(directoryWalker: DirectoryWalker) {
this.#directoryWalker = directoryWalker;
}
#handleFileChange: FileChangeHandler = (event, workspaceFolder, filePath) => {
const fileUri = fsPathToUri(filePath);
this.#emitFileSystemEvent(VirtualFileSystemEvents.WorkspaceFileUpdate, {
event,
fileUri,
workspaceFolder,
});
};
async initialize(workspaceFolders: WorkspaceFolder[]): Promise<void> {
await Promise.all(
workspaceFolders.map(async (workspaceFolder) => {
const files = await this.#directoryWalker.findFilesForDirectory({
directoryUri: workspaceFolder.uri,
});
this.#emitFileSystemEvent(VirtualFileSystemEvents.WorkspaceFilesUpdate, {
files,
workspaceFolder,
});
this.#directoryWalker.setupFileWatcher(workspaceFolder, this.#handleFileChange);
}),
);
}
#emitFileSystemEvent<T extends VirtualFileSystemEvents>(
eventType: T,
data: FileSystemEventMap[T],
) {
this.#emitter.emit(FILE_SYSTEM_EVENT_NAME, eventType, data);
}
onFileSystemEvent(listener: FileSystemEventListener) {
this.#emitter.on(FILE_SYSTEM_EVENT_NAME, listener);
return {
dispose: () => this.#emitter.removeListener(FILE_SYSTEM_EVENT_NAME, listener),
};
}
}
References:
- src/common/workspace/workspace_service.ts:54
- src/common/git/repository_service.ts:93
- src/common/git/repository_service.ts:203
- src/common/services/fs/virtual_file_service.ts:26 |
You are a code assistant | Definition of 'Required' in file src/common/suggestion/suggestions_cache.ts in project gitlab-lsp | Definition:
type Required<T> = {
[P in keyof T]-?: T[P];
};
const DEFAULT_CONFIG: Required<ISuggestionsCacheOptions> = {
enabled: true,
maxSize: 1024 * 1024,
ttl: 60 * 1000,
prefixLines: 1,
suffixLines: 1,
};
export class SuggestionsCache {
#cache: LRUCache<string, SuggestionCacheEntry>;
#configService: ConfigService;
constructor(configService: ConfigService) {
this.#configService = configService;
const currentConfig = this.#getCurrentConfig();
this.#cache = new LRUCache<string, SuggestionCacheEntry>({
ttlAutopurge: true,
sizeCalculation: (value, key) =>
value.suggestions.reduce((acc, suggestion) => acc + suggestion.text.length, 0) + key.length,
...DEFAULT_CONFIG,
...currentConfig,
ttl: Number(currentConfig.ttl),
});
}
#getCurrentConfig(): Required<ISuggestionsCacheOptions> {
return {
...DEFAULT_CONFIG,
...(this.#configService.get('client.suggestionsCache') ?? {}),
};
}
#getSuggestionKey(ctx: SuggestionCacheContext) {
const prefixLines = ctx.context.prefix.split('\n');
const currentLine = prefixLines.pop() ?? '';
const indentation = (currentLine.match(/^\s*/)?.[0] ?? '').length;
const config = this.#getCurrentConfig();
const cachedPrefixLines = prefixLines
.filter(isNonEmptyLine)
.slice(-config.prefixLines)
.join('\n');
const cachedSuffixLines = ctx.context.suffix
.split('\n')
.filter(isNonEmptyLine)
.slice(0, config.suffixLines)
.join('\n');
return [
ctx.document.uri,
ctx.position.line,
cachedPrefixLines,
cachedSuffixLines,
indentation,
].join(':');
}
#increaseCacheEntryRetrievedCount(suggestionKey: string, character: number) {
const item = this.#cache.get(suggestionKey);
if (item && item.timesRetrievedByPosition) {
item.timesRetrievedByPosition[character] =
(item.timesRetrievedByPosition[character] ?? 0) + 1;
}
}
addToSuggestionCache(config: {
request: SuggestionCacheContext;
suggestions: SuggestionOption[];
}) {
if (!this.#getCurrentConfig().enabled) {
return;
}
const currentLine = config.request.context.prefix.split('\n').at(-1) ?? '';
this.#cache.set(this.#getSuggestionKey(config.request), {
character: config.request.position.character,
suggestions: config.suggestions,
currentLine,
timesRetrievedByPosition: {},
additionalContexts: config.request.additionalContexts,
});
}
getCachedSuggestions(request: SuggestionCacheContext): SuggestionCache | undefined {
if (!this.#getCurrentConfig().enabled) {
return undefined;
}
const currentLine = request.context.prefix.split('\n').at(-1) ?? '';
const key = this.#getSuggestionKey(request);
const candidate = this.#cache.get(key);
if (!candidate) {
return undefined;
}
const { character } = request.position;
if (candidate.timesRetrievedByPosition[character] > 0) {
// If cache has already returned this suggestion from the same position before, discard it.
this.#cache.delete(key);
return undefined;
}
this.#increaseCacheEntryRetrievedCount(key, character);
const options = candidate.suggestions
.map((s) => {
const currentLength = currentLine.length;
const previousLength = candidate.currentLine.length;
const diff = currentLength - previousLength;
if (diff < 0) {
return null;
}
if (
currentLine.slice(0, previousLength) !== candidate.currentLine ||
s.text.slice(0, diff) !== currentLine.slice(previousLength)
) {
return null;
}
return {
...s,
text: s.text.slice(diff),
uniqueTrackingId: generateUniqueTrackingId(),
};
})
.filter((x): x is SuggestionOption => Boolean(x));
return {
options,
additionalContexts: candidate.additionalContexts,
};
}
}
References: |
You are a code assistant | Definition of 'createFastifySocketIoPlugin' in file src/node/http/plugin/fastify_socket_io_plugin.ts in project gitlab-lsp | Definition:
export const createFastifySocketIoPlugin = (
options?: Partial<ServerOptions>,
): FastifyPluginRegistration<Partial<ServerOptions>> => {
return {
plugin: fastifySocketIO,
options: options ?? {},
};
};
declare module 'fastify' {
interface FastifyInstance {
io: Server;
}
}
References:
- src/node/setup_http.ts:27 |
You are a code assistant | Definition of 'MockFastifyInstance' in file src/node/webview/test-utils/mock_fastify_instance.ts in project gitlab-lsp | Definition:
export type MockFastifyInstance = {
[P in keyof FastifyInstance]: jest.Mock<FastifyInstance[P]>;
};
export const createMockFastifyInstance = (): MockFastifyInstance & FastifyInstance => {
const reply: Partial<MockFastifyInstance> = {};
reply.register = jest.fn().mockReturnThis();
reply.get = jest.fn().mockReturnThis();
return reply as MockFastifyInstance & FastifyInstance;
};
References: |
You are a code assistant | Definition of 'Greet' in file src/tests/fixtures/intent/empty_function/ruby.rb in project gitlab-lsp | Definition:
class Greet
def initialize(name)
end
def greet
end
end
class Greet2
def initialize(name)
@name = name
end
def greet
puts "Hello #{@name}"
end
end
class Greet3
end
def generate_greetings
end
def greet_generator
yield 'Hello'
end
References:
- src/tests/fixtures/intent/empty_function/go.go:13
- src/tests/fixtures/intent/empty_function/go.go:23
- src/tests/fixtures/intent/empty_function/ruby.rb:16
- src/tests/fixtures/intent/empty_function/go.go:15
- src/tests/fixtures/intent/empty_function/go.go:20
- src/tests/fixtures/intent/go_comments.go:24 |
You are a code assistant | Definition of 'endStates' in file src/common/tracking/constants.ts in project gitlab-lsp | Definition:
export const endStates = [...endStatesGraph].map(([state]) => state);
export const SAAS_INSTANCE_URL = 'https://gitlab.com';
export const TELEMETRY_NOTIFICATION = '$/gitlab/telemetry';
export const CODE_SUGGESTIONS_CATEGORY = 'code_suggestions';
export const GC_TIME = 60000;
export const INSTANCE_TRACKING_EVENTS_MAP = {
[TRACKING_EVENTS.REQUESTED]: null,
[TRACKING_EVENTS.LOADED]: null,
[TRACKING_EVENTS.NOT_PROVIDED]: null,
[TRACKING_EVENTS.SHOWN]: 'code_suggestion_shown_in_ide',
[TRACKING_EVENTS.ERRORED]: null,
[TRACKING_EVENTS.ACCEPTED]: 'code_suggestion_accepted_in_ide',
[TRACKING_EVENTS.REJECTED]: 'code_suggestion_rejected_in_ide',
[TRACKING_EVENTS.CANCELLED]: null,
[TRACKING_EVENTS.STREAM_STARTED]: null,
[TRACKING_EVENTS.STREAM_COMPLETED]: null,
};
// FIXME: once we remove the default from ConfigService, we can move this back to the SnowplowTracker
export const DEFAULT_TRACKING_ENDPOINT = 'https://snowplow.trx.gitlab.net';
export const TELEMETRY_DISABLED_WARNING_MSG =
'GitLab Duo Code Suggestions telemetry is disabled. Please consider enabling telemetry to help improve our service.';
export const TELEMETRY_ENABLED_MSG = 'GitLab Duo Code Suggestions telemetry is enabled.';
References: |
You are a code assistant | Definition of 'greet2' in file src/tests/fixtures/intent/empty_function/typescript.ts in project gitlab-lsp | Definition:
function greet2(name) {
console.log(name);
}
const greet3 = function (name) {};
const greet4 = function (name) {
console.log(name);
};
const greet5 = (name) => {};
const greet6 = (name) => {
console.log(name);
};
class Greet {
constructor(name) {}
greet() {}
}
class Greet2 {
name: string;
constructor(name) {
this.name = name;
}
greet() {
console.log(`Hello ${this.name}`);
}
}
class Greet3 {}
function* generateGreetings() {}
function* greetGenerator() {
yield 'Hello';
}
References:
- src/tests/fixtures/intent/empty_function/ruby.rb:4 |
You are a code assistant | Definition of 'dispose' in file src/common/git/ignore_trie.ts in project gitlab-lsp | Definition:
dispose(): void {
this.#clear();
}
#clear(): void {
this.#children.forEach((child) => child.#clear());
this.#children.clear();
this.#ignoreInstance = null;
}
#removeChild(key: string): void {
const child = this.#children.get(key);
if (child) {
child.#clear();
this.#children.delete(key);
}
}
#prune(): void {
this.#children.forEach((child, key) => {
if (child.#isEmpty()) {
this.#removeChild(key);
} else {
child.#prune();
}
});
}
#isEmpty(): boolean {
return this.#children.size === 0 && !this.#ignoreInstance;
}
}
References: |
You are a code assistant | Definition of 'DocumentService' in file src/common/document_service.ts in project gitlab-lsp | Definition:
export const DocumentService = createInterfaceId<DocumentService>('DocumentsWrapper');
const DOCUMENT_CHANGE_EVENT_NAME = 'documentChange';
export class DefaultDocumentService
implements DocumentService, HandlesNotification<DidChangeDocumentInActiveEditorParams>
{
#subscriptions: Disposable[] = [];
#emitter = new EventEmitter();
#documents: TextDocuments<TextDocument>;
constructor(documents: TextDocuments<TextDocument>) {
this.#documents = documents;
this.#subscriptions.push(
documents.onDidOpen(this.#createMediatorListener(TextDocumentChangeListenerType.onDidOpen)),
);
documents.onDidChangeContent(
this.#createMediatorListener(TextDocumentChangeListenerType.onDidChangeContent),
);
documents.onDidClose(this.#createMediatorListener(TextDocumentChangeListenerType.onDidClose));
documents.onDidSave(this.#createMediatorListener(TextDocumentChangeListenerType.onDidSave));
}
notificationHandler = (param: DidChangeDocumentInActiveEditorParams) => {
const document = isTextDocument(param) ? param : this.#documents.get(param);
if (!document) {
log.error(`Active editor document cannot be retrieved by URL: ${param}`);
return;
}
const event: TextDocumentChangeEvent<TextDocument> = { document };
this.#emitter.emit(
DOCUMENT_CHANGE_EVENT_NAME,
event,
TextDocumentChangeListenerType.onDidSetActive,
);
};
#createMediatorListener =
(type: TextDocumentChangeListenerType) => (event: TextDocumentChangeEvent<TextDocument>) => {
this.#emitter.emit(DOCUMENT_CHANGE_EVENT_NAME, event, type);
};
onDocumentChange(listener: TextDocumentChangeListener) {
this.#emitter.on(DOCUMENT_CHANGE_EVENT_NAME, listener);
return {
dispose: () => this.#emitter.removeListener(DOCUMENT_CHANGE_EVENT_NAME, listener),
};
}
}
References:
- src/common/feature_state/project_duo_acces_check.ts:41
- src/common/security_diagnostics_publisher.ts:42
- src/common/security_diagnostics_publisher.test.ts:21
- src/common/advanced_context/advanced_context_service.ts:35
- src/common/feature_state/supported_language_check.ts:31
- src/common/feature_state/supported_language_check.ts:18
- src/common/connection_service.ts:65 |
You are a code assistant | Definition of 'LOG_LEVEL' in file src/common/log_types.ts in project gitlab-lsp | Definition:
export const LOG_LEVEL = {
DEBUG: 'debug',
INFO: 'info',
WARNING: 'warning',
ERROR: 'error',
} as const;
export type LogLevel = (typeof LOG_LEVEL)[keyof typeof LOG_LEVEL];
References: |
You are a code assistant | Definition of 'getUri' in file src/common/webview/webview_resource_location_service.ts in project gitlab-lsp | Definition:
getUri(webviewId: WebviewId): Uri;
}
export interface WebviewUriProviderRegistry {
register(provider: WebviewUriProvider): void;
}
export class WebviewLocationService implements WebviewUriProviderRegistry {
#uriProviders = new Set<WebviewUriProvider>();
register(provider: WebviewUriProvider) {
this.#uriProviders.add(provider);
}
resolveUris(webviewId: WebviewId): Uri[] {
const uris: Uri[] = [];
for (const provider of this.#uriProviders) {
uris.push(provider.getUri(webviewId));
}
return uris;
}
}
References: |
You are a code assistant | Definition of 'TransportListener' in file packages/lib_webview_transport/src/types.ts in project gitlab-lsp | Definition:
export interface TransportListener {
on<K extends keyof MessagesToServer>(
type: K,
callback: TransportMessageHandler<MessagesToServer[K]>,
): Disposable;
}
export interface TransportPublisher {
publish<K extends keyof MessagesToClient>(type: K, payload: MessagesToClient[K]): Promise<void>;
}
export interface Transport extends TransportListener, TransportPublisher {}
References: |
You are a code assistant | Definition of 'getContextForQuery' in file src/common/ai_context_management_2/ai_context_aggregator.ts in project gitlab-lsp | Definition:
async getContextForQuery(query: AiContextQuery): Promise<AiContextItem[]> {
switch (query.providerType) {
case 'file': {
const providerItems = await this.#AiFileContextProvider.getProviderItems(
query.query,
query.workspaceFolders,
);
const contextItems = await Promise.all(
providerItems.map((providerItem) => this.#providerItemToContextItem(providerItem)),
);
return contextItems;
}
default:
return [];
}
}
async #providerItemToContextItem(providerItem: AiContextProviderItem): Promise<AiContextItem> {
if (providerItem.providerType === 'file') {
const { fileUri, workspaceFolder, providerType, subType, repositoryFile } = providerItem;
const policyResult = await this.#AiContextPolicyManager.runPolicies(providerItem);
return {
id: fileUri.toString(),
isEnabled: policyResult.allowed,
info: {
project: repositoryFile?.repositoryUri.fsPath,
disabledReasons: policyResult.reasons,
relFilePath: repositoryFile
? this.#getBasePath(fileUri, parseURIString(workspaceFolder.uri))
: undefined,
},
name: Utils.basename(fileUri),
type: providerType,
subType,
};
}
throw new Error('Unknown provider type');
}
#getBasePath(targetUri: URI, baseUri: URI): string {
const targetPath = targetUri.fsPath;
const basePath = baseUri.fsPath;
return targetPath.replace(basePath, '').replace(/^[/\\]+/, '');
}
}
References: |
You are a code assistant | Definition of 'MockWebviewUriProvider' in file src/common/webview/webview_resource_location_service.test.ts in project gitlab-lsp | Definition:
class MockWebviewUriProvider implements WebviewUriProvider {
constructor(private uri: string) {}
getUri(): string {
return this.uri;
}
}
describe('WebviewLocationService', () => {
let service: WebviewLocationService;
const TEST_URI_1 = 'http://example.com';
const TEST_URI_2 = 'file:///foo/bar';
const TEST_WEBVIEW_ID: WebviewId = 'webview-1' as WebviewId;
beforeEach(() => {
service = new WebviewLocationService();
});
describe('resolveUris', () => {
it('should resolve URIs from multiple providers', () => {
const provider1 = new MockWebviewUriProvider(TEST_URI_1);
const provider2 = new MockWebviewUriProvider(TEST_URI_2);
service.register(provider1);
service.register(provider2);
const uris = service.resolveUris(TEST_WEBVIEW_ID);
expect(uris).toEqual([TEST_URI_1, TEST_URI_2]);
});
it('should return an empty array if no providers are registered', () => {
const uris = service.resolveUris(TEST_WEBVIEW_ID);
expect(uris).toEqual([]);
});
it('should not register the same provider multiple times', () => {
const provider = new MockWebviewUriProvider(TEST_URI_1);
service.register(provider);
service.register(provider);
const uris = service.resolveUris(TEST_WEBVIEW_ID);
expect(uris).toEqual([TEST_URI_1]);
});
});
});
References:
- src/common/webview/webview_resource_location_service.test.ts:41
- src/common/webview/webview_resource_location_service.test.ts:25
- src/common/webview/webview_resource_location_service.test.ts:26 |
You are a code assistant | Definition of 'getDefaultProviders' in file packages/lib_webview_client/src/bus/provider/get_default_providers.ts in project gitlab-lsp | Definition:
export const getDefaultProviders = () => {
const hostApplicationProvider = new HostApplicationMessageBusProvider();
const socketIoMessageBusProvider = new SocketIoMessageBusProvider();
return [hostApplicationProvider, socketIoMessageBusProvider];
};
References:
- packages/lib_webview_client/src/bus/resolve_message_bus.ts:16 |
You are a code assistant | Definition of 'pollWorkflowEvents' in file packages/webview_duo_workflow/src/plugin/index.ts in project gitlab-lsp | Definition:
pollWorkflowEvents(id: string, messageBus: MessageBus): Promise<void>;
getWorkflowEvents(id: string): Promise<LangGraphCheckpoint[]>;
}
export const workflowPluginFactory = (
graphqlApi: WorkflowGraphQLService,
workflowApi: WorkflowAPI,
connection: Connection,
): WebviewPlugin<DuoWorkflowMessages> => {
return {
id: WEBVIEW_ID,
title: WEBVIEW_TITLE,
setup: ({ webview }) => {
webview.onInstanceConnected((_webviewInstanceId, messageBus) => {
messageBus.onNotification('startWorkflow', async ({ goal, image }) => {
try {
const workflowId = await workflowApi.runWorkflow(goal, image);
messageBus.sendNotification('workflowStarted', workflowId);
await graphqlApi.pollWorkflowEvents(workflowId, messageBus);
} catch (e) {
const error = e as Error;
messageBus.sendNotification('workflowError', error.message);
}
});
messageBus.onNotification('openUrl', async ({ url }) => {
await connection.sendNotification('$/gitlab/openUrl', { url });
});
});
},
};
};
References: |
You are a code assistant | Definition of 'checkProjectStatus' in file src/common/services/duo_access/project_access_checker.ts in project gitlab-lsp | Definition:
checkProjectStatus(uri: string, workspaceFolder: WorkspaceFolder): DuoProjectStatus {
const projects = this.#projectAccessCache.getProjectsForWorkspaceFolder(workspaceFolder);
if (projects.length === 0) {
return DuoProjectStatus.NonGitlabProject;
}
const project = this.#findDeepestProjectByPath(uri, projects);
if (!project) {
return DuoProjectStatus.NonGitlabProject;
}
return project.enabled ? DuoProjectStatus.DuoEnabled : DuoProjectStatus.DuoDisabled;
}
#findDeepestProjectByPath(uri: string, projects: DuoProject[]): DuoProject | undefined {
let deepestProject: DuoProject | undefined;
for (const project of projects) {
if (uri.startsWith(project.uri.replace('.git/config', ''))) {
if (!deepestProject || project.uri.length > deepestProject.uri.length) {
deepestProject = project;
}
}
}
return deepestProject;
}
}
References: |
You are a code assistant | Definition of 'run' in file scripts/commit-lint/lint.js in project gitlab-lsp | Definition:
async function run() {
if (!CI) {
console.error('This script can only run in GitLab CI.');
process.exit(1);
}
if (!LAST_MR_COMMIT) {
console.error(
'LAST_MR_COMMIT environment variable is not present. Make sure this script is run from `lint.sh`',
);
process.exit(1);
}
const results = await lintMr();
console.error(format({ results }, { helpUrl: urlSemanticRelease }));
const numOfErrors = results.reduce((acc, result) => acc + result.errors.length, 0);
if (numOfErrors !== 0) {
process.exit(1);
}
}
run().catch((err) => {
console.error(err);
process.exit(1);
});
References:
- scripts/watcher/watch.ts:95
- scripts/watcher/watch.ts:87
- scripts/watcher/watch.ts:99
- scripts/commit-lint/lint.js:93 |
You are a code assistant | Definition of 'streamingSuggestionStateGraph' in file src/common/tracking/constants.ts in project gitlab-lsp | Definition:
export const streamingSuggestionStateGraph = new Map<TRACKING_EVENTS, TRACKING_EVENTS[]>([
[
TRACKING_EVENTS.REQUESTED,
[TRACKING_EVENTS.STREAM_STARTED, TRACKING_EVENTS.ERRORED, TRACKING_EVENTS.CANCELLED],
],
[
TRACKING_EVENTS.STREAM_STARTED,
[TRACKING_EVENTS.SHOWN, TRACKING_EVENTS.ERRORED, TRACKING_EVENTS.STREAM_COMPLETED],
],
[
TRACKING_EVENTS.SHOWN,
[
TRACKING_EVENTS.ERRORED,
TRACKING_EVENTS.STREAM_COMPLETED,
TRACKING_EVENTS.ACCEPTED,
TRACKING_EVENTS.REJECTED,
],
],
[
TRACKING_EVENTS.STREAM_COMPLETED,
[TRACKING_EVENTS.ACCEPTED, TRACKING_EVENTS.REJECTED, TRACKING_EVENTS.NOT_PROVIDED],
],
...endStatesGraph,
]);
export const endStates = [...endStatesGraph].map(([state]) => state);
export const SAAS_INSTANCE_URL = 'https://gitlab.com';
export const TELEMETRY_NOTIFICATION = '$/gitlab/telemetry';
export const CODE_SUGGESTIONS_CATEGORY = 'code_suggestions';
export const GC_TIME = 60000;
export const INSTANCE_TRACKING_EVENTS_MAP = {
[TRACKING_EVENTS.REQUESTED]: null,
[TRACKING_EVENTS.LOADED]: null,
[TRACKING_EVENTS.NOT_PROVIDED]: null,
[TRACKING_EVENTS.SHOWN]: 'code_suggestion_shown_in_ide',
[TRACKING_EVENTS.ERRORED]: null,
[TRACKING_EVENTS.ACCEPTED]: 'code_suggestion_accepted_in_ide',
[TRACKING_EVENTS.REJECTED]: 'code_suggestion_rejected_in_ide',
[TRACKING_EVENTS.CANCELLED]: null,
[TRACKING_EVENTS.STREAM_STARTED]: null,
[TRACKING_EVENTS.STREAM_COMPLETED]: null,
};
// FIXME: once we remove the default from ConfigService, we can move this back to the SnowplowTracker
export const DEFAULT_TRACKING_ENDPOINT = 'https://snowplow.trx.gitlab.net';
export const TELEMETRY_DISABLED_WARNING_MSG =
'GitLab Duo Code Suggestions telemetry is disabled. Please consider enabling telemetry to help improve our service.';
export const TELEMETRY_ENABLED_MSG = 'GitLab Duo Code Suggestions telemetry is enabled.';
References: |
You are a code assistant | Definition of 'DuoWorkflowEventConnectionType' in file src/common/graphql/workflow/types.ts in project gitlab-lsp | Definition:
export type DuoWorkflowEventConnectionType = {
duoWorkflowEvents: DuoWorkflowEvents;
};
References:
- src/common/graphql/workflow/service.ts:76 |
You are a code assistant | Definition of 'processCompletion' in file src/common/suggestion_client/post_processors/post_processor_pipeline.test.ts in project gitlab-lsp | Definition:
async processCompletion(
_context: IDocContext,
input: SuggestionOption[],
): Promise<SuggestionOption[]> {
return input;
}
}
pipeline.addProcessor(new TestProcessor());
const invalidInput = { invalid: 'input' };
await expect(
pipeline.run({
documentContext: mockContext,
input: invalidInput as unknown as StreamingCompletionResponse,
type: 'invalid' as 'stream',
}),
).rejects.toThrow('Unexpected type in pipeline processing');
});
});
References: |
You are a code assistant | Definition of 'AiContextAggregator' in file src/common/ai_context_management_2/ai_context_aggregator.ts in project gitlab-lsp | Definition:
export const AiContextAggregator = createInterfaceId<AiContextAggregator>('AiContextAggregator');
export type AiContextQuery = {
query: string;
providerType: 'file';
textDocument?: TextDocument;
workspaceFolders: WorkspaceFolder[];
};
@Injectable(AiContextAggregator, [AiFileContextProvider, AiContextPolicyManager])
export class DefaultAiContextAggregator {
#AiFileContextProvider: AiFileContextProvider;
#AiContextPolicyManager: AiContextPolicyManager;
constructor(
aiFileContextProvider: AiFileContextProvider,
aiContextPolicyManager: AiContextPolicyManager,
) {
this.#AiFileContextProvider = aiFileContextProvider;
this.#AiContextPolicyManager = aiContextPolicyManager;
}
async getContextForQuery(query: AiContextQuery): Promise<AiContextItem[]> {
switch (query.providerType) {
case 'file': {
const providerItems = await this.#AiFileContextProvider.getProviderItems(
query.query,
query.workspaceFolders,
);
const contextItems = await Promise.all(
providerItems.map((providerItem) => this.#providerItemToContextItem(providerItem)),
);
return contextItems;
}
default:
return [];
}
}
async #providerItemToContextItem(providerItem: AiContextProviderItem): Promise<AiContextItem> {
if (providerItem.providerType === 'file') {
const { fileUri, workspaceFolder, providerType, subType, repositoryFile } = providerItem;
const policyResult = await this.#AiContextPolicyManager.runPolicies(providerItem);
return {
id: fileUri.toString(),
isEnabled: policyResult.allowed,
info: {
project: repositoryFile?.repositoryUri.fsPath,
disabledReasons: policyResult.reasons,
relFilePath: repositoryFile
? this.#getBasePath(fileUri, parseURIString(workspaceFolder.uri))
: undefined,
},
name: Utils.basename(fileUri),
type: providerType,
subType,
};
}
throw new Error('Unknown provider type');
}
#getBasePath(targetUri: URI, baseUri: URI): string {
const targetPath = targetUri.fsPath;
const basePath = baseUri.fsPath;
return targetPath.replace(basePath, '').replace(/^[/\\]+/, '');
}
}
References:
- src/common/connection_service.ts:55
- src/common/connection_service.ts:66 |
You are a code assistant | Definition of 'GET_WORKFLOW_EVENTS_QUERY' in file src/common/graphql/workflow/queries.ts in project gitlab-lsp | Definition:
export const GET_WORKFLOW_EVENTS_QUERY = gql`
query getDuoWorkflowEvents($workflowId: AiDuoWorkflowsWorkflowID!) {
duoWorkflowEvents(workflowId: $workflowId) {
nodes {
checkpoint
}
}
}
`;
References: |
You are a code assistant | Definition of 'TokenAccount' in file packages/webview_duo_chat/src/plugin/port/platform/gitlab_account.ts in project gitlab-lsp | Definition:
export interface TokenAccount extends AccountBase {
type: 'token';
}
export interface OAuthAccount extends AccountBase {
type: 'oauth';
scopes: string[];
refreshToken: string;
expiresAtTimestampInSeconds: number;
}
export type Account = TokenAccount | OAuthAccount;
export const serializeAccountSafe = (account: Account) =>
JSON.stringify(account, ['instanceUrl', 'id', 'username', 'scopes']);
export const makeAccountId = (instanceUrl: string, userId: string | number) =>
`${instanceUrl}|${userId}`;
export const extractUserId = (accountId: string) => accountId.split('|').pop();
References: |
You are a code assistant | Definition of 'isDisposable' in file packages/lib_disposable/src/utils.ts in project gitlab-lsp | Definition:
export const isDisposable = (value: unknown): value is Disposable => {
return (
typeof value === 'object' &&
value !== null &&
'dispose' in value &&
typeof (value as Disposable).dispose === 'function'
);
};
References:
- packages/lib_webview/src/setup/plugin/setup_plugins.ts:46
- packages/lib_webview/src/setup/plugin/webview_controller.ts:106
- src/common/webview/extension/extension_connection_message_bus.test.ts:66
- packages/lib_webview/src/setup/plugin/webview_controller.ts:63
- src/common/webview/extension/extension_connection_message_bus.test.ts:49 |
You are a code assistant | Definition of 'constructor' in file src/common/tracking/multi_tracker.ts in project gitlab-lsp | Definition:
constructor(trackers: TelemetryTracker[]) {
this.#trackers = trackers;
}
get #enabledTrackers() {
return this.#trackers.filter((t) => t.isEnabled());
}
isEnabled(): boolean {
return Boolean(this.#enabledTrackers.length);
}
setCodeSuggestionsContext(
uniqueTrackingId: string,
context: Partial<ICodeSuggestionContextUpdate>,
) {
this.#enabledTrackers.forEach((t) => t.setCodeSuggestionsContext(uniqueTrackingId, context));
}
updateCodeSuggestionsContext(
uniqueTrackingId: string,
contextUpdate: Partial<ICodeSuggestionContextUpdate>,
) {
this.#enabledTrackers.forEach((t) =>
t.updateCodeSuggestionsContext(uniqueTrackingId, contextUpdate),
);
}
updateSuggestionState(uniqueTrackingId: string, newState: TRACKING_EVENTS) {
this.#enabledTrackers.forEach((t) => t.updateSuggestionState(uniqueTrackingId, newState));
}
rejectOpenedSuggestions() {
this.#enabledTrackers.forEach((t) => t.rejectOpenedSuggestions());
}
}
References: |
You are a code assistant | Definition of 'HashedRegistry' in file packages/lib_handler_registry/src/registry/hashed_registry.ts in project gitlab-lsp | Definition:
export class HashedRegistry<TKey, THandler extends Handler = Handler>
implements HandlerRegistry<TKey, THandler>
{
#hashFunc: HashFunc<TKey>;
#basicRegistry: SimpleRegistry<THandler>;
constructor(hashFunc: HashFunc<TKey>) {
this.#hashFunc = hashFunc;
this.#basicRegistry = new SimpleRegistry<THandler>();
}
get size() {
return this.#basicRegistry.size;
}
register(key: TKey, handler: THandler): Disposable {
const hash = this.#hashFunc(key);
return this.#basicRegistry.register(hash, handler);
}
has(key: TKey): boolean {
const hash = this.#hashFunc(key);
return this.#basicRegistry.has(hash);
}
async handle(key: TKey, ...args: Parameters<THandler>): Promise<ReturnType<THandler>> {
const hash = this.#hashFunc(key);
return this.#basicRegistry.handle(hash, ...args);
}
dispose() {
this.#basicRegistry.dispose();
}
}
References:
- packages/lib_handler_registry/src/registry/hashed_registry.test.ts:9 |
You are a code assistant | Definition of 'SnowplowTracker' in file src/common/tracking/snowplow_tracker.ts in project gitlab-lsp | Definition:
export class SnowplowTracker implements TelemetryTracker {
#snowplow: Snowplow;
#ajv = new Ajv({ strict: false });
#configService: ConfigService;
#api: GitLabApiClient;
#options: ITelemetryOptions = {
enabled: true,
baseUrl: SAAS_INSTANCE_URL,
trackingUrl: DEFAULT_TRACKING_ENDPOINT,
// the list of events that the client can track themselves
actions: [],
};
#clientContext: ISnowplowClientContext = {
schema: 'iglu:com.gitlab/ide_extension_version/jsonschema/1-1-0',
data: {},
};
#codeSuggestionStates = new Map<string, TRACKING_EVENTS>();
#lsFetch: LsFetch;
#featureFlagService: FeatureFlagService;
#gitlabRealm: GitlabRealm = GitlabRealm.saas;
#codeSuggestionsContextMap = new Map<string, ISnowplowCodeSuggestionContext>();
constructor(
lsFetch: LsFetch,
configService: ConfigService,
featureFlagService: FeatureFlagService,
api: GitLabApiClient,
) {
this.#configService = configService;
this.#configService.onConfigChange((config) => this.#reconfigure(config));
this.#api = api;
const trackingUrl = DEFAULT_TRACKING_ENDPOINT;
this.#lsFetch = lsFetch;
this.#configService = configService;
this.#featureFlagService = featureFlagService;
this.#snowplow = Snowplow.getInstance(this.#lsFetch, {
...DEFAULT_SNOWPLOW_OPTIONS,
endpoint: trackingUrl,
enabled: this.isEnabled.bind(this),
});
this.#options.trackingUrl = trackingUrl;
this.#ajv.addMetaSchema(SnowplowMetaSchema);
}
isEnabled(): boolean {
return Boolean(this.#options.enabled);
}
async #reconfigure(config: IConfig) {
const { baseUrl } = config.client;
const trackingUrl = config.client.telemetry?.trackingUrl;
const enabled = config.client.telemetry?.enabled;
const actions = config.client.telemetry?.actions;
if (typeof enabled !== 'undefined') {
this.#options.enabled = enabled;
if (enabled === false) {
log.warn(`Snowplow Telemetry: ${TELEMETRY_DISABLED_WARNING_MSG}`);
} else if (enabled === true) {
log.info(`Snowplow Telemetry: ${TELEMETRY_ENABLED_MSG}`);
}
}
if (baseUrl) {
this.#options.baseUrl = baseUrl;
this.#gitlabRealm = baseUrl.endsWith(SAAS_INSTANCE_URL)
? GitlabRealm.saas
: GitlabRealm.selfManaged;
}
if (trackingUrl && this.#options.trackingUrl !== trackingUrl) {
await this.#snowplow.stop();
this.#snowplow.destroy();
this.#snowplow = Snowplow.getInstance(this.#lsFetch, {
...DEFAULT_SNOWPLOW_OPTIONS,
endpoint: trackingUrl,
enabled: this.isEnabled.bind(this),
});
}
if (actions) {
this.#options.actions = actions;
}
this.#setClientContext({
extension: config.client.telemetry?.extension,
ide: config.client.telemetry?.ide,
});
}
#setClientContext(context: IClientContext) {
this.#clientContext.data = {
ide_name: context?.ide?.name ?? null,
ide_vendor: context?.ide?.vendor ?? null,
ide_version: context?.ide?.version ?? null,
extension_name: context?.extension?.name ?? null,
extension_version: context?.extension?.version ?? null,
language_server_version: lsVersion ?? null,
};
}
public setCodeSuggestionsContext(
uniqueTrackingId: string,
context: Partial<ICodeSuggestionContextUpdate>,
) {
const {
documentContext,
source = SuggestionSource.network,
language,
isStreaming,
triggerKind,
optionsCount,
additionalContexts,
isDirectConnection,
} = context;
const {
gitlab_instance_id,
gitlab_global_user_id,
gitlab_host_name,
gitlab_saas_duo_pro_namespace_ids,
} = this.#configService.get('client.snowplowTrackerOptions') ?? {};
if (source === SuggestionSource.cache) {
log.debug(`Snowplow Telemetry: Retrieved suggestion from cache`);
} else {
log.debug(`Snowplow Telemetry: Received request to create a new suggestion`);
}
// Only auto-reject if client is set up to track accepted and not rejected events.
if (
canClientTrackEvent(this.#options.actions, TRACKING_EVENTS.ACCEPTED) &&
!canClientTrackEvent(this.#options.actions, TRACKING_EVENTS.REJECTED)
) {
this.rejectOpenedSuggestions();
}
setTimeout(() => {
if (this.#codeSuggestionsContextMap.has(uniqueTrackingId)) {
this.#codeSuggestionsContextMap.delete(uniqueTrackingId);
this.#codeSuggestionStates.delete(uniqueTrackingId);
}
}, GC_TIME);
const advancedContextData = this.#getAdvancedContextData({
additionalContexts,
documentContext,
});
this.#codeSuggestionsContextMap.set(uniqueTrackingId, {
schema: 'iglu:com.gitlab/code_suggestions_context/jsonschema/3-5-0',
data: {
suffix_length: documentContext?.suffix.length ?? 0,
prefix_length: documentContext?.prefix.length ?? 0,
gitlab_realm: this.#gitlabRealm,
model_engine: null,
model_name: null,
language: language ?? null,
api_status_code: null,
debounce_interval: source === SuggestionSource.cache ? 0 : SUGGESTIONS_DEBOUNCE_INTERVAL_MS,
suggestion_source: source,
gitlab_global_user_id: gitlab_global_user_id ?? null,
gitlab_host_name: gitlab_host_name ?? null,
gitlab_instance_id: gitlab_instance_id ?? null,
gitlab_saas_duo_pro_namespace_ids: gitlab_saas_duo_pro_namespace_ids ?? null,
gitlab_instance_version: this.#api.instanceVersion ?? null,
is_streaming: isStreaming ?? false,
is_invoked: SnowplowTracker.#isCompletionInvoked(triggerKind),
options_count: optionsCount ?? null,
has_advanced_context: advancedContextData.hasAdvancedContext,
is_direct_connection: isDirectConnection ?? null,
total_context_size_bytes: advancedContextData.totalContextSizeBytes,
content_above_cursor_size_bytes: advancedContextData.contentAboveCursorSizeBytes,
content_below_cursor_size_bytes: advancedContextData.contentBelowCursorSizeBytes,
context_items: advancedContextData.contextItems,
},
});
this.#codeSuggestionStates.set(uniqueTrackingId, TRACKING_EVENTS.REQUESTED);
this.#trackCodeSuggestionsEvent(TRACKING_EVENTS.REQUESTED, uniqueTrackingId).catch((e) =>
log.warn('Snowplow Telemetry: Could not track telemetry', e),
);
log.debug(`Snowplow Telemetry: New suggestion ${uniqueTrackingId} has been requested`);
}
// FIXME: the set and update context methods have similar logic and they should have to grow linearly with each new attribute
// the solution might be some generic update method used by both
public updateCodeSuggestionsContext(
uniqueTrackingId: string,
contextUpdate: Partial<ICodeSuggestionContextUpdate>,
) {
const context = this.#codeSuggestionsContextMap.get(uniqueTrackingId);
const { model, status, optionsCount, acceptedOption, isDirectConnection } = contextUpdate;
if (context) {
if (model) {
context.data.language = model.lang ?? null;
context.data.model_engine = model.engine ?? null;
context.data.model_name = model.name ?? null;
context.data.input_tokens = model?.tokens_consumption_metadata?.input_tokens ?? null;
context.data.output_tokens = model.tokens_consumption_metadata?.output_tokens ?? null;
context.data.context_tokens_sent =
model.tokens_consumption_metadata?.context_tokens_sent ?? null;
context.data.context_tokens_used =
model.tokens_consumption_metadata?.context_tokens_used ?? null;
}
if (status) {
context.data.api_status_code = status;
}
if (optionsCount) {
context.data.options_count = optionsCount;
}
if (isDirectConnection !== undefined) {
context.data.is_direct_connection = isDirectConnection;
}
if (acceptedOption) {
context.data.accepted_option = acceptedOption;
}
this.#codeSuggestionsContextMap.set(uniqueTrackingId, context);
}
}
async #trackCodeSuggestionsEvent(eventType: TRACKING_EVENTS, uniqueTrackingId: string) {
if (!this.isEnabled()) {
return;
}
const event: StructuredEvent = {
category: CODE_SUGGESTIONS_CATEGORY,
action: eventType,
label: uniqueTrackingId,
};
try {
const contexts: SelfDescribingJson[] = [this.#clientContext];
const codeSuggestionContext = this.#codeSuggestionsContextMap.get(uniqueTrackingId);
if (codeSuggestionContext) {
contexts.push(codeSuggestionContext);
}
const suggestionContextValid = this.#ajv.validate(
CodeSuggestionContextSchema,
codeSuggestionContext?.data,
);
if (!suggestionContextValid) {
log.warn(EVENT_VALIDATION_ERROR_MSG);
log.debug(JSON.stringify(this.#ajv.errors, null, 2));
return;
}
const ideExtensionContextValid = this.#ajv.validate(
IdeExtensionContextSchema,
this.#clientContext?.data,
);
if (!ideExtensionContextValid) {
log.warn(EVENT_VALIDATION_ERROR_MSG);
log.debug(JSON.stringify(this.#ajv.errors, null, 2));
return;
}
await this.#snowplow.trackStructEvent(event, contexts);
} catch (error) {
log.warn(`Snowplow Telemetry: Failed to track telemetry event: ${eventType}`, error);
}
}
public updateSuggestionState(uniqueTrackingId: string, newState: TRACKING_EVENTS): void {
const state = this.#codeSuggestionStates.get(uniqueTrackingId);
if (!state) {
log.debug(`Snowplow Telemetry: The suggestion with ${uniqueTrackingId} can't be found`);
return;
}
const isStreaming = Boolean(
this.#codeSuggestionsContextMap.get(uniqueTrackingId)?.data.is_streaming,
);
const allowedTransitions = isStreaming
? streamingSuggestionStateGraph.get(state)
: nonStreamingSuggestionStateGraph.get(state);
if (!allowedTransitions) {
log.debug(
`Snowplow Telemetry: The suggestion's ${uniqueTrackingId} state ${state} can't be found in state graph`,
);
return;
}
if (!allowedTransitions.includes(newState)) {
log.debug(
`Snowplow Telemetry: Unexpected transition from ${state} into ${newState} for ${uniqueTrackingId}`,
);
// Allow state to update to ACCEPTED despite 'allowed transitions' constraint.
if (newState !== TRACKING_EVENTS.ACCEPTED) {
return;
}
log.debug(
`Snowplow Telemetry: Conditionally allowing transition to accepted state for ${uniqueTrackingId}`,
);
}
this.#codeSuggestionStates.set(uniqueTrackingId, newState);
this.#trackCodeSuggestionsEvent(newState, uniqueTrackingId).catch((e) =>
log.warn('Snowplow Telemetry: Could not track telemetry', e),
);
log.debug(`Snowplow Telemetry: ${uniqueTrackingId} transisted from ${state} to ${newState}`);
}
rejectOpenedSuggestions() {
log.debug(`Snowplow Telemetry: Reject all opened suggestions`);
this.#codeSuggestionStates.forEach((state, uniqueTrackingId) => {
if (endStates.includes(state)) {
return;
}
this.updateSuggestionState(uniqueTrackingId, TRACKING_EVENTS.REJECTED);
});
}
#hasAdvancedContext(advancedContexts?: AdditionalContext[]): boolean | null {
const advancedContextFeatureFlagsEnabled = shouldUseAdvancedContext(
this.#featureFlagService,
this.#configService,
);
if (advancedContextFeatureFlagsEnabled) {
return Boolean(advancedContexts?.length);
}
return null;
}
#getAdvancedContextData({
additionalContexts,
documentContext,
}: {
additionalContexts?: AdditionalContext[];
documentContext?: IDocContext;
}) {
const hasAdvancedContext = this.#hasAdvancedContext(additionalContexts);
const contentAboveCursorSizeBytes = documentContext?.prefix
? getByteSize(documentContext.prefix)
: 0;
const contentBelowCursorSizeBytes = documentContext?.suffix
? getByteSize(documentContext.suffix)
: 0;
const contextItems: ContextItem[] | null =
additionalContexts?.map((item) => ({
file_extension: item.name.split('.').pop() || '',
type: item.type,
resolution_strategy: item.resolution_strategy,
byte_size: item?.content ? getByteSize(item.content) : 0,
})) ?? null;
const totalContextSizeBytes =
contextItems?.reduce((total, item) => total + item.byte_size, 0) ?? 0;
return {
totalContextSizeBytes,
contentAboveCursorSizeBytes,
contentBelowCursorSizeBytes,
contextItems,
hasAdvancedContext,
};
}
static #isCompletionInvoked(triggerKind?: InlineCompletionTriggerKind): boolean | null {
let isInvoked = null;
if (triggerKind === InlineCompletionTriggerKind.Invoked) {
isInvoked = true;
} else if (triggerKind === InlineCompletionTriggerKind.Automatic) {
isInvoked = false;
}
return isInvoked;
}
}
References:
- src/browser/main.ts:100
- src/node/main.ts:152
- src/common/tracking/snowplow_tracker.test.ts:87
- src/common/suggestion/streaming_handler.test.ts:44
- src/common/tracking/snowplow_tracker.test.ts:69 |
You are a code assistant | Definition of 'GITLAB_API_BASE_URL' in file src/common/constants.ts in project gitlab-lsp | Definition:
export const GITLAB_API_BASE_URL = 'https://gitlab.com';
export const SUGGESTION_ACCEPTED_COMMAND = 'gitlab.ls.codeSuggestionAccepted';
export const START_STREAMING_COMMAND = 'gitlab.ls.startStreaming';
export const WORKFLOW_EXECUTOR_VERSION = 'v0.0.5';
export const SUGGESTIONS_DEBOUNCE_INTERVAL_MS = 250;
export const WORKFLOW_EXECUTOR_DOWNLOAD_PATH = `https://gitlab.com/api/v4/projects/58711783/packages/generic/duo_workflow_executor/${WORKFLOW_EXECUTOR_VERSION}/duo_workflow_executor.tar.gz`;
References: |
You are a code assistant | Definition of 'dispose' in file src/node/services/fs/dir.ts in project gitlab-lsp | Definition:
async dispose(): Promise<void> {
const promises = Array.from(this.#watchers.values()).map((watcher) => watcher.close());
await Promise.all(promises);
this.#watchers.clear();
}
}
References: |
You are a code assistant | Definition of 'constructor' in file src/common/services/fs/virtual_file_service.ts in project gitlab-lsp | Definition:
constructor(directoryWalker: DirectoryWalker) {
this.#directoryWalker = directoryWalker;
}
#handleFileChange: FileChangeHandler = (event, workspaceFolder, filePath) => {
const fileUri = fsPathToUri(filePath);
this.#emitFileSystemEvent(VirtualFileSystemEvents.WorkspaceFileUpdate, {
event,
fileUri,
workspaceFolder,
});
};
async initialize(workspaceFolders: WorkspaceFolder[]): Promise<void> {
await Promise.all(
workspaceFolders.map(async (workspaceFolder) => {
const files = await this.#directoryWalker.findFilesForDirectory({
directoryUri: workspaceFolder.uri,
});
this.#emitFileSystemEvent(VirtualFileSystemEvents.WorkspaceFilesUpdate, {
files,
workspaceFolder,
});
this.#directoryWalker.setupFileWatcher(workspaceFolder, this.#handleFileChange);
}),
);
}
#emitFileSystemEvent<T extends VirtualFileSystemEvents>(
eventType: T,
data: FileSystemEventMap[T],
) {
this.#emitter.emit(FILE_SYSTEM_EVENT_NAME, eventType, data);
}
onFileSystemEvent(listener: FileSystemEventListener) {
this.#emitter.on(FILE_SYSTEM_EVENT_NAME, listener);
return {
dispose: () => this.#emitter.removeListener(FILE_SYSTEM_EVENT_NAME, listener),
};
}
}
References: |
You are a code assistant | Definition of 'info' in file packages/lib_logging/src/types.ts in project gitlab-lsp | Definition:
info(e: Error): void;
info(message: string, e?: Error): void;
warn(e: Error): void;
warn(message: string, e?: Error): void;
error(e: Error): void;
error(message: string, e?: Error): void;
}
References: |
You are a code assistant | Definition of 'put' in file src/common/fetch.ts in project gitlab-lsp | Definition:
put(input: RequestInfo | URL, init?: RequestInit): Promise<Response>;
updateAgentOptions(options: FetchAgentOptions): void;
streamFetch(url: string, body: string, headers: FetchHeaders): AsyncGenerator<string, void, void>;
}
export const LsFetch = createInterfaceId<LsFetch>('LsFetch');
export class FetchBase implements LsFetch {
updateRequestInit(method: string, init?: RequestInit): RequestInit {
if (typeof init === 'undefined') {
// eslint-disable-next-line no-param-reassign
init = { method };
} else {
// eslint-disable-next-line no-param-reassign
init.method = method;
}
return init;
}
async initialize(): Promise<void> {}
async destroy(): Promise<void> {}
async fetch(input: RequestInfo | URL, init?: RequestInit): Promise<Response> {
return fetch(input, init);
}
async *streamFetch(
/* eslint-disable @typescript-eslint/no-unused-vars */
_url: string,
_body: string,
_headers: FetchHeaders,
/* eslint-enable @typescript-eslint/no-unused-vars */
): AsyncGenerator<string, void, void> {
// Stub. Should delegate to the node or browser fetch implementations
throw new Error('Not implemented');
yield '';
}
async delete(input: RequestInfo | URL, init?: RequestInit): Promise<Response> {
return this.fetch(input, this.updateRequestInit('DELETE', init));
}
async get(input: RequestInfo | URL, init?: RequestInit): Promise<Response> {
return this.fetch(input, this.updateRequestInit('GET', init));
}
async post(input: RequestInfo | URL, init?: RequestInit): Promise<Response> {
return this.fetch(input, this.updateRequestInit('POST', init));
}
async put(input: RequestInfo | URL, init?: RequestInit): Promise<Response> {
return this.fetch(input, this.updateRequestInit('PUT', init));
}
async fetchBase(input: RequestInfo | URL, init?: RequestInit): Promise<Response> {
// eslint-disable-next-line no-underscore-dangle, no-restricted-globals
const _global = typeof global === 'undefined' ? self : global;
return _global.fetch(input, init);
}
// eslint-disable-next-line @typescript-eslint/no-unused-vars
updateAgentOptions(_opts: FetchAgentOptions): void {}
}
References: |
You are a code assistant | Definition of 'MINIMUM_VERSION' in file packages/webview_duo_chat/src/plugin/port/constants.ts in project gitlab-lsp | Definition:
export const MINIMUM_VERSION = '16.1.0';
export const REQUEST_TIMEOUT_MILLISECONDS = 25000;
// Webview IDs
export const DUO_WORKFLOW_WEBVIEW_ID = 'duo-workflow';
export const DUO_CHAT_WEBVIEW_ID = 'chat';
References: |
You are a code assistant | Definition of 'InteropConfig' in file packages/webview_duo_chat/src/plugin/port/platform/web_ide.ts in project gitlab-lsp | Definition:
export interface InteropConfig {
projectPath: string;
gitlabUrl: string;
}
// region: API types ---------------------------------------------------
/**
* The response body is parsed as JSON and it's up to the client to ensure it
* matches the _TReturnType
*/
export interface PostRequest<_TReturnType> {
type: 'rest';
method: 'POST';
/**
* The request path without `/api/v4`
* If you want to make request to `https://gitlab.example/api/v4/projects`
* set the path to `/projects`
*/
path: string;
body?: unknown;
headers?: Record<string, string>;
}
/**
* The response body is parsed as JSON and it's up to the client to ensure it
* matches the _TReturnType
*/
interface GetRequestBase<_TReturnType> {
method: 'GET';
/**
* The request path without `/api/v4`
* If you want to make request to `https://gitlab.example/api/v4/projects`
* set the path to `/projects`
*/
path: string;
searchParams?: Record<string, string>;
headers?: Record<string, string>;
}
export interface GetRequest<_TReturnType> extends GetRequestBase<_TReturnType> {
type: 'rest';
}
export interface GetBufferRequest extends GetRequestBase<Uint8Array> {
type: 'rest-buffer';
}
export interface GraphQLRequest<_TReturnType> {
type: 'graphql';
query: string;
/** Options passed to the GraphQL query */
variables: Record<string, unknown>;
}
export type ApiRequest<_TReturnType> =
| GetRequest<_TReturnType>
| PostRequest<_TReturnType>
| GraphQLRequest<_TReturnType>;
// The interface of the VSCode mediator command COMMAND_FETCH_FROM_API
// Will throw ResponseError if HTTP response status isn't 200
export type fetchFromApi = <_TReturnType>(
request: ApiRequest<_TReturnType>,
) => Promise<_TReturnType>;
// The interface of the VSCode mediator command COMMAND_FETCH_BUFFER_FROM_API
// Will throw ResponseError if HTTP response status isn't 200
export type fetchBufferFromApi = (request: GetBufferRequest) => Promise<VSCodeBuffer>;
/* API exposed by the Web IDE extension
* See https://code.visualstudio.com/api/references/vscode-api#extensions
*/
export interface WebIDEExtension {
isTelemetryEnabled: () => boolean;
projectPath: string;
gitlabUrl: string;
}
export interface ResponseError extends Error {
status: number;
body?: unknown;
}
References: |
You are a code assistant | Definition of 'GitLabPlatformManager' in file packages/webview_duo_chat/src/plugin/port/platform/gitlab_platform.ts in project gitlab-lsp | Definition:
export interface GitLabPlatformManager {
/**
* Returns GitLabPlatform for the active project
*
* This is how we decide what is "active project":
* - if there is only one Git repository opened, we always return GitLab project associated with that repository
* - if there are multiple Git repositories opened, we return the one associated with the active editor
* - if there isn't active editor, we will return undefined if `userInitiated` is false, or we ask user to select one if user initiated is `true`
*
* @param userInitiated - Indicates whether the user initiated the action.
* @returns A Promise that resolves with the fetched GitLabProject or undefined if an active project does not exist.
*/
getForActiveProject(userInitiated: boolean): Promise<GitLabPlatformForProject | undefined>;
/**
* Returns a GitLabPlatform for the active account
*
* This is how we decide what is "active account":
* - If the user has signed in to a single GitLab account, it will return that account.
* - If the user has signed in to multiple GitLab accounts, a UI picker will request the user to choose the desired account.
*/
getForActiveAccount(): Promise<GitLabPlatformForAccount | undefined>;
/**
* onAccountChange indicates that any of the GitLab accounts in the extension has changed.
* This can mean account was removed, added or the account token has been changed.
*/
// onAccountChange: vscode.Event<void>;
getForAllAccounts(): Promise<GitLabPlatformForAccount[]>;
/**
* Returns GitLabPlatformForAccount if there is a SaaS account added. Otherwise returns undefined.
*/
getForSaaSAccount(): Promise<GitLabPlatformForAccount | undefined>;
}
References:
- packages/webview_duo_chat/src/plugin/port/chat/get_platform_manager_for_chat.ts:18
- packages/webview_duo_chat/src/plugin/port/chat/get_platform_manager_for_chat.ts:20
- packages/webview_duo_chat/src/plugin/port/chat/get_platform_manager_for_chat.test.ts:27 |
You are a code assistant | Definition of '__init__' in file src/tests/fixtures/intent/empty_function/python.py in project gitlab-lsp | Definition:
def __init__(self, name):
...
def greet(self):
...
class Greet3:
...
def greet3(name):
class Greet4:
def __init__(self, name):
def greet(self):
class Greet3:
References: |
You are a code assistant | Definition of 'CODE_SUGGESTIONS_CATEGORY' in file src/common/tracking/constants.ts in project gitlab-lsp | Definition:
export const CODE_SUGGESTIONS_CATEGORY = 'code_suggestions';
export const GC_TIME = 60000;
export const INSTANCE_TRACKING_EVENTS_MAP = {
[TRACKING_EVENTS.REQUESTED]: null,
[TRACKING_EVENTS.LOADED]: null,
[TRACKING_EVENTS.NOT_PROVIDED]: null,
[TRACKING_EVENTS.SHOWN]: 'code_suggestion_shown_in_ide',
[TRACKING_EVENTS.ERRORED]: null,
[TRACKING_EVENTS.ACCEPTED]: 'code_suggestion_accepted_in_ide',
[TRACKING_EVENTS.REJECTED]: 'code_suggestion_rejected_in_ide',
[TRACKING_EVENTS.CANCELLED]: null,
[TRACKING_EVENTS.STREAM_STARTED]: null,
[TRACKING_EVENTS.STREAM_COMPLETED]: null,
};
// FIXME: once we remove the default from ConfigService, we can move this back to the SnowplowTracker
export const DEFAULT_TRACKING_ENDPOINT = 'https://snowplow.trx.gitlab.net';
export const TELEMETRY_DISABLED_WARNING_MSG =
'GitLab Duo Code Suggestions telemetry is disabled. Please consider enabling telemetry to help improve our service.';
export const TELEMETRY_ENABLED_MSG = 'GitLab Duo Code Suggestions telemetry is enabled.';
References: |
You are a code assistant | Definition of 'fileExists' in file src/tests/int/hasbin.ts in project gitlab-lsp | Definition:
export function fileExists(filePath: string, done: (result: boolean) => void) {
stat(filePath, function (error, stat) {
if (error) {
return done(false);
}
done(stat.isFile());
});
}
export function fileExistsSync(filePath: string) {
try {
return statSync(filePath).isFile();
} catch (error) {
return false;
}
}
References: |
You are a code assistant | Definition of 'COMMAND_GET_CONFIG' in file packages/webview_duo_chat/src/plugin/port/platform/web_ide.ts in project gitlab-lsp | Definition:
export const COMMAND_GET_CONFIG = `gitlab-web-ide.mediator.get-config`;
// Return type from `COMMAND_FETCH_BUFFER_FROM_API`
export interface VSCodeBuffer {
readonly buffer: Uint8Array;
}
// region: Shared configuration ----------------------------------------
export interface InteropConfig {
projectPath: string;
gitlabUrl: string;
}
// region: API types ---------------------------------------------------
/**
* The response body is parsed as JSON and it's up to the client to ensure it
* matches the _TReturnType
*/
export interface PostRequest<_TReturnType> {
type: 'rest';
method: 'POST';
/**
* The request path without `/api/v4`
* If you want to make request to `https://gitlab.example/api/v4/projects`
* set the path to `/projects`
*/
path: string;
body?: unknown;
headers?: Record<string, string>;
}
/**
* The response body is parsed as JSON and it's up to the client to ensure it
* matches the _TReturnType
*/
interface GetRequestBase<_TReturnType> {
method: 'GET';
/**
* The request path without `/api/v4`
* If you want to make request to `https://gitlab.example/api/v4/projects`
* set the path to `/projects`
*/
path: string;
searchParams?: Record<string, string>;
headers?: Record<string, string>;
}
export interface GetRequest<_TReturnType> extends GetRequestBase<_TReturnType> {
type: 'rest';
}
export interface GetBufferRequest extends GetRequestBase<Uint8Array> {
type: 'rest-buffer';
}
export interface GraphQLRequest<_TReturnType> {
type: 'graphql';
query: string;
/** Options passed to the GraphQL query */
variables: Record<string, unknown>;
}
export type ApiRequest<_TReturnType> =
| GetRequest<_TReturnType>
| PostRequest<_TReturnType>
| GraphQLRequest<_TReturnType>;
// The interface of the VSCode mediator command COMMAND_FETCH_FROM_API
// Will throw ResponseError if HTTP response status isn't 200
export type fetchFromApi = <_TReturnType>(
request: ApiRequest<_TReturnType>,
) => Promise<_TReturnType>;
// The interface of the VSCode mediator command COMMAND_FETCH_BUFFER_FROM_API
// Will throw ResponseError if HTTP response status isn't 200
export type fetchBufferFromApi = (request: GetBufferRequest) => Promise<VSCodeBuffer>;
/* API exposed by the Web IDE extension
* See https://code.visualstudio.com/api/references/vscode-api#extensions
*/
export interface WebIDEExtension {
isTelemetryEnabled: () => boolean;
projectPath: string;
gitlabUrl: string;
}
export interface ResponseError extends Error {
status: number;
body?: unknown;
}
References: |
You are a code assistant | Definition of 'SecurityDiagnosticsPublisher' in file src/common/security_diagnostics_publisher.ts in project gitlab-lsp | Definition:
export interface SecurityDiagnosticsPublisher extends DiagnosticsPublisher {}
export const SecurityDiagnosticsPublisher = createInterfaceId<SecurityDiagnosticsPublisher>(
'SecurityDiagnosticsPublisher',
);
@Injectable(SecurityDiagnosticsPublisher, [FeatureFlagService, ConfigService, DocumentService])
export class DefaultSecurityDiagnosticsPublisher implements SecurityDiagnosticsPublisher {
#publish: DiagnosticsPublisherFn | undefined;
#opts?: ISecurityScannerOptions;
#featureFlagService: FeatureFlagService;
constructor(
featureFlagService: FeatureFlagService,
configService: ConfigService,
documentService: DocumentService,
) {
this.#featureFlagService = featureFlagService;
configService.onConfigChange((config: IConfig) => {
this.#opts = config.client.securityScannerOptions;
});
documentService.onDocumentChange(
async (
event: TextDocumentChangeEvent<TextDocument>,
handlerType: TextDocumentChangeListenerType,
) => {
if (handlerType === TextDocumentChangeListenerType.onDidSave) {
await this.#runSecurityScan(event.document);
}
},
);
}
init(callback: DiagnosticsPublisherFn): void {
this.#publish = callback;
}
async #runSecurityScan(document: TextDocument) {
try {
if (!this.#publish) {
throw new Error('The DefaultSecurityService has not been initialized. Call init first.');
}
if (!this.#featureFlagService.isClientFlagEnabled(ClientFeatureFlags.RemoteSecurityScans)) {
return;
}
if (!this.#opts?.enabled) {
return;
}
if (!this.#opts) {
return;
}
const url = this.#opts.serviceUrl ?? DEFAULT_SCANNER_SERVICE_URL;
if (url === '') {
return;
}
const content = document.getText();
const fileName = UriUtils.basename(URI.parse(document.uri));
const formData = new FormData();
const blob = new Blob([content]);
formData.append('file', blob, fileName);
const request = {
method: 'POST',
headers: {
Accept: 'application/json',
},
body: formData,
};
log.debug(`Executing request to url="${url}" with contents of "${fileName}"`);
const response = await fetch(url, request);
await handleFetchError(response, 'security scan');
const json = await response.json();
const { vulnerabilities: vulns } = json;
if (vulns == null || !Array.isArray(vulns)) {
return;
}
const diagnostics: Diagnostic[] = vulns.map((vuln: Vulnerability) => {
let message = `${vuln.name}\n\n${vuln.description.substring(0, 200)}`;
if (vuln.description.length > 200) {
message += '...';
}
const severity =
vuln.severity === 'high' ? DiagnosticSeverity.Error : DiagnosticSeverity.Warning;
// TODO: Use a more precise range when it's available from the service.
return {
message,
range: {
start: {
line: vuln.location.start_line - 1,
character: 0,
},
end: {
line: vuln.location.end_line,
character: 0,
},
},
severity,
source: 'gitlab_security_scan',
};
});
await this.#publish({
uri: document.uri,
diagnostics,
});
} catch (error) {
log.warn('SecurityScan: failed to run security scan', error);
}
}
}
References:
- src/common/connection_service.ts:64
- src/common/security_diagnostics_publisher.test.ts:23 |
You are a code assistant | Definition of 'handleRequestMessage' in file src/common/webview/extension/handlers/handle_request_message.ts in project gitlab-lsp | Definition:
export const handleRequestMessage =
(handlerRegistry: ExtensionMessageHandlerRegistry, logger: Logger) =>
async (message: unknown): Promise<unknown> => {
if (!isExtensionMessage(message)) {
logger.debug(`Received invalid request message: ${JSON.stringify(message)}`);
throw new Error('Invalid message format');
}
const { webviewId, type, payload } = message;
try {
const result = await handlerRegistry.handle({ webviewId, type }, payload);
return result;
} catch (error) {
logger.error(
`Failed to handle notification for webviewId: ${webviewId}, type: ${type}, payload: ${JSON.stringify(payload)}`,
error as Error,
);
throw error;
}
};
References:
- src/common/webview/extension/extension_connection_message_bus_provider.ts:86 |
You are a code assistant | Definition of 'ChangeConfigOptions' in file src/common/suggestion/suggestion_service.ts in project gitlab-lsp | Definition:
export type ChangeConfigOptions = { settings: IClientConfig };
export type CustomInitializeParams = InitializeParams & {
initializationOptions?: IClientContext;
};
export const WORKFLOW_MESSAGE_NOTIFICATION = '$/gitlab/workflowMessage';
export interface SuggestionServiceOptions {
telemetryTracker: TelemetryTracker;
configService: ConfigService;
api: GitLabApiClient;
connection: Connection;
documentTransformerService: DocumentTransformerService;
treeSitterParser: TreeSitterParser;
featureFlagService: FeatureFlagService;
duoProjectAccessChecker: DuoProjectAccessChecker;
}
export interface ITelemetryNotificationParams {
category: 'code_suggestions';
action: TRACKING_EVENTS;
context: {
trackingId: string;
optionId?: number;
};
}
export interface IStartWorkflowParams {
goal: string;
image: string;
}
export const waitMs = (msToWait: number) =>
new Promise((resolve) => {
setTimeout(resolve, msToWait);
});
/* CompletionRequest represents LS client's request for either completion or inlineCompletion */
export interface CompletionRequest {
textDocument: TextDocumentIdentifier;
position: Position;
token: CancellationToken;
inlineCompletionContext?: InlineCompletionContext;
}
export class DefaultSuggestionService {
readonly #suggestionClientPipeline: SuggestionClientPipeline;
#configService: ConfigService;
#api: GitLabApiClient;
#tracker: TelemetryTracker;
#connection: Connection;
#documentTransformerService: DocumentTransformerService;
#circuitBreaker = new FixedTimeCircuitBreaker('Code Suggestion Requests');
#subscriptions: Disposable[] = [];
#suggestionsCache: SuggestionsCache;
#treeSitterParser: TreeSitterParser;
#duoProjectAccessChecker: DuoProjectAccessChecker;
#featureFlagService: FeatureFlagService;
#postProcessorPipeline = new PostProcessorPipeline();
constructor({
telemetryTracker,
configService,
api,
connection,
documentTransformerService,
featureFlagService,
treeSitterParser,
duoProjectAccessChecker,
}: SuggestionServiceOptions) {
this.#configService = configService;
this.#api = api;
this.#tracker = telemetryTracker;
this.#connection = connection;
this.#documentTransformerService = documentTransformerService;
this.#suggestionsCache = new SuggestionsCache(this.#configService);
this.#treeSitterParser = treeSitterParser;
this.#featureFlagService = featureFlagService;
const suggestionClient = new FallbackClient(
new DirectConnectionClient(this.#api, this.#configService),
new DefaultSuggestionClient(this.#api),
);
this.#suggestionClientPipeline = new SuggestionClientPipeline([
clientToMiddleware(suggestionClient),
createTreeSitterMiddleware({
treeSitterParser,
getIntentFn: getIntent,
}),
]);
this.#subscribeToCircuitBreakerEvents();
this.#duoProjectAccessChecker = duoProjectAccessChecker;
}
completionHandler = async (
{ textDocument, position }: CompletionParams,
token: CancellationToken,
): Promise<CompletionItem[]> => {
log.debug('Completion requested');
const suggestionOptions = await this.#getSuggestionOptions({ textDocument, position, token });
if (suggestionOptions.find(isStream)) {
log.warn(
`Completion response unexpectedly contained streaming response. Streaming for completion is not supported. Please report this issue.`,
);
}
return completionOptionMapper(suggestionOptions.filter(isTextSuggestion));
};
#getSuggestionOptions = async (
request: CompletionRequest,
): Promise<SuggestionOptionOrStream[]> => {
const { textDocument, position, token, inlineCompletionContext: context } = request;
const suggestionContext = this.#documentTransformerService.getContext(
textDocument.uri,
position,
this.#configService.get('client.workspaceFolders') ?? [],
context,
);
if (!suggestionContext) {
return [];
}
const cachedSuggestions = this.#useAndTrackCachedSuggestions(
textDocument,
position,
suggestionContext,
context?.triggerKind,
);
if (context?.triggerKind === InlineCompletionTriggerKind.Invoked) {
const options = await this.#handleNonStreamingCompletion(request, suggestionContext);
options.unshift(...(cachedSuggestions ?? []));
(cachedSuggestions ?? []).forEach((cs) =>
this.#tracker.updateCodeSuggestionsContext(cs.uniqueTrackingId, {
optionsCount: options.length,
}),
);
return options;
}
if (cachedSuggestions) {
return cachedSuggestions;
}
// debounce
await waitMs(SUGGESTIONS_DEBOUNCE_INTERVAL_MS);
if (token.isCancellationRequested) {
log.debug('Debounce triggered for completion');
return [];
}
if (
context &&
shouldRejectCompletionWithSelectedCompletionTextMismatch(
context,
this.#documentTransformerService.get(textDocument.uri),
)
) {
return [];
}
const additionalContexts = await this.#getAdditionalContexts(suggestionContext);
// right now we only support streaming for inlineCompletion
// if the context is present, we know we are handling inline completion
if (
context &&
this.#featureFlagService.isClientFlagEnabled(ClientFeatureFlags.StreamCodeGenerations)
) {
const intentResolution = await this.#getIntent(suggestionContext);
if (intentResolution?.intent === 'generation') {
return this.#handleStreamingInlineCompletion(
suggestionContext,
intentResolution.commentForCursor?.content,
intentResolution.generationType,
additionalContexts,
);
}
}
return this.#handleNonStreamingCompletion(request, suggestionContext, additionalContexts);
};
inlineCompletionHandler = async (
params: InlineCompletionParams,
token: CancellationToken,
): Promise<InlineCompletionList> => {
log.debug('Inline completion requested');
const options = await this.#getSuggestionOptions({
textDocument: params.textDocument,
position: params.position,
token,
inlineCompletionContext: params.context,
});
return inlineCompletionOptionMapper(params, options);
};
async #handleStreamingInlineCompletion(
context: IDocContext,
userInstruction?: string,
generationType?: GenerationType,
additionalContexts?: AdditionalContext[],
): Promise<StartStreamOption[]> {
if (this.#circuitBreaker.isOpen()) {
log.warn('Stream was not started as the circuit breaker is open.');
return [];
}
const streamId = uniqueId('code-suggestion-stream-');
const uniqueTrackingId = generateUniqueTrackingId();
setTimeout(() => {
log.debug(`Starting to stream (id: ${streamId})`);
const streamingHandler = new DefaultStreamingHandler({
api: this.#api,
circuitBreaker: this.#circuitBreaker,
connection: this.#connection,
documentContext: context,
parser: this.#treeSitterParser,
postProcessorPipeline: this.#postProcessorPipeline,
streamId,
tracker: this.#tracker,
uniqueTrackingId,
userInstruction,
generationType,
additionalContexts,
});
streamingHandler.startStream().catch((e: Error) => log.error('Failed to start streaming', e));
}, 0);
return [{ streamId, uniqueTrackingId }];
}
async #handleNonStreamingCompletion(
request: CompletionRequest,
documentContext: IDocContext,
additionalContexts?: AdditionalContext[],
): Promise<SuggestionOption[]> {
const uniqueTrackingId: string = generateUniqueTrackingId();
try {
return await this.#getSuggestions({
request,
uniqueTrackingId,
documentContext,
additionalContexts,
});
} catch (e) {
if (isFetchError(e)) {
this.#tracker.updateCodeSuggestionsContext(uniqueTrackingId, { status: e.status });
}
this.#tracker.updateSuggestionState(uniqueTrackingId, TRACKING_EVENTS.ERRORED);
this.#circuitBreaker.error();
log.error('Failed to get code suggestions!', e);
return [];
}
}
/**
* FIXME: unify how we get code completion and generation
* so we don't have duplicate intent detection (see `tree_sitter_middleware.ts`)
* */
async #getIntent(context: IDocContext): Promise<IntentResolution | undefined> {
try {
const treeAndLanguage = await this.#treeSitterParser.parseFile(context);
if (!treeAndLanguage) {
return undefined;
}
return await getIntent({
treeAndLanguage,
position: context.position,
prefix: context.prefix,
suffix: context.suffix,
});
} catch (error) {
log.error('Failed to parse with tree sitter', error);
return undefined;
}
}
#trackShowIfNeeded(uniqueTrackingId: string) {
if (
!canClientTrackEvent(
this.#configService.get('client.telemetry.actions'),
TRACKING_EVENTS.SHOWN,
)
) {
/* If the Client can detect when the suggestion is shown in the IDE, it will notify the Server.
Otherwise the server will assume that returned suggestions are shown and tracks the event */
this.#tracker.updateSuggestionState(uniqueTrackingId, TRACKING_EVENTS.SHOWN);
}
}
async #getSuggestions({
request,
uniqueTrackingId,
documentContext,
additionalContexts,
}: {
request: CompletionRequest;
uniqueTrackingId: string;
documentContext: IDocContext;
additionalContexts?: AdditionalContext[];
}): Promise<SuggestionOption[]> {
const { textDocument, position, token } = request;
const triggerKind = request.inlineCompletionContext?.triggerKind;
log.info('Suggestion requested.');
if (this.#circuitBreaker.isOpen()) {
log.warn('Code suggestions were not requested as the circuit breaker is open.');
return [];
}
if (!this.#configService.get('client.token')) {
return [];
}
// Do not send a suggestion if content is less than 10 characters
const contentLength =
(documentContext?.prefix?.length || 0) + (documentContext?.suffix?.length || 0);
if (contentLength < 10) {
return [];
}
if (!isAtOrNearEndOfLine(documentContext.suffix)) {
return [];
}
// Creates the suggestion and tracks suggestion_requested
this.#tracker.setCodeSuggestionsContext(uniqueTrackingId, {
documentContext,
triggerKind,
additionalContexts,
});
/** how many suggestion options should we request from the API */
const optionsCount: OptionsCount =
triggerKind === InlineCompletionTriggerKind.Invoked ? MANUAL_REQUEST_OPTIONS_COUNT : 1;
const suggestionsResponse = await this.#suggestionClientPipeline.getSuggestions({
document: documentContext,
projectPath: this.#configService.get('client.projectPath'),
optionsCount,
additionalContexts,
});
this.#tracker.updateCodeSuggestionsContext(uniqueTrackingId, {
model: suggestionsResponse?.model,
status: suggestionsResponse?.status,
optionsCount: suggestionsResponse?.choices?.length,
isDirectConnection: suggestionsResponse?.isDirectConnection,
});
if (suggestionsResponse?.error) {
throw new Error(suggestionsResponse.error);
}
this.#tracker.updateSuggestionState(uniqueTrackingId, TRACKING_EVENTS.LOADED);
this.#circuitBreaker.success();
const areSuggestionsNotProvided =
!suggestionsResponse?.choices?.length ||
suggestionsResponse?.choices.every(({ text }) => !text?.length);
const suggestionOptions = (suggestionsResponse?.choices || []).map((choice, index) => ({
...choice,
index,
uniqueTrackingId,
lang: suggestionsResponse?.model?.lang,
}));
const processedChoices = await this.#postProcessorPipeline.run({
documentContext,
input: suggestionOptions,
type: 'completion',
});
this.#suggestionsCache.addToSuggestionCache({
request: {
document: textDocument,
position,
context: documentContext,
additionalContexts,
},
suggestions: processedChoices,
});
if (token.isCancellationRequested) {
this.#tracker.updateSuggestionState(uniqueTrackingId, TRACKING_EVENTS.CANCELLED);
return [];
}
if (areSuggestionsNotProvided) {
this.#tracker.updateSuggestionState(uniqueTrackingId, TRACKING_EVENTS.NOT_PROVIDED);
return [];
}
this.#tracker.updateCodeSuggestionsContext(uniqueTrackingId, { suggestionOptions });
this.#trackShowIfNeeded(uniqueTrackingId);
return processedChoices;
}
dispose() {
this.#subscriptions.forEach((subscription) => subscription?.dispose());
}
#subscribeToCircuitBreakerEvents() {
this.#subscriptions.push(
this.#circuitBreaker.onOpen(() => this.#connection.sendNotification(API_ERROR_NOTIFICATION)),
);
this.#subscriptions.push(
this.#circuitBreaker.onClose(() =>
this.#connection.sendNotification(API_RECOVERY_NOTIFICATION),
),
);
}
#useAndTrackCachedSuggestions(
textDocument: TextDocumentIdentifier,
position: Position,
documentContext: IDocContext,
triggerKind?: InlineCompletionTriggerKind,
): SuggestionOption[] | undefined {
const suggestionsCache = this.#suggestionsCache.getCachedSuggestions({
document: textDocument,
position,
context: documentContext,
});
if (suggestionsCache?.options?.length) {
const { uniqueTrackingId, lang } = suggestionsCache.options[0];
const { additionalContexts } = suggestionsCache;
this.#tracker.setCodeSuggestionsContext(uniqueTrackingId, {
documentContext,
source: SuggestionSource.cache,
triggerKind,
suggestionOptions: suggestionsCache?.options,
language: lang,
additionalContexts,
});
this.#tracker.updateSuggestionState(uniqueTrackingId, TRACKING_EVENTS.LOADED);
this.#trackShowIfNeeded(uniqueTrackingId);
return suggestionsCache.options.map((option, index) => ({ ...option, index }));
}
return undefined;
}
async #getAdditionalContexts(documentContext: IDocContext): Promise<AdditionalContext[]> {
let additionalContexts: AdditionalContext[] = [];
const advancedContextEnabled = shouldUseAdvancedContext(
this.#featureFlagService,
this.#configService,
);
if (advancedContextEnabled) {
const advancedContext = await getAdvancedContext({
documentContext,
dependencies: { duoProjectAccessChecker: this.#duoProjectAccessChecker },
});
additionalContexts = advancedContextToRequestBody(advancedContext);
}
return additionalContexts;
}
}
References:
- src/common/message_handler.ts:111 |
You are a code assistant | Definition of 'isDetailedError' in file src/common/fetch_error.ts in project gitlab-lsp | Definition:
export function isDetailedError(object: unknown): object is DetailedError {
return Boolean((object as DetailedError).details);
}
export function isFetchError(object: unknown): object is FetchError {
return object instanceof FetchError;
}
export const stackToArray = (stack: string | undefined): string[] => (stack ?? '').split('\n');
export interface ResponseError extends Error {
status: number;
body?: unknown;
}
const getErrorType = (body: string): string | unknown => {
try {
const parsedBody = JSON.parse(body);
return parsedBody?.error;
} catch {
return undefined;
}
};
const isInvalidTokenError = (response: Response, body?: string) =>
Boolean(response.status === 401 && body && getErrorType(body) === 'invalid_token');
const isInvalidRefresh = (response: Response, body?: string) =>
Boolean(response.status === 400 && body && getErrorType(body) === 'invalid_grant');
export class FetchError extends Error implements ResponseError, DetailedError {
response: Response;
#body?: string;
constructor(response: Response, resourceName: string, body?: string) {
let message = `Fetching ${resourceName} from ${response.url} failed`;
if (isInvalidTokenError(response, body)) {
message = `Request for ${resourceName} failed because the token is expired or revoked.`;
}
if (isInvalidRefresh(response, body)) {
message = `Request to refresh token failed, because it's revoked or already refreshed.`;
}
super(message);
this.response = response;
this.#body = body;
}
get status() {
return this.response.status;
}
isInvalidToken(): boolean {
return (
isInvalidTokenError(this.response, this.#body) || isInvalidRefresh(this.response, this.#body)
);
}
get details() {
const { message, stack } = this;
return {
message,
stack: stackToArray(stack),
response: {
status: this.response.status,
headers: this.response.headers,
body: this.#body,
},
};
}
}
export class TimeoutError extends Error {
constructor(url: URL | RequestInfo) {
const timeoutInSeconds = Math.round(REQUEST_TIMEOUT_MILLISECONDS / 1000);
super(
`Request to ${extractURL(url)} timed out after ${timeoutInSeconds} second${timeoutInSeconds === 1 ? '' : 's'}`,
);
}
}
export class InvalidInstanceVersionError extends Error {}
References:
- src/common/log.ts:33 |
You are a code assistant | Definition of 'CODE_SUGGESTIONS_RESPONSE' in file src/common/test_utils/mocks.ts in project gitlab-lsp | Definition:
export const CODE_SUGGESTIONS_RESPONSE: CodeSuggestionResponse = {
choices: [
{ text: 'choice1', uniqueTrackingId: 'ut1' },
{ text: 'choice2', uniqueTrackingId: 'ut2' },
],
status: 200,
};
export const INITIALIZE_PARAMS: CustomInitializeParams = {
clientInfo: {
name: 'Visual Studio Code',
version: '1.82.0',
},
capabilities: { textDocument: { completion: {}, inlineCompletion: {} } },
rootUri: '/',
initializationOptions: {},
processId: 1,
};
export const EMPTY_COMPLETION_CONTEXT: IDocContext = {
prefix: '',
suffix: '',
fileRelativePath: 'test.js',
position: {
line: 0,
character: 0,
},
uri: 'file:///example.ts',
languageId: 'javascript',
};
export const SHORT_COMPLETION_CONTEXT: IDocContext = {
prefix: 'abc',
suffix: 'def',
fileRelativePath: 'test.js',
position: {
line: 0,
character: 3,
},
uri: 'file:///example.ts',
languageId: 'typescript',
};
export const LONG_COMPLETION_CONTEXT: IDocContext = {
prefix: 'abc 123',
suffix: 'def 456',
fileRelativePath: 'test.js',
position: {
line: 0,
character: 7,
},
uri: 'file:///example.ts',
languageId: 'typescript',
};
const textDocument: TextDocumentIdentifier = { uri: '/' };
const position: Position = { line: 0, character: 0 };
export const COMPLETION_PARAMS: TextDocumentPositionParams = { textDocument, position };
References: |
You are a code assistant | Definition of 'solve' in file packages/lib-pkg-1/src/simple_fibonacci_solver.ts in project gitlab-lsp | Definition:
solve(index: number): number {
if (index <= 1) return index;
return this.solve(index - 1) + this.solve(index - 2);
}
}
References: |
You are a code assistant | Definition of 'DidChangeWorkspaceFoldersHandler' in file src/common/core/handlers/did_change_workspace_folders_handler.ts in project gitlab-lsp | Definition:
export const DidChangeWorkspaceFoldersHandler =
createInterfaceId<DidChangeWorkspaceFoldersHandler>('InitializeHandler');
@Injectable(DidChangeWorkspaceFoldersHandler, [ConfigService])
export class DefaultDidChangeWorkspaceFoldersHandler implements DidChangeWorkspaceFoldersHandler {
#configService: ConfigService;
constructor(configService: ConfigService) {
this.#configService = configService;
}
notificationHandler: NotificationHandler<WorkspaceFoldersChangeEvent> = (
params: WorkspaceFoldersChangeEvent,
): void => {
const { added, removed } = params;
const removedKeys = removed.map(({ name }) => name);
const currentWorkspaceFolders = this.#configService.get('client.workspaceFolders') || [];
const afterRemoved = currentWorkspaceFolders.filter((f) => !removedKeys.includes(f.name));
const afterAdded = [...afterRemoved, ...(added || [])];
this.#configService.set('client.workspaceFolders', afterAdded);
};
}
References:
- src/common/connection_service.ts:63
- src/common/core/handlers/did_change_workspace_folders_handler.test.ts:14 |
You are a code assistant | Definition of 'greet' in file src/tests/fixtures/intent/empty_function/javascript.js in project gitlab-lsp | Definition:
function greet(name) {}
function greet2(name) {
console.log(name);
}
const greet3 = function (name) {};
const greet4 = function (name) {
console.log(name);
};
const greet5 = (name) => {};
const greet6 = (name) => {
console.log(name);
};
class Greet {
constructor(name) {}
greet() {}
}
class Greet2 {
constructor(name) {
this.name = name;
}
greet() {
console.log(`Hello ${this.name}`);
}
}
class Greet3 {}
function* generateGreetings() {}
function* greetGenerator() {
yield 'Hello';
}
References:
- src/tests/fixtures/intent/empty_function/ruby.rb:29
- src/tests/fixtures/intent/empty_function/ruby.rb:1
- src/tests/fixtures/intent/ruby_comments.rb:21
- src/tests/fixtures/intent/empty_function/ruby.rb:20 |
You are a code assistant | Definition of 'error' in file src/common/circuit_breaker/circuit_breaker.ts in project gitlab-lsp | Definition:
error(): void;
success(): void;
isOpen(): boolean;
onOpen(listener: () => void): Disposable;
onClose(listener: () => void): Disposable;
}
References:
- scripts/commit-lint/lint.js:77
- scripts/commit-lint/lint.js:85
- scripts/commit-lint/lint.js:94
- scripts/commit-lint/lint.js:72 |
You are a code assistant | Definition of 'init' in file src/common/tree_sitter/parser.ts in project gitlab-lsp | Definition:
abstract init(): Promise<void>;
constructor({ languages }: { languages: TreeSitterLanguageInfo[] }) {
this.languages = this.buildTreeSitterInfoByExtMap(languages);
this.loadState = TreeSitterParserLoadState.INIT;
}
get loadStateValue(): TreeSitterParserLoadState {
return this.loadState;
}
async parseFile(context: IDocContext): Promise<TreeAndLanguage | undefined> {
const init = await this.#handleInit();
if (!init) {
return undefined;
}
const languageInfo = this.getLanguageInfoForFile(context.fileRelativePath);
if (!languageInfo) {
return undefined;
}
const parser = await this.getParser(languageInfo);
if (!parser) {
log.debug(
'TreeSitterParser: Skipping intent detection using tree-sitter due to missing parser.',
);
return undefined;
}
const tree = parser.parse(`${context.prefix}${context.suffix}`);
return {
tree,
language: parser.getLanguage(),
languageInfo,
};
}
async #handleInit(): Promise<boolean> {
try {
await this.init();
return true;
} catch (err) {
log.warn('TreeSitterParser: Error initializing an appropriate tree-sitter parser', err);
this.loadState = TreeSitterParserLoadState.ERRORED;
}
return false;
}
getLanguageNameForFile(filename: string): TreeSitterLanguageName | undefined {
return this.getLanguageInfoForFile(filename)?.name;
}
async getParser(languageInfo: TreeSitterLanguageInfo): Promise<Parser | undefined> {
if (this.parsers.has(languageInfo.name)) {
return this.parsers.get(languageInfo.name) as Parser;
}
try {
const parser = new Parser();
const language = await Parser.Language.load(languageInfo.wasmPath);
parser.setLanguage(language);
this.parsers.set(languageInfo.name, parser);
log.debug(
`TreeSitterParser: Loaded tree-sitter parser (tree-sitter-${languageInfo.name}.wasm present).`,
);
return parser;
} catch (err) {
this.loadState = TreeSitterParserLoadState.ERRORED;
// NOTE: We validate the below is not present in generation.test.ts integration test.
// Make sure to update the test appropriately if changing the error.
log.warn(
'TreeSitterParser: Unable to load tree-sitter parser due to an unexpected error.',
err,
);
return undefined;
}
}
getLanguageInfoForFile(filename: string): TreeSitterLanguageInfo | undefined {
const ext = filename.split('.').pop();
return this.languages.get(`.${ext}`);
}
buildTreeSitterInfoByExtMap(
languages: TreeSitterLanguageInfo[],
): Map<string, TreeSitterLanguageInfo> {
return languages.reduce((map, language) => {
for (const extension of language.extensions) {
map.set(extension, language);
}
return map;
}, new Map<string, TreeSitterLanguageInfo>());
}
}
References: |
You are a code assistant | Definition of 'onLanguageChange' in file src/common/suggestion/supported_languages_service.ts in project gitlab-lsp | Definition:
onLanguageChange(listener: () => void): Disposable;
}
export const SupportedLanguagesService = createInterfaceId<SupportedLanguagesService>(
'SupportedLanguagesService',
);
@Injectable(SupportedLanguagesService, [ConfigService])
export class DefaultSupportedLanguagesService implements SupportedLanguagesService {
#enabledLanguages: Set<string>;
#supportedLanguages: Set<string>;
#configService: ConfigService;
#eventEmitter = new EventEmitter();
constructor(configService: ConfigService) {
this.#enabledLanguages = new Set(BASE_SUPPORTED_CODE_SUGGESTIONS_LANGUAGES);
this.#supportedLanguages = new Set(BASE_SUPPORTED_CODE_SUGGESTIONS_LANGUAGES);
this.#configService = configService;
this.#configService.onConfigChange(() => this.#update());
}
#getConfiguredLanguages() {
const languages: SupportedLanguagesUpdateParam = {};
const additionalLanguages = this.#configService.get(
'client.codeCompletion.additionalLanguages',
);
if (Array.isArray(additionalLanguages)) {
languages.allow = additionalLanguages.map(this.#normalizeLanguageIdentifier);
} else {
log.warn(
'Failed to parse user-configured Code Suggestions languages. Code Suggestions will still work for the default languages.',
);
}
const disabledSupportedLanguages = this.#configService.get(
'client.codeCompletion.disabledSupportedLanguages',
);
if (Array.isArray(disabledSupportedLanguages)) {
languages.deny = disabledSupportedLanguages;
} else {
log.warn(
'Invalid configuration for disabled Code Suggestions languages. All default languages remain enabled.',
);
}
return languages;
}
#update() {
const { allow = [], deny = [] } = this.#getConfiguredLanguages();
const newSet: Set<string> = new Set(BASE_SUPPORTED_CODE_SUGGESTIONS_LANGUAGES);
for (const language of allow) {
newSet.add(language.trim());
}
for (const language of deny) {
newSet.delete(language);
}
if (newSet.size === 0) {
log.warn('All languages have been disabled for Code Suggestions.');
}
const previousEnabledLanguages = this.#enabledLanguages;
this.#enabledLanguages = newSet;
if (!isEqual(previousEnabledLanguages, this.#enabledLanguages)) {
this.#triggerChange();
}
}
isLanguageSupported(languageId: string) {
return this.#supportedLanguages.has(languageId);
}
isLanguageEnabled(languageId: string) {
return this.#enabledLanguages.has(languageId);
}
onLanguageChange(listener: () => void): Disposable {
this.#eventEmitter.on('languageChange', listener);
return { dispose: () => this.#eventEmitter.removeListener('configChange', listener) };
}
#triggerChange() {
this.#eventEmitter.emit('languageChange');
}
#normalizeLanguageIdentifier(language: string) {
return language.trim().toLowerCase().replace(/^\./, '');
}
}
References: |
You are a code assistant | Definition of 'isSocketResponseMessage' in file packages/lib_webview_transport_socket_io/src/utils/message_utils.ts in project gitlab-lsp | Definition:
export function isSocketResponseMessage(message: unknown): message is SocketResponseMessage {
return (
typeof message === 'object' &&
message !== null &&
'requestId' in message &&
typeof message.requestId === 'string'
);
}
References:
- packages/lib_webview_transport_socket_io/src/socket_io_webview_transport.ts:98 |
You are a code assistant | Definition of 'constructor' in file src/common/graphql/workflow/service.ts in project gitlab-lsp | Definition:
constructor(apiClient: GitLabApiClient, logger: Logger) {
this.#apiClient = apiClient;
this.#logger = withPrefix(logger, '[WorkflowGraphQLService]');
}
generateWorkflowID(id: string): string {
return `gid://gitlab/Ai::DuoWorkflows::Workflow/${id}`;
}
sortCheckpoints(checkpoints: LangGraphCheckpoint[]) {
return [...checkpoints].sort((a: LangGraphCheckpoint, b: LangGraphCheckpoint) => {
const parsedCheckpointA = JSON.parse(a.checkpoint);
const parsedCheckpointB = JSON.parse(b.checkpoint);
return new Date(parsedCheckpointA.ts).getTime() - new Date(parsedCheckpointB.ts).getTime();
});
}
getStatus(checkpoints: LangGraphCheckpoint[]): string {
const startingCheckpoint: LangGraphCheckpoint = {
checkpoint: '{ "channel_values": { "status": "Starting" }}',
};
const lastCheckpoint = checkpoints.at(-1) || startingCheckpoint;
const checkpoint = JSON.parse(lastCheckpoint.checkpoint);
return checkpoint?.channel_values?.status;
}
async pollWorkflowEvents(id: string, messageBus: MessageBus): Promise<void> {
const workflowId = this.generateWorkflowID(id);
let timeout: NodeJS.Timeout;
const poll = async (): Promise<void> => {
try {
const checkpoints: LangGraphCheckpoint[] = await this.getWorkflowEvents(workflowId);
messageBus.sendNotification('workflowCheckpoints', checkpoints);
const status = this.getStatus(checkpoints);
messageBus.sendNotification('workflowStatus', status);
// If the status is Completed, we dont call the next setTimeout and polling stops
if (status !== 'Completed') {
timeout = setTimeout(poll, 3000);
} else {
clearTimeout(timeout);
}
} catch (e) {
const error = e as Error;
this.#logger.error(error.message);
throw new Error(error.message);
}
};
await poll();
}
async getWorkflowEvents(id: string): Promise<LangGraphCheckpoint[]> {
try {
const data: DuoWorkflowEventConnectionType = await this.#apiClient.fetchFromApi({
type: 'graphql',
query: GET_WORKFLOW_EVENTS_QUERY,
variables: { workflowId: id },
});
return this.sortCheckpoints(data?.duoWorkflowEvents?.nodes || []);
} catch (e) {
const error = e as Error;
this.#logger.error(error.message);
throw new Error(error.message);
}
}
}
References: |
You are a code assistant | Definition of 'FeatureStateChangeNotificationType' in file src/common/notifications.ts in project gitlab-lsp | Definition:
export const FeatureStateChangeNotificationType =
new NotificationType<FeatureStateNotificationParams>(FEATURE_STATE_CHANGE);
export interface TokenCheckNotificationParams {
message?: string;
}
export const TokenCheckNotificationType = new NotificationType<TokenCheckNotificationParams>(
TOKEN_CHECK_NOTIFICATION,
);
// TODO: once the following clients are updated:
//
// - JetBrains: https://gitlab.com/gitlab-org/editor-extensions/gitlab-jetbrains-plugin/-/blob/main/src/main/kotlin/com/gitlab/plugin/lsp/GitLabLanguageServer.kt#L16
//
// We should remove the `TextDocument` type from the parameter since it's deprecated
export type DidChangeDocumentInActiveEditorParams = TextDocument | DocumentUri;
export const DidChangeDocumentInActiveEditor =
new NotificationType<DidChangeDocumentInActiveEditorParams>(
'$/gitlab/didChangeDocumentInActiveEditor',
);
References: |
You are a code assistant | Definition of 'solve' in file packages/lib-pkg-2/src/fast_fibonacci_solver.ts in project gitlab-lsp | Definition:
solve(index: number): number {
if (index < 0) {
throw NegativeIndexError;
}
if (this.#memo.has(index)) {
return this.#memo.get(index) as number;
}
let a = this.#memo.get(this.#lastComputedIndex - 1) as number;
let b = this.#memo.get(this.#lastComputedIndex) as number;
for (let i = this.#lastComputedIndex + 1; i <= index; i++) {
const nextValue = a + b;
a = b;
b = nextValue;
this.#memo.set(i, nextValue);
}
this.#lastComputedIndex = index;
return this.#memo.get(index) as number;
}
}
References: |
You are a code assistant | Definition of 'createFakeResponse' in file src/common/test_utils/create_fake_response.ts in project gitlab-lsp | Definition:
export const createFakeResponse = ({
status = 200,
text = '',
json = {},
url = '',
headers = {},
}: FakeResponseOptions): Response => {
return createFakePartial<Response>({
ok: status >= 200 && status < 400,
status,
url,
text: () => Promise.resolve(text),
json: () => Promise.resolve(json),
headers: new Headers(headers),
body: new ReadableStream({
start(controller) {
// Add text (as Uint8Array) to the stream
controller.enqueue(new TextEncoder().encode(text));
},
}),
});
};
References:
- src/common/api.test.ts:273
- src/common/api.test.ts:102
- src/common/suggestion_client/direct_connection_client.test.ts:47
- src/common/api.test.ts:340
- src/common/handle_fetch_error.test.ts:21
- src/common/handle_fetch_error.test.ts:31
- src/common/suggestion/suggestion_service.test.ts:295
- src/common/security_diagnostics_publisher.test.ts:114
- src/common/handle_fetch_error.test.ts:9
- src/common/api.test.ts:475
- src/common/suggestion/streaming_handler.test.ts:319
- src/common/api.test.ts:403
- src/common/api.test.ts:59
- src/common/suggestion/suggestion_service.test.ts:889
- src/common/api.test.ts:419
- src/common/suggestion_client/direct_connection_client.test.ts:200
- src/common/api.test.ts:478 |
You are a code assistant | Definition of 'sendNotification' in file src/common/webview/extension/extension_connection_message_bus.ts in project gitlab-lsp | Definition:
async sendNotification<T extends keyof TMessageMap['outbound']['notifications'] & string>(
type: T,
payload?: TMessageMap['outbound']['notifications'][T],
): Promise<void> {
await this.#connection.sendNotification(this.#rpcMethods.notification, {
webviewId: this.#webviewId,
type,
payload,
});
}
}
References: |
You are a code assistant | Definition of 'ChatPlatformForAccount' in file packages/webview_duo_chat/src/plugin/chat_platform.ts in project gitlab-lsp | Definition:
export class ChatPlatformForAccount extends ChatPlatform implements GitLabPlatformForAccount {
readonly type = 'account' as const;
project: undefined;
}
export class ChatPlatformForProject extends ChatPlatform implements GitLabPlatformForProject {
readonly type = 'project' as const;
project: GitLabProject = {
gqlId: 'gid://gitlab/Project/123456',
restId: 0,
name: '',
description: '',
namespaceWithPath: '',
webUrl: '',
};
}
References:
- packages/webview_duo_chat/src/plugin/chat_platform_manager.ts:26
- packages/webview_duo_chat/src/plugin/chat_platform_manager.ts:30
- packages/webview_duo_chat/src/plugin/chat_platform_manager.ts:22 |
You are a code assistant | Definition of 'Greet2' in file src/tests/fixtures/intent/empty_function/python.py in project gitlab-lsp | Definition:
class Greet2:
def __init__(self, name):
self.name = name
def greet(self):
print(f"Hello {self.name}")
class Greet3:
pass
def greet3(name):
...
class Greet4:
def __init__(self, name):
...
def greet(self):
...
class Greet3:
...
def greet3(name):
class Greet4:
def __init__(self, name):
def greet(self):
class Greet3:
References:
- src/tests/fixtures/intent/empty_function/ruby.rb:24 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.