instruction,input,output You are a code assistant,Definition of 'onClose' in file src/common/circuit_breaker/fixed_time_circuit_breaker.ts in project gitlab-lsp,"Definition: onClose(listener: () => void): Disposable { this.#eventEmitter.on('close', listener); return { dispose: () => this.#eventEmitter.removeListener('close', listener) }; } } References:" You are a code assistant,Definition of 'init' in file src/node/tree_sitter/parser.ts in project gitlab-lsp,"Definition: async init(): Promise { try { await Parser.init(); log.debug('DesktopTreeSitterParser: Initialized tree-sitter parser.'); this.loadState = TreeSitterParserLoadState.READY; } catch (err) { log.warn('DesktopTreeSitterParser: Error initializing tree-sitter parsers.', err); this.loadState = TreeSitterParserLoadState.ERRORED; } } } References:" You are a code assistant,Definition of 'INITIALIZE_PARAMS' in file src/common/test_utils/mocks.ts in project gitlab-lsp,"Definition: 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 'WebviewTransportEventEmitter' in file packages/lib_webview_transport_socket_io/src/utils/webview_transport_event_emitter.ts in project gitlab-lsp,"Definition: export type WebviewTransportEventEmitter = TypedEmitter; export const createWebviewTransportEventEmitter = (): WebviewTransportEventEmitter => new EventEmitter() as WebviewTransportEventEmitter; References: - packages/lib_webview_transport_json_rpc/src/json_rpc_connection_transport.ts:43 - packages/lib_webview_transport_socket_io/src/utils/webview_transport_event_emitter.ts:11 - packages/lib_webview_transport_json_rpc/src/json_rpc_connection_transport.ts:35 - packages/lib_webview_transport_json_rpc/src/json_rpc_connection_transport.ts:27 - packages/lib_webview_transport_json_rpc/src/utils/webview_transport_event_emitter.ts:11" You are a code assistant,Definition of 'TestType' in file src/tests/unit/tree_sitter/intent_resolver.test.ts in project gitlab-lsp,"Definition: type TestType = | 'empty_function_declaration' | 'non_empty_function_declaration' | 'empty_function_expression' | 'non_empty_function_expression' | 'empty_arrow_function' | 'non_empty_arrow_function' | 'empty_method_definition' | 'non_empty_method_definition' | 'empty_class_constructor' | 'non_empty_class_constructor' | 'empty_class_declaration' | 'non_empty_class_declaration' | 'empty_anonymous_function' | 'non_empty_anonymous_function' | 'empty_implementation' | 'non_empty_implementation' | 'empty_closure_expression' | 'non_empty_closure_expression' | 'empty_generator' | 'non_empty_generator' | 'empty_macro' | 'non_empty_macro'; type FileExtension = string; /** * Position refers to the position of the cursor in the test file. */ type IntentTestCase = [TestType, Position, Intent]; const emptyFunctionTestCases: Array< [LanguageServerLanguageId, FileExtension, IntentTestCase[]] > = [ [ 'typescript', '.ts', // ../../fixtures/intent/empty_function/typescript.ts [ ['empty_function_declaration', { line: 0, character: 22 }, 'generation'], ['non_empty_function_declaration', { line: 3, character: 4 }, undefined], ['empty_function_expression', { line: 6, character: 32 }, 'generation'], ['non_empty_function_expression', { line: 10, character: 4 }, undefined], ['empty_arrow_function', { line: 12, character: 26 }, 'generation'], ['non_empty_arrow_function', { line: 15, character: 4 }, undefined], ['empty_class_constructor', { line: 19, character: 21 }, 'generation'], ['empty_method_definition', { line: 21, character: 11 }, 'generation'], ['non_empty_class_constructor', { line: 29, character: 7 }, undefined], ['non_empty_method_definition', { line: 33, character: 0 }, undefined], ['empty_class_declaration', { line: 36, character: 14 }, 'generation'], ['empty_generator', { line: 38, character: 31 }, 'generation'], ['non_empty_generator', { line: 41, character: 4 }, undefined], ], ], [ 'javascript', '.js', // ../../fixtures/intent/empty_function/javascript.js [ ['empty_function_declaration', { line: 0, character: 22 }, 'generation'], ['non_empty_function_declaration', { line: 3, character: 4 }, undefined], ['empty_function_expression', { line: 6, character: 32 }, 'generation'], ['non_empty_function_expression', { line: 10, character: 4 }, undefined], ['empty_arrow_function', { line: 12, character: 26 }, 'generation'], ['non_empty_arrow_function', { line: 15, character: 4 }, undefined], ['empty_class_constructor', { line: 19, character: 21 }, 'generation'], ['empty_method_definition', { line: 21, character: 11 }, 'generation'], ['non_empty_class_constructor', { line: 27, character: 7 }, undefined], ['non_empty_method_definition', { line: 31, character: 0 }, undefined], ['empty_class_declaration', { line: 34, character: 14 }, 'generation'], ['empty_generator', { line: 36, character: 31 }, 'generation'], ['non_empty_generator', { line: 39, character: 4 }, undefined], ], ], [ 'go', '.go', // ../../fixtures/intent/empty_function/go.go [ ['empty_function_declaration', { line: 0, character: 25 }, 'generation'], ['non_empty_function_declaration', { line: 3, character: 4 }, undefined], ['empty_anonymous_function', { line: 6, character: 32 }, 'generation'], ['non_empty_anonymous_function', { line: 10, character: 0 }, undefined], ['empty_method_definition', { line: 19, character: 25 }, 'generation'], ['non_empty_method_definition', { line: 23, character: 0 }, undefined], ], ], [ 'java', '.java', // ../../fixtures/intent/empty_function/java.java [ ['empty_function_declaration', { line: 0, character: 26 }, 'generation'], ['non_empty_function_declaration', { line: 3, character: 4 }, undefined], ['empty_anonymous_function', { line: 7, character: 0 }, 'generation'], ['non_empty_anonymous_function', { line: 10, character: 0 }, undefined], ['empty_class_declaration', { line: 15, character: 18 }, 'generation'], ['non_empty_class_declaration', { line: 19, character: 0 }, undefined], ['empty_class_constructor', { line: 18, character: 13 }, 'generation'], ['empty_method_definition', { line: 20, character: 18 }, 'generation'], ['non_empty_class_constructor', { line: 26, character: 18 }, undefined], ['non_empty_method_definition', { line: 30, character: 18 }, undefined], ], ], [ 'rust', '.rs', // ../../fixtures/intent/empty_function/rust.vue [ ['empty_function_declaration', { line: 0, character: 23 }, 'generation'], ['non_empty_function_declaration', { line: 3, character: 4 }, undefined], ['empty_implementation', { line: 8, character: 13 }, 'generation'], ['non_empty_implementation', { line: 11, character: 0 }, undefined], ['empty_class_constructor', { line: 13, character: 0 }, 'generation'], ['non_empty_class_constructor', { line: 23, character: 0 }, undefined], ['empty_method_definition', { line: 17, character: 0 }, 'generation'], ['non_empty_method_definition', { line: 26, character: 0 }, undefined], ['empty_closure_expression', { line: 32, character: 0 }, 'generation'], ['non_empty_closure_expression', { line: 36, character: 0 }, undefined], ['empty_macro', { line: 42, character: 11 }, 'generation'], ['non_empty_macro', { line: 45, character: 11 }, undefined], ['empty_macro', { line: 55, character: 0 }, 'generation'], ['non_empty_macro', { line: 62, character: 20 }, undefined], ], ], [ 'kotlin', '.kt', // ../../fixtures/intent/empty_function/kotlin.kt [ ['empty_function_declaration', { line: 0, character: 25 }, 'generation'], ['non_empty_function_declaration', { line: 4, character: 0 }, undefined], ['empty_anonymous_function', { line: 6, character: 32 }, 'generation'], ['non_empty_anonymous_function', { line: 9, character: 4 }, undefined], ['empty_class_declaration', { line: 12, character: 14 }, 'generation'], ['non_empty_class_declaration', { line: 15, character: 14 }, undefined], ['empty_method_definition', { line: 24, character: 0 }, 'generation'], ['non_empty_method_definition', { line: 28, character: 0 }, undefined], ], ], [ 'typescriptreact', '.tsx', // ../../fixtures/intent/empty_function/typescriptreact.tsx [ ['empty_function_declaration', { line: 0, character: 22 }, 'generation'], ['non_empty_function_declaration', { line: 3, character: 4 }, undefined], ['empty_function_expression', { line: 6, character: 32 }, 'generation'], ['non_empty_function_expression', { line: 10, character: 4 }, undefined], ['empty_arrow_function', { line: 12, character: 26 }, 'generation'], ['non_empty_arrow_function', { line: 15, character: 4 }, undefined], ['empty_class_constructor', { line: 19, character: 21 }, 'generation'], ['empty_method_definition', { line: 21, character: 11 }, 'generation'], ['non_empty_class_constructor', { line: 29, character: 7 }, undefined], ['non_empty_method_definition', { line: 33, character: 0 }, undefined], ['empty_class_declaration', { line: 36, character: 14 }, 'generation'], ['non_empty_arrow_function', { line: 40, character: 0 }, undefined], ['empty_arrow_function', { line: 41, character: 23 }, 'generation'], ['non_empty_arrow_function', { line: 44, character: 23 }, undefined], ['empty_generator', { line: 54, character: 31 }, 'generation'], ['non_empty_generator', { line: 57, character: 4 }, undefined], ], ], [ 'c', '.c', // ../../fixtures/intent/empty_function/c.c [ ['empty_function_declaration', { line: 0, character: 24 }, 'generation'], ['non_empty_function_declaration', { line: 3, character: 0 }, undefined], ], ], [ 'cpp', '.cpp', // ../../fixtures/intent/empty_function/cpp.cpp [ ['empty_function_declaration', { line: 0, character: 37 }, 'generation'], ['non_empty_function_declaration', { line: 3, character: 0 }, undefined], ['empty_function_expression', { line: 6, character: 43 }, 'generation'], ['non_empty_function_expression', { line: 10, character: 4 }, undefined], ['empty_class_constructor', { line: 15, character: 37 }, 'generation'], ['empty_method_definition', { line: 17, character: 18 }, 'generation'], ['non_empty_class_constructor', { line: 27, character: 7 }, undefined], ['non_empty_method_definition', { line: 31, character: 0 }, undefined], ['empty_class_declaration', { line: 35, character: 14 }, 'generation'], ], ], [ 'c_sharp', '.cs', // ../../fixtures/intent/empty_function/c_sharp.cs [ ['empty_function_expression', { line: 2, character: 48 }, 'generation'], ['empty_class_constructor', { line: 4, character: 31 }, 'generation'], ['empty_method_definition', { line: 6, character: 31 }, 'generation'], ['non_empty_class_constructor', { line: 15, character: 0 }, undefined], ['non_empty_method_definition', { line: 20, character: 0 }, undefined], ['empty_class_declaration', { line: 24, character: 22 }, 'generation'], ], ], [ 'bash', '.sh', // ../../fixtures/intent/empty_function/bash.sh [ ['empty_function_declaration', { line: 3, character: 48 }, 'generation'], ['non_empty_function_declaration', { line: 6, character: 31 }, undefined], ], ], [ 'scala', '.scala', // ../../fixtures/intent/empty_function/scala.scala [ ['empty_function_declaration', { line: 1, character: 4 }, 'generation'], ['non_empty_function_declaration', { line: 5, character: 4 }, undefined], ['empty_method_definition', { line: 28, character: 3 }, 'generation'], ['non_empty_method_definition', { line: 34, character: 3 }, undefined], ['empty_class_declaration', { line: 22, character: 4 }, 'generation'], ['non_empty_class_declaration', { line: 27, character: 0 }, undefined], ['empty_anonymous_function', { line: 13, character: 0 }, 'generation'], ['non_empty_anonymous_function', { line: 17, character: 0 }, undefined], ], ], [ 'ruby', '.rb', // ../../fixtures/intent/empty_function/ruby.rb [ ['empty_method_definition', { line: 0, character: 23 }, 'generation'], ['empty_method_definition', { line: 0, character: 6 }, undefined], ['non_empty_method_definition', { line: 3, character: 0 }, undefined], ['empty_anonymous_function', { line: 7, character: 27 }, 'generation'], ['non_empty_anonymous_function', { line: 9, character: 37 }, undefined], ['empty_anonymous_function', { line: 11, character: 25 }, 'generation'], ['empty_class_constructor', { line: 16, character: 22 }, 'generation'], ['non_empty_class_declaration', { line: 18, character: 0 }, undefined], ['empty_method_definition', { line: 20, character: 1 }, 'generation'], ['empty_class_declaration', { line: 33, character: 12 }, 'generation'], ], ], [ 'python', '.py', // ../../fixtures/intent/empty_function/python.py [ ['empty_function_declaration', { line: 1, character: 4 }, 'generation'], ['non_empty_function_declaration', { line: 5, character: 4 }, undefined], ['empty_class_constructor', { line: 10, character: 0 }, 'generation'], ['empty_method_definition', { line: 14, character: 0 }, 'generation'], ['non_empty_class_constructor', { line: 19, character: 0 }, undefined], ['non_empty_method_definition', { line: 23, character: 4 }, undefined], ['empty_class_declaration', { line: 27, character: 4 }, 'generation'], ['empty_function_declaration', { line: 31, character: 4 }, 'generation'], ['empty_class_constructor', { line: 36, character: 4 }, 'generation'], ['empty_method_definition', { line: 40, character: 4 }, 'generation'], ['empty_class_declaration', { line: 44, character: 4 }, 'generation'], ['empty_function_declaration', { line: 49, character: 4 }, 'generation'], ['empty_class_constructor', { line: 53, character: 4 }, 'generation'], ['empty_method_definition', { line: 56, character: 4 }, 'generation'], ['empty_class_declaration', { line: 59, character: 4 }, 'generation'], ], ], ]; describe.each(emptyFunctionTestCases)('%s', (language, fileExt, cases) => { it.each(cases)('should resolve %s intent correctly', async (_, position, expectedIntent) => { const fixturePath = getFixturePath('intent', `empty_function/${language}${fileExt}`); const { treeAndLanguage, prefix, suffix } = await getTreeAndTestFile({ fixturePath, position, languageId: language, }); const intent = await getIntent({ treeAndLanguage, position, prefix, suffix }); expect(intent.intent).toBe(expectedIntent); if (expectedIntent === 'generation') { expect(intent.generationType).toBe('empty_function'); } }); }); }); }); References:" You are a code assistant,Definition of 'AiContextFileRetriever' in file src/common/ai_context_management_2/retrievers/ai_file_context_retriever.ts in project gitlab-lsp,"Definition: export interface AiContextFileRetriever extends DefaultAiContextFileRetriever {} export const AiContextFileRetriever = createInterfaceId('AiContextFileRetriever'); @Injectable(AiContextFileRetriever, [FileResolver, SecretRedactor]) export class DefaultAiContextFileRetriever implements AiContextRetriever { constructor( private fileResolver: FileResolver, private secretRedactor: SecretRedactor, ) {} async retrieve(aiContextItem: AiContextItem): Promise { if (aiContextItem.type !== 'file') { return null; } try { log.info(`retrieving file ${aiContextItem.id}`); const fileContent = await this.fileResolver.readFile({ fileUri: aiContextItem.id, }); log.info(`redacting secrets for file ${aiContextItem.id}`); const redactedContent = this.secretRedactor.redactSecrets(fileContent); return redactedContent; } catch (e) { log.warn(`Failed to retrieve file ${aiContextItem.id}`, e); return null; } } } References: - src/common/ai_context_management_2/ai_context_manager.ts:13 - src/common/ai_context_management_2/ai_context_manager.ts:15" You are a code assistant,Definition of 'EMPTY_COMPLETION_CONTEXT' in file src/common/test_utils/mocks.ts in project gitlab-lsp,"Definition: 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 'updateCodeSuggestionsContext' in file src/common/tracking/tracking_types.ts in project gitlab-lsp,"Definition: updateCodeSuggestionsContext( uniqueTrackingId: string, contextUpdate: Partial, ): void; rejectOpenedSuggestions(): void; updateSuggestionState(uniqueTrackingId: string, newState: TRACKING_EVENTS): void; } export const TelemetryTracker = createInterfaceId('TelemetryTracker'); References:" You are a code assistant,Definition of 'destroy' in file src/common/tracking/snowplow/snowplow.ts in project gitlab-lsp,"Definition: public destroy() { Snowplow.#instance = undefined; } } References:" You are a code assistant,Definition of 'BrandedInstance' in file packages/lib_di/src/index.ts in project gitlab-lsp,"Definition: export type BrandedInstance = T; /** * use brandInstance to be able to pass this instance to the container.addInstances method */ export const brandInstance = ( id: InterfaceId, instance: T, ): BrandedInstance => { injectableMetadata.set(instance, { id, dependencies: [] }); return instance; }; /** * Container is responsible for initializing a dependency tree. * * It receives a list of classes decorated with the `@Injectable` decorator * and it constructs instances of these classes in an order that ensures class' dependencies * are initialized before the class itself. * * check https://gitlab.com/viktomas/needle for full documentation of this mini-framework */ export class Container { #instances = new Map(); /** * addInstances allows you to add pre-initialized objects to the container. * This is useful when you want to keep mandatory parameters in class' constructor (e.g. some runtime objects like server connection). * addInstances accepts a list of any objects that have been ""branded"" by the `brandInstance` method */ addInstances(...instances: BrandedInstance[]) { for (const instance of instances) { const metadata = injectableMetadata.get(instance); if (!metadata) { throw new Error( 'assertion error: addInstance invoked without branded object, make sure all arguments are branded with `brandInstance`', ); } if (this.#instances.has(metadata.id)) { throw new Error( `you are trying to add instance for interfaceId ${metadata.id}, but instance with this ID is already in the container.`, ); } this.#instances.set(metadata.id, instance); } } /** * instantiate accepts list of classes, validates that they can be managed by the container * and then initialized them in such order that dependencies of a class are initialized before the class */ instantiate(...classes: WithConstructor[]) { // ensure all classes have been decorated with @Injectable const undecorated = classes.filter((c) => !injectableMetadata.has(c)).map((c) => c.name); if (undecorated.length) { throw new Error(`Classes [${undecorated}] are not decorated with @Injectable.`); } const classesWithDeps: ClassWithDependencies[] = classes.map((cls) => { // we verified just above that all classes are present in the metadata map // eslint-disable-next-line @typescript-eslint/no-non-null-assertion const { id, dependencies } = injectableMetadata.get(cls)!; return { cls, id, dependencies }; }); const validators: Validator[] = [ interfaceUsedOnlyOnce, dependenciesArePresent, noCircularDependencies, ]; validators.forEach((v) => v(classesWithDeps, Array.from(this.#instances.keys()))); const classesById = new Map(); // Index classes by their interface id classesWithDeps.forEach((cwd) => { classesById.set(cwd.id, cwd); }); // Create instances in topological order for (const cwd of sortDependencies(classesById)) { const args = cwd.dependencies.map((dependencyId) => this.#instances.get(dependencyId)); // eslint-disable-next-line new-cap const instance = new cwd.cls(...args); this.#instances.set(cwd.id, instance); } } get(id: InterfaceId): T { const instance = this.#instances.get(id); if (!instance) { throw new Error(`Instance for interface '${sanitizeId(id)}' is not in the container.`); } return instance as T; } } References:" You are a code assistant,Definition of 'getLanguageInfoForFile' in file src/common/tree_sitter/parser.ts in project gitlab-lsp,"Definition: getLanguageInfoForFile(filename: string): TreeSitterLanguageInfo | undefined { const ext = filename.split('.').pop(); return this.languages.get(`.${ext}`); } buildTreeSitterInfoByExtMap( languages: TreeSitterLanguageInfo[], ): Map { return languages.reduce((map, language) => { for (const extension of language.extensions) { map.set(extension, language); } return map; }, new Map()); } } References:" You are a code assistant,Definition of 'completionOptionMapper' in file src/common/utils/suggestion_mappers.ts in project gitlab-lsp,"Definition: export const completionOptionMapper = (options: SuggestionOption[]): CompletionItem[] => options.map((option, index) => ({ label: `GitLab Suggestion ${index + 1}: ${option.text}`, kind: CompletionItemKind.Text, insertText: option.text, detail: option.text, command: { title: 'Accept suggestion', command: SUGGESTION_ACCEPTED_COMMAND, arguments: [option.uniqueTrackingId], }, data: { index, trackingId: option.uniqueTrackingId, }, })); /* this value will be used for telemetry so to make it human-readable we use the 1-based indexing instead of 0 */ const getOptionTrackingIndex = (option: SuggestionOption) => { return typeof option.index === 'number' ? option.index + 1 : undefined; }; export const inlineCompletionOptionMapper = ( params: InlineCompletionParams, options: SuggestionOptionOrStream[], ): InlineCompletionList => ({ items: options.map((option) => { if (isStream(option)) { // the streaming item is empty and only indicates to the client that streaming started return { insertText: '', command: { title: 'Start streaming', command: START_STREAMING_COMMAND, arguments: [option.streamId, option.uniqueTrackingId], }, }; } const completionInfo = params.context.selectedCompletionInfo; let rangeDiff = 0; if (completionInfo) { const range = sanitizeRange(completionInfo.range); rangeDiff = range.end.character - range.start.character; } return { insertText: completionInfo ? `${completionInfo.text.substring(rangeDiff)}${option.text}` : option.text, range: Range.create(params.position, params.position), command: { title: 'Accept suggestion', command: SUGGESTION_ACCEPTED_COMMAND, arguments: [option.uniqueTrackingId, getOptionTrackingIndex(option)], }, }; }), }); References: - src/common/utils/suggestion_mapper.test.ts:17 - src/common/suggestion/suggestion_service.ts:189" You are a code assistant,Definition of 'WorkflowAPI' in file packages/lib_workflow_api/src/index.ts in project gitlab-lsp,"Definition: export interface WorkflowAPI { runWorkflow(goal: string, image: string): Promise; } References: - packages/webview_duo_workflow/src/plugin/index.ts:15" You are a code assistant,Definition of 'getGitLabPlatform' in file packages/webview_duo_chat/src/plugin/port/chat/get_platform_manager_for_chat.ts in project gitlab-lsp,"Definition: async getGitLabPlatform(): Promise { const platforms = await this.#platformManager.getForAllAccounts(); if (!platforms.length) { return undefined; } let platform: GitLabPlatformForAccount | undefined; // Using a for await loop in this context because we want to stop // evaluating accounts as soon as we find one with code suggestions enabled for await (const result of platforms.map(getChatSupport)) { if (result.hasSupportForChat) { platform = result.platform; break; } } return platform; } async getGitLabEnvironment(): Promise { const platform = await this.getGitLabPlatform(); const instanceUrl = platform?.account.instanceUrl; switch (instanceUrl) { case GITLAB_COM_URL: return GitLabEnvironment.GITLAB_COM; case GITLAB_DEVELOPMENT_URL: return GitLabEnvironment.GITLAB_DEVELOPMENT; case GITLAB_STAGING_URL: return GitLabEnvironment.GITLAB_STAGING; case GITLAB_ORG_URL: return GitLabEnvironment.GITLAB_ORG; default: return GitLabEnvironment.GITLAB_SELF_MANAGED; } } } References:" You are a code assistant,Definition of 'ExtensionConnectionMessageBusProvider' in file src/common/webview/extension/extension_connection_message_bus_provider.ts in project gitlab-lsp,"Definition: export class ExtensionConnectionMessageBusProvider implements ExtensionMessageBusProvider, Disposable { #connection: Connection; #rpcMethods: RpcMethods; #handlers: Handlers; #logger: Logger; #notificationHandlers = new ExtensionMessageHandlerRegistry(); #requestHandlers = new ExtensionMessageHandlerRegistry(); #disposables = new CompositeDisposable(); constructor({ connection, logger, notificationRpcMethod = DEFAULT_NOTIFICATION_RPC_METHOD, requestRpcMethod = DEFAULT_REQUEST_RPC_METHOD, }: ExtensionConnectionMessageBusProviderProps) { this.#connection = connection; this.#logger = withPrefix(logger, '[ExtensionConnectionMessageBusProvider]'); this.#rpcMethods = { notification: notificationRpcMethod, request: requestRpcMethod, }; this.#handlers = { notification: new ExtensionMessageHandlerRegistry(), request: new ExtensionMessageHandlerRegistry(), }; this.#setupConnectionSubscriptions(); } getMessageBus(webviewId: WebviewId): MessageBus { return new ExtensionConnectionMessageBus({ webviewId, connection: this.#connection, rpcMethods: this.#rpcMethods, handlers: this.#handlers, }); } dispose(): void { this.#disposables.dispose(); } #setupConnectionSubscriptions() { this.#disposables.add( this.#connection.onNotification( this.#rpcMethods.notification, handleNotificationMessage(this.#notificationHandlers, this.#logger), ), ); this.#disposables.add( this.#connection.onRequest( this.#rpcMethods.request, handleRequestMessage(this.#requestHandlers, this.#logger), ), ); } } References: - src/common/webview/extension/extension_connection_message_bus_provider.test.ts:24 - src/node/main.ts:192 - src/common/webview/extension/extension_connection_message_bus_provider.test.ts:11" You are a code assistant,Definition of 'removeItem' in file src/common/ai_context_management_2/ai_context_manager.ts in project gitlab-lsp,"Definition: removeItem(id: string): boolean { return this.#items.delete(id); } getItem(id: string): AiContextItem | undefined { return this.#items.get(id); } currentItems(): AiContextItem[] { return Array.from(this.#items.values()); } async retrieveItems(): Promise { const items = Array.from(this.#items.values()); log.info(`Retrieving ${items.length} items`); const retrievedItems = await Promise.all( items.map(async (item) => { try { switch (item.type) { case 'file': { const content = await this.#fileRetriever.retrieve(item); return content ? { ...item, content } : null; } default: throw new Error(`Unknown item type: ${item.type}`); } } catch (error) { log.error(`Failed to retrieve item ${item.id}`, error); return null; } }), ); return retrievedItems.filter((item) => item !== null); } } References:" You are a code assistant,Definition of 'MANUAL_REQUEST_OPTIONS_COUNT' in file src/common/suggestion_client/suggestion_client.ts in project gitlab-lsp,"Definition: export const MANUAL_REQUEST_OPTIONS_COUNT = 4; export type OptionsCount = 1 | typeof MANUAL_REQUEST_OPTIONS_COUNT; export const GENERATION = 'generation'; export const COMPLETION = 'completion'; export type Intent = typeof GENERATION | typeof COMPLETION | undefined; export interface SuggestionContext { document: IDocContext; intent?: Intent; projectPath?: string; optionsCount?: OptionsCount; additionalContexts?: AdditionalContext[]; } export interface SuggestionResponse { choices?: SuggestionResponseChoice[]; model?: SuggestionModel; status: number; error?: string; isDirectConnection?: boolean; } export interface SuggestionResponseChoice { text: string; } export interface SuggestionClient { getSuggestions(context: SuggestionContext): Promise; } export type SuggestionClientFn = SuggestionClient['getSuggestions']; export type SuggestionClientMiddleware = ( context: SuggestionContext, next: SuggestionClientFn, ) => ReturnType; References:" You are a code assistant,Definition of 'NotificationPublisher' in file packages/lib_message_bus/src/types/bus.ts in project gitlab-lsp,"Definition: export interface NotificationPublisher { sendNotification>(type: T): void; sendNotification(type: T, payload: TNotifications[T]): void; } /** * Interface for listening to notifications. * @interface * @template {NotificationMap} TNotifications */ export interface NotificationListener { onNotification>( type: T, handler: () => void, ): Disposable; onNotification( type: T, handler: (payload: TNotifications[T]) => void, ): Disposable; } /** * Maps request message types to their corresponding request/response payloads. * @typedef {Record} RequestMap */ export type RequestMap = Record< Method, { params: MessagePayload; result: MessagePayload; } >; type KeysWithOptionalParams = { [K in keyof R]: R[K]['params'] extends undefined ? never : K; }[keyof R]; /** * Extracts the response payload type from a request type. * @template {MessagePayload} T * @typedef {T extends [never] ? void : T[0]} ExtractRequestResponse */ export type ExtractRequestResult = // eslint-disable-next-line @typescript-eslint/no-invalid-void-type T['result'] extends undefined ? void : T; /** * Interface for publishing requests. * @interface * @template {RequestMap} TRequests */ export interface RequestPublisher { sendRequest>( type: T, ): Promise>; sendRequest( type: T, payload: TRequests[T]['params'], ): Promise>; } /** * Interface for listening to requests. * @interface * @template {RequestMap} TRequests */ export interface RequestListener { onRequest>( type: T, handler: () => Promise>, ): Disposable; onRequest( type: T, handler: (payload: TRequests[T]['params']) => Promise>, ): Disposable; } /** * Defines the structure for message definitions, including notifications and requests. */ export type MessageDefinitions< TNotifications extends NotificationMap = NotificationMap, TRequests extends RequestMap = RequestMap, > = { notifications: TNotifications; requests: TRequests; }; export type MessageMap< TInboundMessageDefinitions extends MessageDefinitions = MessageDefinitions, TOutboundMessageDefinitions extends MessageDefinitions = MessageDefinitions, > = { inbound: TInboundMessageDefinitions; outbound: TOutboundMessageDefinitions; }; export interface MessageBus extends NotificationPublisher, NotificationListener, RequestPublisher, RequestListener {} References:" You are a code assistant,Definition of 'error' in file src/common/log.ts in project gitlab-lsp,"Definition: error(messageOrError: Error | string, trailingError?: Error | unknown) { this.#log(LOG_LEVEL.ERROR, messageOrError, trailingError); } } // TODO: rename the export and replace usages of `log` with `Log`. export const log = new Log(); 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 'isIgnored' in file src/common/git/ignore_trie.ts in project gitlab-lsp,"Definition: isIgnored(pathParts: string[]): boolean { if (pathParts.length === 0) { return false; } const [current, ...rest] = pathParts; if (this.#ignoreInstance && this.#ignoreInstance.ignores(path.join(...pathParts))) { return true; } const child = this.#children.get(current); if (child) { return child.isIgnored(rest); } return false; } 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 'addToSuggestionCache' in file src/common/suggestion/suggestions_cache.ts in project gitlab-lsp,"Definition: 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 'HandlerRegistry' in file packages/lib_handler_registry/src/types.ts in project gitlab-lsp,"Definition: export interface HandlerRegistry { size: number; has(key: TKey): boolean; register(key: TKey, handler: THandler): Disposable; handle(key: TKey, ...args: Parameters): Promise>; dispose(): void; } References:" You are a code assistant,Definition of 'SupportedSinceInstanceVersion' in file packages/webview_duo_chat/src/plugin/types.ts in project gitlab-lsp,"Definition: interface SupportedSinceInstanceVersion { version: string; resourceName: string; } interface BaseRestRequest<_TReturnType> { type: 'rest'; /** * 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; headers?: Record; supportedSinceInstanceVersion?: SupportedSinceInstanceVersion; } interface GraphQLRequest<_TReturnType> { type: 'graphql'; query: string; /** Options passed to the GraphQL query */ variables: Record; 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; supportedSinceInstanceVersion?: SupportedSinceInstanceVersion; } export type ApiRequest<_TReturnType> = | GetRequest<_TReturnType> | PostRequest<_TReturnType> | GraphQLRequest<_TReturnType>; export interface GitLabApiClient { fetchFromApi(request: ApiRequest): Promise; connectToCable(): Promise; } References: - src/common/api_types.ts:47 - src/common/api_types.ts:31 - packages/webview_duo_chat/src/plugin/types.ts:41 - packages/webview_duo_chat/src/plugin/types.ts:49 - src/common/api_types.ts:23 - packages/webview_duo_chat/src/plugin/types.ts:65" You are a code assistant,Definition of 'info' in file packages/lib_logging/src/null_logger.ts in project gitlab-lsp,"Definition: info(e: Error): void; info(message: string, e?: Error | undefined): void; info(): void { // NOOP } warn(e: Error): void; warn(message: string, e?: Error | undefined): void; warn(): void { // NOOP } error(e: Error): void; error(message: string, e?: Error | undefined): void; error(): void { // NOOP } } References:" You are a code assistant,Definition of 'isLanguageSupported' in file src/common/suggestion/supported_languages_service.ts in project gitlab-lsp,"Definition: 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 'resolveUris' in file src/common/webview/webview_resource_location_service.ts in project gitlab-lsp,"Definition: 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 'onChanged' in file src/common/feature_state/supported_language_check.ts in project gitlab-lsp,"Definition: onChanged(listener: (data: StateCheckChangedEventData) => void): Disposable { this.#stateEmitter.on('change', listener); return { dispose: () => this.#stateEmitter.removeListener('change', listener), }; } #updateWithDocument(document: TextDocument) { this.#currentDocument = document; this.#update(); } get engaged() { return !this.#isLanguageEnabled; } get id() { return this.#isLanguageSupported && !this.#isLanguageEnabled ? DISABLED_LANGUAGE : UNSUPPORTED_LANGUAGE; } details = 'Code suggestions are not supported for this language'; #update() { this.#checkLanguage(); this.#stateEmitter.emit('change', this); } #checkLanguage() { if (!this.#currentDocument) { this.#isLanguageEnabled = false; this.#isLanguageSupported = false; return; } const { languageId } = this.#currentDocument; this.#isLanguageEnabled = this.#supportedLanguagesService.isLanguageEnabled(languageId); this.#isLanguageSupported = this.#supportedLanguagesService.isLanguageSupported(languageId); } } References:" You are a code assistant,Definition of 'NotificationMap' in file packages/lib_message_bus/src/types/bus.ts in project gitlab-lsp,"Definition: export type NotificationMap = Record; /** * Interface for publishing notifications. * @interface * @template {NotificationMap} TNotifications */ export interface NotificationPublisher { sendNotification>(type: T): void; sendNotification(type: T, payload: TNotifications[T]): void; } /** * Interface for listening to notifications. * @interface * @template {NotificationMap} TNotifications */ export interface NotificationListener { onNotification>( type: T, handler: () => void, ): Disposable; onNotification( type: T, handler: (payload: TNotifications[T]) => void, ): Disposable; } /** * Maps request message types to their corresponding request/response payloads. * @typedef {Record} RequestMap */ export type RequestMap = Record< Method, { params: MessagePayload; result: MessagePayload; } >; type KeysWithOptionalParams = { [K in keyof R]: R[K]['params'] extends undefined ? never : K; }[keyof R]; /** * Extracts the response payload type from a request type. * @template {MessagePayload} T * @typedef {T extends [never] ? void : T[0]} ExtractRequestResponse */ export type ExtractRequestResult = // eslint-disable-next-line @typescript-eslint/no-invalid-void-type T['result'] extends undefined ? void : T; /** * Interface for publishing requests. * @interface * @template {RequestMap} TRequests */ export interface RequestPublisher { sendRequest>( type: T, ): Promise>; sendRequest( type: T, payload: TRequests[T]['params'], ): Promise>; } /** * Interface for listening to requests. * @interface * @template {RequestMap} TRequests */ export interface RequestListener { onRequest>( type: T, handler: () => Promise>, ): Disposable; onRequest( type: T, handler: (payload: TRequests[T]['params']) => Promise>, ): Disposable; } /** * Defines the structure for message definitions, including notifications and requests. */ export type MessageDefinitions< TNotifications extends NotificationMap = NotificationMap, TRequests extends RequestMap = RequestMap, > = { notifications: TNotifications; requests: TRequests; }; export type MessageMap< TInboundMessageDefinitions extends MessageDefinitions = MessageDefinitions, TOutboundMessageDefinitions extends MessageDefinitions = MessageDefinitions, > = { inbound: TInboundMessageDefinitions; outbound: TOutboundMessageDefinitions; }; export interface MessageBus extends NotificationPublisher, NotificationListener, RequestPublisher, RequestListener {} References:" You are a code assistant,Definition of 'buildCurrentContext' in file packages/webview_duo_chat/src/plugin/port/chat/gitlab_chat_record_context.ts in project gitlab-lsp,"Definition: export const buildCurrentContext = (): GitLabChatRecordContext | undefined => { const currentFile = getActiveFileContext(); if (!currentFile) { return undefined; } return { currentFile }; }; References: - packages/webview_duo_chat/src/plugin/port/chat/gitlab_chat_record_context.test.ts:29 - packages/webview_duo_chat/src/plugin/port/chat/gitlab_chat_record.ts:83 - packages/webview_duo_chat/src/plugin/port/chat/gitlab_chat_record_context.test.ts:20" You are a code assistant,Definition of 'fetchFromApi' in file packages/webview_duo_chat/src/plugin/chat_platform.ts in project gitlab-lsp,"Definition: fetchFromApi(request: ApiRequest): Promise { return this.#client.fetchFromApi(request); } connectToCable(): Promise { return this.#client.connectToCable(); } getUserAgentHeader(): Record { return {}; } } 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/port/platform/gitlab_platform.ts:11 - packages/webview_duo_chat/src/plugin/port/test_utils/create_fake_fetch_from_api.ts:10" You are a code assistant,Definition of 'LsFetchMocked' in file src/common/tracking/snowplow/snowplow.test.ts in project gitlab-lsp,"Definition: class LsFetchMocked extends FetchBase implements LsFetch {} const structEvent = { category: 'test', action: 'test', label: 'test', value: 1, }; const enabledMock = jest.fn(); const lsFetch = new LsFetchMocked(); const sp = Snowplow.getInstance(lsFetch, { appId: 'test', timeInterval: 1000, maxItems: 1, endpoint: 'http://localhost', enabled: enabledMock, }); describe('Snowplow', () => { describe('Snowplow interface', () => { it('should initialize', async () => { const newSP = Snowplow.getInstance(lsFetch); expect(newSP).toBe(sp); }); it('should let you track events', async () => { (fetch as jest.MockedFunction).mockResolvedValue({ status: 200, statusText: 'OK', } as Response); enabledMock.mockReturnValue(true); await sp.trackStructEvent(structEvent); await sp.stop(); }); it('should let you stop when the program ends', async () => { enabledMock.mockReturnValue(true); await sp.stop(); }); it('should destroy the instance', async () => { const sameInstance = Snowplow.getInstance(lsFetch, { appId: 'test', timeInterval: 1000, maxItems: 1, endpoint: 'http://localhost', enabled: enabledMock, }); expect(sp).toBe(sameInstance); await sp.stop(); sp.destroy(); const newInstance = Snowplow.getInstance(lsFetch, { appId: 'test', timeInterval: 1000, maxItems: 1, endpoint: 'http://localhost', enabled: enabledMock, }); expect(sp).not.toBe(newInstance); await newInstance.stop(); }); }); describe('should track and send events to snowplow', () => { beforeEach(() => { enabledMock.mockReturnValue(true); }); afterEach(async () => { await sp.stop(); }); it('should send the events to snowplow', async () => { (fetch as jest.MockedFunction).mockClear(); (fetch as jest.MockedFunction).mockResolvedValue({ status: 200, statusText: 'OK', } as Response); const structEvent1 = { ...structEvent }; structEvent1.action = 'action'; await sp.trackStructEvent(structEvent); await sp.trackStructEvent(structEvent1); expect(fetch).toBeCalledTimes(2); await sp.stop(); }); }); describe('enabled function', () => { it('should not send events to snowplow when disabled', async () => { (fetch as jest.MockedFunction).mockResolvedValue({ status: 200, statusText: 'OK', } as Response); enabledMock.mockReturnValue(false); const structEvent1 = { ...structEvent }; structEvent1.action = 'action'; await sp.trackStructEvent(structEvent); expect(fetch).not.toBeCalled(); await sp.stop(); }); it('should send events to snowplow when enabled', async () => { (fetch as jest.MockedFunction).mockResolvedValue({ status: 200, statusText: 'OK', } as Response); enabledMock.mockReturnValue(true); const structEvent1 = { ...structEvent }; structEvent1.action = 'action'; await sp.trackStructEvent(structEvent); expect(fetch).toBeCalled(); await sp.stop(); }); }); describe('when hostname cannot be resolved', () => { it('should disable sending events', async () => { const logSpy = jest.spyOn(global.console, 'log'); // FIXME: this eslint violation was introduced before we set up linting // eslint-disable-next-line @typescript-eslint/no-shadow const sp = Snowplow.getInstance(lsFetch, { appId: 'test', timeInterval: 1000, maxItems: 2, endpoint: 'http://askdalksdjalksjd.com', enabled: enabledMock, }); (fetch as jest.MockedFunction).mockRejectedValue({ message: '', errno: 'ENOTFOUND', }); expect(sp.disabled).toBe(false); await sp.trackStructEvent(structEvent); await sp.stop(); expect(sp.disabled).toBe(true); expect(logSpy).toHaveBeenCalledWith( expect.stringContaining('Disabling telemetry, unable to resolve endpoint address.'), ); logSpy.mockClear(); await sp.trackStructEvent(structEvent); await sp.stop(); expect(sp.disabled).toBe(true); expect(logSpy).not.toHaveBeenCalledWith(); }); }); }); References: - src/common/tracking/snowplow/snowplow.test.ts:18" You are a code assistant,Definition of 'IStartWorkflowParams' in file src/common/suggestion/suggestion_service.ts in project gitlab-lsp,"Definition: 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 => { 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 => { 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 => { 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 { 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 { 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 { 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 { 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 { 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:187" You are a code assistant,Definition of 'createMockTransport' in file packages/lib_webview/src/test_utils/mocks.ts in project gitlab-lsp,"Definition: export const createMockTransport = (): jest.Mocked => ({ publish: jest.fn(), on: jest.fn(), }); References:" You are a code assistant,Definition of 'CImpl' in file packages/lib_di/src/index.test.ts in project gitlab-lsp,"Definition: class CImpl implements C { #a: A; #b: B; constructor(a: A, b: B) { this.#a = a; this.#b = b; } c = () => `C(${this.#b.b()}, ${this.#a.a()})`; } let container: Container; beforeEach(() => { container = new Container(); }); describe('addInstances', () => { const O = createInterfaceId('object'); it('fails if the instance is not branded', () => { expect(() => container.addInstances({ say: 'hello' } as BrandedInstance)).toThrow( /invoked without branded object/, ); }); it('fails if the instance is already present', () => { const a = brandInstance(O, { a: 'a' }); const b = brandInstance(O, { b: 'b' }); expect(() => container.addInstances(a, b)).toThrow(/this ID is already in the container/); }); it('adds instance', () => { const instance = { a: 'a' }; const a = brandInstance(O, instance); container.addInstances(a); expect(container.get(O)).toBe(instance); }); }); describe('instantiate', () => { it('can instantiate three classes A,B,C', () => { container.instantiate(AImpl, BImpl, CImpl); const cInstance = container.get(C); expect(cInstance.c()).toBe('C(B(a), a)'); }); it('instantiates dependencies in multiple instantiate calls', () => { container.instantiate(AImpl); // the order is important for this test // we want to make sure that the stack in circular dependency discovery is being cleared // to try why this order is necessary, remove the `inStack.delete()` from // the `if (!cwd && instanceIds.includes(id))` condition in prod code expect(() => container.instantiate(CImpl, BImpl)).not.toThrow(); }); it('detects duplicate ids', () => { @Injectable(A, []) 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 'SUGGESTIONS_DEBOUNCE_INTERVAL_MS' in file src/common/constants.ts in project gitlab-lsp,"Definition: 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 'greet' in file src/tests/fixtures/intent/typescript_comments.ts in project gitlab-lsp,"Definition: function greet(name: string): string { return `Hello, ${name}!`; } // This file has more than 5 non-comment lines const a = 1; const b = 2; const c = 3; const d = 4; const e = 5; const f = 6; function hello(user) { // function to greet the user } References: - src/tests/fixtures/intent/empty_function/ruby.rb:20 - 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" You are a code assistant,Definition of 'AiFileContextProvider' in file src/common/ai_context_management_2/providers/ai_file_context_provider.ts in project gitlab-lsp,"Definition: export const AiFileContextProvider = createInterfaceId('AiFileContextProvider'); @Injectable(AiFileContextProvider, [RepositoryService, DuoProjectAccessChecker]) export class DefaultAiFileContextProvider implements AiContextProvider { #repositoryService: DefaultRepositoryService; constructor(repositoryService: DefaultRepositoryService) { this.#repositoryService = repositoryService; } async getProviderItems( query: string, workspaceFolders: WorkspaceFolder[], ): Promise { const items = query.trim() === '' ? await this.#getOpenTabsItems() : await this.#getSearchedItems(query, workspaceFolders); log.info(`Found ${items.length} results for ${query}`); return items; } async #getOpenTabsItems(): Promise { const resolutions: ContextResolution[] = []; for await (const resolution of OpenTabsResolver.getInstance().buildContext({ includeCurrentFile: true, })) { resolutions.push(resolution); } return resolutions.map((resolution) => this.#providerItemForOpenTab(resolution)); } async #getSearchedItems( query: string, workspaceFolders: WorkspaceFolder[], ): Promise { const allFiles: RepositoryFile[] = []; for (const folder of workspaceFolders) { const files = this.#repositoryService.getFilesForWorkspace(folder.uri, { excludeGitFolder: true, excludeIgnored: true, }); allFiles.push(...files); } const fileNames = allFiles.map((file) => file.uri.fsPath); const allFilesMap = new Map(allFiles.map((file) => [file.uri.fsPath, file])); const results = filter(fileNames, query, { maxResults: 100 }); const resultFiles: RepositoryFile[] = []; for (const result of results) { if (allFilesMap.has(result)) { resultFiles.push(allFilesMap.get(result) as RepositoryFile); } } return resultFiles.map((file) => this.#providerItemForSearchResult(file)); } #openTabResolutionToRepositoryFile(resolution: ContextResolution): [URI, RepositoryFile | null] { const fileUri = parseURIString(resolution.uri); const repo = this.#repositoryService.findMatchingRepositoryUri( fileUri, resolution.workspaceFolder, ); if (!repo) { log.warn(`Could not find repository for ${resolution.uri}`); return [fileUri, null]; } const repositoryFile = this.#repositoryService.getRepositoryFileForUri( fileUri, repo, resolution.workspaceFolder, ); if (!repositoryFile) { log.warn(`Could not find repository file for ${resolution.uri}`); return [fileUri, null]; } return [fileUri, repositoryFile]; } #providerItemForOpenTab(resolution: ContextResolution): AiContextProviderItem { const [fileUri, repositoryFile] = this.#openTabResolutionToRepositoryFile(resolution); return { fileUri, workspaceFolder: resolution.workspaceFolder, providerType: 'file', subType: 'open_tab', repositoryFile, }; } #providerItemForSearchResult(repositoryFile: RepositoryFile): AiContextProviderItem { return { fileUri: repositoryFile.uri, workspaceFolder: repositoryFile.workspaceFolder, providerType: 'file', subType: 'local_file_search', repositoryFile, }; } } References: - src/common/ai_context_management_2/ai_context_aggregator.ts:29 - src/common/ai_context_management_2/ai_context_aggregator.ts:24" You are a code assistant,Definition of 'GENERATION' in file src/common/suggestion_client/suggestion_client.ts in project gitlab-lsp,"Definition: export const GENERATION = 'generation'; export const COMPLETION = 'completion'; export type Intent = typeof GENERATION | typeof COMPLETION | undefined; export interface SuggestionContext { document: IDocContext; intent?: Intent; projectPath?: string; optionsCount?: OptionsCount; additionalContexts?: AdditionalContext[]; } export interface SuggestionResponse { choices?: SuggestionResponseChoice[]; model?: SuggestionModel; status: number; error?: string; isDirectConnection?: boolean; } export interface SuggestionResponseChoice { text: string; } export interface SuggestionClient { getSuggestions(context: SuggestionContext): Promise; } export type SuggestionClientFn = SuggestionClient['getSuggestions']; export type SuggestionClientMiddleware = ( context: SuggestionContext, next: SuggestionClientFn, ) => ReturnType; References:" You are a code assistant,Definition of 'IClientInfo' in file src/common/tracking/tracking_types.ts in project gitlab-lsp,"Definition: export type IClientInfo = InitializeParams['clientInfo']; export enum GitlabRealm { saas = 'saas', selfManaged = 'self-managed', } export enum SuggestionSource { cache = 'cache', network = 'network', } export interface IIDEInfo { name: string; version: string; vendor: string; } 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, ): void; updateCodeSuggestionsContext( uniqueTrackingId: string, contextUpdate: Partial, ): void; rejectOpenedSuggestions(): void; updateSuggestionState(uniqueTrackingId: string, newState: TRACKING_EVENTS): void; } export const TelemetryTracker = createInterfaceId('TelemetryTracker'); References: - src/common/tracking/tracking_types.ts:47 - src/common/config_service.ts:58 - src/common/api.ts:125 - src/common/tracking/tracking_types.ts:56" You are a code assistant,Definition of 'WebviewRuntimeMessageBus' in file packages/lib_webview/src/events/webview_runtime_message_bus.ts in project gitlab-lsp,"Definition: export class WebviewRuntimeMessageBus extends MessageBus {} References: - packages/lib_webview/src/setup/plugin/webview_controller.test.ts:22 - packages/lib_webview/src/setup/transport/utils/setup_transport_event_handlers.ts:9 - packages/lib_webview/src/setup/plugin/webview_instance_message_bus.test.ts:19 - packages/lib_webview/src/setup/transport/utils/setup_event_subscriptions.ts:7 - packages/lib_webview/src/setup/transport/utils/setup_event_subscriptions.test.ts:8 - packages/lib_webview/src/setup/plugin/setup_plugins.ts:13 - packages/lib_webview/src/setup/plugin/webview_controller.test.ts:28 - packages/lib_webview/src/setup/transport/utils/setup_transport_event_handlers.test.ts:17 - packages/lib_webview/src/setup/plugin/webview_controller.ts:75 - packages/lib_webview/src/setup/transport/setup_transport.ts:37 - packages/lib_webview/src/setup/plugin/webview_controller.ts:39 - packages/lib_webview/src/setup/plugin/webview_instance_message_bus.ts:20 - packages/lib_webview/src/setup/plugin/webview_instance_message_bus.test.ts:14 - packages/lib_webview/src/setup/transport/setup_transport.ts:10 - packages/lib_webview/src/setup/transport/utils/setup_event_subscriptions.test.ts:13 - packages/lib_webview/src/setup/setup_webview_runtime.ts:22 - packages/lib_webview/src/setup/transport/utils/setup_transport_event_handlers.test.ts:9 - packages/lib_webview/src/setup/plugin/webview_instance_message_bus.ts:34" You are a code assistant,Definition of 'GitLabChatController' in file packages/webview_duo_chat/src/plugin/chat_controller.ts in project gitlab-lsp,"Definition: export class GitLabChatController implements Disposable { readonly chatHistory: GitLabChatRecord[]; readonly #api: GitLabChatApi; readonly #extensionMessageBus: DuoChatExtensionMessageBus; readonly #webviewMessageBus: DuoChatWebviewMessageBus; readonly #subscriptions = new CompositeDisposable(); constructor( manager: GitLabPlatformManagerForChat, webviewMessageBus: DuoChatWebviewMessageBus, extensionMessageBus: DuoChatExtensionMessageBus, ) { this.#api = new GitLabChatApi(manager); this.chatHistory = []; this.#webviewMessageBus = webviewMessageBus; this.#extensionMessageBus = extensionMessageBus; this.#setupMessageHandlers.bind(this)(); } dispose(): void { this.#subscriptions.dispose(); } #setupMessageHandlers() { this.#subscriptions.add( this.#webviewMessageBus.onNotification('newPrompt', async (message) => { const record = GitLabChatRecord.buildWithContext({ role: 'user', content: message.record.content, }); await this.#processNewUserRecord(record); }), ); } async #processNewUserRecord(record: GitLabChatRecord) { if (!record.content) return; await this.#sendNewPrompt(record); if (record.errors.length > 0) { this.#extensionMessageBus.sendNotification('showErrorMessage', { message: record.errors[0], }); return; } await this.#addToChat(record); if (record.type === 'newConversation') return; const responseRecord = new GitLabChatRecord({ role: 'assistant', state: 'pending', requestId: record.requestId, }); await this.#addToChat(responseRecord); try { await this.#api.subscribeToUpdates(this.#subscriptionUpdateHandler.bind(this), record.id); } catch (err) { // TODO: log error } // Fallback if websocket fails or disabled. await Promise.all([this.#refreshRecord(record), this.#refreshRecord(responseRecord)]); } async #subscriptionUpdateHandler(data: AiCompletionResponseMessageType) { const record = this.#findRecord(data); if (!record) return; record.update({ chunkId: data.chunkId, content: data.content, contentHtml: data.contentHtml, extras: data.extras, timestamp: data.timestamp, errors: data.errors, }); record.state = 'ready'; this.#webviewMessageBus.sendNotification('updateRecord', record); } // async #restoreHistory() { // this.chatHistory.forEach((record) => { // this.#webviewMessageBus.sendNotification('newRecord', record); // }, this); // } async #addToChat(record: GitLabChatRecord) { this.chatHistory.push(record); this.#webviewMessageBus.sendNotification('newRecord', record); } async #sendNewPrompt(record: GitLabChatRecord) { if (!record.content) throw new Error('Trying to send prompt without content.'); try { const actionResponse = await this.#api.processNewUserPrompt( record.content, record.id, record.context?.currentFile, ); record.update(actionResponse.aiAction); } catch (err) { // eslint-disable-next-line @typescript-eslint/no-explicit-any record.update({ errors: [`API error: ${(err as any).response.errors[0].message}`] }); } } async #refreshRecord(record: GitLabChatRecord) { if (!record.requestId) { throw Error('requestId must be present!'); } const apiResponse = await this.#api.pullAiMessage(record.requestId, record.role); if (apiResponse.type !== 'error') { record.update({ content: apiResponse.content, contentHtml: apiResponse.contentHtml, extras: apiResponse.extras, timestamp: apiResponse.timestamp, }); } record.update({ errors: apiResponse.errors, state: 'ready' }); this.#webviewMessageBus.sendNotification('updateRecord', record); } #findRecord(data: { requestId: string; role: string }) { return this.chatHistory.find( (r) => r.requestId === data.requestId && r.role.toLowerCase() === data.role.toLowerCase(), ); } } References: - packages/webview_duo_chat/src/plugin/index.ts:22" You are a code assistant,Definition of 'clientToMiddleware' in file src/common/suggestion_client/client_to_middleware.ts in project gitlab-lsp,"Definition: export const clientToMiddleware = (client: SuggestionClient): SuggestionClientMiddleware => (context) => client.getSuggestions(context); References: - src/common/suggestion/suggestion_service.ts:166" You are a code assistant,Definition of 'hello' in file src/tests/fixtures/intent/javascript_comments.js in project gitlab-lsp,"Definition: function hello(user) { // function to greet the user } References:" You are a code assistant,Definition of 'createLoggerTransport' in file src/node/http/utils/create_logger_transport.ts in project gitlab-lsp,"Definition: export const createLoggerTransport = (logger: ILog, level: keyof ILog = 'debug') => new Writable({ objectMode: true, write(chunk, _encoding, callback) { logger[level](chunk.toString()); callback(); }, }); References: - src/node/http/create_fastify_http_server.ts:90 - src/node/http/utils/create_logger_transport.test.ts:31 - src/node/http/utils/create_logger_transport.test.ts:18" You are a code assistant,Definition of 'pullHandler' in file packages/webview_duo_chat/src/plugin/port/chat/api/pulling.ts in project gitlab-lsp,"Definition: export const pullHandler = async ( handler: () => Promise, retry = API_PULLING.maxRetries, ): Promise => { if (retry <= 0) { log.debug('Pull handler: no retries left, exiting without return value.'); return undefined; } log.debug(`Pull handler: pulling, ${retry - 1} retries left.`); const response = await handler(); if (response) return response; await waitForMs(API_PULLING.interval); return pullHandler(handler, retry - 1); }; References: - packages/webview_duo_chat/src/plugin/port/chat/api/pulling.ts:24 - packages/webview_duo_chat/src/plugin/port/chat/api/pulling.test.ts:27 - packages/webview_duo_chat/src/plugin/port/chat/api/pulling.test.ts:20 - packages/webview_duo_chat/src/plugin/port/chat/gitlab_chat_api.ts:169" You are a code assistant,Definition of 'sendRequest' in file packages/lib_message_bus/src/types/bus.ts in project gitlab-lsp,"Definition: sendRequest( type: T, payload: TRequests[T]['params'], ): Promise>; } /** * Interface for listening to requests. * @interface * @template {RequestMap} TRequests */ export interface RequestListener { onRequest>( type: T, handler: () => Promise>, ): Disposable; onRequest( type: T, handler: (payload: TRequests[T]['params']) => Promise>, ): Disposable; } /** * Defines the structure for message definitions, including notifications and requests. */ export type MessageDefinitions< TNotifications extends NotificationMap = NotificationMap, TRequests extends RequestMap = RequestMap, > = { notifications: TNotifications; requests: TRequests; }; export type MessageMap< TInboundMessageDefinitions extends MessageDefinitions = MessageDefinitions, TOutboundMessageDefinitions extends MessageDefinitions = MessageDefinitions, > = { inbound: TInboundMessageDefinitions; outbound: TOutboundMessageDefinitions; }; export interface MessageBus extends NotificationPublisher, NotificationListener, RequestPublisher, RequestListener {} References:" You are a code assistant,Definition of 'LsAgentOptions' in file src/node/fetch.ts in project gitlab-lsp,"Definition: interface LsAgentOptions { rejectUnauthorized: boolean; ca?: Buffer; cert?: Buffer; key?: Buffer; } /** * Wrap fetch to support proxy configurations */ @Injectable(LsFetch, []) export class Fetch extends FetchBase implements LsFetch { #proxy?: ProxyAgent; #userProxy?: string; #initialized: boolean = false; #httpsAgent: https.Agent; #agentOptions: Readonly; constructor(userProxy?: string) { super(); this.#agentOptions = { rejectUnauthorized: true, }; this.#userProxy = userProxy; this.#httpsAgent = this.#createHttpsAgent(); } async initialize(): Promise { // Set http_proxy and https_proxy environment variables // which will then get picked up by the ProxyAgent and // used. try { const proxy = await getProxySettings(); if (proxy?.http) { process.env.http_proxy = `${proxy.http.protocol}://${proxy.http.host}:${proxy.http.port}`; log.debug(`fetch: Detected http proxy through settings: ${process.env.http_proxy}`); } if (proxy?.https) { process.env.https_proxy = `${proxy.https.protocol}://${proxy.https.host}:${proxy.https.port}`; log.debug(`fetch: Detected https proxy through settings: ${process.env.https_proxy}`); } if (!proxy?.http && !proxy?.https) { log.debug(`fetch: Detected no proxy settings`); } } catch (err) { log.warn('Unable to load proxy settings', err); } if (this.#userProxy) { log.debug(`fetch: Detected user proxy ${this.#userProxy}`); process.env.http_proxy = this.#userProxy; process.env.https_proxy = this.#userProxy; } if (process.env.http_proxy || process.env.https_proxy) { log.info( `fetch: Setting proxy to https_proxy=${process.env.https_proxy}; http_proxy=${process.env.http_proxy}`, ); this.#proxy = this.#createProxyAgent(); } this.#initialized = true; } async destroy(): Promise { this.#proxy?.destroy(); } async fetch(input: RequestInfo | URL, init?: RequestInit): Promise { 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 { let buffer = ''; const decoder = new TextDecoder(); async function* readStream( stream: ReadableStream, ): AsyncGenerator { 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 { 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: '' } : {}), ...(cert ? { cert: '' } : {}), ...(key ? { key: '' } : {}), }; } } References: - src/node/fetch.ts:251 - src/node/fetch.ts:132" You are a code assistant,Definition of 'WebviewTransportEventEmitterMessages' in file packages/lib_webview_transport_json_rpc/src/utils/webview_transport_event_emitter.ts in project gitlab-lsp,"Definition: export type WebviewTransportEventEmitterMessages = { [K in keyof MessagesToServer]: (payload: MessagesToServer[K]) => void; }; export type WebviewTransportEventEmitter = TypedEmitter; export const createWebviewTransportEventEmitter = (): WebviewTransportEventEmitter => new EventEmitter() as WebviewTransportEventEmitter; References:" You are a code assistant,Definition of 'WebviewTransportEventEmitter' in file packages/lib_webview_transport_json_rpc/src/utils/webview_transport_event_emitter.ts in project gitlab-lsp,"Definition: export type WebviewTransportEventEmitter = TypedEmitter; export const createWebviewTransportEventEmitter = (): WebviewTransportEventEmitter => new EventEmitter() as WebviewTransportEventEmitter; References: - packages/lib_webview_transport_socket_io/src/utils/webview_transport_event_emitter.ts:11 - packages/lib_webview_transport_json_rpc/src/json_rpc_connection_transport.ts:35 - packages/lib_webview_transport_json_rpc/src/json_rpc_connection_transport.ts:27 - packages/lib_webview_transport_json_rpc/src/utils/webview_transport_event_emitter.ts:11 - packages/lib_webview_transport_json_rpc/src/json_rpc_connection_transport.ts:43" You are a code assistant,Definition of 'ACircular' in file packages/lib_di/src/index.test.ts in project gitlab-lsp,"Definition: 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 'GitLabPlatformBase' in file packages/webview_duo_chat/src/plugin/port/platform/gitlab_platform.ts in project gitlab-lsp,"Definition: export interface GitLabPlatformBase { fetchFromApi: fetchFromApi; connectToCable: () => Promise; account: Account; /** * What user agent should be used for API calls that are not made to GitLab API * (e.g. when calling Model Gateway for code suggestions) */ getUserAgentHeader(): Record; } export interface GitLabPlatformForAccount extends GitLabPlatformBase { type: 'account'; project: undefined; } export interface GitLabPlatformForProject extends GitLabPlatformBase { type: 'project'; project: GitLabProject; } export type GitLabPlatform = GitLabPlatformForProject | GitLabPlatformForAccount; 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; /** * 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; /** * 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; getForAllAccounts(): Promise; /** * Returns GitLabPlatformForAccount if there is a SaaS account added. Otherwise returns undefined. */ getForSaaSAccount(): Promise; } References:" You are a code assistant,Definition of 'processStream' in file src/common/suggestion_client/post_processors/post_processor_pipeline.test.ts in project gitlab-lsp,"Definition: async processStream( _context: IDocContext, input: StreamingCompletionResponse, ): Promise { return input; } async processCompletion( _context: IDocContext, input: SuggestionOption[], ): Promise { return input.map((option) => ({ ...option, text: `${option.text} [1]` })); } } class Processor2 extends PostProcessor { async processStream( _context: IDocContext, input: StreamingCompletionResponse, ): Promise { return input; } async processCompletion( _context: IDocContext, input: SuggestionOption[], ): Promise { return input.map((option) => ({ ...option, text: `${option.text} [2]` })); } } pipeline.addProcessor(new Processor1()); pipeline.addProcessor(new Processor2()); const completionInput: SuggestionOption[] = [{ text: 'option1', uniqueTrackingId: '1' }]; const result = await pipeline.run({ documentContext: mockContext, input: completionInput, type: 'completion', }); expect(result).toEqual([{ text: 'option1 [1] [2]', uniqueTrackingId: '1' }]); }); test('should throw an error for unexpected type', async () => { class TestProcessor extends PostProcessor { async processStream( _context: IDocContext, input: StreamingCompletionResponse, ): Promise { return input; } async processCompletion( _context: IDocContext, input: SuggestionOption[], ): Promise { 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 'REQUEST_TIMEOUT_MS' in file packages/lib_webview_client/src/bus/provider/socket_io_message_bus.ts in project gitlab-lsp,"Definition: export const REQUEST_TIMEOUT_MS = 10000; export const SOCKET_NOTIFICATION_CHANNEL = 'notification'; export const SOCKET_REQUEST_CHANNEL = 'request'; export const SOCKET_RESPONSE_CHANNEL = 'response'; export type SocketEvents = | typeof SOCKET_NOTIFICATION_CHANNEL | typeof SOCKET_REQUEST_CHANNEL | typeof SOCKET_RESPONSE_CHANNEL; export class SocketIoMessageBus implements MessageBus { #notificationHandlers = new SimpleRegistry(); #requestHandlers = new SimpleRegistry(); #pendingRequests = new SimpleRegistry(); #socket: Socket; constructor(socket: Socket) { this.#socket = socket; this.#setupSocketEventHandlers(); } async sendNotification( messageType: T, payload?: TMessages['outbound']['notifications'][T], ): Promise { this.#socket.emit(SOCKET_NOTIFICATION_CHANNEL, { type: messageType, payload }); } sendRequest( type: T, payload?: TMessages['outbound']['requests'][T]['params'], ): Promise> { const requestId = generateRequestId(); let timeout: NodeJS.Timeout | undefined; return new Promise((resolve, reject) => { const pendingRequestDisposable = this.#pendingRequests.register( requestId, (value: ExtractRequestResult) => { resolve(value); clearTimeout(timeout); pendingRequestDisposable.dispose(); }, ); timeout = setTimeout(() => { pendingRequestDisposable.dispose(); reject(new Error('Request timed out')); }, REQUEST_TIMEOUT_MS); this.#socket.emit(SOCKET_REQUEST_CHANNEL, { requestId, type, payload, }); }); } onNotification( messageType: T, callback: (payload: TMessages['inbound']['notifications'][T]) => void, ): Disposable { return this.#notificationHandlers.register(messageType, callback); } onRequest( type: T, handler: ( payload: TMessages['inbound']['requests'][T]['params'], ) => Promise>, ): Disposable { return this.#requestHandlers.register(type, handler); } dispose() { this.#socket.off(SOCKET_NOTIFICATION_CHANNEL, this.#handleNotificationMessage); this.#socket.off(SOCKET_REQUEST_CHANNEL, this.#handleRequestMessage); this.#socket.off(SOCKET_RESPONSE_CHANNEL, this.#handleResponseMessage); this.#notificationHandlers.dispose(); this.#requestHandlers.dispose(); this.#pendingRequests.dispose(); } #setupSocketEventHandlers = () => { this.#socket.on(SOCKET_NOTIFICATION_CHANNEL, this.#handleNotificationMessage); this.#socket.on(SOCKET_REQUEST_CHANNEL, this.#handleRequestMessage); this.#socket.on(SOCKET_RESPONSE_CHANNEL, this.#handleResponseMessage); }; #handleNotificationMessage = async (message: { type: keyof TMessages['inbound']['notifications'] & string; payload: unknown; }) => { await this.#notificationHandlers.handle(message.type, message.payload); }; #handleRequestMessage = async (message: { requestId: string; event: keyof TMessages['inbound']['requests'] & string; payload: unknown; }) => { const response = await this.#requestHandlers.handle(message.event, message.payload); this.#socket.emit(SOCKET_RESPONSE_CHANNEL, { requestId: message.requestId, payload: response, }); }; #handleResponseMessage = async (message: { requestId: string; payload: unknown }) => { await this.#pendingRequests.handle(message.requestId, message.payload); }; } References:" You are a code assistant,Definition of 'FailedResponse' in file packages/lib_webview_transport/src/types.ts in project gitlab-lsp,"Definition: export type FailedResponse = { success: false; reason: string; }; export type WebviewInstanceResponseEventData = WebviewAddress & WebviewRequestInfo & WebviewEventInfo & (SuccessfulResponse | FailedResponse); export type MessagesToServer = { webview_instance_created: WebviewInstanceCreatedEventData; webview_instance_destroyed: WebviewInstanceDestroyedEventData; webview_instance_notification_received: WebviewInstanceNotificationEventData; webview_instance_request_received: WebviewInstanceRequestEventData; webview_instance_response_received: WebviewInstanceResponseEventData; }; export type MessagesToClient = { webview_instance_notification: WebviewInstanceNotificationEventData; webview_instance_request: WebviewInstanceRequestEventData; webview_instance_response: WebviewInstanceResponseEventData; }; export interface TransportMessageHandler { (payload: T): void; } export interface TransportListener { on( type: K, callback: TransportMessageHandler, ): Disposable; } export interface TransportPublisher { publish(type: K, payload: MessagesToClient[K]): Promise; } export interface Transport extends TransportListener, TransportPublisher {} References:" You are a code assistant,Definition of 'IDocTransformer' in file src/common/document_transformer_service.ts in project gitlab-lsp,"Definition: export interface IDocTransformer { transform(context: IDocContext): IDocContext; } const getMatchingWorkspaceFolder = ( fileUri: DocumentUri, workspaceFolders: WorkspaceFolder[], ): WorkspaceFolder | undefined => workspaceFolders.find((wf) => fileUri.startsWith(wf.uri)); const getRelativePath = (fileUri: DocumentUri, workspaceFolder?: WorkspaceFolder): string => { if (!workspaceFolder) { // splitting a string will produce at least one item and so the pop can't return undefined // eslint-disable-next-line @typescript-eslint/no-non-null-assertion return fileUri.split(/[\\/]/).pop()!; } return fileUri.slice(workspaceFolder.uri.length).replace(/^\//, ''); }; export interface DocumentTransformerService { get(uri: string): TextDocument | undefined; getContext( uri: string, position: Position, workspaceFolders: WorkspaceFolder[], completionContext?: InlineCompletionContext, ): IDocContext | undefined; transform(context: IDocContext): IDocContext; } export const DocumentTransformerService = createInterfaceId( 'DocumentTransformerService', ); @Injectable(DocumentTransformerService, [LsTextDocuments, SecretRedactor]) export class DefaultDocumentTransformerService implements DocumentTransformerService { #transformers: IDocTransformer[] = []; #documents: LsTextDocuments; 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 'constructor' in file packages/lib-pkg-2/src/fast_fibonacci_solver.ts in project gitlab-lsp,"Definition: constructor() { this.#memo.set(0, 0); this.#memo.set(1, 1); } 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 'AiCompletionResponseMessageType' in file packages/webview_duo_chat/src/plugin/port/api/graphql/ai_completion_response_channel.ts in project gitlab-lsp,"Definition: export type AiCompletionResponseMessageType = { requestId: string; role: string; content: string; contentHtml?: string; timestamp: string; errors: string[]; extras?: { sources: object[]; }; chunkId?: number; type?: string; }; type AiCompletionResponseResponseType = { result: { data: { aiCompletionResponse: AiCompletionResponseMessageType; }; }; more: boolean; }; interface AiCompletionResponseChannelEvents extends ChannelEvents { systemMessage: (msg: AiCompletionResponseMessageType) => void; newChunk: (msg: AiCompletionResponseMessageType) => void; fullMessage: (msg: AiCompletionResponseMessageType) => void; } export class AiCompletionResponseChannel extends Channel< AiCompletionResponseParams, AiCompletionResponseResponseType, AiCompletionResponseChannelEvents > { static identifier = 'GraphqlChannel'; constructor(params: AiCompletionResponseInput) { super({ channel: 'GraphqlChannel', operationName: 'aiCompletionResponse', query: AI_MESSAGE_SUBSCRIPTION_QUERY, variables: JSON.stringify(params), }); } receive(message: AiCompletionResponseResponseType) { if (!message.result.data.aiCompletionResponse) return; const data = message.result.data.aiCompletionResponse; if (data.role.toLowerCase() === 'system') { this.emit('systemMessage', data); } else if (data.chunkId) { this.emit('newChunk', data); } else { this.emit('fullMessage', data); } } } References: - packages/webview_duo_chat/src/plugin/port/api/graphql/ai_completion_response_channel.ts:72 - packages/webview_duo_chat/src/plugin/port/api/graphql/ai_completion_response_channel.ts:71 - packages/webview_duo_chat/src/plugin/port/api/graphql/ai_completion_response_channel.ts:73 - packages/webview_duo_chat/src/plugin/port/chat/gitlab_chat_api.ts:200 - packages/webview_duo_chat/src/plugin/port/api/graphql/ai_completion_response_channel.ts:63 - packages/webview_duo_chat/src/plugin/chat_controller.ts:82" You are a code assistant,Definition of 'connectToCable' in file src/common/action_cable.ts in project gitlab-lsp,"Definition: export const connectToCable = async (instanceUrl: string, websocketOptions?: object) => { const cableUrl = new URL('/-/cable', instanceUrl); cableUrl.protocol = cableUrl.protocol === 'http:' ? 'ws:' : 'wss:'; const cable = createCable(cableUrl.href, { websocketImplementation: WebSocket, websocketOptions, }); await cable.connect(); return cable; }; References: - src/common/action_cable.test.ts:40 - src/common/api.ts:348 - src/common/action_cable.test.ts:54 - src/common/action_cable.test.ts:32 - src/common/action_cable.test.ts:21" You are a code assistant,Definition of 'extractUserId' in file packages/webview_duo_chat/src/plugin/port/platform/gitlab_account.ts in project gitlab-lsp,"Definition: export const extractUserId = (accountId: string) => accountId.split('|').pop(); References: - packages/webview_duo_chat/src/plugin/port/chat/gitlab_chat_api.ts:207" You are a code assistant,Definition of 'getSuggestions' in file src/common/suggestion_client/fallback_client.ts in project gitlab-lsp,"Definition: async getSuggestions(context: SuggestionContext) { for (const client of this.#clients) { // eslint-disable-next-line no-await-in-loop const result = await client.getSuggestions(context); if (result) { // TODO create a follow up issue to consider scenario when the result is defined, but it contains an error field return result; } } return undefined; } } References:" You are a code assistant,Definition of 'setupFileWatcher' in file src/node/services/fs/dir.ts in project gitlab-lsp,"Definition: setupFileWatcher(workspaceFolder: WorkspaceFolder, fileChangeHandler: FileChangeHandler): void { const fsPath = fsPathFromUri(workspaceFolder.uri); const watcher = chokidar.watch(fsPath, { persistent: true, alwaysStat: false, ignoreInitial: true, }); watcher .on('add', (path) => fileChangeHandler('add', workspaceFolder, path)) .on('change', (path) => fileChangeHandler('change', workspaceFolder, path)) .on('unlink', (path) => fileChangeHandler('unlink', workspaceFolder, path)); this.#watchers.set(workspaceFolder.uri, watcher); } async dispose(): Promise { 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 'DUO_WORKFLOW_WEBVIEW_ID' in file packages/webview_duo_chat/src/plugin/port/constants.ts in project gitlab-lsp,"Definition: export const DUO_WORKFLOW_WEBVIEW_ID = 'duo-workflow'; export const DUO_CHAT_WEBVIEW_ID = 'chat'; References:" You are a code assistant,Definition of 'AiContextItemInfo' in file src/common/ai_context_management_2/ai_context_item.ts in project gitlab-lsp,"Definition: export type AiContextItemInfo = { project?: string; disabledReasons?: string[]; iid?: number; relFilePath?: string; }; export type AiContextItemType = 'issue' | 'merge_request' | 'file'; export type AiContextItemSubType = 'open_tab' | 'local_file_search'; export type AiContextItem = { id: string; name: string; isEnabled: boolean; info: AiContextItemInfo; type: AiContextItemType; } & ( | { type: 'issue' | 'merge_request'; subType?: never } | { type: 'file'; subType: AiContextItemSubType } ); export type AiContextItemWithContent = AiContextItem & { content: string; }; References: - src/common/ai_context_management_2/ai_context_item.ts:16" You are a code assistant,Definition of 'dispose' in file src/common/git/repository.ts in project gitlab-lsp,"Definition: dispose(): void { this.#ignoreManager.dispose(); this.#files.clear(); } } References:" You are a code assistant,Definition of 'LsTextDocuments' in file src/common/external_interfaces.ts in project gitlab-lsp,"Definition: export type LsTextDocuments = TextDocuments; export const LsTextDocuments = createInterfaceId('LsTextDocuments'); References: - src/common/document_transformer_service.ts:79 - src/common/document_transformer_service.ts:81" You are a code assistant,Definition of 'getMessageBus' in file packages/lib_webview/src/types.ts in project gitlab-lsp,"Definition: getMessageBus(webviewId: WebviewId): MessageBus; } References:" You are a code assistant,Definition of 'isOpen' in file src/common/circuit_breaker/fixed_time_circuit_breaker.ts in project gitlab-lsp,"Definition: 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:" You are a code assistant,Definition of 'greet3' in file src/tests/fixtures/intent/empty_function/python.py in project gitlab-lsp,"Definition: 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:8" You are a code assistant,Definition of 'AiContextManager' in file src/common/ai_context_management_2/ai_context_manager.ts in project gitlab-lsp,"Definition: export interface AiContextManager extends DefaultAiContextManager {} export const AiContextManager = createInterfaceId('AiContextManager'); @Injectable(AiContextManager, [AiContextFileRetriever]) export class DefaultAiContextManager { #fileRetriever: AiContextFileRetriever; constructor(fileRetriever: AiContextFileRetriever) { this.#fileRetriever = fileRetriever; } #items: Map = new Map(); addItem(item: AiContextItem): boolean { if (this.#items.has(item.id)) { return false; } this.#items.set(item.id, item); return true; } removeItem(id: string): boolean { return this.#items.delete(id); } getItem(id: string): AiContextItem | undefined { return this.#items.get(id); } currentItems(): AiContextItem[] { return Array.from(this.#items.values()); } async retrieveItems(): Promise { const items = Array.from(this.#items.values()); log.info(`Retrieving ${items.length} items`); const retrievedItems = await Promise.all( items.map(async (item) => { try { switch (item.type) { case 'file': { const content = await this.#fileRetriever.retrieve(item); return content ? { ...item, content } : null; } default: throw new Error(`Unknown item type: ${item.type}`); } } catch (error) { log.error(`Failed to retrieve item ${item.id}`, error); return null; } }), ); return retrievedItems.filter((item) => item !== null); } } References: - src/common/connection_service.ts:57 - src/common/connection_service.ts:67" You are a code assistant,Definition of 'IDirectConnectionModelDetails' in file src/common/api.ts in project gitlab-lsp,"Definition: export interface IDirectConnectionModelDetails { model_provider: string; model_name: string; } export interface IDirectConnectionDetails { base_url: string; token: string; expires_at: number; headers: IDirectConnectionDetailsHeaders; model_details: IDirectConnectionModelDetails; } const CONFIG_CHANGE_EVENT_NAME = 'apiReconfigured'; @Injectable(GitLabApiClient, [LsFetch, ConfigService]) export class GitLabAPI implements GitLabApiClient { #token: string | undefined; #baseURL: string; #clientInfo?: IClientInfo; #lsFetch: LsFetch; #eventEmitter = new EventEmitter(); #configService: ConfigService; #instanceVersion?: string; constructor(lsFetch: LsFetch, configService: ConfigService) { this.#baseURL = GITLAB_API_BASE_URL; this.#lsFetch = lsFetch; this.#configService = configService; this.#configService.onConfigChange(async (config) => { this.#clientInfo = configService.get('client.clientInfo'); this.#lsFetch.updateAgentOptions({ ignoreCertificateErrors: this.#configService.get('client.ignoreCertificateErrors') ?? false, ...(this.#configService.get('client.httpAgentOptions') ?? {}), }); await this.configureApi(config.client); }); } onApiReconfigured(listener: (data: ApiReconfiguredData) => void): Disposable { this.#eventEmitter.on(CONFIG_CHANGE_EVENT_NAME, listener); return { dispose: () => this.#eventEmitter.removeListener(CONFIG_CHANGE_EVENT_NAME, listener) }; } #fireApiReconfigured(isInValidState: boolean, validationMessage?: string) { const data: ApiReconfiguredData = { isInValidState, validationMessage }; this.#eventEmitter.emit(CONFIG_CHANGE_EVENT_NAME, data); } async configureApi({ token, baseUrl = GITLAB_API_BASE_URL, }: { token?: string; baseUrl?: string; }) { if (this.#token === token && this.#baseURL === baseUrl) return; this.#token = token; this.#baseURL = baseUrl; const { valid, reason, message } = await this.checkToken(this.#token); let validationMessage; if (!valid) { this.#configService.set('client.token', undefined); validationMessage = `Token is invalid. ${message}. Reason: ${reason}`; log.warn(validationMessage); } else { log.info('Token is valid'); } this.#instanceVersion = await this.#getGitLabInstanceVersion(); this.#fireApiReconfigured(valid, validationMessage); } #looksLikePatToken(token: string): boolean { // OAuth tokens will be longer than 42 characters and PATs will be shorter. return token.length < 42; } async #checkPatToken(token: string): Promise { const headers = this.#getDefaultHeaders(token); const response = await this.#lsFetch.get( `${this.#baseURL}/api/v4/personal_access_tokens/self`, { headers }, ); await handleFetchError(response, 'Information about personal access token'); const { active, scopes } = (await response.json()) as PersonalAccessToken; if (!active) { return { valid: false, reason: 'not_active', message: 'Token is not active.', }; } if (!this.#hasValidScopes(scopes)) { const joinedScopes = scopes.map((scope) => `'${scope}'`).join(', '); return { valid: false, reason: 'invalid_scopes', message: `Token has scope(s) ${joinedScopes} (needs 'api').`, }; } return { valid: true }; } async #checkOAuthToken(token: string): Promise { const headers = this.#getDefaultHeaders(token); const response = await this.#lsFetch.get(`${this.#baseURL}/oauth/token/info`, { headers, }); await handleFetchError(response, 'Information about OAuth token'); const { scope: scopes } = (await response.json()) as OAuthToken; if (!this.#hasValidScopes(scopes)) { const joinedScopes = scopes.map((scope) => `'${scope}'`).join(', '); return { valid: false, reason: 'invalid_scopes', message: `Token has scope(s) ${joinedScopes} (needs 'api').`, }; } return { valid: true }; } async checkToken(token: string = ''): Promise { try { if (this.#looksLikePatToken(token)) { log.info('Checking token for PAT validity'); return await this.#checkPatToken(token); } log.info('Checking token for OAuth validity'); return await this.#checkOAuthToken(token); } catch (err) { log.error('Error performing token check', err); return { valid: false, reason: 'unknown', message: `Failed to check token: ${err}`, }; } } #hasValidScopes(scopes: string[]): boolean { return scopes.includes('api'); } async getCodeSuggestions( request: CodeSuggestionRequest, ): Promise { if (!this.#token) { throw new Error('Token needs to be provided to request Code Suggestions'); } const headers = { ...this.#getDefaultHeaders(this.#token), 'Content-Type': 'application/json', }; const response = await this.#lsFetch.post( `${this.#baseURL}/api/v4/code_suggestions/completions`, { headers, body: JSON.stringify(request) }, ); await handleFetchError(response, 'Code Suggestions'); const data = await response.json(); return { ...data, status: response.status }; } async *getStreamingCodeSuggestions( request: CodeSuggestionRequest, ): AsyncGenerator { if (!this.#token) { throw new Error('Token needs to be provided to stream code suggestions'); } const headers = { ...this.#getDefaultHeaders(this.#token), 'Content-Type': 'application/json', }; yield* this.#lsFetch.streamFetch( `${this.#baseURL}/api/v4/code_suggestions/completions`, JSON.stringify(request), headers, ); } async fetchFromApi(request: ApiRequest): Promise { if (!this.#token) { return Promise.reject(new Error('Token needs to be provided to authorise API request.')); } if ( request.supportedSinceInstanceVersion && !this.#instanceVersionHigherOrEqualThen(request.supportedSinceInstanceVersion.version) ) { return Promise.reject( new InvalidInstanceVersionError( `Can't ${request.supportedSinceInstanceVersion.resourceName} until your instance is upgraded to ${request.supportedSinceInstanceVersion.version} or higher.`, ), ); } if (request.type === 'graphql') { return this.#graphqlRequest(request.query, request.variables); } switch (request.method) { case 'GET': return this.#fetch(request.path, request.searchParams, 'resource', request.headers); case 'POST': return this.#postFetch(request.path, 'resource', request.body, request.headers); default: // the type assertion is necessary because TS doesn't expect any other types throw new Error(`Unknown request type ${(request as ApiRequest).type}`); } } async connectToCable(): Promise { const headers = this.#getDefaultHeaders(this.#token); const websocketOptions = { headers: { ...headers, Origin: this.#baseURL, }, }; return connectToCable(this.#baseURL, websocketOptions); } async #graphqlRequest( document: RequestDocument, variables?: V, ): Promise { const ensureEndsWithSlash = (url: string) => url.replace(/\/?$/, '/'); const endpoint = new URL('./api/graphql', ensureEndsWithSlash(this.#baseURL)).href; // supports GitLab instances that are on a custom path, e.g. ""https://example.com/gitlab"" const graphqlFetch = async ( input: RequestInfo | URL, init?: RequestInit, ): Promise => { const url = input instanceof URL ? input.toString() : input; return this.#lsFetch.post(url, { ...init, headers: { ...headers, ...init?.headers }, }); }; const headers = this.#getDefaultHeaders(this.#token); const client = new GraphQLClient(endpoint, { headers, fetch: graphqlFetch, }); return client.request(document, variables); } async #fetch( apiResourcePath: string, query: Record = {}, resourceName = 'resource', headers?: Record, ): Promise { const url = `${this.#baseURL}/api/v4${apiResourcePath}${createQueryString(query)}`; const result = await this.#lsFetch.get(url, { headers: { ...this.#getDefaultHeaders(this.#token), ...headers }, }); await handleFetchError(result, resourceName); return result.json() as Promise; } async #postFetch( apiResourcePath: string, resourceName = 'resource', body?: unknown, headers?: Record, ): Promise { const url = `${this.#baseURL}/api/v4${apiResourcePath}`; const response = await this.#lsFetch.post(url, { headers: { 'Content-Type': 'application/json', ...this.#getDefaultHeaders(this.#token), ...headers, }, body: JSON.stringify(body), }); await handleFetchError(response, resourceName); return response.json() as Promise; } #getDefaultHeaders(token?: string) { return { Authorization: `Bearer ${token}`, 'User-Agent': `code-completions-language-server-experiment (${this.#clientInfo?.name}:${this.#clientInfo?.version})`, 'X-Gitlab-Language-Server-Version': getLanguageServerVersion(), }; } #instanceVersionHigherOrEqualThen(version: string): boolean { if (!this.#instanceVersion) return false; return semverCompare(this.#instanceVersion, version) >= 0; } async #getGitLabInstanceVersion(): Promise { if (!this.#token) { return ''; } const headers = this.#getDefaultHeaders(this.#token); const response = await this.#lsFetch.get(`${this.#baseURL}/api/v4/version`, { headers, }); const { version } = await response.json(); return version; } get instanceVersion() { return this.#instanceVersion; } } References: - src/common/suggestion_client/create_v2_request.ts:6 - src/common/api.ts:114" You are a code assistant,Definition of 'DefaultRepositoryService' in file src/common/git/repository_service.ts in project gitlab-lsp,"Definition: export class DefaultRepositoryService { #virtualFileSystemService: DefaultVirtualFileSystemService; constructor(virtualFileSystemService: DefaultVirtualFileSystemService) { this.#virtualFileSystemService = virtualFileSystemService; this.#setupEventListeners(); } #setupEventListeners() { return this.#virtualFileSystemService.onFileSystemEvent(async (eventType, data) => { switch (eventType) { case VirtualFileSystemEvents.WorkspaceFilesUpdate: await this.#handleWorkspaceFilesUpdate(data as WorkspaceFilesUpdate); break; case VirtualFileSystemEvents.WorkspaceFileUpdate: await this.#handleWorkspaceFileUpdate(data as WorkspaceFileUpdate); break; default: break; } }); } async #handleWorkspaceFilesUpdate(update: WorkspaceFilesUpdate) { log.info(`Workspace files update: ${update.files.length}`); const perf1 = performance.now(); await this.handleWorkspaceFilesUpdate({ ...update, }); const perf2 = performance.now(); log.info(`Workspace files initialization took ${perf2 - perf1}ms`); const perf3 = performance.now(); const files = this.getFilesForWorkspace(update.workspaceFolder.uri, { excludeGitFolder: true, excludeIgnored: true, }); const perf4 = performance.now(); log.info(`Fetched workspace files in ${perf4 - perf3}ms`); log.info(`Workspace git files: ${files.length}`); // const treeFile = await readFile( // '/Users/angelo.rivera/gitlab/gitlab-development-kit/gitlab/tree.txt', // 'utf-8', // ); // const treeFiles = treeFile.split('\n').filter(Boolean); // // get the set difference between the files in the tree and the non-ignored files // // we need the difference between the two sets to know which files are not in the tree // const diff = new Set( // files.map((file) => // relative('/Users/angelo.rivera/gitlab/gitlab-development-kit/gitlab', file.uri.fsPath), // ), // ); // for (const file of treeFiles) { // diff.delete(file); // } // log.info(`Files not in the tree.txt: ${JSON.stringify(Array.from(diff))}`); } async #handleWorkspaceFileUpdate(update: WorkspaceFileUpdate) { log.info(`Workspace file update: ${JSON.stringify(update)}`); await this.handleWorkspaceFileUpdate({ ...update, }); const perf1 = performance.now(); const files = this.getFilesForWorkspace(update.workspaceFolder.uri, { excludeGitFolder: true, excludeIgnored: true, }); const perf2 = performance.now(); log.info(`Fetched workspace files in ${perf2 - perf1}ms`); log.info(`Workspace git files: ${files.length}`); } /** * unique map of workspace folders that point to a map of repositories * We store separate repository maps for each workspace because * the events from the VFS service are at the workspace level. * If we combined them, we may get race conditions */ #workspaces: Map = new Map(); #workspaceRepositoryTries: Map = new Map(); #buildRepositoryTrie(repositories: Repository[]): RepositoryTrie { const root = new RepositoryTrie(); for (const repo of repositories) { let node = root; const parts = repo.uri.path.split('/').filter(Boolean); for (const part of parts) { if (!node.children.has(part)) { node.children.set(part, new RepositoryTrie()); } node = node.children.get(part) as RepositoryTrie; } node.repository = repo.uri; } return root; } findMatchingRepositoryUri(fileUri: URI, workspaceFolderUri: WorkspaceFolder): URI | null { const trie = this.#workspaceRepositoryTries.get(workspaceFolderUri.uri); if (!trie) return null; let node = trie; let lastMatchingRepo: URI | null = null; const parts = fileUri.path.split('/').filter(Boolean); for (const part of parts) { if (node.repository) { lastMatchingRepo = node.repository; } if (!node.children.has(part)) break; node = node.children.get(part) as RepositoryTrie; } return node.repository || lastMatchingRepo; } getRepositoryFileForUri( fileUri: URI, repositoryUri: URI, workspaceFolder: WorkspaceFolder, ): RepositoryFile | null { const repository = this.#getRepositoriesForWorkspace(workspaceFolder.uri).get( repositoryUri.toString(), ); if (!repository) { return null; } return repository.getFile(fileUri.toString()) ?? null; } #updateRepositoriesForFolder( workspaceFolder: WorkspaceFolder, repositoryMap: RepositoryMap, repositoryTrie: RepositoryTrie, ) { this.#workspaces.set(workspaceFolder.uri, repositoryMap); this.#workspaceRepositoryTries.set(workspaceFolder.uri, repositoryTrie); } async handleWorkspaceFilesUpdate({ workspaceFolder, files }: WorkspaceFilesUpdate) { // clear existing repositories from workspace this.#emptyRepositoriesForWorkspace(workspaceFolder.uri); const repositories = this.#detectRepositories(files, workspaceFolder); const repositoryMap = new Map(repositories.map((repo) => [repo.uri.toString(), repo])); // Build and cache the repository trie for this workspace const trie = this.#buildRepositoryTrie(repositories); this.#updateRepositoriesForFolder(workspaceFolder, repositoryMap, trie); await Promise.all( repositories.map((repo) => repo.addFilesAndLoadGitIgnore( files.filter((file) => { const matchingRepo = this.findMatchingRepositoryUri(file, workspaceFolder); return matchingRepo && matchingRepo.toString() === repo.uri.toString(); }), ), ), ); } async handleWorkspaceFileUpdate({ fileUri, workspaceFolder, event }: WorkspaceFileUpdate) { const repoUri = this.findMatchingRepositoryUri(fileUri, workspaceFolder); if (!repoUri) { log.debug(`No matching repository found for file ${fileUri.toString()}`); return; } const repositoryMap = this.#getRepositoriesForWorkspace(workspaceFolder.uri); const repository = repositoryMap.get(repoUri.toString()); if (!repository) { log.debug(`Repository not found for URI ${repoUri.toString()}`); return; } if (repository.isFileIgnored(fileUri)) { log.debug(`File ${fileUri.toString()} is ignored`); return; } switch (event) { case 'add': repository.setFile(fileUri); log.debug(`File ${fileUri.toString()} added to repository ${repoUri.toString()}`); break; case 'change': repository.setFile(fileUri); log.debug(`File ${fileUri.toString()} updated in repository ${repoUri.toString()}`); break; case 'unlink': repository.removeFile(fileUri.toString()); log.debug(`File ${fileUri.toString()} removed from repository ${repoUri.toString()}`); break; default: log.warn(`Unknown file event ${event} for file ${fileUri.toString()}`); } } #getRepositoriesForWorkspace(workspaceFolderUri: WorkspaceFolderUri): RepositoryMap { return this.#workspaces.get(workspaceFolderUri) || new Map(); } #emptyRepositoriesForWorkspace(workspaceFolderUri: WorkspaceFolderUri): void { log.debug(`Emptying repositories for workspace ${workspaceFolderUri}`); const repos = this.#workspaces.get(workspaceFolderUri); if (!repos || repos.size === 0) return; // clear up ignore manager trie from memory repos.forEach((repo) => { repo.dispose(); log.debug(`Repository ${repo.uri} has been disposed`); }); repos.clear(); const trie = this.#workspaceRepositoryTries.get(workspaceFolderUri); if (trie) { trie.dispose(); this.#workspaceRepositoryTries.delete(workspaceFolderUri); } this.#workspaces.delete(workspaceFolderUri); log.debug(`Repositories for workspace ${workspaceFolderUri} have been emptied`); } #detectRepositories(files: URI[], workspaceFolder: WorkspaceFolder): Repository[] { const gitConfigFiles = files.filter((file) => file.toString().endsWith('.git/config')); return gitConfigFiles.map((file) => { const projectUri = fsPathToUri(file.path.replace('.git/config', '')); const ignoreManager = new IgnoreManager(projectUri.fsPath); log.info(`Detected repository at ${projectUri.path}`); return new Repository({ ignoreManager, uri: projectUri, configFileUri: file, workspaceFolder, }); }); } getFilesForWorkspace( workspaceFolderUri: WorkspaceFolderUri, options: { excludeGitFolder?: boolean; excludeIgnored?: boolean } = {}, ): RepositoryFile[] { const repositories = this.#getRepositoriesForWorkspace(workspaceFolderUri); const allFiles: RepositoryFile[] = []; repositories.forEach((repository) => { repository.getFiles().forEach((file) => { // apply the filters if (options.excludeGitFolder && this.#isInGitFolder(file.uri, repository.uri)) { return; } if (options.excludeIgnored && file.isIgnored) { return; } allFiles.push(file); }); }); return allFiles; } // Helper method to check if a file is in the .git folder #isInGitFolder(fileUri: URI, repositoryUri: URI): boolean { const relativePath = fileUri.path.slice(repositoryUri.path.length); return relativePath.split('/').some((part) => part === '.git'); } } References: - src/common/ai_context_management_2/providers/ai_file_context_provider.ts:23 - src/common/ai_context_management_2/providers/ai_file_context_provider.ts:21" You are a code assistant,Definition of 'start' in file src/common/test_utils/create_fake_response.ts in project gitlab-lsp,"Definition: start(controller) { // Add text (as Uint8Array) to the stream controller.enqueue(new TextEncoder().encode(text)); }, }), }); }; References:" You are a code assistant,Definition of 'isStream' in file src/common/utils/suggestion_mappers.ts in project gitlab-lsp,"Definition: export const isStream = (o: SuggestionOptionOrStream): o is StartStreamOption => Boolean((o as StartStreamOption).streamId); export const isTextSuggestion = (o: SuggestionOptionOrStream): o is SuggestionOption => Boolean((o as SuggestionOption).text); export const completionOptionMapper = (options: SuggestionOption[]): CompletionItem[] => options.map((option, index) => ({ label: `GitLab Suggestion ${index + 1}: ${option.text}`, kind: CompletionItemKind.Text, insertText: option.text, detail: option.text, command: { title: 'Accept suggestion', command: SUGGESTION_ACCEPTED_COMMAND, arguments: [option.uniqueTrackingId], }, data: { index, trackingId: option.uniqueTrackingId, }, })); /* this value will be used for telemetry so to make it human-readable we use the 1-based indexing instead of 0 */ const getOptionTrackingIndex = (option: SuggestionOption) => { return typeof option.index === 'number' ? option.index + 1 : undefined; }; export const inlineCompletionOptionMapper = ( params: InlineCompletionParams, options: SuggestionOptionOrStream[], ): InlineCompletionList => ({ items: options.map((option) => { if (isStream(option)) { // the streaming item is empty and only indicates to the client that streaming started return { insertText: '', command: { title: 'Start streaming', command: START_STREAMING_COMMAND, arguments: [option.streamId, option.uniqueTrackingId], }, }; } const completionInfo = params.context.selectedCompletionInfo; let rangeDiff = 0; if (completionInfo) { const range = sanitizeRange(completionInfo.range); rangeDiff = range.end.character - range.start.character; } return { insertText: completionInfo ? `${completionInfo.text.substring(rangeDiff)}${option.text}` : option.text, range: Range.create(params.position, params.position), command: { title: 'Accept suggestion', command: SUGGESTION_ACCEPTED_COMMAND, arguments: [option.uniqueTrackingId, getOptionTrackingIndex(option)], }, }; }), }); References: - src/common/utils/suggestion_mappers.ts:46" You are a code assistant,Definition of 'ContextItem' in file src/common/tracking/snowplow_tracker.ts in project gitlab-lsp,"Definition: interface ContextItem { file_extension: string; type: AdditionalContext['type']; resolution_strategy: ContextResolution['strategy']; byte_size: number; } export interface ISnowplowCodeSuggestionContext { schema: string; data: { prefix_length?: number; suffix_length?: number; language?: string | null; gitlab_realm?: GitlabRealm; model_engine?: string | null; model_name?: string | null; api_status_code?: number | null; debounce_interval?: number | null; suggestion_source?: SuggestionSource; gitlab_global_user_id?: string | null; gitlab_instance_id?: string | null; gitlab_host_name?: string | null; gitlab_saas_duo_pro_namespace_ids: number[] | null; gitlab_instance_version: string | null; is_streaming?: boolean; is_invoked?: boolean | null; options_count?: number | null; accepted_option?: number | null; /** * boolean indicating whether the feature is enabled * and we sent context in the request */ has_advanced_context?: boolean | null; /** * boolean indicating whether request is direct to cloud connector */ is_direct_connection?: boolean | null; total_context_size_bytes?: number; content_above_cursor_size_bytes?: number; content_below_cursor_size_bytes?: number; /** * set of final context items sent to AI Gateway */ context_items?: ContextItem[] | null; /** * total tokens used in request to model provider */ input_tokens?: number | null; /** * total output tokens recieved from model provider */ output_tokens?: number | null; /** * total tokens sent as context to AI Gateway */ context_tokens_sent?: number | null; /** * total context tokens used in request to model provider */ context_tokens_used?: number | null; }; } interface ISnowplowClientContext { schema: string; data: { ide_name?: string | null; ide_vendor?: string | null; ide_version?: string | null; extension_name?: string | null; extension_version?: string | null; language_server_version?: string | null; }; } const DEFAULT_SNOWPLOW_OPTIONS = { appId: 'gitlab_ide_extension', timeInterval: 5000, maxItems: 10, }; export const EVENT_VALIDATION_ERROR_MSG = `Telemetry event context is not valid - event won't be tracked.`; 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(); #lsFetch: LsFetch; #featureFlagService: FeatureFlagService; #gitlabRealm: GitlabRealm = GitlabRealm.saas; #codeSuggestionsContextMap = new Map(); 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, ) { 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, ) { 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 'engaged' in file src/common/feature_state/supported_language_check.ts in project gitlab-lsp,"Definition: get engaged() { return !this.#isLanguageEnabled; } get id() { return this.#isLanguageSupported && !this.#isLanguageEnabled ? DISABLED_LANGUAGE : UNSUPPORTED_LANGUAGE; } details = 'Code suggestions are not supported for this language'; #update() { this.#checkLanguage(); this.#stateEmitter.emit('change', this); } #checkLanguage() { if (!this.#currentDocument) { this.#isLanguageEnabled = false; this.#isLanguageSupported = false; return; } const { languageId } = this.#currentDocument; this.#isLanguageEnabled = this.#supportedLanguagesService.isLanguageEnabled(languageId); this.#isLanguageSupported = this.#supportedLanguagesService.isLanguageSupported(languageId); } } References:" You are a code assistant,Definition of 'hasbin' in file src/tests/int/hasbin.ts in project gitlab-lsp,"Definition: export function hasbin(bin: string, done: (result: boolean) => void) { async.some(getPaths(bin), fileExists, done); } export function hasbinSync(bin: string) { return getPaths(bin).some(fileExistsSync); } export function hasbinAll(bins: string[], done: (result: boolean) => void) { async.every(bins, hasbin.async, done); } export function hasbinAllSync(bins: string[]) { return bins.every(hasbin.sync); } export function hasbinSome(bins: string[], done: (result: boolean) => void) { async.some(bins, hasbin.async, done); } export function hasbinSomeSync(bins: string[]) { return bins.some(hasbin.sync); } export function hasbinFirst(bins: string[], done: (result: boolean) => void) { async.detect(bins, hasbin.async, function (result) { done(result || false); }); } export function hasbinFirstSync(bins: string[]) { const matched = bins.filter(hasbin.sync); return matched.length ? matched[0] : false; } export function getPaths(bin: string) { const envPath = process.env.PATH || ''; const envExt = process.env.PATHEXT || ''; return envPath .replace(/[""]+/g, '') .split(delimiter) .map(function (chunk) { return envExt.split(delimiter).map(function (ext) { return join(chunk, bin + ext); }); }) .reduce(function (a, b) { return a.concat(b); }); } 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 'VirtualFileSystemEvents' in file src/common/services/fs/virtual_file_service.ts in project gitlab-lsp,"Definition: 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 { (eventType: T, data: FileSystemEventMap[T]): void; } export type VirtualFileSystemService = typeof DefaultVirtualFileSystemService.prototype; export const VirtualFileSystemService = createInterfaceId( '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 { 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( 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 'Greet3' in file src/tests/fixtures/intent/empty_function/python.py in project gitlab-lsp,"Definition: 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:34" You are a code assistant,Definition of 'CommentResolution' in file src/common/tree_sitter/comments/comment_resolver.ts in project gitlab-lsp,"Definition: export type CommentResolution = | { commentAtCursor: Comment; commentAboveCursor?: never } | { commentAtCursor?: never; commentAboveCursor: Comment }; export class CommentResolver { protected queryByLanguage: Map; constructor() { this.queryByLanguage = new Map(); } #getQueryByLanguage( language: TreeSitterLanguageName, treeSitterLanguage: Language, ): Query | undefined { const query = this.queryByLanguage.get(language); if (query) { return query; } const queryString = commentQueries[language]; if (!queryString) { log.warn(`No comment query found for language: ${language}`); return undefined; } const newQuery = treeSitterLanguage.query(queryString); this.queryByLanguage.set(language, newQuery); return newQuery; } /** * Returns the comment that is on or directly above the cursor, if it exists. * To handle the case the comment may be several new lines above the cursor, * we traverse the tree to check if any nodes are between the comment and the cursor. */ getCommentForCursor({ languageName, tree, cursorPosition, treeSitterLanguage, }: { languageName: TreeSitterLanguageName; tree: Tree; treeSitterLanguage: Language; cursorPosition: Point; }): CommentResolution | undefined { const query = this.#getQueryByLanguage(languageName, treeSitterLanguage); if (!query) { return undefined; } const comments = query.captures(tree.rootNode).map((capture) => { return { start: capture.node.startPosition, end: capture.node.endPosition, content: capture.node.text, capture, }; }); const commentAtCursor = CommentResolver.#getCommentAtCursor(comments, cursorPosition); if (commentAtCursor) { // No need to further check for isPositionInNode etc. as cursor is directly on the comment return { commentAtCursor }; } const commentAboveCursor = CommentResolver.#getCommentAboveCursor(comments, cursorPosition); if (!commentAboveCursor) { return undefined; } const commentParentNode = commentAboveCursor.capture.node.parent; if (!commentParentNode) { return undefined; } if (!CommentResolver.#isPositionInNode(cursorPosition, commentParentNode)) { return undefined; } const directChildren = commentParentNode.children; for (const child of directChildren) { const hasNodeBetweenCursorAndComment = child.startPosition.row > commentAboveCursor.capture.node.endPosition.row && child.startPosition.row <= cursorPosition.row; if (hasNodeBetweenCursorAndComment) { return undefined; } } return { commentAboveCursor }; } static #isPositionInNode(position: Point, node: SyntaxNode): boolean { return position.row >= node.startPosition.row && position.row <= node.endPosition.row; } static #getCommentAboveCursor(comments: Comment[], cursorPosition: Point): Comment | undefined { return CommentResolver.#getLastComment( comments.filter((comment) => comment.end.row < cursorPosition.row), ); } static #getCommentAtCursor(comments: Comment[], cursorPosition: Point): Comment | undefined { return CommentResolver.#getLastComment( comments.filter( (comment) => comment.start.row <= cursorPosition.row && comment.end.row >= cursorPosition.row, ), ); } static #getLastComment(comments: Comment[]): Comment | undefined { return comments.sort((a, b) => b.end.row - a.end.row)[0]; } /** * Returns the total number of lines that are comments in a parsed syntax tree. * Uses a Set because we only want to count each line once. * @param {Object} params - Parameters for counting comment lines. * @param {TreeSitterLanguageName} params.languageName - The name of the programming language. * @param {Tree} params.tree - The syntax tree to analyze. * @param {Language} params.treeSitterLanguage - The Tree-sitter language instance. * @returns {number} - The total number of unique lines containing comments. */ getTotalCommentLines({ treeSitterLanguage, languageName, tree, }: { languageName: TreeSitterLanguageName; treeSitterLanguage: Language; tree: Tree; }): number { const query = this.#getQueryByLanguage(languageName, treeSitterLanguage); const captures = query ? query.captures(tree.rootNode) : []; // Note: in future, we could potentially re-use captures from getCommentForCursor() const commentLineSet = new Set(); // A Set is used to only count each line once (the same comment can span multiple lines) captures.forEach((capture) => { const { startPosition, endPosition } = capture.node; for (let { row } = startPosition; row <= endPosition.row; row++) { commentLineSet.add(row); } }); return commentLineSet.size; } static isCommentEmpty(comment: Comment): boolean { const trimmedContent = comment.content.trim().replace(/[\n\r\\]/g, ' '); // Count the number of alphanumeric characters in the trimmed content const alphanumericCount = (trimmedContent.match(/[a-zA-Z0-9]/g) || []).length; return alphanumericCount <= 2; } } let commentResolver: CommentResolver; export function getCommentResolver(): CommentResolver { if (!commentResolver) { commentResolver = new CommentResolver(); } return commentResolver; } References:" You are a code assistant,Definition of 'hasbinSome' in file src/tests/int/hasbin.ts in project gitlab-lsp,"Definition: export function hasbinSome(bins: string[], done: (result: boolean) => void) { async.some(bins, hasbin.async, done); } export function hasbinSomeSync(bins: string[]) { return bins.some(hasbin.sync); } export function hasbinFirst(bins: string[], done: (result: boolean) => void) { async.detect(bins, hasbin.async, function (result) { done(result || false); }); } export function hasbinFirstSync(bins: string[]) { const matched = bins.filter(hasbin.sync); return matched.length ? matched[0] : false; } export function getPaths(bin: string) { const envPath = process.env.PATH || ''; const envExt = process.env.PATHEXT || ''; return envPath .replace(/[""]+/g, '') .split(delimiter) .map(function (chunk) { return envExt.split(delimiter).map(function (ext) { return join(chunk, bin + ext); }); }) .reduce(function (a, b) { return a.concat(b); }); } 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 'processStream' in file src/common/suggestion_client/post_processors/post_processor_pipeline.test.ts in project gitlab-lsp,"Definition: async processStream( _context: IDocContext, input: StreamingCompletionResponse, ): Promise { return input; } async processCompletion( _context: IDocContext, input: SuggestionOption[], ): Promise { 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 'GET_WEBVIEW_METADATA_REQUEST' in file src/common/connection.ts in project gitlab-lsp,"Definition: export const GET_WEBVIEW_METADATA_REQUEST = '$/gitlab/webview-metadata'; export function setup( telemetryTracker: TelemetryTracker, connection: Connection, documentTransformerService: DocumentTransformerService, apiClient: GitLabApiClient, featureFlagService: FeatureFlagService, configService: ConfigService, { treeSitterParser, }: { treeSitterParser: TreeSitterParser; }, webviewMetadataProvider: WebviewMetadataProvider | undefined = undefined, workflowAPI: WorkflowAPI | undefined = undefined, duoProjectAccessChecker: DuoProjectAccessChecker, duoProjectAccessCache: DuoProjectAccessCache, virtualFileSystemService: VirtualFileSystemService, ) { const suggestionService = new DefaultSuggestionService({ telemetryTracker, connection, configService, api: apiClient, featureFlagService, treeSitterParser, documentTransformerService, duoProjectAccessChecker, }); const messageHandler = new MessageHandler({ telemetryTracker, connection, configService, featureFlagService, duoProjectAccessCache, virtualFileSystemService, workflowAPI, }); connection.onCompletion(suggestionService.completionHandler); // TODO: does Visual Studio or Neovim need this? VS Code doesn't connection.onCompletionResolve((item: CompletionItem) => item); connection.onRequest(InlineCompletionRequest.type, suggestionService.inlineCompletionHandler); connection.onDidChangeConfiguration(messageHandler.didChangeConfigurationHandler); connection.onNotification(TELEMETRY_NOTIFICATION, messageHandler.telemetryNotificationHandler); connection.onNotification( START_WORKFLOW_NOTIFICATION, messageHandler.startWorkflowNotificationHandler, ); connection.onRequest(GET_WEBVIEW_METADATA_REQUEST, () => { return webviewMetadataProvider?.getMetadata() ?? []; }); connection.onShutdown(messageHandler.onShutdownHandler); } References:" You are a code assistant,Definition of 'GC_TIME' in file src/common/tracking/constants.ts in project gitlab-lsp,"Definition: 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 'Method' in file packages/lib_message_bus/src/types/bus.ts in project gitlab-lsp,"Definition: export type Method = string; /** * Represents the state of a message payload and can either be empty (no data) or contain a single data item. * Payloads are wrapped in a tuple to maintain consistent structure and type-checking capabilities across message handlers. * * @example * type NoPayload = []; * type WithStringPayload = [string]; */ export type MessagePayload = unknown | undefined; export type KeysWithOptionalValues = { [K in keyof T]: undefined extends T[K] ? K : never; }[keyof T]; /** * Maps notification message types to their corresponding payloads. * @typedef {Record} NotificationMap */ export type NotificationMap = Record; /** * Interface for publishing notifications. * @interface * @template {NotificationMap} TNotifications */ export interface NotificationPublisher { sendNotification>(type: T): void; sendNotification(type: T, payload: TNotifications[T]): void; } /** * Interface for listening to notifications. * @interface * @template {NotificationMap} TNotifications */ export interface NotificationListener { onNotification>( type: T, handler: () => void, ): Disposable; onNotification( type: T, handler: (payload: TNotifications[T]) => void, ): Disposable; } /** * Maps request message types to their corresponding request/response payloads. * @typedef {Record} RequestMap */ export type RequestMap = Record< Method, { params: MessagePayload; result: MessagePayload; } >; type KeysWithOptionalParams = { [K in keyof R]: R[K]['params'] extends undefined ? never : K; }[keyof R]; /** * Extracts the response payload type from a request type. * @template {MessagePayload} T * @typedef {T extends [never] ? void : T[0]} ExtractRequestResponse */ export type ExtractRequestResult = // eslint-disable-next-line @typescript-eslint/no-invalid-void-type T['result'] extends undefined ? void : T; /** * Interface for publishing requests. * @interface * @template {RequestMap} TRequests */ export interface RequestPublisher { sendRequest>( type: T, ): Promise>; sendRequest( type: T, payload: TRequests[T]['params'], ): Promise>; } /** * Interface for listening to requests. * @interface * @template {RequestMap} TRequests */ export interface RequestListener { onRequest>( type: T, handler: () => Promise>, ): Disposable; onRequest( type: T, handler: (payload: TRequests[T]['params']) => Promise>, ): Disposable; } /** * Defines the structure for message definitions, including notifications and requests. */ export type MessageDefinitions< TNotifications extends NotificationMap = NotificationMap, TRequests extends RequestMap = RequestMap, > = { notifications: TNotifications; requests: TRequests; }; export type MessageMap< TInboundMessageDefinitions extends MessageDefinitions = MessageDefinitions, TOutboundMessageDefinitions extends MessageDefinitions = MessageDefinitions, > = { inbound: TInboundMessageDefinitions; outbound: TOutboundMessageDefinitions; }; export interface MessageBus extends NotificationPublisher, NotificationListener, RequestPublisher, RequestListener {} References: - packages/lib_webview/src/setup/plugin/webview_instance_message_bus.ts:90 - packages/lib_webview/src/setup/plugin/webview_instance_message_bus.ts:139 - packages/lib_webview/src/setup/plugin/webview_instance_message_bus.ts:99 - packages/lib_webview/src/setup/plugin/webview_instance_message_bus.ts:103" You are a code assistant,Definition of 'error' in file packages/lib_logging/src/null_logger.ts in project gitlab-lsp,"Definition: error(message: string, e?: Error | undefined): void; error(): void { // NOOP } } 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 'WORKFLOW_EXECUTOR_DOWNLOAD_PATH' in file src/common/constants.ts in project gitlab-lsp,"Definition: 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 'getMessageBus' in file src/common/webview/extension/extension_connection_message_bus_provider.ts in project gitlab-lsp,"Definition: getMessageBus(webviewId: WebviewId): MessageBus { return new ExtensionConnectionMessageBus({ webviewId, connection: this.#connection, rpcMethods: this.#rpcMethods, handlers: this.#handlers, }); } dispose(): void { this.#disposables.dispose(); } #setupConnectionSubscriptions() { this.#disposables.add( this.#connection.onNotification( this.#rpcMethods.notification, handleNotificationMessage(this.#notificationHandlers, this.#logger), ), ); this.#disposables.add( this.#connection.onRequest( this.#rpcMethods.request, handleRequestMessage(this.#requestHandlers, this.#logger), ), ); } } References:" You are a code assistant,Definition of 'WorkflowGraphQLService' in file packages/webview_duo_workflow/src/plugin/index.ts in project gitlab-lsp,"Definition: export interface WorkflowGraphQLService { pollWorkflowEvents(id: string, messageBus: MessageBus): Promise; getWorkflowEvents(id: string): Promise; } export const workflowPluginFactory = ( graphqlApi: WorkflowGraphQLService, workflowApi: WorkflowAPI, connection: Connection, ): WebviewPlugin => { 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: - src/node/main.ts:174 - src/common/graphql/workflow/service.test.ts:14 - src/common/graphql/workflow/service.test.ts:44 - packages/webview_duo_workflow/src/plugin/index.ts:14" You are a code assistant,Definition of 'debug' in file packages/lib_logging/src/null_logger.ts in project gitlab-lsp,"Definition: debug(e: Error): void; debug(message: string, e?: Error | undefined): void; debug(): void { // NOOP } info(e: Error): void; info(message: string, e?: Error | undefined): void; info(): void { // NOOP } warn(e: Error): void; warn(message: string, e?: Error | undefined): void; warn(): void { // NOOP } error(e: Error): void; error(message: string, e?: Error | undefined): void; error(): void { // NOOP } } References:" You are a code assistant,Definition of 'Greet2' in file src/tests/fixtures/intent/empty_function/javascript.js in project gitlab-lsp,"Definition: 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:24" You are a code assistant,Definition of 'GetBufferRequest' in file packages/webview_duo_chat/src/plugin/port/platform/web_ide.ts in project gitlab-lsp,"Definition: export interface GetBufferRequest extends GetRequestBase { type: 'rest-buffer'; } export interface GraphQLRequest<_TReturnType> { type: 'graphql'; query: string; /** Options passed to the GraphQL query */ variables: Record; } 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; /* 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: - packages/webview_duo_chat/src/plugin/port/platform/web_ide.ts:96" You are a code assistant,Definition of 'ExtensionConnectionMessageBusProps' in file src/common/webview/extension/extension_connection_message_bus.ts in project gitlab-lsp,"Definition: type ExtensionConnectionMessageBusProps = { webviewId: WebviewId; connection: Connection; rpcMethods: RpcMethods; handlers: Handlers; }; export class ExtensionConnectionMessageBus implements MessageBus { #webviewId: WebviewId; #connection: Connection; #rpcMethods: RpcMethods; #handlers: Handlers; constructor({ webviewId, connection, rpcMethods, handlers }: ExtensionConnectionMessageBusProps) { this.#webviewId = webviewId; this.#connection = connection; this.#rpcMethods = rpcMethods; this.#handlers = handlers; } onRequest( type: T, handler: ( payload: TMessageMap['inbound']['requests'][T]['params'], ) => Promise>, ): Disposable { return this.#handlers.request.register({ webviewId: this.#webviewId, type }, handler); } onNotification( type: T, handler: (payload: TMessageMap['inbound']['notifications'][T]) => void, ): Disposable { return this.#handlers.notification.register({ webviewId: this.#webviewId, type }, handler); } sendRequest( type: T, payload?: TMessageMap['outbound']['requests'][T]['params'], ): Promise> { return this.#connection.sendRequest(this.#rpcMethods.request, { webviewId: this.#webviewId, type, payload, }); } async sendNotification( type: T, payload?: TMessageMap['outbound']['notifications'][T], ): Promise { await this.#connection.sendNotification(this.#rpcMethods.notification, { webviewId: this.#webviewId, type, payload, }); } } References: - src/common/webview/extension/extension_connection_message_bus.ts:25" You are a code assistant,Definition of 'dispose' in file packages/lib_handler_registry/src/registry/hashed_registry.ts in project gitlab-lsp,"Definition: dispose() { this.#basicRegistry.dispose(); } } References:" You are a code assistant,Definition of 'IDirectConnectionDetailsHeaders' in file src/common/api.ts in project gitlab-lsp,"Definition: export interface IDirectConnectionDetailsHeaders { 'X-Gitlab-Global-User-Id': string; 'X-Gitlab-Instance-Id': string; 'X-Gitlab-Host-Name': string; 'X-Gitlab-Saas-Duo-Pro-Namespace-Ids': string; } export interface IDirectConnectionModelDetails { model_provider: string; model_name: string; } export interface IDirectConnectionDetails { base_url: string; token: string; expires_at: number; headers: IDirectConnectionDetailsHeaders; model_details: IDirectConnectionModelDetails; } const CONFIG_CHANGE_EVENT_NAME = 'apiReconfigured'; @Injectable(GitLabApiClient, [LsFetch, ConfigService]) export class GitLabAPI implements GitLabApiClient { #token: string | undefined; #baseURL: string; #clientInfo?: IClientInfo; #lsFetch: LsFetch; #eventEmitter = new EventEmitter(); #configService: ConfigService; #instanceVersion?: string; constructor(lsFetch: LsFetch, configService: ConfigService) { this.#baseURL = GITLAB_API_BASE_URL; this.#lsFetch = lsFetch; this.#configService = configService; this.#configService.onConfigChange(async (config) => { this.#clientInfo = configService.get('client.clientInfo'); this.#lsFetch.updateAgentOptions({ ignoreCertificateErrors: this.#configService.get('client.ignoreCertificateErrors') ?? false, ...(this.#configService.get('client.httpAgentOptions') ?? {}), }); await this.configureApi(config.client); }); } onApiReconfigured(listener: (data: ApiReconfiguredData) => void): Disposable { this.#eventEmitter.on(CONFIG_CHANGE_EVENT_NAME, listener); return { dispose: () => this.#eventEmitter.removeListener(CONFIG_CHANGE_EVENT_NAME, listener) }; } #fireApiReconfigured(isInValidState: boolean, validationMessage?: string) { const data: ApiReconfiguredData = { isInValidState, validationMessage }; this.#eventEmitter.emit(CONFIG_CHANGE_EVENT_NAME, data); } async configureApi({ token, baseUrl = GITLAB_API_BASE_URL, }: { token?: string; baseUrl?: string; }) { if (this.#token === token && this.#baseURL === baseUrl) return; this.#token = token; this.#baseURL = baseUrl; const { valid, reason, message } = await this.checkToken(this.#token); let validationMessage; if (!valid) { this.#configService.set('client.token', undefined); validationMessage = `Token is invalid. ${message}. Reason: ${reason}`; log.warn(validationMessage); } else { log.info('Token is valid'); } this.#instanceVersion = await this.#getGitLabInstanceVersion(); this.#fireApiReconfigured(valid, validationMessage); } #looksLikePatToken(token: string): boolean { // OAuth tokens will be longer than 42 characters and PATs will be shorter. return token.length < 42; } async #checkPatToken(token: string): Promise { const headers = this.#getDefaultHeaders(token); const response = await this.#lsFetch.get( `${this.#baseURL}/api/v4/personal_access_tokens/self`, { headers }, ); await handleFetchError(response, 'Information about personal access token'); const { active, scopes } = (await response.json()) as PersonalAccessToken; if (!active) { return { valid: false, reason: 'not_active', message: 'Token is not active.', }; } if (!this.#hasValidScopes(scopes)) { const joinedScopes = scopes.map((scope) => `'${scope}'`).join(', '); return { valid: false, reason: 'invalid_scopes', message: `Token has scope(s) ${joinedScopes} (needs 'api').`, }; } return { valid: true }; } async #checkOAuthToken(token: string): Promise { const headers = this.#getDefaultHeaders(token); const response = await this.#lsFetch.get(`${this.#baseURL}/oauth/token/info`, { headers, }); await handleFetchError(response, 'Information about OAuth token'); const { scope: scopes } = (await response.json()) as OAuthToken; if (!this.#hasValidScopes(scopes)) { const joinedScopes = scopes.map((scope) => `'${scope}'`).join(', '); return { valid: false, reason: 'invalid_scopes', message: `Token has scope(s) ${joinedScopes} (needs 'api').`, }; } return { valid: true }; } async checkToken(token: string = ''): Promise { try { if (this.#looksLikePatToken(token)) { log.info('Checking token for PAT validity'); return await this.#checkPatToken(token); } log.info('Checking token for OAuth validity'); return await this.#checkOAuthToken(token); } catch (err) { log.error('Error performing token check', err); return { valid: false, reason: 'unknown', message: `Failed to check token: ${err}`, }; } } #hasValidScopes(scopes: string[]): boolean { return scopes.includes('api'); } async getCodeSuggestions( request: CodeSuggestionRequest, ): Promise { if (!this.#token) { throw new Error('Token needs to be provided to request Code Suggestions'); } const headers = { ...this.#getDefaultHeaders(this.#token), 'Content-Type': 'application/json', }; const response = await this.#lsFetch.post( `${this.#baseURL}/api/v4/code_suggestions/completions`, { headers, body: JSON.stringify(request) }, ); await handleFetchError(response, 'Code Suggestions'); const data = await response.json(); return { ...data, status: response.status }; } async *getStreamingCodeSuggestions( request: CodeSuggestionRequest, ): AsyncGenerator { if (!this.#token) { throw new Error('Token needs to be provided to stream code suggestions'); } const headers = { ...this.#getDefaultHeaders(this.#token), 'Content-Type': 'application/json', }; yield* this.#lsFetch.streamFetch( `${this.#baseURL}/api/v4/code_suggestions/completions`, JSON.stringify(request), headers, ); } async fetchFromApi(request: ApiRequest): Promise { if (!this.#token) { return Promise.reject(new Error('Token needs to be provided to authorise API request.')); } if ( request.supportedSinceInstanceVersion && !this.#instanceVersionHigherOrEqualThen(request.supportedSinceInstanceVersion.version) ) { return Promise.reject( new InvalidInstanceVersionError( `Can't ${request.supportedSinceInstanceVersion.resourceName} until your instance is upgraded to ${request.supportedSinceInstanceVersion.version} or higher.`, ), ); } if (request.type === 'graphql') { return this.#graphqlRequest(request.query, request.variables); } switch (request.method) { case 'GET': return this.#fetch(request.path, request.searchParams, 'resource', request.headers); case 'POST': return this.#postFetch(request.path, 'resource', request.body, request.headers); default: // the type assertion is necessary because TS doesn't expect any other types throw new Error(`Unknown request type ${(request as ApiRequest).type}`); } } async connectToCable(): Promise { const headers = this.#getDefaultHeaders(this.#token); const websocketOptions = { headers: { ...headers, Origin: this.#baseURL, }, }; return connectToCable(this.#baseURL, websocketOptions); } async #graphqlRequest( document: RequestDocument, variables?: V, ): Promise { const ensureEndsWithSlash = (url: string) => url.replace(/\/?$/, '/'); const endpoint = new URL('./api/graphql', ensureEndsWithSlash(this.#baseURL)).href; // supports GitLab instances that are on a custom path, e.g. ""https://example.com/gitlab"" const graphqlFetch = async ( input: RequestInfo | URL, init?: RequestInit, ): Promise => { const url = input instanceof URL ? input.toString() : input; return this.#lsFetch.post(url, { ...init, headers: { ...headers, ...init?.headers }, }); }; const headers = this.#getDefaultHeaders(this.#token); const client = new GraphQLClient(endpoint, { headers, fetch: graphqlFetch, }); return client.request(document, variables); } async #fetch( apiResourcePath: string, query: Record = {}, resourceName = 'resource', headers?: Record, ): Promise { const url = `${this.#baseURL}/api/v4${apiResourcePath}${createQueryString(query)}`; const result = await this.#lsFetch.get(url, { headers: { ...this.#getDefaultHeaders(this.#token), ...headers }, }); await handleFetchError(result, resourceName); return result.json() as Promise; } async #postFetch( apiResourcePath: string, resourceName = 'resource', body?: unknown, headers?: Record, ): Promise { const url = `${this.#baseURL}/api/v4${apiResourcePath}`; const response = await this.#lsFetch.post(url, { headers: { 'Content-Type': 'application/json', ...this.#getDefaultHeaders(this.#token), ...headers, }, body: JSON.stringify(body), }); await handleFetchError(response, resourceName); return response.json() as Promise; } #getDefaultHeaders(token?: string) { return { Authorization: `Bearer ${token}`, 'User-Agent': `code-completions-language-server-experiment (${this.#clientInfo?.name}:${this.#clientInfo?.version})`, 'X-Gitlab-Language-Server-Version': getLanguageServerVersion(), }; } #instanceVersionHigherOrEqualThen(version: string): boolean { if (!this.#instanceVersion) return false; return semverCompare(this.#instanceVersion, version) >= 0; } async #getGitLabInstanceVersion(): Promise { if (!this.#token) { return ''; } const headers = this.#getDefaultHeaders(this.#token); const response = await this.#lsFetch.get(`${this.#baseURL}/api/v4/version`, { headers, }); const { version } = await response.json(); return version; } get instanceVersion() { return this.#instanceVersion; } } References: - src/common/utils/headers_to_snowplow_options.ts:7 - src/common/api.ts:113" You are a code assistant,Definition of 'COMPLETION' in file src/common/suggestion_client/suggestion_client.ts in project gitlab-lsp,"Definition: export const COMPLETION = 'completion'; export type Intent = typeof GENERATION | typeof COMPLETION | undefined; export interface SuggestionContext { document: IDocContext; intent?: Intent; projectPath?: string; optionsCount?: OptionsCount; additionalContexts?: AdditionalContext[]; } export interface SuggestionResponse { choices?: SuggestionResponseChoice[]; model?: SuggestionModel; status: number; error?: string; isDirectConnection?: boolean; } export interface SuggestionResponseChoice { text: string; } export interface SuggestionClient { getSuggestions(context: SuggestionContext): Promise; } export type SuggestionClientFn = SuggestionClient['getSuggestions']; export type SuggestionClientMiddleware = ( context: SuggestionContext, next: SuggestionClientFn, ) => ReturnType; References:" You are a code assistant,Definition of 'hello' in file src/tests/fixtures/intent/typescript_comments.ts in project gitlab-lsp,"Definition: function hello(user) { // function to greet the user } References:" You are a code assistant,Definition of 'getStatus' in file src/common/graphql/workflow/service.ts in project gitlab-lsp,"Definition: 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 { const workflowId = this.generateWorkflowID(id); let timeout: NodeJS.Timeout; const poll = async (): Promise => { 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 { 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 'toEventuallyContainChildProcessConsoleOutput' in file src/tests/int/test_utils.ts in project gitlab-lsp,"Definition: toEventuallyContainChildProcessConsoleOutput( expectedMessage: string, timeoutMs?: number, intervalMs?: number, ): Promise; } } } expect.extend({ /** * Custom matcher to check the language client child process console output for an expected string. * This is useful when an operation does not directly run some logic, (e.g. internally emits events * which something later does the thing you're testing), so you cannot just await and check the output. * * await expect(lsClient).toEventuallyContainChildProcessConsoleOutput('foo'); * * @param lsClient LspClient instance to check * @param expectedMessage Message to check for * @param timeoutMs How long to keep checking before test is considered failed * @param intervalMs How frequently to check the log */ async toEventuallyContainChildProcessConsoleOutput( lsClient: LspClient, expectedMessage: string, timeoutMs = 1000, intervalMs = 25, ) { const expectedResult = `Expected language service child process console output to contain ""${expectedMessage}""`; const checkOutput = () => lsClient.childProcessConsole.some((line) => line.includes(expectedMessage)); const sleep = () => new Promise((resolve) => { setTimeout(resolve, intervalMs); }); let remainingRetries = Math.ceil(timeoutMs / intervalMs); while (remainingRetries > 0) { if (checkOutput()) { return { message: () => expectedResult, pass: true, }; } // eslint-disable-next-line no-await-in-loop await sleep(); remainingRetries--; } return { message: () => `""${expectedResult}"", but it was not found within ${timeoutMs}ms`, pass: false, }; }, }); References:" You are a code assistant,Definition of 'greet' in file src/tests/fixtures/intent/javascript_comments.js in project gitlab-lsp,"Definition: function greet(name) { return `Hello, ${name}!`; } // This file has more than 5 non-comment lines const a = 1; const b = 2; const c = 3; const d = 4; const e = 5; const f = 6; function hello(user) { // function to greet the user } 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 'getEntries' in file src/common/utils/get_entries.ts in project gitlab-lsp,"Definition: export const getEntries = (obj: T): Entries => Object.entries(obj) as Entries; References: - src/common/feature_state/feature_state_manager.ts:57" You are a code assistant,Definition of 'dispose' in file src/common/feature_state/project_duo_acces_check.ts in project gitlab-lsp,"Definition: dispose() { this.#subscriptions.forEach((s) => s.dispose()); } } References:" You are a code assistant,Definition of 'debug' in file src/common/log_types.ts in project gitlab-lsp,"Definition: debug(message: string, e?: Error): void; 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; } 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 'DidChangeDocumentInActiveEditor' in file src/common/notifications.ts in project gitlab-lsp,"Definition: export const DidChangeDocumentInActiveEditor = new NotificationType( '$/gitlab/didChangeDocumentInActiveEditor', ); References:" You are a code assistant,Definition of 'HandlesRequest' in file src/common/handler.ts in project gitlab-lsp,"Definition: export interface HandlesRequest { requestHandler: RequestHandler; } export interface HandlesNotification

{ notificationHandler: NotificationHandler

; } References:" You are a code assistant,Definition of 'sortCheckpoints' in file src/common/graphql/workflow/service.ts in project gitlab-lsp,"Definition: 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 { const workflowId = this.generateWorkflowID(id); let timeout: NodeJS.Timeout; const poll = async (): Promise => { 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 { 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 'Greet3' in file src/tests/fixtures/intent/empty_function/typescript.ts in project gitlab-lsp,"Definition: class Greet3 {} function* generateGreetings() {} function* greetGenerator() { yield 'Hello'; } References: - src/tests/fixtures/intent/empty_function/ruby.rb:34" You are a code assistant,Definition of 'DefaultDocumentTransformerService' in file src/common/document_transformer_service.ts in project gitlab-lsp,"Definition: export class DefaultDocumentTransformerService implements DocumentTransformerService { #transformers: IDocTransformer[] = []; #documents: LsTextDocuments; 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 'WEBVIEW_TITLE' in file packages/webview_duo_workflow/src/contract.ts in project gitlab-lsp,"Definition: export const WEBVIEW_TITLE = 'GitLab Duo Workflow'; export type DuoWorkflowMessages = CreatePluginMessageMap<{ webviewToPlugin: { notifications: { startWorkflow: { goal: string; image: string; }; stopWorkflow: []; openUrl: { url: string; }; }; }; pluginToWebview: { notifications: { workflowCheckpoints: LangGraphCheckpoint[]; workflowError: string; workflowStarted: string; workflowStatus: string; }; }; }>; References:" You are a code assistant,Definition of 'PLATFORM_ORIGIN' in file packages/webview_duo_chat/src/plugin/port/chat/constants.ts in project gitlab-lsp,"Definition: export const PLATFORM_ORIGIN = 'vs_code_extension'; References:" You are a code assistant,Definition of 'constructor' in file packages/webview_duo_chat/src/plugin/chat_platform.ts in project gitlab-lsp,"Definition: constructor(client: GitLabApiClient) { this.#client = client; } account: Account = { id: 'https://gitlab.com|16918910', instanceUrl: 'https://gitlab.com', } as Partial as Account; fetchFromApi(request: ApiRequest): Promise { return this.#client.fetchFromApi(request); } connectToCable(): Promise { return this.#client.connectToCable(); } getUserAgentHeader(): Record { return {}; } } 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:" You are a code assistant,Definition of 'isLanguageSupported' in file src/common/suggestion/supported_languages_service.ts in project gitlab-lsp,"Definition: isLanguageSupported(languageId: string): boolean; onLanguageChange(listener: () => void): Disposable; } export const SupportedLanguagesService = createInterfaceId( 'SupportedLanguagesService', ); @Injectable(SupportedLanguagesService, [ConfigService]) export class DefaultSupportedLanguagesService implements SupportedLanguagesService { #enabledLanguages: Set; #supportedLanguages: Set; #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 = 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 'sendNotification' in file packages/lib_message_bus/src/types/bus.ts in project gitlab-lsp,"Definition: sendNotification>(type: T): void; sendNotification(type: T, payload: TNotifications[T]): void; } /** * Interface for listening to notifications. * @interface * @template {NotificationMap} TNotifications */ export interface NotificationListener { onNotification>( type: T, handler: () => void, ): Disposable; onNotification( type: T, handler: (payload: TNotifications[T]) => void, ): Disposable; } /** * Maps request message types to their corresponding request/response payloads. * @typedef {Record} RequestMap */ export type RequestMap = Record< Method, { params: MessagePayload; result: MessagePayload; } >; type KeysWithOptionalParams = { [K in keyof R]: R[K]['params'] extends undefined ? never : K; }[keyof R]; /** * Extracts the response payload type from a request type. * @template {MessagePayload} T * @typedef {T extends [never] ? void : T[0]} ExtractRequestResponse */ export type ExtractRequestResult = // eslint-disable-next-line @typescript-eslint/no-invalid-void-type T['result'] extends undefined ? void : T; /** * Interface for publishing requests. * @interface * @template {RequestMap} TRequests */ export interface RequestPublisher { sendRequest>( type: T, ): Promise>; sendRequest( type: T, payload: TRequests[T]['params'], ): Promise>; } /** * Interface for listening to requests. * @interface * @template {RequestMap} TRequests */ export interface RequestListener { onRequest>( type: T, handler: () => Promise>, ): Disposable; onRequest( type: T, handler: (payload: TRequests[T]['params']) => Promise>, ): Disposable; } /** * Defines the structure for message definitions, including notifications and requests. */ export type MessageDefinitions< TNotifications extends NotificationMap = NotificationMap, TRequests extends RequestMap = RequestMap, > = { notifications: TNotifications; requests: TRequests; }; export type MessageMap< TInboundMessageDefinitions extends MessageDefinitions = MessageDefinitions, TOutboundMessageDefinitions extends MessageDefinitions = MessageDefinitions, > = { inbound: TInboundMessageDefinitions; outbound: TOutboundMessageDefinitions; }; export interface MessageBus extends NotificationPublisher, NotificationListener, RequestPublisher, RequestListener {} References:" You are a code assistant,Definition of 'sendInitialized' in file src/tests/int/lsp_client.ts in project gitlab-lsp,"Definition: public async sendInitialized(options?: InitializedParams | undefined): Promise { const defaults = {}; const params = { ...defaults, ...options }; const request = new NotificationType('initialized'); await this.#connection.sendNotification(request, params); } /** * Send the LSP 'workspace/didChangeConfiguration' notification */ public async sendDidChangeConfiguration( options?: ChangeConfigOptions | undefined, ): Promise { const defaults = createFakePartial({ settings: { token: this.#gitlabToken, baseUrl: this.#gitlabBaseUrl, codeCompletion: { enableSecretRedaction: true, }, telemetry: { enabled: false, }, }, }); const params = { ...defaults, ...options }; const request = new NotificationType( 'workspace/didChangeConfiguration', ); await this.#connection.sendNotification(request, params); } public async sendTextDocumentDidOpen( uri: string, languageId: string, version: number, text: string, ): Promise { const params = { textDocument: { uri, languageId, version, text, }, }; const request = new NotificationType('textDocument/didOpen'); await this.#connection.sendNotification(request, params); } public async sendTextDocumentDidClose(uri: string): Promise { const params = { textDocument: { uri, }, }; const request = new NotificationType('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 { const params = { textDocument: { uri, version, }, contentChanges: [{ text }], }; const request = new NotificationType('textDocument/didChange'); await this.#connection.sendNotification(request, params); } public async sendTextDocumentCompletion( uri: string, line: number, character: number, ): Promise { 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 { await this.#connection.sendNotification(DidChangeDocumentInActiveEditor, uri); } public async getWebviewMetadata(): Promise { const result = await this.#connection.sendRequest( '$/gitlab/webview-metadata', ); return result; } } References:" You are a code assistant,Definition of 'sendNotification' in file packages/lib_message_bus/src/types/bus.ts in project gitlab-lsp,"Definition: sendNotification(type: T, payload: TNotifications[T]): void; } /** * Interface for listening to notifications. * @interface * @template {NotificationMap} TNotifications */ export interface NotificationListener { onNotification>( type: T, handler: () => void, ): Disposable; onNotification( type: T, handler: (payload: TNotifications[T]) => void, ): Disposable; } /** * Maps request message types to their corresponding request/response payloads. * @typedef {Record} RequestMap */ export type RequestMap = Record< Method, { params: MessagePayload; result: MessagePayload; } >; type KeysWithOptionalParams = { [K in keyof R]: R[K]['params'] extends undefined ? never : K; }[keyof R]; /** * Extracts the response payload type from a request type. * @template {MessagePayload} T * @typedef {T extends [never] ? void : T[0]} ExtractRequestResponse */ export type ExtractRequestResult = // eslint-disable-next-line @typescript-eslint/no-invalid-void-type T['result'] extends undefined ? void : T; /** * Interface for publishing requests. * @interface * @template {RequestMap} TRequests */ export interface RequestPublisher { sendRequest>( type: T, ): Promise>; sendRequest( type: T, payload: TRequests[T]['params'], ): Promise>; } /** * Interface for listening to requests. * @interface * @template {RequestMap} TRequests */ export interface RequestListener { onRequest>( type: T, handler: () => Promise>, ): Disposable; onRequest( type: T, handler: (payload: TRequests[T]['params']) => Promise>, ): Disposable; } /** * Defines the structure for message definitions, including notifications and requests. */ export type MessageDefinitions< TNotifications extends NotificationMap = NotificationMap, TRequests extends RequestMap = RequestMap, > = { notifications: TNotifications; requests: TRequests; }; export type MessageMap< TInboundMessageDefinitions extends MessageDefinitions = MessageDefinitions, TOutboundMessageDefinitions extends MessageDefinitions = MessageDefinitions, > = { inbound: TInboundMessageDefinitions; outbound: TOutboundMessageDefinitions; }; export interface MessageBus extends NotificationPublisher, NotificationListener, RequestPublisher, RequestListener {} References:" You are a code assistant,Definition of 'isCursorAfterEmptyPythonFunction' in file src/common/tree_sitter/empty_function/empty_function_resolver.ts in project gitlab-lsp,"Definition: static isCursorAfterEmptyPythonFunction({ languageName, tree, cursorPosition, treeSitterLanguage, }: { languageName: TreeSitterLanguageName; tree: Tree; treeSitterLanguage: Language; cursorPosition: Point; }): boolean { if (languageName !== 'python') return false; const pythonQuery = treeSitterLanguage.query(`[ (function_definition) (class_definition) ] @function`); const captures = pythonQuery.captures(tree.rootNode); if (captures.length === 0) return false; // Check if any function or class body is empty and cursor is after it return captures.some((capture) => { const bodyNode = capture.node.childForFieldName('body'); return ( bodyNode?.childCount === 0 && EmptyFunctionResolver.#isCursorRightAfterNode(cursorPosition, capture.node.endPosition) ); }); } } let emptyFunctionResolver: EmptyFunctionResolver; export function getEmptyFunctionResolver(): EmptyFunctionResolver { if (!emptyFunctionResolver) { emptyFunctionResolver = new EmptyFunctionResolver(); } return emptyFunctionResolver; } References:" You are a code assistant,Definition of 'ChatRecordType' in file packages/webview_duo_chat/src/plugin/port/chat/gitlab_chat_record.ts in project gitlab-lsp,"Definition: type ChatRecordType = | 'general' | 'explainCode' | 'generateTests' | 'refactorCode' | 'newConversation'; type GitLabChatRecordAttributes = { chunkId?: number | null; type?: ChatRecordType; role: ChatRecordRole; content?: string; contentHtml?: string; requestId?: string; state?: ChatRecordState; errors?: string[]; timestamp?: string; extras?: { sources: object[]; }; }; export class GitLabChatRecord { chunkId?: number | null; role: ChatRecordRole; content?: string; contentHtml?: string; id: string; requestId?: string; state: ChatRecordState; timestamp: number; type: ChatRecordType; errors: string[]; extras?: { sources: object[]; }; context?: GitLabChatRecordContext; constructor({ chunkId, type, role, content, contentHtml, state, requestId, errors, timestamp, extras, }: GitLabChatRecordAttributes) { this.chunkId = chunkId; this.role = role; this.content = content; this.contentHtml = contentHtml; this.type = type ?? this.#detectType(); this.state = state ?? 'ready'; this.requestId = requestId; this.errors = errors ?? []; this.id = uuidv4(); this.timestamp = timestamp ? Date.parse(timestamp) : Date.now(); this.extras = extras; } static buildWithContext(attributes: GitLabChatRecordAttributes): GitLabChatRecord { const record = new GitLabChatRecord(attributes); record.context = buildCurrentContext(); return record; } update(attributes: Partial) { const convertedAttributes = attributes as Partial; if (attributes.timestamp) { convertedAttributes.timestamp = Date.parse(attributes.timestamp); } Object.assign(this, convertedAttributes); } #detectType(): ChatRecordType { if (this.content === SPECIAL_MESSAGES.RESET) { return 'newConversation'; } return 'general'; } } References: - packages/webview_duo_chat/src/plugin/port/chat/gitlab_chat_record.ts:46 - packages/webview_duo_chat/src/plugin/port/chat/gitlab_chat_record.ts:96 - packages/webview_duo_chat/src/plugin/port/chat/gitlab_chat_record.ts:16" You are a code assistant,Definition of 'buildContext' in file src/common/advanced_context/context_resolvers/advanced_context_resolver.ts in project gitlab-lsp,"Definition: abstract buildContext({ documentContext, }: { documentContext: IDocContext; }): AsyncGenerator; } References:" You are a code assistant,Definition of 'Repository' in file src/common/git/repository.ts in project gitlab-lsp,"Definition: export class Repository { workspaceFolder: WorkspaceFolder; uri: URI; configFileUri: URI; #files: Map; #ignoreManager: IgnoreManager; constructor({ configFileUri, workspaceFolder, uri, ignoreManager, }: { workspaceFolder: WorkspaceFolder; uri: RepositoryUri; configFileUri: URI; ignoreManager: IgnoreManager; }) { this.workspaceFolder = workspaceFolder; this.uri = uri; this.configFileUri = configFileUri; this.#files = new Map(); this.#ignoreManager = ignoreManager; } async addFilesAndLoadGitIgnore(files: URI[]): Promise { log.info(`Adding ${files.length} files to repository ${this.uri.toString()}`); await this.#ignoreManager.loadIgnoreFiles(files.map((uri) => uri.fsPath)); for (const file of files) { if (!this.#ignoreManager.isIgnored(file.fsPath)) { this.#files.set(file.toString(), { uri: file, isIgnored: false, repositoryUri: this.uri, workspaceFolder: this.workspaceFolder, }); } else { this.#files.set(file.toString(), { uri: file, isIgnored: true, repositoryUri: this.uri, workspaceFolder: this.workspaceFolder, }); } } } isFileIgnored(filePath: URI): boolean { return this.#ignoreManager.isIgnored(filePath.fsPath); } setFile(fileUri: URI): void { if (!this.isFileIgnored(fileUri)) { this.#files.set(fileUri.toString(), { uri: fileUri, isIgnored: false, repositoryUri: this.uri, workspaceFolder: this.workspaceFolder, }); } else { this.#files.set(fileUri.toString(), { uri: fileUri, isIgnored: true, repositoryUri: this.uri, workspaceFolder: this.workspaceFolder, }); } } getFile(fileUri: string): RepositoryFile | undefined { return this.#files.get(fileUri); } removeFile(fileUri: string): void { this.#files.delete(fileUri); } getFiles(): Map { return this.#files; } dispose(): void { this.#ignoreManager.dispose(); this.#files.clear(); } } References: - src/common/git/repository_service.ts:270" You are a code assistant,Definition of 'Subscription' in file packages/lib_webview/src/events/message_bus.ts in project gitlab-lsp,"Definition: interface Subscription { listener: Listener; filter?: FilterFunction; } export class MessageBus> implements Disposable { #subscriptions = new Map>>(); public subscribe( messageType: K, listener: Listener, filter?: FilterFunction, ): Disposable { const subscriptions = this.#subscriptions.get(messageType) ?? new Set>(); const subscription: Subscription = { listener: listener as Listener, filter: filter as FilterFunction | undefined, }; subscriptions.add(subscription); this.#subscriptions.set(messageType, subscriptions); return { dispose: () => { const targetSubscriptions = this.#subscriptions.get(messageType); if (targetSubscriptions) { targetSubscriptions.delete(subscription); if (targetSubscriptions.size === 0) { this.#subscriptions.delete(messageType); } } }, }; } public publish(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; if (!filter || filter(data)) { listener(data); } }); } } public hasListeners(messageType: K): boolean { return this.#subscriptions.has(messageType); } public listenerCount(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 'CompletionRequest' in file src/common/suggestion/suggestion_service.ts in project gitlab-lsp,"Definition: 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 => { 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 => { 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 => { 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 { 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 { 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 { 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 { 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 { 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/suggestion/suggestion_service.ts:324 - src/common/suggestion/suggestion_service.ts:193 - src/common/suggestion/suggestion_service.ts:389" You are a code assistant,Definition of 'EmitterState' in file src/common/tracking/snowplow/emitter.ts in project gitlab-lsp,"Definition: 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 { 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:20" You are a code assistant,Definition of 'shouldRejectCompletionWithSelectedCompletionTextMismatch' in file src/common/suggestion/suggestion_filter.ts in project gitlab-lsp,"Definition: export function shouldRejectCompletionWithSelectedCompletionTextMismatch( context: InlineCompletionContext, document?: TextDocument, ): boolean { if (!context.selectedCompletionInfo || !document) { return false; } const currentText = document.getText(sanitizeRange(context.selectedCompletionInfo.range)); const selectedText = context.selectedCompletionInfo.text; return !selectedText.startsWith(currentText); } References: - src/common/suggestion/suggestion_filter.test.ts:64 - src/common/suggestion/suggestion_filter.test.ts:47 - src/common/suggestion/suggestion_filter.test.ts:89 - src/common/suggestion/suggestion_service.ts:240" You are a code assistant,Definition of 'onDuoProjectCacheUpdate' in file src/common/services/duo_access/project_access_cache.ts in project gitlab-lsp,"Definition: onDuoProjectCacheUpdate(listener: () => void): Disposable; } export const DuoProjectAccessCache = createInterfaceId('DuoProjectAccessCache'); @Injectable(DuoProjectAccessCache, [DirectoryWalker, FileResolver, GitLabApiClient]) export class DefaultDuoProjectAccessCache { #duoProjects: Map; #eventEmitter = new EventEmitter(); constructor( private readonly directoryWalker: DirectoryWalker, private readonly fileResolver: FileResolver, private readonly api: GitLabApiClient, ) { this.#duoProjects = new Map(); } getProjectsForWorkspaceFolder(workspaceFolder: WorkspaceFolder): DuoProject[] { return this.#duoProjects.get(workspaceFolder.uri) ?? []; } async updateCache({ baseUrl, workspaceFolders, }: { baseUrl: string; workspaceFolders: WorkspaceFolder[]; }) { try { this.#duoProjects.clear(); const duoProjects = await Promise.all( workspaceFolders.map(async (workspaceFolder) => { return { workspaceFolder, projects: await this.#duoProjectsForWorkspaceFolder({ workspaceFolder, baseUrl, }), }; }), ); for (const { workspaceFolder, projects } of duoProjects) { this.#logProjectsInfo(projects, workspaceFolder); this.#duoProjects.set(workspaceFolder.uri, projects); } this.#triggerChange(); } catch (err) { log.error('DuoProjectAccessCache: failed to update project access cache', err); } } #logProjectsInfo(projects: DuoProject[], workspaceFolder: WorkspaceFolder) { if (!projects.length) { log.warn( `DuoProjectAccessCache: no projects found for workspace folder ${workspaceFolder.uri}`, ); return; } log.debug( `DuoProjectAccessCache: found ${projects.length} projects for workspace folder ${workspaceFolder.uri}: ${JSON.stringify(projects, null, 2)}`, ); } async #duoProjectsForWorkspaceFolder({ workspaceFolder, baseUrl, }: { workspaceFolder: WorkspaceFolder; baseUrl: string; }): Promise { const remotes = await this.#gitlabRemotesForWorkspaceFolder(workspaceFolder, baseUrl); const projects = await Promise.all( remotes.map(async (remote) => { const enabled = await this.#checkDuoFeaturesEnabled(remote.namespaceWithPath); return { projectPath: remote.projectPath, uri: remote.fileUri, enabled, host: remote.host, namespace: remote.namespace, namespaceWithPath: remote.namespaceWithPath, } satisfies DuoProject; }), ); return projects; } async #gitlabRemotesForWorkspaceFolder( workspaceFolder: WorkspaceFolder, baseUrl: string, ): Promise { const paths = await this.directoryWalker.findFilesForDirectory({ directoryUri: workspaceFolder.uri, filters: { fileEndsWith: ['/.git/config'], }, }); const remotes = await Promise.all( paths.map(async (fileUri) => this.#gitlabRemotesForFileUri(fileUri.toString(), baseUrl)), ); return remotes.flat(); } async #gitlabRemotesForFileUri( fileUri: string, baseUrl: string, ): Promise { const remoteUrls = await this.#remoteUrlsFromGitConfig(fileUri); return remoteUrls.reduce((acc, remoteUrl) => { const remote = parseGitLabRemote(remoteUrl, baseUrl); if (remote) { acc.push({ ...remote, fileUri }); } return acc; }, []); } async #remoteUrlsFromGitConfig(fileUri: string): Promise { try { const fileString = await this.fileResolver.readFile({ fileUri }); const config = ini.parse(fileString); return this.#getRemoteUrls(config); } catch (error) { log.error(`DuoProjectAccessCache: Failed to read git config file: ${fileUri}`, error); return []; } } #getRemoteUrls(config: GitConfig): string[] { return Object.keys(config).reduce((acc, section) => { if (section.startsWith('remote ')) { acc.push(config[section].url); } return acc; }, []); } async #checkDuoFeaturesEnabled(projectPath: string): Promise { try { const response = await this.api.fetchFromApi<{ project: GqlProjectWithDuoEnabledInfo }>({ type: 'graphql', query: duoFeaturesEnabledQuery, variables: { projectPath, }, } satisfies ApiRequest<{ project: GqlProjectWithDuoEnabledInfo }>); return Boolean(response?.project?.duoFeaturesEnabled); } catch (error) { log.error( `DuoProjectAccessCache: Failed to check if Duo features are enabled for project: ${projectPath}`, error, ); return true; } } onDuoProjectCacheUpdate( listener: (duoProjectsCache: Map) => void, ): Disposable { this.#eventEmitter.on(DUO_PROJECT_CACHE_UPDATE_EVENT, listener); return { dispose: () => this.#eventEmitter.removeListener(DUO_PROJECT_CACHE_UPDATE_EVENT, listener), }; } #triggerChange() { this.#eventEmitter.emit(DUO_PROJECT_CACHE_UPDATE_EVENT, this.#duoProjects); } } References:" You are a code assistant,Definition of 'get' in file src/common/document_transformer_service.ts in project gitlab-lsp,"Definition: 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: - src/common/utils/headers_to_snowplow_options.ts:21 - src/common/config_service.ts:134 - src/common/utils/headers_to_snowplow_options.ts:12 - src/common/utils/headers_to_snowplow_options.ts:20 - src/common/utils/headers_to_snowplow_options.ts:22" You are a code assistant,Definition of 'SuggestionClientPipeline' in file src/common/suggestion_client/suggestion_client_pipeline.ts in project gitlab-lsp,"Definition: export class SuggestionClientPipeline implements SuggestionClient { #middlewares: SuggestionClientMiddleware[]; #pipeline: SuggestionClientFn; constructor(middlewares: SuggestionClientMiddleware[]) { this.#middlewares = [...middlewares]; this.#pipeline = this.#buildPipeline(); } use(middleware: SuggestionClientMiddleware) { this.#middlewares.push(middleware); this.#pipeline = this.#buildPipeline(); } #buildPipeline() { return this.#middlewares.reduce( (acc, middleware) => { return (x: SuggestionContext) => { return middleware(x, acc); }; }, () => Promise.reject( new Error(`[SuggestionClientPipeline] Reached end of the pipeline without resolution!`), ), ); } getSuggestions(context: SuggestionContext): Promise { return this.#pipeline(context); } } References: - src/common/suggestion/suggestion_service.ts:165 - src/common/suggestion_client/suggestion_client_pipeline.test.ts:55 - src/common/suggestion_client/suggestion_client_pipeline.test.ts:101 - src/common/suggestion/suggestion_service.ts:115 - src/common/suggestion_client/suggestion_client_pipeline.test.ts:34" You are a code assistant,Definition of 'Credentials' in file packages/webview_duo_chat/src/plugin/port/platform/gitlab_account.ts in project gitlab-lsp,"Definition: export interface Credentials { instanceUrl: string; token: string; } interface AccountBase extends Credentials { username: string; id: string; } 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 'inlineCompletionOptionMapper' in file src/common/utils/suggestion_mappers.ts in project gitlab-lsp,"Definition: export const inlineCompletionOptionMapper = ( params: InlineCompletionParams, options: SuggestionOptionOrStream[], ): InlineCompletionList => ({ items: options.map((option) => { if (isStream(option)) { // the streaming item is empty and only indicates to the client that streaming started return { insertText: '', command: { title: 'Start streaming', command: START_STREAMING_COMMAND, arguments: [option.streamId, option.uniqueTrackingId], }, }; } const completionInfo = params.context.selectedCompletionInfo; let rangeDiff = 0; if (completionInfo) { const range = sanitizeRange(completionInfo.range); rangeDiff = range.end.character - range.start.character; } return { insertText: completionInfo ? `${completionInfo.text.substring(rangeDiff)}${option.text}` : option.text, range: Range.create(params.position, params.position), command: { title: 'Accept suggestion', command: SUGGESTION_ACCEPTED_COMMAND, arguments: [option.uniqueTrackingId, getOptionTrackingIndex(option)], }, }; }), }); References: - src/common/utils/suggestion_mapper.test.ts:65 - src/common/utils/suggestion_mapper.test.ts:100 - src/common/suggestion/suggestion_service.ts:283" You are a code assistant,Definition of 'commentQueries' in file src/common/tree_sitter/comments/comment_queries.ts in project gitlab-lsp,"Definition: export const commentQueries = { bash: bashCommentQuery, c: cCommentQuery, cpp: cppCommentQuery, c_sharp: csharpCommentQuery, css: cssCommentQuery, go: goCommentQuery, // hcl: hclCommentQuery, html: htmlCommentQuery, java: javaCommentQuery, javascript: javascriptCommentQuery, json: jsonCommentQuery, kotlin: kotlinCommentQuery, powershell: powershellCommentQuery, python: pythonCommentQuery, rust: rustCommentQuery, ruby: rubyCommentQuery, scala: scalaCommentQuery, // sql: sqlCommentQuery, typescript: typescriptCommentQuery, tsx: typescriptCommentQuery, vue: vueCommentQuery, yaml: yamlCommentQuery, } satisfies Record; References:" You are a code assistant,Definition of 'getMessageBus' in file packages/lib_webview_client/src/bus/provider/socket_io_message_bus_provider.ts in project gitlab-lsp,"Definition: getMessageBus(webviewId: string): MessageBus | null { if (!webviewId) { return null; } const socketUri = getSocketUri(webviewId); const socket = io(socketUri); const bus = new SocketIoMessageBus(socket); return bus; } } References:" You are a code assistant,Definition of 'handleWorkspaceFilesUpdate' in file src/common/git/repository_service.ts in project gitlab-lsp,"Definition: async handleWorkspaceFilesUpdate({ workspaceFolder, files }: WorkspaceFilesUpdate) { // clear existing repositories from workspace this.#emptyRepositoriesForWorkspace(workspaceFolder.uri); const repositories = this.#detectRepositories(files, workspaceFolder); const repositoryMap = new Map(repositories.map((repo) => [repo.uri.toString(), repo])); // Build and cache the repository trie for this workspace const trie = this.#buildRepositoryTrie(repositories); this.#updateRepositoriesForFolder(workspaceFolder, repositoryMap, trie); await Promise.all( repositories.map((repo) => repo.addFilesAndLoadGitIgnore( files.filter((file) => { const matchingRepo = this.findMatchingRepositoryUri(file, workspaceFolder); return matchingRepo && matchingRepo.toString() === repo.uri.toString(); }), ), ), ); } async handleWorkspaceFileUpdate({ fileUri, workspaceFolder, event }: WorkspaceFileUpdate) { const repoUri = this.findMatchingRepositoryUri(fileUri, workspaceFolder); if (!repoUri) { log.debug(`No matching repository found for file ${fileUri.toString()}`); return; } const repositoryMap = this.#getRepositoriesForWorkspace(workspaceFolder.uri); const repository = repositoryMap.get(repoUri.toString()); if (!repository) { log.debug(`Repository not found for URI ${repoUri.toString()}`); return; } if (repository.isFileIgnored(fileUri)) { log.debug(`File ${fileUri.toString()} is ignored`); return; } switch (event) { case 'add': repository.setFile(fileUri); log.debug(`File ${fileUri.toString()} added to repository ${repoUri.toString()}`); break; case 'change': repository.setFile(fileUri); log.debug(`File ${fileUri.toString()} updated in repository ${repoUri.toString()}`); break; case 'unlink': repository.removeFile(fileUri.toString()); log.debug(`File ${fileUri.toString()} removed from repository ${repoUri.toString()}`); break; default: log.warn(`Unknown file event ${event} for file ${fileUri.toString()}`); } } #getRepositoriesForWorkspace(workspaceFolderUri: WorkspaceFolderUri): RepositoryMap { return this.#workspaces.get(workspaceFolderUri) || new Map(); } #emptyRepositoriesForWorkspace(workspaceFolderUri: WorkspaceFolderUri): void { log.debug(`Emptying repositories for workspace ${workspaceFolderUri}`); const repos = this.#workspaces.get(workspaceFolderUri); if (!repos || repos.size === 0) return; // clear up ignore manager trie from memory repos.forEach((repo) => { repo.dispose(); log.debug(`Repository ${repo.uri} has been disposed`); }); repos.clear(); const trie = this.#workspaceRepositoryTries.get(workspaceFolderUri); if (trie) { trie.dispose(); this.#workspaceRepositoryTries.delete(workspaceFolderUri); } this.#workspaces.delete(workspaceFolderUri); log.debug(`Repositories for workspace ${workspaceFolderUri} have been emptied`); } #detectRepositories(files: URI[], workspaceFolder: WorkspaceFolder): Repository[] { const gitConfigFiles = files.filter((file) => file.toString().endsWith('.git/config')); return gitConfigFiles.map((file) => { const projectUri = fsPathToUri(file.path.replace('.git/config', '')); const ignoreManager = new IgnoreManager(projectUri.fsPath); log.info(`Detected repository at ${projectUri.path}`); return new Repository({ ignoreManager, uri: projectUri, configFileUri: file, workspaceFolder, }); }); } getFilesForWorkspace( workspaceFolderUri: WorkspaceFolderUri, options: { excludeGitFolder?: boolean; excludeIgnored?: boolean } = {}, ): RepositoryFile[] { const repositories = this.#getRepositoriesForWorkspace(workspaceFolderUri); const allFiles: RepositoryFile[] = []; repositories.forEach((repository) => { repository.getFiles().forEach((file) => { // apply the filters if (options.excludeGitFolder && this.#isInGitFolder(file.uri, repository.uri)) { return; } if (options.excludeIgnored && file.isIgnored) { return; } allFiles.push(file); }); }); return allFiles; } // Helper method to check if a file is in the .git folder #isInGitFolder(fileUri: URI, repositoryUri: URI): boolean { const relativePath = fileUri.path.slice(repositoryUri.path.length); return relativePath.split('/').some((part) => part === '.git'); } } References:" You are a code assistant,Definition of 'onClose' in file src/common/circuit_breaker/exponential_backoff_circuit_breaker.ts in project gitlab-lsp,"Definition: onClose(listener: () => void): Disposable { this.#eventEmitter.on('close', listener); return { dispose: () => this.#eventEmitter.removeListener('close', listener) }; } #getBackoffTime() { return Math.min( this.#initialBackoffMs * this.#backoffMultiplier ** (this.#errorCount - 1), this.#maxBackoffMs, ); } } References:" You are a code assistant,Definition of 'getGitLabEnvironment' in file packages/webview_duo_chat/src/plugin/port/chat/get_platform_manager_for_chat.ts in project gitlab-lsp,"Definition: async getGitLabEnvironment(): Promise { const platform = await this.getGitLabPlatform(); const instanceUrl = platform?.account.instanceUrl; switch (instanceUrl) { case GITLAB_COM_URL: return GitLabEnvironment.GITLAB_COM; case GITLAB_DEVELOPMENT_URL: return GitLabEnvironment.GITLAB_DEVELOPMENT; case GITLAB_STAGING_URL: return GitLabEnvironment.GITLAB_STAGING; case GITLAB_ORG_URL: return GitLabEnvironment.GITLAB_ORG; default: return GitLabEnvironment.GITLAB_SELF_MANAGED; } } } References:" You are a code assistant,Definition of 'getWebviewMetadata' in file src/tests/int/lsp_client.ts in project gitlab-lsp,"Definition: public async getWebviewMetadata(): Promise { const result = await this.#connection.sendRequest( '$/gitlab/webview-metadata', ); return result; } } References:" You are a code assistant,Definition of 'constructor' in file src/common/suggestion/streaming_handler.ts in project gitlab-lsp,"Definition: constructor(params: StartStreamParams) { this.#params = params; } async startStream() { return startStreaming(this.#params); } } const startStreaming = async ({ additionalContexts, api, circuitBreaker, connection, documentContext, parser, postProcessorPipeline, streamId, tracker, uniqueTrackingId, userInstruction, generationType, }: StartStreamParams) => { const language = parser.getLanguageNameForFile(documentContext.fileRelativePath); tracker.setCodeSuggestionsContext(uniqueTrackingId, { documentContext, additionalContexts, source: SuggestionSource.network, language, isStreaming: true, }); let streamShown = false; let suggestionProvided = false; let streamCancelledOrErrored = false; const cancellationTokenSource = new CancellationTokenSource(); const disposeStopStreaming = connection.onNotification(CancelStreaming, (stream) => { if (stream.id === streamId) { streamCancelledOrErrored = true; cancellationTokenSource.cancel(); if (streamShown) { tracker.updateSuggestionState(uniqueTrackingId, TRACKING_EVENTS.REJECTED); } else { tracker.updateSuggestionState(uniqueTrackingId, TRACKING_EVENTS.CANCELLED); } } }); const cancellationToken = cancellationTokenSource.token; const endStream = async () => { await connection.sendNotification(StreamingCompletionResponse, { id: streamId, done: true, }); if (!streamCancelledOrErrored) { tracker.updateSuggestionState(uniqueTrackingId, TRACKING_EVENTS.STREAM_COMPLETED); if (!suggestionProvided) { tracker.updateSuggestionState(uniqueTrackingId, TRACKING_EVENTS.NOT_PROVIDED); } } }; circuitBreaker.success(); const request: CodeSuggestionRequest = { prompt_version: 1, project_path: '', project_id: -1, current_file: { content_above_cursor: documentContext.prefix, content_below_cursor: documentContext.suffix, file_name: documentContext.fileRelativePath, }, intent: 'generation', stream: true, ...(additionalContexts?.length && { context: additionalContexts, }), ...(userInstruction && { user_instruction: userInstruction, }), generation_type: generationType, }; const trackStreamStarted = once(() => { tracker.updateSuggestionState(uniqueTrackingId, TRACKING_EVENTS.STREAM_STARTED); }); const trackStreamShown = once(() => { tracker.updateSuggestionState(uniqueTrackingId, TRACKING_EVENTS.SHOWN); streamShown = true; }); try { for await (const response of api.getStreamingCodeSuggestions(request)) { if (cancellationToken.isCancellationRequested) { break; } if (circuitBreaker.isOpen()) { break; } trackStreamStarted(); const processedCompletion = await postProcessorPipeline.run({ documentContext, input: { id: streamId, completion: response, done: false }, type: 'stream', }); await connection.sendNotification(StreamingCompletionResponse, processedCompletion); if (response.replace(/\s/g, '').length) { trackStreamShown(); suggestionProvided = true; } } } catch (err) { circuitBreaker.error(); if (isFetchError(err)) { tracker.updateCodeSuggestionsContext(uniqueTrackingId, { status: err.status }); } tracker.updateSuggestionState(uniqueTrackingId, TRACKING_EVENTS.ERRORED); streamCancelledOrErrored = true; log.error('Error streaming code suggestions.', err); } finally { await endStream(); disposeStopStreaming.dispose(); cancellationTokenSource.dispose(); } }; References:" You are a code assistant,Definition of 'publish' in file packages/lib_webview_transport_socket_io/src/socket_io_webview_transport.ts in project gitlab-lsp,"Definition: async publish( type: K, message: MessagesToClient[K], ): Promise { const connectionId = buildConnectionId({ webviewId: message.webviewId, webviewInstanceId: message.webviewInstanceId, }); const connection = this.#connections.get(connectionId); if (!connection) { this.#logger?.error(`No active socket found for ID ${connectionId}`); return; } switch (type) { case 'webview_instance_notification': connection.emit(SOCKET_NOTIFICATION_CHANNEL, { type: message.type, payload: message.payload, }); return; case 'webview_instance_request': connection.emit(SOCKET_REQUEST_CHANNEL, { type: message.type, payload: message.payload, requestId: (message as MessagesToClient['webview_instance_request']).requestId, }); return; case 'webview_instance_response': connection.emit(SOCKET_RESPONSE_CHANNEL, { type: message.type, payload: message.payload, requestId: (message as MessagesToClient['webview_instance_response']).requestId, }); return; default: this.#logger?.error(`Unknown message type ${type}`); } } on( type: K, callback: TransportMessageHandler, ): 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 'isSmallFile' in file src/common/tree_sitter/small_files.ts in project gitlab-lsp,"Definition: export function isSmallFile(textContent: string, totalCommentLines: number): boolean { const minLinesOfCode = 5; // threshold to determine whether a source code file is considered 'small' const totalNonEmptyLines = getTotalNonEmptyLines(textContent); return totalNonEmptyLines - totalCommentLines < minLinesOfCode; } References: - src/common/tree_sitter/intent_resolver.ts:77 - src/common/tree_sitter/small_files.test.ts:11" You are a code assistant,Definition of 'WEB_IDE_AUTH_PROVIDER_ID' in file packages/webview_duo_chat/src/plugin/port/platform/web_ide.ts in project gitlab-lsp,"Definition: export const WEB_IDE_AUTH_PROVIDER_ID = 'gitlab-web-ide'; export const WEB_IDE_AUTH_SCOPE = 'api'; // region: Mediator commands ------------------------------------------- export const COMMAND_FETCH_FROM_API = `gitlab-web-ide.mediator.fetch-from-api`; export const COMMAND_FETCH_BUFFER_FROM_API = `gitlab-web-ide.mediator.fetch-buffer-from-api`; export const COMMAND_MEDIATOR_TOKEN = `gitlab-web-ide.mediator.mediator-token`; 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; } /** * 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; headers?: Record; } export interface GetRequest<_TReturnType> extends GetRequestBase<_TReturnType> { type: 'rest'; } export interface GetBufferRequest extends GetRequestBase { type: 'rest-buffer'; } export interface GraphQLRequest<_TReturnType> { type: 'graphql'; query: string; /** Options passed to the GraphQL query */ variables: Record; } 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; /* 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 'DefaultAiContextAggregator' in file src/common/ai_context_management_2/ai_context_aggregator.ts in project gitlab-lsp,"Definition: export class DefaultAiContextAggregator { #AiFileContextProvider: AiFileContextProvider; #AiContextPolicyManager: AiContextPolicyManager; constructor( aiFileContextProvider: AiFileContextProvider, aiContextPolicyManager: AiContextPolicyManager, ) { this.#AiFileContextProvider = aiFileContextProvider; this.#AiContextPolicyManager = aiContextPolicyManager; } async getContextForQuery(query: AiContextQuery): Promise { 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 { 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 'greet' in file src/tests/fixtures/intent/empty_function/ruby.rb in project gitlab-lsp,"Definition: 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/ruby.rb:20 - 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" You are a code assistant,Definition of 'isSocketNotificationMessage' in file packages/lib_webview_transport_socket_io/src/utils/message_utils.ts in project gitlab-lsp,"Definition: 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: - packages/lib_webview_transport_socket_io/src/socket_io_webview_transport.ts:68" You are a code assistant,Definition of 'TestProcessor' in file src/common/suggestion_client/post_processors/post_processor_pipeline.test.ts in project gitlab-lsp,"Definition: class TestProcessor extends PostProcessor { async processStream( _context: IDocContext, input: StreamingCompletionResponse, ): Promise { return input; } async processCompletion( _context: IDocContext, input: SuggestionOption[], ): Promise { 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: - src/common/suggestion_client/post_processors/post_processor_pipeline.test.ts:191" You are a code assistant,Definition of 'LsFetch' in file src/common/fetch.ts in project gitlab-lsp,"Definition: export interface LsFetch { initialize(): Promise; destroy(): Promise; fetch(input: RequestInfo | URL, init?: RequestInit): Promise; fetchBase(input: RequestInfo | URL, init?: RequestInit): Promise; delete(input: RequestInfo | URL, init?: RequestInit): Promise; get(input: RequestInfo | URL, init?: RequestInit): Promise; post(input: RequestInfo | URL, init?: RequestInit): Promise; put(input: RequestInfo | URL, init?: RequestInit): Promise; updateAgentOptions(options: FetchAgentOptions): void; streamFetch(url: string, body: string, headers: FetchHeaders): AsyncGenerator; } export const LsFetch = createInterfaceId('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 {} async destroy(): Promise {} async fetch(input: RequestInfo | URL, init?: RequestInit): Promise { 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 { // Stub. Should delegate to the node or browser fetch implementations throw new Error('Not implemented'); yield ''; } async delete(input: RequestInfo | URL, init?: RequestInit): Promise { return this.fetch(input, this.updateRequestInit('DELETE', init)); } async get(input: RequestInfo | URL, init?: RequestInit): Promise { return this.fetch(input, this.updateRequestInit('GET', init)); } async post(input: RequestInfo | URL, init?: RequestInit): Promise { return this.fetch(input, this.updateRequestInit('POST', init)); } async put(input: RequestInfo | URL, init?: RequestInit): Promise { return this.fetch(input, this.updateRequestInit('PUT', init)); } async fetchBase(input: RequestInfo | URL, init?: RequestInit): Promise { // 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/node/duo_workflow/desktop_workflow_runner.test.ts:22 - src/common/tracking/snowplow/snowplow.ts:48 - src/common/tracking/snowplow_tracker.test.ts:70 - src/common/tracking/snowplow/snowplow.ts:69 - src/common/tracking/snowplow_tracker.ts:150 - src/common/api.test.ts:34 - src/common/api.ts:127 - src/node/duo_workflow/desktop_workflow_runner.ts:53 - src/common/tracking/snowplow/snowplow.ts:57 - src/common/api.ts:135 - src/node/duo_workflow/desktop_workflow_runner.ts:47 - src/common/tracking/snowplow_tracker.ts:159" You are a code assistant,Definition of 'DefaultConfigService' in file src/common/config_service.ts in project gitlab-lsp,"Definition: 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 = (key?: string) => { return key ? get(this.#config, key) : this.#config; }; set: TypedSetter = (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) { mergeWith(this.#config, newConfig, (target, src) => (isArray(target) ? src : undefined)); this.#triggerChange(); } } References: - src/common/tracking/instance_tracker.test.ts:36 - src/common/tracking/snowplow_tracker.test.ts:75 - src/common/secret_redaction/redactor.test.ts:24 - src/common/core/handlers/initialize_handler.test.ts:20 - src/common/config_service.test.ts:9 - src/common/advanced_context/advanced_context_service.test.ts:41 - src/common/connection.test.ts:49 - src/common/message_handler.test.ts:98 - src/common/suggestion/supported_languages_service.test.ts:12 - src/common/suggestion/suggestion_service.test.ts:462 - src/common/feature_state/project_duo_acces_check.test.ts:30 - src/common/core/handlers/did_change_workspace_folders_handler.test.ts:17 - src/common/suggestion_client/direct_connection_client.test.ts:38 - src/browser/tree_sitter/index.test.ts:17 - src/common/api.test.ts:482 - src/common/feature_state/supported_language_check.test.ts:31 - src/common/suggestion/suggestion_service.test.ts:191 - src/common/api.test.ts:82 - src/common/security_diagnostics_publisher.test.ts:47 - src/node/duo_workflow/desktop_workflow_runner.test.ts:27 - src/common/suggestion/suggestions_cache.test.ts:46 - src/common/suggestion/suggestions_cache.test.ts:43 - src/common/message_handler.test.ts:212 - src/common/config_service.test.ts:6" You are a code assistant,Definition of 'IWorkflowSettings' in file src/common/config_service.ts in project gitlab-lsp,"Definition: export interface IWorkflowSettings { dockerSocket?: string; } export interface IDuoConfig { enabledWithoutGitlabProject?: boolean; } export interface IClientConfig { /** GitLab API URL used for getting code suggestions */ baseUrl?: string; /** Full project path. */ projectPath?: string; /** PAT or OAuth token used to authenticate to GitLab API */ token?: string; /** The base URL for language server assets in the client-side extension */ baseAssetsUrl?: string; clientInfo?: IClientInfo; // FIXME: this key should be codeSuggestions (we have code completion and code generation) codeCompletion?: ICodeCompletionConfig; openTabsContext?: boolean; telemetry?: ITelemetryOptions; /** Config used for caching code suggestions */ suggestionsCache?: ISuggestionsCacheOptions; workspaceFolders?: WorkspaceFolder[] | null; /** Collection of Feature Flag values which are sent from the client */ featureFlags?: Record; logLevel?: LogLevel; ignoreCertificateErrors?: boolean; httpAgentOptions?: IHttpAgentOptions; snowplowTrackerOptions?: ISnowplowTrackerOptions; // TODO: move to `duo` duoWorkflowSettings?: IWorkflowSettings; securityScannerOptions?: ISecurityScannerOptions; duo?: IDuoConfig; } export interface IConfig { // TODO: we can possibly remove this extra level of config and move all IClientConfig properties to IConfig client: IClientConfig; } /** * ConfigService manages user configuration (e.g. baseUrl) and application state (e.g. codeCompletion.enabled) * TODO: Maybe in the future we would like to separate these two */ export interface ConfigService { get: TypedGetter; /** * set sets the property of the config * the new value completely overrides the old one */ set: TypedSetter; onConfigChange(listener: (config: IConfig) => void): Disposable; /** * merge adds `newConfig` properties into existing config, if the * property is present in both old and new config, `newConfig` * properties take precedence unless not defined * * This method performs deep merge * * **Arrays are not merged; they are replaced with the new value.** * */ merge(newConfig: Partial): void; } export const ConfigService = createInterfaceId('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 = (key?: string) => { return key ? get(this.#config, key) : this.#config; }; set: TypedSetter = (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) { mergeWith(this.#config, newConfig, (target, src) => (isArray(target) ? src : undefined)); this.#triggerChange(); } } References: - src/common/config_service.ts:73" You are a code assistant,Definition of 'NegativeIndexError' in file packages/lib-pkg-2/src/fast_fibonacci_solver.ts in project gitlab-lsp,"Definition: export const NegativeIndexError = new Error('Index must be non-negative'); export class FastFibonacciSolver implements FibonacciSolver { #memo: Map = new Map(); #lastComputedIndex: number = 1; constructor() { this.#memo.set(0, 0); this.#memo.set(1, 1); } 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 'transform' in file src/common/secret_redaction/index.ts in project gitlab-lsp,"Definition: 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:" You are a code assistant,Definition of 'LspClient' in file src/tests/int/lsp_client.ts in project gitlab-lsp,"Definition: 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 { const params = { ...DEFAULT_INITIALIZE_PARAMS, ...initializeParams }; const request = new RequestType( 'initialize', ); const response = await this.#connection.sendRequest(request, params); return response; } /** * Send the LSP 'initialized' notification */ public async sendInitialized(options?: InitializedParams | undefined): Promise { const defaults = {}; const params = { ...defaults, ...options }; const request = new NotificationType('initialized'); await this.#connection.sendNotification(request, params); } /** * Send the LSP 'workspace/didChangeConfiguration' notification */ public async sendDidChangeConfiguration( options?: ChangeConfigOptions | undefined, ): Promise { const defaults = createFakePartial({ settings: { token: this.#gitlabToken, baseUrl: this.#gitlabBaseUrl, codeCompletion: { enableSecretRedaction: true, }, telemetry: { enabled: false, }, }, }); const params = { ...defaults, ...options }; const request = new NotificationType( 'workspace/didChangeConfiguration', ); await this.#connection.sendNotification(request, params); } public async sendTextDocumentDidOpen( uri: string, languageId: string, version: number, text: string, ): Promise { const params = { textDocument: { uri, languageId, version, text, }, }; const request = new NotificationType('textDocument/didOpen'); await this.#connection.sendNotification(request, params); } public async sendTextDocumentDidClose(uri: string): Promise { const params = { textDocument: { uri, }, }; const request = new NotificationType('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 { const params = { textDocument: { uri, version, }, contentChanges: [{ text }], }; const request = new NotificationType('textDocument/didChange'); await this.#connection.sendNotification(request, params); } public async sendTextDocumentCompletion( uri: string, line: number, character: number, ): Promise { 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 { await this.#connection.sendNotification(DidChangeDocumentInActiveEditor, uri); } public async getWebviewMetadata(): Promise { const result = await this.#connection.sendRequest( '$/gitlab/webview-metadata', ); return result; } } References: - src/tests/int/snowplow_tracker.test.ts:7 - src/tests/int/advanced_context.test.ts:6 - src/tests/int/suggestion.test.ts:9 - src/tests/int/lsp_client.test.ts:5 - src/tests/int/webview.test.ts:6 - src/tests/int/test_utils.ts:46 - src/tests/int/advanced_context.test.ts:9 - src/tests/int/tree_sitter_loaded.test.ts:7 - src/tests/int/snowplow_tracker.test.ts:38" You are a code assistant,Definition of 'greet' in file src/tests/fixtures/intent/empty_function/python.py in project gitlab-lsp,"Definition: 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: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 'WebviewInstanceDestroyedEventData' in file packages/lib_webview_transport/src/types.ts in project gitlab-lsp,"Definition: export type WebviewInstanceDestroyedEventData = WebviewAddress; export type WebviewInstanceNotificationEventData = WebviewAddress & WebviewEventInfo; export type WebviewInstanceRequestEventData = WebviewAddress & WebviewEventInfo & WebviewRequestInfo; export type SuccessfulResponse = { success: true; }; export type FailedResponse = { success: false; reason: string; }; export type WebviewInstanceResponseEventData = WebviewAddress & WebviewRequestInfo & WebviewEventInfo & (SuccessfulResponse | FailedResponse); export type MessagesToServer = { webview_instance_created: WebviewInstanceCreatedEventData; webview_instance_destroyed: WebviewInstanceDestroyedEventData; webview_instance_notification_received: WebviewInstanceNotificationEventData; webview_instance_request_received: WebviewInstanceRequestEventData; webview_instance_response_received: WebviewInstanceResponseEventData; }; export type MessagesToClient = { webview_instance_notification: WebviewInstanceNotificationEventData; webview_instance_request: WebviewInstanceRequestEventData; webview_instance_response: WebviewInstanceResponseEventData; }; export interface TransportMessageHandler { (payload: T): void; } export interface TransportListener { on( type: K, callback: TransportMessageHandler, ): Disposable; } export interface TransportPublisher { publish(type: K, payload: MessagesToClient[K]): Promise; } export interface Transport extends TransportListener, TransportPublisher {} References: - packages/lib_webview_transport/src/types.ts:41" You are a code assistant,Definition of 'IStartWorkflowParams' in file src/common/message_handler.ts in project gitlab-lsp,"Definition: 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 => { 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:187" You are a code assistant,Definition of 'DefaultVirtualFileSystemService' in file src/common/services/fs/virtual_file_service.ts in project gitlab-lsp,"Definition: 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 { 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( 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/git/repository_service.ts:30 - src/common/workspace/workspace_service.ts:20 - src/common/git/repository_service.ts:28 - src/common/workspace/workspace_service.ts:26" You are a code assistant,Definition of 'IsManagedEventFilter' in file packages/lib_webview/src/setup/transport/utils/event_filters.ts in project gitlab-lsp,"Definition: export type IsManagedEventFilter = ( event: TEvent, ) => boolean; export const createIsManagedFunc = (managedInstances: ManagedInstances): IsManagedEventFilter => (event: TEvent) => managedInstances.has(event.webviewInstanceId); References: - packages/lib_webview/src/setup/transport/utils/event_filters.ts:9 - packages/lib_webview/src/setup/transport/utils/setup_event_subscriptions.ts:9" You are a code assistant,Definition of 'delete' in file src/common/fetch.ts in project gitlab-lsp,"Definition: async delete(input: RequestInfo | URL, init?: RequestInit): Promise { return this.fetch(input, this.updateRequestInit('DELETE', init)); } async get(input: RequestInfo | URL, init?: RequestInit): Promise { return this.fetch(input, this.updateRequestInit('GET', init)); } async post(input: RequestInfo | URL, init?: RequestInit): Promise { return this.fetch(input, this.updateRequestInit('POST', init)); } async put(input: RequestInfo | URL, init?: RequestInit): Promise { return this.fetch(input, this.updateRequestInit('PUT', init)); } async fetchBase(input: RequestInfo | URL, init?: RequestInit): Promise { // 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 'TransportPublisher' in file packages/lib_webview_transport/src/types.ts in project gitlab-lsp,"Definition: export interface TransportPublisher { publish(type: K, payload: MessagesToClient[K]): Promise; } export interface Transport extends TransportListener, TransportPublisher {} References:" You are a code assistant,Definition of 'RepositoryMap' in file src/common/git/repository_service.ts in project gitlab-lsp,"Definition: type RepositoryMap = Map; export type RepositoryService = typeof DefaultRepositoryService.prototype; export const RepositoryService = createInterfaceId('RepositoryService'); @Injectable(RepositoryService, [VirtualFileSystemService]) export class DefaultRepositoryService { #virtualFileSystemService: DefaultVirtualFileSystemService; constructor(virtualFileSystemService: DefaultVirtualFileSystemService) { this.#virtualFileSystemService = virtualFileSystemService; this.#setupEventListeners(); } #setupEventListeners() { return this.#virtualFileSystemService.onFileSystemEvent(async (eventType, data) => { switch (eventType) { case VirtualFileSystemEvents.WorkspaceFilesUpdate: await this.#handleWorkspaceFilesUpdate(data as WorkspaceFilesUpdate); break; case VirtualFileSystemEvents.WorkspaceFileUpdate: await this.#handleWorkspaceFileUpdate(data as WorkspaceFileUpdate); break; default: break; } }); } async #handleWorkspaceFilesUpdate(update: WorkspaceFilesUpdate) { log.info(`Workspace files update: ${update.files.length}`); const perf1 = performance.now(); await this.handleWorkspaceFilesUpdate({ ...update, }); const perf2 = performance.now(); log.info(`Workspace files initialization took ${perf2 - perf1}ms`); const perf3 = performance.now(); const files = this.getFilesForWorkspace(update.workspaceFolder.uri, { excludeGitFolder: true, excludeIgnored: true, }); const perf4 = performance.now(); log.info(`Fetched workspace files in ${perf4 - perf3}ms`); log.info(`Workspace git files: ${files.length}`); // const treeFile = await readFile( // '/Users/angelo.rivera/gitlab/gitlab-development-kit/gitlab/tree.txt', // 'utf-8', // ); // const treeFiles = treeFile.split('\n').filter(Boolean); // // get the set difference between the files in the tree and the non-ignored files // // we need the difference between the two sets to know which files are not in the tree // const diff = new Set( // files.map((file) => // relative('/Users/angelo.rivera/gitlab/gitlab-development-kit/gitlab', file.uri.fsPath), // ), // ); // for (const file of treeFiles) { // diff.delete(file); // } // log.info(`Files not in the tree.txt: ${JSON.stringify(Array.from(diff))}`); } async #handleWorkspaceFileUpdate(update: WorkspaceFileUpdate) { log.info(`Workspace file update: ${JSON.stringify(update)}`); await this.handleWorkspaceFileUpdate({ ...update, }); const perf1 = performance.now(); const files = this.getFilesForWorkspace(update.workspaceFolder.uri, { excludeGitFolder: true, excludeIgnored: true, }); const perf2 = performance.now(); log.info(`Fetched workspace files in ${perf2 - perf1}ms`); log.info(`Workspace git files: ${files.length}`); } /** * unique map of workspace folders that point to a map of repositories * We store separate repository maps for each workspace because * the events from the VFS service are at the workspace level. * If we combined them, we may get race conditions */ #workspaces: Map = new Map(); #workspaceRepositoryTries: Map = new Map(); #buildRepositoryTrie(repositories: Repository[]): RepositoryTrie { const root = new RepositoryTrie(); for (const repo of repositories) { let node = root; const parts = repo.uri.path.split('/').filter(Boolean); for (const part of parts) { if (!node.children.has(part)) { node.children.set(part, new RepositoryTrie()); } node = node.children.get(part) as RepositoryTrie; } node.repository = repo.uri; } return root; } findMatchingRepositoryUri(fileUri: URI, workspaceFolderUri: WorkspaceFolder): URI | null { const trie = this.#workspaceRepositoryTries.get(workspaceFolderUri.uri); if (!trie) return null; let node = trie; let lastMatchingRepo: URI | null = null; const parts = fileUri.path.split('/').filter(Boolean); for (const part of parts) { if (node.repository) { lastMatchingRepo = node.repository; } if (!node.children.has(part)) break; node = node.children.get(part) as RepositoryTrie; } return node.repository || lastMatchingRepo; } getRepositoryFileForUri( fileUri: URI, repositoryUri: URI, workspaceFolder: WorkspaceFolder, ): RepositoryFile | null { const repository = this.#getRepositoriesForWorkspace(workspaceFolder.uri).get( repositoryUri.toString(), ); if (!repository) { return null; } return repository.getFile(fileUri.toString()) ?? null; } #updateRepositoriesForFolder( workspaceFolder: WorkspaceFolder, repositoryMap: RepositoryMap, repositoryTrie: RepositoryTrie, ) { this.#workspaces.set(workspaceFolder.uri, repositoryMap); this.#workspaceRepositoryTries.set(workspaceFolder.uri, repositoryTrie); } async handleWorkspaceFilesUpdate({ workspaceFolder, files }: WorkspaceFilesUpdate) { // clear existing repositories from workspace this.#emptyRepositoriesForWorkspace(workspaceFolder.uri); const repositories = this.#detectRepositories(files, workspaceFolder); const repositoryMap = new Map(repositories.map((repo) => [repo.uri.toString(), repo])); // Build and cache the repository trie for this workspace const trie = this.#buildRepositoryTrie(repositories); this.#updateRepositoriesForFolder(workspaceFolder, repositoryMap, trie); await Promise.all( repositories.map((repo) => repo.addFilesAndLoadGitIgnore( files.filter((file) => { const matchingRepo = this.findMatchingRepositoryUri(file, workspaceFolder); return matchingRepo && matchingRepo.toString() === repo.uri.toString(); }), ), ), ); } async handleWorkspaceFileUpdate({ fileUri, workspaceFolder, event }: WorkspaceFileUpdate) { const repoUri = this.findMatchingRepositoryUri(fileUri, workspaceFolder); if (!repoUri) { log.debug(`No matching repository found for file ${fileUri.toString()}`); return; } const repositoryMap = this.#getRepositoriesForWorkspace(workspaceFolder.uri); const repository = repositoryMap.get(repoUri.toString()); if (!repository) { log.debug(`Repository not found for URI ${repoUri.toString()}`); return; } if (repository.isFileIgnored(fileUri)) { log.debug(`File ${fileUri.toString()} is ignored`); return; } switch (event) { case 'add': repository.setFile(fileUri); log.debug(`File ${fileUri.toString()} added to repository ${repoUri.toString()}`); break; case 'change': repository.setFile(fileUri); log.debug(`File ${fileUri.toString()} updated in repository ${repoUri.toString()}`); break; case 'unlink': repository.removeFile(fileUri.toString()); log.debug(`File ${fileUri.toString()} removed from repository ${repoUri.toString()}`); break; default: log.warn(`Unknown file event ${event} for file ${fileUri.toString()}`); } } #getRepositoriesForWorkspace(workspaceFolderUri: WorkspaceFolderUri): RepositoryMap { return this.#workspaces.get(workspaceFolderUri) || new Map(); } #emptyRepositoriesForWorkspace(workspaceFolderUri: WorkspaceFolderUri): void { log.debug(`Emptying repositories for workspace ${workspaceFolderUri}`); const repos = this.#workspaces.get(workspaceFolderUri); if (!repos || repos.size === 0) return; // clear up ignore manager trie from memory repos.forEach((repo) => { repo.dispose(); log.debug(`Repository ${repo.uri} has been disposed`); }); repos.clear(); const trie = this.#workspaceRepositoryTries.get(workspaceFolderUri); if (trie) { trie.dispose(); this.#workspaceRepositoryTries.delete(workspaceFolderUri); } this.#workspaces.delete(workspaceFolderUri); log.debug(`Repositories for workspace ${workspaceFolderUri} have been emptied`); } #detectRepositories(files: URI[], workspaceFolder: WorkspaceFolder): Repository[] { const gitConfigFiles = files.filter((file) => file.toString().endsWith('.git/config')); return gitConfigFiles.map((file) => { const projectUri = fsPathToUri(file.path.replace('.git/config', '')); const ignoreManager = new IgnoreManager(projectUri.fsPath); log.info(`Detected repository at ${projectUri.path}`); return new Repository({ ignoreManager, uri: projectUri, configFileUri: file, workspaceFolder, }); }); } getFilesForWorkspace( workspaceFolderUri: WorkspaceFolderUri, options: { excludeGitFolder?: boolean; excludeIgnored?: boolean } = {}, ): RepositoryFile[] { const repositories = this.#getRepositoriesForWorkspace(workspaceFolderUri); const allFiles: RepositoryFile[] = []; repositories.forEach((repository) => { repository.getFiles().forEach((file) => { // apply the filters if (options.excludeGitFolder && this.#isInGitFolder(file.uri, repository.uri)) { return; } if (options.excludeIgnored && file.isIgnored) { return; } allFiles.push(file); }); }); return allFiles; } // Helper method to check if a file is in the .git folder #isInGitFolder(fileUri: URI, repositoryUri: URI): boolean { const relativePath = fileUri.path.slice(repositoryUri.path.length); return relativePath.split('/').some((part) => part === '.git'); } } References: - src/common/git/repository_service.ts:241 - src/common/git/repository_service.ts:175" You are a code assistant,Definition of 'GitLabChatRecordAttributes' in file packages/webview_duo_chat/src/plugin/port/chat/gitlab_chat_record.ts in project gitlab-lsp,"Definition: type GitLabChatRecordAttributes = { chunkId?: number | null; type?: ChatRecordType; role: ChatRecordRole; content?: string; contentHtml?: string; requestId?: string; state?: ChatRecordState; errors?: string[]; timestamp?: string; extras?: { sources: object[]; }; }; export class GitLabChatRecord { chunkId?: number | null; role: ChatRecordRole; content?: string; contentHtml?: string; id: string; requestId?: string; state: ChatRecordState; timestamp: number; type: ChatRecordType; errors: string[]; extras?: { sources: object[]; }; context?: GitLabChatRecordContext; constructor({ chunkId, type, role, content, contentHtml, state, requestId, errors, timestamp, extras, }: GitLabChatRecordAttributes) { this.chunkId = chunkId; this.role = role; this.content = content; this.contentHtml = contentHtml; this.type = type ?? this.#detectType(); this.state = state ?? 'ready'; this.requestId = requestId; this.errors = errors ?? []; this.id = uuidv4(); this.timestamp = timestamp ? Date.parse(timestamp) : Date.now(); this.extras = extras; } static buildWithContext(attributes: GitLabChatRecordAttributes): GitLabChatRecord { const record = new GitLabChatRecord(attributes); record.context = buildCurrentContext(); return record; } update(attributes: Partial) { const convertedAttributes = attributes as Partial; if (attributes.timestamp) { convertedAttributes.timestamp = Date.parse(attributes.timestamp); } Object.assign(this, convertedAttributes); } #detectType(): ChatRecordType { if (this.content === SPECIAL_MESSAGES.RESET) { return 'newConversation'; } return 'general'; } } References: - packages/webview_duo_chat/src/plugin/port/chat/gitlab_chat_record.ts:67 - packages/webview_duo_chat/src/plugin/port/chat/gitlab_chat_record.ts:81" You are a code assistant,Definition of 'AdvancedContextService' in file src/common/advanced_context/advanced_context_service.ts in project gitlab-lsp,"Definition: export interface AdvancedContextService {} export const AdvancedContextService = createInterfaceId('AdvancedContextService'); @Injectable(AdvancedContextService, [ ConfigService, LsConnection, DocumentService, DocumentTransformerService, SupportedLanguagesService, ]) export class DefaultAdvancedContextService implements AdvancedContextService { #configService: ConfigService; #documentTransformer: DocumentTransformerService; #supportedLanguagesService: SupportedLanguagesService; constructor( configService: ConfigService, connection: LsConnection, documentService: DocumentService, documentTransformer: DocumentTransformerService, supportedLanguagesService: SupportedLanguagesService, ) { this.#configService = configService; this.#documentTransformer = documentTransformer; this.#supportedLanguagesService = supportedLanguagesService; const subscription = documentService.onDocumentChange(async ({ document }, handlerType) => { await this.#updateAdvancedContext(document, handlerType); }); connection.onShutdown(() => subscription.dispose()); } /** * Currently updates the LRU cache with the most recently accessed files in the workspace. * We only update the advanced context for supported languages. We also ensure to run * documents through the `DocumentTransformer` to ensure the secret redaction is applied. */ async #updateAdvancedContext( document: TextDocument, handlerType: TextDocumentChangeListenerType, ) { const lruCache = LruCache.getInstance(LRU_CACHE_BYTE_SIZE_LIMIT); // eslint-disable-next-line default-case switch (handlerType) { case TextDocumentChangeListenerType.onDidClose: { // We don't check if the language is supported for `onDidClose` because we want // always attempt to delete the file from the cache. const fileDeleted = lruCache.deleteFile(document.uri); if (fileDeleted) { log.debug(`Advanced Context: File ${document.uri} was deleted from the LRU cache`); } else { log.debug(`Advanced Context: File ${document.uri} was not found in the LRU cache`); } break; } case TextDocumentChangeListenerType.onDidChangeContent: case TextDocumentChangeListenerType.onDidSave: case TextDocumentChangeListenerType.onDidOpen: case TextDocumentChangeListenerType.onDidSetActive: { const languageEnabled = this.#supportedLanguagesService.isLanguageEnabled( document.languageId, ); if (!languageEnabled) { return; } const context = this.#documentTransformer.getContext( document.uri, { line: 0, character: 0 }, this.#configService.get().client.workspaceFolders ?? [], undefined, ); if (!context) { log.debug(`Advanced Context: document context for ${document.uri} was not found`); return; } lruCache.updateFile(context); log.debug(`Advanced Context: uri ${document.uri} was updated in the MRU cache`); break; } } } } References:" You are a code assistant,Definition of 'onApiReconfigured' in file src/common/api.ts in project gitlab-lsp,"Definition: onApiReconfigured(listener: (data: ApiReconfiguredData) => void): Disposable { this.#eventEmitter.on(CONFIG_CHANGE_EVENT_NAME, listener); return { dispose: () => this.#eventEmitter.removeListener(CONFIG_CHANGE_EVENT_NAME, listener) }; } #fireApiReconfigured(isInValidState: boolean, validationMessage?: string) { const data: ApiReconfiguredData = { isInValidState, validationMessage }; this.#eventEmitter.emit(CONFIG_CHANGE_EVENT_NAME, data); } async configureApi({ token, baseUrl = GITLAB_API_BASE_URL, }: { token?: string; baseUrl?: string; }) { if (this.#token === token && this.#baseURL === baseUrl) return; this.#token = token; this.#baseURL = baseUrl; const { valid, reason, message } = await this.checkToken(this.#token); let validationMessage; if (!valid) { this.#configService.set('client.token', undefined); validationMessage = `Token is invalid. ${message}. Reason: ${reason}`; log.warn(validationMessage); } else { log.info('Token is valid'); } this.#instanceVersion = await this.#getGitLabInstanceVersion(); this.#fireApiReconfigured(valid, validationMessage); } #looksLikePatToken(token: string): boolean { // OAuth tokens will be longer than 42 characters and PATs will be shorter. return token.length < 42; } async #checkPatToken(token: string): Promise { const headers = this.#getDefaultHeaders(token); const response = await this.#lsFetch.get( `${this.#baseURL}/api/v4/personal_access_tokens/self`, { headers }, ); await handleFetchError(response, 'Information about personal access token'); const { active, scopes } = (await response.json()) as PersonalAccessToken; if (!active) { return { valid: false, reason: 'not_active', message: 'Token is not active.', }; } if (!this.#hasValidScopes(scopes)) { const joinedScopes = scopes.map((scope) => `'${scope}'`).join(', '); return { valid: false, reason: 'invalid_scopes', message: `Token has scope(s) ${joinedScopes} (needs 'api').`, }; } return { valid: true }; } async #checkOAuthToken(token: string): Promise { const headers = this.#getDefaultHeaders(token); const response = await this.#lsFetch.get(`${this.#baseURL}/oauth/token/info`, { headers, }); await handleFetchError(response, 'Information about OAuth token'); const { scope: scopes } = (await response.json()) as OAuthToken; if (!this.#hasValidScopes(scopes)) { const joinedScopes = scopes.map((scope) => `'${scope}'`).join(', '); return { valid: false, reason: 'invalid_scopes', message: `Token has scope(s) ${joinedScopes} (needs 'api').`, }; } return { valid: true }; } async checkToken(token: string = ''): Promise { try { if (this.#looksLikePatToken(token)) { log.info('Checking token for PAT validity'); return await this.#checkPatToken(token); } log.info('Checking token for OAuth validity'); return await this.#checkOAuthToken(token); } catch (err) { log.error('Error performing token check', err); return { valid: false, reason: 'unknown', message: `Failed to check token: ${err}`, }; } } #hasValidScopes(scopes: string[]): boolean { return scopes.includes('api'); } async getCodeSuggestions( request: CodeSuggestionRequest, ): Promise { if (!this.#token) { throw new Error('Token needs to be provided to request Code Suggestions'); } const headers = { ...this.#getDefaultHeaders(this.#token), 'Content-Type': 'application/json', }; const response = await this.#lsFetch.post( `${this.#baseURL}/api/v4/code_suggestions/completions`, { headers, body: JSON.stringify(request) }, ); await handleFetchError(response, 'Code Suggestions'); const data = await response.json(); return { ...data, status: response.status }; } async *getStreamingCodeSuggestions( request: CodeSuggestionRequest, ): AsyncGenerator { if (!this.#token) { throw new Error('Token needs to be provided to stream code suggestions'); } const headers = { ...this.#getDefaultHeaders(this.#token), 'Content-Type': 'application/json', }; yield* this.#lsFetch.streamFetch( `${this.#baseURL}/api/v4/code_suggestions/completions`, JSON.stringify(request), headers, ); } async fetchFromApi(request: ApiRequest): Promise { if (!this.#token) { return Promise.reject(new Error('Token needs to be provided to authorise API request.')); } if ( request.supportedSinceInstanceVersion && !this.#instanceVersionHigherOrEqualThen(request.supportedSinceInstanceVersion.version) ) { return Promise.reject( new InvalidInstanceVersionError( `Can't ${request.supportedSinceInstanceVersion.resourceName} until your instance is upgraded to ${request.supportedSinceInstanceVersion.version} or higher.`, ), ); } if (request.type === 'graphql') { return this.#graphqlRequest(request.query, request.variables); } switch (request.method) { case 'GET': return this.#fetch(request.path, request.searchParams, 'resource', request.headers); case 'POST': return this.#postFetch(request.path, 'resource', request.body, request.headers); default: // the type assertion is necessary because TS doesn't expect any other types throw new Error(`Unknown request type ${(request as ApiRequest).type}`); } } async connectToCable(): Promise { const headers = this.#getDefaultHeaders(this.#token); const websocketOptions = { headers: { ...headers, Origin: this.#baseURL, }, }; return connectToCable(this.#baseURL, websocketOptions); } async #graphqlRequest( document: RequestDocument, variables?: V, ): Promise { const ensureEndsWithSlash = (url: string) => url.replace(/\/?$/, '/'); const endpoint = new URL('./api/graphql', ensureEndsWithSlash(this.#baseURL)).href; // supports GitLab instances that are on a custom path, e.g. ""https://example.com/gitlab"" const graphqlFetch = async ( input: RequestInfo | URL, init?: RequestInit, ): Promise => { const url = input instanceof URL ? input.toString() : input; return this.#lsFetch.post(url, { ...init, headers: { ...headers, ...init?.headers }, }); }; const headers = this.#getDefaultHeaders(this.#token); const client = new GraphQLClient(endpoint, { headers, fetch: graphqlFetch, }); return client.request(document, variables); } async #fetch( apiResourcePath: string, query: Record = {}, resourceName = 'resource', headers?: Record, ): Promise { const url = `${this.#baseURL}/api/v4${apiResourcePath}${createQueryString(query)}`; const result = await this.#lsFetch.get(url, { headers: { ...this.#getDefaultHeaders(this.#token), ...headers }, }); await handleFetchError(result, resourceName); return result.json() as Promise; } async #postFetch( apiResourcePath: string, resourceName = 'resource', body?: unknown, headers?: Record, ): Promise { const url = `${this.#baseURL}/api/v4${apiResourcePath}`; const response = await this.#lsFetch.post(url, { headers: { 'Content-Type': 'application/json', ...this.#getDefaultHeaders(this.#token), ...headers, }, body: JSON.stringify(body), }); await handleFetchError(response, resourceName); return response.json() as Promise; } #getDefaultHeaders(token?: string) { return { Authorization: `Bearer ${token}`, 'User-Agent': `code-completions-language-server-experiment (${this.#clientInfo?.name}:${this.#clientInfo?.version})`, 'X-Gitlab-Language-Server-Version': getLanguageServerVersion(), }; } #instanceVersionHigherOrEqualThen(version: string): boolean { if (!this.#instanceVersion) return false; return semverCompare(this.#instanceVersion, version) >= 0; } async #getGitLabInstanceVersion(): Promise { if (!this.#token) { return ''; } const headers = this.#getDefaultHeaders(this.#token); const response = await this.#lsFetch.get(`${this.#baseURL}/api/v4/version`, { headers, }); const { version } = await response.json(); return version; } get instanceVersion() { return this.#instanceVersion; } } References:" You are a code assistant,Definition of 'TokenCheckResponse' in file src/common/api.ts in project gitlab-lsp,"Definition: export interface TokenCheckResponse { valid: boolean; reason?: 'unknown' | 'not_active' | 'invalid_scopes'; message?: string; } export interface IDirectConnectionDetailsHeaders { 'X-Gitlab-Global-User-Id': string; 'X-Gitlab-Instance-Id': string; 'X-Gitlab-Host-Name': string; 'X-Gitlab-Saas-Duo-Pro-Namespace-Ids': string; } export interface IDirectConnectionModelDetails { model_provider: string; model_name: string; } export interface IDirectConnectionDetails { base_url: string; token: string; expires_at: number; headers: IDirectConnectionDetailsHeaders; model_details: IDirectConnectionModelDetails; } const CONFIG_CHANGE_EVENT_NAME = 'apiReconfigured'; @Injectable(GitLabApiClient, [LsFetch, ConfigService]) export class GitLabAPI implements GitLabApiClient { #token: string | undefined; #baseURL: string; #clientInfo?: IClientInfo; #lsFetch: LsFetch; #eventEmitter = new EventEmitter(); #configService: ConfigService; #instanceVersion?: string; constructor(lsFetch: LsFetch, configService: ConfigService) { this.#baseURL = GITLAB_API_BASE_URL; this.#lsFetch = lsFetch; this.#configService = configService; this.#configService.onConfigChange(async (config) => { this.#clientInfo = configService.get('client.clientInfo'); this.#lsFetch.updateAgentOptions({ ignoreCertificateErrors: this.#configService.get('client.ignoreCertificateErrors') ?? false, ...(this.#configService.get('client.httpAgentOptions') ?? {}), }); await this.configureApi(config.client); }); } onApiReconfigured(listener: (data: ApiReconfiguredData) => void): Disposable { this.#eventEmitter.on(CONFIG_CHANGE_EVENT_NAME, listener); return { dispose: () => this.#eventEmitter.removeListener(CONFIG_CHANGE_EVENT_NAME, listener) }; } #fireApiReconfigured(isInValidState: boolean, validationMessage?: string) { const data: ApiReconfiguredData = { isInValidState, validationMessage }; this.#eventEmitter.emit(CONFIG_CHANGE_EVENT_NAME, data); } async configureApi({ token, baseUrl = GITLAB_API_BASE_URL, }: { token?: string; baseUrl?: string; }) { if (this.#token === token && this.#baseURL === baseUrl) return; this.#token = token; this.#baseURL = baseUrl; const { valid, reason, message } = await this.checkToken(this.#token); let validationMessage; if (!valid) { this.#configService.set('client.token', undefined); validationMessage = `Token is invalid. ${message}. Reason: ${reason}`; log.warn(validationMessage); } else { log.info('Token is valid'); } this.#instanceVersion = await this.#getGitLabInstanceVersion(); this.#fireApiReconfigured(valid, validationMessage); } #looksLikePatToken(token: string): boolean { // OAuth tokens will be longer than 42 characters and PATs will be shorter. return token.length < 42; } async #checkPatToken(token: string): Promise { const headers = this.#getDefaultHeaders(token); const response = await this.#lsFetch.get( `${this.#baseURL}/api/v4/personal_access_tokens/self`, { headers }, ); await handleFetchError(response, 'Information about personal access token'); const { active, scopes } = (await response.json()) as PersonalAccessToken; if (!active) { return { valid: false, reason: 'not_active', message: 'Token is not active.', }; } if (!this.#hasValidScopes(scopes)) { const joinedScopes = scopes.map((scope) => `'${scope}'`).join(', '); return { valid: false, reason: 'invalid_scopes', message: `Token has scope(s) ${joinedScopes} (needs 'api').`, }; } return { valid: true }; } async #checkOAuthToken(token: string): Promise { const headers = this.#getDefaultHeaders(token); const response = await this.#lsFetch.get(`${this.#baseURL}/oauth/token/info`, { headers, }); await handleFetchError(response, 'Information about OAuth token'); const { scope: scopes } = (await response.json()) as OAuthToken; if (!this.#hasValidScopes(scopes)) { const joinedScopes = scopes.map((scope) => `'${scope}'`).join(', '); return { valid: false, reason: 'invalid_scopes', message: `Token has scope(s) ${joinedScopes} (needs 'api').`, }; } return { valid: true }; } async checkToken(token: string = ''): Promise { try { if (this.#looksLikePatToken(token)) { log.info('Checking token for PAT validity'); return await this.#checkPatToken(token); } log.info('Checking token for OAuth validity'); return await this.#checkOAuthToken(token); } catch (err) { log.error('Error performing token check', err); return { valid: false, reason: 'unknown', message: `Failed to check token: ${err}`, }; } } #hasValidScopes(scopes: string[]): boolean { return scopes.includes('api'); } async getCodeSuggestions( request: CodeSuggestionRequest, ): Promise { if (!this.#token) { throw new Error('Token needs to be provided to request Code Suggestions'); } const headers = { ...this.#getDefaultHeaders(this.#token), 'Content-Type': 'application/json', }; const response = await this.#lsFetch.post( `${this.#baseURL}/api/v4/code_suggestions/completions`, { headers, body: JSON.stringify(request) }, ); await handleFetchError(response, 'Code Suggestions'); const data = await response.json(); return { ...data, status: response.status }; } async *getStreamingCodeSuggestions( request: CodeSuggestionRequest, ): AsyncGenerator { if (!this.#token) { throw new Error('Token needs to be provided to stream code suggestions'); } const headers = { ...this.#getDefaultHeaders(this.#token), 'Content-Type': 'application/json', }; yield* this.#lsFetch.streamFetch( `${this.#baseURL}/api/v4/code_suggestions/completions`, JSON.stringify(request), headers, ); } async fetchFromApi(request: ApiRequest): Promise { if (!this.#token) { return Promise.reject(new Error('Token needs to be provided to authorise API request.')); } if ( request.supportedSinceInstanceVersion && !this.#instanceVersionHigherOrEqualThen(request.supportedSinceInstanceVersion.version) ) { return Promise.reject( new InvalidInstanceVersionError( `Can't ${request.supportedSinceInstanceVersion.resourceName} until your instance is upgraded to ${request.supportedSinceInstanceVersion.version} or higher.`, ), ); } if (request.type === 'graphql') { return this.#graphqlRequest(request.query, request.variables); } switch (request.method) { case 'GET': return this.#fetch(request.path, request.searchParams, 'resource', request.headers); case 'POST': return this.#postFetch(request.path, 'resource', request.body, request.headers); default: // the type assertion is necessary because TS doesn't expect any other types throw new Error(`Unknown request type ${(request as ApiRequest).type}`); } } async connectToCable(): Promise { const headers = this.#getDefaultHeaders(this.#token); const websocketOptions = { headers: { ...headers, Origin: this.#baseURL, }, }; return connectToCable(this.#baseURL, websocketOptions); } async #graphqlRequest( document: RequestDocument, variables?: V, ): Promise { const ensureEndsWithSlash = (url: string) => url.replace(/\/?$/, '/'); const endpoint = new URL('./api/graphql', ensureEndsWithSlash(this.#baseURL)).href; // supports GitLab instances that are on a custom path, e.g. ""https://example.com/gitlab"" const graphqlFetch = async ( input: RequestInfo | URL, init?: RequestInit, ): Promise => { const url = input instanceof URL ? input.toString() : input; return this.#lsFetch.post(url, { ...init, headers: { ...headers, ...init?.headers }, }); }; const headers = this.#getDefaultHeaders(this.#token); const client = new GraphQLClient(endpoint, { headers, fetch: graphqlFetch, }); return client.request(document, variables); } async #fetch( apiResourcePath: string, query: Record = {}, resourceName = 'resource', headers?: Record, ): Promise { const url = `${this.#baseURL}/api/v4${apiResourcePath}${createQueryString(query)}`; const result = await this.#lsFetch.get(url, { headers: { ...this.#getDefaultHeaders(this.#token), ...headers }, }); await handleFetchError(result, resourceName); return result.json() as Promise; } async #postFetch( apiResourcePath: string, resourceName = 'resource', body?: unknown, headers?: Record, ): Promise { const url = `${this.#baseURL}/api/v4${apiResourcePath}`; const response = await this.#lsFetch.post(url, { headers: { 'Content-Type': 'application/json', ...this.#getDefaultHeaders(this.#token), ...headers, }, body: JSON.stringify(body), }); await handleFetchError(response, resourceName); return response.json() as Promise; } #getDefaultHeaders(token?: string) { return { Authorization: `Bearer ${token}`, 'User-Agent': `code-completions-language-server-experiment (${this.#clientInfo?.name}:${this.#clientInfo?.version})`, 'X-Gitlab-Language-Server-Version': getLanguageServerVersion(), }; } #instanceVersionHigherOrEqualThen(version: string): boolean { if (!this.#instanceVersion) return false; return semverCompare(this.#instanceVersion, version) >= 0; } async #getGitLabInstanceVersion(): Promise { if (!this.#token) { return ''; } const headers = this.#getDefaultHeaders(this.#token); const response = await this.#lsFetch.get(`${this.#baseURL}/api/v4/version`, { headers, }); const { version } = await response.json(); return version; } get instanceVersion() { return this.#instanceVersion; } } References:" You are a code assistant,Definition of 'isEnabled' in file src/common/tracking/tracking_types.ts in project gitlab-lsp,"Definition: isEnabled(): boolean; setCodeSuggestionsContext( uniqueTrackingId: string, context: Partial, ): void; updateCodeSuggestionsContext( uniqueTrackingId: string, contextUpdate: Partial, ): void; rejectOpenedSuggestions(): void; updateSuggestionState(uniqueTrackingId: string, newState: TRACKING_EVENTS): void; } export const TelemetryTracker = createInterfaceId('TelemetryTracker'); References:" You are a code assistant,Definition of 'SimpleFibonacciSolver' in file packages/lib-pkg-1/src/simple_fibonacci_solver.ts in project gitlab-lsp,"Definition: export class SimpleFibonacciSolver implements FibonacciSolver { solve(index: number): number { if (index <= 1) return index; return this.solve(index - 1) + this.solve(index - 2); } } References: - packages/webview-chat/src/app/index.ts:10 - packages/lib-pkg-1/src/simple_fibonacci_solver.test.ts:4 - packages/lib-pkg-1/src/simple_fibonacci_solver.test.ts:7" You are a code assistant,Definition of 'warn' in file src/common/log_types.ts in project gitlab-lsp,"Definition: warn(message: string, e?: Error): void; error(e: Error): void; error(message: string, e?: Error): void; } 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 'getStreamingCodeSuggestions' in file src/common/api.ts in project gitlab-lsp,"Definition: getStreamingCodeSuggestions(request: CodeSuggestionRequest): AsyncGenerator; fetchFromApi(request: ApiRequest): Promise; connectToCable(): Promise; onApiReconfigured(listener: (data: ApiReconfiguredData) => void): Disposable; readonly instanceVersion?: string; } export const GitLabApiClient = createInterfaceId('GitLabApiClient'); export type GenerationType = 'comment' | 'small_file' | 'empty_function' | undefined; export interface CodeSuggestionRequest { prompt_version: number; project_path: string; model_provider?: string; project_id: number; current_file: CodeSuggestionRequestCurrentFile; intent?: 'completion' | 'generation'; stream?: boolean; /** how many suggestion options should the API return */ choices_count?: number; /** additional context to provide to the model */ context?: AdditionalContext[]; /* A user's instructions for code suggestions. */ user_instruction?: string; /* The backend can add additional prompt info based on the type of event */ generation_type?: GenerationType; } export interface CodeSuggestionRequestCurrentFile { file_name: string; content_above_cursor: string; content_below_cursor: string; } export interface CodeSuggestionResponse { choices?: SuggestionOption[]; model?: ICodeSuggestionModel; status: number; error?: string; isDirectConnection?: boolean; } // FIXME: Rename to SuggestionOptionStream when renaming the SuggestionOption export interface StartStreamOption { uniqueTrackingId: string; /** the streamId represents the beginning of a stream * */ streamId: string; } export type SuggestionOptionOrStream = SuggestionOption | StartStreamOption; export interface PersonalAccessToken { name: string; scopes: string[]; active: boolean; } export interface OAuthToken { scope: string[]; } export interface TokenCheckResponse { valid: boolean; reason?: 'unknown' | 'not_active' | 'invalid_scopes'; message?: string; } export interface IDirectConnectionDetailsHeaders { 'X-Gitlab-Global-User-Id': string; 'X-Gitlab-Instance-Id': string; 'X-Gitlab-Host-Name': string; 'X-Gitlab-Saas-Duo-Pro-Namespace-Ids': string; } export interface IDirectConnectionModelDetails { model_provider: string; model_name: string; } export interface IDirectConnectionDetails { base_url: string; token: string; expires_at: number; headers: IDirectConnectionDetailsHeaders; model_details: IDirectConnectionModelDetails; } const CONFIG_CHANGE_EVENT_NAME = 'apiReconfigured'; @Injectable(GitLabApiClient, [LsFetch, ConfigService]) export class GitLabAPI implements GitLabApiClient { #token: string | undefined; #baseURL: string; #clientInfo?: IClientInfo; #lsFetch: LsFetch; #eventEmitter = new EventEmitter(); #configService: ConfigService; #instanceVersion?: string; constructor(lsFetch: LsFetch, configService: ConfigService) { this.#baseURL = GITLAB_API_BASE_URL; this.#lsFetch = lsFetch; this.#configService = configService; this.#configService.onConfigChange(async (config) => { this.#clientInfo = configService.get('client.clientInfo'); this.#lsFetch.updateAgentOptions({ ignoreCertificateErrors: this.#configService.get('client.ignoreCertificateErrors') ?? false, ...(this.#configService.get('client.httpAgentOptions') ?? {}), }); await this.configureApi(config.client); }); } onApiReconfigured(listener: (data: ApiReconfiguredData) => void): Disposable { this.#eventEmitter.on(CONFIG_CHANGE_EVENT_NAME, listener); return { dispose: () => this.#eventEmitter.removeListener(CONFIG_CHANGE_EVENT_NAME, listener) }; } #fireApiReconfigured(isInValidState: boolean, validationMessage?: string) { const data: ApiReconfiguredData = { isInValidState, validationMessage }; this.#eventEmitter.emit(CONFIG_CHANGE_EVENT_NAME, data); } async configureApi({ token, baseUrl = GITLAB_API_BASE_URL, }: { token?: string; baseUrl?: string; }) { if (this.#token === token && this.#baseURL === baseUrl) return; this.#token = token; this.#baseURL = baseUrl; const { valid, reason, message } = await this.checkToken(this.#token); let validationMessage; if (!valid) { this.#configService.set('client.token', undefined); validationMessage = `Token is invalid. ${message}. Reason: ${reason}`; log.warn(validationMessage); } else { log.info('Token is valid'); } this.#instanceVersion = await this.#getGitLabInstanceVersion(); this.#fireApiReconfigured(valid, validationMessage); } #looksLikePatToken(token: string): boolean { // OAuth tokens will be longer than 42 characters and PATs will be shorter. return token.length < 42; } async #checkPatToken(token: string): Promise { const headers = this.#getDefaultHeaders(token); const response = await this.#lsFetch.get( `${this.#baseURL}/api/v4/personal_access_tokens/self`, { headers }, ); await handleFetchError(response, 'Information about personal access token'); const { active, scopes } = (await response.json()) as PersonalAccessToken; if (!active) { return { valid: false, reason: 'not_active', message: 'Token is not active.', }; } if (!this.#hasValidScopes(scopes)) { const joinedScopes = scopes.map((scope) => `'${scope}'`).join(', '); return { valid: false, reason: 'invalid_scopes', message: `Token has scope(s) ${joinedScopes} (needs 'api').`, }; } return { valid: true }; } async #checkOAuthToken(token: string): Promise { const headers = this.#getDefaultHeaders(token); const response = await this.#lsFetch.get(`${this.#baseURL}/oauth/token/info`, { headers, }); await handleFetchError(response, 'Information about OAuth token'); const { scope: scopes } = (await response.json()) as OAuthToken; if (!this.#hasValidScopes(scopes)) { const joinedScopes = scopes.map((scope) => `'${scope}'`).join(', '); return { valid: false, reason: 'invalid_scopes', message: `Token has scope(s) ${joinedScopes} (needs 'api').`, }; } return { valid: true }; } async checkToken(token: string = ''): Promise { try { if (this.#looksLikePatToken(token)) { log.info('Checking token for PAT validity'); return await this.#checkPatToken(token); } log.info('Checking token for OAuth validity'); return await this.#checkOAuthToken(token); } catch (err) { log.error('Error performing token check', err); return { valid: false, reason: 'unknown', message: `Failed to check token: ${err}`, }; } } #hasValidScopes(scopes: string[]): boolean { return scopes.includes('api'); } async getCodeSuggestions( request: CodeSuggestionRequest, ): Promise { if (!this.#token) { throw new Error('Token needs to be provided to request Code Suggestions'); } const headers = { ...this.#getDefaultHeaders(this.#token), 'Content-Type': 'application/json', }; const response = await this.#lsFetch.post( `${this.#baseURL}/api/v4/code_suggestions/completions`, { headers, body: JSON.stringify(request) }, ); await handleFetchError(response, 'Code Suggestions'); const data = await response.json(); return { ...data, status: response.status }; } async *getStreamingCodeSuggestions( request: CodeSuggestionRequest, ): AsyncGenerator { if (!this.#token) { throw new Error('Token needs to be provided to stream code suggestions'); } const headers = { ...this.#getDefaultHeaders(this.#token), 'Content-Type': 'application/json', }; yield* this.#lsFetch.streamFetch( `${this.#baseURL}/api/v4/code_suggestions/completions`, JSON.stringify(request), headers, ); } async fetchFromApi(request: ApiRequest): Promise { if (!this.#token) { return Promise.reject(new Error('Token needs to be provided to authorise API request.')); } if ( request.supportedSinceInstanceVersion && !this.#instanceVersionHigherOrEqualThen(request.supportedSinceInstanceVersion.version) ) { return Promise.reject( new InvalidInstanceVersionError( `Can't ${request.supportedSinceInstanceVersion.resourceName} until your instance is upgraded to ${request.supportedSinceInstanceVersion.version} or higher.`, ), ); } if (request.type === 'graphql') { return this.#graphqlRequest(request.query, request.variables); } switch (request.method) { case 'GET': return this.#fetch(request.path, request.searchParams, 'resource', request.headers); case 'POST': return this.#postFetch(request.path, 'resource', request.body, request.headers); default: // the type assertion is necessary because TS doesn't expect any other types throw new Error(`Unknown request type ${(request as ApiRequest).type}`); } } async connectToCable(): Promise { const headers = this.#getDefaultHeaders(this.#token); const websocketOptions = { headers: { ...headers, Origin: this.#baseURL, }, }; return connectToCable(this.#baseURL, websocketOptions); } async #graphqlRequest( document: RequestDocument, variables?: V, ): Promise { const ensureEndsWithSlash = (url: string) => url.replace(/\/?$/, '/'); const endpoint = new URL('./api/graphql', ensureEndsWithSlash(this.#baseURL)).href; // supports GitLab instances that are on a custom path, e.g. ""https://example.com/gitlab"" const graphqlFetch = async ( input: RequestInfo | URL, init?: RequestInit, ): Promise => { const url = input instanceof URL ? input.toString() : input; return this.#lsFetch.post(url, { ...init, headers: { ...headers, ...init?.headers }, }); }; const headers = this.#getDefaultHeaders(this.#token); const client = new GraphQLClient(endpoint, { headers, fetch: graphqlFetch, }); return client.request(document, variables); } async #fetch( apiResourcePath: string, query: Record = {}, resourceName = 'resource', headers?: Record, ): Promise { const url = `${this.#baseURL}/api/v4${apiResourcePath}${createQueryString(query)}`; const result = await this.#lsFetch.get(url, { headers: { ...this.#getDefaultHeaders(this.#token), ...headers }, }); await handleFetchError(result, resourceName); return result.json() as Promise; } async #postFetch( apiResourcePath: string, resourceName = 'resource', body?: unknown, headers?: Record, ): Promise { const url = `${this.#baseURL}/api/v4${apiResourcePath}`; const response = await this.#lsFetch.post(url, { headers: { 'Content-Type': 'application/json', ...this.#getDefaultHeaders(this.#token), ...headers, }, body: JSON.stringify(body), }); await handleFetchError(response, resourceName); return response.json() as Promise; } #getDefaultHeaders(token?: string) { return { Authorization: `Bearer ${token}`, 'User-Agent': `code-completions-language-server-experiment (${this.#clientInfo?.name}:${this.#clientInfo?.version})`, 'X-Gitlab-Language-Server-Version': getLanguageServerVersion(), }; } #instanceVersionHigherOrEqualThen(version: string): boolean { if (!this.#instanceVersion) return false; return semverCompare(this.#instanceVersion, version) >= 0; } async #getGitLabInstanceVersion(): Promise { if (!this.#token) { return ''; } const headers = this.#getDefaultHeaders(this.#token); const response = await this.#lsFetch.get(`${this.#baseURL}/api/v4/version`, { headers, }); const { version } = await response.json(); return version; } get instanceVersion() { return this.#instanceVersion; } } References:" You are a code assistant,Definition of 'FILE_INFO' in file src/common/test_utils/mocks.ts in project gitlab-lsp,"Definition: export const FILE_INFO: IDocContext = { fileRelativePath: 'example.ts', prefix: 'const x = 10;', suffix: 'console.log(x);', position: { line: 0, character: 13, }, uri: 'file:///example.ts', languageId: 'javascript', }; 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 'AiContextQuery' in file src/common/ai_context_management_2/ai_context_aggregator.ts in project gitlab-lsp,"Definition: 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 { 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 { 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/ai_context_management_2/ai_context_aggregator.ts:36 - src/common/connection_service.ts:105" You are a code assistant,Definition of 'constructor' in file src/common/webview/webview_resource_location_service.test.ts in project gitlab-lsp,"Definition: 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:" You are a code assistant,Definition of 'c' in file packages/lib_di/src/index.test.ts in project gitlab-lsp,"Definition: c(): string; } const A = createInterfaceId('A'); const B = createInterfaceId('B'); const C = createInterfaceId('C'); @Injectable(A, []) class AImpl implements A { a = () => 'a'; } @Injectable(B, [A]) class BImpl implements B { #a: A; constructor(a: A) { this.#a = a; } b = () => `B(${this.#a.a()})`; } @Injectable(C, [A, B]) class CImpl implements C { #a: A; #b: B; constructor(a: A, b: B) { this.#a = a; this.#b = b; } c = () => `C(${this.#b.b()}, ${this.#a.a()})`; } let container: Container; beforeEach(() => { container = new Container(); }); describe('addInstances', () => { const O = createInterfaceId('object'); it('fails if the instance is not branded', () => { expect(() => container.addInstances({ say: 'hello' } as BrandedInstance)).toThrow( /invoked without branded object/, ); }); it('fails if the instance is already present', () => { const a = brandInstance(O, { a: 'a' }); const b = brandInstance(O, { b: 'b' }); expect(() => container.addInstances(a, b)).toThrow(/this ID is already in the container/); }); it('adds instance', () => { const instance = { a: 'a' }; const a = brandInstance(O, instance); container.addInstances(a); expect(container.get(O)).toBe(instance); }); }); describe('instantiate', () => { it('can instantiate three classes A,B,C', () => { container.instantiate(AImpl, BImpl, CImpl); const cInstance = container.get(C); expect(cInstance.c()).toBe('C(B(a), a)'); }); it('instantiates dependencies in multiple instantiate calls', () => { container.instantiate(AImpl); // the order is important for this test // we want to make sure that the stack in circular dependency discovery is being cleared // to try why this order is necessary, remove the `inStack.delete()` from // the `if (!cwd && instanceIds.includes(id))` condition in prod code expect(() => container.instantiate(CImpl, BImpl)).not.toThrow(); }); it('detects duplicate ids', () => { @Injectable(A, []) 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: - src/tests/fixtures/intent/ruby_comments.rb:16" You are a code assistant,Definition of 'WebViewInitialStateInterface' in file packages/webview_duo_chat/src/contract.ts in project gitlab-lsp,"Definition: export interface WebViewInitialStateInterface { slashCommands: GitlabChatSlashCommand[]; } export type Messages = CreatePluginMessageMap<{ pluginToWebview: { notifications: { newRecord: Record; updateRecord: Record; setLoadingState: boolean; cleanChat: undefined; }; }; webviewToPlugin: { notifications: { onReady: undefined; cleanChat: undefined; newPrompt: { record: { content: string; }; }; trackFeedback: { data?: { extendedTextFeedback: string | null; feedbackChoices: Array | null; }; }; }; }; pluginToExtension: { notifications: { showErrorMessage: { message: string; }; }; }; }>; References:" You are a code assistant,Definition of 'deleteFile' in file src/common/advanced_context/lru_cache.ts in project gitlab-lsp,"Definition: deleteFile(uri: DocumentUri): boolean { return this.#cache.delete(uri); } /** * Get the most recently accessed files in the workspace * @param context - The current document context `IDocContext` * @param includeCurrentFile - Include the current file in the list of most recent files, default is `true` */ mostRecentFiles({ context, includeCurrentFile = true, }: { context?: IDocContext; includeCurrentFile?: boolean; }): IDocContext[] { const files = Array.from(this.#cache.values()); if (includeCurrentFile) { return files; } return files.filter( (file) => context?.workspaceFolder?.uri === file.workspaceFolder?.uri && file.uri !== context?.uri, ); } } References:" You are a code assistant,Definition of 'success' in file src/common/circuit_breaker/exponential_backoff_circuit_breaker.ts in project gitlab-lsp,"Definition: 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) }; } #getBackoffTime() { return Math.min( this.#initialBackoffMs * this.#backoffMultiplier ** (this.#errorCount - 1), this.#maxBackoffMs, ); } } References:" You are a code assistant,Definition of 'DO_NOT_SHOW_CODE_SUGGESTIONS_VERSION_WARNING' in file packages/webview_duo_chat/src/plugin/port/constants.ts in project gitlab-lsp,"Definition: export const DO_NOT_SHOW_CODE_SUGGESTIONS_VERSION_WARNING = 'DO_NOT_SHOW_VERSION_WARNING'; // NOTE: This needs to _always_ be a 3 digits export const MINIMUM_CODE_SUGGESTIONS_VERSION = '16.8.0'; export const DO_NOT_SHOW_VERSION_WARNING = 'DO_NOT_SHOW_VERSION_WARNING'; // NOTE: This needs to _always_ be a 3 digits 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 'AiContextManager' in file src/common/ai_context_management_2/ai_context_manager.ts in project gitlab-lsp,"Definition: export const AiContextManager = createInterfaceId('AiContextManager'); @Injectable(AiContextManager, [AiContextFileRetriever]) export class DefaultAiContextManager { #fileRetriever: AiContextFileRetriever; constructor(fileRetriever: AiContextFileRetriever) { this.#fileRetriever = fileRetriever; } #items: Map = new Map(); addItem(item: AiContextItem): boolean { if (this.#items.has(item.id)) { return false; } this.#items.set(item.id, item); return true; } removeItem(id: string): boolean { return this.#items.delete(id); } getItem(id: string): AiContextItem | undefined { return this.#items.get(id); } currentItems(): AiContextItem[] { return Array.from(this.#items.values()); } async retrieveItems(): Promise { const items = Array.from(this.#items.values()); log.info(`Retrieving ${items.length} items`); const retrievedItems = await Promise.all( items.map(async (item) => { try { switch (item.type) { case 'file': { const content = await this.#fileRetriever.retrieve(item); return content ? { ...item, content } : null; } default: throw new Error(`Unknown item type: ${item.type}`); } } catch (error) { log.error(`Failed to retrieve item ${item.id}`, error); return null; } }), ); return retrievedItems.filter((item) => item !== null); } } References: - src/common/connection_service.ts:67 - src/common/connection_service.ts:57" You are a code assistant,Definition of 'CreateWorkflowResponse' in file src/node/duo_workflow/desktop_workflow_runner.ts in project gitlab-lsp,"Definition: interface CreateWorkflowResponse { id: string; } const DuoWorkflowAPIService = createInterfaceId('WorkflowAPI'); @Injectable(DuoWorkflowAPIService, [ConfigService, LsFetch, GitLabApiClient]) export class DesktopWorkflowRunner implements WorkflowAPI { #dockerSocket?: string; #folders?: WorkspaceFolder[]; #fetch: LsFetch; #api: GitLabApiClient; #projectPath: string | undefined; constructor(configService: ConfigService, fetch: LsFetch, api: GitLabApiClient) { this.#fetch = fetch; this.#api = api; configService.onConfigChange((config) => this.#reconfigure(config)); } #reconfigure(config: IConfig) { this.#dockerSocket = config.client.duoWorkflowSettings?.dockerSocket; this.#folders = config.client.workspaceFolders || []; this.#projectPath = config.client.projectPath; } async runWorkflow(goal: string, image: string): Promise { if (!this.#dockerSocket) { throw new Error('Docker socket not configured'); } if (!this.#folders || this.#folders.length === 0) { throw new Error('No workspace folders'); } const executorPath = path.join( __dirname, `../vendor/duo_workflow_executor-${WORKFLOW_EXECUTOR_VERSION}.tar.gz`, ); await this.#downloadWorkflowExecutor(executorPath); const folderName = this.#folders[0].uri.replace(/^file:\/\//, ''); if (this.#folders.length > 0) { log.info(`More than one workspace folder detected. Using workspace folder ${folderName}`); } const workflowID = await this.#createWorkflow(); const workflowToken = await this.#getWorkflowToken(); const containerOptions = { Image: image, Cmd: [ '/duo-workflow-executor', `--workflow-id=${workflowID}`, '--server', workflowToken.duo_workflow_service.base_url || 'localhost:50052', '--goal', goal, '--base-url', workflowToken.gitlab_rails.base_url, '--token', workflowToken.gitlab_rails.token, '--duo-workflow-service-token', workflowToken.duo_workflow_service.token, '--realm', workflowToken.duo_workflow_service.headers['X-Gitlab-Realm'], '--user-id', workflowToken.duo_workflow_service.headers['X-Gitlab-Global-User-Id'], ], HostConfig: { Binds: [`${folderName}:/workspace`], }, }; // Create a container const createResponse = JSON.parse( await this.#makeRequest('/v1.43/containers/create', 'POST', JSON.stringify(containerOptions)), ); // Check if Id in createResponse if (!createResponse.Id) { throw new Error('Failed to create container: No Id in response'); } const containerID = createResponse.Id; // Copy the executor into the container await this.#copyExecutor(containerID, executorPath); // Start the container await this.#makeRequest(`/v1.43/containers/${containerID}/start`, 'POST', ''); return workflowID; } async #copyExecutor(containerID: string, executorPath: string) { const fileContents = await readFile(executorPath); await this.#makeRequest( `/v1.43/containers/${containerID}/archive?path=/`, 'PUT', fileContents, 'application/x-tar', ); } #makeRequest( apiPath: string, method: string, data: string | Buffer, contentType = 'application/json', ): Promise { return new Promise((resolve, reject) => { if (!this.#dockerSocket) { throw new Error('Docker socket not set'); } const options: http.RequestOptions = { socketPath: this.#dockerSocket, path: apiPath, method, headers: { 'Content-Type': contentType, 'Content-Length': Buffer.byteLength(data), }, }; const callback = (res: http.IncomingMessage) => { res.setEncoding('utf-8'); res.on('data', (content) => resolve(content)); res.on('error', (err) => reject(err)); res.on('end', () => { resolve(''); }); }; const clientRequest = http.request(options, callback); clientRequest.write(data); clientRequest.end(); }); } async #downloadWorkflowExecutor(executorPath: string): Promise { try { await readFile(executorPath); } catch (error) { log.info('Downloading workflow executor...'); await this.#downloadFile(executorPath); } } async #downloadFile(outputPath: string): Promise { const response = await this.#fetch.fetch(WORKFLOW_EXECUTOR_DOWNLOAD_PATH, { method: 'GET', headers: { 'Content-Type': 'application/octet-stream', }, }); if (!response.ok) { throw new Error(`Failed to download file: ${response.statusText}`); } const buffer = await response.arrayBuffer(); await writeFile(outputPath, Buffer.from(buffer)); } async #createWorkflow(): Promise { const response = await this.#api?.fetchFromApi({ type: 'rest', method: 'POST', path: '/ai/duo_workflows/workflows', body: { project_id: this.#projectPath, }, supportedSinceInstanceVersion: { resourceName: 'create a workflow', version: '17.3.0', }, }); if (!response) { throw new Error('Failed to create workflow'); } return response.id; } async #getWorkflowToken(): Promise { const token = await this.#api?.fetchFromApi({ type: 'rest', method: 'POST', path: '/ai/duo_workflows/direct_access', supportedSinceInstanceVersion: { resourceName: 'get workflow direct access', version: '17.3.0', }, }); if (!token) { throw new Error('Failed to get workflow token'); } return token; } } References:" You are a code assistant,Definition of 'account' in file packages/webview_duo_chat/src/plugin/port/test_utils/entities.ts in project gitlab-lsp,"Definition: export const account: Account = { username: 'foobar', id: 'foobar', type: 'token', instanceUrl: 'gitlab-instance.xx', token: 'foobar-token', }; export const createFakeCable = () => createFakePartial({ subscribe: jest.fn(), disconnect: jest.fn(), }); export const gitlabPlatformForAccount: GitLabPlatformForAccount = { type: 'account', account, project: undefined, fetchFromApi: createFakeFetchFromApi(), connectToCable: async () => createFakeCable(), getUserAgentHeader: () => ({}), }; References:" You are a code assistant,Definition of 'isEnabled' in file src/common/tracking/instance_tracker.ts in project gitlab-lsp,"Definition: isEnabled(): boolean { return Boolean(this.#options.enabled); } public setCodeSuggestionsContext( uniqueTrackingId: string, context: Partial, ) { if (this.#circuitBreaker.isOpen()) { return; } const { language, isStreaming } = context; // 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); this.#codeSuggestionsContextMap.set(uniqueTrackingId, { is_streaming: isStreaming, language, timestamp: new Date().toISOString(), }); if (this.#isStreamingSuggestion(uniqueTrackingId)) return; this.#codeSuggestionStates.set(uniqueTrackingId, TRACKING_EVENTS.REQUESTED); this.#trackCodeSuggestionsEvent(TRACKING_EVENTS.REQUESTED, uniqueTrackingId).catch((e) => log.warn('Instance telemetry: Could not track telemetry', e), ); log.debug(`Instance telemetry: New suggestion ${uniqueTrackingId} has been requested`); } async updateCodeSuggestionsContext( uniqueTrackingId: string, contextUpdate: Partial, ) { if (this.#circuitBreaker.isOpen()) { return; } if (this.#isStreamingSuggestion(uniqueTrackingId)) return; const context = this.#codeSuggestionsContextMap.get(uniqueTrackingId); const { model, suggestionOptions, isStreaming } = contextUpdate; if (context) { if (model) { context.language = model.lang ?? null; } if (suggestionOptions?.length) { context.suggestion_size = InstanceTracker.#suggestionSize(suggestionOptions); } if (typeof isStreaming === 'boolean') { context.is_streaming = isStreaming; } this.#codeSuggestionsContextMap.set(uniqueTrackingId, context); } } updateSuggestionState(uniqueTrackingId: string, newState: TRACKING_EVENTS): void { if (this.#circuitBreaker.isOpen()) { return; } if (!this.isEnabled()) return; if (this.#isStreamingSuggestion(uniqueTrackingId)) return; const state = this.#codeSuggestionStates.get(uniqueTrackingId); if (!state) { log.debug(`Instance telemetry: The suggestion with ${uniqueTrackingId} can't be found`); return; } const allowedTransitions = nonStreamingSuggestionStateGraph.get(state); if (!allowedTransitions) { log.debug( `Instance telemetry: The suggestion's ${uniqueTrackingId} state ${state} can't be found in state graph`, ); return; } if (!allowedTransitions.includes(newState)) { log.debug( `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( `Instance telemetry: Conditionally allowing transition to accepted state for ${uniqueTrackingId}`, ); } this.#codeSuggestionStates.set(uniqueTrackingId, newState); this.#trackCodeSuggestionsEvent(newState, uniqueTrackingId).catch((e) => log.warn('Instance telemetry: Could not track telemetry', e), ); log.debug(`Instance telemetry: ${uniqueTrackingId} transisted from ${state} to ${newState}`); } async #trackCodeSuggestionsEvent(eventType: TRACKING_EVENTS, uniqueTrackingId: string) { const event = INSTANCE_TRACKING_EVENTS_MAP[eventType]; if (!event) { return; } try { const { language, suggestion_size } = this.#codeSuggestionsContextMap.get(uniqueTrackingId) ?? {}; await this.#api.fetchFromApi({ type: 'rest', method: 'POST', path: '/usage_data/track_event', body: { event, additional_properties: { unique_tracking_id: uniqueTrackingId, timestamp: new Date().toISOString(), language, suggestion_size, }, }, supportedSinceInstanceVersion: { resourceName: 'track instance telemetry', version: '17.2.0', }, }); this.#circuitBreaker.success(); } catch (error) { if (error instanceof InvalidInstanceVersionError) { if (this.#invalidInstanceMsgLogged) return; this.#invalidInstanceMsgLogged = true; } log.warn(`Instance telemetry: Failed to track event: ${eventType}`, error); this.#circuitBreaker.error(); } } rejectOpenedSuggestions() { log.debug(`Instance Telemetry: Reject all opened suggestions`); this.#codeSuggestionStates.forEach((state, uniqueTrackingId) => { if (endStates.includes(state)) { return; } this.updateSuggestionState(uniqueTrackingId, TRACKING_EVENTS.REJECTED); }); } static #suggestionSize(options: SuggestionOption[]): number { const countLines = (text: string) => (text ? text.split('\n').length : 0); return Math.max(...options.map(({ text }) => countLines(text))); } #isStreamingSuggestion(uniqueTrackingId: string): boolean { return Boolean(this.#codeSuggestionsContextMap.get(uniqueTrackingId)?.is_streaming); } } References:" You are a code assistant,Definition of 'Logger' in file packages/lib_logging/src/types.ts in project gitlab-lsp,"Definition: export interface Logger { debug(e: Error): void; debug(message: string, e?: Error): void; 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: - packages/lib_logging/src/utils/with_prefix.ts:5 - packages/lib_webview/src/setup/plugin/webview_instance_message_bus.ts:35 - src/common/graphql/workflow/service.test.ts:16 - packages/lib_webview_transport_json_rpc/src/utils/with_json_rpc_message_validation.test.ts:7 - packages/webview_duo_chat/src/plugin/port/log.ts:3 - packages/lib_webview/src/setup/transport/setup_transport.ts:38 - src/common/webview/extension/extension_connection_message_bus_provider.ts:32 - src/node/setup_http.ts:24 - src/common/webview/extension/handlers/handle_request_message.ts:6 - src/common/graphql/workflow/service.ts:16 - packages/lib_webview/src/setup/transport/setup_transport.ts:11 - packages/lib_webview/src/setup/plugin/webview_controller.ts:35 - packages/lib_webview_transport_json_rpc/src/json_rpc_connection_transport.ts:44 - src/common/graphql/workflow/service.ts:18 - src/common/webview/extension/extension_connection_message_bus_provider.ts:18 - src/common/webview/extension/handlers/handle_notification_message.ts:6 - packages/lib_webview/src/setup/setup_webview_runtime.ts:14 - packages/lib_webview_transport_socket_io/src/socket_io_webview_transport.ts:38 - packages/lib_webview_client/src/bus/resolve_message_bus.ts:8 - packages/lib_webview_client/src/bus/resolve_message_bus.ts:31 - src/node/setup_http.ts:13 - packages/lib_webview/src/setup/plugin/webview_instance_message_bus.ts:30 - packages/lib_webview_transport_json_rpc/src/json_rpc_connection_transport.ts:36 - packages/lib_logging/src/utils/with_prefix.test.ts:5 - src/common/webview/extension/extension_connection_message_bus_provider.test.ts:10 - packages/lib_webview_transport_json_rpc/src/json_rpc_connection_transport.ts:52 - packages/lib_webview_transport_json_rpc/src/json_rpc_connection_transport.ts:69 - packages/lib_webview_transport_json_rpc/src/json_rpc_connection_transport.ts:28 - packages/lib_webview_transport_socket_io/src/socket_io_webview_transport.ts:32 - packages/lib_webview/src/setup/plugin/setup_plugins.ts:12 - packages/lib_webview/src/setup/plugin/webview_controller.ts:41" You are a code assistant,Definition of 'hasListeners' in file packages/lib_webview/src/events/message_bus.ts in project gitlab-lsp,"Definition: public hasListeners(messageType: K): boolean { return this.#subscriptions.has(messageType); } public listenerCount(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 'setupTransports' in file packages/lib_webview/src/setup/transport/setup_transport.ts in project gitlab-lsp,"Definition: export const setupTransports = ( transports: Transport[], runtimeMessageBus: WebviewRuntimeMessageBus, logger: Logger, ): Disposable => { logger.debug(`Setting up ${transports.length} transports`); const disposables = transports.map((transport) => setupTransport(transport, runtimeMessageBus, logger), ); return { dispose: () => { logger.debug(`Disposing ${disposables.length} transports`); for (const disposable of disposables) { disposable.dispose(); } logger.debug('All transports disposed'); }, }; }; References: - packages/lib_webview/src/setup/setup_webview_runtime.ts:23" You are a code assistant,Definition of 'AdvancedContextResolverFactory' in file src/common/advanced_context/advanced_context_factory.ts in project gitlab-lsp,"Definition: type AdvancedContextResolverFactory = () => AdvancedContextResolver; const advancedContextResolverFactories: AdvancedContextResolverFactory[] = [ OpenTabsResolver.getInstance, ]; export const getAdvancedContext = async ({ documentContext, dependencies: { duoProjectAccessChecker }, }: { documentContext: IDocContext; dependencies: { duoProjectAccessChecker: DuoProjectAccessChecker }; }): Promise => { try { const resolvers = advancedContextResolverFactories.map((factory) => factory()); const resolutions: ContextResolution[] = []; for (const resolver of resolvers) { // eslint-disable-next-line no-await-in-loop for await (const resolution of resolver.buildContext({ documentContext })) { resolutions.push(resolution); } } const filteredResolutions = await filterContextResolutions({ contextResolutions: resolutions, documentContext, dependencies: { duoProjectAccessChecker }, byteSizeLimit: CODE_SUGGESTIONS_REQUEST_BYTE_SIZE_LIMIT, }); log.debug(`Advanced Context Factory: using ${filteredResolutions.length} context resolutions `); return filteredResolutions; } catch (e) { log.error('Advanced Context: Error while getting advanced context', e); return []; } }; /** * Maps `ContextResolution` to the request body format `AdditionalContext`. * Note: We intentionally keep these two separate to avoid coupling the request body * format to the advanced context resolver internal data. */ export function advancedContextToRequestBody( advancedContext: ContextResolution[], ): AdditionalContext[] { return advancedContext.map((ac) => ({ type: ac.type, name: ac.fileRelativePath, content: ac.content, resolution_strategy: ac.strategy, })); } References:" You are a code assistant,Definition of 'notNullOrUndefined' in file src/common/utils/not_null_or_undefined.ts in project gitlab-lsp,"Definition: export function notNullOrUndefined(value: T | null | undefined): value is T { return value !== null && value !== undefined; } References: - src/common/utils/create_query_string.ts:8" You are a code assistant,Definition of 'BaseRestRequest' in file src/common/api_types.ts in project gitlab-lsp,"Definition: interface BaseRestRequest<_TReturnType> { type: 'rest'; /** * 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; headers?: Record; supportedSinceInstanceVersion?: SupportedSinceInstanceVersion; } interface GraphQLRequest<_TReturnType> { type: 'graphql'; query: string; /** Options passed to the GraphQL query */ variables: Record; 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; supportedSinceInstanceVersion?: SupportedSinceInstanceVersion; } export type ApiRequest<_TReturnType> = | GetRequest<_TReturnType> | PostRequest<_TReturnType> | GraphQLRequest<_TReturnType>; export type AdditionalContext = { /** * The type of the context element. Options: `file` or `snippet`. */ type: 'file' | 'snippet'; /** * The name of the context element. A name of the file or a code snippet. */ name: string; /** * The content of the context element. The body of the file or a function. */ content: string; /** * Where the context was derived from */ resolution_strategy: ContextResolution['strategy']; }; // FIXME: Rename to SuggestionOptionText and then rename SuggestionOptionOrStream to SuggestionOption // this refactor can't be done now (2024-05-28) because all the conflicts it would cause with WIP export interface SuggestionOption { index?: number; text: string; uniqueTrackingId: string; lang?: string; } export interface TelemetryRequest { event: string; additional_properties: { unique_tracking_id: string; language?: string; suggestion_size?: number; timestamp: string; }; } References:" You are a code assistant,Definition of 'sendTextDocumentDidChangeFull' in file src/tests/int/lsp_client.ts in project gitlab-lsp,"Definition: public async sendTextDocumentDidChangeFull( uri: string, version: number, text: string, ): Promise { const params = { textDocument: { uri, version, }, contentChanges: [{ text }], }; const request = new NotificationType('textDocument/didChange'); await this.#connection.sendNotification(request, params); } public async sendTextDocumentCompletion( uri: string, line: number, character: number, ): Promise { 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 { await this.#connection.sendNotification(DidChangeDocumentInActiveEditor, uri); } public async getWebviewMetadata(): Promise { const result = await this.#connection.sendRequest( '$/gitlab/webview-metadata', ); return result; } } References:" You are a code assistant,Definition of 'clear' in file packages/lib_webview/src/events/message_bus.ts in project gitlab-lsp,"Definition: public clear(): void { this.#subscriptions.clear(); } public dispose(): void { this.clear(); } } References:" You are a code assistant,Definition of 'handleWebviewCreated' in file packages/lib_webview_transport_json_rpc/src/json_rpc_connection_transport.ts in project gitlab-lsp,"Definition: export const handleWebviewCreated = ( messageEmitter: WebviewTransportEventEmitter, logger?: Logger, ) => withJsonRpcMessageValidation(isWebviewInstanceCreatedEventData, logger, (message) => { messageEmitter.emit('webview_instance_created', message); }); export const handleWebviewDestroyed = ( messageEmitter: WebviewTransportEventEmitter, logger?: Logger, ) => withJsonRpcMessageValidation(isWebviewInstanceDestroyedEventData, logger, (message) => { messageEmitter.emit('webview_instance_destroyed', message); }); export const handleWebviewMessage = ( messageEmitter: WebviewTransportEventEmitter, logger?: Logger, ) => withJsonRpcMessageValidation(isWebviewInstanceMessageEventData, logger, (message) => { messageEmitter.emit('webview_instance_notification_received', message); }); export type JsonRpcConnectionTransportProps = { connection: Connection; logger: Logger; notificationRpcMethod?: string; webviewCreatedRpcMethod?: string; webviewDestroyedRpcMethod?: string; }; export class JsonRpcConnectionTransport implements Transport { #messageEmitter = createWebviewTransportEventEmitter(); #connection: Connection; #notificationChannel: string; #webviewCreatedChannel: string; #webviewDestroyedChannel: string; #logger?: Logger; #disposables: Disposable[] = []; constructor({ connection, logger, notificationRpcMethod: notificationChannel = DEFAULT_NOTIFICATION_RPC_METHOD, webviewCreatedRpcMethod: webviewCreatedChannel = DEFAULT_WEBVIEW_CREATED_RPC_METHOD, webviewDestroyedRpcMethod: webviewDestroyedChannel = DEFAULT_WEBVIEW_DESTROYED_RPC_METHOD, }: JsonRpcConnectionTransportProps) { this.#connection = connection; this.#logger = logger ? withPrefix(logger, LOGGER_PREFIX) : undefined; this.#notificationChannel = notificationChannel; this.#webviewCreatedChannel = webviewCreatedChannel; this.#webviewDestroyedChannel = webviewDestroyedChannel; this.#subscribeToConnection(); } #subscribeToConnection() { const channelToNotificationHandlerMap = { [this.#webviewCreatedChannel]: handleWebviewCreated(this.#messageEmitter, this.#logger), [this.#webviewDestroyedChannel]: handleWebviewDestroyed(this.#messageEmitter, this.#logger), [this.#notificationChannel]: handleWebviewMessage(this.#messageEmitter, this.#logger), }; Object.entries(channelToNotificationHandlerMap).forEach(([channel, handler]) => { const disposable = this.#connection.onNotification(channel, handler); this.#disposables.push(disposable); }); } on( type: K, callback: TransportMessageHandler, ): Disposable { this.#messageEmitter.on(type, callback as WebviewTransportEventEmitterMessages[K]); return { dispose: () => this.#messageEmitter.off(type, callback as WebviewTransportEventEmitterMessages[K]), }; } publish(type: K, payload: MessagesToClient[K]): Promise { if (type === 'webview_instance_notification') { return this.#connection.sendNotification(this.#notificationChannel, payload); } throw new Error(`Unknown message type: ${type}`); } dispose(): void { this.#messageEmitter.removeAllListeners(); this.#disposables.forEach((disposable) => disposable.dispose()); this.#logger?.debug('JsonRpcConnectionTransport disposed'); } } References: - packages/lib_webview_transport_json_rpc/src/json_rpc_connection_transport.ts:91" You are a code assistant,Definition of 'init' in file src/common/notifier.ts in project gitlab-lsp,"Definition: init(notify: NotifyFn): void; } References:" You are a code assistant,Definition of 'DEFAULT_INITIAL_BACKOFF_MS' in file src/common/circuit_breaker/exponential_backoff_circuit_breaker.ts in project gitlab-lsp,"Definition: export const DEFAULT_INITIAL_BACKOFF_MS = 1000; export const DEFAULT_MAX_BACKOFF_MS = 60000; export const DEFAULT_BACKOFF_MULTIPLIER = 2; export interface ExponentialBackoffCircuitBreakerOptions { maxErrorsBeforeBreaking?: number; initialBackoffMs?: number; maxBackoffMs?: number; backoffMultiplier?: number; } export class ExponentialBackoffCircuitBreaker implements CircuitBreaker { #name: string; #state: CircuitBreakerState = CircuitBreakerState.CLOSED; readonly #initialBackoffMs: number; readonly #maxBackoffMs: number; readonly #backoffMultiplier: number; #errorCount = 0; #eventEmitter = new EventEmitter(); #timeoutId: NodeJS.Timeout | null = null; constructor( name: string, { initialBackoffMs = DEFAULT_INITIAL_BACKOFF_MS, maxBackoffMs = DEFAULT_MAX_BACKOFF_MS, backoffMultiplier = DEFAULT_BACKOFF_MULTIPLIER, }: ExponentialBackoffCircuitBreakerOptions = {}, ) { this.#name = name; this.#initialBackoffMs = initialBackoffMs; this.#maxBackoffMs = maxBackoffMs; this.#backoffMultiplier = backoffMultiplier; } error() { this.#errorCount += 1; this.#open(); } megaError() { this.#errorCount += 3; this.#open(); } #open() { if (this.#state === CircuitBreakerState.OPEN) { return; } this.#state = CircuitBreakerState.OPEN; log.warn( `Excess errors detected, opening '${this.#name}' circuit breaker for ${this.#getBackoffTime() / 1000} second(s).`, ); this.#timeoutId = setTimeout(() => this.#close(), this.#getBackoffTime()); this.#eventEmitter.emit('open'); } #close() { if (this.#state === CircuitBreakerState.CLOSED) { return; } if (this.#timeoutId) { clearTimeout(this.#timeoutId); } this.#state = CircuitBreakerState.CLOSED; this.#eventEmitter.emit('close'); } isOpen() { return this.#state === CircuitBreakerState.OPEN; } 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) }; } #getBackoffTime() { return Math.min( this.#initialBackoffMs * this.#backoffMultiplier ** (this.#errorCount - 1), this.#maxBackoffMs, ); } } References:" You are a code assistant,Definition of 'GitLabApiClient' in file src/common/api.ts in project gitlab-lsp,"Definition: export interface GitLabApiClient { checkToken(token: string | undefined): Promise; getCodeSuggestions(request: CodeSuggestionRequest): Promise; getStreamingCodeSuggestions(request: CodeSuggestionRequest): AsyncGenerator; fetchFromApi(request: ApiRequest): Promise; connectToCable(): Promise; onApiReconfigured(listener: (data: ApiReconfiguredData) => void): Disposable; readonly instanceVersion?: string; } export const GitLabApiClient = createInterfaceId('GitLabApiClient'); export type GenerationType = 'comment' | 'small_file' | 'empty_function' | undefined; export interface CodeSuggestionRequest { prompt_version: number; project_path: string; model_provider?: string; project_id: number; current_file: CodeSuggestionRequestCurrentFile; intent?: 'completion' | 'generation'; stream?: boolean; /** how many suggestion options should the API return */ choices_count?: number; /** additional context to provide to the model */ context?: AdditionalContext[]; /* A user's instructions for code suggestions. */ user_instruction?: string; /* The backend can add additional prompt info based on the type of event */ generation_type?: GenerationType; } export interface CodeSuggestionRequestCurrentFile { file_name: string; content_above_cursor: string; content_below_cursor: string; } export interface CodeSuggestionResponse { choices?: SuggestionOption[]; model?: ICodeSuggestionModel; status: number; error?: string; isDirectConnection?: boolean; } // FIXME: Rename to SuggestionOptionStream when renaming the SuggestionOption export interface StartStreamOption { uniqueTrackingId: string; /** the streamId represents the beginning of a stream * */ streamId: string; } export type SuggestionOptionOrStream = SuggestionOption | StartStreamOption; export interface PersonalAccessToken { name: string; scopes: string[]; active: boolean; } export interface OAuthToken { scope: string[]; } export interface TokenCheckResponse { valid: boolean; reason?: 'unknown' | 'not_active' | 'invalid_scopes'; message?: string; } export interface IDirectConnectionDetailsHeaders { 'X-Gitlab-Global-User-Id': string; 'X-Gitlab-Instance-Id': string; 'X-Gitlab-Host-Name': string; 'X-Gitlab-Saas-Duo-Pro-Namespace-Ids': string; } export interface IDirectConnectionModelDetails { model_provider: string; model_name: string; } export interface IDirectConnectionDetails { base_url: string; token: string; expires_at: number; headers: IDirectConnectionDetailsHeaders; model_details: IDirectConnectionModelDetails; } const CONFIG_CHANGE_EVENT_NAME = 'apiReconfigured'; @Injectable(GitLabApiClient, [LsFetch, ConfigService]) export class GitLabAPI implements GitLabApiClient { #token: string | undefined; #baseURL: string; #clientInfo?: IClientInfo; #lsFetch: LsFetch; #eventEmitter = new EventEmitter(); #configService: ConfigService; #instanceVersion?: string; constructor(lsFetch: LsFetch, configService: ConfigService) { this.#baseURL = GITLAB_API_BASE_URL; this.#lsFetch = lsFetch; this.#configService = configService; this.#configService.onConfigChange(async (config) => { this.#clientInfo = configService.get('client.clientInfo'); this.#lsFetch.updateAgentOptions({ ignoreCertificateErrors: this.#configService.get('client.ignoreCertificateErrors') ?? false, ...(this.#configService.get('client.httpAgentOptions') ?? {}), }); await this.configureApi(config.client); }); } onApiReconfigured(listener: (data: ApiReconfiguredData) => void): Disposable { this.#eventEmitter.on(CONFIG_CHANGE_EVENT_NAME, listener); return { dispose: () => this.#eventEmitter.removeListener(CONFIG_CHANGE_EVENT_NAME, listener) }; } #fireApiReconfigured(isInValidState: boolean, validationMessage?: string) { const data: ApiReconfiguredData = { isInValidState, validationMessage }; this.#eventEmitter.emit(CONFIG_CHANGE_EVENT_NAME, data); } async configureApi({ token, baseUrl = GITLAB_API_BASE_URL, }: { token?: string; baseUrl?: string; }) { if (this.#token === token && this.#baseURL === baseUrl) return; this.#token = token; this.#baseURL = baseUrl; const { valid, reason, message } = await this.checkToken(this.#token); let validationMessage; if (!valid) { this.#configService.set('client.token', undefined); validationMessage = `Token is invalid. ${message}. Reason: ${reason}`; log.warn(validationMessage); } else { log.info('Token is valid'); } this.#instanceVersion = await this.#getGitLabInstanceVersion(); this.#fireApiReconfigured(valid, validationMessage); } #looksLikePatToken(token: string): boolean { // OAuth tokens will be longer than 42 characters and PATs will be shorter. return token.length < 42; } async #checkPatToken(token: string): Promise { const headers = this.#getDefaultHeaders(token); const response = await this.#lsFetch.get( `${this.#baseURL}/api/v4/personal_access_tokens/self`, { headers }, ); await handleFetchError(response, 'Information about personal access token'); const { active, scopes } = (await response.json()) as PersonalAccessToken; if (!active) { return { valid: false, reason: 'not_active', message: 'Token is not active.', }; } if (!this.#hasValidScopes(scopes)) { const joinedScopes = scopes.map((scope) => `'${scope}'`).join(', '); return { valid: false, reason: 'invalid_scopes', message: `Token has scope(s) ${joinedScopes} (needs 'api').`, }; } return { valid: true }; } async #checkOAuthToken(token: string): Promise { const headers = this.#getDefaultHeaders(token); const response = await this.#lsFetch.get(`${this.#baseURL}/oauth/token/info`, { headers, }); await handleFetchError(response, 'Information about OAuth token'); const { scope: scopes } = (await response.json()) as OAuthToken; if (!this.#hasValidScopes(scopes)) { const joinedScopes = scopes.map((scope) => `'${scope}'`).join(', '); return { valid: false, reason: 'invalid_scopes', message: `Token has scope(s) ${joinedScopes} (needs 'api').`, }; } return { valid: true }; } async checkToken(token: string = ''): Promise { try { if (this.#looksLikePatToken(token)) { log.info('Checking token for PAT validity'); return await this.#checkPatToken(token); } log.info('Checking token for OAuth validity'); return await this.#checkOAuthToken(token); } catch (err) { log.error('Error performing token check', err); return { valid: false, reason: 'unknown', message: `Failed to check token: ${err}`, }; } } #hasValidScopes(scopes: string[]): boolean { return scopes.includes('api'); } async getCodeSuggestions( request: CodeSuggestionRequest, ): Promise { if (!this.#token) { throw new Error('Token needs to be provided to request Code Suggestions'); } const headers = { ...this.#getDefaultHeaders(this.#token), 'Content-Type': 'application/json', }; const response = await this.#lsFetch.post( `${this.#baseURL}/api/v4/code_suggestions/completions`, { headers, body: JSON.stringify(request) }, ); await handleFetchError(response, 'Code Suggestions'); const data = await response.json(); return { ...data, status: response.status }; } async *getStreamingCodeSuggestions( request: CodeSuggestionRequest, ): AsyncGenerator { if (!this.#token) { throw new Error('Token needs to be provided to stream code suggestions'); } const headers = { ...this.#getDefaultHeaders(this.#token), 'Content-Type': 'application/json', }; yield* this.#lsFetch.streamFetch( `${this.#baseURL}/api/v4/code_suggestions/completions`, JSON.stringify(request), headers, ); } async fetchFromApi(request: ApiRequest): Promise { if (!this.#token) { return Promise.reject(new Error('Token needs to be provided to authorise API request.')); } if ( request.supportedSinceInstanceVersion && !this.#instanceVersionHigherOrEqualThen(request.supportedSinceInstanceVersion.version) ) { return Promise.reject( new InvalidInstanceVersionError( `Can't ${request.supportedSinceInstanceVersion.resourceName} until your instance is upgraded to ${request.supportedSinceInstanceVersion.version} or higher.`, ), ); } if (request.type === 'graphql') { return this.#graphqlRequest(request.query, request.variables); } switch (request.method) { case 'GET': return this.#fetch(request.path, request.searchParams, 'resource', request.headers); case 'POST': return this.#postFetch(request.path, 'resource', request.body, request.headers); default: // the type assertion is necessary because TS doesn't expect any other types throw new Error(`Unknown request type ${(request as ApiRequest).type}`); } } async connectToCable(): Promise { const headers = this.#getDefaultHeaders(this.#token); const websocketOptions = { headers: { ...headers, Origin: this.#baseURL, }, }; return connectToCable(this.#baseURL, websocketOptions); } async #graphqlRequest( document: RequestDocument, variables?: V, ): Promise { const ensureEndsWithSlash = (url: string) => url.replace(/\/?$/, '/'); const endpoint = new URL('./api/graphql', ensureEndsWithSlash(this.#baseURL)).href; // supports GitLab instances that are on a custom path, e.g. ""https://example.com/gitlab"" const graphqlFetch = async ( input: RequestInfo | URL, init?: RequestInit, ): Promise => { const url = input instanceof URL ? input.toString() : input; return this.#lsFetch.post(url, { ...init, headers: { ...headers, ...init?.headers }, }); }; const headers = this.#getDefaultHeaders(this.#token); const client = new GraphQLClient(endpoint, { headers, fetch: graphqlFetch, }); return client.request(document, variables); } async #fetch( apiResourcePath: string, query: Record = {}, resourceName = 'resource', headers?: Record, ): Promise { const url = `${this.#baseURL}/api/v4${apiResourcePath}${createQueryString(query)}`; const result = await this.#lsFetch.get(url, { headers: { ...this.#getDefaultHeaders(this.#token), ...headers }, }); await handleFetchError(result, resourceName); return result.json() as Promise; } async #postFetch( apiResourcePath: string, resourceName = 'resource', body?: unknown, headers?: Record, ): Promise { const url = `${this.#baseURL}/api/v4${apiResourcePath}`; const response = await this.#lsFetch.post(url, { headers: { 'Content-Type': 'application/json', ...this.#getDefaultHeaders(this.#token), ...headers, }, body: JSON.stringify(body), }); await handleFetchError(response, resourceName); return response.json() as Promise; } #getDefaultHeaders(token?: string) { return { Authorization: `Bearer ${token}`, 'User-Agent': `code-completions-language-server-experiment (${this.#clientInfo?.name}:${this.#clientInfo?.version})`, 'X-Gitlab-Language-Server-Version': getLanguageServerVersion(), }; } #instanceVersionHigherOrEqualThen(version: string): boolean { if (!this.#instanceVersion) return false; return semverCompare(this.#instanceVersion, version) >= 0; } async #getGitLabInstanceVersion(): Promise { if (!this.#token) { return ''; } const headers = this.#getDefaultHeaders(this.#token); const response = await this.#lsFetch.get(`${this.#baseURL}/api/v4/version`, { headers, }); const { version } = await response.json(); return version; } get instanceVersion() { return this.#instanceVersion; } } References: - src/common/feature_flags.ts:49 - src/common/connection.ts:23 - packages/webview_duo_chat/src/plugin/chat_platform_manager.ts:12 - src/common/tracking/snowplow_tracker.ts:133 - src/common/suggestion_client/default_suggestion_client.test.ts:20 - src/common/suggestion_client/direct_connection_client.test.ts:23 - src/common/suggestion/streaming_handler.test.ts:30 - src/common/suggestion_client/direct_connection_client.ts:54 - src/common/tracking/snowplow_tracker.ts:162 - packages/webview_duo_chat/src/plugin/chat_platform.ts:16 - src/node/duo_workflow/desktop_workflow_runner.ts:49 - src/common/graphql/workflow/service.ts:14 - src/common/tracking/instance_tracker.ts:31 - src/common/feature_flags.test.ts:12 - src/common/core/handlers/token_check_notifier.ts:14 - src/node/duo_workflow/desktop_workflow_runner.ts:53 - src/common/suggestion/streaming_handler.ts:36 - src/common/core/handlers/token_check_notifier.test.ts:7 - packages/webview_duo_chat/src/plugin/chat_platform_manager.ts:10 - src/common/suggestion/suggestion_service.ts:119 - packages/webview_duo_chat/src/plugin/index.ts:9 - src/common/suggestion_client/direct_connection_client.ts:28 - src/common/suggestion/suggestion_service.ts:79 - packages/webview_duo_chat/src/plugin/chat_platform.ts:14 - src/common/feature_flags.ts:43 - src/common/graphql/workflow/service.test.ts:15 - src/common/suggestion_client/default_suggestion_client.ts:8 - src/common/services/duo_access/project_access_cache.ts:94 - src/common/suggestion_client/default_suggestion_client.ts:6 - src/common/graphql/workflow/service.ts:18 - src/common/tracking/instance_tracker.ts:51" You are a code assistant,Definition of 'ExtensionMessage' in file src/common/webview/extension/utils/extension_message.ts in project gitlab-lsp,"Definition: export type ExtensionMessage = { webviewId: WebviewId; type: string; payload: unknown; }; export const isExtensionMessage = (message: unknown): message is ExtensionMessage => { return ( typeof message === 'object' && message !== null && 'webviewId' in message && 'type' in message ); }; References:" You are a code assistant,Definition of 'Greet3' in file src/tests/fixtures/intent/empty_function/python.py in project gitlab-lsp,"Definition: class Greet3: References: - src/tests/fixtures/intent/empty_function/ruby.rb:34" You are a code assistant,Definition of 'rejectOpenedSuggestions' in file src/common/tracking/snowplow_tracker.ts in project gitlab-lsp,"Definition: 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 'DefaultConnectionService' in file src/common/connection_service.ts in project gitlab-lsp,"Definition: 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(method: NotificationType, notifier: Notifier) { 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 'WebviewPlugin' in file packages/lib_webview_plugin/src/webview_plugin.ts in project gitlab-lsp,"Definition: export type WebviewPlugin< TWebviewPluginMessageMap extends PartialDeep = PluginMessageMap, > = { id: WebviewId; title: string; setup: WebviewPluginSetupFunc>; }; References: - src/common/webview/webview_metadata_provider.test.ts:37 - src/common/webview/webview_metadata_provider.test.ts:42" You are a code assistant,Definition of 'constructor' in file src/common/ai_context_management_2/ai_policy_management.ts in project gitlab-lsp,"Definition: 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:" You are a code assistant,Definition of 'init' in file src/common/security_diagnostics_publisher.ts in project gitlab-lsp,"Definition: 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:" You are a code assistant,Definition of 'handleWorkspaceFileUpdate' in file src/common/git/repository_service.ts in project gitlab-lsp,"Definition: async handleWorkspaceFileUpdate({ fileUri, workspaceFolder, event }: WorkspaceFileUpdate) { const repoUri = this.findMatchingRepositoryUri(fileUri, workspaceFolder); if (!repoUri) { log.debug(`No matching repository found for file ${fileUri.toString()}`); return; } const repositoryMap = this.#getRepositoriesForWorkspace(workspaceFolder.uri); const repository = repositoryMap.get(repoUri.toString()); if (!repository) { log.debug(`Repository not found for URI ${repoUri.toString()}`); return; } if (repository.isFileIgnored(fileUri)) { log.debug(`File ${fileUri.toString()} is ignored`); return; } switch (event) { case 'add': repository.setFile(fileUri); log.debug(`File ${fileUri.toString()} added to repository ${repoUri.toString()}`); break; case 'change': repository.setFile(fileUri); log.debug(`File ${fileUri.toString()} updated in repository ${repoUri.toString()}`); break; case 'unlink': repository.removeFile(fileUri.toString()); log.debug(`File ${fileUri.toString()} removed from repository ${repoUri.toString()}`); break; default: log.warn(`Unknown file event ${event} for file ${fileUri.toString()}`); } } #getRepositoriesForWorkspace(workspaceFolderUri: WorkspaceFolderUri): RepositoryMap { return this.#workspaces.get(workspaceFolderUri) || new Map(); } #emptyRepositoriesForWorkspace(workspaceFolderUri: WorkspaceFolderUri): void { log.debug(`Emptying repositories for workspace ${workspaceFolderUri}`); const repos = this.#workspaces.get(workspaceFolderUri); if (!repos || repos.size === 0) return; // clear up ignore manager trie from memory repos.forEach((repo) => { repo.dispose(); log.debug(`Repository ${repo.uri} has been disposed`); }); repos.clear(); const trie = this.#workspaceRepositoryTries.get(workspaceFolderUri); if (trie) { trie.dispose(); this.#workspaceRepositoryTries.delete(workspaceFolderUri); } this.#workspaces.delete(workspaceFolderUri); log.debug(`Repositories for workspace ${workspaceFolderUri} have been emptied`); } #detectRepositories(files: URI[], workspaceFolder: WorkspaceFolder): Repository[] { const gitConfigFiles = files.filter((file) => file.toString().endsWith('.git/config')); return gitConfigFiles.map((file) => { const projectUri = fsPathToUri(file.path.replace('.git/config', '')); const ignoreManager = new IgnoreManager(projectUri.fsPath); log.info(`Detected repository at ${projectUri.path}`); return new Repository({ ignoreManager, uri: projectUri, configFileUri: file, workspaceFolder, }); }); } getFilesForWorkspace( workspaceFolderUri: WorkspaceFolderUri, options: { excludeGitFolder?: boolean; excludeIgnored?: boolean } = {}, ): RepositoryFile[] { const repositories = this.#getRepositoriesForWorkspace(workspaceFolderUri); const allFiles: RepositoryFile[] = []; repositories.forEach((repository) => { repository.getFiles().forEach((file) => { // apply the filters if (options.excludeGitFolder && this.#isInGitFolder(file.uri, repository.uri)) { return; } if (options.excludeIgnored && file.isIgnored) { return; } allFiles.push(file); }); }); return allFiles; } // Helper method to check if a file is in the .git folder #isInGitFolder(fileUri: URI, repositoryUri: URI): boolean { const relativePath = fileUri.path.slice(repositoryUri.path.length); return relativePath.split('/').some((part) => part === '.git'); } } References:" You are a code assistant,Definition of 'RequestMap' in file packages/lib_message_bus/src/types/bus.ts in project gitlab-lsp,"Definition: export type RequestMap = Record< Method, { params: MessagePayload; result: MessagePayload; } >; type KeysWithOptionalParams = { [K in keyof R]: R[K]['params'] extends undefined ? never : K; }[keyof R]; /** * Extracts the response payload type from a request type. * @template {MessagePayload} T * @typedef {T extends [never] ? void : T[0]} ExtractRequestResponse */ export type ExtractRequestResult = // eslint-disable-next-line @typescript-eslint/no-invalid-void-type T['result'] extends undefined ? void : T; /** * Interface for publishing requests. * @interface * @template {RequestMap} TRequests */ export interface RequestPublisher { sendRequest>( type: T, ): Promise>; sendRequest( type: T, payload: TRequests[T]['params'], ): Promise>; } /** * Interface for listening to requests. * @interface * @template {RequestMap} TRequests */ export interface RequestListener { onRequest>( type: T, handler: () => Promise>, ): Disposable; onRequest( type: T, handler: (payload: TRequests[T]['params']) => Promise>, ): Disposable; } /** * Defines the structure for message definitions, including notifications and requests. */ export type MessageDefinitions< TNotifications extends NotificationMap = NotificationMap, TRequests extends RequestMap = RequestMap, > = { notifications: TNotifications; requests: TRequests; }; export type MessageMap< TInboundMessageDefinitions extends MessageDefinitions = MessageDefinitions, TOutboundMessageDefinitions extends MessageDefinitions = MessageDefinitions, > = { inbound: TInboundMessageDefinitions; outbound: TOutboundMessageDefinitions; }; export interface MessageBus extends NotificationPublisher, NotificationListener, RequestPublisher, RequestListener {} References:" You are a code assistant,Definition of 'sendRequest' in file packages/lib_webview_client/src/bus/provider/socket_io_message_bus.ts in project gitlab-lsp,"Definition: sendRequest( type: T, payload?: TMessages['outbound']['requests'][T]['params'], ): Promise> { const requestId = generateRequestId(); let timeout: NodeJS.Timeout | undefined; return new Promise((resolve, reject) => { const pendingRequestDisposable = this.#pendingRequests.register( requestId, (value: ExtractRequestResult) => { resolve(value); clearTimeout(timeout); pendingRequestDisposable.dispose(); }, ); timeout = setTimeout(() => { pendingRequestDisposable.dispose(); reject(new Error('Request timed out')); }, REQUEST_TIMEOUT_MS); this.#socket.emit(SOCKET_REQUEST_CHANNEL, { requestId, type, payload, }); }); } onNotification( messageType: T, callback: (payload: TMessages['inbound']['notifications'][T]) => void, ): Disposable { return this.#notificationHandlers.register(messageType, callback); } onRequest( type: T, handler: ( payload: TMessages['inbound']['requests'][T]['params'], ) => Promise>, ): Disposable { return this.#requestHandlers.register(type, handler); } dispose() { this.#socket.off(SOCKET_NOTIFICATION_CHANNEL, this.#handleNotificationMessage); this.#socket.off(SOCKET_REQUEST_CHANNEL, this.#handleRequestMessage); this.#socket.off(SOCKET_RESPONSE_CHANNEL, this.#handleResponseMessage); this.#notificationHandlers.dispose(); this.#requestHandlers.dispose(); this.#pendingRequests.dispose(); } #setupSocketEventHandlers = () => { this.#socket.on(SOCKET_NOTIFICATION_CHANNEL, this.#handleNotificationMessage); this.#socket.on(SOCKET_REQUEST_CHANNEL, this.#handleRequestMessage); this.#socket.on(SOCKET_RESPONSE_CHANNEL, this.#handleResponseMessage); }; #handleNotificationMessage = async (message: { type: keyof TMessages['inbound']['notifications'] & string; payload: unknown; }) => { await this.#notificationHandlers.handle(message.type, message.payload); }; #handleRequestMessage = async (message: { requestId: string; event: keyof TMessages['inbound']['requests'] & string; payload: unknown; }) => { const response = await this.#requestHandlers.handle(message.event, message.payload); this.#socket.emit(SOCKET_RESPONSE_CHANNEL, { requestId: message.requestId, payload: response, }); }; #handleResponseMessage = async (message: { requestId: string; payload: unknown }) => { await this.#pendingRequests.handle(message.requestId, message.payload); }; } References:" You are a code assistant,Definition of 'SuggestionOptionOrStream' in file src/common/api.ts in project gitlab-lsp,"Definition: export type SuggestionOptionOrStream = SuggestionOption | StartStreamOption; export interface PersonalAccessToken { name: string; scopes: string[]; active: boolean; } export interface OAuthToken { scope: string[]; } export interface TokenCheckResponse { valid: boolean; reason?: 'unknown' | 'not_active' | 'invalid_scopes'; message?: string; } export interface IDirectConnectionDetailsHeaders { 'X-Gitlab-Global-User-Id': string; 'X-Gitlab-Instance-Id': string; 'X-Gitlab-Host-Name': string; 'X-Gitlab-Saas-Duo-Pro-Namespace-Ids': string; } export interface IDirectConnectionModelDetails { model_provider: string; model_name: string; } export interface IDirectConnectionDetails { base_url: string; token: string; expires_at: number; headers: IDirectConnectionDetailsHeaders; model_details: IDirectConnectionModelDetails; } const CONFIG_CHANGE_EVENT_NAME = 'apiReconfigured'; @Injectable(GitLabApiClient, [LsFetch, ConfigService]) export class GitLabAPI implements GitLabApiClient { #token: string | undefined; #baseURL: string; #clientInfo?: IClientInfo; #lsFetch: LsFetch; #eventEmitter = new EventEmitter(); #configService: ConfigService; #instanceVersion?: string; constructor(lsFetch: LsFetch, configService: ConfigService) { this.#baseURL = GITLAB_API_BASE_URL; this.#lsFetch = lsFetch; this.#configService = configService; this.#configService.onConfigChange(async (config) => { this.#clientInfo = configService.get('client.clientInfo'); this.#lsFetch.updateAgentOptions({ ignoreCertificateErrors: this.#configService.get('client.ignoreCertificateErrors') ?? false, ...(this.#configService.get('client.httpAgentOptions') ?? {}), }); await this.configureApi(config.client); }); } onApiReconfigured(listener: (data: ApiReconfiguredData) => void): Disposable { this.#eventEmitter.on(CONFIG_CHANGE_EVENT_NAME, listener); return { dispose: () => this.#eventEmitter.removeListener(CONFIG_CHANGE_EVENT_NAME, listener) }; } #fireApiReconfigured(isInValidState: boolean, validationMessage?: string) { const data: ApiReconfiguredData = { isInValidState, validationMessage }; this.#eventEmitter.emit(CONFIG_CHANGE_EVENT_NAME, data); } async configureApi({ token, baseUrl = GITLAB_API_BASE_URL, }: { token?: string; baseUrl?: string; }) { if (this.#token === token && this.#baseURL === baseUrl) return; this.#token = token; this.#baseURL = baseUrl; const { valid, reason, message } = await this.checkToken(this.#token); let validationMessage; if (!valid) { this.#configService.set('client.token', undefined); validationMessage = `Token is invalid. ${message}. Reason: ${reason}`; log.warn(validationMessage); } else { log.info('Token is valid'); } this.#instanceVersion = await this.#getGitLabInstanceVersion(); this.#fireApiReconfigured(valid, validationMessage); } #looksLikePatToken(token: string): boolean { // OAuth tokens will be longer than 42 characters and PATs will be shorter. return token.length < 42; } async #checkPatToken(token: string): Promise { const headers = this.#getDefaultHeaders(token); const response = await this.#lsFetch.get( `${this.#baseURL}/api/v4/personal_access_tokens/self`, { headers }, ); await handleFetchError(response, 'Information about personal access token'); const { active, scopes } = (await response.json()) as PersonalAccessToken; if (!active) { return { valid: false, reason: 'not_active', message: 'Token is not active.', }; } if (!this.#hasValidScopes(scopes)) { const joinedScopes = scopes.map((scope) => `'${scope}'`).join(', '); return { valid: false, reason: 'invalid_scopes', message: `Token has scope(s) ${joinedScopes} (needs 'api').`, }; } return { valid: true }; } async #checkOAuthToken(token: string): Promise { const headers = this.#getDefaultHeaders(token); const response = await this.#lsFetch.get(`${this.#baseURL}/oauth/token/info`, { headers, }); await handleFetchError(response, 'Information about OAuth token'); const { scope: scopes } = (await response.json()) as OAuthToken; if (!this.#hasValidScopes(scopes)) { const joinedScopes = scopes.map((scope) => `'${scope}'`).join(', '); return { valid: false, reason: 'invalid_scopes', message: `Token has scope(s) ${joinedScopes} (needs 'api').`, }; } return { valid: true }; } async checkToken(token: string = ''): Promise { try { if (this.#looksLikePatToken(token)) { log.info('Checking token for PAT validity'); return await this.#checkPatToken(token); } log.info('Checking token for OAuth validity'); return await this.#checkOAuthToken(token); } catch (err) { log.error('Error performing token check', err); return { valid: false, reason: 'unknown', message: `Failed to check token: ${err}`, }; } } #hasValidScopes(scopes: string[]): boolean { return scopes.includes('api'); } async getCodeSuggestions( request: CodeSuggestionRequest, ): Promise { if (!this.#token) { throw new Error('Token needs to be provided to request Code Suggestions'); } const headers = { ...this.#getDefaultHeaders(this.#token), 'Content-Type': 'application/json', }; const response = await this.#lsFetch.post( `${this.#baseURL}/api/v4/code_suggestions/completions`, { headers, body: JSON.stringify(request) }, ); await handleFetchError(response, 'Code Suggestions'); const data = await response.json(); return { ...data, status: response.status }; } async *getStreamingCodeSuggestions( request: CodeSuggestionRequest, ): AsyncGenerator { if (!this.#token) { throw new Error('Token needs to be provided to stream code suggestions'); } const headers = { ...this.#getDefaultHeaders(this.#token), 'Content-Type': 'application/json', }; yield* this.#lsFetch.streamFetch( `${this.#baseURL}/api/v4/code_suggestions/completions`, JSON.stringify(request), headers, ); } async fetchFromApi(request: ApiRequest): Promise { if (!this.#token) { return Promise.reject(new Error('Token needs to be provided to authorise API request.')); } if ( request.supportedSinceInstanceVersion && !this.#instanceVersionHigherOrEqualThen(request.supportedSinceInstanceVersion.version) ) { return Promise.reject( new InvalidInstanceVersionError( `Can't ${request.supportedSinceInstanceVersion.resourceName} until your instance is upgraded to ${request.supportedSinceInstanceVersion.version} or higher.`, ), ); } if (request.type === 'graphql') { return this.#graphqlRequest(request.query, request.variables); } switch (request.method) { case 'GET': return this.#fetch(request.path, request.searchParams, 'resource', request.headers); case 'POST': return this.#postFetch(request.path, 'resource', request.body, request.headers); default: // the type assertion is necessary because TS doesn't expect any other types throw new Error(`Unknown request type ${(request as ApiRequest).type}`); } } async connectToCable(): Promise { const headers = this.#getDefaultHeaders(this.#token); const websocketOptions = { headers: { ...headers, Origin: this.#baseURL, }, }; return connectToCable(this.#baseURL, websocketOptions); } async #graphqlRequest( document: RequestDocument, variables?: V, ): Promise { const ensureEndsWithSlash = (url: string) => url.replace(/\/?$/, '/'); const endpoint = new URL('./api/graphql', ensureEndsWithSlash(this.#baseURL)).href; // supports GitLab instances that are on a custom path, e.g. ""https://example.com/gitlab"" const graphqlFetch = async ( input: RequestInfo | URL, init?: RequestInit, ): Promise => { const url = input instanceof URL ? input.toString() : input; return this.#lsFetch.post(url, { ...init, headers: { ...headers, ...init?.headers }, }); }; const headers = this.#getDefaultHeaders(this.#token); const client = new GraphQLClient(endpoint, { headers, fetch: graphqlFetch, }); return client.request(document, variables); } async #fetch( apiResourcePath: string, query: Record = {}, resourceName = 'resource', headers?: Record, ): Promise { const url = `${this.#baseURL}/api/v4${apiResourcePath}${createQueryString(query)}`; const result = await this.#lsFetch.get(url, { headers: { ...this.#getDefaultHeaders(this.#token), ...headers }, }); await handleFetchError(result, resourceName); return result.json() as Promise; } async #postFetch( apiResourcePath: string, resourceName = 'resource', body?: unknown, headers?: Record, ): Promise { const url = `${this.#baseURL}/api/v4${apiResourcePath}`; const response = await this.#lsFetch.post(url, { headers: { 'Content-Type': 'application/json', ...this.#getDefaultHeaders(this.#token), ...headers, }, body: JSON.stringify(body), }); await handleFetchError(response, resourceName); return response.json() as Promise; } #getDefaultHeaders(token?: string) { return { Authorization: `Bearer ${token}`, 'User-Agent': `code-completions-language-server-experiment (${this.#clientInfo?.name}:${this.#clientInfo?.version})`, 'X-Gitlab-Language-Server-Version': getLanguageServerVersion(), }; } #instanceVersionHigherOrEqualThen(version: string): boolean { if (!this.#instanceVersion) return false; return semverCompare(this.#instanceVersion, version) >= 0; } async #getGitLabInstanceVersion(): Promise { if (!this.#token) { return ''; } const headers = this.#getDefaultHeaders(this.#token); const response = await this.#lsFetch.get(`${this.#baseURL}/api/v4/version`, { headers, }); const { version } = await response.json(); return version; } get instanceVersion() { return this.#instanceVersion; } } References: - src/common/utils/suggestion_mappers.ts:13 - src/common/utils/suggestion_mappers.ts:15" You are a code assistant,Definition of 'TreeSitterLanguageName' in file src/common/tree_sitter/languages.ts in project gitlab-lsp,"Definition: export type TreeSitterLanguageName = | 'bash' | 'c' | 'cpp' | 'c_sharp' | 'css' | 'go' | 'html' | 'java' | 'javascript' | 'json' | 'kotlin' | 'powershell' | 'python' | 'ruby' | 'rust' | 'scala' | 'typescript' | 'tsx' | 'vue' | 'yaml'; export interface TreeSitterLanguageInfo { name: TreeSitterLanguageName; extensions: string[]; wasmPath: string; nodeModulesPath?: string; } References: - src/common/tree_sitter/comments/comment_resolver.ts:53 - src/common/tree_sitter/empty_function/empty_function_resolver.ts:15 - src/common/tree_sitter/empty_function/empty_function_resolver.ts:125 - src/common/tree_sitter/comments/comment_resolver.ts:25 - src/common/tree_sitter/empty_function/empty_function_resolver.ts:44 - src/common/tree_sitter/comments/comment_resolver.ts:140 - src/common/tree_sitter/comments/comment_resolver.test.ts:242 - src/common/tree_sitter/languages.ts:24" You are a code assistant,Definition of 'ISnowplowClientContext' in file src/common/tracking/snowplow_tracker.ts in project gitlab-lsp,"Definition: interface ISnowplowClientContext { schema: string; data: { ide_name?: string | null; ide_vendor?: string | null; ide_version?: string | null; extension_name?: string | null; extension_version?: string | null; language_server_version?: string | null; }; } const DEFAULT_SNOWPLOW_OPTIONS = { appId: 'gitlab_ide_extension', timeInterval: 5000, maxItems: 10, }; export const EVENT_VALIDATION_ERROR_MSG = `Telemetry event context is not valid - event won't be tracked.`; 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(); #lsFetch: LsFetch; #featureFlagService: FeatureFlagService; #gitlabRealm: GitlabRealm = GitlabRealm.saas; #codeSuggestionsContextMap = new Map(); 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, ) { 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, ) { 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/common/tracking/snowplow_tracker.ts:143" You are a code assistant,Definition of 'GITLAB_COM_URL' in file packages/webview_duo_chat/src/plugin/port/chat/get_platform_manager_for_chat.ts in project gitlab-lsp,"Definition: export const GITLAB_COM_URL: string = 'https://gitlab.com'; export const GITLAB_STAGING_URL: string = 'https://staging.gitlab.com'; export const GITLAB_ORG_URL: string = 'https://dev.gitlab.org'; export const GITLAB_DEVELOPMENT_URL: string = 'http://localhost'; export enum GitLabEnvironment { GITLAB_COM = 'production', GITLAB_STAGING = 'staging', GITLAB_ORG = 'org', GITLAB_DEVELOPMENT = 'development', GITLAB_SELF_MANAGED = 'self-managed', } export class GitLabPlatformManagerForChat { readonly #platformManager: GitLabPlatformManager; constructor(platformManager: GitLabPlatformManager) { this.#platformManager = platformManager; } async getProjectGqlId(): Promise { const projectManager = await this.#platformManager.getForActiveProject(false); return projectManager?.project.gqlId; } /** * Obtains a GitLab Platform to send API requests to the GitLab API * for the Duo Chat feature. * * - It returns a GitLabPlatformForAccount for the first linked account. * - It returns undefined if there are no accounts linked */ async getGitLabPlatform(): Promise { const platforms = await this.#platformManager.getForAllAccounts(); if (!platforms.length) { return undefined; } let platform: GitLabPlatformForAccount | undefined; // Using a for await loop in this context because we want to stop // evaluating accounts as soon as we find one with code suggestions enabled for await (const result of platforms.map(getChatSupport)) { if (result.hasSupportForChat) { platform = result.platform; break; } } return platform; } async getGitLabEnvironment(): Promise { const platform = await this.getGitLabPlatform(); const instanceUrl = platform?.account.instanceUrl; switch (instanceUrl) { case GITLAB_COM_URL: return GitLabEnvironment.GITLAB_COM; case GITLAB_DEVELOPMENT_URL: return GitLabEnvironment.GITLAB_DEVELOPMENT; case GITLAB_STAGING_URL: return GitLabEnvironment.GITLAB_STAGING; case GITLAB_ORG_URL: return GitLabEnvironment.GITLAB_ORG; default: return GitLabEnvironment.GITLAB_SELF_MANAGED; } } } References:" You are a code assistant,Definition of 'subscribe' in file packages/lib_webview/src/events/message_bus.ts in project gitlab-lsp,"Definition: public subscribe( messageType: K, listener: Listener, filter?: FilterFunction, ): Disposable { const subscriptions = this.#subscriptions.get(messageType) ?? new Set>(); const subscription: Subscription = { listener: listener as Listener, filter: filter as FilterFunction | undefined, }; subscriptions.add(subscription); this.#subscriptions.set(messageType, subscriptions); return { dispose: () => { const targetSubscriptions = this.#subscriptions.get(messageType); if (targetSubscriptions) { targetSubscriptions.delete(subscription); if (targetSubscriptions.size === 0) { this.#subscriptions.delete(messageType); } } }, }; } public publish(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; if (!filter || filter(data)) { listener(data); } }); } } public hasListeners(messageType: K): boolean { return this.#subscriptions.has(messageType); } public listenerCount(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 'handleFetchError' in file src/common/handle_fetch_error.ts in project gitlab-lsp,"Definition: export const handleFetchError = async (response: Response, resourceName: string) => { if (!response.ok) { const body = await response.text().catch(() => undefined); throw new FetchError(response, resourceName, body); } }; References: - src/common/api.ts:284 - src/common/api.ts:410 - src/common/api.ts:229 - src/common/handle_fetch_error.test.ts:15 - src/node/fetch.ts:172 - src/common/api.ts:388 - src/common/security_diagnostics_publisher.ts:103 - src/common/handle_fetch_error.test.ts:27 - src/common/suggestion_client/direct_connection_client.ts:117 - src/browser/fetch.ts:24 - src/common/api.ts:198 - src/common/handle_fetch_error.test.ts:37" You are a code assistant,Definition of 'ErrorMessage' in file packages/webview_duo_chat/src/plugin/port/chat/gitlab_chat_api.ts in project gitlab-lsp,"Definition: interface ErrorMessage { type: 'error'; requestId: string; role: 'system'; errors: string[]; } const errorResponse = (requestId: string, errors: string[]): ErrorMessage => ({ requestId, errors, role: 'system', type: 'error', }); interface SuccessMessage { type: 'message'; requestId: string; role: string; content: string; contentHtml: string; timestamp: string; errors: string[]; extras?: { sources: object[]; }; } const successResponse = (response: AiMessageResponseType): SuccessMessage => ({ type: 'message', ...response, }); type AiMessage = SuccessMessage | ErrorMessage; type ChatInputTemplate = { query: string; defaultVariables: { platformOrigin?: string; }; }; export class GitLabChatApi { #cachedActionQuery?: ChatInputTemplate = undefined; #manager: GitLabPlatformManagerForChat; constructor(manager: GitLabPlatformManagerForChat) { this.#manager = manager; } async processNewUserPrompt( question: string, subscriptionId?: string, currentFileContext?: GitLabChatFileContext, ): Promise { return this.#sendAiAction({ question, currentFileContext, clientSubscriptionId: subscriptionId, }); } async pullAiMessage(requestId: string, role: string): Promise { const response = await pullHandler(() => this.#getAiMessage(requestId, role)); if (!response) return errorResponse(requestId, ['Reached timeout while fetching response.']); return successResponse(response); } async cleanChat(): Promise { return this.#sendAiAction({ question: SPECIAL_MESSAGES.CLEAN }); } async #currentPlatform() { const platform = await this.#manager.getGitLabPlatform(); if (!platform) throw new Error('Platform is missing!'); return platform; } async #getAiMessage(requestId: string, role: string): Promise { const request: GraphQLRequest = { type: 'graphql', query: AI_MESSAGES_QUERY, variables: { requestIds: [requestId], roles: [role.toUpperCase()] }, }; const platform = await this.#currentPlatform(); const history = await platform.fetchFromApi(request); return history.aiMessages.nodes[0]; } async subscribeToUpdates( messageCallback: (message: AiCompletionResponseMessageType) => Promise, subscriptionId?: string, ) { const platform = await this.#currentPlatform(); const channel = new AiCompletionResponseChannel({ htmlResponse: true, userId: `gid://gitlab/User/${extractUserId(platform.account.id)}`, aiAction: 'CHAT', clientSubscriptionId: subscriptionId, }); const cable = await platform.connectToCable(); // we use this flag to fix https://gitlab.com/gitlab-org/gitlab-vscode-extension/-/issues/1397 // sometimes a chunk comes after the full message and it broke the chat let fullMessageReceived = false; channel.on('newChunk', async (msg) => { if (fullMessageReceived) { log.info(`CHAT-DEBUG: full message received, ignoring chunk`); return; } await messageCallback(msg); }); channel.on('fullMessage', async (message) => { fullMessageReceived = true; await messageCallback(message); if (subscriptionId) { cable.disconnect(); } }); cable.subscribe(channel); } async #sendAiAction(variables: object): Promise { const platform = await this.#currentPlatform(); const { query, defaultVariables } = await this.#actionQuery(); const projectGqlId = await this.#manager.getProjectGqlId(); const request: GraphQLRequest = { type: 'graphql', query, variables: { ...variables, ...defaultVariables, resourceId: projectGqlId ?? null, }, }; return platform.fetchFromApi(request); } async #actionQuery(): Promise { if (!this.#cachedActionQuery) { const platform = await this.#currentPlatform(); try { const { version } = await platform.fetchFromApi(versionRequest); this.#cachedActionQuery = ifVersionGte( version, MINIMUM_PLATFORM_ORIGIN_FIELD_VERSION, () => CHAT_INPUT_TEMPLATE_17_3_AND_LATER, () => CHAT_INPUT_TEMPLATE_17_2_AND_EARLIER, ); } catch (e) { log.debug(`GitLab version check for sending chat failed:`, e as Error); this.#cachedActionQuery = CHAT_INPUT_TEMPLATE_17_3_AND_LATER; } } return this.#cachedActionQuery; } } References: - packages/webview_duo_chat/src/plugin/port/chat/gitlab_chat_api.ts:113" You are a code assistant,Definition of 'DefaultAiContextManager' in file src/common/ai_context_management_2/ai_context_manager.ts in project gitlab-lsp,"Definition: export class DefaultAiContextManager { #fileRetriever: AiContextFileRetriever; constructor(fileRetriever: AiContextFileRetriever) { this.#fileRetriever = fileRetriever; } #items: Map = new Map(); addItem(item: AiContextItem): boolean { if (this.#items.has(item.id)) { return false; } this.#items.set(item.id, item); return true; } removeItem(id: string): boolean { return this.#items.delete(id); } getItem(id: string): AiContextItem | undefined { return this.#items.get(id); } currentItems(): AiContextItem[] { return Array.from(this.#items.values()); } async retrieveItems(): Promise { const items = Array.from(this.#items.values()); log.info(`Retrieving ${items.length} items`); const retrievedItems = await Promise.all( items.map(async (item) => { try { switch (item.type) { case 'file': { const content = await this.#fileRetriever.retrieve(item); return content ? { ...item, content } : null; } default: throw new Error(`Unknown item type: ${item.type}`); } } catch (error) { log.error(`Failed to retrieve item ${item.id}`, error); return null; } }), ); return retrievedItems.filter((item) => item !== null); } } References:" You are a code assistant,Definition of 'createQueryString' in file src/common/utils/create_query_string.ts in project gitlab-lsp,"Definition: export const createQueryString = (query: Record): string => { const q = new URLSearchParams(); Object.entries(query).forEach(([name, value]) => { if (notNullOrUndefined(value)) { q.set(name, `${value}`); } }); return q.toString() && `?${q}`; }; References: - src/common/api.ts:382" You are a code assistant,Definition of 'greet2' in file src/tests/fixtures/intent/empty_function/ruby.rb in project gitlab-lsp,"Definition: def greet2(name) puts name end greet3 = Proc.new { |name| } greet4 = Proc.new { |name| puts name } greet5 = lambda { |name| } greet6 = lambda { |name| puts name } 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/ruby.rb:4" You are a code assistant,Definition of 'constructor' in file src/common/webview/extension/extension_connection_message_bus.ts in project gitlab-lsp,"Definition: constructor({ webviewId, connection, rpcMethods, handlers }: ExtensionConnectionMessageBusProps) { this.#webviewId = webviewId; this.#connection = connection; this.#rpcMethods = rpcMethods; this.#handlers = handlers; } onRequest( type: T, handler: ( payload: TMessageMap['inbound']['requests'][T]['params'], ) => Promise>, ): Disposable { return this.#handlers.request.register({ webviewId: this.#webviewId, type }, handler); } onNotification( type: T, handler: (payload: TMessageMap['inbound']['notifications'][T]) => void, ): Disposable { return this.#handlers.notification.register({ webviewId: this.#webviewId, type }, handler); } sendRequest( type: T, payload?: TMessageMap['outbound']['requests'][T]['params'], ): Promise> { return this.#connection.sendRequest(this.#rpcMethods.request, { webviewId: this.#webviewId, type, payload, }); } async sendNotification( type: T, payload?: TMessageMap['outbound']['notifications'][T], ): Promise { await this.#connection.sendNotification(this.#rpcMethods.notification, { webviewId: this.#webviewId, type, payload, }); } } References:" You are a code assistant,Definition of 'size' in file packages/lib_handler_registry/src/registry/hashed_registry.ts in project gitlab-lsp,"Definition: 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): Promise> { const hash = this.#hashFunc(key); return this.#basicRegistry.handle(hash, ...args); } dispose() { this.#basicRegistry.dispose(); } } References:" You are a code assistant,Definition of 'setupFileWatcher' in file src/common/services/fs/dir.ts in project gitlab-lsp,"Definition: setupFileWatcher(workspaceFolder: WorkspaceFolder, changeHandler: FileChangeHandler) { throw new Error(`${workspaceFolder} ${changeHandler} not implemented`); } } References:" You are a code assistant,Definition of 'WebviewEventInfo' in file packages/lib_webview_transport/src/types.ts in project gitlab-lsp,"Definition: export type WebviewEventInfo = { type: string; payload?: unknown; }; export type WebviewInstanceCreatedEventData = WebviewAddress; export type WebviewInstanceDestroyedEventData = WebviewAddress; export type WebviewInstanceNotificationEventData = WebviewAddress & WebviewEventInfo; export type WebviewInstanceRequestEventData = WebviewAddress & WebviewEventInfo & WebviewRequestInfo; export type SuccessfulResponse = { success: true; }; export type FailedResponse = { success: false; reason: string; }; export type WebviewInstanceResponseEventData = WebviewAddress & WebviewRequestInfo & WebviewEventInfo & (SuccessfulResponse | FailedResponse); export type MessagesToServer = { webview_instance_created: WebviewInstanceCreatedEventData; webview_instance_destroyed: WebviewInstanceDestroyedEventData; webview_instance_notification_received: WebviewInstanceNotificationEventData; webview_instance_request_received: WebviewInstanceRequestEventData; webview_instance_response_received: WebviewInstanceResponseEventData; }; export type MessagesToClient = { webview_instance_notification: WebviewInstanceNotificationEventData; webview_instance_request: WebviewInstanceRequestEventData; webview_instance_response: WebviewInstanceResponseEventData; }; export interface TransportMessageHandler { (payload: T): void; } export interface TransportListener { on( type: K, callback: TransportMessageHandler, ): Disposable; } export interface TransportPublisher { publish(type: K, payload: MessagesToClient[K]): Promise; } export interface Transport extends TransportListener, TransportPublisher {} References:" You are a code assistant,Definition of 'run' in file scripts/watcher/watch.ts in project gitlab-lsp,"Definition: async function run() { const watchMsg = () => console.log(textColor, `Watching for file changes on ${dir}`); const now = performance.now(); const buildSuccessful = await runBuild(); if (!buildSuccessful) return watchMsg(); await Promise.all(postBuild()); console.log(successColor, `Finished in ${Math.round(performance.now() - now)}ms`); watchMsg(); } let timeout: NodeJS.Timeout | null = null; const dir = './src'; const watcher = chokidar.watch(dir, { ignored: /(^|[/\\])\../, // ignore dotfiles persistent: true, }); let isReady = false; watcher .on('add', async (filePath) => { if (!isReady) return; console.log(`File ${filePath} has been added`); await run(); }) .on('change', async (filePath) => { if (!isReady) return; console.log(`File ${filePath} has been changed`); if (timeout) clearTimeout(timeout); // We debounce the run function on change events in the case of many files being changed at once timeout = setTimeout(async () => { await run(); }, 1000); }) .on('ready', async () => { await run(); isReady = true; }) .on('unlink', (filePath) => console.log(`File ${filePath} has been removed`)); console.log(textColor, 'Starting watcher...'); 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 'notificationHandler' in file src/common/document_service.ts in project gitlab-lsp,"Definition: notificationHandler(params: DidChangeDocumentInActiveEditorParams): void; } export const DocumentService = createInterfaceId('DocumentsWrapper'); const DOCUMENT_CHANGE_EVENT_NAME = 'documentChange'; export class DefaultDocumentService implements DocumentService, HandlesNotification { #subscriptions: Disposable[] = []; #emitter = new EventEmitter(); #documents: TextDocuments; constructor(documents: TextDocuments) { 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 = { document }; this.#emitter.emit( DOCUMENT_CHANGE_EVENT_NAME, event, TextDocumentChangeListenerType.onDidSetActive, ); }; #createMediatorListener = (type: TextDocumentChangeListenerType) => (event: TextDocumentChangeEvent) => { 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: - packages/lib_webview_transport_json_rpc/src/json_rpc_connection_transport.test.ts:60" You are a code assistant,Definition of 'constructor' in file src/common/advanced_context/advanced_context_service.ts in project gitlab-lsp,"Definition: constructor( configService: ConfigService, connection: LsConnection, documentService: DocumentService, documentTransformer: DocumentTransformerService, supportedLanguagesService: SupportedLanguagesService, ) { this.#configService = configService; this.#documentTransformer = documentTransformer; this.#supportedLanguagesService = supportedLanguagesService; const subscription = documentService.onDocumentChange(async ({ document }, handlerType) => { await this.#updateAdvancedContext(document, handlerType); }); connection.onShutdown(() => subscription.dispose()); } /** * Currently updates the LRU cache with the most recently accessed files in the workspace. * We only update the advanced context for supported languages. We also ensure to run * documents through the `DocumentTransformer` to ensure the secret redaction is applied. */ async #updateAdvancedContext( document: TextDocument, handlerType: TextDocumentChangeListenerType, ) { const lruCache = LruCache.getInstance(LRU_CACHE_BYTE_SIZE_LIMIT); // eslint-disable-next-line default-case switch (handlerType) { case TextDocumentChangeListenerType.onDidClose: { // We don't check if the language is supported for `onDidClose` because we want // always attempt to delete the file from the cache. const fileDeleted = lruCache.deleteFile(document.uri); if (fileDeleted) { log.debug(`Advanced Context: File ${document.uri} was deleted from the LRU cache`); } else { log.debug(`Advanced Context: File ${document.uri} was not found in the LRU cache`); } break; } case TextDocumentChangeListenerType.onDidChangeContent: case TextDocumentChangeListenerType.onDidSave: case TextDocumentChangeListenerType.onDidOpen: case TextDocumentChangeListenerType.onDidSetActive: { const languageEnabled = this.#supportedLanguagesService.isLanguageEnabled( document.languageId, ); if (!languageEnabled) { return; } const context = this.#documentTransformer.getContext( document.uri, { line: 0, character: 0 }, this.#configService.get().client.workspaceFolders ?? [], undefined, ); if (!context) { log.debug(`Advanced Context: document context for ${document.uri} was not found`); return; } lruCache.updateFile(context); log.debug(`Advanced Context: uri ${document.uri} was updated in the MRU cache`); break; } } } } References:" You are a code assistant,Definition of 'REQUEST_TIMEOUT_MILLISECONDS' in file src/common/constants.ts in project gitlab-lsp,"Definition: export const REQUEST_TIMEOUT_MILLISECONDS = 15000; 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/tests/int/lsp_client.ts in project gitlab-lsp,"Definition: 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 { const params = { ...DEFAULT_INITIALIZE_PARAMS, ...initializeParams }; const request = new RequestType( 'initialize', ); const response = await this.#connection.sendRequest(request, params); return response; } /** * Send the LSP 'initialized' notification */ public async sendInitialized(options?: InitializedParams | undefined): Promise { const defaults = {}; const params = { ...defaults, ...options }; const request = new NotificationType('initialized'); await this.#connection.sendNotification(request, params); } /** * Send the LSP 'workspace/didChangeConfiguration' notification */ public async sendDidChangeConfiguration( options?: ChangeConfigOptions | undefined, ): Promise { const defaults = createFakePartial({ settings: { token: this.#gitlabToken, baseUrl: this.#gitlabBaseUrl, codeCompletion: { enableSecretRedaction: true, }, telemetry: { enabled: false, }, }, }); const params = { ...defaults, ...options }; const request = new NotificationType( 'workspace/didChangeConfiguration', ); await this.#connection.sendNotification(request, params); } public async sendTextDocumentDidOpen( uri: string, languageId: string, version: number, text: string, ): Promise { const params = { textDocument: { uri, languageId, version, text, }, }; const request = new NotificationType('textDocument/didOpen'); await this.#connection.sendNotification(request, params); } public async sendTextDocumentDidClose(uri: string): Promise { const params = { textDocument: { uri, }, }; const request = new NotificationType('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 { const params = { textDocument: { uri, version, }, contentChanges: [{ text }], }; const request = new NotificationType('textDocument/didChange'); await this.#connection.sendNotification(request, params); } public async sendTextDocumentCompletion( uri: string, line: number, character: number, ): Promise { 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 { await this.#connection.sendNotification(DidChangeDocumentInActiveEditor, uri); } public async getWebviewMetadata(): Promise { const result = await this.#connection.sendRequest( '$/gitlab/webview-metadata', ); return result; } } References:" You are a code assistant,Definition of 'loggerWithPrefix' in file src/node/http/utils/logger_with_prefix.ts in project gitlab-lsp,"Definition: export function loggerWithPrefix(logger: ILog, prefix: string): ILog { const addPrefix = (message: string) => `${prefix} ${message}`; return LOG_METHODS.reduce((acc, method) => { acc[method] = (message: string | Error, e?: Error): void => { if (typeof message === 'string') { logger[method](addPrefix(message), e); } else { logger[method](message); } }; return acc; }, {} as ILog); } References: - src/node/http/utils/logger_with_prefix.test.ts:28 - src/node/http/create_fastify_http_server.ts:22" You are a code assistant,Definition of 'constructor' in file src/tests/fixtures/intent/empty_function/typescript.ts in project gitlab-lsp,"Definition: 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:" You are a code assistant,Definition of 'DirectoryToSearch' in file src/common/services/fs/dir.ts in project gitlab-lsp,"Definition: export interface DirectoryToSearch { /** * The URI of the directory to search. * Example: 'file:///path/to/directory' */ directoryUri: string; /** * The filters to apply to the search. * They form a logical AND, meaning * that a file must match all filters to be included in the results. */ filters?: { /** * The file name or extensions to filter by. * MUST be Unix-style paths. */ fileEndsWith?: string[]; }; } export type FileChangeHandler = ( event: 'add' | 'change' | 'unlink', workspaceFolder: WorkspaceFolder, filePath: string, stats?: Stats, ) => void; export interface DirectoryWalker { findFilesForDirectory(_args: DirectoryToSearch): Promise; setupFileWatcher(workspaceFolder: WorkspaceFolder, changeHandler: FileChangeHandler): void; } export const DirectoryWalker = createInterfaceId('DirectoryWalker'); @Injectable(DirectoryWalker, []) export class DefaultDirectoryWalker { /** * Returns a list of files in the specified directory that match the specified criteria. * The returned files will be the full paths to the files, they also will be in the form of URIs. * Example: [' file:///path/to/file.txt', 'file:///path/to/another/file.js'] */ // eslint-disable-next-line @typescript-eslint/no-unused-vars findFilesForDirectory(_args: DirectoryToSearch): Promise { return Promise.resolve([]); } // eslint-disable-next-line @typescript-eslint/no-unused-vars setupFileWatcher(workspaceFolder: WorkspaceFolder, changeHandler: FileChangeHandler) { throw new Error(`${workspaceFolder} ${changeHandler} not implemented`); } } References: - src/node/services/fs/dir.ts:36 - src/common/services/fs/dir.ts:48 - src/common/services/fs/dir.ts:34" You are a code assistant,Definition of 'sendDidChangeConfiguration' in file src/tests/int/lsp_client.ts in project gitlab-lsp,"Definition: public async sendDidChangeConfiguration( options?: ChangeConfigOptions | undefined, ): Promise { const defaults = createFakePartial({ settings: { token: this.#gitlabToken, baseUrl: this.#gitlabBaseUrl, codeCompletion: { enableSecretRedaction: true, }, telemetry: { enabled: false, }, }, }); const params = { ...defaults, ...options }; const request = new NotificationType( 'workspace/didChangeConfiguration', ); await this.#connection.sendNotification(request, params); } public async sendTextDocumentDidOpen( uri: string, languageId: string, version: number, text: string, ): Promise { const params = { textDocument: { uri, languageId, version, text, }, }; const request = new NotificationType('textDocument/didOpen'); await this.#connection.sendNotification(request, params); } public async sendTextDocumentDidClose(uri: string): Promise { const params = { textDocument: { uri, }, }; const request = new NotificationType('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 { const params = { textDocument: { uri, version, }, contentChanges: [{ text }], }; const request = new NotificationType('textDocument/didChange'); await this.#connection.sendNotification(request, params); } public async sendTextDocumentCompletion( uri: string, line: number, character: number, ): Promise { 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 { await this.#connection.sendNotification(DidChangeDocumentInActiveEditor, uri); } public async getWebviewMetadata(): Promise { const result = await this.#connection.sendRequest( '$/gitlab/webview-metadata', ); return result; } } References:" You are a code assistant,Definition of 'processStream' in file src/common/suggestion_client/post_processors/post_processor_pipeline.test.ts in project gitlab-lsp,"Definition: async processStream( _context: IDocContext, input: StreamingCompletionResponse, ): Promise { return { ...input, completion: `${input.completion} processed` }; } async processCompletion( _context: IDocContext, input: SuggestionOption[], ): Promise { return input; } } pipeline.addProcessor(new TestStreamProcessor()); const streamInput: StreamingCompletionResponse = { id: '1', completion: 'test', done: false }; const result = await pipeline.run({ documentContext: mockContext, input: streamInput, type: 'stream', }); expect(result).toEqual({ id: '1', completion: 'test processed', done: false }); }); test('should process completion input correctly', async () => { class TestCompletionProcessor extends PostProcessor { async processStream( _context: IDocContext, input: StreamingCompletionResponse, ): Promise { return input; } async processCompletion( _context: IDocContext, input: SuggestionOption[], ): Promise { return input.map((option) => ({ ...option, text: `${option.text} processed` })); } } pipeline.addProcessor(new TestCompletionProcessor()); const completionInput: SuggestionOption[] = [{ text: 'option1', uniqueTrackingId: '1' }]; const result = await pipeline.run({ documentContext: mockContext, input: completionInput, type: 'completion', }); expect(result).toEqual([{ text: 'option1 processed', uniqueTrackingId: '1' }]); }); test('should chain multiple processors correctly for stream input', async () => { class Processor1 extends PostProcessor { async processStream( _context: IDocContext, input: StreamingCompletionResponse, ): Promise { return { ...input, completion: `${input.completion} [1]` }; } async processCompletion( _context: IDocContext, input: SuggestionOption[], ): Promise { return input; } } class Processor2 extends PostProcessor { async processStream( _context: IDocContext, input: StreamingCompletionResponse, ): Promise { return { ...input, completion: `${input.completion} [2]` }; } async processCompletion( _context: IDocContext, input: SuggestionOption[], ): Promise { return input; } } pipeline.addProcessor(new Processor1()); pipeline.addProcessor(new Processor2()); const streamInput: StreamingCompletionResponse = { id: '1', completion: 'test', done: false }; const result = await pipeline.run({ documentContext: mockContext, input: streamInput, type: 'stream', }); expect(result).toEqual({ id: '1', completion: 'test [1] [2]', done: false }); }); test('should chain multiple processors correctly for completion input', async () => { class Processor1 extends PostProcessor { async processStream( _context: IDocContext, input: StreamingCompletionResponse, ): Promise { return input; } async processCompletion( _context: IDocContext, input: SuggestionOption[], ): Promise { return input.map((option) => ({ ...option, text: `${option.text} [1]` })); } } class Processor2 extends PostProcessor { async processStream( _context: IDocContext, input: StreamingCompletionResponse, ): Promise { return input; } async processCompletion( _context: IDocContext, input: SuggestionOption[], ): Promise { return input.map((option) => ({ ...option, text: `${option.text} [2]` })); } } pipeline.addProcessor(new Processor1()); pipeline.addProcessor(new Processor2()); const completionInput: SuggestionOption[] = [{ text: 'option1', uniqueTrackingId: '1' }]; const result = await pipeline.run({ documentContext: mockContext, input: completionInput, type: 'completion', }); expect(result).toEqual([{ text: 'option1 [1] [2]', uniqueTrackingId: '1' }]); }); test('should throw an error for unexpected type', async () => { class TestProcessor extends PostProcessor { async processStream( _context: IDocContext, input: StreamingCompletionResponse, ): Promise { return input; } async processCompletion( _context: IDocContext, input: SuggestionOption[], ): Promise { 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 'updateCache' in file src/common/services/duo_access/project_access_cache.ts in project gitlab-lsp,"Definition: async updateCache({ baseUrl, workspaceFolders, }: { baseUrl: string; workspaceFolders: WorkspaceFolder[]; }) { try { this.#duoProjects.clear(); const duoProjects = await Promise.all( workspaceFolders.map(async (workspaceFolder) => { return { workspaceFolder, projects: await this.#duoProjectsForWorkspaceFolder({ workspaceFolder, baseUrl, }), }; }), ); for (const { workspaceFolder, projects } of duoProjects) { this.#logProjectsInfo(projects, workspaceFolder); this.#duoProjects.set(workspaceFolder.uri, projects); } this.#triggerChange(); } catch (err) { log.error('DuoProjectAccessCache: failed to update project access cache', err); } } #logProjectsInfo(projects: DuoProject[], workspaceFolder: WorkspaceFolder) { if (!projects.length) { log.warn( `DuoProjectAccessCache: no projects found for workspace folder ${workspaceFolder.uri}`, ); return; } log.debug( `DuoProjectAccessCache: found ${projects.length} projects for workspace folder ${workspaceFolder.uri}: ${JSON.stringify(projects, null, 2)}`, ); } async #duoProjectsForWorkspaceFolder({ workspaceFolder, baseUrl, }: { workspaceFolder: WorkspaceFolder; baseUrl: string; }): Promise { const remotes = await this.#gitlabRemotesForWorkspaceFolder(workspaceFolder, baseUrl); const projects = await Promise.all( remotes.map(async (remote) => { const enabled = await this.#checkDuoFeaturesEnabled(remote.namespaceWithPath); return { projectPath: remote.projectPath, uri: remote.fileUri, enabled, host: remote.host, namespace: remote.namespace, namespaceWithPath: remote.namespaceWithPath, } satisfies DuoProject; }), ); return projects; } async #gitlabRemotesForWorkspaceFolder( workspaceFolder: WorkspaceFolder, baseUrl: string, ): Promise { const paths = await this.directoryWalker.findFilesForDirectory({ directoryUri: workspaceFolder.uri, filters: { fileEndsWith: ['/.git/config'], }, }); const remotes = await Promise.all( paths.map(async (fileUri) => this.#gitlabRemotesForFileUri(fileUri.toString(), baseUrl)), ); return remotes.flat(); } async #gitlabRemotesForFileUri( fileUri: string, baseUrl: string, ): Promise { const remoteUrls = await this.#remoteUrlsFromGitConfig(fileUri); return remoteUrls.reduce((acc, remoteUrl) => { const remote = parseGitLabRemote(remoteUrl, baseUrl); if (remote) { acc.push({ ...remote, fileUri }); } return acc; }, []); } async #remoteUrlsFromGitConfig(fileUri: string): Promise { try { const fileString = await this.fileResolver.readFile({ fileUri }); const config = ini.parse(fileString); return this.#getRemoteUrls(config); } catch (error) { log.error(`DuoProjectAccessCache: Failed to read git config file: ${fileUri}`, error); return []; } } #getRemoteUrls(config: GitConfig): string[] { return Object.keys(config).reduce((acc, section) => { if (section.startsWith('remote ')) { acc.push(config[section].url); } return acc; }, []); } async #checkDuoFeaturesEnabled(projectPath: string): Promise { try { const response = await this.api.fetchFromApi<{ project: GqlProjectWithDuoEnabledInfo }>({ type: 'graphql', query: duoFeaturesEnabledQuery, variables: { projectPath, }, } satisfies ApiRequest<{ project: GqlProjectWithDuoEnabledInfo }>); return Boolean(response?.project?.duoFeaturesEnabled); } catch (error) { log.error( `DuoProjectAccessCache: Failed to check if Duo features are enabled for project: ${projectPath}`, error, ); return true; } } onDuoProjectCacheUpdate( listener: (duoProjectsCache: Map) => void, ): Disposable { this.#eventEmitter.on(DUO_PROJECT_CACHE_UPDATE_EVENT, listener); return { dispose: () => this.#eventEmitter.removeListener(DUO_PROJECT_CACHE_UPDATE_EVENT, listener), }; } #triggerChange() { this.#eventEmitter.emit(DUO_PROJECT_CACHE_UPDATE_EVENT, this.#duoProjects); } } References:" You are a code assistant,Definition of 'isLanguageEnabled' in file src/common/suggestion/supported_languages_service.ts in project gitlab-lsp,"Definition: isLanguageEnabled(languageId: string): boolean; isLanguageSupported(languageId: string): boolean; onLanguageChange(listener: () => void): Disposable; } export const SupportedLanguagesService = createInterfaceId( 'SupportedLanguagesService', ); @Injectable(SupportedLanguagesService, [ConfigService]) export class DefaultSupportedLanguagesService implements SupportedLanguagesService { #enabledLanguages: Set; #supportedLanguages: Set; #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 = 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 'CodeSuggestionResponse' in file src/common/api.ts in project gitlab-lsp,"Definition: export interface CodeSuggestionResponse { choices?: SuggestionOption[]; model?: ICodeSuggestionModel; status: number; error?: string; isDirectConnection?: boolean; } // FIXME: Rename to SuggestionOptionStream when renaming the SuggestionOption export interface StartStreamOption { uniqueTrackingId: string; /** the streamId represents the beginning of a stream * */ streamId: string; } export type SuggestionOptionOrStream = SuggestionOption | StartStreamOption; export interface PersonalAccessToken { name: string; scopes: string[]; active: boolean; } export interface OAuthToken { scope: string[]; } export interface TokenCheckResponse { valid: boolean; reason?: 'unknown' | 'not_active' | 'invalid_scopes'; message?: string; } export interface IDirectConnectionDetailsHeaders { 'X-Gitlab-Global-User-Id': string; 'X-Gitlab-Instance-Id': string; 'X-Gitlab-Host-Name': string; 'X-Gitlab-Saas-Duo-Pro-Namespace-Ids': string; } export interface IDirectConnectionModelDetails { model_provider: string; model_name: string; } export interface IDirectConnectionDetails { base_url: string; token: string; expires_at: number; headers: IDirectConnectionDetailsHeaders; model_details: IDirectConnectionModelDetails; } const CONFIG_CHANGE_EVENT_NAME = 'apiReconfigured'; @Injectable(GitLabApiClient, [LsFetch, ConfigService]) export class GitLabAPI implements GitLabApiClient { #token: string | undefined; #baseURL: string; #clientInfo?: IClientInfo; #lsFetch: LsFetch; #eventEmitter = new EventEmitter(); #configService: ConfigService; #instanceVersion?: string; constructor(lsFetch: LsFetch, configService: ConfigService) { this.#baseURL = GITLAB_API_BASE_URL; this.#lsFetch = lsFetch; this.#configService = configService; this.#configService.onConfigChange(async (config) => { this.#clientInfo = configService.get('client.clientInfo'); this.#lsFetch.updateAgentOptions({ ignoreCertificateErrors: this.#configService.get('client.ignoreCertificateErrors') ?? false, ...(this.#configService.get('client.httpAgentOptions') ?? {}), }); await this.configureApi(config.client); }); } onApiReconfigured(listener: (data: ApiReconfiguredData) => void): Disposable { this.#eventEmitter.on(CONFIG_CHANGE_EVENT_NAME, listener); return { dispose: () => this.#eventEmitter.removeListener(CONFIG_CHANGE_EVENT_NAME, listener) }; } #fireApiReconfigured(isInValidState: boolean, validationMessage?: string) { const data: ApiReconfiguredData = { isInValidState, validationMessage }; this.#eventEmitter.emit(CONFIG_CHANGE_EVENT_NAME, data); } async configureApi({ token, baseUrl = GITLAB_API_BASE_URL, }: { token?: string; baseUrl?: string; }) { if (this.#token === token && this.#baseURL === baseUrl) return; this.#token = token; this.#baseURL = baseUrl; const { valid, reason, message } = await this.checkToken(this.#token); let validationMessage; if (!valid) { this.#configService.set('client.token', undefined); validationMessage = `Token is invalid. ${message}. Reason: ${reason}`; log.warn(validationMessage); } else { log.info('Token is valid'); } this.#instanceVersion = await this.#getGitLabInstanceVersion(); this.#fireApiReconfigured(valid, validationMessage); } #looksLikePatToken(token: string): boolean { // OAuth tokens will be longer than 42 characters and PATs will be shorter. return token.length < 42; } async #checkPatToken(token: string): Promise { const headers = this.#getDefaultHeaders(token); const response = await this.#lsFetch.get( `${this.#baseURL}/api/v4/personal_access_tokens/self`, { headers }, ); await handleFetchError(response, 'Information about personal access token'); const { active, scopes } = (await response.json()) as PersonalAccessToken; if (!active) { return { valid: false, reason: 'not_active', message: 'Token is not active.', }; } if (!this.#hasValidScopes(scopes)) { const joinedScopes = scopes.map((scope) => `'${scope}'`).join(', '); return { valid: false, reason: 'invalid_scopes', message: `Token has scope(s) ${joinedScopes} (needs 'api').`, }; } return { valid: true }; } async #checkOAuthToken(token: string): Promise { const headers = this.#getDefaultHeaders(token); const response = await this.#lsFetch.get(`${this.#baseURL}/oauth/token/info`, { headers, }); await handleFetchError(response, 'Information about OAuth token'); const { scope: scopes } = (await response.json()) as OAuthToken; if (!this.#hasValidScopes(scopes)) { const joinedScopes = scopes.map((scope) => `'${scope}'`).join(', '); return { valid: false, reason: 'invalid_scopes', message: `Token has scope(s) ${joinedScopes} (needs 'api').`, }; } return { valid: true }; } async checkToken(token: string = ''): Promise { try { if (this.#looksLikePatToken(token)) { log.info('Checking token for PAT validity'); return await this.#checkPatToken(token); } log.info('Checking token for OAuth validity'); return await this.#checkOAuthToken(token); } catch (err) { log.error('Error performing token check', err); return { valid: false, reason: 'unknown', message: `Failed to check token: ${err}`, }; } } #hasValidScopes(scopes: string[]): boolean { return scopes.includes('api'); } async getCodeSuggestions( request: CodeSuggestionRequest, ): Promise { if (!this.#token) { throw new Error('Token needs to be provided to request Code Suggestions'); } const headers = { ...this.#getDefaultHeaders(this.#token), 'Content-Type': 'application/json', }; const response = await this.#lsFetch.post( `${this.#baseURL}/api/v4/code_suggestions/completions`, { headers, body: JSON.stringify(request) }, ); await handleFetchError(response, 'Code Suggestions'); const data = await response.json(); return { ...data, status: response.status }; } async *getStreamingCodeSuggestions( request: CodeSuggestionRequest, ): AsyncGenerator { if (!this.#token) { throw new Error('Token needs to be provided to stream code suggestions'); } const headers = { ...this.#getDefaultHeaders(this.#token), 'Content-Type': 'application/json', }; yield* this.#lsFetch.streamFetch( `${this.#baseURL}/api/v4/code_suggestions/completions`, JSON.stringify(request), headers, ); } async fetchFromApi(request: ApiRequest): Promise { if (!this.#token) { return Promise.reject(new Error('Token needs to be provided to authorise API request.')); } if ( request.supportedSinceInstanceVersion && !this.#instanceVersionHigherOrEqualThen(request.supportedSinceInstanceVersion.version) ) { return Promise.reject( new InvalidInstanceVersionError( `Can't ${request.supportedSinceInstanceVersion.resourceName} until your instance is upgraded to ${request.supportedSinceInstanceVersion.version} or higher.`, ), ); } if (request.type === 'graphql') { return this.#graphqlRequest(request.query, request.variables); } switch (request.method) { case 'GET': return this.#fetch(request.path, request.searchParams, 'resource', request.headers); case 'POST': return this.#postFetch(request.path, 'resource', request.body, request.headers); default: // the type assertion is necessary because TS doesn't expect any other types throw new Error(`Unknown request type ${(request as ApiRequest).type}`); } } async connectToCable(): Promise { const headers = this.#getDefaultHeaders(this.#token); const websocketOptions = { headers: { ...headers, Origin: this.#baseURL, }, }; return connectToCable(this.#baseURL, websocketOptions); } async #graphqlRequest( document: RequestDocument, variables?: V, ): Promise { const ensureEndsWithSlash = (url: string) => url.replace(/\/?$/, '/'); const endpoint = new URL('./api/graphql', ensureEndsWithSlash(this.#baseURL)).href; // supports GitLab instances that are on a custom path, e.g. ""https://example.com/gitlab"" const graphqlFetch = async ( input: RequestInfo | URL, init?: RequestInit, ): Promise => { const url = input instanceof URL ? input.toString() : input; return this.#lsFetch.post(url, { ...init, headers: { ...headers, ...init?.headers }, }); }; const headers = this.#getDefaultHeaders(this.#token); const client = new GraphQLClient(endpoint, { headers, fetch: graphqlFetch, }); return client.request(document, variables); } async #fetch( apiResourcePath: string, query: Record = {}, resourceName = 'resource', headers?: Record, ): Promise { const url = `${this.#baseURL}/api/v4${apiResourcePath}${createQueryString(query)}`; const result = await this.#lsFetch.get(url, { headers: { ...this.#getDefaultHeaders(this.#token), ...headers }, }); await handleFetchError(result, resourceName); return result.json() as Promise; } async #postFetch( apiResourcePath: string, resourceName = 'resource', body?: unknown, headers?: Record, ): Promise { const url = `${this.#baseURL}/api/v4${apiResourcePath}`; const response = await this.#lsFetch.post(url, { headers: { 'Content-Type': 'application/json', ...this.#getDefaultHeaders(this.#token), ...headers, }, body: JSON.stringify(body), }); await handleFetchError(response, resourceName); return response.json() as Promise; } #getDefaultHeaders(token?: string) { return { Authorization: `Bearer ${token}`, 'User-Agent': `code-completions-language-server-experiment (${this.#clientInfo?.name}:${this.#clientInfo?.version})`, 'X-Gitlab-Language-Server-Version': getLanguageServerVersion(), }; } #instanceVersionHigherOrEqualThen(version: string): boolean { if (!this.#instanceVersion) return false; return semverCompare(this.#instanceVersion, version) >= 0; } async #getGitLabInstanceVersion(): Promise { if (!this.#token) { return ''; } const headers = this.#getDefaultHeaders(this.#token); const response = await this.#lsFetch.get(`${this.#baseURL}/api/v4/version`, { headers, }); const { version } = await response.json(); return version; } get instanceVersion() { return this.#instanceVersion; } } References: - src/common/test_utils/mocks.ts:19" You are a code assistant,Definition of 'DO_NOT_SHOW_VERSION_WARNING' in file packages/webview_duo_chat/src/plugin/port/constants.ts in project gitlab-lsp,"Definition: export const DO_NOT_SHOW_VERSION_WARNING = 'DO_NOT_SHOW_VERSION_WARNING'; // NOTE: This needs to _always_ be a 3 digits 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 'CircuitBreakerState' in file src/common/circuit_breaker/circuit_breaker.ts in project gitlab-lsp,"Definition: export enum CircuitBreakerState { OPEN = 'Open', CLOSED = 'Closed', } export interface CircuitBreaker { error(): void; success(): void; isOpen(): boolean; onOpen(listener: () => void): Disposable; onClose(listener: () => void): Disposable; } References: - src/common/circuit_breaker/exponential_backoff_circuit_breaker.ts:20 - src/common/circuit_breaker/fixed_time_circuit_breaker.ts:14" You are a code assistant,Definition of 'fetchFromApi' in file packages/webview_duo_chat/src/plugin/types.ts in project gitlab-lsp,"Definition: fetchFromApi(request: ApiRequest): Promise; connectToCable(): Promise; } References: - packages/webview_duo_chat/src/plugin/port/platform/gitlab_platform.ts:11 - packages/webview_duo_chat/src/plugin/port/test_utils/create_fake_fetch_from_api.ts:10" You are a code assistant,Definition of 'handleWebviewMessage' in file packages/lib_webview_transport_json_rpc/src/json_rpc_connection_transport.ts in project gitlab-lsp,"Definition: export const handleWebviewMessage = ( messageEmitter: WebviewTransportEventEmitter, logger?: Logger, ) => withJsonRpcMessageValidation(isWebviewInstanceMessageEventData, logger, (message) => { messageEmitter.emit('webview_instance_notification_received', message); }); export type JsonRpcConnectionTransportProps = { connection: Connection; logger: Logger; notificationRpcMethod?: string; webviewCreatedRpcMethod?: string; webviewDestroyedRpcMethod?: string; }; export class JsonRpcConnectionTransport implements Transport { #messageEmitter = createWebviewTransportEventEmitter(); #connection: Connection; #notificationChannel: string; #webviewCreatedChannel: string; #webviewDestroyedChannel: string; #logger?: Logger; #disposables: Disposable[] = []; constructor({ connection, logger, notificationRpcMethod: notificationChannel = DEFAULT_NOTIFICATION_RPC_METHOD, webviewCreatedRpcMethod: webviewCreatedChannel = DEFAULT_WEBVIEW_CREATED_RPC_METHOD, webviewDestroyedRpcMethod: webviewDestroyedChannel = DEFAULT_WEBVIEW_DESTROYED_RPC_METHOD, }: JsonRpcConnectionTransportProps) { this.#connection = connection; this.#logger = logger ? withPrefix(logger, LOGGER_PREFIX) : undefined; this.#notificationChannel = notificationChannel; this.#webviewCreatedChannel = webviewCreatedChannel; this.#webviewDestroyedChannel = webviewDestroyedChannel; this.#subscribeToConnection(); } #subscribeToConnection() { const channelToNotificationHandlerMap = { [this.#webviewCreatedChannel]: handleWebviewCreated(this.#messageEmitter, this.#logger), [this.#webviewDestroyedChannel]: handleWebviewDestroyed(this.#messageEmitter, this.#logger), [this.#notificationChannel]: handleWebviewMessage(this.#messageEmitter, this.#logger), }; Object.entries(channelToNotificationHandlerMap).forEach(([channel, handler]) => { const disposable = this.#connection.onNotification(channel, handler); this.#disposables.push(disposable); }); } on( type: K, callback: TransportMessageHandler, ): Disposable { this.#messageEmitter.on(type, callback as WebviewTransportEventEmitterMessages[K]); return { dispose: () => this.#messageEmitter.off(type, callback as WebviewTransportEventEmitterMessages[K]), }; } publish(type: K, payload: MessagesToClient[K]): Promise { if (type === 'webview_instance_notification') { return this.#connection.sendNotification(this.#notificationChannel, payload); } throw new Error(`Unknown message type: ${type}`); } dispose(): void { this.#messageEmitter.removeAllListeners(); this.#disposables.forEach((disposable) => disposable.dispose()); this.#logger?.debug('JsonRpcConnectionTransport disposed'); } } References: - packages/lib_webview_transport_json_rpc/src/json_rpc_connection_transport.ts:93" You are a code assistant,Definition of 'removeFile' in file src/common/git/repository.ts in project gitlab-lsp,"Definition: removeFile(fileUri: string): void { this.#files.delete(fileUri); } getFiles(): Map { return this.#files; } dispose(): void { this.#ignoreManager.dispose(); this.#files.clear(); } } References:" You are a code assistant,Definition of 'DefaultSupportedLanguagesService' in file src/common/suggestion/supported_languages_service.ts in project gitlab-lsp,"Definition: export class DefaultSupportedLanguagesService implements SupportedLanguagesService { #enabledLanguages: Set; #supportedLanguages: Set; #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 = 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: - src/common/feature_state/supported_language_check.test.ts:32 - src/common/suggestion/supported_languages_service.test.ts:9 - src/common/suggestion/supported_languages_service.test.ts:13" You are a code assistant,Definition of 'dispose' in file packages/lib_webview/src/setup/plugin/webview_controller.ts in project gitlab-lsp,"Definition: dispose(): void { this.#compositeDisposable.dispose(); this.#instanceInfos.forEach((info) => info.messageBus.dispose()); this.#instanceInfos.clear(); } #subscribeToEvents(runtimeMessageBus: WebviewRuntimeMessageBus) { const eventFilter = buildWebviewIdFilter(this.webviewId); this.#compositeDisposable.add( runtimeMessageBus.subscribe('webview:connect', this.#handleConnected.bind(this), eventFilter), runtimeMessageBus.subscribe( 'webview:disconnect', this.#handleDisconnected.bind(this), eventFilter, ), ); } #handleConnected(address: WebviewAddress) { this.#logger.debug(`Instance connected: ${address.webviewInstanceId}`); if (this.#instanceInfos.has(address.webviewInstanceId)) { // we are already connected with this webview instance return; } const messageBus = this.#messageBusFactory(address); const pluginCallbackDisposables = new CompositeDisposable(); this.#instanceInfos.set(address.webviewInstanceId, { messageBus, pluginCallbackDisposables, }); this.#handlers.forEach((handler) => { const disposable = handler(address.webviewInstanceId, messageBus); if (isDisposable(disposable)) { pluginCallbackDisposables.add(disposable); } }); } #handleDisconnected(address: WebviewAddress) { this.#logger.debug(`Instance disconnected: ${address.webviewInstanceId}`); const instanceInfo = this.#instanceInfos.get(address.webviewInstanceId); if (!instanceInfo) { // we aren't tracking this instance return; } instanceInfo.pluginCallbackDisposables.dispose(); instanceInfo.messageBus.dispose(); this.#instanceInfos.delete(address.webviewInstanceId); } } References:" You are a code assistant,Definition of 'RepositoryService' in file src/common/git/repository_service.ts in project gitlab-lsp,"Definition: export type RepositoryService = typeof DefaultRepositoryService.prototype; export const RepositoryService = createInterfaceId('RepositoryService'); @Injectable(RepositoryService, [VirtualFileSystemService]) export class DefaultRepositoryService { #virtualFileSystemService: DefaultVirtualFileSystemService; constructor(virtualFileSystemService: DefaultVirtualFileSystemService) { this.#virtualFileSystemService = virtualFileSystemService; this.#setupEventListeners(); } #setupEventListeners() { return this.#virtualFileSystemService.onFileSystemEvent(async (eventType, data) => { switch (eventType) { case VirtualFileSystemEvents.WorkspaceFilesUpdate: await this.#handleWorkspaceFilesUpdate(data as WorkspaceFilesUpdate); break; case VirtualFileSystemEvents.WorkspaceFileUpdate: await this.#handleWorkspaceFileUpdate(data as WorkspaceFileUpdate); break; default: break; } }); } async #handleWorkspaceFilesUpdate(update: WorkspaceFilesUpdate) { log.info(`Workspace files update: ${update.files.length}`); const perf1 = performance.now(); await this.handleWorkspaceFilesUpdate({ ...update, }); const perf2 = performance.now(); log.info(`Workspace files initialization took ${perf2 - perf1}ms`); const perf3 = performance.now(); const files = this.getFilesForWorkspace(update.workspaceFolder.uri, { excludeGitFolder: true, excludeIgnored: true, }); const perf4 = performance.now(); log.info(`Fetched workspace files in ${perf4 - perf3}ms`); log.info(`Workspace git files: ${files.length}`); // const treeFile = await readFile( // '/Users/angelo.rivera/gitlab/gitlab-development-kit/gitlab/tree.txt', // 'utf-8', // ); // const treeFiles = treeFile.split('\n').filter(Boolean); // // get the set difference between the files in the tree and the non-ignored files // // we need the difference between the two sets to know which files are not in the tree // const diff = new Set( // files.map((file) => // relative('/Users/angelo.rivera/gitlab/gitlab-development-kit/gitlab', file.uri.fsPath), // ), // ); // for (const file of treeFiles) { // diff.delete(file); // } // log.info(`Files not in the tree.txt: ${JSON.stringify(Array.from(diff))}`); } async #handleWorkspaceFileUpdate(update: WorkspaceFileUpdate) { log.info(`Workspace file update: ${JSON.stringify(update)}`); await this.handleWorkspaceFileUpdate({ ...update, }); const perf1 = performance.now(); const files = this.getFilesForWorkspace(update.workspaceFolder.uri, { excludeGitFolder: true, excludeIgnored: true, }); const perf2 = performance.now(); log.info(`Fetched workspace files in ${perf2 - perf1}ms`); log.info(`Workspace git files: ${files.length}`); } /** * unique map of workspace folders that point to a map of repositories * We store separate repository maps for each workspace because * the events from the VFS service are at the workspace level. * If we combined them, we may get race conditions */ #workspaces: Map = new Map(); #workspaceRepositoryTries: Map = new Map(); #buildRepositoryTrie(repositories: Repository[]): RepositoryTrie { const root = new RepositoryTrie(); for (const repo of repositories) { let node = root; const parts = repo.uri.path.split('/').filter(Boolean); for (const part of parts) { if (!node.children.has(part)) { node.children.set(part, new RepositoryTrie()); } node = node.children.get(part) as RepositoryTrie; } node.repository = repo.uri; } return root; } findMatchingRepositoryUri(fileUri: URI, workspaceFolderUri: WorkspaceFolder): URI | null { const trie = this.#workspaceRepositoryTries.get(workspaceFolderUri.uri); if (!trie) return null; let node = trie; let lastMatchingRepo: URI | null = null; const parts = fileUri.path.split('/').filter(Boolean); for (const part of parts) { if (node.repository) { lastMatchingRepo = node.repository; } if (!node.children.has(part)) break; node = node.children.get(part) as RepositoryTrie; } return node.repository || lastMatchingRepo; } getRepositoryFileForUri( fileUri: URI, repositoryUri: URI, workspaceFolder: WorkspaceFolder, ): RepositoryFile | null { const repository = this.#getRepositoriesForWorkspace(workspaceFolder.uri).get( repositoryUri.toString(), ); if (!repository) { return null; } return repository.getFile(fileUri.toString()) ?? null; } #updateRepositoriesForFolder( workspaceFolder: WorkspaceFolder, repositoryMap: RepositoryMap, repositoryTrie: RepositoryTrie, ) { this.#workspaces.set(workspaceFolder.uri, repositoryMap); this.#workspaceRepositoryTries.set(workspaceFolder.uri, repositoryTrie); } async handleWorkspaceFilesUpdate({ workspaceFolder, files }: WorkspaceFilesUpdate) { // clear existing repositories from workspace this.#emptyRepositoriesForWorkspace(workspaceFolder.uri); const repositories = this.#detectRepositories(files, workspaceFolder); const repositoryMap = new Map(repositories.map((repo) => [repo.uri.toString(), repo])); // Build and cache the repository trie for this workspace const trie = this.#buildRepositoryTrie(repositories); this.#updateRepositoriesForFolder(workspaceFolder, repositoryMap, trie); await Promise.all( repositories.map((repo) => repo.addFilesAndLoadGitIgnore( files.filter((file) => { const matchingRepo = this.findMatchingRepositoryUri(file, workspaceFolder); return matchingRepo && matchingRepo.toString() === repo.uri.toString(); }), ), ), ); } async handleWorkspaceFileUpdate({ fileUri, workspaceFolder, event }: WorkspaceFileUpdate) { const repoUri = this.findMatchingRepositoryUri(fileUri, workspaceFolder); if (!repoUri) { log.debug(`No matching repository found for file ${fileUri.toString()}`); return; } const repositoryMap = this.#getRepositoriesForWorkspace(workspaceFolder.uri); const repository = repositoryMap.get(repoUri.toString()); if (!repository) { log.debug(`Repository not found for URI ${repoUri.toString()}`); return; } if (repository.isFileIgnored(fileUri)) { log.debug(`File ${fileUri.toString()} is ignored`); return; } switch (event) { case 'add': repository.setFile(fileUri); log.debug(`File ${fileUri.toString()} added to repository ${repoUri.toString()}`); break; case 'change': repository.setFile(fileUri); log.debug(`File ${fileUri.toString()} updated in repository ${repoUri.toString()}`); break; case 'unlink': repository.removeFile(fileUri.toString()); log.debug(`File ${fileUri.toString()} removed from repository ${repoUri.toString()}`); break; default: log.warn(`Unknown file event ${event} for file ${fileUri.toString()}`); } } #getRepositoriesForWorkspace(workspaceFolderUri: WorkspaceFolderUri): RepositoryMap { return this.#workspaces.get(workspaceFolderUri) || new Map(); } #emptyRepositoriesForWorkspace(workspaceFolderUri: WorkspaceFolderUri): void { log.debug(`Emptying repositories for workspace ${workspaceFolderUri}`); const repos = this.#workspaces.get(workspaceFolderUri); if (!repos || repos.size === 0) return; // clear up ignore manager trie from memory repos.forEach((repo) => { repo.dispose(); log.debug(`Repository ${repo.uri} has been disposed`); }); repos.clear(); const trie = this.#workspaceRepositoryTries.get(workspaceFolderUri); if (trie) { trie.dispose(); this.#workspaceRepositoryTries.delete(workspaceFolderUri); } this.#workspaces.delete(workspaceFolderUri); log.debug(`Repositories for workspace ${workspaceFolderUri} have been emptied`); } #detectRepositories(files: URI[], workspaceFolder: WorkspaceFolder): Repository[] { const gitConfigFiles = files.filter((file) => file.toString().endsWith('.git/config')); return gitConfigFiles.map((file) => { const projectUri = fsPathToUri(file.path.replace('.git/config', '')); const ignoreManager = new IgnoreManager(projectUri.fsPath); log.info(`Detected repository at ${projectUri.path}`); return new Repository({ ignoreManager, uri: projectUri, configFileUri: file, workspaceFolder, }); }); } getFilesForWorkspace( workspaceFolderUri: WorkspaceFolderUri, options: { excludeGitFolder?: boolean; excludeIgnored?: boolean } = {}, ): RepositoryFile[] { const repositories = this.#getRepositoriesForWorkspace(workspaceFolderUri); const allFiles: RepositoryFile[] = []; repositories.forEach((repository) => { repository.getFiles().forEach((file) => { // apply the filters if (options.excludeGitFolder && this.#isInGitFolder(file.uri, repository.uri)) { return; } if (options.excludeIgnored && file.isIgnored) { return; } allFiles.push(file); }); }); return allFiles; } // Helper method to check if a file is in the .git folder #isInGitFolder(fileUri: URI, repositoryUri: URI): boolean { const relativePath = fileUri.path.slice(repositoryUri.path.length); return relativePath.split('/').some((part) => part === '.git'); } } References:" You are a code assistant,Definition of 'GraphQLRequest' in file packages/webview_duo_chat/src/plugin/port/platform/web_ide.ts in project gitlab-lsp,"Definition: export interface GraphQLRequest<_TReturnType> { type: 'graphql'; query: string; /** Options passed to the GraphQL query */ variables: Record; } 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; /* 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 'ProcessorType' in file src/common/suggestion_client/post_processors/post_processor_pipeline.ts in project gitlab-lsp,"Definition: type ProcessorType = 'stream' | 'completion'; type ProcessorInputMap = { stream: StreamingCompletionResponse; completion: SuggestionOption[]; }; /** * PostProcessor is an interface for classes that can be used to modify completion responses * before they are sent to the client. * They are run in order according to the order they are added to the PostProcessorPipeline. * Post-processors can be used to filter, sort, or modify completion and streaming suggestions. * Be sure to handle both streaming and completion responses in your implementation (if applicable). * */ export abstract class PostProcessor { processStream( _context: IDocContext, input: StreamingCompletionResponse, ): Promise { return Promise.resolve(input); } processCompletion(_context: IDocContext, input: SuggestionOption[]): Promise { return Promise.resolve(input); } } /** * Pipeline for running post-processors on completion and streaming (generation) responses. * Post-processors are used to modify completion responses before they are sent to the client. * They can be used to filter, sort, or modify completion suggestions. */ export class PostProcessorPipeline { #processors: PostProcessor[] = []; addProcessor(processor: PostProcessor): void { this.#processors.push(processor); } async run({ documentContext, input, type, }: { documentContext: IDocContext; input: ProcessorInputMap[T]; type: T; }): Promise { if (!this.#processors.length) return input as ProcessorInputMap[T]; return this.#processors.reduce( async (prevPromise, processor) => { const result = await prevPromise; // eslint-disable-next-line default-case switch (type) { case 'stream': return processor.processStream( documentContext, result as StreamingCompletionResponse, ) as Promise; case 'completion': return processor.processCompletion( documentContext, result as SuggestionOption[], ) as Promise; } throw new Error('Unexpected type in pipeline processing'); }, Promise.resolve(input) as Promise, ); } } References:" You are a code assistant,Definition of 'SetupWebviewRuntimeProps' in file packages/lib_webview/src/setup/setup_webview_runtime.ts in project gitlab-lsp,"Definition: export type SetupWebviewRuntimeProps = { extensionMessageBusProvider: ExtensionMessageBusProvider; transports: Transport[]; plugins: WebviewPlugin[]; logger: Logger; }; export function setupWebviewRuntime(props: SetupWebviewRuntimeProps): Disposable { const logger = withPrefix(props.logger, '[Webview]'); logger.debug('Setting up webview runtime'); try { const runtimeMessageBus = new WebviewRuntimeMessageBus(); const transportDisposable = setupTransports(props.transports, runtimeMessageBus, logger); const webviewPluginDisposable = setupWebviewPlugins({ runtimeMessageBus, logger, plugins: props.plugins, extensionMessageBusProvider: props.extensionMessageBusProvider, }); logger.info('Webview runtime setup completed successfully'); return { dispose: () => { logger.debug('Disposing webview runtime'); transportDisposable.dispose(); webviewPluginDisposable.dispose(); logger.info('Webview runtime disposed'); }, }; } catch (error) { props.logger.error( 'Failed to setup webview runtime', error instanceof Error ? error : undefined, ); return { dispose: () => { logger.debug('Disposing empty webview runtime due to setup failure'); }, }; } } References: - packages/lib_webview/src/setup/setup_webview_runtime.ts:17" You are a code assistant,Definition of 'defaultSlashCommands' in file packages/webview_duo_chat/src/plugin/port/chat/gitlab_chat_slash_commands.ts in project gitlab-lsp,"Definition: export const defaultSlashCommands: GitlabChatSlashCommand[] = [ ResetCommand, CleanCommand, TestsCommand, RefactorCommand, ExplainCommand, ]; References:" You are a code assistant,Definition of 'onConfigChange' in file src/common/config_service.ts in project gitlab-lsp,"Definition: 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) { mergeWith(this.#config, newConfig, (target, src) => (isArray(target) ? src : undefined)); this.#triggerChange(); } } References:" You are a code assistant,Definition of 'transformHeadersToSnowplowOptions' in file src/common/utils/headers_to_snowplow_options.ts in project gitlab-lsp,"Definition: export const transformHeadersToSnowplowOptions = ( headers?: IDirectConnectionDetailsHeaders, ): ISnowplowTrackerOptions => { let gitlabSaasDuoProNamespaceIds: number[] | undefined; try { gitlabSaasDuoProNamespaceIds = get(headers, 'X-Gitlab-Saas-Duo-Pro-Namespace-Ids') ?.split(',') .map((id) => parseInt(id, 10)); } catch (err) { log.debug('Failed to transform ""X-Gitlab-Saas-Duo-Pro-Namespace-Ids"" to telemetry options.'); } return { gitlab_instance_id: get(headers, 'X-Gitlab-Instance-Id'), gitlab_global_user_id: get(headers, 'X-Gitlab-Global-User-Id'), gitlab_host_name: get(headers, 'X-Gitlab-Host-Name'), gitlab_saas_duo_pro_namespace_ids: gitlabSaasDuoProNamespaceIds, }; }; References: - src/common/utils/headers_to_snowplow_options.test.ts:16 - src/common/suggestion_client/direct_connection_client.ts:94" You are a code assistant,Definition of 'AiContextRetriever' in file src/common/ai_context_management_2/retrievers/ai_context_retriever.ts in project gitlab-lsp,"Definition: export interface AiContextRetriever { retrieve(item: AiContextItem): Promise; } References:" You are a code assistant,Definition of 'START_STREAMING_COMMAND' in file src/common/constants.ts in project gitlab-lsp,"Definition: 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 'AiContextProviderItem' in file src/common/ai_context_management_2/providers/ai_context_provider.ts in project gitlab-lsp,"Definition: export type AiContextProviderItem = | { providerType: 'file'; subType: 'open_tab' | 'local_file_search'; fileUri: URI; workspaceFolder: WorkspaceFolder; repositoryFile: RepositoryFile | null; } | { providerType: 'other'; }; export interface AiContextProvider { getProviderItems( query: string, workspaceFolder: WorkspaceFolder[], ): Promise; } References: - src/common/ai_context_management_2/providers/ai_file_context_provider.ts:111 - src/common/ai_context_management_2/ai_context_aggregator.ts:54 - src/common/ai_context_management_2/ai_policy_management.ts:28 - src/common/ai_context_management_2/policies/ai_context_policy.ts:4 - src/common/ai_context_management_2/policies/duo_project_policy.ts:15 - src/common/ai_context_management_2/providers/ai_file_context_provider.ts:100" You are a code assistant,Definition of 'Greet2' in file src/tests/fixtures/intent/empty_function/ruby.rb in project gitlab-lsp,"Definition: 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/ruby.rb:24" You are a code assistant,Definition of 'SnowplowOptions' in file src/common/tracking/snowplow/snowplow.ts in project gitlab-lsp,"Definition: export type SnowplowOptions = { appId: string; endpoint: string; timeInterval: number; maxItems: number; enabled: EnabledCallback; }; /** * Adds the 'stm' parameter with the current time to the payload * Stringify all payload values * @param payload - The payload which will be mutated */ function preparePayload(payload: Payload): Record { const stringifiedPayload: Record = {}; Object.keys(payload).forEach((key) => { stringifiedPayload[key] = String(payload[key]); }); stringifiedPayload.stm = new Date().getTime().toString(); return stringifiedPayload; } export class Snowplow { /** Disable sending events when it's not possible. */ disabled: boolean = false; #emitter: Emitter; #lsFetch: LsFetch; #options: SnowplowOptions; #tracker: TrackerCore; static #instance?: Snowplow; // eslint-disable-next-line no-restricted-syntax private constructor(lsFetch: LsFetch, options: SnowplowOptions) { this.#lsFetch = lsFetch; this.#options = options; this.#emitter = new Emitter( this.#options.timeInterval, this.#options.maxItems, this.#sendEvent.bind(this), ); this.#emitter.start(); this.#tracker = trackerCore({ callback: this.#emitter.add.bind(this.#emitter) }); } public static getInstance(lsFetch: LsFetch, options?: SnowplowOptions): Snowplow { if (!this.#instance) { if (!options) { throw new Error('Snowplow should be instantiated'); } const sp = new Snowplow(lsFetch, options); Snowplow.#instance = sp; } // FIXME: this eslint violation was introduced before we set up linting // eslint-disable-next-line @typescript-eslint/no-non-null-assertion return Snowplow.#instance!; } async #sendEvent(events: PayloadBuilder[]): Promise { if (!this.#options.enabled() || this.disabled) { return; } try { const url = `${this.#options.endpoint}/com.snowplowanalytics.snowplow/tp2`; const data = { schema: 'iglu:com.snowplowanalytics.snowplow/payload_data/jsonschema/1-0-4', data: events.map((event) => { const eventId = uuidv4(); // All values prefilled below are part of snowplow tracker protocol // https://docs.snowplow.io/docs/collecting-data/collecting-from-own-applications/snowplow-tracker-protocol/#common-parameters // Values are set according to either common GitLab standard: // tna - representing tracker namespace and being set across GitLab to ""gl"" // tv - represents tracker value, to make it aligned with downstream system it has to be prefixed with ""js-*"""" // aid - represents app Id is configured via options to gitlab_ide_extension // eid - represents uuid for each emitted event event.add('eid', eventId); event.add('p', 'app'); event.add('tv', 'js-gitlab'); event.add('tna', 'gl'); event.add('aid', this.#options.appId); return preparePayload(event.build()); }), }; const config = { headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(data), }; const response = await this.#lsFetch.post(url, config); if (response.status !== 200) { log.warn( `Could not send telemetry to snowplow, this warning can be safely ignored. status=${response.status}`, ); } } catch (error) { let errorHandled = false; if (typeof error === 'object' && 'errno' in (error as object)) { const errObject = error as object; // ENOTFOUND occurs when the snowplow hostname cannot be resolved. if ('errno' in errObject && errObject.errno === 'ENOTFOUND') { this.disabled = true; errorHandled = true; log.info('Disabling telemetry, unable to resolve endpoint address.'); } else { log.warn(JSON.stringify(errObject)); } } if (!errorHandled) { log.warn('Failed to send telemetry event, this warning can be safely ignored'); log.warn(JSON.stringify(error)); } } } public async trackStructEvent( event: StructuredEvent, context?: SelfDescribingJson[] | null, ): Promise { this.#tracker.track(buildStructEvent(event), context); } async stop() { await this.#emitter.stop(); } public destroy() { Snowplow.#instance = undefined; } } References: - src/common/tracking/snowplow/snowplow.ts:69 - src/common/tracking/snowplow/snowplow.ts:57 - src/common/tracking/snowplow/snowplow.ts:50" You are a code assistant,Definition of 'getForAllAccounts' in file packages/webview_duo_chat/src/plugin/port/platform/gitlab_platform.ts in project gitlab-lsp,"Definition: getForAllAccounts(): Promise; /** * Returns GitLabPlatformForAccount if there is a SaaS account added. Otherwise returns undefined. */ getForSaaSAccount(): Promise; } References:" You are a code assistant,Definition of 'constructor' in file src/common/document_service.ts in project gitlab-lsp,"Definition: constructor(documents: TextDocuments) { 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 = { document }; this.#emitter.emit( DOCUMENT_CHANGE_EVENT_NAME, event, TextDocumentChangeListenerType.onDidSetActive, ); }; #createMediatorListener = (type: TextDocumentChangeListenerType) => (event: TextDocumentChangeEvent) => { 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:" You are a code assistant,Definition of 'greet' in file src/tests/fixtures/intent/empty_function/python.py in project gitlab-lsp,"Definition: def greet(self): pass 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/ruby_comments.rb:21 - src/tests/fixtures/intent/empty_function/ruby.rb:20 - src/tests/fixtures/intent/empty_function/ruby.rb:29 - src/tests/fixtures/intent/empty_function/ruby.rb:1" You are a code assistant,Definition of 'info' in file packages/lib_logging/src/types.ts in project gitlab-lsp,"Definition: 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 'CircuitBreaker' in file src/common/circuit_breaker/circuit_breaker.ts in project gitlab-lsp,"Definition: export interface CircuitBreaker { error(): void; success(): void; isOpen(): boolean; onOpen(listener: () => void): Disposable; onClose(listener: () => void): Disposable; } References: - src/common/suggestion/streaming_handler.test.ts:31 - src/common/suggestion/streaming_handler.ts:37" 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(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 'isAllowed' in file src/common/ai_context_management_2/policies/ai_context_policy.ts in project gitlab-lsp,"Definition: isAllowed(aiProviderItem: AiContextProviderItem): Promise<{ allowed: boolean; reason?: string; }>; } References:" You are a code assistant,Definition of 'SupportedLanguagesUpdateParam' in file src/common/suggestion/supported_languages_service.ts in project gitlab-lsp,"Definition: export interface SupportedLanguagesUpdateParam { allow?: string[]; deny?: string[]; } export interface SupportedLanguagesService { isLanguageEnabled(languageId: string): boolean; isLanguageSupported(languageId: string): boolean; onLanguageChange(listener: () => void): Disposable; } export const SupportedLanguagesService = createInterfaceId( 'SupportedLanguagesService', ); @Injectable(SupportedLanguagesService, [ConfigService]) export class DefaultSupportedLanguagesService implements SupportedLanguagesService { #enabledLanguages: Set; #supportedLanguages: Set; #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 = 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: - src/common/suggestion/supported_languages_service.ts:46" You are a code assistant,Definition of 'WebviewUriProviderRegistry' in file src/common/webview/webview_resource_location_service.ts in project gitlab-lsp,"Definition: export interface WebviewUriProviderRegistry { register(provider: WebviewUriProvider): void; } export class WebviewLocationService implements WebviewUriProviderRegistry { #uriProviders = new Set(); 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: - src/node/setup_http.ts:11" You are a code assistant,Definition of 'ApiRequest' in file packages/webview_duo_chat/src/plugin/port/platform/web_ide.ts in project gitlab-lsp,"Definition: 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; /* 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 'isEnabled' in file src/common/tracking/multi_tracker.ts in project gitlab-lsp,"Definition: isEnabled(): boolean { return Boolean(this.#enabledTrackers.length); } setCodeSuggestionsContext( uniqueTrackingId: string, context: Partial, ) { this.#enabledTrackers.forEach((t) => t.setCodeSuggestionsContext(uniqueTrackingId, context)); } updateCodeSuggestionsContext( uniqueTrackingId: string, contextUpdate: Partial, ) { 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 'constructor' in file packages/lib_di/src/index.test.ts in project gitlab-lsp,"Definition: constructor(a: A) { this.#a = a; } b = () => `B(${this.#a.a()})`; } @Injectable(C, [A, B]) class CImpl implements C { #a: A; #b: B; constructor(a: A, b: B) { this.#a = a; this.#b = b; } c = () => `C(${this.#b.b()}, ${this.#a.a()})`; } let container: Container; beforeEach(() => { container = new Container(); }); describe('addInstances', () => { const O = createInterfaceId('object'); it('fails if the instance is not branded', () => { expect(() => container.addInstances({ say: 'hello' } as BrandedInstance)).toThrow( /invoked without branded object/, ); }); it('fails if the instance is already present', () => { const a = brandInstance(O, { a: 'a' }); const b = brandInstance(O, { b: 'b' }); expect(() => container.addInstances(a, b)).toThrow(/this ID is already in the container/); }); it('adds instance', () => { const instance = { a: 'a' }; const a = brandInstance(O, instance); container.addInstances(a); expect(container.get(O)).toBe(instance); }); }); describe('instantiate', () => { it('can instantiate three classes A,B,C', () => { container.instantiate(AImpl, BImpl, CImpl); const cInstance = container.get(C); expect(cInstance.c()).toBe('C(B(a), a)'); }); it('instantiates dependencies in multiple instantiate calls', () => { container.instantiate(AImpl); // the order is important for this test // we want to make sure that the stack in circular dependency discovery is being cleared // to try why this order is necessary, remove the `inStack.delete()` from // the `if (!cwd && instanceIds.includes(id))` condition in prod code expect(() => container.instantiate(CImpl, BImpl)).not.toThrow(); }); it('detects duplicate ids', () => { @Injectable(A, []) 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 'CHAT' in file src/common/feature_state/feature_state_management_types.ts in project gitlab-lsp,"Definition: export const CHAT = 'chat' as const; // export const WORKFLOW = 'workflow' as const; export type Feature = typeof CODE_SUGGESTIONS | typeof CHAT; // | typeof WORKFLOW; export const NO_LICENSE = 'code-suggestions-no-license' as const; export const DUO_DISABLED_FOR_PROJECT = 'duo-disabled-for-project' as const; export const UNSUPPORTED_GITLAB_VERSION = 'unsupported-gitlab-version' as const; export const UNSUPPORTED_LANGUAGE = 'code-suggestions-document-unsupported-language' as const; export const DISABLED_LANGUAGE = 'code-suggestions-document-disabled-language' as const; export type StateCheckId = | typeof NO_LICENSE | typeof DUO_DISABLED_FOR_PROJECT | typeof UNSUPPORTED_GITLAB_VERSION | typeof UNSUPPORTED_LANGUAGE | typeof DISABLED_LANGUAGE; export interface FeatureStateCheck { checkId: StateCheckId; details?: string; } export interface FeatureState { featureId: Feature; engagedChecks: FeatureStateCheck[]; } const CODE_SUGGESTIONS_CHECKS_PRIORITY_ORDERED = [ DUO_DISABLED_FOR_PROJECT, UNSUPPORTED_LANGUAGE, DISABLED_LANGUAGE, ]; const CHAT_CHECKS_PRIORITY_ORDERED = [DUO_DISABLED_FOR_PROJECT]; export const CHECKS_PER_FEATURE: { [key in Feature]: StateCheckId[] } = { [CODE_SUGGESTIONS]: CODE_SUGGESTIONS_CHECKS_PRIORITY_ORDERED, [CHAT]: CHAT_CHECKS_PRIORITY_ORDERED, // [WORKFLOW]: [], }; References:" You are a code assistant,Definition of 'greet' in file src/tests/fixtures/intent/empty_function/go.go in project gitlab-lsp,"Definition: func (g Greet) greet() { fmt.Printf(""Hello %s\n"", g.name) } 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 'Fetch' in file src/node/fetch.ts in project gitlab-lsp,"Definition: export class Fetch extends FetchBase implements LsFetch { #proxy?: ProxyAgent; #userProxy?: string; #initialized: boolean = false; #httpsAgent: https.Agent; #agentOptions: Readonly; constructor(userProxy?: string) { super(); this.#agentOptions = { rejectUnauthorized: true, }; this.#userProxy = userProxy; this.#httpsAgent = this.#createHttpsAgent(); } async initialize(): Promise { // Set http_proxy and https_proxy environment variables // which will then get picked up by the ProxyAgent and // used. try { const proxy = await getProxySettings(); if (proxy?.http) { process.env.http_proxy = `${proxy.http.protocol}://${proxy.http.host}:${proxy.http.port}`; log.debug(`fetch: Detected http proxy through settings: ${process.env.http_proxy}`); } if (proxy?.https) { process.env.https_proxy = `${proxy.https.protocol}://${proxy.https.host}:${proxy.https.port}`; log.debug(`fetch: Detected https proxy through settings: ${process.env.https_proxy}`); } if (!proxy?.http && !proxy?.https) { log.debug(`fetch: Detected no proxy settings`); } } catch (err) { log.warn('Unable to load proxy settings', err); } if (this.#userProxy) { log.debug(`fetch: Detected user proxy ${this.#userProxy}`); process.env.http_proxy = this.#userProxy; process.env.https_proxy = this.#userProxy; } if (process.env.http_proxy || process.env.https_proxy) { log.info( `fetch: Setting proxy to https_proxy=${process.env.https_proxy}; http_proxy=${process.env.http_proxy}`, ); this.#proxy = this.#createProxyAgent(); } this.#initialized = true; } async destroy(): Promise { this.#proxy?.destroy(); } async fetch(input: RequestInfo | URL, init?: RequestInit): Promise { 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 { let buffer = ''; const decoder = new TextDecoder(); async function* readStream( stream: ReadableStream, ): AsyncGenerator { 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 { 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: '' } : {}), ...(cert ? { cert: '' } : {}), ...(key ? { key: '' } : {}), }; } } References: - src/tests/int/fetch.test.ts:154 - src/node/fetch.test.ts:38 - src/node/fetch.test.ts:57 - src/node/fetch.test.ts:90 - src/browser/fetch.test.ts:33 - src/node/fetch.test.ts:74 - src/tests/int/snowplow.test.ts:16 - src/browser/main.ts:67 - src/node/main.ts:113 - src/tests/int/fetch.test.ts:124 - src/node/fetch.test.ts:191 - src/node/fetch.test.ts:194 - src/tests/int/fetch.test.ts:82" You are a code assistant,Definition of 'WEBVIEW_ID' in file packages/webview-chat/src/constants.ts in project gitlab-lsp,"Definition: export const WEBVIEW_ID = 'chat' as WebviewId; export const WEBVIEW_TITLE = 'GitLab: Duo Chat'; References:" You are a code assistant,Definition of 'getForAllAccounts' in file packages/webview_duo_chat/src/plugin/chat_platform_manager.ts in project gitlab-lsp,"Definition: async getForAllAccounts(): Promise { return [new ChatPlatformForAccount(this.#client)]; } async getForSaaSAccount(): Promise { return new ChatPlatformForAccount(this.#client); } } References:" You are a code assistant,Definition of 'CreateFastifyRequestParams' in file src/node/webview/test-utils/mock_fastify_request.ts in project gitlab-lsp,"Definition: type CreateFastifyRequestParams = { url: string; params: Record; }; export function createMockFastifyRequest( params?: Partial, ): FastifyRequest { // eslint-disable-next-line no-param-reassign params ??= {}; return { url: params.url ?? '', params: params.params ?? {}, } as FastifyRequest; } References:" You are a code assistant,Definition of 'SupportedSinceInstanceVersion' in file src/common/api_types.ts in project gitlab-lsp,"Definition: interface SupportedSinceInstanceVersion { version: string; resourceName: string; } interface BaseRestRequest<_TReturnType> { type: 'rest'; /** * 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; headers?: Record; supportedSinceInstanceVersion?: SupportedSinceInstanceVersion; } interface GraphQLRequest<_TReturnType> { type: 'graphql'; query: string; /** Options passed to the GraphQL query */ variables: Record; 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; supportedSinceInstanceVersion?: SupportedSinceInstanceVersion; } export type ApiRequest<_TReturnType> = | GetRequest<_TReturnType> | PostRequest<_TReturnType> | GraphQLRequest<_TReturnType>; export type AdditionalContext = { /** * The type of the context element. Options: `file` or `snippet`. */ type: 'file' | 'snippet'; /** * The name of the context element. A name of the file or a code snippet. */ name: string; /** * The content of the context element. The body of the file or a function. */ content: string; /** * Where the context was derived from */ resolution_strategy: ContextResolution['strategy']; }; // FIXME: Rename to SuggestionOptionText and then rename SuggestionOptionOrStream to SuggestionOption // this refactor can't be done now (2024-05-28) because all the conflicts it would cause with WIP export interface SuggestionOption { index?: number; text: string; uniqueTrackingId: string; lang?: string; } export interface TelemetryRequest { event: string; additional_properties: { unique_tracking_id: string; language?: string; suggestion_size?: number; timestamp: string; }; } References: - src/common/api_types.ts:31 - packages/webview_duo_chat/src/plugin/types.ts:41 - packages/webview_duo_chat/src/plugin/types.ts:49 - src/common/api_types.ts:23 - packages/webview_duo_chat/src/plugin/types.ts:65 - src/common/api_types.ts:47" You are a code assistant,Definition of 'WORKSPACE_FOLDER_URI' in file src/tests/int/test_utils.ts in project gitlab-lsp,"Definition: export const WORKSPACE_FOLDER_URI: URI = 'file://base/path'; export const MOCK_FILE_1 = { uri: `${WORKSPACE_FOLDER_URI}/some-file.js`, languageId: 'javascript', version: 0, text: '', }; export const MOCK_FILE_2 = { uri: `${WORKSPACE_FOLDER_URI}/some-other-file.js`, languageId: 'javascript', version: 0, text: '', }; declare global { // eslint-disable-next-line @typescript-eslint/no-namespace namespace jest { interface Matchers { toEventuallyContainChildProcessConsoleOutput( expectedMessage: string, timeoutMs?: number, intervalMs?: number, ): Promise; } } } expect.extend({ /** * Custom matcher to check the language client child process console output for an expected string. * This is useful when an operation does not directly run some logic, (e.g. internally emits events * which something later does the thing you're testing), so you cannot just await and check the output. * * await expect(lsClient).toEventuallyContainChildProcessConsoleOutput('foo'); * * @param lsClient LspClient instance to check * @param expectedMessage Message to check for * @param timeoutMs How long to keep checking before test is considered failed * @param intervalMs How frequently to check the log */ async toEventuallyContainChildProcessConsoleOutput( lsClient: LspClient, expectedMessage: string, timeoutMs = 1000, intervalMs = 25, ) { const expectedResult = `Expected language service child process console output to contain ""${expectedMessage}""`; const checkOutput = () => lsClient.childProcessConsole.some((line) => line.includes(expectedMessage)); const sleep = () => new Promise((resolve) => { setTimeout(resolve, intervalMs); }); let remainingRetries = Math.ceil(timeoutMs / intervalMs); while (remainingRetries > 0) { if (checkOutput()) { return { message: () => expectedResult, pass: true, }; } // eslint-disable-next-line no-await-in-loop await sleep(); remainingRetries--; } return { message: () => `""${expectedResult}"", but it was not found within ${timeoutMs}ms`, pass: false, }; }, }); References:" You are a code assistant,Definition of 'ExtractRequestResult' in file packages/lib_message_bus/src/types/bus.ts in project gitlab-lsp,"Definition: export type ExtractRequestResult = // eslint-disable-next-line @typescript-eslint/no-invalid-void-type T['result'] extends undefined ? void : T; /** * Interface for publishing requests. * @interface * @template {RequestMap} TRequests */ export interface RequestPublisher { sendRequest>( type: T, ): Promise>; sendRequest( type: T, payload: TRequests[T]['params'], ): Promise>; } /** * Interface for listening to requests. * @interface * @template {RequestMap} TRequests */ export interface RequestListener { onRequest>( type: T, handler: () => Promise>, ): Disposable; onRequest( type: T, handler: (payload: TRequests[T]['params']) => Promise>, ): Disposable; } /** * Defines the structure for message definitions, including notifications and requests. */ export type MessageDefinitions< TNotifications extends NotificationMap = NotificationMap, TRequests extends RequestMap = RequestMap, > = { notifications: TNotifications; requests: TRequests; }; export type MessageMap< TInboundMessageDefinitions extends MessageDefinitions = MessageDefinitions, TOutboundMessageDefinitions extends MessageDefinitions = MessageDefinitions, > = { inbound: TInboundMessageDefinitions; outbound: TOutboundMessageDefinitions; }; export interface MessageBus extends NotificationPublisher, NotificationListener, RequestPublisher, RequestListener {} References:" You are a code assistant,Definition of 'BaseRestRequest' in file packages/webview_duo_chat/src/plugin/types.ts in project gitlab-lsp,"Definition: interface BaseRestRequest<_TReturnType> { type: 'rest'; /** * 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; headers?: Record; supportedSinceInstanceVersion?: SupportedSinceInstanceVersion; } interface GraphQLRequest<_TReturnType> { type: 'graphql'; query: string; /** Options passed to the GraphQL query */ variables: Record; 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; supportedSinceInstanceVersion?: SupportedSinceInstanceVersion; } export type ApiRequest<_TReturnType> = | GetRequest<_TReturnType> | PostRequest<_TReturnType> | GraphQLRequest<_TReturnType>; export interface GitLabApiClient { fetchFromApi(request: ApiRequest): Promise; connectToCable(): Promise; } References:" You are a code assistant,Definition of 'RepositoryUri' in file src/common/git/repository_service.ts in project gitlab-lsp,"Definition: type RepositoryUri = string; type WorkspaceFolderUri = string; type RepositoryMap = Map; export type RepositoryService = typeof DefaultRepositoryService.prototype; export const RepositoryService = createInterfaceId('RepositoryService'); @Injectable(RepositoryService, [VirtualFileSystemService]) export class DefaultRepositoryService { #virtualFileSystemService: DefaultVirtualFileSystemService; constructor(virtualFileSystemService: DefaultVirtualFileSystemService) { this.#virtualFileSystemService = virtualFileSystemService; this.#setupEventListeners(); } #setupEventListeners() { return this.#virtualFileSystemService.onFileSystemEvent(async (eventType, data) => { switch (eventType) { case VirtualFileSystemEvents.WorkspaceFilesUpdate: await this.#handleWorkspaceFilesUpdate(data as WorkspaceFilesUpdate); break; case VirtualFileSystemEvents.WorkspaceFileUpdate: await this.#handleWorkspaceFileUpdate(data as WorkspaceFileUpdate); break; default: break; } }); } async #handleWorkspaceFilesUpdate(update: WorkspaceFilesUpdate) { log.info(`Workspace files update: ${update.files.length}`); const perf1 = performance.now(); await this.handleWorkspaceFilesUpdate({ ...update, }); const perf2 = performance.now(); log.info(`Workspace files initialization took ${perf2 - perf1}ms`); const perf3 = performance.now(); const files = this.getFilesForWorkspace(update.workspaceFolder.uri, { excludeGitFolder: true, excludeIgnored: true, }); const perf4 = performance.now(); log.info(`Fetched workspace files in ${perf4 - perf3}ms`); log.info(`Workspace git files: ${files.length}`); // const treeFile = await readFile( // '/Users/angelo.rivera/gitlab/gitlab-development-kit/gitlab/tree.txt', // 'utf-8', // ); // const treeFiles = treeFile.split('\n').filter(Boolean); // // get the set difference between the files in the tree and the non-ignored files // // we need the difference between the two sets to know which files are not in the tree // const diff = new Set( // files.map((file) => // relative('/Users/angelo.rivera/gitlab/gitlab-development-kit/gitlab', file.uri.fsPath), // ), // ); // for (const file of treeFiles) { // diff.delete(file); // } // log.info(`Files not in the tree.txt: ${JSON.stringify(Array.from(diff))}`); } async #handleWorkspaceFileUpdate(update: WorkspaceFileUpdate) { log.info(`Workspace file update: ${JSON.stringify(update)}`); await this.handleWorkspaceFileUpdate({ ...update, }); const perf1 = performance.now(); const files = this.getFilesForWorkspace(update.workspaceFolder.uri, { excludeGitFolder: true, excludeIgnored: true, }); const perf2 = performance.now(); log.info(`Fetched workspace files in ${perf2 - perf1}ms`); log.info(`Workspace git files: ${files.length}`); } /** * unique map of workspace folders that point to a map of repositories * We store separate repository maps for each workspace because * the events from the VFS service are at the workspace level. * If we combined them, we may get race conditions */ #workspaces: Map = new Map(); #workspaceRepositoryTries: Map = new Map(); #buildRepositoryTrie(repositories: Repository[]): RepositoryTrie { const root = new RepositoryTrie(); for (const repo of repositories) { let node = root; const parts = repo.uri.path.split('/').filter(Boolean); for (const part of parts) { if (!node.children.has(part)) { node.children.set(part, new RepositoryTrie()); } node = node.children.get(part) as RepositoryTrie; } node.repository = repo.uri; } return root; } findMatchingRepositoryUri(fileUri: URI, workspaceFolderUri: WorkspaceFolder): URI | null { const trie = this.#workspaceRepositoryTries.get(workspaceFolderUri.uri); if (!trie) return null; let node = trie; let lastMatchingRepo: URI | null = null; const parts = fileUri.path.split('/').filter(Boolean); for (const part of parts) { if (node.repository) { lastMatchingRepo = node.repository; } if (!node.children.has(part)) break; node = node.children.get(part) as RepositoryTrie; } return node.repository || lastMatchingRepo; } getRepositoryFileForUri( fileUri: URI, repositoryUri: URI, workspaceFolder: WorkspaceFolder, ): RepositoryFile | null { const repository = this.#getRepositoriesForWorkspace(workspaceFolder.uri).get( repositoryUri.toString(), ); if (!repository) { return null; } return repository.getFile(fileUri.toString()) ?? null; } #updateRepositoriesForFolder( workspaceFolder: WorkspaceFolder, repositoryMap: RepositoryMap, repositoryTrie: RepositoryTrie, ) { this.#workspaces.set(workspaceFolder.uri, repositoryMap); this.#workspaceRepositoryTries.set(workspaceFolder.uri, repositoryTrie); } async handleWorkspaceFilesUpdate({ workspaceFolder, files }: WorkspaceFilesUpdate) { // clear existing repositories from workspace this.#emptyRepositoriesForWorkspace(workspaceFolder.uri); const repositories = this.#detectRepositories(files, workspaceFolder); const repositoryMap = new Map(repositories.map((repo) => [repo.uri.toString(), repo])); // Build and cache the repository trie for this workspace const trie = this.#buildRepositoryTrie(repositories); this.#updateRepositoriesForFolder(workspaceFolder, repositoryMap, trie); await Promise.all( repositories.map((repo) => repo.addFilesAndLoadGitIgnore( files.filter((file) => { const matchingRepo = this.findMatchingRepositoryUri(file, workspaceFolder); return matchingRepo && matchingRepo.toString() === repo.uri.toString(); }), ), ), ); } async handleWorkspaceFileUpdate({ fileUri, workspaceFolder, event }: WorkspaceFileUpdate) { const repoUri = this.findMatchingRepositoryUri(fileUri, workspaceFolder); if (!repoUri) { log.debug(`No matching repository found for file ${fileUri.toString()}`); return; } const repositoryMap = this.#getRepositoriesForWorkspace(workspaceFolder.uri); const repository = repositoryMap.get(repoUri.toString()); if (!repository) { log.debug(`Repository not found for URI ${repoUri.toString()}`); return; } if (repository.isFileIgnored(fileUri)) { log.debug(`File ${fileUri.toString()} is ignored`); return; } switch (event) { case 'add': repository.setFile(fileUri); log.debug(`File ${fileUri.toString()} added to repository ${repoUri.toString()}`); break; case 'change': repository.setFile(fileUri); log.debug(`File ${fileUri.toString()} updated in repository ${repoUri.toString()}`); break; case 'unlink': repository.removeFile(fileUri.toString()); log.debug(`File ${fileUri.toString()} removed from repository ${repoUri.toString()}`); break; default: log.warn(`Unknown file event ${event} for file ${fileUri.toString()}`); } } #getRepositoriesForWorkspace(workspaceFolderUri: WorkspaceFolderUri): RepositoryMap { return this.#workspaces.get(workspaceFolderUri) || new Map(); } #emptyRepositoriesForWorkspace(workspaceFolderUri: WorkspaceFolderUri): void { log.debug(`Emptying repositories for workspace ${workspaceFolderUri}`); const repos = this.#workspaces.get(workspaceFolderUri); if (!repos || repos.size === 0) return; // clear up ignore manager trie from memory repos.forEach((repo) => { repo.dispose(); log.debug(`Repository ${repo.uri} has been disposed`); }); repos.clear(); const trie = this.#workspaceRepositoryTries.get(workspaceFolderUri); if (trie) { trie.dispose(); this.#workspaceRepositoryTries.delete(workspaceFolderUri); } this.#workspaces.delete(workspaceFolderUri); log.debug(`Repositories for workspace ${workspaceFolderUri} have been emptied`); } #detectRepositories(files: URI[], workspaceFolder: WorkspaceFolder): Repository[] { const gitConfigFiles = files.filter((file) => file.toString().endsWith('.git/config')); return gitConfigFiles.map((file) => { const projectUri = fsPathToUri(file.path.replace('.git/config', '')); const ignoreManager = new IgnoreManager(projectUri.fsPath); log.info(`Detected repository at ${projectUri.path}`); return new Repository({ ignoreManager, uri: projectUri, configFileUri: file, workspaceFolder, }); }); } getFilesForWorkspace( workspaceFolderUri: WorkspaceFolderUri, options: { excludeGitFolder?: boolean; excludeIgnored?: boolean } = {}, ): RepositoryFile[] { const repositories = this.#getRepositoriesForWorkspace(workspaceFolderUri); const allFiles: RepositoryFile[] = []; repositories.forEach((repository) => { repository.getFiles().forEach((file) => { // apply the filters if (options.excludeGitFolder && this.#isInGitFolder(file.uri, repository.uri)) { return; } if (options.excludeIgnored && file.isIgnored) { return; } allFiles.push(file); }); }); return allFiles; } // Helper method to check if a file is in the .git folder #isInGitFolder(fileUri: URI, repositoryUri: URI): boolean { const relativePath = fileUri.path.slice(repositoryUri.path.length); return relativePath.split('/').some((part) => part === '.git'); } } References: - src/common/git/repository.ts:11 - src/common/git/repository.ts:34" You are a code assistant,Definition of 'WebviewInstanceInfo' in file packages/lib_webview_transport_socket_io/src/types.ts in project gitlab-lsp,"Definition: export type WebviewInstanceInfo = { webviewId: WebviewId; webviewInstanceId: WebviewInstanceId; }; References: - packages/lib_webview_transport_socket_io/src/utils/connection_utils.ts:6 - packages/lib_webview_transport_socket_io/src/socket_io_webview_transport.ts:58" You are a code assistant,Definition of 'warn' in file src/common/log_types.ts in project gitlab-lsp,"Definition: warn(e: Error): void; warn(message: string, e?: Error): void; error(e: Error): void; error(message: string, e?: Error): void; } 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 'parseFile' in file src/common/tree_sitter/parser.ts in project gitlab-lsp,"Definition: async parseFile(context: IDocContext): Promise { 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 { 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 { 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 { return languages.reduce((map, language) => { for (const extension of language.extensions) { map.set(extension, language); } return map; }, new Map()); } } References:" You are a code assistant,Definition of 'greet' in file src/tests/fixtures/intent/empty_function/typescript.ts in project gitlab-lsp,"Definition: greet() { console.log(`Hello ${this.name}`); } } class Greet3 {} function* generateGreetings() {} function* greetGenerator() { yield 'Hello'; } References: - 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 - src/tests/fixtures/intent/empty_function/ruby.rb:29" You are a code assistant,Definition of 'handle' in file packages/lib_handler_registry/src/registry/simple_registry.ts in project gitlab-lsp,"Definition: async handle(key: string, ...args: Parameters): Promise> { const handler = this.#handlers.get(key); if (!handler) { throw new HandlerNotFoundError(key); } try { const handlerResult = await handler(...args); return handlerResult as ReturnType; } catch (error) { throw new UnhandledHandlerError(key, resolveError(error)); } } dispose() { this.#handlers.clear(); } } function resolveError(e: unknown): Error { if (e instanceof Error) { return e; } if (typeof e === 'string') { return new Error(e); } return new Error('Unknown error'); } References:" You are a code assistant,Definition of 'hasbinFirstSync' in file src/tests/int/hasbin.ts in project gitlab-lsp,"Definition: export function hasbinFirstSync(bins: string[]) { const matched = bins.filter(hasbin.sync); return matched.length ? matched[0] : false; } export function getPaths(bin: string) { const envPath = process.env.PATH || ''; const envExt = process.env.PATHEXT || ''; return envPath .replace(/[""]+/g, '') .split(delimiter) .map(function (chunk) { return envExt.split(delimiter).map(function (ext) { return join(chunk, bin + ext); }); }) .reduce(function (a, b) { return a.concat(b); }); } 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 'onOpen' in file src/common/circuit_breaker/circuit_breaker.ts in project gitlab-lsp,"Definition: onOpen(listener: () => void): Disposable; onClose(listener: () => void): Disposable; } References:" You are a code assistant,Definition of 'has' in file packages/lib_handler_registry/src/registry/simple_registry.ts in project gitlab-lsp,"Definition: has(key: string) { return this.#handlers.has(key); } async handle(key: string, ...args: Parameters): Promise> { const handler = this.#handlers.get(key); if (!handler) { throw new HandlerNotFoundError(key); } try { const handlerResult = await handler(...args); return handlerResult as ReturnType; } catch (error) { throw new UnhandledHandlerError(key, resolveError(error)); } } dispose() { this.#handlers.clear(); } } function resolveError(e: unknown): Error { if (e instanceof Error) { return e; } if (typeof e === 'string') { return new Error(e); } return new Error('Unknown error'); } References:" You are a code assistant,Definition of 'MessageHandlerOptions' in file src/common/message_handler.ts in project gitlab-lsp,"Definition: 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 => { 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:97" You are a code assistant,Definition of 'ExtensionMessageBusProvider' in file packages/lib_webview/src/types.ts in project gitlab-lsp,"Definition: export interface ExtensionMessageBusProvider { getMessageBus(webviewId: WebviewId): MessageBus; } References: - packages/lib_webview/src/setup/setup_webview_runtime.ts:11 - packages/lib_webview/src/setup/plugin/setup_plugins.ts:11" 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: References:" You are a code assistant,Definition of 'MessageHandler' in file src/common/message_handler.ts in project gitlab-lsp,"Definition: 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 => { 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/connection.ts:48 - src/common/message_handler.test.ts:141 - src/common/message_handler.test.ts:213 - src/common/message_handler.test.ts:40 - src/common/message_handler.test.ts:105" You are a code assistant,Definition of 'Processor1' in file src/common/suggestion_client/post_processors/post_processor_pipeline.test.ts in project gitlab-lsp,"Definition: class Processor1 extends PostProcessor { async processStream( _context: IDocContext, input: StreamingCompletionResponse, ): Promise { return input; } async processCompletion( _context: IDocContext, input: SuggestionOption[], ): Promise { return input.map((option) => ({ ...option, text: `${option.text} [1]` })); } } class Processor2 extends PostProcessor { async processStream( _context: IDocContext, input: StreamingCompletionResponse, ): Promise { return input; } async processCompletion( _context: IDocContext, input: SuggestionOption[], ): Promise { return input.map((option) => ({ ...option, text: `${option.text} [2]` })); } } pipeline.addProcessor(new Processor1()); pipeline.addProcessor(new Processor2()); const completionInput: SuggestionOption[] = [{ text: 'option1', uniqueTrackingId: '1' }]; const result = await pipeline.run({ documentContext: mockContext, input: completionInput, type: 'completion', }); expect(result).toEqual([{ text: 'option1 [1] [2]', uniqueTrackingId: '1' }]); }); test('should throw an error for unexpected type', async () => { class TestProcessor extends PostProcessor { async processStream( _context: IDocContext, input: StreamingCompletionResponse, ): Promise { return input; } async processCompletion( _context: IDocContext, input: SuggestionOption[], ): Promise { 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: - src/common/suggestion_client/post_processors/post_processor_pipeline.test.ts:162 - src/common/suggestion_client/post_processors/post_processor_pipeline.test.ts:116" 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 const AiContextPolicyManager = createInterfaceId('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:30 - src/common/ai_context_management_2/ai_context_aggregator.ts:26" You are a code assistant,Definition of 'AiContextItem' in file src/common/ai_context_management_2/ai_context_item.ts in project gitlab-lsp,"Definition: export type AiContextItem = { id: string; name: string; isEnabled: boolean; info: AiContextItemInfo; type: AiContextItemType; } & ( | { type: 'issue' | 'merge_request'; subType?: never } | { type: 'file'; subType: AiContextItemSubType } ); export type AiContextItemWithContent = AiContextItem & { content: string; }; References: - src/common/ai_context_management_2/retrievers/ai_context_retriever.ts:4 - src/common/ai_context_management_2/ai_context_manager.ts:21 - src/common/ai_context_management_2/retrievers/ai_file_context_retriever.ts:21 - src/common/connection_service.ts:112" You are a code assistant,Definition of 'ResponseError' in file packages/webview_duo_chat/src/plugin/port/platform/web_ide.ts in project gitlab-lsp,"Definition: export interface ResponseError extends Error { status: number; body?: unknown; } References:" You are a code assistant,Definition of 'WebviewController' in file packages/lib_webview/src/setup/plugin/webview_controller.ts in project gitlab-lsp,"Definition: export class WebviewController implements WebviewConnection, Disposable { readonly webviewId: WebviewId; #messageBusFactory: WebviewMessageBusFactory; #handlers = new Set>(); #instanceInfos = new Map(); #compositeDisposable = new CompositeDisposable(); #logger: Logger; constructor( webviewId: WebviewId, runtimeMessageBus: WebviewRuntimeMessageBus, messageBusFactory: WebviewMessageBusFactory, logger: Logger, ) { this.#logger = withPrefix(logger, `[WebviewController:${webviewId}]`); this.webviewId = webviewId; this.#messageBusFactory = messageBusFactory; this.#subscribeToEvents(runtimeMessageBus); } broadcast( type: TMethod, payload: T['outbound']['notifications'][TMethod], ) { for (const info of this.#instanceInfos.values()) { info.messageBus.sendNotification(type.toString(), payload); } } onInstanceConnected(handler: WebviewMessageBusManagerHandler) { this.#handlers.add(handler); for (const [instanceId, info] of this.#instanceInfos) { const disposable = handler(instanceId, info.messageBus); if (isDisposable(disposable)) { info.pluginCallbackDisposables.add(disposable); } } } dispose(): void { this.#compositeDisposable.dispose(); this.#instanceInfos.forEach((info) => info.messageBus.dispose()); this.#instanceInfos.clear(); } #subscribeToEvents(runtimeMessageBus: WebviewRuntimeMessageBus) { const eventFilter = buildWebviewIdFilter(this.webviewId); this.#compositeDisposable.add( runtimeMessageBus.subscribe('webview:connect', this.#handleConnected.bind(this), eventFilter), runtimeMessageBus.subscribe( 'webview:disconnect', this.#handleDisconnected.bind(this), eventFilter, ), ); } #handleConnected(address: WebviewAddress) { this.#logger.debug(`Instance connected: ${address.webviewInstanceId}`); if (this.#instanceInfos.has(address.webviewInstanceId)) { // we are already connected with this webview instance return; } const messageBus = this.#messageBusFactory(address); const pluginCallbackDisposables = new CompositeDisposable(); this.#instanceInfos.set(address.webviewInstanceId, { messageBus, pluginCallbackDisposables, }); this.#handlers.forEach((handler) => { const disposable = handler(address.webviewInstanceId, messageBus); if (isDisposable(disposable)) { pluginCallbackDisposables.add(disposable); } }); } #handleDisconnected(address: WebviewAddress) { this.#logger.debug(`Instance disconnected: ${address.webviewInstanceId}`); const instanceInfo = this.#instanceInfos.get(address.webviewInstanceId); if (!instanceInfo) { // we aren't tracking this instance return; } instanceInfo.pluginCallbackDisposables.dispose(); instanceInfo.messageBus.dispose(); this.#instanceInfos.delete(address.webviewInstanceId); } } References: - packages/lib_webview/src/setup/plugin/webview_controller.test.ts:32 - packages/lib_webview/src/setup/plugin/setup_plugins.ts:34" You are a code assistant,Definition of 'Uri' in file src/common/webview/webview_resource_location_service.ts in project gitlab-lsp,"Definition: type Uri = string; export interface WebviewUriProvider { getUri(webviewId: WebviewId): Uri; } export interface WebviewUriProviderRegistry { register(provider: WebviewUriProvider): void; } export class WebviewLocationService implements WebviewUriProviderRegistry { #uriProviders = new Set(); 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: - src/common/webview/webview_resource_location_service.ts:6" You are a code assistant,Definition of 'main' in file src/browser/main.ts in project gitlab-lsp,"Definition: async function main() { // eslint-disable-next-line no-restricted-globals const worker: Worker = self as unknown as Worker; const messageReader = new BrowserMessageReader(worker); const messageWriter = new BrowserMessageWriter(worker); const container = new Container(); container.instantiate(DefaultConfigService, DefaultSupportedLanguagesService); const lsFetch = new Fetch(); container.addInstances(brandInstance(LsFetch, lsFetch)); const connection = createConnection(ProposedFeatures.all, messageReader, messageWriter); container.addInstances(brandInstance(LsConnection, connection)); const documents: TextDocuments = new TextDocuments(TextDocument); container.addInstances(brandInstance(LsTextDocuments, documents)); const configService = container.get(ConfigService); const documentService = new DefaultDocumentService(documents); container.addInstances(brandInstance(DocumentService, documentService)); container.instantiate( GitLabAPI, DefaultDocumentTransformerService, DefaultFeatureFlagService, DefaultTokenCheckNotifier, DefaultSecretRedactor, DefaultSecurityDiagnosticsPublisher, DefaultConnectionService, DefaultInitializeHandler, DefaultCodeSuggestionsSupportedLanguageCheck, DefaultProjectDuoAccessCheck, DefaultFeatureStateManager, DefaultAdvancedContextService, DefaultDuoProjectAccessChecker, DefaultDuoProjectAccessCache, DefaultVirtualFileSystemService, DefaultRepositoryService, DefaultWorkspaceService, DefaultDirectoryWalker, EmptyFileResolver, ); const snowplowTracker = new SnowplowTracker( lsFetch, container.get(ConfigService), container.get(FeatureFlagService), container.get(GitLabApiClient), ); const instanceTracker = new InstanceTracker( container.get(GitLabApiClient), container.get(ConfigService), ); const telemetryTracker = new MultiTracker([snowplowTracker, instanceTracker]); container.addInstances(brandInstance(TelemetryTracker, telemetryTracker)); const treeSitterParser = new BrowserTreeSitterParser(configService); log.setup(configService); const version = getLanguageServerVersion(); log.info(`GitLab Language Server is starting (v${version})`); await lsFetch.initialize(); setup( telemetryTracker, connection, container.get(DocumentTransformerService), container.get(GitLabApiClient), container.get(FeatureFlagService), configService, { treeSitterParser, }, undefined, undefined, container.get(DuoProjectAccessChecker), container.get(DuoProjectAccessCache), container.get(VirtualFileSystemService), ); // Make the text document manager listen on the connection for open, change and close text document events documents.listen(connection); // Listen on the connection connection.listen(); log.info('GitLab Language Server has started'); } main().catch((e) => log.error(e)); References: - src/browser/main.ts:147 - src/node/main.ts:238" You are a code assistant,Definition of 'delete' in file src/common/fetch.ts in project gitlab-lsp,"Definition: delete(input: RequestInfo | URL, init?: RequestInit): Promise; get(input: RequestInfo | URL, init?: RequestInit): Promise; post(input: RequestInfo | URL, init?: RequestInit): Promise; put(input: RequestInfo | URL, init?: RequestInit): Promise; updateAgentOptions(options: FetchAgentOptions): void; streamFetch(url: string, body: string, headers: FetchHeaders): AsyncGenerator; } export const LsFetch = createInterfaceId('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 {} async destroy(): Promise {} async fetch(input: RequestInfo | URL, init?: RequestInit): Promise { 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 { // Stub. Should delegate to the node or browser fetch implementations throw new Error('Not implemented'); yield ''; } async delete(input: RequestInfo | URL, init?: RequestInit): Promise { return this.fetch(input, this.updateRequestInit('DELETE', init)); } async get(input: RequestInfo | URL, init?: RequestInit): Promise { return this.fetch(input, this.updateRequestInit('GET', init)); } async post(input: RequestInfo | URL, init?: RequestInit): Promise { return this.fetch(input, this.updateRequestInit('POST', init)); } async put(input: RequestInfo | URL, init?: RequestInit): Promise { return this.fetch(input, this.updateRequestInit('PUT', init)); } async fetchBase(input: RequestInfo | URL, init?: RequestInit): Promise { // 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 'DefaultFeatureStateManager' in file src/common/feature_state/feature_state_manager.ts in project gitlab-lsp,"Definition: export class DefaultFeatureStateManager implements FeatureStateManager { #checks: StateCheck[] = []; #subscriptions: Disposable[] = []; #notify?: NotifyFn; constructor( supportedLanguagePolicy: CodeSuggestionsSupportedLanguageCheck, projectDuoAccessCheck: ProjectDuoAccessCheck, ) { this.#checks.push(supportedLanguagePolicy, projectDuoAccessCheck); this.#subscriptions.push( ...this.#checks.map((check) => check.onChanged(() => this.#notifyClient())), ); } init(notify: NotifyFn): void { this.#notify = notify; } async #notifyClient() { if (!this.#notify) { throw new Error( ""The state manager hasn't been initialized. It can't send notifications. Call the init method first."", ); } await this.#notify(this.#state); } dispose() { this.#subscriptions.forEach((s) => s.dispose()); } get #state(): FeatureState[] { const engagedChecks = this.#checks.filter((check) => check.engaged); return getEntries(CHECKS_PER_FEATURE).map(([featureId, stateChecks]) => { const engagedFeatureChecks: FeatureStateCheck[] = engagedChecks .filter(({ id }) => stateChecks.includes(id)) .map((stateCheck) => ({ checkId: stateCheck.id, details: stateCheck.details, })); return { featureId, engagedChecks: engagedFeatureChecks, }; }); } } References: - src/common/feature_state/feature_state_manager.test.ts:44" You are a code assistant,Definition of 'run' in file src/common/suggestion_client/post_processors/post_processor_pipeline.ts in project gitlab-lsp,"Definition: async run({ documentContext, input, type, }: { documentContext: IDocContext; input: ProcessorInputMap[T]; type: T; }): Promise { if (!this.#processors.length) return input as ProcessorInputMap[T]; return this.#processors.reduce( async (prevPromise, processor) => { const result = await prevPromise; // eslint-disable-next-line default-case switch (type) { case 'stream': return processor.processStream( documentContext, result as StreamingCompletionResponse, ) as Promise; case 'completion': return processor.processCompletion( documentContext, result as SuggestionOption[], ) as Promise; } throw new Error('Unexpected type in pipeline processing'); }, Promise.resolve(input) as Promise, ); } } References: - scripts/watcher/watch.ts:99 - scripts/commit-lint/lint.js:93 - scripts/watcher/watch.ts:95 - scripts/watcher/watch.ts:87" You are a code assistant,Definition of 'DefaultTokenCheckNotifier' in file src/common/core/handlers/token_check_notifier.ts in project gitlab-lsp,"Definition: export class DefaultTokenCheckNotifier implements TokenCheckNotifier { #notify: NotifyFn | undefined; constructor(api: GitLabApiClient) { api.onApiReconfigured(async ({ isInValidState, validationMessage }) => { if (!isInValidState) { if (!this.#notify) { throw new Error( 'The DefaultTokenCheckNotifier has not been initialized. Call init first.', ); } await this.#notify({ message: validationMessage, }); } }); } init(callback: NotifyFn) { this.#notify = callback; } } References: - src/common/core/handlers/token_check_notifier.test.ts:26" You are a code assistant,Definition of 'constructor' in file src/common/suggestion/suggestions_cache.ts in project gitlab-lsp,"Definition: constructor(configService: ConfigService) { this.#configService = configService; const currentConfig = this.#getCurrentConfig(); this.#cache = new LRUCache({ 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 { 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 'СodeSuggestionContext' in file src/common/tracking/instance_tracker.ts in project gitlab-lsp,"Definition: interface СodeSuggestionContext { language?: string; suggestion_size?: number; timestamp: string; is_streaming?: boolean; } export class InstanceTracker implements TelemetryTracker { #api: GitLabApiClient; #codeSuggestionsContextMap = new Map(); #circuitBreaker = new FixedTimeCircuitBreaker('Instance telemetry'); #configService: ConfigService; #options: ITelemetryOptions = { enabled: true, actions: [], }; #codeSuggestionStates = new Map(); // API used for tracking events is available since GitLab v17.2.0. // Given the track request is done for each CS request // we need to make sure we do not log the unsupported instance message many times #invalidInstanceMsgLogged = false; constructor(api: GitLabApiClient, configService: ConfigService) { this.#configService = configService; this.#configService.onConfigChange((config) => this.#reconfigure(config)); this.#api = api; } #reconfigure(config: IConfig) { const { baseUrl } = config.client; 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(`Instance Telemetry: ${TELEMETRY_DISABLED_WARNING_MSG}`); } else if (enabled === true) { log.info(`Instance Telemetry: ${TELEMETRY_ENABLED_MSG}`); } } if (baseUrl) { this.#options.baseUrl = baseUrl; } if (actions) { this.#options.actions = actions; } } isEnabled(): boolean { return Boolean(this.#options.enabled); } public setCodeSuggestionsContext( uniqueTrackingId: string, context: Partial, ) { if (this.#circuitBreaker.isOpen()) { return; } const { language, isStreaming } = context; // 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); this.#codeSuggestionsContextMap.set(uniqueTrackingId, { is_streaming: isStreaming, language, timestamp: new Date().toISOString(), }); if (this.#isStreamingSuggestion(uniqueTrackingId)) return; this.#codeSuggestionStates.set(uniqueTrackingId, TRACKING_EVENTS.REQUESTED); this.#trackCodeSuggestionsEvent(TRACKING_EVENTS.REQUESTED, uniqueTrackingId).catch((e) => log.warn('Instance telemetry: Could not track telemetry', e), ); log.debug(`Instance telemetry: New suggestion ${uniqueTrackingId} has been requested`); } async updateCodeSuggestionsContext( uniqueTrackingId: string, contextUpdate: Partial, ) { if (this.#circuitBreaker.isOpen()) { return; } if (this.#isStreamingSuggestion(uniqueTrackingId)) return; const context = this.#codeSuggestionsContextMap.get(uniqueTrackingId); const { model, suggestionOptions, isStreaming } = contextUpdate; if (context) { if (model) { context.language = model.lang ?? null; } if (suggestionOptions?.length) { context.suggestion_size = InstanceTracker.#suggestionSize(suggestionOptions); } if (typeof isStreaming === 'boolean') { context.is_streaming = isStreaming; } this.#codeSuggestionsContextMap.set(uniqueTrackingId, context); } } updateSuggestionState(uniqueTrackingId: string, newState: TRACKING_EVENTS): void { if (this.#circuitBreaker.isOpen()) { return; } if (!this.isEnabled()) return; if (this.#isStreamingSuggestion(uniqueTrackingId)) return; const state = this.#codeSuggestionStates.get(uniqueTrackingId); if (!state) { log.debug(`Instance telemetry: The suggestion with ${uniqueTrackingId} can't be found`); return; } const allowedTransitions = nonStreamingSuggestionStateGraph.get(state); if (!allowedTransitions) { log.debug( `Instance telemetry: The suggestion's ${uniqueTrackingId} state ${state} can't be found in state graph`, ); return; } if (!allowedTransitions.includes(newState)) { log.debug( `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( `Instance telemetry: Conditionally allowing transition to accepted state for ${uniqueTrackingId}`, ); } this.#codeSuggestionStates.set(uniqueTrackingId, newState); this.#trackCodeSuggestionsEvent(newState, uniqueTrackingId).catch((e) => log.warn('Instance telemetry: Could not track telemetry', e), ); log.debug(`Instance telemetry: ${uniqueTrackingId} transisted from ${state} to ${newState}`); } async #trackCodeSuggestionsEvent(eventType: TRACKING_EVENTS, uniqueTrackingId: string) { const event = INSTANCE_TRACKING_EVENTS_MAP[eventType]; if (!event) { return; } try { const { language, suggestion_size } = this.#codeSuggestionsContextMap.get(uniqueTrackingId) ?? {}; await this.#api.fetchFromApi({ type: 'rest', method: 'POST', path: '/usage_data/track_event', body: { event, additional_properties: { unique_tracking_id: uniqueTrackingId, timestamp: new Date().toISOString(), language, suggestion_size, }, }, supportedSinceInstanceVersion: { resourceName: 'track instance telemetry', version: '17.2.0', }, }); this.#circuitBreaker.success(); } catch (error) { if (error instanceof InvalidInstanceVersionError) { if (this.#invalidInstanceMsgLogged) return; this.#invalidInstanceMsgLogged = true; } log.warn(`Instance telemetry: Failed to track event: ${eventType}`, error); this.#circuitBreaker.error(); } } rejectOpenedSuggestions() { log.debug(`Instance Telemetry: Reject all opened suggestions`); this.#codeSuggestionStates.forEach((state, uniqueTrackingId) => { if (endStates.includes(state)) { return; } this.updateSuggestionState(uniqueTrackingId, TRACKING_EVENTS.REJECTED); }); } static #suggestionSize(options: SuggestionOption[]): number { const countLines = (text: string) => (text ? text.split('\n').length : 0); return Math.max(...options.map(({ text }) => countLines(text))); } #isStreamingSuggestion(uniqueTrackingId: string): boolean { return Boolean(this.#codeSuggestionsContextMap.get(uniqueTrackingId)?.is_streaming); } } References:" You are a code assistant,Definition of 'error' in file packages/lib_logging/src/types.ts in project gitlab-lsp,"Definition: error(e: Error): void; error(message: string, e?: Error): void; } References: - scripts/commit-lint/lint.js:72 - scripts/commit-lint/lint.js:77 - scripts/commit-lint/lint.js:85 - scripts/commit-lint/lint.js:94" You are a code assistant,Definition of 'HandlesNotification' in file src/common/handler.ts in project gitlab-lsp,"Definition: export interface HandlesNotification

{ notificationHandler: NotificationHandler

; } References:" You are a code assistant,Definition of 'getStreamingCodeSuggestions' in file src/common/api.ts in project gitlab-lsp,"Definition: async *getStreamingCodeSuggestions( request: CodeSuggestionRequest, ): AsyncGenerator { if (!this.#token) { throw new Error('Token needs to be provided to stream code suggestions'); } const headers = { ...this.#getDefaultHeaders(this.#token), 'Content-Type': 'application/json', }; yield* this.#lsFetch.streamFetch( `${this.#baseURL}/api/v4/code_suggestions/completions`, JSON.stringify(request), headers, ); } async fetchFromApi(request: ApiRequest): Promise { if (!this.#token) { return Promise.reject(new Error('Token needs to be provided to authorise API request.')); } if ( request.supportedSinceInstanceVersion && !this.#instanceVersionHigherOrEqualThen(request.supportedSinceInstanceVersion.version) ) { return Promise.reject( new InvalidInstanceVersionError( `Can't ${request.supportedSinceInstanceVersion.resourceName} until your instance is upgraded to ${request.supportedSinceInstanceVersion.version} or higher.`, ), ); } if (request.type === 'graphql') { return this.#graphqlRequest(request.query, request.variables); } switch (request.method) { case 'GET': return this.#fetch(request.path, request.searchParams, 'resource', request.headers); case 'POST': return this.#postFetch(request.path, 'resource', request.body, request.headers); default: // the type assertion is necessary because TS doesn't expect any other types throw new Error(`Unknown request type ${(request as ApiRequest).type}`); } } async connectToCable(): Promise { const headers = this.#getDefaultHeaders(this.#token); const websocketOptions = { headers: { ...headers, Origin: this.#baseURL, }, }; return connectToCable(this.#baseURL, websocketOptions); } async #graphqlRequest( document: RequestDocument, variables?: V, ): Promise { const ensureEndsWithSlash = (url: string) => url.replace(/\/?$/, '/'); const endpoint = new URL('./api/graphql', ensureEndsWithSlash(this.#baseURL)).href; // supports GitLab instances that are on a custom path, e.g. ""https://example.com/gitlab"" const graphqlFetch = async ( input: RequestInfo | URL, init?: RequestInit, ): Promise => { const url = input instanceof URL ? input.toString() : input; return this.#lsFetch.post(url, { ...init, headers: { ...headers, ...init?.headers }, }); }; const headers = this.#getDefaultHeaders(this.#token); const client = new GraphQLClient(endpoint, { headers, fetch: graphqlFetch, }); return client.request(document, variables); } async #fetch( apiResourcePath: string, query: Record = {}, resourceName = 'resource', headers?: Record, ): Promise { const url = `${this.#baseURL}/api/v4${apiResourcePath}${createQueryString(query)}`; const result = await this.#lsFetch.get(url, { headers: { ...this.#getDefaultHeaders(this.#token), ...headers }, }); await handleFetchError(result, resourceName); return result.json() as Promise; } async #postFetch( apiResourcePath: string, resourceName = 'resource', body?: unknown, headers?: Record, ): Promise { const url = `${this.#baseURL}/api/v4${apiResourcePath}`; const response = await this.#lsFetch.post(url, { headers: { 'Content-Type': 'application/json', ...this.#getDefaultHeaders(this.#token), ...headers, }, body: JSON.stringify(body), }); await handleFetchError(response, resourceName); return response.json() as Promise; } #getDefaultHeaders(token?: string) { return { Authorization: `Bearer ${token}`, 'User-Agent': `code-completions-language-server-experiment (${this.#clientInfo?.name}:${this.#clientInfo?.version})`, 'X-Gitlab-Language-Server-Version': getLanguageServerVersion(), }; } #instanceVersionHigherOrEqualThen(version: string): boolean { if (!this.#instanceVersion) return false; return semverCompare(this.#instanceVersion, version) >= 0; } async #getGitLabInstanceVersion(): Promise { if (!this.#token) { return ''; } const headers = this.#getDefaultHeaders(this.#token); const response = await this.#lsFetch.get(`${this.#baseURL}/api/v4/version`, { headers, }); const { version } = await response.json(); return version; } get instanceVersion() { return this.#instanceVersion; } } References:" You are a code assistant,Definition of 'KeysWithOptionalParams' in file packages/lib_message_bus/src/types/bus.ts in project gitlab-lsp,"Definition: type KeysWithOptionalParams = { [K in keyof R]: R[K]['params'] extends undefined ? never : K; }[keyof R]; /** * Extracts the response payload type from a request type. * @template {MessagePayload} T * @typedef {T extends [never] ? void : T[0]} ExtractRequestResponse */ export type ExtractRequestResult = // eslint-disable-next-line @typescript-eslint/no-invalid-void-type T['result'] extends undefined ? void : T; /** * Interface for publishing requests. * @interface * @template {RequestMap} TRequests */ export interface RequestPublisher { sendRequest>( type: T, ): Promise>; sendRequest( type: T, payload: TRequests[T]['params'], ): Promise>; } /** * Interface for listening to requests. * @interface * @template {RequestMap} TRequests */ export interface RequestListener { onRequest>( type: T, handler: () => Promise>, ): Disposable; onRequest( type: T, handler: (payload: TRequests[T]['params']) => Promise>, ): Disposable; } /** * Defines the structure for message definitions, including notifications and requests. */ export type MessageDefinitions< TNotifications extends NotificationMap = NotificationMap, TRequests extends RequestMap = RequestMap, > = { notifications: TNotifications; requests: TRequests; }; export type MessageMap< TInboundMessageDefinitions extends MessageDefinitions = MessageDefinitions, TOutboundMessageDefinitions extends MessageDefinitions = MessageDefinitions, > = { inbound: TInboundMessageDefinitions; outbound: TOutboundMessageDefinitions; }; export interface MessageBus extends NotificationPublisher, NotificationListener, RequestPublisher, RequestListener {} References:" You are a code assistant,Definition of 'withJsonRpcMessageValidation' in file packages/lib_webview_transport_json_rpc/src/utils/with_json_rpc_message_validation.ts in project gitlab-lsp,"Definition: export function withJsonRpcMessageValidation( validator: MessageValidator, logger: Logger | undefined, action: (message: T) => void, ): (message: unknown) => void { return (message: unknown) => { if (!validator(message)) { logger?.error(`Invalid JSON-RPC message: ${JSON.stringify(message)}`); return; } action(message); }; } References: - packages/lib_webview_transport_json_rpc/src/json_rpc_connection_transport.ts:38 - packages/lib_webview_transport_json_rpc/src/utils/with_json_rpc_message_validation.test.ts:35 - packages/lib_webview_transport_json_rpc/src/json_rpc_connection_transport.ts:46 - packages/lib_webview_transport_json_rpc/src/utils/with_json_rpc_message_validation.test.ts:23 - packages/lib_webview_transport_json_rpc/src/json_rpc_connection_transport.ts:30 - packages/lib_webview_transport_json_rpc/src/utils/with_json_rpc_message_validation.test.ts:12" You are a code assistant,Definition of 'IIDEInfo' in file src/common/tracking/tracking_types.ts in project gitlab-lsp,"Definition: export interface IIDEInfo { name: string; version: string; vendor: string; } 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, ): void; updateCodeSuggestionsContext( uniqueTrackingId: string, contextUpdate: Partial, ): void; rejectOpenedSuggestions(): void; updateSuggestionState(uniqueTrackingId: string, newState: TRACKING_EVENTS): void; } export const TelemetryTracker = createInterfaceId('TelemetryTracker'); References: - src/common/tracking/tracking_types.ts:46 - src/common/tracking/tracking_types.ts:55" You are a code assistant,Definition of 'TypedGetter' in file src/common/utils/type_utils.d.ts in project gitlab-lsp,"Definition: export interface TypedGetter { (): T; (key: `${K1 extends string ? K1 : never}`): T[K1]; /* * from 2nd level down, we need to qualify the values with `NonNullable` utility. * without doing that, we could possibly end up with a type `never` * as long as any key in the string concatenation is `never`, the concatenated type becomes `never` * and with deep nesting, without the `NonNullable`, there could always be at lest one `never` because of optional parameters in T */ >(key: `${K1 extends string ? K1 : never}.${K2 extends string ? K2 : never}`): NonNullable[K2] | undefined; , K3 extends keyof NonNullable[K2]>>(key: `${K1 extends string ? K1 : never}.${K2 extends string ? K2 : never}.${K3 extends string ? K3 : never}`): NonNullable[K2]>[K3] | undefined; } /* TypedSetter allows type-safe setting of nested properties of an object */ // there is no benefit in readability from formatting this type utility // prettier-ignore export interface TypedSetter { (key: `${K1 extends string ? K1 : never}`, value: T[K1]): void; /* * from 2nd level down, we need to qualify the values with `NonNullable` utility. * without doing that, we could possibly end up with a type `never` * as long as any key in the string concatenation is `never`, the concatenated type becomes `never` * and with deep nesting, without the `NonNullable`, there could always be at lest one `never` because of optional parameters in T */ >(key: `${K1 extends string ? K1 : never}.${K2 extends string ? K2 : never}`, value: T[K1][K2]): void; , K3 extends keyof NonNullable[K2]>>(key: `${K1 extends string ? K1 : never}.${K2 extends string ? K2 : never}.${K3 extends string ? K3 : never}`, value: T[K1][K2][K3]): void; } References:" You are a code assistant,Definition of 'Validator' in file packages/lib_di/src/index.ts in project gitlab-lsp,"Definition: type Validator = (cwds: ClassWithDependencies[], instanceIds: string[]) => void; const sanitizeId = (idWithRandom: string) => idWithRandom.replace(/-[^-]+$/, ''); /** ensures that only one interface ID implementation is present */ const interfaceUsedOnlyOnce: Validator = (cwds, instanceIds) => { const clashingWithExistingInstance = cwds.filter((cwd) => instanceIds.includes(cwd.id)); if (clashingWithExistingInstance.length > 0) { throw new Error( `The following classes are clashing (have duplicate ID) with instances already present in the container: ${clashingWithExistingInstance.map((cwd) => cwd.cls.name)}`, ); } const groupedById = groupBy(cwds, (cwd) => cwd.id); if (Object.values(groupedById).every((groupedCwds) => groupedCwds.length === 1)) { return; } const messages = Object.entries(groupedById).map( ([id, groupedCwds]) => `'${sanitizeId(id)}' (classes: ${groupedCwds.map((cwd) => cwd.cls.name).join(',')})`, ); throw new Error(`The following interface IDs were used multiple times ${messages.join(',')}`); }; /** throws an error if any class depends on an interface that is not available */ const dependenciesArePresent: Validator = (cwds, instanceIds) => { const allIds = new Set([...cwds.map((cwd) => cwd.id), ...instanceIds]); const cwsWithUnmetDeps = cwds.filter((cwd) => !cwd.dependencies.every((d) => allIds.has(d))); if (cwsWithUnmetDeps.length === 0) { return; } const messages = cwsWithUnmetDeps.map((cwd) => { const unmetDeps = cwd.dependencies.filter((d) => !allIds.has(d)).map(sanitizeId); return `Class ${cwd.cls.name} (interface ${sanitizeId(cwd.id)}) depends on interfaces [${unmetDeps}] that weren't added to the init method.`; }); throw new Error(messages.join('\n')); }; /** uses depth first search to find out if the classes have circular dependency */ const noCircularDependencies: Validator = (cwds, instanceIds) => { const inStack = new Set(); const hasCircularDependency = (id: string): boolean => { if (inStack.has(id)) { return true; } inStack.add(id); const cwd = cwds.find((c) => c.id === id); // we reference existing instance, there won't be circular dependency past this one because instances don't have any dependencies if (!cwd && instanceIds.includes(id)) { inStack.delete(id); return false; } if (!cwd) throw new Error(`assertion error: dependency ID missing ${sanitizeId(id)}`); for (const dependencyId of cwd.dependencies) { if (hasCircularDependency(dependencyId)) { return true; } } inStack.delete(id); return false; }; for (const cwd of cwds) { if (hasCircularDependency(cwd.id)) { throw new Error( `Circular dependency detected between interfaces (${Array.from(inStack).map(sanitizeId)}), starting with '${sanitizeId(cwd.id)}' (class: ${cwd.cls.name}).`, ); } } }; /** * Topological sort of the dependencies - returns array of classes. The classes should be initialized in order given by the array. * https://en.wikipedia.org/wiki/Topological_sorting */ const sortDependencies = (classes: Map): ClassWithDependencies[] => { const visited = new Set(); const sortedClasses: ClassWithDependencies[] = []; const topologicalSort = (interfaceId: string) => { if (visited.has(interfaceId)) { return; } visited.add(interfaceId); const cwd = classes.get(interfaceId); if (!cwd) { // the instance for this ID is already initiated return; } for (const d of cwd.dependencies || []) { topologicalSort(d); } sortedClasses.push(cwd); }; for (const id of classes.keys()) { topologicalSort(id); } return sortedClasses; }; /** * Helper type used by the brandInstance function to ensure that all container.addInstances parameters are branded */ export type BrandedInstance = T; /** * use brandInstance to be able to pass this instance to the container.addInstances method */ export const brandInstance = ( id: InterfaceId, instance: T, ): BrandedInstance => { injectableMetadata.set(instance, { id, dependencies: [] }); return instance; }; /** * Container is responsible for initializing a dependency tree. * * It receives a list of classes decorated with the `@Injectable` decorator * and it constructs instances of these classes in an order that ensures class' dependencies * are initialized before the class itself. * * check https://gitlab.com/viktomas/needle for full documentation of this mini-framework */ export class Container { #instances = new Map(); /** * addInstances allows you to add pre-initialized objects to the container. * This is useful when you want to keep mandatory parameters in class' constructor (e.g. some runtime objects like server connection). * addInstances accepts a list of any objects that have been ""branded"" by the `brandInstance` method */ addInstances(...instances: BrandedInstance[]) { for (const instance of instances) { const metadata = injectableMetadata.get(instance); if (!metadata) { throw new Error( 'assertion error: addInstance invoked without branded object, make sure all arguments are branded with `brandInstance`', ); } if (this.#instances.has(metadata.id)) { throw new Error( `you are trying to add instance for interfaceId ${metadata.id}, but instance with this ID is already in the container.`, ); } this.#instances.set(metadata.id, instance); } } /** * instantiate accepts list of classes, validates that they can be managed by the container * and then initialized them in such order that dependencies of a class are initialized before the class */ instantiate(...classes: WithConstructor[]) { // ensure all classes have been decorated with @Injectable const undecorated = classes.filter((c) => !injectableMetadata.has(c)).map((c) => c.name); if (undecorated.length) { throw new Error(`Classes [${undecorated}] are not decorated with @Injectable.`); } const classesWithDeps: ClassWithDependencies[] = classes.map((cls) => { // we verified just above that all classes are present in the metadata map // eslint-disable-next-line @typescript-eslint/no-non-null-assertion const { id, dependencies } = injectableMetadata.get(cls)!; return { cls, id, dependencies }; }); const validators: Validator[] = [ interfaceUsedOnlyOnce, dependenciesArePresent, noCircularDependencies, ]; validators.forEach((v) => v(classesWithDeps, Array.from(this.#instances.keys()))); const classesById = new Map(); // Index classes by their interface id classesWithDeps.forEach((cwd) => { classesById.set(cwd.id, cwd); }); // Create instances in topological order for (const cwd of sortDependencies(classesById)) { const args = cwd.dependencies.map((dependencyId) => this.#instances.get(dependencyId)); // eslint-disable-next-line new-cap const instance = new cwd.cls(...args); this.#instances.set(cwd.id, instance); } } get(id: InterfaceId): T { const instance = this.#instances.get(id); if (!instance) { throw new Error(`Instance for interface '${sanitizeId(id)}' is not in the container.`); } return instance as T; } } References: - packages/lib_di/src/index.ts:112 - packages/lib_di/src/index.ts:77 - packages/lib_di/src/index.ts:98" You are a code assistant,Definition of 'Log' in file src/common/log.ts in project gitlab-lsp,"Definition: class Log implements ILog { #configService: ConfigService | undefined; setup(configService: ConfigService) { this.#configService = configService; } /** * @param messageOrError can be error (if we don't want to provide any additional info), or a string message * @param trailingError is an optional error (if messageOrError was a message) * but we also mention `unknown` type because JS doesn't guarantee that in `catch(e)`, * the `e` is an `Error`, it can be anything. * */ #log( incomingLogLevel: LogLevel, messageOrError: Error | string, trailingError?: Error | unknown, ) { const configuredLevel = this.#configService?.get('client.logLevel'); const shouldShowLog = getNumericMapping(configuredLevel) >= LOG_LEVEL_MAPPING[incomingLogLevel]; if (shouldShowLog) { logWithLevel(incomingLogLevel, messageOrError, ensureError(trailingError)); } } debug(messageOrError: Error | string, trailingError?: Error | unknown) { this.#log(LOG_LEVEL.DEBUG, messageOrError, trailingError); } info(messageOrError: Error | string, trailingError?: Error | unknown) { this.#log(LOG_LEVEL.INFO, messageOrError, trailingError); } warn(messageOrError: Error | string, trailingError?: Error | unknown) { this.#log(LOG_LEVEL.WARNING, messageOrError, trailingError); } error(messageOrError: Error | string, trailingError?: Error | unknown) { this.#log(LOG_LEVEL.ERROR, messageOrError, trailingError); } } // TODO: rename the export and replace usages of `log` with `Log`. export const log = new Log(); References: - src/common/log.ts:105" You are a code assistant,Definition of 'constructor' in file src/tests/fixtures/intent/empty_function/javascript.js in project gitlab-lsp,"Definition: constructor(name) { this.name = name; } greet() { console.log(`Hello ${this.name}`); } } class Greet3 {} function* generateGreetings() {} function* greetGenerator() { yield 'Hello'; } References:" You are a code assistant,Definition of 'DuoProjectAccessChecker' in file src/common/services/duo_access/project_access_checker.ts in project gitlab-lsp,"Definition: export interface DuoProjectAccessChecker { checkProjectStatus(uri: string, workspaceFolder: WorkspaceFolder): DuoProjectStatus; } export const DuoProjectAccessChecker = createInterfaceId('DuoProjectAccessChecker'); @Injectable(DuoProjectAccessChecker, [DuoProjectAccessCache]) export class DefaultDuoProjectAccessChecker { #projectAccessCache: DuoProjectAccessCache; constructor(projectAccessCache: DuoProjectAccessCache) { this.#projectAccessCache = projectAccessCache; } /** * Check if Duo features are enabled for a given DocumentUri. * * We match the DocumentUri to the project with the longest path. * The enabled projects come from the `DuoProjectAccessCache`. * * @reference `DocumentUri` is the URI of the document to check. Comes from * the `TextDocument` object. */ 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: - src/common/feature_state/project_duo_acces_check.ts:32 - src/common/advanced_context/advanced_context_filters.test.ts:16 - src/common/advanced_context/advanced_context_filters.ts:14 - src/common/feature_state/project_duo_acces_check.ts:43 - src/common/suggestion/suggestion_service.ts:135 - src/common/ai_context_management_2/policies/duo_project_policy.ts:13 - src/common/suggestion/suggestion_service.ts:84 - src/common/services/duo_access/project_access_checker.test.ts:12 - src/common/advanced_context/advanced_context_factory.ts:24 - src/common/connection.ts:33" You are a code assistant,Definition of '_DeepPartialArray' in file packages/webview_duo_chat/src/plugin/port/test_utils/create_fake_partial.ts in project gitlab-lsp,"Definition: interface _DeepPartialArray extends Array<_DeepPartial> {} // ban-types lint rule disabled so we can use Function from the copied utility-types implementation // eslint-disable-next-line @typescript-eslint/ban-types type _DeepPartial = T extends Function ? T : T extends Array ? _DeepPartialArray : T extends object ? // eslint-disable-next-line no-use-before-define DeepPartial : T | undefined; type DeepPartial = { [P in keyof T]?: _DeepPartial }; export const createFakePartial = (x: DeepPartial): T => x as T; References:" You are a code assistant,Definition of 'createFakePartial' in file src/common/test_utils/create_fake_partial.ts in project gitlab-lsp,"Definition: export const createFakePartial = (x: Partial): T => x as T; References: - src/common/suggestion_client/default_suggestion_client.test.ts:7 - src/common/suggestion/suggestion_service.test.ts:86 - src/common/tree_sitter/parser.test.ts:127 - src/common/services/duo_access/project_access_checker.test.ts:145 - src/common/tree_sitter/comments/comment_resolver.test.ts:30 - packages/webview_duo_chat/src/plugin/port/chat/get_platform_manager_for_chat.test.ts:44 - src/common/suggestion_client/direct_connection_client.test.ts:32 - src/common/suggestion/streaming_handler.test.ts:50 - src/common/feature_state/project_duo_acces_check.test.ts:27 - src/common/document_transformer_service.test.ts:68 - src/node/duo_workflow/desktop_workflow_runner.test.ts:22 - src/common/suggestion/suggestion_service.test.ts:164 - src/common/suggestion/suggestion_service.test.ts:89 - src/common/suggestion/suggestion_service.test.ts:76 - src/common/suggestion_client/direct_connection_client.test.ts:152 - src/common/feature_state/project_duo_acces_check.test.ts:41 - src/common/suggestion_client/fallback_client.test.ts:9 - src/common/advanced_context/advanced_context_factory.test.ts:72 - src/common/fetch_error.test.ts:37 - src/common/suggestion_client/direct_connection_client.test.ts:52 - src/common/suggestion_client/direct_connection_client.test.ts:35 - src/common/feature_state/feature_state_manager.test.ts:34 - src/common/services/duo_access/project_access_checker.test.ts:40 - src/common/api.test.ts:438 - src/common/tree_sitter/comments/comment_resolver.test.ts:31 - src/common/suggestion/suggestion_filter.test.ts:56 - src/common/tree_sitter/empty_function/empty_function_resolver.test.ts:32 - src/common/services/duo_access/project_access_cache.test.ts:20 - src/common/suggestion_client/fallback_client.test.ts:30 - src/common/feature_state/feature_state_manager.test.ts:55 - src/common/services/duo_access/project_access_checker.test.ts:44 - src/common/suggestion/suggestion_filter.test.ts:77 - src/common/tree_sitter/comments/comment_resolver.test.ts:208 - src/common/tree_sitter/comments/comment_resolver.test.ts:212 - src/common/message_handler.test.ts:215 - src/common/suggestion/suggestion_service.test.ts:84 - src/common/services/duo_access/project_access_checker.test.ts:126 - src/common/connection.test.ts:44 - src/common/advanced_context/advanced_context_service.test.ts:39 - src/common/tracking/instance_tracker.test.ts:32 - src/common/services/duo_access/project_access_checker.test.ts:153 - src/common/services/duo_access/project_access_checker.test.ts:74 - src/common/tree_sitter/parser.test.ts:83 - src/common/suggestion/streaming_handler.test.ts:70 - src/common/tree_sitter/intent_resolver.test.ts:47 - src/common/services/duo_access/project_access_checker.test.ts:157 - src/common/fetch_error.test.ts:7 - src/common/core/handlers/initialize_handler.test.ts:8 - src/common/message_handler.test.ts:204 - src/common/suggestion/suggestion_service.test.ts:108 - src/common/advanced_context/advanced_context_service.test.ts:47 - src/common/suggestion_client/direct_connection_client.test.ts:58 - src/common/suggestion/suggestion_service.test.ts:100 - src/common/tree_sitter/comments/comment_resolver.test.ts:162 - src/common/tree_sitter/comments/comment_resolver.test.ts:27 - src/common/tree_sitter/comments/comment_resolver.test.ts:206 - src/common/feature_flags.test.ts:21 - src/common/message_handler.test.ts:136 - src/common/advanced_context/helpers.test.ts:7 - src/common/message_handler.test.ts:42 - src/common/suggestion/suggestion_service.test.ts:1038 - src/common/suggestion/suggestion_service.test.ts:469 - src/common/tree_sitter/comments/comment_resolver.test.ts:127 - src/common/suggestion/suggestion_service.test.ts:582 - src/common/services/duo_access/project_access_checker.test.ts:66 - src/common/graphql/workflow/service.test.ts:38 - src/common/advanced_context/context_resolvers/open_tabs_context_resolver.test.ts:57 - src/common/tree_sitter/comments/comment_resolver.test.ts:16 - src/common/services/duo_access/project_access_checker.test.ts:100 - src/common/tracking/multi_tracker.test.ts:8 - src/common/suggestion/suggestion_service.test.ts:492 - src/common/advanced_context/advanced_context_service.test.ts:28 - src/common/suggestion_client/suggestion_client_pipeline.test.ts:10 - src/common/connection.test.ts:57 - src/common/suggestion/suggestion_service.test.ts:1073 - src/common/suggestion/streaming_handler.test.ts:46 - src/common/tree_sitter/comments/comment_resolver.test.ts:193 - src/common/suggestion/suggestion_filter.test.ts:57 - src/common/suggestion/suggestion_service.test.ts:756 - src/common/tree_sitter/comments/comment_resolver.test.ts:195 - src/common/advanced_context/advanced_context_factory.test.ts:73 - src/common/tree_sitter/comments/comment_resolver.test.ts:133 - src/common/connection.test.ts:59 - src/node/duo_workflow/desktop_workflow_runner.test.ts:24 - src/common/services/duo_access/project_access_checker.test.ts:122 - src/common/security_diagnostics_publisher.test.ts:51 - src/common/fetch_error.test.ts:21 - src/common/core/handlers/token_check_notifier.test.ts:11 - src/common/message_handler.test.ts:61 - src/common/suggestion/suggestion_service.test.ts:476 - src/common/suggestion_client/create_v2_request.test.ts:8 - src/common/suggestion/suggestion_service.test.ts:199 - src/common/services/duo_access/project_access_cache.test.ts:16 - src/common/advanced_context/advanced_context_service.test.ts:42 - src/common/services/duo_access/project_access_checker.test.ts:24 - src/common/api.test.ts:422 - src/common/security_diagnostics_publisher.test.ts:48 - src/common/suggestion/streaming_handler.test.ts:56 - src/common/tracking/instance_tracker.test.ts:176 - src/common/tree_sitter/empty_function/empty_function_resolver.test.ts:28 - src/common/suggestion_client/fallback_client.test.ts:12 - src/common/feature_state/project_duo_acces_check.test.ts:35 - src/common/services/duo_access/project_access_checker.test.ts:118 - src/common/suggestion_client/direct_connection_client.test.ts:150 - src/common/feature_state/supported_language_check.test.ts:39 - src/common/services/duo_access/project_access_checker.test.ts:96 - src/common/suggestion_client/direct_connection_client.test.ts:33 - src/node/fetch.test.ts:16 - src/common/suggestion/streaming_handler.test.ts:62 - src/common/suggestion_client/tree_sitter_middleware.test.ts:24 - src/common/api.test.ts:298 - src/common/suggestion/suggestion_service.test.ts:205 - src/common/feature_state/feature_state_manager.test.ts:78 - src/common/suggestion/suggestion_service.test.ts:94 - src/common/suggestion_client/direct_connection_client.test.ts:106 - src/common/suggestion/suggestion_service.test.ts:461 - src/common/suggestion_client/default_suggestion_client.test.ts:11 - src/common/suggestion_client/direct_connection_client.test.ts:103 - src/common/api.test.ts:318 - src/common/services/duo_access/project_access_checker.test.ts:163 - src/common/feature_state/supported_language_check.test.ts:27 - src/common/suggestion/suggestion_service.test.ts:436 - src/common/suggestion_client/create_v2_request.test.ts:10 - src/common/feature_state/project_duo_acces_check.test.ts:32 - src/common/suggestion/suggestion_filter.test.ts:80 - src/common/tree_sitter/comments/comment_resolver.test.ts:164 - src/common/message_handler.test.ts:53 - packages/webview_duo_chat/src/plugin/port/chat/gitlab_chat_api.test.ts:74 - packages/webview_duo_chat/src/plugin/port/chat/get_platform_manager_for_chat.test.ts:198 - src/common/services/duo_access/project_access_checker.test.ts:48 - src/common/services/duo_access/project_access_checker.test.ts:15 - src/common/advanced_context/advanced_context_service.test.ts:34 - src/common/message_handler.test.ts:57 - src/common/connection.test.ts:48 - src/common/advanced_context/context_resolvers/open_tabs_context_resolver.test.ts:14 - src/common/advanced_context/helpers.test.ts:10 - src/common/connection.test.ts:58 - src/tests/int/lsp_client.ts:38 - src/common/tree_sitter/intent_resolver.test.ts:40 - src/common/connection.test.ts:47 - src/common/graphql/workflow/service.test.ts:35 - src/common/suggestion/suggestion_service.test.ts:983 - src/common/suggestion/suggestion_service.test.ts:105 - src/common/graphql/workflow/service.test.ts:41 - packages/webview_duo_chat/src/plugin/port/test_utils/entities.ts:16 - src/common/services/duo_access/project_access_checker.test.ts:70 - src/common/connection.test.ts:31 - src/common/feature_state/project_duo_acces_check.test.ts:23 - src/common/tree_sitter/empty_function/empty_function_resolver.test.ts:17 - src/common/core/handlers/initialize_handler.test.ts:17 - src/common/feature_state/project_duo_acces_check.test.ts:40 - src/common/tracking/snowplow_tracker.test.ts:82 - src/common/api.test.ts:349 - src/common/tree_sitter/comments/comment_resolver.test.ts:129 - src/common/feature_state/supported_language_check.test.ts:38 - src/common/tracking/snowplow_tracker.test.ts:78 - src/common/suggestion_client/direct_connection_client.test.ts:50 - src/common/tree_sitter/intent_resolver.test.ts:160 - src/common/suggestion/streaming_handler.test.ts:65 - src/tests/int/lsp_client.ts:164 - src/common/suggestion_client/fallback_client.test.ts:8 - src/common/log.test.ts:10 - src/common/services/duo_access/project_access_cache.test.ts:12 - src/common/suggestion_client/fallback_client.test.ts:15 - src/common/test_utils/create_fake_response.ts:18 - src/common/tree_sitter/parser.test.ts:86 - src/common/suggestion_client/fallback_client.test.ts:7 - src/common/suggestion_client/tree_sitter_middleware.test.ts:33 - src/common/feature_flags.test.ts:17 - src/common/services/duo_access/project_access_checker.test.ts:148 - src/common/suggestion/suggestion_service.test.ts:193 - src/common/suggestion/suggestion_service.test.ts:1054 - src/common/connection.test.ts:53 - src/common/suggestion/streaming_handler.test.ts:75 - src/common/suggestion/suggestion_service.test.ts:464 - src/common/advanced_context/advanced_context_service.test.ts:53 - src/common/feature_state/feature_state_manager.test.ts:21 - src/common/message_handler.test.ts:48 - src/common/document_service.test.ts:8 - src/common/services/duo_access/project_access_checker.test.ts:92 - src/common/tree_sitter/comments/comment_resolver.test.ts:199 - src/common/suggestion_client/tree_sitter_middleware.test.ts:86 - src/common/suggestion/suggestion_service.test.ts:190 - src/common/suggestion/suggestion_filter.test.ts:79 - src/common/feature_flags.test.ts:93 - src/common/advanced_context/advanced_context_service.test.ts:50 - src/common/message_handler.test.ts:64 - src/common/suggestion/suggestion_filter.test.ts:35 - src/common/suggestion/suggestion_service.test.ts:770 - src/common/api.test.ts:406 - src/common/tracking/instance_tracker.test.ts:179 - src/common/suggestion_client/default_suggestion_client.test.ts:24 - src/common/tree_sitter/empty_function/empty_function_resolver.test.ts:31 - src/common/suggestion_client/tree_sitter_middleware.test.ts:62 - packages/webview_duo_chat/src/plugin/port/chat/get_platform_manager_for_chat.test.ts:199 - src/common/suggestion_client/fallback_client.test.ts:27 - src/common/advanced_context/context_resolvers/open_tabs_context_resolver.test.ts:24" You are a code assistant,Definition of 'generateGreetings' in file src/tests/fixtures/intent/empty_function/javascript.js in project gitlab-lsp,"Definition: function* generateGreetings() {} function* greetGenerator() { yield 'Hello'; } References:" You are a code assistant,Definition of 'greet_generator' in file src/tests/fixtures/intent/empty_function/ruby.rb in project gitlab-lsp,"Definition: def greet_generator yield 'Hello' end References: - src/tests/fixtures/intent/empty_function/ruby.rb:40" You are a code assistant,Definition of 'shouldUseAdvancedContext' in file src/common/advanced_context/helpers.ts in project gitlab-lsp,"Definition: export const shouldUseAdvancedContext = ( featureFlagService: FeatureFlagService, configService: ConfigService, ) => { const isEditorAdvancedContextEnabled = featureFlagService.isInstanceFlagEnabled( InstanceFeatureFlags.EditorAdvancedContext, ); const isGenericContextEnabled = featureFlagService.isInstanceFlagEnabled( InstanceFeatureFlags.CodeSuggestionsContext, ); let isEditorOpenTabsContextEnabled = configService.get('client.openTabsContext'); if (isEditorOpenTabsContextEnabled === undefined) { isEditorOpenTabsContextEnabled = true; } /** * TODO - when we introduce other context resolution strategies, * have `isEditorOpenTabsContextEnabled` only disable the corresponding resolver (`lruResolver`) * https://gitlab.com/gitlab-org/editor-extensions/gitlab-lsp/-/issues/298 * https://gitlab.com/groups/gitlab-org/editor-extensions/-/epics/59#note_1981542181 */ return ( isEditorAdvancedContextEnabled && isGenericContextEnabled && isEditorOpenTabsContextEnabled ); }; References: - src/common/suggestion/suggestion_service.ts:544 - src/common/advanced_context/helpers.test.ts:49 - src/common/tracking/snowplow_tracker.ts:467" You are a code assistant,Definition of 'Snowplow' in file src/common/tracking/snowplow/snowplow.ts in project gitlab-lsp,"Definition: export class Snowplow { /** Disable sending events when it's not possible. */ disabled: boolean = false; #emitter: Emitter; #lsFetch: LsFetch; #options: SnowplowOptions; #tracker: TrackerCore; static #instance?: Snowplow; // eslint-disable-next-line no-restricted-syntax private constructor(lsFetch: LsFetch, options: SnowplowOptions) { this.#lsFetch = lsFetch; this.#options = options; this.#emitter = new Emitter( this.#options.timeInterval, this.#options.maxItems, this.#sendEvent.bind(this), ); this.#emitter.start(); this.#tracker = trackerCore({ callback: this.#emitter.add.bind(this.#emitter) }); } public static getInstance(lsFetch: LsFetch, options?: SnowplowOptions): Snowplow { if (!this.#instance) { if (!options) { throw new Error('Snowplow should be instantiated'); } const sp = new Snowplow(lsFetch, options); Snowplow.#instance = sp; } // FIXME: this eslint violation was introduced before we set up linting // eslint-disable-next-line @typescript-eslint/no-non-null-assertion return Snowplow.#instance!; } async #sendEvent(events: PayloadBuilder[]): Promise { if (!this.#options.enabled() || this.disabled) { return; } try { const url = `${this.#options.endpoint}/com.snowplowanalytics.snowplow/tp2`; const data = { schema: 'iglu:com.snowplowanalytics.snowplow/payload_data/jsonschema/1-0-4', data: events.map((event) => { const eventId = uuidv4(); // All values prefilled below are part of snowplow tracker protocol // https://docs.snowplow.io/docs/collecting-data/collecting-from-own-applications/snowplow-tracker-protocol/#common-parameters // Values are set according to either common GitLab standard: // tna - representing tracker namespace and being set across GitLab to ""gl"" // tv - represents tracker value, to make it aligned with downstream system it has to be prefixed with ""js-*"""" // aid - represents app Id is configured via options to gitlab_ide_extension // eid - represents uuid for each emitted event event.add('eid', eventId); event.add('p', 'app'); event.add('tv', 'js-gitlab'); event.add('tna', 'gl'); event.add('aid', this.#options.appId); return preparePayload(event.build()); }), }; const config = { headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(data), }; const response = await this.#lsFetch.post(url, config); if (response.status !== 200) { log.warn( `Could not send telemetry to snowplow, this warning can be safely ignored. status=${response.status}`, ); } } catch (error) { let errorHandled = false; if (typeof error === 'object' && 'errno' in (error as object)) { const errObject = error as object; // ENOTFOUND occurs when the snowplow hostname cannot be resolved. if ('errno' in errObject && errObject.errno === 'ENOTFOUND') { this.disabled = true; errorHandled = true; log.info('Disabling telemetry, unable to resolve endpoint address.'); } else { log.warn(JSON.stringify(errObject)); } } if (!errorHandled) { log.warn('Failed to send telemetry event, this warning can be safely ignored'); log.warn(JSON.stringify(error)); } } } public async trackStructEvent( event: StructuredEvent, context?: SelfDescribingJson[] | null, ): Promise { this.#tracker.track(buildStructEvent(event), context); } async stop() { await this.#emitter.stop(); } public destroy() { Snowplow.#instance = undefined; } } References: - src/common/tracking/snowplow/snowplow.ts:74 - src/common/tracking/snowplow/snowplow.ts:54 - src/common/tracking/snowplow/snowplow.ts:69 - src/common/tracking/snowplow_tracker.ts:127" You are a code assistant,Definition of 'HostConfig' in file packages/lib_webview_client/src/types.ts in project gitlab-lsp,"Definition: export interface HostConfig { host: MessageBus; } References:" You are a code assistant,Definition of 'constructor' in file src/common/feature_state/supported_language_check.ts in project gitlab-lsp,"Definition: constructor( documentService: DocumentService, supportedLanguagesService: SupportedLanguagesService, ) { this.#documentService = documentService; this.#supportedLanguagesService = supportedLanguagesService; this.#documentService.onDocumentChange((event, handlerType) => { if (handlerType === TextDocumentChangeListenerType.onDidSetActive) { this.#updateWithDocument(event.document); } }); this.#supportedLanguagesService.onLanguageChange(() => this.#update()); } onChanged(listener: (data: StateCheckChangedEventData) => void): Disposable { this.#stateEmitter.on('change', listener); return { dispose: () => this.#stateEmitter.removeListener('change', listener), }; } #updateWithDocument(document: TextDocument) { this.#currentDocument = document; this.#update(); } get engaged() { return !this.#isLanguageEnabled; } get id() { return this.#isLanguageSupported && !this.#isLanguageEnabled ? DISABLED_LANGUAGE : UNSUPPORTED_LANGUAGE; } details = 'Code suggestions are not supported for this language'; #update() { this.#checkLanguage(); this.#stateEmitter.emit('change', this); } #checkLanguage() { if (!this.#currentDocument) { this.#isLanguageEnabled = false; this.#isLanguageSupported = false; return; } const { languageId } = this.#currentDocument; this.#isLanguageEnabled = this.#supportedLanguagesService.isLanguageEnabled(languageId); this.#isLanguageSupported = this.#supportedLanguagesService.isLanguageSupported(languageId); } } References:" You are a code assistant,Definition of 'WebviewInstanceRequestEventData' in file packages/lib_webview_transport/src/types.ts in project gitlab-lsp,"Definition: export type WebviewInstanceRequestEventData = WebviewAddress & WebviewEventInfo & WebviewRequestInfo; export type SuccessfulResponse = { success: true; }; export type FailedResponse = { success: false; reason: string; }; export type WebviewInstanceResponseEventData = WebviewAddress & WebviewRequestInfo & WebviewEventInfo & (SuccessfulResponse | FailedResponse); export type MessagesToServer = { webview_instance_created: WebviewInstanceCreatedEventData; webview_instance_destroyed: WebviewInstanceDestroyedEventData; webview_instance_notification_received: WebviewInstanceNotificationEventData; webview_instance_request_received: WebviewInstanceRequestEventData; webview_instance_response_received: WebviewInstanceResponseEventData; }; export type MessagesToClient = { webview_instance_notification: WebviewInstanceNotificationEventData; webview_instance_request: WebviewInstanceRequestEventData; webview_instance_response: WebviewInstanceResponseEventData; }; export interface TransportMessageHandler { (payload: T): void; } export interface TransportListener { on( type: K, callback: TransportMessageHandler, ): Disposable; } export interface TransportPublisher { publish(type: K, payload: MessagesToClient[K]): Promise; } export interface Transport extends TransportListener, TransportPublisher {} References: - packages/lib_webview_transport/src/types.ts:49 - packages/lib_webview_transport/src/types.ts:43" You are a code assistant,Definition of 'GitLabPlatformManagerForChat' in file packages/webview_duo_chat/src/plugin/port/chat/get_platform_manager_for_chat.ts in project gitlab-lsp,"Definition: export class GitLabPlatformManagerForChat { readonly #platformManager: GitLabPlatformManager; constructor(platformManager: GitLabPlatformManager) { this.#platformManager = platformManager; } async getProjectGqlId(): Promise { const projectManager = await this.#platformManager.getForActiveProject(false); return projectManager?.project.gqlId; } /** * Obtains a GitLab Platform to send API requests to the GitLab API * for the Duo Chat feature. * * - It returns a GitLabPlatformForAccount for the first linked account. * - It returns undefined if there are no accounts linked */ async getGitLabPlatform(): Promise { const platforms = await this.#platformManager.getForAllAccounts(); if (!platforms.length) { return undefined; } let platform: GitLabPlatformForAccount | undefined; // Using a for await loop in this context because we want to stop // evaluating accounts as soon as we find one with code suggestions enabled for await (const result of platforms.map(getChatSupport)) { if (result.hasSupportForChat) { platform = result.platform; break; } } return platform; } async getGitLabEnvironment(): Promise { const platform = await this.getGitLabPlatform(); const instanceUrl = platform?.account.instanceUrl; switch (instanceUrl) { case GITLAB_COM_URL: return GitLabEnvironment.GITLAB_COM; case GITLAB_DEVELOPMENT_URL: return GitLabEnvironment.GITLAB_DEVELOPMENT; case GITLAB_STAGING_URL: return GitLabEnvironment.GITLAB_STAGING; case GITLAB_ORG_URL: return GitLabEnvironment.GITLAB_ORG; default: return GitLabEnvironment.GITLAB_SELF_MANAGED; } } } References: - packages/webview_duo_chat/src/plugin/port/chat/gitlab_chat_api.test.ts:50 - packages/webview_duo_chat/src/plugin/port/chat/get_platform_manager_for_chat.test.ts:51 - packages/webview_duo_chat/src/plugin/index.ts:19 - packages/webview_duo_chat/src/plugin/port/chat/get_platform_manager_for_chat.test.ts:26 - packages/webview_duo_chat/src/plugin/port/chat/gitlab_chat_api.ts:150 - packages/webview_duo_chat/src/plugin/chat_controller.ts:20 - packages/webview_duo_chat/src/plugin/port/chat/gitlab_chat_api.test.ts:58 - packages/webview_duo_chat/src/plugin/port/chat/gitlab_chat_api.ts:152" You are a code assistant,Definition of 'createFakeFetchFromApi' in file packages/webview_duo_chat/src/plugin/port/test_utils/create_fake_fetch_from_api.ts in project gitlab-lsp,"Definition: export const createFakeFetchFromApi = (...handlers: FakeRequestHandler[]): fetchFromApi => async (request: ApiRequest) => { const handler = handlers.find((h) => isEqual(h.request, request)); if (!handler) { throw new Error(`No fake handler to handle request: ${JSON.stringify(request)}`); } return handler.response as T; }; References: - packages/webview_duo_chat/src/plugin/port/test_utils/entities.ts:25" You are a code assistant,Definition of 'retrieveItems' in file src/common/ai_context_management_2/ai_context_manager.ts in project gitlab-lsp,"Definition: async retrieveItems(): Promise { const items = Array.from(this.#items.values()); log.info(`Retrieving ${items.length} items`); const retrievedItems = await Promise.all( items.map(async (item) => { try { switch (item.type) { case 'file': { const content = await this.#fileRetriever.retrieve(item); return content ? { ...item, content } : null; } default: throw new Error(`Unknown item type: ${item.type}`); } } catch (error) { log.error(`Failed to retrieve item ${item.id}`, error); return null; } }), ); return retrievedItems.filter((item) => item !== null); } } References:" You are a code assistant,Definition of 'TestType' in file src/tests/unit/tree_sitter/intent_resolver.test.ts in project gitlab-lsp,"Definition: type TestType = | 'on_empty_comment' | 'after_empty_comment' | 'on_non_empty_comment' | 'after_non_empty_comment' | 'in_block_comment' | 'on_block_comment' | 'after_block_comment' | 'in_jsdoc_comment' | 'on_jsdoc_comment' | 'after_jsdoc_comment' | 'in_doc_comment' | 'on_doc_comment' | 'after_doc_comment' | 'no_comment_large_file' | 'on_comment_in_empty_function' | 'after_comment_in_empty_function'; type FileExtension = string; /** * Position refers to the position of the cursor in the test file. */ type IntentTestCase = [TestType, Position, Intent]; /** * Note: We use the language server procotol Ids here because `IDocContext` expects * these Ids (which is passed into `ParseFile`) and because they are unique. * `ParseFile` derives the tree sitter gramamr from the file's extension. * Some grammars apply to multiple extensions, eg. `typescript` applies * to both `.ts` and `.tsx`. */ const testCases: Array<[LanguageServerLanguageId, FileExtension, IntentTestCase[]]> = [ /* [ FIXME: add back support for vue 'vue', '.vue', // ../../fixtures/intent/vue_comments.vue [ ['on_empty_comment', { line: 2, character: 9 }, 'completion'], ['after_empty_comment', { line: 3, character: 0 }, 'completion'], ['on_non_empty_comment', { line: 4, character: 30 }, 'completion'], ['after_non_empty_comment', { line: 5, character: 0 }, 'generation'], ['in_block_comment', { line: 8, character: 23 }, 'completion'], ['on_block_comment', { line: 9, character: 2 }, 'completion'], ['after_block_comment', { line: 10, character: 0 }, 'generation'], ['no_comment_large_file', { line: 30, character: 0 }, undefined], // TODO: comments in the Vue `script` are not captured // ['on_comment_in_empty_function', { line: 34, character: 33 }, 'completion'], // ['after_comment_in_empty_function', { line: 35, character: 0 }, 'generation'], ], ], */ [ 'typescript', '.ts', // ../../fixtures/intent/typescript_comments.ts [ ['on_empty_comment', { line: 1, character: 3 }, 'completion'], ['after_empty_comment', { line: 2, character: 0 }, 'completion'], ['on_non_empty_comment', { line: 4, character: 30 }, 'completion'], ['after_non_empty_comment', { line: 5, character: 0 }, 'generation'], ['in_block_comment', { line: 8, character: 23 }, 'completion'], ['on_block_comment', { line: 9, character: 2 }, 'completion'], ['after_block_comment', { line: 10, character: 0 }, 'generation'], ['in_jsdoc_comment', { line: 14, character: 21 }, 'completion'], ['on_jsdoc_comment', { line: 15, character: 3 }, 'completion'], ['after_jsdoc_comment', { line: 16, character: 0 }, 'generation'], ['no_comment_large_file', { line: 24, character: 0 }, undefined], ['on_comment_in_empty_function', { line: 30, character: 31 }, 'completion'], ['after_comment_in_empty_function', { line: 31, character: 0 }, 'generation'], ], ], [ 'typescriptreact', '.tsx', // ../../fixtures/intent/typescriptreact_comments.tsx [ ['on_empty_comment', { line: 1, character: 3 }, 'completion'], ['after_empty_comment', { line: 2, character: 0 }, 'completion'], ['on_non_empty_comment', { line: 4, character: 30 }, 'completion'], ['after_non_empty_comment', { line: 5, character: 0 }, 'generation'], ['in_block_comment', { line: 8, character: 23 }, 'completion'], ['on_block_comment', { line: 9, character: 2 }, 'completion'], ['after_block_comment', { line: 10, character: 0 }, 'generation'], ['in_jsdoc_comment', { line: 14, character: 21 }, 'completion'], ['on_jsdoc_comment', { line: 15, character: 3 }, 'completion'], ['after_jsdoc_comment', { line: 16, character: 0 }, 'generation'], ['no_comment_large_file', { line: 24, character: 0 }, undefined], ['on_comment_in_empty_function', { line: 30, character: 31 }, 'completion'], ['after_comment_in_empty_function', { line: 31, character: 0 }, 'generation'], ], ], [ 'javascript', '.js', // ../../fixtures/intent/javascript_comments.js [ ['on_empty_comment', { line: 1, character: 3 }, 'completion'], ['after_empty_comment', { line: 2, character: 0 }, 'completion'], ['on_non_empty_comment', { line: 4, character: 30 }, 'completion'], ['after_non_empty_comment', { line: 5, character: 0 }, 'generation'], ['in_block_comment', { line: 8, character: 23 }, 'completion'], ['on_block_comment', { line: 9, character: 2 }, 'completion'], ['after_block_comment', { line: 10, character: 0 }, 'generation'], ['in_jsdoc_comment', { line: 14, character: 21 }, 'completion'], ['on_jsdoc_comment', { line: 15, character: 3 }, 'completion'], ['after_jsdoc_comment', { line: 16, character: 0 }, 'generation'], ['no_comment_large_file', { line: 24, character: 0 }, undefined], ['on_comment_in_empty_function', { line: 30, character: 31 }, 'completion'], ['after_comment_in_empty_function', { line: 31, character: 0 }, 'generation'], ], ], [ 'javascriptreact', '.jsx', // ../../fixtures/intent/javascriptreact_comments.jsx [ ['on_empty_comment', { line: 1, character: 3 }, 'completion'], ['after_empty_comment', { line: 2, character: 0 }, 'completion'], ['on_non_empty_comment', { line: 4, character: 30 }, 'completion'], ['after_non_empty_comment', { line: 5, character: 0 }, 'generation'], ['in_block_comment', { line: 8, character: 23 }, 'completion'], ['on_block_comment', { line: 9, character: 2 }, 'completion'], ['after_block_comment', { line: 10, character: 0 }, 'generation'], ['in_jsdoc_comment', { line: 15, character: 25 }, 'completion'], ['on_jsdoc_comment', { line: 16, character: 3 }, 'completion'], ['after_jsdoc_comment', { line: 17, character: 0 }, 'generation'], ['no_comment_large_file', { line: 24, character: 0 }, undefined], ['on_comment_in_empty_function', { line: 31, character: 31 }, 'completion'], ['after_comment_in_empty_function', { line: 32, character: 0 }, 'generation'], ], ], [ 'ruby', '.rb', // ../../fixtures/intent/ruby_comments.rb [ ['on_empty_comment', { line: 1, character: 3 }, 'completion'], ['after_empty_comment', { line: 2, character: 0 }, 'completion'], ['on_non_empty_comment', { line: 4, character: 30 }, 'completion'], ['after_non_empty_comment', { line: 5, character: 0 }, 'generation'], ['in_block_comment', { line: 9, character: 23 }, 'completion'], ['on_block_comment', { line: 10, character: 4 }, 'completion'], ['after_block_comment', { line: 11, character: 0 }, 'generation'], ['no_comment_large_file', { line: 17, character: 0 }, undefined], ['on_comment_in_empty_function', { line: 21, character: 30 }, 'completion'], ['after_comment_in_empty_function', { line: 22, character: 22 }, 'generation'], ], ], [ 'go', '.go', // ../../fixtures/intent/go_comments.go [ ['on_empty_comment', { line: 1, character: 3 }, 'completion'], ['after_empty_comment', { line: 2, character: 0 }, 'completion'], ['on_non_empty_comment', { line: 4, character: 30 }, 'completion'], ['after_non_empty_comment', { line: 5, character: 0 }, 'generation'], ['in_block_comment', { line: 8, character: 23 }, 'completion'], ['on_block_comment', { line: 9, character: 2 }, 'completion'], ['after_block_comment', { line: 10, character: 0 }, 'generation'], ['no_comment_large_file', { line: 20, character: 0 }, undefined], ['on_comment_in_empty_function', { line: 24, character: 31 }, 'completion'], ['after_comment_in_empty_function', { line: 25, character: 0 }, 'generation'], ], ], [ 'java', '.java', // ../../fixtures/intent/java_comments.java [ ['on_empty_comment', { line: 1, character: 3 }, 'completion'], ['after_empty_comment', { line: 2, character: 0 }, 'completion'], ['on_non_empty_comment', { line: 4, character: 30 }, 'completion'], ['after_non_empty_comment', { line: 5, character: 0 }, 'generation'], ['in_block_comment', { line: 8, character: 23 }, 'completion'], ['on_block_comment', { line: 9, character: 2 }, 'completion'], ['after_block_comment', { line: 10, character: 0 }, 'generation'], ['in_doc_comment', { line: 14, character: 29 }, 'completion'], ['on_doc_comment', { line: 15, character: 3 }, 'completion'], ['after_doc_comment', { line: 16, character: 0 }, 'generation'], ['no_comment_large_file', { line: 23, character: 0 }, undefined], ['on_comment_in_empty_function', { line: 30, character: 31 }, 'completion'], ['after_comment_in_empty_function', { line: 31, character: 0 }, 'generation'], ], ], [ 'kotlin', '.kt', // ../../fixtures/intent/kotlin_comments.kt [ ['on_empty_comment', { line: 1, character: 3 }, 'completion'], ['after_empty_comment', { line: 2, character: 0 }, 'completion'], ['on_non_empty_comment', { line: 4, character: 30 }, 'completion'], ['after_non_empty_comment', { line: 5, character: 0 }, 'generation'], ['in_block_comment', { line: 8, character: 23 }, 'completion'], ['on_block_comment', { line: 9, character: 2 }, 'completion'], ['after_block_comment', { line: 10, character: 0 }, 'generation'], ['in_doc_comment', { line: 14, character: 29 }, 'completion'], ['on_doc_comment', { line: 15, character: 3 }, 'completion'], ['after_doc_comment', { line: 16, character: 0 }, 'generation'], ['no_comment_large_file', { line: 23, character: 0 }, undefined], ['on_comment_in_empty_function', { line: 30, character: 31 }, 'completion'], ['after_comment_in_empty_function', { line: 31, character: 0 }, 'generation'], ], ], [ 'rust', '.rs', // ../../fixtures/intent/rust_comments.rs [ ['on_empty_comment', { line: 1, character: 3 }, 'completion'], ['after_empty_comment', { line: 2, character: 0 }, 'completion'], ['on_non_empty_comment', { line: 4, character: 30 }, 'completion'], ['after_non_empty_comment', { line: 5, character: 0 }, 'generation'], ['in_block_comment', { line: 8, character: 23 }, 'completion'], ['on_block_comment', { line: 9, character: 2 }, 'completion'], ['after_block_comment', { line: 10, character: 0 }, 'generation'], ['in_doc_comment', { line: 11, character: 25 }, 'completion'], ['on_doc_comment', { line: 12, character: 42 }, 'completion'], ['after_doc_comment', { line: 15, character: 0 }, 'generation'], ['no_comment_large_file', { line: 23, character: 0 }, undefined], ['on_comment_in_empty_function', { line: 26, character: 31 }, 'completion'], ['after_comment_in_empty_function', { line: 27, character: 0 }, 'generation'], ], ], [ 'yaml', '.yaml', // ../../fixtures/intent/yaml_comments.yaml [ ['on_empty_comment', { line: 1, character: 3 }, 'completion'], ['after_empty_comment', { line: 2, character: 0 }, 'completion'], ['on_non_empty_comment', { line: 4, character: 30 }, 'completion'], ['after_non_empty_comment', { line: 5, character: 0 }, 'generation'], ['no_comment_large_file', { line: 17, character: 0 }, undefined], ], ], [ 'html', '.html', // ../../fixtures/intent/html_comments.html [ ['on_empty_comment', { line: 14, character: 12 }, 'completion'], ['after_empty_comment', { line: 15, character: 0 }, 'completion'], ['on_non_empty_comment', { line: 8, character: 91 }, 'completion'], ['after_non_empty_comment', { line: 9, character: 0 }, 'generation'], ['in_block_comment', { line: 18, character: 29 }, 'completion'], ['on_block_comment', { line: 19, character: 7 }, 'completion'], ['after_block_comment', { line: 20, character: 0 }, 'generation'], ['no_comment_large_file', { line: 12, character: 66 }, undefined], ], ], [ 'c', '.c', // ../../fixtures/intent/c_comments.c [ ['on_empty_comment', { line: 1, character: 3 }, 'completion'], ['after_empty_comment', { line: 2, character: 0 }, 'completion'], ['on_non_empty_comment', { line: 4, character: 30 }, 'completion'], ['after_non_empty_comment', { line: 5, character: 0 }, 'generation'], ['in_block_comment', { line: 8, character: 23 }, 'completion'], ['on_block_comment', { line: 9, character: 2 }, 'completion'], ['after_block_comment', { line: 10, character: 0 }, 'generation'], ['no_comment_large_file', { line: 17, character: 0 }, undefined], ['on_comment_in_empty_function', { line: 20, character: 31 }, 'completion'], ['after_comment_in_empty_function', { line: 21, character: 0 }, 'generation'], ], ], [ 'cpp', '.cpp', // ../../fixtures/intent/cpp_comments.cpp [ ['on_empty_comment', { line: 1, character: 3 }, 'completion'], ['after_empty_comment', { line: 2, character: 0 }, 'completion'], ['on_non_empty_comment', { line: 4, character: 30 }, 'completion'], ['after_non_empty_comment', { line: 5, character: 0 }, 'generation'], ['in_block_comment', { line: 8, character: 23 }, 'completion'], ['on_block_comment', { line: 9, character: 2 }, 'completion'], ['after_block_comment', { line: 10, character: 0 }, 'generation'], ['no_comment_large_file', { line: 17, character: 0 }, undefined], ['on_comment_in_empty_function', { line: 20, character: 31 }, 'completion'], ['after_comment_in_empty_function', { line: 21, character: 0 }, 'generation'], ], ], [ 'c_sharp', '.cs', // ../../fixtures/intent/c_sharp_comments.cs [ ['on_empty_comment', { line: 1, character: 3 }, 'completion'], ['after_empty_comment', { line: 2, character: 0 }, 'completion'], ['on_non_empty_comment', { line: 4, character: 30 }, 'completion'], ['after_non_empty_comment', { line: 5, character: 0 }, 'generation'], ['in_block_comment', { line: 8, character: 23 }, 'completion'], ['on_block_comment', { line: 9, character: 2 }, 'completion'], ['after_block_comment', { line: 10, character: 0 }, 'generation'], ['no_comment_large_file', { line: 17, character: 0 }, undefined], ['on_comment_in_empty_function', { line: 20, character: 31 }, 'completion'], ['after_comment_in_empty_function', { line: 21, character: 22 }, 'generation'], ], ], [ 'css', '.css', // ../../fixtures/intent/css_comments.css [ ['on_empty_comment', { line: 1, character: 3 }, 'completion'], ['after_empty_comment', { line: 2, character: 0 }, 'completion'], ['on_non_empty_comment', { line: 3, character: 31 }, 'completion'], ['after_non_empty_comment', { line: 4, character: 0 }, 'generation'], ['in_block_comment', { line: 7, character: 23 }, 'completion'], ['on_block_comment', { line: 8, character: 2 }, 'completion'], ['after_block_comment', { line: 9, character: 0 }, 'generation'], ['no_comment_large_file', { line: 17, character: 0 }, undefined], ], ], [ 'bash', '.sh', // ../../fixtures/intent/bash_comments.css [ ['on_empty_comment', { line: 4, character: 1 }, 'completion'], ['after_empty_comment', { line: 5, character: 0 }, 'completion'], ['on_non_empty_comment', { line: 2, character: 65 }, 'completion'], ['after_non_empty_comment', { line: 3, character: 0 }, 'generation'], ['no_comment_large_file', { line: 10, character: 0 }, undefined], ['on_comment_in_empty_function', { line: 19, character: 12 }, 'completion'], ['after_comment_in_empty_function', { line: 20, character: 0 }, 'generation'], ], ], [ 'json', '.json', // ../../fixtures/intent/json_comments.css [ ['on_empty_comment', { line: 20, character: 3 }, 'completion'], ['after_empty_comment', { line: 21, character: 0 }, 'completion'], ['on_non_empty_comment', { line: 0, character: 38 }, 'completion'], ['after_non_empty_comment', { line: 1, character: 0 }, 'generation'], ['no_comment_large_file', { line: 10, character: 0 }, undefined], ], ], [ 'scala', '.scala', // ../../fixtures/intent/scala_comments.scala [ ['on_empty_comment', { line: 1, character: 3 }, 'completion'], ['after_empty_comment', { line: 2, character: 3 }, 'completion'], ['after_non_empty_comment', { line: 5, character: 0 }, 'generation'], ['after_block_comment', { line: 10, character: 0 }, 'generation'], ['no_comment_large_file', { line: 12, character: 0 }, undefined], ['after_comment_in_empty_function', { line: 21, character: 0 }, 'generation'], ], ], [ 'powersell', '.ps1', // ../../fixtures/intent/powershell_comments.ps1 [ ['on_empty_comment', { line: 20, character: 3 }, 'completion'], ['after_empty_comment', { line: 21, character: 3 }, 'completion'], ['after_non_empty_comment', { line: 10, character: 0 }, 'generation'], ['after_block_comment', { line: 8, character: 0 }, 'generation'], ['no_comment_large_file', { line: 22, character: 0 }, undefined], ['after_comment_in_empty_function', { line: 26, character: 0 }, 'generation'], ], ], ]; describe.each(testCases)('%s', (language, fileExt, cases) => { it.each(cases)('should resolve %s intent correctly', async (_, position, expectedIntent) => { const fixturePath = getFixturePath('intent', `${language}_comments${fileExt}`); const { treeAndLanguage, prefix, suffix } = await getTreeAndTestFile({ fixturePath, position, languageId: language, }); const intent = await getIntent({ treeAndLanguage, position, prefix, suffix }); expect(intent.intent).toBe(expectedIntent); if (expectedIntent === 'generation') { expect(intent.generationType).toBe('comment'); } }); }); }); describe('Empty Function Intent', () => { type TestType = | 'empty_function_declaration' | 'non_empty_function_declaration' | 'empty_function_expression' | 'non_empty_function_expression' | 'empty_arrow_function' | 'non_empty_arrow_function' | 'empty_method_definition' | 'non_empty_method_definition' | 'empty_class_constructor' | 'non_empty_class_constructor' | 'empty_class_declaration' | 'non_empty_class_declaration' | 'empty_anonymous_function' | 'non_empty_anonymous_function' | 'empty_implementation' | 'non_empty_implementation' | 'empty_closure_expression' | 'non_empty_closure_expression' | 'empty_generator' | 'non_empty_generator' | 'empty_macro' | 'non_empty_macro'; type FileExtension = string; /** * Position refers to the position of the cursor in the test file. */ type IntentTestCase = [TestType, Position, Intent]; const emptyFunctionTestCases: Array< [LanguageServerLanguageId, FileExtension, IntentTestCase[]] > = [ [ 'typescript', '.ts', // ../../fixtures/intent/empty_function/typescript.ts [ ['empty_function_declaration', { line: 0, character: 22 }, 'generation'], ['non_empty_function_declaration', { line: 3, character: 4 }, undefined], ['empty_function_expression', { line: 6, character: 32 }, 'generation'], ['non_empty_function_expression', { line: 10, character: 4 }, undefined], ['empty_arrow_function', { line: 12, character: 26 }, 'generation'], ['non_empty_arrow_function', { line: 15, character: 4 }, undefined], ['empty_class_constructor', { line: 19, character: 21 }, 'generation'], ['empty_method_definition', { line: 21, character: 11 }, 'generation'], ['non_empty_class_constructor', { line: 29, character: 7 }, undefined], ['non_empty_method_definition', { line: 33, character: 0 }, undefined], ['empty_class_declaration', { line: 36, character: 14 }, 'generation'], ['empty_generator', { line: 38, character: 31 }, 'generation'], ['non_empty_generator', { line: 41, character: 4 }, undefined], ], ], [ 'javascript', '.js', // ../../fixtures/intent/empty_function/javascript.js [ ['empty_function_declaration', { line: 0, character: 22 }, 'generation'], ['non_empty_function_declaration', { line: 3, character: 4 }, undefined], ['empty_function_expression', { line: 6, character: 32 }, 'generation'], ['non_empty_function_expression', { line: 10, character: 4 }, undefined], ['empty_arrow_function', { line: 12, character: 26 }, 'generation'], ['non_empty_arrow_function', { line: 15, character: 4 }, undefined], ['empty_class_constructor', { line: 19, character: 21 }, 'generation'], ['empty_method_definition', { line: 21, character: 11 }, 'generation'], ['non_empty_class_constructor', { line: 27, character: 7 }, undefined], ['non_empty_method_definition', { line: 31, character: 0 }, undefined], ['empty_class_declaration', { line: 34, character: 14 }, 'generation'], ['empty_generator', { line: 36, character: 31 }, 'generation'], ['non_empty_generator', { line: 39, character: 4 }, undefined], ], ], [ 'go', '.go', // ../../fixtures/intent/empty_function/go.go [ ['empty_function_declaration', { line: 0, character: 25 }, 'generation'], ['non_empty_function_declaration', { line: 3, character: 4 }, undefined], ['empty_anonymous_function', { line: 6, character: 32 }, 'generation'], ['non_empty_anonymous_function', { line: 10, character: 0 }, undefined], ['empty_method_definition', { line: 19, character: 25 }, 'generation'], ['non_empty_method_definition', { line: 23, character: 0 }, undefined], ], ], [ 'java', '.java', // ../../fixtures/intent/empty_function/java.java [ ['empty_function_declaration', { line: 0, character: 26 }, 'generation'], ['non_empty_function_declaration', { line: 3, character: 4 }, undefined], ['empty_anonymous_function', { line: 7, character: 0 }, 'generation'], ['non_empty_anonymous_function', { line: 10, character: 0 }, undefined], ['empty_class_declaration', { line: 15, character: 18 }, 'generation'], ['non_empty_class_declaration', { line: 19, character: 0 }, undefined], ['empty_class_constructor', { line: 18, character: 13 }, 'generation'], ['empty_method_definition', { line: 20, character: 18 }, 'generation'], ['non_empty_class_constructor', { line: 26, character: 18 }, undefined], ['non_empty_method_definition', { line: 30, character: 18 }, undefined], ], ], [ 'rust', '.rs', // ../../fixtures/intent/empty_function/rust.vue [ ['empty_function_declaration', { line: 0, character: 23 }, 'generation'], ['non_empty_function_declaration', { line: 3, character: 4 }, undefined], ['empty_implementation', { line: 8, character: 13 }, 'generation'], ['non_empty_implementation', { line: 11, character: 0 }, undefined], ['empty_class_constructor', { line: 13, character: 0 }, 'generation'], ['non_empty_class_constructor', { line: 23, character: 0 }, undefined], ['empty_method_definition', { line: 17, character: 0 }, 'generation'], ['non_empty_method_definition', { line: 26, character: 0 }, undefined], ['empty_closure_expression', { line: 32, character: 0 }, 'generation'], ['non_empty_closure_expression', { line: 36, character: 0 }, undefined], ['empty_macro', { line: 42, character: 11 }, 'generation'], ['non_empty_macro', { line: 45, character: 11 }, undefined], ['empty_macro', { line: 55, character: 0 }, 'generation'], ['non_empty_macro', { line: 62, character: 20 }, undefined], ], ], [ 'kotlin', '.kt', // ../../fixtures/intent/empty_function/kotlin.kt [ ['empty_function_declaration', { line: 0, character: 25 }, 'generation'], ['non_empty_function_declaration', { line: 4, character: 0 }, undefined], ['empty_anonymous_function', { line: 6, character: 32 }, 'generation'], ['non_empty_anonymous_function', { line: 9, character: 4 }, undefined], ['empty_class_declaration', { line: 12, character: 14 }, 'generation'], ['non_empty_class_declaration', { line: 15, character: 14 }, undefined], ['empty_method_definition', { line: 24, character: 0 }, 'generation'], ['non_empty_method_definition', { line: 28, character: 0 }, undefined], ], ], [ 'typescriptreact', '.tsx', // ../../fixtures/intent/empty_function/typescriptreact.tsx [ ['empty_function_declaration', { line: 0, character: 22 }, 'generation'], ['non_empty_function_declaration', { line: 3, character: 4 }, undefined], ['empty_function_expression', { line: 6, character: 32 }, 'generation'], ['non_empty_function_expression', { line: 10, character: 4 }, undefined], ['empty_arrow_function', { line: 12, character: 26 }, 'generation'], ['non_empty_arrow_function', { line: 15, character: 4 }, undefined], ['empty_class_constructor', { line: 19, character: 21 }, 'generation'], ['empty_method_definition', { line: 21, character: 11 }, 'generation'], ['non_empty_class_constructor', { line: 29, character: 7 }, undefined], ['non_empty_method_definition', { line: 33, character: 0 }, undefined], ['empty_class_declaration', { line: 36, character: 14 }, 'generation'], ['non_empty_arrow_function', { line: 40, character: 0 }, undefined], ['empty_arrow_function', { line: 41, character: 23 }, 'generation'], ['non_empty_arrow_function', { line: 44, character: 23 }, undefined], ['empty_generator', { line: 54, character: 31 }, 'generation'], ['non_empty_generator', { line: 57, character: 4 }, undefined], ], ], [ 'c', '.c', // ../../fixtures/intent/empty_function/c.c [ ['empty_function_declaration', { line: 0, character: 24 }, 'generation'], ['non_empty_function_declaration', { line: 3, character: 0 }, undefined], ], ], [ 'cpp', '.cpp', // ../../fixtures/intent/empty_function/cpp.cpp [ ['empty_function_declaration', { line: 0, character: 37 }, 'generation'], ['non_empty_function_declaration', { line: 3, character: 0 }, undefined], ['empty_function_expression', { line: 6, character: 43 }, 'generation'], ['non_empty_function_expression', { line: 10, character: 4 }, undefined], ['empty_class_constructor', { line: 15, character: 37 }, 'generation'], ['empty_method_definition', { line: 17, character: 18 }, 'generation'], ['non_empty_class_constructor', { line: 27, character: 7 }, undefined], ['non_empty_method_definition', { line: 31, character: 0 }, undefined], ['empty_class_declaration', { line: 35, character: 14 }, 'generation'], ], ], [ 'c_sharp', '.cs', // ../../fixtures/intent/empty_function/c_sharp.cs [ ['empty_function_expression', { line: 2, character: 48 }, 'generation'], ['empty_class_constructor', { line: 4, character: 31 }, 'generation'], ['empty_method_definition', { line: 6, character: 31 }, 'generation'], ['non_empty_class_constructor', { line: 15, character: 0 }, undefined], ['non_empty_method_definition', { line: 20, character: 0 }, undefined], ['empty_class_declaration', { line: 24, character: 22 }, 'generation'], ], ], [ 'bash', '.sh', // ../../fixtures/intent/empty_function/bash.sh [ ['empty_function_declaration', { line: 3, character: 48 }, 'generation'], ['non_empty_function_declaration', { line: 6, character: 31 }, undefined], ], ], [ 'scala', '.scala', // ../../fixtures/intent/empty_function/scala.scala [ ['empty_function_declaration', { line: 1, character: 4 }, 'generation'], ['non_empty_function_declaration', { line: 5, character: 4 }, undefined], ['empty_method_definition', { line: 28, character: 3 }, 'generation'], ['non_empty_method_definition', { line: 34, character: 3 }, undefined], ['empty_class_declaration', { line: 22, character: 4 }, 'generation'], ['non_empty_class_declaration', { line: 27, character: 0 }, undefined], ['empty_anonymous_function', { line: 13, character: 0 }, 'generation'], ['non_empty_anonymous_function', { line: 17, character: 0 }, undefined], ], ], [ 'ruby', '.rb', // ../../fixtures/intent/empty_function/ruby.rb [ ['empty_method_definition', { line: 0, character: 23 }, 'generation'], ['empty_method_definition', { line: 0, character: 6 }, undefined], ['non_empty_method_definition', { line: 3, character: 0 }, undefined], ['empty_anonymous_function', { line: 7, character: 27 }, 'generation'], ['non_empty_anonymous_function', { line: 9, character: 37 }, undefined], ['empty_anonymous_function', { line: 11, character: 25 }, 'generation'], ['empty_class_constructor', { line: 16, character: 22 }, 'generation'], ['non_empty_class_declaration', { line: 18, character: 0 }, undefined], ['empty_method_definition', { line: 20, character: 1 }, 'generation'], ['empty_class_declaration', { line: 33, character: 12 }, 'generation'], ], ], [ 'python', '.py', // ../../fixtures/intent/empty_function/python.py [ ['empty_function_declaration', { line: 1, character: 4 }, 'generation'], ['non_empty_function_declaration', { line: 5, character: 4 }, undefined], ['empty_class_constructor', { line: 10, character: 0 }, 'generation'], ['empty_method_definition', { line: 14, character: 0 }, 'generation'], ['non_empty_class_constructor', { line: 19, character: 0 }, undefined], ['non_empty_method_definition', { line: 23, character: 4 }, undefined], ['empty_class_declaration', { line: 27, character: 4 }, 'generation'], ['empty_function_declaration', { line: 31, character: 4 }, 'generation'], ['empty_class_constructor', { line: 36, character: 4 }, 'generation'], ['empty_method_definition', { line: 40, character: 4 }, 'generation'], ['empty_class_declaration', { line: 44, character: 4 }, 'generation'], ['empty_function_declaration', { line: 49, character: 4 }, 'generation'], ['empty_class_constructor', { line: 53, character: 4 }, 'generation'], ['empty_method_definition', { line: 56, character: 4 }, 'generation'], ['empty_class_declaration', { line: 59, character: 4 }, 'generation'], ], ], ]; describe.each(emptyFunctionTestCases)('%s', (language, fileExt, cases) => { it.each(cases)('should resolve %s intent correctly', async (_, position, expectedIntent) => { const fixturePath = getFixturePath('intent', `empty_function/${language}${fileExt}`); const { treeAndLanguage, prefix, suffix } = await getTreeAndTestFile({ fixturePath, position, languageId: language, }); const intent = await getIntent({ treeAndLanguage, position, prefix, suffix }); expect(intent.intent).toBe(expectedIntent); if (expectedIntent === 'generation') { expect(intent.generationType).toBe('empty_function'); } }); }); }); }); References:" You are a code assistant,Definition of 'CONFIG_NAMESPACE' in file packages/webview_duo_chat/src/plugin/port/constants.ts in project gitlab-lsp,"Definition: export const CONFIG_NAMESPACE = 'gitlab'; export const DO_NOT_SHOW_CODE_SUGGESTIONS_VERSION_WARNING = 'DO_NOT_SHOW_VERSION_WARNING'; // NOTE: This needs to _always_ be a 3 digits export const MINIMUM_CODE_SUGGESTIONS_VERSION = '16.8.0'; export const DO_NOT_SHOW_VERSION_WARNING = 'DO_NOT_SHOW_VERSION_WARNING'; // NOTE: This needs to _always_ be a 3 digits 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 'getLanguages' in file src/browser/tree_sitter/index.ts in project gitlab-lsp,"Definition: getLanguages() { return this.languages; } getLoadState() { return this.loadState; } async init(): Promise { 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:" You are a code assistant,Definition of 'messageMatcher' in file scripts/commit-lint/lint.js in project gitlab-lsp,"Definition: const messageMatcher = (r) => r.test.bind(r); async function isConventional(message) { return lint( message, { ...config.rules, ...customRules }, { defaultIgnores: false, ignores: [ messageMatcher(/^[Rr]evert .*/), messageMatcher(/^(?:fixup|squash)!/), messageMatcher(/^Merge branch/), messageMatcher(/^\d+\.\d+\.\d+/), ], }, ); } async function lintMr() { const commits = await getCommitsInMr(); // When MR is set to squash, but it's not yet being merged, we check the MR Title if ( CI_MERGE_REQUEST_SQUASH_ON_MERGE === 'true' && CI_MERGE_REQUEST_EVENT_TYPE !== 'merge_train' ) { console.log( 'INFO: The MR is set to squash. We will lint the MR Title (used as the commit message by default).', ); return isConventional(CI_MERGE_REQUEST_TITLE).then(Array.of); } console.log('INFO: Checking all commits that will be added by this MR.'); return Promise.all(commits.map(isConventional)); } 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/commit-lint/lint.js:45 - scripts/commit-lint/lint.js:44 - scripts/commit-lint/lint.js:46 - scripts/commit-lint/lint.js:47" You are a code assistant,Definition of 'debug' in file packages/lib_logging/src/types.ts in project gitlab-lsp,"Definition: debug(message: string, e?: Error): void; 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 'BASE_SUPPORTED_CODE_SUGGESTIONS_LANGUAGES' in file src/common/suggestion/supported_languages_service.ts in project gitlab-lsp,"Definition: export const BASE_SUPPORTED_CODE_SUGGESTIONS_LANGUAGES = supportedLanguages.map( (l) => l.languageId, ); export interface SupportedLanguagesUpdateParam { allow?: string[]; deny?: string[]; } export interface SupportedLanguagesService { isLanguageEnabled(languageId: string): boolean; isLanguageSupported(languageId: string): boolean; onLanguageChange(listener: () => void): Disposable; } export const SupportedLanguagesService = createInterfaceId( 'SupportedLanguagesService', ); @Injectable(SupportedLanguagesService, [ConfigService]) export class DefaultSupportedLanguagesService implements SupportedLanguagesService { #enabledLanguages: Set; #supportedLanguages: Set; #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 = 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 'debug' in file packages/lib_logging/src/types.ts in project gitlab-lsp,"Definition: debug(e: Error): void; debug(message: string, e?: Error): void; 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 'WEBVIEW_ID' in file packages/webview_duo_chat/src/contract.ts in project gitlab-lsp,"Definition: export const WEBVIEW_ID = 'duo-chat' as WebviewId; export const WEBVIEW_TITLE = 'GitLab Duo Chat'; type Record = { id: string; }; export interface GitlabChatSlashCommand { name: string; description: string; shouldSubmit?: boolean; } export interface WebViewInitialStateInterface { slashCommands: GitlabChatSlashCommand[]; } export type Messages = CreatePluginMessageMap<{ pluginToWebview: { notifications: { newRecord: Record; updateRecord: Record; setLoadingState: boolean; cleanChat: undefined; }; }; webviewToPlugin: { notifications: { onReady: undefined; cleanChat: undefined; newPrompt: { record: { content: string; }; }; trackFeedback: { data?: { extendedTextFeedback: string | null; feedbackChoices: Array | null; }; }; }; }; pluginToExtension: { notifications: { showErrorMessage: { message: string; }; }; }; }>; References:" You are a code assistant,Definition of 'WebIDEExtension' in file packages/webview_duo_chat/src/plugin/port/platform/web_ide.ts in project gitlab-lsp,"Definition: 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 'constructor' in file src/common/connection_service.ts in project gitlab-lsp,"Definition: 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(method: NotificationType, notifier: Notifier) { 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 'ProcessorInputMap' in file src/common/suggestion_client/post_processors/post_processor_pipeline.ts in project gitlab-lsp,"Definition: type ProcessorInputMap = { stream: StreamingCompletionResponse; completion: SuggestionOption[]; }; /** * PostProcessor is an interface for classes that can be used to modify completion responses * before they are sent to the client. * They are run in order according to the order they are added to the PostProcessorPipeline. * Post-processors can be used to filter, sort, or modify completion and streaming suggestions. * Be sure to handle both streaming and completion responses in your implementation (if applicable). * */ export abstract class PostProcessor { processStream( _context: IDocContext, input: StreamingCompletionResponse, ): Promise { return Promise.resolve(input); } processCompletion(_context: IDocContext, input: SuggestionOption[]): Promise { return Promise.resolve(input); } } /** * Pipeline for running post-processors on completion and streaming (generation) responses. * Post-processors are used to modify completion responses before they are sent to the client. * They can be used to filter, sort, or modify completion suggestions. */ export class PostProcessorPipeline { #processors: PostProcessor[] = []; addProcessor(processor: PostProcessor): void { this.#processors.push(processor); } async run({ documentContext, input, type, }: { documentContext: IDocContext; input: ProcessorInputMap[T]; type: T; }): Promise { if (!this.#processors.length) return input as ProcessorInputMap[T]; return this.#processors.reduce( async (prevPromise, processor) => { const result = await prevPromise; // eslint-disable-next-line default-case switch (type) { case 'stream': return processor.processStream( documentContext, result as StreamingCompletionResponse, ) as Promise; case 'completion': return processor.processCompletion( documentContext, result as SuggestionOption[], ) as Promise; } throw new Error('Unexpected type in pipeline processing'); }, Promise.resolve(input) as Promise, ); } } References:" You are a code assistant,Definition of 'createMockFastifyInstance' in file src/node/webview/test-utils/mock_fastify_instance.ts in project gitlab-lsp,"Definition: export const createMockFastifyInstance = (): MockFastifyInstance & FastifyInstance => { const reply: Partial = {}; reply.register = jest.fn().mockReturnThis(); reply.get = jest.fn().mockReturnThis(); return reply as MockFastifyInstance & FastifyInstance; }; References: - src/node/webview/routes/webview_routes.test.ts:17" You are a code assistant,Definition of 'Options' in file src/node/webview/webview_fastify_middleware.ts in project gitlab-lsp,"Definition: type Options = { webviewIds: WebviewId[]; }; export const createWebviewPlugin = (options: Options): FastifyPluginRegistration => ({ plugin: (fastify, { webviewIds }) => setupWebviewRoutes(fastify, { webviewIds, getWebviewResourcePath: buildWebviewPath, }), options, }); const buildWebviewPath = (webviewId: WebviewId) => path.join(WEBVIEW_BASE_PATH, webviewId); References: - src/node/webview/webview_fastify_middleware.ts:12" You are a code assistant,Definition of 'GqlProjectWithDuoEnabledInfo' in file src/common/services/duo_access/project_access_cache.ts in project gitlab-lsp,"Definition: export interface GqlProjectWithDuoEnabledInfo { duoFeaturesEnabled: boolean; } export interface DuoProjectAccessCache { getProjectsForWorkspaceFolder(workspaceFolder: WorkspaceFolder): DuoProject[]; updateCache({ baseUrl, workspaceFolders, }: { baseUrl: string; workspaceFolders: WorkspaceFolder[]; }): Promise; onDuoProjectCacheUpdate(listener: () => void): Disposable; } export const DuoProjectAccessCache = createInterfaceId('DuoProjectAccessCache'); @Injectable(DuoProjectAccessCache, [DirectoryWalker, FileResolver, GitLabApiClient]) export class DefaultDuoProjectAccessCache { #duoProjects: Map; #eventEmitter = new EventEmitter(); constructor( private readonly directoryWalker: DirectoryWalker, private readonly fileResolver: FileResolver, private readonly api: GitLabApiClient, ) { this.#duoProjects = new Map(); } getProjectsForWorkspaceFolder(workspaceFolder: WorkspaceFolder): DuoProject[] { return this.#duoProjects.get(workspaceFolder.uri) ?? []; } async updateCache({ baseUrl, workspaceFolders, }: { baseUrl: string; workspaceFolders: WorkspaceFolder[]; }) { try { this.#duoProjects.clear(); const duoProjects = await Promise.all( workspaceFolders.map(async (workspaceFolder) => { return { workspaceFolder, projects: await this.#duoProjectsForWorkspaceFolder({ workspaceFolder, baseUrl, }), }; }), ); for (const { workspaceFolder, projects } of duoProjects) { this.#logProjectsInfo(projects, workspaceFolder); this.#duoProjects.set(workspaceFolder.uri, projects); } this.#triggerChange(); } catch (err) { log.error('DuoProjectAccessCache: failed to update project access cache', err); } } #logProjectsInfo(projects: DuoProject[], workspaceFolder: WorkspaceFolder) { if (!projects.length) { log.warn( `DuoProjectAccessCache: no projects found for workspace folder ${workspaceFolder.uri}`, ); return; } log.debug( `DuoProjectAccessCache: found ${projects.length} projects for workspace folder ${workspaceFolder.uri}: ${JSON.stringify(projects, null, 2)}`, ); } async #duoProjectsForWorkspaceFolder({ workspaceFolder, baseUrl, }: { workspaceFolder: WorkspaceFolder; baseUrl: string; }): Promise { const remotes = await this.#gitlabRemotesForWorkspaceFolder(workspaceFolder, baseUrl); const projects = await Promise.all( remotes.map(async (remote) => { const enabled = await this.#checkDuoFeaturesEnabled(remote.namespaceWithPath); return { projectPath: remote.projectPath, uri: remote.fileUri, enabled, host: remote.host, namespace: remote.namespace, namespaceWithPath: remote.namespaceWithPath, } satisfies DuoProject; }), ); return projects; } async #gitlabRemotesForWorkspaceFolder( workspaceFolder: WorkspaceFolder, baseUrl: string, ): Promise { const paths = await this.directoryWalker.findFilesForDirectory({ directoryUri: workspaceFolder.uri, filters: { fileEndsWith: ['/.git/config'], }, }); const remotes = await Promise.all( paths.map(async (fileUri) => this.#gitlabRemotesForFileUri(fileUri.toString(), baseUrl)), ); return remotes.flat(); } async #gitlabRemotesForFileUri( fileUri: string, baseUrl: string, ): Promise { const remoteUrls = await this.#remoteUrlsFromGitConfig(fileUri); return remoteUrls.reduce((acc, remoteUrl) => { const remote = parseGitLabRemote(remoteUrl, baseUrl); if (remote) { acc.push({ ...remote, fileUri }); } return acc; }, []); } async #remoteUrlsFromGitConfig(fileUri: string): Promise { try { const fileString = await this.fileResolver.readFile({ fileUri }); const config = ini.parse(fileString); return this.#getRemoteUrls(config); } catch (error) { log.error(`DuoProjectAccessCache: Failed to read git config file: ${fileUri}`, error); return []; } } #getRemoteUrls(config: GitConfig): string[] { return Object.keys(config).reduce((acc, section) => { if (section.startsWith('remote ')) { acc.push(config[section].url); } return acc; }, []); } async #checkDuoFeaturesEnabled(projectPath: string): Promise { try { const response = await this.api.fetchFromApi<{ project: GqlProjectWithDuoEnabledInfo }>({ type: 'graphql', query: duoFeaturesEnabledQuery, variables: { projectPath, }, } satisfies ApiRequest<{ project: GqlProjectWithDuoEnabledInfo }>); return Boolean(response?.project?.duoFeaturesEnabled); } catch (error) { log.error( `DuoProjectAccessCache: Failed to check if Duo features are enabled for project: ${projectPath}`, error, ); return true; } } onDuoProjectCacheUpdate( listener: (duoProjectsCache: Map) => void, ): Disposable { this.#eventEmitter.on(DUO_PROJECT_CACHE_UPDATE_EVENT, listener); return { dispose: () => this.#eventEmitter.removeListener(DUO_PROJECT_CACHE_UPDATE_EVENT, listener), }; } #triggerChange() { this.#eventEmitter.emit(DUO_PROJECT_CACHE_UPDATE_EVENT, this.#duoProjects); } } References: - src/common/services/duo_access/project_access_cache.test.ts:51 - src/common/services/duo_access/project_access_cache.ts:227 - src/common/services/duo_access/project_access_cache.test.ts:123 - src/common/services/duo_access/project_access_cache.ts:221 - src/common/services/duo_access/project_access_cache.test.ts:155 - src/common/services/duo_access/project_access_cache.test.ts:86" You are a code assistant,Definition of 'buildTreeSitterInfoByExtMap' in file src/common/tree_sitter/parser.ts in project gitlab-lsp,"Definition: buildTreeSitterInfoByExtMap( languages: TreeSitterLanguageInfo[], ): Map { return languages.reduce((map, language) => { for (const extension of language.extensions) { map.set(extension, language); } return map; }, new Map()); } } References:" You are a code assistant,Definition of 'GitLabPlatform' in file packages/webview_duo_chat/src/plugin/port/platform/gitlab_platform.ts in project gitlab-lsp,"Definition: export type GitLabPlatform = GitLabPlatformForProject | GitLabPlatformForAccount; 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; /** * 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; /** * 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; getForAllAccounts(): Promise; /** * Returns GitLabPlatformForAccount if there is a SaaS account added. Otherwise returns undefined. */ getForSaaSAccount(): Promise; } References:" You are a code assistant,Definition of 'ChatRecordRole' in file packages/webview_duo_chat/src/plugin/port/chat/gitlab_chat_record.ts in project gitlab-lsp,"Definition: type ChatRecordRole = 'user' | 'assistant' | 'system'; type ChatRecordState = 'pending' | 'ready'; type ChatRecordType = | 'general' | 'explainCode' | 'generateTests' | 'refactorCode' | 'newConversation'; type GitLabChatRecordAttributes = { chunkId?: number | null; type?: ChatRecordType; role: ChatRecordRole; content?: string; contentHtml?: string; requestId?: string; state?: ChatRecordState; errors?: string[]; timestamp?: string; extras?: { sources: object[]; }; }; export class GitLabChatRecord { chunkId?: number | null; role: ChatRecordRole; content?: string; contentHtml?: string; id: string; requestId?: string; state: ChatRecordState; timestamp: number; type: ChatRecordType; errors: string[]; extras?: { sources: object[]; }; context?: GitLabChatRecordContext; constructor({ chunkId, type, role, content, contentHtml, state, requestId, errors, timestamp, extras, }: GitLabChatRecordAttributes) { this.chunkId = chunkId; this.role = role; this.content = content; this.contentHtml = contentHtml; this.type = type ?? this.#detectType(); this.state = state ?? 'ready'; this.requestId = requestId; this.errors = errors ?? []; this.id = uuidv4(); this.timestamp = timestamp ? Date.parse(timestamp) : Date.now(); this.extras = extras; } static buildWithContext(attributes: GitLabChatRecordAttributes): GitLabChatRecord { const record = new GitLabChatRecord(attributes); record.context = buildCurrentContext(); return record; } update(attributes: Partial) { const convertedAttributes = attributes as Partial; if (attributes.timestamp) { convertedAttributes.timestamp = Date.parse(attributes.timestamp); } Object.assign(this, convertedAttributes); } #detectType(): ChatRecordType { if (this.content === SPECIAL_MESSAGES.RESET) { return 'newConversation'; } return 'general'; } } References: - packages/webview_duo_chat/src/plugin/port/chat/gitlab_chat_record.ts:32 - packages/webview_duo_chat/src/plugin/port/chat/gitlab_chat_record.ts:17" You are a code assistant,Definition of 'INSTANCE_TRACKING_EVENTS_MAP' in file src/common/tracking/constants.ts in project gitlab-lsp,"Definition: 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 'withPrefix' in file packages/lib_logging/src/utils/with_prefix.ts in project gitlab-lsp,"Definition: export function withPrefix(logger: Logger, prefix: string): Logger { const addPrefix = (message: string) => `${prefix} ${message}`; return LOG_METHODS.reduce((acc, method) => { acc[method] = (message: string | Error, e?: Error): void => { if (typeof message === 'string') { logger[method](addPrefix(message), e); } else { logger[method](message); } }; return acc; }, {} as Logger); } References: - src/common/graphql/workflow/service.ts:20 - packages/lib_webview_transport_json_rpc/src/json_rpc_connection_transport.ts:81 - packages/lib_webview/src/setup/setup_webview_runtime.ts:18 - packages/lib_webview/src/setup/plugin/webview_instance_message_bus.ts:39 - packages/lib_logging/src/utils/with_prefix.test.ts:28 - src/common/webview/extension/extension_connection_message_bus_provider.ts:47 - packages/lib_webview/src/setup/plugin/webview_controller.ts:43 - packages/lib_webview_transport_socket_io/src/socket_io_webview_transport.ts:40" You are a code assistant,Definition of 'DidChangeDocumentInActiveEditorParams' in file src/common/notifications.ts in project gitlab-lsp,"Definition: export type DidChangeDocumentInActiveEditorParams = TextDocument | DocumentUri; export const DidChangeDocumentInActiveEditor = new NotificationType( '$/gitlab/didChangeDocumentInActiveEditor', ); References: - src/common/document_service.ts:20 - src/common/document_service.ts:52" You are a code assistant,Definition of 'put' in file src/common/fetch.ts in project gitlab-lsp,"Definition: async put(input: RequestInfo | URL, init?: RequestInit): Promise { return this.fetch(input, this.updateRequestInit('PUT', init)); } async fetchBase(input: RequestInfo | URL, init?: RequestInit): Promise { // 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 'RepoFileUri' in file src/common/git/repository.ts in project gitlab-lsp,"Definition: type RepoFileUri = URI; type RepositoryUri = URI; export type RepositoryFile = { uri: RepoFileUri; repositoryUri: RepositoryUri; isIgnored: boolean; workspaceFolder: WorkspaceFolder; }; export class Repository { workspaceFolder: WorkspaceFolder; uri: URI; configFileUri: URI; #files: Map; #ignoreManager: IgnoreManager; constructor({ configFileUri, workspaceFolder, uri, ignoreManager, }: { workspaceFolder: WorkspaceFolder; uri: RepositoryUri; configFileUri: URI; ignoreManager: IgnoreManager; }) { this.workspaceFolder = workspaceFolder; this.uri = uri; this.configFileUri = configFileUri; this.#files = new Map(); this.#ignoreManager = ignoreManager; } async addFilesAndLoadGitIgnore(files: URI[]): Promise { log.info(`Adding ${files.length} files to repository ${this.uri.toString()}`); await this.#ignoreManager.loadIgnoreFiles(files.map((uri) => uri.fsPath)); for (const file of files) { if (!this.#ignoreManager.isIgnored(file.fsPath)) { this.#files.set(file.toString(), { uri: file, isIgnored: false, repositoryUri: this.uri, workspaceFolder: this.workspaceFolder, }); } else { this.#files.set(file.toString(), { uri: file, isIgnored: true, repositoryUri: this.uri, workspaceFolder: this.workspaceFolder, }); } } } isFileIgnored(filePath: URI): boolean { return this.#ignoreManager.isIgnored(filePath.fsPath); } setFile(fileUri: URI): void { if (!this.isFileIgnored(fileUri)) { this.#files.set(fileUri.toString(), { uri: fileUri, isIgnored: false, repositoryUri: this.uri, workspaceFolder: this.workspaceFolder, }); } else { this.#files.set(fileUri.toString(), { uri: fileUri, isIgnored: true, repositoryUri: this.uri, workspaceFolder: this.workspaceFolder, }); } } getFile(fileUri: string): RepositoryFile | undefined { return this.#files.get(fileUri); } removeFile(fileUri: string): void { this.#files.delete(fileUri); } getFiles(): Map { return this.#files; } dispose(): void { this.#ignoreManager.dispose(); this.#files.clear(); } } References: - src/common/git/repository.ts:10" You are a code assistant,Definition of 'addPattern' in file src/common/git/ignore_trie.ts in project gitlab-lsp,"Definition: addPattern(pathParts: string[], pattern: string): void { if (pathParts.length === 0) { if (!this.#ignoreInstance) { this.#ignoreInstance = ignore(); } this.#ignoreInstance.add(pattern); } else { const [current, ...rest] = pathParts; if (!this.#children.has(current)) { this.#children.set(current, new IgnoreTrie()); } const child = this.#children.get(current); if (!child) { return; } child.addPattern(rest, pattern); } } isIgnored(pathParts: string[]): boolean { if (pathParts.length === 0) { return false; } const [current, ...rest] = pathParts; if (this.#ignoreInstance && this.#ignoreInstance.ignores(path.join(...pathParts))) { return true; } const child = this.#children.get(current); if (child) { return child.isIgnored(rest); } return false; } 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 'Intent' in file src/common/suggestion_client/suggestion_client.ts in project gitlab-lsp,"Definition: export type Intent = typeof GENERATION | typeof COMPLETION | undefined; export interface SuggestionContext { document: IDocContext; intent?: Intent; projectPath?: string; optionsCount?: OptionsCount; additionalContexts?: AdditionalContext[]; } export interface SuggestionResponse { choices?: SuggestionResponseChoice[]; model?: SuggestionModel; status: number; error?: string; isDirectConnection?: boolean; } export interface SuggestionResponseChoice { text: string; } export interface SuggestionClient { getSuggestions(context: SuggestionContext): Promise; } export type SuggestionClientFn = SuggestionClient['getSuggestions']; export type SuggestionClientMiddleware = ( context: SuggestionContext, next: SuggestionClientFn, ) => ReturnType; References: - src/common/tree_sitter/intent_resolver.ts:12 - src/common/suggestion_client/suggestion_client.ts:21" You are a code assistant,Definition of 'AdvancedContextFilterArgs' in file src/common/advanced_context/advanced_context_filters.ts in project gitlab-lsp,"Definition: type AdvancedContextFilterArgs = { contextResolutions: ContextResolution[]; documentContext: IDocContext; byteSizeLimit: number; dependencies: { duoProjectAccessChecker: DuoProjectAccessChecker; }; }; type AdvanceContextFilter = (args: AdvancedContextFilterArgs) => Promise; /** * Filters context resolutions that have empty content. */ const emptyContentFilter = async ({ contextResolutions }: AdvancedContextFilterArgs) => { return contextResolutions.filter(({ content }) => content.replace(/\s/g, '') !== ''); }; /** * Filters context resolutions that * contain a Duo project that have Duo features enabled. * See `DuoProjectAccessChecker` for more details. */ const duoProjectAccessFilter: AdvanceContextFilter = async ({ contextResolutions, dependencies: { duoProjectAccessChecker }, documentContext, }: AdvancedContextFilterArgs) => { if (!documentContext?.workspaceFolder) { return contextResolutions; } return contextResolutions.reduce((acc, resolution) => { const { uri: resolutionUri } = resolution; const projectStatus = duoProjectAccessChecker.checkProjectStatus( resolutionUri, documentContext.workspaceFolder as WorkspaceFolder, ); if (projectStatus === DuoProjectStatus.DuoDisabled) { log.warn(`Advanced Context Filter: Duo features are not enabled for ${resolutionUri}`); return acc; } return [...acc, resolution]; }, [] as ContextResolution[]); }; /** * Filters context resolutions that meet the byte size limit. * The byte size limit takes into the size of the total * context resolutions content + size of document content. */ const byteSizeLimitFilter: AdvanceContextFilter = async ({ contextResolutions, documentContext, byteSizeLimit, }: AdvancedContextFilterArgs) => { const documentSize = getByteSize(`${documentContext.prefix}${documentContext.suffix}`); let currentTotalSize = documentSize; const filteredResolutions: ContextResolution[] = []; for (const resolution of contextResolutions) { currentTotalSize += getByteSize(resolution.content); if (currentTotalSize > byteSizeLimit) { // trim the current resolution content to fit the byte size limit const trimmedContent = Buffer.from(resolution.content) .slice(0, byteSizeLimit - currentTotalSize) .toString(); if (trimmedContent.length) { log.info( `Advanced Context Filter: ${resolution.uri} content trimmed to fit byte size limit: ${trimmedContent.length} bytes.`, ); filteredResolutions.push({ ...resolution, content: trimmedContent }); } log.debug( `Advanced Context Filter: Byte size limit exceeded for ${resolution.uri}. Skipping resolution.`, ); break; } filteredResolutions.push(resolution); } return filteredResolutions; }; /** * Advanced context filters that are applied to context resolutions. * @see filterContextResolutions */ const advancedContextFilters: AdvanceContextFilter[] = [ emptyContentFilter, duoProjectAccessFilter, byteSizeLimitFilter, ]; /** * Filters context resolutions based on business logic. * The filters are order dependent. * @see advancedContextFilters */ export const filterContextResolutions = async ({ contextResolutions, dependencies, documentContext, byteSizeLimit, }: AdvancedContextFilterArgs): Promise => { return advancedContextFilters.reduce(async (prevPromise, filter) => { const resolutions = await prevPromise; return filter({ contextResolutions: resolutions, dependencies, documentContext, byteSizeLimit, }); }, Promise.resolve(contextResolutions)); }; References: - src/common/advanced_context/advanced_context_filters.ts:18 - src/common/advanced_context/advanced_context_filters.ts:23 - src/common/advanced_context/advanced_context_filters.ts:64 - src/common/advanced_context/advanced_context_filters.ts:114 - src/common/advanced_context/advanced_context_filters.ts:36" You are a code assistant,Definition of 'Greet' in file src/tests/fixtures/intent/empty_function/python.py in project gitlab-lsp,"Definition: class Greet: def __init__(self, name): pass def greet(self): pass 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/go_comments.go:24 - 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" You are a code assistant,Definition of 'isTextSuggestion' in file src/common/utils/suggestion_mappers.ts in project gitlab-lsp,"Definition: export const isTextSuggestion = (o: SuggestionOptionOrStream): o is SuggestionOption => Boolean((o as SuggestionOption).text); export const completionOptionMapper = (options: SuggestionOption[]): CompletionItem[] => options.map((option, index) => ({ label: `GitLab Suggestion ${index + 1}: ${option.text}`, kind: CompletionItemKind.Text, insertText: option.text, detail: option.text, command: { title: 'Accept suggestion', command: SUGGESTION_ACCEPTED_COMMAND, arguments: [option.uniqueTrackingId], }, data: { index, trackingId: option.uniqueTrackingId, }, })); /* this value will be used for telemetry so to make it human-readable we use the 1-based indexing instead of 0 */ const getOptionTrackingIndex = (option: SuggestionOption) => { return typeof option.index === 'number' ? option.index + 1 : undefined; }; export const inlineCompletionOptionMapper = ( params: InlineCompletionParams, options: SuggestionOptionOrStream[], ): InlineCompletionList => ({ items: options.map((option) => { if (isStream(option)) { // the streaming item is empty and only indicates to the client that streaming started return { insertText: '', command: { title: 'Start streaming', command: START_STREAMING_COMMAND, arguments: [option.streamId, option.uniqueTrackingId], }, }; } const completionInfo = params.context.selectedCompletionInfo; let rangeDiff = 0; if (completionInfo) { const range = sanitizeRange(completionInfo.range); rangeDiff = range.end.character - range.start.character; } return { insertText: completionInfo ? `${completionInfo.text.substring(rangeDiff)}${option.text}` : option.text, range: Range.create(params.position, params.position), command: { title: 'Accept suggestion', command: SUGGESTION_ACCEPTED_COMMAND, arguments: [option.uniqueTrackingId, getOptionTrackingIndex(option)], }, }; }), }); References:" You are a code assistant,Definition of 'isInstanceFlagEnabled' in file src/common/feature_flags.ts in project gitlab-lsp,"Definition: isInstanceFlagEnabled(name: InstanceFeatureFlags): boolean; /** * Checks if a feature flag is enabled on the client. * @see `ConfigService` for client configuration. */ isClientFlagEnabled(name: ClientFeatureFlags): boolean; } @Injectable(FeatureFlagService, [GitLabApiClient, ConfigService]) export class DefaultFeatureFlagService { #api: GitLabApiClient; #configService: ConfigService; #featureFlags: Map = 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 { 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 { 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 'addFilesAndLoadGitIgnore' in file src/common/git/repository.ts in project gitlab-lsp,"Definition: async addFilesAndLoadGitIgnore(files: URI[]): Promise { log.info(`Adding ${files.length} files to repository ${this.uri.toString()}`); await this.#ignoreManager.loadIgnoreFiles(files.map((uri) => uri.fsPath)); for (const file of files) { if (!this.#ignoreManager.isIgnored(file.fsPath)) { this.#files.set(file.toString(), { uri: file, isIgnored: false, repositoryUri: this.uri, workspaceFolder: this.workspaceFolder, }); } else { this.#files.set(file.toString(), { uri: file, isIgnored: true, repositoryUri: this.uri, workspaceFolder: this.workspaceFolder, }); } } } isFileIgnored(filePath: URI): boolean { return this.#ignoreManager.isIgnored(filePath.fsPath); } setFile(fileUri: URI): void { if (!this.isFileIgnored(fileUri)) { this.#files.set(fileUri.toString(), { uri: fileUri, isIgnored: false, repositoryUri: this.uri, workspaceFolder: this.workspaceFolder, }); } else { this.#files.set(fileUri.toString(), { uri: fileUri, isIgnored: true, repositoryUri: this.uri, workspaceFolder: this.workspaceFolder, }); } } getFile(fileUri: string): RepositoryFile | undefined { return this.#files.get(fileUri); } removeFile(fileUri: string): void { this.#files.delete(fileUri); } getFiles(): Map { return this.#files; } dispose(): void { this.#ignoreManager.dispose(); this.#files.clear(); } } References:" You are a code assistant,Definition of 'CreateFastifyServerProps' in file src/node/http/create_fastify_http_server.ts in project gitlab-lsp,"Definition: type CreateFastifyServerProps = { port: number; plugins: FastifyPluginRegistration[]; logger: ILog; }; type CreateHttpServerResult = { address: URL; server: FastifyInstance; shutdown: () => Promise; }; export const createFastifyHttpServer = async ( props: Partial, ): Promise => { const { port = 0, plugins = [] } = props; const logger = props.logger && loggerWithPrefix(props.logger, '[HttpServer]:'); const server = fastify({ forceCloseConnections: true, ignoreTrailingSlash: true, logger: createFastifyLogger(logger), }); try { await registerPlugins(server, plugins, logger); const address = await startFastifyServer(server, port, logger); await server.ready(); logger?.info(`server listening on ${address}`); return { address, server, shutdown: async () => { try { await server.close(); logger?.info('server shutdown'); } catch (err) { logger?.error('error during server shutdown', err as Error); } }, }; } catch (err) { logger?.error('error during server setup', err as Error); throw err; } }; const registerPlugins = async ( server: FastifyInstance, plugins: FastifyPluginRegistration[], logger?: ILog, ) => { await Promise.all( plugins.map(async ({ plugin, options }) => { try { await server.register(plugin, options); } catch (err) { logger?.error('Error during plugin registration', err as Error); throw err; } }), ); }; const startFastifyServer = (server: FastifyInstance, port: number, logger?: ILog): Promise => new Promise((resolve, reject) => { try { server.listen({ port, host: '127.0.0.1' }, (err, address) => { if (err) { logger?.error(err); reject(err); return; } resolve(new URL(address)); }); } catch (error) { reject(error); } }); const createFastifyLogger = (logger?: ILog): FastifyBaseLogger | undefined => logger ? pino(createLoggerTransport(logger)) : undefined; References:" You are a code assistant,Definition of 'testSolvers' in file packages/webview-chat/src/app/index.ts in project gitlab-lsp,"Definition: function testSolvers(index: number) { const results = solvers.map(({ name, solver }) => { const start = performance.now(); const result = solver.solve(index); const duration = performance.now() - start; return { name, result, duration }; }); results.forEach(({ name, result, duration }) => { // eslint-disable-next-line no-alert alert(`${name}: Fibonacci of ${index} is ${result} (calculated in ${duration.toFixed(2)} ms)`); }); } document.body.appendChild(inputBox); document.body.appendChild(button); References: - packages/webview-chat/src/app/index.ts:27" You are a code assistant,Definition of 'TestTuple' in file src/common/log.test.ts in project gitlab-lsp,"Definition: type TestTuple = [keyof ILog, LogLevel]; it('does not log debug logs by default', () => { log.debug('message'); expect(logFunction).not.toBeCalled(); }); it.each([ ['info', LOG_LEVEL.INFO], ['warn', LOG_LEVEL.WARNING], ['error', LOG_LEVEL.ERROR], ])('it handles log level ""%s""', (methodName, logLevel) => { log[methodName]('message'); expect(getLoggedMessage()).toContain(`[${logLevel}]: message`); expect(getLoggedMessage()).not.toMatch(/\s+Error\s+at.*log\.[jt]s/m); }); it('indents multiline messages', () => { log.error('error happened\nand the next line\nexplains why'); expect(getLoggedMessage()).toContain( `[error]: error happened\n and the next line\n explains why`, ); }); describe.each` exception | error | expectation ${new Error('wrong')} | ${new Error('wrong')} | ${'returns the error object '} ${'error'} | ${new Error('error')} | ${'transforms string into Error'} ${0} | ${'0'} | ${'returns JSON.stringify of the exception otherwise'} `('get Error from unknown exception', ({ exception, error, expectation }) => { it(`${expectation}`, () => { log.error('test message', exception); expect(getLoggedMessage()).toContain(error.message || error); }); }); }); describe('log Error', () => { it('passes the argument to the handler', () => { const message = 'A very bad error occurred'; const error = { message, stack: 'stack', }; log.error(error as Error); expect(getLoggedMessage()).toMatch(/\[error\]: A very bad error occurred\s+stack/m); }); }); }); }); References:" You are a code assistant,Definition of 'constructor' in file packages/lib_handler_registry/src/errors/unhandled_handler_error.ts in project gitlab-lsp,"Definition: constructor(handlerId: string, originalError: Error) { super(`Unhandled error in handler '${handlerId}': ${originalError.message}`); this.name = 'UnhandledHandlerError'; this.originalError = originalError; this.stack = originalError.stack; } } References:" You are a code assistant,Definition of 'DesktopDirectoryWalker' in file src/node/services/fs/dir.ts in project gitlab-lsp,"Definition: export class DesktopDirectoryWalker implements DirectoryWalker { #watchers: Map = new Map(); #applyFilters(fileUri: DocumentUri, filters: DirectoryToSearch['filters']) { if (!filters) { return true; } if (filters.fileEndsWith) { return filters.fileEndsWith.some((end) => fileUri.endsWith(end)); } return true; } async findFilesForDirectory(args: DirectoryToSearch): Promise { const { filters, directoryUri } = args; const perf = performance.now(); const pathMap = new Map(); const promise = new FastDirectoryCrawler() .withFullPaths() .filter((path) => { const fileUri = fsPathToUri(path); // save each normalized filesystem path avoid re-parsing the path pathMap.set(path, fileUri); return this.#applyFilters(fileUri.path, filters); }) .crawl(fsPathFromUri(directoryUri)) .withPromise(); const paths = await promise; log.debug( `DirectoryWalker: found ${paths.length} paths, took ${Math.round(performance.now() - perf)}ms`, ); return paths.map((path) => pathMap.get(path) as URI); } setupFileWatcher(workspaceFolder: WorkspaceFolder, fileChangeHandler: FileChangeHandler): void { const fsPath = fsPathFromUri(workspaceFolder.uri); const watcher = chokidar.watch(fsPath, { persistent: true, alwaysStat: false, ignoreInitial: true, }); watcher .on('add', (path) => fileChangeHandler('add', workspaceFolder, path)) .on('change', (path) => fileChangeHandler('change', workspaceFolder, path)) .on('unlink', (path) => fileChangeHandler('unlink', workspaceFolder, path)); this.#watchers.set(workspaceFolder.uri, watcher); } async dispose(): Promise { const promises = Array.from(this.#watchers.values()).map((watcher) => watcher.close()); await Promise.all(promises); this.#watchers.clear(); } } References: - src/node/services/fs/dir.test.ts:27 - src/node/services/fs/dir.test.ts:14" You are a code assistant,Definition of 'isConventional' in file scripts/commit-lint/lint.js in project gitlab-lsp,"Definition: async function isConventional(message) { return lint( message, { ...config.rules, ...customRules }, { defaultIgnores: false, ignores: [ messageMatcher(/^[Rr]evert .*/), messageMatcher(/^(?:fixup|squash)!/), messageMatcher(/^Merge branch/), messageMatcher(/^\d+\.\d+\.\d+/), ], }, ); } async function lintMr() { const commits = await getCommitsInMr(); // When MR is set to squash, but it's not yet being merged, we check the MR Title if ( CI_MERGE_REQUEST_SQUASH_ON_MERGE === 'true' && CI_MERGE_REQUEST_EVENT_TYPE !== 'merge_train' ) { console.log( 'INFO: The MR is set to squash. We will lint the MR Title (used as the commit message by default).', ); return isConventional(CI_MERGE_REQUEST_TITLE).then(Array.of); } console.log('INFO: Checking all commits that will be added by this MR.'); return Promise.all(commits.map(isConventional)); } 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/commit-lint/lint.js:64" You are a code assistant,Definition of 'Greet' in file src/tests/fixtures/intent/empty_function/go.go in project gitlab-lsp,"Definition: type Greet struct{} type Greet struct { name string } // empty method declaration func (g Greet) greet() { } // non-empty method declaration func (g Greet) greet() { fmt.Printf(""Hello %s\n"", g.name) } 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 'onRequest' in file packages/lib_message_bus/src/types/bus.ts in project gitlab-lsp,"Definition: onRequest>( type: T, handler: () => Promise>, ): Disposable; onRequest( type: T, handler: (payload: TRequests[T]['params']) => Promise>, ): Disposable; } /** * Defines the structure for message definitions, including notifications and requests. */ export type MessageDefinitions< TNotifications extends NotificationMap = NotificationMap, TRequests extends RequestMap = RequestMap, > = { notifications: TNotifications; requests: TRequests; }; export type MessageMap< TInboundMessageDefinitions extends MessageDefinitions = MessageDefinitions, TOutboundMessageDefinitions extends MessageDefinitions = MessageDefinitions, > = { inbound: TInboundMessageDefinitions; outbound: TOutboundMessageDefinitions; }; export interface MessageBus extends NotificationPublisher, NotificationListener, RequestPublisher, RequestListener {} References:" You are a code assistant,Definition of 'subscribeToUpdates' in file packages/webview_duo_chat/src/plugin/port/chat/gitlab_chat_api.ts in project gitlab-lsp,"Definition: async subscribeToUpdates( messageCallback: (message: AiCompletionResponseMessageType) => Promise, subscriptionId?: string, ) { const platform = await this.#currentPlatform(); const channel = new AiCompletionResponseChannel({ htmlResponse: true, userId: `gid://gitlab/User/${extractUserId(platform.account.id)}`, aiAction: 'CHAT', clientSubscriptionId: subscriptionId, }); const cable = await platform.connectToCable(); // we use this flag to fix https://gitlab.com/gitlab-org/gitlab-vscode-extension/-/issues/1397 // sometimes a chunk comes after the full message and it broke the chat let fullMessageReceived = false; channel.on('newChunk', async (msg) => { if (fullMessageReceived) { log.info(`CHAT-DEBUG: full message received, ignoring chunk`); return; } await messageCallback(msg); }); channel.on('fullMessage', async (message) => { fullMessageReceived = true; await messageCallback(message); if (subscriptionId) { cable.disconnect(); } }); cable.subscribe(channel); } async #sendAiAction(variables: object): Promise { const platform = await this.#currentPlatform(); const { query, defaultVariables } = await this.#actionQuery(); const projectGqlId = await this.#manager.getProjectGqlId(); const request: GraphQLRequest = { type: 'graphql', query, variables: { ...variables, ...defaultVariables, resourceId: projectGqlId ?? null, }, }; return platform.fetchFromApi(request); } async #actionQuery(): Promise { if (!this.#cachedActionQuery) { const platform = await this.#currentPlatform(); try { const { version } = await platform.fetchFromApi(versionRequest); this.#cachedActionQuery = ifVersionGte( version, MINIMUM_PLATFORM_ORIGIN_FIELD_VERSION, () => CHAT_INPUT_TEMPLATE_17_3_AND_LATER, () => CHAT_INPUT_TEMPLATE_17_2_AND_EARLIER, ); } catch (e) { log.debug(`GitLab version check for sending chat failed:`, e as Error); this.#cachedActionQuery = CHAT_INPUT_TEMPLATE_17_3_AND_LATER; } } return this.#cachedActionQuery; } } References:" You are a code assistant,Definition of 'AImpl' in file packages/lib_di/src/index.test.ts in project gitlab-lsp,"Definition: class AImpl implements A { a = () => 'a'; } @Injectable(B, [A]) class BImpl implements B { #a: A; constructor(a: A) { this.#a = a; } b = () => `B(${this.#a.a()})`; } @Injectable(C, [A, B]) class CImpl implements C { #a: A; #b: B; constructor(a: A, b: B) { this.#a = a; this.#b = b; } c = () => `C(${this.#b.b()}, ${this.#a.a()})`; } let container: Container; beforeEach(() => { container = new Container(); }); describe('addInstances', () => { const O = createInterfaceId('object'); it('fails if the instance is not branded', () => { expect(() => container.addInstances({ say: 'hello' } as BrandedInstance)).toThrow( /invoked without branded object/, ); }); it('fails if the instance is already present', () => { const a = brandInstance(O, { a: 'a' }); const b = brandInstance(O, { b: 'b' }); expect(() => container.addInstances(a, b)).toThrow(/this ID is already in the container/); }); it('adds instance', () => { const instance = { a: 'a' }; const a = brandInstance(O, instance); container.addInstances(a); expect(container.get(O)).toBe(instance); }); }); describe('instantiate', () => { it('can instantiate three classes A,B,C', () => { container.instantiate(AImpl, BImpl, CImpl); const cInstance = container.get(C); expect(cInstance.c()).toBe('C(B(a), a)'); }); it('instantiates dependencies in multiple instantiate calls', () => { container.instantiate(AImpl); // the order is important for this test // we want to make sure that the stack in circular dependency discovery is being cleared // to try why this order is necessary, remove the `inStack.delete()` from // the `if (!cwd && instanceIds.includes(id))` condition in prod code expect(() => container.instantiate(CImpl, BImpl)).not.toThrow(); }); it('detects duplicate ids', () => { @Injectable(A, []) 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: - packages/lib_di/src/index.test.ts:109 - packages/lib_di/src/index.test.ts:122" You are a code assistant,Definition of 'MessageBus' in file packages/lib_message_bus/src/types/bus.ts in project gitlab-lsp,"Definition: export interface MessageBus extends NotificationPublisher, NotificationListener, RequestPublisher, RequestListener {} References: - packages/webview_duo_workflow/src/plugin/index.ts:9 - packages/lib_webview_client/src/bus/provider/host_application_message_bus_provider.test.ts:4 - src/common/graphql/workflow/service.ts:45 - src/common/graphql/workflow/service.test.ts:17" You are a code assistant,Definition of 'destroy' in file src/common/fetch.ts in project gitlab-lsp,"Definition: destroy(): Promise; fetch(input: RequestInfo | URL, init?: RequestInit): Promise; fetchBase(input: RequestInfo | URL, init?: RequestInit): Promise; delete(input: RequestInfo | URL, init?: RequestInit): Promise; get(input: RequestInfo | URL, init?: RequestInit): Promise; post(input: RequestInfo | URL, init?: RequestInit): Promise; put(input: RequestInfo | URL, init?: RequestInit): Promise; updateAgentOptions(options: FetchAgentOptions): void; streamFetch(url: string, body: string, headers: FetchHeaders): AsyncGenerator; } export const LsFetch = createInterfaceId('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 {} async destroy(): Promise {} async fetch(input: RequestInfo | URL, init?: RequestInit): Promise { 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 { // Stub. Should delegate to the node or browser fetch implementations throw new Error('Not implemented'); yield ''; } async delete(input: RequestInfo | URL, init?: RequestInit): Promise { return this.fetch(input, this.updateRequestInit('DELETE', init)); } async get(input: RequestInfo | URL, init?: RequestInit): Promise { return this.fetch(input, this.updateRequestInit('GET', init)); } async post(input: RequestInfo | URL, init?: RequestInit): Promise { return this.fetch(input, this.updateRequestInit('POST', init)); } async put(input: RequestInfo | URL, init?: RequestInit): Promise { return this.fetch(input, this.updateRequestInit('PUT', init)); } async fetchBase(input: RequestInfo | URL, init?: RequestInit): Promise { // 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 'CommentResolver' in file src/common/tree_sitter/comments/comment_resolver.ts in project gitlab-lsp,"Definition: export class CommentResolver { protected queryByLanguage: Map; constructor() { this.queryByLanguage = new Map(); } #getQueryByLanguage( language: TreeSitterLanguageName, treeSitterLanguage: Language, ): Query | undefined { const query = this.queryByLanguage.get(language); if (query) { return query; } const queryString = commentQueries[language]; if (!queryString) { log.warn(`No comment query found for language: ${language}`); return undefined; } const newQuery = treeSitterLanguage.query(queryString); this.queryByLanguage.set(language, newQuery); return newQuery; } /** * Returns the comment that is on or directly above the cursor, if it exists. * To handle the case the comment may be several new lines above the cursor, * we traverse the tree to check if any nodes are between the comment and the cursor. */ getCommentForCursor({ languageName, tree, cursorPosition, treeSitterLanguage, }: { languageName: TreeSitterLanguageName; tree: Tree; treeSitterLanguage: Language; cursorPosition: Point; }): CommentResolution | undefined { const query = this.#getQueryByLanguage(languageName, treeSitterLanguage); if (!query) { return undefined; } const comments = query.captures(tree.rootNode).map((capture) => { return { start: capture.node.startPosition, end: capture.node.endPosition, content: capture.node.text, capture, }; }); const commentAtCursor = CommentResolver.#getCommentAtCursor(comments, cursorPosition); if (commentAtCursor) { // No need to further check for isPositionInNode etc. as cursor is directly on the comment return { commentAtCursor }; } const commentAboveCursor = CommentResolver.#getCommentAboveCursor(comments, cursorPosition); if (!commentAboveCursor) { return undefined; } const commentParentNode = commentAboveCursor.capture.node.parent; if (!commentParentNode) { return undefined; } if (!CommentResolver.#isPositionInNode(cursorPosition, commentParentNode)) { return undefined; } const directChildren = commentParentNode.children; for (const child of directChildren) { const hasNodeBetweenCursorAndComment = child.startPosition.row > commentAboveCursor.capture.node.endPosition.row && child.startPosition.row <= cursorPosition.row; if (hasNodeBetweenCursorAndComment) { return undefined; } } return { commentAboveCursor }; } static #isPositionInNode(position: Point, node: SyntaxNode): boolean { return position.row >= node.startPosition.row && position.row <= node.endPosition.row; } static #getCommentAboveCursor(comments: Comment[], cursorPosition: Point): Comment | undefined { return CommentResolver.#getLastComment( comments.filter((comment) => comment.end.row < cursorPosition.row), ); } static #getCommentAtCursor(comments: Comment[], cursorPosition: Point): Comment | undefined { return CommentResolver.#getLastComment( comments.filter( (comment) => comment.start.row <= cursorPosition.row && comment.end.row >= cursorPosition.row, ), ); } static #getLastComment(comments: Comment[]): Comment | undefined { return comments.sort((a, b) => b.end.row - a.end.row)[0]; } /** * Returns the total number of lines that are comments in a parsed syntax tree. * Uses a Set because we only want to count each line once. * @param {Object} params - Parameters for counting comment lines. * @param {TreeSitterLanguageName} params.languageName - The name of the programming language. * @param {Tree} params.tree - The syntax tree to analyze. * @param {Language} params.treeSitterLanguage - The Tree-sitter language instance. * @returns {number} - The total number of unique lines containing comments. */ getTotalCommentLines({ treeSitterLanguage, languageName, tree, }: { languageName: TreeSitterLanguageName; treeSitterLanguage: Language; tree: Tree; }): number { const query = this.#getQueryByLanguage(languageName, treeSitterLanguage); const captures = query ? query.captures(tree.rootNode) : []; // Note: in future, we could potentially re-use captures from getCommentForCursor() const commentLineSet = new Set(); // A Set is used to only count each line once (the same comment can span multiple lines) captures.forEach((capture) => { const { startPosition, endPosition } = capture.node; for (let { row } = startPosition; row <= endPosition.row; row++) { commentLineSet.add(row); } }); return commentLineSet.size; } static isCommentEmpty(comment: Comment): boolean { const trimmedContent = comment.content.trim().replace(/[\n\r\\]/g, ' '); // Count the number of alphanumeric characters in the trimmed content const alphanumericCount = (trimmedContent.match(/[a-zA-Z0-9]/g) || []).length; return alphanumericCount <= 2; } } let commentResolver: CommentResolver; export function getCommentResolver(): CommentResolver { if (!commentResolver) { commentResolver = new CommentResolver(); } return commentResolver; } References: - src/common/tree_sitter/comments/comment_resolver.ts:172 - src/common/tree_sitter/comments/comment_resolver.ts:169 - src/common/tree_sitter/comments/comment_resolver.ts:170 - src/common/tree_sitter/comments/comment_resolver.test.ts:15 - src/common/tree_sitter/comments/comment_resolver.test.ts:9" You are a code assistant,Definition of 'updateSuggestionState' in file src/common/tracking/instance_tracker.ts in project gitlab-lsp,"Definition: updateSuggestionState(uniqueTrackingId: string, newState: TRACKING_EVENTS): void { if (this.#circuitBreaker.isOpen()) { return; } if (!this.isEnabled()) return; if (this.#isStreamingSuggestion(uniqueTrackingId)) return; const state = this.#codeSuggestionStates.get(uniqueTrackingId); if (!state) { log.debug(`Instance telemetry: The suggestion with ${uniqueTrackingId} can't be found`); return; } const allowedTransitions = nonStreamingSuggestionStateGraph.get(state); if (!allowedTransitions) { log.debug( `Instance telemetry: The suggestion's ${uniqueTrackingId} state ${state} can't be found in state graph`, ); return; } if (!allowedTransitions.includes(newState)) { log.debug( `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( `Instance telemetry: Conditionally allowing transition to accepted state for ${uniqueTrackingId}`, ); } this.#codeSuggestionStates.set(uniqueTrackingId, newState); this.#trackCodeSuggestionsEvent(newState, uniqueTrackingId).catch((e) => log.warn('Instance telemetry: Could not track telemetry', e), ); log.debug(`Instance telemetry: ${uniqueTrackingId} transisted from ${state} to ${newState}`); } async #trackCodeSuggestionsEvent(eventType: TRACKING_EVENTS, uniqueTrackingId: string) { const event = INSTANCE_TRACKING_EVENTS_MAP[eventType]; if (!event) { return; } try { const { language, suggestion_size } = this.#codeSuggestionsContextMap.get(uniqueTrackingId) ?? {}; await this.#api.fetchFromApi({ type: 'rest', method: 'POST', path: '/usage_data/track_event', body: { event, additional_properties: { unique_tracking_id: uniqueTrackingId, timestamp: new Date().toISOString(), language, suggestion_size, }, }, supportedSinceInstanceVersion: { resourceName: 'track instance telemetry', version: '17.2.0', }, }); this.#circuitBreaker.success(); } catch (error) { if (error instanceof InvalidInstanceVersionError) { if (this.#invalidInstanceMsgLogged) return; this.#invalidInstanceMsgLogged = true; } log.warn(`Instance telemetry: Failed to track event: ${eventType}`, error); this.#circuitBreaker.error(); } } rejectOpenedSuggestions() { log.debug(`Instance Telemetry: Reject all opened suggestions`); this.#codeSuggestionStates.forEach((state, uniqueTrackingId) => { if (endStates.includes(state)) { return; } this.updateSuggestionState(uniqueTrackingId, TRACKING_EVENTS.REJECTED); }); } static #suggestionSize(options: SuggestionOption[]): number { const countLines = (text: string) => (text ? text.split('\n').length : 0); return Math.max(...options.map(({ text }) => countLines(text))); } #isStreamingSuggestion(uniqueTrackingId: string): boolean { return Boolean(this.#codeSuggestionsContextMap.get(uniqueTrackingId)?.is_streaming); } } References:" You are a code assistant,Definition of 'ChatAvailableResponseType' in file packages/webview_duo_chat/src/plugin/port/chat/api/get_chat_support.ts in project gitlab-lsp,"Definition: export type ChatAvailableResponseType = { currentUser: { duoChatAvailable: boolean; }; }; export async function getChatSupport( platform?: GitLabPlatformForAccount | undefined, ): Promise { const request: GraphQLRequest = { type: 'graphql', query: queryGetChatAvailability, variables: {}, }; const noSupportResponse: ChatSupportResponseInterface = { hasSupportForChat: false }; if (!platform) { return noSupportResponse; } try { const { currentUser: { duoChatAvailable }, } = await platform.fetchFromApi(request); if (duoChatAvailable) { return { hasSupportForChat: duoChatAvailable, platform, }; } return noSupportResponse; } catch (e) { log.error(e as Error); return noSupportResponse; } } References: - packages/webview_duo_chat/src/plugin/port/chat/api/get_chat_support.test.ts:11" You are a code assistant,Definition of 'findFilesForDirectory' in file src/node/services/fs/dir.ts in project gitlab-lsp,"Definition: async findFilesForDirectory(args: DirectoryToSearch): Promise { const { filters, directoryUri } = args; const perf = performance.now(); const pathMap = new Map(); const promise = new FastDirectoryCrawler() .withFullPaths() .filter((path) => { const fileUri = fsPathToUri(path); // save each normalized filesystem path avoid re-parsing the path pathMap.set(path, fileUri); return this.#applyFilters(fileUri.path, filters); }) .crawl(fsPathFromUri(directoryUri)) .withPromise(); const paths = await promise; log.debug( `DirectoryWalker: found ${paths.length} paths, took ${Math.round(performance.now() - perf)}ms`, ); return paths.map((path) => pathMap.get(path) as URI); } setupFileWatcher(workspaceFolder: WorkspaceFolder, fileChangeHandler: FileChangeHandler): void { const fsPath = fsPathFromUri(workspaceFolder.uri); const watcher = chokidar.watch(fsPath, { persistent: true, alwaysStat: false, ignoreInitial: true, }); watcher .on('add', (path) => fileChangeHandler('add', workspaceFolder, path)) .on('change', (path) => fileChangeHandler('change', workspaceFolder, path)) .on('unlink', (path) => fileChangeHandler('unlink', workspaceFolder, path)); this.#watchers.set(workspaceFolder.uri, watcher); } async dispose(): Promise { 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 'prettyJson' in file src/common/utils/json.ts in project gitlab-lsp,"Definition: export const prettyJson = ( obj: Record | unknown[], space: string | number = 2, ): string => JSON.stringify(obj, null, space); References: - src/common/log.ts:33" You are a code assistant,Definition of 'constructor' in file src/common/ai_context_management_2/policies/duo_project_policy.ts in project gitlab-lsp,"Definition: constructor(private duoProjectAccessChecker: DuoProjectAccessChecker) {} 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 'GitConfig' in file src/common/services/duo_access/project_access_cache.ts in project gitlab-lsp,"Definition: interface GitConfig { [section: string]: { [key: string]: string }; } type GitlabRemoteAndFileUri = GitLabRemote & { fileUri: string }; export interface GqlProjectWithDuoEnabledInfo { duoFeaturesEnabled: boolean; } export interface DuoProjectAccessCache { getProjectsForWorkspaceFolder(workspaceFolder: WorkspaceFolder): DuoProject[]; updateCache({ baseUrl, workspaceFolders, }: { baseUrl: string; workspaceFolders: WorkspaceFolder[]; }): Promise; onDuoProjectCacheUpdate(listener: () => void): Disposable; } export const DuoProjectAccessCache = createInterfaceId('DuoProjectAccessCache'); @Injectable(DuoProjectAccessCache, [DirectoryWalker, FileResolver, GitLabApiClient]) export class DefaultDuoProjectAccessCache { #duoProjects: Map; #eventEmitter = new EventEmitter(); constructor( private readonly directoryWalker: DirectoryWalker, private readonly fileResolver: FileResolver, private readonly api: GitLabApiClient, ) { this.#duoProjects = new Map(); } getProjectsForWorkspaceFolder(workspaceFolder: WorkspaceFolder): DuoProject[] { return this.#duoProjects.get(workspaceFolder.uri) ?? []; } async updateCache({ baseUrl, workspaceFolders, }: { baseUrl: string; workspaceFolders: WorkspaceFolder[]; }) { try { this.#duoProjects.clear(); const duoProjects = await Promise.all( workspaceFolders.map(async (workspaceFolder) => { return { workspaceFolder, projects: await this.#duoProjectsForWorkspaceFolder({ workspaceFolder, baseUrl, }), }; }), ); for (const { workspaceFolder, projects } of duoProjects) { this.#logProjectsInfo(projects, workspaceFolder); this.#duoProjects.set(workspaceFolder.uri, projects); } this.#triggerChange(); } catch (err) { log.error('DuoProjectAccessCache: failed to update project access cache', err); } } #logProjectsInfo(projects: DuoProject[], workspaceFolder: WorkspaceFolder) { if (!projects.length) { log.warn( `DuoProjectAccessCache: no projects found for workspace folder ${workspaceFolder.uri}`, ); return; } log.debug( `DuoProjectAccessCache: found ${projects.length} projects for workspace folder ${workspaceFolder.uri}: ${JSON.stringify(projects, null, 2)}`, ); } async #duoProjectsForWorkspaceFolder({ workspaceFolder, baseUrl, }: { workspaceFolder: WorkspaceFolder; baseUrl: string; }): Promise { const remotes = await this.#gitlabRemotesForWorkspaceFolder(workspaceFolder, baseUrl); const projects = await Promise.all( remotes.map(async (remote) => { const enabled = await this.#checkDuoFeaturesEnabled(remote.namespaceWithPath); return { projectPath: remote.projectPath, uri: remote.fileUri, enabled, host: remote.host, namespace: remote.namespace, namespaceWithPath: remote.namespaceWithPath, } satisfies DuoProject; }), ); return projects; } async #gitlabRemotesForWorkspaceFolder( workspaceFolder: WorkspaceFolder, baseUrl: string, ): Promise { const paths = await this.directoryWalker.findFilesForDirectory({ directoryUri: workspaceFolder.uri, filters: { fileEndsWith: ['/.git/config'], }, }); const remotes = await Promise.all( paths.map(async (fileUri) => this.#gitlabRemotesForFileUri(fileUri.toString(), baseUrl)), ); return remotes.flat(); } async #gitlabRemotesForFileUri( fileUri: string, baseUrl: string, ): Promise { const remoteUrls = await this.#remoteUrlsFromGitConfig(fileUri); return remoteUrls.reduce((acc, remoteUrl) => { const remote = parseGitLabRemote(remoteUrl, baseUrl); if (remote) { acc.push({ ...remote, fileUri }); } return acc; }, []); } async #remoteUrlsFromGitConfig(fileUri: string): Promise { try { const fileString = await this.fileResolver.readFile({ fileUri }); const config = ini.parse(fileString); return this.#getRemoteUrls(config); } catch (error) { log.error(`DuoProjectAccessCache: Failed to read git config file: ${fileUri}`, error); return []; } } #getRemoteUrls(config: GitConfig): string[] { return Object.keys(config).reduce((acc, section) => { if (section.startsWith('remote ')) { acc.push(config[section].url); } return acc; }, []); } async #checkDuoFeaturesEnabled(projectPath: string): Promise { try { const response = await this.api.fetchFromApi<{ project: GqlProjectWithDuoEnabledInfo }>({ type: 'graphql', query: duoFeaturesEnabledQuery, variables: { projectPath, }, } satisfies ApiRequest<{ project: GqlProjectWithDuoEnabledInfo }>); return Boolean(response?.project?.duoFeaturesEnabled); } catch (error) { log.error( `DuoProjectAccessCache: Failed to check if Duo features are enabled for project: ${projectPath}`, error, ); return true; } } onDuoProjectCacheUpdate( listener: (duoProjectsCache: Map) => void, ): Disposable { this.#eventEmitter.on(DUO_PROJECT_CACHE_UPDATE_EVENT, listener); return { dispose: () => this.#eventEmitter.removeListener(DUO_PROJECT_CACHE_UPDATE_EVENT, listener), }; } #triggerChange() { this.#eventEmitter.emit(DUO_PROJECT_CACHE_UPDATE_EVENT, this.#duoProjects); } } References: - src/common/services/duo_access/project_access_cache.ts:210" You are a code assistant,Definition of 'ApiRequest' in file src/common/api_types.ts in project gitlab-lsp,"Definition: export type ApiRequest<_TReturnType> = | GetRequest<_TReturnType> | PostRequest<_TReturnType> | GraphQLRequest<_TReturnType>; export type AdditionalContext = { /** * The type of the context element. Options: `file` or `snippet`. */ type: 'file' | 'snippet'; /** * The name of the context element. A name of the file or a code snippet. */ name: string; /** * The content of the context element. The body of the file or a function. */ content: string; /** * Where the context was derived from */ resolution_strategy: ContextResolution['strategy']; }; // FIXME: Rename to SuggestionOptionText and then rename SuggestionOptionOrStream to SuggestionOption // this refactor can't be done now (2024-05-28) because all the conflicts it would cause with WIP export interface SuggestionOption { index?: number; text: string; uniqueTrackingId: string; lang?: string; } export interface TelemetryRequest { event: string; additional_properties: { unique_tracking_id: string; language?: string; suggestion_size?: number; timestamp: string; }; } References:" You are a code assistant,Definition of 'setCodeSuggestionsContext' in file src/common/tracking/snowplow_tracker.ts in project gitlab-lsp,"Definition: public setCodeSuggestionsContext( uniqueTrackingId: string, context: Partial, ) { 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, ) { 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 'transform' in file packages/lib_vite_common_config/vite.config.shared.ts in project gitlab-lsp,"Definition: transform(code, id) { if (id.endsWith('@gitlab/svgs/dist/icons.svg')) { svgSpriteContent = fs.readFileSync(id, 'utf-8'); return 'export default """"'; } if (id.match(/@gitlab\/svgs\/dist\/illustrations\/.*\.svg$/)) { const base64Data = imageToBase64(id); return `export default ""data:image/svg+xml;base64,${base64Data}""`; } return code; }, }; export function createViteConfigForWebview(name): UserConfig { const outDir = path.resolve(__dirname, `../../../../out/webviews/${name}`); return { plugins: [vue2(), InlineSvgPlugin, SyncLoadScriptsPlugin, HtmlTransformPlugin], resolve: { alias: { '@': fileURLToPath(new URL('./src/app', import.meta.url)), }, }, root: './src/app', base: '', build: { target: 'es2022', emptyOutDir: true, outDir, rollupOptions: { input: [path.join('src', 'app', 'index.html')], }, }, }; } References:" You are a code assistant,Definition of 'TELEMETRY_NOTIFICATION' in file src/common/tracking/constants.ts in project gitlab-lsp,"Definition: 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 'DEFAULT_TRACKING_ENDPOINT' in file src/common/tracking/constants.ts in project gitlab-lsp,"Definition: 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 'IConfig' in file src/common/config_service.ts in project gitlab-lsp,"Definition: export interface IConfig { // TODO: we can possibly remove this extra level of config and move all IClientConfig properties to IConfig client: IClientConfig; } /** * ConfigService manages user configuration (e.g. baseUrl) and application state (e.g. codeCompletion.enabled) * TODO: Maybe in the future we would like to separate these two */ export interface ConfigService { get: TypedGetter; /** * set sets the property of the config * the new value completely overrides the old one */ set: TypedSetter; onConfigChange(listener: (config: IConfig) => void): Disposable; /** * merge adds `newConfig` properties into existing config, if the * property is present in both old and new config, `newConfig` * properties take precedence unless not defined * * This method performs deep merge * * **Arrays are not merged; they are replaced with the new value.** * */ merge(newConfig: Partial): void; } export const ConfigService = createInterfaceId('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 = (key?: string) => { return key ? get(this.#config, key) : this.#config; }; set: TypedSetter = (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) { mergeWith(this.#config, newConfig, (target, src) => (isArray(target) ? src : undefined)); this.#triggerChange(); } } References: - src/common/config_service.ts:112 - src/node/duo_workflow/desktop_workflow_runner.ts:59 - src/common/tracking/instance_tracker.ts:57 - src/common/config_service.ts:94 - src/common/security_diagnostics_publisher.ts:46 - src/common/config_service.ts:142 - src/common/tracking/snowplow_tracker.ts:187" You are a code assistant,Definition of 'rejectOpenedSuggestions' in file src/common/tracking/multi_tracker.ts in project gitlab-lsp,"Definition: rejectOpenedSuggestions() { this.#enabledTrackers.forEach((t) => t.rejectOpenedSuggestions()); } } References:" You are a code assistant,Definition of 'loadStateValue' in file src/common/tree_sitter/parser.ts in project gitlab-lsp,"Definition: get loadStateValue(): TreeSitterParserLoadState { return this.loadState; } async parseFile(context: IDocContext): Promise { 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 { 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 { 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 { return languages.reduce((map, language) => { for (const extension of language.extensions) { map.set(extension, language); } return map; }, new Map()); } } References:" You are a code assistant,Definition of 'instanceVersion' in file src/common/api.ts in project gitlab-lsp,"Definition: get instanceVersion() { return this.#instanceVersion; } } References:" You are a code assistant,Definition of 'constructor' in file packages/lib_handler_registry/src/errors/handler_not_found_error.ts in project gitlab-lsp,"Definition: constructor(key: string) { const message = `Handler not found for key ${key}`; super(message); } } References:" You are a code assistant,Definition of 'WEB_IDE_EXTENSION_ID' in file packages/webview_duo_chat/src/plugin/port/platform/web_ide.ts in project gitlab-lsp,"Definition: export const WEB_IDE_EXTENSION_ID = 'gitlab.gitlab-web-ide'; export const WEB_IDE_AUTH_PROVIDER_ID = 'gitlab-web-ide'; export const WEB_IDE_AUTH_SCOPE = 'api'; // region: Mediator commands ------------------------------------------- export const COMMAND_FETCH_FROM_API = `gitlab-web-ide.mediator.fetch-from-api`; export const COMMAND_FETCH_BUFFER_FROM_API = `gitlab-web-ide.mediator.fetch-buffer-from-api`; export const COMMAND_MEDIATOR_TOKEN = `gitlab-web-ide.mediator.mediator-token`; 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; } /** * 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; headers?: Record; } export interface GetRequest<_TReturnType> extends GetRequestBase<_TReturnType> { type: 'rest'; } export interface GetBufferRequest extends GetRequestBase { type: 'rest-buffer'; } export interface GraphQLRequest<_TReturnType> { type: 'graphql'; query: string; /** Options passed to the GraphQL query */ variables: Record; } 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; /* 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 'GitLabProject' in file packages/webview_duo_chat/src/plugin/port/platform/gitlab_project.ts in project gitlab-lsp,"Definition: export interface GitLabProject { gqlId: string; restId: number; name: string; description: string; namespaceWithPath: string; webUrl: string; // TODO: This is used only in one spot, probably a good idea to remove it from this main class groupRestId?: number; } References: - packages/webview_duo_chat/src/plugin/chat_platform.ts:47 - packages/webview_duo_chat/src/plugin/port/platform/gitlab_platform.ts:28" You are a code assistant,Definition of 'constructor' in file src/common/advanced_context/lru_cache.ts in project gitlab-lsp,"Definition: private constructor(maxSize: number) { this.#cache = new LRUCache({ maxSize, sizeCalculation: (value) => this.#getDocumentSize(value), }); } public static getInstance(maxSize: number): LruCache { if (!LruCache.#instance) { log.debug('LruCache: initializing'); LruCache.#instance = new LruCache(maxSize); } return LruCache.#instance; } public static destroyInstance(): void { LruCache.#instance = undefined; } get openFiles() { return this.#cache; } #getDocumentSize(context: IDocContext): number { const size = getByteSize(`${context.prefix}${context.suffix}`); return Math.max(1, size); } /** * Update the file in the cache. * Uses lru-cache under the hood. */ updateFile(context: IDocContext) { return this.#cache.set(context.uri, context); } /** * @returns `true` if the file was deleted, `false` if the file was not found */ deleteFile(uri: DocumentUri): boolean { return this.#cache.delete(uri); } /** * Get the most recently accessed files in the workspace * @param context - The current document context `IDocContext` * @param includeCurrentFile - Include the current file in the list of most recent files, default is `true` */ mostRecentFiles({ context, includeCurrentFile = true, }: { context?: IDocContext; includeCurrentFile?: boolean; }): IDocContext[] { const files = Array.from(this.#cache.values()); if (includeCurrentFile) { return files; } return files.filter( (file) => context?.workspaceFolder?.uri === file.workspaceFolder?.uri && file.uri !== context?.uri, ); } } References:" You are a code assistant,Definition of 'WithConstructor' in file packages/lib_di/src/index.ts in project gitlab-lsp,"Definition: type WithConstructor = { new (...args: any[]): any; name: string }; type ClassWithDependencies = { cls: WithConstructor; id: string; dependencies: string[] }; type Validator = (cwds: ClassWithDependencies[], instanceIds: string[]) => void; const sanitizeId = (idWithRandom: string) => idWithRandom.replace(/-[^-]+$/, ''); /** ensures that only one interface ID implementation is present */ const interfaceUsedOnlyOnce: Validator = (cwds, instanceIds) => { const clashingWithExistingInstance = cwds.filter((cwd) => instanceIds.includes(cwd.id)); if (clashingWithExistingInstance.length > 0) { throw new Error( `The following classes are clashing (have duplicate ID) with instances already present in the container: ${clashingWithExistingInstance.map((cwd) => cwd.cls.name)}`, ); } const groupedById = groupBy(cwds, (cwd) => cwd.id); if (Object.values(groupedById).every((groupedCwds) => groupedCwds.length === 1)) { return; } const messages = Object.entries(groupedById).map( ([id, groupedCwds]) => `'${sanitizeId(id)}' (classes: ${groupedCwds.map((cwd) => cwd.cls.name).join(',')})`, ); throw new Error(`The following interface IDs were used multiple times ${messages.join(',')}`); }; /** throws an error if any class depends on an interface that is not available */ const dependenciesArePresent: Validator = (cwds, instanceIds) => { const allIds = new Set([...cwds.map((cwd) => cwd.id), ...instanceIds]); const cwsWithUnmetDeps = cwds.filter((cwd) => !cwd.dependencies.every((d) => allIds.has(d))); if (cwsWithUnmetDeps.length === 0) { return; } const messages = cwsWithUnmetDeps.map((cwd) => { const unmetDeps = cwd.dependencies.filter((d) => !allIds.has(d)).map(sanitizeId); return `Class ${cwd.cls.name} (interface ${sanitizeId(cwd.id)}) depends on interfaces [${unmetDeps}] that weren't added to the init method.`; }); throw new Error(messages.join('\n')); }; /** uses depth first search to find out if the classes have circular dependency */ const noCircularDependencies: Validator = (cwds, instanceIds) => { const inStack = new Set(); const hasCircularDependency = (id: string): boolean => { if (inStack.has(id)) { return true; } inStack.add(id); const cwd = cwds.find((c) => c.id === id); // we reference existing instance, there won't be circular dependency past this one because instances don't have any dependencies if (!cwd && instanceIds.includes(id)) { inStack.delete(id); return false; } if (!cwd) throw new Error(`assertion error: dependency ID missing ${sanitizeId(id)}`); for (const dependencyId of cwd.dependencies) { if (hasCircularDependency(dependencyId)) { return true; } } inStack.delete(id); return false; }; for (const cwd of cwds) { if (hasCircularDependency(cwd.id)) { throw new Error( `Circular dependency detected between interfaces (${Array.from(inStack).map(sanitizeId)}), starting with '${sanitizeId(cwd.id)}' (class: ${cwd.cls.name}).`, ); } } }; /** * Topological sort of the dependencies - returns array of classes. The classes should be initialized in order given by the array. * https://en.wikipedia.org/wiki/Topological_sorting */ const sortDependencies = (classes: Map): ClassWithDependencies[] => { const visited = new Set(); const sortedClasses: ClassWithDependencies[] = []; const topologicalSort = (interfaceId: string) => { if (visited.has(interfaceId)) { return; } visited.add(interfaceId); const cwd = classes.get(interfaceId); if (!cwd) { // the instance for this ID is already initiated return; } for (const d of cwd.dependencies || []) { topologicalSort(d); } sortedClasses.push(cwd); }; for (const id of classes.keys()) { topologicalSort(id); } return sortedClasses; }; /** * Helper type used by the brandInstance function to ensure that all container.addInstances parameters are branded */ export type BrandedInstance = T; /** * use brandInstance to be able to pass this instance to the container.addInstances method */ export const brandInstance = ( id: InterfaceId, instance: T, ): BrandedInstance => { injectableMetadata.set(instance, { id, dependencies: [] }); return instance; }; /** * Container is responsible for initializing a dependency tree. * * It receives a list of classes decorated with the `@Injectable` decorator * and it constructs instances of these classes in an order that ensures class' dependencies * are initialized before the class itself. * * check https://gitlab.com/viktomas/needle for full documentation of this mini-framework */ export class Container { #instances = new Map(); /** * addInstances allows you to add pre-initialized objects to the container. * This is useful when you want to keep mandatory parameters in class' constructor (e.g. some runtime objects like server connection). * addInstances accepts a list of any objects that have been ""branded"" by the `brandInstance` method */ addInstances(...instances: BrandedInstance[]) { for (const instance of instances) { const metadata = injectableMetadata.get(instance); if (!metadata) { throw new Error( 'assertion error: addInstance invoked without branded object, make sure all arguments are branded with `brandInstance`', ); } if (this.#instances.has(metadata.id)) { throw new Error( `you are trying to add instance for interfaceId ${metadata.id}, but instance with this ID is already in the container.`, ); } this.#instances.set(metadata.id, instance); } } /** * instantiate accepts list of classes, validates that they can be managed by the container * and then initialized them in such order that dependencies of a class are initialized before the class */ instantiate(...classes: WithConstructor[]) { // ensure all classes have been decorated with @Injectable const undecorated = classes.filter((c) => !injectableMetadata.has(c)).map((c) => c.name); if (undecorated.length) { throw new Error(`Classes [${undecorated}] are not decorated with @Injectable.`); } const classesWithDeps: ClassWithDependencies[] = classes.map((cls) => { // we verified just above that all classes are present in the metadata map // eslint-disable-next-line @typescript-eslint/no-non-null-assertion const { id, dependencies } = injectableMetadata.get(cls)!; return { cls, id, dependencies }; }); const validators: Validator[] = [ interfaceUsedOnlyOnce, dependenciesArePresent, noCircularDependencies, ]; validators.forEach((v) => v(classesWithDeps, Array.from(this.#instances.keys()))); const classesById = new Map(); // Index classes by their interface id classesWithDeps.forEach((cwd) => { classesById.set(cwd.id, cwd); }); // Create instances in topological order for (const cwd of sortDependencies(classesById)) { const args = cwd.dependencies.map((dependencyId) => this.#instances.get(dependencyId)); // eslint-disable-next-line new-cap const instance = new cwd.cls(...args); this.#instances.set(cwd.id, instance); } } get(id: InterfaceId): T { const instance = this.#instances.get(id); if (!instance) { throw new Error(`Instance for interface '${sanitizeId(id)}' is not in the container.`); } return instance as T; } } References: - packages/lib_di/src/index.ts:70" You are a code assistant,Definition of 'transformIndexHtml' in file packages/lib_vite_common_config/vite.config.shared.ts in project gitlab-lsp,"Definition: transformIndexHtml(html) { return html.replace('{{ svg placeholder }}', svgSpriteContent); }, }; export const InlineSvgPlugin = { name: 'inline-svg', transform(code, id) { if (id.endsWith('@gitlab/svgs/dist/icons.svg')) { svgSpriteContent = fs.readFileSync(id, 'utf-8'); return 'export default """"'; } if (id.match(/@gitlab\/svgs\/dist\/illustrations\/.*\.svg$/)) { const base64Data = imageToBase64(id); return `export default ""data:image/svg+xml;base64,${base64Data}""`; } return code; }, }; export function createViteConfigForWebview(name): UserConfig { const outDir = path.resolve(__dirname, `../../../../out/webviews/${name}`); return { plugins: [vue2(), InlineSvgPlugin, SyncLoadScriptsPlugin, HtmlTransformPlugin], resolve: { alias: { '@': fileURLToPath(new URL('./src/app', import.meta.url)), }, }, root: './src/app', base: '', build: { target: 'es2022', emptyOutDir: true, outDir, rollupOptions: { input: [path.join('src', 'app', 'index.html')], }, }, }; } References:" You are a code assistant,Definition of 'Intent' in file src/common/tree_sitter/intent_resolver.ts in project gitlab-lsp,"Definition: export type Intent = 'completion' | 'generation' | undefined; export type IntentResolution = { intent: Intent; commentForCursor?: Comment; generationType?: GenerationType; }; /** * Determines the user intent based on cursor position and context within the file. * Intent is determined based on several ordered rules: * - Returns 'completion' if the cursor is located on or after an empty comment. * - Returns 'generation' if the cursor is located after a non-empty comment. * - Returns 'generation' if the cursor is not located after a comment and the file is less than 5 lines. * - Returns undefined if neither a comment nor small file is detected. */ export async function getIntent({ treeAndLanguage, position, prefix, suffix, }: { treeAndLanguage: TreeAndLanguage; position: Position; prefix: string; suffix: string; }): Promise { const commentResolver = getCommentResolver(); const emptyFunctionResolver = getEmptyFunctionResolver(); const cursorPosition = { row: position.line, column: position.character }; const { languageInfo, tree, language: treeSitterLanguage } = treeAndLanguage; const commentResolution = commentResolver.getCommentForCursor({ languageName: languageInfo.name, tree, cursorPosition, treeSitterLanguage, }); if (commentResolution) { const { commentAtCursor, commentAboveCursor } = commentResolution; if (commentAtCursor) { log.debug('IntentResolver: Cursor is directly on a comment, sending intent: completion'); return { intent: 'completion' }; } const isCommentEmpty = CommentResolver.isCommentEmpty(commentAboveCursor); if (isCommentEmpty) { log.debug('IntentResolver: Cursor is after an empty comment, sending intent: completion'); return { intent: 'completion' }; } log.debug('IntentResolver: Cursor is after a non-empty comment, sending intent: generation'); return { intent: 'generation', generationType: 'comment', commentForCursor: commentAboveCursor, }; } const textContent = `${prefix}${suffix}`; const totalCommentLines = commentResolver.getTotalCommentLines({ languageName: languageInfo.name, treeSitterLanguage, tree, }); if (isSmallFile(textContent, totalCommentLines)) { log.debug('IntentResolver: Small file detected, sending intent: generation'); return { intent: 'generation', generationType: 'small_file' }; } const isCursorInEmptyFunction = emptyFunctionResolver.isCursorInEmptyFunction({ languageName: languageInfo.name, tree, cursorPosition, treeSitterLanguage, }); if (isCursorInEmptyFunction) { log.debug('IntentResolver: Cursor is in an empty function, sending intent: generation'); return { intent: 'generation', generationType: 'empty_function' }; } log.debug( 'IntentResolver: Cursor is neither at the end of non-empty comment, nor in a small file, nor in empty function - not sending intent.', ); return { intent: undefined }; } References: - src/common/tree_sitter/intent_resolver.ts:12 - src/common/suggestion_client/suggestion_client.ts:21" You are a code assistant,Definition of 'ISnowplowCodeSuggestionContext' in file src/common/tracking/snowplow_tracker.ts in project gitlab-lsp,"Definition: export interface ISnowplowCodeSuggestionContext { schema: string; data: { prefix_length?: number; suffix_length?: number; language?: string | null; gitlab_realm?: GitlabRealm; model_engine?: string | null; model_name?: string | null; api_status_code?: number | null; debounce_interval?: number | null; suggestion_source?: SuggestionSource; gitlab_global_user_id?: string | null; gitlab_instance_id?: string | null; gitlab_host_name?: string | null; gitlab_saas_duo_pro_namespace_ids: number[] | null; gitlab_instance_version: string | null; is_streaming?: boolean; is_invoked?: boolean | null; options_count?: number | null; accepted_option?: number | null; /** * boolean indicating whether the feature is enabled * and we sent context in the request */ has_advanced_context?: boolean | null; /** * boolean indicating whether request is direct to cloud connector */ is_direct_connection?: boolean | null; total_context_size_bytes?: number; content_above_cursor_size_bytes?: number; content_below_cursor_size_bytes?: number; /** * set of final context items sent to AI Gateway */ context_items?: ContextItem[] | null; /** * total tokens used in request to model provider */ input_tokens?: number | null; /** * total output tokens recieved from model provider */ output_tokens?: number | null; /** * total tokens sent as context to AI Gateway */ context_tokens_sent?: number | null; /** * total context tokens used in request to model provider */ context_tokens_used?: number | null; }; } interface ISnowplowClientContext { schema: string; data: { ide_name?: string | null; ide_vendor?: string | null; ide_version?: string | null; extension_name?: string | null; extension_version?: string | null; language_server_version?: string | null; }; } const DEFAULT_SNOWPLOW_OPTIONS = { appId: 'gitlab_ide_extension', timeInterval: 5000, maxItems: 10, }; export const EVENT_VALIDATION_ERROR_MSG = `Telemetry event context is not valid - event won't be tracked.`; 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(); #lsFetch: LsFetch; #featureFlagService: FeatureFlagService; #gitlabRealm: GitlabRealm = GitlabRealm.saas; #codeSuggestionsContextMap = new Map(); 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, ) { 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, ) { 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 'sendDidChangeDocumentInActiveEditor' in file src/tests/int/lsp_client.ts in project gitlab-lsp,"Definition: public async sendDidChangeDocumentInActiveEditor(uri: string): Promise { await this.#connection.sendNotification(DidChangeDocumentInActiveEditor, uri); } public async getWebviewMetadata(): Promise { const result = await this.#connection.sendRequest( '$/gitlab/webview-metadata', ); return result; } } References:" You are a code assistant,Definition of 'PostRequest' in file packages/webview_duo_chat/src/plugin/types.ts in project gitlab-lsp,"Definition: 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; supportedSinceInstanceVersion?: SupportedSinceInstanceVersion; } export type ApiRequest<_TReturnType> = | GetRequest<_TReturnType> | PostRequest<_TReturnType> | GraphQLRequest<_TReturnType>; export interface GitLabApiClient { fetchFromApi(request: ApiRequest): Promise; connectToCable(): Promise; } References:" You are a code assistant,Definition of 'WorkspaceFilesUpdate' in file src/common/services/fs/virtual_file_service.ts in project gitlab-lsp,"Definition: 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 { (eventType: T, data: FileSystemEventMap[T]): void; } export type VirtualFileSystemService = typeof DefaultVirtualFileSystemService.prototype; export const VirtualFileSystemService = createInterfaceId( '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 { 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( 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/git/repository_service.ts:182 - src/common/workspace/workspace_service.ts:46 - src/common/services/fs/virtual_file_service.ts:27 - src/common/git/repository_service.ts:51" You are a code assistant,Definition of 'DefaultDuoProjectAccessChecker' in file src/common/services/duo_access/project_access_checker.ts in project gitlab-lsp,"Definition: export class DefaultDuoProjectAccessChecker { #projectAccessCache: DuoProjectAccessCache; constructor(projectAccessCache: DuoProjectAccessCache) { this.#projectAccessCache = projectAccessCache; } /** * Check if Duo features are enabled for a given DocumentUri. * * We match the DocumentUri to the project with the longest path. * The enabled projects come from the `DuoProjectAccessCache`. * * @reference `DocumentUri` is the URI of the document to check. Comes from * the `TextDocument` object. */ 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: - src/common/services/duo_access/project_access_checker.test.ts:18" You are a code assistant,Definition of 'Metadata' in file packages/lib_di/src/index.ts in project gitlab-lsp,"Definition: interface Metadata { id: string; dependencies: string[]; } /** * Here we store the id and dependencies for all classes decorated with @Injectable */ const injectableMetadata = new WeakMap(); /** * Decorate your class with @Injectable(id, dependencies) * param id = InterfaceId of the interface implemented by your class (use createInterfaceId to create one) * param dependencies = List of InterfaceIds that will be injected into class' constructor */ export function Injectable[]>( id: InterfaceId, dependencies: [...TDependencies], // we can add `| [] = [],` to make dependencies optional, but the type checker messages are quite cryptic when the decorated class has some constructor arguments ) { // this is the trickiest part of the whole DI framework // we say, this decorator takes // - id (the interface that the injectable implements) // - dependencies (list of interface ids that will be injected to constructor) // // With then we return function that ensures that the decorated class implements the id interface // and its constructor has arguments of same type and order as the dependencies argument to the decorator return function ): I }>( constructor: T, { kind }: ClassDecoratorContext, ) { if (kind === 'class') { injectableMetadata.set(constructor, { id, dependencies: dependencies || [] }); return constructor; } throw new Error('Injectable decorator can only be used on a class.'); }; } // new (...args: any[]): any is actually how TS defines type of a class // eslint-disable-next-line @typescript-eslint/no-explicit-any type WithConstructor = { new (...args: any[]): any; name: string }; type ClassWithDependencies = { cls: WithConstructor; id: string; dependencies: string[] }; type Validator = (cwds: ClassWithDependencies[], instanceIds: string[]) => void; const sanitizeId = (idWithRandom: string) => idWithRandom.replace(/-[^-]+$/, ''); /** ensures that only one interface ID implementation is present */ const interfaceUsedOnlyOnce: Validator = (cwds, instanceIds) => { const clashingWithExistingInstance = cwds.filter((cwd) => instanceIds.includes(cwd.id)); if (clashingWithExistingInstance.length > 0) { throw new Error( `The following classes are clashing (have duplicate ID) with instances already present in the container: ${clashingWithExistingInstance.map((cwd) => cwd.cls.name)}`, ); } const groupedById = groupBy(cwds, (cwd) => cwd.id); if (Object.values(groupedById).every((groupedCwds) => groupedCwds.length === 1)) { return; } const messages = Object.entries(groupedById).map( ([id, groupedCwds]) => `'${sanitizeId(id)}' (classes: ${groupedCwds.map((cwd) => cwd.cls.name).join(',')})`, ); throw new Error(`The following interface IDs were used multiple times ${messages.join(',')}`); }; /** throws an error if any class depends on an interface that is not available */ const dependenciesArePresent: Validator = (cwds, instanceIds) => { const allIds = new Set([...cwds.map((cwd) => cwd.id), ...instanceIds]); const cwsWithUnmetDeps = cwds.filter((cwd) => !cwd.dependencies.every((d) => allIds.has(d))); if (cwsWithUnmetDeps.length === 0) { return; } const messages = cwsWithUnmetDeps.map((cwd) => { const unmetDeps = cwd.dependencies.filter((d) => !allIds.has(d)).map(sanitizeId); return `Class ${cwd.cls.name} (interface ${sanitizeId(cwd.id)}) depends on interfaces [${unmetDeps}] that weren't added to the init method.`; }); throw new Error(messages.join('\n')); }; /** uses depth first search to find out if the classes have circular dependency */ const noCircularDependencies: Validator = (cwds, instanceIds) => { const inStack = new Set(); const hasCircularDependency = (id: string): boolean => { if (inStack.has(id)) { return true; } inStack.add(id); const cwd = cwds.find((c) => c.id === id); // we reference existing instance, there won't be circular dependency past this one because instances don't have any dependencies if (!cwd && instanceIds.includes(id)) { inStack.delete(id); return false; } if (!cwd) throw new Error(`assertion error: dependency ID missing ${sanitizeId(id)}`); for (const dependencyId of cwd.dependencies) { if (hasCircularDependency(dependencyId)) { return true; } } inStack.delete(id); return false; }; for (const cwd of cwds) { if (hasCircularDependency(cwd.id)) { throw new Error( `Circular dependency detected between interfaces (${Array.from(inStack).map(sanitizeId)}), starting with '${sanitizeId(cwd.id)}' (class: ${cwd.cls.name}).`, ); } } }; /** * Topological sort of the dependencies - returns array of classes. The classes should be initialized in order given by the array. * https://en.wikipedia.org/wiki/Topological_sorting */ const sortDependencies = (classes: Map): ClassWithDependencies[] => { const visited = new Set(); const sortedClasses: ClassWithDependencies[] = []; const topologicalSort = (interfaceId: string) => { if (visited.has(interfaceId)) { return; } visited.add(interfaceId); const cwd = classes.get(interfaceId); if (!cwd) { // the instance for this ID is already initiated return; } for (const d of cwd.dependencies || []) { topologicalSort(d); } sortedClasses.push(cwd); }; for (const id of classes.keys()) { topologicalSort(id); } return sortedClasses; }; /** * Helper type used by the brandInstance function to ensure that all container.addInstances parameters are branded */ export type BrandedInstance = T; /** * use brandInstance to be able to pass this instance to the container.addInstances method */ export const brandInstance = ( id: InterfaceId, instance: T, ): BrandedInstance => { injectableMetadata.set(instance, { id, dependencies: [] }); return instance; }; /** * Container is responsible for initializing a dependency tree. * * It receives a list of classes decorated with the `@Injectable` decorator * and it constructs instances of these classes in an order that ensures class' dependencies * are initialized before the class itself. * * check https://gitlab.com/viktomas/needle for full documentation of this mini-framework */ export class Container { #instances = new Map(); /** * addInstances allows you to add pre-initialized objects to the container. * This is useful when you want to keep mandatory parameters in class' constructor (e.g. some runtime objects like server connection). * addInstances accepts a list of any objects that have been ""branded"" by the `brandInstance` method */ addInstances(...instances: BrandedInstance[]) { for (const instance of instances) { const metadata = injectableMetadata.get(instance); if (!metadata) { throw new Error( 'assertion error: addInstance invoked without branded object, make sure all arguments are branded with `brandInstance`', ); } if (this.#instances.has(metadata.id)) { throw new Error( `you are trying to add instance for interfaceId ${metadata.id}, but instance with this ID is already in the container.`, ); } this.#instances.set(metadata.id, instance); } } /** * instantiate accepts list of classes, validates that they can be managed by the container * and then initialized them in such order that dependencies of a class are initialized before the class */ instantiate(...classes: WithConstructor[]) { // ensure all classes have been decorated with @Injectable const undecorated = classes.filter((c) => !injectableMetadata.has(c)).map((c) => c.name); if (undecorated.length) { throw new Error(`Classes [${undecorated}] are not decorated with @Injectable.`); } const classesWithDeps: ClassWithDependencies[] = classes.map((cls) => { // we verified just above that all classes are present in the metadata map // eslint-disable-next-line @typescript-eslint/no-non-null-assertion const { id, dependencies } = injectableMetadata.get(cls)!; return { cls, id, dependencies }; }); const validators: Validator[] = [ interfaceUsedOnlyOnce, dependenciesArePresent, noCircularDependencies, ]; validators.forEach((v) => v(classesWithDeps, Array.from(this.#instances.keys()))); const classesById = new Map(); // Index classes by their interface id classesWithDeps.forEach((cwd) => { classesById.set(cwd.id, cwd); }); // Create instances in topological order for (const cwd of sortDependencies(classesById)) { const args = cwd.dependencies.map((dependencyId) => this.#instances.get(dependencyId)); // eslint-disable-next-line new-cap const instance = new cwd.cls(...args); this.#instances.set(cwd.id, instance); } } get(id: InterfaceId): T { const instance = this.#instances.get(id); if (!instance) { throw new Error(`Instance for interface '${sanitizeId(id)}' is not in the container.`); } return instance as T; } } References:" You are a code assistant,Definition of 'ExponentialBackoffCircuitBreaker' in file src/common/circuit_breaker/exponential_backoff_circuit_breaker.ts in project gitlab-lsp,"Definition: export class ExponentialBackoffCircuitBreaker implements CircuitBreaker { #name: string; #state: CircuitBreakerState = CircuitBreakerState.CLOSED; readonly #initialBackoffMs: number; readonly #maxBackoffMs: number; readonly #backoffMultiplier: number; #errorCount = 0; #eventEmitter = new EventEmitter(); #timeoutId: NodeJS.Timeout | null = null; constructor( name: string, { initialBackoffMs = DEFAULT_INITIAL_BACKOFF_MS, maxBackoffMs = DEFAULT_MAX_BACKOFF_MS, backoffMultiplier = DEFAULT_BACKOFF_MULTIPLIER, }: ExponentialBackoffCircuitBreakerOptions = {}, ) { this.#name = name; this.#initialBackoffMs = initialBackoffMs; this.#maxBackoffMs = maxBackoffMs; this.#backoffMultiplier = backoffMultiplier; } error() { this.#errorCount += 1; this.#open(); } megaError() { this.#errorCount += 3; this.#open(); } #open() { if (this.#state === CircuitBreakerState.OPEN) { return; } this.#state = CircuitBreakerState.OPEN; log.warn( `Excess errors detected, opening '${this.#name}' circuit breaker for ${this.#getBackoffTime() / 1000} second(s).`, ); this.#timeoutId = setTimeout(() => this.#close(), this.#getBackoffTime()); this.#eventEmitter.emit('open'); } #close() { if (this.#state === CircuitBreakerState.CLOSED) { return; } if (this.#timeoutId) { clearTimeout(this.#timeoutId); } this.#state = CircuitBreakerState.CLOSED; this.#eventEmitter.emit('close'); } isOpen() { return this.#state === CircuitBreakerState.OPEN; } 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) }; } #getBackoffTime() { return Math.min( this.#initialBackoffMs * this.#backoffMultiplier ** (this.#errorCount - 1), this.#maxBackoffMs, ); } } References: - src/common/circuit_breaker/exponential_backoff_circuit_breaker.test.ts:50 - src/common/circuit_breaker/exponential_backoff_circuit_breaker.test.ts:63 - src/common/suggestion_client/direct_connection_client.ts:36 - src/common/circuit_breaker/exponential_backoff_circuit_breaker.test.ts:80 - src/common/circuit_breaker/exponential_backoff_circuit_breaker.test.ts:92 - src/common/circuit_breaker/exponential_backoff_circuit_breaker.test.ts:35 - src/common/suggestion_client/direct_connection_client.ts:45 - src/common/circuit_breaker/exponential_backoff_circuit_breaker.test.ts:26 - src/common/circuit_breaker/exponential_backoff_circuit_breaker.test.ts:7 - src/common/circuit_breaker/exponential_backoff_circuit_breaker.test.ts:18 - src/common/circuit_breaker/exponential_backoff_circuit_breaker.test.ts:12" You are a code assistant,Definition of 'Transport' in file packages/lib_webview_transport/src/types.ts in project gitlab-lsp,"Definition: export interface Transport extends TransportListener, TransportPublisher {} References: - packages/lib_webview/src/setup/transport/utils/setup_transport_event_handlers.ts:8 - packages/lib_webview/src/setup/transport/utils/setup_event_subscriptions.ts:8 - packages/lib_webview/src/setup/transport/setup_transport.ts:9" You are a code assistant,Definition of 'PostProcessorPipeline' in file src/common/suggestion_client/post_processors/post_processor_pipeline.ts in project gitlab-lsp,"Definition: export class PostProcessorPipeline { #processors: PostProcessor[] = []; addProcessor(processor: PostProcessor): void { this.#processors.push(processor); } async run({ documentContext, input, type, }: { documentContext: IDocContext; input: ProcessorInputMap[T]; type: T; }): Promise { if (!this.#processors.length) return input as ProcessorInputMap[T]; return this.#processors.reduce( async (prevPromise, processor) => { const result = await prevPromise; // eslint-disable-next-line default-case switch (type) { case 'stream': return processor.processStream( documentContext, result as StreamingCompletionResponse, ) as Promise; case 'completion': return processor.processCompletion( documentContext, result as SuggestionOption[], ) as Promise; } throw new Error('Unexpected type in pipeline processing'); }, Promise.resolve(input) as Promise, ); } } References: - src/common/suggestion/streaming_handler.ts:41 - src/common/suggestion_client/post_processors/post_processor_pipeline.test.ts:7 - src/common/suggestion_client/post_processors/post_processor_pipeline.test.ts:11 - src/common/suggestion/suggestion_service.ts:139" You are a code assistant,Definition of 'AdvancedContextResolver' in file src/common/advanced_context/context_resolvers/advanced_context_resolver.ts in project gitlab-lsp,"Definition: export abstract class AdvancedContextResolver { abstract buildContext({ documentContext, }: { documentContext: IDocContext; }): AsyncGenerator; } References:" You are a code assistant,Definition of 'MessageMap' in file packages/lib_message_bus/src/types/bus.ts in project gitlab-lsp,"Definition: export type MessageMap< TInboundMessageDefinitions extends MessageDefinitions = MessageDefinitions, TOutboundMessageDefinitions extends MessageDefinitions = MessageDefinitions, > = { inbound: TInboundMessageDefinitions; outbound: TOutboundMessageDefinitions; }; export interface MessageBus extends NotificationPublisher, NotificationListener, RequestPublisher, RequestListener {} References:" You are a code assistant,Definition of 'getFiles' in file src/common/git/repository.ts in project gitlab-lsp,"Definition: getFiles(): Map { return this.#files; } dispose(): void { this.#ignoreManager.dispose(); this.#files.clear(); } } References:" You are a code assistant,Definition of 'MINIMUM_CODE_SUGGESTIONS_VERSION' in file packages/webview_duo_chat/src/plugin/port/constants.ts in project gitlab-lsp,"Definition: export const MINIMUM_CODE_SUGGESTIONS_VERSION = '16.8.0'; export const DO_NOT_SHOW_VERSION_WARNING = 'DO_NOT_SHOW_VERSION_WARNING'; // NOTE: This needs to _always_ be a 3 digits 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 'SHORT_COMPLETION_CONTEXT' in file src/common/test_utils/mocks.ts in project gitlab-lsp,"Definition: 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 'getMessageBus' in file packages/lib_webview_client/src/bus/provider/host_application_message_bus_provider.ts in project gitlab-lsp,"Definition: getMessageBus(): MessageBus | null { return 'gitlab' in window && isHostConfig(window.gitlab) ? window.gitlab.host : null; } } References:" You are a code assistant,Definition of 'SubmitFeedbackParams' in file packages/webview_duo_chat/src/plugin/port/chat/utils/submit_feedback.ts in project gitlab-lsp,"Definition: export type SubmitFeedbackParams = { extendedTextFeedback: string | null; feedbackChoices: string[] | null; gitlabEnvironment: GitLabEnvironment; }; // eslint-disable-next-line @typescript-eslint/no-unused-vars export const submitFeedback = async (_: SubmitFeedbackParams) => { // const hasFeedback = Boolean(extendedTextFeedback?.length) || Boolean(feedbackChoices?.length); // if (!hasFeedback) { // return; // } // const standardContext = buildStandardContext(extendedTextFeedback, gitlabEnvironment); // const ideExtensionVersion = buildIdeExtensionContext(); // await Snowplow.getInstance().trackStructEvent( // { // category: 'ask_gitlab_chat', // action: 'click_button', // label: 'response_feedback', // property: feedbackChoices?.join(','), // }, // [standardContext, ideExtensionVersion], // ); }; References: - packages/webview_duo_chat/src/plugin/port/chat/utils/submit_feedback.ts:46" You are a code assistant,Definition of 'onClose' in file src/common/circuit_breaker/circuit_breaker.ts in project gitlab-lsp,"Definition: onClose(listener: () => void): Disposable; } References:" You are a code assistant,Definition of 'STREAMING_COMPLETION_RESPONSE_NOTIFICATION' in file src/common/suggestion/streaming_handler.ts in project gitlab-lsp,"Definition: export const STREAMING_COMPLETION_RESPONSE_NOTIFICATION = 'streamingCompletionResponse'; export const CANCEL_STREAMING_COMPLETION_NOTIFICATION = 'cancelStreaming'; export const StreamingCompletionResponse = new NotificationType( STREAMING_COMPLETION_RESPONSE_NOTIFICATION, ); export const CancelStreaming = new NotificationType( CANCEL_STREAMING_COMPLETION_NOTIFICATION, ); export interface StartStreamParams { api: GitLabApiClient; circuitBreaker: CircuitBreaker; connection: Connection; documentContext: IDocContext; parser: TreeSitterParser; postProcessorPipeline: PostProcessorPipeline; streamId: string; tracker: TelemetryTracker; uniqueTrackingId: string; userInstruction?: string; generationType?: GenerationType; additionalContexts?: AdditionalContext[]; } export class DefaultStreamingHandler { #params: StartStreamParams; constructor(params: StartStreamParams) { this.#params = params; } async startStream() { return startStreaming(this.#params); } } const startStreaming = async ({ additionalContexts, api, circuitBreaker, connection, documentContext, parser, postProcessorPipeline, streamId, tracker, uniqueTrackingId, userInstruction, generationType, }: StartStreamParams) => { const language = parser.getLanguageNameForFile(documentContext.fileRelativePath); tracker.setCodeSuggestionsContext(uniqueTrackingId, { documentContext, additionalContexts, source: SuggestionSource.network, language, isStreaming: true, }); let streamShown = false; let suggestionProvided = false; let streamCancelledOrErrored = false; const cancellationTokenSource = new CancellationTokenSource(); const disposeStopStreaming = connection.onNotification(CancelStreaming, (stream) => { if (stream.id === streamId) { streamCancelledOrErrored = true; cancellationTokenSource.cancel(); if (streamShown) { tracker.updateSuggestionState(uniqueTrackingId, TRACKING_EVENTS.REJECTED); } else { tracker.updateSuggestionState(uniqueTrackingId, TRACKING_EVENTS.CANCELLED); } } }); const cancellationToken = cancellationTokenSource.token; const endStream = async () => { await connection.sendNotification(StreamingCompletionResponse, { id: streamId, done: true, }); if (!streamCancelledOrErrored) { tracker.updateSuggestionState(uniqueTrackingId, TRACKING_EVENTS.STREAM_COMPLETED); if (!suggestionProvided) { tracker.updateSuggestionState(uniqueTrackingId, TRACKING_EVENTS.NOT_PROVIDED); } } }; circuitBreaker.success(); const request: CodeSuggestionRequest = { prompt_version: 1, project_path: '', project_id: -1, current_file: { content_above_cursor: documentContext.prefix, content_below_cursor: documentContext.suffix, file_name: documentContext.fileRelativePath, }, intent: 'generation', stream: true, ...(additionalContexts?.length && { context: additionalContexts, }), ...(userInstruction && { user_instruction: userInstruction, }), generation_type: generationType, }; const trackStreamStarted = once(() => { tracker.updateSuggestionState(uniqueTrackingId, TRACKING_EVENTS.STREAM_STARTED); }); const trackStreamShown = once(() => { tracker.updateSuggestionState(uniqueTrackingId, TRACKING_EVENTS.SHOWN); streamShown = true; }); try { for await (const response of api.getStreamingCodeSuggestions(request)) { if (cancellationToken.isCancellationRequested) { break; } if (circuitBreaker.isOpen()) { break; } trackStreamStarted(); const processedCompletion = await postProcessorPipeline.run({ documentContext, input: { id: streamId, completion: response, done: false }, type: 'stream', }); await connection.sendNotification(StreamingCompletionResponse, processedCompletion); if (response.replace(/\s/g, '').length) { trackStreamShown(); suggestionProvided = true; } } } catch (err) { circuitBreaker.error(); if (isFetchError(err)) { tracker.updateCodeSuggestionsContext(uniqueTrackingId, { status: err.status }); } tracker.updateSuggestionState(uniqueTrackingId, TRACKING_EVENTS.ERRORED); streamCancelledOrErrored = true; log.error('Error streaming code suggestions.', err); } finally { await endStream(); disposeStopStreaming.dispose(); cancellationTokenSource.dispose(); } }; References:" You are a code assistant,Definition of 'StreamingCompletionResponse' in file src/common/suggestion/streaming_handler.ts in project gitlab-lsp,"Definition: export const StreamingCompletionResponse = new NotificationType( STREAMING_COMPLETION_RESPONSE_NOTIFICATION, ); export const CancelStreaming = new NotificationType( CANCEL_STREAMING_COMPLETION_NOTIFICATION, ); export interface StartStreamParams { api: GitLabApiClient; circuitBreaker: CircuitBreaker; connection: Connection; documentContext: IDocContext; parser: TreeSitterParser; postProcessorPipeline: PostProcessorPipeline; streamId: string; tracker: TelemetryTracker; uniqueTrackingId: string; userInstruction?: string; generationType?: GenerationType; additionalContexts?: AdditionalContext[]; } export class DefaultStreamingHandler { #params: StartStreamParams; constructor(params: StartStreamParams) { this.#params = params; } async startStream() { return startStreaming(this.#params); } } const startStreaming = async ({ additionalContexts, api, circuitBreaker, connection, documentContext, parser, postProcessorPipeline, streamId, tracker, uniqueTrackingId, userInstruction, generationType, }: StartStreamParams) => { const language = parser.getLanguageNameForFile(documentContext.fileRelativePath); tracker.setCodeSuggestionsContext(uniqueTrackingId, { documentContext, additionalContexts, source: SuggestionSource.network, language, isStreaming: true, }); let streamShown = false; let suggestionProvided = false; let streamCancelledOrErrored = false; const cancellationTokenSource = new CancellationTokenSource(); const disposeStopStreaming = connection.onNotification(CancelStreaming, (stream) => { if (stream.id === streamId) { streamCancelledOrErrored = true; cancellationTokenSource.cancel(); if (streamShown) { tracker.updateSuggestionState(uniqueTrackingId, TRACKING_EVENTS.REJECTED); } else { tracker.updateSuggestionState(uniqueTrackingId, TRACKING_EVENTS.CANCELLED); } } }); const cancellationToken = cancellationTokenSource.token; const endStream = async () => { await connection.sendNotification(StreamingCompletionResponse, { id: streamId, done: true, }); if (!streamCancelledOrErrored) { tracker.updateSuggestionState(uniqueTrackingId, TRACKING_EVENTS.STREAM_COMPLETED); if (!suggestionProvided) { tracker.updateSuggestionState(uniqueTrackingId, TRACKING_EVENTS.NOT_PROVIDED); } } }; circuitBreaker.success(); const request: CodeSuggestionRequest = { prompt_version: 1, project_path: '', project_id: -1, current_file: { content_above_cursor: documentContext.prefix, content_below_cursor: documentContext.suffix, file_name: documentContext.fileRelativePath, }, intent: 'generation', stream: true, ...(additionalContexts?.length && { context: additionalContexts, }), ...(userInstruction && { user_instruction: userInstruction, }), generation_type: generationType, }; const trackStreamStarted = once(() => { tracker.updateSuggestionState(uniqueTrackingId, TRACKING_EVENTS.STREAM_STARTED); }); const trackStreamShown = once(() => { tracker.updateSuggestionState(uniqueTrackingId, TRACKING_EVENTS.SHOWN); streamShown = true; }); try { for await (const response of api.getStreamingCodeSuggestions(request)) { if (cancellationToken.isCancellationRequested) { break; } if (circuitBreaker.isOpen()) { break; } trackStreamStarted(); const processedCompletion = await postProcessorPipeline.run({ documentContext, input: { id: streamId, completion: response, done: false }, type: 'stream', }); await connection.sendNotification(StreamingCompletionResponse, processedCompletion); if (response.replace(/\s/g, '').length) { trackStreamShown(); suggestionProvided = true; } } } catch (err) { circuitBreaker.error(); if (isFetchError(err)) { tracker.updateCodeSuggestionsContext(uniqueTrackingId, { status: err.status }); } tracker.updateSuggestionState(uniqueTrackingId, TRACKING_EVENTS.ERRORED); streamCancelledOrErrored = true; log.error('Error streaming code suggestions.', err); } finally { await endStream(); disposeStopStreaming.dispose(); cancellationTokenSource.dispose(); } }; References: - src/common/suggestion_client/post_processors/post_processor_pipeline.ts:9 - src/common/suggestion_client/post_processors/post_processor_pipeline.test.ts:119 - src/common/suggestion_client/post_processors/post_processor_pipeline.test.ts:16 - src/common/suggestion_client/post_processors/post_processor_pipeline.test.ts:58 - src/common/suggestion_client/post_processors/post_processor_pipeline.test.ts:44 - src/common/suggestion_client/post_processors/post_processor_pipeline.ts:23 - src/common/suggestion_client/post_processors/post_processor_pipeline.test.ts:133 - src/common/suggestion_client/post_processors/post_processor_pipeline.test.ts:149 - src/common/suggestion_client/post_processors/post_processor_pipeline.test.ts:103 - src/common/suggestion_client/post_processors/post_processor_pipeline.test.ts:87 - src/common/suggestion_client/post_processors/post_processor_pipeline.test.ts:179 - src/common/suggestion_client/post_processors/post_processor_pipeline.test.ts:29" You are a code assistant,Definition of 'constructor' in file src/common/suggestion_client/default_suggestion_client.ts in project gitlab-lsp,"Definition: constructor(api: GitLabApiClient) { this.#api = api; } async getSuggestions( suggestionContext: SuggestionContext, ): Promise { const response = await this.#api.getCodeSuggestions(createV2Request(suggestionContext)); return response && { ...response, isDirectConnection: false }; } } References:" You are a code assistant,Definition of 'WebviewHttpAccessInfoProvider' in file src/node/webview/http_access_info_provider.ts in project gitlab-lsp,"Definition: export class WebviewHttpAccessInfoProvider implements WebviewUriProvider { #addressInfo: AddressInfo; constructor(address: AddressInfo) { this.#addressInfo = address; } getUri(webviewId: WebviewId): string { return `http://${this.#addressInfo.address}:${this.#addressInfo.port}/webview/${webviewId}`; } } References: - src/node/setup_http.ts:20" You are a code assistant,Definition of 'constructor' in file src/common/ai_context_management_2/ai_context_manager.ts in project gitlab-lsp,"Definition: constructor(fileRetriever: AiContextFileRetriever) { this.#fileRetriever = fileRetriever; } #items: Map = new Map(); addItem(item: AiContextItem): boolean { if (this.#items.has(item.id)) { return false; } this.#items.set(item.id, item); return true; } removeItem(id: string): boolean { return this.#items.delete(id); } getItem(id: string): AiContextItem | undefined { return this.#items.get(id); } currentItems(): AiContextItem[] { return Array.from(this.#items.values()); } async retrieveItems(): Promise { const items = Array.from(this.#items.values()); log.info(`Retrieving ${items.length} items`); const retrievedItems = await Promise.all( items.map(async (item) => { try { switch (item.type) { case 'file': { const content = await this.#fileRetriever.retrieve(item); return content ? { ...item, content } : null; } default: throw new Error(`Unknown item type: ${item.type}`); } } catch (error) { log.error(`Failed to retrieve item ${item.id}`, error); return null; } }), ); return retrievedItems.filter((item) => item !== null); } } References:" You are a code assistant,Definition of 'FetchError' in file src/common/fetch_error.ts in project gitlab-lsp,"Definition: 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/suggestion/streaming_handler.test.ts:326 - src/common/fetch_error.test.ts:20 - src/common/suggestion/suggestion_service.test.ts:302 - src/common/handle_fetch_error.ts:6 - src/common/fetch_error.test.ts:36 - src/common/suggestion/suggestion_service.test.ts:896 - src/common/fetch_error.test.ts:6" You are a code assistant,Definition of 'GetRequestBase' in file packages/webview_duo_chat/src/plugin/port/platform/web_ide.ts in project gitlab-lsp,"Definition: 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; headers?: Record; } export interface GetRequest<_TReturnType> extends GetRequestBase<_TReturnType> { type: 'rest'; } export interface GetBufferRequest extends GetRequestBase { type: 'rest-buffer'; } export interface GraphQLRequest<_TReturnType> { type: 'graphql'; query: string; /** Options passed to the GraphQL query */ variables: Record; } 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; /* 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 'ConfigService' in file src/common/config_service.ts in project gitlab-lsp,"Definition: export interface ConfigService { get: TypedGetter; /** * set sets the property of the config * the new value completely overrides the old one */ set: TypedSetter; onConfigChange(listener: (config: IConfig) => void): Disposable; /** * merge adds `newConfig` properties into existing config, if the * property is present in both old and new config, `newConfig` * properties take precedence unless not defined * * This method performs deep merge * * **Arrays are not merged; they are replaced with the new value.** * */ merge(newConfig: Partial): void; } export const ConfigService = createInterfaceId('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 = (key?: string) => { return key ? get(this.#config, key) : this.#config; }; set: TypedSetter = (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) { mergeWith(this.#config, newConfig, (target, src) => (isArray(target) ? src : undefined)); this.#triggerChange(); } } References: - 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 - 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" You are a code assistant,Definition of 'ChatRecordState' in file packages/webview_duo_chat/src/plugin/port/chat/gitlab_chat_record.ts in project gitlab-lsp,"Definition: type ChatRecordState = 'pending' | 'ready'; type ChatRecordType = | 'general' | 'explainCode' | 'generateTests' | 'refactorCode' | 'newConversation'; type GitLabChatRecordAttributes = { chunkId?: number | null; type?: ChatRecordType; role: ChatRecordRole; content?: string; contentHtml?: string; requestId?: string; state?: ChatRecordState; errors?: string[]; timestamp?: string; extras?: { sources: object[]; }; }; export class GitLabChatRecord { chunkId?: number | null; role: ChatRecordRole; content?: string; contentHtml?: string; id: string; requestId?: string; state: ChatRecordState; timestamp: number; type: ChatRecordType; errors: string[]; extras?: { sources: object[]; }; context?: GitLabChatRecordContext; constructor({ chunkId, type, role, content, contentHtml, state, requestId, errors, timestamp, extras, }: GitLabChatRecordAttributes) { this.chunkId = chunkId; this.role = role; this.content = content; this.contentHtml = contentHtml; this.type = type ?? this.#detectType(); this.state = state ?? 'ready'; this.requestId = requestId; this.errors = errors ?? []; this.id = uuidv4(); this.timestamp = timestamp ? Date.parse(timestamp) : Date.now(); this.extras = extras; } static buildWithContext(attributes: GitLabChatRecordAttributes): GitLabChatRecord { const record = new GitLabChatRecord(attributes); record.context = buildCurrentContext(); return record; } update(attributes: Partial) { const convertedAttributes = attributes as Partial; if (attributes.timestamp) { convertedAttributes.timestamp = Date.parse(attributes.timestamp); } Object.assign(this, convertedAttributes); } #detectType(): ChatRecordType { if (this.content === SPECIAL_MESSAGES.RESET) { return 'newConversation'; } return 'general'; } } References: - packages/webview_duo_chat/src/plugin/port/chat/gitlab_chat_record.ts:21 - packages/webview_duo_chat/src/plugin/port/chat/gitlab_chat_record.ts:42" You are a code assistant,Definition of 'constructor' in file src/common/suggestion/suggestion_service.ts in project gitlab-lsp,"Definition: 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 => { 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 => { 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 => { 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 { 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 { 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 { 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 { 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 { 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:" You are a code assistant,Definition of 'HostApplicationMessageBusProvider' in file packages/lib_webview_client/src/bus/provider/host_application_message_bus_provider.ts in project gitlab-lsp,"Definition: export class HostApplicationMessageBusProvider implements MessageBusProvider { readonly name = 'HostApplicationMessageBusProvider'; getMessageBus(): MessageBus | null { return 'gitlab' in window && isHostConfig(window.gitlab) ? window.gitlab.host : null; } } References: - packages/lib_webview_client/src/bus/provider/get_default_providers.ts:5 - packages/lib_webview_client/src/bus/provider/host_application_message_bus_provider.test.ts:20 - packages/lib_webview_client/src/bus/provider/host_application_message_bus_provider.test.ts:7" You are a code assistant,Definition of 'TELEMETRY_DISABLED_WARNING_MSG' in file src/common/tracking/constants.ts in project gitlab-lsp,"Definition: 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 'constructor' in file packages/webview_duo_chat/src/plugin/port/chat/gitlab_chat_api.ts in project gitlab-lsp,"Definition: constructor(manager: GitLabPlatformManagerForChat) { this.#manager = manager; } async processNewUserPrompt( question: string, subscriptionId?: string, currentFileContext?: GitLabChatFileContext, ): Promise { return this.#sendAiAction({ question, currentFileContext, clientSubscriptionId: subscriptionId, }); } async pullAiMessage(requestId: string, role: string): Promise { const response = await pullHandler(() => this.#getAiMessage(requestId, role)); if (!response) return errorResponse(requestId, ['Reached timeout while fetching response.']); return successResponse(response); } async cleanChat(): Promise { return this.#sendAiAction({ question: SPECIAL_MESSAGES.CLEAN }); } async #currentPlatform() { const platform = await this.#manager.getGitLabPlatform(); if (!platform) throw new Error('Platform is missing!'); return platform; } async #getAiMessage(requestId: string, role: string): Promise { const request: GraphQLRequest = { type: 'graphql', query: AI_MESSAGES_QUERY, variables: { requestIds: [requestId], roles: [role.toUpperCase()] }, }; const platform = await this.#currentPlatform(); const history = await platform.fetchFromApi(request); return history.aiMessages.nodes[0]; } async subscribeToUpdates( messageCallback: (message: AiCompletionResponseMessageType) => Promise, subscriptionId?: string, ) { const platform = await this.#currentPlatform(); const channel = new AiCompletionResponseChannel({ htmlResponse: true, userId: `gid://gitlab/User/${extractUserId(platform.account.id)}`, aiAction: 'CHAT', clientSubscriptionId: subscriptionId, }); const cable = await platform.connectToCable(); // we use this flag to fix https://gitlab.com/gitlab-org/gitlab-vscode-extension/-/issues/1397 // sometimes a chunk comes after the full message and it broke the chat let fullMessageReceived = false; channel.on('newChunk', async (msg) => { if (fullMessageReceived) { log.info(`CHAT-DEBUG: full message received, ignoring chunk`); return; } await messageCallback(msg); }); channel.on('fullMessage', async (message) => { fullMessageReceived = true; await messageCallback(message); if (subscriptionId) { cable.disconnect(); } }); cable.subscribe(channel); } async #sendAiAction(variables: object): Promise { const platform = await this.#currentPlatform(); const { query, defaultVariables } = await this.#actionQuery(); const projectGqlId = await this.#manager.getProjectGqlId(); const request: GraphQLRequest = { type: 'graphql', query, variables: { ...variables, ...defaultVariables, resourceId: projectGqlId ?? null, }, }; return platform.fetchFromApi(request); } async #actionQuery(): Promise { if (!this.#cachedActionQuery) { const platform = await this.#currentPlatform(); try { const { version } = await platform.fetchFromApi(versionRequest); this.#cachedActionQuery = ifVersionGte( version, MINIMUM_PLATFORM_ORIGIN_FIELD_VERSION, () => CHAT_INPUT_TEMPLATE_17_3_AND_LATER, () => CHAT_INPUT_TEMPLATE_17_2_AND_EARLIER, ); } catch (e) { log.debug(`GitLab version check for sending chat failed:`, e as Error); this.#cachedActionQuery = CHAT_INPUT_TEMPLATE_17_3_AND_LATER; } } return this.#cachedActionQuery; } } References:" You are a code assistant,Definition of 'ChatPlatformForProject' in file packages/webview_duo_chat/src/plugin/chat_platform.ts in project gitlab-lsp,"Definition: 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:" You are a code assistant,Definition of 'sendNotification' in file packages/lib_webview/src/setup/plugin/webview_instance_message_bus.ts in project gitlab-lsp,"Definition: 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 { 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); } 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 'FeatureState' in file src/common/feature_state/feature_state_management_types.ts in project gitlab-lsp,"Definition: export interface FeatureState { featureId: Feature; engagedChecks: FeatureStateCheck[]; } const CODE_SUGGESTIONS_CHECKS_PRIORITY_ORDERED = [ DUO_DISABLED_FOR_PROJECT, UNSUPPORTED_LANGUAGE, DISABLED_LANGUAGE, ]; const CHAT_CHECKS_PRIORITY_ORDERED = [DUO_DISABLED_FOR_PROJECT]; export const CHECKS_PER_FEATURE: { [key in Feature]: StateCheckId[] } = { [CODE_SUGGESTIONS]: CODE_SUGGESTIONS_CHECKS_PRIORITY_ORDERED, [CHAT]: CHAT_CHECKS_PRIORITY_ORDERED, // [WORKFLOW]: [], }; References:" You are a code assistant,Definition of 'buildContext' in file src/common/advanced_context/context_resolvers/open_tabs_context_resolver.ts in project gitlab-lsp,"Definition: async *buildContext({ documentContext, includeCurrentFile = false, }: { documentContext?: IDocContext; includeCurrentFile?: boolean; }): AsyncGenerator { const lruCache = LruCache.getInstance(LRU_CACHE_BYTE_SIZE_LIMIT); const openFiles = lruCache.mostRecentFiles({ context: documentContext, includeCurrentFile, }); for (const file of openFiles) { yield { uri: file.uri, type: 'file' as const, content: `${file.prefix}${file.suffix}`, fileRelativePath: file.fileRelativePath, strategy: 'open_tabs' as const, workspaceFolder: file.workspaceFolder ?? { name: '', uri: '' }, }; } } } References:" You are a code assistant,Definition of 'Handler' in file packages/lib_handler_registry/src/types.ts in project gitlab-lsp,"Definition: export type Handler = (...args: any) => any; export interface HandlerRegistry { size: number; has(key: TKey): boolean; register(key: TKey, handler: THandler): Disposable; handle(key: TKey, ...args: Parameters): Promise>; dispose(): void; } References: - packages/lib_webview/src/setup/plugin/webview_instance_message_bus.ts:139 - packages/lib_webview/src/setup/plugin/webview_instance_message_bus.ts:99" You are a code assistant,Definition of 'size' in file packages/lib_handler_registry/src/registry/simple_registry.ts in project gitlab-lsp,"Definition: get size() { return this.#handlers.size; } register(key: string, handler: THandler): Disposable { this.#handlers.set(key, handler); return { dispose: () => { this.#handlers.delete(key); }, }; } has(key: string) { return this.#handlers.has(key); } async handle(key: string, ...args: Parameters): Promise> { const handler = this.#handlers.get(key); if (!handler) { throw new HandlerNotFoundError(key); } try { const handlerResult = await handler(...args); return handlerResult as ReturnType; } catch (error) { throw new UnhandledHandlerError(key, resolveError(error)); } } dispose() { this.#handlers.clear(); } } function resolveError(e: unknown): Error { if (e instanceof Error) { return e; } if (typeof e === 'string') { return new Error(e); } return new Error('Unknown error'); } References:" You are a code assistant,Definition of 'EVENT_VALIDATION_ERROR_MSG' in file src/common/tracking/snowplow_tracker.ts in project gitlab-lsp,"Definition: export const EVENT_VALIDATION_ERROR_MSG = `Telemetry event context is not valid - event won't be tracked.`; 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(); #lsFetch: LsFetch; #featureFlagService: FeatureFlagService; #gitlabRealm: GitlabRealm = GitlabRealm.saas; #codeSuggestionsContextMap = new Map(); 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, ) { 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, ) { 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 'InvalidInstanceVersionError' in file src/common/fetch_error.ts in project gitlab-lsp,"Definition: export class InvalidInstanceVersionError extends Error {} References: - src/common/api.ts:319 - src/common/tracking/instance_tracker.test.ts:345" You are a code assistant,Definition of 'UnwrapInterfaceIds' in file packages/lib_di/src/index.ts in project gitlab-lsp,"Definition: type UnwrapInterfaceIds[]> = { [K in keyof T]: T[K] extends InterfaceId ? U : never; }; interface Metadata { id: string; dependencies: string[]; } /** * Here we store the id and dependencies for all classes decorated with @Injectable */ const injectableMetadata = new WeakMap(); /** * Decorate your class with @Injectable(id, dependencies) * param id = InterfaceId of the interface implemented by your class (use createInterfaceId to create one) * param dependencies = List of InterfaceIds that will be injected into class' constructor */ export function Injectable[]>( id: InterfaceId, dependencies: [...TDependencies], // we can add `| [] = [],` to make dependencies optional, but the type checker messages are quite cryptic when the decorated class has some constructor arguments ) { // this is the trickiest part of the whole DI framework // we say, this decorator takes // - id (the interface that the injectable implements) // - dependencies (list of interface ids that will be injected to constructor) // // With then we return function that ensures that the decorated class implements the id interface // and its constructor has arguments of same type and order as the dependencies argument to the decorator return function ): I }>( constructor: T, { kind }: ClassDecoratorContext, ) { if (kind === 'class') { injectableMetadata.set(constructor, { id, dependencies: dependencies || [] }); return constructor; } throw new Error('Injectable decorator can only be used on a class.'); }; } // new (...args: any[]): any is actually how TS defines type of a class // eslint-disable-next-line @typescript-eslint/no-explicit-any type WithConstructor = { new (...args: any[]): any; name: string }; type ClassWithDependencies = { cls: WithConstructor; id: string; dependencies: string[] }; type Validator = (cwds: ClassWithDependencies[], instanceIds: string[]) => void; const sanitizeId = (idWithRandom: string) => idWithRandom.replace(/-[^-]+$/, ''); /** ensures that only one interface ID implementation is present */ const interfaceUsedOnlyOnce: Validator = (cwds, instanceIds) => { const clashingWithExistingInstance = cwds.filter((cwd) => instanceIds.includes(cwd.id)); if (clashingWithExistingInstance.length > 0) { throw new Error( `The following classes are clashing (have duplicate ID) with instances already present in the container: ${clashingWithExistingInstance.map((cwd) => cwd.cls.name)}`, ); } const groupedById = groupBy(cwds, (cwd) => cwd.id); if (Object.values(groupedById).every((groupedCwds) => groupedCwds.length === 1)) { return; } const messages = Object.entries(groupedById).map( ([id, groupedCwds]) => `'${sanitizeId(id)}' (classes: ${groupedCwds.map((cwd) => cwd.cls.name).join(',')})`, ); throw new Error(`The following interface IDs were used multiple times ${messages.join(',')}`); }; /** throws an error if any class depends on an interface that is not available */ const dependenciesArePresent: Validator = (cwds, instanceIds) => { const allIds = new Set([...cwds.map((cwd) => cwd.id), ...instanceIds]); const cwsWithUnmetDeps = cwds.filter((cwd) => !cwd.dependencies.every((d) => allIds.has(d))); if (cwsWithUnmetDeps.length === 0) { return; } const messages = cwsWithUnmetDeps.map((cwd) => { const unmetDeps = cwd.dependencies.filter((d) => !allIds.has(d)).map(sanitizeId); return `Class ${cwd.cls.name} (interface ${sanitizeId(cwd.id)}) depends on interfaces [${unmetDeps}] that weren't added to the init method.`; }); throw new Error(messages.join('\n')); }; /** uses depth first search to find out if the classes have circular dependency */ const noCircularDependencies: Validator = (cwds, instanceIds) => { const inStack = new Set(); const hasCircularDependency = (id: string): boolean => { if (inStack.has(id)) { return true; } inStack.add(id); const cwd = cwds.find((c) => c.id === id); // we reference existing instance, there won't be circular dependency past this one because instances don't have any dependencies if (!cwd && instanceIds.includes(id)) { inStack.delete(id); return false; } if (!cwd) throw new Error(`assertion error: dependency ID missing ${sanitizeId(id)}`); for (const dependencyId of cwd.dependencies) { if (hasCircularDependency(dependencyId)) { return true; } } inStack.delete(id); return false; }; for (const cwd of cwds) { if (hasCircularDependency(cwd.id)) { throw new Error( `Circular dependency detected between interfaces (${Array.from(inStack).map(sanitizeId)}), starting with '${sanitizeId(cwd.id)}' (class: ${cwd.cls.name}).`, ); } } }; /** * Topological sort of the dependencies - returns array of classes. The classes should be initialized in order given by the array. * https://en.wikipedia.org/wiki/Topological_sorting */ const sortDependencies = (classes: Map): ClassWithDependencies[] => { const visited = new Set(); const sortedClasses: ClassWithDependencies[] = []; const topologicalSort = (interfaceId: string) => { if (visited.has(interfaceId)) { return; } visited.add(interfaceId); const cwd = classes.get(interfaceId); if (!cwd) { // the instance for this ID is already initiated return; } for (const d of cwd.dependencies || []) { topologicalSort(d); } sortedClasses.push(cwd); }; for (const id of classes.keys()) { topologicalSort(id); } return sortedClasses; }; /** * Helper type used by the brandInstance function to ensure that all container.addInstances parameters are branded */ export type BrandedInstance = T; /** * use brandInstance to be able to pass this instance to the container.addInstances method */ export const brandInstance = ( id: InterfaceId, instance: T, ): BrandedInstance => { injectableMetadata.set(instance, { id, dependencies: [] }); return instance; }; /** * Container is responsible for initializing a dependency tree. * * It receives a list of classes decorated with the `@Injectable` decorator * and it constructs instances of these classes in an order that ensures class' dependencies * are initialized before the class itself. * * check https://gitlab.com/viktomas/needle for full documentation of this mini-framework */ export class Container { #instances = new Map(); /** * addInstances allows you to add pre-initialized objects to the container. * This is useful when you want to keep mandatory parameters in class' constructor (e.g. some runtime objects like server connection). * addInstances accepts a list of any objects that have been ""branded"" by the `brandInstance` method */ addInstances(...instances: BrandedInstance[]) { for (const instance of instances) { const metadata = injectableMetadata.get(instance); if (!metadata) { throw new Error( 'assertion error: addInstance invoked without branded object, make sure all arguments are branded with `brandInstance`', ); } if (this.#instances.has(metadata.id)) { throw new Error( `you are trying to add instance for interfaceId ${metadata.id}, but instance with this ID is already in the container.`, ); } this.#instances.set(metadata.id, instance); } } /** * instantiate accepts list of classes, validates that they can be managed by the container * and then initialized them in such order that dependencies of a class are initialized before the class */ instantiate(...classes: WithConstructor[]) { // ensure all classes have been decorated with @Injectable const undecorated = classes.filter((c) => !injectableMetadata.has(c)).map((c) => c.name); if (undecorated.length) { throw new Error(`Classes [${undecorated}] are not decorated with @Injectable.`); } const classesWithDeps: ClassWithDependencies[] = classes.map((cls) => { // we verified just above that all classes are present in the metadata map // eslint-disable-next-line @typescript-eslint/no-non-null-assertion const { id, dependencies } = injectableMetadata.get(cls)!; return { cls, id, dependencies }; }); const validators: Validator[] = [ interfaceUsedOnlyOnce, dependenciesArePresent, noCircularDependencies, ]; validators.forEach((v) => v(classesWithDeps, Array.from(this.#instances.keys()))); const classesById = new Map(); // Index classes by their interface id classesWithDeps.forEach((cwd) => { classesById.set(cwd.id, cwd); }); // Create instances in topological order for (const cwd of sortDependencies(classesById)) { const args = cwd.dependencies.map((dependencyId) => this.#instances.get(dependencyId)); // eslint-disable-next-line new-cap const instance = new cwd.cls(...args); this.#instances.set(cwd.id, instance); } } get(id: InterfaceId): T { const instance = this.#instances.get(id); if (!instance) { throw new Error(`Instance for interface '${sanitizeId(id)}' is not in the container.`); } return instance as T; } } References:" You are a code assistant,Definition of 'constructor' in file packages/webview_duo_chat/src/plugin/port/api/graphql/ai_completion_response_channel.ts in project gitlab-lsp,"Definition: constructor(params: AiCompletionResponseInput) { super({ channel: 'GraphqlChannel', operationName: 'aiCompletionResponse', query: AI_MESSAGE_SUBSCRIPTION_QUERY, variables: JSON.stringify(params), }); } receive(message: AiCompletionResponseResponseType) { if (!message.result.data.aiCompletionResponse) return; const data = message.result.data.aiCompletionResponse; if (data.role.toLowerCase() === 'system') { this.emit('systemMessage', data); } else if (data.chunkId) { this.emit('newChunk', data); } else { this.emit('fullMessage', data); } } } References:" You are a code assistant,Definition of 'engaged' in file src/common/feature_state/project_duo_acces_check.ts in project gitlab-lsp,"Definition: get engaged() { return !this.#hasDuoAccess; } async #checkIfProjectHasDuoAccess(): Promise { this.#hasDuoAccess = this.#isEnabledInSettings; if (!this.#currentDocument) { this.#stateEmitter.emit('change', this); return; } const workspaceFolder = await this.#getWorkspaceFolderForUri(this.#currentDocument.uri); if (workspaceFolder) { const status = this.#duoProjectAccessChecker.checkProjectStatus( this.#currentDocument.uri, workspaceFolder, ); if (status === DuoProjectStatus.DuoEnabled) { this.#hasDuoAccess = true; } else if (status === DuoProjectStatus.DuoDisabled) { this.#hasDuoAccess = false; } } this.#stateEmitter.emit('change', this); } id = DUO_DISABLED_FOR_PROJECT; details = 'Duo features are disabled for this project'; async #getWorkspaceFolderForUri(uri: URI): Promise { const workspaceFolders = await this.#configService.get('client.workspaceFolders'); return workspaceFolders?.find((folder) => uri.startsWith(folder.uri)); } dispose() { this.#subscriptions.forEach((s) => s.dispose()); } } References:" You are a code assistant,Definition of 'greetGenerator' in file src/tests/fixtures/intent/empty_function/javascript.js in project gitlab-lsp,"Definition: function* greetGenerator() { yield 'Hello'; } References:" You are a code assistant,Definition of 'MessagesToClient' in file packages/lib_webview_transport/src/types.ts in project gitlab-lsp,"Definition: export type MessagesToClient = { webview_instance_notification: WebviewInstanceNotificationEventData; webview_instance_request: WebviewInstanceRequestEventData; webview_instance_response: WebviewInstanceResponseEventData; }; export interface TransportMessageHandler { (payload: T): void; } export interface TransportListener { on( type: K, callback: TransportMessageHandler, ): Disposable; } export interface TransportPublisher { publish(type: K, payload: MessagesToClient[K]): Promise; } export interface Transport extends TransportListener, TransportPublisher {} References:" You are a code assistant,Definition of 'getForActiveProject' in file packages/webview_duo_chat/src/plugin/chat_platform_manager.ts in project gitlab-lsp,"Definition: async getForActiveProject(): Promise { // return new ChatPlatformForProject(this.#client); return undefined; } async getForActiveAccount(): Promise { return new ChatPlatformForAccount(this.#client); } async getForAllAccounts(): Promise { return [new ChatPlatformForAccount(this.#client)]; } async getForSaaSAccount(): Promise { return new ChatPlatformForAccount(this.#client); } } References:" You are a code assistant,Definition of 'redactSecrets' in file src/common/secret_redaction/index.ts in project gitlab-lsp,"Definition: redactSecrets(raw: string): string; } export const SecretRedactor = createInterfaceId('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:" You are a code assistant,Definition of 'Matchers' in file src/tests/int/test_utils.ts in project gitlab-lsp,"Definition: interface Matchers { toEventuallyContainChildProcessConsoleOutput( expectedMessage: string, timeoutMs?: number, intervalMs?: number, ): Promise; } } } expect.extend({ /** * Custom matcher to check the language client child process console output for an expected string. * This is useful when an operation does not directly run some logic, (e.g. internally emits events * which something later does the thing you're testing), so you cannot just await and check the output. * * await expect(lsClient).toEventuallyContainChildProcessConsoleOutput('foo'); * * @param lsClient LspClient instance to check * @param expectedMessage Message to check for * @param timeoutMs How long to keep checking before test is considered failed * @param intervalMs How frequently to check the log */ async toEventuallyContainChildProcessConsoleOutput( lsClient: LspClient, expectedMessage: string, timeoutMs = 1000, intervalMs = 25, ) { const expectedResult = `Expected language service child process console output to contain ""${expectedMessage}""`; const checkOutput = () => lsClient.childProcessConsole.some((line) => line.includes(expectedMessage)); const sleep = () => new Promise((resolve) => { setTimeout(resolve, intervalMs); }); let remainingRetries = Math.ceil(timeoutMs / intervalMs); while (remainingRetries > 0) { if (checkOutput()) { return { message: () => expectedResult, pass: true, }; } // eslint-disable-next-line no-await-in-loop await sleep(); remainingRetries--; } return { message: () => `""${expectedResult}"", but it was not found within ${timeoutMs}ms`, pass: false, }; }, }); References:" You are a code assistant,Definition of 'TransportMessageHandler' in file packages/lib_webview_transport/src/types.ts in project gitlab-lsp,"Definition: export interface TransportMessageHandler { (payload: T): void; } export interface TransportListener { on( type: K, callback: TransportMessageHandler, ): Disposable; } export interface TransportPublisher { publish(type: K, payload: MessagesToClient[K]): Promise; } export interface Transport extends TransportListener, TransportPublisher {} References:" You are a code assistant,Definition of 'GITLAB_STAGING_URL' in file packages/webview_duo_chat/src/plugin/port/chat/get_platform_manager_for_chat.ts in project gitlab-lsp,"Definition: export const GITLAB_STAGING_URL: string = 'https://staging.gitlab.com'; export const GITLAB_ORG_URL: string = 'https://dev.gitlab.org'; export const GITLAB_DEVELOPMENT_URL: string = 'http://localhost'; export enum GitLabEnvironment { GITLAB_COM = 'production', GITLAB_STAGING = 'staging', GITLAB_ORG = 'org', GITLAB_DEVELOPMENT = 'development', GITLAB_SELF_MANAGED = 'self-managed', } export class GitLabPlatformManagerForChat { readonly #platformManager: GitLabPlatformManager; constructor(platformManager: GitLabPlatformManager) { this.#platformManager = platformManager; } async getProjectGqlId(): Promise { const projectManager = await this.#platformManager.getForActiveProject(false); return projectManager?.project.gqlId; } /** * Obtains a GitLab Platform to send API requests to the GitLab API * for the Duo Chat feature. * * - It returns a GitLabPlatformForAccount for the first linked account. * - It returns undefined if there are no accounts linked */ async getGitLabPlatform(): Promise { const platforms = await this.#platformManager.getForAllAccounts(); if (!platforms.length) { return undefined; } let platform: GitLabPlatformForAccount | undefined; // Using a for await loop in this context because we want to stop // evaluating accounts as soon as we find one with code suggestions enabled for await (const result of platforms.map(getChatSupport)) { if (result.hasSupportForChat) { platform = result.platform; break; } } return platform; } async getGitLabEnvironment(): Promise { const platform = await this.getGitLabPlatform(); const instanceUrl = platform?.account.instanceUrl; switch (instanceUrl) { case GITLAB_COM_URL: return GitLabEnvironment.GITLAB_COM; case GITLAB_DEVELOPMENT_URL: return GitLabEnvironment.GITLAB_DEVELOPMENT; case GITLAB_STAGING_URL: return GitLabEnvironment.GITLAB_STAGING; case GITLAB_ORG_URL: return GitLabEnvironment.GITLAB_ORG; default: return GitLabEnvironment.GITLAB_SELF_MANAGED; } } } References:" You are a code assistant,Definition of 'FeatureStateManager' in file src/common/feature_state/feature_state_manager.ts in project gitlab-lsp,"Definition: export interface FeatureStateManager extends Notifier, Disposable {} export const FeatureStateManager = createInterfaceId('FeatureStateManager'); @Injectable(FeatureStateManager, [CodeSuggestionsSupportedLanguageCheck, ProjectDuoAccessCheck]) export class DefaultFeatureStateManager implements FeatureStateManager { #checks: StateCheck[] = []; #subscriptions: Disposable[] = []; #notify?: NotifyFn; constructor( supportedLanguagePolicy: CodeSuggestionsSupportedLanguageCheck, projectDuoAccessCheck: ProjectDuoAccessCheck, ) { this.#checks.push(supportedLanguagePolicy, projectDuoAccessCheck); this.#subscriptions.push( ...this.#checks.map((check) => check.onChanged(() => this.#notifyClient())), ); } init(notify: NotifyFn): void { this.#notify = notify; } async #notifyClient() { if (!this.#notify) { throw new Error( ""The state manager hasn't been initialized. It can't send notifications. Call the init method first."", ); } await this.#notify(this.#state); } dispose() { this.#subscriptions.forEach((s) => s.dispose()); } get #state(): FeatureState[] { const engagedChecks = this.#checks.filter((check) => check.engaged); return getEntries(CHECKS_PER_FEATURE).map(([featureId, stateChecks]) => { const engagedFeatureChecks: FeatureStateCheck[] = engagedChecks .filter(({ id }) => stateChecks.includes(id)) .map((stateCheck) => ({ checkId: stateCheck.id, details: stateCheck.details, })); return { featureId, engagedChecks: engagedFeatureChecks, }; }); } } References: - src/common/connection_service.ts:68" You are a code assistant,Definition of 'greet' in file src/tests/fixtures/intent/ruby_comments.rb in project gitlab-lsp,"Definition: def greet(name) # function to greet the user end 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 'runWorkflow' in file src/node/duo_workflow/desktop_workflow_runner.ts in project gitlab-lsp,"Definition: async runWorkflow(goal: string, image: string): Promise { if (!this.#dockerSocket) { throw new Error('Docker socket not configured'); } if (!this.#folders || this.#folders.length === 0) { throw new Error('No workspace folders'); } const executorPath = path.join( __dirname, `../vendor/duo_workflow_executor-${WORKFLOW_EXECUTOR_VERSION}.tar.gz`, ); await this.#downloadWorkflowExecutor(executorPath); const folderName = this.#folders[0].uri.replace(/^file:\/\//, ''); if (this.#folders.length > 0) { log.info(`More than one workspace folder detected. Using workspace folder ${folderName}`); } const workflowID = await this.#createWorkflow(); const workflowToken = await this.#getWorkflowToken(); const containerOptions = { Image: image, Cmd: [ '/duo-workflow-executor', `--workflow-id=${workflowID}`, '--server', workflowToken.duo_workflow_service.base_url || 'localhost:50052', '--goal', goal, '--base-url', workflowToken.gitlab_rails.base_url, '--token', workflowToken.gitlab_rails.token, '--duo-workflow-service-token', workflowToken.duo_workflow_service.token, '--realm', workflowToken.duo_workflow_service.headers['X-Gitlab-Realm'], '--user-id', workflowToken.duo_workflow_service.headers['X-Gitlab-Global-User-Id'], ], HostConfig: { Binds: [`${folderName}:/workspace`], }, }; // Create a container const createResponse = JSON.parse( await this.#makeRequest('/v1.43/containers/create', 'POST', JSON.stringify(containerOptions)), ); // Check if Id in createResponse if (!createResponse.Id) { throw new Error('Failed to create container: No Id in response'); } const containerID = createResponse.Id; // Copy the executor into the container await this.#copyExecutor(containerID, executorPath); // Start the container await this.#makeRequest(`/v1.43/containers/${containerID}/start`, 'POST', ''); return workflowID; } async #copyExecutor(containerID: string, executorPath: string) { const fileContents = await readFile(executorPath); await this.#makeRequest( `/v1.43/containers/${containerID}/archive?path=/`, 'PUT', fileContents, 'application/x-tar', ); } #makeRequest( apiPath: string, method: string, data: string | Buffer, contentType = 'application/json', ): Promise { return new Promise((resolve, reject) => { if (!this.#dockerSocket) { throw new Error('Docker socket not set'); } const options: http.RequestOptions = { socketPath: this.#dockerSocket, path: apiPath, method, headers: { 'Content-Type': contentType, 'Content-Length': Buffer.byteLength(data), }, }; const callback = (res: http.IncomingMessage) => { res.setEncoding('utf-8'); res.on('data', (content) => resolve(content)); res.on('error', (err) => reject(err)); res.on('end', () => { resolve(''); }); }; const clientRequest = http.request(options, callback); clientRequest.write(data); clientRequest.end(); }); } async #downloadWorkflowExecutor(executorPath: string): Promise { try { await readFile(executorPath); } catch (error) { log.info('Downloading workflow executor...'); await this.#downloadFile(executorPath); } } async #downloadFile(outputPath: string): Promise { const response = await this.#fetch.fetch(WORKFLOW_EXECUTOR_DOWNLOAD_PATH, { method: 'GET', headers: { 'Content-Type': 'application/octet-stream', }, }); if (!response.ok) { throw new Error(`Failed to download file: ${response.statusText}`); } const buffer = await response.arrayBuffer(); await writeFile(outputPath, Buffer.from(buffer)); } async #createWorkflow(): Promise { const response = await this.#api?.fetchFromApi({ type: 'rest', method: 'POST', path: '/ai/duo_workflows/workflows', body: { project_id: this.#projectPath, }, supportedSinceInstanceVersion: { resourceName: 'create a workflow', version: '17.3.0', }, }); if (!response) { throw new Error('Failed to create workflow'); } return response.id; } async #getWorkflowToken(): Promise { const token = await this.#api?.fetchFromApi({ type: 'rest', method: 'POST', path: '/ai/duo_workflows/direct_access', supportedSinceInstanceVersion: { resourceName: 'get workflow direct access', version: '17.3.0', }, }); if (!token) { throw new Error('Failed to get workflow token'); } return token; } } References:" You are a code assistant,Definition of 'ProjectDuoAccessCheck' in file src/common/feature_state/project_duo_acces_check.ts in project gitlab-lsp,"Definition: export const ProjectDuoAccessCheck = createInterfaceId('ProjectDuoAccessCheck'); @Injectable(ProjectDuoAccessCheck, [ DocumentService, ConfigService, DuoProjectAccessChecker, DuoProjectAccessCache, ]) export class DefaultProjectDuoAccessCheck implements StateCheck { #subscriptions: Disposable[] = []; #stateEmitter = new EventEmitter(); #hasDuoAccess?: boolean; #duoProjectAccessChecker: DuoProjectAccessChecker; #configService: ConfigService; #currentDocument?: TextDocument; #isEnabledInSettings = true; constructor( documentService: DocumentService, configService: ConfigService, duoProjectAccessChecker: DuoProjectAccessChecker, duoProjectAccessCache: DuoProjectAccessCache, ) { this.#configService = configService; this.#duoProjectAccessChecker = duoProjectAccessChecker; this.#subscriptions.push( documentService.onDocumentChange(async (event, handlerType) => { if (handlerType === TextDocumentChangeListenerType.onDidSetActive) { this.#currentDocument = event.document; await this.#checkIfProjectHasDuoAccess(); } }), configService.onConfigChange(async (config) => { this.#isEnabledInSettings = config.client.duo?.enabledWithoutGitlabProject ?? true; await this.#checkIfProjectHasDuoAccess(); }), duoProjectAccessCache.onDuoProjectCacheUpdate(() => this.#checkIfProjectHasDuoAccess()), ); } onChanged(listener: (data: StateCheckChangedEventData) => void): Disposable { this.#stateEmitter.on('change', listener); return { dispose: () => this.#stateEmitter.removeListener('change', listener), }; } get engaged() { return !this.#hasDuoAccess; } async #checkIfProjectHasDuoAccess(): Promise { this.#hasDuoAccess = this.#isEnabledInSettings; if (!this.#currentDocument) { this.#stateEmitter.emit('change', this); return; } const workspaceFolder = await this.#getWorkspaceFolderForUri(this.#currentDocument.uri); if (workspaceFolder) { const status = this.#duoProjectAccessChecker.checkProjectStatus( this.#currentDocument.uri, workspaceFolder, ); if (status === DuoProjectStatus.DuoEnabled) { this.#hasDuoAccess = true; } else if (status === DuoProjectStatus.DuoDisabled) { this.#hasDuoAccess = false; } } this.#stateEmitter.emit('change', this); } id = DUO_DISABLED_FOR_PROJECT; details = 'Duo features are disabled for this project'; async #getWorkspaceFolderForUri(uri: URI): Promise { const workspaceFolders = await this.#configService.get('client.workspaceFolders'); return workspaceFolders?.find((folder) => uri.startsWith(folder.uri)); } dispose() { this.#subscriptions.forEach((s) => s.dispose()); } } References: - src/common/feature_state/project_duo_acces_check.test.ts:15 - src/common/feature_state/feature_state_manager.ts:29" You are a code assistant,Definition of 'SuggestionCache' in file src/common/suggestion/suggestions_cache.ts in project gitlab-lsp,"Definition: export type SuggestionCache = { options: SuggestionOption[]; additionalContexts?: AdditionalContext[]; }; function isNonEmptyLine(s: string) { return s.trim().length > 0; } type Required = { [P in keyof T]-?: T[P]; }; const DEFAULT_CONFIG: Required = { enabled: true, maxSize: 1024 * 1024, ttl: 60 * 1000, prefixLines: 1, suffixLines: 1, }; export class SuggestionsCache { #cache: LRUCache; #configService: ConfigService; constructor(configService: ConfigService) { this.#configService = configService; const currentConfig = this.#getCurrentConfig(); this.#cache = new LRUCache({ 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 { 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 'setup' in file scripts/esbuild/helpers.ts in project gitlab-lsp,"Definition: setup(build) { build.onLoad({ filter: /[/\\]get_language_server_version\.ts$/ }, ({ path: filePath }) => { if (!filePath.match(nodeModulesRegex)) { let contents = readFileSync(filePath, 'utf8'); contents = contents.replaceAll( '{{GITLAB_LANGUAGE_SERVER_VERSION}}', packageJson['version'], ); return { contents, loader: extname(filePath).substring(1) as Loader, }; } return null; }); }, } satisfies Plugin; export { fixVendorGrammarsPlugin, fixWebviewPathPlugin, setLanguageServerVersionPlugin, wasmEntryPoints, }; References: - src/common/connection.test.ts:43 - src/browser/main.ts:122 - src/node/main.ts:197" You are a code assistant,Definition of 'IHttpAgentOptions' in file src/common/config_service.ts in project gitlab-lsp,"Definition: export interface IHttpAgentOptions { ca?: string; cert?: string; certKey?: string; } export interface ISnowplowTrackerOptions { gitlab_instance_id?: string; gitlab_global_user_id?: string; gitlab_host_name?: string; gitlab_saas_duo_pro_namespace_ids?: number[]; } export interface ISecurityScannerOptions { enabled?: boolean; serviceUrl?: string; } export interface IWorkflowSettings { dockerSocket?: string; } export interface IDuoConfig { enabledWithoutGitlabProject?: boolean; } export interface IClientConfig { /** GitLab API URL used for getting code suggestions */ baseUrl?: string; /** Full project path. */ projectPath?: string; /** PAT or OAuth token used to authenticate to GitLab API */ token?: string; /** The base URL for language server assets in the client-side extension */ baseAssetsUrl?: string; clientInfo?: IClientInfo; // FIXME: this key should be codeSuggestions (we have code completion and code generation) codeCompletion?: ICodeCompletionConfig; openTabsContext?: boolean; telemetry?: ITelemetryOptions; /** Config used for caching code suggestions */ suggestionsCache?: ISuggestionsCacheOptions; workspaceFolders?: WorkspaceFolder[] | null; /** Collection of Feature Flag values which are sent from the client */ featureFlags?: Record; logLevel?: LogLevel; ignoreCertificateErrors?: boolean; httpAgentOptions?: IHttpAgentOptions; snowplowTrackerOptions?: ISnowplowTrackerOptions; // TODO: move to `duo` duoWorkflowSettings?: IWorkflowSettings; securityScannerOptions?: ISecurityScannerOptions; duo?: IDuoConfig; } export interface IConfig { // TODO: we can possibly remove this extra level of config and move all IClientConfig properties to IConfig client: IClientConfig; } /** * ConfigService manages user configuration (e.g. baseUrl) and application state (e.g. codeCompletion.enabled) * TODO: Maybe in the future we would like to separate these two */ export interface ConfigService { get: TypedGetter; /** * set sets the property of the config * the new value completely overrides the old one */ set: TypedSetter; onConfigChange(listener: (config: IConfig) => void): Disposable; /** * merge adds `newConfig` properties into existing config, if the * property is present in both old and new config, `newConfig` * properties take precedence unless not defined * * This method performs deep merge * * **Arrays are not merged; they are replaced with the new value.** * */ merge(newConfig: Partial): void; } export const ConfigService = createInterfaceId('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 = (key?: string) => { return key ? get(this.#config, key) : this.#config; }; set: TypedSetter = (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) { mergeWith(this.#config, newConfig, (target, src) => (isArray(target) ? src : undefined)); this.#triggerChange(); } } References: - src/common/config_service.ts:70" You are a code assistant,Definition of 'Processor1' in file src/common/suggestion_client/post_processors/post_processor_pipeline.test.ts in project gitlab-lsp,"Definition: class Processor1 extends PostProcessor { async processStream( _context: IDocContext, input: StreamingCompletionResponse, ): Promise { return { ...input, completion: `${input.completion} [1]` }; } async processCompletion( _context: IDocContext, input: SuggestionOption[], ): Promise { return input; } } class Processor2 extends PostProcessor { async processStream( _context: IDocContext, input: StreamingCompletionResponse, ): Promise { return { ...input, completion: `${input.completion} [2]` }; } async processCompletion( _context: IDocContext, input: SuggestionOption[], ): Promise { return input; } } pipeline.addProcessor(new Processor1()); pipeline.addProcessor(new Processor2()); const streamInput: StreamingCompletionResponse = { id: '1', completion: 'test', done: false }; const result = await pipeline.run({ documentContext: mockContext, input: streamInput, type: 'stream', }); expect(result).toEqual({ id: '1', completion: 'test [1] [2]', done: false }); }); test('should chain multiple processors correctly for completion input', async () => { class Processor1 extends PostProcessor { async processStream( _context: IDocContext, input: StreamingCompletionResponse, ): Promise { return input; } async processCompletion( _context: IDocContext, input: SuggestionOption[], ): Promise { return input.map((option) => ({ ...option, text: `${option.text} [1]` })); } } class Processor2 extends PostProcessor { async processStream( _context: IDocContext, input: StreamingCompletionResponse, ): Promise { return input; } async processCompletion( _context: IDocContext, input: SuggestionOption[], ): Promise { return input.map((option) => ({ ...option, text: `${option.text} [2]` })); } } pipeline.addProcessor(new Processor1()); pipeline.addProcessor(new Processor2()); const completionInput: SuggestionOption[] = [{ text: 'option1', uniqueTrackingId: '1' }]; const result = await pipeline.run({ documentContext: mockContext, input: completionInput, type: 'completion', }); expect(result).toEqual([{ text: 'option1 [1] [2]', uniqueTrackingId: '1' }]); }); test('should throw an error for unexpected type', async () => { class TestProcessor extends PostProcessor { async processStream( _context: IDocContext, input: StreamingCompletionResponse, ): Promise { return input; } async processCompletion( _context: IDocContext, input: SuggestionOption[], ): Promise { 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: - src/common/suggestion_client/post_processors/post_processor_pipeline.test.ts:162 - src/common/suggestion_client/post_processors/post_processor_pipeline.test.ts:116" You are a code assistant,Definition of 'lintMr' in file scripts/commit-lint/lint.js in project gitlab-lsp,"Definition: async function lintMr() { const commits = await getCommitsInMr(); // When MR is set to squash, but it's not yet being merged, we check the MR Title if ( CI_MERGE_REQUEST_SQUASH_ON_MERGE === 'true' && CI_MERGE_REQUEST_EVENT_TYPE !== 'merge_train' ) { console.log( 'INFO: The MR is set to squash. We will lint the MR Title (used as the commit message by default).', ); return isConventional(CI_MERGE_REQUEST_TITLE).then(Array.of); } console.log('INFO: Checking all commits that will be added by this MR.'); return Promise.all(commits.map(isConventional)); } 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/commit-lint/lint.js:83" You are a code assistant,Definition of 'greet' in file src/tests/fixtures/intent/empty_function/python.py in project gitlab-lsp,"Definition: def greet(self): class Greet3: References: - src/tests/fixtures/intent/empty_function/ruby.rb:20 - 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" You are a code assistant,Definition of 'getChatSupport' in file packages/webview_duo_chat/src/plugin/port/chat/api/get_chat_support.ts in project gitlab-lsp,"Definition: export async function getChatSupport( platform?: GitLabPlatformForAccount | undefined, ): Promise { const request: GraphQLRequest = { type: 'graphql', query: queryGetChatAvailability, variables: {}, }; const noSupportResponse: ChatSupportResponseInterface = { hasSupportForChat: false }; if (!platform) { return noSupportResponse; } try { const { currentUser: { duoChatAvailable }, } = await platform.fetchFromApi(request); if (duoChatAvailable) { return { hasSupportForChat: duoChatAvailable, platform, }; } return noSupportResponse; } catch (e) { log.error(e as Error); return noSupportResponse; } } References: - packages/webview_duo_chat/src/plugin/port/chat/api/get_chat_support.test.ts:31 - packages/webview_duo_chat/src/plugin/port/chat/api/get_chat_support.test.ts:40 - packages/webview_duo_chat/src/plugin/port/chat/api/get_chat_support.test.ts:59 - packages/webview_duo_chat/src/plugin/port/chat/api/get_chat_support.test.ts:33 - packages/webview_duo_chat/src/plugin/port/chat/api/get_chat_support.test.ts:52" You are a code assistant,Definition of 'AiContextPolicy' in file src/common/ai_context_management_2/policies/ai_context_policy.ts in project gitlab-lsp,"Definition: export interface AiContextPolicy { isAllowed(aiProviderItem: AiContextProviderItem): Promise<{ allowed: boolean; reason?: string; }>; } References:" You are a code assistant,Definition of 'GenerateTokenResponse' in file src/node/duo_workflow/desktop_workflow_runner.ts in project gitlab-lsp,"Definition: interface GenerateTokenResponse { gitlab_rails: { base_url: string; token: string; }; duo_workflow_service: { base_url: string; token: string; headers: { 'X-Gitlab-Host-Name': string; 'X-Gitlab-Instance-Id': string; 'X-Gitlab-Realm': string; 'X-Gitlab-Version': string; 'X-Gitlab-Global-User-Id': string; }; }; } interface CreateWorkflowResponse { id: string; } const DuoWorkflowAPIService = createInterfaceId('WorkflowAPI'); @Injectable(DuoWorkflowAPIService, [ConfigService, LsFetch, GitLabApiClient]) export class DesktopWorkflowRunner implements WorkflowAPI { #dockerSocket?: string; #folders?: WorkspaceFolder[]; #fetch: LsFetch; #api: GitLabApiClient; #projectPath: string | undefined; constructor(configService: ConfigService, fetch: LsFetch, api: GitLabApiClient) { this.#fetch = fetch; this.#api = api; configService.onConfigChange((config) => this.#reconfigure(config)); } #reconfigure(config: IConfig) { this.#dockerSocket = config.client.duoWorkflowSettings?.dockerSocket; this.#folders = config.client.workspaceFolders || []; this.#projectPath = config.client.projectPath; } async runWorkflow(goal: string, image: string): Promise { if (!this.#dockerSocket) { throw new Error('Docker socket not configured'); } if (!this.#folders || this.#folders.length === 0) { throw new Error('No workspace folders'); } const executorPath = path.join( __dirname, `../vendor/duo_workflow_executor-${WORKFLOW_EXECUTOR_VERSION}.tar.gz`, ); await this.#downloadWorkflowExecutor(executorPath); const folderName = this.#folders[0].uri.replace(/^file:\/\//, ''); if (this.#folders.length > 0) { log.info(`More than one workspace folder detected. Using workspace folder ${folderName}`); } const workflowID = await this.#createWorkflow(); const workflowToken = await this.#getWorkflowToken(); const containerOptions = { Image: image, Cmd: [ '/duo-workflow-executor', `--workflow-id=${workflowID}`, '--server', workflowToken.duo_workflow_service.base_url || 'localhost:50052', '--goal', goal, '--base-url', workflowToken.gitlab_rails.base_url, '--token', workflowToken.gitlab_rails.token, '--duo-workflow-service-token', workflowToken.duo_workflow_service.token, '--realm', workflowToken.duo_workflow_service.headers['X-Gitlab-Realm'], '--user-id', workflowToken.duo_workflow_service.headers['X-Gitlab-Global-User-Id'], ], HostConfig: { Binds: [`${folderName}:/workspace`], }, }; // Create a container const createResponse = JSON.parse( await this.#makeRequest('/v1.43/containers/create', 'POST', JSON.stringify(containerOptions)), ); // Check if Id in createResponse if (!createResponse.Id) { throw new Error('Failed to create container: No Id in response'); } const containerID = createResponse.Id; // Copy the executor into the container await this.#copyExecutor(containerID, executorPath); // Start the container await this.#makeRequest(`/v1.43/containers/${containerID}/start`, 'POST', ''); return workflowID; } async #copyExecutor(containerID: string, executorPath: string) { const fileContents = await readFile(executorPath); await this.#makeRequest( `/v1.43/containers/${containerID}/archive?path=/`, 'PUT', fileContents, 'application/x-tar', ); } #makeRequest( apiPath: string, method: string, data: string | Buffer, contentType = 'application/json', ): Promise { return new Promise((resolve, reject) => { if (!this.#dockerSocket) { throw new Error('Docker socket not set'); } const options: http.RequestOptions = { socketPath: this.#dockerSocket, path: apiPath, method, headers: { 'Content-Type': contentType, 'Content-Length': Buffer.byteLength(data), }, }; const callback = (res: http.IncomingMessage) => { res.setEncoding('utf-8'); res.on('data', (content) => resolve(content)); res.on('error', (err) => reject(err)); res.on('end', () => { resolve(''); }); }; const clientRequest = http.request(options, callback); clientRequest.write(data); clientRequest.end(); }); } async #downloadWorkflowExecutor(executorPath: string): Promise { try { await readFile(executorPath); } catch (error) { log.info('Downloading workflow executor...'); await this.#downloadFile(executorPath); } } async #downloadFile(outputPath: string): Promise { const response = await this.#fetch.fetch(WORKFLOW_EXECUTOR_DOWNLOAD_PATH, { method: 'GET', headers: { 'Content-Type': 'application/octet-stream', }, }); if (!response.ok) { throw new Error(`Failed to download file: ${response.statusText}`); } const buffer = await response.arrayBuffer(); await writeFile(outputPath, Buffer.from(buffer)); } async #createWorkflow(): Promise { const response = await this.#api?.fetchFromApi({ type: 'rest', method: 'POST', path: '/ai/duo_workflows/workflows', body: { project_id: this.#projectPath, }, supportedSinceInstanceVersion: { resourceName: 'create a workflow', version: '17.3.0', }, }); if (!response) { throw new Error('Failed to create workflow'); } return response.id; } async #getWorkflowToken(): Promise { const token = await this.#api?.fetchFromApi({ type: 'rest', method: 'POST', path: '/ai/duo_workflows/direct_access', supportedSinceInstanceVersion: { resourceName: 'get workflow direct access', version: '17.3.0', }, }); if (!token) { throw new Error('Failed to get workflow token'); } return token; } } References:" You are a code assistant,Definition of 'ApiRequest' in file packages/webview_duo_chat/src/plugin/types.ts in project gitlab-lsp,"Definition: export type ApiRequest<_TReturnType> = | GetRequest<_TReturnType> | PostRequest<_TReturnType> | GraphQLRequest<_TReturnType>; export interface GitLabApiClient { fetchFromApi(request: ApiRequest): Promise; connectToCable(): Promise; } References:" You are a code assistant,Definition of 'FastifyInstance' in file src/node/http/plugin/fastify_socket_io_plugin.ts in project gitlab-lsp,"Definition: interface FastifyInstance { io: Server; } } References: - src/node/webview/handlers/webview_handler.ts:27 - src/node/http/utils/register_static_plugin_safely.ts:5 - src/node/http/create_fastify_http_server.ts:72 - src/node/webview/routes/webview_routes.ts:15 - src/node/http/create_fastify_http_server.ts:56 - src/node/http/fastify_utilities.ts:4 - src/node/http/create_fastify_http_server.ts:14" You are a code assistant,Definition of 'DuoChatPluginFactoryParams' in file packages/webview_duo_chat/src/plugin/index.ts in project gitlab-lsp,"Definition: type DuoChatPluginFactoryParams = { gitlabApiClient: GitLabApiClient; }; export const duoChatPluginFactory = ({ gitlabApiClient, }: DuoChatPluginFactoryParams): WebviewPlugin => ({ id: WEBVIEW_ID, title: WEBVIEW_TITLE, setup: ({ webview, extension }) => { const platformManager = new ChatPlatformManager(gitlabApiClient); const gitlabPlatformManagerForChat = new GitLabPlatformManagerForChat(platformManager); webview.onInstanceConnected((_, webviewMessageBus) => { const controller = new GitLabChatController( gitlabPlatformManagerForChat, webviewMessageBus, extension, ); return { dispose: () => { controller.dispose(); }, }; }); }, }); References: - packages/webview_duo_chat/src/plugin/index.ts:14" You are a code assistant,Definition of 'OAuthToken' in file src/common/api.ts in project gitlab-lsp,"Definition: export interface OAuthToken { scope: string[]; } export interface TokenCheckResponse { valid: boolean; reason?: 'unknown' | 'not_active' | 'invalid_scopes'; message?: string; } export interface IDirectConnectionDetailsHeaders { 'X-Gitlab-Global-User-Id': string; 'X-Gitlab-Instance-Id': string; 'X-Gitlab-Host-Name': string; 'X-Gitlab-Saas-Duo-Pro-Namespace-Ids': string; } export interface IDirectConnectionModelDetails { model_provider: string; model_name: string; } export interface IDirectConnectionDetails { base_url: string; token: string; expires_at: number; headers: IDirectConnectionDetailsHeaders; model_details: IDirectConnectionModelDetails; } const CONFIG_CHANGE_EVENT_NAME = 'apiReconfigured'; @Injectable(GitLabApiClient, [LsFetch, ConfigService]) export class GitLabAPI implements GitLabApiClient { #token: string | undefined; #baseURL: string; #clientInfo?: IClientInfo; #lsFetch: LsFetch; #eventEmitter = new EventEmitter(); #configService: ConfigService; #instanceVersion?: string; constructor(lsFetch: LsFetch, configService: ConfigService) { this.#baseURL = GITLAB_API_BASE_URL; this.#lsFetch = lsFetch; this.#configService = configService; this.#configService.onConfigChange(async (config) => { this.#clientInfo = configService.get('client.clientInfo'); this.#lsFetch.updateAgentOptions({ ignoreCertificateErrors: this.#configService.get('client.ignoreCertificateErrors') ?? false, ...(this.#configService.get('client.httpAgentOptions') ?? {}), }); await this.configureApi(config.client); }); } onApiReconfigured(listener: (data: ApiReconfiguredData) => void): Disposable { this.#eventEmitter.on(CONFIG_CHANGE_EVENT_NAME, listener); return { dispose: () => this.#eventEmitter.removeListener(CONFIG_CHANGE_EVENT_NAME, listener) }; } #fireApiReconfigured(isInValidState: boolean, validationMessage?: string) { const data: ApiReconfiguredData = { isInValidState, validationMessage }; this.#eventEmitter.emit(CONFIG_CHANGE_EVENT_NAME, data); } async configureApi({ token, baseUrl = GITLAB_API_BASE_URL, }: { token?: string; baseUrl?: string; }) { if (this.#token === token && this.#baseURL === baseUrl) return; this.#token = token; this.#baseURL = baseUrl; const { valid, reason, message } = await this.checkToken(this.#token); let validationMessage; if (!valid) { this.#configService.set('client.token', undefined); validationMessage = `Token is invalid. ${message}. Reason: ${reason}`; log.warn(validationMessage); } else { log.info('Token is valid'); } this.#instanceVersion = await this.#getGitLabInstanceVersion(); this.#fireApiReconfigured(valid, validationMessage); } #looksLikePatToken(token: string): boolean { // OAuth tokens will be longer than 42 characters and PATs will be shorter. return token.length < 42; } async #checkPatToken(token: string): Promise { const headers = this.#getDefaultHeaders(token); const response = await this.#lsFetch.get( `${this.#baseURL}/api/v4/personal_access_tokens/self`, { headers }, ); await handleFetchError(response, 'Information about personal access token'); const { active, scopes } = (await response.json()) as PersonalAccessToken; if (!active) { return { valid: false, reason: 'not_active', message: 'Token is not active.', }; } if (!this.#hasValidScopes(scopes)) { const joinedScopes = scopes.map((scope) => `'${scope}'`).join(', '); return { valid: false, reason: 'invalid_scopes', message: `Token has scope(s) ${joinedScopes} (needs 'api').`, }; } return { valid: true }; } async #checkOAuthToken(token: string): Promise { const headers = this.#getDefaultHeaders(token); const response = await this.#lsFetch.get(`${this.#baseURL}/oauth/token/info`, { headers, }); await handleFetchError(response, 'Information about OAuth token'); const { scope: scopes } = (await response.json()) as OAuthToken; if (!this.#hasValidScopes(scopes)) { const joinedScopes = scopes.map((scope) => `'${scope}'`).join(', '); return { valid: false, reason: 'invalid_scopes', message: `Token has scope(s) ${joinedScopes} (needs 'api').`, }; } return { valid: true }; } async checkToken(token: string = ''): Promise { try { if (this.#looksLikePatToken(token)) { log.info('Checking token for PAT validity'); return await this.#checkPatToken(token); } log.info('Checking token for OAuth validity'); return await this.#checkOAuthToken(token); } catch (err) { log.error('Error performing token check', err); return { valid: false, reason: 'unknown', message: `Failed to check token: ${err}`, }; } } #hasValidScopes(scopes: string[]): boolean { return scopes.includes('api'); } async getCodeSuggestions( request: CodeSuggestionRequest, ): Promise { if (!this.#token) { throw new Error('Token needs to be provided to request Code Suggestions'); } const headers = { ...this.#getDefaultHeaders(this.#token), 'Content-Type': 'application/json', }; const response = await this.#lsFetch.post( `${this.#baseURL}/api/v4/code_suggestions/completions`, { headers, body: JSON.stringify(request) }, ); await handleFetchError(response, 'Code Suggestions'); const data = await response.json(); return { ...data, status: response.status }; } async *getStreamingCodeSuggestions( request: CodeSuggestionRequest, ): AsyncGenerator { if (!this.#token) { throw new Error('Token needs to be provided to stream code suggestions'); } const headers = { ...this.#getDefaultHeaders(this.#token), 'Content-Type': 'application/json', }; yield* this.#lsFetch.streamFetch( `${this.#baseURL}/api/v4/code_suggestions/completions`, JSON.stringify(request), headers, ); } async fetchFromApi(request: ApiRequest): Promise { if (!this.#token) { return Promise.reject(new Error('Token needs to be provided to authorise API request.')); } if ( request.supportedSinceInstanceVersion && !this.#instanceVersionHigherOrEqualThen(request.supportedSinceInstanceVersion.version) ) { return Promise.reject( new InvalidInstanceVersionError( `Can't ${request.supportedSinceInstanceVersion.resourceName} until your instance is upgraded to ${request.supportedSinceInstanceVersion.version} or higher.`, ), ); } if (request.type === 'graphql') { return this.#graphqlRequest(request.query, request.variables); } switch (request.method) { case 'GET': return this.#fetch(request.path, request.searchParams, 'resource', request.headers); case 'POST': return this.#postFetch(request.path, 'resource', request.body, request.headers); default: // the type assertion is necessary because TS doesn't expect any other types throw new Error(`Unknown request type ${(request as ApiRequest).type}`); } } async connectToCable(): Promise { const headers = this.#getDefaultHeaders(this.#token); const websocketOptions = { headers: { ...headers, Origin: this.#baseURL, }, }; return connectToCable(this.#baseURL, websocketOptions); } async #graphqlRequest( document: RequestDocument, variables?: V, ): Promise { const ensureEndsWithSlash = (url: string) => url.replace(/\/?$/, '/'); const endpoint = new URL('./api/graphql', ensureEndsWithSlash(this.#baseURL)).href; // supports GitLab instances that are on a custom path, e.g. ""https://example.com/gitlab"" const graphqlFetch = async ( input: RequestInfo | URL, init?: RequestInit, ): Promise => { const url = input instanceof URL ? input.toString() : input; return this.#lsFetch.post(url, { ...init, headers: { ...headers, ...init?.headers }, }); }; const headers = this.#getDefaultHeaders(this.#token); const client = new GraphQLClient(endpoint, { headers, fetch: graphqlFetch, }); return client.request(document, variables); } async #fetch( apiResourcePath: string, query: Record = {}, resourceName = 'resource', headers?: Record, ): Promise { const url = `${this.#baseURL}/api/v4${apiResourcePath}${createQueryString(query)}`; const result = await this.#lsFetch.get(url, { headers: { ...this.#getDefaultHeaders(this.#token), ...headers }, }); await handleFetchError(result, resourceName); return result.json() as Promise; } async #postFetch( apiResourcePath: string, resourceName = 'resource', body?: unknown, headers?: Record, ): Promise { const url = `${this.#baseURL}/api/v4${apiResourcePath}`; const response = await this.#lsFetch.post(url, { headers: { 'Content-Type': 'application/json', ...this.#getDefaultHeaders(this.#token), ...headers, }, body: JSON.stringify(body), }); await handleFetchError(response, resourceName); return response.json() as Promise; } #getDefaultHeaders(token?: string) { return { Authorization: `Bearer ${token}`, 'User-Agent': `code-completions-language-server-experiment (${this.#clientInfo?.name}:${this.#clientInfo?.version})`, 'X-Gitlab-Language-Server-Version': getLanguageServerVersion(), }; } #instanceVersionHigherOrEqualThen(version: string): boolean { if (!this.#instanceVersion) return false; return semverCompare(this.#instanceVersion, version) >= 0; } async #getGitLabInstanceVersion(): Promise { if (!this.#token) { return ''; } const headers = this.#getDefaultHeaders(this.#token); const response = await this.#lsFetch.get(`${this.#baseURL}/api/v4/version`, { headers, }); const { version } = await response.json(); return version; } get instanceVersion() { return this.#instanceVersion; } } 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; } export const DuoProjectAccessChecker = createInterfaceId('DuoProjectAccessChecker'); @Injectable(DuoProjectAccessChecker, [DuoProjectAccessCache]) export class DefaultDuoProjectAccessChecker { #projectAccessCache: DuoProjectAccessCache; constructor(projectAccessCache: DuoProjectAccessCache) { this.#projectAccessCache = projectAccessCache; } /** * Check if Duo features are enabled for a given DocumentUri. * * We match the DocumentUri to the project with the longest path. * The enabled projects come from the `DuoProjectAccessCache`. * * @reference `DocumentUri` is the URI of the document to check. Comes from * the `TextDocument` object. */ 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 'DuoWorkflowEvents' in file src/common/graphql/workflow/types.ts in project gitlab-lsp,"Definition: export type DuoWorkflowEvents = { nodes: LangGraphCheckpoint[]; }; export type DuoWorkflowEventConnectionType = { duoWorkflowEvents: DuoWorkflowEvents; }; References: - packages/webview_duo_workflow/src/types.ts:10 - src/common/graphql/workflow/types.ts:10" You are a code assistant,Definition of 'WebviewConnection' in file packages/lib_webview_plugin/src/types.ts in project gitlab-lsp,"Definition: export interface WebviewConnection { broadcast: ( type: TMethod, payload: T['outbound']['notifications'][TMethod], ) => void; onInstanceConnected: (handler: WebviewMessageBusManagerHandler) => void; } References:" You are a code assistant,Definition of 'destroyInstance' in file src/common/advanced_context/context_resolvers/open_tabs_context_resolver.ts in project gitlab-lsp,"Definition: public static destroyInstance(): void { OpenTabsResolver.#instance = undefined; } async *buildContext({ documentContext, includeCurrentFile = false, }: { documentContext?: IDocContext; includeCurrentFile?: boolean; }): AsyncGenerator { const lruCache = LruCache.getInstance(LRU_CACHE_BYTE_SIZE_LIMIT); const openFiles = lruCache.mostRecentFiles({ context: documentContext, includeCurrentFile, }); for (const file of openFiles) { yield { uri: file.uri, type: 'file' as const, content: `${file.prefix}${file.suffix}`, fileRelativePath: file.fileRelativePath, strategy: 'open_tabs' as const, workspaceFolder: file.workspaceFolder ?? { name: '', uri: '' }, }; } } } References:" You are a code assistant,Definition of 'getProviderItems' in file src/common/ai_context_management_2/providers/ai_file_context_provider.ts in project gitlab-lsp,"Definition: async getProviderItems( query: string, workspaceFolders: WorkspaceFolder[], ): Promise { const items = query.trim() === '' ? await this.#getOpenTabsItems() : await this.#getSearchedItems(query, workspaceFolders); log.info(`Found ${items.length} results for ${query}`); return items; } async #getOpenTabsItems(): Promise { const resolutions: ContextResolution[] = []; for await (const resolution of OpenTabsResolver.getInstance().buildContext({ includeCurrentFile: true, })) { resolutions.push(resolution); } return resolutions.map((resolution) => this.#providerItemForOpenTab(resolution)); } async #getSearchedItems( query: string, workspaceFolders: WorkspaceFolder[], ): Promise { const allFiles: RepositoryFile[] = []; for (const folder of workspaceFolders) { const files = this.#repositoryService.getFilesForWorkspace(folder.uri, { excludeGitFolder: true, excludeIgnored: true, }); allFiles.push(...files); } const fileNames = allFiles.map((file) => file.uri.fsPath); const allFilesMap = new Map(allFiles.map((file) => [file.uri.fsPath, file])); const results = filter(fileNames, query, { maxResults: 100 }); const resultFiles: RepositoryFile[] = []; for (const result of results) { if (allFilesMap.has(result)) { resultFiles.push(allFilesMap.get(result) as RepositoryFile); } } return resultFiles.map((file) => this.#providerItemForSearchResult(file)); } #openTabResolutionToRepositoryFile(resolution: ContextResolution): [URI, RepositoryFile | null] { const fileUri = parseURIString(resolution.uri); const repo = this.#repositoryService.findMatchingRepositoryUri( fileUri, resolution.workspaceFolder, ); if (!repo) { log.warn(`Could not find repository for ${resolution.uri}`); return [fileUri, null]; } const repositoryFile = this.#repositoryService.getRepositoryFileForUri( fileUri, repo, resolution.workspaceFolder, ); if (!repositoryFile) { log.warn(`Could not find repository file for ${resolution.uri}`); return [fileUri, null]; } return [fileUri, repositoryFile]; } #providerItemForOpenTab(resolution: ContextResolution): AiContextProviderItem { const [fileUri, repositoryFile] = this.#openTabResolutionToRepositoryFile(resolution); return { fileUri, workspaceFolder: resolution.workspaceFolder, providerType: 'file', subType: 'open_tab', repositoryFile, }; } #providerItemForSearchResult(repositoryFile: RepositoryFile): AiContextProviderItem { return { fileUri: repositoryFile.uri, workspaceFolder: repositoryFile.workspaceFolder, providerType: 'file', subType: 'local_file_search', repositoryFile, }; } } References:" You are a code assistant,Definition of 'isFileIgnored' in file src/common/git/repository.ts in project gitlab-lsp,"Definition: isFileIgnored(filePath: URI): boolean { return this.#ignoreManager.isIgnored(filePath.fsPath); } setFile(fileUri: URI): void { if (!this.isFileIgnored(fileUri)) { this.#files.set(fileUri.toString(), { uri: fileUri, isIgnored: false, repositoryUri: this.uri, workspaceFolder: this.workspaceFolder, }); } else { this.#files.set(fileUri.toString(), { uri: fileUri, isIgnored: true, repositoryUri: this.uri, workspaceFolder: this.workspaceFolder, }); } } getFile(fileUri: string): RepositoryFile | undefined { return this.#files.get(fileUri); } removeFile(fileUri: string): void { this.#files.delete(fileUri); } getFiles(): Map { return this.#files; } dispose(): void { this.#ignoreManager.dispose(); this.#files.clear(); } } References:" You are a code assistant,Definition of 'setup' in file scripts/esbuild/helpers.ts in project gitlab-lsp,"Definition: setup(build) { console.log('[fixWebviewPath] plugin initialized'); build.onLoad({ filter: /.*[/\\]webview[/\\]constants\.ts/ }, ({ path: filePath }) => { console.log('[fixWebviewPath] File load attempt:', filePath); if (!filePath.match(/.*[/\\]?node_modules[/\\].*?/)) { console.log('[fixWebviewPath] Modifying file:', filePath); let contents = readFileSync(filePath, 'utf8'); contents = contents.replaceAll( ""WEBVIEW_BASE_PATH = path.join(__dirname, '../../../out/webviews/');"", ""WEBVIEW_BASE_PATH = path.join(__dirname, '../webviews/');"", ); return { contents, loader: extname(filePath).substring(1) as Loader, }; } else { console.log('[fixWebviewPath] Skipping file:', filePath); } return null; }); }, } satisfies Plugin; const setLanguageServerVersionPlugin = { name: 'setLanguageServerVersion', setup(build) { build.onLoad({ filter: /[/\\]get_language_server_version\.ts$/ }, ({ path: filePath }) => { if (!filePath.match(nodeModulesRegex)) { let contents = readFileSync(filePath, 'utf8'); contents = contents.replaceAll( '{{GITLAB_LANGUAGE_SERVER_VERSION}}', packageJson['version'], ); return { contents, loader: extname(filePath).substring(1) as Loader, }; } return null; }); }, } satisfies Plugin; export { fixVendorGrammarsPlugin, fixWebviewPathPlugin, setLanguageServerVersionPlugin, wasmEntryPoints, }; References: - src/common/connection.test.ts:43 - src/browser/main.ts:122 - src/node/main.ts:197" You are a code assistant,Definition of 'openFiles' in file src/common/advanced_context/lru_cache.ts in project gitlab-lsp,"Definition: get openFiles() { return this.#cache; } #getDocumentSize(context: IDocContext): number { const size = getByteSize(`${context.prefix}${context.suffix}`); return Math.max(1, size); } /** * Update the file in the cache. * Uses lru-cache under the hood. */ updateFile(context: IDocContext) { return this.#cache.set(context.uri, context); } /** * @returns `true` if the file was deleted, `false` if the file was not found */ deleteFile(uri: DocumentUri): boolean { return this.#cache.delete(uri); } /** * Get the most recently accessed files in the workspace * @param context - The current document context `IDocContext` * @param includeCurrentFile - Include the current file in the list of most recent files, default is `true` */ mostRecentFiles({ context, includeCurrentFile = true, }: { context?: IDocContext; includeCurrentFile?: boolean; }): IDocContext[] { const files = Array.from(this.#cache.values()); if (includeCurrentFile) { return files; } return files.filter( (file) => context?.workspaceFolder?.uri === file.workspaceFolder?.uri && file.uri !== context?.uri, ); } } References:" You are a code assistant,Definition of 'EmptyFunctionResolver' in file src/common/tree_sitter/empty_function/empty_function_resolver.ts in project gitlab-lsp,"Definition: export class EmptyFunctionResolver { protected queryByLanguage: Map; constructor() { this.queryByLanguage = new Map(); } #getQueryByLanguage( language: TreeSitterLanguageName, treeSitterLanguage: Language, ): Query | undefined { const query = this.queryByLanguage.get(language); if (query) { return query; } const queryString = emptyFunctionQueries[language]; if (!queryString) { log.warn(`No empty function query found for: ${language}`); return undefined; } const newQuery = treeSitterLanguage.query(queryString); this.queryByLanguage.set(language, newQuery); return newQuery; } /** * Returns the comment that is directly above the cursor, if it exists. * To handle the case the comment may be several new lines above the cursor, * we traverse the tree to check if any nodes are between the comment and the cursor. */ isCursorInEmptyFunction({ languageName, tree, cursorPosition, treeSitterLanguage, }: { languageName: TreeSitterLanguageName; tree: Tree; treeSitterLanguage: Language; cursorPosition: Point; }): boolean { const query = this.#getQueryByLanguage(languageName, treeSitterLanguage); if (!query) { return false; } const emptyBodyPositions = query.captures(tree.rootNode).map((capture) => { return EmptyFunctionResolver.#findEmptyBodyPosition(capture.node); }); const cursorInsideInOneOfTheCaptures = emptyBodyPositions.some( (emptyBody) => EmptyFunctionResolver.#isValidBodyPosition(emptyBody) && EmptyFunctionResolver.#isCursorInsideNode( cursorPosition, emptyBody.startPosition, emptyBody.endPosition, ), ); return ( cursorInsideInOneOfTheCaptures || EmptyFunctionResolver.isCursorAfterEmptyPythonFunction({ languageName, tree, treeSitterLanguage, cursorPosition, }) ); } static #isCursorInsideNode( cursorPosition: Point, startPosition: Point, endPosition: Point, ): boolean { const { row: cursorRow, column: cursorColumn } = cursorPosition; const isCursorAfterNodeStart = cursorRow > startPosition.row || (cursorRow === startPosition.row && cursorColumn >= startPosition.column); const isCursorBeforeNodeEnd = cursorRow < endPosition.row || (cursorRow === endPosition.row && cursorColumn <= endPosition.column); return isCursorAfterNodeStart && isCursorBeforeNodeEnd; } static #isCursorRightAfterNode(cursorPosition: Point, endPosition: Point): boolean { const { row: cursorRow, column: cursorColumn } = cursorPosition; const isCursorRightAfterNode = cursorRow - endPosition.row === 1 || (cursorRow === endPosition.row && cursorColumn > endPosition.column); return isCursorRightAfterNode; } static #findEmptyBodyPosition(node: SyntaxNode): { startPosition?: Point; endPosition?: Point } { const startPosition = node.lastChild?.previousSibling?.endPosition; const endPosition = node.lastChild?.startPosition; return { startPosition, endPosition }; } static #isValidBodyPosition(arg: { startPosition?: Point; endPosition?: Point; }): arg is { startPosition: Point; endPosition: Point } { return !isUndefined(arg.startPosition) && !isUndefined(arg.endPosition); } static isCursorAfterEmptyPythonFunction({ languageName, tree, cursorPosition, treeSitterLanguage, }: { languageName: TreeSitterLanguageName; tree: Tree; treeSitterLanguage: Language; cursorPosition: Point; }): boolean { if (languageName !== 'python') return false; const pythonQuery = treeSitterLanguage.query(`[ (function_definition) (class_definition) ] @function`); const captures = pythonQuery.captures(tree.rootNode); if (captures.length === 0) return false; // Check if any function or class body is empty and cursor is after it return captures.some((capture) => { const bodyNode = capture.node.childForFieldName('body'); return ( bodyNode?.childCount === 0 && EmptyFunctionResolver.#isCursorRightAfterNode(cursorPosition, capture.node.endPosition) ); }); } } let emptyFunctionResolver: EmptyFunctionResolver; export function getEmptyFunctionResolver(): EmptyFunctionResolver { if (!emptyFunctionResolver) { emptyFunctionResolver = new EmptyFunctionResolver(); } return emptyFunctionResolver; } References: - src/common/tree_sitter/empty_function/empty_function_resolver.ts:153 - src/common/tree_sitter/empty_function/empty_function_resolver.test.ts:9 - src/common/tree_sitter/empty_function/empty_function_resolver.test.ts:16 - src/common/tree_sitter/empty_function/empty_function_resolver.ts:155 - src/common/tree_sitter/empty_function/empty_function_resolver.ts:152" You are a code assistant,Definition of 'SuggestionResponse' in file src/common/suggestion_client/suggestion_client.ts in project gitlab-lsp,"Definition: export interface SuggestionResponse { choices?: SuggestionResponseChoice[]; model?: SuggestionModel; status: number; error?: string; isDirectConnection?: boolean; } export interface SuggestionResponseChoice { text: string; } export interface SuggestionClient { getSuggestions(context: SuggestionContext): Promise; } export type SuggestionClientFn = SuggestionClient['getSuggestions']; export type SuggestionClientMiddleware = ( context: SuggestionContext, next: SuggestionClientFn, ) => ReturnType; References:" You are a code assistant,Definition of 'ResponseError' in file src/common/fetch_error.ts in project gitlab-lsp,"Definition: 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:" You are a code assistant,Definition of 'IDocContext' in file src/common/document_transformer_service.ts in project gitlab-lsp,"Definition: export interface IDocContext { /** * The text before the cursor. */ prefix: string; /** * The text after the cursor. */ suffix: string; /** * This is most likely path to a file relative to the workspace * but if the file doesn't belong to a workspace, this field is identical to document URI * * Example: If the workspace root is `/home/user/workspace` * and the file is `/home/user/workspace/src/file.txt`, * then the filename is `src/file.txt`. */ fileRelativePath: string; position: Position; /** * The URI of the document. */ uri: DocumentUri; /** * languageId of the document * @readonly */ languageId: TextDocument['languageId']; /** * The workspace folder that the document belongs to. */ workspaceFolder?: WorkspaceFolder; } export interface IDocTransformer { transform(context: IDocContext): IDocContext; } const getMatchingWorkspaceFolder = ( fileUri: DocumentUri, workspaceFolders: WorkspaceFolder[], ): WorkspaceFolder | undefined => workspaceFolders.find((wf) => fileUri.startsWith(wf.uri)); const getRelativePath = (fileUri: DocumentUri, workspaceFolder?: WorkspaceFolder): string => { if (!workspaceFolder) { // splitting a string will produce at least one item and so the pop can't return undefined // eslint-disable-next-line @typescript-eslint/no-non-null-assertion return fileUri.split(/[\\/]/).pop()!; } return fileUri.slice(workspaceFolder.uri.length).replace(/^\//, ''); }; export interface DocumentTransformerService { get(uri: string): TextDocument | undefined; getContext( uri: string, position: Position, workspaceFolders: WorkspaceFolder[], completionContext?: InlineCompletionContext, ): IDocContext | undefined; transform(context: IDocContext): IDocContext; } export const DocumentTransformerService = createInterfaceId( 'DocumentTransformerService', ); @Injectable(DocumentTransformerService, [LsTextDocuments, SecretRedactor]) export class DefaultDocumentTransformerService implements DocumentTransformerService { #transformers: IDocTransformer[] = []; #documents: LsTextDocuments; 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: - src/common/test_utils/mocks.ts:62 - src/common/suggestion_client/post_processors/post_processor_pipeline.test.ts:178 - src/common/suggestion/suggestion_service.ts:287 - src/common/advanced_context/context_resolvers/advanced_context_resolver.ts:47 - src/common/advanced_context/context_resolvers/open_tabs_context_resolver.test.ts:10 - src/common/suggestion_client/post_processors/post_processor_pipeline.test.ts:86 - src/common/tracking/instance_tracker.test.ts:15 - src/common/suggestion_client/post_processors/post_processor_pipeline.test.ts:148 - src/common/suggestion_client/post_processors/post_processor_pipeline.test.ts:8 - src/common/tracking/snowplow_tracker.ts:484 - src/common/tracking/snowplow_tracker.test.ts:56 - src/common/advanced_context/lru_cache.test.ts:23 - src/common/suggestion_client/post_processors/post_processor_pipeline.test.ts:93 - src/common/document_transformer_service.ts:103 - src/common/advanced_context/lru_cache.ts:42 - src/common/suggestion_client/post_processors/post_processor_pipeline.test.ts:185 - src/common/test_utils/mocks.ts:7 - src/common/suggestion/suggestion_service.ts:541 - src/common/document_transformer_service.ts:69 - src/common/tracking/tracking_types.ts:8 - src/common/suggestion_client/post_processors/post_processor_pipeline.test.ts:57 - src/common/suggestion/suggestion_service.ts:352 - src/common/suggestion/suggestion_service.ts:510 - src/common/advanced_context/advanced_context_filters.ts:11 - src/common/tree_sitter/parser.test.ts:103 - src/common/suggestion_client/post_processors/post_processor_pipeline.test.ts:28 - src/common/advanced_context/lru_cache.ts:51 - src/common/suggestion/suggestion_service.ts:391 - src/common/suggestion_client/post_processors/post_processor_pipeline.ts:50 - src/common/suggestion_client/post_processors/post_processor_pipeline.test.ts:64 - src/common/advanced_context/lru_cache.ts:71 - src/common/tree_sitter/parser.test.ts:74 - src/common/suggestion_client/post_processors/post_processor_pipeline.test.ts:155 - src/common/suggestion_client/post_processors/post_processor_pipeline.ts:28 - src/common/advanced_context/advanced_context_factory.ts:23 - src/common/suggestion/suggestion_service.ts:325 - src/common/suggestion_client/post_processors/post_processor_pipeline.test.ts:132 - src/common/suggestion/suggestions_cache.ts:22 - src/common/suggestion_client/post_processors/post_processor_pipeline.ts:22 - src/common/document_transformer_service.ts:113 - src/common/document_transformer_service.ts:44 - src/common/suggestion_client/post_processors/post_processor_pipeline.test.ts:109 - src/common/tree_sitter/parser.ts:37 - src/common/suggestion_client/suggestion_client.ts:20 - src/common/test_utils/mocks.ts:38 - src/common/test_utils/mocks.ts:50 - src/common/secret_redaction/index.ts:28 - src/common/suggestion_client/post_processors/post_processor_pipeline.test.ts:102 - src/common/suggestion/streaming_handler.ts:39 - src/common/advanced_context/context_resolvers/open_tabs_context_resolver.ts:26 - src/common/suggestion_client/post_processors/post_processor_pipeline.test.ts:35 - src/common/suggestion_client/post_processors/post_processor_pipeline.test.ts:139 - src/common/advanced_context/advanced_context_filters.test.ts:17 - src/common/suggestion/streaming_handler.test.ts:33" You are a code assistant,Definition of 'init' in file src/common/diagnostics_publisher.ts in project gitlab-lsp,"Definition: init(publish: DiagnosticsPublisherFn): void; } References:" You are a code assistant,Definition of 'StateCheckChangedEventData' in file src/common/feature_state/state_check.ts in project gitlab-lsp,"Definition: export interface StateCheckChangedEventData { checkId: StateCheckId; engaged: boolean; details?: string; } export interface StateCheck { id: StateCheckId; engaged: boolean; /** registers a listener that's called when the policy changes */ onChanged: (listener: (data: StateCheckChangedEventData) => void) => Disposable; details?: string; } References: - src/common/feature_state/project_duo_acces_check.ts:68 - src/common/feature_state/state_check.ts:14 - src/common/feature_state/supported_language_check.ts:45" You are a code assistant,Definition of 'CodeSuggestionsSupportedLanguageCheck' in file src/common/feature_state/supported_language_check.ts in project gitlab-lsp,"Definition: export const CodeSuggestionsSupportedLanguageCheck = createInterfaceId('CodeSuggestionsSupportedLanguageCheck'); @Injectable(CodeSuggestionsSupportedLanguageCheck, [DocumentService, SupportedLanguagesService]) export class DefaultCodeSuggestionsSupportedLanguageCheck implements StateCheck { #documentService: DocumentService; #isLanguageEnabled = false; #isLanguageSupported = false; #supportedLanguagesService: SupportedLanguagesService; #currentDocument?: TextDocument; #stateEmitter = new EventEmitter(); constructor( documentService: DocumentService, supportedLanguagesService: SupportedLanguagesService, ) { this.#documentService = documentService; this.#supportedLanguagesService = supportedLanguagesService; this.#documentService.onDocumentChange((event, handlerType) => { if (handlerType === TextDocumentChangeListenerType.onDidSetActive) { this.#updateWithDocument(event.document); } }); this.#supportedLanguagesService.onLanguageChange(() => this.#update()); } onChanged(listener: (data: StateCheckChangedEventData) => void): Disposable { this.#stateEmitter.on('change', listener); return { dispose: () => this.#stateEmitter.removeListener('change', listener), }; } #updateWithDocument(document: TextDocument) { this.#currentDocument = document; this.#update(); } get engaged() { return !this.#isLanguageEnabled; } get id() { return this.#isLanguageSupported && !this.#isLanguageEnabled ? DISABLED_LANGUAGE : UNSUPPORTED_LANGUAGE; } details = 'Code suggestions are not supported for this language'; #update() { this.#checkLanguage(); this.#stateEmitter.emit('change', this); } #checkLanguage() { if (!this.#currentDocument) { this.#isLanguageEnabled = false; this.#isLanguageSupported = false; return; } const { languageId } = this.#currentDocument; this.#isLanguageEnabled = this.#supportedLanguagesService.isLanguageEnabled(languageId); this.#isLanguageSupported = this.#supportedLanguagesService.isLanguageSupported(languageId); } } References: - src/common/feature_state/feature_state_manager.ts:28 - src/common/feature_state/supported_language_check.test.ts:22" You are a code assistant,Definition of 'GitLabChatRecordContext' in file packages/webview_duo_chat/src/plugin/port/chat/gitlab_chat_record_context.ts in project gitlab-lsp,"Definition: export type GitLabChatRecordContext = { currentFile: GitLabChatFileContext; }; export const buildCurrentContext = (): GitLabChatRecordContext | undefined => { const currentFile = getActiveFileContext(); if (!currentFile) { return undefined; } return { currentFile }; }; References: - packages/webview_duo_chat/src/plugin/port/chat/gitlab_chat_record.ts:54" You are a code assistant,Definition of 'startTinyProxy' in file src/tests/int/fetch.test.ts in project gitlab-lsp,"Definition: async function startTinyProxy(): Promise { const tinyProxy = spawn(TINYPROXY, ['-d', '-c', TINYPROXY_CONF]); if (tinyProxy == null) { throw new Error('Error, failed to start tinyproxy. tinyProxy == null.'); } if (!tinyProxy?.pid) { throw new Error('Error, failed to start tinyproxy. pid undefined.'); } try { // Wait for tinyproxy to startup await tcpPortUsed.waitUntilUsedOnHost(PROXY_PORT, '127.0.0.1'); } catch (err) { console.error('Timed out checking for proxy port in use.'); if (tinyProxy.exitCode) { console.error(`Tinyproxy exited with code ${tinyProxy.exitCode}. Logs:`); } else { console.warn('Tinyproxy still running. Logs:'); } const data = await readFile(TINYPROXY_LOG, 'utf8'); console.warn(data); throw err; } return tinyProxy; } const cleanupTinyProxy = async (tinyProxy: ChildProcessWithoutNullStreams): Promise => { // Wait a little bit to make sure sockets are // cleaned up in node before we kill our proxy // instance. Otherwise we might get connection // reset exceptions from node. const delay = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); await delay(500); // Try and stop tinyproxy nicely (SIGTERM) tinyProxy.kill(); for (let cnt = 0; cnt < 5 && tinyProxy.exitCode == null; cnt++) { await delay(100); } if (tinyProxy.exitCode == null) { // Kill the process if it didn't exit nicely tinyProxy.kill('SIGKILL'); for (let cnt = 0; cnt < 5 && tinyProxy.exitCode == null; cnt++) { await delay(100); } if (tinyProxy.exitCode == null) { throw new Error('Tinyproxy failed to exit properly.'); } } if (fs.existsSync(TINYPROXY_LOG)) { fs.unlinkSync(TINYPROXY_LOG); } }; describe('LsFetch', () => { it('can make a get request', async () => { const lsFetch = new Fetch(); await lsFetch.initialize(); const resp = await lsFetch.get('https://gitlab.com/'); expect(resp.status).toBe(200); }); describe('proxy Support', () => { it('tinyproxy is installed', () => { expect(hasbinSync(TINYPROXY)).toBeTruthy(); }); describe('when proxy is configured', () => { beforeEach(() => { if (fs.existsSync(TINYPROXY_LOG)) { fs.unlinkSync(TINYPROXY_LOG); } if (process.env.https_proxy) { delete process.env.https_proxy; } if (process.env.http_proxy) { delete process.env.http_proxy; } }); afterEach(() => { if (fs.existsSync(TINYPROXY_LOG)) { fs.unlinkSync(TINYPROXY_LOG); } if (process.env.https_proxy) { delete process.env.https_proxy; } if (process.env.http_proxy) { delete process.env.http_proxy; } }); describe('when proxy not running', () => { it('get should return connection error', async () => { process.env.https_proxy = PROXY; process.env.http_proxy = PROXY; const lsFetch = new Fetch(); await lsFetch.initialize(); try { await expect(() => lsFetch.get('https://gitlab.com/')).rejects.toHaveProperty( 'message', 'request to https://gitlab.com/ failed, reason: connect ECONNREFUSED 127.0.0.1:8888', ); } finally { await lsFetch.destroy(); } }); }); describe('when proxy is running', () => { let tinyProxy: ChildProcessWithoutNullStreams; jest.setTimeout(10 * 1000); beforeEach(async () => { tinyProxy = await startTinyProxy(); }); afterEach(async () => { await cleanupTinyProxy(tinyProxy); }); it('request should happen through proxy', async () => { process.env.https_proxy = PROXY; process.env.http_proxy = PROXY; const lsFetch = new Fetch(); await lsFetch.initialize(); try { const resp = await lsFetch.get('https://gitlab.com/'); await resp.text(); expect(resp.status).toBe(200); expect(await checkLogForRequest('gitlab.com:443')).toBe(true); } finally { await lsFetch.destroy(); } }); }); }); }); }); References: - src/tests/int/fetch.test.ts:143" You are a code assistant,Definition of 'error' in file packages/lib_logging/src/null_logger.ts in project gitlab-lsp,"Definition: error(e: Error): void; error(message: string, e?: Error | undefined): void; error(): void { // NOOP } } References: - scripts/commit-lint/lint.js:72 - scripts/commit-lint/lint.js:77 - scripts/commit-lint/lint.js:85 - scripts/commit-lint/lint.js:94" You are a code assistant,Definition of 'gitlabPlatformForAccount' in file packages/webview_duo_chat/src/plugin/port/test_utils/entities.ts in project gitlab-lsp,"Definition: export const gitlabPlatformForAccount: GitLabPlatformForAccount = { type: 'account', account, project: undefined, fetchFromApi: createFakeFetchFromApi(), connectToCable: async () => createFakeCable(), getUserAgentHeader: () => ({}), }; References:" You are a code assistant,Definition of 'retrieve' in file src/common/ai_context_management_2/retrievers/ai_file_context_retriever.ts in project gitlab-lsp,"Definition: async retrieve(aiContextItem: AiContextItem): Promise { if (aiContextItem.type !== 'file') { return null; } try { log.info(`retrieving file ${aiContextItem.id}`); const fileContent = await this.fileResolver.readFile({ fileUri: aiContextItem.id, }); log.info(`redacting secrets for file ${aiContextItem.id}`); const redactedContent = this.secretRedactor.redactSecrets(fileContent); return redactedContent; } catch (e) { log.warn(`Failed to retrieve file ${aiContextItem.id}`, e); return null; } } } References:" You are a code assistant,Definition of 'TimesRetrievedByPosition' in file src/common/suggestion/suggestions_cache.ts in project gitlab-lsp,"Definition: type TimesRetrievedByPosition = { [key: string]: number; }; export type SuggestionCacheEntry = { character: number; suggestions: SuggestionOption[]; additionalContexts?: AdditionalContext[]; currentLine: string; timesRetrievedByPosition: TimesRetrievedByPosition; }; export type SuggestionCacheContext = { document: TextDocumentIdentifier; context: IDocContext; position: Position; additionalContexts?: AdditionalContext[]; }; export type SuggestionCache = { options: SuggestionOption[]; additionalContexts?: AdditionalContext[]; }; function isNonEmptyLine(s: string) { return s.trim().length > 0; } type Required = { [P in keyof T]-?: T[P]; }; const DEFAULT_CONFIG: Required = { enabled: true, maxSize: 1024 * 1024, ttl: 60 * 1000, prefixLines: 1, suffixLines: 1, }; export class SuggestionsCache { #cache: LRUCache; #configService: ConfigService; constructor(configService: ConfigService) { this.#configService = configService; const currentConfig = this.#getCurrentConfig(); this.#cache = new LRUCache({ 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 { 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: - src/common/suggestion/suggestions_cache.ts:17" You are a code assistant,Definition of 'withTrailingSlashRedirect' in file src/node/http/fastify_utilities.ts in project gitlab-lsp,"Definition: export const withTrailingSlashRedirect = (handler: RouteHandlerMethod): RouteHandlerMethod => { return function (this: FastifyInstance, request: FastifyRequest, reply: FastifyReply) { if (!request.url.endsWith('/')) { return reply.redirect(`${request.url}/`); } return handler.call(this, request, reply); }; }; References: - src/node/webview/handlers/webview_handler.ts:9" You are a code assistant,Definition of 'runScript' in file scripts/watcher/run_script.ts in project gitlab-lsp,"Definition: export async function runScript(script: string, dir?: string): Promise { const [file, ...args] = script.split(' '); const { exitCode } = await execa(file, args, { env: { ...process.env, FORCE_COLOR: 'true' }, stdio: 'inherit', // Inherit stdio to preserve color and formatting cwd: dir, extendEnv: true, shell: true, }); if (exitCode !== 0) { throw new Error(`Script ${script} exited with code ${exitCode}`); } } References: - scripts/watcher/watch.ts:32 - scripts/watcher/watch.ts:14 - scripts/watcher/watch.ts:30" You are a code assistant,Definition of 'onOpen' in file src/common/circuit_breaker/exponential_backoff_circuit_breaker.ts in project gitlab-lsp,"Definition: 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) }; } #getBackoffTime() { return Math.min( this.#initialBackoffMs * this.#backoffMultiplier ** (this.#errorCount - 1), this.#maxBackoffMs, ); } } References:" You are a code assistant,Definition of 'WorkflowGraphQLService' in file src/common/graphql/workflow/service.ts in project gitlab-lsp,"Definition: export class WorkflowGraphQLService implements WorkflowServiceInterface { #apiClient: GitLabApiClient; #logger: Logger; 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 { const workflowId = this.generateWorkflowID(id); let timeout: NodeJS.Timeout; const poll = async (): Promise => { 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 { 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: - src/common/graphql/workflow/service.test.ts:14 - src/common/graphql/workflow/service.test.ts:44 - packages/webview_duo_workflow/src/plugin/index.ts:14 - src/node/main.ts:174" You are a code assistant,Definition of 'connectToCable' in file src/common/api.ts in project gitlab-lsp,"Definition: connectToCable(): Promise; onApiReconfigured(listener: (data: ApiReconfiguredData) => void): Disposable; readonly instanceVersion?: string; } export const GitLabApiClient = createInterfaceId('GitLabApiClient'); export type GenerationType = 'comment' | 'small_file' | 'empty_function' | undefined; export interface CodeSuggestionRequest { prompt_version: number; project_path: string; model_provider?: string; project_id: number; current_file: CodeSuggestionRequestCurrentFile; intent?: 'completion' | 'generation'; stream?: boolean; /** how many suggestion options should the API return */ choices_count?: number; /** additional context to provide to the model */ context?: AdditionalContext[]; /* A user's instructions for code suggestions. */ user_instruction?: string; /* The backend can add additional prompt info based on the type of event */ generation_type?: GenerationType; } export interface CodeSuggestionRequestCurrentFile { file_name: string; content_above_cursor: string; content_below_cursor: string; } export interface CodeSuggestionResponse { choices?: SuggestionOption[]; model?: ICodeSuggestionModel; status: number; error?: string; isDirectConnection?: boolean; } // FIXME: Rename to SuggestionOptionStream when renaming the SuggestionOption export interface StartStreamOption { uniqueTrackingId: string; /** the streamId represents the beginning of a stream * */ streamId: string; } export type SuggestionOptionOrStream = SuggestionOption | StartStreamOption; export interface PersonalAccessToken { name: string; scopes: string[]; active: boolean; } export interface OAuthToken { scope: string[]; } export interface TokenCheckResponse { valid: boolean; reason?: 'unknown' | 'not_active' | 'invalid_scopes'; message?: string; } export interface IDirectConnectionDetailsHeaders { 'X-Gitlab-Global-User-Id': string; 'X-Gitlab-Instance-Id': string; 'X-Gitlab-Host-Name': string; 'X-Gitlab-Saas-Duo-Pro-Namespace-Ids': string; } export interface IDirectConnectionModelDetails { model_provider: string; model_name: string; } export interface IDirectConnectionDetails { base_url: string; token: string; expires_at: number; headers: IDirectConnectionDetailsHeaders; model_details: IDirectConnectionModelDetails; } const CONFIG_CHANGE_EVENT_NAME = 'apiReconfigured'; @Injectable(GitLabApiClient, [LsFetch, ConfigService]) export class GitLabAPI implements GitLabApiClient { #token: string | undefined; #baseURL: string; #clientInfo?: IClientInfo; #lsFetch: LsFetch; #eventEmitter = new EventEmitter(); #configService: ConfigService; #instanceVersion?: string; constructor(lsFetch: LsFetch, configService: ConfigService) { this.#baseURL = GITLAB_API_BASE_URL; this.#lsFetch = lsFetch; this.#configService = configService; this.#configService.onConfigChange(async (config) => { this.#clientInfo = configService.get('client.clientInfo'); this.#lsFetch.updateAgentOptions({ ignoreCertificateErrors: this.#configService.get('client.ignoreCertificateErrors') ?? false, ...(this.#configService.get('client.httpAgentOptions') ?? {}), }); await this.configureApi(config.client); }); } onApiReconfigured(listener: (data: ApiReconfiguredData) => void): Disposable { this.#eventEmitter.on(CONFIG_CHANGE_EVENT_NAME, listener); return { dispose: () => this.#eventEmitter.removeListener(CONFIG_CHANGE_EVENT_NAME, listener) }; } #fireApiReconfigured(isInValidState: boolean, validationMessage?: string) { const data: ApiReconfiguredData = { isInValidState, validationMessage }; this.#eventEmitter.emit(CONFIG_CHANGE_EVENT_NAME, data); } async configureApi({ token, baseUrl = GITLAB_API_BASE_URL, }: { token?: string; baseUrl?: string; }) { if (this.#token === token && this.#baseURL === baseUrl) return; this.#token = token; this.#baseURL = baseUrl; const { valid, reason, message } = await this.checkToken(this.#token); let validationMessage; if (!valid) { this.#configService.set('client.token', undefined); validationMessage = `Token is invalid. ${message}. Reason: ${reason}`; log.warn(validationMessage); } else { log.info('Token is valid'); } this.#instanceVersion = await this.#getGitLabInstanceVersion(); this.#fireApiReconfigured(valid, validationMessage); } #looksLikePatToken(token: string): boolean { // OAuth tokens will be longer than 42 characters and PATs will be shorter. return token.length < 42; } async #checkPatToken(token: string): Promise { const headers = this.#getDefaultHeaders(token); const response = await this.#lsFetch.get( `${this.#baseURL}/api/v4/personal_access_tokens/self`, { headers }, ); await handleFetchError(response, 'Information about personal access token'); const { active, scopes } = (await response.json()) as PersonalAccessToken; if (!active) { return { valid: false, reason: 'not_active', message: 'Token is not active.', }; } if (!this.#hasValidScopes(scopes)) { const joinedScopes = scopes.map((scope) => `'${scope}'`).join(', '); return { valid: false, reason: 'invalid_scopes', message: `Token has scope(s) ${joinedScopes} (needs 'api').`, }; } return { valid: true }; } async #checkOAuthToken(token: string): Promise { const headers = this.#getDefaultHeaders(token); const response = await this.#lsFetch.get(`${this.#baseURL}/oauth/token/info`, { headers, }); await handleFetchError(response, 'Information about OAuth token'); const { scope: scopes } = (await response.json()) as OAuthToken; if (!this.#hasValidScopes(scopes)) { const joinedScopes = scopes.map((scope) => `'${scope}'`).join(', '); return { valid: false, reason: 'invalid_scopes', message: `Token has scope(s) ${joinedScopes} (needs 'api').`, }; } return { valid: true }; } async checkToken(token: string = ''): Promise { try { if (this.#looksLikePatToken(token)) { log.info('Checking token for PAT validity'); return await this.#checkPatToken(token); } log.info('Checking token for OAuth validity'); return await this.#checkOAuthToken(token); } catch (err) { log.error('Error performing token check', err); return { valid: false, reason: 'unknown', message: `Failed to check token: ${err}`, }; } } #hasValidScopes(scopes: string[]): boolean { return scopes.includes('api'); } async getCodeSuggestions( request: CodeSuggestionRequest, ): Promise { if (!this.#token) { throw new Error('Token needs to be provided to request Code Suggestions'); } const headers = { ...this.#getDefaultHeaders(this.#token), 'Content-Type': 'application/json', }; const response = await this.#lsFetch.post( `${this.#baseURL}/api/v4/code_suggestions/completions`, { headers, body: JSON.stringify(request) }, ); await handleFetchError(response, 'Code Suggestions'); const data = await response.json(); return { ...data, status: response.status }; } async *getStreamingCodeSuggestions( request: CodeSuggestionRequest, ): AsyncGenerator { if (!this.#token) { throw new Error('Token needs to be provided to stream code suggestions'); } const headers = { ...this.#getDefaultHeaders(this.#token), 'Content-Type': 'application/json', }; yield* this.#lsFetch.streamFetch( `${this.#baseURL}/api/v4/code_suggestions/completions`, JSON.stringify(request), headers, ); } async fetchFromApi(request: ApiRequest): Promise { if (!this.#token) { return Promise.reject(new Error('Token needs to be provided to authorise API request.')); } if ( request.supportedSinceInstanceVersion && !this.#instanceVersionHigherOrEqualThen(request.supportedSinceInstanceVersion.version) ) { return Promise.reject( new InvalidInstanceVersionError( `Can't ${request.supportedSinceInstanceVersion.resourceName} until your instance is upgraded to ${request.supportedSinceInstanceVersion.version} or higher.`, ), ); } if (request.type === 'graphql') { return this.#graphqlRequest(request.query, request.variables); } switch (request.method) { case 'GET': return this.#fetch(request.path, request.searchParams, 'resource', request.headers); case 'POST': return this.#postFetch(request.path, 'resource', request.body, request.headers); default: // the type assertion is necessary because TS doesn't expect any other types throw new Error(`Unknown request type ${(request as ApiRequest).type}`); } } async connectToCable(): Promise { const headers = this.#getDefaultHeaders(this.#token); const websocketOptions = { headers: { ...headers, Origin: this.#baseURL, }, }; return connectToCable(this.#baseURL, websocketOptions); } async #graphqlRequest( document: RequestDocument, variables?: V, ): Promise { const ensureEndsWithSlash = (url: string) => url.replace(/\/?$/, '/'); const endpoint = new URL('./api/graphql', ensureEndsWithSlash(this.#baseURL)).href; // supports GitLab instances that are on a custom path, e.g. ""https://example.com/gitlab"" const graphqlFetch = async ( input: RequestInfo | URL, init?: RequestInit, ): Promise => { const url = input instanceof URL ? input.toString() : input; return this.#lsFetch.post(url, { ...init, headers: { ...headers, ...init?.headers }, }); }; const headers = this.#getDefaultHeaders(this.#token); const client = new GraphQLClient(endpoint, { headers, fetch: graphqlFetch, }); return client.request(document, variables); } async #fetch( apiResourcePath: string, query: Record = {}, resourceName = 'resource', headers?: Record, ): Promise { const url = `${this.#baseURL}/api/v4${apiResourcePath}${createQueryString(query)}`; const result = await this.#lsFetch.get(url, { headers: { ...this.#getDefaultHeaders(this.#token), ...headers }, }); await handleFetchError(result, resourceName); return result.json() as Promise; } async #postFetch( apiResourcePath: string, resourceName = 'resource', body?: unknown, headers?: Record, ): Promise { const url = `${this.#baseURL}/api/v4${apiResourcePath}`; const response = await this.#lsFetch.post(url, { headers: { 'Content-Type': 'application/json', ...this.#getDefaultHeaders(this.#token), ...headers, }, body: JSON.stringify(body), }); await handleFetchError(response, resourceName); return response.json() as Promise; } #getDefaultHeaders(token?: string) { return { Authorization: `Bearer ${token}`, 'User-Agent': `code-completions-language-server-experiment (${this.#clientInfo?.name}:${this.#clientInfo?.version})`, 'X-Gitlab-Language-Server-Version': getLanguageServerVersion(), }; } #instanceVersionHigherOrEqualThen(version: string): boolean { if (!this.#instanceVersion) return false; return semverCompare(this.#instanceVersion, version) >= 0; } async #getGitLabInstanceVersion(): Promise { if (!this.#token) { return ''; } const headers = this.#getDefaultHeaders(this.#token); const response = await this.#lsFetch.get(`${this.#baseURL}/api/v4/version`, { headers, }); const { version } = await response.json(); return version; } get instanceVersion() { return this.#instanceVersion; } } References: - src/common/action_cable.test.ts:21 - src/common/action_cable.test.ts:40 - src/common/api.ts:348 - src/common/action_cable.test.ts:54 - src/common/action_cable.test.ts:32" You are a code assistant,Definition of 'DEFAULT_MAX_BACKOFF_MS' in file src/common/circuit_breaker/exponential_backoff_circuit_breaker.ts in project gitlab-lsp,"Definition: export const DEFAULT_MAX_BACKOFF_MS = 60000; export const DEFAULT_BACKOFF_MULTIPLIER = 2; export interface ExponentialBackoffCircuitBreakerOptions { maxErrorsBeforeBreaking?: number; initialBackoffMs?: number; maxBackoffMs?: number; backoffMultiplier?: number; } export class ExponentialBackoffCircuitBreaker implements CircuitBreaker { #name: string; #state: CircuitBreakerState = CircuitBreakerState.CLOSED; readonly #initialBackoffMs: number; readonly #maxBackoffMs: number; readonly #backoffMultiplier: number; #errorCount = 0; #eventEmitter = new EventEmitter(); #timeoutId: NodeJS.Timeout | null = null; constructor( name: string, { initialBackoffMs = DEFAULT_INITIAL_BACKOFF_MS, maxBackoffMs = DEFAULT_MAX_BACKOFF_MS, backoffMultiplier = DEFAULT_BACKOFF_MULTIPLIER, }: ExponentialBackoffCircuitBreakerOptions = {}, ) { this.#name = name; this.#initialBackoffMs = initialBackoffMs; this.#maxBackoffMs = maxBackoffMs; this.#backoffMultiplier = backoffMultiplier; } error() { this.#errorCount += 1; this.#open(); } megaError() { this.#errorCount += 3; this.#open(); } #open() { if (this.#state === CircuitBreakerState.OPEN) { return; } this.#state = CircuitBreakerState.OPEN; log.warn( `Excess errors detected, opening '${this.#name}' circuit breaker for ${this.#getBackoffTime() / 1000} second(s).`, ); this.#timeoutId = setTimeout(() => this.#close(), this.#getBackoffTime()); this.#eventEmitter.emit('open'); } #close() { if (this.#state === CircuitBreakerState.CLOSED) { return; } if (this.#timeoutId) { clearTimeout(this.#timeoutId); } this.#state = CircuitBreakerState.CLOSED; this.#eventEmitter.emit('close'); } isOpen() { return this.#state === CircuitBreakerState.OPEN; } 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) }; } #getBackoffTime() { return Math.min( this.#initialBackoffMs * this.#backoffMultiplier ** (this.#errorCount - 1), this.#maxBackoffMs, ); } } References:" You are a code assistant,Definition of 'dispose' in file packages/lib_webview/src/events/message_bus.ts in project gitlab-lsp,"Definition: public dispose(): void { this.clear(); } } References:" You are a code assistant,Definition of 'DISABLED_LANGUAGE' in file src/common/feature_state/feature_state_management_types.ts in project gitlab-lsp,"Definition: export const DISABLED_LANGUAGE = 'code-suggestions-document-disabled-language' as const; export type StateCheckId = | typeof NO_LICENSE | typeof DUO_DISABLED_FOR_PROJECT | typeof UNSUPPORTED_GITLAB_VERSION | typeof UNSUPPORTED_LANGUAGE | typeof DISABLED_LANGUAGE; export interface FeatureStateCheck { checkId: StateCheckId; details?: string; } export interface FeatureState { featureId: Feature; engagedChecks: FeatureStateCheck[]; } const CODE_SUGGESTIONS_CHECKS_PRIORITY_ORDERED = [ DUO_DISABLED_FOR_PROJECT, UNSUPPORTED_LANGUAGE, DISABLED_LANGUAGE, ]; const CHAT_CHECKS_PRIORITY_ORDERED = [DUO_DISABLED_FOR_PROJECT]; export const CHECKS_PER_FEATURE: { [key in Feature]: StateCheckId[] } = { [CODE_SUGGESTIONS]: CODE_SUGGESTIONS_CHECKS_PRIORITY_ORDERED, [CHAT]: CHAT_CHECKS_PRIORITY_ORDERED, // [WORKFLOW]: [], }; References:" You are a code assistant,Definition of 'Handlers' in file src/common/webview/extension/types.ts in project gitlab-lsp,"Definition: export type Handlers = { notification: ExtensionMessageHandlerRegistry; request: ExtensionMessageHandlerRegistry; }; References: - src/common/webview/extension/extension_connection_message_bus.ts:23 - src/common/webview/extension/extension_connection_message_bus_provider.ts:30 - src/common/webview/extension/extension_connection_message_bus.ts:11" You are a code assistant,Definition of 'getContext' in file src/common/document_transformer_service.ts in project gitlab-lsp,"Definition: getContext( uri: string, position: Position, workspaceFolders: WorkspaceFolder[], completionContext?: InlineCompletionContext, ): IDocContext | undefined; transform(context: IDocContext): IDocContext; } export const DocumentTransformerService = createInterfaceId( 'DocumentTransformerService', ); @Injectable(DocumentTransformerService, [LsTextDocuments, SecretRedactor]) export class DefaultDocumentTransformerService implements DocumentTransformerService { #transformers: IDocTransformer[] = []; #documents: LsTextDocuments; 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 'buildWebviewCollectionMetadataRequestHandler' in file src/node/webview/handlers/build_webview_metadata_request_handler.ts in project gitlab-lsp,"Definition: export const buildWebviewCollectionMetadataRequestHandler = ( webviewIds: WebviewId[], ): ((req: FastifyRequest, reply: FastifyReply) => Promise) => { return async (_, reply) => { const urls = webviewIds.reduce( (acc, webviewId) => { acc[webviewId] = `/webview/${webviewId}/`; return acc; }, {} as Record, ); await reply.send(urls); }; }; References: - src/node/webview/handlers/build_webview_metadata_request_handler.test.ts:10 - src/node/webview/routes/webview_routes.ts:20" You are a code assistant,Definition of 'MockFastifyReply' in file src/node/webview/test-utils/mock_fastify_reply.ts in project gitlab-lsp,"Definition: export type MockFastifyReply = { [P in keyof FastifyReply]: jest.Mock; }; export const createMockFastifyReply = (): MockFastifyReply & FastifyReply => { const reply: Partial = {}; reply.send = jest.fn().mockReturnThis(); reply.status = jest.fn().mockReturnThis(); reply.redirect = jest.fn().mockReturnThis(); reply.sendFile = jest.fn().mockReturnThis(); reply.code = jest.fn().mockReturnThis(); reply.header = jest.fn().mockReturnThis(); reply.type = jest.fn().mockReturnThis(); return reply as MockFastifyReply & FastifyReply; }; References:" You are a code assistant,Definition of 'INSTANCE_FEATURE_FLAG_QUERY' in file src/common/feature_flags.ts in project gitlab-lsp,"Definition: export const INSTANCE_FEATURE_FLAG_QUERY = gql` query featureFlagsEnabled($name: String!) { featureFlagEnabled(name: $name) } `; export const FeatureFlagService = createInterfaceId('FeatureFlagService'); export interface FeatureFlagService { /** * Checks if a feature flag is enabled on the GitLab instance. * @see `IGitLabAPI` for how the instance is determined. * @requires `updateInstanceFeatureFlags` to be called first. */ isInstanceFlagEnabled(name: InstanceFeatureFlags): boolean; /** * Checks if a feature flag is enabled on the client. * @see `ConfigService` for client configuration. */ isClientFlagEnabled(name: ClientFeatureFlags): boolean; } @Injectable(FeatureFlagService, [GitLabApiClient, ConfigService]) export class DefaultFeatureFlagService { #api: GitLabApiClient; #configService: ConfigService; #featureFlags: Map = 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 { 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 { 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 '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 { return input.map((option) => ({ ...option, text: `${option.text} [1]` })); } } class Processor2 extends PostProcessor { async processStream( _context: IDocContext, input: StreamingCompletionResponse, ): Promise { return input; } async processCompletion( _context: IDocContext, input: SuggestionOption[], ): Promise { return input.map((option) => ({ ...option, text: `${option.text} [2]` })); } } pipeline.addProcessor(new Processor1()); pipeline.addProcessor(new Processor2()); const completionInput: SuggestionOption[] = [{ text: 'option1', uniqueTrackingId: '1' }]; const result = await pipeline.run({ documentContext: mockContext, input: completionInput, type: 'completion', }); expect(result).toEqual([{ text: 'option1 [1] [2]', uniqueTrackingId: '1' }]); }); test('should throw an error for unexpected type', async () => { class TestProcessor extends PostProcessor { async processStream( _context: IDocContext, input: StreamingCompletionResponse, ): Promise { return input; } async processCompletion( _context: IDocContext, input: SuggestionOption[], ): Promise { 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 'getSuggestions' in file src/common/suggestion_client/default_suggestion_client.ts in project gitlab-lsp,"Definition: async getSuggestions( suggestionContext: SuggestionContext, ): Promise { const response = await this.#api.getCodeSuggestions(createV2Request(suggestionContext)); return response && { ...response, isDirectConnection: false }; } } References:" You are a code assistant,Definition of 'getProjectsForWorkspaceFolder' in file src/common/services/duo_access/project_access_cache.ts in project gitlab-lsp,"Definition: getProjectsForWorkspaceFolder(workspaceFolder: WorkspaceFolder): DuoProject[] { return this.#duoProjects.get(workspaceFolder.uri) ?? []; } async updateCache({ baseUrl, workspaceFolders, }: { baseUrl: string; workspaceFolders: WorkspaceFolder[]; }) { try { this.#duoProjects.clear(); const duoProjects = await Promise.all( workspaceFolders.map(async (workspaceFolder) => { return { workspaceFolder, projects: await this.#duoProjectsForWorkspaceFolder({ workspaceFolder, baseUrl, }), }; }), ); for (const { workspaceFolder, projects } of duoProjects) { this.#logProjectsInfo(projects, workspaceFolder); this.#duoProjects.set(workspaceFolder.uri, projects); } this.#triggerChange(); } catch (err) { log.error('DuoProjectAccessCache: failed to update project access cache', err); } } #logProjectsInfo(projects: DuoProject[], workspaceFolder: WorkspaceFolder) { if (!projects.length) { log.warn( `DuoProjectAccessCache: no projects found for workspace folder ${workspaceFolder.uri}`, ); return; } log.debug( `DuoProjectAccessCache: found ${projects.length} projects for workspace folder ${workspaceFolder.uri}: ${JSON.stringify(projects, null, 2)}`, ); } async #duoProjectsForWorkspaceFolder({ workspaceFolder, baseUrl, }: { workspaceFolder: WorkspaceFolder; baseUrl: string; }): Promise { const remotes = await this.#gitlabRemotesForWorkspaceFolder(workspaceFolder, baseUrl); const projects = await Promise.all( remotes.map(async (remote) => { const enabled = await this.#checkDuoFeaturesEnabled(remote.namespaceWithPath); return { projectPath: remote.projectPath, uri: remote.fileUri, enabled, host: remote.host, namespace: remote.namespace, namespaceWithPath: remote.namespaceWithPath, } satisfies DuoProject; }), ); return projects; } async #gitlabRemotesForWorkspaceFolder( workspaceFolder: WorkspaceFolder, baseUrl: string, ): Promise { const paths = await this.directoryWalker.findFilesForDirectory({ directoryUri: workspaceFolder.uri, filters: { fileEndsWith: ['/.git/config'], }, }); const remotes = await Promise.all( paths.map(async (fileUri) => this.#gitlabRemotesForFileUri(fileUri.toString(), baseUrl)), ); return remotes.flat(); } async #gitlabRemotesForFileUri( fileUri: string, baseUrl: string, ): Promise { const remoteUrls = await this.#remoteUrlsFromGitConfig(fileUri); return remoteUrls.reduce((acc, remoteUrl) => { const remote = parseGitLabRemote(remoteUrl, baseUrl); if (remote) { acc.push({ ...remote, fileUri }); } return acc; }, []); } async #remoteUrlsFromGitConfig(fileUri: string): Promise { try { const fileString = await this.fileResolver.readFile({ fileUri }); const config = ini.parse(fileString); return this.#getRemoteUrls(config); } catch (error) { log.error(`DuoProjectAccessCache: Failed to read git config file: ${fileUri}`, error); return []; } } #getRemoteUrls(config: GitConfig): string[] { return Object.keys(config).reduce((acc, section) => { if (section.startsWith('remote ')) { acc.push(config[section].url); } return acc; }, []); } async #checkDuoFeaturesEnabled(projectPath: string): Promise { try { const response = await this.api.fetchFromApi<{ project: GqlProjectWithDuoEnabledInfo }>({ type: 'graphql', query: duoFeaturesEnabledQuery, variables: { projectPath, }, } satisfies ApiRequest<{ project: GqlProjectWithDuoEnabledInfo }>); return Boolean(response?.project?.duoFeaturesEnabled); } catch (error) { log.error( `DuoProjectAccessCache: Failed to check if Duo features are enabled for project: ${projectPath}`, error, ); return true; } } onDuoProjectCacheUpdate( listener: (duoProjectsCache: Map) => void, ): Disposable { this.#eventEmitter.on(DUO_PROJECT_CACHE_UPDATE_EVENT, listener); return { dispose: () => this.#eventEmitter.removeListener(DUO_PROJECT_CACHE_UPDATE_EVENT, listener), }; } #triggerChange() { this.#eventEmitter.emit(DUO_PROJECT_CACHE_UPDATE_EVENT, this.#duoProjects); } } References:" You are a code assistant,Definition of 'DuoProjectPolicy' in file src/common/ai_context_management_2/policies/duo_project_policy.ts in project gitlab-lsp,"Definition: export interface DuoProjectPolicy extends DefaultDuoProjectPolicy {} export const DuoProjectPolicy = createInterfaceId('AiFileContextProvider'); @Injectable(DuoProjectPolicy, [DuoProjectAccessChecker]) export class DefaultDuoProjectPolicy implements AiContextPolicy { constructor(private duoProjectAccessChecker: DuoProjectAccessChecker) {} 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: - src/common/ai_context_management_2/ai_policy_management.ts:24" You are a code assistant,Definition of 'warn' in file packages/lib_logging/src/null_logger.ts in project gitlab-lsp,"Definition: warn(message: string, e?: Error | undefined): void; warn(): void { // NOOP } error(e: Error): void; error(message: string, e?: Error | undefined): void; error(): void { // NOOP } } References:" You are a code assistant,Definition of 'onChanged' in file src/common/feature_state/project_duo_acces_check.ts in project gitlab-lsp,"Definition: onChanged(listener: (data: StateCheckChangedEventData) => void): Disposable { this.#stateEmitter.on('change', listener); return { dispose: () => this.#stateEmitter.removeListener('change', listener), }; } get engaged() { return !this.#hasDuoAccess; } async #checkIfProjectHasDuoAccess(): Promise { this.#hasDuoAccess = this.#isEnabledInSettings; if (!this.#currentDocument) { this.#stateEmitter.emit('change', this); return; } const workspaceFolder = await this.#getWorkspaceFolderForUri(this.#currentDocument.uri); if (workspaceFolder) { const status = this.#duoProjectAccessChecker.checkProjectStatus( this.#currentDocument.uri, workspaceFolder, ); if (status === DuoProjectStatus.DuoEnabled) { this.#hasDuoAccess = true; } else if (status === DuoProjectStatus.DuoDisabled) { this.#hasDuoAccess = false; } } this.#stateEmitter.emit('change', this); } id = DUO_DISABLED_FOR_PROJECT; details = 'Duo features are disabled for this project'; async #getWorkspaceFolderForUri(uri: URI): Promise { const workspaceFolders = await this.#configService.get('client.workspaceFolders'); return workspaceFolders?.find((folder) => uri.startsWith(folder.uri)); } dispose() { this.#subscriptions.forEach((s) => s.dispose()); } } References:" You are a code assistant,Definition of 'GenerationType' in file src/common/api.ts in project gitlab-lsp,"Definition: export type GenerationType = 'comment' | 'small_file' | 'empty_function' | undefined; export interface CodeSuggestionRequest { prompt_version: number; project_path: string; model_provider?: string; project_id: number; current_file: CodeSuggestionRequestCurrentFile; intent?: 'completion' | 'generation'; stream?: boolean; /** how many suggestion options should the API return */ choices_count?: number; /** additional context to provide to the model */ context?: AdditionalContext[]; /* A user's instructions for code suggestions. */ user_instruction?: string; /* The backend can add additional prompt info based on the type of event */ generation_type?: GenerationType; } export interface CodeSuggestionRequestCurrentFile { file_name: string; content_above_cursor: string; content_below_cursor: string; } export interface CodeSuggestionResponse { choices?: SuggestionOption[]; model?: ICodeSuggestionModel; status: number; error?: string; isDirectConnection?: boolean; } // FIXME: Rename to SuggestionOptionStream when renaming the SuggestionOption export interface StartStreamOption { uniqueTrackingId: string; /** the streamId represents the beginning of a stream * */ streamId: string; } export type SuggestionOptionOrStream = SuggestionOption | StartStreamOption; export interface PersonalAccessToken { name: string; scopes: string[]; active: boolean; } export interface OAuthToken { scope: string[]; } export interface TokenCheckResponse { valid: boolean; reason?: 'unknown' | 'not_active' | 'invalid_scopes'; message?: string; } export interface IDirectConnectionDetailsHeaders { 'X-Gitlab-Global-User-Id': string; 'X-Gitlab-Instance-Id': string; 'X-Gitlab-Host-Name': string; 'X-Gitlab-Saas-Duo-Pro-Namespace-Ids': string; } export interface IDirectConnectionModelDetails { model_provider: string; model_name: string; } export interface IDirectConnectionDetails { base_url: string; token: string; expires_at: number; headers: IDirectConnectionDetailsHeaders; model_details: IDirectConnectionModelDetails; } const CONFIG_CHANGE_EVENT_NAME = 'apiReconfigured'; @Injectable(GitLabApiClient, [LsFetch, ConfigService]) export class GitLabAPI implements GitLabApiClient { #token: string | undefined; #baseURL: string; #clientInfo?: IClientInfo; #lsFetch: LsFetch; #eventEmitter = new EventEmitter(); #configService: ConfigService; #instanceVersion?: string; constructor(lsFetch: LsFetch, configService: ConfigService) { this.#baseURL = GITLAB_API_BASE_URL; this.#lsFetch = lsFetch; this.#configService = configService; this.#configService.onConfigChange(async (config) => { this.#clientInfo = configService.get('client.clientInfo'); this.#lsFetch.updateAgentOptions({ ignoreCertificateErrors: this.#configService.get('client.ignoreCertificateErrors') ?? false, ...(this.#configService.get('client.httpAgentOptions') ?? {}), }); await this.configureApi(config.client); }); } onApiReconfigured(listener: (data: ApiReconfiguredData) => void): Disposable { this.#eventEmitter.on(CONFIG_CHANGE_EVENT_NAME, listener); return { dispose: () => this.#eventEmitter.removeListener(CONFIG_CHANGE_EVENT_NAME, listener) }; } #fireApiReconfigured(isInValidState: boolean, validationMessage?: string) { const data: ApiReconfiguredData = { isInValidState, validationMessage }; this.#eventEmitter.emit(CONFIG_CHANGE_EVENT_NAME, data); } async configureApi({ token, baseUrl = GITLAB_API_BASE_URL, }: { token?: string; baseUrl?: string; }) { if (this.#token === token && this.#baseURL === baseUrl) return; this.#token = token; this.#baseURL = baseUrl; const { valid, reason, message } = await this.checkToken(this.#token); let validationMessage; if (!valid) { this.#configService.set('client.token', undefined); validationMessage = `Token is invalid. ${message}. Reason: ${reason}`; log.warn(validationMessage); } else { log.info('Token is valid'); } this.#instanceVersion = await this.#getGitLabInstanceVersion(); this.#fireApiReconfigured(valid, validationMessage); } #looksLikePatToken(token: string): boolean { // OAuth tokens will be longer than 42 characters and PATs will be shorter. return token.length < 42; } async #checkPatToken(token: string): Promise { const headers = this.#getDefaultHeaders(token); const response = await this.#lsFetch.get( `${this.#baseURL}/api/v4/personal_access_tokens/self`, { headers }, ); await handleFetchError(response, 'Information about personal access token'); const { active, scopes } = (await response.json()) as PersonalAccessToken; if (!active) { return { valid: false, reason: 'not_active', message: 'Token is not active.', }; } if (!this.#hasValidScopes(scopes)) { const joinedScopes = scopes.map((scope) => `'${scope}'`).join(', '); return { valid: false, reason: 'invalid_scopes', message: `Token has scope(s) ${joinedScopes} (needs 'api').`, }; } return { valid: true }; } async #checkOAuthToken(token: string): Promise { const headers = this.#getDefaultHeaders(token); const response = await this.#lsFetch.get(`${this.#baseURL}/oauth/token/info`, { headers, }); await handleFetchError(response, 'Information about OAuth token'); const { scope: scopes } = (await response.json()) as OAuthToken; if (!this.#hasValidScopes(scopes)) { const joinedScopes = scopes.map((scope) => `'${scope}'`).join(', '); return { valid: false, reason: 'invalid_scopes', message: `Token has scope(s) ${joinedScopes} (needs 'api').`, }; } return { valid: true }; } async checkToken(token: string = ''): Promise { try { if (this.#looksLikePatToken(token)) { log.info('Checking token for PAT validity'); return await this.#checkPatToken(token); } log.info('Checking token for OAuth validity'); return await this.#checkOAuthToken(token); } catch (err) { log.error('Error performing token check', err); return { valid: false, reason: 'unknown', message: `Failed to check token: ${err}`, }; } } #hasValidScopes(scopes: string[]): boolean { return scopes.includes('api'); } async getCodeSuggestions( request: CodeSuggestionRequest, ): Promise { if (!this.#token) { throw new Error('Token needs to be provided to request Code Suggestions'); } const headers = { ...this.#getDefaultHeaders(this.#token), 'Content-Type': 'application/json', }; const response = await this.#lsFetch.post( `${this.#baseURL}/api/v4/code_suggestions/completions`, { headers, body: JSON.stringify(request) }, ); await handleFetchError(response, 'Code Suggestions'); const data = await response.json(); return { ...data, status: response.status }; } async *getStreamingCodeSuggestions( request: CodeSuggestionRequest, ): AsyncGenerator { if (!this.#token) { throw new Error('Token needs to be provided to stream code suggestions'); } const headers = { ...this.#getDefaultHeaders(this.#token), 'Content-Type': 'application/json', }; yield* this.#lsFetch.streamFetch( `${this.#baseURL}/api/v4/code_suggestions/completions`, JSON.stringify(request), headers, ); } async fetchFromApi(request: ApiRequest): Promise { if (!this.#token) { return Promise.reject(new Error('Token needs to be provided to authorise API request.')); } if ( request.supportedSinceInstanceVersion && !this.#instanceVersionHigherOrEqualThen(request.supportedSinceInstanceVersion.version) ) { return Promise.reject( new InvalidInstanceVersionError( `Can't ${request.supportedSinceInstanceVersion.resourceName} until your instance is upgraded to ${request.supportedSinceInstanceVersion.version} or higher.`, ), ); } if (request.type === 'graphql') { return this.#graphqlRequest(request.query, request.variables); } switch (request.method) { case 'GET': return this.#fetch(request.path, request.searchParams, 'resource', request.headers); case 'POST': return this.#postFetch(request.path, 'resource', request.body, request.headers); default: // the type assertion is necessary because TS doesn't expect any other types throw new Error(`Unknown request type ${(request as ApiRequest).type}`); } } async connectToCable(): Promise { const headers = this.#getDefaultHeaders(this.#token); const websocketOptions = { headers: { ...headers, Origin: this.#baseURL, }, }; return connectToCable(this.#baseURL, websocketOptions); } async #graphqlRequest( document: RequestDocument, variables?: V, ): Promise { const ensureEndsWithSlash = (url: string) => url.replace(/\/?$/, '/'); const endpoint = new URL('./api/graphql', ensureEndsWithSlash(this.#baseURL)).href; // supports GitLab instances that are on a custom path, e.g. ""https://example.com/gitlab"" const graphqlFetch = async ( input: RequestInfo | URL, init?: RequestInit, ): Promise => { const url = input instanceof URL ? input.toString() : input; return this.#lsFetch.post(url, { ...init, headers: { ...headers, ...init?.headers }, }); }; const headers = this.#getDefaultHeaders(this.#token); const client = new GraphQLClient(endpoint, { headers, fetch: graphqlFetch, }); return client.request(document, variables); } async #fetch( apiResourcePath: string, query: Record = {}, resourceName = 'resource', headers?: Record, ): Promise { const url = `${this.#baseURL}/api/v4${apiResourcePath}${createQueryString(query)}`; const result = await this.#lsFetch.get(url, { headers: { ...this.#getDefaultHeaders(this.#token), ...headers }, }); await handleFetchError(result, resourceName); return result.json() as Promise; } async #postFetch( apiResourcePath: string, resourceName = 'resource', body?: unknown, headers?: Record, ): Promise { const url = `${this.#baseURL}/api/v4${apiResourcePath}`; const response = await this.#lsFetch.post(url, { headers: { 'Content-Type': 'application/json', ...this.#getDefaultHeaders(this.#token), ...headers, }, body: JSON.stringify(body), }); await handleFetchError(response, resourceName); return response.json() as Promise; } #getDefaultHeaders(token?: string) { return { Authorization: `Bearer ${token}`, 'User-Agent': `code-completions-language-server-experiment (${this.#clientInfo?.name}:${this.#clientInfo?.version})`, 'X-Gitlab-Language-Server-Version': getLanguageServerVersion(), }; } #instanceVersionHigherOrEqualThen(version: string): boolean { if (!this.#instanceVersion) return false; return semverCompare(this.#instanceVersion, version) >= 0; } async #getGitLabInstanceVersion(): Promise { if (!this.#token) { return ''; } const headers = this.#getDefaultHeaders(this.#token); const response = await this.#lsFetch.get(`${this.#baseURL}/api/v4/version`, { headers, }); const { version } = await response.json(); return version; } get instanceVersion() { return this.#instanceVersion; } } References: - src/common/suggestion/streaming_handler.ts:46 - src/common/api.ts:55 - src/common/tree_sitter/intent_resolver.ts:14 - src/common/suggestion/streaming_handler.test.ts:181 - src/common/suggestion/suggestion_service.ts:289" You are a code assistant,Definition of 'SuccessfulResponse' in file packages/lib_webview/src/events/webview_runtime_message_bus.ts in project gitlab-lsp,"Definition: export type SuccessfulResponse = WebviewAddress & { requestId: string; success: true; type: string; payload?: unknown; }; 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 {} References:" You are a code assistant,Definition of 'getInstance' in file src/common/advanced_context/context_resolvers/open_tabs_context_resolver.ts in project gitlab-lsp,"Definition: public static getInstance(): OpenTabsResolver { if (!OpenTabsResolver.#instance) { log.debug('OpenTabsResolver: initializing'); OpenTabsResolver.#instance = new OpenTabsResolver(); } return OpenTabsResolver.#instance; } public static destroyInstance(): void { OpenTabsResolver.#instance = undefined; } async *buildContext({ documentContext, includeCurrentFile = false, }: { documentContext?: IDocContext; includeCurrentFile?: boolean; }): AsyncGenerator { const lruCache = LruCache.getInstance(LRU_CACHE_BYTE_SIZE_LIMIT); const openFiles = lruCache.mostRecentFiles({ context: documentContext, includeCurrentFile, }); for (const file of openFiles) { yield { uri: file.uri, type: 'file' as const, content: `${file.prefix}${file.suffix}`, fileRelativePath: file.fileRelativePath, strategy: 'open_tabs' as const, workspaceFolder: file.workspaceFolder ?? { name: '', uri: '' }, }; } } } References:" You are a code assistant,Definition of 'waitForMs' in file packages/webview_duo_chat/src/plugin/port/utils/wait_for_ms.ts in project gitlab-lsp,"Definition: export const waitForMs = (ms: number) => new Promise((resolve) => { setTimeout(resolve, ms); }); References: - packages/webview_duo_chat/src/plugin/port/utils/wait_for_ms.test.ts:7 - packages/webview_duo_chat/src/plugin/port/chat/api/pulling.ts:23" You are a code assistant,Definition of 'Emitter' in file src/common/tracking/snowplow/emitter.ts in project gitlab-lsp,"Definition: 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 { 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.test.ts:14 - src/common/tracking/snowplow/emitter.test.ts:73 - src/common/tracking/snowplow/emitter.test.ts:9 - src/common/tracking/snowplow/emitter.test.ts:19 - src/common/tracking/snowplow/snowplow.ts:46 - src/common/tracking/snowplow/emitter.test.ts:61 - src/common/tracking/snowplow/emitter.test.ts:28 - src/common/tracking/snowplow/emitter.test.ts:37 - src/common/tracking/snowplow/snowplow.ts:60 - src/common/tracking/snowplow/emitter.test.ts:49" You are a code assistant,Definition of 'ICodeCompletionConfig' in file src/common/config_service.ts in project gitlab-lsp,"Definition: export interface ICodeCompletionConfig { enableSecretRedaction?: boolean; additionalLanguages?: string[]; disabledSupportedLanguages?: string[]; } export interface ISuggestionsCacheOptions { enabled?: boolean; maxSize?: number; ttl?: number; prefixLines?: number; suffixLines?: number; } export interface IHttpAgentOptions { ca?: string; cert?: string; certKey?: string; } export interface ISnowplowTrackerOptions { gitlab_instance_id?: string; gitlab_global_user_id?: string; gitlab_host_name?: string; gitlab_saas_duo_pro_namespace_ids?: number[]; } export interface ISecurityScannerOptions { enabled?: boolean; serviceUrl?: string; } export interface IWorkflowSettings { dockerSocket?: string; } export interface IDuoConfig { enabledWithoutGitlabProject?: boolean; } export interface IClientConfig { /** GitLab API URL used for getting code suggestions */ baseUrl?: string; /** Full project path. */ projectPath?: string; /** PAT or OAuth token used to authenticate to GitLab API */ token?: string; /** The base URL for language server assets in the client-side extension */ baseAssetsUrl?: string; clientInfo?: IClientInfo; // FIXME: this key should be codeSuggestions (we have code completion and code generation) codeCompletion?: ICodeCompletionConfig; openTabsContext?: boolean; telemetry?: ITelemetryOptions; /** Config used for caching code suggestions */ suggestionsCache?: ISuggestionsCacheOptions; workspaceFolders?: WorkspaceFolder[] | null; /** Collection of Feature Flag values which are sent from the client */ featureFlags?: Record; logLevel?: LogLevel; ignoreCertificateErrors?: boolean; httpAgentOptions?: IHttpAgentOptions; snowplowTrackerOptions?: ISnowplowTrackerOptions; // TODO: move to `duo` duoWorkflowSettings?: IWorkflowSettings; securityScannerOptions?: ISecurityScannerOptions; duo?: IDuoConfig; } export interface IConfig { // TODO: we can possibly remove this extra level of config and move all IClientConfig properties to IConfig client: IClientConfig; } /** * ConfigService manages user configuration (e.g. baseUrl) and application state (e.g. codeCompletion.enabled) * TODO: Maybe in the future we would like to separate these two */ export interface ConfigService { get: TypedGetter; /** * set sets the property of the config * the new value completely overrides the old one */ set: TypedSetter; onConfigChange(listener: (config: IConfig) => void): Disposable; /** * merge adds `newConfig` properties into existing config, if the * property is present in both old and new config, `newConfig` * properties take precedence unless not defined * * This method performs deep merge * * **Arrays are not merged; they are replaced with the new value.** * */ merge(newConfig: Partial): void; } export const ConfigService = createInterfaceId('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 = (key?: string) => { return key ? get(this.#config, key) : this.#config; }; set: TypedSetter = (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) { mergeWith(this.#config, newConfig, (target, src) => (isArray(target) ? src : undefined)); this.#triggerChange(); } } References: - src/common/config_service.ts:60" You are a code assistant,Definition of 'ChatInputTemplate' in file packages/webview_duo_chat/src/plugin/port/chat/gitlab_chat_api.ts in project gitlab-lsp,"Definition: type ChatInputTemplate = { query: string; defaultVariables: { platformOrigin?: string; }; }; export class GitLabChatApi { #cachedActionQuery?: ChatInputTemplate = undefined; #manager: GitLabPlatformManagerForChat; constructor(manager: GitLabPlatformManagerForChat) { this.#manager = manager; } async processNewUserPrompt( question: string, subscriptionId?: string, currentFileContext?: GitLabChatFileContext, ): Promise { return this.#sendAiAction({ question, currentFileContext, clientSubscriptionId: subscriptionId, }); } async pullAiMessage(requestId: string, role: string): Promise { const response = await pullHandler(() => this.#getAiMessage(requestId, role)); if (!response) return errorResponse(requestId, ['Reached timeout while fetching response.']); return successResponse(response); } async cleanChat(): Promise { return this.#sendAiAction({ question: SPECIAL_MESSAGES.CLEAN }); } async #currentPlatform() { const platform = await this.#manager.getGitLabPlatform(); if (!platform) throw new Error('Platform is missing!'); return platform; } async #getAiMessage(requestId: string, role: string): Promise { const request: GraphQLRequest = { type: 'graphql', query: AI_MESSAGES_QUERY, variables: { requestIds: [requestId], roles: [role.toUpperCase()] }, }; const platform = await this.#currentPlatform(); const history = await platform.fetchFromApi(request); return history.aiMessages.nodes[0]; } async subscribeToUpdates( messageCallback: (message: AiCompletionResponseMessageType) => Promise, subscriptionId?: string, ) { const platform = await this.#currentPlatform(); const channel = new AiCompletionResponseChannel({ htmlResponse: true, userId: `gid://gitlab/User/${extractUserId(platform.account.id)}`, aiAction: 'CHAT', clientSubscriptionId: subscriptionId, }); const cable = await platform.connectToCable(); // we use this flag to fix https://gitlab.com/gitlab-org/gitlab-vscode-extension/-/issues/1397 // sometimes a chunk comes after the full message and it broke the chat let fullMessageReceived = false; channel.on('newChunk', async (msg) => { if (fullMessageReceived) { log.info(`CHAT-DEBUG: full message received, ignoring chunk`); return; } await messageCallback(msg); }); channel.on('fullMessage', async (message) => { fullMessageReceived = true; await messageCallback(message); if (subscriptionId) { cable.disconnect(); } }); cable.subscribe(channel); } async #sendAiAction(variables: object): Promise { const platform = await this.#currentPlatform(); const { query, defaultVariables } = await this.#actionQuery(); const projectGqlId = await this.#manager.getProjectGqlId(); const request: GraphQLRequest = { type: 'graphql', query, variables: { ...variables, ...defaultVariables, resourceId: projectGqlId ?? null, }, }; return platform.fetchFromApi(request); } async #actionQuery(): Promise { if (!this.#cachedActionQuery) { const platform = await this.#currentPlatform(); try { const { version } = await platform.fetchFromApi(versionRequest); this.#cachedActionQuery = ifVersionGte( version, MINIMUM_PLATFORM_ORIGIN_FIELD_VERSION, () => CHAT_INPUT_TEMPLATE_17_3_AND_LATER, () => CHAT_INPUT_TEMPLATE_17_2_AND_EARLIER, ); } catch (e) { log.debug(`GitLab version check for sending chat failed:`, e as Error); this.#cachedActionQuery = CHAT_INPUT_TEMPLATE_17_3_AND_LATER; } } return this.#cachedActionQuery; } } References: - packages/webview_duo_chat/src/plugin/port/chat/gitlab_chat_api.ts:148" You are a code assistant,Definition of 'getInstance' in file src/common/advanced_context/lru_cache.ts in project gitlab-lsp,"Definition: public static getInstance(maxSize: number): LruCache { if (!LruCache.#instance) { log.debug('LruCache: initializing'); LruCache.#instance = new LruCache(maxSize); } return LruCache.#instance; } public static destroyInstance(): void { LruCache.#instance = undefined; } get openFiles() { return this.#cache; } #getDocumentSize(context: IDocContext): number { const size = getByteSize(`${context.prefix}${context.suffix}`); return Math.max(1, size); } /** * Update the file in the cache. * Uses lru-cache under the hood. */ updateFile(context: IDocContext) { return this.#cache.set(context.uri, context); } /** * @returns `true` if the file was deleted, `false` if the file was not found */ deleteFile(uri: DocumentUri): boolean { return this.#cache.delete(uri); } /** * Get the most recently accessed files in the workspace * @param context - The current document context `IDocContext` * @param includeCurrentFile - Include the current file in the list of most recent files, default is `true` */ mostRecentFiles({ context, includeCurrentFile = true, }: { context?: IDocContext; includeCurrentFile?: boolean; }): IDocContext[] { const files = Array.from(this.#cache.values()); if (includeCurrentFile) { return files; } return files.filter( (file) => context?.workspaceFolder?.uri === file.workspaceFolder?.uri && file.uri !== context?.uri, ); } } References:" You are a code assistant,Definition of 'updateCache' in file src/common/services/duo_access/project_access_cache.ts in project gitlab-lsp,"Definition: updateCache({ baseUrl, workspaceFolders, }: { baseUrl: string; workspaceFolders: WorkspaceFolder[]; }): Promise; onDuoProjectCacheUpdate(listener: () => void): Disposable; } export const DuoProjectAccessCache = createInterfaceId('DuoProjectAccessCache'); @Injectable(DuoProjectAccessCache, [DirectoryWalker, FileResolver, GitLabApiClient]) export class DefaultDuoProjectAccessCache { #duoProjects: Map; #eventEmitter = new EventEmitter(); constructor( private readonly directoryWalker: DirectoryWalker, private readonly fileResolver: FileResolver, private readonly api: GitLabApiClient, ) { this.#duoProjects = new Map(); } getProjectsForWorkspaceFolder(workspaceFolder: WorkspaceFolder): DuoProject[] { return this.#duoProjects.get(workspaceFolder.uri) ?? []; } async updateCache({ baseUrl, workspaceFolders, }: { baseUrl: string; workspaceFolders: WorkspaceFolder[]; }) { try { this.#duoProjects.clear(); const duoProjects = await Promise.all( workspaceFolders.map(async (workspaceFolder) => { return { workspaceFolder, projects: await this.#duoProjectsForWorkspaceFolder({ workspaceFolder, baseUrl, }), }; }), ); for (const { workspaceFolder, projects } of duoProjects) { this.#logProjectsInfo(projects, workspaceFolder); this.#duoProjects.set(workspaceFolder.uri, projects); } this.#triggerChange(); } catch (err) { log.error('DuoProjectAccessCache: failed to update project access cache', err); } } #logProjectsInfo(projects: DuoProject[], workspaceFolder: WorkspaceFolder) { if (!projects.length) { log.warn( `DuoProjectAccessCache: no projects found for workspace folder ${workspaceFolder.uri}`, ); return; } log.debug( `DuoProjectAccessCache: found ${projects.length} projects for workspace folder ${workspaceFolder.uri}: ${JSON.stringify(projects, null, 2)}`, ); } async #duoProjectsForWorkspaceFolder({ workspaceFolder, baseUrl, }: { workspaceFolder: WorkspaceFolder; baseUrl: string; }): Promise { const remotes = await this.#gitlabRemotesForWorkspaceFolder(workspaceFolder, baseUrl); const projects = await Promise.all( remotes.map(async (remote) => { const enabled = await this.#checkDuoFeaturesEnabled(remote.namespaceWithPath); return { projectPath: remote.projectPath, uri: remote.fileUri, enabled, host: remote.host, namespace: remote.namespace, namespaceWithPath: remote.namespaceWithPath, } satisfies DuoProject; }), ); return projects; } async #gitlabRemotesForWorkspaceFolder( workspaceFolder: WorkspaceFolder, baseUrl: string, ): Promise { const paths = await this.directoryWalker.findFilesForDirectory({ directoryUri: workspaceFolder.uri, filters: { fileEndsWith: ['/.git/config'], }, }); const remotes = await Promise.all( paths.map(async (fileUri) => this.#gitlabRemotesForFileUri(fileUri.toString(), baseUrl)), ); return remotes.flat(); } async #gitlabRemotesForFileUri( fileUri: string, baseUrl: string, ): Promise { const remoteUrls = await this.#remoteUrlsFromGitConfig(fileUri); return remoteUrls.reduce((acc, remoteUrl) => { const remote = parseGitLabRemote(remoteUrl, baseUrl); if (remote) { acc.push({ ...remote, fileUri }); } return acc; }, []); } async #remoteUrlsFromGitConfig(fileUri: string): Promise { try { const fileString = await this.fileResolver.readFile({ fileUri }); const config = ini.parse(fileString); return this.#getRemoteUrls(config); } catch (error) { log.error(`DuoProjectAccessCache: Failed to read git config file: ${fileUri}`, error); return []; } } #getRemoteUrls(config: GitConfig): string[] { return Object.keys(config).reduce((acc, section) => { if (section.startsWith('remote ')) { acc.push(config[section].url); } return acc; }, []); } async #checkDuoFeaturesEnabled(projectPath: string): Promise { try { const response = await this.api.fetchFromApi<{ project: GqlProjectWithDuoEnabledInfo }>({ type: 'graphql', query: duoFeaturesEnabledQuery, variables: { projectPath, }, } satisfies ApiRequest<{ project: GqlProjectWithDuoEnabledInfo }>); return Boolean(response?.project?.duoFeaturesEnabled); } catch (error) { log.error( `DuoProjectAccessCache: Failed to check if Duo features are enabled for project: ${projectPath}`, error, ); return true; } } onDuoProjectCacheUpdate( listener: (duoProjectsCache: Map) => void, ): Disposable { this.#eventEmitter.on(DUO_PROJECT_CACHE_UPDATE_EVENT, listener); return { dispose: () => this.#eventEmitter.removeListener(DUO_PROJECT_CACHE_UPDATE_EVENT, listener), }; } #triggerChange() { this.#eventEmitter.emit(DUO_PROJECT_CACHE_UPDATE_EVENT, this.#duoProjects); } } References:" You are a code assistant,Definition of 'WebviewMetadata' in file src/common/webview/webview_metadata_provider.ts in project gitlab-lsp,"Definition: export type WebviewMetadata = { id: WebviewId; title: string; uris: string[]; }; export class WebviewMetadataProvider { #plugins: Set; #accessInfoProviders: WebviewLocationService; constructor(accessInfoProviders: WebviewLocationService, plugins: Set) { this.#accessInfoProviders = accessInfoProviders; this.#plugins = plugins; } getMetadata(): WebviewMetadata[] { return Array.from(this.#plugins).map((plugin) => ({ id: plugin.id, title: plugin.title, uris: this.#accessInfoProviders.resolveUris(plugin.id), })); } } References:" You are a code assistant,Definition of 'onNotification' in file packages/lib_webview_client/src/bus/provider/socket_io_message_bus.ts in project gitlab-lsp,"Definition: onNotification( messageType: T, callback: (payload: TMessages['inbound']['notifications'][T]) => void, ): Disposable { return this.#notificationHandlers.register(messageType, callback); } onRequest( type: T, handler: ( payload: TMessages['inbound']['requests'][T]['params'], ) => Promise>, ): Disposable { return this.#requestHandlers.register(type, handler); } dispose() { this.#socket.off(SOCKET_NOTIFICATION_CHANNEL, this.#handleNotificationMessage); this.#socket.off(SOCKET_REQUEST_CHANNEL, this.#handleRequestMessage); this.#socket.off(SOCKET_RESPONSE_CHANNEL, this.#handleResponseMessage); this.#notificationHandlers.dispose(); this.#requestHandlers.dispose(); this.#pendingRequests.dispose(); } #setupSocketEventHandlers = () => { this.#socket.on(SOCKET_NOTIFICATION_CHANNEL, this.#handleNotificationMessage); this.#socket.on(SOCKET_REQUEST_CHANNEL, this.#handleRequestMessage); this.#socket.on(SOCKET_RESPONSE_CHANNEL, this.#handleResponseMessage); }; #handleNotificationMessage = async (message: { type: keyof TMessages['inbound']['notifications'] & string; payload: unknown; }) => { await this.#notificationHandlers.handle(message.type, message.payload); }; #handleRequestMessage = async (message: { requestId: string; event: keyof TMessages['inbound']['requests'] & string; payload: unknown; }) => { const response = await this.#requestHandlers.handle(message.event, message.payload); this.#socket.emit(SOCKET_RESPONSE_CHANNEL, { requestId: message.requestId, payload: response, }); }; #handleResponseMessage = async (message: { requestId: string; payload: unknown }) => { await this.#pendingRequests.handle(message.requestId, message.payload); }; } References:" You are a code assistant,Definition of 'constructor' in file src/common/api.ts in project gitlab-lsp,"Definition: constructor(lsFetch: LsFetch, configService: ConfigService) { this.#baseURL = GITLAB_API_BASE_URL; this.#lsFetch = lsFetch; this.#configService = configService; this.#configService.onConfigChange(async (config) => { this.#clientInfo = configService.get('client.clientInfo'); this.#lsFetch.updateAgentOptions({ ignoreCertificateErrors: this.#configService.get('client.ignoreCertificateErrors') ?? false, ...(this.#configService.get('client.httpAgentOptions') ?? {}), }); await this.configureApi(config.client); }); } onApiReconfigured(listener: (data: ApiReconfiguredData) => void): Disposable { this.#eventEmitter.on(CONFIG_CHANGE_EVENT_NAME, listener); return { dispose: () => this.#eventEmitter.removeListener(CONFIG_CHANGE_EVENT_NAME, listener) }; } #fireApiReconfigured(isInValidState: boolean, validationMessage?: string) { const data: ApiReconfiguredData = { isInValidState, validationMessage }; this.#eventEmitter.emit(CONFIG_CHANGE_EVENT_NAME, data); } async configureApi({ token, baseUrl = GITLAB_API_BASE_URL, }: { token?: string; baseUrl?: string; }) { if (this.#token === token && this.#baseURL === baseUrl) return; this.#token = token; this.#baseURL = baseUrl; const { valid, reason, message } = await this.checkToken(this.#token); let validationMessage; if (!valid) { this.#configService.set('client.token', undefined); validationMessage = `Token is invalid. ${message}. Reason: ${reason}`; log.warn(validationMessage); } else { log.info('Token is valid'); } this.#instanceVersion = await this.#getGitLabInstanceVersion(); this.#fireApiReconfigured(valid, validationMessage); } #looksLikePatToken(token: string): boolean { // OAuth tokens will be longer than 42 characters and PATs will be shorter. return token.length < 42; } async #checkPatToken(token: string): Promise { const headers = this.#getDefaultHeaders(token); const response = await this.#lsFetch.get( `${this.#baseURL}/api/v4/personal_access_tokens/self`, { headers }, ); await handleFetchError(response, 'Information about personal access token'); const { active, scopes } = (await response.json()) as PersonalAccessToken; if (!active) { return { valid: false, reason: 'not_active', message: 'Token is not active.', }; } if (!this.#hasValidScopes(scopes)) { const joinedScopes = scopes.map((scope) => `'${scope}'`).join(', '); return { valid: false, reason: 'invalid_scopes', message: `Token has scope(s) ${joinedScopes} (needs 'api').`, }; } return { valid: true }; } async #checkOAuthToken(token: string): Promise { const headers = this.#getDefaultHeaders(token); const response = await this.#lsFetch.get(`${this.#baseURL}/oauth/token/info`, { headers, }); await handleFetchError(response, 'Information about OAuth token'); const { scope: scopes } = (await response.json()) as OAuthToken; if (!this.#hasValidScopes(scopes)) { const joinedScopes = scopes.map((scope) => `'${scope}'`).join(', '); return { valid: false, reason: 'invalid_scopes', message: `Token has scope(s) ${joinedScopes} (needs 'api').`, }; } return { valid: true }; } async checkToken(token: string = ''): Promise { try { if (this.#looksLikePatToken(token)) { log.info('Checking token for PAT validity'); return await this.#checkPatToken(token); } log.info('Checking token for OAuth validity'); return await this.#checkOAuthToken(token); } catch (err) { log.error('Error performing token check', err); return { valid: false, reason: 'unknown', message: `Failed to check token: ${err}`, }; } } #hasValidScopes(scopes: string[]): boolean { return scopes.includes('api'); } async getCodeSuggestions( request: CodeSuggestionRequest, ): Promise { if (!this.#token) { throw new Error('Token needs to be provided to request Code Suggestions'); } const headers = { ...this.#getDefaultHeaders(this.#token), 'Content-Type': 'application/json', }; const response = await this.#lsFetch.post( `${this.#baseURL}/api/v4/code_suggestions/completions`, { headers, body: JSON.stringify(request) }, ); await handleFetchError(response, 'Code Suggestions'); const data = await response.json(); return { ...data, status: response.status }; } async *getStreamingCodeSuggestions( request: CodeSuggestionRequest, ): AsyncGenerator { if (!this.#token) { throw new Error('Token needs to be provided to stream code suggestions'); } const headers = { ...this.#getDefaultHeaders(this.#token), 'Content-Type': 'application/json', }; yield* this.#lsFetch.streamFetch( `${this.#baseURL}/api/v4/code_suggestions/completions`, JSON.stringify(request), headers, ); } async fetchFromApi(request: ApiRequest): Promise { if (!this.#token) { return Promise.reject(new Error('Token needs to be provided to authorise API request.')); } if ( request.supportedSinceInstanceVersion && !this.#instanceVersionHigherOrEqualThen(request.supportedSinceInstanceVersion.version) ) { return Promise.reject( new InvalidInstanceVersionError( `Can't ${request.supportedSinceInstanceVersion.resourceName} until your instance is upgraded to ${request.supportedSinceInstanceVersion.version} or higher.`, ), ); } if (request.type === 'graphql') { return this.#graphqlRequest(request.query, request.variables); } switch (request.method) { case 'GET': return this.#fetch(request.path, request.searchParams, 'resource', request.headers); case 'POST': return this.#postFetch(request.path, 'resource', request.body, request.headers); default: // the type assertion is necessary because TS doesn't expect any other types throw new Error(`Unknown request type ${(request as ApiRequest).type}`); } } async connectToCable(): Promise { const headers = this.#getDefaultHeaders(this.#token); const websocketOptions = { headers: { ...headers, Origin: this.#baseURL, }, }; return connectToCable(this.#baseURL, websocketOptions); } async #graphqlRequest( document: RequestDocument, variables?: V, ): Promise { const ensureEndsWithSlash = (url: string) => url.replace(/\/?$/, '/'); const endpoint = new URL('./api/graphql', ensureEndsWithSlash(this.#baseURL)).href; // supports GitLab instances that are on a custom path, e.g. ""https://example.com/gitlab"" const graphqlFetch = async ( input: RequestInfo | URL, init?: RequestInit, ): Promise => { const url = input instanceof URL ? input.toString() : input; return this.#lsFetch.post(url, { ...init, headers: { ...headers, ...init?.headers }, }); }; const headers = this.#getDefaultHeaders(this.#token); const client = new GraphQLClient(endpoint, { headers, fetch: graphqlFetch, }); return client.request(document, variables); } async #fetch( apiResourcePath: string, query: Record = {}, resourceName = 'resource', headers?: Record, ): Promise { const url = `${this.#baseURL}/api/v4${apiResourcePath}${createQueryString(query)}`; const result = await this.#lsFetch.get(url, { headers: { ...this.#getDefaultHeaders(this.#token), ...headers }, }); await handleFetchError(result, resourceName); return result.json() as Promise; } async #postFetch( apiResourcePath: string, resourceName = 'resource', body?: unknown, headers?: Record, ): Promise { const url = `${this.#baseURL}/api/v4${apiResourcePath}`; const response = await this.#lsFetch.post(url, { headers: { 'Content-Type': 'application/json', ...this.#getDefaultHeaders(this.#token), ...headers, }, body: JSON.stringify(body), }); await handleFetchError(response, resourceName); return response.json() as Promise; } #getDefaultHeaders(token?: string) { return { Authorization: `Bearer ${token}`, 'User-Agent': `code-completions-language-server-experiment (${this.#clientInfo?.name}:${this.#clientInfo?.version})`, 'X-Gitlab-Language-Server-Version': getLanguageServerVersion(), }; } #instanceVersionHigherOrEqualThen(version: string): boolean { if (!this.#instanceVersion) return false; return semverCompare(this.#instanceVersion, version) >= 0; } async #getGitLabInstanceVersion(): Promise { if (!this.#token) { return ''; } const headers = this.#getDefaultHeaders(this.#token); const response = await this.#lsFetch.get(`${this.#baseURL}/api/v4/version`, { headers, }); const { version } = await response.json(); return version; } get instanceVersion() { return this.#instanceVersion; } } References:" You are a code assistant,Definition of 'RequestListener' in file packages/lib_message_bus/src/types/bus.ts in project gitlab-lsp,"Definition: export interface RequestListener { onRequest>( type: T, handler: () => Promise>, ): Disposable; onRequest( type: T, handler: (payload: TRequests[T]['params']) => Promise>, ): Disposable; } /** * Defines the structure for message definitions, including notifications and requests. */ export type MessageDefinitions< TNotifications extends NotificationMap = NotificationMap, TRequests extends RequestMap = RequestMap, > = { notifications: TNotifications; requests: TRequests; }; export type MessageMap< TInboundMessageDefinitions extends MessageDefinitions = MessageDefinitions, TOutboundMessageDefinitions extends MessageDefinitions = MessageDefinitions, > = { inbound: TInboundMessageDefinitions; outbound: TOutboundMessageDefinitions; }; export interface MessageBus extends NotificationPublisher, NotificationListener, RequestPublisher, RequestListener {} References:" You are a code assistant,Definition of 'Greet3' in file src/tests/fixtures/intent/empty_function/python.py in project gitlab-lsp,"Definition: 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:34" You are a code assistant,Definition of 'serializeAccountSafe' in file packages/webview_duo_chat/src/plugin/port/platform/gitlab_account.ts in project gitlab-lsp,"Definition: 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: - packages/webview_duo_chat/src/plugin/port/platform/gitlab_account.test.ts:14" You are a code assistant,Definition of 'WebviewSocketConnectionId' in file packages/lib_webview_transport_socket_io/src/utils/connection_utils.ts in project gitlab-lsp,"Definition: export type WebviewSocketConnectionId = string & { __type: 'WebviewSocketConnectionId' }; export function buildConnectionId( webviewInstanceInfo: WebviewInstanceInfo, ): WebviewSocketConnectionId { return `${webviewInstanceInfo.webviewId}:${webviewInstanceInfo.webviewInstanceId}` as WebviewSocketConnectionId; } References: - packages/lib_webview_transport_socket_io/src/utils/connection_utils.ts:7" You are a code assistant,Definition of 'setup' in file src/common/log.ts in project gitlab-lsp,"Definition: setup(configService: ConfigService) { this.#configService = configService; } /** * @param messageOrError can be error (if we don't want to provide any additional info), or a string message * @param trailingError is an optional error (if messageOrError was a message) * but we also mention `unknown` type because JS doesn't guarantee that in `catch(e)`, * the `e` is an `Error`, it can be anything. * */ #log( incomingLogLevel: LogLevel, messageOrError: Error | string, trailingError?: Error | unknown, ) { const configuredLevel = this.#configService?.get('client.logLevel'); const shouldShowLog = getNumericMapping(configuredLevel) >= LOG_LEVEL_MAPPING[incomingLogLevel]; if (shouldShowLog) { logWithLevel(incomingLogLevel, messageOrError, ensureError(trailingError)); } } debug(messageOrError: Error | string, trailingError?: Error | unknown) { this.#log(LOG_LEVEL.DEBUG, messageOrError, trailingError); } info(messageOrError: Error | string, trailingError?: Error | unknown) { this.#log(LOG_LEVEL.INFO, messageOrError, trailingError); } warn(messageOrError: Error | string, trailingError?: Error | unknown) { this.#log(LOG_LEVEL.WARNING, messageOrError, trailingError); } error(messageOrError: Error | string, trailingError?: Error | unknown) { this.#log(LOG_LEVEL.ERROR, messageOrError, trailingError); } } // TODO: rename the export and replace usages of `log` with `Log`. export const log = new Log(); References: - src/common/connection.test.ts:43 - src/browser/main.ts:122 - src/node/main.ts:197" You are a code assistant,Definition of 'GitLabChatApi' in file packages/webview_duo_chat/src/plugin/port/chat/gitlab_chat_api.ts in project gitlab-lsp,"Definition: export class GitLabChatApi { #cachedActionQuery?: ChatInputTemplate = undefined; #manager: GitLabPlatformManagerForChat; constructor(manager: GitLabPlatformManagerForChat) { this.#manager = manager; } async processNewUserPrompt( question: string, subscriptionId?: string, currentFileContext?: GitLabChatFileContext, ): Promise { return this.#sendAiAction({ question, currentFileContext, clientSubscriptionId: subscriptionId, }); } async pullAiMessage(requestId: string, role: string): Promise { const response = await pullHandler(() => this.#getAiMessage(requestId, role)); if (!response) return errorResponse(requestId, ['Reached timeout while fetching response.']); return successResponse(response); } async cleanChat(): Promise { return this.#sendAiAction({ question: SPECIAL_MESSAGES.CLEAN }); } async #currentPlatform() { const platform = await this.#manager.getGitLabPlatform(); if (!platform) throw new Error('Platform is missing!'); return platform; } async #getAiMessage(requestId: string, role: string): Promise { const request: GraphQLRequest = { type: 'graphql', query: AI_MESSAGES_QUERY, variables: { requestIds: [requestId], roles: [role.toUpperCase()] }, }; const platform = await this.#currentPlatform(); const history = await platform.fetchFromApi(request); return history.aiMessages.nodes[0]; } async subscribeToUpdates( messageCallback: (message: AiCompletionResponseMessageType) => Promise, subscriptionId?: string, ) { const platform = await this.#currentPlatform(); const channel = new AiCompletionResponseChannel({ htmlResponse: true, userId: `gid://gitlab/User/${extractUserId(platform.account.id)}`, aiAction: 'CHAT', clientSubscriptionId: subscriptionId, }); const cable = await platform.connectToCable(); // we use this flag to fix https://gitlab.com/gitlab-org/gitlab-vscode-extension/-/issues/1397 // sometimes a chunk comes after the full message and it broke the chat let fullMessageReceived = false; channel.on('newChunk', async (msg) => { if (fullMessageReceived) { log.info(`CHAT-DEBUG: full message received, ignoring chunk`); return; } await messageCallback(msg); }); channel.on('fullMessage', async (message) => { fullMessageReceived = true; await messageCallback(message); if (subscriptionId) { cable.disconnect(); } }); cable.subscribe(channel); } async #sendAiAction(variables: object): Promise { const platform = await this.#currentPlatform(); const { query, defaultVariables } = await this.#actionQuery(); const projectGqlId = await this.#manager.getProjectGqlId(); const request: GraphQLRequest = { type: 'graphql', query, variables: { ...variables, ...defaultVariables, resourceId: projectGqlId ?? null, }, }; return platform.fetchFromApi(request); } async #actionQuery(): Promise { if (!this.#cachedActionQuery) { const platform = await this.#currentPlatform(); try { const { version } = await platform.fetchFromApi(versionRequest); this.#cachedActionQuery = ifVersionGte( version, MINIMUM_PLATFORM_ORIGIN_FIELD_VERSION, () => CHAT_INPUT_TEMPLATE_17_3_AND_LATER, () => CHAT_INPUT_TEMPLATE_17_2_AND_EARLIER, ); } catch (e) { log.debug(`GitLab version check for sending chat failed:`, e as Error); this.#cachedActionQuery = CHAT_INPUT_TEMPLATE_17_3_AND_LATER; } } return this.#cachedActionQuery; } } References: - packages/webview_duo_chat/src/plugin/port/chat/gitlab_chat_api.test.ts:87 - packages/webview_duo_chat/src/plugin/chat_controller.ts:11 - packages/webview_duo_chat/src/plugin/port/chat/gitlab_chat_api.test.ts:52 - packages/webview_duo_chat/src/plugin/port/chat/gitlab_chat_api.test.ts:118 - packages/webview_duo_chat/src/plugin/chat_controller.ts:24" You are a code assistant,Definition of 'FakeRequestHandler' in file packages/webview_duo_chat/src/plugin/port/test_utils/create_fake_fetch_from_api.ts in project gitlab-lsp,"Definition: export interface FakeRequestHandler { request: ApiRequest; response: T; } export const createFakeFetchFromApi = (...handlers: FakeRequestHandler[]): fetchFromApi => async (request: ApiRequest) => { const handler = handlers.find((h) => isEqual(h.request, request)); if (!handler) { throw new Error(`No fake handler to handle request: ${JSON.stringify(request)}`); } return handler.response as T; }; References:" You are a code assistant,Definition of 'GitLabChatFileContext' in file packages/webview_duo_chat/src/plugin/port/chat/gitlab_chat_file_context.ts in project gitlab-lsp,"Definition: export type GitLabChatFileContext = { fileName: string; selectedText: string; contentAboveCursor: string | null; contentBelowCursor: string | null; }; export const getActiveFileContext = (): GitLabChatFileContext | undefined => { const selectedText = getSelectedText(); const fileName = getActiveFileName(); if (!selectedText || !fileName) { return undefined; } return { selectedText, fileName, contentAboveCursor: getTextBeforeSelected(), contentBelowCursor: getTextAfterSelected(), }; }; References: - packages/webview_duo_chat/src/plugin/port/chat/gitlab_chat_api.ts:159 - packages/webview_duo_chat/src/plugin/port/chat/gitlab_chat_record_context.ts:4" You are a code assistant,Definition of 'onInstanceConnected' in file packages/lib_webview/src/setup/plugin/webview_controller.ts in project gitlab-lsp,"Definition: onInstanceConnected(handler: WebviewMessageBusManagerHandler) { this.#handlers.add(handler); for (const [instanceId, info] of this.#instanceInfos) { const disposable = handler(instanceId, info.messageBus); if (isDisposable(disposable)) { info.pluginCallbackDisposables.add(disposable); } } } dispose(): void { this.#compositeDisposable.dispose(); this.#instanceInfos.forEach((info) => info.messageBus.dispose()); this.#instanceInfos.clear(); } #subscribeToEvents(runtimeMessageBus: WebviewRuntimeMessageBus) { const eventFilter = buildWebviewIdFilter(this.webviewId); this.#compositeDisposable.add( runtimeMessageBus.subscribe('webview:connect', this.#handleConnected.bind(this), eventFilter), runtimeMessageBus.subscribe( 'webview:disconnect', this.#handleDisconnected.bind(this), eventFilter, ), ); } #handleConnected(address: WebviewAddress) { this.#logger.debug(`Instance connected: ${address.webviewInstanceId}`); if (this.#instanceInfos.has(address.webviewInstanceId)) { // we are already connected with this webview instance return; } const messageBus = this.#messageBusFactory(address); const pluginCallbackDisposables = new CompositeDisposable(); this.#instanceInfos.set(address.webviewInstanceId, { messageBus, pluginCallbackDisposables, }); this.#handlers.forEach((handler) => { const disposable = handler(address.webviewInstanceId, messageBus); if (isDisposable(disposable)) { pluginCallbackDisposables.add(disposable); } }); } #handleDisconnected(address: WebviewAddress) { this.#logger.debug(`Instance disconnected: ${address.webviewInstanceId}`); const instanceInfo = this.#instanceInfos.get(address.webviewInstanceId); if (!instanceInfo) { // we aren't tracking this instance return; } instanceInfo.pluginCallbackDisposables.dispose(); instanceInfo.messageBus.dispose(); this.#instanceInfos.delete(address.webviewInstanceId); } } References:" You are a code assistant,Definition of 'AiMessageResponseType' in file packages/webview_duo_chat/src/plugin/port/chat/gitlab_chat_api.ts in project gitlab-lsp,"Definition: type AiMessageResponseType = { requestId: string; role: string; content: string; contentHtml: string; timestamp: string; errors: string[]; extras?: { sources: object[]; }; }; type AiMessagesResponseType = { aiMessages: { nodes: AiMessageResponseType[]; }; }; interface ErrorMessage { type: 'error'; requestId: string; role: 'system'; errors: string[]; } const errorResponse = (requestId: string, errors: string[]): ErrorMessage => ({ requestId, errors, role: 'system', type: 'error', }); interface SuccessMessage { type: 'message'; requestId: string; role: string; content: string; contentHtml: string; timestamp: string; errors: string[]; extras?: { sources: object[]; }; } const successResponse = (response: AiMessageResponseType): SuccessMessage => ({ type: 'message', ...response, }); type AiMessage = SuccessMessage | ErrorMessage; type ChatInputTemplate = { query: string; defaultVariables: { platformOrigin?: string; }; }; export class GitLabChatApi { #cachedActionQuery?: ChatInputTemplate = undefined; #manager: GitLabPlatformManagerForChat; constructor(manager: GitLabPlatformManagerForChat) { this.#manager = manager; } async processNewUserPrompt( question: string, subscriptionId?: string, currentFileContext?: GitLabChatFileContext, ): Promise { return this.#sendAiAction({ question, currentFileContext, clientSubscriptionId: subscriptionId, }); } async pullAiMessage(requestId: string, role: string): Promise { const response = await pullHandler(() => this.#getAiMessage(requestId, role)); if (!response) return errorResponse(requestId, ['Reached timeout while fetching response.']); return successResponse(response); } async cleanChat(): Promise { return this.#sendAiAction({ question: SPECIAL_MESSAGES.CLEAN }); } async #currentPlatform() { const platform = await this.#manager.getGitLabPlatform(); if (!platform) throw new Error('Platform is missing!'); return platform; } async #getAiMessage(requestId: string, role: string): Promise { const request: GraphQLRequest = { type: 'graphql', query: AI_MESSAGES_QUERY, variables: { requestIds: [requestId], roles: [role.toUpperCase()] }, }; const platform = await this.#currentPlatform(); const history = await platform.fetchFromApi(request); return history.aiMessages.nodes[0]; } async subscribeToUpdates( messageCallback: (message: AiCompletionResponseMessageType) => Promise, subscriptionId?: string, ) { const platform = await this.#currentPlatform(); const channel = new AiCompletionResponseChannel({ htmlResponse: true, userId: `gid://gitlab/User/${extractUserId(platform.account.id)}`, aiAction: 'CHAT', clientSubscriptionId: subscriptionId, }); const cable = await platform.connectToCable(); // we use this flag to fix https://gitlab.com/gitlab-org/gitlab-vscode-extension/-/issues/1397 // sometimes a chunk comes after the full message and it broke the chat let fullMessageReceived = false; channel.on('newChunk', async (msg) => { if (fullMessageReceived) { log.info(`CHAT-DEBUG: full message received, ignoring chunk`); return; } await messageCallback(msg); }); channel.on('fullMessage', async (message) => { fullMessageReceived = true; await messageCallback(message); if (subscriptionId) { cable.disconnect(); } }); cable.subscribe(channel); } async #sendAiAction(variables: object): Promise { const platform = await this.#currentPlatform(); const { query, defaultVariables } = await this.#actionQuery(); const projectGqlId = await this.#manager.getProjectGqlId(); const request: GraphQLRequest = { type: 'graphql', query, variables: { ...variables, ...defaultVariables, resourceId: projectGqlId ?? null, }, }; return platform.fetchFromApi(request); } async #actionQuery(): Promise { if (!this.#cachedActionQuery) { const platform = await this.#currentPlatform(); try { const { version } = await platform.fetchFromApi(versionRequest); this.#cachedActionQuery = ifVersionGte( version, MINIMUM_PLATFORM_ORIGIN_FIELD_VERSION, () => CHAT_INPUT_TEMPLATE_17_3_AND_LATER, () => CHAT_INPUT_TEMPLATE_17_2_AND_EARLIER, ); } catch (e) { log.debug(`GitLab version check for sending chat failed:`, e as Error); this.#cachedActionQuery = CHAT_INPUT_TEMPLATE_17_3_AND_LATER; } } return this.#cachedActionQuery; } } References: - packages/webview_duo_chat/src/plugin/port/chat/gitlab_chat_api.ts:133" You are a code assistant,Definition of 'GitLabRemote' in file src/common/services/git/git_remote_parser.ts in project gitlab-lsp,"Definition: export interface GitLabRemote { host: string; /** * Namespace is the group(s) or user to whom the project belongs: https://docs.gitlab.com/ee/api/projects.html#get-single-project * * e.g. `gitlab-org/security` in the `gitlab-org/security/gitlab-vscode-extension` project */ namespace: string; /** * Path is the ""project slug"": https://docs.gitlab.com/ee/api/projects.html#get-single-project * * e.g. `gitlab-vscode-extension` in the `gitlab-org/gitlab-vscode-extension` project */ projectPath: string; /** * Namespace with path is the full project identifier: https://docs.gitlab.com/ee/api/projects.html#get-single-project * * e.g. `gitlab-org/gitlab-vscode-extension` */ namespaceWithPath: string; } // returns path without the trailing slash or empty string if there is no path const getInstancePath = (instanceUrl: string) => { const { pathname } = tryParseUrl(instanceUrl) || {}; return pathname ? pathname.replace(/\/$/, '') : ''; }; const escapeForRegExp = (str: string) => str.replace(/[-[\]/{}()*+?.\\^$|]/g, '\\$&'); function normalizeSshRemote(remote: string): string { // Regex to match git SSH remotes with custom port. // Example: [git@dev.company.com:7999]:group/repo_name.git // For more information see: // https://gitlab.com/gitlab-org/gitlab-vscode-extension/-/issues/309 const sshRemoteWithCustomPort = remote.match(`^\\[([a-zA-Z0-9_-]+@.*?):\\d+\\](.*)$`); if (sshRemoteWithCustomPort) { return `ssh://${sshRemoteWithCustomPort[1]}/${sshRemoteWithCustomPort[2]}`; } // Regex to match git SSH remotes with URL scheme and a custom port // Example: ssh://git@example.com:2222/fatihacet/gitlab-vscode-extension.git // For more information see: // https://gitlab.com/gitlab-org/gitlab-vscode-extension/-/issues/644 const sshRemoteWithSchemeAndCustomPort = remote.match(`^ssh://([a-zA-Z0-9_-]+@.*?):\\d+(.*)$`); if (sshRemoteWithSchemeAndCustomPort) { return `ssh://${sshRemoteWithSchemeAndCustomPort[1]}${sshRemoteWithSchemeAndCustomPort[2]}`; } // Regex to match git SSH remotes without URL scheme and no custom port // Example: git@example.com:2222/fatihacet/gitlab-vscode-extension.git // For more information see this comment: // https://gitlab.com/gitlab-org/gitlab-vscode-extension/-/issues/611#note_1154175809 const sshRemoteWithPath = remote.match(`([a-zA-Z0-9_-]+@.*?):(.*)`); if (sshRemoteWithPath) { return `ssh://${sshRemoteWithPath[1]}/${sshRemoteWithPath[2]}`; } if (remote.match(`^[a-zA-Z0-9_-]+@`)) { // Regex to match gitlab potential starting names for ssh remotes. return `ssh://${remote}`; } return remote; } export function parseGitLabRemote(remote: string, instanceUrl: string): GitLabRemote | undefined { const { host, pathname } = tryParseUrl(normalizeSshRemote(remote)) || {}; if (!host || !pathname) { return undefined; } // The instance url might have a custom route, i.e. www.company.com/gitlab. This route is // optional in the remote url. This regex extracts namespace and project from the remote // url while ignoring any custom route, if present. For more information see: // - https://gitlab.com/gitlab-org/gitlab-vscode-extension/-/merge_requests/11 // - https://gitlab.com/gitlab-org/gitlab-vscode-extension/-/issues/103 const pathRegExp = instanceUrl || instanceUrl.trim() !== '' ? escapeForRegExp(getInstancePath(instanceUrl)) : ''; const match = pathname.match(`(?:${pathRegExp})?/:?(.+)/([^/]+?)(?:.git)?/?$`); if (!match) { return undefined; } const [namespace, projectPath] = match.slice(1, 3); const namespaceWithPath = `${namespace}/${projectPath}`; return { host, namespace, projectPath, namespaceWithPath }; } References:" You are a code assistant,Definition of 'COMPLETION_PARAMS' in file src/common/test_utils/mocks.ts in project gitlab-lsp,"Definition: export const COMPLETION_PARAMS: TextDocumentPositionParams = { textDocument, position }; References:" You are a code assistant,Definition of 'createTreeSitterMiddleware' in file src/common/suggestion_client/tree_sitter_middleware.ts in project gitlab-lsp,"Definition: export const createTreeSitterMiddleware = ({ treeSitterParser, getIntentFn, }: { treeSitterParser: TreeSitterParser; getIntentFn: typeof getIntent; }): SuggestionClientMiddleware => async (context, next) => { if (context.intent) { return next(context); } let treeAndLanguage: TreeAndLanguage | undefined; try { treeAndLanguage = await treeSitterParser.parseFile(context.document); } catch (err) { log.warn('Error determining user intent for code suggestion request.', err); } if (!treeAndLanguage) { return next(context); } const { intent } = await getIntentFn({ treeAndLanguage, position: context.document.position, prefix: context.document.prefix, suffix: context.document.suffix, }); return next({ ...context, intent }); }; References: - src/common/suggestion/suggestion_service.ts:167 - src/common/suggestion_client/tree_sitter_middleware.test.ts:38" You are a code assistant,Definition of 'DEFAULT_BACKOFF_MULTIPLIER' in file src/common/circuit_breaker/exponential_backoff_circuit_breaker.ts in project gitlab-lsp,"Definition: export const DEFAULT_BACKOFF_MULTIPLIER = 2; export interface ExponentialBackoffCircuitBreakerOptions { maxErrorsBeforeBreaking?: number; initialBackoffMs?: number; maxBackoffMs?: number; backoffMultiplier?: number; } export class ExponentialBackoffCircuitBreaker implements CircuitBreaker { #name: string; #state: CircuitBreakerState = CircuitBreakerState.CLOSED; readonly #initialBackoffMs: number; readonly #maxBackoffMs: number; readonly #backoffMultiplier: number; #errorCount = 0; #eventEmitter = new EventEmitter(); #timeoutId: NodeJS.Timeout | null = null; constructor( name: string, { initialBackoffMs = DEFAULT_INITIAL_BACKOFF_MS, maxBackoffMs = DEFAULT_MAX_BACKOFF_MS, backoffMultiplier = DEFAULT_BACKOFF_MULTIPLIER, }: ExponentialBackoffCircuitBreakerOptions = {}, ) { this.#name = name; this.#initialBackoffMs = initialBackoffMs; this.#maxBackoffMs = maxBackoffMs; this.#backoffMultiplier = backoffMultiplier; } error() { this.#errorCount += 1; this.#open(); } megaError() { this.#errorCount += 3; this.#open(); } #open() { if (this.#state === CircuitBreakerState.OPEN) { return; } this.#state = CircuitBreakerState.OPEN; log.warn( `Excess errors detected, opening '${this.#name}' circuit breaker for ${this.#getBackoffTime() / 1000} second(s).`, ); this.#timeoutId = setTimeout(() => this.#close(), this.#getBackoffTime()); this.#eventEmitter.emit('open'); } #close() { if (this.#state === CircuitBreakerState.CLOSED) { return; } if (this.#timeoutId) { clearTimeout(this.#timeoutId); } this.#state = CircuitBreakerState.CLOSED; this.#eventEmitter.emit('close'); } isOpen() { return this.#state === CircuitBreakerState.OPEN; } 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) }; } #getBackoffTime() { return Math.min( this.#initialBackoffMs * this.#backoffMultiplier ** (this.#errorCount - 1), this.#maxBackoffMs, ); } } References:" You are a code assistant,Definition of 'checkToken' in file src/common/api.ts in project gitlab-lsp,"Definition: checkToken(token: string | undefined): Promise; getCodeSuggestions(request: CodeSuggestionRequest): Promise; getStreamingCodeSuggestions(request: CodeSuggestionRequest): AsyncGenerator; fetchFromApi(request: ApiRequest): Promise; connectToCable(): Promise; onApiReconfigured(listener: (data: ApiReconfiguredData) => void): Disposable; readonly instanceVersion?: string; } export const GitLabApiClient = createInterfaceId('GitLabApiClient'); export type GenerationType = 'comment' | 'small_file' | 'empty_function' | undefined; export interface CodeSuggestionRequest { prompt_version: number; project_path: string; model_provider?: string; project_id: number; current_file: CodeSuggestionRequestCurrentFile; intent?: 'completion' | 'generation'; stream?: boolean; /** how many suggestion options should the API return */ choices_count?: number; /** additional context to provide to the model */ context?: AdditionalContext[]; /* A user's instructions for code suggestions. */ user_instruction?: string; /* The backend can add additional prompt info based on the type of event */ generation_type?: GenerationType; } export interface CodeSuggestionRequestCurrentFile { file_name: string; content_above_cursor: string; content_below_cursor: string; } export interface CodeSuggestionResponse { choices?: SuggestionOption[]; model?: ICodeSuggestionModel; status: number; error?: string; isDirectConnection?: boolean; } // FIXME: Rename to SuggestionOptionStream when renaming the SuggestionOption export interface StartStreamOption { uniqueTrackingId: string; /** the streamId represents the beginning of a stream * */ streamId: string; } export type SuggestionOptionOrStream = SuggestionOption | StartStreamOption; export interface PersonalAccessToken { name: string; scopes: string[]; active: boolean; } export interface OAuthToken { scope: string[]; } export interface TokenCheckResponse { valid: boolean; reason?: 'unknown' | 'not_active' | 'invalid_scopes'; message?: string; } export interface IDirectConnectionDetailsHeaders { 'X-Gitlab-Global-User-Id': string; 'X-Gitlab-Instance-Id': string; 'X-Gitlab-Host-Name': string; 'X-Gitlab-Saas-Duo-Pro-Namespace-Ids': string; } export interface IDirectConnectionModelDetails { model_provider: string; model_name: string; } export interface IDirectConnectionDetails { base_url: string; token: string; expires_at: number; headers: IDirectConnectionDetailsHeaders; model_details: IDirectConnectionModelDetails; } const CONFIG_CHANGE_EVENT_NAME = 'apiReconfigured'; @Injectable(GitLabApiClient, [LsFetch, ConfigService]) export class GitLabAPI implements GitLabApiClient { #token: string | undefined; #baseURL: string; #clientInfo?: IClientInfo; #lsFetch: LsFetch; #eventEmitter = new EventEmitter(); #configService: ConfigService; #instanceVersion?: string; constructor(lsFetch: LsFetch, configService: ConfigService) { this.#baseURL = GITLAB_API_BASE_URL; this.#lsFetch = lsFetch; this.#configService = configService; this.#configService.onConfigChange(async (config) => { this.#clientInfo = configService.get('client.clientInfo'); this.#lsFetch.updateAgentOptions({ ignoreCertificateErrors: this.#configService.get('client.ignoreCertificateErrors') ?? false, ...(this.#configService.get('client.httpAgentOptions') ?? {}), }); await this.configureApi(config.client); }); } onApiReconfigured(listener: (data: ApiReconfiguredData) => void): Disposable { this.#eventEmitter.on(CONFIG_CHANGE_EVENT_NAME, listener); return { dispose: () => this.#eventEmitter.removeListener(CONFIG_CHANGE_EVENT_NAME, listener) }; } #fireApiReconfigured(isInValidState: boolean, validationMessage?: string) { const data: ApiReconfiguredData = { isInValidState, validationMessage }; this.#eventEmitter.emit(CONFIG_CHANGE_EVENT_NAME, data); } async configureApi({ token, baseUrl = GITLAB_API_BASE_URL, }: { token?: string; baseUrl?: string; }) { if (this.#token === token && this.#baseURL === baseUrl) return; this.#token = token; this.#baseURL = baseUrl; const { valid, reason, message } = await this.checkToken(this.#token); let validationMessage; if (!valid) { this.#configService.set('client.token', undefined); validationMessage = `Token is invalid. ${message}. Reason: ${reason}`; log.warn(validationMessage); } else { log.info('Token is valid'); } this.#instanceVersion = await this.#getGitLabInstanceVersion(); this.#fireApiReconfigured(valid, validationMessage); } #looksLikePatToken(token: string): boolean { // OAuth tokens will be longer than 42 characters and PATs will be shorter. return token.length < 42; } async #checkPatToken(token: string): Promise { const headers = this.#getDefaultHeaders(token); const response = await this.#lsFetch.get( `${this.#baseURL}/api/v4/personal_access_tokens/self`, { headers }, ); await handleFetchError(response, 'Information about personal access token'); const { active, scopes } = (await response.json()) as PersonalAccessToken; if (!active) { return { valid: false, reason: 'not_active', message: 'Token is not active.', }; } if (!this.#hasValidScopes(scopes)) { const joinedScopes = scopes.map((scope) => `'${scope}'`).join(', '); return { valid: false, reason: 'invalid_scopes', message: `Token has scope(s) ${joinedScopes} (needs 'api').`, }; } return { valid: true }; } async #checkOAuthToken(token: string): Promise { const headers = this.#getDefaultHeaders(token); const response = await this.#lsFetch.get(`${this.#baseURL}/oauth/token/info`, { headers, }); await handleFetchError(response, 'Information about OAuth token'); const { scope: scopes } = (await response.json()) as OAuthToken; if (!this.#hasValidScopes(scopes)) { const joinedScopes = scopes.map((scope) => `'${scope}'`).join(', '); return { valid: false, reason: 'invalid_scopes', message: `Token has scope(s) ${joinedScopes} (needs 'api').`, }; } return { valid: true }; } async checkToken(token: string = ''): Promise { try { if (this.#looksLikePatToken(token)) { log.info('Checking token for PAT validity'); return await this.#checkPatToken(token); } log.info('Checking token for OAuth validity'); return await this.#checkOAuthToken(token); } catch (err) { log.error('Error performing token check', err); return { valid: false, reason: 'unknown', message: `Failed to check token: ${err}`, }; } } #hasValidScopes(scopes: string[]): boolean { return scopes.includes('api'); } async getCodeSuggestions( request: CodeSuggestionRequest, ): Promise { if (!this.#token) { throw new Error('Token needs to be provided to request Code Suggestions'); } const headers = { ...this.#getDefaultHeaders(this.#token), 'Content-Type': 'application/json', }; const response = await this.#lsFetch.post( `${this.#baseURL}/api/v4/code_suggestions/completions`, { headers, body: JSON.stringify(request) }, ); await handleFetchError(response, 'Code Suggestions'); const data = await response.json(); return { ...data, status: response.status }; } async *getStreamingCodeSuggestions( request: CodeSuggestionRequest, ): AsyncGenerator { if (!this.#token) { throw new Error('Token needs to be provided to stream code suggestions'); } const headers = { ...this.#getDefaultHeaders(this.#token), 'Content-Type': 'application/json', }; yield* this.#lsFetch.streamFetch( `${this.#baseURL}/api/v4/code_suggestions/completions`, JSON.stringify(request), headers, ); } async fetchFromApi(request: ApiRequest): Promise { if (!this.#token) { return Promise.reject(new Error('Token needs to be provided to authorise API request.')); } if ( request.supportedSinceInstanceVersion && !this.#instanceVersionHigherOrEqualThen(request.supportedSinceInstanceVersion.version) ) { return Promise.reject( new InvalidInstanceVersionError( `Can't ${request.supportedSinceInstanceVersion.resourceName} until your instance is upgraded to ${request.supportedSinceInstanceVersion.version} or higher.`, ), ); } if (request.type === 'graphql') { return this.#graphqlRequest(request.query, request.variables); } switch (request.method) { case 'GET': return this.#fetch(request.path, request.searchParams, 'resource', request.headers); case 'POST': return this.#postFetch(request.path, 'resource', request.body, request.headers); default: // the type assertion is necessary because TS doesn't expect any other types throw new Error(`Unknown request type ${(request as ApiRequest).type}`); } } async connectToCable(): Promise { const headers = this.#getDefaultHeaders(this.#token); const websocketOptions = { headers: { ...headers, Origin: this.#baseURL, }, }; return connectToCable(this.#baseURL, websocketOptions); } async #graphqlRequest( document: RequestDocument, variables?: V, ): Promise { const ensureEndsWithSlash = (url: string) => url.replace(/\/?$/, '/'); const endpoint = new URL('./api/graphql', ensureEndsWithSlash(this.#baseURL)).href; // supports GitLab instances that are on a custom path, e.g. ""https://example.com/gitlab"" const graphqlFetch = async ( input: RequestInfo | URL, init?: RequestInit, ): Promise => { const url = input instanceof URL ? input.toString() : input; return this.#lsFetch.post(url, { ...init, headers: { ...headers, ...init?.headers }, }); }; const headers = this.#getDefaultHeaders(this.#token); const client = new GraphQLClient(endpoint, { headers, fetch: graphqlFetch, }); return client.request(document, variables); } async #fetch( apiResourcePath: string, query: Record = {}, resourceName = 'resource', headers?: Record, ): Promise { const url = `${this.#baseURL}/api/v4${apiResourcePath}${createQueryString(query)}`; const result = await this.#lsFetch.get(url, { headers: { ...this.#getDefaultHeaders(this.#token), ...headers }, }); await handleFetchError(result, resourceName); return result.json() as Promise; } async #postFetch( apiResourcePath: string, resourceName = 'resource', body?: unknown, headers?: Record, ): Promise { const url = `${this.#baseURL}/api/v4${apiResourcePath}`; const response = await this.#lsFetch.post(url, { headers: { 'Content-Type': 'application/json', ...this.#getDefaultHeaders(this.#token), ...headers, }, body: JSON.stringify(body), }); await handleFetchError(response, resourceName); return response.json() as Promise; } #getDefaultHeaders(token?: string) { return { Authorization: `Bearer ${token}`, 'User-Agent': `code-completions-language-server-experiment (${this.#clientInfo?.name}:${this.#clientInfo?.version})`, 'X-Gitlab-Language-Server-Version': getLanguageServerVersion(), }; } #instanceVersionHigherOrEqualThen(version: string): boolean { if (!this.#instanceVersion) return false; return semverCompare(this.#instanceVersion, version) >= 0; } async #getGitLabInstanceVersion(): Promise { if (!this.#token) { return ''; } const headers = this.#getDefaultHeaders(this.#token); const response = await this.#lsFetch.get(`${this.#baseURL}/api/v4/version`, { headers, }); const { version } = await response.json(); return version; } get instanceVersion() { return this.#instanceVersion; } } References:" You are a code assistant,Definition of 'FileSet' in file src/common/workspace/workspace_service.ts in project gitlab-lsp,"Definition: type FileSet = Map; type WorkspaceService = typeof DefaultWorkspaceService.prototype; export const WorkspaceService = createInterfaceId('WorkspaceService'); @Injectable(WorkspaceService, [VirtualFileSystemService]) export class DefaultWorkspaceService { #virtualFileSystemService: DefaultVirtualFileSystemService; #workspaceFilesMap = new Map(); #disposable: { dispose: () => void }; constructor(virtualFileSystemService: DefaultVirtualFileSystemService) { this.#virtualFileSystemService = virtualFileSystemService; this.#disposable = this.#setupEventListeners(); } #setupEventListeners() { return this.#virtualFileSystemService.onFileSystemEvent((eventType, data) => { switch (eventType) { case VirtualFileSystemEvents.WorkspaceFilesUpdate: this.#handleWorkspaceFilesUpdate(data as WorkspaceFilesUpdate); break; case VirtualFileSystemEvents.WorkspaceFileUpdate: this.#handleWorkspaceFileUpdate(data as WorkspaceFileUpdate); break; default: break; } }); } #handleWorkspaceFilesUpdate(update: WorkspaceFilesUpdate) { const files: FileSet = new Map(); for (const file of update.files) { files.set(file.toString(), file); } this.#workspaceFilesMap.set(update.workspaceFolder.uri, files); } #handleWorkspaceFileUpdate(update: WorkspaceFileUpdate) { let files = this.#workspaceFilesMap.get(update.workspaceFolder.uri); if (!files) { files = new Map(); this.#workspaceFilesMap.set(update.workspaceFolder.uri, files); } switch (update.event) { case 'add': case 'change': files.set(update.fileUri.toString(), update.fileUri); break; case 'unlink': files.delete(update.fileUri.toString()); break; default: break; } } getWorkspaceFiles(workspaceFolder: WorkspaceFolder): FileSet | undefined { return this.#workspaceFilesMap.get(workspaceFolder.uri); } dispose() { this.#disposable.dispose(); } } References: - src/common/workspace/workspace_service.ts:47" You are a code assistant,Definition of 'SOCKET_NOTIFICATION_CHANNEL' in file packages/lib_webview_client/src/bus/provider/socket_io_message_bus.ts in project gitlab-lsp,"Definition: export const SOCKET_NOTIFICATION_CHANNEL = 'notification'; export const SOCKET_REQUEST_CHANNEL = 'request'; export const SOCKET_RESPONSE_CHANNEL = 'response'; export type SocketEvents = | typeof SOCKET_NOTIFICATION_CHANNEL | typeof SOCKET_REQUEST_CHANNEL | typeof SOCKET_RESPONSE_CHANNEL; export class SocketIoMessageBus implements MessageBus { #notificationHandlers = new SimpleRegistry(); #requestHandlers = new SimpleRegistry(); #pendingRequests = new SimpleRegistry(); #socket: Socket; constructor(socket: Socket) { this.#socket = socket; this.#setupSocketEventHandlers(); } async sendNotification( messageType: T, payload?: TMessages['outbound']['notifications'][T], ): Promise { this.#socket.emit(SOCKET_NOTIFICATION_CHANNEL, { type: messageType, payload }); } sendRequest( type: T, payload?: TMessages['outbound']['requests'][T]['params'], ): Promise> { const requestId = generateRequestId(); let timeout: NodeJS.Timeout | undefined; return new Promise((resolve, reject) => { const pendingRequestDisposable = this.#pendingRequests.register( requestId, (value: ExtractRequestResult) => { resolve(value); clearTimeout(timeout); pendingRequestDisposable.dispose(); }, ); timeout = setTimeout(() => { pendingRequestDisposable.dispose(); reject(new Error('Request timed out')); }, REQUEST_TIMEOUT_MS); this.#socket.emit(SOCKET_REQUEST_CHANNEL, { requestId, type, payload, }); }); } onNotification( messageType: T, callback: (payload: TMessages['inbound']['notifications'][T]) => void, ): Disposable { return this.#notificationHandlers.register(messageType, callback); } onRequest( type: T, handler: ( payload: TMessages['inbound']['requests'][T]['params'], ) => Promise>, ): Disposable { return this.#requestHandlers.register(type, handler); } dispose() { this.#socket.off(SOCKET_NOTIFICATION_CHANNEL, this.#handleNotificationMessage); this.#socket.off(SOCKET_REQUEST_CHANNEL, this.#handleRequestMessage); this.#socket.off(SOCKET_RESPONSE_CHANNEL, this.#handleResponseMessage); this.#notificationHandlers.dispose(); this.#requestHandlers.dispose(); this.#pendingRequests.dispose(); } #setupSocketEventHandlers = () => { this.#socket.on(SOCKET_NOTIFICATION_CHANNEL, this.#handleNotificationMessage); this.#socket.on(SOCKET_REQUEST_CHANNEL, this.#handleRequestMessage); this.#socket.on(SOCKET_RESPONSE_CHANNEL, this.#handleResponseMessage); }; #handleNotificationMessage = async (message: { type: keyof TMessages['inbound']['notifications'] & string; payload: unknown; }) => { await this.#notificationHandlers.handle(message.type, message.payload); }; #handleRequestMessage = async (message: { requestId: string; event: keyof TMessages['inbound']['requests'] & string; payload: unknown; }) => { const response = await this.#requestHandlers.handle(message.event, message.payload); this.#socket.emit(SOCKET_RESPONSE_CHANNEL, { requestId: message.requestId, payload: response, }); }; #handleResponseMessage = async (message: { requestId: string; payload: unknown }) => { await this.#pendingRequests.handle(message.requestId, message.payload); }; } References:" You are a code assistant,Definition of 'ITelemetryNotificationParams' in file src/common/message_handler.ts in project gitlab-lsp,"Definition: 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 => { 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:131" You are a code assistant,Definition of 'fetchBase' in file src/common/fetch.ts in project gitlab-lsp,"Definition: fetchBase(input: RequestInfo | URL, init?: RequestInit): Promise; delete(input: RequestInfo | URL, init?: RequestInit): Promise; get(input: RequestInfo | URL, init?: RequestInit): Promise; post(input: RequestInfo | URL, init?: RequestInit): Promise; put(input: RequestInfo | URL, init?: RequestInit): Promise; updateAgentOptions(options: FetchAgentOptions): void; streamFetch(url: string, body: string, headers: FetchHeaders): AsyncGenerator; } export const LsFetch = createInterfaceId('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 {} async destroy(): Promise {} async fetch(input: RequestInfo | URL, init?: RequestInit): Promise { 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 { // Stub. Should delegate to the node or browser fetch implementations throw new Error('Not implemented'); yield ''; } async delete(input: RequestInfo | URL, init?: RequestInit): Promise { return this.fetch(input, this.updateRequestInit('DELETE', init)); } async get(input: RequestInfo | URL, init?: RequestInit): Promise { return this.fetch(input, this.updateRequestInit('GET', init)); } async post(input: RequestInfo | URL, init?: RequestInit): Promise { return this.fetch(input, this.updateRequestInit('POST', init)); } async put(input: RequestInfo | URL, init?: RequestInit): Promise { return this.fetch(input, this.updateRequestInit('PUT', init)); } async fetchBase(input: RequestInfo | URL, init?: RequestInit): Promise { // 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 'DuoWorkflowMessages' in file packages/webview_duo_workflow/src/contract.ts in project gitlab-lsp,"Definition: export type DuoWorkflowMessages = CreatePluginMessageMap<{ webviewToPlugin: { notifications: { startWorkflow: { goal: string; image: string; }; stopWorkflow: []; openUrl: { url: string; }; }; }; pluginToWebview: { notifications: { workflowCheckpoints: LangGraphCheckpoint[]; workflowError: string; workflowStarted: string; workflowStatus: string; }; }; }>; References:" You are a code assistant,Definition of 'transform' in file src/common/document_transformer_service.ts in project gitlab-lsp,"Definition: transform(context: IDocContext): IDocContext; } export const DocumentTransformerService = createInterfaceId( 'DocumentTransformerService', ); @Injectable(DocumentTransformerService, [LsTextDocuments, SecretRedactor]) export class DefaultDocumentTransformerService implements DocumentTransformerService { #transformers: IDocTransformer[] = []; #documents: LsTextDocuments; 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 '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 { return input.map((option) => ({ ...option, text: `${option.text} processed` })); } } pipeline.addProcessor(new TestCompletionProcessor()); const completionInput: SuggestionOption[] = [{ text: 'option1', uniqueTrackingId: '1' }]; const result = await pipeline.run({ documentContext: mockContext, input: completionInput, type: 'completion', }); expect(result).toEqual([{ text: 'option1 processed', uniqueTrackingId: '1' }]); }); test('should chain multiple processors correctly for stream input', async () => { class Processor1 extends PostProcessor { async processStream( _context: IDocContext, input: StreamingCompletionResponse, ): Promise { return { ...input, completion: `${input.completion} [1]` }; } async processCompletion( _context: IDocContext, input: SuggestionOption[], ): Promise { return input; } } class Processor2 extends PostProcessor { async processStream( _context: IDocContext, input: StreamingCompletionResponse, ): Promise { return { ...input, completion: `${input.completion} [2]` }; } async processCompletion( _context: IDocContext, input: SuggestionOption[], ): Promise { return input; } } pipeline.addProcessor(new Processor1()); pipeline.addProcessor(new Processor2()); const streamInput: StreamingCompletionResponse = { id: '1', completion: 'test', done: false }; const result = await pipeline.run({ documentContext: mockContext, input: streamInput, type: 'stream', }); expect(result).toEqual({ id: '1', completion: 'test [1] [2]', done: false }); }); test('should chain multiple processors correctly for completion input', async () => { class Processor1 extends PostProcessor { async processStream( _context: IDocContext, input: StreamingCompletionResponse, ): Promise { return input; } async processCompletion( _context: IDocContext, input: SuggestionOption[], ): Promise { return input.map((option) => ({ ...option, text: `${option.text} [1]` })); } } class Processor2 extends PostProcessor { async processStream( _context: IDocContext, input: StreamingCompletionResponse, ): Promise { return input; } async processCompletion( _context: IDocContext, input: SuggestionOption[], ): Promise { return input.map((option) => ({ ...option, text: `${option.text} [2]` })); } } pipeline.addProcessor(new Processor1()); pipeline.addProcessor(new Processor2()); const completionInput: SuggestionOption[] = [{ text: 'option1', uniqueTrackingId: '1' }]; const result = await pipeline.run({ documentContext: mockContext, input: completionInput, type: 'completion', }); expect(result).toEqual([{ text: 'option1 [1] [2]', uniqueTrackingId: '1' }]); }); test('should throw an error for unexpected type', async () => { class TestProcessor extends PostProcessor { async processStream( _context: IDocContext, input: StreamingCompletionResponse, ): Promise { return input; } async processCompletion( _context: IDocContext, input: SuggestionOption[], ): Promise { 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 'FileResolver' in file src/common/services/fs/file.ts in project gitlab-lsp,"Definition: export interface FileResolver { readFile(_args: ReadFile): Promise; } export const FileResolver = createInterfaceId('FileResolver'); @Injectable(FileResolver, []) export class EmptyFileResolver { // eslint-disable-next-line @typescript-eslint/no-unused-vars readFile(_args: ReadFile): Promise { return Promise.resolve(''); } } References: - src/common/ai_context_management_2/retrievers/ai_file_context_retriever.ts:17 - src/common/services/duo_access/project_access_cache.ts:93" 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 { return input.map((option) => ({ ...option, text: `${option.text} [2]` })); } } pipeline.addProcessor(new Processor1()); pipeline.addProcessor(new Processor2()); const completionInput: SuggestionOption[] = [{ text: 'option1', uniqueTrackingId: '1' }]; const result = await pipeline.run({ documentContext: mockContext, input: completionInput, type: 'completion', }); expect(result).toEqual([{ text: 'option1 [1] [2]', uniqueTrackingId: '1' }]); }); test('should throw an error for unexpected type', async () => { class TestProcessor extends PostProcessor { async processStream( _context: IDocContext, input: StreamingCompletionResponse, ): Promise { return input; } async processCompletion( _context: IDocContext, input: SuggestionOption[], ): Promise { 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 'createV2Request' in file src/common/suggestion_client/create_v2_request.ts in project gitlab-lsp,"Definition: export const createV2Request = ( suggestionContext: SuggestionContext, modelDetails?: IDirectConnectionModelDetails, ): CodeSuggestionRequest => ({ prompt_version: 1, project_path: suggestionContext.projectPath ?? '', project_id: -1, current_file: { content_above_cursor: suggestionContext.document.prefix, content_below_cursor: suggestionContext.document.suffix, file_name: suggestionContext.document.fileRelativePath, }, choices_count: suggestionContext.optionsCount, ...(suggestionContext.intent && { intent: suggestionContext.intent }), ...(suggestionContext?.additionalContexts?.length && { context: suggestionContext.additionalContexts, }), ...(modelDetails || {}), }); References: - src/common/suggestion_client/default_suggestion_client.ts:15 - src/common/suggestion_client/create_v2_request.test.ts:27 - src/common/suggestion_client/direct_connection_client.ts:148" You are a code assistant,Definition of 'constructor' in file src/common/tracking/snowplow/emitter.ts in project gitlab-lsp,"Definition: 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 { 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:" You are a code assistant,Definition of 'WebviewRequestInfo' in file packages/lib_webview_transport/src/types.ts in project gitlab-lsp,"Definition: export type WebviewRequestInfo = { requestId: string; }; export type WebviewEventInfo = { type: string; payload?: unknown; }; export type WebviewInstanceCreatedEventData = WebviewAddress; export type WebviewInstanceDestroyedEventData = WebviewAddress; export type WebviewInstanceNotificationEventData = WebviewAddress & WebviewEventInfo; export type WebviewInstanceRequestEventData = WebviewAddress & WebviewEventInfo & WebviewRequestInfo; export type SuccessfulResponse = { success: true; }; export type FailedResponse = { success: false; reason: string; }; export type WebviewInstanceResponseEventData = WebviewAddress & WebviewRequestInfo & WebviewEventInfo & (SuccessfulResponse | FailedResponse); export type MessagesToServer = { webview_instance_created: WebviewInstanceCreatedEventData; webview_instance_destroyed: WebviewInstanceDestroyedEventData; webview_instance_notification_received: WebviewInstanceNotificationEventData; webview_instance_request_received: WebviewInstanceRequestEventData; webview_instance_response_received: WebviewInstanceResponseEventData; }; export type MessagesToClient = { webview_instance_notification: WebviewInstanceNotificationEventData; webview_instance_request: WebviewInstanceRequestEventData; webview_instance_response: WebviewInstanceResponseEventData; }; export interface TransportMessageHandler { (payload: T): void; } export interface TransportListener { on( type: K, callback: TransportMessageHandler, ): Disposable; } export interface TransportPublisher { publish(type: K, payload: MessagesToClient[K]): Promise; } export interface Transport extends TransportListener, TransportPublisher {} References:" You are a code assistant,Definition of 'SuggestionClientFn' in file src/common/suggestion_client/suggestion_client.ts in project gitlab-lsp,"Definition: export type SuggestionClientFn = SuggestionClient['getSuggestions']; export type SuggestionClientMiddleware = ( context: SuggestionContext, next: SuggestionClientFn, ) => ReturnType; References: - src/common/suggestion_client/tree_sitter_middleware.test.ts:18 - src/common/suggestion_client/suggestion_client_pipeline.test.ts:40 - src/common/suggestion_client/suggestion_client.ts:47 - src/common/suggestion_client/suggestion_client_pipeline.ts:12" You are a code assistant,Definition of 'TreeAndLanguage' in file src/common/tree_sitter/parser.ts in project gitlab-lsp,"Definition: export type TreeAndLanguage = { tree: Parser.Tree; languageInfo: TreeSitterLanguageInfo; language: Language; }; export abstract class TreeSitterParser { protected loadState: TreeSitterParserLoadState; protected languages: Map; protected readonly parsers = new Map(); abstract init(): Promise; constructor({ languages }: { languages: TreeSitterLanguageInfo[] }) { this.languages = this.buildTreeSitterInfoByExtMap(languages); this.loadState = TreeSitterParserLoadState.INIT; } get loadStateValue(): TreeSitterParserLoadState { return this.loadState; } async parseFile(context: IDocContext): Promise { 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 { 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 { 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 { return languages.reduce((map, language) => { for (const extension of language.extensions) { map.set(extension, language); } return map; }, new Map()); } } References: - src/common/tree_sitter/intent_resolver.test.ts:32 - src/common/tree_sitter/intent_resolver.ts:31" You are a code assistant,Definition of 'onConfigChange' in file src/common/config_service.ts in project gitlab-lsp,"Definition: onConfigChange(listener: (config: IConfig) => void): Disposable; /** * merge adds `newConfig` properties into existing config, if the * property is present in both old and new config, `newConfig` * properties take precedence unless not defined * * This method performs deep merge * * **Arrays are not merged; they are replaced with the new value.** * */ merge(newConfig: Partial): void; } export const ConfigService = createInterfaceId('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 = (key?: string) => { return key ? get(this.#config, key) : this.#config; }; set: TypedSetter = (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) { mergeWith(this.#config, newConfig, (target, src) => (isArray(target) ? src : undefined)); this.#triggerChange(); } } References:" You are a code assistant,Definition of 'setupWebviewPlugins' in file packages/lib_webview/src/setup/plugin/setup_plugins.ts in project gitlab-lsp,"Definition: export function setupWebviewPlugins({ plugins, extensionMessageBusProvider, logger, runtimeMessageBus, }: setupWebviewPluginsProps) { logger.debug(`Setting up (${plugins.length}) plugins`); const compositeDisposable = new CompositeDisposable(); for (const plugin of plugins) { logger.debug(`Setting up plugin: ${plugin.id}`); const extensionMessageBus = extensionMessageBusProvider.getMessageBus(plugin.id); const webviewInstanceMessageBusFactory = (address: WebviewAddress) => { return new WebviewInstanceMessageBus(address, runtimeMessageBus, logger); }; const webviewController = new WebviewController( plugin.id, runtimeMessageBus, webviewInstanceMessageBusFactory, logger, ); const disposable = plugin.setup({ webview: webviewController, extension: extensionMessageBus, }); if (isDisposable(disposable)) { compositeDisposable.add(disposable); } } logger.debug('All plugins were set up successfully'); return compositeDisposable; } References: - packages/lib_webview/src/setup/setup_webview_runtime.ts:24" You are a code assistant,Definition of 'ChatPlatform' in file packages/webview_duo_chat/src/plugin/chat_platform.ts in project gitlab-lsp,"Definition: export class ChatPlatform implements GitLabPlatformBase { #client: GitLabApiClient; constructor(client: GitLabApiClient) { this.#client = client; } account: Account = { id: 'https://gitlab.com|16918910', instanceUrl: 'https://gitlab.com', } as Partial as Account; fetchFromApi(request: ApiRequest): Promise { return this.#client.fetchFromApi(request); } connectToCable(): Promise { return this.#client.connectToCable(); } getUserAgentHeader(): Record { return {}; } } 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:" You are a code assistant,Definition of 'DefaultAiPolicyManager' in file src/common/ai_context_management_2/ai_policy_management.ts in project gitlab-lsp,"Definition: 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:" 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 interface DidChangeWorkspaceFoldersHandler extends HandlesNotification {} export const DidChangeWorkspaceFoldersHandler = createInterfaceId('InitializeHandler'); @Injectable(DidChangeWorkspaceFoldersHandler, [ConfigService]) export class DefaultDidChangeWorkspaceFoldersHandler implements DidChangeWorkspaceFoldersHandler { #configService: ConfigService; constructor(configService: ConfigService) { this.#configService = configService; } notificationHandler: NotificationHandler = ( 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/core/handlers/did_change_workspace_folders_handler.test.ts:14 - src/common/connection_service.ts:63" You are a code assistant,Definition of 'WebviewTransportEventEmitterMessages' in file packages/lib_webview_transport_socket_io/src/utils/webview_transport_event_emitter.ts in project gitlab-lsp,"Definition: export type WebviewTransportEventEmitterMessages = { [K in keyof MessagesToServer]: (payload: MessagesToServer[K]) => void; }; export type WebviewTransportEventEmitter = TypedEmitter; export const createWebviewTransportEventEmitter = (): WebviewTransportEventEmitter => new EventEmitter() as WebviewTransportEventEmitter; References:" You are a code assistant,Definition of 'constructor' in file src/common/services/duo_access/project_access_cache.ts in project gitlab-lsp,"Definition: constructor( private readonly directoryWalker: DirectoryWalker, private readonly fileResolver: FileResolver, private readonly api: GitLabApiClient, ) { this.#duoProjects = new Map(); } getProjectsForWorkspaceFolder(workspaceFolder: WorkspaceFolder): DuoProject[] { return this.#duoProjects.get(workspaceFolder.uri) ?? []; } async updateCache({ baseUrl, workspaceFolders, }: { baseUrl: string; workspaceFolders: WorkspaceFolder[]; }) { try { this.#duoProjects.clear(); const duoProjects = await Promise.all( workspaceFolders.map(async (workspaceFolder) => { return { workspaceFolder, projects: await this.#duoProjectsForWorkspaceFolder({ workspaceFolder, baseUrl, }), }; }), ); for (const { workspaceFolder, projects } of duoProjects) { this.#logProjectsInfo(projects, workspaceFolder); this.#duoProjects.set(workspaceFolder.uri, projects); } this.#triggerChange(); } catch (err) { log.error('DuoProjectAccessCache: failed to update project access cache', err); } } #logProjectsInfo(projects: DuoProject[], workspaceFolder: WorkspaceFolder) { if (!projects.length) { log.warn( `DuoProjectAccessCache: no projects found for workspace folder ${workspaceFolder.uri}`, ); return; } log.debug( `DuoProjectAccessCache: found ${projects.length} projects for workspace folder ${workspaceFolder.uri}: ${JSON.stringify(projects, null, 2)}`, ); } async #duoProjectsForWorkspaceFolder({ workspaceFolder, baseUrl, }: { workspaceFolder: WorkspaceFolder; baseUrl: string; }): Promise { const remotes = await this.#gitlabRemotesForWorkspaceFolder(workspaceFolder, baseUrl); const projects = await Promise.all( remotes.map(async (remote) => { const enabled = await this.#checkDuoFeaturesEnabled(remote.namespaceWithPath); return { projectPath: remote.projectPath, uri: remote.fileUri, enabled, host: remote.host, namespace: remote.namespace, namespaceWithPath: remote.namespaceWithPath, } satisfies DuoProject; }), ); return projects; } async #gitlabRemotesForWorkspaceFolder( workspaceFolder: WorkspaceFolder, baseUrl: string, ): Promise { const paths = await this.directoryWalker.findFilesForDirectory({ directoryUri: workspaceFolder.uri, filters: { fileEndsWith: ['/.git/config'], }, }); const remotes = await Promise.all( paths.map(async (fileUri) => this.#gitlabRemotesForFileUri(fileUri.toString(), baseUrl)), ); return remotes.flat(); } async #gitlabRemotesForFileUri( fileUri: string, baseUrl: string, ): Promise { const remoteUrls = await this.#remoteUrlsFromGitConfig(fileUri); return remoteUrls.reduce((acc, remoteUrl) => { const remote = parseGitLabRemote(remoteUrl, baseUrl); if (remote) { acc.push({ ...remote, fileUri }); } return acc; }, []); } async #remoteUrlsFromGitConfig(fileUri: string): Promise { try { const fileString = await this.fileResolver.readFile({ fileUri }); const config = ini.parse(fileString); return this.#getRemoteUrls(config); } catch (error) { log.error(`DuoProjectAccessCache: Failed to read git config file: ${fileUri}`, error); return []; } } #getRemoteUrls(config: GitConfig): string[] { return Object.keys(config).reduce((acc, section) => { if (section.startsWith('remote ')) { acc.push(config[section].url); } return acc; }, []); } async #checkDuoFeaturesEnabled(projectPath: string): Promise { try { const response = await this.api.fetchFromApi<{ project: GqlProjectWithDuoEnabledInfo }>({ type: 'graphql', query: duoFeaturesEnabledQuery, variables: { projectPath, }, } satisfies ApiRequest<{ project: GqlProjectWithDuoEnabledInfo }>); return Boolean(response?.project?.duoFeaturesEnabled); } catch (error) { log.error( `DuoProjectAccessCache: Failed to check if Duo features are enabled for project: ${projectPath}`, error, ); return true; } } onDuoProjectCacheUpdate( listener: (duoProjectsCache: Map) => void, ): Disposable { this.#eventEmitter.on(DUO_PROJECT_CACHE_UPDATE_EVENT, listener); return { dispose: () => this.#eventEmitter.removeListener(DUO_PROJECT_CACHE_UPDATE_EVENT, listener), }; } #triggerChange() { this.#eventEmitter.emit(DUO_PROJECT_CACHE_UPDATE_EVENT, this.#duoProjects); } } References:" You are a code assistant,Definition of 'constructor' in file src/common/fetch_error.ts in project gitlab-lsp,"Definition: 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:" You are a code assistant,Definition of 'constructor' in file src/common/git/repository_service.ts in project gitlab-lsp,"Definition: constructor(virtualFileSystemService: DefaultVirtualFileSystemService) { this.#virtualFileSystemService = virtualFileSystemService; this.#setupEventListeners(); } #setupEventListeners() { return this.#virtualFileSystemService.onFileSystemEvent(async (eventType, data) => { switch (eventType) { case VirtualFileSystemEvents.WorkspaceFilesUpdate: await this.#handleWorkspaceFilesUpdate(data as WorkspaceFilesUpdate); break; case VirtualFileSystemEvents.WorkspaceFileUpdate: await this.#handleWorkspaceFileUpdate(data as WorkspaceFileUpdate); break; default: break; } }); } async #handleWorkspaceFilesUpdate(update: WorkspaceFilesUpdate) { log.info(`Workspace files update: ${update.files.length}`); const perf1 = performance.now(); await this.handleWorkspaceFilesUpdate({ ...update, }); const perf2 = performance.now(); log.info(`Workspace files initialization took ${perf2 - perf1}ms`); const perf3 = performance.now(); const files = this.getFilesForWorkspace(update.workspaceFolder.uri, { excludeGitFolder: true, excludeIgnored: true, }); const perf4 = performance.now(); log.info(`Fetched workspace files in ${perf4 - perf3}ms`); log.info(`Workspace git files: ${files.length}`); // const treeFile = await readFile( // '/Users/angelo.rivera/gitlab/gitlab-development-kit/gitlab/tree.txt', // 'utf-8', // ); // const treeFiles = treeFile.split('\n').filter(Boolean); // // get the set difference between the files in the tree and the non-ignored files // // we need the difference between the two sets to know which files are not in the tree // const diff = new Set( // files.map((file) => // relative('/Users/angelo.rivera/gitlab/gitlab-development-kit/gitlab', file.uri.fsPath), // ), // ); // for (const file of treeFiles) { // diff.delete(file); // } // log.info(`Files not in the tree.txt: ${JSON.stringify(Array.from(diff))}`); } async #handleWorkspaceFileUpdate(update: WorkspaceFileUpdate) { log.info(`Workspace file update: ${JSON.stringify(update)}`); await this.handleWorkspaceFileUpdate({ ...update, }); const perf1 = performance.now(); const files = this.getFilesForWorkspace(update.workspaceFolder.uri, { excludeGitFolder: true, excludeIgnored: true, }); const perf2 = performance.now(); log.info(`Fetched workspace files in ${perf2 - perf1}ms`); log.info(`Workspace git files: ${files.length}`); } /** * unique map of workspace folders that point to a map of repositories * We store separate repository maps for each workspace because * the events from the VFS service are at the workspace level. * If we combined them, we may get race conditions */ #workspaces: Map = new Map(); #workspaceRepositoryTries: Map = new Map(); #buildRepositoryTrie(repositories: Repository[]): RepositoryTrie { const root = new RepositoryTrie(); for (const repo of repositories) { let node = root; const parts = repo.uri.path.split('/').filter(Boolean); for (const part of parts) { if (!node.children.has(part)) { node.children.set(part, new RepositoryTrie()); } node = node.children.get(part) as RepositoryTrie; } node.repository = repo.uri; } return root; } findMatchingRepositoryUri(fileUri: URI, workspaceFolderUri: WorkspaceFolder): URI | null { const trie = this.#workspaceRepositoryTries.get(workspaceFolderUri.uri); if (!trie) return null; let node = trie; let lastMatchingRepo: URI | null = null; const parts = fileUri.path.split('/').filter(Boolean); for (const part of parts) { if (node.repository) { lastMatchingRepo = node.repository; } if (!node.children.has(part)) break; node = node.children.get(part) as RepositoryTrie; } return node.repository || lastMatchingRepo; } getRepositoryFileForUri( fileUri: URI, repositoryUri: URI, workspaceFolder: WorkspaceFolder, ): RepositoryFile | null { const repository = this.#getRepositoriesForWorkspace(workspaceFolder.uri).get( repositoryUri.toString(), ); if (!repository) { return null; } return repository.getFile(fileUri.toString()) ?? null; } #updateRepositoriesForFolder( workspaceFolder: WorkspaceFolder, repositoryMap: RepositoryMap, repositoryTrie: RepositoryTrie, ) { this.#workspaces.set(workspaceFolder.uri, repositoryMap); this.#workspaceRepositoryTries.set(workspaceFolder.uri, repositoryTrie); } async handleWorkspaceFilesUpdate({ workspaceFolder, files }: WorkspaceFilesUpdate) { // clear existing repositories from workspace this.#emptyRepositoriesForWorkspace(workspaceFolder.uri); const repositories = this.#detectRepositories(files, workspaceFolder); const repositoryMap = new Map(repositories.map((repo) => [repo.uri.toString(), repo])); // Build and cache the repository trie for this workspace const trie = this.#buildRepositoryTrie(repositories); this.#updateRepositoriesForFolder(workspaceFolder, repositoryMap, trie); await Promise.all( repositories.map((repo) => repo.addFilesAndLoadGitIgnore( files.filter((file) => { const matchingRepo = this.findMatchingRepositoryUri(file, workspaceFolder); return matchingRepo && matchingRepo.toString() === repo.uri.toString(); }), ), ), ); } async handleWorkspaceFileUpdate({ fileUri, workspaceFolder, event }: WorkspaceFileUpdate) { const repoUri = this.findMatchingRepositoryUri(fileUri, workspaceFolder); if (!repoUri) { log.debug(`No matching repository found for file ${fileUri.toString()}`); return; } const repositoryMap = this.#getRepositoriesForWorkspace(workspaceFolder.uri); const repository = repositoryMap.get(repoUri.toString()); if (!repository) { log.debug(`Repository not found for URI ${repoUri.toString()}`); return; } if (repository.isFileIgnored(fileUri)) { log.debug(`File ${fileUri.toString()} is ignored`); return; } switch (event) { case 'add': repository.setFile(fileUri); log.debug(`File ${fileUri.toString()} added to repository ${repoUri.toString()}`); break; case 'change': repository.setFile(fileUri); log.debug(`File ${fileUri.toString()} updated in repository ${repoUri.toString()}`); break; case 'unlink': repository.removeFile(fileUri.toString()); log.debug(`File ${fileUri.toString()} removed from repository ${repoUri.toString()}`); break; default: log.warn(`Unknown file event ${event} for file ${fileUri.toString()}`); } } #getRepositoriesForWorkspace(workspaceFolderUri: WorkspaceFolderUri): RepositoryMap { return this.#workspaces.get(workspaceFolderUri) || new Map(); } #emptyRepositoriesForWorkspace(workspaceFolderUri: WorkspaceFolderUri): void { log.debug(`Emptying repositories for workspace ${workspaceFolderUri}`); const repos = this.#workspaces.get(workspaceFolderUri); if (!repos || repos.size === 0) return; // clear up ignore manager trie from memory repos.forEach((repo) => { repo.dispose(); log.debug(`Repository ${repo.uri} has been disposed`); }); repos.clear(); const trie = this.#workspaceRepositoryTries.get(workspaceFolderUri); if (trie) { trie.dispose(); this.#workspaceRepositoryTries.delete(workspaceFolderUri); } this.#workspaces.delete(workspaceFolderUri); log.debug(`Repositories for workspace ${workspaceFolderUri} have been emptied`); } #detectRepositories(files: URI[], workspaceFolder: WorkspaceFolder): Repository[] { const gitConfigFiles = files.filter((file) => file.toString().endsWith('.git/config')); return gitConfigFiles.map((file) => { const projectUri = fsPathToUri(file.path.replace('.git/config', '')); const ignoreManager = new IgnoreManager(projectUri.fsPath); log.info(`Detected repository at ${projectUri.path}`); return new Repository({ ignoreManager, uri: projectUri, configFileUri: file, workspaceFolder, }); }); } getFilesForWorkspace( workspaceFolderUri: WorkspaceFolderUri, options: { excludeGitFolder?: boolean; excludeIgnored?: boolean } = {}, ): RepositoryFile[] { const repositories = this.#getRepositoriesForWorkspace(workspaceFolderUri); const allFiles: RepositoryFile[] = []; repositories.forEach((repository) => { repository.getFiles().forEach((file) => { // apply the filters if (options.excludeGitFolder && this.#isInGitFolder(file.uri, repository.uri)) { return; } if (options.excludeIgnored && file.isIgnored) { return; } allFiles.push(file); }); }); return allFiles; } // Helper method to check if a file is in the .git folder #isInGitFolder(fileUri: URI, repositoryUri: URI): boolean { const relativePath = fileUri.path.slice(repositoryUri.path.length); return relativePath.split('/').some((part) => part === '.git'); } } References:" You are a code assistant,Definition of 'debug' in file packages/lib_logging/src/null_logger.ts in project gitlab-lsp,"Definition: debug(): void { // NOOP } info(e: Error): void; info(message: string, e?: Error | undefined): void; info(): void { // NOOP } warn(e: Error): void; warn(message: string, e?: Error | undefined): void; warn(): void { // NOOP } error(e: Error): void; error(message: string, e?: Error | undefined): void; error(): void { // NOOP } } References:" You are a code assistant,Definition of 'UNSUPPORTED_GITLAB_VERSION' in file src/common/feature_state/feature_state_management_types.ts in project gitlab-lsp,"Definition: export const UNSUPPORTED_GITLAB_VERSION = 'unsupported-gitlab-version' as const; export const UNSUPPORTED_LANGUAGE = 'code-suggestions-document-unsupported-language' as const; export const DISABLED_LANGUAGE = 'code-suggestions-document-disabled-language' as const; export type StateCheckId = | typeof NO_LICENSE | typeof DUO_DISABLED_FOR_PROJECT | typeof UNSUPPORTED_GITLAB_VERSION | typeof UNSUPPORTED_LANGUAGE | typeof DISABLED_LANGUAGE; export interface FeatureStateCheck { checkId: StateCheckId; details?: string; } export interface FeatureState { featureId: Feature; engagedChecks: FeatureStateCheck[]; } const CODE_SUGGESTIONS_CHECKS_PRIORITY_ORDERED = [ DUO_DISABLED_FOR_PROJECT, UNSUPPORTED_LANGUAGE, DISABLED_LANGUAGE, ]; const CHAT_CHECKS_PRIORITY_ORDERED = [DUO_DISABLED_FOR_PROJECT]; export const CHECKS_PER_FEATURE: { [key in Feature]: StateCheckId[] } = { [CODE_SUGGESTIONS]: CODE_SUGGESTIONS_CHECKS_PRIORITY_ORDERED, [CHAT]: CHAT_CHECKS_PRIORITY_ORDERED, // [WORKFLOW]: [], }; References:" You are a code assistant,Definition of 'generateRequestId' in file packages/lib_webview_client/src/generate_request_id.ts in project gitlab-lsp,"Definition: export const generateRequestId = () => v4(); References: - packages/lib_webview_client/src/bus/provider/socket_io_message_bus.ts:43 - packages/lib_webview/src/setup/plugin/webview_instance_message_bus.ts:104" You are a code assistant,Definition of 'Processor2' in file src/common/suggestion_client/post_processors/post_processor_pipeline.test.ts in project gitlab-lsp,"Definition: class Processor2 extends PostProcessor { async processStream( _context: IDocContext, input: StreamingCompletionResponse, ): Promise { return { ...input, completion: `${input.completion} [2]` }; } async processCompletion( _context: IDocContext, input: SuggestionOption[], ): Promise { return input; } } pipeline.addProcessor(new Processor1()); pipeline.addProcessor(new Processor2()); const streamInput: StreamingCompletionResponse = { id: '1', completion: 'test', done: false }; const result = await pipeline.run({ documentContext: mockContext, input: streamInput, type: 'stream', }); expect(result).toEqual({ id: '1', completion: 'test [1] [2]', done: false }); }); test('should chain multiple processors correctly for completion input', async () => { class Processor1 extends PostProcessor { async processStream( _context: IDocContext, input: StreamingCompletionResponse, ): Promise { return input; } async processCompletion( _context: IDocContext, input: SuggestionOption[], ): Promise { return input.map((option) => ({ ...option, text: `${option.text} [1]` })); } } class Processor2 extends PostProcessor { async processStream( _context: IDocContext, input: StreamingCompletionResponse, ): Promise { return input; } async processCompletion( _context: IDocContext, input: SuggestionOption[], ): Promise { return input.map((option) => ({ ...option, text: `${option.text} [2]` })); } } pipeline.addProcessor(new Processor1()); pipeline.addProcessor(new Processor2()); const completionInput: SuggestionOption[] = [{ text: 'option1', uniqueTrackingId: '1' }]; const result = await pipeline.run({ documentContext: mockContext, input: completionInput, type: 'completion', }); expect(result).toEqual([{ text: 'option1 [1] [2]', uniqueTrackingId: '1' }]); }); test('should throw an error for unexpected type', async () => { class TestProcessor extends PostProcessor { async processStream( _context: IDocContext, input: StreamingCompletionResponse, ): Promise { return input; } async processCompletion( _context: IDocContext, input: SuggestionOption[], ): Promise { 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: - src/common/suggestion_client/post_processors/post_processor_pipeline.test.ts:117 - src/common/suggestion_client/post_processors/post_processor_pipeline.test.ts:163" You are a code assistant,Definition of 'isCommentEmpty' in file src/common/tree_sitter/comments/comment_resolver.ts in project gitlab-lsp,"Definition: static isCommentEmpty(comment: Comment): boolean { const trimmedContent = comment.content.trim().replace(/[\n\r\\]/g, ' '); // Count the number of alphanumeric characters in the trimmed content const alphanumericCount = (trimmedContent.match(/[a-zA-Z0-9]/g) || []).length; return alphanumericCount <= 2; } } let commentResolver: CommentResolver; export function getCommentResolver(): CommentResolver { if (!commentResolver) { commentResolver = new CommentResolver(); } return commentResolver; } References:" You are a code assistant,Definition of 'TypedSetter' in file src/common/utils/type_utils.d.ts in project gitlab-lsp,"Definition: export interface TypedSetter { (key: `${K1 extends string ? K1 : never}`, value: T[K1]): void; /* * from 2nd level down, we need to qualify the values with `NonNullable` utility. * without doing that, we could possibly end up with a type `never` * as long as any key in the string concatenation is `never`, the concatenated type becomes `never` * and with deep nesting, without the `NonNullable`, there could always be at lest one `never` because of optional parameters in T */ >(key: `${K1 extends string ? K1 : never}.${K2 extends string ? K2 : never}`, value: T[K1][K2]): void; , K3 extends keyof NonNullable[K2]>>(key: `${K1 extends string ? K1 : never}.${K2 extends string ? K2 : never}.${K3 extends string ? K3 : never}`, value: T[K1][K2][K3]): void; } References:" You are a code assistant,Definition of 'dispose' in file packages/lib_handler_registry/src/types.ts in project gitlab-lsp,"Definition: dispose(): void; } References:" You are a code assistant,Definition of 'constructor' in file src/common/secret_redaction/index.ts in project gitlab-lsp,"Definition: 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:" You are a code assistant,Definition of 'COMMAND_FETCH_BUFFER_FROM_API' in file packages/webview_duo_chat/src/plugin/port/platform/web_ide.ts in project gitlab-lsp,"Definition: export const COMMAND_FETCH_BUFFER_FROM_API = `gitlab-web-ide.mediator.fetch-buffer-from-api`; export const COMMAND_MEDIATOR_TOKEN = `gitlab-web-ide.mediator.mediator-token`; 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; } /** * 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; headers?: Record; } export interface GetRequest<_TReturnType> extends GetRequestBase<_TReturnType> { type: 'rest'; } export interface GetBufferRequest extends GetRequestBase { type: 'rest-buffer'; } export interface GraphQLRequest<_TReturnType> { type: 'graphql'; query: string; /** Options passed to the GraphQL query */ variables: Record; } 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; /* 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 'getActiveEditorText' in file packages/webview_duo_chat/src/plugin/port/chat/utils/editor_text_utils.ts in project gitlab-lsp,"Definition: export const getActiveEditorText = (): string | null => { return ''; // const editor = vscode.window.activeTextEditor; // if (!editor) return null; // return editor.document.getText(); }; export const getSelectedText = (): string | null => { return null; // const editor = vscode.window.activeTextEditor; // if (!editor || !editor.selection || editor.selection.isEmpty) return null; // const { selection } = editor; // const selectionRange = new vscode.Range( // selection.start.line, // selection.start.character, // selection.end.line, // selection.end.character, // ); // return editor.document.getText(selectionRange); }; export const getActiveFileName = (): string | null => { return null; // const editor = vscode.window.activeTextEditor; // if (!editor) return null; // return vscode.workspace.asRelativePath(editor.document.uri); }; export const getTextBeforeSelected = (): string | null => { return null; // const editor = vscode.window.activeTextEditor; // if (!editor || !editor.selection || editor.selection.isEmpty) return null; // const { selection, document } = editor; // const { line: lineNum, character: charNum } = selection.start; // const isFirstCharOnLineSelected = charNum === 0; // const isFirstLine = lineNum === 0; // const getEndLine = () => { // if (isFirstCharOnLineSelected) { // if (isFirstLine) { // return lineNum; // } // return lineNum - 1; // } // return lineNum; // }; // const getEndChar = () => { // if (isFirstCharOnLineSelected) { // if (isFirstLine) { // return 0; // } // return document.lineAt(lineNum - 1).range.end.character; // } // return charNum - 1; // }; // const selectionRange = new vscode.Range(0, 0, getEndLine(), getEndChar()); // return editor.document.getText(selectionRange); }; export const getTextAfterSelected = (): string | null => { return null; // const editor = vscode.window.activeTextEditor; // if (!editor || !editor.selection || editor.selection.isEmpty) return null; // const { selection, document } = editor; // const { line: lineNum, character: charNum } = selection.end; // const isLastCharOnLineSelected = charNum === document.lineAt(lineNum).range.end.character; // const isLastLine = lineNum === document.lineCount; // const getStartLine = () => { // if (isLastCharOnLineSelected) { // if (isLastLine) { // return lineNum; // } // return lineNum + 1; // } // return lineNum; // }; // const getStartChar = () => { // if (isLastCharOnLineSelected) { // if (isLastLine) { // return charNum; // } // return 0; // } // return charNum + 1; // }; // const selectionRange = new vscode.Range( // getStartLine(), // getStartChar(), // document.lineCount, // document.lineAt(document.lineCount - 1).range.end.character, // ); // return editor.document.getText(selectionRange); }; References:" You are a code assistant,Definition of 'CreateHttpServerResult' in file src/node/http/create_fastify_http_server.ts in project gitlab-lsp,"Definition: type CreateHttpServerResult = { address: URL; server: FastifyInstance; shutdown: () => Promise; }; export const createFastifyHttpServer = async ( props: Partial, ): Promise => { const { port = 0, plugins = [] } = props; const logger = props.logger && loggerWithPrefix(props.logger, '[HttpServer]:'); const server = fastify({ forceCloseConnections: true, ignoreTrailingSlash: true, logger: createFastifyLogger(logger), }); try { await registerPlugins(server, plugins, logger); const address = await startFastifyServer(server, port, logger); await server.ready(); logger?.info(`server listening on ${address}`); return { address, server, shutdown: async () => { try { await server.close(); logger?.info('server shutdown'); } catch (err) { logger?.error('error during server shutdown', err as Error); } }, }; } catch (err) { logger?.error('error during server setup', err as Error); throw err; } }; const registerPlugins = async ( server: FastifyInstance, plugins: FastifyPluginRegistration[], logger?: ILog, ) => { await Promise.all( plugins.map(async ({ plugin, options }) => { try { await server.register(plugin, options); } catch (err) { logger?.error('Error during plugin registration', err as Error); throw err; } }), ); }; const startFastifyServer = (server: FastifyInstance, port: number, logger?: ILog): Promise => new Promise((resolve, reject) => { try { server.listen({ port, host: '127.0.0.1' }, (err, address) => { if (err) { logger?.error(err); reject(err); return; } resolve(new URL(address)); }); } catch (error) { reject(error); } }); const createFastifyLogger = (logger?: ILog): FastifyBaseLogger | undefined => logger ? pino(createLoggerTransport(logger)) : undefined; References:" You are a code assistant,Definition of 'getForActiveProject' in file packages/webview_duo_chat/src/plugin/port/platform/gitlab_platform.ts in project gitlab-lsp,"Definition: getForActiveProject(userInitiated: boolean): Promise; /** * 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; /** * 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; getForAllAccounts(): Promise; /** * Returns GitLabPlatformForAccount if there is a SaaS account added. Otherwise returns undefined. */ getForSaaSAccount(): Promise; } References:" You are a code assistant,Definition of 'isAtOrNearEndOfLine' in file src/common/suggestion/suggestion_filter.ts in project gitlab-lsp,"Definition: export function isAtOrNearEndOfLine(suffix: string) { const match = suffix.match(/\r?\n/); const lineSuffix = match ? suffix.substring(0, match.index) : suffix; // Remainder of line only contains characters within the allowed set // The reasoning for this regex is documented here: // https://gitlab.com/gitlab-org/editor-extensions/gitlab-language-server-for-code-suggestions/-/merge_requests/61#note_1608564289 const allowedCharactersPastCursorRegExp = /^\s*[)}\]""'`]*\s*[:{;,]?\s*$/; return allowedCharactersPastCursorRegExp.test(lineSuffix); } /** * Returns true when context.selectedCompletionInfo.range property represents a text * range in the document that doesn't match the text contained in context.selectedCompletionInfo.text. * * This scenario may occur in autocomplete dropdown widgets, for example VSCode's IntelliSense. * In such a case, it will not display the inline completion so we should not request the suggestion. * * @param context * @param document * @returns */ export function shouldRejectCompletionWithSelectedCompletionTextMismatch( context: InlineCompletionContext, document?: TextDocument, ): boolean { if (!context.selectedCompletionInfo || !document) { return false; } const currentText = document.getText(sanitizeRange(context.selectedCompletionInfo.range)); const selectedText = context.selectedCompletionInfo.text; return !selectedText.startsWith(currentText); } References: - src/common/suggestion/suggestion_service.ts:413 - src/common/suggestion/suggestion_filter.test.ts:25" You are a code assistant,Definition of 'constructor' in file src/common/feature_flags.ts in project gitlab-lsp,"Definition: 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 { 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 { 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 'OpenTabsResolver' in file src/common/advanced_context/context_resolvers/open_tabs_context_resolver.ts in project gitlab-lsp,"Definition: export class OpenTabsResolver extends AdvancedContextResolver { static #instance: OpenTabsResolver | undefined; public static getInstance(): OpenTabsResolver { if (!OpenTabsResolver.#instance) { log.debug('OpenTabsResolver: initializing'); OpenTabsResolver.#instance = new OpenTabsResolver(); } return OpenTabsResolver.#instance; } public static destroyInstance(): void { OpenTabsResolver.#instance = undefined; } async *buildContext({ documentContext, includeCurrentFile = false, }: { documentContext?: IDocContext; includeCurrentFile?: boolean; }): AsyncGenerator { const lruCache = LruCache.getInstance(LRU_CACHE_BYTE_SIZE_LIMIT); const openFiles = lruCache.mostRecentFiles({ context: documentContext, includeCurrentFile, }); for (const file of openFiles) { yield { uri: file.uri, type: 'file' as const, content: `${file.prefix}${file.suffix}`, fileRelativePath: file.fileRelativePath, strategy: 'open_tabs' as const, workspaceFolder: file.workspaceFolder ?? { name: '', uri: '' }, }; } } } References: - src/common/advanced_context/context_resolvers/open_tabs_context_resolver.test.ts:9 - src/common/advanced_context/context_resolvers/open_tabs_context_resolver.ts:13 - src/common/advanced_context/context_resolvers/open_tabs_context_resolver.test.ts:13 - src/common/advanced_context/context_resolvers/open_tabs_context_resolver.ts:10" You are a code assistant,Definition of 'FakeParser' in file src/common/tree_sitter/parser.test.ts in project gitlab-lsp,"Definition: class FakeParser { setLanguage = jest.fn(); } jest.mocked(Parser).mockImplementation(() => createFakePartial(new FakeParser())); const loadSpy = jest.spyOn(Parser.Language, 'load'); const result = await treeSitterParser.getParser({ name: 'typescript', extensions: ['.ts'], wasmPath: '/path/to/tree-sitter-typescript.wasm', nodeModulesPath: '/path/to/node_modules', }); expect(loadSpy).toHaveBeenCalledWith('/path/to/tree-sitter-typescript.wasm'); expect(result).toBeInstanceOf(FakeParser); }); it('should handle parser loading error', async () => { (Parser.Language.load as jest.Mock).mockRejectedValue(new Error('Loading error')); const result = await treeSitterParser.getParser({ name: 'typescript', extensions: ['.ts'], wasmPath: '/path/to/tree-sitter-typescript.wasm', nodeModulesPath: '/path/to/node_modules', }); expect(treeSitterParser.loadStateValue).toBe(TreeSitterParserLoadState.ERRORED); expect(result).toBeUndefined(); }); }); describe('getLanguageNameForFile', () => { it('should return the language name for a given file', () => { const result = treeSitterParser.getLanguageNameForFile('test.ts'); expect(result).toBe('typescript'); }); it('should return undefined when no language is found for a file', () => { const result = treeSitterParser.getLanguageNameForFile('test.txt'); expect(result).toBeUndefined(); }); }); describe('buildTreeSitterInfoByExtMap', () => { it('should build the language info map by extension', () => { const result = treeSitterParser.buildTreeSitterInfoByExtMap(languages); expect(result).toEqual( new Map([ ['.ts', languages[0]], ['.js', languages[1]], ]), ); }); }); }); References: - src/common/tree_sitter/parser.test.ts:127" You are a code assistant,Definition of 'WorkspaceService' in file src/common/workspace/workspace_service.ts in project gitlab-lsp,"Definition: export const WorkspaceService = createInterfaceId('WorkspaceService'); @Injectable(WorkspaceService, [VirtualFileSystemService]) export class DefaultWorkspaceService { #virtualFileSystemService: DefaultVirtualFileSystemService; #workspaceFilesMap = new Map(); #disposable: { dispose: () => void }; constructor(virtualFileSystemService: DefaultVirtualFileSystemService) { this.#virtualFileSystemService = virtualFileSystemService; this.#disposable = this.#setupEventListeners(); } #setupEventListeners() { return this.#virtualFileSystemService.onFileSystemEvent((eventType, data) => { switch (eventType) { case VirtualFileSystemEvents.WorkspaceFilesUpdate: this.#handleWorkspaceFilesUpdate(data as WorkspaceFilesUpdate); break; case VirtualFileSystemEvents.WorkspaceFileUpdate: this.#handleWorkspaceFileUpdate(data as WorkspaceFileUpdate); break; default: break; } }); } #handleWorkspaceFilesUpdate(update: WorkspaceFilesUpdate) { const files: FileSet = new Map(); for (const file of update.files) { files.set(file.toString(), file); } this.#workspaceFilesMap.set(update.workspaceFolder.uri, files); } #handleWorkspaceFileUpdate(update: WorkspaceFileUpdate) { let files = this.#workspaceFilesMap.get(update.workspaceFolder.uri); if (!files) { files = new Map(); this.#workspaceFilesMap.set(update.workspaceFolder.uri, files); } switch (update.event) { case 'add': case 'change': files.set(update.fileUri.toString(), update.fileUri); break; case 'unlink': files.delete(update.fileUri.toString()); break; default: break; } } getWorkspaceFiles(workspaceFolder: WorkspaceFolder): FileSet | undefined { return this.#workspaceFilesMap.get(workspaceFolder.uri); } dispose() { this.#disposable.dispose(); } } References:" You are a code assistant,Definition of 'constructor' in file packages/lib_di/src/index.test.ts in project gitlab-lsp,"Definition: 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 'GitLabChatRecord' in file packages/webview_duo_chat/src/plugin/port/chat/gitlab_chat_record.ts in project gitlab-lsp,"Definition: export class GitLabChatRecord { chunkId?: number | null; role: ChatRecordRole; content?: string; contentHtml?: string; id: string; requestId?: string; state: ChatRecordState; timestamp: number; type: ChatRecordType; errors: string[]; extras?: { sources: object[]; }; context?: GitLabChatRecordContext; constructor({ chunkId, type, role, content, contentHtml, state, requestId, errors, timestamp, extras, }: GitLabChatRecordAttributes) { this.chunkId = chunkId; this.role = role; this.content = content; this.contentHtml = contentHtml; this.type = type ?? this.#detectType(); this.state = state ?? 'ready'; this.requestId = requestId; this.errors = errors ?? []; this.id = uuidv4(); this.timestamp = timestamp ? Date.parse(timestamp) : Date.now(); this.extras = extras; } static buildWithContext(attributes: GitLabChatRecordAttributes): GitLabChatRecord { const record = new GitLabChatRecord(attributes); record.context = buildCurrentContext(); return record; } update(attributes: Partial) { const convertedAttributes = attributes as Partial; if (attributes.timestamp) { convertedAttributes.timestamp = Date.parse(attributes.timestamp); } Object.assign(this, convertedAttributes); } #detectType(): ChatRecordType { if (this.content === SPECIAL_MESSAGES.RESET) { return 'newConversation'; } return 'general'; } } References: - packages/webview_duo_chat/src/plugin/chat_controller.ts:49 - packages/webview_duo_chat/src/plugin/port/chat/gitlab_chat_record.ts:82 - packages/webview_duo_chat/src/plugin/port/chat/gitlab_chat_record.test.ts:19 - packages/webview_duo_chat/src/plugin/chat_controller.ts:111 - packages/webview_duo_chat/src/plugin/chat_controller.ts:66 - packages/webview_duo_chat/src/plugin/port/chat/gitlab_chat_record.test.ts:34 - packages/webview_duo_chat/src/plugin/chat_controller.ts:127 - packages/webview_duo_chat/src/plugin/port/chat/gitlab_chat_record.test.ts:13 - packages/webview_duo_chat/src/plugin/chat_controller.ts:106 - packages/webview_duo_chat/src/plugin/port/chat/gitlab_chat_record.test.ts:35 - packages/webview_duo_chat/src/plugin/port/chat/gitlab_chat_record.ts:81 - packages/webview_duo_chat/src/plugin/port/chat/gitlab_chat_record.test.ts:10" You are a code assistant,Definition of 'WORKFLOW_MESSAGE_NOTIFICATION' in file src/common/suggestion/suggestion_service.ts in project gitlab-lsp,"Definition: 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 => { 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 => { 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 => { 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 { 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 { 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 { 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 { 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 { 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:" You are a code assistant,Definition of 'WebviewMessageBusManagerHandler' in file packages/lib_webview_plugin/src/types.ts in project gitlab-lsp,"Definition: export type WebviewMessageBusManagerHandler = ( webviewInstanceId: WebviewInstanceId, messageBus: MessageBus, // eslint-disable-next-line @typescript-eslint/no-invalid-void-type ) => Disposable | void; export interface WebviewConnection { broadcast: ( type: TMethod, payload: T['outbound']['notifications'][TMethod], ) => void; onInstanceConnected: (handler: WebviewMessageBusManagerHandler) => void; } References:" You are a code assistant,Definition of 'transform' in file src/common/document_transformer_service.ts in project gitlab-lsp,"Definition: transform(context: IDocContext): IDocContext; } const getMatchingWorkspaceFolder = ( fileUri: DocumentUri, workspaceFolders: WorkspaceFolder[], ): WorkspaceFolder | undefined => workspaceFolders.find((wf) => fileUri.startsWith(wf.uri)); const getRelativePath = (fileUri: DocumentUri, workspaceFolder?: WorkspaceFolder): string => { if (!workspaceFolder) { // splitting a string will produce at least one item and so the pop can't return undefined // eslint-disable-next-line @typescript-eslint/no-non-null-assertion return fileUri.split(/[\\/]/).pop()!; } return fileUri.slice(workspaceFolder.uri.length).replace(/^\//, ''); }; export interface DocumentTransformerService { get(uri: string): TextDocument | undefined; getContext( uri: string, position: Position, workspaceFolders: WorkspaceFolder[], completionContext?: InlineCompletionContext, ): IDocContext | undefined; transform(context: IDocContext): IDocContext; } export const DocumentTransformerService = createInterfaceId( 'DocumentTransformerService', ); @Injectable(DocumentTransformerService, [LsTextDocuments, SecretRedactor]) export class DefaultDocumentTransformerService implements DocumentTransformerService { #transformers: IDocTransformer[] = []; #documents: LsTextDocuments; 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 'createInterfaceId' in file packages/lib_di/src/index.ts in project gitlab-lsp,"Definition: export const createInterfaceId = (id: string): InterfaceId => `${id}-${getRandomString()}` as InterfaceId; /* * Takes an array of InterfaceIDs with unknown type and turn them into an array of the types that the InterfaceIds wrap * * e.g. `UnwrapInterfaceIds<[InterfaceId, InterfaceId]>` equals to `[string, number]` * * this type is used to enforce dependency types in the constructor of the injected class */ type UnwrapInterfaceIds[]> = { [K in keyof T]: T[K] extends InterfaceId ? U : never; }; interface Metadata { id: string; dependencies: string[]; } /** * Here we store the id and dependencies for all classes decorated with @Injectable */ const injectableMetadata = new WeakMap(); /** * Decorate your class with @Injectable(id, dependencies) * param id = InterfaceId of the interface implemented by your class (use createInterfaceId to create one) * param dependencies = List of InterfaceIds that will be injected into class' constructor */ export function Injectable[]>( id: InterfaceId, dependencies: [...TDependencies], // we can add `| [] = [],` to make dependencies optional, but the type checker messages are quite cryptic when the decorated class has some constructor arguments ) { // this is the trickiest part of the whole DI framework // we say, this decorator takes // - id (the interface that the injectable implements) // - dependencies (list of interface ids that will be injected to constructor) // // With then we return function that ensures that the decorated class implements the id interface // and its constructor has arguments of same type and order as the dependencies argument to the decorator return function ): I }>( constructor: T, { kind }: ClassDecoratorContext, ) { if (kind === 'class') { injectableMetadata.set(constructor, { id, dependencies: dependencies || [] }); return constructor; } throw new Error('Injectable decorator can only be used on a class.'); }; } // new (...args: any[]): any is actually how TS defines type of a class // eslint-disable-next-line @typescript-eslint/no-explicit-any type WithConstructor = { new (...args: any[]): any; name: string }; type ClassWithDependencies = { cls: WithConstructor; id: string; dependencies: string[] }; type Validator = (cwds: ClassWithDependencies[], instanceIds: string[]) => void; const sanitizeId = (idWithRandom: string) => idWithRandom.replace(/-[^-]+$/, ''); /** ensures that only one interface ID implementation is present */ const interfaceUsedOnlyOnce: Validator = (cwds, instanceIds) => { const clashingWithExistingInstance = cwds.filter((cwd) => instanceIds.includes(cwd.id)); if (clashingWithExistingInstance.length > 0) { throw new Error( `The following classes are clashing (have duplicate ID) with instances already present in the container: ${clashingWithExistingInstance.map((cwd) => cwd.cls.name)}`, ); } const groupedById = groupBy(cwds, (cwd) => cwd.id); if (Object.values(groupedById).every((groupedCwds) => groupedCwds.length === 1)) { return; } const messages = Object.entries(groupedById).map( ([id, groupedCwds]) => `'${sanitizeId(id)}' (classes: ${groupedCwds.map((cwd) => cwd.cls.name).join(',')})`, ); throw new Error(`The following interface IDs were used multiple times ${messages.join(',')}`); }; /** throws an error if any class depends on an interface that is not available */ const dependenciesArePresent: Validator = (cwds, instanceIds) => { const allIds = new Set([...cwds.map((cwd) => cwd.id), ...instanceIds]); const cwsWithUnmetDeps = cwds.filter((cwd) => !cwd.dependencies.every((d) => allIds.has(d))); if (cwsWithUnmetDeps.length === 0) { return; } const messages = cwsWithUnmetDeps.map((cwd) => { const unmetDeps = cwd.dependencies.filter((d) => !allIds.has(d)).map(sanitizeId); return `Class ${cwd.cls.name} (interface ${sanitizeId(cwd.id)}) depends on interfaces [${unmetDeps}] that weren't added to the init method.`; }); throw new Error(messages.join('\n')); }; /** uses depth first search to find out if the classes have circular dependency */ const noCircularDependencies: Validator = (cwds, instanceIds) => { const inStack = new Set(); const hasCircularDependency = (id: string): boolean => { if (inStack.has(id)) { return true; } inStack.add(id); const cwd = cwds.find((c) => c.id === id); // we reference existing instance, there won't be circular dependency past this one because instances don't have any dependencies if (!cwd && instanceIds.includes(id)) { inStack.delete(id); return false; } if (!cwd) throw new Error(`assertion error: dependency ID missing ${sanitizeId(id)}`); for (const dependencyId of cwd.dependencies) { if (hasCircularDependency(dependencyId)) { return true; } } inStack.delete(id); return false; }; for (const cwd of cwds) { if (hasCircularDependency(cwd.id)) { throw new Error( `Circular dependency detected between interfaces (${Array.from(inStack).map(sanitizeId)}), starting with '${sanitizeId(cwd.id)}' (class: ${cwd.cls.name}).`, ); } } }; /** * Topological sort of the dependencies - returns array of classes. The classes should be initialized in order given by the array. * https://en.wikipedia.org/wiki/Topological_sorting */ const sortDependencies = (classes: Map): ClassWithDependencies[] => { const visited = new Set(); const sortedClasses: ClassWithDependencies[] = []; const topologicalSort = (interfaceId: string) => { if (visited.has(interfaceId)) { return; } visited.add(interfaceId); const cwd = classes.get(interfaceId); if (!cwd) { // the instance for this ID is already initiated return; } for (const d of cwd.dependencies || []) { topologicalSort(d); } sortedClasses.push(cwd); }; for (const id of classes.keys()) { topologicalSort(id); } return sortedClasses; }; /** * Helper type used by the brandInstance function to ensure that all container.addInstances parameters are branded */ export type BrandedInstance = T; /** * use brandInstance to be able to pass this instance to the container.addInstances method */ export const brandInstance = ( id: InterfaceId, instance: T, ): BrandedInstance => { injectableMetadata.set(instance, { id, dependencies: [] }); return instance; }; /** * Container is responsible for initializing a dependency tree. * * It receives a list of classes decorated with the `@Injectable` decorator * and it constructs instances of these classes in an order that ensures class' dependencies * are initialized before the class itself. * * check https://gitlab.com/viktomas/needle for full documentation of this mini-framework */ export class Container { #instances = new Map(); /** * addInstances allows you to add pre-initialized objects to the container. * This is useful when you want to keep mandatory parameters in class' constructor (e.g. some runtime objects like server connection). * addInstances accepts a list of any objects that have been ""branded"" by the `brandInstance` method */ addInstances(...instances: BrandedInstance[]) { for (const instance of instances) { const metadata = injectableMetadata.get(instance); if (!metadata) { throw new Error( 'assertion error: addInstance invoked without branded object, make sure all arguments are branded with `brandInstance`', ); } if (this.#instances.has(metadata.id)) { throw new Error( `you are trying to add instance for interfaceId ${metadata.id}, but instance with this ID is already in the container.`, ); } this.#instances.set(metadata.id, instance); } } /** * instantiate accepts list of classes, validates that they can be managed by the container * and then initialized them in such order that dependencies of a class are initialized before the class */ instantiate(...classes: WithConstructor[]) { // ensure all classes have been decorated with @Injectable const undecorated = classes.filter((c) => !injectableMetadata.has(c)).map((c) => c.name); if (undecorated.length) { throw new Error(`Classes [${undecorated}] are not decorated with @Injectable.`); } const classesWithDeps: ClassWithDependencies[] = classes.map((cls) => { // we verified just above that all classes are present in the metadata map // eslint-disable-next-line @typescript-eslint/no-non-null-assertion const { id, dependencies } = injectableMetadata.get(cls)!; return { cls, id, dependencies }; }); const validators: Validator[] = [ interfaceUsedOnlyOnce, dependenciesArePresent, noCircularDependencies, ]; validators.forEach((v) => v(classesWithDeps, Array.from(this.#instances.keys()))); const classesById = new Map(); // Index classes by their interface id classesWithDeps.forEach((cwd) => { classesById.set(cwd.id, cwd); }); // Create instances in topological order for (const cwd of sortDependencies(classesById)) { const args = cwd.dependencies.map((dependencyId) => this.#instances.get(dependencyId)); // eslint-disable-next-line new-cap const instance = new cwd.cls(...args); this.#instances.set(cwd.id, instance); } } get(id: InterfaceId): T { const instance = this.#instances.get(id); if (!instance) { throw new Error(`Instance for interface '${sanitizeId(id)}' is not in the container.`); } return instance as T; } } References: - packages/lib_di/src/index.test.ts:57 - src/common/core/handlers/did_change_workspace_folders_handler.ts:10 - src/common/document_service.ts:23 - src/common/services/fs/dir.ts:38 - src/common/ai_context_management_2/ai_policy_management.ts:11 - src/common/connection_service.ts:31 - src/common/external_interfaces.ts:9 - src/common/ai_context_management_2/policies/duo_project_policy.ts:9 - src/common/api.ts:36 - src/common/suggestion/supported_languages_service.ts:24 - src/common/config_service.ts:108 - src/common/core/handlers/initialize_handler.ts:15 - src/common/graphql/workflow/service.ts:10 - src/common/ai_context_management_2/retrievers/ai_file_context_retriever.ts:12 - src/common/core/handlers/token_check_notifier.ts:8 - packages/lib_di/src/index.test.ts:17 - src/common/services/fs/file.ts:11 - src/common/feature_state/supported_language_check.ts:14 - src/common/secret_redaction/index.ts:11 - src/common/fetch.ts:28 - src/node/duo_workflow/desktop_workflow_runner.ts:39 - src/common/feature_state/project_duo_acces_check.ts:17 - src/common/services/fs/virtual_file_service.ts:36 - src/common/services/duo_access/project_access_checker.ts:16 - src/common/feature_state/feature_state_manager.ts:17 - src/common/security_diagnostics_publisher.ts:27 - packages/lib_di/src/index.test.ts:18 - src/common/graphql/workflow/service.ts:9 - src/common/services/duo_access/project_access_cache.ts:83 - packages/lib_di/src/index.test.ts:16 - src/common/external_interfaces.ts:6 - src/common/ai_context_management_2/providers/ai_file_context_provider.ts:17 - src/common/advanced_context/advanced_context_service.ts:16 - src/common/tracking/tracking_types.ts:88 - src/common/ai_context_management_2/ai_context_manager.ts:9 - src/common/workspace/workspace_service.ts:16 - src/common/ai_context_management_2/ai_context_aggregator.ts:13 - src/common/feature_flags.ts:24 - src/common/document_transformer_service.ts:72 - src/common/git/repository_service.ts:24" You are a code assistant,Definition of 'dispose' in file packages/lib_webview/src/setup/plugin/webview_instance_message_bus.ts in project gitlab-lsp,"Definition: dispose(): void { this.#eventSubscriptions.dispose(); this.#notificationEvents.dispose(); this.#requestEvents.dispose(); this.#pendingResponseEvents.dispose(); } } References:" You are a code assistant,Definition of 'JsonRpcConnectionTransport' in file packages/lib_webview_transport_json_rpc/src/json_rpc_connection_transport.ts in project gitlab-lsp,"Definition: export class JsonRpcConnectionTransport implements Transport { #messageEmitter = createWebviewTransportEventEmitter(); #connection: Connection; #notificationChannel: string; #webviewCreatedChannel: string; #webviewDestroyedChannel: string; #logger?: Logger; #disposables: Disposable[] = []; constructor({ connection, logger, notificationRpcMethod: notificationChannel = DEFAULT_NOTIFICATION_RPC_METHOD, webviewCreatedRpcMethod: webviewCreatedChannel = DEFAULT_WEBVIEW_CREATED_RPC_METHOD, webviewDestroyedRpcMethod: webviewDestroyedChannel = DEFAULT_WEBVIEW_DESTROYED_RPC_METHOD, }: JsonRpcConnectionTransportProps) { this.#connection = connection; this.#logger = logger ? withPrefix(logger, LOGGER_PREFIX) : undefined; this.#notificationChannel = notificationChannel; this.#webviewCreatedChannel = webviewCreatedChannel; this.#webviewDestroyedChannel = webviewDestroyedChannel; this.#subscribeToConnection(); } #subscribeToConnection() { const channelToNotificationHandlerMap = { [this.#webviewCreatedChannel]: handleWebviewCreated(this.#messageEmitter, this.#logger), [this.#webviewDestroyedChannel]: handleWebviewDestroyed(this.#messageEmitter, this.#logger), [this.#notificationChannel]: handleWebviewMessage(this.#messageEmitter, this.#logger), }; Object.entries(channelToNotificationHandlerMap).forEach(([channel, handler]) => { const disposable = this.#connection.onNotification(channel, handler); this.#disposables.push(disposable); }); } on( type: K, callback: TransportMessageHandler, ): Disposable { this.#messageEmitter.on(type, callback as WebviewTransportEventEmitterMessages[K]); return { dispose: () => this.#messageEmitter.off(type, callback as WebviewTransportEventEmitterMessages[K]), }; } publish(type: K, payload: MessagesToClient[K]): Promise { if (type === 'webview_instance_notification') { return this.#connection.sendNotification(this.#notificationChannel, payload); } throw new Error(`Unknown message type: ${type}`); } dispose(): void { this.#messageEmitter.removeAllListeners(); this.#disposables.forEach((disposable) => disposable.dispose()); this.#logger?.debug('JsonRpcConnectionTransport disposed'); } } References: - src/node/main.ts:186 - packages/lib_webview_transport_json_rpc/src/json_rpc_connection_transport.test.ts:19 - packages/lib_webview_transport_json_rpc/src/json_rpc_connection_transport.test.ts:8" You are a code assistant,Definition of 'constructor' in file src/common/core/handlers/did_change_workspace_folders_handler.ts in project gitlab-lsp,"Definition: constructor(configService: ConfigService) { this.#configService = configService; } notificationHandler: NotificationHandler = ( 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:" You are a code assistant,Definition of 'handleNotificationMessage' in file src/common/webview/extension/handlers/handle_notification_message.ts in project gitlab-lsp,"Definition: export const handleNotificationMessage = (handlerRegistry: ExtensionMessageHandlerRegistry, logger: Logger) => async (message: unknown) => { if (!isExtensionMessage(message)) { logger.debug(`Received invalid request message: ${JSON.stringify(message)}`); return; } const { webviewId, type, payload } = message; try { await handlerRegistry.handle({ webviewId, type }, payload); } catch (error) { logger.error( `Failed to handle reuest for webviewId: ${webviewId}, type: ${type}, payload: ${JSON.stringify(payload)}`, error as Error, ); } }; References: - src/common/webview/extension/extension_connection_message_bus_provider.ts:79" You are a code assistant,Definition of 'runPolicies' in file src/common/ai_context_management_2/ai_policy_management.ts in project gitlab-lsp,"Definition: 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:" You are a code assistant,Definition of 'FileResolver' in file src/common/services/fs/file.ts in project gitlab-lsp,"Definition: export const FileResolver = createInterfaceId('FileResolver'); @Injectable(FileResolver, []) export class EmptyFileResolver { // eslint-disable-next-line @typescript-eslint/no-unused-vars readFile(_args: ReadFile): Promise { return Promise.resolve(''); } } References: - src/common/services/duo_access/project_access_cache.ts:93 - src/common/ai_context_management_2/retrievers/ai_file_context_retriever.ts:17" You are a code assistant,Definition of 'CHAT_MODEL_ROLES' in file packages/webview_duo_chat/src/app/constants.ts in project gitlab-lsp,"Definition: export const CHAT_MODEL_ROLES = { user: 'user', system: 'system', assistant: 'assistant', }; export const SPECIAL_MESSAGES = { CLEAN: '/clean', CLEAR: '/clear', RESET: '/reset', }; References:" You are a code assistant,Definition of 'processStream' in file src/common/suggestion_client/post_processors/post_processor_pipeline.test.ts in project gitlab-lsp,"Definition: async processStream( _context: IDocContext, input: StreamingCompletionResponse, ): Promise { return input; } async processCompletion( _context: IDocContext, input: SuggestionOption[], ): Promise { return input.map((option) => ({ ...option, text: `${option.text} processed` })); } } pipeline.addProcessor(new TestCompletionProcessor()); const completionInput: SuggestionOption[] = [{ text: 'option1', uniqueTrackingId: '1' }]; const result = await pipeline.run({ documentContext: mockContext, input: completionInput, type: 'completion', }); expect(result).toEqual([{ text: 'option1 processed', uniqueTrackingId: '1' }]); }); test('should chain multiple processors correctly for stream input', async () => { class Processor1 extends PostProcessor { async processStream( _context: IDocContext, input: StreamingCompletionResponse, ): Promise { return { ...input, completion: `${input.completion} [1]` }; } async processCompletion( _context: IDocContext, input: SuggestionOption[], ): Promise { return input; } } class Processor2 extends PostProcessor { async processStream( _context: IDocContext, input: StreamingCompletionResponse, ): Promise { return { ...input, completion: `${input.completion} [2]` }; } async processCompletion( _context: IDocContext, input: SuggestionOption[], ): Promise { return input; } } pipeline.addProcessor(new Processor1()); pipeline.addProcessor(new Processor2()); const streamInput: StreamingCompletionResponse = { id: '1', completion: 'test', done: false }; const result = await pipeline.run({ documentContext: mockContext, input: streamInput, type: 'stream', }); expect(result).toEqual({ id: '1', completion: 'test [1] [2]', done: false }); }); test('should chain multiple processors correctly for completion input', async () => { class Processor1 extends PostProcessor { async processStream( _context: IDocContext, input: StreamingCompletionResponse, ): Promise { return input; } async processCompletion( _context: IDocContext, input: SuggestionOption[], ): Promise { return input.map((option) => ({ ...option, text: `${option.text} [1]` })); } } class Processor2 extends PostProcessor { async processStream( _context: IDocContext, input: StreamingCompletionResponse, ): Promise { return input; } async processCompletion( _context: IDocContext, input: SuggestionOption[], ): Promise { return input.map((option) => ({ ...option, text: `${option.text} [2]` })); } } pipeline.addProcessor(new Processor1()); pipeline.addProcessor(new Processor2()); const completionInput: SuggestionOption[] = [{ text: 'option1', uniqueTrackingId: '1' }]; const result = await pipeline.run({ documentContext: mockContext, input: completionInput, type: 'completion', }); expect(result).toEqual([{ text: 'option1 [1] [2]', uniqueTrackingId: '1' }]); }); test('should throw an error for unexpected type', async () => { class TestProcessor extends PostProcessor { async processStream( _context: IDocContext, input: StreamingCompletionResponse, ): Promise { return input; } async processCompletion( _context: IDocContext, input: SuggestionOption[], ): Promise { 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 'post' in file src/common/fetch.ts in project gitlab-lsp,"Definition: async post(input: RequestInfo | URL, init?: RequestInit): Promise { return this.fetch(input, this.updateRequestInit('POST', init)); } async put(input: RequestInfo | URL, init?: RequestInit): Promise { return this.fetch(input, this.updateRequestInit('PUT', init)); } async fetchBase(input: RequestInfo | URL, init?: RequestInit): Promise { // 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 'waitMs' in file src/common/message_handler.ts in project gitlab-lsp,"Definition: 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 => { 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/suggestion/suggestion_service.ts:232" You are a code assistant,Definition of 'LsConnection' in file src/common/external_interfaces.ts in project gitlab-lsp,"Definition: export const LsConnection = createInterfaceId('LsConnection'); export type LsTextDocuments = TextDocuments; export const LsTextDocuments = createInterfaceId('LsTextDocuments'); References: - src/common/connection_service.ts:60 - src/common/connection_service.ts:53 - src/common/connection_service.ts:34 - src/common/connection_service.ts:38 - src/common/advanced_context/advanced_context_service.ts:34" You are a code assistant,Definition of 'greet5' in file src/tests/fixtures/intent/empty_function/javascript.js in project gitlab-lsp,"Definition: 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:12" You are a code assistant,Definition of 'WEBVIEW_TITLE' in file packages/webview-chat/src/constants.ts in project gitlab-lsp,"Definition: export const WEBVIEW_TITLE = 'GitLab: Duo Chat'; References:" You are a code assistant,Definition of 'dispose' in file packages/lib_webview_transport_socket_io/src/socket_io_webview_transport.ts in project gitlab-lsp,"Definition: dispose() { this.#messageEmitter.removeAllListeners(); for (const connection of this.#connections.values()) { connection.disconnect(); } this.#connections.clear(); } } References:" You are a code assistant,Definition of 'getCommitsInMr' in file scripts/commit-lint/lint.js in project gitlab-lsp,"Definition: async function getCommitsInMr() { const diffBaseSha = CI_MERGE_REQUEST_DIFF_BASE_SHA; const sourceBranchSha = LAST_MR_COMMIT; const messages = await read({ from: diffBaseSha, to: sourceBranchSha }); return messages; } const messageMatcher = (r) => r.test.bind(r); async function isConventional(message) { return lint( message, { ...config.rules, ...customRules }, { defaultIgnores: false, ignores: [ messageMatcher(/^[Rr]evert .*/), messageMatcher(/^(?:fixup|squash)!/), messageMatcher(/^Merge branch/), messageMatcher(/^\d+\.\d+\.\d+/), ], }, ); } async function lintMr() { const commits = await getCommitsInMr(); // When MR is set to squash, but it's not yet being merged, we check the MR Title if ( CI_MERGE_REQUEST_SQUASH_ON_MERGE === 'true' && CI_MERGE_REQUEST_EVENT_TYPE !== 'merge_train' ) { console.log( 'INFO: The MR is set to squash. We will lint the MR Title (used as the commit message by default).', ); return isConventional(CI_MERGE_REQUEST_TITLE).then(Array.of); } console.log('INFO: Checking all commits that will be added by this MR.'); return Promise.all(commits.map(isConventional)); } 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/commit-lint/lint.js:54" You are a code assistant,Definition of 'CreatePluginMessageMap' in file packages/lib_webview_plugin/src/webview_plugin.ts in project gitlab-lsp,"Definition: export type CreatePluginMessageMap> = { extensionToPlugin: CreateMessageDefinitions; pluginToExtension: CreateMessageDefinitions; webviewToPlugin: CreateMessageDefinitions; pluginToWebview: CreateMessageDefinitions; }; type WebviewPluginSetupParams = { webview: WebviewConnection<{ inbound: T['webviewToPlugin']; outbound: T['pluginToWebview']; }>; extension: MessageBus<{ inbound: T['extensionToPlugin']; outbound: T['pluginToExtension']; }>; }; /** * The `WebviewPluginSetupFunc` is responsible for setting up the communication between the webview plugin and the extension, as well as between the webview plugin and individual webview instances. * * @template TWebviewPluginMessageMap - Message types recognized by the plugin. * @param webviewMessageBus - The message bus for communication with individual webview instances. * @param extensionMessageBus - The message bus for communication with the webview host (extension). * @returns An optional function to dispose of resources when the plugin is unloaded. */ type WebviewPluginSetupFunc = ( context: WebviewPluginSetupParams, // eslint-disable-next-line @typescript-eslint/no-invalid-void-type ) => Disposable | void; /** * The `WebviewPlugin` is a user implemented type defining the integration of the webview plugin with a webview host (extension) and webview instances. * * @template TWebviewPluginMessageMap - Message types recognized by the plugin. */ export type WebviewPlugin< TWebviewPluginMessageMap extends PartialDeep = PluginMessageMap, > = { id: WebviewId; title: string; setup: WebviewPluginSetupFunc>; }; References:" You are a code assistant,Definition of 'processCompletion' in file src/common/suggestion_client/post_processors/post_processor_pipeline.ts in project gitlab-lsp,"Definition: processCompletion(_context: IDocContext, input: SuggestionOption[]): Promise { return Promise.resolve(input); } } /** * Pipeline for running post-processors on completion and streaming (generation) responses. * Post-processors are used to modify completion responses before they are sent to the client. * They can be used to filter, sort, or modify completion suggestions. */ export class PostProcessorPipeline { #processors: PostProcessor[] = []; addProcessor(processor: PostProcessor): void { this.#processors.push(processor); } async run({ documentContext, input, type, }: { documentContext: IDocContext; input: ProcessorInputMap[T]; type: T; }): Promise { if (!this.#processors.length) return input as ProcessorInputMap[T]; return this.#processors.reduce( async (prevPromise, processor) => { const result = await prevPromise; // eslint-disable-next-line default-case switch (type) { case 'stream': return processor.processStream( documentContext, result as StreamingCompletionResponse, ) as Promise; case 'completion': return processor.processCompletion( documentContext, result as SuggestionOption[], ) as Promise; } throw new Error('Unexpected type in pipeline processing'); }, Promise.resolve(input) as Promise, ); } } References:" You are a code assistant,Definition of 'megaError' in file src/common/circuit_breaker/exponential_backoff_circuit_breaker.ts in project gitlab-lsp,"Definition: megaError() { this.#errorCount += 3; this.#open(); } #open() { if (this.#state === CircuitBreakerState.OPEN) { return; } this.#state = CircuitBreakerState.OPEN; log.warn( `Excess errors detected, opening '${this.#name}' circuit breaker for ${this.#getBackoffTime() / 1000} second(s).`, ); this.#timeoutId = setTimeout(() => this.#close(), this.#getBackoffTime()); this.#eventEmitter.emit('open'); } #close() { if (this.#state === CircuitBreakerState.CLOSED) { return; } if (this.#timeoutId) { clearTimeout(this.#timeoutId); } this.#state = CircuitBreakerState.CLOSED; this.#eventEmitter.emit('close'); } isOpen() { return this.#state === CircuitBreakerState.OPEN; } 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) }; } #getBackoffTime() { return Math.min( this.#initialBackoffMs * this.#backoffMultiplier ** (this.#errorCount - 1), this.#maxBackoffMs, ); } } References:" You are a code assistant,Definition of 'ISnowplowTrackerOptions' in file src/common/config_service.ts in project gitlab-lsp,"Definition: export interface ISnowplowTrackerOptions { gitlab_instance_id?: string; gitlab_global_user_id?: string; gitlab_host_name?: string; gitlab_saas_duo_pro_namespace_ids?: number[]; } export interface ISecurityScannerOptions { enabled?: boolean; serviceUrl?: string; } export interface IWorkflowSettings { dockerSocket?: string; } export interface IDuoConfig { enabledWithoutGitlabProject?: boolean; } export interface IClientConfig { /** GitLab API URL used for getting code suggestions */ baseUrl?: string; /** Full project path. */ projectPath?: string; /** PAT or OAuth token used to authenticate to GitLab API */ token?: string; /** The base URL for language server assets in the client-side extension */ baseAssetsUrl?: string; clientInfo?: IClientInfo; // FIXME: this key should be codeSuggestions (we have code completion and code generation) codeCompletion?: ICodeCompletionConfig; openTabsContext?: boolean; telemetry?: ITelemetryOptions; /** Config used for caching code suggestions */ suggestionsCache?: ISuggestionsCacheOptions; workspaceFolders?: WorkspaceFolder[] | null; /** Collection of Feature Flag values which are sent from the client */ featureFlags?: Record; logLevel?: LogLevel; ignoreCertificateErrors?: boolean; httpAgentOptions?: IHttpAgentOptions; snowplowTrackerOptions?: ISnowplowTrackerOptions; // TODO: move to `duo` duoWorkflowSettings?: IWorkflowSettings; securityScannerOptions?: ISecurityScannerOptions; duo?: IDuoConfig; } export interface IConfig { // TODO: we can possibly remove this extra level of config and move all IClientConfig properties to IConfig client: IClientConfig; } /** * ConfigService manages user configuration (e.g. baseUrl) and application state (e.g. codeCompletion.enabled) * TODO: Maybe in the future we would like to separate these two */ export interface ConfigService { get: TypedGetter; /** * set sets the property of the config * the new value completely overrides the old one */ set: TypedSetter; onConfigChange(listener: (config: IConfig) => void): Disposable; /** * merge adds `newConfig` properties into existing config, if the * property is present in both old and new config, `newConfig` * properties take precedence unless not defined * * This method performs deep merge * * **Arrays are not merged; they are replaced with the new value.** * */ merge(newConfig: Partial): void; } export const ConfigService = createInterfaceId('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 = (key?: string) => { return key ? get(this.#config, key) : this.#config; }; set: TypedSetter = (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) { mergeWith(this.#config, newConfig, (target, src) => (isArray(target) ? src : undefined)); this.#triggerChange(); } } References: - src/common/config_service.ts:71 - src/common/utils/headers_to_snowplow_options.ts:8" You are a code assistant,Definition of 'pollWorkflowEvents' in file src/common/graphql/workflow/service.ts in project gitlab-lsp,"Definition: async pollWorkflowEvents(id: string, messageBus: MessageBus): Promise { const workflowId = this.generateWorkflowID(id); let timeout: NodeJS.Timeout; const poll = async (): Promise => { 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 { 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 'LogLevel' in file src/common/log_types.ts in project gitlab-lsp,"Definition: export type LogLevel = (typeof LOG_LEVEL)[keyof typeof LOG_LEVEL]; References: - src/common/log.ts:25 - src/common/config_service.ts:68 - src/common/log.ts:53 - src/common/log.test.ts:9 - src/common/log.ts:76" You are a code assistant,Definition of 'receive' in file packages/webview_duo_chat/src/plugin/port/api/graphql/ai_completion_response_channel.ts in project gitlab-lsp,"Definition: receive(message: AiCompletionResponseResponseType) { if (!message.result.data.aiCompletionResponse) return; const data = message.result.data.aiCompletionResponse; if (data.role.toLowerCase() === 'system') { this.emit('systemMessage', data); } else if (data.chunkId) { this.emit('newChunk', data); } else { this.emit('fullMessage', data); } } } References:" You are a code assistant,Definition of 'setFile' in file src/common/git/repository.ts in project gitlab-lsp,"Definition: setFile(fileUri: URI): void { if (!this.isFileIgnored(fileUri)) { this.#files.set(fileUri.toString(), { uri: fileUri, isIgnored: false, repositoryUri: this.uri, workspaceFolder: this.workspaceFolder, }); } else { this.#files.set(fileUri.toString(), { uri: fileUri, isIgnored: true, repositoryUri: this.uri, workspaceFolder: this.workspaceFolder, }); } } getFile(fileUri: string): RepositoryFile | undefined { return this.#files.get(fileUri); } removeFile(fileUri: string): void { this.#files.delete(fileUri); } getFiles(): Map { return this.#files; } dispose(): void { this.#ignoreManager.dispose(); this.#files.clear(); } } References:" You are a code assistant,Definition of 'render' in file packages/webview_duo_chat/src/app/main.ts in project gitlab-lsp,"Definition: render(createElement) { return createElement(App); }, }).$mount(); } References:" You are a code assistant,Definition of 'updateRequestInit' in file src/common/fetch.ts in project gitlab-lsp,"Definition: 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 {} async destroy(): Promise {} async fetch(input: RequestInfo | URL, init?: RequestInit): Promise { 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 { // Stub. Should delegate to the node or browser fetch implementations throw new Error('Not implemented'); yield ''; } async delete(input: RequestInfo | URL, init?: RequestInit): Promise { return this.fetch(input, this.updateRequestInit('DELETE', init)); } async get(input: RequestInfo | URL, init?: RequestInit): Promise { return this.fetch(input, this.updateRequestInit('GET', init)); } async post(input: RequestInfo | URL, init?: RequestInit): Promise { return this.fetch(input, this.updateRequestInit('POST', init)); } async put(input: RequestInfo | URL, init?: RequestInit): Promise { return this.fetch(input, this.updateRequestInit('PUT', init)); } async fetchBase(input: RequestInfo | URL, init?: RequestInit): Promise { // 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 'createFakeContext' in file src/common/advanced_context/lru_cache.test.ts in project gitlab-lsp,"Definition: export function createFakeContext(overrides: Partial = {}): IDocContext { return { prefix: '', suffix: '', fileRelativePath: 'file:///test.ts', position: { line: 0, character: 0 }, uri: 'file:///test.ts', languageId: 'typescript', workspaceFolder: { uri: 'file:///workspace', name: 'test-workspace', }, ...overrides, }; } describe('LruCache', () => { let lruCache: LruCache; beforeEach(() => { lruCache = LruCache.getInstance(TEST_BYTE_LIMIT); }); afterEach(() => { LruCache.destroyInstance(); }); describe('getInstance', () => { it('should return a singleton instance of LruCache', () => { const cache1 = LruCache.getInstance(TEST_BYTE_LIMIT); const cache2 = LruCache.getInstance(TEST_BYTE_LIMIT); expect(cache1).toBe(cache2); expect(cache1).toBeInstanceOf(LruCache); }); }); describe('updateFile', () => { it('should add a new file to the cache', () => { const context = createFakeContext(); lruCache.updateFile(context); expect(lruCache.openFiles.size).toBe(1); expect(lruCache.openFiles.get(context.uri)).toEqual(context); }); it('should update an existing file in the cache', () => { const context1 = createFakeContext(); const context2 = { ...context1, text: 'Updated text' }; lruCache.updateFile(context1); lruCache.updateFile(context2); expect(lruCache.openFiles.size).toBe(1); expect(lruCache.openFiles.get(context1.uri)).toEqual(context2); }); }); describe('deleteFile', () => { it('should remove a file from the cache', () => { const context = createFakeContext(); lruCache.updateFile(context); const isDeleted = lruCache.deleteFile(context.uri); expect(lruCache.openFiles.size).toBe(0); expect(isDeleted).toBe(true); }); it(`should not remove a file that doesn't exist`, () => { const context = createFakeContext(); lruCache.updateFile(context); const isDeleted = lruCache.deleteFile('fake/uri/that/does/not.exist'); expect(lruCache.openFiles.size).toBe(1); expect(isDeleted).toBe(false); }); it('should return correct order of files after deletion', () => { const workspaceFolder = { uri: 'file:///workspace', name: 'test-workspace' }; const context1 = createFakeContext({ uri: 'file:///workspace/file1.ts', workspaceFolder }); const context2 = createFakeContext({ uri: 'file:///workspace/file2.ts', workspaceFolder }); const context3 = createFakeContext({ uri: 'file:///workspace/file3.ts', workspaceFolder }); lruCache.updateFile(context1); lruCache.updateFile(context2); lruCache.updateFile(context3); lruCache.deleteFile(context2.uri); expect(lruCache.mostRecentFiles({ context: context1 })).toEqual([context3, context1]); }); }); describe('mostRecentFiles', () => { it('should return ordered files', () => { const workspaceFolder = { uri: 'file:///workspace', name: 'test-workspace' }; const context1 = createFakeContext({ uri: 'file:///workspace/file1.ts', workspaceFolder }); const context2 = createFakeContext({ uri: 'file:///workspace/file2.ts', workspaceFolder }); const context3 = createFakeContext({ uri: 'file:///workspace/file3.ts', workspaceFolder }); lruCache.updateFile(context1); lruCache.updateFile(context2); lruCache.updateFile(context3); lruCache.updateFile(context2); const result = lruCache.mostRecentFiles({ context: context2 }); expect(result).toEqual([context2, context3, context1]); }); it('should return the most recently accessed files in the same workspace', () => { const workspaceFolder = { uri: 'file:///workspace', name: 'test-workspace' }; const otherWorkspaceFolder = { uri: 'file:///other', name: 'other-workspace' }; const context1 = createFakeContext({ uri: 'file:///workspace/file1.ts', workspaceFolder }); const context2 = createFakeContext({ uri: 'file:///workspace/file2.ts', workspaceFolder }); const context3 = createFakeContext({ uri: 'file:///workspace/file3.ts', workspaceFolder }); const context4 = createFakeContext({ uri: 'file:///other/file4.ts', workspaceFolder: otherWorkspaceFolder, }); lruCache.updateFile(context1); lruCache.updateFile(context2); lruCache.updateFile(context3); lruCache.updateFile(context4); const result = lruCache.mostRecentFiles({ context: context2 }); expect(result.find((file) => file.uri === context4.uri)).toBeUndefined(); }); it('should include the current file if includeCurrentFile is true', () => { const workspaceFolder = { uri: 'file:///workspace', name: 'test-workspace' }; const context1 = createFakeContext({ uri: 'file:///workspace/file1.ts', workspaceFolder }); const context2 = createFakeContext({ uri: 'file:///workspace/file2.ts', workspaceFolder }); lruCache.updateFile(context1); lruCache.updateFile(context2); const result = lruCache.mostRecentFiles({ context: context2, includeCurrentFile: true }); expect(result).toEqual([context2, context1]); }); it('should not include the current file if includeCurrentFile is false', () => { const workspaceFolder = { uri: 'file:///workspace', name: 'test-workspace' }; const context1 = createFakeContext({ uri: 'file:///workspace/file1.ts', workspaceFolder }); const context2 = createFakeContext({ uri: 'file:///workspace/file2.ts', workspaceFolder }); lruCache.updateFile(context1); lruCache.updateFile(context2); const result = lruCache.mostRecentFiles({ context: context2, includeCurrentFile: false }); expect(result).toEqual([context1]); }); it('should return an empty array if no files match the criteria', () => { const context = createFakeContext(); const result = lruCache.mostRecentFiles({ context }); expect(result).toEqual([]); }); }); describe('updateFile with size limit', () => { it('should evict least recently used items when limit is reached', () => { const context1 = createFakeContext({ uri: 'file:///workspace/file1.ts', prefix: smallString, // 200 bytes suffix: smallString, // 200 bytes }); const context2 = createFakeContext({ uri: 'file:///workspace/file2.ts', prefix: smallString, // 200 bytes suffix: smallString, // 200 bytes }); const context3 = createFakeContext({ uri: 'file:///workspace/file3.ts', prefix: largeString, // 400 bytes suffix: '', }); const context4 = createFakeContext({ uri: 'file:///workspace/file4.ts', prefix: extraSmallString, // 50 bytes suffix: extraSmallString, // 50 bytes }); expect(lruCache.updateFile(context1)).toBeTruthy(); expect(lruCache.updateFile(context2)).toBeTruthy(); expect(lruCache.updateFile(context3)).toBeTruthy(); expect(lruCache.updateFile(context4)).toBeTruthy(); // The least recently used item (context1) should have been evicted expect(lruCache.openFiles.size).toBe(3); expect(lruCache.openFiles.has(context1.uri)).toBe(false); expect(lruCache.openFiles.has(context2.uri)).toBe(true); expect(lruCache.openFiles.has(context3.uri)).toBe(true); expect(lruCache.openFiles.has(context4.uri)).toBe(true); }); }); }); References: - src/common/advanced_context/lru_cache.test.ts:123 - src/common/advanced_context/lru_cache.test.ts:84 - src/common/advanced_context/lru_cache.test.ts:106 - src/common/advanced_context/lru_cache.test.ts:139 - src/common/advanced_context/lru_cache.test.ts:140 - src/common/advanced_context/lru_cache.test.ts:124 - src/common/advanced_context/lru_cache.test.ts:71 - src/common/advanced_context/lru_cache.test.ts:62 - src/common/advanced_context/lru_cache.test.ts:105 - src/common/advanced_context/lru_cache.test.ts:183 - src/common/advanced_context/lru_cache.test.ts:193 - src/common/advanced_context/lru_cache.test.ts:171 - src/common/advanced_context/lru_cache.test.ts:94 - src/common/advanced_context/lru_cache.test.ts:142 - src/common/advanced_context/lru_cache.test.ts:159 - src/common/advanced_context/lru_cache.test.ts:172 - src/common/advanced_context/lru_cache.test.ts:208 - src/common/advanced_context/lru_cache.test.ts:107 - src/common/advanced_context/lru_cache.test.ts:198 - src/common/advanced_context/lru_cache.test.ts:141 - src/common/advanced_context/lru_cache.test.ts:158 - src/common/advanced_context/lru_cache.test.ts:122 - src/common/advanced_context/lru_cache.test.ts:203" You are a code assistant,Definition of 'FakeResponseOptions' in file src/common/test_utils/create_fake_response.ts in project gitlab-lsp,"Definition: interface FakeResponseOptions { status?: number; text?: string; json?: unknown; url?: string; headers?: Record; } export const createFakeResponse = ({ status = 200, text = '', json = {}, url = '', headers = {}, }: FakeResponseOptions): Response => { return createFakePartial({ 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/test_utils/create_fake_response.ts:17" You are a code assistant,Definition of 'SocketIoMessageBusProvider' in file packages/lib_webview_client/src/bus/provider/socket_io_message_bus_provider.ts in project gitlab-lsp,"Definition: export class SocketIoMessageBusProvider implements MessageBusProvider { readonly name = 'SocketIoMessageBusProvider'; getMessageBus(webviewId: string): MessageBus | null { if (!webviewId) { return null; } const socketUri = getSocketUri(webviewId); const socket = io(socketUri); const bus = new SocketIoMessageBus(socket); return bus; } } References: - packages/lib_webview_client/src/bus/provider/get_default_providers.ts:6" You are a code assistant,Definition of 'locateFile' in file src/browser/tree_sitter/index.ts in project gitlab-lsp,"Definition: 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:" You are a code assistant,Definition of 'info' in file src/common/log_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; } 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 'createFakeCable' in file packages/webview_duo_chat/src/plugin/port/test_utils/entities.ts in project gitlab-lsp,"Definition: export const createFakeCable = () => createFakePartial({ subscribe: jest.fn(), disconnect: jest.fn(), }); export const gitlabPlatformForAccount: GitLabPlatformForAccount = { type: 'account', account, project: undefined, fetchFromApi: createFakeFetchFromApi(), connectToCable: async () => createFakeCable(), getUserAgentHeader: () => ({}), }; References: - packages/webview_duo_chat/src/plugin/port/chat/gitlab_chat_api.test.ts:85 - packages/webview_duo_chat/src/plugin/port/test_utils/entities.ts:26" You are a code assistant,Definition of 'MINIMUM_PLATFORM_ORIGIN_FIELD_VERSION' in file packages/webview_duo_chat/src/plugin/port/chat/gitlab_chat_api.ts in project gitlab-lsp,"Definition: export const MINIMUM_PLATFORM_ORIGIN_FIELD_VERSION = '17.3.0'; export const CHAT_INPUT_TEMPLATE_17_2_AND_EARLIER = { query: gql` mutation chat( $question: String! $resourceId: AiModelID $currentFileContext: AiCurrentFileInput $clientSubscriptionId: String ) { aiAction( input: { chat: { resourceId: $resourceId, content: $question, currentFile: $currentFileContext } clientSubscriptionId: $clientSubscriptionId } ) { requestId errors } } `, defaultVariables: {}, }; export const CHAT_INPUT_TEMPLATE_17_3_AND_LATER = { query: gql` mutation chat( $question: String! $resourceId: AiModelID $currentFileContext: AiCurrentFileInput $clientSubscriptionId: String $platformOrigin: String! ) { aiAction( input: { chat: { resourceId: $resourceId, content: $question, currentFile: $currentFileContext } clientSubscriptionId: $clientSubscriptionId platformOrigin: $platformOrigin } ) { requestId errors } } `, defaultVariables: { platformOrigin: PLATFORM_ORIGIN, }, }; export type AiActionResponseType = { aiAction: { requestId: string; errors: string[] }; }; export const AI_MESSAGES_QUERY = gql` query getAiMessages($requestIds: [ID!], $roles: [AiMessageRole!]) { aiMessages(requestIds: $requestIds, roles: $roles) { nodes { requestId role content contentHtml timestamp errors extras { sources } } } } `; type AiMessageResponseType = { requestId: string; role: string; content: string; contentHtml: string; timestamp: string; errors: string[]; extras?: { sources: object[]; }; }; type AiMessagesResponseType = { aiMessages: { nodes: AiMessageResponseType[]; }; }; interface ErrorMessage { type: 'error'; requestId: string; role: 'system'; errors: string[]; } const errorResponse = (requestId: string, errors: string[]): ErrorMessage => ({ requestId, errors, role: 'system', type: 'error', }); interface SuccessMessage { type: 'message'; requestId: string; role: string; content: string; contentHtml: string; timestamp: string; errors: string[]; extras?: { sources: object[]; }; } const successResponse = (response: AiMessageResponseType): SuccessMessage => ({ type: 'message', ...response, }); type AiMessage = SuccessMessage | ErrorMessage; type ChatInputTemplate = { query: string; defaultVariables: { platformOrigin?: string; }; }; export class GitLabChatApi { #cachedActionQuery?: ChatInputTemplate = undefined; #manager: GitLabPlatformManagerForChat; constructor(manager: GitLabPlatformManagerForChat) { this.#manager = manager; } async processNewUserPrompt( question: string, subscriptionId?: string, currentFileContext?: GitLabChatFileContext, ): Promise { return this.#sendAiAction({ question, currentFileContext, clientSubscriptionId: subscriptionId, }); } async pullAiMessage(requestId: string, role: string): Promise { const response = await pullHandler(() => this.#getAiMessage(requestId, role)); if (!response) return errorResponse(requestId, ['Reached timeout while fetching response.']); return successResponse(response); } async cleanChat(): Promise { return this.#sendAiAction({ question: SPECIAL_MESSAGES.CLEAN }); } async #currentPlatform() { const platform = await this.#manager.getGitLabPlatform(); if (!platform) throw new Error('Platform is missing!'); return platform; } async #getAiMessage(requestId: string, role: string): Promise { const request: GraphQLRequest = { type: 'graphql', query: AI_MESSAGES_QUERY, variables: { requestIds: [requestId], roles: [role.toUpperCase()] }, }; const platform = await this.#currentPlatform(); const history = await platform.fetchFromApi(request); return history.aiMessages.nodes[0]; } async subscribeToUpdates( messageCallback: (message: AiCompletionResponseMessageType) => Promise, subscriptionId?: string, ) { const platform = await this.#currentPlatform(); const channel = new AiCompletionResponseChannel({ htmlResponse: true, userId: `gid://gitlab/User/${extractUserId(platform.account.id)}`, aiAction: 'CHAT', clientSubscriptionId: subscriptionId, }); const cable = await platform.connectToCable(); // we use this flag to fix https://gitlab.com/gitlab-org/gitlab-vscode-extension/-/issues/1397 // sometimes a chunk comes after the full message and it broke the chat let fullMessageReceived = false; channel.on('newChunk', async (msg) => { if (fullMessageReceived) { log.info(`CHAT-DEBUG: full message received, ignoring chunk`); return; } await messageCallback(msg); }); channel.on('fullMessage', async (message) => { fullMessageReceived = true; await messageCallback(message); if (subscriptionId) { cable.disconnect(); } }); cable.subscribe(channel); } async #sendAiAction(variables: object): Promise { const platform = await this.#currentPlatform(); const { query, defaultVariables } = await this.#actionQuery(); const projectGqlId = await this.#manager.getProjectGqlId(); const request: GraphQLRequest = { type: 'graphql', query, variables: { ...variables, ...defaultVariables, resourceId: projectGqlId ?? null, }, }; return platform.fetchFromApi(request); } async #actionQuery(): Promise { if (!this.#cachedActionQuery) { const platform = await this.#currentPlatform(); try { const { version } = await platform.fetchFromApi(versionRequest); this.#cachedActionQuery = ifVersionGte( version, MINIMUM_PLATFORM_ORIGIN_FIELD_VERSION, () => CHAT_INPUT_TEMPLATE_17_3_AND_LATER, () => CHAT_INPUT_TEMPLATE_17_2_AND_EARLIER, ); } catch (e) { log.debug(`GitLab version check for sending chat failed:`, e as Error); this.#cachedActionQuery = CHAT_INPUT_TEMPLATE_17_3_AND_LATER; } } return this.#cachedActionQuery; } } References:" You are a code assistant,Definition of 'FeatureStateNotificationParams' in file src/common/notifications.ts in project gitlab-lsp,"Definition: export type FeatureStateNotificationParams = FeatureState[]; export const FeatureStateChangeNotificationType = new NotificationType(FEATURE_STATE_CHANGE); export interface TokenCheckNotificationParams { message?: string; } export const TokenCheckNotificationType = new NotificationType( 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( '$/gitlab/didChangeDocumentInActiveEditor', ); References:" You are a code assistant,Definition of 'getActiveFileContext' in file packages/webview_duo_chat/src/plugin/port/chat/gitlab_chat_file_context.ts in project gitlab-lsp,"Definition: export const getActiveFileContext = (): GitLabChatFileContext | undefined => { const selectedText = getSelectedText(); const fileName = getActiveFileName(); if (!selectedText || !fileName) { return undefined; } return { selectedText, fileName, contentAboveCursor: getTextBeforeSelected(), contentBelowCursor: getTextAfterSelected(), }; }; References: - packages/webview_duo_chat/src/plugin/port/chat/gitlab_chat_record_context.ts:8 - packages/webview_duo_chat/src/plugin/port/chat/gitlab_chat_file_context.test.ts:23 - packages/webview_duo_chat/src/plugin/port/chat/gitlab_chat_file_context.test.ts:17 - packages/webview_duo_chat/src/plugin/port/chat/gitlab_chat_file_context.test.ts:30" You are a code assistant,Definition of 'DuoWorkflowEvents' in file packages/webview_duo_workflow/src/types.ts in project gitlab-lsp,"Definition: export type DuoWorkflowEvents = { nodes: LangGraphCheckpoint[]; }; export type DuoWorkflowEventConnectionType = { duoWorkflowEvents: DuoWorkflowEvents; }; References: - packages/webview_duo_workflow/src/types.ts:10 - src/common/graphql/workflow/types.ts:10" You are a code assistant,Definition of 'generateWorkflowID' in file src/common/graphql/workflow/service.ts in project gitlab-lsp,"Definition: 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 { const workflowId = this.generateWorkflowID(id); let timeout: NodeJS.Timeout; const poll = async (): Promise => { 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 { 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 'pullAiMessage' in file packages/webview_duo_chat/src/plugin/port/chat/gitlab_chat_api.ts in project gitlab-lsp,"Definition: async pullAiMessage(requestId: string, role: string): Promise { const response = await pullHandler(() => this.#getAiMessage(requestId, role)); if (!response) return errorResponse(requestId, ['Reached timeout while fetching response.']); return successResponse(response); } async cleanChat(): Promise { return this.#sendAiAction({ question: SPECIAL_MESSAGES.CLEAN }); } async #currentPlatform() { const platform = await this.#manager.getGitLabPlatform(); if (!platform) throw new Error('Platform is missing!'); return platform; } async #getAiMessage(requestId: string, role: string): Promise { const request: GraphQLRequest = { type: 'graphql', query: AI_MESSAGES_QUERY, variables: { requestIds: [requestId], roles: [role.toUpperCase()] }, }; const platform = await this.#currentPlatform(); const history = await platform.fetchFromApi(request); return history.aiMessages.nodes[0]; } async subscribeToUpdates( messageCallback: (message: AiCompletionResponseMessageType) => Promise, subscriptionId?: string, ) { const platform = await this.#currentPlatform(); const channel = new AiCompletionResponseChannel({ htmlResponse: true, userId: `gid://gitlab/User/${extractUserId(platform.account.id)}`, aiAction: 'CHAT', clientSubscriptionId: subscriptionId, }); const cable = await platform.connectToCable(); // we use this flag to fix https://gitlab.com/gitlab-org/gitlab-vscode-extension/-/issues/1397 // sometimes a chunk comes after the full message and it broke the chat let fullMessageReceived = false; channel.on('newChunk', async (msg) => { if (fullMessageReceived) { log.info(`CHAT-DEBUG: full message received, ignoring chunk`); return; } await messageCallback(msg); }); channel.on('fullMessage', async (message) => { fullMessageReceived = true; await messageCallback(message); if (subscriptionId) { cable.disconnect(); } }); cable.subscribe(channel); } async #sendAiAction(variables: object): Promise { const platform = await this.#currentPlatform(); const { query, defaultVariables } = await this.#actionQuery(); const projectGqlId = await this.#manager.getProjectGqlId(); const request: GraphQLRequest = { type: 'graphql', query, variables: { ...variables, ...defaultVariables, resourceId: projectGqlId ?? null, }, }; return platform.fetchFromApi(request); } async #actionQuery(): Promise { if (!this.#cachedActionQuery) { const platform = await this.#currentPlatform(); try { const { version } = await platform.fetchFromApi(versionRequest); this.#cachedActionQuery = ifVersionGte( version, MINIMUM_PLATFORM_ORIGIN_FIELD_VERSION, () => CHAT_INPUT_TEMPLATE_17_3_AND_LATER, () => CHAT_INPUT_TEMPLATE_17_2_AND_EARLIER, ); } catch (e) { log.debug(`GitLab version check for sending chat failed:`, e as Error); this.#cachedActionQuery = CHAT_INPUT_TEMPLATE_17_3_AND_LATER; } } return this.#cachedActionQuery; } } References:" You are a code assistant,Definition of 'postBuild' in file scripts/watcher/watch.ts in project gitlab-lsp,"Definition: function postBuild() { const editor = process.argv.find((arg) => arg.startsWith('--editor='))?.split('=')[1]; if (editor === 'vscode') { const vsCodePath = process.env.VSCODE_EXTENSION_RELATIVE_PATH ?? '../gitlab-vscode-extension'; return [postBuildVscCodeYalcPublish(vsCodePath), postBuildVSCodeCopyFiles(vsCodePath)]; } console.warn('No editor specified, skipping post-build steps'); return [new Promise((resolve) => resolve())]; } async function run() { const watchMsg = () => console.log(textColor, `Watching for file changes on ${dir}`); const now = performance.now(); const buildSuccessful = await runBuild(); if (!buildSuccessful) return watchMsg(); await Promise.all(postBuild()); console.log(successColor, `Finished in ${Math.round(performance.now() - now)}ms`); watchMsg(); } let timeout: NodeJS.Timeout | null = null; const dir = './src'; const watcher = chokidar.watch(dir, { ignored: /(^|[/\\])\../, // ignore dotfiles persistent: true, }); let isReady = false; watcher .on('add', async (filePath) => { if (!isReady) return; console.log(`File ${filePath} has been added`); await run(); }) .on('change', async (filePath) => { if (!isReady) return; console.log(`File ${filePath} has been changed`); if (timeout) clearTimeout(timeout); // We debounce the run function on change events in the case of many files being changed at once timeout = setTimeout(async () => { await run(); }, 1000); }) .on('ready', async () => { await run(); isReady = true; }) .on('unlink', (filePath) => console.log(`File ${filePath} has been removed`)); console.log(textColor, 'Starting watcher...'); References: - scripts/watcher/watch.ts:67" You are a code assistant,Definition of 'LanguageServerLanguageId' in file src/tests/unit/tree_sitter/test_utils.ts in project gitlab-lsp,"Definition: export type LanguageServerLanguageId = | (typeof BASE_SUPPORTED_CODE_SUGGESTIONS_LANGUAGES)[number] | 'yaml'; /** * Use this function to get the path of a fixture file. * Pulls from the `src/tests/fixtures` directory. */ export const getFixturePath = (category: Category, filePath: string) => resolve(cwd(), 'src', 'tests', 'fixtures', category, filePath); /** * Use this function to get the test file and tree for a given fixture file * to be used for Tree Sitter testing purposes. */ 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/test_utils.ts:35" You are a code assistant,Definition of 'parseGitLabRemote' in file src/common/services/git/git_remote_parser.ts in project gitlab-lsp,"Definition: export function parseGitLabRemote(remote: string, instanceUrl: string): GitLabRemote | undefined { const { host, pathname } = tryParseUrl(normalizeSshRemote(remote)) || {}; if (!host || !pathname) { return undefined; } // The instance url might have a custom route, i.e. www.company.com/gitlab. This route is // optional in the remote url. This regex extracts namespace and project from the remote // url while ignoring any custom route, if present. For more information see: // - https://gitlab.com/gitlab-org/gitlab-vscode-extension/-/merge_requests/11 // - https://gitlab.com/gitlab-org/gitlab-vscode-extension/-/issues/103 const pathRegExp = instanceUrl || instanceUrl.trim() !== '' ? escapeForRegExp(getInstancePath(instanceUrl)) : ''; const match = pathname.match(`(?:${pathRegExp})?/:?(.+)/([^/]+?)(?:.git)?/?$`); if (!match) { return undefined; } const [namespace, projectPath] = match.slice(1, 3); const namespaceWithPath = `${namespace}/${projectPath}`; return { host, namespace, projectPath, namespaceWithPath }; } References: - src/common/services/duo_access/project_access_cache.ts:191 - src/common/services/git/git_remote_parser.test.ts:121 - src/common/services/git/git_remote_parser.test.ts:104 - src/common/services/git/git_remote_parser.test.ts:90 - src/common/services/git/git_remote_parser.test.ts:79 - src/common/services/git/git_remote_parser.test.ts:117" You are a code assistant,Definition of 'getForActiveAccount' in file packages/webview_duo_chat/src/plugin/chat_platform_manager.ts in project gitlab-lsp,"Definition: async getForActiveAccount(): Promise { return new ChatPlatformForAccount(this.#client); } async getForAllAccounts(): Promise { return [new ChatPlatformForAccount(this.#client)]; } async getForSaaSAccount(): Promise { return new ChatPlatformForAccount(this.#client); } } References:" You are a code assistant,Definition of 'A' in file packages/lib_di/src/index.test.ts in project gitlab-lsp,"Definition: interface A { a(): string; } interface B { b(): string; } interface C { c(): string; } const A = createInterfaceId('A'); const B = createInterfaceId('B'); const C = createInterfaceId('C'); @Injectable(A, []) class AImpl implements A { a = () => 'a'; } @Injectable(B, [A]) class BImpl implements B { #a: A; constructor(a: A) { this.#a = a; } b = () => `B(${this.#a.a()})`; } @Injectable(C, [A, B]) class CImpl implements C { #a: A; #b: B; constructor(a: A, b: B) { this.#a = a; this.#b = b; } c = () => `C(${this.#b.b()}, ${this.#a.a()})`; } let container: Container; beforeEach(() => { container = new Container(); }); describe('addInstances', () => { const O = createInterfaceId('object'); it('fails if the instance is not branded', () => { expect(() => container.addInstances({ say: 'hello' } as BrandedInstance)).toThrow( /invoked without branded object/, ); }); it('fails if the instance is already present', () => { const a = brandInstance(O, { a: 'a' }); const b = brandInstance(O, { b: 'b' }); expect(() => container.addInstances(a, b)).toThrow(/this ID is already in the container/); }); it('adds instance', () => { const instance = { a: 'a' }; const a = brandInstance(O, instance); container.addInstances(a); expect(container.get(O)).toBe(instance); }); }); describe('instantiate', () => { it('can instantiate three classes A,B,C', () => { container.instantiate(AImpl, BImpl, CImpl); const cInstance = container.get(C); expect(cInstance.c()).toBe('C(B(a), a)'); }); it('instantiates dependencies in multiple instantiate calls', () => { container.instantiate(AImpl); // the order is important for this test // we want to make sure that the stack in circular dependency discovery is being cleared // to try why this order is necessary, remove the `inStack.delete()` from // the `if (!cwd && instanceIds.includes(id))` condition in prod code expect(() => container.instantiate(CImpl, BImpl)).not.toThrow(); }); it('detects duplicate ids', () => { @Injectable(A, []) 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: - packages/lib_di/src/index.test.ts:29 - packages/lib_di/src/index.test.ts:27 - packages/lib_di/src/index.test.ts:38 - packages/lib_di/src/index.test.ts:42" You are a code assistant,Definition of 'FilterFunction' in file packages/lib_webview/src/events/message_bus.ts in project gitlab-lsp,"Definition: type FilterFunction = (data: T) => boolean; interface Subscription { listener: Listener; filter?: FilterFunction; } export class MessageBus> implements Disposable { #subscriptions = new Map>>(); public subscribe( messageType: K, listener: Listener, filter?: FilterFunction, ): Disposable { const subscriptions = this.#subscriptions.get(messageType) ?? new Set>(); const subscription: Subscription = { listener: listener as Listener, filter: filter as FilterFunction | undefined, }; subscriptions.add(subscription); this.#subscriptions.set(messageType, subscriptions); return { dispose: () => { const targetSubscriptions = this.#subscriptions.get(messageType); if (targetSubscriptions) { targetSubscriptions.delete(subscription); if (targetSubscriptions.size === 0) { this.#subscriptions.delete(messageType); } } }, }; } public publish(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; if (!filter || filter(data)) { listener(data); } }); } } public hasListeners(messageType: K): boolean { return this.#subscriptions.has(messageType); } public listenerCount(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 'processStream' in file src/common/suggestion_client/post_processors/post_processor_pipeline.test.ts in project gitlab-lsp,"Definition: async processStream( _context: IDocContext, input: StreamingCompletionResponse, ): Promise { return input; } async processCompletion( _context: IDocContext, input: SuggestionOption[], ): Promise { return input.map((option) => ({ ...option, text: `${option.text} [2]` })); } } pipeline.addProcessor(new Processor1()); pipeline.addProcessor(new Processor2()); const completionInput: SuggestionOption[] = [{ text: 'option1', uniqueTrackingId: '1' }]; const result = await pipeline.run({ documentContext: mockContext, input: completionInput, type: 'completion', }); expect(result).toEqual([{ text: 'option1 [1] [2]', uniqueTrackingId: '1' }]); }); test('should throw an error for unexpected type', async () => { class TestProcessor extends PostProcessor { async processStream( _context: IDocContext, input: StreamingCompletionResponse, ): Promise { return input; } async processCompletion( _context: IDocContext, input: SuggestionOption[], ): Promise { 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 'register' in file packages/lib_handler_registry/src/registry/simple_registry.ts in project gitlab-lsp,"Definition: register(key: string, handler: THandler): Disposable { this.#handlers.set(key, handler); return { dispose: () => { this.#handlers.delete(key); }, }; } has(key: string) { return this.#handlers.has(key); } async handle(key: string, ...args: Parameters): Promise> { const handler = this.#handlers.get(key); if (!handler) { throw new HandlerNotFoundError(key); } try { const handlerResult = await handler(...args); return handlerResult as ReturnType; } catch (error) { throw new UnhandledHandlerError(key, resolveError(error)); } } dispose() { this.#handlers.clear(); } } function resolveError(e: unknown): Error { if (e instanceof Error) { return e; } if (typeof e === 'string') { return new Error(e); } return new Error('Unknown error'); } References:" You are a code assistant,Definition of 'WebviewPluginSetupParams' in file packages/lib_webview_plugin/src/webview_plugin.ts in project gitlab-lsp,"Definition: type WebviewPluginSetupParams = { webview: WebviewConnection<{ inbound: T['webviewToPlugin']; outbound: T['pluginToWebview']; }>; extension: MessageBus<{ inbound: T['extensionToPlugin']; outbound: T['pluginToExtension']; }>; }; /** * The `WebviewPluginSetupFunc` is responsible for setting up the communication between the webview plugin and the extension, as well as between the webview plugin and individual webview instances. * * @template TWebviewPluginMessageMap - Message types recognized by the plugin. * @param webviewMessageBus - The message bus for communication with individual webview instances. * @param extensionMessageBus - The message bus for communication with the webview host (extension). * @returns An optional function to dispose of resources when the plugin is unloaded. */ type WebviewPluginSetupFunc = ( context: WebviewPluginSetupParams, // eslint-disable-next-line @typescript-eslint/no-invalid-void-type ) => Disposable | void; /** * The `WebviewPlugin` is a user implemented type defining the integration of the webview plugin with a webview host (extension) and webview instances. * * @template TWebviewPluginMessageMap - Message types recognized by the plugin. */ export type WebviewPlugin< TWebviewPluginMessageMap extends PartialDeep = PluginMessageMap, > = { id: WebviewId; title: string; setup: WebviewPluginSetupFunc>; }; References:" You are a code assistant,Definition of 'emptyFunctionQueries' in file src/common/tree_sitter/empty_function/empty_function_queries.ts in project gitlab-lsp,"Definition: export const emptyFunctionQueries = { bash: bashEmptyFunctionQuery, c: cEmptyFunctionQuery, cpp: cppEmptyFunctionQuery, c_sharp: csharpEmptyFunctionQuery, css: '', go: goEmptyFunctionQuery, java: javaEmptyFunctionQuery, powershell: powershellEmptyFunctionQuery, python: pythonEmptyFunctionQuery, scala: scalaEmptyFunctionQuery, typescript: typescriptEmptyFunctionQuery, tsx: tsxEmptyFunctionQuery, javascript: javascriptEmptyFunctionQuery, kotlin: kotlinEmptyFunctionQuery, rust: rustEmptyFunctionQuery, ruby: rubyEmptyFunctionQuery, vue: vueEmptyFunctionQuery, // the following languages do not have functions, so queries are empty yaml: '', html: '', json: '', } satisfies Record; References:" You are a code assistant,Definition of 'greet3' in file src/tests/fixtures/intent/empty_function/python.py in project gitlab-lsp,"Definition: def greet3(name): class Greet4: def __init__(self, name): def greet(self): class Greet3: References: - src/tests/fixtures/intent/empty_function/ruby.rb:8" You are a code assistant,Definition of 'initialize' in file src/common/fetch.ts in project gitlab-lsp,"Definition: async initialize(): Promise {} async destroy(): Promise {} async fetch(input: RequestInfo | URL, init?: RequestInit): Promise { 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 { // Stub. Should delegate to the node or browser fetch implementations throw new Error('Not implemented'); yield ''; } async delete(input: RequestInfo | URL, init?: RequestInit): Promise { return this.fetch(input, this.updateRequestInit('DELETE', init)); } async get(input: RequestInfo | URL, init?: RequestInit): Promise { return this.fetch(input, this.updateRequestInit('GET', init)); } async post(input: RequestInfo | URL, init?: RequestInit): Promise { return this.fetch(input, this.updateRequestInit('POST', init)); } async put(input: RequestInfo | URL, init?: RequestInit): Promise { return this.fetch(input, this.updateRequestInit('PUT', init)); } async fetchBase(input: RequestInfo | URL, init?: RequestInit): Promise { // 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/tests/fixtures/intent/empty_function/ruby.rb:17 - src/tests/fixtures/intent/empty_function/ruby.rb:25" You are a code assistant,Definition of 'getLanguageNameForFile' in file src/common/tree_sitter/parser.ts in project gitlab-lsp,"Definition: getLanguageNameForFile(filename: string): TreeSitterLanguageName | undefined { return this.getLanguageInfoForFile(filename)?.name; } async getParser(languageInfo: TreeSitterLanguageInfo): Promise { 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 { return languages.reduce((map, language) => { for (const extension of language.extensions) { map.set(extension, language); } return map; }, new Map()); } } References:" You are a code assistant,Definition of 'dispose' in file src/common/workspace/workspace_service.ts in project gitlab-lsp,"Definition: dispose() { this.#disposable.dispose(); } } References:" You are a code assistant,Definition of 'TelemetryTracker' in file src/common/tracking/tracking_types.ts in project gitlab-lsp,"Definition: export interface TelemetryTracker { isEnabled(): boolean; setCodeSuggestionsContext( uniqueTrackingId: string, context: Partial, ): void; updateCodeSuggestionsContext( uniqueTrackingId: string, contextUpdate: Partial, ): void; rejectOpenedSuggestions(): void; updateSuggestionState(uniqueTrackingId: string, newState: TRACKING_EVENTS): void; } export const TelemetryTracker = createInterfaceId('TelemetryTracker'); References: - src/common/connection.ts:20 - src/common/message_handler.ts:34 - src/common/suggestion/suggestion_service.ts:77 - src/common/message_handler.ts:73 - src/common/suggestion/suggestion_service.ts:121 - src/common/suggestion/streaming_handler.ts:43" You are a code assistant,Definition of 'Account' in file packages/webview_duo_chat/src/plugin/port/platform/gitlab_account.ts in project gitlab-lsp,"Definition: 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: - packages/webview_duo_chat/src/plugin/port/test_utils/entities.ts:7 - packages/webview_duo_chat/src/plugin/chat_platform.ts:20 - packages/webview_duo_chat/src/plugin/port/platform/gitlab_platform.ts:13 - packages/webview_duo_chat/src/plugin/port/platform/gitlab_account.ts:23 - packages/webview_duo_chat/src/plugin/port/chat/get_platform_manager_for_chat.test.ts:29" You are a code assistant,Definition of 'constructor' in file src/common/git/ignore_manager.ts in project gitlab-lsp,"Definition: constructor(repoUri: string) { this.repoUri = repoUri; this.#ignoreTrie = new IgnoreTrie(); } async loadIgnoreFiles(files: string[]): Promise { 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 { 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 { 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 'postBuildVSCodeCopyFiles' in file scripts/watcher/watch.ts in project gitlab-lsp,"Definition: async function postBuildVSCodeCopyFiles(vsCodePath: string) { const desktopAssetsDir = `${vsCodePath}/dist-desktop/assets/language-server`; try { await copy(resolvePath(`${cwd()}/out`), desktopAssetsDir); console.log(successColor, 'Copied files to vscode extension'); } catch (error) { console.error(errorColor, 'Whoops, something went wrong...'); console.error(error); } } function postBuild() { const editor = process.argv.find((arg) => arg.startsWith('--editor='))?.split('=')[1]; if (editor === 'vscode') { const vsCodePath = process.env.VSCODE_EXTENSION_RELATIVE_PATH ?? '../gitlab-vscode-extension'; return [postBuildVscCodeYalcPublish(vsCodePath), postBuildVSCodeCopyFiles(vsCodePath)]; } console.warn('No editor specified, skipping post-build steps'); return [new Promise((resolve) => resolve())]; } async function run() { const watchMsg = () => console.log(textColor, `Watching for file changes on ${dir}`); const now = performance.now(); const buildSuccessful = await runBuild(); if (!buildSuccessful) return watchMsg(); await Promise.all(postBuild()); console.log(successColor, `Finished in ${Math.round(performance.now() - now)}ms`); watchMsg(); } let timeout: NodeJS.Timeout | null = null; const dir = './src'; const watcher = chokidar.watch(dir, { ignored: /(^|[/\\])\../, // ignore dotfiles persistent: true, }); let isReady = false; watcher .on('add', async (filePath) => { if (!isReady) return; console.log(`File ${filePath} has been added`); await run(); }) .on('change', async (filePath) => { if (!isReady) return; console.log(`File ${filePath} has been changed`); if (timeout) clearTimeout(timeout); // We debounce the run function on change events in the case of many files being changed at once timeout = setTimeout(async () => { await run(); }, 1000); }) .on('ready', async () => { await run(); isReady = true; }) .on('unlink', (filePath) => console.log(`File ${filePath} has been removed`)); console.log(textColor, 'Starting watcher...'); References: - scripts/watcher/watch.ts:55" You are a code assistant,Definition of 'ClientFeatureFlags' in file src/common/feature_flags.ts in project gitlab-lsp,"Definition: export enum ClientFeatureFlags { // Should match names found in https://gitlab.com/gitlab-org/gitlab-vscode-extension/-/blob/main/src/common/feature_flags/constants.ts StreamCodeGenerations = 'streamCodeGenerations', DuoWorkflow = 'duoWorkflow', RemoteSecurityScans = 'remoteSecurityScans', } export enum InstanceFeatureFlags { EditorAdvancedContext = 'advanced_context_resolver', CodeSuggestionsContext = 'code_suggestions_context', } export const INSTANCE_FEATURE_FLAG_QUERY = gql` query featureFlagsEnabled($name: String!) { featureFlagEnabled(name: $name) } `; export const FeatureFlagService = createInterfaceId('FeatureFlagService'); export interface FeatureFlagService { /** * Checks if a feature flag is enabled on the GitLab instance. * @see `IGitLabAPI` for how the instance is determined. * @requires `updateInstanceFeatureFlags` to be called first. */ isInstanceFlagEnabled(name: InstanceFeatureFlags): boolean; /** * Checks if a feature flag is enabled on the client. * @see `ConfigService` for client configuration. */ isClientFlagEnabled(name: ClientFeatureFlags): boolean; } @Injectable(FeatureFlagService, [GitLabApiClient, ConfigService]) export class DefaultFeatureFlagService { #api: GitLabApiClient; #configService: ConfigService; #featureFlags: Map = 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 { 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 { 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: - src/common/feature_flags.ts:115 - src/common/feature_flags.ts:38" You are a code assistant,Definition of 'fileExistsSync' in file src/tests/int/hasbin.ts in project gitlab-lsp,"Definition: export function fileExistsSync(filePath: string) { try { return statSync(filePath).isFile(); } catch (error) { return false; } } References:" You are a code assistant,Definition of 'normalizeSshRemote' in file src/common/services/git/git_remote_parser.ts in project gitlab-lsp,"Definition: function normalizeSshRemote(remote: string): string { // Regex to match git SSH remotes with custom port. // Example: [git@dev.company.com:7999]:group/repo_name.git // For more information see: // https://gitlab.com/gitlab-org/gitlab-vscode-extension/-/issues/309 const sshRemoteWithCustomPort = remote.match(`^\\[([a-zA-Z0-9_-]+@.*?):\\d+\\](.*)$`); if (sshRemoteWithCustomPort) { return `ssh://${sshRemoteWithCustomPort[1]}/${sshRemoteWithCustomPort[2]}`; } // Regex to match git SSH remotes with URL scheme and a custom port // Example: ssh://git@example.com:2222/fatihacet/gitlab-vscode-extension.git // For more information see: // https://gitlab.com/gitlab-org/gitlab-vscode-extension/-/issues/644 const sshRemoteWithSchemeAndCustomPort = remote.match(`^ssh://([a-zA-Z0-9_-]+@.*?):\\d+(.*)$`); if (sshRemoteWithSchemeAndCustomPort) { return `ssh://${sshRemoteWithSchemeAndCustomPort[1]}${sshRemoteWithSchemeAndCustomPort[2]}`; } // Regex to match git SSH remotes without URL scheme and no custom port // Example: git@example.com:2222/fatihacet/gitlab-vscode-extension.git // For more information see this comment: // https://gitlab.com/gitlab-org/gitlab-vscode-extension/-/issues/611#note_1154175809 const sshRemoteWithPath = remote.match(`([a-zA-Z0-9_-]+@.*?):(.*)`); if (sshRemoteWithPath) { return `ssh://${sshRemoteWithPath[1]}/${sshRemoteWithPath[2]}`; } if (remote.match(`^[a-zA-Z0-9_-]+@`)) { // Regex to match gitlab potential starting names for ssh remotes. return `ssh://${remote}`; } return remote; } export function parseGitLabRemote(remote: string, instanceUrl: string): GitLabRemote | undefined { const { host, pathname } = tryParseUrl(normalizeSshRemote(remote)) || {}; if (!host || !pathname) { return undefined; } // The instance url might have a custom route, i.e. www.company.com/gitlab. This route is // optional in the remote url. This regex extracts namespace and project from the remote // url while ignoring any custom route, if present. For more information see: // - https://gitlab.com/gitlab-org/gitlab-vscode-extension/-/merge_requests/11 // - https://gitlab.com/gitlab-org/gitlab-vscode-extension/-/issues/103 const pathRegExp = instanceUrl || instanceUrl.trim() !== '' ? escapeForRegExp(getInstancePath(instanceUrl)) : ''; const match = pathname.match(`(?:${pathRegExp})?/:?(.+)/([^/]+?)(?:.git)?/?$`); if (!match) { return undefined; } const [namespace, projectPath] = match.slice(1, 3); const namespaceWithPath = `${namespace}/${projectPath}`; return { host, namespace, projectPath, namespaceWithPath }; } References: - src/common/services/git/git_remote_parser.ts:73" You are a code assistant,Definition of 'TokenCheckNotificationParams' in file src/common/notifications.ts in project gitlab-lsp,"Definition: export interface TokenCheckNotificationParams { message?: string; } export const TokenCheckNotificationType = new NotificationType( 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( '$/gitlab/didChangeDocumentInActiveEditor', ); References:" You are a code assistant,Definition of 'isNonEmptyLine' in file src/common/suggestion/suggestions_cache.ts in project gitlab-lsp,"Definition: function isNonEmptyLine(s: string) { return s.trim().length > 0; } type Required = { [P in keyof T]-?: T[P]; }; const DEFAULT_CONFIG: Required = { enabled: true, maxSize: 1024 * 1024, ttl: 60 * 1000, prefixLines: 1, suffixLines: 1, }; export class SuggestionsCache { #cache: LRUCache; #configService: ConfigService; constructor(configService: ConfigService) { this.#configService = configService; const currentConfig = this.#getCurrentConfig(); this.#cache = new LRUCache({ 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 { 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 'ExtensionMessageHandlerKey' in file src/common/webview/extension/utils/extension_message_handler_registry.ts in project gitlab-lsp,"Definition: export type ExtensionMessageHandlerKey = { webviewId: WebviewId; type: string; }; export class ExtensionMessageHandlerRegistry extends HashedRegistry { constructor() { super((key) => `${key.webviewId}:${key.type}`); } } References:" You are a code assistant,Definition of 'warn' in file packages/lib_logging/src/types.ts in project gitlab-lsp,"Definition: 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 'get' in file src/common/document_transformer_service.ts in project gitlab-lsp,"Definition: get(uri: string): TextDocument | undefined; getContext( uri: string, position: Position, workspaceFolders: WorkspaceFolder[], completionContext?: InlineCompletionContext, ): IDocContext | undefined; transform(context: IDocContext): IDocContext; } export const DocumentTransformerService = createInterfaceId( 'DocumentTransformerService', ); @Injectable(DocumentTransformerService, [LsTextDocuments, SecretRedactor]) export class DefaultDocumentTransformerService implements DocumentTransformerService { #transformers: IDocTransformer[] = []; #documents: LsTextDocuments; 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: - src/common/utils/headers_to_snowplow_options.ts:20 - src/common/utils/headers_to_snowplow_options.ts:22 - src/common/utils/headers_to_snowplow_options.ts:21 - src/common/config_service.ts:134 - src/common/utils/headers_to_snowplow_options.ts:12" You are a code assistant,Definition of 'ContextResolution' in file src/common/advanced_context/context_resolvers/advanced_context_resolver.ts in project gitlab-lsp,"Definition: export type ContextResolution = { /** * The uri of the resolution */ uri: TextDocument['uri']; /** * The type of resolution, either a file or a snippet * `file` - indicates the content is a whole file * `snippet` - indicates the content is a snippet of a file */ type: 'file' | 'snippet'; /** * The content of the resolution */ content: string; /** * relative path of the file */ fileRelativePath: string; /** * resolution strategy */ strategy: 'open_tabs'; /** * workspace folder for the item */ workspaceFolder: WorkspaceFolder; }; /** * Resolves additional (or advanced) context for a given `IDocContext`. * Each resolution strategy will have its own resolver, eg. Open Files (LRU), * Symbols, EcmaScript Imports, etc */ export abstract class AdvancedContextResolver { abstract buildContext({ documentContext, }: { documentContext: IDocContext; }): AsyncGenerator; } References: - src/common/ai_context_management_2/providers/ai_file_context_provider.ts:77 - src/common/ai_context_management_2/providers/ai_file_context_provider.ts:100" You are a code assistant,Definition of 'Notifier' in file src/common/notifier.ts in project gitlab-lsp,"Definition: export interface Notifier { init(notify: NotifyFn): void; } References:" You are a code assistant,Definition of 'init' in file src/browser/tree_sitter/index.ts in project gitlab-lsp,"Definition: async init(): Promise { 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:" You are a code assistant,Definition of 'LruCache' in file src/common/advanced_context/lru_cache.ts in project gitlab-lsp,"Definition: export class LruCache { #cache: LRUCache; static #instance: LruCache | undefined; // eslint-disable-next-line no-restricted-syntax private constructor(maxSize: number) { this.#cache = new LRUCache({ maxSize, sizeCalculation: (value) => this.#getDocumentSize(value), }); } public static getInstance(maxSize: number): LruCache { if (!LruCache.#instance) { log.debug('LruCache: initializing'); LruCache.#instance = new LruCache(maxSize); } return LruCache.#instance; } public static destroyInstance(): void { LruCache.#instance = undefined; } get openFiles() { return this.#cache; } #getDocumentSize(context: IDocContext): number { const size = getByteSize(`${context.prefix}${context.suffix}`); return Math.max(1, size); } /** * Update the file in the cache. * Uses lru-cache under the hood. */ updateFile(context: IDocContext) { return this.#cache.set(context.uri, context); } /** * @returns `true` if the file was deleted, `false` if the file was not found */ deleteFile(uri: DocumentUri): boolean { return this.#cache.delete(uri); } /** * Get the most recently accessed files in the workspace * @param context - The current document context `IDocContext` * @param includeCurrentFile - Include the current file in the list of most recent files, default is `true` */ mostRecentFiles({ context, includeCurrentFile = true, }: { context?: IDocContext; includeCurrentFile?: boolean; }): IDocContext[] { const files = Array.from(this.#cache.values()); if (includeCurrentFile) { return files; } return files.filter( (file) => context?.workspaceFolder?.uri === file.workspaceFolder?.uri && file.uri !== context?.uri, ); } } References: - src/common/advanced_context/advanced_context_service.test.ts:16 - src/common/advanced_context/lru_cache.ts:29 - src/common/advanced_context/lru_cache.test.ts:40 - src/common/advanced_context/lru_cache.ts:26" You are a code assistant,Definition of 'ExtensionConnectionMessageBus' in file src/common/webview/extension/extension_connection_message_bus.ts in project gitlab-lsp,"Definition: export class ExtensionConnectionMessageBus implements MessageBus { #webviewId: WebviewId; #connection: Connection; #rpcMethods: RpcMethods; #handlers: Handlers; constructor({ webviewId, connection, rpcMethods, handlers }: ExtensionConnectionMessageBusProps) { this.#webviewId = webviewId; this.#connection = connection; this.#rpcMethods = rpcMethods; this.#handlers = handlers; } onRequest( type: T, handler: ( payload: TMessageMap['inbound']['requests'][T]['params'], ) => Promise>, ): Disposable { return this.#handlers.request.register({ webviewId: this.#webviewId, type }, handler); } onNotification( type: T, handler: (payload: TMessageMap['inbound']['notifications'][T]) => void, ): Disposable { return this.#handlers.notification.register({ webviewId: this.#webviewId, type }, handler); } sendRequest( type: T, payload?: TMessageMap['outbound']['requests'][T]['params'], ): Promise> { return this.#connection.sendRequest(this.#rpcMethods.request, { webviewId: this.#webviewId, type, payload, }); } async sendNotification( type: T, payload?: TMessageMap['outbound']['notifications'][T], ): Promise { await this.#connection.sendNotification(this.#rpcMethods.notification, { webviewId: this.#webviewId, type, payload, }); } } References: - src/common/webview/extension/extension_connection_message_bus_provider.ts:63 - src/common/webview/extension/extension_connection_message_bus.test.ts:17 - src/common/webview/extension/extension_connection_message_bus.test.ts:27" You are a code assistant,Definition of 'SocketResponseMessage' in file packages/lib_webview_transport_socket_io/src/utils/message_utils.ts in project gitlab-lsp,"Definition: 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 'WEBVIEW_TITLE' in file packages/webview_duo_chat/src/contract.ts in project gitlab-lsp,"Definition: export const WEBVIEW_TITLE = 'GitLab Duo Chat'; type Record = { id: string; }; export interface GitlabChatSlashCommand { name: string; description: string; shouldSubmit?: boolean; } export interface WebViewInitialStateInterface { slashCommands: GitlabChatSlashCommand[]; } export type Messages = CreatePluginMessageMap<{ pluginToWebview: { notifications: { newRecord: Record; updateRecord: Record; setLoadingState: boolean; cleanChat: undefined; }; }; webviewToPlugin: { notifications: { onReady: undefined; cleanChat: undefined; newPrompt: { record: { content: string; }; }; trackFeedback: { data?: { extendedTextFeedback: string | null; feedbackChoices: Array | null; }; }; }; }; pluginToExtension: { notifications: { showErrorMessage: { message: string; }; }; }; }>; References:" You are a code assistant,Definition of 'GitLabPlatformForAccount' in file packages/webview_duo_chat/src/plugin/port/platform/gitlab_platform.ts in project gitlab-lsp,"Definition: export interface GitLabPlatformForAccount extends GitLabPlatformBase { type: 'account'; project: undefined; } export interface GitLabPlatformForProject extends GitLabPlatformBase { type: 'project'; project: GitLabProject; } export type GitLabPlatform = GitLabPlatformForProject | GitLabPlatformForAccount; 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; /** * 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; /** * 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; getForAllAccounts(): Promise; /** * Returns GitLabPlatformForAccount if there is a SaaS account added. Otherwise returns undefined. */ getForSaaSAccount(): Promise; } References: - packages/webview_duo_chat/src/plugin/port/chat/get_platform_manager_for_chat.test.ts:29 - packages/webview_duo_chat/src/plugin/port/chat/api/get_chat_support.ts:16 - packages/webview_duo_chat/src/plugin/port/chat/get_platform_manager_for_chat.test.ts:34 - packages/webview_duo_chat/src/plugin/port/chat/get_platform_manager_for_chat.test.ts:38 - packages/webview_duo_chat/src/plugin/port/chat/get_platform_manager_for_chat.test.ts:70 - packages/webview_duo_chat/src/plugin/port/chat/get_platform_manager_for_chat.test.ts:134 - packages/webview_duo_chat/src/plugin/port/test_utils/entities.ts:21" You are a code assistant,Definition of 'WorkspaceService' in file src/common/workspace/workspace_service.ts in project gitlab-lsp,"Definition: type WorkspaceService = typeof DefaultWorkspaceService.prototype; export const WorkspaceService = createInterfaceId('WorkspaceService'); @Injectable(WorkspaceService, [VirtualFileSystemService]) export class DefaultWorkspaceService { #virtualFileSystemService: DefaultVirtualFileSystemService; #workspaceFilesMap = new Map(); #disposable: { dispose: () => void }; constructor(virtualFileSystemService: DefaultVirtualFileSystemService) { this.#virtualFileSystemService = virtualFileSystemService; this.#disposable = this.#setupEventListeners(); } #setupEventListeners() { return this.#virtualFileSystemService.onFileSystemEvent((eventType, data) => { switch (eventType) { case VirtualFileSystemEvents.WorkspaceFilesUpdate: this.#handleWorkspaceFilesUpdate(data as WorkspaceFilesUpdate); break; case VirtualFileSystemEvents.WorkspaceFileUpdate: this.#handleWorkspaceFileUpdate(data as WorkspaceFileUpdate); break; default: break; } }); } #handleWorkspaceFilesUpdate(update: WorkspaceFilesUpdate) { const files: FileSet = new Map(); for (const file of update.files) { files.set(file.toString(), file); } this.#workspaceFilesMap.set(update.workspaceFolder.uri, files); } #handleWorkspaceFileUpdate(update: WorkspaceFileUpdate) { let files = this.#workspaceFilesMap.get(update.workspaceFolder.uri); if (!files) { files = new Map(); this.#workspaceFilesMap.set(update.workspaceFolder.uri, files); } switch (update.event) { case 'add': case 'change': files.set(update.fileUri.toString(), update.fileUri); break; case 'unlink': files.delete(update.fileUri.toString()); break; default: break; } } getWorkspaceFiles(workspaceFolder: WorkspaceFolder): FileSet | undefined { return this.#workspaceFilesMap.get(workspaceFolder.uri); } dispose() { this.#disposable.dispose(); } } References:" You are a code assistant,Definition of 'HashFunc' in file packages/lib_handler_registry/src/registry/hashed_registry.ts in project gitlab-lsp,"Definition: export type HashFunc = (key: K) => string; export class HashedRegistry implements HandlerRegistry { #hashFunc: HashFunc; #basicRegistry: SimpleRegistry; constructor(hashFunc: HashFunc) { this.#hashFunc = hashFunc; this.#basicRegistry = new SimpleRegistry(); } 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): Promise> { const hash = this.#hashFunc(key); return this.#basicRegistry.handle(hash, ...args); } dispose() { this.#basicRegistry.dispose(); } } References:" You are a code assistant,Definition of 'fetchFromApi' in file src/common/api.ts in project gitlab-lsp,"Definition: async fetchFromApi(request: ApiRequest): Promise { if (!this.#token) { return Promise.reject(new Error('Token needs to be provided to authorise API request.')); } if ( request.supportedSinceInstanceVersion && !this.#instanceVersionHigherOrEqualThen(request.supportedSinceInstanceVersion.version) ) { return Promise.reject( new InvalidInstanceVersionError( `Can't ${request.supportedSinceInstanceVersion.resourceName} until your instance is upgraded to ${request.supportedSinceInstanceVersion.version} or higher.`, ), ); } if (request.type === 'graphql') { return this.#graphqlRequest(request.query, request.variables); } switch (request.method) { case 'GET': return this.#fetch(request.path, request.searchParams, 'resource', request.headers); case 'POST': return this.#postFetch(request.path, 'resource', request.body, request.headers); default: // the type assertion is necessary because TS doesn't expect any other types throw new Error(`Unknown request type ${(request as ApiRequest).type}`); } } async connectToCable(): Promise { const headers = this.#getDefaultHeaders(this.#token); const websocketOptions = { headers: { ...headers, Origin: this.#baseURL, }, }; return connectToCable(this.#baseURL, websocketOptions); } async #graphqlRequest( document: RequestDocument, variables?: V, ): Promise { const ensureEndsWithSlash = (url: string) => url.replace(/\/?$/, '/'); const endpoint = new URL('./api/graphql', ensureEndsWithSlash(this.#baseURL)).href; // supports GitLab instances that are on a custom path, e.g. ""https://example.com/gitlab"" const graphqlFetch = async ( input: RequestInfo | URL, init?: RequestInit, ): Promise => { const url = input instanceof URL ? input.toString() : input; return this.#lsFetch.post(url, { ...init, headers: { ...headers, ...init?.headers }, }); }; const headers = this.#getDefaultHeaders(this.#token); const client = new GraphQLClient(endpoint, { headers, fetch: graphqlFetch, }); return client.request(document, variables); } async #fetch( apiResourcePath: string, query: Record = {}, resourceName = 'resource', headers?: Record, ): Promise { const url = `${this.#baseURL}/api/v4${apiResourcePath}${createQueryString(query)}`; const result = await this.#lsFetch.get(url, { headers: { ...this.#getDefaultHeaders(this.#token), ...headers }, }); await handleFetchError(result, resourceName); return result.json() as Promise; } async #postFetch( apiResourcePath: string, resourceName = 'resource', body?: unknown, headers?: Record, ): Promise { const url = `${this.#baseURL}/api/v4${apiResourcePath}`; const response = await this.#lsFetch.post(url, { headers: { 'Content-Type': 'application/json', ...this.#getDefaultHeaders(this.#token), ...headers, }, body: JSON.stringify(body), }); await handleFetchError(response, resourceName); return response.json() as Promise; } #getDefaultHeaders(token?: string) { return { Authorization: `Bearer ${token}`, 'User-Agent': `code-completions-language-server-experiment (${this.#clientInfo?.name}:${this.#clientInfo?.version})`, 'X-Gitlab-Language-Server-Version': getLanguageServerVersion(), }; } #instanceVersionHigherOrEqualThen(version: string): boolean { if (!this.#instanceVersion) return false; return semverCompare(this.#instanceVersion, version) >= 0; } async #getGitLabInstanceVersion(): Promise { if (!this.#token) { return ''; } const headers = this.#getDefaultHeaders(this.#token); const response = await this.#lsFetch.get(`${this.#baseURL}/api/v4/version`, { headers, }); const { version } = await response.json(); return version; } get instanceVersion() { return this.#instanceVersion; } } References: - packages/webview_duo_chat/src/plugin/port/platform/gitlab_platform.ts:11 - packages/webview_duo_chat/src/plugin/port/test_utils/create_fake_fetch_from_api.ts:10" You are a code assistant,Definition of 'SuggestionClient' in file src/common/suggestion_client/suggestion_client.ts in project gitlab-lsp,"Definition: export interface SuggestionClient { getSuggestions(context: SuggestionContext): Promise; } export type SuggestionClientFn = SuggestionClient['getSuggestions']; export type SuggestionClientMiddleware = ( context: SuggestionContext, next: SuggestionClientFn, ) => ReturnType; References: - src/common/suggestion_client/client_to_middleware.ts:4" You are a code assistant,Definition of 'CustomInitializeParams' in file src/common/suggestion/suggestion_service.ts in project gitlab-lsp,"Definition: 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 => { 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 => { 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 => { 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 { 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 { 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 { 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 { 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 { 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/core/handlers/initialize_handler.ts:26 - src/common/core/handlers/initialize_handler.test.ts:8 - src/tests/int/lsp_client.ts:138 - src/common/test_utils/mocks.ts:27" You are a code assistant,Definition of 'setup' in file src/common/connection.ts in project gitlab-lsp,"Definition: export function setup( telemetryTracker: TelemetryTracker, connection: Connection, documentTransformerService: DocumentTransformerService, apiClient: GitLabApiClient, featureFlagService: FeatureFlagService, configService: ConfigService, { treeSitterParser, }: { treeSitterParser: TreeSitterParser; }, webviewMetadataProvider: WebviewMetadataProvider | undefined = undefined, workflowAPI: WorkflowAPI | undefined = undefined, duoProjectAccessChecker: DuoProjectAccessChecker, duoProjectAccessCache: DuoProjectAccessCache, virtualFileSystemService: VirtualFileSystemService, ) { const suggestionService = new DefaultSuggestionService({ telemetryTracker, connection, configService, api: apiClient, featureFlagService, treeSitterParser, documentTransformerService, duoProjectAccessChecker, }); const messageHandler = new MessageHandler({ telemetryTracker, connection, configService, featureFlagService, duoProjectAccessCache, virtualFileSystemService, workflowAPI, }); connection.onCompletion(suggestionService.completionHandler); // TODO: does Visual Studio or Neovim need this? VS Code doesn't connection.onCompletionResolve((item: CompletionItem) => item); connection.onRequest(InlineCompletionRequest.type, suggestionService.inlineCompletionHandler); connection.onDidChangeConfiguration(messageHandler.didChangeConfigurationHandler); connection.onNotification(TELEMETRY_NOTIFICATION, messageHandler.telemetryNotificationHandler); connection.onNotification( START_WORKFLOW_NOTIFICATION, messageHandler.startWorkflowNotificationHandler, ); connection.onRequest(GET_WEBVIEW_METADATA_REQUEST, () => { return webviewMetadataProvider?.getMetadata() ?? []; }); connection.onShutdown(messageHandler.onShutdownHandler); } References: - src/common/connection.test.ts:43 - src/browser/main.ts:122 - src/node/main.ts:197" You are a code assistant,Definition of 'greet' in file src/tests/fixtures/intent/go_comments.go in project gitlab-lsp,"Definition: func (g Greet) greet() { // function to greet the user } References: - src/tests/fixtures/intent/empty_function/ruby.rb:20 - 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" You are a code assistant,Definition of 'greet4' in file src/tests/fixtures/intent/empty_function/javascript.js in project gitlab-lsp,"Definition: 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:10" You are a code assistant,Definition of 'updateCodeSuggestionsContext' in file src/common/tracking/snowplow_tracker.ts in project gitlab-lsp,"Definition: public updateCodeSuggestionsContext( uniqueTrackingId: string, contextUpdate: Partial, ) { 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 'has' in file packages/lib_handler_registry/src/registry/hashed_registry.ts in project gitlab-lsp,"Definition: has(key: TKey): boolean { const hash = this.#hashFunc(key); return this.#basicRegistry.has(hash); } async handle(key: TKey, ...args: Parameters): Promise> { const hash = this.#hashFunc(key); return this.#basicRegistry.handle(hash, ...args); } dispose() { this.#basicRegistry.dispose(); } } References:" You are a code assistant,Definition of 'Greet3' in file src/tests/fixtures/intent/empty_function/javascript.js in project gitlab-lsp,"Definition: class Greet3 {} function* generateGreetings() {} function* greetGenerator() { yield 'Hello'; } References: - src/tests/fixtures/intent/empty_function/ruby.rb:34" You are a code assistant,Definition of 'AiCompletionResponseParams' in file packages/webview_duo_chat/src/plugin/port/api/graphql/ai_completion_response_channel.ts in project gitlab-lsp,"Definition: type AiCompletionResponseParams = { channel: 'GraphqlChannel'; query: string; variables: string; operationName: 'aiCompletionResponse'; }; const AI_MESSAGE_SUBSCRIPTION_QUERY = gql` subscription aiCompletionResponse( $userId: UserID $clientSubscriptionId: String $aiAction: AiAction $htmlResponse: Boolean = true ) { aiCompletionResponse( userId: $userId aiAction: $aiAction clientSubscriptionId: $clientSubscriptionId ) { id requestId content contentHtml @include(if: $htmlResponse) errors role timestamp type chunkId extras { sources } } } `; export type AiCompletionResponseMessageType = { requestId: string; role: string; content: string; contentHtml?: string; timestamp: string; errors: string[]; extras?: { sources: object[]; }; chunkId?: number; type?: string; }; type AiCompletionResponseResponseType = { result: { data: { aiCompletionResponse: AiCompletionResponseMessageType; }; }; more: boolean; }; interface AiCompletionResponseChannelEvents extends ChannelEvents { systemMessage: (msg: AiCompletionResponseMessageType) => void; newChunk: (msg: AiCompletionResponseMessageType) => void; fullMessage: (msg: AiCompletionResponseMessageType) => void; } export class AiCompletionResponseChannel extends Channel< AiCompletionResponseParams, AiCompletionResponseResponseType, AiCompletionResponseChannelEvents > { static identifier = 'GraphqlChannel'; constructor(params: AiCompletionResponseInput) { super({ channel: 'GraphqlChannel', operationName: 'aiCompletionResponse', query: AI_MESSAGE_SUBSCRIPTION_QUERY, variables: JSON.stringify(params), }); } receive(message: AiCompletionResponseResponseType) { if (!message.result.data.aiCompletionResponse) return; const data = message.result.data.aiCompletionResponse; if (data.role.toLowerCase() === 'system') { this.emit('systemMessage', data); } else if (data.chunkId) { this.emit('newChunk', data); } else { this.emit('fullMessage', data); } } } References:" You are a code assistant,Definition of 'broadcast' in file packages/lib_webview/src/setup/plugin/webview_controller.ts in project gitlab-lsp,"Definition: broadcast( type: TMethod, payload: T['outbound']['notifications'][TMethod], ) { for (const info of this.#instanceInfos.values()) { info.messageBus.sendNotification(type.toString(), payload); } } onInstanceConnected(handler: WebviewMessageBusManagerHandler) { this.#handlers.add(handler); for (const [instanceId, info] of this.#instanceInfos) { const disposable = handler(instanceId, info.messageBus); if (isDisposable(disposable)) { info.pluginCallbackDisposables.add(disposable); } } } dispose(): void { this.#compositeDisposable.dispose(); this.#instanceInfos.forEach((info) => info.messageBus.dispose()); this.#instanceInfos.clear(); } #subscribeToEvents(runtimeMessageBus: WebviewRuntimeMessageBus) { const eventFilter = buildWebviewIdFilter(this.webviewId); this.#compositeDisposable.add( runtimeMessageBus.subscribe('webview:connect', this.#handleConnected.bind(this), eventFilter), runtimeMessageBus.subscribe( 'webview:disconnect', this.#handleDisconnected.bind(this), eventFilter, ), ); } #handleConnected(address: WebviewAddress) { this.#logger.debug(`Instance connected: ${address.webviewInstanceId}`); if (this.#instanceInfos.has(address.webviewInstanceId)) { // we are already connected with this webview instance return; } const messageBus = this.#messageBusFactory(address); const pluginCallbackDisposables = new CompositeDisposable(); this.#instanceInfos.set(address.webviewInstanceId, { messageBus, pluginCallbackDisposables, }); this.#handlers.forEach((handler) => { const disposable = handler(address.webviewInstanceId, messageBus); if (isDisposable(disposable)) { pluginCallbackDisposables.add(disposable); } }); } #handleDisconnected(address: WebviewAddress) { this.#logger.debug(`Instance disconnected: ${address.webviewInstanceId}`); const instanceInfo = this.#instanceInfos.get(address.webviewInstanceId); if (!instanceInfo) { // we aren't tracking this instance return; } instanceInfo.pluginCallbackDisposables.dispose(); instanceInfo.messageBus.dispose(); this.#instanceInfos.delete(address.webviewInstanceId); } } References:" You are a code assistant,Definition of 'WebviewLocationService' in file src/common/webview/webview_resource_location_service.ts in project gitlab-lsp,"Definition: export class WebviewLocationService implements WebviewUriProviderRegistry { #uriProviders = new Set(); 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: - src/common/webview/webview_metadata_provider.ts:13 - src/common/webview/webview_resource_location_service.test.ts:20 - src/node/main.ts:176 - src/common/webview/webview_resource_location_service.test.ts:13 - src/common/webview/webview_metadata_provider.ts:15" You are a code assistant,Definition of 'RepositoryFile' in file src/common/git/repository.ts in project gitlab-lsp,"Definition: export type RepositoryFile = { uri: RepoFileUri; repositoryUri: RepositoryUri; isIgnored: boolean; workspaceFolder: WorkspaceFolder; }; export class Repository { workspaceFolder: WorkspaceFolder; uri: URI; configFileUri: URI; #files: Map; #ignoreManager: IgnoreManager; constructor({ configFileUri, workspaceFolder, uri, ignoreManager, }: { workspaceFolder: WorkspaceFolder; uri: RepositoryUri; configFileUri: URI; ignoreManager: IgnoreManager; }) { this.workspaceFolder = workspaceFolder; this.uri = uri; this.configFileUri = configFileUri; this.#files = new Map(); this.#ignoreManager = ignoreManager; } async addFilesAndLoadGitIgnore(files: URI[]): Promise { log.info(`Adding ${files.length} files to repository ${this.uri.toString()}`); await this.#ignoreManager.loadIgnoreFiles(files.map((uri) => uri.fsPath)); for (const file of files) { if (!this.#ignoreManager.isIgnored(file.fsPath)) { this.#files.set(file.toString(), { uri: file, isIgnored: false, repositoryUri: this.uri, workspaceFolder: this.workspaceFolder, }); } else { this.#files.set(file.toString(), { uri: file, isIgnored: true, repositoryUri: this.uri, workspaceFolder: this.workspaceFolder, }); } } } isFileIgnored(filePath: URI): boolean { return this.#ignoreManager.isIgnored(filePath.fsPath); } setFile(fileUri: URI): void { if (!this.isFileIgnored(fileUri)) { this.#files.set(fileUri.toString(), { uri: fileUri, isIgnored: false, repositoryUri: this.uri, workspaceFolder: this.workspaceFolder, }); } else { this.#files.set(fileUri.toString(), { uri: fileUri, isIgnored: true, repositoryUri: this.uri, workspaceFolder: this.workspaceFolder, }); } } getFile(fileUri: string): RepositoryFile | undefined { return this.#files.get(fileUri); } removeFile(fileUri: string): void { this.#files.delete(fileUri); } getFiles(): Map { return this.#files; } dispose(): void { this.#ignoreManager.dispose(); this.#files.clear(); } } References: - src/common/ai_context_management_2/providers/ai_file_context_provider.ts:111" You are a code assistant,Definition of 'IgnoreTrie' in file src/common/git/ignore_trie.ts in project gitlab-lsp,"Definition: export class IgnoreTrie { #children: Map; #ignoreInstance: Ignore | null; constructor() { this.#children = new Map(); this.#ignoreInstance = null; } addPattern(pathParts: string[], pattern: string): void { if (pathParts.length === 0) { if (!this.#ignoreInstance) { this.#ignoreInstance = ignore(); } this.#ignoreInstance.add(pattern); } else { const [current, ...rest] = pathParts; if (!this.#children.has(current)) { this.#children.set(current, new IgnoreTrie()); } const child = this.#children.get(current); if (!child) { return; } child.addPattern(rest, pattern); } } isIgnored(pathParts: string[]): boolean { if (pathParts.length === 0) { return false; } const [current, ...rest] = pathParts; if (this.#ignoreInstance && this.#ignoreInstance.ignores(path.join(...pathParts))) { return true; } const child = this.#children.get(current); if (child) { return child.isIgnored(rest); } return false; } 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: - src/common/git/ignore_trie.ts:23 - src/common/git/ignore_manager.ts:6 - src/common/git/ignore_manager.ts:12" You are a code assistant,Definition of 'GraphQLRequest' in file src/common/api_types.ts in project gitlab-lsp,"Definition: interface GraphQLRequest<_TReturnType> { type: 'graphql'; query: string; /** Options passed to the GraphQL query */ variables: Record; 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; supportedSinceInstanceVersion?: SupportedSinceInstanceVersion; } export type ApiRequest<_TReturnType> = | GetRequest<_TReturnType> | PostRequest<_TReturnType> | GraphQLRequest<_TReturnType>; export type AdditionalContext = { /** * The type of the context element. Options: `file` or `snippet`. */ type: 'file' | 'snippet'; /** * The name of the context element. A name of the file or a code snippet. */ name: string; /** * The content of the context element. The body of the file or a function. */ content: string; /** * Where the context was derived from */ resolution_strategy: ContextResolution['strategy']; }; // FIXME: Rename to SuggestionOptionText and then rename SuggestionOptionOrStream to SuggestionOption // this refactor can't be done now (2024-05-28) because all the conflicts it would cause with WIP export interface SuggestionOption { index?: number; text: string; uniqueTrackingId: string; lang?: string; } export interface TelemetryRequest { event: string; additional_properties: { unique_tracking_id: string; language?: string; suggestion_size?: number; timestamp: string; }; } References:" You are a code assistant,Definition of 'PostRequest' in file packages/webview_duo_chat/src/plugin/port/platform/web_ide.ts in project gitlab-lsp,"Definition: 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; } /** * 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; headers?: Record; } export interface GetRequest<_TReturnType> extends GetRequestBase<_TReturnType> { type: 'rest'; } export interface GetBufferRequest extends GetRequestBase { type: 'rest-buffer'; } export interface GraphQLRequest<_TReturnType> { type: 'graphql'; query: string; /** Options passed to the GraphQL query */ variables: Record; } 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; /* 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 'DuoProjectAccessCache' in file src/common/services/duo_access/project_access_cache.ts in project gitlab-lsp,"Definition: export interface DuoProjectAccessCache { getProjectsForWorkspaceFolder(workspaceFolder: WorkspaceFolder): DuoProject[]; updateCache({ baseUrl, workspaceFolders, }: { baseUrl: string; workspaceFolders: WorkspaceFolder[]; }): Promise; onDuoProjectCacheUpdate(listener: () => void): Disposable; } export const DuoProjectAccessCache = createInterfaceId('DuoProjectAccessCache'); @Injectable(DuoProjectAccessCache, [DirectoryWalker, FileResolver, GitLabApiClient]) export class DefaultDuoProjectAccessCache { #duoProjects: Map; #eventEmitter = new EventEmitter(); constructor( private readonly directoryWalker: DirectoryWalker, private readonly fileResolver: FileResolver, private readonly api: GitLabApiClient, ) { this.#duoProjects = new Map(); } getProjectsForWorkspaceFolder(workspaceFolder: WorkspaceFolder): DuoProject[] { return this.#duoProjects.get(workspaceFolder.uri) ?? []; } async updateCache({ baseUrl, workspaceFolders, }: { baseUrl: string; workspaceFolders: WorkspaceFolder[]; }) { try { this.#duoProjects.clear(); const duoProjects = await Promise.all( workspaceFolders.map(async (workspaceFolder) => { return { workspaceFolder, projects: await this.#duoProjectsForWorkspaceFolder({ workspaceFolder, baseUrl, }), }; }), ); for (const { workspaceFolder, projects } of duoProjects) { this.#logProjectsInfo(projects, workspaceFolder); this.#duoProjects.set(workspaceFolder.uri, projects); } this.#triggerChange(); } catch (err) { log.error('DuoProjectAccessCache: failed to update project access cache', err); } } #logProjectsInfo(projects: DuoProject[], workspaceFolder: WorkspaceFolder) { if (!projects.length) { log.warn( `DuoProjectAccessCache: no projects found for workspace folder ${workspaceFolder.uri}`, ); return; } log.debug( `DuoProjectAccessCache: found ${projects.length} projects for workspace folder ${workspaceFolder.uri}: ${JSON.stringify(projects, null, 2)}`, ); } async #duoProjectsForWorkspaceFolder({ workspaceFolder, baseUrl, }: { workspaceFolder: WorkspaceFolder; baseUrl: string; }): Promise { const remotes = await this.#gitlabRemotesForWorkspaceFolder(workspaceFolder, baseUrl); const projects = await Promise.all( remotes.map(async (remote) => { const enabled = await this.#checkDuoFeaturesEnabled(remote.namespaceWithPath); return { projectPath: remote.projectPath, uri: remote.fileUri, enabled, host: remote.host, namespace: remote.namespace, namespaceWithPath: remote.namespaceWithPath, } satisfies DuoProject; }), ); return projects; } async #gitlabRemotesForWorkspaceFolder( workspaceFolder: WorkspaceFolder, baseUrl: string, ): Promise { const paths = await this.directoryWalker.findFilesForDirectory({ directoryUri: workspaceFolder.uri, filters: { fileEndsWith: ['/.git/config'], }, }); const remotes = await Promise.all( paths.map(async (fileUri) => this.#gitlabRemotesForFileUri(fileUri.toString(), baseUrl)), ); return remotes.flat(); } async #gitlabRemotesForFileUri( fileUri: string, baseUrl: string, ): Promise { const remoteUrls = await this.#remoteUrlsFromGitConfig(fileUri); return remoteUrls.reduce((acc, remoteUrl) => { const remote = parseGitLabRemote(remoteUrl, baseUrl); if (remote) { acc.push({ ...remote, fileUri }); } return acc; }, []); } async #remoteUrlsFromGitConfig(fileUri: string): Promise { try { const fileString = await this.fileResolver.readFile({ fileUri }); const config = ini.parse(fileString); return this.#getRemoteUrls(config); } catch (error) { log.error(`DuoProjectAccessCache: Failed to read git config file: ${fileUri}`, error); return []; } } #getRemoteUrls(config: GitConfig): string[] { return Object.keys(config).reduce((acc, section) => { if (section.startsWith('remote ')) { acc.push(config[section].url); } return acc; }, []); } async #checkDuoFeaturesEnabled(projectPath: string): Promise { try { const response = await this.api.fetchFromApi<{ project: GqlProjectWithDuoEnabledInfo }>({ type: 'graphql', query: duoFeaturesEnabledQuery, variables: { projectPath, }, } satisfies ApiRequest<{ project: GqlProjectWithDuoEnabledInfo }>); return Boolean(response?.project?.duoFeaturesEnabled); } catch (error) { log.error( `DuoProjectAccessCache: Failed to check if Duo features are enabled for project: ${projectPath}`, error, ); return true; } } onDuoProjectCacheUpdate( listener: (duoProjectsCache: Map) => void, ): Disposable { this.#eventEmitter.on(DUO_PROJECT_CACHE_UPDATE_EVENT, listener); return { dispose: () => this.#eventEmitter.removeListener(DUO_PROJECT_CACHE_UPDATE_EVENT, listener), }; } #triggerChange() { this.#eventEmitter.emit(DUO_PROJECT_CACHE_UPDATE_EVENT, this.#duoProjects); } } References: - src/common/services/duo_access/project_access_checker.ts:20 - src/common/message_handler.ts:38 - src/common/connection.ts:34 - src/common/services/duo_access/project_access_checker.ts:22 - src/common/message_handler.ts:81 - src/common/services/duo_access/project_access_checker.test.ts:11 - src/common/feature_state/project_duo_acces_check.ts:44" You are a code assistant,Definition of 'getParser' in file src/common/tree_sitter/parser.ts in project gitlab-lsp,"Definition: async getParser(languageInfo: TreeSitterLanguageInfo): Promise { 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 { return languages.reduce((map, language) => { for (const extension of language.extensions) { map.set(extension, language); } return map; }, new Map()); } } References:" You are a code assistant,Definition of 'ConnectionService' in file src/common/connection_service.ts in project gitlab-lsp,"Definition: export const ConnectionService = createInterfaceId('ConnectionService'); const createNotifyFn = (c: LsConnection, method: NotificationType) => (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(method: NotificationType, notifier: Notifier) { 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 'COMMAND_FETCH_FROM_API' in file packages/webview_duo_chat/src/plugin/port/platform/web_ide.ts in project gitlab-lsp,"Definition: export const COMMAND_FETCH_FROM_API = `gitlab-web-ide.mediator.fetch-from-api`; export const COMMAND_FETCH_BUFFER_FROM_API = `gitlab-web-ide.mediator.fetch-buffer-from-api`; export const COMMAND_MEDIATOR_TOKEN = `gitlab-web-ide.mediator.mediator-token`; 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; } /** * 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; headers?: Record; } export interface GetRequest<_TReturnType> extends GetRequestBase<_TReturnType> { type: 'rest'; } export interface GetBufferRequest extends GetRequestBase { type: 'rest-buffer'; } export interface GraphQLRequest<_TReturnType> { type: 'graphql'; query: string; /** Options passed to the GraphQL query */ variables: Record; } 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; /* 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 'constructor' in file src/common/config_service.ts in project gitlab-lsp,"Definition: constructor() { this.#config = { client: { baseUrl: GITLAB_API_BASE_URL, codeCompletion: { enableSecretRedaction: true, }, telemetry: { enabled: true, }, logLevel: LOG_LEVEL.INFO, ignoreCertificateErrors: false, httpAgentOptions: {}, }, }; } get: TypedGetter = (key?: string) => { return key ? get(this.#config, key) : this.#config; }; set: TypedSetter = (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) { mergeWith(this.#config, newConfig, (target, src) => (isArray(target) ? src : undefined)); this.#triggerChange(); } } References:" You are a code assistant,Definition of 'LsRequestInit' in file src/node/fetch.ts in project gitlab-lsp,"Definition: export interface LsRequestInit extends RequestInit { agent: ProxyAgent | https.Agent | http.Agent; } interface LsAgentOptions { rejectUnauthorized: boolean; ca?: Buffer; cert?: Buffer; key?: Buffer; } /** * Wrap fetch to support proxy configurations */ @Injectable(LsFetch, []) export class Fetch extends FetchBase implements LsFetch { #proxy?: ProxyAgent; #userProxy?: string; #initialized: boolean = false; #httpsAgent: https.Agent; #agentOptions: Readonly; constructor(userProxy?: string) { super(); this.#agentOptions = { rejectUnauthorized: true, }; this.#userProxy = userProxy; this.#httpsAgent = this.#createHttpsAgent(); } async initialize(): Promise { // Set http_proxy and https_proxy environment variables // which will then get picked up by the ProxyAgent and // used. try { const proxy = await getProxySettings(); if (proxy?.http) { process.env.http_proxy = `${proxy.http.protocol}://${proxy.http.host}:${proxy.http.port}`; log.debug(`fetch: Detected http proxy through settings: ${process.env.http_proxy}`); } if (proxy?.https) { process.env.https_proxy = `${proxy.https.protocol}://${proxy.https.host}:${proxy.https.port}`; log.debug(`fetch: Detected https proxy through settings: ${process.env.https_proxy}`); } if (!proxy?.http && !proxy?.https) { log.debug(`fetch: Detected no proxy settings`); } } catch (err) { log.warn('Unable to load proxy settings', err); } if (this.#userProxy) { log.debug(`fetch: Detected user proxy ${this.#userProxy}`); process.env.http_proxy = this.#userProxy; process.env.https_proxy = this.#userProxy; } if (process.env.http_proxy || process.env.https_proxy) { log.info( `fetch: Setting proxy to https_proxy=${process.env.https_proxy}; http_proxy=${process.env.http_proxy}`, ); this.#proxy = this.#createProxyAgent(); } this.#initialized = true; } async destroy(): Promise { this.#proxy?.destroy(); } async fetch(input: RequestInfo | URL, init?: RequestInit): Promise { 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 { let buffer = ''; const decoder = new TextDecoder(); async function* readStream( stream: ReadableStream, ): AsyncGenerator { 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 { 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: '' } : {}), ...(cert ? { cert: '' } : {}), ...(key ? { key: '' } : {}), }; } } References: - src/node/fetch.ts:202" You are a code assistant,Definition of 'InitializeHandler' in file src/common/core/handlers/initialize_handler.ts in project gitlab-lsp,"Definition: export const InitializeHandler = createInterfaceId('InitializeHandler'); @Injectable(InitializeHandler, [ConfigService]) export class DefaultInitializeHandler implements InitializeHandler { #configService: ConfigService; constructor(configService: ConfigService) { this.#configService = configService; } requestHandler: RequestHandler = ( params: CustomInitializeParams, ): InitializeResult => { const { clientInfo, initializationOptions, workspaceFolders } = params; this.#configService.set('client.clientInfo', clientInfo); this.#configService.set('client.workspaceFolders', workspaceFolders); this.#configService.set('client.baseAssetsUrl', initializationOptions?.baseAssetsUrl); this.#configService.set('client.telemetry.ide', initializationOptions?.ide ?? clientInfo); this.#configService.set('client.telemetry.extension', initializationOptions?.extension); return { capabilities: { completionProvider: { resolveProvider: true, }, inlineCompletionProvider: true, textDocumentSync: TextDocumentSyncKind.Full, }, }; }; } References: - src/common/core/handlers/initialize_handler.test.ts:16 - src/common/connection_service.ts:62" You are a code assistant,Definition of 'getWorkflowEvents' in file packages/webview_duo_workflow/src/plugin/index.ts in project gitlab-lsp,"Definition: getWorkflowEvents(id: string): Promise; } export const workflowPluginFactory = ( graphqlApi: WorkflowGraphQLService, workflowApi: WorkflowAPI, connection: Connection, ): WebviewPlugin => { 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 'DefaultInitializeHandler' in file src/common/core/handlers/initialize_handler.ts in project gitlab-lsp,"Definition: export class DefaultInitializeHandler implements InitializeHandler { #configService: ConfigService; constructor(configService: ConfigService) { this.#configService = configService; } requestHandler: RequestHandler = ( params: CustomInitializeParams, ): InitializeResult => { const { clientInfo, initializationOptions, workspaceFolders } = params; this.#configService.set('client.clientInfo', clientInfo); this.#configService.set('client.workspaceFolders', workspaceFolders); this.#configService.set('client.baseAssetsUrl', initializationOptions?.baseAssetsUrl); this.#configService.set('client.telemetry.ide', initializationOptions?.ide ?? clientInfo); this.#configService.set('client.telemetry.extension', initializationOptions?.extension); return { capabilities: { completionProvider: { resolveProvider: true, }, inlineCompletionProvider: true, textDocumentSync: TextDocumentSyncKind.Full, }, }; }; } References: - src/common/core/handlers/initialize_handler.test.ts:22" You are a code assistant,Definition of 'constructor' in file src/common/message_handler.ts in project gitlab-lsp,"Definition: 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 => { 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:" You are a code assistant,Definition of 'DefaultStreamingHandler' in file src/common/suggestion/streaming_handler.ts in project gitlab-lsp,"Definition: export class DefaultStreamingHandler { #params: StartStreamParams; constructor(params: StartStreamParams) { this.#params = params; } async startStream() { return startStreaming(this.#params); } } const startStreaming = async ({ additionalContexts, api, circuitBreaker, connection, documentContext, parser, postProcessorPipeline, streamId, tracker, uniqueTrackingId, userInstruction, generationType, }: StartStreamParams) => { const language = parser.getLanguageNameForFile(documentContext.fileRelativePath); tracker.setCodeSuggestionsContext(uniqueTrackingId, { documentContext, additionalContexts, source: SuggestionSource.network, language, isStreaming: true, }); let streamShown = false; let suggestionProvided = false; let streamCancelledOrErrored = false; const cancellationTokenSource = new CancellationTokenSource(); const disposeStopStreaming = connection.onNotification(CancelStreaming, (stream) => { if (stream.id === streamId) { streamCancelledOrErrored = true; cancellationTokenSource.cancel(); if (streamShown) { tracker.updateSuggestionState(uniqueTrackingId, TRACKING_EVENTS.REJECTED); } else { tracker.updateSuggestionState(uniqueTrackingId, TRACKING_EVENTS.CANCELLED); } } }); const cancellationToken = cancellationTokenSource.token; const endStream = async () => { await connection.sendNotification(StreamingCompletionResponse, { id: streamId, done: true, }); if (!streamCancelledOrErrored) { tracker.updateSuggestionState(uniqueTrackingId, TRACKING_EVENTS.STREAM_COMPLETED); if (!suggestionProvided) { tracker.updateSuggestionState(uniqueTrackingId, TRACKING_EVENTS.NOT_PROVIDED); } } }; circuitBreaker.success(); const request: CodeSuggestionRequest = { prompt_version: 1, project_path: '', project_id: -1, current_file: { content_above_cursor: documentContext.prefix, content_below_cursor: documentContext.suffix, file_name: documentContext.fileRelativePath, }, intent: 'generation', stream: true, ...(additionalContexts?.length && { context: additionalContexts, }), ...(userInstruction && { user_instruction: userInstruction, }), generation_type: generationType, }; const trackStreamStarted = once(() => { tracker.updateSuggestionState(uniqueTrackingId, TRACKING_EVENTS.STREAM_STARTED); }); const trackStreamShown = once(() => { tracker.updateSuggestionState(uniqueTrackingId, TRACKING_EVENTS.SHOWN); streamShown = true; }); try { for await (const response of api.getStreamingCodeSuggestions(request)) { if (cancellationToken.isCancellationRequested) { break; } if (circuitBreaker.isOpen()) { break; } trackStreamStarted(); const processedCompletion = await postProcessorPipeline.run({ documentContext, input: { id: streamId, completion: response, done: false }, type: 'stream', }); await connection.sendNotification(StreamingCompletionResponse, processedCompletion); if (response.replace(/\s/g, '').length) { trackStreamShown(); suggestionProvided = true; } } } catch (err) { circuitBreaker.error(); if (isFetchError(err)) { tracker.updateCodeSuggestionsContext(uniqueTrackingId, { status: err.status }); } tracker.updateSuggestionState(uniqueTrackingId, TRACKING_EVENTS.ERRORED); streamCancelledOrErrored = true; log.error('Error streaming code suggestions.', err); } finally { await endStream(); disposeStopStreaming.dispose(); cancellationTokenSource.dispose(); } }; References: - src/common/suggestion/streaming_handler.test.ts:83 - src/common/suggestion/suggestion_service.ts:302" You are a code assistant,Definition of 'GitlabRemoteAndFileUri' in file src/common/services/duo_access/project_access_cache.ts in project gitlab-lsp,"Definition: type GitlabRemoteAndFileUri = GitLabRemote & { fileUri: string }; export interface GqlProjectWithDuoEnabledInfo { duoFeaturesEnabled: boolean; } export interface DuoProjectAccessCache { getProjectsForWorkspaceFolder(workspaceFolder: WorkspaceFolder): DuoProject[]; updateCache({ baseUrl, workspaceFolders, }: { baseUrl: string; workspaceFolders: WorkspaceFolder[]; }): Promise; onDuoProjectCacheUpdate(listener: () => void): Disposable; } export const DuoProjectAccessCache = createInterfaceId('DuoProjectAccessCache'); @Injectable(DuoProjectAccessCache, [DirectoryWalker, FileResolver, GitLabApiClient]) export class DefaultDuoProjectAccessCache { #duoProjects: Map; #eventEmitter = new EventEmitter(); constructor( private readonly directoryWalker: DirectoryWalker, private readonly fileResolver: FileResolver, private readonly api: GitLabApiClient, ) { this.#duoProjects = new Map(); } getProjectsForWorkspaceFolder(workspaceFolder: WorkspaceFolder): DuoProject[] { return this.#duoProjects.get(workspaceFolder.uri) ?? []; } async updateCache({ baseUrl, workspaceFolders, }: { baseUrl: string; workspaceFolders: WorkspaceFolder[]; }) { try { this.#duoProjects.clear(); const duoProjects = await Promise.all( workspaceFolders.map(async (workspaceFolder) => { return { workspaceFolder, projects: await this.#duoProjectsForWorkspaceFolder({ workspaceFolder, baseUrl, }), }; }), ); for (const { workspaceFolder, projects } of duoProjects) { this.#logProjectsInfo(projects, workspaceFolder); this.#duoProjects.set(workspaceFolder.uri, projects); } this.#triggerChange(); } catch (err) { log.error('DuoProjectAccessCache: failed to update project access cache', err); } } #logProjectsInfo(projects: DuoProject[], workspaceFolder: WorkspaceFolder) { if (!projects.length) { log.warn( `DuoProjectAccessCache: no projects found for workspace folder ${workspaceFolder.uri}`, ); return; } log.debug( `DuoProjectAccessCache: found ${projects.length} projects for workspace folder ${workspaceFolder.uri}: ${JSON.stringify(projects, null, 2)}`, ); } async #duoProjectsForWorkspaceFolder({ workspaceFolder, baseUrl, }: { workspaceFolder: WorkspaceFolder; baseUrl: string; }): Promise { const remotes = await this.#gitlabRemotesForWorkspaceFolder(workspaceFolder, baseUrl); const projects = await Promise.all( remotes.map(async (remote) => { const enabled = await this.#checkDuoFeaturesEnabled(remote.namespaceWithPath); return { projectPath: remote.projectPath, uri: remote.fileUri, enabled, host: remote.host, namespace: remote.namespace, namespaceWithPath: remote.namespaceWithPath, } satisfies DuoProject; }), ); return projects; } async #gitlabRemotesForWorkspaceFolder( workspaceFolder: WorkspaceFolder, baseUrl: string, ): Promise { const paths = await this.directoryWalker.findFilesForDirectory({ directoryUri: workspaceFolder.uri, filters: { fileEndsWith: ['/.git/config'], }, }); const remotes = await Promise.all( paths.map(async (fileUri) => this.#gitlabRemotesForFileUri(fileUri.toString(), baseUrl)), ); return remotes.flat(); } async #gitlabRemotesForFileUri( fileUri: string, baseUrl: string, ): Promise { const remoteUrls = await this.#remoteUrlsFromGitConfig(fileUri); return remoteUrls.reduce((acc, remoteUrl) => { const remote = parseGitLabRemote(remoteUrl, baseUrl); if (remote) { acc.push({ ...remote, fileUri }); } return acc; }, []); } async #remoteUrlsFromGitConfig(fileUri: string): Promise { try { const fileString = await this.fileResolver.readFile({ fileUri }); const config = ini.parse(fileString); return this.#getRemoteUrls(config); } catch (error) { log.error(`DuoProjectAccessCache: Failed to read git config file: ${fileUri}`, error); return []; } } #getRemoteUrls(config: GitConfig): string[] { return Object.keys(config).reduce((acc, section) => { if (section.startsWith('remote ')) { acc.push(config[section].url); } return acc; }, []); } async #checkDuoFeaturesEnabled(projectPath: string): Promise { try { const response = await this.api.fetchFromApi<{ project: GqlProjectWithDuoEnabledInfo }>({ type: 'graphql', query: duoFeaturesEnabledQuery, variables: { projectPath, }, } satisfies ApiRequest<{ project: GqlProjectWithDuoEnabledInfo }>); return Boolean(response?.project?.duoFeaturesEnabled); } catch (error) { log.error( `DuoProjectAccessCache: Failed to check if Duo features are enabled for project: ${projectPath}`, error, ); return true; } } onDuoProjectCacheUpdate( listener: (duoProjectsCache: Map) => void, ): Disposable { this.#eventEmitter.on(DUO_PROJECT_CACHE_UPDATE_EVENT, listener); return { dispose: () => this.#eventEmitter.removeListener(DUO_PROJECT_CACHE_UPDATE_EVENT, listener), }; } #triggerChange() { this.#eventEmitter.emit(DUO_PROJECT_CACHE_UPDATE_EVENT, this.#duoProjects); } } References:" You are a code assistant,Definition of 'GitLabPlatformForProject' in file packages/webview_duo_chat/src/plugin/port/platform/gitlab_platform.ts in project gitlab-lsp,"Definition: export interface GitLabPlatformForProject extends GitLabPlatformBase { type: 'project'; project: GitLabProject; } export type GitLabPlatform = GitLabPlatformForProject | GitLabPlatformForAccount; 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; /** * 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; /** * 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; getForAllAccounts(): Promise; /** * Returns GitLabPlatformForAccount if there is a SaaS account added. Otherwise returns undefined. */ getForSaaSAccount(): Promise; } References:" You are a code assistant,Definition of 'CustomInitializeParams' in file src/common/message_handler.ts in project gitlab-lsp,"Definition: 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 => { 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/test_utils/mocks.ts:27 - src/common/core/handlers/initialize_handler.ts:26 - src/common/core/handlers/initialize_handler.test.ts:8 - src/tests/int/lsp_client.ts:138" You are a code assistant,Definition of 'greet' in file src/tests/fixtures/intent/empty_function/go.go in project gitlab-lsp,"Definition: func greet(name string) { fmt.Println(name) } var greet = func(name string) { } var greet = func(name string) { fmt.Println(name) } type Greet struct{} type Greet struct { name string } // empty method declaration func (g Greet) greet() { } // non-empty method declaration func (g Greet) greet() { fmt.Printf(""Hello %s\n"", g.name) } References: - src/tests/fixtures/intent/empty_function/ruby.rb:20 - 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" You are a code assistant,Definition of 'ISecurityScannerOptions' in file src/common/config_service.ts in project gitlab-lsp,"Definition: export interface ISecurityScannerOptions { enabled?: boolean; serviceUrl?: string; } export interface IWorkflowSettings { dockerSocket?: string; } export interface IDuoConfig { enabledWithoutGitlabProject?: boolean; } export interface IClientConfig { /** GitLab API URL used for getting code suggestions */ baseUrl?: string; /** Full project path. */ projectPath?: string; /** PAT or OAuth token used to authenticate to GitLab API */ token?: string; /** The base URL for language server assets in the client-side extension */ baseAssetsUrl?: string; clientInfo?: IClientInfo; // FIXME: this key should be codeSuggestions (we have code completion and code generation) codeCompletion?: ICodeCompletionConfig; openTabsContext?: boolean; telemetry?: ITelemetryOptions; /** Config used for caching code suggestions */ suggestionsCache?: ISuggestionsCacheOptions; workspaceFolders?: WorkspaceFolder[] | null; /** Collection of Feature Flag values which are sent from the client */ featureFlags?: Record; logLevel?: LogLevel; ignoreCertificateErrors?: boolean; httpAgentOptions?: IHttpAgentOptions; snowplowTrackerOptions?: ISnowplowTrackerOptions; // TODO: move to `duo` duoWorkflowSettings?: IWorkflowSettings; securityScannerOptions?: ISecurityScannerOptions; duo?: IDuoConfig; } export interface IConfig { // TODO: we can possibly remove this extra level of config and move all IClientConfig properties to IConfig client: IClientConfig; } /** * ConfigService manages user configuration (e.g. baseUrl) and application state (e.g. codeCompletion.enabled) * TODO: Maybe in the future we would like to separate these two */ export interface ConfigService { get: TypedGetter; /** * set sets the property of the config * the new value completely overrides the old one */ set: TypedSetter; onConfigChange(listener: (config: IConfig) => void): Disposable; /** * merge adds `newConfig` properties into existing config, if the * property is present in both old and new config, `newConfig` * properties take precedence unless not defined * * This method performs deep merge * * **Arrays are not merged; they are replaced with the new value.** * */ merge(newConfig: Partial): void; } export const ConfigService = createInterfaceId('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 = (key?: string) => { return key ? get(this.#config, key) : this.#config; }; set: TypedSetter = (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) { mergeWith(this.#config, newConfig, (target, src) => (isArray(target) ? src : undefined)); this.#triggerChange(); } } References: - src/common/security_diagnostics_publisher.ts:35 - src/common/config_service.ts:74" You are a code assistant,Definition of 'GitlabChatSlashCommand' in file packages/webview_duo_chat/src/plugin/port/chat/gitlab_chat_slash_commands.ts in project gitlab-lsp,"Definition: export interface GitlabChatSlashCommand { name: string; description: string; shouldSubmit?: boolean; } const ResetCommand: GitlabChatSlashCommand = { name: '/reset', description: 'Reset conversation and ignore the previous messages.', shouldSubmit: true, }; const CleanCommand: GitlabChatSlashCommand = { name: '/clear', description: 'Delete all messages in this conversation.', }; const TestsCommand: GitlabChatSlashCommand = { name: '/tests', description: 'Write tests for the selected snippet.', }; const RefactorCommand: GitlabChatSlashCommand = { name: '/refactor', description: 'Refactor the selected snippet.', }; const ExplainCommand: GitlabChatSlashCommand = { name: '/explain', description: 'Explain the selected snippet.', }; export const defaultSlashCommands: GitlabChatSlashCommand[] = [ ResetCommand, CleanCommand, TestsCommand, RefactorCommand, ExplainCommand, ]; References: - packages/webview_duo_chat/src/plugin/port/chat/gitlab_chat_slash_commands.ts:23 - packages/webview_duo_chat/src/plugin/port/chat/gitlab_chat_slash_commands.ts:13 - packages/webview_duo_chat/src/plugin/port/chat/gitlab_chat_slash_commands.ts:28 - packages/webview_duo_chat/src/plugin/port/chat/gitlab_chat_slash_commands.ts:7 - packages/webview_duo_chat/src/plugin/port/chat/gitlab_chat_slash_commands.ts:18" You are a code assistant,Definition of 'updateSuggestionState' in file src/common/tracking/tracking_types.ts in project gitlab-lsp,"Definition: updateSuggestionState(uniqueTrackingId: string, newState: TRACKING_EVENTS): void; } export const TelemetryTracker = createInterfaceId('TelemetryTracker'); References:" You are a code assistant,Definition of 'initialize' in file src/common/fetch.ts in project gitlab-lsp,"Definition: initialize(): Promise; destroy(): Promise; fetch(input: RequestInfo | URL, init?: RequestInit): Promise; fetchBase(input: RequestInfo | URL, init?: RequestInit): Promise; delete(input: RequestInfo | URL, init?: RequestInit): Promise; get(input: RequestInfo | URL, init?: RequestInit): Promise; post(input: RequestInfo | URL, init?: RequestInit): Promise; put(input: RequestInfo | URL, init?: RequestInit): Promise; updateAgentOptions(options: FetchAgentOptions): void; streamFetch(url: string, body: string, headers: FetchHeaders): AsyncGenerator; } export const LsFetch = createInterfaceId('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 {} async destroy(): Promise {} async fetch(input: RequestInfo | URL, init?: RequestInit): Promise { 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 { // Stub. Should delegate to the node or browser fetch implementations throw new Error('Not implemented'); yield ''; } async delete(input: RequestInfo | URL, init?: RequestInit): Promise { return this.fetch(input, this.updateRequestInit('DELETE', init)); } async get(input: RequestInfo | URL, init?: RequestInit): Promise { return this.fetch(input, this.updateRequestInit('GET', init)); } async post(input: RequestInfo | URL, init?: RequestInit): Promise { return this.fetch(input, this.updateRequestInit('POST', init)); } async put(input: RequestInfo | URL, init?: RequestInit): Promise { return this.fetch(input, this.updateRequestInit('PUT', init)); } async fetchBase(input: RequestInfo | URL, init?: RequestInit): Promise { // 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/tests/fixtures/intent/empty_function/ruby.rb:25 - src/tests/fixtures/intent/empty_function/ruby.rb:17" You are a code assistant,Definition of 'isIgnored' in file src/common/git/ignore_manager.ts in project gitlab-lsp,"Definition: 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/core/handlers/initialize_handler.ts in project gitlab-lsp,"Definition: constructor(configService: ConfigService) { this.#configService = configService; } requestHandler: RequestHandler = ( params: CustomInitializeParams, ): InitializeResult => { const { clientInfo, initializationOptions, workspaceFolders } = params; this.#configService.set('client.clientInfo', clientInfo); this.#configService.set('client.workspaceFolders', workspaceFolders); this.#configService.set('client.baseAssetsUrl', initializationOptions?.baseAssetsUrl); this.#configService.set('client.telemetry.ide', initializationOptions?.ide ?? clientInfo); this.#configService.set('client.telemetry.extension', initializationOptions?.extension); return { capabilities: { completionProvider: { resolveProvider: true, }, inlineCompletionProvider: true, textDocumentSync: TextDocumentSyncKind.Full, }, }; }; } References:" You are a code assistant,Definition of 'dispose' in file packages/lib_webview_transport_json_rpc/src/json_rpc_connection_transport.ts in project gitlab-lsp,"Definition: dispose(): void { this.#messageEmitter.removeAllListeners(); this.#disposables.forEach((disposable) => disposable.dispose()); this.#logger?.debug('JsonRpcConnectionTransport disposed'); } } References:" You are a code assistant,Definition of 'createMockFastifyRequest' in file src/node/webview/test-utils/mock_fastify_request.ts in project gitlab-lsp,"Definition: export function createMockFastifyRequest( params?: Partial, ): FastifyRequest { // eslint-disable-next-line no-param-reassign params ??= {}; return { url: params.url ?? '', params: params.params ?? {}, } as FastifyRequest; } References: - src/node/webview/handlers/webview_handler.test.ts:21 - src/node/webview/handlers/webview_handler.test.ts:49 - src/node/webview/handlers/build_webview_metadata_request_handler.test.ts:13 - src/node/webview/handlers/webview_handler.test.ts:34" You are a code assistant,Definition of 'FeatureFlagService' in file src/common/feature_flags.ts in project gitlab-lsp,"Definition: export const FeatureFlagService = createInterfaceId('FeatureFlagService'); export interface FeatureFlagService { /** * Checks if a feature flag is enabled on the GitLab instance. * @see `IGitLabAPI` for how the instance is determined. * @requires `updateInstanceFeatureFlags` to be called first. */ isInstanceFlagEnabled(name: InstanceFeatureFlags): boolean; /** * Checks if a feature flag is enabled on the client. * @see `ConfigService` for client configuration. */ isClientFlagEnabled(name: ClientFeatureFlags): boolean; } @Injectable(FeatureFlagService, [GitLabApiClient, ConfigService]) export class DefaultFeatureFlagService { #api: GitLabApiClient; #configService: ConfigService; #featureFlags: Map = 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 { 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 { 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: - src/common/suggestion/suggestion_service.ts:83 - src/common/tracking/snowplow_tracker.ts:152 - src/common/connection.ts:24 - src/common/message_handler.ts:37 - src/common/security_diagnostics_publisher.ts:40 - src/common/suggestion/suggestion_service.ts:137 - src/common/advanced_context/helpers.ts:21 - src/common/security_diagnostics_publisher.ts:37 - src/common/message_handler.ts:83 - src/common/feature_flags.test.ts:13 - src/common/security_diagnostics_publisher.test.ts:19 - src/common/tracking/snowplow_tracker.ts:161 - src/common/tracking/snowplow_tracker.test.ts:76" You are a code assistant,Definition of 'AiMessage' in file packages/webview_duo_chat/src/plugin/port/chat/gitlab_chat_api.ts in project gitlab-lsp,"Definition: type AiMessage = SuccessMessage | ErrorMessage; type ChatInputTemplate = { query: string; defaultVariables: { platformOrigin?: string; }; }; export class GitLabChatApi { #cachedActionQuery?: ChatInputTemplate = undefined; #manager: GitLabPlatformManagerForChat; constructor(manager: GitLabPlatformManagerForChat) { this.#manager = manager; } async processNewUserPrompt( question: string, subscriptionId?: string, currentFileContext?: GitLabChatFileContext, ): Promise { return this.#sendAiAction({ question, currentFileContext, clientSubscriptionId: subscriptionId, }); } async pullAiMessage(requestId: string, role: string): Promise { const response = await pullHandler(() => this.#getAiMessage(requestId, role)); if (!response) return errorResponse(requestId, ['Reached timeout while fetching response.']); return successResponse(response); } async cleanChat(): Promise { return this.#sendAiAction({ question: SPECIAL_MESSAGES.CLEAN }); } async #currentPlatform() { const platform = await this.#manager.getGitLabPlatform(); if (!platform) throw new Error('Platform is missing!'); return platform; } async #getAiMessage(requestId: string, role: string): Promise { const request: GraphQLRequest = { type: 'graphql', query: AI_MESSAGES_QUERY, variables: { requestIds: [requestId], roles: [role.toUpperCase()] }, }; const platform = await this.#currentPlatform(); const history = await platform.fetchFromApi(request); return history.aiMessages.nodes[0]; } async subscribeToUpdates( messageCallback: (message: AiCompletionResponseMessageType) => Promise, subscriptionId?: string, ) { const platform = await this.#currentPlatform(); const channel = new AiCompletionResponseChannel({ htmlResponse: true, userId: `gid://gitlab/User/${extractUserId(platform.account.id)}`, aiAction: 'CHAT', clientSubscriptionId: subscriptionId, }); const cable = await platform.connectToCable(); // we use this flag to fix https://gitlab.com/gitlab-org/gitlab-vscode-extension/-/issues/1397 // sometimes a chunk comes after the full message and it broke the chat let fullMessageReceived = false; channel.on('newChunk', async (msg) => { if (fullMessageReceived) { log.info(`CHAT-DEBUG: full message received, ignoring chunk`); return; } await messageCallback(msg); }); channel.on('fullMessage', async (message) => { fullMessageReceived = true; await messageCallback(message); if (subscriptionId) { cable.disconnect(); } }); cable.subscribe(channel); } async #sendAiAction(variables: object): Promise { const platform = await this.#currentPlatform(); const { query, defaultVariables } = await this.#actionQuery(); const projectGqlId = await this.#manager.getProjectGqlId(); const request: GraphQLRequest = { type: 'graphql', query, variables: { ...variables, ...defaultVariables, resourceId: projectGqlId ?? null, }, }; return platform.fetchFromApi(request); } async #actionQuery(): Promise { if (!this.#cachedActionQuery) { const platform = await this.#currentPlatform(); try { const { version } = await platform.fetchFromApi(versionRequest); this.#cachedActionQuery = ifVersionGte( version, MINIMUM_PLATFORM_ORIGIN_FIELD_VERSION, () => CHAT_INPUT_TEMPLATE_17_3_AND_LATER, () => CHAT_INPUT_TEMPLATE_17_2_AND_EARLIER, ); } catch (e) { log.debug(`GitLab version check for sending chat failed:`, e as Error); this.#cachedActionQuery = CHAT_INPUT_TEMPLATE_17_3_AND_LATER; } } return this.#cachedActionQuery; } } References:" You are a code assistant,Definition of 'sendTextDocumentDidClose' in file src/tests/int/lsp_client.ts in project gitlab-lsp,"Definition: public async sendTextDocumentDidClose(uri: string): Promise { const params = { textDocument: { uri, }, }; const request = new NotificationType('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 { const params = { textDocument: { uri, version, }, contentChanges: [{ text }], }; const request = new NotificationType('textDocument/didChange'); await this.#connection.sendNotification(request, params); } public async sendTextDocumentCompletion( uri: string, line: number, character: number, ): Promise { 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 { await this.#connection.sendNotification(DidChangeDocumentInActiveEditor, uri); } public async getWebviewMetadata(): Promise { const result = await this.#connection.sendRequest( '$/gitlab/webview-metadata', ); return result; } } References:" You are a code assistant,Definition of 'WebviewInstanceCreatedEventData' in file packages/lib_webview_transport/src/types.ts in project gitlab-lsp,"Definition: export type WebviewInstanceCreatedEventData = WebviewAddress; export type WebviewInstanceDestroyedEventData = WebviewAddress; export type WebviewInstanceNotificationEventData = WebviewAddress & WebviewEventInfo; export type WebviewInstanceRequestEventData = WebviewAddress & WebviewEventInfo & WebviewRequestInfo; export type SuccessfulResponse = { success: true; }; export type FailedResponse = { success: false; reason: string; }; export type WebviewInstanceResponseEventData = WebviewAddress & WebviewRequestInfo & WebviewEventInfo & (SuccessfulResponse | FailedResponse); export type MessagesToServer = { webview_instance_created: WebviewInstanceCreatedEventData; webview_instance_destroyed: WebviewInstanceDestroyedEventData; webview_instance_notification_received: WebviewInstanceNotificationEventData; webview_instance_request_received: WebviewInstanceRequestEventData; webview_instance_response_received: WebviewInstanceResponseEventData; }; export type MessagesToClient = { webview_instance_notification: WebviewInstanceNotificationEventData; webview_instance_request: WebviewInstanceRequestEventData; webview_instance_response: WebviewInstanceResponseEventData; }; export interface TransportMessageHandler { (payload: T): void; } export interface TransportListener { on( type: K, callback: TransportMessageHandler, ): Disposable; } export interface TransportPublisher { publish(type: K, payload: MessagesToClient[K]): Promise; } export interface Transport extends TransportListener, TransportPublisher {} References: - packages/lib_webview_transport/src/types.ts:40" You are a code assistant,Definition of 'ReadFile' in file src/common/services/fs/file.ts in project gitlab-lsp,"Definition: export interface ReadFile { fileUri: string; } export interface FileResolver { readFile(_args: ReadFile): Promise; } export const FileResolver = createInterfaceId('FileResolver'); @Injectable(FileResolver, []) export class EmptyFileResolver { // eslint-disable-next-line @typescript-eslint/no-unused-vars readFile(_args: ReadFile): Promise { return Promise.resolve(''); } } References: - src/common/services/fs/file.ts:16 - src/node/services/fs/file.ts:8 - src/common/services/fs/file.ts:8" You are a code assistant,Definition of 'SuggestionCacheEntry' in file src/common/suggestion/suggestions_cache.ts in project gitlab-lsp,"Definition: export type SuggestionCacheEntry = { character: number; suggestions: SuggestionOption[]; additionalContexts?: AdditionalContext[]; currentLine: string; timesRetrievedByPosition: TimesRetrievedByPosition; }; export type SuggestionCacheContext = { document: TextDocumentIdentifier; context: IDocContext; position: Position; additionalContexts?: AdditionalContext[]; }; export type SuggestionCache = { options: SuggestionOption[]; additionalContexts?: AdditionalContext[]; }; function isNonEmptyLine(s: string) { return s.trim().length > 0; } type Required = { [P in keyof T]-?: T[P]; }; const DEFAULT_CONFIG: Required = { enabled: true, maxSize: 1024 * 1024, ttl: 60 * 1000, prefixLines: 1, suffixLines: 1, }; export class SuggestionsCache { #cache: LRUCache; #configService: ConfigService; constructor(configService: ConfigService) { this.#configService = configService; const currentConfig = this.#getCurrentConfig(); this.#cache = new LRUCache({ 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 { 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 'warn' in file packages/lib_logging/src/null_logger.ts in project gitlab-lsp,"Definition: warn(): void { // NOOP } error(e: Error): void; error(message: string, e?: Error | undefined): void; error(): void { // NOOP } } References:" You are a code assistant,Definition of 'info' in file src/common/log.ts in project gitlab-lsp,"Definition: info(messageOrError: Error | string, trailingError?: Error | unknown) { this.#log(LOG_LEVEL.INFO, messageOrError, trailingError); } warn(messageOrError: Error | string, trailingError?: Error | unknown) { this.#log(LOG_LEVEL.WARNING, messageOrError, trailingError); } error(messageOrError: Error | string, trailingError?: Error | unknown) { this.#log(LOG_LEVEL.ERROR, messageOrError, trailingError); } } // TODO: rename the export and replace usages of `log` with `Log`. export const log = new Log(); References:" You are a code assistant,Definition of 'constructor' in file src/common/services/duo_access/project_access_checker.ts in project gitlab-lsp,"Definition: constructor(projectAccessCache: DuoProjectAccessCache) { this.#projectAccessCache = projectAccessCache; } /** * Check if Duo features are enabled for a given DocumentUri. * * We match the DocumentUri to the project with the longest path. * The enabled projects come from the `DuoProjectAccessCache`. * * @reference `DocumentUri` is the URI of the document to check. Comes from * the `TextDocument` object. */ 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 'nonStreamingSuggestionStateGraph' in file src/common/tracking/constants.ts in project gitlab-lsp,"Definition: export const nonStreamingSuggestionStateGraph = new Map([ [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.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 'convertToJavaScriptRegex' in file src/common/secret_redaction/helpers.ts in project gitlab-lsp,"Definition: export const convertToJavaScriptRegex = (pcreRegex: string) => { // Remove the (?i) flag (case-insensitive) if present const regexWithoutCaseInsensitiveFlag = pcreRegex.replace(/\(\?i\)/g, ''); // Replace \x60 escape with a backtick const jsRegex = regexWithoutCaseInsensitiveFlag.replace(/\\x60/g, '`'); return jsRegex; }; References: - src/common/secret_redaction/helpers.test.ts:26 - src/common/secret_redaction/helpers.test.ts:8 - src/common/secret_redaction/index.ts:22 - src/common/secret_redaction/helpers.test.ts:17" You are a code assistant,Definition of 'readFile' in file src/common/services/fs/file.ts in project gitlab-lsp,"Definition: readFile(_args: ReadFile): Promise; } export const FileResolver = createInterfaceId('FileResolver'); @Injectable(FileResolver, []) export class EmptyFileResolver { // eslint-disable-next-line @typescript-eslint/no-unused-vars readFile(_args: ReadFile): Promise { return Promise.resolve(''); } } References: - src/tests/int/fetch.test.ts:40 - src/tests/unit/tree_sitter/test_utils.ts:38 - src/tests/int/fetch.test.ts:15 - src/node/services/fs/file.ts:9 - src/node/duo_workflow/desktop_workflow_runner.ts:184 - src/node/duo_workflow/desktop_workflow_runner.ts:137" You are a code assistant,Definition of 'SUGGESTION_ACCEPTED_COMMAND' in file src/common/constants.ts in project gitlab-lsp,"Definition: 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 'splitTextFileForPosition' in file src/tests/unit/tree_sitter/test_utils.ts in project gitlab-lsp,"Definition: 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/test_utils.ts:39" You are a code assistant,Definition of 'DuoProjectAccessChecker' in file src/common/services/duo_access/project_access_checker.ts in project gitlab-lsp,"Definition: export const DuoProjectAccessChecker = createInterfaceId('DuoProjectAccessChecker'); @Injectable(DuoProjectAccessChecker, [DuoProjectAccessCache]) export class DefaultDuoProjectAccessChecker { #projectAccessCache: DuoProjectAccessCache; constructor(projectAccessCache: DuoProjectAccessCache) { this.#projectAccessCache = projectAccessCache; } /** * Check if Duo features are enabled for a given DocumentUri. * * We match the DocumentUri to the project with the longest path. * The enabled projects come from the `DuoProjectAccessCache`. * * @reference `DocumentUri` is the URI of the document to check. Comes from * the `TextDocument` object. */ 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: - src/common/advanced_context/advanced_context_factory.ts:24 - src/common/connection.ts:33 - src/common/feature_state/project_duo_acces_check.ts:32 - src/common/advanced_context/advanced_context_filters.test.ts:16 - src/common/advanced_context/advanced_context_filters.ts:14 - src/common/feature_state/project_duo_acces_check.ts:43 - src/common/suggestion/suggestion_service.ts:135 - src/common/ai_context_management_2/policies/duo_project_policy.ts:13 - src/common/suggestion/suggestion_service.ts:84 - src/common/services/duo_access/project_access_checker.test.ts:12" You are a code assistant,Definition of 'SimpleRegistry' in file packages/lib_handler_registry/src/registry/simple_registry.ts in project gitlab-lsp,"Definition: export class SimpleRegistry implements HandlerRegistry { #handlers = new Map(); get size() { return this.#handlers.size; } register(key: string, handler: THandler): Disposable { this.#handlers.set(key, handler); return { dispose: () => { this.#handlers.delete(key); }, }; } has(key: string) { return this.#handlers.has(key); } async handle(key: string, ...args: Parameters): Promise> { const handler = this.#handlers.get(key); if (!handler) { throw new HandlerNotFoundError(key); } try { const handlerResult = await handler(...args); return handlerResult as ReturnType; } catch (error) { throw new UnhandledHandlerError(key, resolveError(error)); } } dispose() { this.#handlers.clear(); } } function resolveError(e: unknown): Error { if (e instanceof Error) { return e; } if (typeof e === 'string') { return new Error(e); } return new Error('Unknown error'); } References: - packages/lib_handler_registry/src/registry/hashed_registry.ts:16 - packages/lib_webview_client/src/bus/provider/socket_io_message_bus.ts:22 - packages/lib_webview/src/setup/plugin/webview_instance_message_bus.ts:28 - packages/lib_handler_registry/src/registry/simple_registry.test.ts:5 - packages/lib_webview_client/src/bus/provider/socket_io_message_bus.ts:20 - packages/lib_webview/src/setup/plugin/webview_instance_message_bus.ts:24 - packages/lib_handler_registry/src/registry/simple_registry.test.ts:8 - packages/lib_webview_client/src/bus/provider/socket_io_message_bus.ts:18 - packages/lib_webview/src/setup/plugin/webview_instance_message_bus.ts:26" You are a code assistant,Definition of 'greet3' in file src/tests/fixtures/intent/empty_function/javascript.js in project gitlab-lsp,"Definition: 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:8" You are a code assistant,Definition of 'MOCK_FILE_1' in file src/tests/int/test_utils.ts in project gitlab-lsp,"Definition: export const MOCK_FILE_1 = { uri: `${WORKSPACE_FOLDER_URI}/some-file.js`, languageId: 'javascript', version: 0, text: '', }; export const MOCK_FILE_2 = { uri: `${WORKSPACE_FOLDER_URI}/some-other-file.js`, languageId: 'javascript', version: 0, text: '', }; declare global { // eslint-disable-next-line @typescript-eslint/no-namespace namespace jest { interface Matchers { toEventuallyContainChildProcessConsoleOutput( expectedMessage: string, timeoutMs?: number, intervalMs?: number, ): Promise; } } } expect.extend({ /** * Custom matcher to check the language client child process console output for an expected string. * This is useful when an operation does not directly run some logic, (e.g. internally emits events * which something later does the thing you're testing), so you cannot just await and check the output. * * await expect(lsClient).toEventuallyContainChildProcessConsoleOutput('foo'); * * @param lsClient LspClient instance to check * @param expectedMessage Message to check for * @param timeoutMs How long to keep checking before test is considered failed * @param intervalMs How frequently to check the log */ async toEventuallyContainChildProcessConsoleOutput( lsClient: LspClient, expectedMessage: string, timeoutMs = 1000, intervalMs = 25, ) { const expectedResult = `Expected language service child process console output to contain ""${expectedMessage}""`; const checkOutput = () => lsClient.childProcessConsole.some((line) => line.includes(expectedMessage)); const sleep = () => new Promise((resolve) => { setTimeout(resolve, intervalMs); }); let remainingRetries = Math.ceil(timeoutMs / intervalMs); while (remainingRetries > 0) { if (checkOutput()) { return { message: () => expectedResult, pass: true, }; } // eslint-disable-next-line no-await-in-loop await sleep(); remainingRetries--; } return { message: () => `""${expectedResult}"", but it was not found within ${timeoutMs}ms`, pass: false, }; }, }); References:" You are a code assistant,Definition of 'COMMAND_MEDIATOR_TOKEN' in file packages/webview_duo_chat/src/plugin/port/platform/web_ide.ts in project gitlab-lsp,"Definition: export const COMMAND_MEDIATOR_TOKEN = `gitlab-web-ide.mediator.mediator-token`; 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; } /** * 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; headers?: Record; } export interface GetRequest<_TReturnType> extends GetRequestBase<_TReturnType> { type: 'rest'; } export interface GetBufferRequest extends GetRequestBase { type: 'rest-buffer'; } export interface GraphQLRequest<_TReturnType> { type: 'graphql'; query: string; /** Options passed to the GraphQL query */ variables: Record; } 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; /* 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 'streamFetch' in file src/browser/fetch.ts in project gitlab-lsp,"Definition: async *streamFetch( url: string, body: string, headers: FetchHeaders, ): AsyncGenerator { const response = await this.fetch(url, { method: 'POST', headers, body, }); await handleFetchError(response, 'Streaming Code Suggestions'); const reader = response?.body?.getReader(); if (!reader) { return undefined; } let buffer = ''; let readResult = await reader.read(); while (!readResult.done) { // TODO: We should consider streaming the raw bytes instead of the decoded string const rawContent = new TextDecoder().decode(readResult.value); buffer += rawContent; // TODO if we cancel the stream, and nothing will consume it, we probably leave the HTTP connection open :-O yield buffer; // eslint-disable-next-line no-await-in-loop readResult = await reader.read(); } return undefined; } } References:" You are a code assistant,Definition of 'error' in file src/common/log_types.ts in project gitlab-lsp,"Definition: error(e: Error): void; error(message: string, e?: Error): void; } 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: - scripts/commit-lint/lint.js:72 - scripts/commit-lint/lint.js:77 - scripts/commit-lint/lint.js:85 - scripts/commit-lint/lint.js:94" You are a code assistant,Definition of 'configureApi' in file src/common/api.ts in project gitlab-lsp,"Definition: async configureApi({ token, baseUrl = GITLAB_API_BASE_URL, }: { token?: string; baseUrl?: string; }) { if (this.#token === token && this.#baseURL === baseUrl) return; this.#token = token; this.#baseURL = baseUrl; const { valid, reason, message } = await this.checkToken(this.#token); let validationMessage; if (!valid) { this.#configService.set('client.token', undefined); validationMessage = `Token is invalid. ${message}. Reason: ${reason}`; log.warn(validationMessage); } else { log.info('Token is valid'); } this.#instanceVersion = await this.#getGitLabInstanceVersion(); this.#fireApiReconfigured(valid, validationMessage); } #looksLikePatToken(token: string): boolean { // OAuth tokens will be longer than 42 characters and PATs will be shorter. return token.length < 42; } async #checkPatToken(token: string): Promise { const headers = this.#getDefaultHeaders(token); const response = await this.#lsFetch.get( `${this.#baseURL}/api/v4/personal_access_tokens/self`, { headers }, ); await handleFetchError(response, 'Information about personal access token'); const { active, scopes } = (await response.json()) as PersonalAccessToken; if (!active) { return { valid: false, reason: 'not_active', message: 'Token is not active.', }; } if (!this.#hasValidScopes(scopes)) { const joinedScopes = scopes.map((scope) => `'${scope}'`).join(', '); return { valid: false, reason: 'invalid_scopes', message: `Token has scope(s) ${joinedScopes} (needs 'api').`, }; } return { valid: true }; } async #checkOAuthToken(token: string): Promise { const headers = this.#getDefaultHeaders(token); const response = await this.#lsFetch.get(`${this.#baseURL}/oauth/token/info`, { headers, }); await handleFetchError(response, 'Information about OAuth token'); const { scope: scopes } = (await response.json()) as OAuthToken; if (!this.#hasValidScopes(scopes)) { const joinedScopes = scopes.map((scope) => `'${scope}'`).join(', '); return { valid: false, reason: 'invalid_scopes', message: `Token has scope(s) ${joinedScopes} (needs 'api').`, }; } return { valid: true }; } async checkToken(token: string = ''): Promise { try { if (this.#looksLikePatToken(token)) { log.info('Checking token for PAT validity'); return await this.#checkPatToken(token); } log.info('Checking token for OAuth validity'); return await this.#checkOAuthToken(token); } catch (err) { log.error('Error performing token check', err); return { valid: false, reason: 'unknown', message: `Failed to check token: ${err}`, }; } } #hasValidScopes(scopes: string[]): boolean { return scopes.includes('api'); } async getCodeSuggestions( request: CodeSuggestionRequest, ): Promise { if (!this.#token) { throw new Error('Token needs to be provided to request Code Suggestions'); } const headers = { ...this.#getDefaultHeaders(this.#token), 'Content-Type': 'application/json', }; const response = await this.#lsFetch.post( `${this.#baseURL}/api/v4/code_suggestions/completions`, { headers, body: JSON.stringify(request) }, ); await handleFetchError(response, 'Code Suggestions'); const data = await response.json(); return { ...data, status: response.status }; } async *getStreamingCodeSuggestions( request: CodeSuggestionRequest, ): AsyncGenerator { if (!this.#token) { throw new Error('Token needs to be provided to stream code suggestions'); } const headers = { ...this.#getDefaultHeaders(this.#token), 'Content-Type': 'application/json', }; yield* this.#lsFetch.streamFetch( `${this.#baseURL}/api/v4/code_suggestions/completions`, JSON.stringify(request), headers, ); } async fetchFromApi(request: ApiRequest): Promise { if (!this.#token) { return Promise.reject(new Error('Token needs to be provided to authorise API request.')); } if ( request.supportedSinceInstanceVersion && !this.#instanceVersionHigherOrEqualThen(request.supportedSinceInstanceVersion.version) ) { return Promise.reject( new InvalidInstanceVersionError( `Can't ${request.supportedSinceInstanceVersion.resourceName} until your instance is upgraded to ${request.supportedSinceInstanceVersion.version} or higher.`, ), ); } if (request.type === 'graphql') { return this.#graphqlRequest(request.query, request.variables); } switch (request.method) { case 'GET': return this.#fetch(request.path, request.searchParams, 'resource', request.headers); case 'POST': return this.#postFetch(request.path, 'resource', request.body, request.headers); default: // the type assertion is necessary because TS doesn't expect any other types throw new Error(`Unknown request type ${(request as ApiRequest).type}`); } } async connectToCable(): Promise { const headers = this.#getDefaultHeaders(this.#token); const websocketOptions = { headers: { ...headers, Origin: this.#baseURL, }, }; return connectToCable(this.#baseURL, websocketOptions); } async #graphqlRequest( document: RequestDocument, variables?: V, ): Promise { const ensureEndsWithSlash = (url: string) => url.replace(/\/?$/, '/'); const endpoint = new URL('./api/graphql', ensureEndsWithSlash(this.#baseURL)).href; // supports GitLab instances that are on a custom path, e.g. ""https://example.com/gitlab"" const graphqlFetch = async ( input: RequestInfo | URL, init?: RequestInit, ): Promise => { const url = input instanceof URL ? input.toString() : input; return this.#lsFetch.post(url, { ...init, headers: { ...headers, ...init?.headers }, }); }; const headers = this.#getDefaultHeaders(this.#token); const client = new GraphQLClient(endpoint, { headers, fetch: graphqlFetch, }); return client.request(document, variables); } async #fetch( apiResourcePath: string, query: Record = {}, resourceName = 'resource', headers?: Record, ): Promise { const url = `${this.#baseURL}/api/v4${apiResourcePath}${createQueryString(query)}`; const result = await this.#lsFetch.get(url, { headers: { ...this.#getDefaultHeaders(this.#token), ...headers }, }); await handleFetchError(result, resourceName); return result.json() as Promise; } async #postFetch( apiResourcePath: string, resourceName = 'resource', body?: unknown, headers?: Record, ): Promise { const url = `${this.#baseURL}/api/v4${apiResourcePath}`; const response = await this.#lsFetch.post(url, { headers: { 'Content-Type': 'application/json', ...this.#getDefaultHeaders(this.#token), ...headers, }, body: JSON.stringify(body), }); await handleFetchError(response, resourceName); return response.json() as Promise; } #getDefaultHeaders(token?: string) { return { Authorization: `Bearer ${token}`, 'User-Agent': `code-completions-language-server-experiment (${this.#clientInfo?.name}:${this.#clientInfo?.version})`, 'X-Gitlab-Language-Server-Version': getLanguageServerVersion(), }; } #instanceVersionHigherOrEqualThen(version: string): boolean { if (!this.#instanceVersion) return false; return semverCompare(this.#instanceVersion, version) >= 0; } async #getGitLabInstanceVersion(): Promise { if (!this.#token) { return ''; } const headers = this.#getDefaultHeaders(this.#token); const response = await this.#lsFetch.get(`${this.#baseURL}/api/v4/version`, { headers, }); const { version } = await response.json(); return version; } get instanceVersion() { return this.#instanceVersion; } } References: - src/common/api.test.ts:78 - src/common/api.test.ts:134" You are a code assistant,Definition of 'Greet' in file src/tests/fixtures/intent/empty_function/javascript.js in project gitlab-lsp,"Definition: 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/go_comments.go:24 - 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" You are a code assistant,Definition of 'FileChangeHandler' in file src/common/services/fs/dir.ts in project gitlab-lsp,"Definition: export type FileChangeHandler = ( event: 'add' | 'change' | 'unlink', workspaceFolder: WorkspaceFolder, filePath: string, stats?: Stats, ) => void; export interface DirectoryWalker { findFilesForDirectory(_args: DirectoryToSearch): Promise; setupFileWatcher(workspaceFolder: WorkspaceFolder, changeHandler: FileChangeHandler): void; } export const DirectoryWalker = createInterfaceId('DirectoryWalker'); @Injectable(DirectoryWalker, []) export class DefaultDirectoryWalker { /** * Returns a list of files in the specified directory that match the specified criteria. * The returned files will be the full paths to the files, they also will be in the form of URIs. * Example: [' file:///path/to/file.txt', 'file:///path/to/another/file.js'] */ // eslint-disable-next-line @typescript-eslint/no-unused-vars findFilesForDirectory(_args: DirectoryToSearch): Promise { return Promise.resolve([]); } // eslint-disable-next-line @typescript-eslint/no-unused-vars setupFileWatcher(workspaceFolder: WorkspaceFolder, changeHandler: FileChangeHandler) { throw new Error(`${workspaceFolder} ${changeHandler} not implemented`); } } References: - src/node/services/fs/dir.ts:57 - src/common/services/fs/dir.ts:53 - src/common/services/fs/virtual_file_service.ts:50 - src/common/services/fs/dir.ts:35" You are a code assistant,Definition of 'constructor' in file src/common/git/ignore_trie.ts in project gitlab-lsp,"Definition: constructor() { this.#children = new Map(); this.#ignoreInstance = null; } addPattern(pathParts: string[], pattern: string): void { if (pathParts.length === 0) { if (!this.#ignoreInstance) { this.#ignoreInstance = ignore(); } this.#ignoreInstance.add(pattern); } else { const [current, ...rest] = pathParts; if (!this.#children.has(current)) { this.#children.set(current, new IgnoreTrie()); } const child = this.#children.get(current); if (!child) { return; } child.addPattern(rest, pattern); } } isIgnored(pathParts: string[]): boolean { if (pathParts.length === 0) { return false; } const [current, ...rest] = pathParts; if (this.#ignoreInstance && this.#ignoreInstance.ignores(path.join(...pathParts))) { return true; } const child = this.#children.get(current); if (child) { return child.isIgnored(rest); } return false; } 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 'greet' in file src/tests/fixtures/intent/empty_function/typescript.ts in project gitlab-lsp,"Definition: 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: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 'setupWebviewRoutes' in file src/node/webview/routes/webview_routes.ts in project gitlab-lsp,"Definition: export const setupWebviewRoutes = async ( fastify: FastifyInstance, { webviewIds, getWebviewResourcePath }: SetupWebviewRoutesOptions, ): Promise => { await fastify.register( async (instance) => { instance.get('/', buildWebviewCollectionMetadataRequestHandler(webviewIds)); instance.get('/:webviewId', buildWebviewRequestHandler(webviewIds, getWebviewResourcePath)); // registering static resources across multiple webviews should not be done in parallel since we need to ensure that the fastify instance has been modified by the static files plugin for (const webviewId of webviewIds) { // eslint-disable-next-line no-await-in-loop await registerStaticPluginSafely(instance, { root: getWebviewResourcePath(webviewId), prefix: `/${webviewId}/`, }); } }, { prefix: '/webview' }, ); }; References: - src/node/webview/routes/webview_routes.test.ts:40 - src/node/webview/routes/webview_routes.test.ts:22 - src/node/webview/webview_fastify_middleware.ts:14 - src/node/webview/routes/webview_routes.test.ts:55" You are a code assistant,Definition of 'LsFetch' in file src/common/fetch.ts in project gitlab-lsp,"Definition: export const LsFetch = createInterfaceId('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 {} async destroy(): Promise {} async fetch(input: RequestInfo | URL, init?: RequestInit): Promise { 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 { // Stub. Should delegate to the node or browser fetch implementations throw new Error('Not implemented'); yield ''; } async delete(input: RequestInfo | URL, init?: RequestInit): Promise { return this.fetch(input, this.updateRequestInit('DELETE', init)); } async get(input: RequestInfo | URL, init?: RequestInit): Promise { return this.fetch(input, this.updateRequestInit('GET', init)); } async post(input: RequestInfo | URL, init?: RequestInit): Promise { return this.fetch(input, this.updateRequestInit('POST', init)); } async put(input: RequestInfo | URL, init?: RequestInit): Promise { return this.fetch(input, this.updateRequestInit('PUT', init)); } async fetchBase(input: RequestInfo | URL, init?: RequestInit): Promise { // 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/tracking/snowplow_tracker.test.ts:70 - src/common/tracking/snowplow/snowplow.ts:69 - src/common/tracking/snowplow_tracker.ts:150 - src/common/api.test.ts:34 - src/common/api.ts:127 - src/node/duo_workflow/desktop_workflow_runner.ts:53 - src/common/tracking/snowplow/snowplow.ts:57 - src/common/api.ts:135 - src/node/duo_workflow/desktop_workflow_runner.ts:47 - src/common/tracking/snowplow_tracker.ts:159 - src/node/duo_workflow/desktop_workflow_runner.test.ts:22 - src/common/tracking/snowplow/snowplow.ts:48" You are a code assistant,Definition of 'CANCEL_STREAMING_COMPLETION_NOTIFICATION' in file src/common/suggestion/streaming_handler.ts in project gitlab-lsp,"Definition: export const CANCEL_STREAMING_COMPLETION_NOTIFICATION = 'cancelStreaming'; export const StreamingCompletionResponse = new NotificationType( STREAMING_COMPLETION_RESPONSE_NOTIFICATION, ); export const CancelStreaming = new NotificationType( CANCEL_STREAMING_COMPLETION_NOTIFICATION, ); export interface StartStreamParams { api: GitLabApiClient; circuitBreaker: CircuitBreaker; connection: Connection; documentContext: IDocContext; parser: TreeSitterParser; postProcessorPipeline: PostProcessorPipeline; streamId: string; tracker: TelemetryTracker; uniqueTrackingId: string; userInstruction?: string; generationType?: GenerationType; additionalContexts?: AdditionalContext[]; } export class DefaultStreamingHandler { #params: StartStreamParams; constructor(params: StartStreamParams) { this.#params = params; } async startStream() { return startStreaming(this.#params); } } const startStreaming = async ({ additionalContexts, api, circuitBreaker, connection, documentContext, parser, postProcessorPipeline, streamId, tracker, uniqueTrackingId, userInstruction, generationType, }: StartStreamParams) => { const language = parser.getLanguageNameForFile(documentContext.fileRelativePath); tracker.setCodeSuggestionsContext(uniqueTrackingId, { documentContext, additionalContexts, source: SuggestionSource.network, language, isStreaming: true, }); let streamShown = false; let suggestionProvided = false; let streamCancelledOrErrored = false; const cancellationTokenSource = new CancellationTokenSource(); const disposeStopStreaming = connection.onNotification(CancelStreaming, (stream) => { if (stream.id === streamId) { streamCancelledOrErrored = true; cancellationTokenSource.cancel(); if (streamShown) { tracker.updateSuggestionState(uniqueTrackingId, TRACKING_EVENTS.REJECTED); } else { tracker.updateSuggestionState(uniqueTrackingId, TRACKING_EVENTS.CANCELLED); } } }); const cancellationToken = cancellationTokenSource.token; const endStream = async () => { await connection.sendNotification(StreamingCompletionResponse, { id: streamId, done: true, }); if (!streamCancelledOrErrored) { tracker.updateSuggestionState(uniqueTrackingId, TRACKING_EVENTS.STREAM_COMPLETED); if (!suggestionProvided) { tracker.updateSuggestionState(uniqueTrackingId, TRACKING_EVENTS.NOT_PROVIDED); } } }; circuitBreaker.success(); const request: CodeSuggestionRequest = { prompt_version: 1, project_path: '', project_id: -1, current_file: { content_above_cursor: documentContext.prefix, content_below_cursor: documentContext.suffix, file_name: documentContext.fileRelativePath, }, intent: 'generation', stream: true, ...(additionalContexts?.length && { context: additionalContexts, }), ...(userInstruction && { user_instruction: userInstruction, }), generation_type: generationType, }; const trackStreamStarted = once(() => { tracker.updateSuggestionState(uniqueTrackingId, TRACKING_EVENTS.STREAM_STARTED); }); const trackStreamShown = once(() => { tracker.updateSuggestionState(uniqueTrackingId, TRACKING_EVENTS.SHOWN); streamShown = true; }); try { for await (const response of api.getStreamingCodeSuggestions(request)) { if (cancellationToken.isCancellationRequested) { break; } if (circuitBreaker.isOpen()) { break; } trackStreamStarted(); const processedCompletion = await postProcessorPipeline.run({ documentContext, input: { id: streamId, completion: response, done: false }, type: 'stream', }); await connection.sendNotification(StreamingCompletionResponse, processedCompletion); if (response.replace(/\s/g, '').length) { trackStreamShown(); suggestionProvided = true; } } } catch (err) { circuitBreaker.error(); if (isFetchError(err)) { tracker.updateCodeSuggestionsContext(uniqueTrackingId, { status: err.status }); } tracker.updateSuggestionState(uniqueTrackingId, TRACKING_EVENTS.ERRORED); streamCancelledOrErrored = true; log.error('Error streaming code suggestions.', err); } finally { await endStream(); disposeStopStreaming.dispose(); cancellationTokenSource.dispose(); } }; References:" You are a code assistant,Definition of 'fsPathFromUri' in file src/common/services/fs/utils.ts in project gitlab-lsp,"Definition: export const fsPathFromUri = (uri: DocumentUri): string => { return URI.parse(uri).fsPath; }; export const fsPathToUri = (fsPath: string): URI => { return URI.file(fsPath); }; export const parseURIString = (uri: string): URI => { return URI.parse(uri); }; References: - src/node/services/fs/file.ts:9 - src/node/services/fs/dir.ts:48 - src/node/services/fs/dir.ts:58" You are a code assistant,Definition of 'QueryValue' in file src/common/utils/create_query_string.ts in project gitlab-lsp,"Definition: export type QueryValue = string | boolean | string[] | number | undefined | null; export const createQueryString = (query: Record): string => { const q = new URLSearchParams(); Object.entries(query).forEach(([name, value]) => { if (notNullOrUndefined(value)) { q.set(name, `${value}`); } }); return q.toString() && `?${q}`; }; References:" You are a code assistant,Definition of 'resolveError' in file packages/lib_handler_registry/src/registry/simple_registry.ts in project gitlab-lsp,"Definition: function resolveError(e: unknown): Error { if (e instanceof Error) { return e; } if (typeof e === 'string') { return new Error(e); } return new Error('Unknown error'); } References: - packages/lib_handler_registry/src/registry/simple_registry.ts:39" You are a code assistant,Definition of 'get' in file packages/lib_di/src/index.ts in project gitlab-lsp,"Definition: get(id: InterfaceId): T { const instance = this.#instances.get(id); if (!instance) { throw new Error(`Instance for interface '${sanitizeId(id)}' is not in the container.`); } return instance as T; } } References: - src/common/utils/headers_to_snowplow_options.ts:22 - src/common/utils/headers_to_snowplow_options.ts:21 - src/common/config_service.ts:134 - src/common/utils/headers_to_snowplow_options.ts:12 - src/common/utils/headers_to_snowplow_options.ts:20" You are a code assistant,Definition of 'InstanceTracker' in file src/common/tracking/instance_tracker.ts in project gitlab-lsp,"Definition: export class InstanceTracker implements TelemetryTracker { #api: GitLabApiClient; #codeSuggestionsContextMap = new Map(); #circuitBreaker = new FixedTimeCircuitBreaker('Instance telemetry'); #configService: ConfigService; #options: ITelemetryOptions = { enabled: true, actions: [], }; #codeSuggestionStates = new Map(); // API used for tracking events is available since GitLab v17.2.0. // Given the track request is done for each CS request // we need to make sure we do not log the unsupported instance message many times #invalidInstanceMsgLogged = false; constructor(api: GitLabApiClient, configService: ConfigService) { this.#configService = configService; this.#configService.onConfigChange((config) => this.#reconfigure(config)); this.#api = api; } #reconfigure(config: IConfig) { const { baseUrl } = config.client; 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(`Instance Telemetry: ${TELEMETRY_DISABLED_WARNING_MSG}`); } else if (enabled === true) { log.info(`Instance Telemetry: ${TELEMETRY_ENABLED_MSG}`); } } if (baseUrl) { this.#options.baseUrl = baseUrl; } if (actions) { this.#options.actions = actions; } } isEnabled(): boolean { return Boolean(this.#options.enabled); } public setCodeSuggestionsContext( uniqueTrackingId: string, context: Partial, ) { if (this.#circuitBreaker.isOpen()) { return; } const { language, isStreaming } = context; // 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); this.#codeSuggestionsContextMap.set(uniqueTrackingId, { is_streaming: isStreaming, language, timestamp: new Date().toISOString(), }); if (this.#isStreamingSuggestion(uniqueTrackingId)) return; this.#codeSuggestionStates.set(uniqueTrackingId, TRACKING_EVENTS.REQUESTED); this.#trackCodeSuggestionsEvent(TRACKING_EVENTS.REQUESTED, uniqueTrackingId).catch((e) => log.warn('Instance telemetry: Could not track telemetry', e), ); log.debug(`Instance telemetry: New suggestion ${uniqueTrackingId} has been requested`); } async updateCodeSuggestionsContext( uniqueTrackingId: string, contextUpdate: Partial, ) { if (this.#circuitBreaker.isOpen()) { return; } if (this.#isStreamingSuggestion(uniqueTrackingId)) return; const context = this.#codeSuggestionsContextMap.get(uniqueTrackingId); const { model, suggestionOptions, isStreaming } = contextUpdate; if (context) { if (model) { context.language = model.lang ?? null; } if (suggestionOptions?.length) { context.suggestion_size = InstanceTracker.#suggestionSize(suggestionOptions); } if (typeof isStreaming === 'boolean') { context.is_streaming = isStreaming; } this.#codeSuggestionsContextMap.set(uniqueTrackingId, context); } } updateSuggestionState(uniqueTrackingId: string, newState: TRACKING_EVENTS): void { if (this.#circuitBreaker.isOpen()) { return; } if (!this.isEnabled()) return; if (this.#isStreamingSuggestion(uniqueTrackingId)) return; const state = this.#codeSuggestionStates.get(uniqueTrackingId); if (!state) { log.debug(`Instance telemetry: The suggestion with ${uniqueTrackingId} can't be found`); return; } const allowedTransitions = nonStreamingSuggestionStateGraph.get(state); if (!allowedTransitions) { log.debug( `Instance telemetry: The suggestion's ${uniqueTrackingId} state ${state} can't be found in state graph`, ); return; } if (!allowedTransitions.includes(newState)) { log.debug( `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( `Instance telemetry: Conditionally allowing transition to accepted state for ${uniqueTrackingId}`, ); } this.#codeSuggestionStates.set(uniqueTrackingId, newState); this.#trackCodeSuggestionsEvent(newState, uniqueTrackingId).catch((e) => log.warn('Instance telemetry: Could not track telemetry', e), ); log.debug(`Instance telemetry: ${uniqueTrackingId} transisted from ${state} to ${newState}`); } async #trackCodeSuggestionsEvent(eventType: TRACKING_EVENTS, uniqueTrackingId: string) { const event = INSTANCE_TRACKING_EVENTS_MAP[eventType]; if (!event) { return; } try { const { language, suggestion_size } = this.#codeSuggestionsContextMap.get(uniqueTrackingId) ?? {}; await this.#api.fetchFromApi({ type: 'rest', method: 'POST', path: '/usage_data/track_event', body: { event, additional_properties: { unique_tracking_id: uniqueTrackingId, timestamp: new Date().toISOString(), language, suggestion_size, }, }, supportedSinceInstanceVersion: { resourceName: 'track instance telemetry', version: '17.2.0', }, }); this.#circuitBreaker.success(); } catch (error) { if (error instanceof InvalidInstanceVersionError) { if (this.#invalidInstanceMsgLogged) return; this.#invalidInstanceMsgLogged = true; } log.warn(`Instance telemetry: Failed to track event: ${eventType}`, error); this.#circuitBreaker.error(); } } rejectOpenedSuggestions() { log.debug(`Instance Telemetry: Reject all opened suggestions`); this.#codeSuggestionStates.forEach((state, uniqueTrackingId) => { if (endStates.includes(state)) { return; } this.updateSuggestionState(uniqueTrackingId, TRACKING_EVENTS.REJECTED); }); } static #suggestionSize(options: SuggestionOption[]): number { const countLines = (text: string) => (text ? text.split('\n').length : 0); return Math.max(...options.map(({ text }) => countLines(text))); } #isStreamingSuggestion(uniqueTrackingId: string): boolean { return Boolean(this.#codeSuggestionsContextMap.get(uniqueTrackingId)?.is_streaming); } } References: - src/common/tracking/instance_tracker.test.ts:70 - src/browser/main.ts:106 - src/node/main.ts:159 - src/common/tracking/instance_tracker.test.ts:31" You are a code assistant,Definition of 'greet2' in file src/tests/fixtures/intent/empty_function/javascript.js 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 { 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 'generateRequestId' in file packages/lib_webview/src/setup/plugin/utils/generate_request_id.ts in project gitlab-lsp,"Definition: export const generateRequestId = () => { return Math.random().toString(36).substring(2); }; References: - packages/lib_webview/src/setup/plugin/webview_instance_message_bus.ts:104 - packages/lib_webview_client/src/bus/provider/socket_io_message_bus.ts:43" You are a code assistant,Definition of 'installLanguages' in file scripts/wasm/build_tree_sitter_wasm.ts in project gitlab-lsp,"Definition: async function installLanguages() { const installPromises = TREE_SITTER_LANGUAGES.map(installLanguage); await Promise.all(installPromises); } installLanguages() .then(() => { console.log('Language parsers installed successfully.'); }) .catch((error) => { console.error('Error installing language parsers:', error); }); References: - scripts/wasm/build_tree_sitter_wasm.ts:34" You are a code assistant,Definition of 'FeatureStateManager' in file src/common/feature_state/feature_state_manager.ts in project gitlab-lsp,"Definition: export const FeatureStateManager = createInterfaceId('FeatureStateManager'); @Injectable(FeatureStateManager, [CodeSuggestionsSupportedLanguageCheck, ProjectDuoAccessCheck]) export class DefaultFeatureStateManager implements FeatureStateManager { #checks: StateCheck[] = []; #subscriptions: Disposable[] = []; #notify?: NotifyFn; constructor( supportedLanguagePolicy: CodeSuggestionsSupportedLanguageCheck, projectDuoAccessCheck: ProjectDuoAccessCheck, ) { this.#checks.push(supportedLanguagePolicy, projectDuoAccessCheck); this.#subscriptions.push( ...this.#checks.map((check) => check.onChanged(() => this.#notifyClient())), ); } init(notify: NotifyFn): void { this.#notify = notify; } async #notifyClient() { if (!this.#notify) { throw new Error( ""The state manager hasn't been initialized. It can't send notifications. Call the init method first."", ); } await this.#notify(this.#state); } dispose() { this.#subscriptions.forEach((s) => s.dispose()); } get #state(): FeatureState[] { const engagedChecks = this.#checks.filter((check) => check.engaged); return getEntries(CHECKS_PER_FEATURE).map(([featureId, stateChecks]) => { const engagedFeatureChecks: FeatureStateCheck[] = engagedChecks .filter(({ id }) => stateChecks.includes(id)) .map((stateCheck) => ({ checkId: stateCheck.id, details: stateCheck.details, })); return { featureId, engagedChecks: engagedFeatureChecks, }; }); } } References: - src/common/connection_service.ts:68" You are a code assistant,Definition of 'getActiveFileName' in file packages/webview_duo_chat/src/plugin/port/chat/utils/editor_text_utils.ts in project gitlab-lsp,"Definition: export const getActiveFileName = (): string | null => { return null; // const editor = vscode.window.activeTextEditor; // if (!editor) return null; // return vscode.workspace.asRelativePath(editor.document.uri); }; export const getTextBeforeSelected = (): string | null => { return null; // const editor = vscode.window.activeTextEditor; // if (!editor || !editor.selection || editor.selection.isEmpty) return null; // const { selection, document } = editor; // const { line: lineNum, character: charNum } = selection.start; // const isFirstCharOnLineSelected = charNum === 0; // const isFirstLine = lineNum === 0; // const getEndLine = () => { // if (isFirstCharOnLineSelected) { // if (isFirstLine) { // return lineNum; // } // return lineNum - 1; // } // return lineNum; // }; // const getEndChar = () => { // if (isFirstCharOnLineSelected) { // if (isFirstLine) { // return 0; // } // return document.lineAt(lineNum - 1).range.end.character; // } // return charNum - 1; // }; // const selectionRange = new vscode.Range(0, 0, getEndLine(), getEndChar()); // return editor.document.getText(selectionRange); }; export const getTextAfterSelected = (): string | null => { return null; // const editor = vscode.window.activeTextEditor; // if (!editor || !editor.selection || editor.selection.isEmpty) return null; // const { selection, document } = editor; // const { line: lineNum, character: charNum } = selection.end; // const isLastCharOnLineSelected = charNum === document.lineAt(lineNum).range.end.character; // const isLastLine = lineNum === document.lineCount; // const getStartLine = () => { // if (isLastCharOnLineSelected) { // if (isLastLine) { // return lineNum; // } // return lineNum + 1; // } // return lineNum; // }; // const getStartChar = () => { // if (isLastCharOnLineSelected) { // if (isLastLine) { // return charNum; // } // return 0; // } // return charNum + 1; // }; // const selectionRange = new vscode.Range( // getStartLine(), // getStartChar(), // document.lineCount, // document.lineAt(document.lineCount - 1).range.end.character, // ); // return editor.document.getText(selectionRange); }; References: - packages/webview_duo_chat/src/plugin/port/chat/gitlab_chat_file_context.ts:17" You are a code assistant,Definition of 'getFilesForWorkspace' in file src/common/git/repository_service.ts in project gitlab-lsp,"Definition: getFilesForWorkspace( workspaceFolderUri: WorkspaceFolderUri, options: { excludeGitFolder?: boolean; excludeIgnored?: boolean } = {}, ): RepositoryFile[] { const repositories = this.#getRepositoriesForWorkspace(workspaceFolderUri); const allFiles: RepositoryFile[] = []; repositories.forEach((repository) => { repository.getFiles().forEach((file) => { // apply the filters if (options.excludeGitFolder && this.#isInGitFolder(file.uri, repository.uri)) { return; } if (options.excludeIgnored && file.isIgnored) { return; } allFiles.push(file); }); }); return allFiles; } // Helper method to check if a file is in the .git folder #isInGitFolder(fileUri: URI, repositoryUri: URI): boolean { const relativePath = fileUri.path.slice(repositoryUri.path.length); return relativePath.split('/').some((part) => part === '.git'); } } References:" You are a code assistant,Definition of 'SuggestionContext' in file src/common/suggestion_client/suggestion_client.ts in project gitlab-lsp,"Definition: export interface SuggestionContext { document: IDocContext; intent?: Intent; projectPath?: string; optionsCount?: OptionsCount; additionalContexts?: AdditionalContext[]; } export interface SuggestionResponse { choices?: SuggestionResponseChoice[]; model?: SuggestionModel; status: number; error?: string; isDirectConnection?: boolean; } export interface SuggestionResponseChoice { text: string; } export interface SuggestionClient { getSuggestions(context: SuggestionContext): Promise; } export type SuggestionClientFn = SuggestionClient['getSuggestions']; export type SuggestionClientMiddleware = ( context: SuggestionContext, next: SuggestionClientFn, ) => ReturnType; References: - src/common/suggestion_client/tree_sitter_middleware.test.ts:46 - src/common/suggestion_client/default_suggestion_client.test.ts:10 - src/common/suggestion_client/create_v2_request.ts:5 - src/common/suggestion_client/suggestion_client_pipeline.ts:38 - src/common/suggestion_client/suggestion_client.ts:46 - src/common/suggestion_client/default_suggestion_client.ts:13 - src/common/suggestion_client/suggestion_client_pipeline.test.ts:14 - src/common/suggestion_client/direct_connection_client.ts:124 - src/common/suggestion_client/direct_connection_client.test.ts:24 - src/common/suggestion_client/suggestion_client_pipeline.test.ts:40 - src/common/suggestion_client/tree_sitter_middleware.test.ts:71 - src/common/suggestion_client/suggestion_client.ts:40 - src/common/suggestion_client/suggestion_client_pipeline.ts:27 - src/common/suggestion_client/fallback_client.ts:10" You are a code assistant,Definition of 'LangGraphCheckpoint' in file src/common/graphql/workflow/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 'parseURIString' in file src/common/services/fs/utils.ts in project gitlab-lsp,"Definition: export const parseURIString = (uri: string): URI => { return URI.parse(uri); }; References: - src/common/ai_context_management_2/providers/ai_file_context_provider.ts:78 - src/common/ai_context_management_2/ai_context_aggregator.ts:67" You are a code assistant,Definition of 'handleWebviewDestroyed' in file packages/lib_webview_transport_json_rpc/src/json_rpc_connection_transport.ts in project gitlab-lsp,"Definition: export const handleWebviewDestroyed = ( messageEmitter: WebviewTransportEventEmitter, logger?: Logger, ) => withJsonRpcMessageValidation(isWebviewInstanceDestroyedEventData, logger, (message) => { messageEmitter.emit('webview_instance_destroyed', message); }); export const handleWebviewMessage = ( messageEmitter: WebviewTransportEventEmitter, logger?: Logger, ) => withJsonRpcMessageValidation(isWebviewInstanceMessageEventData, logger, (message) => { messageEmitter.emit('webview_instance_notification_received', message); }); export type JsonRpcConnectionTransportProps = { connection: Connection; logger: Logger; notificationRpcMethod?: string; webviewCreatedRpcMethod?: string; webviewDestroyedRpcMethod?: string; }; export class JsonRpcConnectionTransport implements Transport { #messageEmitter = createWebviewTransportEventEmitter(); #connection: Connection; #notificationChannel: string; #webviewCreatedChannel: string; #webviewDestroyedChannel: string; #logger?: Logger; #disposables: Disposable[] = []; constructor({ connection, logger, notificationRpcMethod: notificationChannel = DEFAULT_NOTIFICATION_RPC_METHOD, webviewCreatedRpcMethod: webviewCreatedChannel = DEFAULT_WEBVIEW_CREATED_RPC_METHOD, webviewDestroyedRpcMethod: webviewDestroyedChannel = DEFAULT_WEBVIEW_DESTROYED_RPC_METHOD, }: JsonRpcConnectionTransportProps) { this.#connection = connection; this.#logger = logger ? withPrefix(logger, LOGGER_PREFIX) : undefined; this.#notificationChannel = notificationChannel; this.#webviewCreatedChannel = webviewCreatedChannel; this.#webviewDestroyedChannel = webviewDestroyedChannel; this.#subscribeToConnection(); } #subscribeToConnection() { const channelToNotificationHandlerMap = { [this.#webviewCreatedChannel]: handleWebviewCreated(this.#messageEmitter, this.#logger), [this.#webviewDestroyedChannel]: handleWebviewDestroyed(this.#messageEmitter, this.#logger), [this.#notificationChannel]: handleWebviewMessage(this.#messageEmitter, this.#logger), }; Object.entries(channelToNotificationHandlerMap).forEach(([channel, handler]) => { const disposable = this.#connection.onNotification(channel, handler); this.#disposables.push(disposable); }); } on( type: K, callback: TransportMessageHandler, ): Disposable { this.#messageEmitter.on(type, callback as WebviewTransportEventEmitterMessages[K]); return { dispose: () => this.#messageEmitter.off(type, callback as WebviewTransportEventEmitterMessages[K]), }; } publish(type: K, payload: MessagesToClient[K]): Promise { if (type === 'webview_instance_notification') { return this.#connection.sendNotification(this.#notificationChannel, payload); } throw new Error(`Unknown message type: ${type}`); } dispose(): void { this.#messageEmitter.removeAllListeners(); this.#disposables.forEach((disposable) => disposable.dispose()); this.#logger?.debug('JsonRpcConnectionTransport disposed'); } } References: - packages/lib_webview_transport_json_rpc/src/json_rpc_connection_transport.ts:92" You are a code assistant,Definition of 'post' in file src/common/fetch.ts in project gitlab-lsp,"Definition: post(input: RequestInfo | URL, init?: RequestInit): Promise; put(input: RequestInfo | URL, init?: RequestInit): Promise; updateAgentOptions(options: FetchAgentOptions): void; streamFetch(url: string, body: string, headers: FetchHeaders): AsyncGenerator; } export const LsFetch = createInterfaceId('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 {} async destroy(): Promise {} async fetch(input: RequestInfo | URL, init?: RequestInit): Promise { 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 { // Stub. Should delegate to the node or browser fetch implementations throw new Error('Not implemented'); yield ''; } async delete(input: RequestInfo | URL, init?: RequestInit): Promise { return this.fetch(input, this.updateRequestInit('DELETE', init)); } async get(input: RequestInfo | URL, init?: RequestInit): Promise { return this.fetch(input, this.updateRequestInit('GET', init)); } async post(input: RequestInfo | URL, init?: RequestInit): Promise { return this.fetch(input, this.updateRequestInit('POST', init)); } async put(input: RequestInfo | URL, init?: RequestInit): Promise { return this.fetch(input, this.updateRequestInit('PUT', init)); } async fetchBase(input: RequestInfo | URL, init?: RequestInit): Promise { // 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 'DesktopTreeSitterParser' in file src/node/tree_sitter/parser.ts in project gitlab-lsp,"Definition: export class DesktopTreeSitterParser extends TreeSitterParser { constructor() { super({ languages: TREE_SITTER_LANGUAGES, }); } async init(): Promise { try { await Parser.init(); log.debug('DesktopTreeSitterParser: Initialized tree-sitter parser.'); this.loadState = TreeSitterParserLoadState.READY; } catch (err) { log.warn('DesktopTreeSitterParser: Error initializing tree-sitter parsers.', err); this.loadState = TreeSitterParserLoadState.ERRORED; } } } References: - src/tests/unit/tree_sitter/test_utils.ts:37 - src/node/main.ts:168" You are a code assistant,Definition of 'DUO_CHAT_WEBVIEW_ID' in file packages/webview_duo_chat/src/plugin/port/constants.ts in project gitlab-lsp,"Definition: export const DUO_CHAT_WEBVIEW_ID = 'chat'; References:" You are a code assistant,Definition of 'log' in file src/common/log.ts in project gitlab-lsp,"Definition: export const log = new Log(); References: - src/tests/fixtures/intent/empty_function/javascript.js:16 - src/tests/fixtures/intent/empty_function/javascript.js:10 - scripts/set_ls_version.js:17 - scripts/commit-lint/lint.js:66 - src/tests/fixtures/intent/empty_function/javascript.js:4 - src/tests/fixtures/intent/empty_function/javascript.js:31 - scripts/commit-lint/lint.js:61" You are a code assistant,Definition of 'debug' in file src/common/log.ts in project gitlab-lsp,"Definition: debug(messageOrError: Error | string, trailingError?: Error | unknown) { this.#log(LOG_LEVEL.DEBUG, messageOrError, trailingError); } info(messageOrError: Error | string, trailingError?: Error | unknown) { this.#log(LOG_LEVEL.INFO, messageOrError, trailingError); } warn(messageOrError: Error | string, trailingError?: Error | unknown) { this.#log(LOG_LEVEL.WARNING, messageOrError, trailingError); } error(messageOrError: Error | string, trailingError?: Error | unknown) { this.#log(LOG_LEVEL.ERROR, messageOrError, trailingError); } } // TODO: rename the export and replace usages of `log` with `Log`. export const log = new Log(); References:" You are a code assistant,Definition of 'Fetch' in file src/browser/fetch.ts in project gitlab-lsp,"Definition: export class Fetch extends FetchBase implements LsFetch { /** * Browser-specific fetch implementation. * See https://gitlab.com/gitlab-org/editor-extensions/gitlab-lsp/-/issues/171 for details */ async *streamFetch( url: string, body: string, headers: FetchHeaders, ): AsyncGenerator { const response = await this.fetch(url, { method: 'POST', headers, body, }); await handleFetchError(response, 'Streaming Code Suggestions'); const reader = response?.body?.getReader(); if (!reader) { return undefined; } let buffer = ''; let readResult = await reader.read(); while (!readResult.done) { // TODO: We should consider streaming the raw bytes instead of the decoded string const rawContent = new TextDecoder().decode(readResult.value); buffer += rawContent; // TODO if we cancel the stream, and nothing will consume it, we probably leave the HTTP connection open :-O yield buffer; // eslint-disable-next-line no-await-in-loop readResult = await reader.read(); } return undefined; } } References: - src/node/fetch.test.ts:57 - src/node/fetch.test.ts:90 - src/browser/fetch.test.ts:33 - src/node/fetch.test.ts:74 - src/tests/int/snowplow.test.ts:16 - src/browser/main.ts:67 - src/node/main.ts:113 - src/tests/int/fetch.test.ts:124 - src/node/fetch.test.ts:191 - src/node/fetch.test.ts:194 - src/tests/int/fetch.test.ts:82 - src/tests/int/fetch.test.ts:154 - src/node/fetch.test.ts:38" You are a code assistant,Definition of 'createFakePartial' in file packages/webview_duo_chat/src/plugin/port/test_utils/create_fake_partial.ts in project gitlab-lsp,"Definition: export const createFakePartial = (x: DeepPartial): T => x as T; References: - src/common/suggestion/suggestion_service.test.ts:436 - src/common/suggestion_client/create_v2_request.test.ts:10 - src/common/feature_state/project_duo_acces_check.test.ts:32 - src/common/suggestion/suggestion_filter.test.ts:80 - src/common/tree_sitter/comments/comment_resolver.test.ts:164 - src/common/message_handler.test.ts:53 - packages/webview_duo_chat/src/plugin/port/chat/gitlab_chat_api.test.ts:74 - packages/webview_duo_chat/src/plugin/port/chat/get_platform_manager_for_chat.test.ts:198 - src/common/services/duo_access/project_access_checker.test.ts:48 - src/common/services/duo_access/project_access_checker.test.ts:15 - src/common/advanced_context/advanced_context_service.test.ts:34 - src/common/message_handler.test.ts:57 - src/common/connection.test.ts:48 - src/common/advanced_context/context_resolvers/open_tabs_context_resolver.test.ts:14 - src/common/advanced_context/helpers.test.ts:10 - src/common/connection.test.ts:58 - src/tests/int/lsp_client.ts:38 - src/common/tree_sitter/intent_resolver.test.ts:40 - src/common/connection.test.ts:47 - src/common/graphql/workflow/service.test.ts:35 - src/common/suggestion/suggestion_service.test.ts:983 - src/common/suggestion/suggestion_service.test.ts:105 - src/common/graphql/workflow/service.test.ts:41 - packages/webview_duo_chat/src/plugin/port/test_utils/entities.ts:16 - src/common/services/duo_access/project_access_checker.test.ts:70 - src/common/connection.test.ts:31 - src/common/feature_state/project_duo_acces_check.test.ts:23 - src/common/tree_sitter/empty_function/empty_function_resolver.test.ts:17 - src/common/core/handlers/initialize_handler.test.ts:17 - src/common/feature_state/project_duo_acces_check.test.ts:40 - src/common/tracking/snowplow_tracker.test.ts:82 - src/common/api.test.ts:349 - src/common/tree_sitter/comments/comment_resolver.test.ts:129 - src/common/feature_state/supported_language_check.test.ts:38 - src/common/tracking/snowplow_tracker.test.ts:78 - src/common/suggestion_client/direct_connection_client.test.ts:50 - src/common/tree_sitter/intent_resolver.test.ts:160 - src/common/suggestion/streaming_handler.test.ts:65 - src/tests/int/lsp_client.ts:164 - src/common/suggestion_client/fallback_client.test.ts:8 - src/common/log.test.ts:10 - src/common/services/duo_access/project_access_cache.test.ts:12 - src/common/suggestion_client/fallback_client.test.ts:15 - src/common/test_utils/create_fake_response.ts:18 - src/common/tree_sitter/parser.test.ts:86 - src/common/suggestion_client/fallback_client.test.ts:7 - src/common/suggestion_client/tree_sitter_middleware.test.ts:33 - src/common/feature_flags.test.ts:17 - src/common/services/duo_access/project_access_checker.test.ts:148 - src/common/suggestion/suggestion_service.test.ts:193 - src/common/suggestion/suggestion_service.test.ts:1054 - src/common/connection.test.ts:53 - src/common/suggestion/streaming_handler.test.ts:75 - src/common/suggestion/suggestion_service.test.ts:464 - src/common/advanced_context/advanced_context_service.test.ts:53 - src/common/feature_state/feature_state_manager.test.ts:21 - src/common/message_handler.test.ts:48 - src/common/document_service.test.ts:8 - src/common/services/duo_access/project_access_checker.test.ts:92 - src/common/tree_sitter/comments/comment_resolver.test.ts:199 - src/common/suggestion_client/tree_sitter_middleware.test.ts:86 - src/common/suggestion/suggestion_service.test.ts:190 - src/common/suggestion/suggestion_filter.test.ts:79 - src/common/feature_flags.test.ts:93 - src/common/advanced_context/advanced_context_service.test.ts:50 - src/common/message_handler.test.ts:64 - src/common/suggestion/suggestion_filter.test.ts:35 - src/common/suggestion/suggestion_service.test.ts:770 - src/common/api.test.ts:406 - src/common/tracking/instance_tracker.test.ts:179 - src/common/suggestion_client/default_suggestion_client.test.ts:24 - src/common/tree_sitter/empty_function/empty_function_resolver.test.ts:31 - src/common/suggestion_client/tree_sitter_middleware.test.ts:62 - packages/webview_duo_chat/src/plugin/port/chat/get_platform_manager_for_chat.test.ts:199 - src/common/suggestion_client/fallback_client.test.ts:27 - src/common/advanced_context/context_resolvers/open_tabs_context_resolver.test.ts:24 - src/common/suggestion_client/default_suggestion_client.test.ts:7 - src/common/suggestion/suggestion_service.test.ts:86 - src/common/tree_sitter/parser.test.ts:127 - src/common/services/duo_access/project_access_checker.test.ts:145 - src/common/tree_sitter/comments/comment_resolver.test.ts:30 - packages/webview_duo_chat/src/plugin/port/chat/get_platform_manager_for_chat.test.ts:44 - src/common/suggestion_client/direct_connection_client.test.ts:32 - src/common/suggestion/streaming_handler.test.ts:50 - src/common/feature_state/project_duo_acces_check.test.ts:27 - src/common/document_transformer_service.test.ts:68 - src/node/duo_workflow/desktop_workflow_runner.test.ts:22 - src/common/suggestion/suggestion_service.test.ts:164 - src/common/suggestion/suggestion_service.test.ts:89 - src/common/suggestion/suggestion_service.test.ts:76 - src/common/suggestion_client/direct_connection_client.test.ts:152 - src/common/feature_state/project_duo_acces_check.test.ts:41 - src/common/suggestion_client/fallback_client.test.ts:9 - src/common/advanced_context/advanced_context_factory.test.ts:72 - src/common/fetch_error.test.ts:37 - src/common/suggestion_client/direct_connection_client.test.ts:52 - src/common/suggestion_client/direct_connection_client.test.ts:35 - src/common/feature_state/feature_state_manager.test.ts:34 - src/common/services/duo_access/project_access_checker.test.ts:40 - src/common/api.test.ts:438 - src/common/tree_sitter/comments/comment_resolver.test.ts:31 - src/common/suggestion/suggestion_filter.test.ts:56 - src/common/tree_sitter/empty_function/empty_function_resolver.test.ts:32 - src/common/services/duo_access/project_access_cache.test.ts:20 - src/common/suggestion_client/fallback_client.test.ts:30 - src/common/feature_state/feature_state_manager.test.ts:55 - src/common/services/duo_access/project_access_checker.test.ts:44 - src/common/suggestion/suggestion_filter.test.ts:77 - src/common/tree_sitter/comments/comment_resolver.test.ts:208 - src/common/tree_sitter/comments/comment_resolver.test.ts:212 - src/common/message_handler.test.ts:215 - src/common/suggestion/suggestion_service.test.ts:84 - src/common/services/duo_access/project_access_checker.test.ts:126 - src/common/connection.test.ts:44 - src/common/advanced_context/advanced_context_service.test.ts:39 - src/common/tracking/instance_tracker.test.ts:32 - src/common/services/duo_access/project_access_checker.test.ts:153 - src/common/services/duo_access/project_access_checker.test.ts:74 - src/common/tree_sitter/parser.test.ts:83 - src/common/suggestion/streaming_handler.test.ts:70 - src/common/tree_sitter/intent_resolver.test.ts:47 - src/common/services/duo_access/project_access_checker.test.ts:157 - src/common/fetch_error.test.ts:7 - src/common/core/handlers/initialize_handler.test.ts:8 - src/common/message_handler.test.ts:204 - src/common/suggestion/suggestion_service.test.ts:108 - src/common/advanced_context/advanced_context_service.test.ts:47 - src/common/suggestion_client/direct_connection_client.test.ts:58 - src/common/suggestion/suggestion_service.test.ts:100 - src/common/tree_sitter/comments/comment_resolver.test.ts:162 - src/common/tree_sitter/comments/comment_resolver.test.ts:27 - src/common/tree_sitter/comments/comment_resolver.test.ts:206 - src/common/feature_flags.test.ts:21 - src/common/message_handler.test.ts:136 - src/common/advanced_context/helpers.test.ts:7 - src/common/message_handler.test.ts:42 - src/common/suggestion/suggestion_service.test.ts:1038 - src/common/suggestion/suggestion_service.test.ts:469 - src/common/tree_sitter/comments/comment_resolver.test.ts:127 - src/common/suggestion/suggestion_service.test.ts:582 - src/common/services/duo_access/project_access_checker.test.ts:66 - src/common/graphql/workflow/service.test.ts:38 - src/common/advanced_context/context_resolvers/open_tabs_context_resolver.test.ts:57 - src/common/tree_sitter/comments/comment_resolver.test.ts:16 - src/common/services/duo_access/project_access_checker.test.ts:100 - src/common/tracking/multi_tracker.test.ts:8 - src/common/suggestion/suggestion_service.test.ts:492 - src/common/advanced_context/advanced_context_service.test.ts:28 - src/common/suggestion_client/suggestion_client_pipeline.test.ts:10 - src/common/connection.test.ts:57 - src/common/suggestion/suggestion_service.test.ts:1073 - src/common/suggestion/streaming_handler.test.ts:46 - src/common/tree_sitter/comments/comment_resolver.test.ts:193 - src/common/suggestion/suggestion_filter.test.ts:57 - src/common/suggestion/suggestion_service.test.ts:756 - src/common/tree_sitter/comments/comment_resolver.test.ts:195 - src/common/advanced_context/advanced_context_factory.test.ts:73 - src/common/tree_sitter/comments/comment_resolver.test.ts:133 - src/common/connection.test.ts:59 - src/node/duo_workflow/desktop_workflow_runner.test.ts:24 - src/common/services/duo_access/project_access_checker.test.ts:122 - src/common/security_diagnostics_publisher.test.ts:51 - src/common/fetch_error.test.ts:21 - src/common/core/handlers/token_check_notifier.test.ts:11 - src/common/message_handler.test.ts:61 - src/common/suggestion/suggestion_service.test.ts:476 - src/common/suggestion_client/create_v2_request.test.ts:8 - src/common/suggestion/suggestion_service.test.ts:199 - src/common/services/duo_access/project_access_cache.test.ts:16 - src/common/advanced_context/advanced_context_service.test.ts:42 - src/common/services/duo_access/project_access_checker.test.ts:24 - src/common/api.test.ts:422 - src/common/security_diagnostics_publisher.test.ts:48 - src/common/suggestion/streaming_handler.test.ts:56 - src/common/tracking/instance_tracker.test.ts:176 - src/common/tree_sitter/empty_function/empty_function_resolver.test.ts:28 - src/common/suggestion_client/fallback_client.test.ts:12 - src/common/feature_state/project_duo_acces_check.test.ts:35 - src/common/services/duo_access/project_access_checker.test.ts:118 - src/common/suggestion_client/direct_connection_client.test.ts:150 - src/common/feature_state/supported_language_check.test.ts:39 - src/common/services/duo_access/project_access_checker.test.ts:96 - src/common/suggestion_client/direct_connection_client.test.ts:33 - src/node/fetch.test.ts:16 - src/common/suggestion/streaming_handler.test.ts:62 - src/common/suggestion_client/tree_sitter_middleware.test.ts:24 - src/common/api.test.ts:298 - src/common/suggestion/suggestion_service.test.ts:205 - src/common/feature_state/feature_state_manager.test.ts:78 - src/common/suggestion/suggestion_service.test.ts:94 - src/common/suggestion_client/direct_connection_client.test.ts:106 - src/common/suggestion/suggestion_service.test.ts:461 - src/common/suggestion_client/default_suggestion_client.test.ts:11 - src/common/suggestion_client/direct_connection_client.test.ts:103 - src/common/api.test.ts:318 - src/common/services/duo_access/project_access_checker.test.ts:163 - src/common/feature_state/supported_language_check.test.ts:27" You are a code assistant,Definition of 'CHAT_INPUT_TEMPLATE_17_3_AND_LATER' in file packages/webview_duo_chat/src/plugin/port/chat/gitlab_chat_api.ts in project gitlab-lsp,"Definition: export const CHAT_INPUT_TEMPLATE_17_3_AND_LATER = { query: gql` mutation chat( $question: String! $resourceId: AiModelID $currentFileContext: AiCurrentFileInput $clientSubscriptionId: String $platformOrigin: String! ) { aiAction( input: { chat: { resourceId: $resourceId, content: $question, currentFile: $currentFileContext } clientSubscriptionId: $clientSubscriptionId platformOrigin: $platformOrigin } ) { requestId errors } } `, defaultVariables: { platformOrigin: PLATFORM_ORIGIN, }, }; export type AiActionResponseType = { aiAction: { requestId: string; errors: string[] }; }; export const AI_MESSAGES_QUERY = gql` query getAiMessages($requestIds: [ID!], $roles: [AiMessageRole!]) { aiMessages(requestIds: $requestIds, roles: $roles) { nodes { requestId role content contentHtml timestamp errors extras { sources } } } } `; type AiMessageResponseType = { requestId: string; role: string; content: string; contentHtml: string; timestamp: string; errors: string[]; extras?: { sources: object[]; }; }; type AiMessagesResponseType = { aiMessages: { nodes: AiMessageResponseType[]; }; }; interface ErrorMessage { type: 'error'; requestId: string; role: 'system'; errors: string[]; } const errorResponse = (requestId: string, errors: string[]): ErrorMessage => ({ requestId, errors, role: 'system', type: 'error', }); interface SuccessMessage { type: 'message'; requestId: string; role: string; content: string; contentHtml: string; timestamp: string; errors: string[]; extras?: { sources: object[]; }; } const successResponse = (response: AiMessageResponseType): SuccessMessage => ({ type: 'message', ...response, }); type AiMessage = SuccessMessage | ErrorMessage; type ChatInputTemplate = { query: string; defaultVariables: { platformOrigin?: string; }; }; export class GitLabChatApi { #cachedActionQuery?: ChatInputTemplate = undefined; #manager: GitLabPlatformManagerForChat; constructor(manager: GitLabPlatformManagerForChat) { this.#manager = manager; } async processNewUserPrompt( question: string, subscriptionId?: string, currentFileContext?: GitLabChatFileContext, ): Promise { return this.#sendAiAction({ question, currentFileContext, clientSubscriptionId: subscriptionId, }); } async pullAiMessage(requestId: string, role: string): Promise { const response = await pullHandler(() => this.#getAiMessage(requestId, role)); if (!response) return errorResponse(requestId, ['Reached timeout while fetching response.']); return successResponse(response); } async cleanChat(): Promise { return this.#sendAiAction({ question: SPECIAL_MESSAGES.CLEAN }); } async #currentPlatform() { const platform = await this.#manager.getGitLabPlatform(); if (!platform) throw new Error('Platform is missing!'); return platform; } async #getAiMessage(requestId: string, role: string): Promise { const request: GraphQLRequest = { type: 'graphql', query: AI_MESSAGES_QUERY, variables: { requestIds: [requestId], roles: [role.toUpperCase()] }, }; const platform = await this.#currentPlatform(); const history = await platform.fetchFromApi(request); return history.aiMessages.nodes[0]; } async subscribeToUpdates( messageCallback: (message: AiCompletionResponseMessageType) => Promise, subscriptionId?: string, ) { const platform = await this.#currentPlatform(); const channel = new AiCompletionResponseChannel({ htmlResponse: true, userId: `gid://gitlab/User/${extractUserId(platform.account.id)}`, aiAction: 'CHAT', clientSubscriptionId: subscriptionId, }); const cable = await platform.connectToCable(); // we use this flag to fix https://gitlab.com/gitlab-org/gitlab-vscode-extension/-/issues/1397 // sometimes a chunk comes after the full message and it broke the chat let fullMessageReceived = false; channel.on('newChunk', async (msg) => { if (fullMessageReceived) { log.info(`CHAT-DEBUG: full message received, ignoring chunk`); return; } await messageCallback(msg); }); channel.on('fullMessage', async (message) => { fullMessageReceived = true; await messageCallback(message); if (subscriptionId) { cable.disconnect(); } }); cable.subscribe(channel); } async #sendAiAction(variables: object): Promise { const platform = await this.#currentPlatform(); const { query, defaultVariables } = await this.#actionQuery(); const projectGqlId = await this.#manager.getProjectGqlId(); const request: GraphQLRequest = { type: 'graphql', query, variables: { ...variables, ...defaultVariables, resourceId: projectGqlId ?? null, }, }; return platform.fetchFromApi(request); } async #actionQuery(): Promise { if (!this.#cachedActionQuery) { const platform = await this.#currentPlatform(); try { const { version } = await platform.fetchFromApi(versionRequest); this.#cachedActionQuery = ifVersionGte( version, MINIMUM_PLATFORM_ORIGIN_FIELD_VERSION, () => CHAT_INPUT_TEMPLATE_17_3_AND_LATER, () => CHAT_INPUT_TEMPLATE_17_2_AND_EARLIER, ); } catch (e) { log.debug(`GitLab version check for sending chat failed:`, e as Error); this.#cachedActionQuery = CHAT_INPUT_TEMPLATE_17_3_AND_LATER; } } return this.#cachedActionQuery; } } References:" You are a code assistant,Definition of 'ISuggestionsCacheOptions' in file src/common/config_service.ts in project gitlab-lsp,"Definition: export interface ISuggestionsCacheOptions { enabled?: boolean; maxSize?: number; ttl?: number; prefixLines?: number; suffixLines?: number; } export interface IHttpAgentOptions { ca?: string; cert?: string; certKey?: string; } export interface ISnowplowTrackerOptions { gitlab_instance_id?: string; gitlab_global_user_id?: string; gitlab_host_name?: string; gitlab_saas_duo_pro_namespace_ids?: number[]; } export interface ISecurityScannerOptions { enabled?: boolean; serviceUrl?: string; } export interface IWorkflowSettings { dockerSocket?: string; } export interface IDuoConfig { enabledWithoutGitlabProject?: boolean; } export interface IClientConfig { /** GitLab API URL used for getting code suggestions */ baseUrl?: string; /** Full project path. */ projectPath?: string; /** PAT or OAuth token used to authenticate to GitLab API */ token?: string; /** The base URL for language server assets in the client-side extension */ baseAssetsUrl?: string; clientInfo?: IClientInfo; // FIXME: this key should be codeSuggestions (we have code completion and code generation) codeCompletion?: ICodeCompletionConfig; openTabsContext?: boolean; telemetry?: ITelemetryOptions; /** Config used for caching code suggestions */ suggestionsCache?: ISuggestionsCacheOptions; workspaceFolders?: WorkspaceFolder[] | null; /** Collection of Feature Flag values which are sent from the client */ featureFlags?: Record; logLevel?: LogLevel; ignoreCertificateErrors?: boolean; httpAgentOptions?: IHttpAgentOptions; snowplowTrackerOptions?: ISnowplowTrackerOptions; // TODO: move to `duo` duoWorkflowSettings?: IWorkflowSettings; securityScannerOptions?: ISecurityScannerOptions; duo?: IDuoConfig; } export interface IConfig { // TODO: we can possibly remove this extra level of config and move all IClientConfig properties to IConfig client: IClientConfig; } /** * ConfigService manages user configuration (e.g. baseUrl) and application state (e.g. codeCompletion.enabled) * TODO: Maybe in the future we would like to separate these two */ export interface ConfigService { get: TypedGetter; /** * set sets the property of the config * the new value completely overrides the old one */ set: TypedSetter; onConfigChange(listener: (config: IConfig) => void): Disposable; /** * merge adds `newConfig` properties into existing config, if the * property is present in both old and new config, `newConfig` * properties take precedence unless not defined * * This method performs deep merge * * **Arrays are not merged; they are replaced with the new value.** * */ merge(newConfig: Partial): void; } export const ConfigService = createInterfaceId('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 = (key?: string) => { return key ? get(this.#config, key) : this.#config; }; set: TypedSetter = (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) { mergeWith(this.#config, newConfig, (target, src) => (isArray(target) ? src : undefined)); this.#triggerChange(); } } References: - src/common/config_service.ts:64" You are a code assistant,Definition of 'getSuggestions' in file src/common/suggestion_client/direct_connection_client.ts in project gitlab-lsp,"Definition: async getSuggestions(context: SuggestionContext): Promise { // TODO we would like to send direct request only for intent === COMPLETION // however, currently we are not certain that the intent is completion // when we finish the following two issues, we can be certain that the intent is COMPLETION // // https://gitlab.com/gitlab-org/editor-extensions/gitlab-lsp/-/issues/173 // https://gitlab.com/gitlab-org/editor-extensions/gitlab-lsp/-/issues/247 if (context.intent === GENERATION) { return undefined; } if (!this.#isValidApi) { return undefined; } if (this.#directConnectionCircuitBreaker.isOpen()) { return undefined; } if (!this.#connectionDetails || areExpired(this.#connectionDetails)) { this.#fetchDirectConnectionDetails().catch( (e) => log.error(`#fetchDirectConnectionDetails error: ${e}`), // this makes eslint happy, the method should never throw ); return undefined; } try { const response = await this.#fetchUsingDirectConnection( createV2Request(context, this.#connectionDetails.model_details), ); return response && { ...response, isDirectConnection: true }; } catch (e) { this.#directConnectionCircuitBreaker.error(); log.warn( 'Direct connection for code suggestions failed. Code suggestion requests will be sent to your GitLab instance.', e, ); } return undefined; } } References:" You are a code assistant,Definition of 'constructor' in file src/common/tracking/snowplow/snowplow.ts in project gitlab-lsp,"Definition: private constructor(lsFetch: LsFetch, options: SnowplowOptions) { this.#lsFetch = lsFetch; this.#options = options; this.#emitter = new Emitter( this.#options.timeInterval, this.#options.maxItems, this.#sendEvent.bind(this), ); this.#emitter.start(); this.#tracker = trackerCore({ callback: this.#emitter.add.bind(this.#emitter) }); } public static getInstance(lsFetch: LsFetch, options?: SnowplowOptions): Snowplow { if (!this.#instance) { if (!options) { throw new Error('Snowplow should be instantiated'); } const sp = new Snowplow(lsFetch, options); Snowplow.#instance = sp; } // FIXME: this eslint violation was introduced before we set up linting // eslint-disable-next-line @typescript-eslint/no-non-null-assertion return Snowplow.#instance!; } async #sendEvent(events: PayloadBuilder[]): Promise { if (!this.#options.enabled() || this.disabled) { return; } try { const url = `${this.#options.endpoint}/com.snowplowanalytics.snowplow/tp2`; const data = { schema: 'iglu:com.snowplowanalytics.snowplow/payload_data/jsonschema/1-0-4', data: events.map((event) => { const eventId = uuidv4(); // All values prefilled below are part of snowplow tracker protocol // https://docs.snowplow.io/docs/collecting-data/collecting-from-own-applications/snowplow-tracker-protocol/#common-parameters // Values are set according to either common GitLab standard: // tna - representing tracker namespace and being set across GitLab to ""gl"" // tv - represents tracker value, to make it aligned with downstream system it has to be prefixed with ""js-*"""" // aid - represents app Id is configured via options to gitlab_ide_extension // eid - represents uuid for each emitted event event.add('eid', eventId); event.add('p', 'app'); event.add('tv', 'js-gitlab'); event.add('tna', 'gl'); event.add('aid', this.#options.appId); return preparePayload(event.build()); }), }; const config = { headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(data), }; const response = await this.#lsFetch.post(url, config); if (response.status !== 200) { log.warn( `Could not send telemetry to snowplow, this warning can be safely ignored. status=${response.status}`, ); } } catch (error) { let errorHandled = false; if (typeof error === 'object' && 'errno' in (error as object)) { const errObject = error as object; // ENOTFOUND occurs when the snowplow hostname cannot be resolved. if ('errno' in errObject && errObject.errno === 'ENOTFOUND') { this.disabled = true; errorHandled = true; log.info('Disabling telemetry, unable to resolve endpoint address.'); } else { log.warn(JSON.stringify(errObject)); } } if (!errorHandled) { log.warn('Failed to send telemetry event, this warning can be safely ignored'); log.warn(JSON.stringify(error)); } } } public async trackStructEvent( event: StructuredEvent, context?: SelfDescribingJson[] | null, ): Promise { this.#tracker.track(buildStructEvent(event), context); } async stop() { await this.#emitter.stop(); } public destroy() { Snowplow.#instance = undefined; } } References:" You are a code assistant,Definition of 'GitLabVersionResponse' in file packages/webview_duo_chat/src/plugin/port/gilab/check_version.ts in project gitlab-lsp,"Definition: export type GitLabVersionResponse = { version: string; enterprise?: boolean; }; export const versionRequest: ApiRequest = { type: 'rest', method: 'GET', path: '/version', }; References:" You are a code assistant,Definition of 'getItem' in file src/common/ai_context_management_2/ai_context_manager.ts in project gitlab-lsp,"Definition: getItem(id: string): AiContextItem | undefined { return this.#items.get(id); } currentItems(): AiContextItem[] { return Array.from(this.#items.values()); } async retrieveItems(): Promise { const items = Array.from(this.#items.values()); log.info(`Retrieving ${items.length} items`); const retrievedItems = await Promise.all( items.map(async (item) => { try { switch (item.type) { case 'file': { const content = await this.#fileRetriever.retrieve(item); return content ? { ...item, content } : null; } default: throw new Error(`Unknown item type: ${item.type}`); } } catch (error) { log.error(`Failed to retrieve item ${item.id}`, error); return null; } }), ); return retrievedItems.filter((item) => item !== null); } } References:" You are a code assistant,Definition of 'API_ERROR_NOTIFICATION' in file src/common/circuit_breaker/circuit_breaker.ts in project gitlab-lsp,"Definition: export const API_ERROR_NOTIFICATION = '$/gitlab/api/error'; export const API_RECOVERY_NOTIFICATION = '$/gitlab/api/recovered'; export enum CircuitBreakerState { OPEN = 'Open', CLOSED = 'Closed', } export interface CircuitBreaker { error(): void; success(): void; isOpen(): boolean; onOpen(listener: () => void): Disposable; onClose(listener: () => void): Disposable; } References:" You are a code assistant,Definition of 'sendTextDocumentDidOpen' in file src/tests/int/lsp_client.ts in project gitlab-lsp,"Definition: public async sendTextDocumentDidOpen( uri: string, languageId: string, version: number, text: string, ): Promise { const params = { textDocument: { uri, languageId, version, text, }, }; const request = new NotificationType('textDocument/didOpen'); await this.#connection.sendNotification(request, params); } public async sendTextDocumentDidClose(uri: string): Promise { const params = { textDocument: { uri, }, }; const request = new NotificationType('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 { const params = { textDocument: { uri, version, }, contentChanges: [{ text }], }; const request = new NotificationType('textDocument/didChange'); await this.#connection.sendNotification(request, params); } public async sendTextDocumentCompletion( uri: string, line: number, character: number, ): Promise { 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 { await this.#connection.sendNotification(DidChangeDocumentInActiveEditor, uri); } public async getWebviewMetadata(): Promise { const result = await this.#connection.sendRequest( '$/gitlab/webview-metadata', ); return result; } } References:" You are a code assistant,Definition of 'getEmptyFunctionResolver' in file src/common/tree_sitter/empty_function/empty_function_resolver.ts in project gitlab-lsp,"Definition: export function getEmptyFunctionResolver(): EmptyFunctionResolver { if (!emptyFunctionResolver) { emptyFunctionResolver = new EmptyFunctionResolver(); } return emptyFunctionResolver; } References: - src/common/tree_sitter/empty_function/empty_function_resolver.test.ts:142 - src/common/tree_sitter/empty_function/empty_function_resolver.test.ts:141 - src/common/tree_sitter/intent_resolver.ts:37" You are a code assistant,Definition of 'constructor' in file packages/lib_webview/src/setup/plugin/webview_instance_message_bus.ts in project gitlab-lsp,"Definition: 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 { 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); } 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 'VSCodeBuffer' in file packages/webview_duo_chat/src/plugin/port/platform/web_ide.ts in project gitlab-lsp,"Definition: 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; } /** * 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; headers?: Record; } export interface GetRequest<_TReturnType> extends GetRequestBase<_TReturnType> { type: 'rest'; } export interface GetBufferRequest extends GetRequestBase { type: 'rest-buffer'; } export interface GraphQLRequest<_TReturnType> { type: 'graphql'; query: string; /** Options passed to the GraphQL query */ variables: Record; } 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; /* 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 'redactSecrets' in file src/common/secret_redaction/index.ts in project gitlab-lsp,"Definition: 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:" You are a code assistant,Definition of 'setupWebviewRuntime' in file packages/lib_webview/src/setup/setup_webview_runtime.ts in project gitlab-lsp,"Definition: export function setupWebviewRuntime(props: SetupWebviewRuntimeProps): Disposable { const logger = withPrefix(props.logger, '[Webview]'); logger.debug('Setting up webview runtime'); try { const runtimeMessageBus = new WebviewRuntimeMessageBus(); const transportDisposable = setupTransports(props.transports, runtimeMessageBus, logger); const webviewPluginDisposable = setupWebviewPlugins({ runtimeMessageBus, logger, plugins: props.plugins, extensionMessageBusProvider: props.extensionMessageBusProvider, }); logger.info('Webview runtime setup completed successfully'); return { dispose: () => { logger.debug('Disposing webview runtime'); transportDisposable.dispose(); webviewPluginDisposable.dispose(); logger.info('Webview runtime disposed'); }, }; } catch (error) { props.logger.error( 'Failed to setup webview runtime', error instanceof Error ? error : undefined, ); return { dispose: () => { logger.debug('Disposing empty webview runtime due to setup failure'); }, }; } } References: - src/node/main.ts:228" You are a code assistant,Definition of 'WebviewAddress' in file packages/lib_webview_transport/src/types.ts in project gitlab-lsp,"Definition: export type WebviewAddress = { webviewId: WebviewId; webviewInstanceId: WebviewInstanceId; }; export type WebviewRequestInfo = { requestId: string; }; export type WebviewEventInfo = { type: string; payload?: unknown; }; export type WebviewInstanceCreatedEventData = WebviewAddress; export type WebviewInstanceDestroyedEventData = WebviewAddress; export type WebviewInstanceNotificationEventData = WebviewAddress & WebviewEventInfo; export type WebviewInstanceRequestEventData = WebviewAddress & WebviewEventInfo & WebviewRequestInfo; export type SuccessfulResponse = { success: true; }; export type FailedResponse = { success: false; reason: string; }; export type WebviewInstanceResponseEventData = WebviewAddress & WebviewRequestInfo & WebviewEventInfo & (SuccessfulResponse | FailedResponse); export type MessagesToServer = { webview_instance_created: WebviewInstanceCreatedEventData; webview_instance_destroyed: WebviewInstanceDestroyedEventData; webview_instance_notification_received: WebviewInstanceNotificationEventData; webview_instance_request_received: WebviewInstanceRequestEventData; webview_instance_response_received: WebviewInstanceResponseEventData; }; export type MessagesToClient = { webview_instance_notification: WebviewInstanceNotificationEventData; webview_instance_request: WebviewInstanceRequestEventData; webview_instance_response: WebviewInstanceResponseEventData; }; export interface TransportMessageHandler { (payload: T): void; } export interface TransportListener { on( type: K, callback: TransportMessageHandler, ): Disposable; } export interface TransportPublisher { publish(type: K, payload: MessagesToClient[K]): Promise; } export interface Transport extends TransportListener, TransportPublisher {} References: - packages/lib_webview/src/setup/plugin/utils/filters.ts:10 - packages/lib_webview/src/setup/plugin/webview_controller.test.ts:15 - packages/lib_webview/src/setup/transport/utils/setup_transport_event_handlers.ts:16 - packages/lib_webview/src/setup/plugin/webview_instance_message_bus.ts:18 - packages/lib_webview/src/events/webview_runtime_message_bus.ts:31 - packages/lib_webview/src/setup/transport/utils/setup_transport_event_handlers.ts:12 - packages/lib_webview/src/setup/plugin/webview_instance_message_bus.test.ts:8 - packages/lib_webview/src/setup/plugin/webview_controller.test.ts:175 - packages/lib_webview/src/events/webview_runtime_message_bus.ts:30 - packages/lib_webview/src/setup/plugin/webview_controller.test.ts:219 - packages/lib_webview/src/setup/plugin/webview_controller.ts:112 - packages/lib_webview/src/setup/plugin/webview_instance_message_bus.test.ts:331 - packages/lib_webview/src/setup/plugin/webview_controller.ts:21 - packages/lib_webview/src/setup/plugin/webview_controller.ts:88 - packages/lib_webview/src/setup/plugin/webview_instance_message_bus.test.ts:15 - packages/lib_webview/src/setup/plugin/webview_instance_message_bus.ts:33 - packages/lib_webview/src/setup/plugin/setup_plugins.ts:30" You are a code assistant,Definition of 'fetchBufferFromApi' in file packages/webview_duo_chat/src/plugin/port/platform/web_ide.ts in project gitlab-lsp,"Definition: export type fetchBufferFromApi = (request: GetBufferRequest) => Promise; /* 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 'waitMs' in file src/common/suggestion/suggestion_service.ts in project gitlab-lsp,"Definition: 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 => { 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 => { 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 => { 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 { 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 { 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 { 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 { 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 { 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/suggestion/suggestion_service.ts:232" You are a code assistant,Definition of 'greet' in file src/tests/fixtures/intent/empty_function/python.py in project gitlab-lsp,"Definition: 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:1 - src/tests/fixtures/intent/ruby_comments.rb:21 - src/tests/fixtures/intent/empty_function/ruby.rb:20 - src/tests/fixtures/intent/empty_function/ruby.rb:29" You are a code assistant,Definition of 'SuggestionCacheContext' in file src/common/suggestion/suggestions_cache.ts in project gitlab-lsp,"Definition: export type SuggestionCacheContext = { document: TextDocumentIdentifier; context: IDocContext; position: Position; additionalContexts?: AdditionalContext[]; }; export type SuggestionCache = { options: SuggestionOption[]; additionalContexts?: AdditionalContext[]; }; function isNonEmptyLine(s: string) { return s.trim().length > 0; } type Required = { [P in keyof T]-?: T[P]; }; const DEFAULT_CONFIG: Required = { enabled: true, maxSize: 1024 * 1024, ttl: 60 * 1000, prefixLines: 1, suffixLines: 1, }; export class SuggestionsCache { #cache: LRUCache; #configService: ConfigService; constructor(configService: ConfigService) { this.#configService = configService; const currentConfig = this.#getCurrentConfig(); this.#cache = new LRUCache({ 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 { 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: - src/common/suggestion/suggestions_cache.ts:126 - src/common/suggestion/suggestions_cache.test.ts:16 - src/common/suggestion/suggestions_cache.ts:73 - src/common/suggestion/suggestions_cache.ts:109" You are a code assistant,Definition of '_DeepPartial' in file packages/webview_duo_chat/src/plugin/port/test_utils/create_fake_partial.ts in project gitlab-lsp,"Definition: type _DeepPartial = T extends Function ? T : T extends Array ? _DeepPartialArray : T extends object ? // eslint-disable-next-line no-use-before-define DeepPartial : T | undefined; type DeepPartial = { [P in keyof T]?: _DeepPartial }; export const createFakePartial = (x: DeepPartial): T => x as T; References:" You are a code assistant,Definition of 'GITLAB_DEVELOPMENT_URL' in file packages/webview_duo_chat/src/plugin/port/chat/get_platform_manager_for_chat.ts in project gitlab-lsp,"Definition: export const GITLAB_DEVELOPMENT_URL: string = 'http://localhost'; export enum GitLabEnvironment { GITLAB_COM = 'production', GITLAB_STAGING = 'staging', GITLAB_ORG = 'org', GITLAB_DEVELOPMENT = 'development', GITLAB_SELF_MANAGED = 'self-managed', } export class GitLabPlatformManagerForChat { readonly #platformManager: GitLabPlatformManager; constructor(platformManager: GitLabPlatformManager) { this.#platformManager = platformManager; } async getProjectGqlId(): Promise { const projectManager = await this.#platformManager.getForActiveProject(false); return projectManager?.project.gqlId; } /** * Obtains a GitLab Platform to send API requests to the GitLab API * for the Duo Chat feature. * * - It returns a GitLabPlatformForAccount for the first linked account. * - It returns undefined if there are no accounts linked */ async getGitLabPlatform(): Promise { const platforms = await this.#platformManager.getForAllAccounts(); if (!platforms.length) { return undefined; } let platform: GitLabPlatformForAccount | undefined; // Using a for await loop in this context because we want to stop // evaluating accounts as soon as we find one with code suggestions enabled for await (const result of platforms.map(getChatSupport)) { if (result.hasSupportForChat) { platform = result.platform; break; } } return platform; } async getGitLabEnvironment(): Promise { const platform = await this.getGitLabPlatform(); const instanceUrl = platform?.account.instanceUrl; switch (instanceUrl) { case GITLAB_COM_URL: return GitLabEnvironment.GITLAB_COM; case GITLAB_DEVELOPMENT_URL: return GitLabEnvironment.GITLAB_DEVELOPMENT; case GITLAB_STAGING_URL: return GitLabEnvironment.GITLAB_STAGING; case GITLAB_ORG_URL: return GitLabEnvironment.GITLAB_ORG; default: return GitLabEnvironment.GITLAB_SELF_MANAGED; } } } References:" You are a code assistant,Definition of 'connectToCable' in file packages/webview_duo_chat/src/plugin/chat_platform.ts in project gitlab-lsp,"Definition: connectToCable(): Promise { return this.#client.connectToCable(); } getUserAgentHeader(): Record { return {}; } } 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: - src/common/action_cable.test.ts:32 - src/common/action_cable.test.ts:21 - src/common/action_cable.test.ts:40 - src/common/api.ts:348 - src/common/action_cable.test.ts:54" You are a code assistant,Definition of 'error' in file src/common/circuit_breaker/fixed_time_circuit_breaker.ts in project gitlab-lsp,"Definition: 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: - 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 'messageBus' in file packages/webview_duo_chat/src/app/message_bus.ts in project gitlab-lsp,"Definition: export const messageBus = resolveMessageBus<{ inbound: Messages['pluginToWebview']; outbound: Messages['webviewToPlugin']; }>({ webviewId: WEBVIEW_ID, }); References:" You are a code assistant,Definition of 'DefaultDocumentService' in file src/common/document_service.ts in project gitlab-lsp,"Definition: export class DefaultDocumentService implements DocumentService, HandlesNotification { #subscriptions: Disposable[] = []; #emitter = new EventEmitter(); #documents: TextDocuments; constructor(documents: TextDocuments) { 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 = { document }; this.#emitter.emit( DOCUMENT_CHANGE_EVENT_NAME, event, TextDocumentChangeListenerType.onDidSetActive, ); }; #createMediatorListener = (type: TextDocumentChangeListenerType) => (event: TextDocumentChangeEvent) => { 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/document_service.test.ts:54 - src/common/document_service.test.ts:18 - src/common/document_service.test.ts:34 - src/browser/main.ts:76 - src/common/document_service.test.ts:50 - src/node/main.ts:117" You are a code assistant,Definition of 'greet' in file src/tests/fixtures/intent/empty_function/python.py in project gitlab-lsp,"Definition: def greet(name): pass def greet2(name): print(name) class Greet: def __init__(self, name): pass def greet(self): pass 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: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 'PersonalAccessToken' in file src/common/api.ts in project gitlab-lsp,"Definition: export interface PersonalAccessToken { name: string; scopes: string[]; active: boolean; } export interface OAuthToken { scope: string[]; } export interface TokenCheckResponse { valid: boolean; reason?: 'unknown' | 'not_active' | 'invalid_scopes'; message?: string; } export interface IDirectConnectionDetailsHeaders { 'X-Gitlab-Global-User-Id': string; 'X-Gitlab-Instance-Id': string; 'X-Gitlab-Host-Name': string; 'X-Gitlab-Saas-Duo-Pro-Namespace-Ids': string; } export interface IDirectConnectionModelDetails { model_provider: string; model_name: string; } export interface IDirectConnectionDetails { base_url: string; token: string; expires_at: number; headers: IDirectConnectionDetailsHeaders; model_details: IDirectConnectionModelDetails; } const CONFIG_CHANGE_EVENT_NAME = 'apiReconfigured'; @Injectable(GitLabApiClient, [LsFetch, ConfigService]) export class GitLabAPI implements GitLabApiClient { #token: string | undefined; #baseURL: string; #clientInfo?: IClientInfo; #lsFetch: LsFetch; #eventEmitter = new EventEmitter(); #configService: ConfigService; #instanceVersion?: string; constructor(lsFetch: LsFetch, configService: ConfigService) { this.#baseURL = GITLAB_API_BASE_URL; this.#lsFetch = lsFetch; this.#configService = configService; this.#configService.onConfigChange(async (config) => { this.#clientInfo = configService.get('client.clientInfo'); this.#lsFetch.updateAgentOptions({ ignoreCertificateErrors: this.#configService.get('client.ignoreCertificateErrors') ?? false, ...(this.#configService.get('client.httpAgentOptions') ?? {}), }); await this.configureApi(config.client); }); } onApiReconfigured(listener: (data: ApiReconfiguredData) => void): Disposable { this.#eventEmitter.on(CONFIG_CHANGE_EVENT_NAME, listener); return { dispose: () => this.#eventEmitter.removeListener(CONFIG_CHANGE_EVENT_NAME, listener) }; } #fireApiReconfigured(isInValidState: boolean, validationMessage?: string) { const data: ApiReconfiguredData = { isInValidState, validationMessage }; this.#eventEmitter.emit(CONFIG_CHANGE_EVENT_NAME, data); } async configureApi({ token, baseUrl = GITLAB_API_BASE_URL, }: { token?: string; baseUrl?: string; }) { if (this.#token === token && this.#baseURL === baseUrl) return; this.#token = token; this.#baseURL = baseUrl; const { valid, reason, message } = await this.checkToken(this.#token); let validationMessage; if (!valid) { this.#configService.set('client.token', undefined); validationMessage = `Token is invalid. ${message}. Reason: ${reason}`; log.warn(validationMessage); } else { log.info('Token is valid'); } this.#instanceVersion = await this.#getGitLabInstanceVersion(); this.#fireApiReconfigured(valid, validationMessage); } #looksLikePatToken(token: string): boolean { // OAuth tokens will be longer than 42 characters and PATs will be shorter. return token.length < 42; } async #checkPatToken(token: string): Promise { const headers = this.#getDefaultHeaders(token); const response = await this.#lsFetch.get( `${this.#baseURL}/api/v4/personal_access_tokens/self`, { headers }, ); await handleFetchError(response, 'Information about personal access token'); const { active, scopes } = (await response.json()) as PersonalAccessToken; if (!active) { return { valid: false, reason: 'not_active', message: 'Token is not active.', }; } if (!this.#hasValidScopes(scopes)) { const joinedScopes = scopes.map((scope) => `'${scope}'`).join(', '); return { valid: false, reason: 'invalid_scopes', message: `Token has scope(s) ${joinedScopes} (needs 'api').`, }; } return { valid: true }; } async #checkOAuthToken(token: string): Promise { const headers = this.#getDefaultHeaders(token); const response = await this.#lsFetch.get(`${this.#baseURL}/oauth/token/info`, { headers, }); await handleFetchError(response, 'Information about OAuth token'); const { scope: scopes } = (await response.json()) as OAuthToken; if (!this.#hasValidScopes(scopes)) { const joinedScopes = scopes.map((scope) => `'${scope}'`).join(', '); return { valid: false, reason: 'invalid_scopes', message: `Token has scope(s) ${joinedScopes} (needs 'api').`, }; } return { valid: true }; } async checkToken(token: string = ''): Promise { try { if (this.#looksLikePatToken(token)) { log.info('Checking token for PAT validity'); return await this.#checkPatToken(token); } log.info('Checking token for OAuth validity'); return await this.#checkOAuthToken(token); } catch (err) { log.error('Error performing token check', err); return { valid: false, reason: 'unknown', message: `Failed to check token: ${err}`, }; } } #hasValidScopes(scopes: string[]): boolean { return scopes.includes('api'); } async getCodeSuggestions( request: CodeSuggestionRequest, ): Promise { if (!this.#token) { throw new Error('Token needs to be provided to request Code Suggestions'); } const headers = { ...this.#getDefaultHeaders(this.#token), 'Content-Type': 'application/json', }; const response = await this.#lsFetch.post( `${this.#baseURL}/api/v4/code_suggestions/completions`, { headers, body: JSON.stringify(request) }, ); await handleFetchError(response, 'Code Suggestions'); const data = await response.json(); return { ...data, status: response.status }; } async *getStreamingCodeSuggestions( request: CodeSuggestionRequest, ): AsyncGenerator { if (!this.#token) { throw new Error('Token needs to be provided to stream code suggestions'); } const headers = { ...this.#getDefaultHeaders(this.#token), 'Content-Type': 'application/json', }; yield* this.#lsFetch.streamFetch( `${this.#baseURL}/api/v4/code_suggestions/completions`, JSON.stringify(request), headers, ); } async fetchFromApi(request: ApiRequest): Promise { if (!this.#token) { return Promise.reject(new Error('Token needs to be provided to authorise API request.')); } if ( request.supportedSinceInstanceVersion && !this.#instanceVersionHigherOrEqualThen(request.supportedSinceInstanceVersion.version) ) { return Promise.reject( new InvalidInstanceVersionError( `Can't ${request.supportedSinceInstanceVersion.resourceName} until your instance is upgraded to ${request.supportedSinceInstanceVersion.version} or higher.`, ), ); } if (request.type === 'graphql') { return this.#graphqlRequest(request.query, request.variables); } switch (request.method) { case 'GET': return this.#fetch(request.path, request.searchParams, 'resource', request.headers); case 'POST': return this.#postFetch(request.path, 'resource', request.body, request.headers); default: // the type assertion is necessary because TS doesn't expect any other types throw new Error(`Unknown request type ${(request as ApiRequest).type}`); } } async connectToCable(): Promise { const headers = this.#getDefaultHeaders(this.#token); const websocketOptions = { headers: { ...headers, Origin: this.#baseURL, }, }; return connectToCable(this.#baseURL, websocketOptions); } async #graphqlRequest( document: RequestDocument, variables?: V, ): Promise { const ensureEndsWithSlash = (url: string) => url.replace(/\/?$/, '/'); const endpoint = new URL('./api/graphql', ensureEndsWithSlash(this.#baseURL)).href; // supports GitLab instances that are on a custom path, e.g. ""https://example.com/gitlab"" const graphqlFetch = async ( input: RequestInfo | URL, init?: RequestInit, ): Promise => { const url = input instanceof URL ? input.toString() : input; return this.#lsFetch.post(url, { ...init, headers: { ...headers, ...init?.headers }, }); }; const headers = this.#getDefaultHeaders(this.#token); const client = new GraphQLClient(endpoint, { headers, fetch: graphqlFetch, }); return client.request(document, variables); } async #fetch( apiResourcePath: string, query: Record = {}, resourceName = 'resource', headers?: Record, ): Promise { const url = `${this.#baseURL}/api/v4${apiResourcePath}${createQueryString(query)}`; const result = await this.#lsFetch.get(url, { headers: { ...this.#getDefaultHeaders(this.#token), ...headers }, }); await handleFetchError(result, resourceName); return result.json() as Promise; } async #postFetch( apiResourcePath: string, resourceName = 'resource', body?: unknown, headers?: Record, ): Promise { const url = `${this.#baseURL}/api/v4${apiResourcePath}`; const response = await this.#lsFetch.post(url, { headers: { 'Content-Type': 'application/json', ...this.#getDefaultHeaders(this.#token), ...headers, }, body: JSON.stringify(body), }); await handleFetchError(response, resourceName); return response.json() as Promise; } #getDefaultHeaders(token?: string) { return { Authorization: `Bearer ${token}`, 'User-Agent': `code-completions-language-server-experiment (${this.#clientInfo?.name}:${this.#clientInfo?.version})`, 'X-Gitlab-Language-Server-Version': getLanguageServerVersion(), }; } #instanceVersionHigherOrEqualThen(version: string): boolean { if (!this.#instanceVersion) return false; return semverCompare(this.#instanceVersion, version) >= 0; } async #getGitLabInstanceVersion(): Promise { if (!this.#token) { return ''; } const headers = this.#getDefaultHeaders(this.#token); const response = await this.#lsFetch.get(`${this.#baseURL}/api/v4/version`, { headers, }); const { version } = await response.json(); return version; } get instanceVersion() { return this.#instanceVersion; } } References:" You are a code assistant,Definition of 'processNewUserPrompt' in file packages/webview_duo_chat/src/plugin/port/chat/gitlab_chat_api.ts in project gitlab-lsp,"Definition: async processNewUserPrompt( question: string, subscriptionId?: string, currentFileContext?: GitLabChatFileContext, ): Promise { return this.#sendAiAction({ question, currentFileContext, clientSubscriptionId: subscriptionId, }); } async pullAiMessage(requestId: string, role: string): Promise { const response = await pullHandler(() => this.#getAiMessage(requestId, role)); if (!response) return errorResponse(requestId, ['Reached timeout while fetching response.']); return successResponse(response); } async cleanChat(): Promise { return this.#sendAiAction({ question: SPECIAL_MESSAGES.CLEAN }); } async #currentPlatform() { const platform = await this.#manager.getGitLabPlatform(); if (!platform) throw new Error('Platform is missing!'); return platform; } async #getAiMessage(requestId: string, role: string): Promise { const request: GraphQLRequest = { type: 'graphql', query: AI_MESSAGES_QUERY, variables: { requestIds: [requestId], roles: [role.toUpperCase()] }, }; const platform = await this.#currentPlatform(); const history = await platform.fetchFromApi(request); return history.aiMessages.nodes[0]; } async subscribeToUpdates( messageCallback: (message: AiCompletionResponseMessageType) => Promise, subscriptionId?: string, ) { const platform = await this.#currentPlatform(); const channel = new AiCompletionResponseChannel({ htmlResponse: true, userId: `gid://gitlab/User/${extractUserId(platform.account.id)}`, aiAction: 'CHAT', clientSubscriptionId: subscriptionId, }); const cable = await platform.connectToCable(); // we use this flag to fix https://gitlab.com/gitlab-org/gitlab-vscode-extension/-/issues/1397 // sometimes a chunk comes after the full message and it broke the chat let fullMessageReceived = false; channel.on('newChunk', async (msg) => { if (fullMessageReceived) { log.info(`CHAT-DEBUG: full message received, ignoring chunk`); return; } await messageCallback(msg); }); channel.on('fullMessage', async (message) => { fullMessageReceived = true; await messageCallback(message); if (subscriptionId) { cable.disconnect(); } }); cable.subscribe(channel); } async #sendAiAction(variables: object): Promise { const platform = await this.#currentPlatform(); const { query, defaultVariables } = await this.#actionQuery(); const projectGqlId = await this.#manager.getProjectGqlId(); const request: GraphQLRequest = { type: 'graphql', query, variables: { ...variables, ...defaultVariables, resourceId: projectGqlId ?? null, }, }; return platform.fetchFromApi(request); } async #actionQuery(): Promise { if (!this.#cachedActionQuery) { const platform = await this.#currentPlatform(); try { const { version } = await platform.fetchFromApi(versionRequest); this.#cachedActionQuery = ifVersionGte( version, MINIMUM_PLATFORM_ORIGIN_FIELD_VERSION, () => CHAT_INPUT_TEMPLATE_17_3_AND_LATER, () => CHAT_INPUT_TEMPLATE_17_2_AND_EARLIER, ); } catch (e) { log.debug(`GitLab version check for sending chat failed:`, e as Error); this.#cachedActionQuery = CHAT_INPUT_TEMPLATE_17_3_AND_LATER; } } return this.#cachedActionQuery; } } References:" You are a code assistant,Definition of 'details' in file src/common/fetch_error.ts in project gitlab-lsp,"Definition: 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:" You are a code assistant,Definition of 'DuoProjectStatus' in file src/common/services/duo_access/project_access_checker.ts in project gitlab-lsp,"Definition: export enum DuoProjectStatus { DuoEnabled = 'duo-enabled', DuoDisabled = 'duo-disabled', NonGitlabProject = 'non-gitlab-project', } export interface DuoProjectAccessChecker { checkProjectStatus(uri: string, workspaceFolder: WorkspaceFolder): DuoProjectStatus; } export const DuoProjectAccessChecker = createInterfaceId('DuoProjectAccessChecker'); @Injectable(DuoProjectAccessChecker, [DuoProjectAccessCache]) export class DefaultDuoProjectAccessChecker { #projectAccessCache: DuoProjectAccessCache; constructor(projectAccessCache: DuoProjectAccessCache) { this.#projectAccessCache = projectAccessCache; } /** * Check if Duo features are enabled for a given DocumentUri. * * We match the DocumentUri to the project with the longest path. * The enabled projects come from the `DuoProjectAccessCache`. * * @reference `DocumentUri` is the URI of the document to check. Comes from * the `TextDocument` object. */ 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: - src/common/services/duo_access/project_access_checker.ts:12 - src/common/services/duo_access/project_access_checker.ts:35" You are a code assistant,Definition of 'setupWebviewPluginsProps' in file packages/lib_webview/src/setup/plugin/setup_plugins.ts in project gitlab-lsp,"Definition: type setupWebviewPluginsProps = { plugins: WebviewPlugin[]; extensionMessageBusProvider: ExtensionMessageBusProvider; logger: Logger; runtimeMessageBus: WebviewRuntimeMessageBus; }; export function setupWebviewPlugins({ plugins, extensionMessageBusProvider, logger, runtimeMessageBus, }: setupWebviewPluginsProps) { logger.debug(`Setting up (${plugins.length}) plugins`); const compositeDisposable = new CompositeDisposable(); for (const plugin of plugins) { logger.debug(`Setting up plugin: ${plugin.id}`); const extensionMessageBus = extensionMessageBusProvider.getMessageBus(plugin.id); const webviewInstanceMessageBusFactory = (address: WebviewAddress) => { return new WebviewInstanceMessageBus(address, runtimeMessageBus, logger); }; const webviewController = new WebviewController( plugin.id, runtimeMessageBus, webviewInstanceMessageBusFactory, logger, ); const disposable = plugin.setup({ webview: webviewController, extension: extensionMessageBus, }); if (isDisposable(disposable)) { compositeDisposable.add(disposable); } } logger.debug('All plugins were set up successfully'); return compositeDisposable; } References: - packages/lib_webview/src/setup/plugin/setup_plugins.ts:21" You are a code assistant,Definition of 'ILog' in file src/common/log_types.ts in project gitlab-lsp,"Definition: export interface ILog { debug(e: Error): void; debug(message: string, e?: Error): void; 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; } 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: - src/node/http/create_fastify_http_server.ts:72 - src/node/http/create_fastify_http_server.test.ts:12 - src/node/http/utils/logger_with_prefix.ts:5 - src/node/http/create_fastify_http_server.ts:58 - src/node/http/utils/logger_with_prefix.test.ts:5 - src/node/http/create_fastify_http_server.ts:89 - src/node/http/utils/create_logger_transport.ts:4 - src/node/http/create_fastify_http_server.ts:9 - src/node/http/utils/create_logger_transport.test.ts:5" You are a code assistant,Definition of 'SuggestionModel' in file src/common/suggestion_client/suggestion_client.ts in project gitlab-lsp,"Definition: export interface SuggestionModel { lang: string; engine: string; name: string; } /** We request 4 options. That's maximum supported number of Google Vertex */ export const MANUAL_REQUEST_OPTIONS_COUNT = 4; export type OptionsCount = 1 | typeof MANUAL_REQUEST_OPTIONS_COUNT; export const GENERATION = 'generation'; export const COMPLETION = 'completion'; export type Intent = typeof GENERATION | typeof COMPLETION | undefined; export interface SuggestionContext { document: IDocContext; intent?: Intent; projectPath?: string; optionsCount?: OptionsCount; additionalContexts?: AdditionalContext[]; } export interface SuggestionResponse { choices?: SuggestionResponseChoice[]; model?: SuggestionModel; status: number; error?: string; isDirectConnection?: boolean; } export interface SuggestionResponseChoice { text: string; } export interface SuggestionClient { getSuggestions(context: SuggestionContext): Promise; } export type SuggestionClientFn = SuggestionClient['getSuggestions']; export type SuggestionClientMiddleware = ( context: SuggestionContext, next: SuggestionClientFn, ) => ReturnType; References: - src/common/suggestion_client/suggestion_client.ts:29" You are a code assistant,Definition of 'VirtualFileSystemService' in file src/common/services/fs/virtual_file_service.ts in project gitlab-lsp,"Definition: export type VirtualFileSystemService = typeof DefaultVirtualFileSystemService.prototype; export const VirtualFileSystemService = createInterfaceId( '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 { 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( 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/connection.ts:35 - src/common/message_handler.ts:87 - src/common/message_handler.ts:39" You are a code assistant,Definition of 'findNotificationHandler' in file packages/lib_webview_transport_json_rpc/src/json_rpc_connection_transport.test.ts in project gitlab-lsp,"Definition: function findNotificationHandler( connection: jest.Mocked, method: string, ): ((message: unknown) => void) | undefined { type NotificationCall = [string, (message: unknown) => void]; return (connection.onNotification.mock.calls as unknown as NotificationCall[]).find( ([notificationMethod]) => notificationMethod === method, )?.[1]; } References: - packages/lib_webview_transport_json_rpc/src/json_rpc_connection_transport.test.ts:57" You are a code assistant,Definition of 'FallbackClient' in file src/common/suggestion_client/fallback_client.ts in project gitlab-lsp,"Definition: export class FallbackClient implements SuggestionClient { #clients: SuggestionClient[]; constructor(...clients: SuggestionClient[]) { this.#clients = clients; } async getSuggestions(context: SuggestionContext) { for (const client of this.#clients) { // eslint-disable-next-line no-await-in-loop const result = await client.getSuggestions(context); if (result) { // TODO create a follow up issue to consider scenario when the result is defined, but it contains an error field return result; } } return undefined; } } References: - src/common/suggestion_client/fallback_client.test.ts:33 - src/common/suggestion_client/fallback_client.test.ts:18 - src/common/suggestion/suggestion_service.ts:160" 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 { return input; } } pipeline.addProcessor(new Processor1()); pipeline.addProcessor(new Processor2()); const streamInput: StreamingCompletionResponse = { id: '1', completion: 'test', done: false }; const result = await pipeline.run({ documentContext: mockContext, input: streamInput, type: 'stream', }); expect(result).toEqual({ id: '1', completion: 'test [1] [2]', done: false }); }); test('should chain multiple processors correctly for completion input', async () => { class Processor1 extends PostProcessor { async processStream( _context: IDocContext, input: StreamingCompletionResponse, ): Promise { return input; } async processCompletion( _context: IDocContext, input: SuggestionOption[], ): Promise { return input.map((option) => ({ ...option, text: `${option.text} [1]` })); } } class Processor2 extends PostProcessor { async processStream( _context: IDocContext, input: StreamingCompletionResponse, ): Promise { return input; } async processCompletion( _context: IDocContext, input: SuggestionOption[], ): Promise { return input.map((option) => ({ ...option, text: `${option.text} [2]` })); } } pipeline.addProcessor(new Processor1()); pipeline.addProcessor(new Processor2()); const completionInput: SuggestionOption[] = [{ text: 'option1', uniqueTrackingId: '1' }]; const result = await pipeline.run({ documentContext: mockContext, input: completionInput, type: 'completion', }); expect(result).toEqual([{ text: 'option1 [1] [2]', uniqueTrackingId: '1' }]); }); test('should throw an error for unexpected type', async () => { class TestProcessor extends PostProcessor { async processStream( _context: IDocContext, input: StreamingCompletionResponse, ): Promise { return input; } async processCompletion( _context: IDocContext, input: SuggestionOption[], ): Promise { 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 'constructor' in file src/common/tree_sitter/parser.ts in project gitlab-lsp,"Definition: constructor({ languages }: { languages: TreeSitterLanguageInfo[] }) { this.languages = this.buildTreeSitterInfoByExtMap(languages); this.loadState = TreeSitterParserLoadState.INIT; } get loadStateValue(): TreeSitterParserLoadState { return this.loadState; } async parseFile(context: IDocContext): Promise { 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 { 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 { 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 { return languages.reduce((map, language) => { for (const extension of language.extensions) { map.set(extension, language); } return map; }, new Map()); } } References:" You are a code assistant,Definition of 'register' in file src/common/webview/webview_resource_location_service.ts in project gitlab-lsp,"Definition: register(provider: WebviewUriProvider): void; } export class WebviewLocationService implements WebviewUriProviderRegistry { #uriProviders = new Set(); 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 'hasbinAll' in file src/tests/int/hasbin.ts in project gitlab-lsp,"Definition: export function hasbinAll(bins: string[], done: (result: boolean) => void) { async.every(bins, hasbin.async, done); } export function hasbinAllSync(bins: string[]) { return bins.every(hasbin.sync); } export function hasbinSome(bins: string[], done: (result: boolean) => void) { async.some(bins, hasbin.async, done); } export function hasbinSomeSync(bins: string[]) { return bins.some(hasbin.sync); } export function hasbinFirst(bins: string[], done: (result: boolean) => void) { async.detect(bins, hasbin.async, function (result) { done(result || false); }); } export function hasbinFirstSync(bins: string[]) { const matched = bins.filter(hasbin.sync); return matched.length ? matched[0] : false; } export function getPaths(bin: string) { const envPath = process.env.PATH || ''; const envExt = process.env.PATHEXT || ''; return envPath .replace(/[""]+/g, '') .split(delimiter) .map(function (chunk) { return envExt.split(delimiter).map(function (ext) { return join(chunk, bin + ext); }); }) .reduce(function (a, b) { return a.concat(b); }); } 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 'SOCKET_RESPONSE_CHANNEL' in file packages/lib_webview_client/src/bus/provider/socket_io_message_bus.ts in project gitlab-lsp,"Definition: export const SOCKET_RESPONSE_CHANNEL = 'response'; export type SocketEvents = | typeof SOCKET_NOTIFICATION_CHANNEL | typeof SOCKET_REQUEST_CHANNEL | typeof SOCKET_RESPONSE_CHANNEL; export class SocketIoMessageBus implements MessageBus { #notificationHandlers = new SimpleRegistry(); #requestHandlers = new SimpleRegistry(); #pendingRequests = new SimpleRegistry(); #socket: Socket; constructor(socket: Socket) { this.#socket = socket; this.#setupSocketEventHandlers(); } async sendNotification( messageType: T, payload?: TMessages['outbound']['notifications'][T], ): Promise { this.#socket.emit(SOCKET_NOTIFICATION_CHANNEL, { type: messageType, payload }); } sendRequest( type: T, payload?: TMessages['outbound']['requests'][T]['params'], ): Promise> { const requestId = generateRequestId(); let timeout: NodeJS.Timeout | undefined; return new Promise((resolve, reject) => { const pendingRequestDisposable = this.#pendingRequests.register( requestId, (value: ExtractRequestResult) => { resolve(value); clearTimeout(timeout); pendingRequestDisposable.dispose(); }, ); timeout = setTimeout(() => { pendingRequestDisposable.dispose(); reject(new Error('Request timed out')); }, REQUEST_TIMEOUT_MS); this.#socket.emit(SOCKET_REQUEST_CHANNEL, { requestId, type, payload, }); }); } onNotification( messageType: T, callback: (payload: TMessages['inbound']['notifications'][T]) => void, ): Disposable { return this.#notificationHandlers.register(messageType, callback); } onRequest( type: T, handler: ( payload: TMessages['inbound']['requests'][T]['params'], ) => Promise>, ): Disposable { return this.#requestHandlers.register(type, handler); } dispose() { this.#socket.off(SOCKET_NOTIFICATION_CHANNEL, this.#handleNotificationMessage); this.#socket.off(SOCKET_REQUEST_CHANNEL, this.#handleRequestMessage); this.#socket.off(SOCKET_RESPONSE_CHANNEL, this.#handleResponseMessage); this.#notificationHandlers.dispose(); this.#requestHandlers.dispose(); this.#pendingRequests.dispose(); } #setupSocketEventHandlers = () => { this.#socket.on(SOCKET_NOTIFICATION_CHANNEL, this.#handleNotificationMessage); this.#socket.on(SOCKET_REQUEST_CHANNEL, this.#handleRequestMessage); this.#socket.on(SOCKET_RESPONSE_CHANNEL, this.#handleResponseMessage); }; #handleNotificationMessage = async (message: { type: keyof TMessages['inbound']['notifications'] & string; payload: unknown; }) => { await this.#notificationHandlers.handle(message.type, message.payload); }; #handleRequestMessage = async (message: { requestId: string; event: keyof TMessages['inbound']['requests'] & string; payload: unknown; }) => { const response = await this.#requestHandlers.handle(message.event, message.payload); this.#socket.emit(SOCKET_RESPONSE_CHANNEL, { requestId: message.requestId, payload: response, }); }; #handleResponseMessage = async (message: { requestId: string; payload: unknown }) => { await this.#pendingRequests.handle(message.requestId, message.payload); }; } References:" You are a code assistant,Definition of 'dispose' in file src/common/feature_state/feature_state_manager.ts in project gitlab-lsp,"Definition: dispose() { this.#subscriptions.forEach((s) => s.dispose()); } get #state(): FeatureState[] { const engagedChecks = this.#checks.filter((check) => check.engaged); return getEntries(CHECKS_PER_FEATURE).map(([featureId, stateChecks]) => { const engagedFeatureChecks: FeatureStateCheck[] = engagedChecks .filter(({ id }) => stateChecks.includes(id)) .map((stateCheck) => ({ checkId: stateCheck.id, details: stateCheck.details, })); return { featureId, engagedChecks: engagedFeatureChecks, }; }); } } References:" You are a code assistant,Definition of 'update' in file packages/webview_duo_chat/src/plugin/port/chat/gitlab_chat_record.ts in project gitlab-lsp,"Definition: update(attributes: Partial) { const convertedAttributes = attributes as Partial; if (attributes.timestamp) { convertedAttributes.timestamp = Date.parse(attributes.timestamp); } Object.assign(this, convertedAttributes); } #detectType(): ChatRecordType { if (this.content === SPECIAL_MESSAGES.RESET) { return 'newConversation'; } return 'general'; } } References:" You are a code assistant,Definition of 'register' in file src/common/webview/webview_resource_location_service.ts in project gitlab-lsp,"Definition: 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 'TestMessageMap' in file packages/lib_webview_client/src/bus/provider/socket_io_message_bus.test.ts in project gitlab-lsp,"Definition: interface TestMessageMap extends MessageMap { inbound: { notifications: { testNotification: string; }; requests: { testRequest: { params: number; result: string; }; }; }; outbound: { notifications: { testOutboundNotification: boolean; }; requests: { testOutboundRequest: { params: string; result: number; }; }; }; } const TEST_REQUEST_ID = 'mock-request-id'; describe('SocketIoMessageBus', () => { let mockSocket: jest.Mocked; let messageBus: SocketIoMessageBus; beforeEach(() => { jest.useFakeTimers(); jest.mocked(generateRequestId).mockReturnValue(TEST_REQUEST_ID); mockSocket = { emit: jest.fn(), on: jest.fn(), off: jest.fn(), } as unknown as jest.Mocked; messageBus = new SocketIoMessageBus(mockSocket); }); afterEach(() => { jest.useRealTimers(); }); describe('sendNotification', () => { it('should emit a notification event', async () => { // Arrange const messageType = 'testOutboundNotification'; const payload = true; // Act await messageBus.sendNotification(messageType, payload); // Assert expect(mockSocket.emit).toHaveBeenCalledWith('notification', { type: messageType, payload, }); }); }); describe('sendRequest', () => { it('should emit a request event and resolve with the response', async () => { // Arrange const messageType = 'testOutboundRequest'; const payload = 'test'; const response = 42; // Act const promise = messageBus.sendRequest(messageType, payload); // Simulate response const handleResponse = getSocketEventHandler(mockSocket, SOCKET_RESPONSE_CHANNEL); handleResponse({ requestId: TEST_REQUEST_ID, payload: response }); // Assert await expect(promise).resolves.toBe(response); expect(mockSocket.emit).toHaveBeenCalledWith('request', { requestId: TEST_REQUEST_ID, type: messageType, payload, }); }); it('should reject if the request times out', async () => { // Arrange const messageType = 'testOutboundRequest'; const payload = 'test'; // Act const promise = messageBus.sendRequest(messageType, payload); // Simulate timeout jest.advanceTimersByTime(REQUEST_TIMEOUT_MS); // Assert await expect(promise).rejects.toThrow('Request timed out'); }); }); describe('onNotification', () => { it('should register a notification handler', () => { // Arrange const messageType = 'testNotification'; const handler = jest.fn(); // Act messageBus.onNotification(messageType, handler); // Simulate incoming notification const handleNotification = getSocketEventHandler(mockSocket, SOCKET_NOTIFICATION_CHANNEL); handleNotification({ type: messageType, payload: 'test' }); // Assert expect(handler).toHaveBeenCalledWith('test'); }); }); describe('onRequest', () => { it('should register a request handler', async () => { // Arrange const messageType = 'testRequest'; const handler = jest.fn().mockResolvedValue('response'); // Act messageBus.onRequest(messageType, handler); // Simulate incoming request const handleRequest = getSocketEventHandler(mockSocket, SOCKET_REQUEST_CHANNEL); await handleRequest({ requestId: 'test-id', event: messageType, payload: 42, }); // Assert expect(handler).toHaveBeenCalledWith(42); expect(mockSocket.emit).toHaveBeenCalledWith('response', { requestId: 'test-id', payload: 'response', }); }); }); describe('dispose', () => { it('should remove all event listeners', () => { // Act messageBus.dispose(); // Assert expect(mockSocket.off).toHaveBeenCalledTimes(3); expect(mockSocket.off).toHaveBeenCalledWith('notification', expect.any(Function)); expect(mockSocket.off).toHaveBeenCalledWith('request', expect.any(Function)); expect(mockSocket.off).toHaveBeenCalledWith('response', expect.any(Function)); }); }); }); // eslint-disable-next-line @typescript-eslint/ban-types function getSocketEventHandler(socket: jest.Mocked, eventName: SocketEvents): Function { const [, handler] = socket.on.mock.calls.find((call) => call[0] === eventName)!; return handler; } References:" You are a code assistant,Definition of 'FastifyPluginRegistration' in file src/node/http/types.ts in project gitlab-lsp,"Definition: export type FastifyPluginRegistration< TPluginOptions extends FastifyPluginOptions = FastifyPluginOptions, > = { plugin: FastifyPluginAsync; options?: TPluginOptions; }; References: - src/node/webview/webview_fastify_middleware.ts:12" You are a code assistant,Definition of 'createViteConfigForWebview' in file packages/lib_vite_common_config/vite.config.shared.ts in project gitlab-lsp,"Definition: export function createViteConfigForWebview(name): UserConfig { const outDir = path.resolve(__dirname, `../../../../out/webviews/${name}`); return { plugins: [vue2(), InlineSvgPlugin, SyncLoadScriptsPlugin, HtmlTransformPlugin], resolve: { alias: { '@': fileURLToPath(new URL('./src/app', import.meta.url)), }, }, root: './src/app', base: '', build: { target: 'es2022', emptyOutDir: true, outDir, rollupOptions: { input: [path.join('src', 'app', 'index.html')], }, }, }; } References: - packages/webview_duo_workflow/vite.config.ts:4 - packages/webview_duo_chat/vite.config.ts:4" You are a code assistant,Definition of 'build' in file scripts/esbuild/desktop.ts in project gitlab-lsp,"Definition: async function build() { await esbuild.build(config); } void build(); References: - scripts/esbuild/common.ts:31 - scripts/esbuild/browser.ts:26 - scripts/esbuild/desktop.ts:41" You are a code assistant,Definition of 'Greet4' in file src/tests/fixtures/intent/empty_function/python.py in project gitlab-lsp,"Definition: 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:" You are a code assistant,Definition of 'getTextAfterSelected' in file packages/webview_duo_chat/src/plugin/port/chat/utils/editor_text_utils.ts in project gitlab-lsp,"Definition: export const getTextAfterSelected = (): string | null => { return null; // const editor = vscode.window.activeTextEditor; // if (!editor || !editor.selection || editor.selection.isEmpty) return null; // const { selection, document } = editor; // const { line: lineNum, character: charNum } = selection.end; // const isLastCharOnLineSelected = charNum === document.lineAt(lineNum).range.end.character; // const isLastLine = lineNum === document.lineCount; // const getStartLine = () => { // if (isLastCharOnLineSelected) { // if (isLastLine) { // return lineNum; // } // return lineNum + 1; // } // return lineNum; // }; // const getStartChar = () => { // if (isLastCharOnLineSelected) { // if (isLastLine) { // return charNum; // } // return 0; // } // return charNum + 1; // }; // const selectionRange = new vscode.Range( // getStartLine(), // getStartChar(), // document.lineCount, // document.lineAt(document.lineCount - 1).range.end.character, // ); // return editor.document.getText(selectionRange); }; References: - packages/webview_duo_chat/src/plugin/port/chat/gitlab_chat_file_context.ts:27" You are a code assistant,Definition of 'a' in file packages/lib_di/src/index.test.ts in project gitlab-lsp,"Definition: a(): string; } interface B { b(): string; } interface C { c(): string; } const A = createInterfaceId('A'); const B = createInterfaceId('B'); const C = createInterfaceId('C'); @Injectable(A, []) class AImpl implements A { a = () => 'a'; } @Injectable(B, [A]) class BImpl implements B { #a: A; constructor(a: A) { this.#a = a; } b = () => `B(${this.#a.a()})`; } @Injectable(C, [A, B]) class CImpl implements C { #a: A; #b: B; constructor(a: A, b: B) { this.#a = a; this.#b = b; } c = () => `C(${this.#b.b()}, ${this.#a.a()})`; } let container: Container; beforeEach(() => { container = new Container(); }); describe('addInstances', () => { const O = createInterfaceId('object'); it('fails if the instance is not branded', () => { expect(() => container.addInstances({ say: 'hello' } as BrandedInstance)).toThrow( /invoked without branded object/, ); }); it('fails if the instance is already present', () => { const a = brandInstance(O, { a: 'a' }); const b = brandInstance(O, { b: 'b' }); expect(() => container.addInstances(a, b)).toThrow(/this ID is already in the container/); }); it('adds instance', () => { const instance = { a: 'a' }; const a = brandInstance(O, instance); container.addInstances(a); expect(container.get(O)).toBe(instance); }); }); describe('instantiate', () => { it('can instantiate three classes A,B,C', () => { container.instantiate(AImpl, BImpl, CImpl); const cInstance = container.get(C); expect(cInstance.c()).toBe('C(B(a), a)'); }); it('instantiates dependencies in multiple instantiate calls', () => { container.instantiate(AImpl); // the order is important for this test // we want to make sure that the stack in circular dependency discovery is being cleared // to try why this order is necessary, remove the `inStack.delete()` from // the `if (!cwd && instanceIds.includes(id))` condition in prod code expect(() => container.instantiate(CImpl, BImpl)).not.toThrow(); }); it('detects duplicate ids', () => { @Injectable(A, []) 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: - src/tests/fixtures/intent/ruby_comments.rb:14" You are a code assistant,Definition of 'CIRCUIT_BREAK_INTERVAL_MS' in file src/common/circuit_breaker/circuit_breaker.ts in project gitlab-lsp,"Definition: export const CIRCUIT_BREAK_INTERVAL_MS = 10000; export const MAX_ERRORS_BEFORE_CIRCUIT_BREAK = 4; export const API_ERROR_NOTIFICATION = '$/gitlab/api/error'; export const API_RECOVERY_NOTIFICATION = '$/gitlab/api/recovered'; export enum CircuitBreakerState { OPEN = 'Open', CLOSED = 'Closed', } export interface CircuitBreaker { error(): void; success(): void; isOpen(): boolean; onOpen(listener: () => void): Disposable; onClose(listener: () => void): Disposable; } References:" You are a code assistant,Definition of 'error' in file packages/lib_logging/src/null_logger.ts in project gitlab-lsp,"Definition: error(): void { // NOOP } } References: - scripts/commit-lint/lint.js:72 - scripts/commit-lint/lint.js:77 - scripts/commit-lint/lint.js:85 - scripts/commit-lint/lint.js:94" You are a code assistant,Definition of 'constructor' in file src/common/suggestion_client/fallback_client.ts in project gitlab-lsp,"Definition: constructor(...clients: SuggestionClient[]) { this.#clients = clients; } async getSuggestions(context: SuggestionContext) { for (const client of this.#clients) { // eslint-disable-next-line no-await-in-loop const result = await client.getSuggestions(context); if (result) { // TODO create a follow up issue to consider scenario when the result is defined, but it contains an error field return result; } } return undefined; } } References:" You are a code assistant,Definition of 'getUserAgentHeader' in file packages/webview_duo_chat/src/plugin/port/platform/gitlab_platform.ts in project gitlab-lsp,"Definition: getUserAgentHeader(): Record; } export interface GitLabPlatformForAccount extends GitLabPlatformBase { type: 'account'; project: undefined; } export interface GitLabPlatformForProject extends GitLabPlatformBase { type: 'project'; project: GitLabProject; } export type GitLabPlatform = GitLabPlatformForProject | GitLabPlatformForAccount; 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; /** * 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; /** * 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; getForAllAccounts(): Promise; /** * Returns GitLabPlatformForAccount if there is a SaaS account added. Otherwise returns undefined. */ getForSaaSAccount(): Promise; } References:" You are a code assistant,Definition of 'Greet' in file src/tests/fixtures/intent/empty_function/go.go in project gitlab-lsp,"Definition: type Greet struct { name string } // empty method declaration func (g Greet) greet() { } // non-empty method declaration func (g Greet) greet() { fmt.Printf(""Hello %s\n"", g.name) } References: - src/tests/fixtures/intent/go_comments.go:24 - 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" You are a code assistant,Definition of 'getTextBeforeSelected' in file packages/webview_duo_chat/src/plugin/port/chat/utils/editor_text_utils.ts in project gitlab-lsp,"Definition: export const getTextBeforeSelected = (): string | null => { return null; // const editor = vscode.window.activeTextEditor; // if (!editor || !editor.selection || editor.selection.isEmpty) return null; // const { selection, document } = editor; // const { line: lineNum, character: charNum } = selection.start; // const isFirstCharOnLineSelected = charNum === 0; // const isFirstLine = lineNum === 0; // const getEndLine = () => { // if (isFirstCharOnLineSelected) { // if (isFirstLine) { // return lineNum; // } // return lineNum - 1; // } // return lineNum; // }; // const getEndChar = () => { // if (isFirstCharOnLineSelected) { // if (isFirstLine) { // return 0; // } // return document.lineAt(lineNum - 1).range.end.character; // } // return charNum - 1; // }; // const selectionRange = new vscode.Range(0, 0, getEndLine(), getEndChar()); // return editor.document.getText(selectionRange); }; export const getTextAfterSelected = (): string | null => { return null; // const editor = vscode.window.activeTextEditor; // if (!editor || !editor.selection || editor.selection.isEmpty) return null; // const { selection, document } = editor; // const { line: lineNum, character: charNum } = selection.end; // const isLastCharOnLineSelected = charNum === document.lineAt(lineNum).range.end.character; // const isLastLine = lineNum === document.lineCount; // const getStartLine = () => { // if (isLastCharOnLineSelected) { // if (isLastLine) { // return lineNum; // } // return lineNum + 1; // } // return lineNum; // }; // const getStartChar = () => { // if (isLastCharOnLineSelected) { // if (isLastLine) { // return charNum; // } // return 0; // } // return charNum + 1; // }; // const selectionRange = new vscode.Range( // getStartLine(), // getStartChar(), // document.lineCount, // document.lineAt(document.lineCount - 1).range.end.character, // ); // return editor.document.getText(selectionRange); }; References: - packages/webview_duo_chat/src/plugin/port/chat/gitlab_chat_file_context.ts:26" You are a code assistant,Definition of 'MessageBusProvider' in file packages/lib_webview_client/src/bus/provider/types.ts in project gitlab-lsp,"Definition: export interface MessageBusProvider { name: string; getMessageBus(webviewId: string): MessageBus | null; } References: - packages/lib_webview_client/src/bus/resolve_message_bus.ts:30" You are a code assistant,Definition of 'SuggestionsCache' in file src/common/suggestion/suggestions_cache.ts in project gitlab-lsp,"Definition: export class SuggestionsCache { #cache: LRUCache; #configService: ConfigService; constructor(configService: ConfigService) { this.#configService = configService; const currentConfig = this.#getCurrentConfig(); this.#cache = new LRUCache({ 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 { 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: - src/common/suggestion/suggestions_cache.test.ts:42 - src/common/suggestion/suggestion_service.ts:156 - src/common/suggestion/suggestion_service.ts:131 - src/common/suggestion/suggestions_cache.test.ts:50" You are a code assistant,Definition of 'InitializeHandler' in file src/common/core/handlers/initialize_handler.ts in project gitlab-lsp,"Definition: export interface InitializeHandler extends HandlesRequest {} export const InitializeHandler = createInterfaceId('InitializeHandler'); @Injectable(InitializeHandler, [ConfigService]) export class DefaultInitializeHandler implements InitializeHandler { #configService: ConfigService; constructor(configService: ConfigService) { this.#configService = configService; } requestHandler: RequestHandler = ( params: CustomInitializeParams, ): InitializeResult => { const { clientInfo, initializationOptions, workspaceFolders } = params; this.#configService.set('client.clientInfo', clientInfo); this.#configService.set('client.workspaceFolders', workspaceFolders); this.#configService.set('client.baseAssetsUrl', initializationOptions?.baseAssetsUrl); this.#configService.set('client.telemetry.ide', initializationOptions?.ide ?? clientInfo); this.#configService.set('client.telemetry.extension', initializationOptions?.extension); return { capabilities: { completionProvider: { resolveProvider: true, }, inlineCompletionProvider: true, textDocumentSync: TextDocumentSyncKind.Full, }, }; }; } References: - src/common/core/handlers/initialize_handler.test.ts:16 - src/common/connection_service.ts:62" You are a code assistant,Definition of 'getIntent' in file src/common/tree_sitter/intent_resolver.ts in project gitlab-lsp,"Definition: export async function getIntent({ treeAndLanguage, position, prefix, suffix, }: { treeAndLanguage: TreeAndLanguage; position: Position; prefix: string; suffix: string; }): Promise { const commentResolver = getCommentResolver(); const emptyFunctionResolver = getEmptyFunctionResolver(); const cursorPosition = { row: position.line, column: position.character }; const { languageInfo, tree, language: treeSitterLanguage } = treeAndLanguage; const commentResolution = commentResolver.getCommentForCursor({ languageName: languageInfo.name, tree, cursorPosition, treeSitterLanguage, }); if (commentResolution) { const { commentAtCursor, commentAboveCursor } = commentResolution; if (commentAtCursor) { log.debug('IntentResolver: Cursor is directly on a comment, sending intent: completion'); return { intent: 'completion' }; } const isCommentEmpty = CommentResolver.isCommentEmpty(commentAboveCursor); if (isCommentEmpty) { log.debug('IntentResolver: Cursor is after an empty comment, sending intent: completion'); return { intent: 'completion' }; } log.debug('IntentResolver: Cursor is after a non-empty comment, sending intent: generation'); return { intent: 'generation', generationType: 'comment', commentForCursor: commentAboveCursor, }; } const textContent = `${prefix}${suffix}`; const totalCommentLines = commentResolver.getTotalCommentLines({ languageName: languageInfo.name, treeSitterLanguage, tree, }); if (isSmallFile(textContent, totalCommentLines)) { log.debug('IntentResolver: Small file detected, sending intent: generation'); return { intent: 'generation', generationType: 'small_file' }; } const isCursorInEmptyFunction = emptyFunctionResolver.isCursorInEmptyFunction({ languageName: languageInfo.name, tree, cursorPosition, treeSitterLanguage, }); if (isCursorInEmptyFunction) { log.debug('IntentResolver: Cursor is in an empty function, sending intent: generation'); return { intent: 'generation', generationType: 'empty_function' }; } log.debug( 'IntentResolver: Cursor is neither at the end of non-empty comment, nor in a small file, nor in empty function - not sending intent.', ); return { intent: undefined }; } References: - src/common/tree_sitter/intent_resolver.test.ts:181 - src/common/tree_sitter/intent_resolver.test.ts:144 - src/tests/unit/tree_sitter/intent_resolver.test.ts:671 - src/common/tree_sitter/intent_resolver.test.ts:167 - src/tests/unit/tree_sitter/intent_resolver.test.ts:33 - src/common/tree_sitter/intent_resolver.test.ts:72 - src/common/tree_sitter/intent_resolver.test.ts:97 - src/common/tree_sitter/intent_resolver.test.ts:119 - src/tests/unit/tree_sitter/intent_resolver.test.ts:20 - src/tests/unit/tree_sitter/intent_resolver.test.ts:400 - src/common/suggestion/suggestion_service.ts:358" You are a code assistant,Definition of 'AiMessagesResponseType' in file packages/webview_duo_chat/src/plugin/port/chat/gitlab_chat_api.ts in project gitlab-lsp,"Definition: type AiMessagesResponseType = { aiMessages: { nodes: AiMessageResponseType[]; }; }; interface ErrorMessage { type: 'error'; requestId: string; role: 'system'; errors: string[]; } const errorResponse = (requestId: string, errors: string[]): ErrorMessage => ({ requestId, errors, role: 'system', type: 'error', }); interface SuccessMessage { type: 'message'; requestId: string; role: string; content: string; contentHtml: string; timestamp: string; errors: string[]; extras?: { sources: object[]; }; } const successResponse = (response: AiMessageResponseType): SuccessMessage => ({ type: 'message', ...response, }); type AiMessage = SuccessMessage | ErrorMessage; type ChatInputTemplate = { query: string; defaultVariables: { platformOrigin?: string; }; }; export class GitLabChatApi { #cachedActionQuery?: ChatInputTemplate = undefined; #manager: GitLabPlatformManagerForChat; constructor(manager: GitLabPlatformManagerForChat) { this.#manager = manager; } async processNewUserPrompt( question: string, subscriptionId?: string, currentFileContext?: GitLabChatFileContext, ): Promise { return this.#sendAiAction({ question, currentFileContext, clientSubscriptionId: subscriptionId, }); } async pullAiMessage(requestId: string, role: string): Promise { const response = await pullHandler(() => this.#getAiMessage(requestId, role)); if (!response) return errorResponse(requestId, ['Reached timeout while fetching response.']); return successResponse(response); } async cleanChat(): Promise { return this.#sendAiAction({ question: SPECIAL_MESSAGES.CLEAN }); } async #currentPlatform() { const platform = await this.#manager.getGitLabPlatform(); if (!platform) throw new Error('Platform is missing!'); return platform; } async #getAiMessage(requestId: string, role: string): Promise { const request: GraphQLRequest = { type: 'graphql', query: AI_MESSAGES_QUERY, variables: { requestIds: [requestId], roles: [role.toUpperCase()] }, }; const platform = await this.#currentPlatform(); const history = await platform.fetchFromApi(request); return history.aiMessages.nodes[0]; } async subscribeToUpdates( messageCallback: (message: AiCompletionResponseMessageType) => Promise, subscriptionId?: string, ) { const platform = await this.#currentPlatform(); const channel = new AiCompletionResponseChannel({ htmlResponse: true, userId: `gid://gitlab/User/${extractUserId(platform.account.id)}`, aiAction: 'CHAT', clientSubscriptionId: subscriptionId, }); const cable = await platform.connectToCable(); // we use this flag to fix https://gitlab.com/gitlab-org/gitlab-vscode-extension/-/issues/1397 // sometimes a chunk comes after the full message and it broke the chat let fullMessageReceived = false; channel.on('newChunk', async (msg) => { if (fullMessageReceived) { log.info(`CHAT-DEBUG: full message received, ignoring chunk`); return; } await messageCallback(msg); }); channel.on('fullMessage', async (message) => { fullMessageReceived = true; await messageCallback(message); if (subscriptionId) { cable.disconnect(); } }); cable.subscribe(channel); } async #sendAiAction(variables: object): Promise { const platform = await this.#currentPlatform(); const { query, defaultVariables } = await this.#actionQuery(); const projectGqlId = await this.#manager.getProjectGqlId(); const request: GraphQLRequest = { type: 'graphql', query, variables: { ...variables, ...defaultVariables, resourceId: projectGqlId ?? null, }, }; return platform.fetchFromApi(request); } async #actionQuery(): Promise { if (!this.#cachedActionQuery) { const platform = await this.#currentPlatform(); try { const { version } = await platform.fetchFromApi(versionRequest); this.#cachedActionQuery = ifVersionGte( version, MINIMUM_PLATFORM_ORIGIN_FIELD_VERSION, () => CHAT_INPUT_TEMPLATE_17_3_AND_LATER, () => CHAT_INPUT_TEMPLATE_17_2_AND_EARLIER, ); } catch (e) { log.debug(`GitLab version check for sending chat failed:`, e as Error); this.#cachedActionQuery = CHAT_INPUT_TEMPLATE_17_3_AND_LATER; } } return this.#cachedActionQuery; } } References:" You are a code assistant,Definition of 'constructor' in file src/node/tree_sitter/parser.ts in project gitlab-lsp,"Definition: constructor() { super({ languages: TREE_SITTER_LANGUAGES, }); } async init(): Promise { try { await Parser.init(); log.debug('DesktopTreeSitterParser: Initialized tree-sitter parser.'); this.loadState = TreeSitterParserLoadState.READY; } catch (err) { log.warn('DesktopTreeSitterParser: Error initializing tree-sitter parsers.', err); this.loadState = TreeSitterParserLoadState.ERRORED; } } } References:" You are a code assistant,Definition of 'constructor' in file src/common/ai_context_management_2/ai_context_aggregator.ts in project gitlab-lsp,"Definition: constructor( aiFileContextProvider: AiFileContextProvider, aiContextPolicyManager: AiContextPolicyManager, ) { this.#AiFileContextProvider = aiFileContextProvider; this.#AiContextPolicyManager = aiContextPolicyManager; } async getContextForQuery(query: AiContextQuery): Promise { 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 { 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 'constructor' in file src/common/core/handlers/token_check_notifier.ts in project gitlab-lsp,"Definition: constructor(api: GitLabApiClient) { api.onApiReconfigured(async ({ isInValidState, validationMessage }) => { if (!isInValidState) { if (!this.#notify) { throw new Error( 'The DefaultTokenCheckNotifier has not been initialized. Call init first.', ); } await this.#notify({ message: validationMessage, }); } }); } init(callback: NotifyFn) { this.#notify = callback; } } References:" You are a code assistant,Definition of 'makeAccountId' in file packages/webview_duo_chat/src/plugin/port/platform/gitlab_account.ts in project gitlab-lsp,"Definition: 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 'getUserAgentHeader' in file packages/webview_duo_chat/src/plugin/chat_platform.ts in project gitlab-lsp,"Definition: getUserAgentHeader(): Record { return {}; } } 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:" You are a code assistant,Definition of 'constructor' in file src/common/git/repository_trie.ts in project gitlab-lsp,"Definition: constructor() { this.children = new Map(); this.repository = null; } dispose(): void { this.children.forEach((child) => child.dispose()); this.children.clear(); this.repository = null; } } References:" You are a code assistant,Definition of 'merge' in file src/common/config_service.ts in project gitlab-lsp,"Definition: merge(newConfig: Partial) { mergeWith(this.#config, newConfig, (target, src) => (isArray(target) ? src : undefined)); this.#triggerChange(); } } References:" You are a code assistant,Definition of 'StreamingCompletionResponse' in file src/common/suggestion/streaming_handler.ts in project gitlab-lsp,"Definition: export interface StreamingCompletionResponse { /** stream ID taken from the request, all stream responses for one request will have the request's stream ID */ id: string; /** most up-to-date generated suggestion, each time LS receives a chunk from LLM, it adds it to this string -> the client doesn't have to join the stream */ completion?: string; done: boolean; } export const STREAMING_COMPLETION_RESPONSE_NOTIFICATION = 'streamingCompletionResponse'; export const CANCEL_STREAMING_COMPLETION_NOTIFICATION = 'cancelStreaming'; export const StreamingCompletionResponse = new NotificationType( STREAMING_COMPLETION_RESPONSE_NOTIFICATION, ); export const CancelStreaming = new NotificationType( CANCEL_STREAMING_COMPLETION_NOTIFICATION, ); export interface StartStreamParams { api: GitLabApiClient; circuitBreaker: CircuitBreaker; connection: Connection; documentContext: IDocContext; parser: TreeSitterParser; postProcessorPipeline: PostProcessorPipeline; streamId: string; tracker: TelemetryTracker; uniqueTrackingId: string; userInstruction?: string; generationType?: GenerationType; additionalContexts?: AdditionalContext[]; } export class DefaultStreamingHandler { #params: StartStreamParams; constructor(params: StartStreamParams) { this.#params = params; } async startStream() { return startStreaming(this.#params); } } const startStreaming = async ({ additionalContexts, api, circuitBreaker, connection, documentContext, parser, postProcessorPipeline, streamId, tracker, uniqueTrackingId, userInstruction, generationType, }: StartStreamParams) => { const language = parser.getLanguageNameForFile(documentContext.fileRelativePath); tracker.setCodeSuggestionsContext(uniqueTrackingId, { documentContext, additionalContexts, source: SuggestionSource.network, language, isStreaming: true, }); let streamShown = false; let suggestionProvided = false; let streamCancelledOrErrored = false; const cancellationTokenSource = new CancellationTokenSource(); const disposeStopStreaming = connection.onNotification(CancelStreaming, (stream) => { if (stream.id === streamId) { streamCancelledOrErrored = true; cancellationTokenSource.cancel(); if (streamShown) { tracker.updateSuggestionState(uniqueTrackingId, TRACKING_EVENTS.REJECTED); } else { tracker.updateSuggestionState(uniqueTrackingId, TRACKING_EVENTS.CANCELLED); } } }); const cancellationToken = cancellationTokenSource.token; const endStream = async () => { await connection.sendNotification(StreamingCompletionResponse, { id: streamId, done: true, }); if (!streamCancelledOrErrored) { tracker.updateSuggestionState(uniqueTrackingId, TRACKING_EVENTS.STREAM_COMPLETED); if (!suggestionProvided) { tracker.updateSuggestionState(uniqueTrackingId, TRACKING_EVENTS.NOT_PROVIDED); } } }; circuitBreaker.success(); const request: CodeSuggestionRequest = { prompt_version: 1, project_path: '', project_id: -1, current_file: { content_above_cursor: documentContext.prefix, content_below_cursor: documentContext.suffix, file_name: documentContext.fileRelativePath, }, intent: 'generation', stream: true, ...(additionalContexts?.length && { context: additionalContexts, }), ...(userInstruction && { user_instruction: userInstruction, }), generation_type: generationType, }; const trackStreamStarted = once(() => { tracker.updateSuggestionState(uniqueTrackingId, TRACKING_EVENTS.STREAM_STARTED); }); const trackStreamShown = once(() => { tracker.updateSuggestionState(uniqueTrackingId, TRACKING_EVENTS.SHOWN); streamShown = true; }); try { for await (const response of api.getStreamingCodeSuggestions(request)) { if (cancellationToken.isCancellationRequested) { break; } if (circuitBreaker.isOpen()) { break; } trackStreamStarted(); const processedCompletion = await postProcessorPipeline.run({ documentContext, input: { id: streamId, completion: response, done: false }, type: 'stream', }); await connection.sendNotification(StreamingCompletionResponse, processedCompletion); if (response.replace(/\s/g, '').length) { trackStreamShown(); suggestionProvided = true; } } } catch (err) { circuitBreaker.error(); if (isFetchError(err)) { tracker.updateCodeSuggestionsContext(uniqueTrackingId, { status: err.status }); } tracker.updateSuggestionState(uniqueTrackingId, TRACKING_EVENTS.ERRORED); streamCancelledOrErrored = true; log.error('Error streaming code suggestions.', err); } finally { await endStream(); disposeStopStreaming.dispose(); cancellationTokenSource.dispose(); } }; References: - src/common/suggestion_client/post_processors/post_processor_pipeline.test.ts:179 - src/common/suggestion_client/post_processors/post_processor_pipeline.test.ts:29 - src/common/suggestion_client/post_processors/post_processor_pipeline.ts:9 - src/common/suggestion_client/post_processors/post_processor_pipeline.test.ts:119 - src/common/suggestion_client/post_processors/post_processor_pipeline.test.ts:16 - src/common/suggestion_client/post_processors/post_processor_pipeline.test.ts:58 - src/common/suggestion_client/post_processors/post_processor_pipeline.test.ts:44 - src/common/suggestion_client/post_processors/post_processor_pipeline.ts:23 - src/common/suggestion_client/post_processors/post_processor_pipeline.test.ts:133 - src/common/suggestion_client/post_processors/post_processor_pipeline.test.ts:149 - src/common/suggestion_client/post_processors/post_processor_pipeline.test.ts:103 - src/common/suggestion_client/post_processors/post_processor_pipeline.test.ts:87" You are a code assistant,Definition of 'id' in file src/common/feature_state/supported_language_check.ts in project gitlab-lsp,"Definition: get id() { return this.#isLanguageSupported && !this.#isLanguageEnabled ? DISABLED_LANGUAGE : UNSUPPORTED_LANGUAGE; } details = 'Code suggestions are not supported for this language'; #update() { this.#checkLanguage(); this.#stateEmitter.emit('change', this); } #checkLanguage() { if (!this.#currentDocument) { this.#isLanguageEnabled = false; this.#isLanguageSupported = false; return; } const { languageId } = this.#currentDocument; this.#isLanguageEnabled = this.#supportedLanguagesService.isLanguageEnabled(languageId); this.#isLanguageSupported = this.#supportedLanguagesService.isLanguageSupported(languageId); } } References:" You are a code assistant,Definition of 'currentItems' in file src/common/ai_context_management_2/ai_context_manager.ts in project gitlab-lsp,"Definition: currentItems(): AiContextItem[] { return Array.from(this.#items.values()); } async retrieveItems(): Promise { const items = Array.from(this.#items.values()); log.info(`Retrieving ${items.length} items`); const retrievedItems = await Promise.all( items.map(async (item) => { try { switch (item.type) { case 'file': { const content = await this.#fileRetriever.retrieve(item); return content ? { ...item, content } : null; } default: throw new Error(`Unknown item type: ${item.type}`); } } catch (error) { log.error(`Failed to retrieve item ${item.id}`, error); return null; } }), ); return retrievedItems.filter((item) => item !== null); } } References:" You are a code assistant,Definition of 'greet' in file src/tests/fixtures/intent/empty_function/ruby.rb in project gitlab-lsp,"Definition: def greet(name) end def greet2(name) puts name end greet3 = Proc.new { |name| } greet4 = Proc.new { |name| puts name } greet5 = lambda { |name| } greet6 = lambda { |name| puts name } 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/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 'IGitleaksRule' in file src/common/secret_redaction/gitleaks_rules.ts in project gitlab-lsp,"Definition: export interface IGitleaksRule { id: string; description: string; secretGroup?: number; entropy?: number; allowlist?: object; regex: string; keywords: string[]; compiledRegex?: RegExp; } const rules: Array = [ { description: 'Adafruit API Key', id: 'adafruit-api-key', regex: '(?i)(?:adafruit)(?:[0-9a-z\\-_\\t .]{0,20})(?:[\\s|\']|[\\s|""]){0,3}(?:=|>|:=|\\|\\|:|<=|=>|:)(?:\'|\\""|\\s|=|\\x60){0,5}([a-z0-9_-]{32})(?:[\'|\\""|\\n|\\r|\\s|\\x60|;]|$)', secretGroup: 1, keywords: ['adafruit'], }, { description: 'Adobe Client ID (OAuth Web)', id: 'adobe-client-id', regex: '(?i)(?:adobe)(?:[0-9a-z\\-_\\t .]{0,20})(?:[\\s|\']|[\\s|""]){0,3}(?:=|>|:=|\\|\\|:|<=|=>|:)(?:\'|\\""|\\s|=|\\x60){0,5}([a-f0-9]{32})(?:[\'|\\""|\\n|\\r|\\s|\\x60|;]|$)', secretGroup: 1, keywords: ['adobe'], }, { description: 'Adobe Client Secret', id: 'adobe-client-secret', regex: '(?i)\\b((p8e-)(?i)[a-z0-9]{32})(?:[\'|\\""|\\n|\\r|\\s|\\x60|;]|$)', keywords: ['p8e-'], }, { description: 'Age secret key', id: 'age secret key', regex: 'AGE-SECRET-KEY-1[QPZRY9X8GF2TVDW0S3JN54KHCE6MUA7L]{58}', keywords: ['age-secret-key-1'], }, { description: 'Airtable API Key', id: 'airtable-api-key', regex: '(?i)(?:airtable)(?:[0-9a-z\\-_\\t .]{0,20})(?:[\\s|\']|[\\s|""]){0,3}(?:=|>|:=|\\|\\|:|<=|=>|:)(?:\'|\\""|\\s|=|\\x60){0,5}([a-z0-9]{17})(?:[\'|\\""|\\n|\\r|\\s|\\x60|;]|$)', secretGroup: 1, keywords: ['airtable'], }, { description: 'Algolia API Key', id: 'algolia-api-key', regex: '(?i)(?:algolia)(?:[0-9a-z\\-_\\t .]{0,20})(?:[\\s|\']|[\\s|""]){0,3}(?:=|>|:=|\\|\\|:|<=|=>|:)(?:\'|\\""|\\s|=|\\x60){0,5}([a-z0-9]{32})(?:[\'|\\""|\\n|\\r|\\s|\\x60|;]|$)', keywords: ['algolia'], }, { description: 'Alibaba AccessKey ID', id: 'alibaba-access-key-id', regex: '(?i)\\b((LTAI)(?i)[a-z0-9]{20})(?:[\'|\\""|\\n|\\r|\\s|\\x60|;]|$)', keywords: ['ltai'], }, { description: 'Alibaba Secret Key', id: 'alibaba-secret-key', regex: '(?i)(?:alibaba)(?:[0-9a-z\\-_\\t .]{0,20})(?:[\\s|\']|[\\s|""]){0,3}(?:=|>|:=|\\|\\|:|<=|=>|:)(?:\'|\\""|\\s|=|\\x60){0,5}([a-z0-9]{30})(?:[\'|\\""|\\n|\\r|\\s|\\x60|;]|$)', secretGroup: 1, keywords: ['alibaba'], }, { description: 'Asana Client ID', id: 'asana-client-id', regex: '(?i)(?:asana)(?:[0-9a-z\\-_\\t .]{0,20})(?:[\\s|\']|[\\s|""]){0,3}(?:=|>|:=|\\|\\|:|<=|=>|:)(?:\'|\\""|\\s|=|\\x60){0,5}([0-9]{16})(?:[\'|\\""|\\n|\\r|\\s|\\x60|;]|$)', secretGroup: 1, keywords: ['asana'], }, { description: 'Asana Client Secret', id: 'asana-client-secret', regex: '(?i)(?:asana)(?:[0-9a-z\\-_\\t .]{0,20})(?:[\\s|\']|[\\s|""]){0,3}(?:=|>|:=|\\|\\|:|<=|=>|:)(?:\'|\\""|\\s|=|\\x60){0,5}([a-z0-9]{32})(?:[\'|\\""|\\n|\\r|\\s|\\x60|;]|$)', secretGroup: 1, keywords: ['asana'], }, { description: 'Atlassian API token', id: 'atlassian-api-token', regex: '(?i)(?:atlassian|confluence|jira)(?:[0-9a-z\\-_\\t .]{0,20})(?:[\\s|\']|[\\s|""]){0,3}(?:=|>|:=|\\|\\|:|<=|=>|:)(?:\'|\\""|\\s|=|\\x60){0,5}([a-z0-9]{24})(?:[\'|\\""|\\n|\\r|\\s|\\x60|;]|$)', secretGroup: 1, keywords: ['atlassian', 'confluence', 'jira'], }, { description: 'Authress Service Client Access Key', id: 'authress-service-client-access-key', regex: '(?i)\\b((?:sc|ext|scauth|authress)_[a-z0-9]{5,30}\\.[a-z0-9]{4,6}\\.acc_[a-z0-9-]{10,32}\\.[a-z0-9+/_=-]{30,120})(?:[\'|\\""|\\n|\\r|\\s|\\x60|;]|$)', secretGroup: 1, keywords: ['sc_', 'ext_', 'scauth_', 'authress_'], }, { description: 'AWS', id: 'aws-access-token', regex: '(A3T[A-Z0-9]|AKIA|AGPA|AIDA|AROA|AIPA|ANPA|ANVA|ASIA)[A-Z0-9]{16}', keywords: ['akia', 'agpa', 'aida', 'aroa', 'aipa', 'anpa', 'anva', 'asia'], }, { description: 'Beamer API token', id: 'beamer-api-token', regex: '(?i)(?:beamer)(?:[0-9a-z\\-_\\t .]{0,20})(?:[\\s|\']|[\\s|""]){0,3}(?:=|>|:=|\\|\\|:|<=|=>|:)(?:\'|\\""|\\s|=|\\x60){0,5}(b_[a-z0-9=_\\-]{44})(?:[\'|\\""|\\n|\\r|\\s|\\x60|;]|$)', secretGroup: 1, keywords: ['beamer'], }, { description: 'Bitbucket Client ID', id: 'bitbucket-client-id', regex: '(?i)(?:bitbucket)(?:[0-9a-z\\-_\\t .]{0,20})(?:[\\s|\']|[\\s|""]){0,3}(?:=|>|:=|\\|\\|:|<=|=>|:)(?:\'|\\""|\\s|=|\\x60){0,5}([a-z0-9]{32})(?:[\'|\\""|\\n|\\r|\\s|\\x60|;]|$)', secretGroup: 1, keywords: ['bitbucket'], }, { description: 'Bitbucket Client Secret', id: 'bitbucket-client-secret', regex: '(?i)(?:bitbucket)(?:[0-9a-z\\-_\\t .]{0,20})(?:[\\s|\']|[\\s|""]){0,3}(?:=|>|:=|\\|\\|:|<=|=>|:)(?:\'|\\""|\\s|=|\\x60){0,5}([a-z0-9=_\\-]{64})(?:[\'|\\""|\\n|\\r|\\s|\\x60|;]|$)', secretGroup: 1, keywords: ['bitbucket'], }, { description: 'Bittrex Access Key', id: 'bittrex-access-key', regex: '(?i)(?:bittrex)(?:[0-9a-z\\-_\\t .]{0,20})(?:[\\s|\']|[\\s|""]){0,3}(?:=|>|:=|\\|\\|:|<=|=>|:)(?:\'|\\""|\\s|=|\\x60){0,5}([a-z0-9]{32})(?:[\'|\\""|\\n|\\r|\\s|\\x60|;]|$)', secretGroup: 1, keywords: ['bittrex'], }, { description: 'Bittrex Secret Key', id: 'bittrex-secret-key', regex: '(?i)(?:bittrex)(?:[0-9a-z\\-_\\t .]{0,20})(?:[\\s|\']|[\\s|""]){0,3}(?:=|>|:=|\\|\\|:|<=|=>|:)(?:\'|\\""|\\s|=|\\x60){0,5}([a-z0-9]{32})(?:[\'|\\""|\\n|\\r|\\s|\\x60|;]|$)', secretGroup: 1, keywords: ['bittrex'], }, { description: 'Clojars API token', id: 'clojars-api-token', regex: '(?i)(CLOJARS_)[a-z0-9]{60}', keywords: ['clojars'], }, { description: 'Codecov Access Token', id: 'codecov-access-token', regex: '(?i)(?:codecov)(?:[0-9a-z\\-_\\t .]{0,20})(?:[\\s|\']|[\\s|""]){0,3}(?:=|>|:=|\\|\\|:|<=|=>|:)(?:\'|\\""|\\s|=|\\x60){0,5}([a-z0-9]{32})(?:[\'|\\""|\\n|\\r|\\s|\\x60|;]|$)', secretGroup: 1, keywords: ['codecov'], }, { description: 'Coinbase Access Token', id: 'coinbase-access-token', regex: '(?i)(?:coinbase)(?:[0-9a-z\\-_\\t .]{0,20})(?:[\\s|\']|[\\s|""]){0,3}(?:=|>|:=|\\|\\|:|<=|=>|:)(?:\'|\\""|\\s|=|\\x60){0,5}([a-z0-9_-]{64})(?:[\'|\\""|\\n|\\r|\\s|\\x60|;]|$)', secretGroup: 1, keywords: ['coinbase'], }, { description: 'Confluent Access Token', id: 'confluent-access-token', regex: '(?i)(?:confluent)(?:[0-9a-z\\-_\\t .]{0,20})(?:[\\s|\']|[\\s|""]){0,3}(?:=|>|:=|\\|\\|:|<=|=>|:)(?:\'|\\""|\\s|=|\\x60){0,5}([a-z0-9]{16})(?:[\'|\\""|\\n|\\r|\\s|\\x60|;]|$)', secretGroup: 1, keywords: ['confluent'], }, { description: 'Confluent Secret Key', id: 'confluent-secret-key', regex: '(?i)(?:confluent)(?:[0-9a-z\\-_\\t .]{0,20})(?:[\\s|\']|[\\s|""]){0,3}(?:=|>|:=|\\|\\|:|<=|=>|:)(?:\'|\\""|\\s|=|\\x60){0,5}([a-z0-9]{64})(?:[\'|\\""|\\n|\\r|\\s|\\x60|;]|$)', secretGroup: 1, keywords: ['confluent'], }, { description: 'Contentful delivery API token', id: 'contentful-delivery-api-token', regex: '(?i)(?:contentful)(?:[0-9a-z\\-_\\t .]{0,20})(?:[\\s|\']|[\\s|""]){0,3}(?:=|>|:=|\\|\\|:|<=|=>|:)(?:\'|\\""|\\s|=|\\x60){0,5}([a-z0-9=_\\-]{43})(?:[\'|\\""|\\n|\\r|\\s|\\x60|;]|$)', secretGroup: 1, keywords: ['contentful'], }, { description: 'Databricks API token', id: 'databricks-api-token', regex: '(?i)\\b(dapi[a-h0-9]{32})(?:[\'|\\""|\\n|\\r|\\s|\\x60|;]|$)', keywords: ['dapi'], }, { description: 'Datadog Access Token', id: 'datadog-access-token', regex: '(?i)(?:datadog)(?:[0-9a-z\\-_\\t .]{0,20})(?:[\\s|\']|[\\s|""]){0,3}(?:=|>|:=|\\|\\|:|<=|=>|:)(?:\'|\\""|\\s|=|\\x60){0,5}([a-z0-9]{40})(?:[\'|\\""|\\n|\\r|\\s|\\x60|;]|$)', secretGroup: 1, keywords: ['datadog'], }, { description: 'Defined Networking API token', id: 'defined-networking-api-token', regex: '(?i)(?:dnkey)(?:[0-9a-z\\-_\\t .]{0,20})(?:[\\s|\']|[\\s|""]){0,3}(?:=|>|:=|\\|\\|:|<=|=>|:)(?:\'|\\""|\\s|=|\\x60){0,5}(dnkey-[a-z0-9=_\\-]{26}-[a-z0-9=_\\-]{52})(?:[\'|\\""|\\n|\\r|\\s|\\x60|;]|$)', secretGroup: 1, keywords: ['dnkey'], }, { description: 'DigitalOcean OAuth Access Token', id: 'digitalocean-access-token', regex: '(?i)\\b(doo_v1_[a-f0-9]{64})(?:[\'|\\""|\\n|\\r|\\s|\\x60|;]|$)', secretGroup: 1, keywords: ['doo_v1_'], }, { description: 'DigitalOcean Personal Access Token', id: 'digitalocean-pat', regex: '(?i)\\b(dop_v1_[a-f0-9]{64})(?:[\'|\\""|\\n|\\r|\\s|\\x60|;]|$)', secretGroup: 1, keywords: ['dop_v1_'], }, { description: 'DigitalOcean OAuth Refresh Token', id: 'digitalocean-refresh-token', regex: '(?i)\\b(dor_v1_[a-f0-9]{64})(?:[\'|\\""|\\n|\\r|\\s|\\x60|;]|$)', secretGroup: 1, keywords: ['dor_v1_'], }, { description: 'Discord API key', id: 'discord-api-token', regex: '(?i)(?:discord)(?:[0-9a-z\\-_\\t .]{0,20})(?:[\\s|\']|[\\s|""]){0,3}(?:=|>|:=|\\|\\|:|<=|=>|:)(?:\'|\\""|\\s|=|\\x60){0,5}([a-f0-9]{64})(?:[\'|\\""|\\n|\\r|\\s|\\x60|;]|$)', secretGroup: 1, keywords: ['discord'], }, { description: 'Discord client ID', id: 'discord-client-id', regex: '(?i)(?:discord)(?:[0-9a-z\\-_\\t .]{0,20})(?:[\\s|\']|[\\s|""]){0,3}(?:=|>|:=|\\|\\|:|<=|=>|:)(?:\'|\\""|\\s|=|\\x60){0,5}([0-9]{18})(?:[\'|\\""|\\n|\\r|\\s|\\x60|;]|$)', secretGroup: 1, keywords: ['discord'], }, { description: 'Discord client secret', id: 'discord-client-secret', regex: '(?i)(?:discord)(?:[0-9a-z\\-_\\t .]{0,20})(?:[\\s|\']|[\\s|""]){0,3}(?:=|>|:=|\\|\\|:|<=|=>|:)(?:\'|\\""|\\s|=|\\x60){0,5}([a-z0-9=_\\-]{32})(?:[\'|\\""|\\n|\\r|\\s|\\x60|;]|$)', secretGroup: 1, keywords: ['discord'], }, { description: 'Doppler API token', id: 'doppler-api-token', regex: '(dp\\.pt\\.)(?i)[a-z0-9]{43}', keywords: ['doppler'], }, { description: 'Droneci Access Token', id: 'droneci-access-token', regex: '(?i)(?:droneci)(?:[0-9a-z\\-_\\t .]{0,20})(?:[\\s|\']|[\\s|""]){0,3}(?:=|>|:=|\\|\\|:|<=|=>|:)(?:\'|\\""|\\s|=|\\x60){0,5}([a-z0-9]{32})(?:[\'|\\""|\\n|\\r|\\s|\\x60|;]|$)', secretGroup: 1, keywords: ['droneci'], }, { description: 'Dropbox API secret', id: 'dropbox-api-token', regex: '(?i)(?:dropbox)(?:[0-9a-z\\-_\\t .]{0,20})(?:[\\s|\']|[\\s|""]){0,3}(?:=|>|:=|\\|\\|:|<=|=>|:)(?:\'|\\""|\\s|=|\\x60){0,5}([a-z0-9]{15})(?:[\'|\\""|\\n|\\r|\\s|\\x60|;]|$)', secretGroup: 1, keywords: ['dropbox'], }, { description: 'Dropbox long lived API token', id: 'dropbox-long-lived-api-token', regex: '(?i)(?:dropbox)(?:[0-9a-z\\-_\\t .]{0,20})(?:[\\s|\']|[\\s|""]){0,3}(?:=|>|:=|\\|\\|:|<=|=>|:)(?:\'|\\""|\\s|=|\\x60){0,5}([a-z0-9]{11}(AAAAAAAAAA)[a-z0-9\\-_=]{43})(?:[\'|\\""|\\n|\\r|\\s|\\x60|;]|$)', keywords: ['dropbox'], }, { description: 'Dropbox short lived API token', id: 'dropbox-short-lived-api-token', regex: '(?i)(?:dropbox)(?:[0-9a-z\\-_\\t .]{0,20})(?:[\\s|\']|[\\s|""]){0,3}(?:=|>|:=|\\|\\|:|<=|=>|:)(?:\'|\\""|\\s|=|\\x60){0,5}(sl\\.[a-z0-9\\-=_]{135})(?:[\'|\\""|\\n|\\r|\\s|\\x60|;]|$)', keywords: ['dropbox'], }, { description: 'Duffel API token', id: 'duffel-api-token', regex: 'duffel_(test|live)_(?i)[a-z0-9_\\-=]{43}', keywords: ['duffel'], }, { description: 'Dynatrace API token', id: 'dynatrace-api-token', regex: 'dt0c01\\.(?i)[a-z0-9]{24}\\.[a-z0-9]{64}', keywords: ['dynatrace'], }, { description: 'EasyPost API token', id: 'easypost-api-token', regex: '\\bEZAK(?i)[a-z0-9]{54}', keywords: ['ezak'], }, { description: 'EasyPost test API token', id: 'easypost-test-api-token', regex: '\\bEZTK(?i)[a-z0-9]{54}', keywords: ['eztk'], }, { description: 'Etsy Access Token', id: 'etsy-access-token', regex: '(?i)(?:etsy)(?:[0-9a-z\\-_\\t .]{0,20})(?:[\\s|\']|[\\s|""]){0,3}(?:=|>|:=|\\|\\|:|<=|=>|:)(?:\'|\\""|\\s|=|\\x60){0,5}([a-z0-9]{24})(?:[\'|\\""|\\n|\\r|\\s|\\x60|;]|$)', secretGroup: 1, keywords: ['etsy'], }, { description: 'Facebook Access Token', id: 'facebook', regex: '(?i)(?:facebook)(?:[0-9a-z\\-_\\t .]{0,20})(?:[\\s|\']|[\\s|""]){0,3}(?:=|>|:=|\\|\\|:|<=|=>|:)(?:\'|\\""|\\s|=|\\x60){0,5}([a-f0-9]{32})(?:[\'|\\""|\\n|\\r|\\s|\\x60|;]|$)', secretGroup: 1, keywords: ['facebook'], }, { description: 'Fastly API key', id: 'fastly-api-token', regex: '(?i)(?:fastly)(?:[0-9a-z\\-_\\t .]{0,20})(?:[\\s|\']|[\\s|""]){0,3}(?:=|>|:=|\\|\\|:|<=|=>|:)(?:\'|\\""|\\s|=|\\x60){0,5}([a-z0-9=_\\-]{32})(?:[\'|\\""|\\n|\\r|\\s|\\x60|;]|$)', secretGroup: 1, keywords: ['fastly'], }, { description: 'Finicity API token', id: 'finicity-api-token', regex: '(?i)(?:finicity)(?:[0-9a-z\\-_\\t .]{0,20})(?:[\\s|\']|[\\s|""]){0,3}(?:=|>|:=|\\|\\|:|<=|=>|:)(?:\'|\\""|\\s|=|\\x60){0,5}([a-f0-9]{32})(?:[\'|\\""|\\n|\\r|\\s|\\x60|;]|$)', secretGroup: 1, keywords: ['finicity'], }, { description: 'Finicity Client Secret', id: 'finicity-client-secret', regex: '(?i)(?:finicity)(?:[0-9a-z\\-_\\t .]{0,20})(?:[\\s|\']|[\\s|""]){0,3}(?:=|>|:=|\\|\\|:|<=|=>|:)(?:\'|\\""|\\s|=|\\x60){0,5}([a-z0-9]{20})(?:[\'|\\""|\\n|\\r|\\s|\\x60|;]|$)', secretGroup: 1, keywords: ['finicity'], }, { description: 'Finnhub Access Token', id: 'finnhub-access-token', regex: '(?i)(?:finnhub)(?:[0-9a-z\\-_\\t .]{0,20})(?:[\\s|\']|[\\s|""]){0,3}(?:=|>|:=|\\|\\|:|<=|=>|:)(?:\'|\\""|\\s|=|\\x60){0,5}([a-z0-9]{20})(?:[\'|\\""|\\n|\\r|\\s|\\x60|;]|$)', secretGroup: 1, keywords: ['finnhub'], }, { description: 'Flickr Access Token', id: 'flickr-access-token', regex: '(?i)(?:flickr)(?:[0-9a-z\\-_\\t .]{0,20})(?:[\\s|\']|[\\s|""]){0,3}(?:=|>|:=|\\|\\|:|<=|=>|:)(?:\'|\\""|\\s|=|\\x60){0,5}([a-z0-9]{32})(?:[\'|\\""|\\n|\\r|\\s|\\x60|;]|$)', secretGroup: 1, keywords: ['flickr'], }, { description: 'Flutterwave Encryption Key', id: 'flutterwave-encryption-key', regex: 'FLWSECK_TEST-(?i)[a-h0-9]{12}', keywords: ['flwseck_test'], }, { description: 'Finicity Public Key', id: 'flutterwave-public-key', regex: 'FLWPUBK_TEST-(?i)[a-h0-9]{32}-X', keywords: ['flwpubk_test'], }, { description: 'Flutterwave Secret Key', id: 'flutterwave-secret-key', regex: 'FLWSECK_TEST-(?i)[a-h0-9]{32}-X', keywords: ['flwseck_test'], }, { description: 'Frame.io API token', id: 'frameio-api-token', regex: 'fio-u-(?i)[a-z0-9\\-_=]{64}', keywords: ['fio-u-'], }, { description: 'Freshbooks Access Token', id: 'freshbooks-access-token', regex: '(?i)(?:freshbooks)(?:[0-9a-z\\-_\\t .]{0,20})(?:[\\s|\']|[\\s|""]){0,3}(?:=|>|:=|\\|\\|:|<=|=>|:)(?:\'|\\""|\\s|=|\\x60){0,5}([a-z0-9]{64})(?:[\'|\\""|\\n|\\r|\\s|\\x60|;]|$)', secretGroup: 1, keywords: ['freshbooks'], }, { description: 'GCP API key', id: 'gcp-api-key', regex: '(?i)\\b(AIza[0-9A-Za-z\\\\-_]{35})(?:[\'|\\""|\\n|\\r|\\s|\\x60|;]|$)', secretGroup: 1, keywords: ['aiza'], }, { description: 'Generic API Key', id: 'generic-api-key', regex: '(?i)(?:key|api|token|secret|client|passwd|password|auth|access)(?:[0-9a-z\\-_\\t .]{0,20})(?:[\\s|\']|[\\s|""]){0,3}(?:=|>|:=|\\|\\|:|<=|=>|:)(?:\'|\\""|\\s|=|\\x60){0,5}([0-9a-z\\-_.=]{10,150})(?:[\'|\\""|\\n|\\r|\\s|\\x60|;]|$)', secretGroup: 1, entropy: 3.5, keywords: ['key', 'api', 'token', 'secret', 'client', 'passwd', 'password', 'auth', 'access'], allowlist: { stopwords: [ 'client', 'endpoint', 'vpn', '_ec2_', 'aws_', 'authorize', 'author', 'define', 'config', 'credential', 'setting', 'sample', 'xxxxxx', '000000', 'buffer', 'delete', 'aaaaaa', 'fewfwef', 'getenv', 'env_', 'system', 'example', 'ecdsa', 'sha256', 'sha1', 'sha2', 'md5', 'alert', 'wizard', 'target', 'onboard', 'welcome', 'page', 'exploit', 'experiment', 'expire', 'rabbitmq', 'scraper', 'widget', 'music', 'dns_', 'dns-', 'yahoo', 'want', 'json', 'action', 'script', 'fix_', 'fix-', 'develop', 'compas', 'stripe', 'service', 'master', 'metric', 'tech', 'gitignore', 'rich', 'open', 'stack', 'irc_', 'irc-', 'sublime', 'kohana', 'has_', 'has-', 'fabric', 'wordpres', 'role', 'osx_', 'osx-', 'boost', 'addres', 'queue', 'working', 'sandbox', 'internet', 'print', 'vision', 'tracking', 'being', 'generator', 'traffic', 'world', 'pull', 'rust', 'watcher', 'small', 'auth', 'full', 'hash', 'more', 'install', 'auto', 'complete', 'learn', 'paper', 'installer', 'research', 'acces', 'last', 'binding', 'spine', 'into', 'chat', 'algorithm', 'resource', 'uploader', 'video', 'maker', 'next', 'proc', 'lock', 'robot', 'snake', 'patch', 'matrix', 'drill', 'terminal', 'term', 'stuff', 'genetic', 'generic', 'identity', 'audit', 'pattern', 'audio', 'web_', 'web-', 'crud', 'problem', 'statu', 'cms-', 'cms_', 'arch', 'coffee', 'workflow', 'changelog', 'another', 'uiview', 'content', 'kitchen', 'gnu_', 'gnu-', 'gnu.', 'conf', 'couchdb', 'client', 'opencv', 'rendering', 'update', 'concept', 'varnish', 'gui_', 'gui-', 'gui.', 'version', 'shared', 'extra', 'product', 'still', 'not_', 'not-', 'not.', 'drop', 'ring', 'png_', 'png-', 'png.', 'actively', 'import', 'output', 'backup', 'start', 'embedded', 'registry', 'pool', 'semantic', 'instagram', 'bash', 'system', 'ninja', 'drupal', 'jquery', 'polyfill', 'physic', 'league', 'guide', 'pack', 'synopsi', 'sketch', 'injection', 'svg_', 'svg-', 'svg.', 'friendly', 'wave', 'convert', 'manage', 'camera', 'link', 'slide', 'timer', 'wrapper', 'gallery', 'url_', 'url-', 'url.', 'todomvc', 'requirej', 'party', 'http', 'payment', 'async', 'library', 'home', 'coco', 'gaia', 'display', 'universal', 'func', 'metadata', 'hipchat', 'under', 'room', 'config', 'personal', 'realtime', 'resume', 'database', 'testing', 'tiny', 'basic', 'forum', 'meetup', 'yet_', 'yet-', 'yet.', 'cento', 'dead', 'fluentd', 'editor', 'utilitie', 'run_', 'run-', 'run.', 'box_', 'box-', 'box.', 'bot_', 'bot-', 'bot.', 'making', 'sample', 'group', 'monitor', 'ajax', 'parallel', 'cassandra', 'ultimate', 'site', 'get_', 'get-', 'get.', 'gen_', 'gen-', 'gen.', 'gem_', 'gem-', 'gem.', 'extended', 'image', 'knife', 'asset', 'nested', 'zero', 'plugin', 'bracket', 'mule', 'mozilla', 'number', 'act_', 'act-', 'act.', 'map_', 'map-', 'map.', 'micro', 'debug', 'openshift', 'chart', 'expres', 'backend', 'task', 'source', 'translate', 'jbos', 'composer', 'sqlite', 'profile', 'mustache', 'mqtt', 'yeoman', 'have', 'builder', 'smart', 'like', 'oauth', 'school', 'guideline', 'captcha', 'filter', 'bitcoin', 'bridge', 'color', 'toolbox', 'discovery', 'new_', 'new-', 'new.', 'dashboard', 'when', 'setting', 'level', 'post', 'standard', 'port', 'platform', 'yui_', 'yui-', 'yui.', 'grunt', 'animation', 'haskell', 'icon', 'latex', 'cheat', 'lua_', 'lua-', 'lua.', 'gulp', 'case', 'author', 'without', 'simulator', 'wifi', 'directory', 'lisp', 'list', 'flat', 'adventure', 'story', 'storm', 'gpu_', 'gpu-', 'gpu.', 'store', 'caching', 'attention', 'solr', 'logger', 'demo', 'shortener', 'hadoop', 'finder', 'phone', 'pipeline', 'range', 'textmate', 'showcase', 'app_', 'app-', 'app.', 'idiomatic', 'edit', 'our_', 'our-', 'our.', 'out_', 'out-', 'out.', 'sentiment', 'linked', 'why_', 'why-', 'why.', 'local', 'cube', 'gmail', 'job_', 'job-', 'job.', 'rpc_', 'rpc-', 'rpc.', 'contest', 'tcp_', 'tcp-', 'tcp.', 'usage', 'buildout', 'weather', 'transfer', 'automated', 'sphinx', 'issue', 'sas_', 'sas-', 'sas.', 'parallax', 'jasmine', 'addon', 'machine', 'solution', 'dsl_', 'dsl-', 'dsl.', 'episode', 'menu', 'theme', 'best', 'adapter', 'debugger', 'chrome', 'tutorial', 'life', 'step', 'people', 'joomla', 'paypal', 'developer', 'solver', 'team', 'current', 'love', 'visual', 'date', 'data', 'canva', 'container', 'future', 'xml_', 'xml-', 'xml.', 'twig', 'nagio', 'spatial', 'original', 'sync', 'archived', 'refinery', 'science', 'mapping', 'gitlab', 'play', 'ext_', 'ext-', 'ext.', 'session', 'impact', 'set_', 'set-', 'set.', 'see_', 'see-', 'see.', 'migration', 'commit', 'community', 'shopify', ""what'"", 'cucumber', 'statamic', 'mysql', 'location', 'tower', 'line', 'code', 'amqp', 'hello', 'send', 'index', 'high', 'notebook', 'alloy', 'python', 'field', 'document', 'soap', 'edition', 'email', 'php_', 'php-', 'php.', 'command', 'transport', 'official', 'upload', 'study', 'secure', 'angularj', 'akka', 'scalable', 'package', 'request', 'con_', 'con-', 'con.', 'flexible', 'security', 'comment', 'module', 'flask', 'graph', 'flash', 'apache', 'change', 'window', 'space', 'lambda', 'sheet', 'bookmark', 'carousel', 'friend', 'objective', 'jekyll', 'bootstrap', 'first', 'article', 'gwt_', 'gwt-', 'gwt.', 'classic', 'media', 'websocket', 'touch', 'desktop', 'real', 'read', 'recorder', 'moved', 'storage', 'validator', 'add-on', 'pusher', 'scs_', 'scs-', 'scs.', 'inline', 'asp_', 'asp-', 'asp.', 'timeline', 'base', 'encoding', 'ffmpeg', 'kindle', 'tinymce', 'pretty', 'jpa_', 'jpa-', 'jpa.', 'used', 'user', 'required', 'webhook', 'download', 'resque', 'espresso', 'cloud', 'mongo', 'benchmark', 'pure', 'cakephp', 'modx', 'mode', 'reactive', 'fuel', 'written', 'flickr', 'mail', 'brunch', 'meteor', 'dynamic', 'neo_', 'neo-', 'neo.', 'new_', 'new-', 'new.', 'net_', 'net-', 'net.', 'typo', 'type', 'keyboard', 'erlang', 'adobe', 'logging', 'ckeditor', 'message', 'iso_', 'iso-', 'iso.', 'hook', 'ldap', 'folder', 'reference', 'railscast', 'www_', 'www-', 'www.', 'tracker', 'azure', 'fork', 'form', 'digital', 'exporter', 'skin', 'string', 'template', 'designer', 'gollum', 'fluent', 'entity', 'language', 'alfred', 'summary', 'wiki', 'kernel', 'calendar', 'plupload', 'symfony', 'foundry', 'remote', 'talk', 'search', 'dev_', 'dev-', 'dev.', 'del_', 'del-', 'del.', 'token', 'idea', 'sencha', 'selector', 'interface', 'create', 'fun_', 'fun-', 'fun.', 'groovy', 'query', 'grail', 'red_', 'red-', 'red.', 'laravel', 'monkey', 'slack', 'supported', 'instant', 'value', 'center', 'latest', 'work', 'but_', 'but-', 'but.', 'bug_', 'bug-', 'bug.', 'virtual', 'tweet', 'statsd', 'studio', 'path', 'real-time', 'frontend', 'notifier', 'coding', 'tool', 'firmware', 'flow', 'random', 'mediawiki', 'bosh', 'been', 'beer', 'lightbox', 'theory', 'origin', 'redmine', 'hub_', 'hub-', 'hub.', 'require', 'pro_', 'pro-', 'pro.', 'ant_', 'ant-', 'ant.', 'any_', 'any-', 'any.', 'recipe', 'closure', 'mapper', 'event', 'todo', 'model', 'redi', 'provider', 'rvm_', 'rvm-', 'rvm.', 'program', 'memcached', 'rail', 'silex', 'foreman', 'activity', 'license', 'strategy', 'batch', 'streaming', 'fast', 'use_', 'use-', 'use.', 'usb_', 'usb-', 'usb.', 'impres', 'academy', 'slider', 'please', 'layer', 'cros', 'now_', 'now-', 'now.', 'miner', 'extension', 'own_', 'own-', 'own.', 'app_', 'app-', 'app.', 'debian', 'symphony', 'example', 'feature', 'serie', 'tree', 'project', 'runner', 'entry', 'leetcode', 'layout', 'webrtc', 'logic', 'login', 'worker', 'toolkit', 'mocha', 'support', 'back', 'inside', 'device', 'jenkin', 'contact', 'fake', 'awesome', 'ocaml', 'bit_', 'bit-', 'bit.', 'drive', 'screen', 'prototype', 'gist', 'binary', 'nosql', 'rest', 'overview', 'dart', 'dark', 'emac', 'mongoid', 'solarized', 'homepage', 'emulator', 'commander', 'django', 'yandex', 'gradle', 'xcode', 'writer', 'crm_', 'crm-', 'crm.', 'jade', 'startup', 'error', 'using', 'format', 'name', 'spring', 'parser', 'scratch', 'magic', 'try_', 'try-', 'try.', 'rack', 'directive', 'challenge', 'slim', 'counter', 'element', 'chosen', 'doc_', 'doc-', 'doc.', 'meta', 'should', 'button', 'packet', 'stream', 'hardware', 'android', 'infinite', 'password', 'software', 'ghost', 'xamarin', 'spec', 'chef', 'interview', 'hubot', 'mvc_', 'mvc-', 'mvc.', 'exercise', 'leaflet', 'launcher', 'air_', 'air-', 'air.', 'photo', 'board', 'boxen', 'way_', 'way-', 'way.', 'computing', 'welcome', 'notepad', 'portfolio', 'cat_', 'cat-', 'cat.', 'can_', 'can-', 'can.', 'magento', 'yaml', 'domain', 'card', 'yii_', 'yii-', 'yii.', 'checker', 'browser', 'upgrade', 'only', 'progres', 'aura', 'ruby_', 'ruby-', 'ruby.', 'polymer', 'util', 'lite', 'hackathon', 'rule', 'log_', 'log-', 'log.', 'opengl', 'stanford', 'skeleton', 'history', 'inspector', 'help', 'soon', 'selenium', 'lab_', 'lab-', 'lab.', 'scheme', 'schema', 'look', 'ready', 'leveldb', 'docker', 'game', 'minimal', 'logstash', 'messaging', 'within', 'heroku', 'mongodb', 'kata', 'suite', 'picker', 'win_', 'win-', 'win.', 'wip_', 'wip-', 'wip.', 'panel', 'started', 'starter', 'front-end', 'detector', 'deploy', 'editing', 'based', 'admin', 'capture', 'spree', 'page', 'bundle', 'goal', 'rpg_', 'rpg-', 'rpg.', 'setup', 'side', 'mean', 'reader', 'cookbook', 'mini', 'modern', 'seed', 'dom_', 'dom-', 'dom.', 'doc_', 'doc-', 'doc.', 'dot_', 'dot-', 'dot.', 'syntax', 'sugar', 'loader', 'website', 'make', 'kit_', 'kit-', 'kit.', 'protocol', 'human', 'daemon', 'golang', 'manager', 'countdown', 'connector', 'swagger', 'map_', 'map-', 'map.', 'mac_', 'mac-', 'mac.', 'man_', 'man-', 'man.', 'orm_', 'orm-', 'orm.', 'org_', 'org-', 'org.', 'little', 'zsh_', 'zsh-', 'zsh.', 'shop', 'show', 'workshop', 'money', 'grid', 'server', 'octopres', 'svn_', 'svn-', 'svn.', 'ember', 'embed', 'general', 'file', 'important', 'dropbox', 'portable', 'public', 'docpad', 'fish', 'sbt_', 'sbt-', 'sbt.', 'done', 'para', 'network', 'common', 'readme', 'popup', 'simple', 'purpose', 'mirror', 'single', 'cordova', 'exchange', 'object', 'design', 'gateway', 'account', 'lamp', 'intellij', 'math', 'mit_', 'mit-', 'mit.', 'control', 'enhanced', 'emitter', 'multi', 'add_', 'add-', 'add.', 'about', 'socket', 'preview', 'vagrant', 'cli_', 'cli-', 'cli.', 'powerful', 'top_', 'top-', 'top.', 'radio', 'watch', 'fluid', 'amazon', 'report', 'couchbase', 'automatic', 'detection', 'sprite', 'pyramid', 'portal', 'advanced', 'plu_', 'plu-', 'plu.', 'runtime', 'git_', 'git-', 'git.', 'uri_', 'uri-', 'uri.', 'haml', 'node', 'sql_', 'sql-', 'sql.', 'cool', 'core', 'obsolete', 'handler', 'iphone', 'extractor', 'array', 'copy', 'nlp_', 'nlp-', 'nlp.', 'reveal', 'pop_', 'pop-', 'pop.', 'engine', 'parse', 'check', 'html', 'nest', 'all_', 'all-', 'all.', 'chinese', 'buildpack', 'what', 'tag_', 'tag-', 'tag.', 'proxy', 'style', 'cookie', 'feed', 'restful', 'compiler', 'creating', 'prelude', 'context', 'java', 'rspec', 'mock', 'backbone', 'light', 'spotify', 'flex', 'related', 'shell', 'which', 'clas', 'webapp', 'swift', 'ansible', 'unity', 'console', 'tumblr', 'export', 'campfire', ""conway'"", 'made', 'riak', 'hero', 'here', 'unix', 'unit', 'glas', 'smtp', 'how_', 'how-', 'how.', 'hot_', 'hot-', 'hot.', 'debug', 'release', 'diff', 'player', 'easy', 'right', 'old_', 'old-', 'old.', 'animate', 'time', 'push', 'explorer', 'course', 'training', 'nette', 'router', 'draft', 'structure', 'note', 'salt', 'where', 'spark', 'trello', 'power', 'method', 'social', 'via_', 'via-', 'via.', 'vim_', 'vim-', 'vim.', 'select', 'webkit', 'github', 'ftp_', 'ftp-', 'ftp.', 'creator', 'mongoose', 'led_', 'led-', 'led.', 'movie', 'currently', 'pdf_', 'pdf-', 'pdf.', 'load', 'markdown', 'phalcon', 'input', 'custom', 'atom', 'oracle', 'phonegap', 'ubuntu', 'great', 'rdf_', 'rdf-', 'rdf.', 'popcorn', 'firefox', 'zip_', 'zip-', 'zip.', 'cuda', 'dotfile', 'static', 'openwrt', 'viewer', 'powered', 'graphic', 'les_', 'les-', 'les.', 'doe_', 'doe-', 'doe.', 'maven', 'word', 'eclipse', 'lab_', 'lab-', 'lab.', 'hacking', 'steam', 'analytic', 'option', 'abstract', 'archive', 'reality', 'switcher', 'club', 'write', 'kafka', 'arduino', 'angular', 'online', 'title', ""don't"", 'contao', 'notice', 'analyzer', 'learning', 'zend', 'external', 'staging', 'busines', 'tdd_', 'tdd-', 'tdd.', 'scanner', 'building', 'snippet', 'modular', 'bower', 'stm_', 'stm-', 'stm.', 'lib_', 'lib-', 'lib.', 'alpha', 'mobile', 'clean', 'linux', 'nginx', 'manifest', 'some', 'raspberry', 'gnome', 'ide_', 'ide-', 'ide.', 'block', 'statistic', 'info', 'drag', 'youtube', 'koan', 'facebook', 'paperclip', 'art_', 'art-', 'art.', 'quality', 'tab_', 'tab-', 'tab.', 'need', 'dojo', 'shield', 'computer', 'stat', 'state', 'twitter', 'utility', 'converter', 'hosting', 'devise', 'liferay', 'updated', 'force', 'tip_', 'tip-', 'tip.', 'behavior', 'active', 'call', 'answer', 'deck', 'better', 'principle', 'ches', 'bar_', 'bar-', 'bar.', 'reddit', 'three', 'haxe', 'just', 'plug-in', 'agile', 'manual', 'tetri', 'super', 'beta', 'parsing', 'doctrine', 'minecraft', 'useful', 'perl', 'sharing', 'agent', 'switch', 'view', 'dash', 'channel', 'repo', 'pebble', 'profiler', 'warning', 'cluster', 'running', 'markup', 'evented', 'mod_', 'mod-', 'mod.', 'share', 'csv_', 'csv-', 'csv.', 'response', 'good', 'house', 'connect', 'built', 'build', 'find', 'ipython', 'webgl', 'big_', 'big-', 'big.', 'google', 'scala', 'sdl_', 'sdl-', 'sdl.', 'sdk_', 'sdk-', 'sdk.', 'native', 'day_', 'day-', 'day.', 'puppet', 'text', 'routing', 'helper', 'linkedin', 'crawler', 'host', 'guard', 'merchant', 'poker', 'over', 'writing', 'free', 'classe', 'component', 'craft', 'nodej', 'phoenix', 'longer', 'quick', 'lazy', 'memory', 'clone', 'hacker', 'middleman', 'factory', 'motion', 'multiple', 'tornado', 'hack', 'ssh_', 'ssh-', 'ssh.', 'review', 'vimrc', 'driver', 'driven', 'blog', 'particle', 'table', 'intro', 'importer', 'thrift', 'xmpp', 'framework', 'refresh', 'react', 'font', 'librarie', 'variou', 'formatter', 'analysi', 'karma', 'scroll', 'tut_', 'tut-', 'tut.', 'apple', 'tag_', 'tag-', 'tag.', 'tab_', 'tab-', 'tab.', 'category', 'ionic', 'cache', 'homebrew', 'reverse', 'english', 'getting', 'shipping', 'clojure', 'boot', 'book', 'branch', 'combination', 'combo', ], }, }, { description: 'GitHub App Token', id: 'github-app-token', regex: '(ghu|ghs)_[0-9a-zA-Z]{36}', keywords: ['ghu_', 'ghs_'], }, { description: 'GitHub Fine-Grained Personal Access Token', id: 'github-fine-grained-pat', regex: 'github_pat_[0-9a-zA-Z_]{82}', keywords: ['github_pat_'], }, { description: 'GitHub OAuth Access Token', id: 'github-oauth', regex: 'gho_[0-9a-zA-Z]{36}', keywords: ['gho_'], }, { description: 'GitHub Personal Access Token', id: 'github-pat', regex: 'ghp_[0-9a-zA-Z]{36}', keywords: ['ghp_'], }, { description: 'GitHub Refresh Token', id: 'github-refresh-token', regex: 'ghr_[0-9a-zA-Z]{36}', keywords: ['ghr_'], }, { description: 'GitLab Personal Access Token', id: 'gitlab-pat', regex: 'glpat-[0-9a-zA-Z\\-\\_]{20}', keywords: ['glpat-'], }, { description: 'GitLab Pipeline Trigger Token', id: 'gitlab-ptt', regex: 'glptt-[0-9a-f]{40}', keywords: ['glptt-'], }, { description: 'GitLab Runner Registration Token', id: 'gitlab-rrt', regex: 'GR1348941[0-9a-zA-Z\\-\\_]{20}', keywords: ['gr1348941'], }, { description: 'Gitter Access Token', id: 'gitter-access-token', regex: '(?i)(?:gitter)(?:[0-9a-z\\-_\\t .]{0,20})(?:[\\s|\']|[\\s|""]){0,3}(?:=|>|:=|\\|\\|:|<=|=>|:)(?:\'|\\""|\\s|=|\\x60){0,5}([a-z0-9_-]{40})(?:[\'|\\""|\\n|\\r|\\s|\\x60|;]|$)', secretGroup: 1, keywords: ['gitter'], }, { description: 'GoCardless API token', id: 'gocardless-api-token', regex: '(?i)(?:gocardless)(?:[0-9a-z\\-_\\t .]{0,20})(?:[\\s|\']|[\\s|""]){0,3}(?:=|>|:=|\\|\\|:|<=|=>|:)(?:\'|\\""|\\s|=|\\x60){0,5}(live_(?i)[a-z0-9\\-_=]{40})(?:[\'|\\""|\\n|\\r|\\s|\\x60|;]|$)', secretGroup: 1, keywords: ['live_', 'gocardless'], }, { description: 'Grafana api key (or Grafana cloud api key)', id: 'grafana-api-key', regex: '(?i)\\b(eyJrIjoi[A-Za-z0-9]{70,400}={0,2})(?:[\'|\\""|\\n|\\r|\\s|\\x60|;]|$)', secretGroup: 1, keywords: ['eyjrijoi'], }, { description: 'Grafana cloud api token', id: 'grafana-cloud-api-token', regex: '(?i)\\b(glc_[A-Za-z0-9+/]{32,400}={0,2})(?:[\'|\\""|\\n|\\r|\\s|\\x60|;]|$)', secretGroup: 1, keywords: ['glc_'], }, { description: 'Grafana service account token', id: 'grafana-service-account-token', regex: '(?i)\\b(glsa_[A-Za-z0-9]{32}_[A-Fa-f0-9]{8})(?:[\'|\\""|\\n|\\r|\\s|\\x60|;]|$)', secretGroup: 1, keywords: ['glsa_'], }, { description: 'HashiCorp Terraform user/org API token', id: 'hashicorp-tf-api-token', regex: '(?i)[a-z0-9]{14}\\.atlasv1\\.[a-z0-9\\-_=]{60,70}', keywords: ['atlasv1'], }, { description: 'Heroku API Key', id: 'heroku-api-key', regex: '(?i)(?:heroku)(?:[0-9a-z\\-_\\t .]{0,20})(?:[\\s|\']|[\\s|""]){0,3}(?:=|>|:=|\\|\\|:|<=|=>|:)(?:\'|\\""|\\s|=|\\x60){0,5}([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})(?:[\'|\\""|\\n|\\r|\\s|\\x60|;]|$)', secretGroup: 1, keywords: ['heroku'], }, { description: 'HubSpot API Token', id: 'hubspot-api-key', regex: '(?i)(?:hubspot)(?:[0-9a-z\\-_\\t .]{0,20})(?:[\\s|\']|[\\s|""]){0,3}(?:=|>|:=|\\|\\|:|<=|=>|:)(?:\'|\\""|\\s|=|\\x60){0,5}([0-9A-F]{8}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{12})(?:[\'|\\""|\\n|\\r|\\s|\\x60|;]|$)', secretGroup: 1, keywords: ['hubspot'], }, { description: 'Intercom API Token', id: 'intercom-api-key', regex: '(?i)(?:intercom)(?:[0-9a-z\\-_\\t .]{0,20})(?:[\\s|\']|[\\s|""]){0,3}(?:=|>|:=|\\|\\|:|<=|=>|:)(?:\'|\\""|\\s|=|\\x60){0,5}([a-z0-9=_\\-]{60})(?:[\'|\\""|\\n|\\r|\\s|\\x60|;]|$)', secretGroup: 1, keywords: ['intercom'], }, { description: 'JSON Web Token', id: 'jwt', regex: '(?i)\\b(ey[0-9a-z]{30,34}\\.ey[0-9a-z-\\/_]{30,500}\\.[0-9a-zA-Z-\\/_]{10,200}={0,2})(?:[\'|\\""|\\n|\\r|\\s|\\x60|;]|$)', keywords: ['ey'], }, { description: 'Kraken Access Token', id: 'kraken-access-token', regex: '(?i)(?:kraken)(?:[0-9a-z\\-_\\t .]{0,20})(?:[\\s|\']|[\\s|""]){0,3}(?:=|>|:=|\\|\\|:|<=|=>|:)(?:\'|\\""|\\s|=|\\x60){0,5}([a-z0-9\\/=_\\+\\-]{80,90})(?:[\'|\\""|\\n|\\r|\\s|\\x60|;]|$)', secretGroup: 1, keywords: ['kraken'], }, { description: 'Kucoin Access Token', id: 'kucoin-access-token', regex: '(?i)(?:kucoin)(?:[0-9a-z\\-_\\t .]{0,20})(?:[\\s|\']|[\\s|""]){0,3}(?:=|>|:=|\\|\\|:|<=|=>|:)(?:\'|\\""|\\s|=|\\x60){0,5}([a-f0-9]{24})(?:[\'|\\""|\\n|\\r|\\s|\\x60|;]|$)', secretGroup: 1, keywords: ['kucoin'], }, { description: 'Kucoin Secret Key', id: 'kucoin-secret-key', regex: '(?i)(?:kucoin)(?:[0-9a-z\\-_\\t .]{0,20})(?:[\\s|\']|[\\s|""]){0,3}(?:=|>|:=|\\|\\|:|<=|=>|:)(?:\'|\\""|\\s|=|\\x60){0,5}([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})(?:[\'|\\""|\\n|\\r|\\s|\\x60|;]|$)', secretGroup: 1, keywords: ['kucoin'], }, { description: 'Launchdarkly Access Token', id: 'launchdarkly-access-token', regex: '(?i)(?:launchdarkly)(?:[0-9a-z\\-_\\t .]{0,20})(?:[\\s|\']|[\\s|""]){0,3}(?:=|>|:=|\\|\\|:|<=|=>|:)(?:\'|\\""|\\s|=|\\x60){0,5}([a-z0-9=_\\-]{40})(?:[\'|\\""|\\n|\\r|\\s|\\x60|;]|$)', secretGroup: 1, keywords: ['launchdarkly'], }, { description: 'Linear API Token', id: 'linear-api-key', regex: 'lin_api_(?i)[a-z0-9]{40}', keywords: ['lin_api_'], }, { description: 'Linear Client Secret', id: 'linear-client-secret', regex: '(?i)(?:linear)(?:[0-9a-z\\-_\\t .]{0,20})(?:[\\s|\']|[\\s|""]){0,3}(?:=|>|:=|\\|\\|:|<=|=>|:)(?:\'|\\""|\\s|=|\\x60){0,5}([a-f0-9]{32})(?:[\'|\\""|\\n|\\r|\\s|\\x60|;]|$)', secretGroup: 1, keywords: ['linear'], }, { description: 'LinkedIn Client ID', id: 'linkedin-client-id', regex: '(?i)(?:linkedin|linked-in)(?:[0-9a-z\\-_\\t .]{0,20})(?:[\\s|\']|[\\s|""]){0,3}(?:=|>|:=|\\|\\|:|<=|=>|:)(?:\'|\\""|\\s|=|\\x60){0,5}([a-z0-9]{14})(?:[\'|\\""|\\n|\\r|\\s|\\x60|;]|$)', secretGroup: 1, keywords: ['linkedin', 'linked-in'], }, { description: 'LinkedIn Client secret', id: 'linkedin-client-secret', regex: '(?i)(?:linkedin|linked-in)(?:[0-9a-z\\-_\\t .]{0,20})(?:[\\s|\']|[\\s|""]){0,3}(?:=|>|:=|\\|\\|:|<=|=>|:)(?:\'|\\""|\\s|=|\\x60){0,5}([a-z0-9]{16})(?:[\'|\\""|\\n|\\r|\\s|\\x60|;]|$)', secretGroup: 1, keywords: ['linkedin', 'linked-in'], }, { description: 'Lob API Key', id: 'lob-api-key', regex: '(?i)(?:lob)(?:[0-9a-z\\-_\\t .]{0,20})(?:[\\s|\']|[\\s|""]){0,3}(?:=|>|:=|\\|\\|:|<=|=>|:)(?:\'|\\""|\\s|=|\\x60){0,5}((live|test)_[a-f0-9]{35})(?:[\'|\\""|\\n|\\r|\\s|\\x60|;]|$)', secretGroup: 1, keywords: ['test_', 'live_'], }, { description: 'Lob Publishable API Key', id: 'lob-pub-api-key', regex: '(?i)(?:lob)(?:[0-9a-z\\-_\\t .]{0,20})(?:[\\s|\']|[\\s|""]){0,3}(?:=|>|:=|\\|\\|:|<=|=>|:)(?:\'|\\""|\\s|=|\\x60){0,5}((test|live)_pub_[a-f0-9]{31})(?:[\'|\\""|\\n|\\r|\\s|\\x60|;]|$)', secretGroup: 1, keywords: ['test_pub', 'live_pub', '_pub'], }, { description: 'Mailchimp API key', id: 'mailchimp-api-key', regex: '(?i)(?:mailchimp)(?:[0-9a-z\\-_\\t .]{0,20})(?:[\\s|\']|[\\s|""]){0,3}(?:=|>|:=|\\|\\|:|<=|=>|:)(?:\'|\\""|\\s|=|\\x60){0,5}([a-f0-9]{32}-us20)(?:[\'|\\""|\\n|\\r|\\s|\\x60|;]|$)', secretGroup: 1, keywords: ['mailchimp'], }, { description: 'Mailgun private API token', id: 'mailgun-private-api-token', regex: '(?i)(?:mailgun)(?:[0-9a-z\\-_\\t .]{0,20})(?:[\\s|\']|[\\s|""]){0,3}(?:=|>|:=|\\|\\|:|<=|=>|:)(?:\'|\\""|\\s|=|\\x60){0,5}(key-[a-f0-9]{32})(?:[\'|\\""|\\n|\\r|\\s|\\x60|;]|$)', secretGroup: 1, keywords: ['mailgun'], }, { description: 'Mailgun public validation key', id: 'mailgun-pub-key', regex: '(?i)(?:mailgun)(?:[0-9a-z\\-_\\t .]{0,20})(?:[\\s|\']|[\\s|""]){0,3}(?:=|>|:=|\\|\\|:|<=|=>|:)(?:\'|\\""|\\s|=|\\x60){0,5}(pubkey-[a-f0-9]{32})(?:[\'|\\""|\\n|\\r|\\s|\\x60|;]|$)', secretGroup: 1, keywords: ['mailgun'], }, { description: 'Mailgun webhook signing key', id: 'mailgun-signing-key', regex: '(?i)(?:mailgun)(?:[0-9a-z\\-_\\t .]{0,20})(?:[\\s|\']|[\\s|""]){0,3}(?:=|>|:=|\\|\\|:|<=|=>|:)(?:\'|\\""|\\s|=|\\x60){0,5}([a-h0-9]{32}-[a-h0-9]{8}-[a-h0-9]{8})(?:[\'|\\""|\\n|\\r|\\s|\\x60|;]|$)', secretGroup: 1, keywords: ['mailgun'], }, { description: 'MapBox API token', id: 'mapbox-api-token', regex: '(?i)(?:mapbox)(?:[0-9a-z\\-_\\t .]{0,20})(?:[\\s|\']|[\\s|""]){0,3}(?:=|>|:=|\\|\\|:|<=|=>|:)(?:\'|\\""|\\s|=|\\x60){0,5}(pk\\.[a-z0-9]{60}\\.[a-z0-9]{22})(?:[\'|\\""|\\n|\\r|\\s|\\x60|;]|$)', secretGroup: 1, keywords: ['mapbox'], }, { description: 'Mattermost Access Token', id: 'mattermost-access-token', regex: '(?i)(?:mattermost)(?:[0-9a-z\\-_\\t .]{0,20})(?:[\\s|\']|[\\s|""]){0,3}(?:=|>|:=|\\|\\|:|<=|=>|:)(?:\'|\\""|\\s|=|\\x60){0,5}([a-z0-9]{26})(?:[\'|\\""|\\n|\\r|\\s|\\x60|;]|$)', secretGroup: 1, keywords: ['mattermost'], }, { description: 'MessageBird API token', id: 'messagebird-api-token', regex: '(?i)(?:messagebird|message-bird|message_bird)(?:[0-9a-z\\-_\\t .]{0,20})(?:[\\s|\']|[\\s|""]){0,3}(?:=|>|:=|\\|\\|:|<=|=>|:)(?:\'|\\""|\\s|=|\\x60){0,5}([a-z0-9]{25})(?:[\'|\\""|\\n|\\r|\\s|\\x60|;]|$)', secretGroup: 1, keywords: ['messagebird', 'message-bird', 'message_bird'], }, { description: 'MessageBird client ID', id: 'messagebird-client-id', regex: '(?i)(?:messagebird|message-bird|message_bird)(?:[0-9a-z\\-_\\t .]{0,20})(?:[\\s|\']|[\\s|""]){0,3}(?:=|>|:=|\\|\\|:|<=|=>|:)(?:\'|\\""|\\s|=|\\x60){0,5}([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})(?:[\'|\\""|\\n|\\r|\\s|\\x60|;]|$)', secretGroup: 1, keywords: ['messagebird', 'message-bird', 'message_bird'], }, { description: 'Microsoft Teams Webhook', id: 'microsoft-teams-webhook', regex: 'https:\\/\\/[a-z0-9]+\\.webhook\\.office\\.com\\/webhookb2\\/[a-z0-9]{8}-([a-z0-9]{4}-){3}[a-z0-9]{12}@[a-z0-9]{8}-([a-z0-9]{4}-){3}[a-z0-9]{12}\\/IncomingWebhook\\/[a-z0-9]{32}\\/[a-z0-9]{8}-([a-z0-9]{4}-){3}[a-z0-9]{12}', keywords: ['webhook.office.com', 'webhookb2', 'incomingwebhook'], }, { description: 'Netlify Access Token', id: 'netlify-access-token', regex: '(?i)(?:netlify)(?:[0-9a-z\\-_\\t .]{0,20})(?:[\\s|\']|[\\s|""]){0,3}(?:=|>|:=|\\|\\|:|<=|=>|:)(?:\'|\\""|\\s|=|\\x60){0,5}([a-z0-9=_\\-]{40,46})(?:[\'|\\""|\\n|\\r|\\s|\\x60|;]|$)', secretGroup: 1, keywords: ['netlify'], }, { description: 'New Relic ingest browser API token', id: 'new-relic-browser-api-token', regex: '(?i)(?:new-relic|newrelic|new_relic)(?:[0-9a-z\\-_\\t .]{0,20})(?:[\\s|\']|[\\s|""]){0,3}(?:=|>|:=|\\|\\|:|<=|=>|:)(?:\'|\\""|\\s|=|\\x60){0,5}(NRJS-[a-f0-9]{19})(?:[\'|\\""|\\n|\\r|\\s|\\x60|;]|$)', secretGroup: 1, keywords: ['nrjs-'], }, { description: 'New Relic user API ID', id: 'new-relic-user-api-id', regex: '(?i)(?:new-relic|newrelic|new_relic)(?:[0-9a-z\\-_\\t .]{0,20})(?:[\\s|\']|[\\s|""]){0,3}(?:=|>|:=|\\|\\|:|<=|=>|:)(?:\'|\\""|\\s|=|\\x60){0,5}([a-z0-9]{64})(?:[\'|\\""|\\n|\\r|\\s|\\x60|;]|$)', secretGroup: 1, keywords: ['new-relic', 'newrelic', 'new_relic'], }, { description: 'New Relic user API Key', id: 'new-relic-user-api-key', regex: '(?i)(?:new-relic|newrelic|new_relic)(?:[0-9a-z\\-_\\t .]{0,20})(?:[\\s|\']|[\\s|""]){0,3}(?:=|>|:=|\\|\\|:|<=|=>|:)(?:\'|\\""|\\s|=|\\x60){0,5}(NRAK-[a-z0-9]{27})(?:[\'|\\""|\\n|\\r|\\s|\\x60|;]|$)', secretGroup: 1, keywords: ['nrak'], }, { description: 'npm access token', id: 'npm-access-token', regex: '(?i)\\b(npm_[a-z0-9]{36})(?:[\'|\\""|\\n|\\r|\\s|\\x60|;]|$)', secretGroup: 1, keywords: ['npm_'], }, { description: 'Nytimes Access Token', id: 'nytimes-access-token', regex: '(?i)(?:nytimes|new-york-times,|newyorktimes)(?:[0-9a-z\\-_\\t .]{0,20})(?:[\\s|\']|[\\s|""]){0,3}(?:=|>|:=|\\|\\|:|<=|=>|:)(?:\'|\\""|\\s|=|\\x60){0,5}([a-z0-9=_\\-]{32})(?:[\'|\\""|\\n|\\r|\\s|\\x60|;]|$)', secretGroup: 1, keywords: ['nytimes', 'new-york-times', 'newyorktimes'], }, { description: 'Okta Access Token', id: 'okta-access-token', regex: '(?i)(?:okta)(?:[0-9a-z\\-_\\t .]{0,20})(?:[\\s|\']|[\\s|""]){0,3}(?:=|>|:=|\\|\\|:|<=|=>|:)(?:\'|\\""|\\s|=|\\x60){0,5}([a-z0-9=_\\-]{42})(?:[\'|\\""|\\n|\\r|\\s|\\x60|;]|$)', secretGroup: 1, keywords: ['okta'], }, { description: 'Plaid API Token', id: 'plaid-api-token', regex: '(?i)(?:plaid)(?:[0-9a-z\\-_\\t .]{0,20})(?:[\\s|\']|[\\s|""]){0,3}(?:=|>|:=|\\|\\|:|<=|=>|:)(?:\'|\\""|\\s|=|\\x60){0,5}(access-(?:sandbox|development|production)-[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})(?:[\'|\\""|\\n|\\r|\\s|\\x60|;]|$)', secretGroup: 1, keywords: ['plaid'], }, { description: 'Plaid Client ID', id: 'plaid-client-id', regex: '(?i)(?:plaid)(?:[0-9a-z\\-_\\t .]{0,20})(?:[\\s|\']|[\\s|""]){0,3}(?:=|>|:=|\\|\\|:|<=|=>|:)(?:\'|\\""|\\s|=|\\x60){0,5}([a-z0-9]{24})(?:[\'|\\""|\\n|\\r|\\s|\\x60|;]|$)', secretGroup: 1, keywords: ['plaid'], }, { description: 'Plaid Secret key', id: 'plaid-secret-key', regex: '(?i)(?:plaid)(?:[0-9a-z\\-_\\t .]{0,20})(?:[\\s|\']|[\\s|""]){0,3}(?:=|>|:=|\\|\\|:|<=|=>|:)(?:\'|\\""|\\s|=|\\x60){0,5}([a-z0-9]{30})(?:[\'|\\""|\\n|\\r|\\s|\\x60|;]|$)', secretGroup: 1, keywords: ['plaid'], }, { description: 'PlanetScale API token', id: 'planetscale-api-token', regex: '(?i)\\b(pscale_tkn_(?i)[a-z0-9=\\-_\\.]{32,64})(?:[\'|\\""|\\n|\\r|\\s|\\x60|;]|$)', secretGroup: 1, keywords: ['pscale_tkn_'], }, { description: 'PlanetScale OAuth token', id: 'planetscale-oauth-token', regex: '(?i)\\b(pscale_oauth_(?i)[a-z0-9=\\-_\\.]{32,64})(?:[\'|\\""|\\n|\\r|\\s|\\x60|;]|$)', secretGroup: 1, keywords: ['pscale_oauth_'], }, { description: 'PlanetScale password', id: 'planetscale-password', regex: '(?i)\\b(pscale_pw_(?i)[a-z0-9=\\-_\\.]{32,64})(?:[\'|\\""|\\n|\\r|\\s|\\x60|;]|$)', secretGroup: 1, keywords: ['pscale_pw_'], }, { description: 'Postman API token', id: 'postman-api-token', regex: '(?i)\\b(PMAK-(?i)[a-f0-9]{24}\\-[a-f0-9]{34})(?:[\'|\\""|\\n|\\r|\\s|\\x60|;]|$)', secretGroup: 1, keywords: ['pmak-'], }, { description: 'Prefect API token', id: 'prefect-api-token', regex: '(?i)\\b(pnu_[a-z0-9]{36})(?:[\'|\\""|\\n|\\r|\\s|\\x60|;]|$)', secretGroup: 1, keywords: ['pnu_'], }, { description: 'Private Key', id: 'private-key', regex: '(?i)-----BEGIN[ A-Z0-9_-]{0,100}PRIVATE KEY( BLOCK)?-----[\\s\\S-]*KEY( BLOCK)?----', keywords: ['-----begin'], }, { description: 'Pulumi API token', id: 'pulumi-api-token', regex: '(?i)\\b(pul-[a-f0-9]{40})(?:[\'|\\""|\\n|\\r|\\s|\\x60|;]|$)', secretGroup: 1, keywords: ['pul-'], }, { description: 'PyPI upload token', id: 'pypi-upload-token', regex: 'pypi-AgEIcHlwaS5vcmc[A-Za-z0-9\\-_]{50,1000}', keywords: ['pypi-ageichlwas5vcmc'], }, { description: 'RapidAPI Access Token', id: 'rapidapi-access-token', regex: '(?i)(?:rapidapi)(?:[0-9a-z\\-_\\t .]{0,20})(?:[\\s|\']|[\\s|""]){0,3}(?:=|>|:=|\\|\\|:|<=|=>|:)(?:\'|\\""|\\s|=|\\x60){0,5}([a-z0-9_-]{50})(?:[\'|\\""|\\n|\\r|\\s|\\x60|;]|$)', secretGroup: 1, keywords: ['rapidapi'], }, { description: 'Readme API token', id: 'readme-api-token', regex: '(?i)\\b(rdme_[a-z0-9]{70})(?:[\'|\\""|\\n|\\r|\\s|\\x60|;]|$)', secretGroup: 1, keywords: ['rdme_'], }, { description: 'Rubygem API token', id: 'rubygems-api-token', regex: '(?i)\\b(rubygems_[a-f0-9]{48})(?:[\'|\\""|\\n|\\r|\\s|\\x60|;]|$)', secretGroup: 1, keywords: ['rubygems_'], }, { description: 'Sendbird Access ID', id: 'sendbird-access-id', regex: '(?i)(?:sendbird)(?:[0-9a-z\\-_\\t .]{0,20})(?:[\\s|\']|[\\s|""]){0,3}(?:=|>|:=|\\|\\|:|<=|=>|:)(?:\'|\\""|\\s|=|\\x60){0,5}([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})(?:[\'|\\""|\\n|\\r|\\s|\\x60|;]|$)', secretGroup: 1, keywords: ['sendbird'], }, { description: 'Sendbird Access Token', id: 'sendbird-access-token', regex: '(?i)(?:sendbird)(?:[0-9a-z\\-_\\t .]{0,20})(?:[\\s|\']|[\\s|""]){0,3}(?:=|>|:=|\\|\\|:|<=|=>|:)(?:\'|\\""|\\s|=|\\x60){0,5}([a-f0-9]{40})(?:[\'|\\""|\\n|\\r|\\s|\\x60|;]|$)', secretGroup: 1, keywords: ['sendbird'], }, { description: 'SendGrid API token', id: 'sendgrid-api-token', regex: '(?i)\\b(SG\\.(?i)[a-z0-9=_\\-\\.]{66})(?:[\'|\\""|\\n|\\r|\\s|\\x60|;]|$)', secretGroup: 1, keywords: ['sg.'], }, { description: 'Sendinblue API token', id: 'sendinblue-api-token', regex: '(?i)\\b(xkeysib-[a-f0-9]{64}\\-(?i)[a-z0-9]{16})(?:[\'|\\""|\\n|\\r|\\s|\\x60|;]|$)', secretGroup: 1, keywords: ['xkeysib-'], }, { description: 'Sentry Access Token', id: 'sentry-access-token', regex: '(?i)(?:sentry)(?:[0-9a-z\\-_\\t .]{0,20})(?:[\\s|\']|[\\s|""]){0,3}(?:=|>|:=|\\|\\|:|<=|=>|:)(?:\'|\\""|\\s|=|\\x60){0,5}([a-f0-9]{64})(?:[\'|\\""|\\n|\\r|\\s|\\x60|;]|$)', secretGroup: 1, keywords: ['sentry'], }, { description: 'Shippo API token', id: 'shippo-api-token', regex: '(?i)\\b(shippo_(live|test)_[a-f0-9]{40})(?:[\'|\\""|\\n|\\r|\\s|\\x60|;]|$)', secretGroup: 1, keywords: ['shippo_'], }, { description: 'Shopify access token', id: 'shopify-access-token', regex: 'shpat_[a-fA-F0-9]{32}', keywords: ['shpat_'], }, { description: 'Shopify custom access token', id: 'shopify-custom-access-token', regex: 'shpca_[a-fA-F0-9]{32}', keywords: ['shpca_'], }, { description: 'Shopify private app access token', id: 'shopify-private-app-access-token', regex: 'shppa_[a-fA-F0-9]{32}', keywords: ['shppa_'], }, { description: 'Shopify shared secret', id: 'shopify-shared-secret', regex: 'shpss_[a-fA-F0-9]{32}', keywords: ['shpss_'], }, { description: 'Sidekiq Secret', id: 'sidekiq-secret', regex: '(?i)(?:BUNDLE_ENTERPRISE__CONTRIBSYS__COM|BUNDLE_GEMS__CONTRIBSYS__COM)(?:[0-9a-z\\-_\\t .]{0,20})(?:[\\s|\']|[\\s|""]){0,3}(?:=|>|:=|\\|\\|:|<=|=>|:)(?:\'|\\""|\\s|=|\\x60){0,5}([a-f0-9]{8}:[a-f0-9]{8})(?:[\'|\\""|\\n|\\r|\\s|\\x60|;]|$)', secretGroup: 1, keywords: ['bundle_enterprise__contribsys__com', 'bundle_gems__contribsys__com'], }, { description: 'Sidekiq Sensitive URL', id: 'sidekiq-sensitive-url', regex: '(?i)\\b(http(?:s??):\\/\\/)([a-f0-9]{8}:[a-f0-9]{8})@(?:gems.contribsys.com|enterprise.contribsys.com)(?:[\\/|\\#|\\?|:]|$)', secretGroup: 2, keywords: ['gems.contribsys.com', 'enterprise.contribsys.com'], }, { description: 'Slack token', id: 'slack-access-token', regex: 'xox[baprs]-([0-9a-zA-Z]{10,48})', keywords: ['xoxb', 'xoxa', 'xoxp', 'xoxr', 'xoxs'], }, { description: 'Slack Webhook', id: 'slack-web-hook', regex: 'https:\\/\\/hooks.slack.com\\/(services|workflows)\\/[A-Za-z0-9+\\/]{44,46}', keywords: ['hooks.slack.com'], }, { description: 'Square Access Token', id: 'square-access-token', regex: '(?i)\\b(sq0atp-[0-9A-Za-z\\-_]{22})(?:[\'|\\""|\\n|\\r|\\s|\\x60|;]|$)', keywords: ['sq0atp-'], }, { description: 'Squarespace Access Token', id: 'squarespace-access-token', regex: '(?i)(?:squarespace)(?:[0-9a-z\\-_\\t .]{0,20})(?:[\\s|\']|[\\s|""]){0,3}(?:=|>|:=|\\|\\|:|<=|=>|:)(?:\'|\\""|\\s|=|\\x60){0,5}([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})(?:[\'|\\""|\\n|\\r|\\s|\\x60|;]|$)', secretGroup: 1, keywords: ['squarespace'], }, { description: 'Stripe Access Token', id: 'stripe-access-token', regex: '(?i)(sk|pk)_(test|live)_[0-9a-z]{10,32}', keywords: ['sk_test', 'pk_test', 'sk_live', 'pk_live'], }, { description: 'SumoLogic Access ID', id: 'sumologic-access-id', regex: '(?i)(?:sumo)(?:[0-9a-z\\-_\\t .]{0,20})(?:[\\s|\']|[\\s|""]){0,3}(?:=|>|:=|\\|\\|:|<=|=>|:)(?:\'|\\""|\\s|=|\\x60){0,5}([a-z0-9]{14})(?:[\'|\\""|\\n|\\r|\\s|\\x60|;]|$)', secretGroup: 1, keywords: ['sumo'], }, { description: 'SumoLogic Access Token', id: 'sumologic-access-token', regex: '(?i)(?:sumo)(?:[0-9a-z\\-_\\t .]{0,20})(?:[\\s|\']|[\\s|""]){0,3}(?:=|>|:=|\\|\\|:|<=|=>|:)(?:\'|\\""|\\s|=|\\x60){0,5}([a-z0-9]{64})(?:[\'|\\""|\\n|\\r|\\s|\\x60|;]|$)', secretGroup: 1, keywords: ['sumo'], }, { description: 'Telegram Bot API Token', id: 'telegram-bot-api-token', regex: '(?i)(?:^|[^0-9])([0-9]{5,16}:A[a-zA-Z0-9_\\-]{34})(?:$|[^a-zA-Z0-9_\\-])', secretGroup: 1, keywords: ['telegram', 'api', 'bot', 'token', 'url'], }, { description: 'Travis CI Access Token', id: 'travisci-access-token', regex: '(?i)(?:travis)(?:[0-9a-z\\-_\\t .]{0,20})(?:[\\s|\']|[\\s|""]){0,3}(?:=|>|:=|\\|\\|:|<=|=>|:)(?:\'|\\""|\\s|=|\\x60){0,5}([a-z0-9]{22})(?:[\'|\\""|\\n|\\r|\\s|\\x60|;]|$)', secretGroup: 1, keywords: ['travis'], }, { description: 'Twilio API Key', id: 'twilio-api-key', regex: 'SK[0-9a-fA-F]{32}', keywords: ['twilio'], }, { description: 'Twitch API token', id: 'twitch-api-token', regex: '(?i)(?:twitch)(?:[0-9a-z\\-_\\t .]{0,20})(?:[\\s|\']|[\\s|""]){0,3}(?:=|>|:=|\\|\\|:|<=|=>|:)(?:\'|\\""|\\s|=|\\x60){0,5}([a-z0-9]{30})(?:[\'|\\""|\\n|\\r|\\s|\\x60|;]|$)', secretGroup: 1, keywords: ['twitch'], }, { description: 'Twitter Access Secret', id: 'twitter-access-secret', regex: '(?i)(?:twitter)(?:[0-9a-z\\-_\\t .]{0,20})(?:[\\s|\']|[\\s|""]){0,3}(?:=|>|:=|\\|\\|:|<=|=>|:)(?:\'|\\""|\\s|=|\\x60){0,5}([a-z0-9]{45})(?:[\'|\\""|\\n|\\r|\\s|\\x60|;]|$)', secretGroup: 1, keywords: ['twitter'], }, { description: 'Twitter Access Token', id: 'twitter-access-token', regex: '(?i)(?:twitter)(?:[0-9a-z\\-_\\t .]{0,20})(?:[\\s|\']|[\\s|""]){0,3}(?:=|>|:=|\\|\\|:|<=|=>|:)(?:\'|\\""|\\s|=|\\x60){0,5}([0-9]{15,25}-[a-zA-Z0-9]{20,40})(?:[\'|\\""|\\n|\\r|\\s|\\x60|;]|$)', secretGroup: 1, keywords: ['twitter'], }, { description: 'Twitter API Key', id: 'twitter-api-key', regex: '(?i)(?:twitter)(?:[0-9a-z\\-_\\t .]{0,20})(?:[\\s|\']|[\\s|""]){0,3}(?:=|>|:=|\\|\\|:|<=|=>|:)(?:\'|\\""|\\s|=|\\x60){0,5}([a-z0-9]{25})(?:[\'|\\""|\\n|\\r|\\s|\\x60|;]|$)', secretGroup: 1, keywords: ['twitter'], }, { description: 'Twitter API Secret', id: 'twitter-api-secret', regex: '(?i)(?:twitter)(?:[0-9a-z\\-_\\t .]{0,20})(?:[\\s|\']|[\\s|""]){0,3}(?:=|>|:=|\\|\\|:|<=|=>|:)(?:\'|\\""|\\s|=|\\x60){0,5}([a-z0-9]{50})(?:[\'|\\""|\\n|\\r|\\s|\\x60|;]|$)', secretGroup: 1, keywords: ['twitter'], }, { description: 'Twitter Bearer Token', id: 'twitter-bearer-token', regex: '(?i)(?:twitter)(?:[0-9a-z\\-_\\t .]{0,20})(?:[\\s|\']|[\\s|""]){0,3}(?:=|>|:=|\\|\\|:|<=|=>|:)(?:\'|\\""|\\s|=|\\x60){0,5}(A{22}[a-zA-Z0-9%]{80,100})(?:[\'|\\""|\\n|\\r|\\s|\\x60|;]|$)', secretGroup: 1, keywords: ['twitter'], }, { description: 'Typeform API token', id: 'typeform-api-token', regex: '(?i)(?:typeform)(?:[0-9a-z\\-_\\t .]{0,20})(?:[\\s|\']|[\\s|""]){0,3}(?:=|>|:=|\\|\\|:|<=|=>|:)(?:\'|\\""|\\s|=|\\x60){0,5}(tfp_[a-z0-9\\-_\\.=]{59})(?:[\'|\\""|\\n|\\r|\\s|\\x60|;]|$)', secretGroup: 1, keywords: ['tfp_'], }, { description: 'Vault Batch Token', id: 'vault-batch-token', regex: '(?i)\\b(hvb\\.[a-z0-9_-]{138,212})(?:[\'|\\""|\\n|\\r|\\s|\\x60|;]|$)', keywords: ['hvb'], }, { description: 'Vault Service Token', id: 'vault-service-token', regex: '(?i)\\b(hvs\\.[a-z0-9_-]{90,100})(?:[\'|\\""|\\n|\\r|\\s|\\x60|;]|$)', keywords: ['hvs'], }, { description: 'Yandex Access Token', id: 'yandex-access-token', regex: '(?i)(?:yandex)(?:[0-9a-z\\-_\\t .]{0,20})(?:[\\s|\']|[\\s|""]){0,3}(?:=|>|:=|\\|\\|:|<=|=>|:)(?:\'|\\""|\\s|=|\\x60){0,5}(t1\\.[A-Z0-9a-z_-]+[=]{0,2}\\.[A-Z0-9a-z_-]{86}[=]{0,2})(?:[\'|\\""|\\n|\\r|\\s|\\x60|;]|$)', secretGroup: 1, keywords: ['yandex'], }, { description: 'Yandex API Key', id: 'yandex-api-key', regex: '(?i)(?:yandex)(?:[0-9a-z\\-_\\t .]{0,20})(?:[\\s|\']|[\\s|""]){0,3}(?:=|>|:=|\\|\\|:|<=|=>|:)(?:\'|\\""|\\s|=|\\x60){0,5}(AQVN[A-Za-z0-9_\\-]{35,38})(?:[\'|\\""|\\n|\\r|\\s|\\x60|;]|$)', secretGroup: 1, keywords: ['yandex'], }, { description: 'Yandex AWS Access Token', id: 'yandex-aws-access-token', regex: '(?i)(?:yandex)(?:[0-9a-z\\-_\\t .]{0,20})(?:[\\s|\']|[\\s|""]){0,3}(?:=|>|:=|\\|\\|:|<=|=>|:)(?:\'|\\""|\\s|=|\\x60){0,5}(YC[a-zA-Z0-9_\\-]{38})(?:[\'|\\""|\\n|\\r|\\s|\\x60|;]|$)', secretGroup: 1, keywords: ['yandex'], }, { description: 'Zendesk Secret Key', id: 'zendesk-secret-key', regex: '(?i)(?:zendesk)(?:[0-9a-z\\-_\\t .]{0,20})(?:[\\s|\']|[\\s|""]){0,3}(?:=|>|:=|\\|\\|:|<=|=>|:)(?:\'|\\""|\\s|=|\\x60){0,5}([a-z0-9]{40})(?:[\'|\\""|\\n|\\r|\\s|\\x60|;]|$)', secretGroup: 1, keywords: ['zendesk'], }, ]; export default rules; References: - src/common/secret_redaction/index.ts:50 - src/common/secret_redaction/index.ts:65 - src/common/secret_redaction/index.ts:45" You are a code assistant,Definition of 'error' in file src/common/log_types.ts in project gitlab-lsp,"Definition: error(message: string, e?: Error): void; } 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: - 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 'MultiTracker' in file src/common/tracking/multi_tracker.ts in project gitlab-lsp,"Definition: export class MultiTracker implements TelemetryTracker { #trackers: TelemetryTracker[] = []; 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, ) { this.#enabledTrackers.forEach((t) => t.setCodeSuggestionsContext(uniqueTrackingId, context)); } updateCodeSuggestionsContext( uniqueTrackingId: string, contextUpdate: Partial, ) { 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: - src/common/tracking/multi_tracker.test.ts:45 - src/node/main.ts:164 - src/browser/main.ts:110 - src/common/tracking/multi_tracker.test.ts:61 - src/common/tracking/multi_tracker.test.ts:70" You are a code assistant,Definition of 'DefaultWorkspaceService' in file src/common/workspace/workspace_service.ts in project gitlab-lsp,"Definition: export class DefaultWorkspaceService { #virtualFileSystemService: DefaultVirtualFileSystemService; #workspaceFilesMap = new Map(); #disposable: { dispose: () => void }; constructor(virtualFileSystemService: DefaultVirtualFileSystemService) { this.#virtualFileSystemService = virtualFileSystemService; this.#disposable = this.#setupEventListeners(); } #setupEventListeners() { return this.#virtualFileSystemService.onFileSystemEvent((eventType, data) => { switch (eventType) { case VirtualFileSystemEvents.WorkspaceFilesUpdate: this.#handleWorkspaceFilesUpdate(data as WorkspaceFilesUpdate); break; case VirtualFileSystemEvents.WorkspaceFileUpdate: this.#handleWorkspaceFileUpdate(data as WorkspaceFileUpdate); break; default: break; } }); } #handleWorkspaceFilesUpdate(update: WorkspaceFilesUpdate) { const files: FileSet = new Map(); for (const file of update.files) { files.set(file.toString(), file); } this.#workspaceFilesMap.set(update.workspaceFolder.uri, files); } #handleWorkspaceFileUpdate(update: WorkspaceFileUpdate) { let files = this.#workspaceFilesMap.get(update.workspaceFolder.uri); if (!files) { files = new Map(); this.#workspaceFilesMap.set(update.workspaceFolder.uri, files); } switch (update.event) { case 'add': case 'change': files.set(update.fileUri.toString(), update.fileUri); break; case 'unlink': files.delete(update.fileUri.toString()); break; default: break; } } getWorkspaceFiles(workspaceFolder: WorkspaceFolder): FileSet | undefined { return this.#workspaceFilesMap.get(workspaceFolder.uri); } dispose() { this.#disposable.dispose(); } } References:" You are a code assistant,Definition of 'AdvancedContextService' in file src/common/advanced_context/advanced_context_service.ts in project gitlab-lsp,"Definition: export const AdvancedContextService = createInterfaceId('AdvancedContextService'); @Injectable(AdvancedContextService, [ ConfigService, LsConnection, DocumentService, DocumentTransformerService, SupportedLanguagesService, ]) export class DefaultAdvancedContextService implements AdvancedContextService { #configService: ConfigService; #documentTransformer: DocumentTransformerService; #supportedLanguagesService: SupportedLanguagesService; constructor( configService: ConfigService, connection: LsConnection, documentService: DocumentService, documentTransformer: DocumentTransformerService, supportedLanguagesService: SupportedLanguagesService, ) { this.#configService = configService; this.#documentTransformer = documentTransformer; this.#supportedLanguagesService = supportedLanguagesService; const subscription = documentService.onDocumentChange(async ({ document }, handlerType) => { await this.#updateAdvancedContext(document, handlerType); }); connection.onShutdown(() => subscription.dispose()); } /** * Currently updates the LRU cache with the most recently accessed files in the workspace. * We only update the advanced context for supported languages. We also ensure to run * documents through the `DocumentTransformer` to ensure the secret redaction is applied. */ async #updateAdvancedContext( document: TextDocument, handlerType: TextDocumentChangeListenerType, ) { const lruCache = LruCache.getInstance(LRU_CACHE_BYTE_SIZE_LIMIT); // eslint-disable-next-line default-case switch (handlerType) { case TextDocumentChangeListenerType.onDidClose: { // We don't check if the language is supported for `onDidClose` because we want // always attempt to delete the file from the cache. const fileDeleted = lruCache.deleteFile(document.uri); if (fileDeleted) { log.debug(`Advanced Context: File ${document.uri} was deleted from the LRU cache`); } else { log.debug(`Advanced Context: File ${document.uri} was not found in the LRU cache`); } break; } case TextDocumentChangeListenerType.onDidChangeContent: case TextDocumentChangeListenerType.onDidSave: case TextDocumentChangeListenerType.onDidOpen: case TextDocumentChangeListenerType.onDidSetActive: { const languageEnabled = this.#supportedLanguagesService.isLanguageEnabled( document.languageId, ); if (!languageEnabled) { return; } const context = this.#documentTransformer.getContext( document.uri, { line: 0, character: 0 }, this.#configService.get().client.workspaceFolders ?? [], undefined, ); if (!context) { log.debug(`Advanced Context: document context for ${document.uri} was not found`); return; } lruCache.updateFile(context); log.debug(`Advanced Context: uri ${document.uri} was updated in the MRU cache`); break; } } } } References:" You are a code assistant,Definition of 'Feature' in file src/common/feature_state/feature_state_management_types.ts in project gitlab-lsp,"Definition: export type Feature = typeof CODE_SUGGESTIONS | typeof CHAT; // | typeof WORKFLOW; export const NO_LICENSE = 'code-suggestions-no-license' as const; export const DUO_DISABLED_FOR_PROJECT = 'duo-disabled-for-project' as const; export const UNSUPPORTED_GITLAB_VERSION = 'unsupported-gitlab-version' as const; export const UNSUPPORTED_LANGUAGE = 'code-suggestions-document-unsupported-language' as const; export const DISABLED_LANGUAGE = 'code-suggestions-document-disabled-language' as const; export type StateCheckId = | typeof NO_LICENSE | typeof DUO_DISABLED_FOR_PROJECT | typeof UNSUPPORTED_GITLAB_VERSION | typeof UNSUPPORTED_LANGUAGE | typeof DISABLED_LANGUAGE; export interface FeatureStateCheck { checkId: StateCheckId; details?: string; } export interface FeatureState { featureId: Feature; engagedChecks: FeatureStateCheck[]; } const CODE_SUGGESTIONS_CHECKS_PRIORITY_ORDERED = [ DUO_DISABLED_FOR_PROJECT, UNSUPPORTED_LANGUAGE, DISABLED_LANGUAGE, ]; const CHAT_CHECKS_PRIORITY_ORDERED = [DUO_DISABLED_FOR_PROJECT]; export const CHECKS_PER_FEATURE: { [key in Feature]: StateCheckId[] } = { [CODE_SUGGESTIONS]: CODE_SUGGESTIONS_CHECKS_PRIORITY_ORDERED, [CHAT]: CHAT_CHECKS_PRIORITY_ORDERED, // [WORKFLOW]: [], }; References: - src/common/feature_state/feature_state_management_types.ts:25" You are a code assistant,Definition of 'build' in file scripts/esbuild/common.ts in project gitlab-lsp,"Definition: async function build() { await esbuild.build(config); } void build(); References: - scripts/esbuild/browser.ts:26 - scripts/esbuild/desktop.ts:41 - scripts/esbuild/common.ts:31" You are a code assistant,Definition of 'DirectConnectionClient' in file src/common/suggestion_client/direct_connection_client.ts in project gitlab-lsp,"Definition: export class DirectConnectionClient implements SuggestionClient { #api: GitLabApiClient; #connectionDetails: IDirectConnectionDetails | undefined; #configService: ConfigService; #isValidApi = true; #connectionDetailsCircuitBreaker = new ExponentialBackoffCircuitBreaker( 'Code Suggestions Direct connection details', { maxBackoffMs: HOUR, initialBackoffMs: SECOND, backoffMultiplier: 3, }, ); #directConnectionCircuitBreaker = new ExponentialBackoffCircuitBreaker( 'Code Suggestions Direct Connection', { initialBackoffMs: SECOND, maxBackoffMs: 10 * MINUTE, backoffMultiplier: 5, }, ); constructor(api: GitLabApiClient, configService: ConfigService) { this.#api = api; this.#configService = configService; this.#api.onApiReconfigured(({ isInValidState }) => { this.#connectionDetails = undefined; this.#isValidApi = isInValidState; this.#directConnectionCircuitBreaker.success(); // resets the circuit breaker // TODO: fetch the direct connection details https://gitlab.com/gitlab-org/editor-extensions/gitlab-lsp/-/issues/239 }); } #fetchDirectConnectionDetails = async () => { if (this.#connectionDetailsCircuitBreaker.isOpen()) { return; } let details; try { details = await this.#api.fetchFromApi({ type: 'rest', method: 'POST', path: '/code_suggestions/direct_access', supportedSinceInstanceVersion: { version: '17.2.0', resourceName: 'get direct connection details', }, }); } catch (e) { // 401 indicates that the user has GitLab Duo disabled and shout result in longer periods of open circuit if (isFetchError(e) && e.status === 401) { this.#connectionDetailsCircuitBreaker.megaError(); } else { this.#connectionDetailsCircuitBreaker.error(); } log.info( `Failed to fetch direct connection details from GitLab instance. Code suggestion requests will be sent to your GitLab instance. Error ${e}`, ); } this.#connectionDetails = details; this.#configService.merge({ client: { snowplowTrackerOptions: transformHeadersToSnowplowOptions(details?.headers) }, }); }; async #fetchUsingDirectConnection(request: CodeSuggestionRequest): Promise { if (!this.#connectionDetails) { throw new Error('Assertion error: connection details are undefined'); } const suggestionEndpoint = `${this.#connectionDetails.base_url}/v2/completions`; const start = Date.now(); const response = await fetch(suggestionEndpoint, { method: 'post', body: JSON.stringify(request), keepalive: true, headers: { ...this.#connectionDetails.headers, Authorization: `Bearer ${this.#connectionDetails.token}`, 'X-Gitlab-Authentication-Type': 'oidc', 'X-Gitlab-Language-Server-Version': getLanguageServerVersion(), 'Content-Type': ' application/json', }, signal: AbortSignal.timeout(5 * SECOND), }); await handleFetchError(response, 'Direct Connection for code suggestions'); const data = await response.json(); const end = Date.now(); log.debug(`Direct connection (${suggestionEndpoint}) suggestion fetched in ${end - start}ms`); return data; } async getSuggestions(context: SuggestionContext): Promise { // TODO we would like to send direct request only for intent === COMPLETION // however, currently we are not certain that the intent is completion // when we finish the following two issues, we can be certain that the intent is COMPLETION // // https://gitlab.com/gitlab-org/editor-extensions/gitlab-lsp/-/issues/173 // https://gitlab.com/gitlab-org/editor-extensions/gitlab-lsp/-/issues/247 if (context.intent === GENERATION) { return undefined; } if (!this.#isValidApi) { return undefined; } if (this.#directConnectionCircuitBreaker.isOpen()) { return undefined; } if (!this.#connectionDetails || areExpired(this.#connectionDetails)) { this.#fetchDirectConnectionDetails().catch( (e) => log.error(`#fetchDirectConnectionDetails error: ${e}`), // this makes eslint happy, the method should never throw ); return undefined; } try { const response = await this.#fetchUsingDirectConnection( createV2Request(context, this.#connectionDetails.model_details), ); return response && { ...response, isDirectConnection: true }; } catch (e) { this.#directConnectionCircuitBreaker.error(); log.warn( 'Direct connection for code suggestions failed. Code suggestion requests will be sent to your GitLab instance.', e, ); } return undefined; } } References: - src/common/suggestion_client/direct_connection_client.test.ts:25 - src/common/suggestion/suggestion_service.ts:161 - src/common/suggestion_client/direct_connection_client.test.ts:159 - src/common/suggestion_client/direct_connection_client.test.ts:112 - src/common/suggestion_client/direct_connection_client.test.ts:39 - src/common/suggestion/suggestion_service.test.ts:458 - src/common/suggestion_client/direct_connection_client.test.ts:62" You are a code assistant,Definition of 'setupTransportEventHandlers' in file packages/lib_webview/src/setup/transport/utils/setup_transport_event_handlers.ts in project gitlab-lsp,"Definition: export const setupTransportEventHandlers = ( transport: Transport, runtimeMessageBus: WebviewRuntimeMessageBus, managedInstances: ManagedInstances, ): Disposable[] => [ transport.on('webview_instance_created', (address: WebviewAddress) => { managedInstances.add(address.webviewInstanceId); runtimeMessageBus.publish('webview:connect', address); }), transport.on('webview_instance_destroyed', (address: WebviewAddress) => { managedInstances.delete(address.webviewInstanceId); runtimeMessageBus.publish('webview:disconnect', address); }), transport.on('webview_instance_notification_received', (message) => runtimeMessageBus.publish('webview:notification', message), ), transport.on('webview_instance_request_received', (message) => runtimeMessageBus.publish('webview:request', message), ), transport.on('webview_instance_response_received', (message) => runtimeMessageBus.publish('webview:response', message), ), ]; References: - packages/lib_webview/src/setup/transport/utils/setup_transport_event_handlers.test.ts:42 - packages/lib_webview/src/setup/transport/utils/setup_transport_event_handlers.test.ts:32 - packages/lib_webview/src/setup/transport/setup_transport.ts:20" 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 = 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 { 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 { 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({ 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 { const params = { ...DEFAULT_INITIALIZE_PARAMS, ...initializeParams }; const request = new RequestType( 'initialize', ); const response = await this.#connection.sendRequest(request, params); return response; } /** * Send the LSP 'initialized' notification */ public async sendInitialized(options?: InitializedParams | undefined): Promise { const defaults = {}; const params = { ...defaults, ...options }; const request = new NotificationType('initialized'); await this.#connection.sendNotification(request, params); } /** * Send the LSP 'workspace/didChangeConfiguration' notification */ public async sendDidChangeConfiguration( options?: ChangeConfigOptions | undefined, ): Promise { const defaults = createFakePartial({ settings: { token: this.#gitlabToken, baseUrl: this.#gitlabBaseUrl, codeCompletion: { enableSecretRedaction: true, }, telemetry: { enabled: false, }, }, }); const params = { ...defaults, ...options }; const request = new NotificationType( 'workspace/didChangeConfiguration', ); await this.#connection.sendNotification(request, params); } public async sendTextDocumentDidOpen( uri: string, languageId: string, version: number, text: string, ): Promise { const params = { textDocument: { uri, languageId, version, text, }, }; const request = new NotificationType('textDocument/didOpen'); await this.#connection.sendNotification(request, params); } public async sendTextDocumentDidClose(uri: string): Promise { const params = { textDocument: { uri, }, }; const request = new NotificationType('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 { const params = { textDocument: { uri, version, }, contentChanges: [{ text }], }; const request = new NotificationType('textDocument/didChange'); await this.#connection.sendNotification(request, params); } public async sendTextDocumentCompletion( uri: string, line: number, character: number, ): Promise { 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 { await this.#connection.sendNotification(DidChangeDocumentInActiveEditor, uri); } public async getWebviewMetadata(): Promise { const result = await this.#connection.sendRequest( '$/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 {} 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, ): void; updateCodeSuggestionsContext( uniqueTrackingId: string, contextUpdate: Partial, ): void; rejectOpenedSuggestions(): void; updateSuggestionState(uniqueTrackingId: string, newState: TRACKING_EVENTS): void; } export const TelemetryTracker = createInterfaceId('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 {} async destroy(): Promise {} async fetch(input: RequestInfo | URL, init?: RequestInit): Promise { 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 { // Stub. Should delegate to the node or browser fetch implementations throw new Error('Not implemented'); yield ''; } async delete(input: RequestInfo | URL, init?: RequestInit): Promise { return this.fetch(input, this.updateRequestInit('DELETE', init)); } async get(input: RequestInfo | URL, init?: RequestInit): Promise { return this.fetch(input, this.updateRequestInit('GET', init)); } async post(input: RequestInfo | URL, init?: RequestInit): Promise { return this.fetch(input, this.updateRequestInit('POST', init)); } async put(input: RequestInfo | URL, init?: RequestInit): Promise { return this.fetch(input, this.updateRequestInit('PUT', init)); } async fetchBase(input: RequestInfo | URL, init?: RequestInit): Promise { // 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.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.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.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 implements WebviewMessageBus, Disposable { #address: WebviewAddress; #runtimeMessageBus: WebviewRuntimeMessageBus; #eventSubscriptions = new CompositeDisposable(); #notificationEvents = new SimpleRegistry(); #requestEvents = new SimpleRegistry(); #pendingResponseEvents = new SimpleRegistry(); #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 { 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); } 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 { let buffer = ''; const decoder = new TextDecoder(); async function* readStream( stream: ReadableStream, ): AsyncGenerator { 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 { 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: '' } : {}), ...(cert ? { cert: '' } : {}), ...(key ? { key: '' } : {}), }; } } 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 { 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, ) { 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, ) { 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, ) { this.#enabledTrackers.forEach((t) => t.setCodeSuggestionsContext(uniqueTrackingId, context)); } updateCodeSuggestionsContext( uniqueTrackingId: string, contextUpdate: Partial, ) { 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( type: T, handler: (payload: TMessageMap['inbound']['notifications'][T]) => void, ): Disposable { return this.#handlers.notification.register({ webviewId: this.#webviewId, type }, handler); } sendRequest( type: T, payload?: TMessageMap['outbound']['requests'][T]['params'], ): Promise> { return this.#connection.sendRequest(this.#rpcMethods.request, { webviewId: this.#webviewId, type, payload, }); } async sendNotification( type: T, payload?: TMessageMap['outbound']['notifications'][T], ): Promise { 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; 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 { 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, ) => { // 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(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; if (!filter || filter(data)) { listener(data); } }); } } public hasListeners(messageType: K): boolean { return this.#subscriptions.has(messageType); } public listenerCount(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'); const createNotifyFn = (c: LsConnection, method: NotificationType) => (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(method: NotificationType, notifier: Notifier) { 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; 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; supportedSinceInstanceVersion?: SupportedSinceInstanceVersion; } export type ApiRequest<_TReturnType> = | GetRequest<_TReturnType> | PostRequest<_TReturnType> | GraphQLRequest<_TReturnType>; export interface GitLabApiClient { fetchFromApi(request: ApiRequest): Promise; connectToCable(): Promise; } 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 => { 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('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( 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; fetchBase(input: RequestInfo | URL, init?: RequestInit): Promise; delete(input: RequestInfo | URL, init?: RequestInit): Promise; get(input: RequestInfo | URL, init?: RequestInit): Promise; post(input: RequestInfo | URL, init?: RequestInit): Promise; put(input: RequestInfo | URL, init?: RequestInit): Promise; updateAgentOptions(options: FetchAgentOptions): void; streamFetch(url: string, body: string, headers: FetchHeaders): AsyncGenerator; } export const LsFetch = createInterfaceId('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 {} async destroy(): Promise {} async fetch(input: RequestInfo | URL, init?: RequestInit): Promise { 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 { // Stub. Should delegate to the node or browser fetch implementations throw new Error('Not implemented'); yield ''; } async delete(input: RequestInfo | URL, init?: RequestInit): Promise { return this.fetch(input, this.updateRequestInit('DELETE', init)); } async get(input: RequestInfo | URL, init?: RequestInit): Promise { return this.fetch(input, this.updateRequestInit('GET', init)); } async post(input: RequestInfo | URL, init?: RequestInit): Promise { return this.fetch(input, this.updateRequestInit('POST', init)); } async put(input: RequestInfo | URL, init?: RequestInit): Promise { return this.fetch(input, this.updateRequestInit('PUT', init)); } async fetchBase(input: RequestInfo | URL, init?: RequestInit): Promise { // 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'); @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 = (key?: string) => { return key ? get(this.#config, key) : this.#config; }; set: TypedSetter = (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) { 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'); @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 { (eventType: T, data: FileSystemEventMap[T]): void; } export type VirtualFileSystemService = typeof DefaultVirtualFileSystemService.prototype; export const VirtualFileSystemService = createInterfaceId( '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 { 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( 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 { 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 { 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 { 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 { 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( type: K, callback: TransportMessageHandler, ): 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 { 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 { let buffer = ''; const decoder = new TextDecoder(); async function* readStream( stream: ReadableStream, ): AsyncGenerator { 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 { 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: '' } : {}), ...(cert ? { cert: '' } : {}), ...(key ? { key: '' } : {}), }; } } 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 { (eventType: T, data: FileSystemEventMap[T]): void; } export type VirtualFileSystemService = typeof DefaultVirtualFileSystemService.prototype; export const VirtualFileSystemService = createInterfaceId( '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 { 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( 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 = { [P in keyof T]-?: T[P]; }; const DEFAULT_CONFIG: Required = { enabled: true, maxSize: 1024 * 1024, ttl: 60 * 1000, prefixLines: 1, suffixLines: 1, }; export class SuggestionsCache { #cache: LRUCache; #configService: ConfigService; constructor(configService: ConfigService) { this.#configService = configService; const currentConfig = this.#getCurrentConfig(); this.#cache = new LRUCache({ 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 { 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, ): FastifyPluginRegistration> => { 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; }; export const createMockFastifyInstance = (): MockFastifyInstance & FastifyInstance => { const reply: Partial = {}; 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('DocumentsWrapper'); const DOCUMENT_CHANGE_EVENT_NAME = 'documentChange'; export class DefaultDocumentService implements DocumentService, HandlesNotification { #subscriptions: Disposable[] = []; #emitter = new EventEmitter(); #documents: TextDocuments; constructor(documents: TextDocuments) { 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 = { document }; this.#emitter.emit( DOCUMENT_CHANGE_EVENT_NAME, event, TextDocumentChangeListenerType.onDidSetActive, ); }; #createMediatorListener = (type: TextDocumentChangeListenerType) => (event: TextDocumentChangeEvent) => { 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(); 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( type: K, callback: TransportMessageHandler, ): Disposable; } export interface TransportPublisher { publish(type: K, payload: MessagesToClient[K]): Promise; } 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 { 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 { 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; getWorkflowEvents(id: string): Promise; } export const workflowPluginFactory = ( graphqlApi: WorkflowGraphQLService, workflowApi: WorkflowAPI, connection: Connection, ): WebviewPlugin => { 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.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 { 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'); 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 { 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 { 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, ) { this.#enabledTrackers.forEach((t) => t.setCodeSuggestionsContext(uniqueTrackingId, context)); } updateCodeSuggestionsContext( uniqueTrackingId: string, contextUpdate: Partial, ) { 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 implements HandlerRegistry { #hashFunc: HashFunc; #basicRegistry: SimpleRegistry; constructor(hashFunc: HashFunc) { this.#hashFunc = hashFunc; this.#basicRegistry = new SimpleRegistry(); } 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): Promise> { 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(); #lsFetch: LsFetch; #featureFlagService: FeatureFlagService; #gitlabRealm: GitlabRealm = GitlabRealm.saas; #codeSuggestionsContextMap = new Map(); 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, ) { 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, ) { 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 { 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 { 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( 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; updateAgentOptions(options: FetchAgentOptions): void; streamFetch(url: string, body: string, headers: FetchHeaders): AsyncGenerator; } export const LsFetch = createInterfaceId('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 {} async destroy(): Promise {} async fetch(input: RequestInfo | URL, init?: RequestInit): Promise { 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 { // Stub. Should delegate to the node or browser fetch implementations throw new Error('Not implemented'); yield ''; } async delete(input: RequestInfo | URL, init?: RequestInit): Promise { return this.fetch(input, this.updateRequestInit('DELETE', init)); } async get(input: RequestInfo | URL, init?: RequestInit): Promise { return this.fetch(input, this.updateRequestInit('GET', init)); } async post(input: RequestInfo | URL, init?: RequestInit): Promise { return this.fetch(input, this.updateRequestInit('POST', init)); } async put(input: RequestInfo | URL, init?: RequestInit): Promise { return this.fetch(input, this.updateRequestInit('PUT', init)); } async fetchBase(input: RequestInfo | URL, init?: RequestInit): Promise { // 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; } /** * 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; headers?: Record; } export interface GetRequest<_TReturnType> extends GetRequestBase<_TReturnType> { type: 'rest'; } export interface GetBufferRequest extends GetRequestBase { type: 'rest-buffer'; } export interface GraphQLRequest<_TReturnType> { type: 'graphql'; query: string; /** Options passed to the GraphQL query */ variables: Record; } 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; /* 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; /** * 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; /** * 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; getForAllAccounts(): Promise; /** * Returns GitLabPlatformForAccount if there is a SaaS account added. Otherwise returns undefined. */ getForSaaSAccount(): Promise; } 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; } /** * 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; headers?: Record; } export interface GetRequest<_TReturnType> extends GetRequestBase<_TReturnType> { type: 'rest'; } export interface GetBufferRequest extends GetRequestBase { type: 'rest-buffer'; } export interface GraphQLRequest<_TReturnType> { type: 'graphql'; query: string; /** Options passed to the GraphQL query */ variables: Record; } 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; /* 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', ); @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, 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 => { 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 => { 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 => { 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 => { 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 { 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 { 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 { 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 { 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 { 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('InitializeHandler'); @Injectable(DidChangeWorkspaceFoldersHandler, [ConfigService]) export class DefaultDidChangeWorkspaceFoldersHandler implements DidChangeWorkspaceFoldersHandler { #configService: ConfigService; constructor(configService: ConfigService) { this.#configService = configService; } notificationHandler: NotificationHandler = ( 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; constructor({ languages }: { languages: TreeSitterLanguageInfo[] }) { this.languages = this.buildTreeSitterInfoByExtMap(languages); this.loadState = TreeSitterParserLoadState.INIT; } get loadStateValue(): TreeSitterParserLoadState { return this.loadState; } async parseFile(context: IDocContext): Promise { 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 { 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 { 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 { return languages.reduce((map, language) => { for (const extension of language.extensions) { map.set(extension, language); } return map; }, new Map()); } } 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', ); @Injectable(SupportedLanguagesService, [ConfigService]) export class DefaultSupportedLanguagesService implements SupportedLanguagesService { #enabledLanguages: Set; #supportedLanguages: Set; #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 = 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 { const workflowId = this.generateWorkflowID(id); let timeout: NodeJS.Timeout; const poll = async (): Promise => { 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 { 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(FEATURE_STATE_CHANGE); export interface TokenCheckNotificationParams { message?: string; } export const TokenCheckNotificationType = new NotificationType( 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( '$/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({ 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( type: T, payload?: TMessageMap['outbound']['notifications'][T], ): Promise { 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" You are a code assistant,Definition of 'onRequest' in file src/common/webview/extension/extension_connection_message_bus.ts in project gitlab-lsp,"Definition: onRequest( type: T, handler: ( payload: TMessageMap['inbound']['requests'][T]['params'], ) => Promise>, ): Disposable { return this.#handlers.request.register({ webviewId: this.#webviewId, type }, handler); } onNotification( type: T, handler: (payload: TMessageMap['inbound']['notifications'][T]) => void, ): Disposable { return this.#handlers.notification.register({ webviewId: this.#webviewId, type }, handler); } sendRequest( type: T, payload?: TMessageMap['outbound']['requests'][T]['params'], ): Promise> { return this.#connection.sendRequest(this.#rpcMethods.request, { webviewId: this.#webviewId, type, payload, }); } async sendNotification( type: T, payload?: TMessageMap['outbound']['notifications'][T], ): Promise { await this.#connection.sendNotification(this.#rpcMethods.notification, { webviewId: this.#webviewId, type, payload, }); } } References:" You are a code assistant,Definition of 'RequestId' in file packages/lib_webview/src/setup/plugin/webview_instance_message_bus.ts in project gitlab-lsp,"Definition: type RequestId = string; type NotificationHandler = (payload: unknown) => void; type RequestHandler = (requestId: RequestId, payload: unknown) => void; type ResponseHandler = (message: ResponseMessage) => void; export class WebviewInstanceMessageBus implements WebviewMessageBus, Disposable { #address: WebviewAddress; #runtimeMessageBus: WebviewRuntimeMessageBus; #eventSubscriptions = new CompositeDisposable(); #notificationEvents = new SimpleRegistry(); #requestEvents = new SimpleRegistry(); #pendingResponseEvents = new SimpleRegistry(); #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 { 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); } 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: - packages/lib_webview/src/setup/plugin/webview_instance_message_bus.ts:140 - packages/lib_webview/src/setup/plugin/webview_instance_message_bus.ts:12" You are a code assistant,Definition of 'ChatMessages' in file packages/webview-chat/src/plugin/index.ts in project gitlab-lsp,"Definition: type ChatMessages = CreatePluginMessageMap<{ webviewToPlugin: { notifications: { newUserPrompt: { prompt: string; }; }; }; pluginToWebview: { notifications: { newUserPrompt: { prompt: string; }; }; }; }>; export const chatWebviewPlugin: WebviewPlugin = { id: WEBVIEW_ID, title: WEBVIEW_TITLE, setup: ({ webview }) => { webview.onInstanceConnected((_webviewInstanceId, messageBus) => { messageBus.sendNotification('newUserPrompt', { prompt: 'This is a new prompt', }); }); }, }; References:" You are a code assistant,Definition of 'constructor' in file src/tests/fixtures/intent/empty_function/typescript.ts in project gitlab-lsp,"Definition: constructor(name) { this.name = name; } greet() { console.log(`Hello ${this.name}`); } } class Greet3 {} function* generateGreetings() {} function* greetGenerator() { yield 'Hello'; } References:" You are a code assistant,Definition of 'updateAgentOptions' in file src/common/fetch.ts in project gitlab-lsp,"Definition: updateAgentOptions(_opts: FetchAgentOptions): void {} } References:" You are a code assistant,Definition of 'Greet3' in file src/tests/fixtures/intent/empty_function/ruby.rb in project gitlab-lsp,"Definition: class Greet3 end def generate_greetings end def greet_generator yield 'Hello' end References: - src/tests/fixtures/intent/empty_function/ruby.rb:34" You are a code assistant,Definition of 'Greet4' in file src/tests/fixtures/intent/empty_function/python.py in project gitlab-lsp,"Definition: class Greet4: def __init__(self, name): def greet(self): class Greet3: References:" You are a code assistant,Definition of 'constructor' in file src/common/tracking/snowplow_tracker.ts in project gitlab-lsp,"Definition: 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, ) { 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, ) { 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 'getCommentResolver' in file src/common/tree_sitter/comments/comment_resolver.ts in project gitlab-lsp,"Definition: export function getCommentResolver(): CommentResolver { if (!commentResolver) { commentResolver = new CommentResolver(); } return commentResolver; } References: - src/common/tree_sitter/intent_resolver.ts:36 - src/common/tree_sitter/comments/comment_resolver.test.ts:335 - src/common/tree_sitter/comments/comment_resolver.test.ts:336" You are a code assistant,Definition of 'RequestMessage' in file packages/lib_webview/src/events/webview_runtime_message_bus.ts in project gitlab-lsp,"Definition: export type RequestMessage = NotificationMessage & { requestId: string; }; export type SuccessfulResponse = WebviewAddress & { requestId: string; success: true; type: string; payload?: unknown; }; 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 {} References: - packages/lib_webview/src/events/webview_runtime_message_bus.ts:36 - packages/lib_webview/src/events/webview_runtime_message_bus.ts:33" You are a code assistant,Definition of 'AiContextItemSubType' in file src/common/ai_context_management_2/ai_context_item.ts in project gitlab-lsp,"Definition: export type AiContextItemSubType = 'open_tab' | 'local_file_search'; export type AiContextItem = { id: string; name: string; isEnabled: boolean; info: AiContextItemInfo; type: AiContextItemType; } & ( | { type: 'issue' | 'merge_request'; subType?: never } | { type: 'file'; subType: AiContextItemSubType } ); export type AiContextItemWithContent = AiContextItem & { content: string; }; References: - src/common/ai_context_management_2/ai_context_item.ts:20" You are a code assistant,Definition of 'updateAgentOptions' in file src/common/fetch.ts in project gitlab-lsp,"Definition: updateAgentOptions(options: FetchAgentOptions): void; streamFetch(url: string, body: string, headers: FetchHeaders): AsyncGenerator; } export const LsFetch = createInterfaceId('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 {} async destroy(): Promise {} async fetch(input: RequestInfo | URL, init?: RequestInit): Promise { 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 { // Stub. Should delegate to the node or browser fetch implementations throw new Error('Not implemented'); yield ''; } async delete(input: RequestInfo | URL, init?: RequestInit): Promise { return this.fetch(input, this.updateRequestInit('DELETE', init)); } async get(input: RequestInfo | URL, init?: RequestInit): Promise { return this.fetch(input, this.updateRequestInit('GET', init)); } async post(input: RequestInfo | URL, init?: RequestInit): Promise { return this.fetch(input, this.updateRequestInit('POST', init)); } async put(input: RequestInfo | URL, init?: RequestInit): Promise { return this.fetch(input, this.updateRequestInit('PUT', init)); } async fetchBase(input: RequestInfo | URL, init?: RequestInit): Promise { // 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 'Record' in file packages/webview_duo_chat/src/contract.ts in project gitlab-lsp,"Definition: type Record = { id: string; }; export interface GitlabChatSlashCommand { name: string; description: string; shouldSubmit?: boolean; } export interface WebViewInitialStateInterface { slashCommands: GitlabChatSlashCommand[]; } export type Messages = CreatePluginMessageMap<{ pluginToWebview: { notifications: { newRecord: Record; updateRecord: Record; setLoadingState: boolean; cleanChat: undefined; }; }; webviewToPlugin: { notifications: { onReady: undefined; cleanChat: undefined; newPrompt: { record: { content: string; }; }; trackFeedback: { data?: { extendedTextFeedback: string | null; feedbackChoices: Array | null; }; }; }; }; pluginToExtension: { notifications: { showErrorMessage: { message: string; }; }; }; }>; References: - packages/webview_duo_chat/src/contract.ts:24 - packages/webview_duo_chat/src/contract.ts:23" You are a code assistant,Definition of 'SocketIOWebViewTransport' in file packages/lib_webview_transport_socket_io/src/socket_io_webview_transport.ts in project gitlab-lsp,"Definition: export class SocketIOWebViewTransport implements Transport { #server: Server; #logger?: Logger; #messageEmitter = createWebviewTransportEventEmitter(); #connections: Map = new Map(); constructor(server: Server, logger?: Logger) { this.#server = server; this.#logger = logger ? withPrefix(logger, LOGGER_PREFIX) : undefined; this.#initialize(); } #initialize(): void { this.#logger?.debug('Initializing webview transport'); const namespace = this.#server.of(NAMESPACE_REGEX_PATTERN); namespace.on('connection', (socket) => { const match = socket.nsp.name.match(NAMESPACE_REGEX_PATTERN); if (!match) { this.#logger?.error('Failed to parse namespace for socket connection'); return; } const webviewId = match[1] as WebviewId; const webviewInstanceId = randomUUID() as WebviewInstanceId; const webviewInstanceInfo: WebviewInstanceInfo = { webviewId, webviewInstanceId, }; const connectionId = buildConnectionId(webviewInstanceInfo); this.#connections.set(connectionId, socket); this.#messageEmitter.emit('webview_instance_created', webviewInstanceInfo); socket.on(SOCKET_NOTIFICATION_CHANNEL, (message: unknown) => { if (!isSocketNotificationMessage(message)) { this.#logger?.debug(`[${connectionId}] received notification with invalid format`); return; } this.#logger?.debug(`[${connectionId}] received notification`); this.#messageEmitter.emit('webview_instance_notification_received', { ...webviewInstanceInfo, type: message.type, payload: message.payload, }); }); socket.on(SOCKET_REQUEST_CHANNEL, (message: unknown) => { if (!isSocketRequestMessage(message)) { this.#logger?.debug(`[${connectionId}] received request with invalid format`); return; } this.#logger?.debug(`[${connectionId}] received request`); this.#messageEmitter.emit('webview_instance_request_received', { ...webviewInstanceInfo, type: message.type, payload: message.payload, requestId: message.requestId, }); }); socket.on(SOCKET_RESPONSE_CHANNEL, (message: unknown) => { if (!isSocketResponseMessage(message)) { this.#logger?.debug(`[${connectionId}] received response with invalid format`); return; } this.#logger?.debug(`[${connectionId}] received response`); this.#messageEmitter.emit('webview_instance_response_received', { ...webviewInstanceInfo, type: message.type, payload: message.payload, requestId: message.requestId, success: message.success, reason: message.reason ?? '', }); }); socket.on('error', (error) => { this.#logger?.debug(`[${connectionId}] error`, error); }); socket.on('disconnect', (reason) => { this.#logger?.debug(`[${connectionId}] disconnected with reason: ${reason}`); this.#connections.delete(connectionId); this.#messageEmitter.emit('webview_instance_destroyed', webviewInstanceInfo); }); }); this.#logger?.debug('transport initialized'); } async publish( type: K, message: MessagesToClient[K], ): Promise { const connectionId = buildConnectionId({ webviewId: message.webviewId, webviewInstanceId: message.webviewInstanceId, }); const connection = this.#connections.get(connectionId); if (!connection) { this.#logger?.error(`No active socket found for ID ${connectionId}`); return; } switch (type) { case 'webview_instance_notification': connection.emit(SOCKET_NOTIFICATION_CHANNEL, { type: message.type, payload: message.payload, }); return; case 'webview_instance_request': connection.emit(SOCKET_REQUEST_CHANNEL, { type: message.type, payload: message.payload, requestId: (message as MessagesToClient['webview_instance_request']).requestId, }); return; case 'webview_instance_response': connection.emit(SOCKET_RESPONSE_CHANNEL, { type: message.type, payload: message.payload, requestId: (message as MessagesToClient['webview_instance_response']).requestId, }); return; default: this.#logger?.error(`Unknown message type ${type}`); } } on( type: K, callback: TransportMessageHandler, ): 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: - src/node/setup_http.ts:21" You are a code assistant,Definition of 'AiCompletionResponseChannelEvents' in file packages/webview_duo_chat/src/plugin/port/api/graphql/ai_completion_response_channel.ts in project gitlab-lsp,"Definition: interface AiCompletionResponseChannelEvents extends ChannelEvents { systemMessage: (msg: AiCompletionResponseMessageType) => void; newChunk: (msg: AiCompletionResponseMessageType) => void; fullMessage: (msg: AiCompletionResponseMessageType) => void; } export class AiCompletionResponseChannel extends Channel< AiCompletionResponseParams, AiCompletionResponseResponseType, AiCompletionResponseChannelEvents > { static identifier = 'GraphqlChannel'; constructor(params: AiCompletionResponseInput) { super({ channel: 'GraphqlChannel', operationName: 'aiCompletionResponse', query: AI_MESSAGE_SUBSCRIPTION_QUERY, variables: JSON.stringify(params), }); } receive(message: AiCompletionResponseResponseType) { if (!message.result.data.aiCompletionResponse) return; const data = message.result.data.aiCompletionResponse; if (data.role.toLowerCase() === 'system') { this.emit('systemMessage', data); } else if (data.chunkId) { this.emit('newChunk', data); } else { this.emit('fullMessage', data); } } } References:" You are a code assistant,Definition of 'GITLAB_COM_URL' in file packages/webview_duo_chat/src/plugin/port/constants.ts in project gitlab-lsp,"Definition: export const GITLAB_COM_URL = 'https://gitlab.com'; export const CONFIG_NAMESPACE = 'gitlab'; export const DO_NOT_SHOW_CODE_SUGGESTIONS_VERSION_WARNING = 'DO_NOT_SHOW_VERSION_WARNING'; // NOTE: This needs to _always_ be a 3 digits export const MINIMUM_CODE_SUGGESTIONS_VERSION = '16.8.0'; export const DO_NOT_SHOW_VERSION_WARNING = 'DO_NOT_SHOW_VERSION_WARNING'; // NOTE: This needs to _always_ be a 3 digits 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 'TestStreamProcessor' in file src/common/suggestion_client/post_processors/post_processor_pipeline.test.ts in project gitlab-lsp,"Definition: class TestStreamProcessor extends PostProcessor { async processStream( _context: IDocContext, input: StreamingCompletionResponse, ): Promise { return { ...input, completion: `${input.completion} processed` }; } async processCompletion( _context: IDocContext, input: SuggestionOption[], ): Promise { return input; } } pipeline.addProcessor(new TestStreamProcessor()); const streamInput: StreamingCompletionResponse = { id: '1', completion: 'test', done: false }; const result = await pipeline.run({ documentContext: mockContext, input: streamInput, type: 'stream', }); expect(result).toEqual({ id: '1', completion: 'test processed', done: false }); }); test('should process completion input correctly', async () => { class TestCompletionProcessor extends PostProcessor { async processStream( _context: IDocContext, input: StreamingCompletionResponse, ): Promise { return input; } async processCompletion( _context: IDocContext, input: SuggestionOption[], ): Promise { return input.map((option) => ({ ...option, text: `${option.text} processed` })); } } pipeline.addProcessor(new TestCompletionProcessor()); const completionInput: SuggestionOption[] = [{ text: 'option1', uniqueTrackingId: '1' }]; const result = await pipeline.run({ documentContext: mockContext, input: completionInput, type: 'completion', }); expect(result).toEqual([{ text: 'option1 processed', uniqueTrackingId: '1' }]); }); test('should chain multiple processors correctly for stream input', async () => { class Processor1 extends PostProcessor { async processStream( _context: IDocContext, input: StreamingCompletionResponse, ): Promise { return { ...input, completion: `${input.completion} [1]` }; } async processCompletion( _context: IDocContext, input: SuggestionOption[], ): Promise { return input; } } class Processor2 extends PostProcessor { async processStream( _context: IDocContext, input: StreamingCompletionResponse, ): Promise { return { ...input, completion: `${input.completion} [2]` }; } async processCompletion( _context: IDocContext, input: SuggestionOption[], ): Promise { return input; } } pipeline.addProcessor(new Processor1()); pipeline.addProcessor(new Processor2()); const streamInput: StreamingCompletionResponse = { id: '1', completion: 'test', done: false }; const result = await pipeline.run({ documentContext: mockContext, input: streamInput, type: 'stream', }); expect(result).toEqual({ id: '1', completion: 'test [1] [2]', done: false }); }); test('should chain multiple processors correctly for completion input', async () => { class Processor1 extends PostProcessor { async processStream( _context: IDocContext, input: StreamingCompletionResponse, ): Promise { return input; } async processCompletion( _context: IDocContext, input: SuggestionOption[], ): Promise { return input.map((option) => ({ ...option, text: `${option.text} [1]` })); } } class Processor2 extends PostProcessor { async processStream( _context: IDocContext, input: StreamingCompletionResponse, ): Promise { return input; } async processCompletion( _context: IDocContext, input: SuggestionOption[], ): Promise { return input.map((option) => ({ ...option, text: `${option.text} [2]` })); } } pipeline.addProcessor(new Processor1()); pipeline.addProcessor(new Processor2()); const completionInput: SuggestionOption[] = [{ text: 'option1', uniqueTrackingId: '1' }]; const result = await pipeline.run({ documentContext: mockContext, input: completionInput, type: 'completion', }); expect(result).toEqual([{ text: 'option1 [1] [2]', uniqueTrackingId: '1' }]); }); test('should throw an error for unexpected type', async () => { class TestProcessor extends PostProcessor { async processStream( _context: IDocContext, input: StreamingCompletionResponse, ): Promise { return input; } async processCompletion( _context: IDocContext, input: SuggestionOption[], ): Promise { 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: - src/common/suggestion_client/post_processors/post_processor_pipeline.test.ts:42" You are a code assistant,Definition of 'readFile' in file src/node/services/fs/file.ts in project gitlab-lsp,"Definition: async readFile({ fileUri }: ReadFile): Promise { return readFile(fsPathFromUri(fileUri), 'utf8'); } } References: - src/node/duo_workflow/desktop_workflow_runner.ts:184 - src/node/duo_workflow/desktop_workflow_runner.ts:137 - src/tests/int/fetch.test.ts:40 - src/tests/unit/tree_sitter/test_utils.ts:38 - src/tests/int/fetch.test.ts:15 - src/node/services/fs/file.ts:9" You are a code assistant,Definition of 'getInstance' in file src/common/tracking/snowplow/snowplow.ts in project gitlab-lsp,"Definition: public static getInstance(lsFetch: LsFetch, options?: SnowplowOptions): Snowplow { if (!this.#instance) { if (!options) { throw new Error('Snowplow should be instantiated'); } const sp = new Snowplow(lsFetch, options); Snowplow.#instance = sp; } // FIXME: this eslint violation was introduced before we set up linting // eslint-disable-next-line @typescript-eslint/no-non-null-assertion return Snowplow.#instance!; } async #sendEvent(events: PayloadBuilder[]): Promise { if (!this.#options.enabled() || this.disabled) { return; } try { const url = `${this.#options.endpoint}/com.snowplowanalytics.snowplow/tp2`; const data = { schema: 'iglu:com.snowplowanalytics.snowplow/payload_data/jsonschema/1-0-4', data: events.map((event) => { const eventId = uuidv4(); // All values prefilled below are part of snowplow tracker protocol // https://docs.snowplow.io/docs/collecting-data/collecting-from-own-applications/snowplow-tracker-protocol/#common-parameters // Values are set according to either common GitLab standard: // tna - representing tracker namespace and being set across GitLab to ""gl"" // tv - represents tracker value, to make it aligned with downstream system it has to be prefixed with ""js-*"""" // aid - represents app Id is configured via options to gitlab_ide_extension // eid - represents uuid for each emitted event event.add('eid', eventId); event.add('p', 'app'); event.add('tv', 'js-gitlab'); event.add('tna', 'gl'); event.add('aid', this.#options.appId); return preparePayload(event.build()); }), }; const config = { headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(data), }; const response = await this.#lsFetch.post(url, config); if (response.status !== 200) { log.warn( `Could not send telemetry to snowplow, this warning can be safely ignored. status=${response.status}`, ); } } catch (error) { let errorHandled = false; if (typeof error === 'object' && 'errno' in (error as object)) { const errObject = error as object; // ENOTFOUND occurs when the snowplow hostname cannot be resolved. if ('errno' in errObject && errObject.errno === 'ENOTFOUND') { this.disabled = true; errorHandled = true; log.info('Disabling telemetry, unable to resolve endpoint address.'); } else { log.warn(JSON.stringify(errObject)); } } if (!errorHandled) { log.warn('Failed to send telemetry event, this warning can be safely ignored'); log.warn(JSON.stringify(error)); } } } public async trackStructEvent( event: StructuredEvent, context?: SelfDescribingJson[] | null, ): Promise { this.#tracker.track(buildStructEvent(event), context); } async stop() { await this.#emitter.stop(); } public destroy() { Snowplow.#instance = undefined; } } References:" You are a code assistant,Definition of 'setCodeSuggestionsContext' in file src/common/tracking/tracking_types.ts in project gitlab-lsp,"Definition: setCodeSuggestionsContext( uniqueTrackingId: string, context: Partial, ): void; updateCodeSuggestionsContext( uniqueTrackingId: string, contextUpdate: Partial, ): void; rejectOpenedSuggestions(): void; updateSuggestionState(uniqueTrackingId: string, newState: TRACKING_EVENTS): void; } export const TelemetryTracker = createInterfaceId('TelemetryTracker'); References:" You are a code assistant,Definition of 'warn' in file packages/lib_logging/src/null_logger.ts in project gitlab-lsp,"Definition: warn(e: Error): void; warn(message: string, e?: Error | undefined): void; warn(): void { // NOOP } error(e: Error): void; error(message: string, e?: Error | undefined): void; error(): void { // NOOP } } References:" You are a code assistant,Definition of 'addItem' in file src/common/ai_context_management_2/ai_context_manager.ts in project gitlab-lsp,"Definition: addItem(item: AiContextItem): boolean { if (this.#items.has(item.id)) { return false; } this.#items.set(item.id, item); return true; } removeItem(id: string): boolean { return this.#items.delete(id); } getItem(id: string): AiContextItem | undefined { return this.#items.get(id); } currentItems(): AiContextItem[] { return Array.from(this.#items.values()); } async retrieveItems(): Promise { const items = Array.from(this.#items.values()); log.info(`Retrieving ${items.length} items`); const retrievedItems = await Promise.all( items.map(async (item) => { try { switch (item.type) { case 'file': { const content = await this.#fileRetriever.retrieve(item); return content ? { ...item, content } : null; } default: throw new Error(`Unknown item type: ${item.type}`); } } catch (error) { log.error(`Failed to retrieve item ${item.id}`, error); return null; } }), ); return retrievedItems.filter((item) => item !== null); } } References:" You are a code assistant,Definition of 'DirectoryWalker' in file src/common/services/fs/dir.ts in project gitlab-lsp,"Definition: export interface DirectoryWalker { findFilesForDirectory(_args: DirectoryToSearch): Promise; setupFileWatcher(workspaceFolder: WorkspaceFolder, changeHandler: FileChangeHandler): void; } export const DirectoryWalker = createInterfaceId('DirectoryWalker'); @Injectable(DirectoryWalker, []) export class DefaultDirectoryWalker { /** * Returns a list of files in the specified directory that match the specified criteria. * The returned files will be the full paths to the files, they also will be in the form of URIs. * Example: [' file:///path/to/file.txt', 'file:///path/to/another/file.js'] */ // eslint-disable-next-line @typescript-eslint/no-unused-vars findFilesForDirectory(_args: DirectoryToSearch): Promise { return Promise.resolve([]); } // eslint-disable-next-line @typescript-eslint/no-unused-vars setupFileWatcher(workspaceFolder: WorkspaceFolder, changeHandler: FileChangeHandler) { throw new Error(`${workspaceFolder} ${changeHandler} not implemented`); } } References: - src/common/services/fs/virtual_file_service.ts:46 - src/common/services/fs/virtual_file_service.ts:42 - src/common/services/duo_access/project_access_cache.ts:92" You are a code assistant,Definition of 'AdvanceContextFilter' in file src/common/advanced_context/advanced_context_filters.ts in project gitlab-lsp,"Definition: type AdvanceContextFilter = (args: AdvancedContextFilterArgs) => Promise; /** * Filters context resolutions that have empty content. */ const emptyContentFilter = async ({ contextResolutions }: AdvancedContextFilterArgs) => { return contextResolutions.filter(({ content }) => content.replace(/\s/g, '') !== ''); }; /** * Filters context resolutions that * contain a Duo project that have Duo features enabled. * See `DuoProjectAccessChecker` for more details. */ const duoProjectAccessFilter: AdvanceContextFilter = async ({ contextResolutions, dependencies: { duoProjectAccessChecker }, documentContext, }: AdvancedContextFilterArgs) => { if (!documentContext?.workspaceFolder) { return contextResolutions; } return contextResolutions.reduce((acc, resolution) => { const { uri: resolutionUri } = resolution; const projectStatus = duoProjectAccessChecker.checkProjectStatus( resolutionUri, documentContext.workspaceFolder as WorkspaceFolder, ); if (projectStatus === DuoProjectStatus.DuoDisabled) { log.warn(`Advanced Context Filter: Duo features are not enabled for ${resolutionUri}`); return acc; } return [...acc, resolution]; }, [] as ContextResolution[]); }; /** * Filters context resolutions that meet the byte size limit. * The byte size limit takes into the size of the total * context resolutions content + size of document content. */ const byteSizeLimitFilter: AdvanceContextFilter = async ({ contextResolutions, documentContext, byteSizeLimit, }: AdvancedContextFilterArgs) => { const documentSize = getByteSize(`${documentContext.prefix}${documentContext.suffix}`); let currentTotalSize = documentSize; const filteredResolutions: ContextResolution[] = []; for (const resolution of contextResolutions) { currentTotalSize += getByteSize(resolution.content); if (currentTotalSize > byteSizeLimit) { // trim the current resolution content to fit the byte size limit const trimmedContent = Buffer.from(resolution.content) .slice(0, byteSizeLimit - currentTotalSize) .toString(); if (trimmedContent.length) { log.info( `Advanced Context Filter: ${resolution.uri} content trimmed to fit byte size limit: ${trimmedContent.length} bytes.`, ); filteredResolutions.push({ ...resolution, content: trimmedContent }); } log.debug( `Advanced Context Filter: Byte size limit exceeded for ${resolution.uri}. Skipping resolution.`, ); break; } filteredResolutions.push(resolution); } return filteredResolutions; }; /** * Advanced context filters that are applied to context resolutions. * @see filterContextResolutions */ const advancedContextFilters: AdvanceContextFilter[] = [ emptyContentFilter, duoProjectAccessFilter, byteSizeLimitFilter, ]; /** * Filters context resolutions based on business logic. * The filters are order dependent. * @see advancedContextFilters */ export const filterContextResolutions = async ({ contextResolutions, dependencies, documentContext, byteSizeLimit, }: AdvancedContextFilterArgs): Promise => { return advancedContextFilters.reduce(async (prevPromise, filter) => { const resolutions = await prevPromise; return filter({ contextResolutions: resolutions, dependencies, documentContext, byteSizeLimit, }); }, Promise.resolve(contextResolutions)); }; References: - src/common/advanced_context/advanced_context_filters.ts:32 - src/common/advanced_context/advanced_context_filters.ts:60" You are a code assistant,Definition of 'constructor' in file src/common/suggestion_client/suggestion_client_pipeline.ts in project gitlab-lsp,"Definition: constructor(middlewares: SuggestionClientMiddleware[]) { this.#middlewares = [...middlewares]; this.#pipeline = this.#buildPipeline(); } use(middleware: SuggestionClientMiddleware) { this.#middlewares.push(middleware); this.#pipeline = this.#buildPipeline(); } #buildPipeline() { return this.#middlewares.reduce( (acc, middleware) => { return (x: SuggestionContext) => { return middleware(x, acc); }; }, () => Promise.reject( new Error(`[SuggestionClientPipeline] Reached end of the pipeline without resolution!`), ), ); } getSuggestions(context: SuggestionContext): Promise { return this.#pipeline(context); } } References:" You are a code assistant,Definition of 'LONG_COMPLETION_CONTEXT' in file src/common/test_utils/mocks.ts in project gitlab-lsp,"Definition: 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 'engaged' in file src/common/feature_state/feature_state_manager.test.ts in project gitlab-lsp,"Definition: get engaged() { return languageCheckEngaged; }, id: UNSUPPORTED_LANGUAGE, details: 'Language is not supported', onChanged: mockOn, }); mockOn.mockImplementation((_callback) => { notifyClient = _callback; }); const duoProjectAccessCheck = createFakePartial({ get engaged() { return duoProjectAccessCheckEngaged; }, id: DUO_DISABLED_FOR_PROJECT, details: 'DUO is disabled for this project', onChanged: mockOn, }); // the CodeSuggestionStateManager is a top-level service that orchestrates the feature checks and sends out notifications, it doesn't have public API const stateManager = new DefaultFeatureStateManager( supportedLanguageCheck, duoProjectAccessCheck, ); stateManager.init(mockSendNotification); mockSendNotification.mockReset(); }); describe('on check engage', () => { it('should notify the client', async () => { const mockChecksEngagedState = createFakePartial([ { featureId: CODE_SUGGESTIONS, engagedChecks: [ { checkId: UNSUPPORTED_LANGUAGE, details: 'Language is not supported', }, ], }, { featureId: CHAT, engagedChecks: [], }, ]); notifyClient(); expect(mockSendNotification).toHaveBeenCalledWith( expect.arrayContaining(mockChecksEngagedState), ); }); }); describe('on check disengage', () => { const mockNoCheckEngagedState = createFakePartial([ { featureId: CODE_SUGGESTIONS, engagedChecks: [], }, { featureId: CHAT, engagedChecks: [], }, ]); it('should notify the client', () => { languageCheckEngaged = false; notifyClient(); expect(mockSendNotification).toHaveBeenCalledWith(mockNoCheckEngagedState); }); }); }); References:" You are a code assistant,Definition of 'MockWebviewLocationService' in file src/common/webview/webview_metadata_provider.test.ts in project gitlab-lsp,"Definition: class MockWebviewLocationService extends WebviewLocationService { #uriMap = new Map(); setUris(webviewId: WebviewId, uris: string[]) { this.#uriMap.set(webviewId, uris); } resolveUris(webviewId: WebviewId): string[] { return this.#uriMap.get(webviewId) || []; } } describe('WebviewMetadataProvider', () => { let accessInfoProviders: MockWebviewLocationService; let plugins: Set; let provider: WebviewMetadataProvider; beforeEach(() => { accessInfoProviders = new MockWebviewLocationService(); plugins = new Set(); provider = new WebviewMetadataProvider(accessInfoProviders, plugins); }); describe('getMetadata', () => { it('should return an empty array if no plugins are registered', () => { const metadata = provider.getMetadata(); expect(metadata).toEqual([]); }); it('should return metadata for registered plugins', () => { // write test const plugin1: WebviewPlugin = { id: 'plugin1' as WebviewId, title: 'Plugin 1', setup: () => {}, }; const plugin2: WebviewPlugin = { id: 'plugin2' as WebviewId, title: 'Plugin 2', setup: () => {}, }; plugins.add(plugin1); plugins.add(plugin2); accessInfoProviders.setUris(plugin1.id, ['uri1', 'uri2']); accessInfoProviders.setUris(plugin2.id, ['uri3', 'uri4']); const metadata = provider.getMetadata(); expect(metadata).toEqual([ { id: 'plugin1', title: 'Plugin 1', uris: ['uri1', 'uri2'], }, { id: 'plugin2', title: 'Plugin 2', uris: ['uri3', 'uri4'], }, ]); }); }); }); References: - src/common/webview/webview_metadata_provider.test.ts:23 - src/common/webview/webview_metadata_provider.test.ts:18" You are a code assistant,Definition of 'Greet' in file src/tests/fixtures/intent/empty_function/typescript.ts in project gitlab-lsp,"Definition: 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/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 'DiagnosticsPublisherFn' in file src/common/diagnostics_publisher.ts in project gitlab-lsp,"Definition: export type DiagnosticsPublisherFn = (data: PublishDiagnosticsParams) => Promise; export interface DiagnosticsPublisher { init(publish: DiagnosticsPublisherFn): void; } References: - src/common/security_diagnostics_publisher.ts:62 - src/common/diagnostics_publisher.ts:6" You are a code assistant,Definition of 'constructor' in file src/browser/tree_sitter/index.ts in project gitlab-lsp,"Definition: constructor(configService: ConfigService) { super({ languages: [] }); this.#configService = configService; } getLanguages() { return this.languages; } getLoadState() { return this.loadState; } async init(): Promise { 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:" You are a code assistant,Definition of 'isExtensionMessage' in file src/common/webview/extension/utils/extension_message.ts in project gitlab-lsp,"Definition: export const isExtensionMessage = (message: unknown): message is ExtensionMessage => { return ( typeof message === 'object' && message !== null && 'webviewId' in message && 'type' in message ); }; References: - src/common/webview/extension/handlers/handle_request_message.ts:8 - src/common/webview/extension/handlers/handle_notification_message.ts:8" You are a code assistant,Definition of 'constructor' in file src/tests/int/lsp_client.ts in project gitlab-lsp,"Definition: 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 { const params = { ...DEFAULT_INITIALIZE_PARAMS, ...initializeParams }; const request = new RequestType( 'initialize', ); const response = await this.#connection.sendRequest(request, params); return response; } /** * Send the LSP 'initialized' notification */ public async sendInitialized(options?: InitializedParams | undefined): Promise { const defaults = {}; const params = { ...defaults, ...options }; const request = new NotificationType('initialized'); await this.#connection.sendNotification(request, params); } /** * Send the LSP 'workspace/didChangeConfiguration' notification */ public async sendDidChangeConfiguration( options?: ChangeConfigOptions | undefined, ): Promise { const defaults = createFakePartial({ settings: { token: this.#gitlabToken, baseUrl: this.#gitlabBaseUrl, codeCompletion: { enableSecretRedaction: true, }, telemetry: { enabled: false, }, }, }); const params = { ...defaults, ...options }; const request = new NotificationType( 'workspace/didChangeConfiguration', ); await this.#connection.sendNotification(request, params); } public async sendTextDocumentDidOpen( uri: string, languageId: string, version: number, text: string, ): Promise { const params = { textDocument: { uri, languageId, version, text, }, }; const request = new NotificationType('textDocument/didOpen'); await this.#connection.sendNotification(request, params); } public async sendTextDocumentDidClose(uri: string): Promise { const params = { textDocument: { uri, }, }; const request = new NotificationType('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 { const params = { textDocument: { uri, version, }, contentChanges: [{ text }], }; const request = new NotificationType('textDocument/didChange'); await this.#connection.sendNotification(request, params); } public async sendTextDocumentCompletion( uri: string, line: number, character: number, ): Promise { 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 { await this.#connection.sendNotification(DidChangeDocumentInActiveEditor, uri); } public async getWebviewMetadata(): Promise { const result = await this.#connection.sendRequest( '$/gitlab/webview-metadata', ); return result; } } References:" You are a code assistant,Definition of 'RequestPublisher' in file packages/lib_message_bus/src/types/bus.ts in project gitlab-lsp,"Definition: export interface RequestPublisher { sendRequest>( type: T, ): Promise>; sendRequest( type: T, payload: TRequests[T]['params'], ): Promise>; } /** * Interface for listening to requests. * @interface * @template {RequestMap} TRequests */ export interface RequestListener { onRequest>( type: T, handler: () => Promise>, ): Disposable; onRequest( type: T, handler: (payload: TRequests[T]['params']) => Promise>, ): Disposable; } /** * Defines the structure for message definitions, including notifications and requests. */ export type MessageDefinitions< TNotifications extends NotificationMap = NotificationMap, TRequests extends RequestMap = RequestMap, > = { notifications: TNotifications; requests: TRequests; }; export type MessageMap< TInboundMessageDefinitions extends MessageDefinitions = MessageDefinitions, TOutboundMessageDefinitions extends MessageDefinitions = MessageDefinitions, > = { inbound: TInboundMessageDefinitions; outbound: TOutboundMessageDefinitions; }; export interface MessageBus extends NotificationPublisher, NotificationListener, RequestPublisher, RequestListener {} References:" You are a code assistant,Definition of 'warn' in file packages/lib_logging/src/types.ts in project gitlab-lsp,"Definition: warn(message: string, e?: Error): void; error(e: Error): void; error(message: string, e?: Error): void; } References:" You are a code assistant,Definition of 'buildWithContext' in file packages/webview_duo_chat/src/plugin/port/chat/gitlab_chat_record.ts in project gitlab-lsp,"Definition: static buildWithContext(attributes: GitLabChatRecordAttributes): GitLabChatRecord { const record = new GitLabChatRecord(attributes); record.context = buildCurrentContext(); return record; } update(attributes: Partial) { const convertedAttributes = attributes as Partial; if (attributes.timestamp) { convertedAttributes.timestamp = Date.parse(attributes.timestamp); } Object.assign(this, convertedAttributes); } #detectType(): ChatRecordType { if (this.content === SPECIAL_MESSAGES.RESET) { return 'newConversation'; } return 'general'; } } References:" You are a code assistant,Definition of 'getTotalCommentLines' in file src/common/tree_sitter/comments/comment_resolver.ts in project gitlab-lsp,"Definition: getTotalCommentLines({ treeSitterLanguage, languageName, tree, }: { languageName: TreeSitterLanguageName; treeSitterLanguage: Language; tree: Tree; }): number { const query = this.#getQueryByLanguage(languageName, treeSitterLanguage); const captures = query ? query.captures(tree.rootNode) : []; // Note: in future, we could potentially re-use captures from getCommentForCursor() const commentLineSet = new Set(); // A Set is used to only count each line once (the same comment can span multiple lines) captures.forEach((capture) => { const { startPosition, endPosition } = capture.node; for (let { row } = startPosition; row <= endPosition.row; row++) { commentLineSet.add(row); } }); return commentLineSet.size; } static isCommentEmpty(comment: Comment): boolean { const trimmedContent = comment.content.trim().replace(/[\n\r\\]/g, ' '); // Count the number of alphanumeric characters in the trimmed content const alphanumericCount = (trimmedContent.match(/[a-zA-Z0-9]/g) || []).length; return alphanumericCount <= 2; } } let commentResolver: CommentResolver; export function getCommentResolver(): CommentResolver { if (!commentResolver) { commentResolver = new CommentResolver(); } return commentResolver; } References:" 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): pass def greet(self): pass 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:" You are a code assistant,Definition of 'WorkspaceFolderUri' in file src/common/services/duo_access/project_access_cache.ts in project gitlab-lsp,"Definition: type WorkspaceFolderUri = string; const duoFeaturesEnabledQuery = gql` query GetProject($projectPath: ID!) { project(fullPath: $projectPath) { duoFeaturesEnabled } } `; interface GitConfig { [section: string]: { [key: string]: string }; } type GitlabRemoteAndFileUri = GitLabRemote & { fileUri: string }; export interface GqlProjectWithDuoEnabledInfo { duoFeaturesEnabled: boolean; } export interface DuoProjectAccessCache { getProjectsForWorkspaceFolder(workspaceFolder: WorkspaceFolder): DuoProject[]; updateCache({ baseUrl, workspaceFolders, }: { baseUrl: string; workspaceFolders: WorkspaceFolder[]; }): Promise; onDuoProjectCacheUpdate(listener: () => void): Disposable; } export const DuoProjectAccessCache = createInterfaceId('DuoProjectAccessCache'); @Injectable(DuoProjectAccessCache, [DirectoryWalker, FileResolver, GitLabApiClient]) export class DefaultDuoProjectAccessCache { #duoProjects: Map; #eventEmitter = new EventEmitter(); constructor( private readonly directoryWalker: DirectoryWalker, private readonly fileResolver: FileResolver, private readonly api: GitLabApiClient, ) { this.#duoProjects = new Map(); } getProjectsForWorkspaceFolder(workspaceFolder: WorkspaceFolder): DuoProject[] { return this.#duoProjects.get(workspaceFolder.uri) ?? []; } async updateCache({ baseUrl, workspaceFolders, }: { baseUrl: string; workspaceFolders: WorkspaceFolder[]; }) { try { this.#duoProjects.clear(); const duoProjects = await Promise.all( workspaceFolders.map(async (workspaceFolder) => { return { workspaceFolder, projects: await this.#duoProjectsForWorkspaceFolder({ workspaceFolder, baseUrl, }), }; }), ); for (const { workspaceFolder, projects } of duoProjects) { this.#logProjectsInfo(projects, workspaceFolder); this.#duoProjects.set(workspaceFolder.uri, projects); } this.#triggerChange(); } catch (err) { log.error('DuoProjectAccessCache: failed to update project access cache', err); } } #logProjectsInfo(projects: DuoProject[], workspaceFolder: WorkspaceFolder) { if (!projects.length) { log.warn( `DuoProjectAccessCache: no projects found for workspace folder ${workspaceFolder.uri}`, ); return; } log.debug( `DuoProjectAccessCache: found ${projects.length} projects for workspace folder ${workspaceFolder.uri}: ${JSON.stringify(projects, null, 2)}`, ); } async #duoProjectsForWorkspaceFolder({ workspaceFolder, baseUrl, }: { workspaceFolder: WorkspaceFolder; baseUrl: string; }): Promise { const remotes = await this.#gitlabRemotesForWorkspaceFolder(workspaceFolder, baseUrl); const projects = await Promise.all( remotes.map(async (remote) => { const enabled = await this.#checkDuoFeaturesEnabled(remote.namespaceWithPath); return { projectPath: remote.projectPath, uri: remote.fileUri, enabled, host: remote.host, namespace: remote.namespace, namespaceWithPath: remote.namespaceWithPath, } satisfies DuoProject; }), ); return projects; } async #gitlabRemotesForWorkspaceFolder( workspaceFolder: WorkspaceFolder, baseUrl: string, ): Promise { const paths = await this.directoryWalker.findFilesForDirectory({ directoryUri: workspaceFolder.uri, filters: { fileEndsWith: ['/.git/config'], }, }); const remotes = await Promise.all( paths.map(async (fileUri) => this.#gitlabRemotesForFileUri(fileUri.toString(), baseUrl)), ); return remotes.flat(); } async #gitlabRemotesForFileUri( fileUri: string, baseUrl: string, ): Promise { const remoteUrls = await this.#remoteUrlsFromGitConfig(fileUri); return remoteUrls.reduce((acc, remoteUrl) => { const remote = parseGitLabRemote(remoteUrl, baseUrl); if (remote) { acc.push({ ...remote, fileUri }); } return acc; }, []); } async #remoteUrlsFromGitConfig(fileUri: string): Promise { try { const fileString = await this.fileResolver.readFile({ fileUri }); const config = ini.parse(fileString); return this.#getRemoteUrls(config); } catch (error) { log.error(`DuoProjectAccessCache: Failed to read git config file: ${fileUri}`, error); return []; } } #getRemoteUrls(config: GitConfig): string[] { return Object.keys(config).reduce((acc, section) => { if (section.startsWith('remote ')) { acc.push(config[section].url); } return acc; }, []); } async #checkDuoFeaturesEnabled(projectPath: string): Promise { try { const response = await this.api.fetchFromApi<{ project: GqlProjectWithDuoEnabledInfo }>({ type: 'graphql', query: duoFeaturesEnabledQuery, variables: { projectPath, }, } satisfies ApiRequest<{ project: GqlProjectWithDuoEnabledInfo }>); return Boolean(response?.project?.duoFeaturesEnabled); } catch (error) { log.error( `DuoProjectAccessCache: Failed to check if Duo features are enabled for project: ${projectPath}`, error, ); return true; } } onDuoProjectCacheUpdate( listener: (duoProjectsCache: Map) => void, ): Disposable { this.#eventEmitter.on(DUO_PROJECT_CACHE_UPDATE_EVENT, listener); return { dispose: () => this.#eventEmitter.removeListener(DUO_PROJECT_CACHE_UPDATE_EVENT, listener), }; } #triggerChange() { this.#eventEmitter.emit(DUO_PROJECT_CACHE_UPDATE_EVENT, this.#duoProjects); } } References: - src/common/git/repository_service.ts:280 - src/common/git/repository_service.ts:245 - src/common/git/repository_service.ts:241" You are a code assistant,Definition of 'getForSaaSAccount' in file packages/webview_duo_chat/src/plugin/chat_platform_manager.ts in project gitlab-lsp,"Definition: async getForSaaSAccount(): Promise { return new ChatPlatformForAccount(this.#client); } } References:" You are a code assistant,Definition of 'ITelemetryNotificationParams' in file src/common/suggestion/suggestion_service.ts in project gitlab-lsp,"Definition: 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 => { 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 => { 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 => { 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 { 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 { 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 { 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 { 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 { 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:131" You are a code assistant,Definition of 'readFile' in file src/common/services/fs/file.ts in project gitlab-lsp,"Definition: readFile(_args: ReadFile): Promise { return Promise.resolve(''); } } References: - src/tests/unit/tree_sitter/test_utils.ts:38 - src/tests/int/fetch.test.ts:15 - src/node/services/fs/file.ts:9 - src/node/duo_workflow/desktop_workflow_runner.ts:184 - src/node/duo_workflow/desktop_workflow_runner.ts:137 - src/tests/int/fetch.test.ts:40" You are a code assistant,Definition of 'use' in file src/common/suggestion_client/suggestion_client_pipeline.ts in project gitlab-lsp,"Definition: use(middleware: SuggestionClientMiddleware) { this.#middlewares.push(middleware); this.#pipeline = this.#buildPipeline(); } #buildPipeline() { return this.#middlewares.reduce( (acc, middleware) => { return (x: SuggestionContext) => { return middleware(x, acc); }; }, () => Promise.reject( new Error(`[SuggestionClientPipeline] Reached end of the pipeline without resolution!`), ), ); } getSuggestions(context: SuggestionContext): Promise { return this.#pipeline(context); } } References:" You are a code assistant,Definition of 'goIntoStreamingMode' in file src/common/suggestion/suggestion_service.test.ts in project gitlab-lsp,"Definition: function goIntoStreamingMode() { mockParseFile.mockReset(); jest.mocked(featureFlagService.isClientFlagEnabled).mockReturnValueOnce(true); mockParseFile.mockResolvedValue('generation'); } function goIntoCompletionMode() { mockParseFile.mockReset(); jest.mocked(featureFlagService.isClientFlagEnabled).mockReturnValueOnce(false); mockParseFile.mockResolvedValue('completion'); } it('starts breaking after 4 errors', async () => { jest.mocked(DefaultStreamingHandler).mockClear(); jest.mocked(DefaultStreamingHandler).mockReturnValue( createFakePartial({ startStream: jest.fn().mockResolvedValue([]), }), ); goIntoStreamingMode(); const successResult = await getCompletions(); expect(successResult.items.length).toEqual(1); jest.runOnlyPendingTimers(); expect(DefaultStreamingHandler).toHaveBeenCalled(); jest.mocked(DefaultStreamingHandler).mockClear(); goIntoCompletionMode(); mockGetCodeSuggestions.mockRejectedValue('test problem'); await turnOnCircuitBreaker(); goIntoStreamingMode(); const result = await getCompletions(); expect(result?.items).toEqual([]); expect(DefaultStreamingHandler).not.toHaveBeenCalled(); }); it(`starts the stream after circuit breaker's break time elapses`, async () => { jest.useFakeTimers().setSystemTime(new Date(Date.now())); goIntoCompletionMode(); mockGetCodeSuggestions.mockRejectedValue(new Error('test problem')); await turnOnCircuitBreaker(); jest.advanceTimersByTime(CIRCUIT_BREAK_INTERVAL_MS + 1); goIntoStreamingMode(); const result = await getCompletions(); expect(result?.items).toHaveLength(1); jest.runOnlyPendingTimers(); expect(DefaultStreamingHandler).toHaveBeenCalled(); }); }); }); describe('selection completion info', () => { beforeEach(() => { mockGetCodeSuggestions.mockReset(); mockGetCodeSuggestions.mockResolvedValue({ choices: [{ text: 'log(""Hello world"")' }], model: { lang: 'js', }, }); }); describe('when undefined', () => { it('does not update choices', async () => { const { items } = await requestInlineCompletionNoDebounce( { ...inlineCompletionParams, context: createFakePartial({ selectedCompletionInfo: undefined, }), }, token, ); expect(items[0].insertText).toBe('log(""Hello world"")'); }); }); describe('with range and text', () => { it('prepends text to suggestion choices', async () => { const { items } = await requestInlineCompletionNoDebounce( { ...inlineCompletionParams, context: createFakePartial({ selectedCompletionInfo: { text: 'console.', range: { start: { line: 1, character: 0 }, end: { line: 1, character: 2 } }, }, }), }, token, ); expect(items[0].insertText).toBe('nsole.log(""Hello world"")'); }); }); describe('with range (Array) and text', () => { it('prepends text to suggestion choices', async () => { const { items } = await requestInlineCompletionNoDebounce( { ...inlineCompletionParams, context: createFakePartial({ selectedCompletionInfo: { text: 'console.', // NOTE: This forcefully simulates the behavior we see where range is an Array at runtime. range: [ { line: 1, character: 0 }, { line: 1, character: 2 }, ] as unknown as Range, }, }), }, token, ); expect(items[0].insertText).toBe('nsole.log(""Hello world"")'); }); }); }); describe('Additional Context', () => { beforeEach(async () => { jest.mocked(shouldUseAdvancedContext).mockReturnValueOnce(true); getAdvancedContextSpy.mockResolvedValue(sampleAdvancedContext); contextBodySpy.mockReturnValue(sampleAdditionalContexts); await requestInlineCompletionNoDebounce(inlineCompletionParams, token); }); it('getCodeSuggestions should have additional context passed if feature is enabled', async () => { expect(getAdvancedContextSpy).toHaveBeenCalled(); expect(contextBodySpy).toHaveBeenCalledWith(sampleAdvancedContext); expect(api.getCodeSuggestions).toHaveBeenCalledWith( expect.objectContaining({ context: sampleAdditionalContexts }), ); }); it('should be tracked with telemetry', () => { expect(tracker.setCodeSuggestionsContext).toHaveBeenCalledWith( TRACKING_ID, expect.objectContaining({ additionalContexts: sampleAdditionalContexts }), ); }); }); }); }); }); References: - src/common/suggestion/suggestion_service.test.ts:987 - src/common/suggestion/suggestion_service.test.ts:1013 - src/common/suggestion/suggestion_service.test.ts:998" You are a code assistant,Definition of 'getSelectedText' in file packages/webview_duo_chat/src/plugin/port/chat/utils/editor_text_utils.ts in project gitlab-lsp,"Definition: export const getSelectedText = (): string | null => { return null; // const editor = vscode.window.activeTextEditor; // if (!editor || !editor.selection || editor.selection.isEmpty) return null; // const { selection } = editor; // const selectionRange = new vscode.Range( // selection.start.line, // selection.start.character, // selection.end.line, // selection.end.character, // ); // return editor.document.getText(selectionRange); }; export const getActiveFileName = (): string | null => { return null; // const editor = vscode.window.activeTextEditor; // if (!editor) return null; // return vscode.workspace.asRelativePath(editor.document.uri); }; export const getTextBeforeSelected = (): string | null => { return null; // const editor = vscode.window.activeTextEditor; // if (!editor || !editor.selection || editor.selection.isEmpty) return null; // const { selection, document } = editor; // const { line: lineNum, character: charNum } = selection.start; // const isFirstCharOnLineSelected = charNum === 0; // const isFirstLine = lineNum === 0; // const getEndLine = () => { // if (isFirstCharOnLineSelected) { // if (isFirstLine) { // return lineNum; // } // return lineNum - 1; // } // return lineNum; // }; // const getEndChar = () => { // if (isFirstCharOnLineSelected) { // if (isFirstLine) { // return 0; // } // return document.lineAt(lineNum - 1).range.end.character; // } // return charNum - 1; // }; // const selectionRange = new vscode.Range(0, 0, getEndLine(), getEndChar()); // return editor.document.getText(selectionRange); }; export const getTextAfterSelected = (): string | null => { return null; // const editor = vscode.window.activeTextEditor; // if (!editor || !editor.selection || editor.selection.isEmpty) return null; // const { selection, document } = editor; // const { line: lineNum, character: charNum } = selection.end; // const isLastCharOnLineSelected = charNum === document.lineAt(lineNum).range.end.character; // const isLastLine = lineNum === document.lineCount; // const getStartLine = () => { // if (isLastCharOnLineSelected) { // if (isLastLine) { // return lineNum; // } // return lineNum + 1; // } // return lineNum; // }; // const getStartChar = () => { // if (isLastCharOnLineSelected) { // if (isLastLine) { // return charNum; // } // return 0; // } // return charNum + 1; // }; // const selectionRange = new vscode.Range( // getStartLine(), // getStartChar(), // document.lineCount, // document.lineAt(document.lineCount - 1).range.end.character, // ); // return editor.document.getText(selectionRange); }; References: - packages/webview_duo_chat/src/plugin/port/chat/gitlab_chat_file_context.ts:16" You are a code assistant,Definition of 'error' in file src/common/circuit_breaker/exponential_backoff_circuit_breaker.ts in project gitlab-lsp,"Definition: error() { this.#errorCount += 1; this.#open(); } megaError() { this.#errorCount += 3; this.#open(); } #open() { if (this.#state === CircuitBreakerState.OPEN) { return; } this.#state = CircuitBreakerState.OPEN; log.warn( `Excess errors detected, opening '${this.#name}' circuit breaker for ${this.#getBackoffTime() / 1000} second(s).`, ); this.#timeoutId = setTimeout(() => this.#close(), this.#getBackoffTime()); this.#eventEmitter.emit('open'); } #close() { if (this.#state === CircuitBreakerState.CLOSED) { return; } if (this.#timeoutId) { clearTimeout(this.#timeoutId); } this.#state = CircuitBreakerState.CLOSED; this.#eventEmitter.emit('close'); } isOpen() { return this.#state === CircuitBreakerState.OPEN; } 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) }; } #getBackoffTime() { return Math.min( this.#initialBackoffMs * this.#backoffMultiplier ** (this.#errorCount - 1), this.#maxBackoffMs, ); } } References: - scripts/commit-lint/lint.js:72 - scripts/commit-lint/lint.js:77 - scripts/commit-lint/lint.js:85 - scripts/commit-lint/lint.js:94" You are a code assistant,Definition of 'triggerDocumentEvent' in file src/common/feature_state/project_duo_acces_check.test.ts in project gitlab-lsp,"Definition: function triggerDocumentEvent(documentUri: string) { const document = createFakePartial({ uri: documentUri }); const event = createFakePartial>({ document }); documentEventListener(event, TextDocumentChangeListenerType.onDidSetActive); } beforeEach(async () => { onDocumentChange.mockImplementation((_listener) => { documentEventListener = _listener; }); onDuoProjectCacheUpdate.mockImplementation((_listener) => { duoProjectCacheUpdateListener = _listener; }); check = new DefaultProjectDuoAccessCheck( documentService, configService, duoProjectAccessChecker, duoProjectAccessCache, ); disposables.push(check.onChanged(policyEngagedChangeListener)); }); afterEach(() => { while (disposables.length > 0) { disposables.pop()!.dispose(); } }); describe('is updated on config change""', () => { it('should NOT be engaged when no client setting provided and there is no active document', () => { configService.set('client.duo.enabledWithoutGitlabProject', null); expect(check.engaged).toBe(false); }); it('should be engaged when disabled in setting and there is no active document', () => { configService.set('client.duo.enabledWithoutGitlabProject', false); expect(check.engaged).toBe(true); }); it('should NOT be engaged when enabled in setting and there is no active document', () => { configService.set('client.duo.enabledWithoutGitlabProject', true); expect(check.engaged).toBe(false); }); }); describe('is updated on document set active in editor event', () => { beforeEach(() => { configService.set('client.workspaceFolders', [workspaceFolder]); }); it('should NOT be engaged when duo enabled for project file', async () => { jest .mocked(duoProjectAccessChecker.checkProjectStatus) .mockReturnValueOnce(DuoProjectStatus.DuoEnabled); triggerDocumentEvent(uri); await new Promise(process.nextTick); expect(check.engaged).toBe(false); }); it('should be engaged when duo disabled for project file', async () => { jest .mocked(duoProjectAccessChecker.checkProjectStatus) .mockReturnValueOnce(DuoProjectStatus.DuoDisabled); triggerDocumentEvent(uri); await new Promise(process.nextTick); expect(check.engaged).toBe(true); }); it('should use default setting when no GitLab project detected', async () => { jest .mocked(duoProjectAccessChecker.checkProjectStatus) .mockReturnValueOnce(DuoProjectStatus.NonGitlabProject); triggerDocumentEvent(uri); await new Promise(process.nextTick); expect(check.engaged).toBe(false); }); }); describe('is updated on duo cache update', () => { beforeEach(() => { configService.set('client.workspaceFolders', [workspaceFolder]); configService.set('client.duo.enabledWithoutGitlabProject', false); }); it('should be engaged and rely on setting value when file does not belong to Duo project', async () => { jest .mocked(duoProjectAccessChecker.checkProjectStatus) .mockReturnValueOnce(DuoProjectStatus.DuoEnabled); triggerDocumentEvent(uri); await new Promise(process.nextTick); expect(check.engaged).toBe(false); jest .mocked(duoProjectAccessChecker.checkProjectStatus) .mockReturnValueOnce(DuoProjectStatus.NonGitlabProject); duoProjectCacheUpdateListener(); expect(check.engaged).toBe(true); }); }); describe('change event', () => { it('emits after check is updated', () => { policyEngagedChangeListener.mockClear(); configService.set('client.duo.enabledWithoutGitlabProject', false); expect(policyEngagedChangeListener).toHaveBeenCalledTimes(1); }); }); }); References: - src/common/feature_state/project_duo_acces_check.test.ts:117 - src/common/feature_state/supported_language_check.test.ts:109 - src/common/feature_state/project_duo_acces_check.test.ts:134 - src/common/feature_state/supported_language_check.test.ts:81 - src/common/feature_state/project_duo_acces_check.test.ts:96 - src/common/feature_state/project_duo_acces_check.test.ts:106 - src/common/feature_state/supported_language_check.test.ts:115 - src/common/feature_state/supported_language_check.test.ts:72 - src/common/feature_state/supported_language_check.test.ts:88 - src/common/feature_state/supported_language_check.test.ts:63" You are a code assistant,Definition of 'generate_greetings' in file src/tests/fixtures/intent/empty_function/ruby.rb in project gitlab-lsp,"Definition: def generate_greetings end def greet_generator yield 'Hello' end References: - src/tests/fixtures/intent/empty_function/ruby.rb:37" You are a code assistant,Definition of 'merge' in file src/common/config_service.ts in project gitlab-lsp,"Definition: merge(newConfig: Partial): void; } export const ConfigService = createInterfaceId('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 = (key?: string) => { return key ? get(this.#config, key) : this.#config; }; set: TypedSetter = (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) { mergeWith(this.#config, newConfig, (target, src) => (isArray(target) ? src : undefined)); this.#triggerChange(); } } References:" You are a code assistant,Definition of 'ProjectDuoAccessCheck' in file src/common/feature_state/project_duo_acces_check.ts in project gitlab-lsp,"Definition: export interface ProjectDuoAccessCheck extends StateCheck {} export const ProjectDuoAccessCheck = createInterfaceId('ProjectDuoAccessCheck'); @Injectable(ProjectDuoAccessCheck, [ DocumentService, ConfigService, DuoProjectAccessChecker, DuoProjectAccessCache, ]) export class DefaultProjectDuoAccessCheck implements StateCheck { #subscriptions: Disposable[] = []; #stateEmitter = new EventEmitter(); #hasDuoAccess?: boolean; #duoProjectAccessChecker: DuoProjectAccessChecker; #configService: ConfigService; #currentDocument?: TextDocument; #isEnabledInSettings = true; constructor( documentService: DocumentService, configService: ConfigService, duoProjectAccessChecker: DuoProjectAccessChecker, duoProjectAccessCache: DuoProjectAccessCache, ) { this.#configService = configService; this.#duoProjectAccessChecker = duoProjectAccessChecker; this.#subscriptions.push( documentService.onDocumentChange(async (event, handlerType) => { if (handlerType === TextDocumentChangeListenerType.onDidSetActive) { this.#currentDocument = event.document; await this.#checkIfProjectHasDuoAccess(); } }), configService.onConfigChange(async (config) => { this.#isEnabledInSettings = config.client.duo?.enabledWithoutGitlabProject ?? true; await this.#checkIfProjectHasDuoAccess(); }), duoProjectAccessCache.onDuoProjectCacheUpdate(() => this.#checkIfProjectHasDuoAccess()), ); } onChanged(listener: (data: StateCheckChangedEventData) => void): Disposable { this.#stateEmitter.on('change', listener); return { dispose: () => this.#stateEmitter.removeListener('change', listener), }; } get engaged() { return !this.#hasDuoAccess; } async #checkIfProjectHasDuoAccess(): Promise { this.#hasDuoAccess = this.#isEnabledInSettings; if (!this.#currentDocument) { this.#stateEmitter.emit('change', this); return; } const workspaceFolder = await this.#getWorkspaceFolderForUri(this.#currentDocument.uri); if (workspaceFolder) { const status = this.#duoProjectAccessChecker.checkProjectStatus( this.#currentDocument.uri, workspaceFolder, ); if (status === DuoProjectStatus.DuoEnabled) { this.#hasDuoAccess = true; } else if (status === DuoProjectStatus.DuoDisabled) { this.#hasDuoAccess = false; } } this.#stateEmitter.emit('change', this); } id = DUO_DISABLED_FOR_PROJECT; details = 'Duo features are disabled for this project'; async #getWorkspaceFolderForUri(uri: URI): Promise { const workspaceFolders = await this.#configService.get('client.workspaceFolders'); return workspaceFolders?.find((folder) => uri.startsWith(folder.uri)); } dispose() { this.#subscriptions.forEach((s) => s.dispose()); } } References: - src/common/feature_state/feature_state_manager.ts:29 - src/common/feature_state/project_duo_acces_check.test.ts:15" You are a code assistant,Definition of 'constructor' in file src/common/feature_state/feature_state_manager.ts in project gitlab-lsp,"Definition: constructor( supportedLanguagePolicy: CodeSuggestionsSupportedLanguageCheck, projectDuoAccessCheck: ProjectDuoAccessCheck, ) { this.#checks.push(supportedLanguagePolicy, projectDuoAccessCheck); this.#subscriptions.push( ...this.#checks.map((check) => check.onChanged(() => this.#notifyClient())), ); } init(notify: NotifyFn): void { this.#notify = notify; } async #notifyClient() { if (!this.#notify) { throw new Error( ""The state manager hasn't been initialized. It can't send notifications. Call the init method first."", ); } await this.#notify(this.#state); } dispose() { this.#subscriptions.forEach((s) => s.dispose()); } get #state(): FeatureState[] { const engagedChecks = this.#checks.filter((check) => check.engaged); return getEntries(CHECKS_PER_FEATURE).map(([featureId, stateChecks]) => { const engagedFeatureChecks: FeatureStateCheck[] = engagedChecks .filter(({ id }) => stateChecks.includes(id)) .map((stateCheck) => ({ checkId: stateCheck.id, details: stateCheck.details, })); return { featureId, engagedChecks: engagedFeatureChecks, }; }); } } References:" You are a code assistant,Definition of 'onRequest' in file packages/lib_message_bus/src/types/bus.ts in project gitlab-lsp,"Definition: onRequest( type: T, handler: (payload: TRequests[T]['params']) => Promise>, ): Disposable; } /** * Defines the structure for message definitions, including notifications and requests. */ export type MessageDefinitions< TNotifications extends NotificationMap = NotificationMap, TRequests extends RequestMap = RequestMap, > = { notifications: TNotifications; requests: TRequests; }; export type MessageMap< TInboundMessageDefinitions extends MessageDefinitions = MessageDefinitions, TOutboundMessageDefinitions extends MessageDefinitions = MessageDefinitions, > = { inbound: TInboundMessageDefinitions; outbound: TOutboundMessageDefinitions; }; export interface MessageBus extends NotificationPublisher, NotificationListener, RequestPublisher, RequestListener {} References:" You are a code assistant,Definition of 'Greet2' in file src/tests/fixtures/intent/empty_function/typescript.ts in project gitlab-lsp,"Definition: 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:24" You are a code assistant,Definition of 'PostProcessor' in file src/common/suggestion_client/post_processors/post_processor_pipeline.ts in project gitlab-lsp,"Definition: export abstract class PostProcessor { processStream( _context: IDocContext, input: StreamingCompletionResponse, ): Promise { return Promise.resolve(input); } processCompletion(_context: IDocContext, input: SuggestionOption[]): Promise { return Promise.resolve(input); } } /** * Pipeline for running post-processors on completion and streaming (generation) responses. * Post-processors are used to modify completion responses before they are sent to the client. * They can be used to filter, sort, or modify completion suggestions. */ export class PostProcessorPipeline { #processors: PostProcessor[] = []; addProcessor(processor: PostProcessor): void { this.#processors.push(processor); } async run({ documentContext, input, type, }: { documentContext: IDocContext; input: ProcessorInputMap[T]; type: T; }): Promise { if (!this.#processors.length) return input as ProcessorInputMap[T]; return this.#processors.reduce( async (prevPromise, processor) => { const result = await prevPromise; // eslint-disable-next-line default-case switch (type) { case 'stream': return processor.processStream( documentContext, result as StreamingCompletionResponse, ) as Promise; case 'completion': return processor.processCompletion( documentContext, result as SuggestionOption[], ) as Promise; } throw new Error('Unexpected type in pipeline processing'); }, Promise.resolve(input) as Promise, ); } } References: - src/common/suggestion_client/post_processors/post_processor_pipeline.ts:41" You are a code assistant,Definition of 'StartStreamParams' in file src/common/suggestion/streaming_handler.ts in project gitlab-lsp,"Definition: export interface StartStreamParams { api: GitLabApiClient; circuitBreaker: CircuitBreaker; connection: Connection; documentContext: IDocContext; parser: TreeSitterParser; postProcessorPipeline: PostProcessorPipeline; streamId: string; tracker: TelemetryTracker; uniqueTrackingId: string; userInstruction?: string; generationType?: GenerationType; additionalContexts?: AdditionalContext[]; } export class DefaultStreamingHandler { #params: StartStreamParams; constructor(params: StartStreamParams) { this.#params = params; } async startStream() { return startStreaming(this.#params); } } const startStreaming = async ({ additionalContexts, api, circuitBreaker, connection, documentContext, parser, postProcessorPipeline, streamId, tracker, uniqueTrackingId, userInstruction, generationType, }: StartStreamParams) => { const language = parser.getLanguageNameForFile(documentContext.fileRelativePath); tracker.setCodeSuggestionsContext(uniqueTrackingId, { documentContext, additionalContexts, source: SuggestionSource.network, language, isStreaming: true, }); let streamShown = false; let suggestionProvided = false; let streamCancelledOrErrored = false; const cancellationTokenSource = new CancellationTokenSource(); const disposeStopStreaming = connection.onNotification(CancelStreaming, (stream) => { if (stream.id === streamId) { streamCancelledOrErrored = true; cancellationTokenSource.cancel(); if (streamShown) { tracker.updateSuggestionState(uniqueTrackingId, TRACKING_EVENTS.REJECTED); } else { tracker.updateSuggestionState(uniqueTrackingId, TRACKING_EVENTS.CANCELLED); } } }); const cancellationToken = cancellationTokenSource.token; const endStream = async () => { await connection.sendNotification(StreamingCompletionResponse, { id: streamId, done: true, }); if (!streamCancelledOrErrored) { tracker.updateSuggestionState(uniqueTrackingId, TRACKING_EVENTS.STREAM_COMPLETED); if (!suggestionProvided) { tracker.updateSuggestionState(uniqueTrackingId, TRACKING_EVENTS.NOT_PROVIDED); } } }; circuitBreaker.success(); const request: CodeSuggestionRequest = { prompt_version: 1, project_path: '', project_id: -1, current_file: { content_above_cursor: documentContext.prefix, content_below_cursor: documentContext.suffix, file_name: documentContext.fileRelativePath, }, intent: 'generation', stream: true, ...(additionalContexts?.length && { context: additionalContexts, }), ...(userInstruction && { user_instruction: userInstruction, }), generation_type: generationType, }; const trackStreamStarted = once(() => { tracker.updateSuggestionState(uniqueTrackingId, TRACKING_EVENTS.STREAM_STARTED); }); const trackStreamShown = once(() => { tracker.updateSuggestionState(uniqueTrackingId, TRACKING_EVENTS.SHOWN); streamShown = true; }); try { for await (const response of api.getStreamingCodeSuggestions(request)) { if (cancellationToken.isCancellationRequested) { break; } if (circuitBreaker.isOpen()) { break; } trackStreamStarted(); const processedCompletion = await postProcessorPipeline.run({ documentContext, input: { id: streamId, completion: response, done: false }, type: 'stream', }); await connection.sendNotification(StreamingCompletionResponse, processedCompletion); if (response.replace(/\s/g, '').length) { trackStreamShown(); suggestionProvided = true; } } } catch (err) { circuitBreaker.error(); if (isFetchError(err)) { tracker.updateCodeSuggestionsContext(uniqueTrackingId, { status: err.status }); } tracker.updateSuggestionState(uniqueTrackingId, TRACKING_EVENTS.ERRORED); streamCancelledOrErrored = true; log.error('Error streaming code suggestions.', err); } finally { await endStream(); disposeStopStreaming.dispose(); cancellationTokenSource.dispose(); } }; References: - src/common/suggestion/streaming_handler.ts:53 - src/common/suggestion/streaming_handler.ts:51 - src/common/suggestion/streaming_handler.ts:75" You are a code assistant,Definition of 'FetchAgentOptions' in file src/common/fetch.ts in project gitlab-lsp,"Definition: export interface FetchAgentOptions { ignoreCertificateErrors: boolean; ca?: string; cert?: string; certKey?: string; } export type FetchHeaders = { [key: string]: string; }; export interface LsFetch { initialize(): Promise; destroy(): Promise; fetch(input: RequestInfo | URL, init?: RequestInit): Promise; fetchBase(input: RequestInfo | URL, init?: RequestInit): Promise; delete(input: RequestInfo | URL, init?: RequestInit): Promise; get(input: RequestInfo | URL, init?: RequestInit): Promise; post(input: RequestInfo | URL, init?: RequestInit): Promise; put(input: RequestInfo | URL, init?: RequestInit): Promise; updateAgentOptions(options: FetchAgentOptions): void; streamFetch(url: string, body: string, headers: FetchHeaders): AsyncGenerator; } export const LsFetch = createInterfaceId('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 {} async destroy(): Promise {} async fetch(input: RequestInfo | URL, init?: RequestInit): Promise { 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 { // Stub. Should delegate to the node or browser fetch implementations throw new Error('Not implemented'); yield ''; } async delete(input: RequestInfo | URL, init?: RequestInit): Promise { return this.fetch(input, this.updateRequestInit('DELETE', init)); } async get(input: RequestInfo | URL, init?: RequestInit): Promise { return this.fetch(input, this.updateRequestInit('GET', init)); } async post(input: RequestInfo | URL, init?: RequestInit): Promise { return this.fetch(input, this.updateRequestInit('POST', init)); } async put(input: RequestInfo | URL, init?: RequestInit): Promise { return this.fetch(input, this.updateRequestInit('PUT', init)); } async fetchBase(input: RequestInfo | URL, init?: RequestInit): Promise { // 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/fetch.ts:87 - src/node/fetch.ts:120 - src/common/fetch.ts:24" You are a code assistant,Definition of 'isTextDocument' in file src/common/document_service.ts in project gitlab-lsp,"Definition: function isTextDocument(param: TextDocument | DocumentUri): param is TextDocument { return (param as TextDocument).uri !== undefined; } export interface TextDocumentChangeListener { (event: TextDocumentChangeEvent, handlerType: TextDocumentChangeListenerType): void; } export interface DocumentService { onDocumentChange(listener: TextDocumentChangeListener): Disposable; notificationHandler(params: DidChangeDocumentInActiveEditorParams): void; } export const DocumentService = createInterfaceId('DocumentsWrapper'); const DOCUMENT_CHANGE_EVENT_NAME = 'documentChange'; export class DefaultDocumentService implements DocumentService, HandlesNotification { #subscriptions: Disposable[] = []; #emitter = new EventEmitter(); #documents: TextDocuments; constructor(documents: TextDocuments) { 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 = { document }; this.#emitter.emit( DOCUMENT_CHANGE_EVENT_NAME, event, TextDocumentChangeListenerType.onDidSetActive, ); }; #createMediatorListener = (type: TextDocumentChangeListenerType) => (event: TextDocumentChangeEvent) => { 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/document_service.ts:53" You are a code assistant,Definition of 'onDuoProjectCacheUpdate' in file src/common/services/duo_access/project_access_cache.ts in project gitlab-lsp,"Definition: onDuoProjectCacheUpdate( listener: (duoProjectsCache: Map) => void, ): Disposable { this.#eventEmitter.on(DUO_PROJECT_CACHE_UPDATE_EVENT, listener); return { dispose: () => this.#eventEmitter.removeListener(DUO_PROJECT_CACHE_UPDATE_EVENT, listener), }; } #triggerChange() { this.#eventEmitter.emit(DUO_PROJECT_CACHE_UPDATE_EVENT, this.#duoProjects); } } References:" You are a code assistant,Definition of 'resolveUris' in file src/common/webview/webview_metadata_provider.test.ts in project gitlab-lsp,"Definition: resolveUris(webviewId: WebviewId): string[] { return this.#uriMap.get(webviewId) || []; } } describe('WebviewMetadataProvider', () => { let accessInfoProviders: MockWebviewLocationService; let plugins: Set; let provider: WebviewMetadataProvider; beforeEach(() => { accessInfoProviders = new MockWebviewLocationService(); plugins = new Set(); provider = new WebviewMetadataProvider(accessInfoProviders, plugins); }); describe('getMetadata', () => { it('should return an empty array if no plugins are registered', () => { const metadata = provider.getMetadata(); expect(metadata).toEqual([]); }); it('should return metadata for registered plugins', () => { // write test const plugin1: WebviewPlugin = { id: 'plugin1' as WebviewId, title: 'Plugin 1', setup: () => {}, }; const plugin2: WebviewPlugin = { id: 'plugin2' as WebviewId, title: 'Plugin 2', setup: () => {}, }; plugins.add(plugin1); plugins.add(plugin2); accessInfoProviders.setUris(plugin1.id, ['uri1', 'uri2']); accessInfoProviders.setUris(plugin2.id, ['uri3', 'uri4']); const metadata = provider.getMetadata(); expect(metadata).toEqual([ { id: 'plugin1', title: 'Plugin 1', uris: ['uri1', 'uri2'], }, { id: 'plugin2', title: 'Plugin 2', uris: ['uri3', 'uri4'], }, ]); }); }); }); References:" You are a code assistant,Definition of 'SAAS_INSTANCE_URL' in file src/common/tracking/constants.ts in project gitlab-lsp,"Definition: 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 'getRepositoryFileForUri' in file src/common/git/repository_service.ts in project gitlab-lsp,"Definition: getRepositoryFileForUri( fileUri: URI, repositoryUri: URI, workspaceFolder: WorkspaceFolder, ): RepositoryFile | null { const repository = this.#getRepositoriesForWorkspace(workspaceFolder.uri).get( repositoryUri.toString(), ); if (!repository) { return null; } return repository.getFile(fileUri.toString()) ?? null; } #updateRepositoriesForFolder( workspaceFolder: WorkspaceFolder, repositoryMap: RepositoryMap, repositoryTrie: RepositoryTrie, ) { this.#workspaces.set(workspaceFolder.uri, repositoryMap); this.#workspaceRepositoryTries.set(workspaceFolder.uri, repositoryTrie); } async handleWorkspaceFilesUpdate({ workspaceFolder, files }: WorkspaceFilesUpdate) { // clear existing repositories from workspace this.#emptyRepositoriesForWorkspace(workspaceFolder.uri); const repositories = this.#detectRepositories(files, workspaceFolder); const repositoryMap = new Map(repositories.map((repo) => [repo.uri.toString(), repo])); // Build and cache the repository trie for this workspace const trie = this.#buildRepositoryTrie(repositories); this.#updateRepositoriesForFolder(workspaceFolder, repositoryMap, trie); await Promise.all( repositories.map((repo) => repo.addFilesAndLoadGitIgnore( files.filter((file) => { const matchingRepo = this.findMatchingRepositoryUri(file, workspaceFolder); return matchingRepo && matchingRepo.toString() === repo.uri.toString(); }), ), ), ); } async handleWorkspaceFileUpdate({ fileUri, workspaceFolder, event }: WorkspaceFileUpdate) { const repoUri = this.findMatchingRepositoryUri(fileUri, workspaceFolder); if (!repoUri) { log.debug(`No matching repository found for file ${fileUri.toString()}`); return; } const repositoryMap = this.#getRepositoriesForWorkspace(workspaceFolder.uri); const repository = repositoryMap.get(repoUri.toString()); if (!repository) { log.debug(`Repository not found for URI ${repoUri.toString()}`); return; } if (repository.isFileIgnored(fileUri)) { log.debug(`File ${fileUri.toString()} is ignored`); return; } switch (event) { case 'add': repository.setFile(fileUri); log.debug(`File ${fileUri.toString()} added to repository ${repoUri.toString()}`); break; case 'change': repository.setFile(fileUri); log.debug(`File ${fileUri.toString()} updated in repository ${repoUri.toString()}`); break; case 'unlink': repository.removeFile(fileUri.toString()); log.debug(`File ${fileUri.toString()} removed from repository ${repoUri.toString()}`); break; default: log.warn(`Unknown file event ${event} for file ${fileUri.toString()}`); } } #getRepositoriesForWorkspace(workspaceFolderUri: WorkspaceFolderUri): RepositoryMap { return this.#workspaces.get(workspaceFolderUri) || new Map(); } #emptyRepositoriesForWorkspace(workspaceFolderUri: WorkspaceFolderUri): void { log.debug(`Emptying repositories for workspace ${workspaceFolderUri}`); const repos = this.#workspaces.get(workspaceFolderUri); if (!repos || repos.size === 0) return; // clear up ignore manager trie from memory repos.forEach((repo) => { repo.dispose(); log.debug(`Repository ${repo.uri} has been disposed`); }); repos.clear(); const trie = this.#workspaceRepositoryTries.get(workspaceFolderUri); if (trie) { trie.dispose(); this.#workspaceRepositoryTries.delete(workspaceFolderUri); } this.#workspaces.delete(workspaceFolderUri); log.debug(`Repositories for workspace ${workspaceFolderUri} have been emptied`); } #detectRepositories(files: URI[], workspaceFolder: WorkspaceFolder): Repository[] { const gitConfigFiles = files.filter((file) => file.toString().endsWith('.git/config')); return gitConfigFiles.map((file) => { const projectUri = fsPathToUri(file.path.replace('.git/config', '')); const ignoreManager = new IgnoreManager(projectUri.fsPath); log.info(`Detected repository at ${projectUri.path}`); return new Repository({ ignoreManager, uri: projectUri, configFileUri: file, workspaceFolder, }); }); } getFilesForWorkspace( workspaceFolderUri: WorkspaceFolderUri, options: { excludeGitFolder?: boolean; excludeIgnored?: boolean } = {}, ): RepositoryFile[] { const repositories = this.#getRepositoriesForWorkspace(workspaceFolderUri); const allFiles: RepositoryFile[] = []; repositories.forEach((repository) => { repository.getFiles().forEach((file) => { // apply the filters if (options.excludeGitFolder && this.#isInGitFolder(file.uri, repository.uri)) { return; } if (options.excludeIgnored && file.isIgnored) { return; } allFiles.push(file); }); }); return allFiles; } // Helper method to check if a file is in the .git folder #isInGitFolder(fileUri: URI, repositoryUri: URI): boolean { const relativePath = fileUri.path.slice(repositoryUri.path.length); return relativePath.split('/').some((part) => part === '.git'); } } References:" You are a code assistant,Definition of 'sanitizeRange' in file src/common/utils/sanitize_range.ts in project gitlab-lsp,"Definition: export function sanitizeRange(range: Range): Range { if (Array.isArray(range)) { return { start: range[0], end: range[1] }; } return range; } References: - src/common/suggestion/suggestion_filter.ts:35 - src/common/utils/sanitize_range.test.ts:9 - src/common/document_transformer_service.ts:118 - src/common/utils/suggestion_mappers.ts:61" You are a code assistant,Definition of 'get' in file src/common/fetch.ts in project gitlab-lsp,"Definition: async get(input: RequestInfo | URL, init?: RequestInit): Promise { return this.fetch(input, this.updateRequestInit('GET', init)); } async post(input: RequestInfo | URL, init?: RequestInit): Promise { return this.fetch(input, this.updateRequestInit('POST', init)); } async put(input: RequestInfo | URL, init?: RequestInit): Promise { return this.fetch(input, this.updateRequestInit('PUT', init)); } async fetchBase(input: RequestInfo | URL, init?: RequestInit): Promise { // 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/utils/headers_to_snowplow_options.ts:21 - src/common/config_service.ts:134 - src/common/utils/headers_to_snowplow_options.ts:12 - src/common/utils/headers_to_snowplow_options.ts:20 - src/common/utils/headers_to_snowplow_options.ts:22" You are a code assistant,Definition of 'hasbinFirst' in file src/tests/int/hasbin.ts in project gitlab-lsp,"Definition: export function hasbinFirst(bins: string[], done: (result: boolean) => void) { async.detect(bins, hasbin.async, function (result) { done(result || false); }); } export function hasbinFirstSync(bins: string[]) { const matched = bins.filter(hasbin.sync); return matched.length ? matched[0] : false; } export function getPaths(bin: string) { const envPath = process.env.PATH || ''; const envExt = process.env.PATHEXT || ''; return envPath .replace(/[""]+/g, '') .split(delimiter) .map(function (chunk) { return envExt.split(delimiter).map(function (ext) { return join(chunk, bin + ext); }); }) .reduce(function (a, b) { return a.concat(b); }); } 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 'submitFeedback' in file packages/webview_duo_chat/src/plugin/port/chat/utils/submit_feedback.ts in project gitlab-lsp,"Definition: export const submitFeedback = async (_: SubmitFeedbackParams) => { // const hasFeedback = Boolean(extendedTextFeedback?.length) || Boolean(feedbackChoices?.length); // if (!hasFeedback) { // return; // } // const standardContext = buildStandardContext(extendedTextFeedback, gitlabEnvironment); // const ideExtensionVersion = buildIdeExtensionContext(); // await Snowplow.getInstance().trackStructEvent( // { // category: 'ask_gitlab_chat', // action: 'click_button', // label: 'response_feedback', // property: feedbackChoices?.join(','), // }, // [standardContext, ideExtensionVersion], // ); }; References:" You are a code assistant,Definition of 'IDuoConfig' in file src/common/config_service.ts in project gitlab-lsp,"Definition: export interface IDuoConfig { enabledWithoutGitlabProject?: boolean; } export interface IClientConfig { /** GitLab API URL used for getting code suggestions */ baseUrl?: string; /** Full project path. */ projectPath?: string; /** PAT or OAuth token used to authenticate to GitLab API */ token?: string; /** The base URL for language server assets in the client-side extension */ baseAssetsUrl?: string; clientInfo?: IClientInfo; // FIXME: this key should be codeSuggestions (we have code completion and code generation) codeCompletion?: ICodeCompletionConfig; openTabsContext?: boolean; telemetry?: ITelemetryOptions; /** Config used for caching code suggestions */ suggestionsCache?: ISuggestionsCacheOptions; workspaceFolders?: WorkspaceFolder[] | null; /** Collection of Feature Flag values which are sent from the client */ featureFlags?: Record; logLevel?: LogLevel; ignoreCertificateErrors?: boolean; httpAgentOptions?: IHttpAgentOptions; snowplowTrackerOptions?: ISnowplowTrackerOptions; // TODO: move to `duo` duoWorkflowSettings?: IWorkflowSettings; securityScannerOptions?: ISecurityScannerOptions; duo?: IDuoConfig; } export interface IConfig { // TODO: we can possibly remove this extra level of config and move all IClientConfig properties to IConfig client: IClientConfig; } /** * ConfigService manages user configuration (e.g. baseUrl) and application state (e.g. codeCompletion.enabled) * TODO: Maybe in the future we would like to separate these two */ export interface ConfigService { get: TypedGetter; /** * set sets the property of the config * the new value completely overrides the old one */ set: TypedSetter; onConfigChange(listener: (config: IConfig) => void): Disposable; /** * merge adds `newConfig` properties into existing config, if the * property is present in both old and new config, `newConfig` * properties take precedence unless not defined * * This method performs deep merge * * **Arrays are not merged; they are replaced with the new value.** * */ merge(newConfig: Partial): void; } export const ConfigService = createInterfaceId('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 = (key?: string) => { return key ? get(this.#config, key) : this.#config; }; set: TypedSetter = (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) { mergeWith(this.#config, newConfig, (target, src) => (isArray(target) ? src : undefined)); this.#triggerChange(); } } References: - src/common/config_service.ts:75" You are a code assistant,Definition of 'DuoWorkflowEventConnectionType' in file packages/webview_duo_workflow/src/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 'IDirectConnectionDetails' in file src/common/api.ts in project gitlab-lsp,"Definition: export interface IDirectConnectionDetails { base_url: string; token: string; expires_at: number; headers: IDirectConnectionDetailsHeaders; model_details: IDirectConnectionModelDetails; } const CONFIG_CHANGE_EVENT_NAME = 'apiReconfigured'; @Injectable(GitLabApiClient, [LsFetch, ConfigService]) export class GitLabAPI implements GitLabApiClient { #token: string | undefined; #baseURL: string; #clientInfo?: IClientInfo; #lsFetch: LsFetch; #eventEmitter = new EventEmitter(); #configService: ConfigService; #instanceVersion?: string; constructor(lsFetch: LsFetch, configService: ConfigService) { this.#baseURL = GITLAB_API_BASE_URL; this.#lsFetch = lsFetch; this.#configService = configService; this.#configService.onConfigChange(async (config) => { this.#clientInfo = configService.get('client.clientInfo'); this.#lsFetch.updateAgentOptions({ ignoreCertificateErrors: this.#configService.get('client.ignoreCertificateErrors') ?? false, ...(this.#configService.get('client.httpAgentOptions') ?? {}), }); await this.configureApi(config.client); }); } onApiReconfigured(listener: (data: ApiReconfiguredData) => void): Disposable { this.#eventEmitter.on(CONFIG_CHANGE_EVENT_NAME, listener); return { dispose: () => this.#eventEmitter.removeListener(CONFIG_CHANGE_EVENT_NAME, listener) }; } #fireApiReconfigured(isInValidState: boolean, validationMessage?: string) { const data: ApiReconfiguredData = { isInValidState, validationMessage }; this.#eventEmitter.emit(CONFIG_CHANGE_EVENT_NAME, data); } async configureApi({ token, baseUrl = GITLAB_API_BASE_URL, }: { token?: string; baseUrl?: string; }) { if (this.#token === token && this.#baseURL === baseUrl) return; this.#token = token; this.#baseURL = baseUrl; const { valid, reason, message } = await this.checkToken(this.#token); let validationMessage; if (!valid) { this.#configService.set('client.token', undefined); validationMessage = `Token is invalid. ${message}. Reason: ${reason}`; log.warn(validationMessage); } else { log.info('Token is valid'); } this.#instanceVersion = await this.#getGitLabInstanceVersion(); this.#fireApiReconfigured(valid, validationMessage); } #looksLikePatToken(token: string): boolean { // OAuth tokens will be longer than 42 characters and PATs will be shorter. return token.length < 42; } async #checkPatToken(token: string): Promise { const headers = this.#getDefaultHeaders(token); const response = await this.#lsFetch.get( `${this.#baseURL}/api/v4/personal_access_tokens/self`, { headers }, ); await handleFetchError(response, 'Information about personal access token'); const { active, scopes } = (await response.json()) as PersonalAccessToken; if (!active) { return { valid: false, reason: 'not_active', message: 'Token is not active.', }; } if (!this.#hasValidScopes(scopes)) { const joinedScopes = scopes.map((scope) => `'${scope}'`).join(', '); return { valid: false, reason: 'invalid_scopes', message: `Token has scope(s) ${joinedScopes} (needs 'api').`, }; } return { valid: true }; } async #checkOAuthToken(token: string): Promise { const headers = this.#getDefaultHeaders(token); const response = await this.#lsFetch.get(`${this.#baseURL}/oauth/token/info`, { headers, }); await handleFetchError(response, 'Information about OAuth token'); const { scope: scopes } = (await response.json()) as OAuthToken; if (!this.#hasValidScopes(scopes)) { const joinedScopes = scopes.map((scope) => `'${scope}'`).join(', '); return { valid: false, reason: 'invalid_scopes', message: `Token has scope(s) ${joinedScopes} (needs 'api').`, }; } return { valid: true }; } async checkToken(token: string = ''): Promise { try { if (this.#looksLikePatToken(token)) { log.info('Checking token for PAT validity'); return await this.#checkPatToken(token); } log.info('Checking token for OAuth validity'); return await this.#checkOAuthToken(token); } catch (err) { log.error('Error performing token check', err); return { valid: false, reason: 'unknown', message: `Failed to check token: ${err}`, }; } } #hasValidScopes(scopes: string[]): boolean { return scopes.includes('api'); } async getCodeSuggestions( request: CodeSuggestionRequest, ): Promise { if (!this.#token) { throw new Error('Token needs to be provided to request Code Suggestions'); } const headers = { ...this.#getDefaultHeaders(this.#token), 'Content-Type': 'application/json', }; const response = await this.#lsFetch.post( `${this.#baseURL}/api/v4/code_suggestions/completions`, { headers, body: JSON.stringify(request) }, ); await handleFetchError(response, 'Code Suggestions'); const data = await response.json(); return { ...data, status: response.status }; } async *getStreamingCodeSuggestions( request: CodeSuggestionRequest, ): AsyncGenerator { if (!this.#token) { throw new Error('Token needs to be provided to stream code suggestions'); } const headers = { ...this.#getDefaultHeaders(this.#token), 'Content-Type': 'application/json', }; yield* this.#lsFetch.streamFetch( `${this.#baseURL}/api/v4/code_suggestions/completions`, JSON.stringify(request), headers, ); } async fetchFromApi(request: ApiRequest): Promise { if (!this.#token) { return Promise.reject(new Error('Token needs to be provided to authorise API request.')); } if ( request.supportedSinceInstanceVersion && !this.#instanceVersionHigherOrEqualThen(request.supportedSinceInstanceVersion.version) ) { return Promise.reject( new InvalidInstanceVersionError( `Can't ${request.supportedSinceInstanceVersion.resourceName} until your instance is upgraded to ${request.supportedSinceInstanceVersion.version} or higher.`, ), ); } if (request.type === 'graphql') { return this.#graphqlRequest(request.query, request.variables); } switch (request.method) { case 'GET': return this.#fetch(request.path, request.searchParams, 'resource', request.headers); case 'POST': return this.#postFetch(request.path, 'resource', request.body, request.headers); default: // the type assertion is necessary because TS doesn't expect any other types throw new Error(`Unknown request type ${(request as ApiRequest).type}`); } } async connectToCable(): Promise { const headers = this.#getDefaultHeaders(this.#token); const websocketOptions = { headers: { ...headers, Origin: this.#baseURL, }, }; return connectToCable(this.#baseURL, websocketOptions); } async #graphqlRequest( document: RequestDocument, variables?: V, ): Promise { const ensureEndsWithSlash = (url: string) => url.replace(/\/?$/, '/'); const endpoint = new URL('./api/graphql', ensureEndsWithSlash(this.#baseURL)).href; // supports GitLab instances that are on a custom path, e.g. ""https://example.com/gitlab"" const graphqlFetch = async ( input: RequestInfo | URL, init?: RequestInit, ): Promise => { const url = input instanceof URL ? input.toString() : input; return this.#lsFetch.post(url, { ...init, headers: { ...headers, ...init?.headers }, }); }; const headers = this.#getDefaultHeaders(this.#token); const client = new GraphQLClient(endpoint, { headers, fetch: graphqlFetch, }); return client.request(document, variables); } async #fetch( apiResourcePath: string, query: Record = {}, resourceName = 'resource', headers?: Record, ): Promise { const url = `${this.#baseURL}/api/v4${apiResourcePath}${createQueryString(query)}`; const result = await this.#lsFetch.get(url, { headers: { ...this.#getDefaultHeaders(this.#token), ...headers }, }); await handleFetchError(result, resourceName); return result.json() as Promise; } async #postFetch( apiResourcePath: string, resourceName = 'resource', body?: unknown, headers?: Record, ): Promise { const url = `${this.#baseURL}/api/v4${apiResourcePath}`; const response = await this.#lsFetch.post(url, { headers: { 'Content-Type': 'application/json', ...this.#getDefaultHeaders(this.#token), ...headers, }, body: JSON.stringify(body), }); await handleFetchError(response, resourceName); return response.json() as Promise; } #getDefaultHeaders(token?: string) { return { Authorization: `Bearer ${token}`, 'User-Agent': `code-completions-language-server-experiment (${this.#clientInfo?.name}:${this.#clientInfo?.version})`, 'X-Gitlab-Language-Server-Version': getLanguageServerVersion(), }; } #instanceVersionHigherOrEqualThen(version: string): boolean { if (!this.#instanceVersion) return false; return semverCompare(this.#instanceVersion, version) >= 0; } async #getGitLabInstanceVersion(): Promise { if (!this.#token) { return ''; } const headers = this.#getDefaultHeaders(this.#token); const response = await this.#lsFetch.get(`${this.#baseURL}/api/v4/version`, { headers, }); const { version } = await response.json(); return version; } get instanceVersion() { return this.#instanceVersion; } } References: - src/common/suggestion_client/direct_connection_client.ts:24" You are a code assistant,Definition of 'UNSUPPORTED_LANGUAGE' in file src/common/feature_state/feature_state_management_types.ts in project gitlab-lsp,"Definition: export const UNSUPPORTED_LANGUAGE = 'code-suggestions-document-unsupported-language' as const; export const DISABLED_LANGUAGE = 'code-suggestions-document-disabled-language' as const; export type StateCheckId = | typeof NO_LICENSE | typeof DUO_DISABLED_FOR_PROJECT | typeof UNSUPPORTED_GITLAB_VERSION | typeof UNSUPPORTED_LANGUAGE | typeof DISABLED_LANGUAGE; export interface FeatureStateCheck { checkId: StateCheckId; details?: string; } export interface FeatureState { featureId: Feature; engagedChecks: FeatureStateCheck[]; } const CODE_SUGGESTIONS_CHECKS_PRIORITY_ORDERED = [ DUO_DISABLED_FOR_PROJECT, UNSUPPORTED_LANGUAGE, DISABLED_LANGUAGE, ]; const CHAT_CHECKS_PRIORITY_ORDERED = [DUO_DISABLED_FOR_PROJECT]; export const CHECKS_PER_FEATURE: { [key in Feature]: StateCheckId[] } = { [CODE_SUGGESTIONS]: CODE_SUGGESTIONS_CHECKS_PRIORITY_ORDERED, [CHAT]: CHAT_CHECKS_PRIORITY_ORDERED, // [WORKFLOW]: [], }; References:" You are a code assistant,Definition of 'SuggestionSource' in file src/common/tracking/tracking_types.ts in project gitlab-lsp,"Definition: export enum SuggestionSource { cache = 'cache', network = 'network', } export interface IIDEInfo { name: string; version: string; vendor: string; } 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, ): void; updateCodeSuggestionsContext( uniqueTrackingId: string, contextUpdate: Partial, ): void; rejectOpenedSuggestions(): void; updateSuggestionState(uniqueTrackingId: string, newState: TRACKING_EVENTS): void; } export const TelemetryTracker = createInterfaceId('TelemetryTracker'); References: - src/common/tracking/snowplow_tracker.ts:61 - src/common/tracking/tracking_types.ts:9" You are a code assistant,Definition of 'Injectable' in file packages/lib_di/src/index.ts in project gitlab-lsp,"Definition: export function Injectable[]>( id: InterfaceId, dependencies: [...TDependencies], // we can add `| [] = [],` to make dependencies optional, but the type checker messages are quite cryptic when the decorated class has some constructor arguments ) { // this is the trickiest part of the whole DI framework // we say, this decorator takes // - id (the interface that the injectable implements) // - dependencies (list of interface ids that will be injected to constructor) // // With then we return function that ensures that the decorated class implements the id interface // and its constructor has arguments of same type and order as the dependencies argument to the decorator return function ): I }>( constructor: T, { kind }: ClassDecoratorContext, ) { if (kind === 'class') { injectableMetadata.set(constructor, { id, dependencies: dependencies || [] }); return constructor; } throw new Error('Injectable decorator can only be used on a class.'); }; } // new (...args: any[]): any is actually how TS defines type of a class // eslint-disable-next-line @typescript-eslint/no-explicit-any type WithConstructor = { new (...args: any[]): any; name: string }; type ClassWithDependencies = { cls: WithConstructor; id: string; dependencies: string[] }; type Validator = (cwds: ClassWithDependencies[], instanceIds: string[]) => void; const sanitizeId = (idWithRandom: string) => idWithRandom.replace(/-[^-]+$/, ''); /** ensures that only one interface ID implementation is present */ const interfaceUsedOnlyOnce: Validator = (cwds, instanceIds) => { const clashingWithExistingInstance = cwds.filter((cwd) => instanceIds.includes(cwd.id)); if (clashingWithExistingInstance.length > 0) { throw new Error( `The following classes are clashing (have duplicate ID) with instances already present in the container: ${clashingWithExistingInstance.map((cwd) => cwd.cls.name)}`, ); } const groupedById = groupBy(cwds, (cwd) => cwd.id); if (Object.values(groupedById).every((groupedCwds) => groupedCwds.length === 1)) { return; } const messages = Object.entries(groupedById).map( ([id, groupedCwds]) => `'${sanitizeId(id)}' (classes: ${groupedCwds.map((cwd) => cwd.cls.name).join(',')})`, ); throw new Error(`The following interface IDs were used multiple times ${messages.join(',')}`); }; /** throws an error if any class depends on an interface that is not available */ const dependenciesArePresent: Validator = (cwds, instanceIds) => { const allIds = new Set([...cwds.map((cwd) => cwd.id), ...instanceIds]); const cwsWithUnmetDeps = cwds.filter((cwd) => !cwd.dependencies.every((d) => allIds.has(d))); if (cwsWithUnmetDeps.length === 0) { return; } const messages = cwsWithUnmetDeps.map((cwd) => { const unmetDeps = cwd.dependencies.filter((d) => !allIds.has(d)).map(sanitizeId); return `Class ${cwd.cls.name} (interface ${sanitizeId(cwd.id)}) depends on interfaces [${unmetDeps}] that weren't added to the init method.`; }); throw new Error(messages.join('\n')); }; /** uses depth first search to find out if the classes have circular dependency */ const noCircularDependencies: Validator = (cwds, instanceIds) => { const inStack = new Set(); const hasCircularDependency = (id: string): boolean => { if (inStack.has(id)) { return true; } inStack.add(id); const cwd = cwds.find((c) => c.id === id); // we reference existing instance, there won't be circular dependency past this one because instances don't have any dependencies if (!cwd && instanceIds.includes(id)) { inStack.delete(id); return false; } if (!cwd) throw new Error(`assertion error: dependency ID missing ${sanitizeId(id)}`); for (const dependencyId of cwd.dependencies) { if (hasCircularDependency(dependencyId)) { return true; } } inStack.delete(id); return false; }; for (const cwd of cwds) { if (hasCircularDependency(cwd.id)) { throw new Error( `Circular dependency detected between interfaces (${Array.from(inStack).map(sanitizeId)}), starting with '${sanitizeId(cwd.id)}' (class: ${cwd.cls.name}).`, ); } } }; /** * Topological sort of the dependencies - returns array of classes. The classes should be initialized in order given by the array. * https://en.wikipedia.org/wiki/Topological_sorting */ const sortDependencies = (classes: Map): ClassWithDependencies[] => { const visited = new Set(); const sortedClasses: ClassWithDependencies[] = []; const topologicalSort = (interfaceId: string) => { if (visited.has(interfaceId)) { return; } visited.add(interfaceId); const cwd = classes.get(interfaceId); if (!cwd) { // the instance for this ID is already initiated return; } for (const d of cwd.dependencies || []) { topologicalSort(d); } sortedClasses.push(cwd); }; for (const id of classes.keys()) { topologicalSort(id); } return sortedClasses; }; /** * Helper type used by the brandInstance function to ensure that all container.addInstances parameters are branded */ export type BrandedInstance = T; /** * use brandInstance to be able to pass this instance to the container.addInstances method */ export const brandInstance = ( id: InterfaceId, instance: T, ): BrandedInstance => { injectableMetadata.set(instance, { id, dependencies: [] }); return instance; }; /** * Container is responsible for initializing a dependency tree. * * It receives a list of classes decorated with the `@Injectable` decorator * and it constructs instances of these classes in an order that ensures class' dependencies * are initialized before the class itself. * * check https://gitlab.com/viktomas/needle for full documentation of this mini-framework */ export class Container { #instances = new Map(); /** * addInstances allows you to add pre-initialized objects to the container. * This is useful when you want to keep mandatory parameters in class' constructor (e.g. some runtime objects like server connection). * addInstances accepts a list of any objects that have been ""branded"" by the `brandInstance` method */ addInstances(...instances: BrandedInstance[]) { for (const instance of instances) { const metadata = injectableMetadata.get(instance); if (!metadata) { throw new Error( 'assertion error: addInstance invoked without branded object, make sure all arguments are branded with `brandInstance`', ); } if (this.#instances.has(metadata.id)) { throw new Error( `you are trying to add instance for interfaceId ${metadata.id}, but instance with this ID is already in the container.`, ); } this.#instances.set(metadata.id, instance); } } /** * instantiate accepts list of classes, validates that they can be managed by the container * and then initialized them in such order that dependencies of a class are initialized before the class */ instantiate(...classes: WithConstructor[]) { // ensure all classes have been decorated with @Injectable const undecorated = classes.filter((c) => !injectableMetadata.has(c)).map((c) => c.name); if (undecorated.length) { throw new Error(`Classes [${undecorated}] are not decorated with @Injectable.`); } const classesWithDeps: ClassWithDependencies[] = classes.map((cls) => { // we verified just above that all classes are present in the metadata map // eslint-disable-next-line @typescript-eslint/no-non-null-assertion const { id, dependencies } = injectableMetadata.get(cls)!; return { cls, id, dependencies }; }); const validators: Validator[] = [ interfaceUsedOnlyOnce, dependenciesArePresent, noCircularDependencies, ]; validators.forEach((v) => v(classesWithDeps, Array.from(this.#instances.keys()))); const classesById = new Map(); // Index classes by their interface id classesWithDeps.forEach((cwd) => { classesById.set(cwd.id, cwd); }); // Create instances in topological order for (const cwd of sortDependencies(classesById)) { const args = cwd.dependencies.map((dependencyId) => this.#instances.get(dependencyId)); // eslint-disable-next-line new-cap const instance = new cwd.cls(...args); this.#instances.set(cwd.id, instance); } } get(id: InterfaceId): T { const instance = this.#instances.get(id); if (!instance) { throw new Error(`Instance for interface '${sanitizeId(id)}' is not in the container.`); } return instance as T; } } References: - packages/lib_di/src/index.test.ts:98 - src/common/config_service.ts:110 - src/common/ai_context_management_2/policies/duo_project_policy.ts:11 - src/common/services/duo_access/project_access_cache.ts:85 - packages/lib_di/src/index.test.ts:25 - packages/lib_di/src/index.test.ts:36 - src/common/api.ts:119 - src/common/ai_context_management_2/ai_context_aggregator.ts:22 - src/common/services/fs/dir.ts:40 - src/common/suggestion/supported_languages_service.ts:28 - src/common/secret_redaction/index.ts:13 - src/common/core/handlers/did_change_workspace_folders_handler.ts:12 - src/common/feature_state/feature_state_manager.ts:19 - packages/lib_di/src/index.test.ts:20 - src/common/ai_context_management_2/retrievers/ai_file_context_retriever.ts:14 - src/common/feature_state/supported_language_check.ts:16 - packages/lib_di/src/index.test.ts:142 - src/common/security_diagnostics_publisher.ts:31 - src/node/services/fs/dir.ts:22 - src/node/duo_workflow/desktop_workflow_runner.ts:41 - src/common/advanced_context/advanced_context_service.ts:18 - packages/lib_di/src/index.test.ts:161 - src/common/core/handlers/initialize_handler.ts:17 - src/common/services/duo_access/project_access_checker.ts:18 - src/common/ai_context_management_2/ai_policy_management.ts:20 - src/node/services/fs/file.ts:6 - src/common/core/handlers/token_check_notifier.ts:10 - src/common/workspace/workspace_service.ts:18 - src/common/document_transformer_service.ts:75 - src/common/services/fs/virtual_file_service.ts:40 - src/common/feature_state/project_duo_acces_check.ts:19 - src/common/git/repository_service.ts:26 - src/common/feature_flags.ts:41 - src/common/ai_context_management_2/ai_context_manager.ts:11 - src/common/services/fs/file.ts:13 - src/node/fetch.ts:36 - src/common/connection_service.ts:41 - src/common/ai_context_management_2/providers/ai_file_context_provider.ts:19 - src/common/graphql/workflow/service.ts:12" You are a code assistant,Definition of 'CODE_SUGGESTIONS' in file src/common/feature_state/feature_state_management_types.ts in project gitlab-lsp,"Definition: export const CODE_SUGGESTIONS = 'code_suggestions' as const; export const CHAT = 'chat' as const; // export const WORKFLOW = 'workflow' as const; export type Feature = typeof CODE_SUGGESTIONS | typeof CHAT; // | typeof WORKFLOW; export const NO_LICENSE = 'code-suggestions-no-license' as const; export const DUO_DISABLED_FOR_PROJECT = 'duo-disabled-for-project' as const; export const UNSUPPORTED_GITLAB_VERSION = 'unsupported-gitlab-version' as const; export const UNSUPPORTED_LANGUAGE = 'code-suggestions-document-unsupported-language' as const; export const DISABLED_LANGUAGE = 'code-suggestions-document-disabled-language' as const; export type StateCheckId = | typeof NO_LICENSE | typeof DUO_DISABLED_FOR_PROJECT | typeof UNSUPPORTED_GITLAB_VERSION | typeof UNSUPPORTED_LANGUAGE | typeof DISABLED_LANGUAGE; export interface FeatureStateCheck { checkId: StateCheckId; details?: string; } export interface FeatureState { featureId: Feature; engagedChecks: FeatureStateCheck[]; } const CODE_SUGGESTIONS_CHECKS_PRIORITY_ORDERED = [ DUO_DISABLED_FOR_PROJECT, UNSUPPORTED_LANGUAGE, DISABLED_LANGUAGE, ]; const CHAT_CHECKS_PRIORITY_ORDERED = [DUO_DISABLED_FOR_PROJECT]; export const CHECKS_PER_FEATURE: { [key in Feature]: StateCheckId[] } = { [CODE_SUGGESTIONS]: CODE_SUGGESTIONS_CHECKS_PRIORITY_ORDERED, [CHAT]: CHAT_CHECKS_PRIORITY_ORDERED, // [WORKFLOW]: [], }; References:" You are a code assistant,Definition of 'constructor' in file src/common/circuit_breaker/fixed_time_circuit_breaker.ts in project gitlab-lsp,"Definition: 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:" You are a code assistant,Definition of 'constructor' in file src/common/workspace/workspace_service.ts in project gitlab-lsp,"Definition: constructor(virtualFileSystemService: DefaultVirtualFileSystemService) { this.#virtualFileSystemService = virtualFileSystemService; this.#disposable = this.#setupEventListeners(); } #setupEventListeners() { return this.#virtualFileSystemService.onFileSystemEvent((eventType, data) => { switch (eventType) { case VirtualFileSystemEvents.WorkspaceFilesUpdate: this.#handleWorkspaceFilesUpdate(data as WorkspaceFilesUpdate); break; case VirtualFileSystemEvents.WorkspaceFileUpdate: this.#handleWorkspaceFileUpdate(data as WorkspaceFileUpdate); break; default: break; } }); } #handleWorkspaceFilesUpdate(update: WorkspaceFilesUpdate) { const files: FileSet = new Map(); for (const file of update.files) { files.set(file.toString(), file); } this.#workspaceFilesMap.set(update.workspaceFolder.uri, files); } #handleWorkspaceFileUpdate(update: WorkspaceFileUpdate) { let files = this.#workspaceFilesMap.get(update.workspaceFolder.uri); if (!files) { files = new Map(); this.#workspaceFilesMap.set(update.workspaceFolder.uri, files); } switch (update.event) { case 'add': case 'change': files.set(update.fileUri.toString(), update.fileUri); break; case 'unlink': files.delete(update.fileUri.toString()); break; default: break; } } getWorkspaceFiles(workspaceFolder: WorkspaceFolder): FileSet | undefined { return this.#workspaceFilesMap.get(workspaceFolder.uri); } dispose() { this.#disposable.dispose(); } } References:" You are a code assistant,Definition of 'constructor' in file src/node/webview/http_access_info_provider.ts in project gitlab-lsp,"Definition: constructor(address: AddressInfo) { this.#addressInfo = address; } getUri(webviewId: WebviewId): string { return `http://${this.#addressInfo.address}:${this.#addressInfo.port}/webview/${webviewId}`; } } References:" You are a code assistant,Definition of 'WEB_IDE_AUTH_SCOPE' in file packages/webview_duo_chat/src/plugin/port/platform/web_ide.ts in project gitlab-lsp,"Definition: export const WEB_IDE_AUTH_SCOPE = 'api'; // region: Mediator commands ------------------------------------------- export const COMMAND_FETCH_FROM_API = `gitlab-web-ide.mediator.fetch-from-api`; export const COMMAND_FETCH_BUFFER_FROM_API = `gitlab-web-ide.mediator.fetch-buffer-from-api`; export const COMMAND_MEDIATOR_TOKEN = `gitlab-web-ide.mediator.mediator-token`; 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; } /** * 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; headers?: Record; } export interface GetRequest<_TReturnType> extends GetRequestBase<_TReturnType> { type: 'rest'; } export interface GetBufferRequest extends GetRequestBase { type: 'rest-buffer'; } export interface GraphQLRequest<_TReturnType> { type: 'graphql'; query: string; /** Options passed to the GraphQL query */ variables: Record; } 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; /* 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 'preparePayload' in file src/common/tracking/snowplow/snowplow.ts in project gitlab-lsp,"Definition: function preparePayload(payload: Payload): Record { const stringifiedPayload: Record = {}; Object.keys(payload).forEach((key) => { stringifiedPayload[key] = String(payload[key]); }); stringifiedPayload.stm = new Date().getTime().toString(); return stringifiedPayload; } export class Snowplow { /** Disable sending events when it's not possible. */ disabled: boolean = false; #emitter: Emitter; #lsFetch: LsFetch; #options: SnowplowOptions; #tracker: TrackerCore; static #instance?: Snowplow; // eslint-disable-next-line no-restricted-syntax private constructor(lsFetch: LsFetch, options: SnowplowOptions) { this.#lsFetch = lsFetch; this.#options = options; this.#emitter = new Emitter( this.#options.timeInterval, this.#options.maxItems, this.#sendEvent.bind(this), ); this.#emitter.start(); this.#tracker = trackerCore({ callback: this.#emitter.add.bind(this.#emitter) }); } public static getInstance(lsFetch: LsFetch, options?: SnowplowOptions): Snowplow { if (!this.#instance) { if (!options) { throw new Error('Snowplow should be instantiated'); } const sp = new Snowplow(lsFetch, options); Snowplow.#instance = sp; } // FIXME: this eslint violation was introduced before we set up linting // eslint-disable-next-line @typescript-eslint/no-non-null-assertion return Snowplow.#instance!; } async #sendEvent(events: PayloadBuilder[]): Promise { if (!this.#options.enabled() || this.disabled) { return; } try { const url = `${this.#options.endpoint}/com.snowplowanalytics.snowplow/tp2`; const data = { schema: 'iglu:com.snowplowanalytics.snowplow/payload_data/jsonschema/1-0-4', data: events.map((event) => { const eventId = uuidv4(); // All values prefilled below are part of snowplow tracker protocol // https://docs.snowplow.io/docs/collecting-data/collecting-from-own-applications/snowplow-tracker-protocol/#common-parameters // Values are set according to either common GitLab standard: // tna - representing tracker namespace and being set across GitLab to ""gl"" // tv - represents tracker value, to make it aligned with downstream system it has to be prefixed with ""js-*"""" // aid - represents app Id is configured via options to gitlab_ide_extension // eid - represents uuid for each emitted event event.add('eid', eventId); event.add('p', 'app'); event.add('tv', 'js-gitlab'); event.add('tna', 'gl'); event.add('aid', this.#options.appId); return preparePayload(event.build()); }), }; const config = { headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(data), }; const response = await this.#lsFetch.post(url, config); if (response.status !== 200) { log.warn( `Could not send telemetry to snowplow, this warning can be safely ignored. status=${response.status}`, ); } } catch (error) { let errorHandled = false; if (typeof error === 'object' && 'errno' in (error as object)) { const errObject = error as object; // ENOTFOUND occurs when the snowplow hostname cannot be resolved. if ('errno' in errObject && errObject.errno === 'ENOTFOUND') { this.disabled = true; errorHandled = true; log.info('Disabling telemetry, unable to resolve endpoint address.'); } else { log.warn(JSON.stringify(errObject)); } } if (!errorHandled) { log.warn('Failed to send telemetry event, this warning can be safely ignored'); log.warn(JSON.stringify(error)); } } } public async trackStructEvent( event: StructuredEvent, context?: SelfDescribingJson[] | null, ): Promise { this.#tracker.track(buildStructEvent(event), context); } async stop() { await this.#emitter.stop(); } public destroy() { Snowplow.#instance = undefined; } } References: - src/common/tracking/snowplow/snowplow.ts:107" You are a code assistant,Definition of 'IntentResolution' in file src/common/tree_sitter/intent_resolver.ts in project gitlab-lsp,"Definition: export type IntentResolution = { intent: Intent; commentForCursor?: Comment; generationType?: GenerationType; }; /** * Determines the user intent based on cursor position and context within the file. * Intent is determined based on several ordered rules: * - Returns 'completion' if the cursor is located on or after an empty comment. * - Returns 'generation' if the cursor is located after a non-empty comment. * - Returns 'generation' if the cursor is not located after a comment and the file is less than 5 lines. * - Returns undefined if neither a comment nor small file is detected. */ export async function getIntent({ treeAndLanguage, position, prefix, suffix, }: { treeAndLanguage: TreeAndLanguage; position: Position; prefix: string; suffix: string; }): Promise { const commentResolver = getCommentResolver(); const emptyFunctionResolver = getEmptyFunctionResolver(); const cursorPosition = { row: position.line, column: position.character }; const { languageInfo, tree, language: treeSitterLanguage } = treeAndLanguage; const commentResolution = commentResolver.getCommentForCursor({ languageName: languageInfo.name, tree, cursorPosition, treeSitterLanguage, }); if (commentResolution) { const { commentAtCursor, commentAboveCursor } = commentResolution; if (commentAtCursor) { log.debug('IntentResolver: Cursor is directly on a comment, sending intent: completion'); return { intent: 'completion' }; } const isCommentEmpty = CommentResolver.isCommentEmpty(commentAboveCursor); if (isCommentEmpty) { log.debug('IntentResolver: Cursor is after an empty comment, sending intent: completion'); return { intent: 'completion' }; } log.debug('IntentResolver: Cursor is after a non-empty comment, sending intent: generation'); return { intent: 'generation', generationType: 'comment', commentForCursor: commentAboveCursor, }; } const textContent = `${prefix}${suffix}`; const totalCommentLines = commentResolver.getTotalCommentLines({ languageName: languageInfo.name, treeSitterLanguage, tree, }); if (isSmallFile(textContent, totalCommentLines)) { log.debug('IntentResolver: Small file detected, sending intent: generation'); return { intent: 'generation', generationType: 'small_file' }; } const isCursorInEmptyFunction = emptyFunctionResolver.isCursorInEmptyFunction({ languageName: languageInfo.name, tree, cursorPosition, treeSitterLanguage, }); if (isCursorInEmptyFunction) { log.debug('IntentResolver: Cursor is in an empty function, sending intent: generation'); return { intent: 'generation', generationType: 'empty_function' }; } log.debug( 'IntentResolver: Cursor is neither at the end of non-empty comment, nor in a small file, nor in empty function - not sending intent.', ); return { intent: undefined }; } References:" You are a code assistant,Definition of 'AiContextFileRetriever' in file src/common/ai_context_management_2/retrievers/ai_file_context_retriever.ts in project gitlab-lsp,"Definition: export const AiContextFileRetriever = createInterfaceId('AiContextFileRetriever'); @Injectable(AiContextFileRetriever, [FileResolver, SecretRedactor]) export class DefaultAiContextFileRetriever implements AiContextRetriever { constructor( private fileResolver: FileResolver, private secretRedactor: SecretRedactor, ) {} async retrieve(aiContextItem: AiContextItem): Promise { if (aiContextItem.type !== 'file') { return null; } try { log.info(`retrieving file ${aiContextItem.id}`); const fileContent = await this.fileResolver.readFile({ fileUri: aiContextItem.id, }); log.info(`redacting secrets for file ${aiContextItem.id}`); const redactedContent = this.secretRedactor.redactSecrets(fileContent); return redactedContent; } catch (e) { log.warn(`Failed to retrieve file ${aiContextItem.id}`, e); return null; } } } References: - src/common/ai_context_management_2/ai_context_manager.ts:15 - src/common/ai_context_management_2/ai_context_manager.ts:13" You are a code assistant,Definition of 'onFileSystemEvent' in file src/common/services/fs/virtual_file_service.ts in project gitlab-lsp,"Definition: 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 'AiCompletionResponseResponseType' in file packages/webview_duo_chat/src/plugin/port/api/graphql/ai_completion_response_channel.ts in project gitlab-lsp,"Definition: type AiCompletionResponseResponseType = { result: { data: { aiCompletionResponse: AiCompletionResponseMessageType; }; }; more: boolean; }; interface AiCompletionResponseChannelEvents extends ChannelEvents { systemMessage: (msg: AiCompletionResponseMessageType) => void; newChunk: (msg: AiCompletionResponseMessageType) => void; fullMessage: (msg: AiCompletionResponseMessageType) => void; } export class AiCompletionResponseChannel extends Channel< AiCompletionResponseParams, AiCompletionResponseResponseType, AiCompletionResponseChannelEvents > { static identifier = 'GraphqlChannel'; constructor(params: AiCompletionResponseInput) { super({ channel: 'GraphqlChannel', operationName: 'aiCompletionResponse', query: AI_MESSAGE_SUBSCRIPTION_QUERY, variables: JSON.stringify(params), }); } receive(message: AiCompletionResponseResponseType) { if (!message.result.data.aiCompletionResponse) return; const data = message.result.data.aiCompletionResponse; if (data.role.toLowerCase() === 'system') { this.emit('systemMessage', data); } else if (data.chunkId) { this.emit('newChunk', data); } else { this.emit('fullMessage', data); } } } References: - packages/webview_duo_chat/src/plugin/port/api/graphql/ai_completion_response_channel.ts:92" You are a code assistant,Definition of 'fetchBase' in file src/common/fetch.ts in project gitlab-lsp,"Definition: async fetchBase(input: RequestInfo | URL, init?: RequestInit): Promise { // 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 'init' in file src/common/feature_state/feature_state_manager.ts in project gitlab-lsp,"Definition: init(notify: NotifyFn): void { this.#notify = notify; } async #notifyClient() { if (!this.#notify) { throw new Error( ""The state manager hasn't been initialized. It can't send notifications. Call the init method first."", ); } await this.#notify(this.#state); } dispose() { this.#subscriptions.forEach((s) => s.dispose()); } get #state(): FeatureState[] { const engagedChecks = this.#checks.filter((check) => check.engaged); return getEntries(CHECKS_PER_FEATURE).map(([featureId, stateChecks]) => { const engagedFeatureChecks: FeatureStateCheck[] = engagedChecks .filter(({ id }) => stateChecks.includes(id)) .map((stateCheck) => ({ checkId: stateCheck.id, details: stateCheck.details, })); return { featureId, engagedChecks: engagedFeatureChecks, }; }); } } References:" You are a code assistant,Definition of 'isInstanceFlagEnabled' in file src/common/feature_flags.ts in project gitlab-lsp,"Definition: 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 'rejectOpenedSuggestions' in file src/common/tracking/tracking_types.ts in project gitlab-lsp,"Definition: rejectOpenedSuggestions(): void; updateSuggestionState(uniqueTrackingId: string, newState: TRACKING_EVENTS): void; } export const TelemetryTracker = createInterfaceId('TelemetryTracker'); References:" You are a code assistant,Definition of 'rejectOpenedSuggestions' in file src/common/tracking/instance_tracker.ts in project gitlab-lsp,"Definition: rejectOpenedSuggestions() { log.debug(`Instance Telemetry: Reject all opened suggestions`); this.#codeSuggestionStates.forEach((state, uniqueTrackingId) => { if (endStates.includes(state)) { return; } this.updateSuggestionState(uniqueTrackingId, TRACKING_EVENTS.REJECTED); }); } static #suggestionSize(options: SuggestionOption[]): number { const countLines = (text: string) => (text ? text.split('\n').length : 0); return Math.max(...options.map(({ text }) => countLines(text))); } #isStreamingSuggestion(uniqueTrackingId: string): boolean { return Boolean(this.#codeSuggestionsContextMap.get(uniqueTrackingId)?.is_streaming); } } References:" You are a code assistant,Definition of 'info' in file packages/lib_logging/src/null_logger.ts in project gitlab-lsp,"Definition: info(message: string, e?: Error | undefined): void; info(): void { // NOOP } warn(e: Error): void; warn(message: string, e?: Error | undefined): void; warn(): void { // NOOP } error(e: Error): void; error(message: string, e?: Error | undefined): void; error(): void { // NOOP } } References:" You are a code assistant,Definition of 'isWebviewInstanceCreatedEventData' in file packages/lib_webview_transport/src/utils/message_validators.ts in project gitlab-lsp,"Definition: export const isWebviewInstanceCreatedEventData: MessageValidator< WebviewInstanceCreatedEventData > = (message: unknown): message is WebviewInstanceCreatedEventData => isWebviewAddress(message); export const isWebviewInstanceDestroyedEventData: MessageValidator< WebviewInstanceDestroyedEventData > = (message: unknown): message is WebviewInstanceDestroyedEventData => isWebviewAddress(message); export const isWebviewInstanceMessageEventData: MessageValidator< WebviewInstanceNotificationEventData > = (message: unknown): message is WebviewInstanceNotificationEventData => isWebviewAddress(message) && 'type' in message; References:" You are a code assistant,Definition of 'FileExtension' in file src/tests/unit/tree_sitter/intent_resolver.test.ts in project gitlab-lsp,"Definition: type FileExtension = string; /** * Position refers to the position of the cursor in the test file. */ type IntentTestCase = [TestType, Position, Intent]; const emptyFunctionTestCases: Array< [LanguageServerLanguageId, FileExtension, IntentTestCase[]] > = [ [ 'typescript', '.ts', // ../../fixtures/intent/empty_function/typescript.ts [ ['empty_function_declaration', { line: 0, character: 22 }, 'generation'], ['non_empty_function_declaration', { line: 3, character: 4 }, undefined], ['empty_function_expression', { line: 6, character: 32 }, 'generation'], ['non_empty_function_expression', { line: 10, character: 4 }, undefined], ['empty_arrow_function', { line: 12, character: 26 }, 'generation'], ['non_empty_arrow_function', { line: 15, character: 4 }, undefined], ['empty_class_constructor', { line: 19, character: 21 }, 'generation'], ['empty_method_definition', { line: 21, character: 11 }, 'generation'], ['non_empty_class_constructor', { line: 29, character: 7 }, undefined], ['non_empty_method_definition', { line: 33, character: 0 }, undefined], ['empty_class_declaration', { line: 36, character: 14 }, 'generation'], ['empty_generator', { line: 38, character: 31 }, 'generation'], ['non_empty_generator', { line: 41, character: 4 }, undefined], ], ], [ 'javascript', '.js', // ../../fixtures/intent/empty_function/javascript.js [ ['empty_function_declaration', { line: 0, character: 22 }, 'generation'], ['non_empty_function_declaration', { line: 3, character: 4 }, undefined], ['empty_function_expression', { line: 6, character: 32 }, 'generation'], ['non_empty_function_expression', { line: 10, character: 4 }, undefined], ['empty_arrow_function', { line: 12, character: 26 }, 'generation'], ['non_empty_arrow_function', { line: 15, character: 4 }, undefined], ['empty_class_constructor', { line: 19, character: 21 }, 'generation'], ['empty_method_definition', { line: 21, character: 11 }, 'generation'], ['non_empty_class_constructor', { line: 27, character: 7 }, undefined], ['non_empty_method_definition', { line: 31, character: 0 }, undefined], ['empty_class_declaration', { line: 34, character: 14 }, 'generation'], ['empty_generator', { line: 36, character: 31 }, 'generation'], ['non_empty_generator', { line: 39, character: 4 }, undefined], ], ], [ 'go', '.go', // ../../fixtures/intent/empty_function/go.go [ ['empty_function_declaration', { line: 0, character: 25 }, 'generation'], ['non_empty_function_declaration', { line: 3, character: 4 }, undefined], ['empty_anonymous_function', { line: 6, character: 32 }, 'generation'], ['non_empty_anonymous_function', { line: 10, character: 0 }, undefined], ['empty_method_definition', { line: 19, character: 25 }, 'generation'], ['non_empty_method_definition', { line: 23, character: 0 }, undefined], ], ], [ 'java', '.java', // ../../fixtures/intent/empty_function/java.java [ ['empty_function_declaration', { line: 0, character: 26 }, 'generation'], ['non_empty_function_declaration', { line: 3, character: 4 }, undefined], ['empty_anonymous_function', { line: 7, character: 0 }, 'generation'], ['non_empty_anonymous_function', { line: 10, character: 0 }, undefined], ['empty_class_declaration', { line: 15, character: 18 }, 'generation'], ['non_empty_class_declaration', { line: 19, character: 0 }, undefined], ['empty_class_constructor', { line: 18, character: 13 }, 'generation'], ['empty_method_definition', { line: 20, character: 18 }, 'generation'], ['non_empty_class_constructor', { line: 26, character: 18 }, undefined], ['non_empty_method_definition', { line: 30, character: 18 }, undefined], ], ], [ 'rust', '.rs', // ../../fixtures/intent/empty_function/rust.vue [ ['empty_function_declaration', { line: 0, character: 23 }, 'generation'], ['non_empty_function_declaration', { line: 3, character: 4 }, undefined], ['empty_implementation', { line: 8, character: 13 }, 'generation'], ['non_empty_implementation', { line: 11, character: 0 }, undefined], ['empty_class_constructor', { line: 13, character: 0 }, 'generation'], ['non_empty_class_constructor', { line: 23, character: 0 }, undefined], ['empty_method_definition', { line: 17, character: 0 }, 'generation'], ['non_empty_method_definition', { line: 26, character: 0 }, undefined], ['empty_closure_expression', { line: 32, character: 0 }, 'generation'], ['non_empty_closure_expression', { line: 36, character: 0 }, undefined], ['empty_macro', { line: 42, character: 11 }, 'generation'], ['non_empty_macro', { line: 45, character: 11 }, undefined], ['empty_macro', { line: 55, character: 0 }, 'generation'], ['non_empty_macro', { line: 62, character: 20 }, undefined], ], ], [ 'kotlin', '.kt', // ../../fixtures/intent/empty_function/kotlin.kt [ ['empty_function_declaration', { line: 0, character: 25 }, 'generation'], ['non_empty_function_declaration', { line: 4, character: 0 }, undefined], ['empty_anonymous_function', { line: 6, character: 32 }, 'generation'], ['non_empty_anonymous_function', { line: 9, character: 4 }, undefined], ['empty_class_declaration', { line: 12, character: 14 }, 'generation'], ['non_empty_class_declaration', { line: 15, character: 14 }, undefined], ['empty_method_definition', { line: 24, character: 0 }, 'generation'], ['non_empty_method_definition', { line: 28, character: 0 }, undefined], ], ], [ 'typescriptreact', '.tsx', // ../../fixtures/intent/empty_function/typescriptreact.tsx [ ['empty_function_declaration', { line: 0, character: 22 }, 'generation'], ['non_empty_function_declaration', { line: 3, character: 4 }, undefined], ['empty_function_expression', { line: 6, character: 32 }, 'generation'], ['non_empty_function_expression', { line: 10, character: 4 }, undefined], ['empty_arrow_function', { line: 12, character: 26 }, 'generation'], ['non_empty_arrow_function', { line: 15, character: 4 }, undefined], ['empty_class_constructor', { line: 19, character: 21 }, 'generation'], ['empty_method_definition', { line: 21, character: 11 }, 'generation'], ['non_empty_class_constructor', { line: 29, character: 7 }, undefined], ['non_empty_method_definition', { line: 33, character: 0 }, undefined], ['empty_class_declaration', { line: 36, character: 14 }, 'generation'], ['non_empty_arrow_function', { line: 40, character: 0 }, undefined], ['empty_arrow_function', { line: 41, character: 23 }, 'generation'], ['non_empty_arrow_function', { line: 44, character: 23 }, undefined], ['empty_generator', { line: 54, character: 31 }, 'generation'], ['non_empty_generator', { line: 57, character: 4 }, undefined], ], ], [ 'c', '.c', // ../../fixtures/intent/empty_function/c.c [ ['empty_function_declaration', { line: 0, character: 24 }, 'generation'], ['non_empty_function_declaration', { line: 3, character: 0 }, undefined], ], ], [ 'cpp', '.cpp', // ../../fixtures/intent/empty_function/cpp.cpp [ ['empty_function_declaration', { line: 0, character: 37 }, 'generation'], ['non_empty_function_declaration', { line: 3, character: 0 }, undefined], ['empty_function_expression', { line: 6, character: 43 }, 'generation'], ['non_empty_function_expression', { line: 10, character: 4 }, undefined], ['empty_class_constructor', { line: 15, character: 37 }, 'generation'], ['empty_method_definition', { line: 17, character: 18 }, 'generation'], ['non_empty_class_constructor', { line: 27, character: 7 }, undefined], ['non_empty_method_definition', { line: 31, character: 0 }, undefined], ['empty_class_declaration', { line: 35, character: 14 }, 'generation'], ], ], [ 'c_sharp', '.cs', // ../../fixtures/intent/empty_function/c_sharp.cs [ ['empty_function_expression', { line: 2, character: 48 }, 'generation'], ['empty_class_constructor', { line: 4, character: 31 }, 'generation'], ['empty_method_definition', { line: 6, character: 31 }, 'generation'], ['non_empty_class_constructor', { line: 15, character: 0 }, undefined], ['non_empty_method_definition', { line: 20, character: 0 }, undefined], ['empty_class_declaration', { line: 24, character: 22 }, 'generation'], ], ], [ 'bash', '.sh', // ../../fixtures/intent/empty_function/bash.sh [ ['empty_function_declaration', { line: 3, character: 48 }, 'generation'], ['non_empty_function_declaration', { line: 6, character: 31 }, undefined], ], ], [ 'scala', '.scala', // ../../fixtures/intent/empty_function/scala.scala [ ['empty_function_declaration', { line: 1, character: 4 }, 'generation'], ['non_empty_function_declaration', { line: 5, character: 4 }, undefined], ['empty_method_definition', { line: 28, character: 3 }, 'generation'], ['non_empty_method_definition', { line: 34, character: 3 }, undefined], ['empty_class_declaration', { line: 22, character: 4 }, 'generation'], ['non_empty_class_declaration', { line: 27, character: 0 }, undefined], ['empty_anonymous_function', { line: 13, character: 0 }, 'generation'], ['non_empty_anonymous_function', { line: 17, character: 0 }, undefined], ], ], [ 'ruby', '.rb', // ../../fixtures/intent/empty_function/ruby.rb [ ['empty_method_definition', { line: 0, character: 23 }, 'generation'], ['empty_method_definition', { line: 0, character: 6 }, undefined], ['non_empty_method_definition', { line: 3, character: 0 }, undefined], ['empty_anonymous_function', { line: 7, character: 27 }, 'generation'], ['non_empty_anonymous_function', { line: 9, character: 37 }, undefined], ['empty_anonymous_function', { line: 11, character: 25 }, 'generation'], ['empty_class_constructor', { line: 16, character: 22 }, 'generation'], ['non_empty_class_declaration', { line: 18, character: 0 }, undefined], ['empty_method_definition', { line: 20, character: 1 }, 'generation'], ['empty_class_declaration', { line: 33, character: 12 }, 'generation'], ], ], [ 'python', '.py', // ../../fixtures/intent/empty_function/python.py [ ['empty_function_declaration', { line: 1, character: 4 }, 'generation'], ['non_empty_function_declaration', { line: 5, character: 4 }, undefined], ['empty_class_constructor', { line: 10, character: 0 }, 'generation'], ['empty_method_definition', { line: 14, character: 0 }, 'generation'], ['non_empty_class_constructor', { line: 19, character: 0 }, undefined], ['non_empty_method_definition', { line: 23, character: 4 }, undefined], ['empty_class_declaration', { line: 27, character: 4 }, 'generation'], ['empty_function_declaration', { line: 31, character: 4 }, 'generation'], ['empty_class_constructor', { line: 36, character: 4 }, 'generation'], ['empty_method_definition', { line: 40, character: 4 }, 'generation'], ['empty_class_declaration', { line: 44, character: 4 }, 'generation'], ['empty_function_declaration', { line: 49, character: 4 }, 'generation'], ['empty_class_constructor', { line: 53, character: 4 }, 'generation'], ['empty_method_definition', { line: 56, character: 4 }, 'generation'], ['empty_class_declaration', { line: 59, character: 4 }, 'generation'], ], ], ]; describe.each(emptyFunctionTestCases)('%s', (language, fileExt, cases) => { it.each(cases)('should resolve %s intent correctly', async (_, position, expectedIntent) => { const fixturePath = getFixturePath('intent', `empty_function/${language}${fileExt}`); const { treeAndLanguage, prefix, suffix } = await getTreeAndTestFile({ fixturePath, position, languageId: language, }); const intent = await getIntent({ treeAndLanguage, position, prefix, suffix }); expect(intent.intent).toBe(expectedIntent); if (expectedIntent === 'generation') { expect(intent.generationType).toBe('empty_function'); } }); }); }); }); References:" You are a code assistant,Definition of 'NullLogger' in file packages/lib_logging/src/null_logger.ts in project gitlab-lsp,"Definition: export class NullLogger implements Logger { debug(e: Error): void; debug(message: string, e?: Error | undefined): void; debug(): void { // NOOP } info(e: Error): void; info(message: string, e?: Error | undefined): void; info(): void { // NOOP } warn(e: Error): void; warn(message: string, e?: Error | undefined): void; warn(): void { // NOOP } error(e: Error): void; error(message: string, e?: Error | undefined): void; error(): void { // NOOP } } References: - packages/lib_webview_transport_json_rpc/src/json_rpc_connection_transport.test.ts:21 - packages/lib_webview_client/src/bus/resolve_message_bus.ts:15 - packages/webview_duo_chat/src/plugin/port/log.ts:3" You are a code assistant,Definition of 'TelemetryTracker' in file src/common/tracking/tracking_types.ts in project gitlab-lsp,"Definition: export const TelemetryTracker = createInterfaceId('TelemetryTracker'); References: - src/common/connection.ts:20 - src/common/message_handler.ts:34 - src/common/suggestion/suggestion_service.ts:77 - src/common/message_handler.ts:73 - src/common/suggestion/suggestion_service.ts:121 - src/common/suggestion/streaming_handler.ts:43" You are a code assistant,Definition of 'main' in file src/node/main.ts in project gitlab-lsp,"Definition: async function main() { const useSourceMaps = process.argv.includes('--use-source-maps'); const printVersion = process.argv.includes('--version') || process.argv.includes('-v'); const version = getLanguageServerVersion(); if (printVersion) { // eslint-disable-next-line no-console console.error(`GitLab Language Server v${version}`); return; } if (useSourceMaps) installSourceMapSupport(); const container = new Container(); container.instantiate(DefaultConfigService, DefaultSupportedLanguagesService); const configService = container.get(ConfigService); const connection = createConnection(ProposedFeatures.all); container.addInstances(brandInstance(LsConnection, connection)); const documents: TextDocuments = new TextDocuments(TextDocument); container.addInstances(brandInstance(LsTextDocuments, documents)); log.setup(configService); // Send all console messages to stderr. Stdin/stdout may be in use // as the LSP communications channel. // // This has to happen after the `createConnection` because the `vscode-languageserver` server version 9 and higher // patches the console as well // https://github.com/microsoft/vscode-languageserver-node/blob/84285312d8d9f22ee0042e709db114e5415dbdde/server/src/node/main.ts#L270 // // FIXME: we should really use the remote logging with `window/logMessage` messages // That's what the authors of the languageserver-node want us to use // https://github.com/microsoft/vscode-languageserver-node/blob/4e057d5d6109eb3fcb075d0f99456f05910fda44/server/src/common/server.ts#L133 global.console = new Console({ stdout: process.stderr, stderr: process.stderr }); const lsFetch = new Fetch(); await lsFetch.initialize(); container.addInstances(brandInstance(LsFetch, lsFetch)); const documentService = new DefaultDocumentService(documents); container.addInstances(brandInstance(DocumentService, documentService)); container.instantiate( GitLabAPI, DefaultDocumentTransformerService, DefaultFeatureFlagService, DefaultTokenCheckNotifier, DefaultSecretRedactor, DefaultSecurityDiagnosticsPublisher, DefaultConnectionService, DefaultInitializeHandler, DefaultDidChangeWorkspaceFoldersHandler, DefaultCodeSuggestionsSupportedLanguageCheck, DefaultProjectDuoAccessCheck, DefaultAdvancedContextService, // Workspace Dependencies DesktopFileResolver, DesktopDirectoryWalker, DefaultDuoProjectAccessChecker, DefaultDuoProjectAccessCache, DefaultVirtualFileSystemService, DefaultRepositoryService, DefaultWorkspaceService, DefaultFeatureStateManager, // Ai Context Dependencies DefaultAiContextAggregator, DefaultAiFileContextProvider, DefaultAiContextFileRetriever, DefaultAiPolicyManager, DefaultDuoProjectPolicy, DefaultAiContextManager, ); const snowplowTracker = new SnowplowTracker( container.get(LsFetch), container.get(ConfigService), container.get(FeatureFlagService), container.get(GitLabApiClient), ); const instanceTracker = new InstanceTracker( container.get(GitLabApiClient), container.get(ConfigService), ); const telemetryTracker = new MultiTracker([snowplowTracker, instanceTracker]); container.addInstances(brandInstance(TelemetryTracker, telemetryTracker)); const treeSitterParser = new DesktopTreeSitterParser(); const workflowAPI = new DesktopWorkflowRunner( configService, lsFetch, container.get(GitLabApiClient), ); const workflowGraphqlAPI = new WorkflowGraphQLService(container.get(GitLabApiClient), log); const webviewLocationService = new WebviewLocationService(); const webviewTransports = new Set(); const webviewMetadataProvider = new WebviewMetadataProvider( webviewLocationService, webviewPlugins, ); log.info(`GitLab Language Server is starting (v${version})`); webviewTransports.add( new JsonRpcConnectionTransport({ connection, logger: log, }), ); const extensionMessageBusProvider = new ExtensionConnectionMessageBusProvider({ connection, logger: log, }); setup( telemetryTracker, connection, container.get(DocumentTransformerService), container.get(GitLabApiClient), container.get(FeatureFlagService), configService, { treeSitterParser, }, webviewMetadataProvider, workflowAPI, container.get(DuoProjectAccessChecker), container.get(DuoProjectAccessCache), container.get(VirtualFileSystemService), ); // Make the text document manager listen on the connection for open, change and close text document events documents.listen(connection); // Listen on the connection connection.listen(); webviewPlugins.add(workflowPluginFactory(workflowGraphqlAPI, workflowAPI, connection)); webviewPlugins.add( duoChatPluginFactory({ gitlabApiClient: container.get(GitLabApiClient), }), ); await setupHttp(Array.from(webviewPlugins), webviewLocationService, webviewTransports, log); setupWebviewRuntime({ extensionMessageBusProvider, plugins: Array.from(webviewPlugins), transports: Array.from(webviewTransports), logger: log, }); log.info('GitLab Language Server has started'); } main().catch((e) => log.error(`failed to start the language server`, e)); References: - src/browser/main.ts:147 - src/node/main.ts:238" You are a code assistant,Definition of 'success' in file src/common/circuit_breaker/circuit_breaker.ts in project gitlab-lsp,"Definition: success(): void; isOpen(): boolean; onOpen(listener: () => void): Disposable; onClose(listener: () => void): Disposable; } References:" You are a code assistant,Definition of 'VirtualFileSystemService' in file src/common/services/fs/virtual_file_service.ts in project gitlab-lsp,"Definition: export const VirtualFileSystemService = createInterfaceId( '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 { 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( 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/message_handler.ts:39 - src/common/connection.ts:35 - src/common/message_handler.ts:87" You are a code assistant,Definition of 'renderGFM' in file packages/webview_duo_chat/src/app/render_gfm.ts in project gitlab-lsp,"Definition: export function renderGFM(element: HTMLElement) { if (!element) { return; } const highlightEls = Array.from( element.querySelectorAll('.js-syntax-highlight'), ) as HTMLElement[]; syntaxHighlight(highlightEls); } References:" You are a code assistant,Definition of 'IgnoreManager' in file src/common/git/ignore_manager.ts in project gitlab-lsp,"Definition: export class IgnoreManager { #ignoreTrie: IgnoreTrie; repoUri: string; constructor(repoUri: string) { this.repoUri = repoUri; this.#ignoreTrie = new IgnoreTrie(); } async loadIgnoreFiles(files: string[]): Promise { 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 { 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 { 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: - src/common/git/repository_service.ts:268 - src/common/git/repository.ts:25 - src/common/git/repository.ts:36" You are a code assistant,Definition of 'TREE_SITTER_LANGUAGES' in file src/node/tree_sitter/languages.ts in project gitlab-lsp,"Definition: export const TREE_SITTER_LANGUAGES = [ { name: 'c', extensions: ['.c'], wasmPath: path.join(__dirname, '../../../vendor/grammars/tree-sitter-c.wasm'), nodeModulesPath: 'tree-sitter-c', }, { name: 'cpp', extensions: ['.cpp'], wasmPath: path.join(__dirname, '../../../vendor/grammars/tree-sitter-cpp.wasm'), nodeModulesPath: 'tree-sitter-cpp', }, { name: 'c_sharp', extensions: ['.cs'], wasmPath: path.join(__dirname, '../../../vendor/grammars/tree-sitter-c_sharp.wasm'), nodeModulesPath: 'tree-sitter-c-sharp', }, { name: 'css', extensions: ['.css'], wasmPath: path.join(__dirname, '../../../vendor/grammars/tree-sitter-css.wasm'), nodeModulesPath: 'tree-sitter-css', }, { name: 'go', extensions: ['.go'], wasmPath: path.join(__dirname, '../../../vendor/grammars/tree-sitter-go.wasm'), nodeModulesPath: 'tree-sitter-go', }, { name: 'java', extensions: ['.java'], wasmPath: path.join(__dirname, '../../../vendor/grammars/tree-sitter-java.wasm'), nodeModulesPath: 'tree-sitter-java', }, { name: 'javascript', extensions: ['.js'], wasmPath: path.join(__dirname, '../../../vendor/grammars/tree-sitter-javascript.wasm'), nodeModulesPath: 'tree-sitter-javascript', }, { name: 'python', extensions: ['.py'], wasmPath: path.join(__dirname, '../../../vendor/grammars/tree-sitter-python.wasm'), nodeModulesPath: 'tree-sitter-python', }, { name: 'ruby', extensions: ['.rb'], wasmPath: path.join(__dirname, '../../../vendor/grammars/tree-sitter-ruby.wasm'), nodeModulesPath: 'tree-sitter-ruby', }, { name: 'scala', extensions: ['.scala'], wasmPath: path.join(__dirname, '../../../vendor/grammars/tree-sitter-scala.wasm'), nodeModulesPath: 'tree-sitter-scala', }, { name: 'typescript', extensions: ['.ts'], wasmPath: path.join(__dirname, '../../../vendor/grammars/tree-sitter-typescript.wasm'), nodeModulesPath: 'tree-sitter-typescript/typescript', }, { name: 'tsx', extensions: ['.tsx', '.jsx'], wasmPath: path.join(__dirname, '../../../vendor/grammars/tree-sitter-tsx.wasm'), nodeModulesPath: 'tree-sitter-typescript/tsx', }, // FIXME: parsing the file throws an error, address separately, same as sql // { // name: 'hcl', // terraform, terragrunt // extensions: ['.tf', '.hcl'], // wasmPath: path.join(__dirname, '../../../vendor/grammars/tree-sitter-hcl.wasm'), // nodeModulesPath: 'tree-sitter-hcl', // }, { name: 'kotlin', extensions: ['.kt'], wasmPath: path.join(__dirname, '../../../vendor/grammars/tree-sitter-kotlin.wasm'), nodeModulesPath: 'tree-sitter-kotlin', }, { name: 'powershell', extensions: ['.ps1'], wasmPath: path.join(__dirname, '../../../vendor/grammars/tree-sitter-powershell.wasm'), nodeModulesPath: 'tree-sitter-powershell', }, { name: 'rust', extensions: ['.rs'], wasmPath: path.join(__dirname, '../../../vendor/grammars/tree-sitter-rust.wasm'), nodeModulesPath: 'tree-sitter-rust', }, // { FIXME: add back support for Vue // name: 'vue', // extensions: ['.vue'], // wasmPath: path.join(__dirname, '../../../vendor/grammars/tree-sitter-vue.wasm'), // }, { name: 'yaml', extensions: ['.yaml'], wasmPath: path.join(__dirname, '../../../vendor/grammars/tree-sitter-yaml.wasm'), nodeModulesPath: '@tree-sitter-grammars/tree-sitter-yaml', }, { name: 'html', extensions: ['.html'], wasmPath: path.join(__dirname, '../../../vendor/grammars/tree-sitter-html.wasm'), nodeModulesPath: 'tree-sitter-html', }, // FIXME: parsing the file throws an error, address separately, same as hcl // { // name: 'sql', // extensions: ['.sql'], // wasmPath: path.join(__dirname, '../../../vendor/grammars/tree-sitter-sql.wasm'), // nodeModulesPath: '@derekstride/tree-sitter-sql', // }, { name: 'bash', extensions: ['.sh', '.bash', '.bashrc', '.bash_profile'], wasmPath: path.join(__dirname, '../../../vendor/grammars/tree-sitter-bash.wasm'), nodeModulesPath: 'tree-sitter-bash', }, { name: 'json', extensions: ['.json'], wasmPath: path.join(__dirname, '../../../vendor/grammars/tree-sitter-json.wasm'), nodeModulesPath: 'tree-sitter-json', }, ] satisfies TreeSitterLanguageInfo[]; References:" You are a code assistant,Definition of 'on' in file packages/lib_webview_transport/src/types.ts in project gitlab-lsp,"Definition: on( type: K, callback: TransportMessageHandler, ): Disposable; } export interface TransportPublisher { publish(type: K, payload: MessagesToClient[K]): Promise; } export interface Transport extends TransportListener, TransportPublisher {} References:" You are a code assistant,Definition of 'createWebviewPlugin' in file src/node/webview/webview_fastify_middleware.ts in project gitlab-lsp,"Definition: export const createWebviewPlugin = (options: Options): FastifyPluginRegistration => ({ plugin: (fastify, { webviewIds }) => setupWebviewRoutes(fastify, { webviewIds, getWebviewResourcePath: buildWebviewPath, }), options, }); const buildWebviewPath = (webviewId: WebviewId) => path.join(WEBVIEW_BASE_PATH, webviewId); References: - src/node/setup_http.ts:28" You are a code assistant,Definition of 'RpcMethods' in file src/common/webview/extension/types.ts in project gitlab-lsp,"Definition: export type RpcMethods = { notification: string; request: string; }; export type Handlers = { notification: ExtensionMessageHandlerRegistry; request: ExtensionMessageHandlerRegistry; }; References: - src/common/webview/extension/extension_connection_message_bus.ts:21 - src/common/webview/extension/extension_connection_message_bus_provider.ts:28 - src/common/webview/extension/extension_connection_message_bus.ts:10" You are a code assistant,Definition of 'tryParseUrl' in file src/common/utils/try_parse_url.ts in project gitlab-lsp,"Definition: export const tryParseUrl = (url: string): URL | undefined => { try { return new URL(url); } catch (e) { return undefined; } }; References: - src/common/services/git/git_remote_parser.ts:31 - src/common/services/git/git_remote_parser.ts:73" You are a code assistant,Definition of 'GitlabChatSlashCommand' in file packages/webview_duo_chat/src/contract.ts in project gitlab-lsp,"Definition: export interface GitlabChatSlashCommand { name: string; description: string; shouldSubmit?: boolean; } export interface WebViewInitialStateInterface { slashCommands: GitlabChatSlashCommand[]; } export type Messages = CreatePluginMessageMap<{ pluginToWebview: { notifications: { newRecord: Record; updateRecord: Record; setLoadingState: boolean; cleanChat: undefined; }; }; webviewToPlugin: { notifications: { onReady: undefined; cleanChat: undefined; newPrompt: { record: { content: string; }; }; trackFeedback: { data?: { extendedTextFeedback: string | null; feedbackChoices: Array | null; }; }; }; }; pluginToExtension: { notifications: { showErrorMessage: { message: string; }; }; }; }>; References: - packages/webview_duo_chat/src/plugin/port/chat/gitlab_chat_slash_commands.ts:28 - packages/webview_duo_chat/src/plugin/port/chat/gitlab_chat_slash_commands.ts:7 - packages/webview_duo_chat/src/plugin/port/chat/gitlab_chat_slash_commands.ts:18 - packages/webview_duo_chat/src/plugin/port/chat/gitlab_chat_slash_commands.ts:23 - packages/webview_duo_chat/src/plugin/port/chat/gitlab_chat_slash_commands.ts:13" You are a code assistant,Definition of 'NotificationHandler' in file packages/lib_webview/src/setup/plugin/webview_instance_message_bus.ts in project gitlab-lsp,"Definition: type NotificationHandler = (payload: unknown) => void; type RequestHandler = (requestId: RequestId, payload: unknown) => void; type ResponseHandler = (message: ResponseMessage) => void; export class WebviewInstanceMessageBus implements WebviewMessageBus, Disposable { #address: WebviewAddress; #runtimeMessageBus: WebviewRuntimeMessageBus; #eventSubscriptions = new CompositeDisposable(); #notificationEvents = new SimpleRegistry(); #requestEvents = new SimpleRegistry(); #pendingResponseEvents = new SimpleRegistry(); #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 { 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); } 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 'SupportedLanguagesService' in file src/common/suggestion/supported_languages_service.ts in project gitlab-lsp,"Definition: export const SupportedLanguagesService = createInterfaceId( 'SupportedLanguagesService', ); @Injectable(SupportedLanguagesService, [ConfigService]) export class DefaultSupportedLanguagesService implements SupportedLanguagesService { #enabledLanguages: Set; #supportedLanguages: Set; #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 = 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: - src/common/feature_state/supported_language_check.ts:32 - src/common/advanced_context/advanced_context_service.ts:37 - src/common/advanced_context/advanced_context_service.ts:30 - src/common/feature_state/supported_language_check.ts:24" 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 { return input; } } class Processor2 extends PostProcessor { async processStream( _context: IDocContext, input: StreamingCompletionResponse, ): Promise { return { ...input, completion: `${input.completion} [2]` }; } async processCompletion( _context: IDocContext, input: SuggestionOption[], ): Promise { return input; } } pipeline.addProcessor(new Processor1()); pipeline.addProcessor(new Processor2()); const streamInput: StreamingCompletionResponse = { id: '1', completion: 'test', done: false }; const result = await pipeline.run({ documentContext: mockContext, input: streamInput, type: 'stream', }); expect(result).toEqual({ id: '1', completion: 'test [1] [2]', done: false }); }); test('should chain multiple processors correctly for completion input', async () => { class Processor1 extends PostProcessor { async processStream( _context: IDocContext, input: StreamingCompletionResponse, ): Promise { return input; } async processCompletion( _context: IDocContext, input: SuggestionOption[], ): Promise { return input.map((option) => ({ ...option, text: `${option.text} [1]` })); } } class Processor2 extends PostProcessor { async processStream( _context: IDocContext, input: StreamingCompletionResponse, ): Promise { return input; } async processCompletion( _context: IDocContext, input: SuggestionOption[], ): Promise { return input.map((option) => ({ ...option, text: `${option.text} [2]` })); } } pipeline.addProcessor(new Processor1()); pipeline.addProcessor(new Processor2()); const completionInput: SuggestionOption[] = [{ text: 'option1', uniqueTrackingId: '1' }]; const result = await pipeline.run({ documentContext: mockContext, input: completionInput, type: 'completion', }); expect(result).toEqual([{ text: 'option1 [1] [2]', uniqueTrackingId: '1' }]); }); test('should throw an error for unexpected type', async () => { class TestProcessor extends PostProcessor { async processStream( _context: IDocContext, input: StreamingCompletionResponse, ): Promise { return input; } async processCompletion( _context: IDocContext, input: SuggestionOption[], ): Promise { 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 'dispose' in file packages/lib_disposable/src/composite_disposable.ts in project gitlab-lsp,"Definition: dispose(): void { for (const disposable of this.#disposables) { disposable.dispose(); } this.#disposables.clear(); } } References:" You are a code assistant,Definition of 'AiCompletionResponseInput' in file packages/webview_duo_chat/src/plugin/port/api/graphql/ai_completion_response_channel.ts in project gitlab-lsp,"Definition: type AiCompletionResponseInput = { htmlResponse?: boolean; userId: string; aiAction?: string; clientSubscriptionId?: string; }; type AiCompletionResponseParams = { channel: 'GraphqlChannel'; query: string; variables: string; operationName: 'aiCompletionResponse'; }; const AI_MESSAGE_SUBSCRIPTION_QUERY = gql` subscription aiCompletionResponse( $userId: UserID $clientSubscriptionId: String $aiAction: AiAction $htmlResponse: Boolean = true ) { aiCompletionResponse( userId: $userId aiAction: $aiAction clientSubscriptionId: $clientSubscriptionId ) { id requestId content contentHtml @include(if: $htmlResponse) errors role timestamp type chunkId extras { sources } } } `; export type AiCompletionResponseMessageType = { requestId: string; role: string; content: string; contentHtml?: string; timestamp: string; errors: string[]; extras?: { sources: object[]; }; chunkId?: number; type?: string; }; type AiCompletionResponseResponseType = { result: { data: { aiCompletionResponse: AiCompletionResponseMessageType; }; }; more: boolean; }; interface AiCompletionResponseChannelEvents extends ChannelEvents { systemMessage: (msg: AiCompletionResponseMessageType) => void; newChunk: (msg: AiCompletionResponseMessageType) => void; fullMessage: (msg: AiCompletionResponseMessageType) => void; } export class AiCompletionResponseChannel extends Channel< AiCompletionResponseParams, AiCompletionResponseResponseType, AiCompletionResponseChannelEvents > { static identifier = 'GraphqlChannel'; constructor(params: AiCompletionResponseInput) { super({ channel: 'GraphqlChannel', operationName: 'aiCompletionResponse', query: AI_MESSAGE_SUBSCRIPTION_QUERY, variables: JSON.stringify(params), }); } receive(message: AiCompletionResponseResponseType) { if (!message.result.data.aiCompletionResponse) return; const data = message.result.data.aiCompletionResponse; if (data.role.toLowerCase() === 'system') { this.emit('systemMessage', data); } else if (data.chunkId) { this.emit('newChunk', data); } else { this.emit('fullMessage', data); } } } References: - packages/webview_duo_chat/src/plugin/port/api/graphql/ai_completion_response_channel.ts:83" You are a code assistant,Definition of 'WebviewInstanceId' in file packages/lib_webview_plugin/src/types.ts in project gitlab-lsp,"Definition: export type WebviewInstanceId = string & { readonly _type: 'WebviewInstanceId' }; export type WebviewAddress = { webviewId: WebviewId; webviewInstanceId: WebviewInstanceId; }; export type WebviewMessageBusManagerHandler = ( webviewInstanceId: WebviewInstanceId, messageBus: MessageBus, // eslint-disable-next-line @typescript-eslint/no-invalid-void-type ) => Disposable | void; export interface WebviewConnection { broadcast: ( type: TMethod, payload: T['outbound']['notifications'][TMethod], ) => void; onInstanceConnected: (handler: WebviewMessageBusManagerHandler) => void; } References: - packages/lib_webview/src/setup/transport/utils/event_filters.ts:10 - packages/lib_webview_plugin/src/types.ts:18 - packages/lib_webview/src/setup/transport/utils/event_filters.ts:4 - packages/lib_webview_plugin/src/types.ts:22 - packages/lib_webview_transport/src/types.ts:6 - packages/lib_webview_transport_socket_io/src/types.ts:5" You are a code assistant,Definition of 'messageBus' in file packages/webview_duo_workflow/src/app/message_bus.ts in project gitlab-lsp,"Definition: export const messageBus = resolveMessageBus<{ inbound: DuoWorkflowMessages['pluginToWebview']; outbound: DuoWorkflowMessages['webviewToPlugin']; }>({ webviewId: WEBVIEW_ID, }); References:" You are a code assistant,Definition of 'findMatchingRepositoryUri' in file src/common/git/repository_service.ts in project gitlab-lsp,"Definition: findMatchingRepositoryUri(fileUri: URI, workspaceFolderUri: WorkspaceFolder): URI | null { const trie = this.#workspaceRepositoryTries.get(workspaceFolderUri.uri); if (!trie) return null; let node = trie; let lastMatchingRepo: URI | null = null; const parts = fileUri.path.split('/').filter(Boolean); for (const part of parts) { if (node.repository) { lastMatchingRepo = node.repository; } if (!node.children.has(part)) break; node = node.children.get(part) as RepositoryTrie; } return node.repository || lastMatchingRepo; } getRepositoryFileForUri( fileUri: URI, repositoryUri: URI, workspaceFolder: WorkspaceFolder, ): RepositoryFile | null { const repository = this.#getRepositoriesForWorkspace(workspaceFolder.uri).get( repositoryUri.toString(), ); if (!repository) { return null; } return repository.getFile(fileUri.toString()) ?? null; } #updateRepositoriesForFolder( workspaceFolder: WorkspaceFolder, repositoryMap: RepositoryMap, repositoryTrie: RepositoryTrie, ) { this.#workspaces.set(workspaceFolder.uri, repositoryMap); this.#workspaceRepositoryTries.set(workspaceFolder.uri, repositoryTrie); } async handleWorkspaceFilesUpdate({ workspaceFolder, files }: WorkspaceFilesUpdate) { // clear existing repositories from workspace this.#emptyRepositoriesForWorkspace(workspaceFolder.uri); const repositories = this.#detectRepositories(files, workspaceFolder); const repositoryMap = new Map(repositories.map((repo) => [repo.uri.toString(), repo])); // Build and cache the repository trie for this workspace const trie = this.#buildRepositoryTrie(repositories); this.#updateRepositoriesForFolder(workspaceFolder, repositoryMap, trie); await Promise.all( repositories.map((repo) => repo.addFilesAndLoadGitIgnore( files.filter((file) => { const matchingRepo = this.findMatchingRepositoryUri(file, workspaceFolder); return matchingRepo && matchingRepo.toString() === repo.uri.toString(); }), ), ), ); } async handleWorkspaceFileUpdate({ fileUri, workspaceFolder, event }: WorkspaceFileUpdate) { const repoUri = this.findMatchingRepositoryUri(fileUri, workspaceFolder); if (!repoUri) { log.debug(`No matching repository found for file ${fileUri.toString()}`); return; } const repositoryMap = this.#getRepositoriesForWorkspace(workspaceFolder.uri); const repository = repositoryMap.get(repoUri.toString()); if (!repository) { log.debug(`Repository not found for URI ${repoUri.toString()}`); return; } if (repository.isFileIgnored(fileUri)) { log.debug(`File ${fileUri.toString()} is ignored`); return; } switch (event) { case 'add': repository.setFile(fileUri); log.debug(`File ${fileUri.toString()} added to repository ${repoUri.toString()}`); break; case 'change': repository.setFile(fileUri); log.debug(`File ${fileUri.toString()} updated in repository ${repoUri.toString()}`); break; case 'unlink': repository.removeFile(fileUri.toString()); log.debug(`File ${fileUri.toString()} removed from repository ${repoUri.toString()}`); break; default: log.warn(`Unknown file event ${event} for file ${fileUri.toString()}`); } } #getRepositoriesForWorkspace(workspaceFolderUri: WorkspaceFolderUri): RepositoryMap { return this.#workspaces.get(workspaceFolderUri) || new Map(); } #emptyRepositoriesForWorkspace(workspaceFolderUri: WorkspaceFolderUri): void { log.debug(`Emptying repositories for workspace ${workspaceFolderUri}`); const repos = this.#workspaces.get(workspaceFolderUri); if (!repos || repos.size === 0) return; // clear up ignore manager trie from memory repos.forEach((repo) => { repo.dispose(); log.debug(`Repository ${repo.uri} has been disposed`); }); repos.clear(); const trie = this.#workspaceRepositoryTries.get(workspaceFolderUri); if (trie) { trie.dispose(); this.#workspaceRepositoryTries.delete(workspaceFolderUri); } this.#workspaces.delete(workspaceFolderUri); log.debug(`Repositories for workspace ${workspaceFolderUri} have been emptied`); } #detectRepositories(files: URI[], workspaceFolder: WorkspaceFolder): Repository[] { const gitConfigFiles = files.filter((file) => file.toString().endsWith('.git/config')); return gitConfigFiles.map((file) => { const projectUri = fsPathToUri(file.path.replace('.git/config', '')); const ignoreManager = new IgnoreManager(projectUri.fsPath); log.info(`Detected repository at ${projectUri.path}`); return new Repository({ ignoreManager, uri: projectUri, configFileUri: file, workspaceFolder, }); }); } getFilesForWorkspace( workspaceFolderUri: WorkspaceFolderUri, options: { excludeGitFolder?: boolean; excludeIgnored?: boolean } = {}, ): RepositoryFile[] { const repositories = this.#getRepositoriesForWorkspace(workspaceFolderUri); const allFiles: RepositoryFile[] = []; repositories.forEach((repository) => { repository.getFiles().forEach((file) => { // apply the filters if (options.excludeGitFolder && this.#isInGitFolder(file.uri, repository.uri)) { return; } if (options.excludeIgnored && file.isIgnored) { return; } allFiles.push(file); }); }); return allFiles; } // Helper method to check if a file is in the .git folder #isInGitFolder(fileUri: URI, repositoryUri: URI): boolean { const relativePath = fileUri.path.slice(repositoryUri.path.length); return relativePath.split('/').some((part) => part === '.git'); } } References:" You are a code assistant,Definition of 'getUri' in file src/common/webview/webview_resource_location_service.test.ts in project gitlab-lsp,"Definition: 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:" You are a code assistant,Definition of 'brandInstance' in file packages/lib_di/src/index.ts in project gitlab-lsp,"Definition: export const brandInstance = ( id: InterfaceId, instance: T, ): BrandedInstance => { injectableMetadata.set(instance, { id, dependencies: [] }); return instance; }; /** * Container is responsible for initializing a dependency tree. * * It receives a list of classes decorated with the `@Injectable` decorator * and it constructs instances of these classes in an order that ensures class' dependencies * are initialized before the class itself. * * check https://gitlab.com/viktomas/needle for full documentation of this mini-framework */ export class Container { #instances = new Map(); /** * addInstances allows you to add pre-initialized objects to the container. * This is useful when you want to keep mandatory parameters in class' constructor (e.g. some runtime objects like server connection). * addInstances accepts a list of any objects that have been ""branded"" by the `brandInstance` method */ addInstances(...instances: BrandedInstance[]) { for (const instance of instances) { const metadata = injectableMetadata.get(instance); if (!metadata) { throw new Error( 'assertion error: addInstance invoked without branded object, make sure all arguments are branded with `brandInstance`', ); } if (this.#instances.has(metadata.id)) { throw new Error( `you are trying to add instance for interfaceId ${metadata.id}, but instance with this ID is already in the container.`, ); } this.#instances.set(metadata.id, instance); } } /** * instantiate accepts list of classes, validates that they can be managed by the container * and then initialized them in such order that dependencies of a class are initialized before the class */ instantiate(...classes: WithConstructor[]) { // ensure all classes have been decorated with @Injectable const undecorated = classes.filter((c) => !injectableMetadata.has(c)).map((c) => c.name); if (undecorated.length) { throw new Error(`Classes [${undecorated}] are not decorated with @Injectable.`); } const classesWithDeps: ClassWithDependencies[] = classes.map((cls) => { // we verified just above that all classes are present in the metadata map // eslint-disable-next-line @typescript-eslint/no-non-null-assertion const { id, dependencies } = injectableMetadata.get(cls)!; return { cls, id, dependencies }; }); const validators: Validator[] = [ interfaceUsedOnlyOnce, dependenciesArePresent, noCircularDependencies, ]; validators.forEach((v) => v(classesWithDeps, Array.from(this.#instances.keys()))); const classesById = new Map(); // Index classes by their interface id classesWithDeps.forEach((cwd) => { classesById.set(cwd.id, cwd); }); // Create instances in topological order for (const cwd of sortDependencies(classesById)) { const args = cwd.dependencies.map((dependencyId) => this.#instances.get(dependencyId)); // eslint-disable-next-line new-cap const instance = new cwd.cls(...args); this.#instances.set(cwd.id, instance); } } get(id: InterfaceId): T { const instance = this.#instances.get(id); if (!instance) { throw new Error(`Instance for interface '${sanitizeId(id)}' is not in the container.`); } return instance as T; } } References: - packages/lib_di/src/index.test.ts:66 - src/node/main.ts:96 - src/node/main.ts:118 - src/browser/main.ts:72 - src/node/main.ts:98 - src/node/main.ts:115 - src/browser/main.ts:70 - src/browser/main.ts:77 - src/browser/main.ts:68 - packages/lib_di/src/index.test.ts:123 - packages/lib_di/src/index.test.ts:67 - src/browser/main.ts:112 - packages/lib_di/src/index.test.ts:110 - src/node/main.ts:166 - packages/lib_di/src/index.test.ts:73" You are a code assistant,Definition of 'constructor' in file src/common/suggestion/supported_languages_service.ts in project gitlab-lsp,"Definition: 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 = 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 'Processor2' in file src/common/suggestion_client/post_processors/post_processor_pipeline.test.ts in project gitlab-lsp,"Definition: class Processor2 extends PostProcessor { async processStream( _context: IDocContext, input: StreamingCompletionResponse, ): Promise { return input; } async processCompletion( _context: IDocContext, input: SuggestionOption[], ): Promise { return input.map((option) => ({ ...option, text: `${option.text} [2]` })); } } pipeline.addProcessor(new Processor1()); pipeline.addProcessor(new Processor2()); const completionInput: SuggestionOption[] = [{ text: 'option1', uniqueTrackingId: '1' }]; const result = await pipeline.run({ documentContext: mockContext, input: completionInput, type: 'completion', }); expect(result).toEqual([{ text: 'option1 [1] [2]', uniqueTrackingId: '1' }]); }); test('should throw an error for unexpected type', async () => { class TestProcessor extends PostProcessor { async processStream( _context: IDocContext, input: StreamingCompletionResponse, ): Promise { return input; } async processCompletion( _context: IDocContext, input: SuggestionOption[], ): Promise { 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: - src/common/suggestion_client/post_processors/post_processor_pipeline.test.ts:163 - src/common/suggestion_client/post_processors/post_processor_pipeline.test.ts:117" You are a code assistant,Definition of 'dispose' in file src/common/webview/extension/extension_connection_message_bus_provider.ts in project gitlab-lsp,"Definition: dispose(): void { this.#disposables.dispose(); } #setupConnectionSubscriptions() { this.#disposables.add( this.#connection.onNotification( this.#rpcMethods.notification, handleNotificationMessage(this.#notificationHandlers, this.#logger), ), ); this.#disposables.add( this.#connection.onRequest( this.#rpcMethods.request, handleRequestMessage(this.#requestHandlers, this.#logger), ), ); } } References:" You are a code assistant,Definition of 'constructor' in file packages/webview_duo_chat/src/plugin/port/chat/gitlab_chat_record.ts in project gitlab-lsp,"Definition: constructor({ chunkId, type, role, content, contentHtml, state, requestId, errors, timestamp, extras, }: GitLabChatRecordAttributes) { this.chunkId = chunkId; this.role = role; this.content = content; this.contentHtml = contentHtml; this.type = type ?? this.#detectType(); this.state = state ?? 'ready'; this.requestId = requestId; this.errors = errors ?? []; this.id = uuidv4(); this.timestamp = timestamp ? Date.parse(timestamp) : Date.now(); this.extras = extras; } static buildWithContext(attributes: GitLabChatRecordAttributes): GitLabChatRecord { const record = new GitLabChatRecord(attributes); record.context = buildCurrentContext(); return record; } update(attributes: Partial) { const convertedAttributes = attributes as Partial; if (attributes.timestamp) { convertedAttributes.timestamp = Date.parse(attributes.timestamp); } Object.assign(this, convertedAttributes); } #detectType(): ChatRecordType { if (this.content === SPECIAL_MESSAGES.RESET) { return 'newConversation'; } return 'general'; } } References:" You are a code assistant,Definition of 'DefaultAdvancedContextService' in file src/common/advanced_context/advanced_context_service.ts in project gitlab-lsp,"Definition: export class DefaultAdvancedContextService implements AdvancedContextService { #configService: ConfigService; #documentTransformer: DocumentTransformerService; #supportedLanguagesService: SupportedLanguagesService; constructor( configService: ConfigService, connection: LsConnection, documentService: DocumentService, documentTransformer: DocumentTransformerService, supportedLanguagesService: SupportedLanguagesService, ) { this.#configService = configService; this.#documentTransformer = documentTransformer; this.#supportedLanguagesService = supportedLanguagesService; const subscription = documentService.onDocumentChange(async ({ document }, handlerType) => { await this.#updateAdvancedContext(document, handlerType); }); connection.onShutdown(() => subscription.dispose()); } /** * Currently updates the LRU cache with the most recently accessed files in the workspace. * We only update the advanced context for supported languages. We also ensure to run * documents through the `DocumentTransformer` to ensure the secret redaction is applied. */ async #updateAdvancedContext( document: TextDocument, handlerType: TextDocumentChangeListenerType, ) { const lruCache = LruCache.getInstance(LRU_CACHE_BYTE_SIZE_LIMIT); // eslint-disable-next-line default-case switch (handlerType) { case TextDocumentChangeListenerType.onDidClose: { // We don't check if the language is supported for `onDidClose` because we want // always attempt to delete the file from the cache. const fileDeleted = lruCache.deleteFile(document.uri); if (fileDeleted) { log.debug(`Advanced Context: File ${document.uri} was deleted from the LRU cache`); } else { log.debug(`Advanced Context: File ${document.uri} was not found in the LRU cache`); } break; } case TextDocumentChangeListenerType.onDidChangeContent: case TextDocumentChangeListenerType.onDidSave: case TextDocumentChangeListenerType.onDidOpen: case TextDocumentChangeListenerType.onDidSetActive: { const languageEnabled = this.#supportedLanguagesService.isLanguageEnabled( document.languageId, ); if (!languageEnabled) { return; } const context = this.#documentTransformer.getContext( document.uri, { line: 0, character: 0 }, this.#configService.get().client.workspaceFolders ?? [], undefined, ); if (!context) { log.debug(`Advanced Context: document context for ${document.uri} was not found`); return; } lruCache.updateFile(context); log.debug(`Advanced Context: uri ${document.uri} was updated in the MRU cache`); break; } } } } References: - src/common/advanced_context/advanced_context_service.test.ts:58" You are a code assistant,Definition of 'b' in file packages/lib_di/src/index.test.ts in project gitlab-lsp,"Definition: b(): string; } interface C { c(): string; } const A = createInterfaceId('A'); const B = createInterfaceId('B'); const C = createInterfaceId('C'); @Injectable(A, []) class AImpl implements A { a = () => 'a'; } @Injectable(B, [A]) class BImpl implements B { #a: A; constructor(a: A) { this.#a = a; } b = () => `B(${this.#a.a()})`; } @Injectable(C, [A, B]) class CImpl implements C { #a: A; #b: B; constructor(a: A, b: B) { this.#a = a; this.#b = b; } c = () => `C(${this.#b.b()}, ${this.#a.a()})`; } let container: Container; beforeEach(() => { container = new Container(); }); describe('addInstances', () => { const O = createInterfaceId('object'); it('fails if the instance is not branded', () => { expect(() => container.addInstances({ say: 'hello' } as BrandedInstance)).toThrow( /invoked without branded object/, ); }); it('fails if the instance is already present', () => { const a = brandInstance(O, { a: 'a' }); const b = brandInstance(O, { b: 'b' }); expect(() => container.addInstances(a, b)).toThrow(/this ID is already in the container/); }); it('adds instance', () => { const instance = { a: 'a' }; const a = brandInstance(O, instance); container.addInstances(a); expect(container.get(O)).toBe(instance); }); }); describe('instantiate', () => { it('can instantiate three classes A,B,C', () => { container.instantiate(AImpl, BImpl, CImpl); const cInstance = container.get(C); expect(cInstance.c()).toBe('C(B(a), a)'); }); it('instantiates dependencies in multiple instantiate calls', () => { container.instantiate(AImpl); // the order is important for this test // we want to make sure that the stack in circular dependency discovery is being cleared // to try why this order is necessary, remove the `inStack.delete()` from // the `if (!cwd && instanceIds.includes(id))` condition in prod code expect(() => container.instantiate(CImpl, BImpl)).not.toThrow(); }); it('detects duplicate ids', () => { @Injectable(A, []) 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: - src/tests/fixtures/intent/ruby_comments.rb:15" You are a code assistant,Definition of 'MessageValidator' in file packages/lib_webview_transport/src/utils/message_validators.ts in project gitlab-lsp,"Definition: export type MessageValidator = (message: unknown) => message is T; export const isWebviewAddress: MessageValidator = ( message: unknown, ): message is WebviewAddress => typeof message === 'object' && message !== null && 'webviewId' in message && 'webviewInstanceId' in message; export const isWebviewInstanceCreatedEventData: MessageValidator< WebviewInstanceCreatedEventData > = (message: unknown): message is WebviewInstanceCreatedEventData => isWebviewAddress(message); export const isWebviewInstanceDestroyedEventData: MessageValidator< WebviewInstanceDestroyedEventData > = (message: unknown): message is WebviewInstanceDestroyedEventData => isWebviewAddress(message); export const isWebviewInstanceMessageEventData: MessageValidator< WebviewInstanceNotificationEventData > = (message: unknown): message is WebviewInstanceNotificationEventData => isWebviewAddress(message) && 'type' in message; References:" You are a code assistant,Definition of 'REQUEST_TIMEOUT_MILLISECONDS' in file packages/webview_duo_chat/src/plugin/port/constants.ts in project gitlab-lsp,"Definition: 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 'add' in file packages/lib_disposable/src/composite_disposable.ts in project gitlab-lsp,"Definition: add(...disposables: Disposable[]): void { for (const disposable of disposables) { this.#disposables.add(disposable); } } dispose(): void { for (const disposable of this.#disposables) { disposable.dispose(); } this.#disposables.clear(); } } References:" You are a code assistant,Definition of 'dispose' in file src/common/git/repository_trie.ts in project gitlab-lsp,"Definition: dispose(): void { this.children.forEach((child) => child.dispose()); this.children.clear(); this.repository = null; } } References:" You are a code assistant,Definition of 'success' in file src/common/circuit_breaker/fixed_time_circuit_breaker.ts in project gitlab-lsp,"Definition: 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:" You are a code assistant,Definition of 'constructor' in file packages/webview_duo_chat/src/plugin/port/chat/get_platform_manager_for_chat.ts in project gitlab-lsp,"Definition: constructor(platformManager: GitLabPlatformManager) { this.#platformManager = platformManager; } async getProjectGqlId(): Promise { const projectManager = await this.#platformManager.getForActiveProject(false); return projectManager?.project.gqlId; } /** * Obtains a GitLab Platform to send API requests to the GitLab API * for the Duo Chat feature. * * - It returns a GitLabPlatformForAccount for the first linked account. * - It returns undefined if there are no accounts linked */ async getGitLabPlatform(): Promise { const platforms = await this.#platformManager.getForAllAccounts(); if (!platforms.length) { return undefined; } let platform: GitLabPlatformForAccount | undefined; // Using a for await loop in this context because we want to stop // evaluating accounts as soon as we find one with code suggestions enabled for await (const result of platforms.map(getChatSupport)) { if (result.hasSupportForChat) { platform = result.platform; break; } } return platform; } async getGitLabEnvironment(): Promise { const platform = await this.getGitLabPlatform(); const instanceUrl = platform?.account.instanceUrl; switch (instanceUrl) { case GITLAB_COM_URL: return GitLabEnvironment.GITLAB_COM; case GITLAB_DEVELOPMENT_URL: return GitLabEnvironment.GITLAB_DEVELOPMENT; case GITLAB_STAGING_URL: return GitLabEnvironment.GITLAB_STAGING; case GITLAB_ORG_URL: return GitLabEnvironment.GITLAB_ORG; default: return GitLabEnvironment.GITLAB_SELF_MANAGED; } } } References:" You are a code assistant,Definition of 'AiContextItemWithContent' in file src/common/ai_context_management_2/ai_context_item.ts in project gitlab-lsp,"Definition: export type AiContextItemWithContent = AiContextItem & { content: string; }; References:" You are a code assistant,Definition of 'DeepPartial' in file packages/webview_duo_chat/src/plugin/port/test_utils/create_fake_partial.ts in project gitlab-lsp,"Definition: type DeepPartial = { [P in keyof T]?: _DeepPartial }; export const createFakePartial = (x: DeepPartial): T => x as T; References:" You are a code assistant,Definition of 'DocumentService' in file src/common/document_service.ts in project gitlab-lsp,"Definition: export interface DocumentService { onDocumentChange(listener: TextDocumentChangeListener): Disposable; notificationHandler(params: DidChangeDocumentInActiveEditorParams): void; } export const DocumentService = createInterfaceId('DocumentsWrapper'); const DOCUMENT_CHANGE_EVENT_NAME = 'documentChange'; export class DefaultDocumentService implements DocumentService, HandlesNotification { #subscriptions: Disposable[] = []; #emitter = new EventEmitter(); #documents: TextDocuments; constructor(documents: TextDocuments) { 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 = { document }; this.#emitter.emit( DOCUMENT_CHANGE_EVENT_NAME, event, TextDocumentChangeListenerType.onDidSetActive, ); }; #createMediatorListener = (type: TextDocumentChangeListenerType) => (event: TextDocumentChangeEvent) => { 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/connection_service.ts:65 - 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" You are a code assistant,Definition of 'DefaultFeatureFlagService' in file src/common/feature_flags.ts in project gitlab-lsp,"Definition: export class DefaultFeatureFlagService { #api: GitLabApiClient; #configService: ConfigService; #featureFlags: Map = 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 { 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 { 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: - src/common/feature_flags.test.ts:22" You are a code assistant,Definition of 'constructor' in file src/common/git/repository.ts in project gitlab-lsp,"Definition: constructor({ configFileUri, workspaceFolder, uri, ignoreManager, }: { workspaceFolder: WorkspaceFolder; uri: RepositoryUri; configFileUri: URI; ignoreManager: IgnoreManager; }) { this.workspaceFolder = workspaceFolder; this.uri = uri; this.configFileUri = configFileUri; this.#files = new Map(); this.#ignoreManager = ignoreManager; } async addFilesAndLoadGitIgnore(files: URI[]): Promise { log.info(`Adding ${files.length} files to repository ${this.uri.toString()}`); await this.#ignoreManager.loadIgnoreFiles(files.map((uri) => uri.fsPath)); for (const file of files) { if (!this.#ignoreManager.isIgnored(file.fsPath)) { this.#files.set(file.toString(), { uri: file, isIgnored: false, repositoryUri: this.uri, workspaceFolder: this.workspaceFolder, }); } else { this.#files.set(file.toString(), { uri: file, isIgnored: true, repositoryUri: this.uri, workspaceFolder: this.workspaceFolder, }); } } } isFileIgnored(filePath: URI): boolean { return this.#ignoreManager.isIgnored(filePath.fsPath); } setFile(fileUri: URI): void { if (!this.isFileIgnored(fileUri)) { this.#files.set(fileUri.toString(), { uri: fileUri, isIgnored: false, repositoryUri: this.uri, workspaceFolder: this.workspaceFolder, }); } else { this.#files.set(fileUri.toString(), { uri: fileUri, isIgnored: true, repositoryUri: this.uri, workspaceFolder: this.workspaceFolder, }); } } getFile(fileUri: string): RepositoryFile | undefined { return this.#files.get(fileUri); } removeFile(fileUri: string): void { this.#files.delete(fileUri); } getFiles(): Map { return this.#files; } dispose(): void { this.#ignoreManager.dispose(); this.#files.clear(); } } References:" You are a code assistant,Definition of 'WebviewInstanceInfo' in file packages/lib_webview/src/setup/plugin/webview_controller.ts in project gitlab-lsp,"Definition: type WebviewInstanceInfo = { messageBus: WebviewInstanceMessageBus; pluginCallbackDisposables: CompositeDisposable; }; export interface WebviewMessageBusFactory { (webviewAddress: WebviewAddress): WebviewInstanceMessageBus; } export class WebviewController implements WebviewConnection, Disposable { readonly webviewId: WebviewId; #messageBusFactory: WebviewMessageBusFactory; #handlers = new Set>(); #instanceInfos = new Map(); #compositeDisposable = new CompositeDisposable(); #logger: Logger; constructor( webviewId: WebviewId, runtimeMessageBus: WebviewRuntimeMessageBus, messageBusFactory: WebviewMessageBusFactory, logger: Logger, ) { this.#logger = withPrefix(logger, `[WebviewController:${webviewId}]`); this.webviewId = webviewId; this.#messageBusFactory = messageBusFactory; this.#subscribeToEvents(runtimeMessageBus); } broadcast( type: TMethod, payload: T['outbound']['notifications'][TMethod], ) { for (const info of this.#instanceInfos.values()) { info.messageBus.sendNotification(type.toString(), payload); } } onInstanceConnected(handler: WebviewMessageBusManagerHandler) { this.#handlers.add(handler); for (const [instanceId, info] of this.#instanceInfos) { const disposable = handler(instanceId, info.messageBus); if (isDisposable(disposable)) { info.pluginCallbackDisposables.add(disposable); } } } dispose(): void { this.#compositeDisposable.dispose(); this.#instanceInfos.forEach((info) => info.messageBus.dispose()); this.#instanceInfos.clear(); } #subscribeToEvents(runtimeMessageBus: WebviewRuntimeMessageBus) { const eventFilter = buildWebviewIdFilter(this.webviewId); this.#compositeDisposable.add( runtimeMessageBus.subscribe('webview:connect', this.#handleConnected.bind(this), eventFilter), runtimeMessageBus.subscribe( 'webview:disconnect', this.#handleDisconnected.bind(this), eventFilter, ), ); } #handleConnected(address: WebviewAddress) { this.#logger.debug(`Instance connected: ${address.webviewInstanceId}`); if (this.#instanceInfos.has(address.webviewInstanceId)) { // we are already connected with this webview instance return; } const messageBus = this.#messageBusFactory(address); const pluginCallbackDisposables = new CompositeDisposable(); this.#instanceInfos.set(address.webviewInstanceId, { messageBus, pluginCallbackDisposables, }); this.#handlers.forEach((handler) => { const disposable = handler(address.webviewInstanceId, messageBus); if (isDisposable(disposable)) { pluginCallbackDisposables.add(disposable); } }); } #handleDisconnected(address: WebviewAddress) { this.#logger.debug(`Instance disconnected: ${address.webviewInstanceId}`); const instanceInfo = this.#instanceInfos.get(address.webviewInstanceId); if (!instanceInfo) { // we aren't tracking this instance return; } instanceInfo.pluginCallbackDisposables.dispose(); instanceInfo.messageBus.dispose(); this.#instanceInfos.delete(address.webviewInstanceId); } } References: - packages/lib_webview_transport_socket_io/src/utils/connection_utils.ts:6 - packages/lib_webview_transport_socket_io/src/socket_io_webview_transport.ts:58" You are a code assistant,Definition of 'SuggestionResponseChoice' in file src/common/suggestion_client/suggestion_client.ts in project gitlab-lsp,"Definition: export interface SuggestionResponseChoice { text: string; } export interface SuggestionClient { getSuggestions(context: SuggestionContext): Promise; } export type SuggestionClientFn = SuggestionClient['getSuggestions']; export type SuggestionClientMiddleware = ( context: SuggestionContext, next: SuggestionClientFn, ) => ReturnType; References:" You are a code assistant,Definition of 'fetch' in file src/common/fetch.ts in project gitlab-lsp,"Definition: async fetch(input: RequestInfo | URL, init?: RequestInit): Promise { 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 { // Stub. Should delegate to the node or browser fetch implementations throw new Error('Not implemented'); yield ''; } async delete(input: RequestInfo | URL, init?: RequestInit): Promise { return this.fetch(input, this.updateRequestInit('DELETE', init)); } async get(input: RequestInfo | URL, init?: RequestInit): Promise { return this.fetch(input, this.updateRequestInit('GET', init)); } async post(input: RequestInfo | URL, init?: RequestInit): Promise { return this.fetch(input, this.updateRequestInit('POST', init)); } async put(input: RequestInfo | URL, init?: RequestInit): Promise { return this.fetch(input, this.updateRequestInit('PUT', init)); } async fetchBase(input: RequestInfo | URL, init?: RequestInit): Promise { // 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/fetch.ts:48 - src/common/security_diagnostics_publisher.ts:101 - src/node/fetch.ts:214 - src/common/suggestion_client/direct_connection_client.ts:104" You are a code assistant,Definition of 'ParserInitOptions' in file src/browser/tree_sitter/index.test.ts in project gitlab-lsp,"Definition: type ParserInitOptions = { locateFile: (scriptName: string) => string }; describe('BrowserTreeSitterParser', () => { let subject: BrowserTreeSitterParser; let configService: ConfigService; const baseAssetsUrl = 'http://localhost/assets/tree-sitter/'; describe('init', () => { beforeEach(async () => { configService = new DefaultConfigService(); configService.set('client.baseAssetsUrl', baseAssetsUrl); subject = new BrowserTreeSitterParser(configService); }); it('initializes languages list with correct wasmPath', async () => { await subject.init(); const actual = subject.getLanguages(); for (const [, treeSitterLangInfo] of actual) { expect(treeSitterLangInfo.wasmPath).toContain(baseAssetsUrl); } }); it('initializes the Treesitter parser with a locateFile function', async () => { let options: ParserInitOptions | undefined; jest.mocked(Parser.init).mockImplementationOnce(async (_options?: object) => { options = _options as ParserInitOptions; }); await subject.init(); expect(options?.locateFile).toBeDefined(); expect(options?.locateFile('tree-sitter.wasm')).toBe(`${baseAssetsUrl}node/tree-sitter.wasm`); }); it.each` initCall | loadState ${() => jest.mocked(Parser.init).mockResolvedValueOnce()} | ${TreeSitterParserLoadState.READY} ${() => jest.mocked(Parser.init).mockRejectedValueOnce(new Error())} | ${TreeSitterParserLoadState.ERRORED} `('sets the correct parser load state', async ({ initCall, loadState }) => { initCall(); await subject.init(); expect(subject.getLoadState()).toBe(loadState); }); }); }); References:" You are a code assistant,Definition of 'constructor' in file src/common/circuit_breaker/exponential_backoff_circuit_breaker.ts in project gitlab-lsp,"Definition: constructor( name: string, { initialBackoffMs = DEFAULT_INITIAL_BACKOFF_MS, maxBackoffMs = DEFAULT_MAX_BACKOFF_MS, backoffMultiplier = DEFAULT_BACKOFF_MULTIPLIER, }: ExponentialBackoffCircuitBreakerOptions = {}, ) { this.#name = name; this.#initialBackoffMs = initialBackoffMs; this.#maxBackoffMs = maxBackoffMs; this.#backoffMultiplier = backoffMultiplier; } error() { this.#errorCount += 1; this.#open(); } megaError() { this.#errorCount += 3; this.#open(); } #open() { if (this.#state === CircuitBreakerState.OPEN) { return; } this.#state = CircuitBreakerState.OPEN; log.warn( `Excess errors detected, opening '${this.#name}' circuit breaker for ${this.#getBackoffTime() / 1000} second(s).`, ); this.#timeoutId = setTimeout(() => this.#close(), this.#getBackoffTime()); this.#eventEmitter.emit('open'); } #close() { if (this.#state === CircuitBreakerState.CLOSED) { return; } if (this.#timeoutId) { clearTimeout(this.#timeoutId); } this.#state = CircuitBreakerState.CLOSED; this.#eventEmitter.emit('close'); } isOpen() { return this.#state === CircuitBreakerState.OPEN; } 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) }; } #getBackoffTime() { return Math.min( this.#initialBackoffMs * this.#backoffMultiplier ** (this.#errorCount - 1), this.#maxBackoffMs, ); } } References:" You are a code assistant,Definition of 'RepositoryService' in file src/common/git/repository_service.ts in project gitlab-lsp,"Definition: export const RepositoryService = createInterfaceId('RepositoryService'); @Injectable(RepositoryService, [VirtualFileSystemService]) export class DefaultRepositoryService { #virtualFileSystemService: DefaultVirtualFileSystemService; constructor(virtualFileSystemService: DefaultVirtualFileSystemService) { this.#virtualFileSystemService = virtualFileSystemService; this.#setupEventListeners(); } #setupEventListeners() { return this.#virtualFileSystemService.onFileSystemEvent(async (eventType, data) => { switch (eventType) { case VirtualFileSystemEvents.WorkspaceFilesUpdate: await this.#handleWorkspaceFilesUpdate(data as WorkspaceFilesUpdate); break; case VirtualFileSystemEvents.WorkspaceFileUpdate: await this.#handleWorkspaceFileUpdate(data as WorkspaceFileUpdate); break; default: break; } }); } async #handleWorkspaceFilesUpdate(update: WorkspaceFilesUpdate) { log.info(`Workspace files update: ${update.files.length}`); const perf1 = performance.now(); await this.handleWorkspaceFilesUpdate({ ...update, }); const perf2 = performance.now(); log.info(`Workspace files initialization took ${perf2 - perf1}ms`); const perf3 = performance.now(); const files = this.getFilesForWorkspace(update.workspaceFolder.uri, { excludeGitFolder: true, excludeIgnored: true, }); const perf4 = performance.now(); log.info(`Fetched workspace files in ${perf4 - perf3}ms`); log.info(`Workspace git files: ${files.length}`); // const treeFile = await readFile( // '/Users/angelo.rivera/gitlab/gitlab-development-kit/gitlab/tree.txt', // 'utf-8', // ); // const treeFiles = treeFile.split('\n').filter(Boolean); // // get the set difference between the files in the tree and the non-ignored files // // we need the difference between the two sets to know which files are not in the tree // const diff = new Set( // files.map((file) => // relative('/Users/angelo.rivera/gitlab/gitlab-development-kit/gitlab', file.uri.fsPath), // ), // ); // for (const file of treeFiles) { // diff.delete(file); // } // log.info(`Files not in the tree.txt: ${JSON.stringify(Array.from(diff))}`); } async #handleWorkspaceFileUpdate(update: WorkspaceFileUpdate) { log.info(`Workspace file update: ${JSON.stringify(update)}`); await this.handleWorkspaceFileUpdate({ ...update, }); const perf1 = performance.now(); const files = this.getFilesForWorkspace(update.workspaceFolder.uri, { excludeGitFolder: true, excludeIgnored: true, }); const perf2 = performance.now(); log.info(`Fetched workspace files in ${perf2 - perf1}ms`); log.info(`Workspace git files: ${files.length}`); } /** * unique map of workspace folders that point to a map of repositories * We store separate repository maps for each workspace because * the events from the VFS service are at the workspace level. * If we combined them, we may get race conditions */ #workspaces: Map = new Map(); #workspaceRepositoryTries: Map = new Map(); #buildRepositoryTrie(repositories: Repository[]): RepositoryTrie { const root = new RepositoryTrie(); for (const repo of repositories) { let node = root; const parts = repo.uri.path.split('/').filter(Boolean); for (const part of parts) { if (!node.children.has(part)) { node.children.set(part, new RepositoryTrie()); } node = node.children.get(part) as RepositoryTrie; } node.repository = repo.uri; } return root; } findMatchingRepositoryUri(fileUri: URI, workspaceFolderUri: WorkspaceFolder): URI | null { const trie = this.#workspaceRepositoryTries.get(workspaceFolderUri.uri); if (!trie) return null; let node = trie; let lastMatchingRepo: URI | null = null; const parts = fileUri.path.split('/').filter(Boolean); for (const part of parts) { if (node.repository) { lastMatchingRepo = node.repository; } if (!node.children.has(part)) break; node = node.children.get(part) as RepositoryTrie; } return node.repository || lastMatchingRepo; } getRepositoryFileForUri( fileUri: URI, repositoryUri: URI, workspaceFolder: WorkspaceFolder, ): RepositoryFile | null { const repository = this.#getRepositoriesForWorkspace(workspaceFolder.uri).get( repositoryUri.toString(), ); if (!repository) { return null; } return repository.getFile(fileUri.toString()) ?? null; } #updateRepositoriesForFolder( workspaceFolder: WorkspaceFolder, repositoryMap: RepositoryMap, repositoryTrie: RepositoryTrie, ) { this.#workspaces.set(workspaceFolder.uri, repositoryMap); this.#workspaceRepositoryTries.set(workspaceFolder.uri, repositoryTrie); } async handleWorkspaceFilesUpdate({ workspaceFolder, files }: WorkspaceFilesUpdate) { // clear existing repositories from workspace this.#emptyRepositoriesForWorkspace(workspaceFolder.uri); const repositories = this.#detectRepositories(files, workspaceFolder); const repositoryMap = new Map(repositories.map((repo) => [repo.uri.toString(), repo])); // Build and cache the repository trie for this workspace const trie = this.#buildRepositoryTrie(repositories); this.#updateRepositoriesForFolder(workspaceFolder, repositoryMap, trie); await Promise.all( repositories.map((repo) => repo.addFilesAndLoadGitIgnore( files.filter((file) => { const matchingRepo = this.findMatchingRepositoryUri(file, workspaceFolder); return matchingRepo && matchingRepo.toString() === repo.uri.toString(); }), ), ), ); } async handleWorkspaceFileUpdate({ fileUri, workspaceFolder, event }: WorkspaceFileUpdate) { const repoUri = this.findMatchingRepositoryUri(fileUri, workspaceFolder); if (!repoUri) { log.debug(`No matching repository found for file ${fileUri.toString()}`); return; } const repositoryMap = this.#getRepositoriesForWorkspace(workspaceFolder.uri); const repository = repositoryMap.get(repoUri.toString()); if (!repository) { log.debug(`Repository not found for URI ${repoUri.toString()}`); return; } if (repository.isFileIgnored(fileUri)) { log.debug(`File ${fileUri.toString()} is ignored`); return; } switch (event) { case 'add': repository.setFile(fileUri); log.debug(`File ${fileUri.toString()} added to repository ${repoUri.toString()}`); break; case 'change': repository.setFile(fileUri); log.debug(`File ${fileUri.toString()} updated in repository ${repoUri.toString()}`); break; case 'unlink': repository.removeFile(fileUri.toString()); log.debug(`File ${fileUri.toString()} removed from repository ${repoUri.toString()}`); break; default: log.warn(`Unknown file event ${event} for file ${fileUri.toString()}`); } } #getRepositoriesForWorkspace(workspaceFolderUri: WorkspaceFolderUri): RepositoryMap { return this.#workspaces.get(workspaceFolderUri) || new Map(); } #emptyRepositoriesForWorkspace(workspaceFolderUri: WorkspaceFolderUri): void { log.debug(`Emptying repositories for workspace ${workspaceFolderUri}`); const repos = this.#workspaces.get(workspaceFolderUri); if (!repos || repos.size === 0) return; // clear up ignore manager trie from memory repos.forEach((repo) => { repo.dispose(); log.debug(`Repository ${repo.uri} has been disposed`); }); repos.clear(); const trie = this.#workspaceRepositoryTries.get(workspaceFolderUri); if (trie) { trie.dispose(); this.#workspaceRepositoryTries.delete(workspaceFolderUri); } this.#workspaces.delete(workspaceFolderUri); log.debug(`Repositories for workspace ${workspaceFolderUri} have been emptied`); } #detectRepositories(files: URI[], workspaceFolder: WorkspaceFolder): Repository[] { const gitConfigFiles = files.filter((file) => file.toString().endsWith('.git/config')); return gitConfigFiles.map((file) => { const projectUri = fsPathToUri(file.path.replace('.git/config', '')); const ignoreManager = new IgnoreManager(projectUri.fsPath); log.info(`Detected repository at ${projectUri.path}`); return new Repository({ ignoreManager, uri: projectUri, configFileUri: file, workspaceFolder, }); }); } getFilesForWorkspace( workspaceFolderUri: WorkspaceFolderUri, options: { excludeGitFolder?: boolean; excludeIgnored?: boolean } = {}, ): RepositoryFile[] { const repositories = this.#getRepositoriesForWorkspace(workspaceFolderUri); const allFiles: RepositoryFile[] = []; repositories.forEach((repository) => { repository.getFiles().forEach((file) => { // apply the filters if (options.excludeGitFolder && this.#isInGitFolder(file.uri, repository.uri)) { return; } if (options.excludeIgnored && file.isIgnored) { return; } allFiles.push(file); }); }); return allFiles; } // Helper method to check if a file is in the .git folder #isInGitFolder(fileUri: URI, repositoryUri: URI): boolean { const relativePath = fileUri.path.slice(repositoryUri.path.length); return relativePath.split('/').some((part) => part === '.git'); } } References:" You are a code assistant,Definition of 'FileSystemEventMap' in file src/common/services/fs/virtual_file_service.ts in project gitlab-lsp,"Definition: export interface FileSystemEventMap { [VirtualFileSystemEvents.WorkspaceFileUpdate]: WorkspaceFileUpdate; [VirtualFileSystemEvents.WorkspaceFilesUpdate]: WorkspaceFilesUpdate; } export interface FileSystemEventListener { (eventType: T, data: FileSystemEventMap[T]): void; } export type VirtualFileSystemService = typeof DefaultVirtualFileSystemService.prototype; export const VirtualFileSystemService = createInterfaceId( '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 { 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( 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 'error' in file packages/lib_logging/src/types.ts in project gitlab-lsp,"Definition: error(message: string, e?: Error): void; } References: - scripts/commit-lint/lint.js:72 - scripts/commit-lint/lint.js:77 - scripts/commit-lint/lint.js:85 - scripts/commit-lint/lint.js:94" You are a code assistant,Definition of 'retrieve' in file src/common/ai_context_management_2/retrievers/ai_context_retriever.ts in project gitlab-lsp,"Definition: retrieve(item: AiContextItem): Promise; } References:" You are a code assistant,Definition of 'API_RECOVERY_NOTIFICATION' in file src/common/circuit_breaker/circuit_breaker.ts in project gitlab-lsp,"Definition: export const API_RECOVERY_NOTIFICATION = '$/gitlab/api/recovered'; export enum CircuitBreakerState { OPEN = 'Open', CLOSED = 'Closed', } export interface CircuitBreaker { error(): void; success(): void; isOpen(): boolean; onOpen(listener: () => void): Disposable; onClose(listener: () => void): Disposable; } References:" You are a code assistant,Definition of 'GitlabRealm' in file src/common/tracking/tracking_types.ts in project gitlab-lsp,"Definition: export enum GitlabRealm { saas = 'saas', selfManaged = 'self-managed', } export enum SuggestionSource { cache = 'cache', network = 'network', } export interface IIDEInfo { name: string; version: string; vendor: string; } 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, ): void; updateCodeSuggestionsContext( uniqueTrackingId: string, contextUpdate: Partial, ): void; rejectOpenedSuggestions(): void; updateSuggestionState(uniqueTrackingId: string, newState: TRACKING_EVENTS): void; } export const TelemetryTracker = createInterfaceId('TelemetryTracker'); References: - src/common/tracking/snowplow_tracker.ts:154 - src/common/tracking/snowplow_tracker.ts:56" You are a code assistant,Definition of 'constructor' in file src/common/ai_context_management_2/providers/ai_file_context_provider.ts in project gitlab-lsp,"Definition: constructor(repositoryService: DefaultRepositoryService) { this.#repositoryService = repositoryService; } async getProviderItems( query: string, workspaceFolders: WorkspaceFolder[], ): Promise { const items = query.trim() === '' ? await this.#getOpenTabsItems() : await this.#getSearchedItems(query, workspaceFolders); log.info(`Found ${items.length} results for ${query}`); return items; } async #getOpenTabsItems(): Promise { const resolutions: ContextResolution[] = []; for await (const resolution of OpenTabsResolver.getInstance().buildContext({ includeCurrentFile: true, })) { resolutions.push(resolution); } return resolutions.map((resolution) => this.#providerItemForOpenTab(resolution)); } async #getSearchedItems( query: string, workspaceFolders: WorkspaceFolder[], ): Promise { const allFiles: RepositoryFile[] = []; for (const folder of workspaceFolders) { const files = this.#repositoryService.getFilesForWorkspace(folder.uri, { excludeGitFolder: true, excludeIgnored: true, }); allFiles.push(...files); } const fileNames = allFiles.map((file) => file.uri.fsPath); const allFilesMap = new Map(allFiles.map((file) => [file.uri.fsPath, file])); const results = filter(fileNames, query, { maxResults: 100 }); const resultFiles: RepositoryFile[] = []; for (const result of results) { if (allFilesMap.has(result)) { resultFiles.push(allFilesMap.get(result) as RepositoryFile); } } return resultFiles.map((file) => this.#providerItemForSearchResult(file)); } #openTabResolutionToRepositoryFile(resolution: ContextResolution): [URI, RepositoryFile | null] { const fileUri = parseURIString(resolution.uri); const repo = this.#repositoryService.findMatchingRepositoryUri( fileUri, resolution.workspaceFolder, ); if (!repo) { log.warn(`Could not find repository for ${resolution.uri}`); return [fileUri, null]; } const repositoryFile = this.#repositoryService.getRepositoryFileForUri( fileUri, repo, resolution.workspaceFolder, ); if (!repositoryFile) { log.warn(`Could not find repository file for ${resolution.uri}`); return [fileUri, null]; } return [fileUri, repositoryFile]; } #providerItemForOpenTab(resolution: ContextResolution): AiContextProviderItem { const [fileUri, repositoryFile] = this.#openTabResolutionToRepositoryFile(resolution); return { fileUri, workspaceFolder: resolution.workspaceFolder, providerType: 'file', subType: 'open_tab', repositoryFile, }; } #providerItemForSearchResult(repositoryFile: RepositoryFile): AiContextProviderItem { return { fileUri: repositoryFile.uri, workspaceFolder: repositoryFile.workspaceFolder, providerType: 'file', subType: 'local_file_search', repositoryFile, }; } } References:" You are a code assistant,Definition of 'GetRequest' in file src/common/api_types.ts in project gitlab-lsp,"Definition: interface GetRequest<_TReturnType> extends BaseRestRequest<_TReturnType> { method: 'GET'; searchParams?: Record; supportedSinceInstanceVersion?: SupportedSinceInstanceVersion; } export type ApiRequest<_TReturnType> = | GetRequest<_TReturnType> | PostRequest<_TReturnType> | GraphQLRequest<_TReturnType>; export type AdditionalContext = { /** * The type of the context element. Options: `file` or `snippet`. */ type: 'file' | 'snippet'; /** * The name of the context element. A name of the file or a code snippet. */ name: string; /** * The content of the context element. The body of the file or a function. */ content: string; /** * Where the context was derived from */ resolution_strategy: ContextResolution['strategy']; }; // FIXME: Rename to SuggestionOptionText and then rename SuggestionOptionOrStream to SuggestionOption // this refactor can't be done now (2024-05-28) because all the conflicts it would cause with WIP export interface SuggestionOption { index?: number; text: string; uniqueTrackingId: string; lang?: string; } export interface TelemetryRequest { event: string; additional_properties: { unique_tracking_id: string; language?: string; suggestion_size?: number; timestamp: string; }; } References:" You are a code assistant,Definition of 'FetchHeaders' in file src/common/fetch.ts in project gitlab-lsp,"Definition: export type FetchHeaders = { [key: string]: string; }; export interface LsFetch { initialize(): Promise; destroy(): Promise; fetch(input: RequestInfo | URL, init?: RequestInit): Promise; fetchBase(input: RequestInfo | URL, init?: RequestInit): Promise; delete(input: RequestInfo | URL, init?: RequestInit): Promise; get(input: RequestInfo | URL, init?: RequestInit): Promise; post(input: RequestInfo | URL, init?: RequestInit): Promise; put(input: RequestInfo | URL, init?: RequestInit): Promise; updateAgentOptions(options: FetchAgentOptions): void; streamFetch(url: string, body: string, headers: FetchHeaders): AsyncGenerator; } export const LsFetch = createInterfaceId('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 {} async destroy(): Promise {} async fetch(input: RequestInfo | URL, init?: RequestInit): Promise { 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 { // Stub. Should delegate to the node or browser fetch implementations throw new Error('Not implemented'); yield ''; } async delete(input: RequestInfo | URL, init?: RequestInit): Promise { return this.fetch(input, this.updateRequestInit('DELETE', init)); } async get(input: RequestInfo | URL, init?: RequestInit): Promise { return this.fetch(input, this.updateRequestInit('GET', init)); } async post(input: RequestInfo | URL, init?: RequestInit): Promise { return this.fetch(input, this.updateRequestInit('POST', init)); } async put(input: RequestInfo | URL, init?: RequestInit): Promise { return this.fetch(input, this.updateRequestInit('PUT', init)); } async fetchBase(input: RequestInfo | URL, init?: RequestInit): Promise { // 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/browser/fetch.ts:16 - src/common/fetch.ts:25 - src/node/fetch.ts:152 - src/common/fetch.ts:55" You are a code assistant,Definition of 'DocumentTransformerService' in file src/common/document_transformer_service.ts in project gitlab-lsp,"Definition: export const DocumentTransformerService = createInterfaceId( 'DocumentTransformerService', ); @Injectable(DocumentTransformerService, [LsTextDocuments, SecretRedactor]) export class DefaultDocumentTransformerService implements DocumentTransformerService { #transformers: IDocTransformer[] = []; #documents: LsTextDocuments; 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: - src/common/advanced_context/advanced_context_service.ts:36 - src/common/suggestion/suggestion_service.ts:125 - src/common/connection.ts:22 - src/common/advanced_context/advanced_context_service.ts:28 - src/common/suggestion/suggestion_service.ts:81" You are a code assistant,Definition of 'init' in file src/common/core/handlers/token_check_notifier.ts in project gitlab-lsp,"Definition: init(callback: NotifyFn) { this.#notify = callback; } } References:" You are a code assistant,Definition of 'status' in file src/common/fetch_error.ts in project gitlab-lsp,"Definition: 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:" You are a code assistant,Definition of 'onRequest' in file packages/lib_webview_client/src/bus/provider/socket_io_message_bus.ts in project gitlab-lsp,"Definition: onRequest( type: T, handler: ( payload: TMessages['inbound']['requests'][T]['params'], ) => Promise>, ): Disposable { return this.#requestHandlers.register(type, handler); } dispose() { this.#socket.off(SOCKET_NOTIFICATION_CHANNEL, this.#handleNotificationMessage); this.#socket.off(SOCKET_REQUEST_CHANNEL, this.#handleRequestMessage); this.#socket.off(SOCKET_RESPONSE_CHANNEL, this.#handleResponseMessage); this.#notificationHandlers.dispose(); this.#requestHandlers.dispose(); this.#pendingRequests.dispose(); } #setupSocketEventHandlers = () => { this.#socket.on(SOCKET_NOTIFICATION_CHANNEL, this.#handleNotificationMessage); this.#socket.on(SOCKET_REQUEST_CHANNEL, this.#handleRequestMessage); this.#socket.on(SOCKET_RESPONSE_CHANNEL, this.#handleResponseMessage); }; #handleNotificationMessage = async (message: { type: keyof TMessages['inbound']['notifications'] & string; payload: unknown; }) => { await this.#notificationHandlers.handle(message.type, message.payload); }; #handleRequestMessage = async (message: { requestId: string; event: keyof TMessages['inbound']['requests'] & string; payload: unknown; }) => { const response = await this.#requestHandlers.handle(message.event, message.payload); this.#socket.emit(SOCKET_RESPONSE_CHANNEL, { requestId: message.requestId, payload: response, }); }; #handleResponseMessage = async (message: { requestId: string; payload: unknown }) => { await this.#pendingRequests.handle(message.requestId, message.payload); }; } References:" You are a code assistant,Definition of 'constructor' in file packages/lib_handler_registry/src/registry/hashed_registry.ts in project gitlab-lsp,"Definition: constructor(hashFunc: HashFunc) { this.#hashFunc = hashFunc; this.#basicRegistry = new SimpleRegistry(); } 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): Promise> { const hash = this.#hashFunc(key); return this.#basicRegistry.handle(hash, ...args); } dispose() { this.#basicRegistry.dispose(); } } References:" You are a code assistant,Definition of 'debug' in file src/common/log_types.ts in project gitlab-lsp,"Definition: debug(e: Error): void; debug(message: string, e?: Error): void; 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; } 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 'START_WORKFLOW_NOTIFICATION' in file src/common/connection.ts in project gitlab-lsp,"Definition: export const START_WORKFLOW_NOTIFICATION = '$/gitlab/startWorkflow'; export const GET_WEBVIEW_METADATA_REQUEST = '$/gitlab/webview-metadata'; export function setup( telemetryTracker: TelemetryTracker, connection: Connection, documentTransformerService: DocumentTransformerService, apiClient: GitLabApiClient, featureFlagService: FeatureFlagService, configService: ConfigService, { treeSitterParser, }: { treeSitterParser: TreeSitterParser; }, webviewMetadataProvider: WebviewMetadataProvider | undefined = undefined, workflowAPI: WorkflowAPI | undefined = undefined, duoProjectAccessChecker: DuoProjectAccessChecker, duoProjectAccessCache: DuoProjectAccessCache, virtualFileSystemService: VirtualFileSystemService, ) { const suggestionService = new DefaultSuggestionService({ telemetryTracker, connection, configService, api: apiClient, featureFlagService, treeSitterParser, documentTransformerService, duoProjectAccessChecker, }); const messageHandler = new MessageHandler({ telemetryTracker, connection, configService, featureFlagService, duoProjectAccessCache, virtualFileSystemService, workflowAPI, }); connection.onCompletion(suggestionService.completionHandler); // TODO: does Visual Studio or Neovim need this? VS Code doesn't connection.onCompletionResolve((item: CompletionItem) => item); connection.onRequest(InlineCompletionRequest.type, suggestionService.inlineCompletionHandler); connection.onDidChangeConfiguration(messageHandler.didChangeConfigurationHandler); connection.onNotification(TELEMETRY_NOTIFICATION, messageHandler.telemetryNotificationHandler); connection.onNotification( START_WORKFLOW_NOTIFICATION, messageHandler.startWorkflowNotificationHandler, ); connection.onRequest(GET_WEBVIEW_METADATA_REQUEST, () => { return webviewMetadataProvider?.getMetadata() ?? []; }); connection.onShutdown(messageHandler.onShutdownHandler); } References:" You are a code assistant,Definition of 'hasbinAllSync' in file src/tests/int/hasbin.ts in project gitlab-lsp,"Definition: export function hasbinAllSync(bins: string[]) { return bins.every(hasbin.sync); } export function hasbinSome(bins: string[], done: (result: boolean) => void) { async.some(bins, hasbin.async, done); } export function hasbinSomeSync(bins: string[]) { return bins.some(hasbin.sync); } export function hasbinFirst(bins: string[], done: (result: boolean) => void) { async.detect(bins, hasbin.async, function (result) { done(result || false); }); } export function hasbinFirstSync(bins: string[]) { const matched = bins.filter(hasbin.sync); return matched.length ? matched[0] : false; } export function getPaths(bin: string) { const envPath = process.env.PATH || ''; const envExt = process.env.PATHEXT || ''; return envPath .replace(/[""]+/g, '') .split(delimiter) .map(function (chunk) { return envExt.split(delimiter).map(function (ext) { return join(chunk, bin + ext); }); }) .reduce(function (a, b) { return a.concat(b); }); } 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 'Counter' in file packages/lib_di/src/index.test.ts in project gitlab-lsp,"Definition: 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 'TextDocumentChangeListenerType' in file src/common/text_document_change_listener_type.ts in project gitlab-lsp,"Definition: export enum TextDocumentChangeListenerType { onDidOpen = 'onDidOpen', onDidChangeContent = 'onDidChangeContent', onDidSave = 'onDidSave', onDidClose = 'onDidClose', onDidSetActive = 'onDidSetActive', } References: - src/common/document_service.ts:15 - src/common/feature_state/supported_language_check.test.ts:36 - src/common/advanced_context/advanced_context_service.ts:56 - src/common/security_diagnostics_publisher.ts:53 - src/common/document_service.ts:69" You are a code assistant,Definition of 'SecurityDiagnosticsPublisher' in file src/common/security_diagnostics_publisher.ts in project gitlab-lsp,"Definition: export const SecurityDiagnosticsPublisher = createInterfaceId( '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, 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 'AiFileContextProvider' in file src/common/ai_context_management_2/providers/ai_file_context_provider.ts in project gitlab-lsp,"Definition: export interface AiFileContextProvider extends DefaultAiFileContextProvider {} export const AiFileContextProvider = createInterfaceId('AiFileContextProvider'); @Injectable(AiFileContextProvider, [RepositoryService, DuoProjectAccessChecker]) export class DefaultAiFileContextProvider implements AiContextProvider { #repositoryService: DefaultRepositoryService; constructor(repositoryService: DefaultRepositoryService) { this.#repositoryService = repositoryService; } async getProviderItems( query: string, workspaceFolders: WorkspaceFolder[], ): Promise { const items = query.trim() === '' ? await this.#getOpenTabsItems() : await this.#getSearchedItems(query, workspaceFolders); log.info(`Found ${items.length} results for ${query}`); return items; } async #getOpenTabsItems(): Promise { const resolutions: ContextResolution[] = []; for await (const resolution of OpenTabsResolver.getInstance().buildContext({ includeCurrentFile: true, })) { resolutions.push(resolution); } return resolutions.map((resolution) => this.#providerItemForOpenTab(resolution)); } async #getSearchedItems( query: string, workspaceFolders: WorkspaceFolder[], ): Promise { const allFiles: RepositoryFile[] = []; for (const folder of workspaceFolders) { const files = this.#repositoryService.getFilesForWorkspace(folder.uri, { excludeGitFolder: true, excludeIgnored: true, }); allFiles.push(...files); } const fileNames = allFiles.map((file) => file.uri.fsPath); const allFilesMap = new Map(allFiles.map((file) => [file.uri.fsPath, file])); const results = filter(fileNames, query, { maxResults: 100 }); const resultFiles: RepositoryFile[] = []; for (const result of results) { if (allFilesMap.has(result)) { resultFiles.push(allFilesMap.get(result) as RepositoryFile); } } return resultFiles.map((file) => this.#providerItemForSearchResult(file)); } #openTabResolutionToRepositoryFile(resolution: ContextResolution): [URI, RepositoryFile | null] { const fileUri = parseURIString(resolution.uri); const repo = this.#repositoryService.findMatchingRepositoryUri( fileUri, resolution.workspaceFolder, ); if (!repo) { log.warn(`Could not find repository for ${resolution.uri}`); return [fileUri, null]; } const repositoryFile = this.#repositoryService.getRepositoryFileForUri( fileUri, repo, resolution.workspaceFolder, ); if (!repositoryFile) { log.warn(`Could not find repository file for ${resolution.uri}`); return [fileUri, null]; } return [fileUri, repositoryFile]; } #providerItemForOpenTab(resolution: ContextResolution): AiContextProviderItem { const [fileUri, repositoryFile] = this.#openTabResolutionToRepositoryFile(resolution); return { fileUri, workspaceFolder: resolution.workspaceFolder, providerType: 'file', subType: 'open_tab', repositoryFile, }; } #providerItemForSearchResult(repositoryFile: RepositoryFile): AiContextProviderItem { return { fileUri: repositoryFile.uri, workspaceFolder: repositoryFile.workspaceFolder, providerType: 'file', subType: 'local_file_search', repositoryFile, }; } } References: - src/common/ai_context_management_2/ai_context_aggregator.ts:24 - src/common/ai_context_management_2/ai_context_aggregator.ts:29" You are a code assistant,Definition of 'DefaultSecretRedactor' in file src/common/secret_redaction/index.ts in project gitlab-lsp,"Definition: 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/secret_redaction/redactor.test.ts:25" You are a code assistant,Definition of 'ITelemetryOptions' in file src/common/tracking/tracking_types.ts in project gitlab-lsp,"Definition: 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, ): void; updateCodeSuggestionsContext( uniqueTrackingId: string, contextUpdate: Partial, ): void; rejectOpenedSuggestions(): void; updateSuggestionState(uniqueTrackingId: string, newState: TRACKING_EVENTS): void; } export const TelemetryTracker = createInterfaceId('TelemetryTracker'); References: - src/common/tracking/snowplow_tracker.ts:135 - src/common/config_service.ts:62 - src/common/tracking/instance_tracker.ts:39" You are a code assistant,Definition of 'MOCK_FILE_2' in file src/tests/int/test_utils.ts in project gitlab-lsp,"Definition: export const MOCK_FILE_2 = { uri: `${WORKSPACE_FOLDER_URI}/some-other-file.js`, languageId: 'javascript', version: 0, text: '', }; declare global { // eslint-disable-next-line @typescript-eslint/no-namespace namespace jest { interface Matchers { toEventuallyContainChildProcessConsoleOutput( expectedMessage: string, timeoutMs?: number, intervalMs?: number, ): Promise; } } } expect.extend({ /** * Custom matcher to check the language client child process console output for an expected string. * This is useful when an operation does not directly run some logic, (e.g. internally emits events * which something later does the thing you're testing), so you cannot just await and check the output. * * await expect(lsClient).toEventuallyContainChildProcessConsoleOutput('foo'); * * @param lsClient LspClient instance to check * @param expectedMessage Message to check for * @param timeoutMs How long to keep checking before test is considered failed * @param intervalMs How frequently to check the log */ async toEventuallyContainChildProcessConsoleOutput( lsClient: LspClient, expectedMessage: string, timeoutMs = 1000, intervalMs = 25, ) { const expectedResult = `Expected language service child process console output to contain ""${expectedMessage}""`; const checkOutput = () => lsClient.childProcessConsole.some((line) => line.includes(expectedMessage)); const sleep = () => new Promise((resolve) => { setTimeout(resolve, intervalMs); }); let remainingRetries = Math.ceil(timeoutMs / intervalMs); while (remainingRetries > 0) { if (checkOutput()) { return { message: () => expectedResult, pass: true, }; } // eslint-disable-next-line no-await-in-loop await sleep(); remainingRetries--; } return { message: () => `""${expectedResult}"", but it was not found within ${timeoutMs}ms`, pass: false, }; }, }); References:" You are a code assistant,Definition of 'ApiReconfiguredData' in file src/common/api.ts in project gitlab-lsp,"Definition: export interface ApiReconfiguredData { /** is the API client configured in a way that allows it to send request to the API */ isInValidState: boolean; validationMessage?: string; } export interface GitLabApiClient { checkToken(token: string | undefined): Promise; getCodeSuggestions(request: CodeSuggestionRequest): Promise; getStreamingCodeSuggestions(request: CodeSuggestionRequest): AsyncGenerator; fetchFromApi(request: ApiRequest): Promise; connectToCable(): Promise; onApiReconfigured(listener: (data: ApiReconfiguredData) => void): Disposable; readonly instanceVersion?: string; } export const GitLabApiClient = createInterfaceId('GitLabApiClient'); export type GenerationType = 'comment' | 'small_file' | 'empty_function' | undefined; export interface CodeSuggestionRequest { prompt_version: number; project_path: string; model_provider?: string; project_id: number; current_file: CodeSuggestionRequestCurrentFile; intent?: 'completion' | 'generation'; stream?: boolean; /** how many suggestion options should the API return */ choices_count?: number; /** additional context to provide to the model */ context?: AdditionalContext[]; /* A user's instructions for code suggestions. */ user_instruction?: string; /* The backend can add additional prompt info based on the type of event */ generation_type?: GenerationType; } export interface CodeSuggestionRequestCurrentFile { file_name: string; content_above_cursor: string; content_below_cursor: string; } export interface CodeSuggestionResponse { choices?: SuggestionOption[]; model?: ICodeSuggestionModel; status: number; error?: string; isDirectConnection?: boolean; } // FIXME: Rename to SuggestionOptionStream when renaming the SuggestionOption export interface StartStreamOption { uniqueTrackingId: string; /** the streamId represents the beginning of a stream * */ streamId: string; } export type SuggestionOptionOrStream = SuggestionOption | StartStreamOption; export interface PersonalAccessToken { name: string; scopes: string[]; active: boolean; } export interface OAuthToken { scope: string[]; } export interface TokenCheckResponse { valid: boolean; reason?: 'unknown' | 'not_active' | 'invalid_scopes'; message?: string; } export interface IDirectConnectionDetailsHeaders { 'X-Gitlab-Global-User-Id': string; 'X-Gitlab-Instance-Id': string; 'X-Gitlab-Host-Name': string; 'X-Gitlab-Saas-Duo-Pro-Namespace-Ids': string; } export interface IDirectConnectionModelDetails { model_provider: string; model_name: string; } export interface IDirectConnectionDetails { base_url: string; token: string; expires_at: number; headers: IDirectConnectionDetailsHeaders; model_details: IDirectConnectionModelDetails; } const CONFIG_CHANGE_EVENT_NAME = 'apiReconfigured'; @Injectable(GitLabApiClient, [LsFetch, ConfigService]) export class GitLabAPI implements GitLabApiClient { #token: string | undefined; #baseURL: string; #clientInfo?: IClientInfo; #lsFetch: LsFetch; #eventEmitter = new EventEmitter(); #configService: ConfigService; #instanceVersion?: string; constructor(lsFetch: LsFetch, configService: ConfigService) { this.#baseURL = GITLAB_API_BASE_URL; this.#lsFetch = lsFetch; this.#configService = configService; this.#configService.onConfigChange(async (config) => { this.#clientInfo = configService.get('client.clientInfo'); this.#lsFetch.updateAgentOptions({ ignoreCertificateErrors: this.#configService.get('client.ignoreCertificateErrors') ?? false, ...(this.#configService.get('client.httpAgentOptions') ?? {}), }); await this.configureApi(config.client); }); } onApiReconfigured(listener: (data: ApiReconfiguredData) => void): Disposable { this.#eventEmitter.on(CONFIG_CHANGE_EVENT_NAME, listener); return { dispose: () => this.#eventEmitter.removeListener(CONFIG_CHANGE_EVENT_NAME, listener) }; } #fireApiReconfigured(isInValidState: boolean, validationMessage?: string) { const data: ApiReconfiguredData = { isInValidState, validationMessage }; this.#eventEmitter.emit(CONFIG_CHANGE_EVENT_NAME, data); } async configureApi({ token, baseUrl = GITLAB_API_BASE_URL, }: { token?: string; baseUrl?: string; }) { if (this.#token === token && this.#baseURL === baseUrl) return; this.#token = token; this.#baseURL = baseUrl; const { valid, reason, message } = await this.checkToken(this.#token); let validationMessage; if (!valid) { this.#configService.set('client.token', undefined); validationMessage = `Token is invalid. ${message}. Reason: ${reason}`; log.warn(validationMessage); } else { log.info('Token is valid'); } this.#instanceVersion = await this.#getGitLabInstanceVersion(); this.#fireApiReconfigured(valid, validationMessage); } #looksLikePatToken(token: string): boolean { // OAuth tokens will be longer than 42 characters and PATs will be shorter. return token.length < 42; } async #checkPatToken(token: string): Promise { const headers = this.#getDefaultHeaders(token); const response = await this.#lsFetch.get( `${this.#baseURL}/api/v4/personal_access_tokens/self`, { headers }, ); await handleFetchError(response, 'Information about personal access token'); const { active, scopes } = (await response.json()) as PersonalAccessToken; if (!active) { return { valid: false, reason: 'not_active', message: 'Token is not active.', }; } if (!this.#hasValidScopes(scopes)) { const joinedScopes = scopes.map((scope) => `'${scope}'`).join(', '); return { valid: false, reason: 'invalid_scopes', message: `Token has scope(s) ${joinedScopes} (needs 'api').`, }; } return { valid: true }; } async #checkOAuthToken(token: string): Promise { const headers = this.#getDefaultHeaders(token); const response = await this.#lsFetch.get(`${this.#baseURL}/oauth/token/info`, { headers, }); await handleFetchError(response, 'Information about OAuth token'); const { scope: scopes } = (await response.json()) as OAuthToken; if (!this.#hasValidScopes(scopes)) { const joinedScopes = scopes.map((scope) => `'${scope}'`).join(', '); return { valid: false, reason: 'invalid_scopes', message: `Token has scope(s) ${joinedScopes} (needs 'api').`, }; } return { valid: true }; } async checkToken(token: string = ''): Promise { try { if (this.#looksLikePatToken(token)) { log.info('Checking token for PAT validity'); return await this.#checkPatToken(token); } log.info('Checking token for OAuth validity'); return await this.#checkOAuthToken(token); } catch (err) { log.error('Error performing token check', err); return { valid: false, reason: 'unknown', message: `Failed to check token: ${err}`, }; } } #hasValidScopes(scopes: string[]): boolean { return scopes.includes('api'); } async getCodeSuggestions( request: CodeSuggestionRequest, ): Promise { if (!this.#token) { throw new Error('Token needs to be provided to request Code Suggestions'); } const headers = { ...this.#getDefaultHeaders(this.#token), 'Content-Type': 'application/json', }; const response = await this.#lsFetch.post( `${this.#baseURL}/api/v4/code_suggestions/completions`, { headers, body: JSON.stringify(request) }, ); await handleFetchError(response, 'Code Suggestions'); const data = await response.json(); return { ...data, status: response.status }; } async *getStreamingCodeSuggestions( request: CodeSuggestionRequest, ): AsyncGenerator { if (!this.#token) { throw new Error('Token needs to be provided to stream code suggestions'); } const headers = { ...this.#getDefaultHeaders(this.#token), 'Content-Type': 'application/json', }; yield* this.#lsFetch.streamFetch( `${this.#baseURL}/api/v4/code_suggestions/completions`, JSON.stringify(request), headers, ); } async fetchFromApi(request: ApiRequest): Promise { if (!this.#token) { return Promise.reject(new Error('Token needs to be provided to authorise API request.')); } if ( request.supportedSinceInstanceVersion && !this.#instanceVersionHigherOrEqualThen(request.supportedSinceInstanceVersion.version) ) { return Promise.reject( new InvalidInstanceVersionError( `Can't ${request.supportedSinceInstanceVersion.resourceName} until your instance is upgraded to ${request.supportedSinceInstanceVersion.version} or higher.`, ), ); } if (request.type === 'graphql') { return this.#graphqlRequest(request.query, request.variables); } switch (request.method) { case 'GET': return this.#fetch(request.path, request.searchParams, 'resource', request.headers); case 'POST': return this.#postFetch(request.path, 'resource', request.body, request.headers); default: // the type assertion is necessary because TS doesn't expect any other types throw new Error(`Unknown request type ${(request as ApiRequest).type}`); } } async connectToCable(): Promise { const headers = this.#getDefaultHeaders(this.#token); const websocketOptions = { headers: { ...headers, Origin: this.#baseURL, }, }; return connectToCable(this.#baseURL, websocketOptions); } async #graphqlRequest( document: RequestDocument, variables?: V, ): Promise { const ensureEndsWithSlash = (url: string) => url.replace(/\/?$/, '/'); const endpoint = new URL('./api/graphql', ensureEndsWithSlash(this.#baseURL)).href; // supports GitLab instances that are on a custom path, e.g. ""https://example.com/gitlab"" const graphqlFetch = async ( input: RequestInfo | URL, init?: RequestInit, ): Promise => { const url = input instanceof URL ? input.toString() : input; return this.#lsFetch.post(url, { ...init, headers: { ...headers, ...init?.headers }, }); }; const headers = this.#getDefaultHeaders(this.#token); const client = new GraphQLClient(endpoint, { headers, fetch: graphqlFetch, }); return client.request(document, variables); } async #fetch( apiResourcePath: string, query: Record = {}, resourceName = 'resource', headers?: Record, ): Promise { const url = `${this.#baseURL}/api/v4${apiResourcePath}${createQueryString(query)}`; const result = await this.#lsFetch.get(url, { headers: { ...this.#getDefaultHeaders(this.#token), ...headers }, }); await handleFetchError(result, resourceName); return result.json() as Promise; } async #postFetch( apiResourcePath: string, resourceName = 'resource', body?: unknown, headers?: Record, ): Promise { const url = `${this.#baseURL}/api/v4${apiResourcePath}`; const response = await this.#lsFetch.post(url, { headers: { 'Content-Type': 'application/json', ...this.#getDefaultHeaders(this.#token), ...headers, }, body: JSON.stringify(body), }); await handleFetchError(response, resourceName); return response.json() as Promise; } #getDefaultHeaders(token?: string) { return { Authorization: `Bearer ${token}`, 'User-Agent': `code-completions-language-server-experiment (${this.#clientInfo?.name}:${this.#clientInfo?.version})`, 'X-Gitlab-Language-Server-Version': getLanguageServerVersion(), }; } #instanceVersionHigherOrEqualThen(version: string): boolean { if (!this.#instanceVersion) return false; return semverCompare(this.#instanceVersion, version) >= 0; } async #getGitLabInstanceVersion(): Promise { if (!this.#token) { return ''; } const headers = this.#getDefaultHeaders(this.#token); const response = await this.#lsFetch.get(`${this.#baseURL}/api/v4/version`, { headers, }); const { version } = await response.json(); return version; } get instanceVersion() { return this.#instanceVersion; } } References: - src/common/api.ts:155 - src/common/api.ts:32 - src/common/core/handlers/token_check_notifier.test.ts:18 - src/common/suggestion_client/direct_connection_client.test.ts:100 - src/common/api.ts:149" You are a code assistant,Definition of 'trackStructEvent' in file src/common/tracking/snowplow/snowplow.ts in project gitlab-lsp,"Definition: public async trackStructEvent( event: StructuredEvent, context?: SelfDescribingJson[] | null, ): Promise { this.#tracker.track(buildStructEvent(event), context); } async stop() { await this.#emitter.stop(); } public destroy() { Snowplow.#instance = undefined; } } References:" You are a code assistant,Definition of 'GetRequest' in file packages/webview_duo_chat/src/plugin/types.ts in project gitlab-lsp,"Definition: interface GetRequest<_TReturnType> extends BaseRestRequest<_TReturnType> { method: 'GET'; searchParams?: Record; supportedSinceInstanceVersion?: SupportedSinceInstanceVersion; } export type ApiRequest<_TReturnType> = | GetRequest<_TReturnType> | PostRequest<_TReturnType> | GraphQLRequest<_TReturnType>; export interface GitLabApiClient { fetchFromApi(request: ApiRequest): Promise; connectToCable(): Promise; } References:" You are a code assistant,Definition of 'ICodeSuggestionContextUpdate' in file src/common/tracking/tracking_types.ts in project gitlab-lsp,"Definition: export interface ICodeSuggestionContextUpdate { documentContext: IDocContext; source: SuggestionSource; language: string; isStreaming: boolean; model: ICodeSuggestionModel; status: number; debounceInterval: number; gitlab_global_user_id: string; gitlab_instance_id: string; gitlab_host_name: string; gitlab_saas_duo_pro_namespace_ids: number[]; isInvoked: boolean; optionsCount: number; acceptedOption: number; triggerKind: InlineCompletionTriggerKind; additionalContexts: AdditionalContext[]; isDirectConnection: boolean; suggestionOptions: SuggestionOption[]; } export type IClientInfo = InitializeParams['clientInfo']; export enum GitlabRealm { saas = 'saas', selfManaged = 'self-managed', } export enum SuggestionSource { cache = 'cache', network = 'network', } export interface IIDEInfo { name: string; version: string; vendor: string; } 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, ): void; updateCodeSuggestionsContext( uniqueTrackingId: string, contextUpdate: Partial, ): void; rejectOpenedSuggestions(): void; updateSuggestionState(uniqueTrackingId: string, newState: TRACKING_EVENTS): void; } export const TelemetryTracker = createInterfaceId('TelemetryTracker'); References:" You are a code assistant,Definition of 'constructor' in file src/common/ai_context_management_2/retrievers/ai_file_context_retriever.ts in project gitlab-lsp,"Definition: constructor( private fileResolver: FileResolver, private secretRedactor: SecretRedactor, ) {} async retrieve(aiContextItem: AiContextItem): Promise { if (aiContextItem.type !== 'file') { return null; } try { log.info(`retrieving file ${aiContextItem.id}`); const fileContent = await this.fileResolver.readFile({ fileUri: aiContextItem.id, }); log.info(`redacting secrets for file ${aiContextItem.id}`); const redactedContent = this.secretRedactor.redactSecrets(fileContent); return redactedContent; } catch (e) { log.warn(`Failed to retrieve file ${aiContextItem.id}`, e); return null; } } } References:" You are a code assistant,Definition of 'SyncLoadScriptsPlugin' in file packages/lib_vite_common_config/vite.config.shared.ts in project gitlab-lsp,"Definition: export const SyncLoadScriptsPlugin = { name: 'sync-load-scripts-plugin', transformIndexHtml(html) { const doc = NodeHtmlParser.parse(html); const body = doc.querySelector('body'); doc.querySelectorAll('head script').forEach((script) => { script.removeAttribute('type'); script.removeAttribute('crossorigin'); body?.appendChild(script); }); return doc.toString(); }, }; export const HtmlTransformPlugin = { name: 'html-transform', transformIndexHtml(html) { return html.replace('{{ svg placeholder }}', svgSpriteContent); }, }; export const InlineSvgPlugin = { name: 'inline-svg', transform(code, id) { if (id.endsWith('@gitlab/svgs/dist/icons.svg')) { svgSpriteContent = fs.readFileSync(id, 'utf-8'); return 'export default """"'; } if (id.match(/@gitlab\/svgs\/dist\/illustrations\/.*\.svg$/)) { const base64Data = imageToBase64(id); return `export default ""data:image/svg+xml;base64,${base64Data}""`; } return code; }, }; export function createViteConfigForWebview(name): UserConfig { const outDir = path.resolve(__dirname, `../../../../out/webviews/${name}`); return { plugins: [vue2(), InlineSvgPlugin, SyncLoadScriptsPlugin, HtmlTransformPlugin], resolve: { alias: { '@': fileURLToPath(new URL('./src/app', import.meta.url)), }, }, root: './src/app', base: '', build: { target: 'es2022', emptyOutDir: true, outDir, rollupOptions: { input: [path.join('src', 'app', 'index.html')], }, }, }; } References:" You are a code assistant,Definition of 'IntentTestCase' in file src/tests/unit/tree_sitter/intent_resolver.test.ts in project gitlab-lsp,"Definition: type IntentTestCase = [TestType, Position, Intent]; /** * Note: We use the language server procotol Ids here because `IDocContext` expects * these Ids (which is passed into `ParseFile`) and because they are unique. * `ParseFile` derives the tree sitter gramamr from the file's extension. * Some grammars apply to multiple extensions, eg. `typescript` applies * to both `.ts` and `.tsx`. */ const testCases: Array<[LanguageServerLanguageId, FileExtension, IntentTestCase[]]> = [ /* [ FIXME: add back support for vue 'vue', '.vue', // ../../fixtures/intent/vue_comments.vue [ ['on_empty_comment', { line: 2, character: 9 }, 'completion'], ['after_empty_comment', { line: 3, character: 0 }, 'completion'], ['on_non_empty_comment', { line: 4, character: 30 }, 'completion'], ['after_non_empty_comment', { line: 5, character: 0 }, 'generation'], ['in_block_comment', { line: 8, character: 23 }, 'completion'], ['on_block_comment', { line: 9, character: 2 }, 'completion'], ['after_block_comment', { line: 10, character: 0 }, 'generation'], ['no_comment_large_file', { line: 30, character: 0 }, undefined], // TODO: comments in the Vue `script` are not captured // ['on_comment_in_empty_function', { line: 34, character: 33 }, 'completion'], // ['after_comment_in_empty_function', { line: 35, character: 0 }, 'generation'], ], ], */ [ 'typescript', '.ts', // ../../fixtures/intent/typescript_comments.ts [ ['on_empty_comment', { line: 1, character: 3 }, 'completion'], ['after_empty_comment', { line: 2, character: 0 }, 'completion'], ['on_non_empty_comment', { line: 4, character: 30 }, 'completion'], ['after_non_empty_comment', { line: 5, character: 0 }, 'generation'], ['in_block_comment', { line: 8, character: 23 }, 'completion'], ['on_block_comment', { line: 9, character: 2 }, 'completion'], ['after_block_comment', { line: 10, character: 0 }, 'generation'], ['in_jsdoc_comment', { line: 14, character: 21 }, 'completion'], ['on_jsdoc_comment', { line: 15, character: 3 }, 'completion'], ['after_jsdoc_comment', { line: 16, character: 0 }, 'generation'], ['no_comment_large_file', { line: 24, character: 0 }, undefined], ['on_comment_in_empty_function', { line: 30, character: 31 }, 'completion'], ['after_comment_in_empty_function', { line: 31, character: 0 }, 'generation'], ], ], [ 'typescriptreact', '.tsx', // ../../fixtures/intent/typescriptreact_comments.tsx [ ['on_empty_comment', { line: 1, character: 3 }, 'completion'], ['after_empty_comment', { line: 2, character: 0 }, 'completion'], ['on_non_empty_comment', { line: 4, character: 30 }, 'completion'], ['after_non_empty_comment', { line: 5, character: 0 }, 'generation'], ['in_block_comment', { line: 8, character: 23 }, 'completion'], ['on_block_comment', { line: 9, character: 2 }, 'completion'], ['after_block_comment', { line: 10, character: 0 }, 'generation'], ['in_jsdoc_comment', { line: 14, character: 21 }, 'completion'], ['on_jsdoc_comment', { line: 15, character: 3 }, 'completion'], ['after_jsdoc_comment', { line: 16, character: 0 }, 'generation'], ['no_comment_large_file', { line: 24, character: 0 }, undefined], ['on_comment_in_empty_function', { line: 30, character: 31 }, 'completion'], ['after_comment_in_empty_function', { line: 31, character: 0 }, 'generation'], ], ], [ 'javascript', '.js', // ../../fixtures/intent/javascript_comments.js [ ['on_empty_comment', { line: 1, character: 3 }, 'completion'], ['after_empty_comment', { line: 2, character: 0 }, 'completion'], ['on_non_empty_comment', { line: 4, character: 30 }, 'completion'], ['after_non_empty_comment', { line: 5, character: 0 }, 'generation'], ['in_block_comment', { line: 8, character: 23 }, 'completion'], ['on_block_comment', { line: 9, character: 2 }, 'completion'], ['after_block_comment', { line: 10, character: 0 }, 'generation'], ['in_jsdoc_comment', { line: 14, character: 21 }, 'completion'], ['on_jsdoc_comment', { line: 15, character: 3 }, 'completion'], ['after_jsdoc_comment', { line: 16, character: 0 }, 'generation'], ['no_comment_large_file', { line: 24, character: 0 }, undefined], ['on_comment_in_empty_function', { line: 30, character: 31 }, 'completion'], ['after_comment_in_empty_function', { line: 31, character: 0 }, 'generation'], ], ], [ 'javascriptreact', '.jsx', // ../../fixtures/intent/javascriptreact_comments.jsx [ ['on_empty_comment', { line: 1, character: 3 }, 'completion'], ['after_empty_comment', { line: 2, character: 0 }, 'completion'], ['on_non_empty_comment', { line: 4, character: 30 }, 'completion'], ['after_non_empty_comment', { line: 5, character: 0 }, 'generation'], ['in_block_comment', { line: 8, character: 23 }, 'completion'], ['on_block_comment', { line: 9, character: 2 }, 'completion'], ['after_block_comment', { line: 10, character: 0 }, 'generation'], ['in_jsdoc_comment', { line: 15, character: 25 }, 'completion'], ['on_jsdoc_comment', { line: 16, character: 3 }, 'completion'], ['after_jsdoc_comment', { line: 17, character: 0 }, 'generation'], ['no_comment_large_file', { line: 24, character: 0 }, undefined], ['on_comment_in_empty_function', { line: 31, character: 31 }, 'completion'], ['after_comment_in_empty_function', { line: 32, character: 0 }, 'generation'], ], ], [ 'ruby', '.rb', // ../../fixtures/intent/ruby_comments.rb [ ['on_empty_comment', { line: 1, character: 3 }, 'completion'], ['after_empty_comment', { line: 2, character: 0 }, 'completion'], ['on_non_empty_comment', { line: 4, character: 30 }, 'completion'], ['after_non_empty_comment', { line: 5, character: 0 }, 'generation'], ['in_block_comment', { line: 9, character: 23 }, 'completion'], ['on_block_comment', { line: 10, character: 4 }, 'completion'], ['after_block_comment', { line: 11, character: 0 }, 'generation'], ['no_comment_large_file', { line: 17, character: 0 }, undefined], ['on_comment_in_empty_function', { line: 21, character: 30 }, 'completion'], ['after_comment_in_empty_function', { line: 22, character: 22 }, 'generation'], ], ], [ 'go', '.go', // ../../fixtures/intent/go_comments.go [ ['on_empty_comment', { line: 1, character: 3 }, 'completion'], ['after_empty_comment', { line: 2, character: 0 }, 'completion'], ['on_non_empty_comment', { line: 4, character: 30 }, 'completion'], ['after_non_empty_comment', { line: 5, character: 0 }, 'generation'], ['in_block_comment', { line: 8, character: 23 }, 'completion'], ['on_block_comment', { line: 9, character: 2 }, 'completion'], ['after_block_comment', { line: 10, character: 0 }, 'generation'], ['no_comment_large_file', { line: 20, character: 0 }, undefined], ['on_comment_in_empty_function', { line: 24, character: 31 }, 'completion'], ['after_comment_in_empty_function', { line: 25, character: 0 }, 'generation'], ], ], [ 'java', '.java', // ../../fixtures/intent/java_comments.java [ ['on_empty_comment', { line: 1, character: 3 }, 'completion'], ['after_empty_comment', { line: 2, character: 0 }, 'completion'], ['on_non_empty_comment', { line: 4, character: 30 }, 'completion'], ['after_non_empty_comment', { line: 5, character: 0 }, 'generation'], ['in_block_comment', { line: 8, character: 23 }, 'completion'], ['on_block_comment', { line: 9, character: 2 }, 'completion'], ['after_block_comment', { line: 10, character: 0 }, 'generation'], ['in_doc_comment', { line: 14, character: 29 }, 'completion'], ['on_doc_comment', { line: 15, character: 3 }, 'completion'], ['after_doc_comment', { line: 16, character: 0 }, 'generation'], ['no_comment_large_file', { line: 23, character: 0 }, undefined], ['on_comment_in_empty_function', { line: 30, character: 31 }, 'completion'], ['after_comment_in_empty_function', { line: 31, character: 0 }, 'generation'], ], ], [ 'kotlin', '.kt', // ../../fixtures/intent/kotlin_comments.kt [ ['on_empty_comment', { line: 1, character: 3 }, 'completion'], ['after_empty_comment', { line: 2, character: 0 }, 'completion'], ['on_non_empty_comment', { line: 4, character: 30 }, 'completion'], ['after_non_empty_comment', { line: 5, character: 0 }, 'generation'], ['in_block_comment', { line: 8, character: 23 }, 'completion'], ['on_block_comment', { line: 9, character: 2 }, 'completion'], ['after_block_comment', { line: 10, character: 0 }, 'generation'], ['in_doc_comment', { line: 14, character: 29 }, 'completion'], ['on_doc_comment', { line: 15, character: 3 }, 'completion'], ['after_doc_comment', { line: 16, character: 0 }, 'generation'], ['no_comment_large_file', { line: 23, character: 0 }, undefined], ['on_comment_in_empty_function', { line: 30, character: 31 }, 'completion'], ['after_comment_in_empty_function', { line: 31, character: 0 }, 'generation'], ], ], [ 'rust', '.rs', // ../../fixtures/intent/rust_comments.rs [ ['on_empty_comment', { line: 1, character: 3 }, 'completion'], ['after_empty_comment', { line: 2, character: 0 }, 'completion'], ['on_non_empty_comment', { line: 4, character: 30 }, 'completion'], ['after_non_empty_comment', { line: 5, character: 0 }, 'generation'], ['in_block_comment', { line: 8, character: 23 }, 'completion'], ['on_block_comment', { line: 9, character: 2 }, 'completion'], ['after_block_comment', { line: 10, character: 0 }, 'generation'], ['in_doc_comment', { line: 11, character: 25 }, 'completion'], ['on_doc_comment', { line: 12, character: 42 }, 'completion'], ['after_doc_comment', { line: 15, character: 0 }, 'generation'], ['no_comment_large_file', { line: 23, character: 0 }, undefined], ['on_comment_in_empty_function', { line: 26, character: 31 }, 'completion'], ['after_comment_in_empty_function', { line: 27, character: 0 }, 'generation'], ], ], [ 'yaml', '.yaml', // ../../fixtures/intent/yaml_comments.yaml [ ['on_empty_comment', { line: 1, character: 3 }, 'completion'], ['after_empty_comment', { line: 2, character: 0 }, 'completion'], ['on_non_empty_comment', { line: 4, character: 30 }, 'completion'], ['after_non_empty_comment', { line: 5, character: 0 }, 'generation'], ['no_comment_large_file', { line: 17, character: 0 }, undefined], ], ], [ 'html', '.html', // ../../fixtures/intent/html_comments.html [ ['on_empty_comment', { line: 14, character: 12 }, 'completion'], ['after_empty_comment', { line: 15, character: 0 }, 'completion'], ['on_non_empty_comment', { line: 8, character: 91 }, 'completion'], ['after_non_empty_comment', { line: 9, character: 0 }, 'generation'], ['in_block_comment', { line: 18, character: 29 }, 'completion'], ['on_block_comment', { line: 19, character: 7 }, 'completion'], ['after_block_comment', { line: 20, character: 0 }, 'generation'], ['no_comment_large_file', { line: 12, character: 66 }, undefined], ], ], [ 'c', '.c', // ../../fixtures/intent/c_comments.c [ ['on_empty_comment', { line: 1, character: 3 }, 'completion'], ['after_empty_comment', { line: 2, character: 0 }, 'completion'], ['on_non_empty_comment', { line: 4, character: 30 }, 'completion'], ['after_non_empty_comment', { line: 5, character: 0 }, 'generation'], ['in_block_comment', { line: 8, character: 23 }, 'completion'], ['on_block_comment', { line: 9, character: 2 }, 'completion'], ['after_block_comment', { line: 10, character: 0 }, 'generation'], ['no_comment_large_file', { line: 17, character: 0 }, undefined], ['on_comment_in_empty_function', { line: 20, character: 31 }, 'completion'], ['after_comment_in_empty_function', { line: 21, character: 0 }, 'generation'], ], ], [ 'cpp', '.cpp', // ../../fixtures/intent/cpp_comments.cpp [ ['on_empty_comment', { line: 1, character: 3 }, 'completion'], ['after_empty_comment', { line: 2, character: 0 }, 'completion'], ['on_non_empty_comment', { line: 4, character: 30 }, 'completion'], ['after_non_empty_comment', { line: 5, character: 0 }, 'generation'], ['in_block_comment', { line: 8, character: 23 }, 'completion'], ['on_block_comment', { line: 9, character: 2 }, 'completion'], ['after_block_comment', { line: 10, character: 0 }, 'generation'], ['no_comment_large_file', { line: 17, character: 0 }, undefined], ['on_comment_in_empty_function', { line: 20, character: 31 }, 'completion'], ['after_comment_in_empty_function', { line: 21, character: 0 }, 'generation'], ], ], [ 'c_sharp', '.cs', // ../../fixtures/intent/c_sharp_comments.cs [ ['on_empty_comment', { line: 1, character: 3 }, 'completion'], ['after_empty_comment', { line: 2, character: 0 }, 'completion'], ['on_non_empty_comment', { line: 4, character: 30 }, 'completion'], ['after_non_empty_comment', { line: 5, character: 0 }, 'generation'], ['in_block_comment', { line: 8, character: 23 }, 'completion'], ['on_block_comment', { line: 9, character: 2 }, 'completion'], ['after_block_comment', { line: 10, character: 0 }, 'generation'], ['no_comment_large_file', { line: 17, character: 0 }, undefined], ['on_comment_in_empty_function', { line: 20, character: 31 }, 'completion'], ['after_comment_in_empty_function', { line: 21, character: 22 }, 'generation'], ], ], [ 'css', '.css', // ../../fixtures/intent/css_comments.css [ ['on_empty_comment', { line: 1, character: 3 }, 'completion'], ['after_empty_comment', { line: 2, character: 0 }, 'completion'], ['on_non_empty_comment', { line: 3, character: 31 }, 'completion'], ['after_non_empty_comment', { line: 4, character: 0 }, 'generation'], ['in_block_comment', { line: 7, character: 23 }, 'completion'], ['on_block_comment', { line: 8, character: 2 }, 'completion'], ['after_block_comment', { line: 9, character: 0 }, 'generation'], ['no_comment_large_file', { line: 17, character: 0 }, undefined], ], ], [ 'bash', '.sh', // ../../fixtures/intent/bash_comments.css [ ['on_empty_comment', { line: 4, character: 1 }, 'completion'], ['after_empty_comment', { line: 5, character: 0 }, 'completion'], ['on_non_empty_comment', { line: 2, character: 65 }, 'completion'], ['after_non_empty_comment', { line: 3, character: 0 }, 'generation'], ['no_comment_large_file', { line: 10, character: 0 }, undefined], ['on_comment_in_empty_function', { line: 19, character: 12 }, 'completion'], ['after_comment_in_empty_function', { line: 20, character: 0 }, 'generation'], ], ], [ 'json', '.json', // ../../fixtures/intent/json_comments.css [ ['on_empty_comment', { line: 20, character: 3 }, 'completion'], ['after_empty_comment', { line: 21, character: 0 }, 'completion'], ['on_non_empty_comment', { line: 0, character: 38 }, 'completion'], ['after_non_empty_comment', { line: 1, character: 0 }, 'generation'], ['no_comment_large_file', { line: 10, character: 0 }, undefined], ], ], [ 'scala', '.scala', // ../../fixtures/intent/scala_comments.scala [ ['on_empty_comment', { line: 1, character: 3 }, 'completion'], ['after_empty_comment', { line: 2, character: 3 }, 'completion'], ['after_non_empty_comment', { line: 5, character: 0 }, 'generation'], ['after_block_comment', { line: 10, character: 0 }, 'generation'], ['no_comment_large_file', { line: 12, character: 0 }, undefined], ['after_comment_in_empty_function', { line: 21, character: 0 }, 'generation'], ], ], [ 'powersell', '.ps1', // ../../fixtures/intent/powershell_comments.ps1 [ ['on_empty_comment', { line: 20, character: 3 }, 'completion'], ['after_empty_comment', { line: 21, character: 3 }, 'completion'], ['after_non_empty_comment', { line: 10, character: 0 }, 'generation'], ['after_block_comment', { line: 8, character: 0 }, 'generation'], ['no_comment_large_file', { line: 22, character: 0 }, undefined], ['after_comment_in_empty_function', { line: 26, character: 0 }, 'generation'], ], ], ]; describe.each(testCases)('%s', (language, fileExt, cases) => { it.each(cases)('should resolve %s intent correctly', async (_, position, expectedIntent) => { const fixturePath = getFixturePath('intent', `${language}_comments${fileExt}`); const { treeAndLanguage, prefix, suffix } = await getTreeAndTestFile({ fixturePath, position, languageId: language, }); const intent = await getIntent({ treeAndLanguage, position, prefix, suffix }); expect(intent.intent).toBe(expectedIntent); if (expectedIntent === 'generation') { expect(intent.generationType).toBe('comment'); } }); }); }); describe('Empty Function Intent', () => { type TestType = | 'empty_function_declaration' | 'non_empty_function_declaration' | 'empty_function_expression' | 'non_empty_function_expression' | 'empty_arrow_function' | 'non_empty_arrow_function' | 'empty_method_definition' | 'non_empty_method_definition' | 'empty_class_constructor' | 'non_empty_class_constructor' | 'empty_class_declaration' | 'non_empty_class_declaration' | 'empty_anonymous_function' | 'non_empty_anonymous_function' | 'empty_implementation' | 'non_empty_implementation' | 'empty_closure_expression' | 'non_empty_closure_expression' | 'empty_generator' | 'non_empty_generator' | 'empty_macro' | 'non_empty_macro'; type FileExtension = string; /** * Position refers to the position of the cursor in the test file. */ type IntentTestCase = [TestType, Position, Intent]; const emptyFunctionTestCases: Array< [LanguageServerLanguageId, FileExtension, IntentTestCase[]] > = [ [ 'typescript', '.ts', // ../../fixtures/intent/empty_function/typescript.ts [ ['empty_function_declaration', { line: 0, character: 22 }, 'generation'], ['non_empty_function_declaration', { line: 3, character: 4 }, undefined], ['empty_function_expression', { line: 6, character: 32 }, 'generation'], ['non_empty_function_expression', { line: 10, character: 4 }, undefined], ['empty_arrow_function', { line: 12, character: 26 }, 'generation'], ['non_empty_arrow_function', { line: 15, character: 4 }, undefined], ['empty_class_constructor', { line: 19, character: 21 }, 'generation'], ['empty_method_definition', { line: 21, character: 11 }, 'generation'], ['non_empty_class_constructor', { line: 29, character: 7 }, undefined], ['non_empty_method_definition', { line: 33, character: 0 }, undefined], ['empty_class_declaration', { line: 36, character: 14 }, 'generation'], ['empty_generator', { line: 38, character: 31 }, 'generation'], ['non_empty_generator', { line: 41, character: 4 }, undefined], ], ], [ 'javascript', '.js', // ../../fixtures/intent/empty_function/javascript.js [ ['empty_function_declaration', { line: 0, character: 22 }, 'generation'], ['non_empty_function_declaration', { line: 3, character: 4 }, undefined], ['empty_function_expression', { line: 6, character: 32 }, 'generation'], ['non_empty_function_expression', { line: 10, character: 4 }, undefined], ['empty_arrow_function', { line: 12, character: 26 }, 'generation'], ['non_empty_arrow_function', { line: 15, character: 4 }, undefined], ['empty_class_constructor', { line: 19, character: 21 }, 'generation'], ['empty_method_definition', { line: 21, character: 11 }, 'generation'], ['non_empty_class_constructor', { line: 27, character: 7 }, undefined], ['non_empty_method_definition', { line: 31, character: 0 }, undefined], ['empty_class_declaration', { line: 34, character: 14 }, 'generation'], ['empty_generator', { line: 36, character: 31 }, 'generation'], ['non_empty_generator', { line: 39, character: 4 }, undefined], ], ], [ 'go', '.go', // ../../fixtures/intent/empty_function/go.go [ ['empty_function_declaration', { line: 0, character: 25 }, 'generation'], ['non_empty_function_declaration', { line: 3, character: 4 }, undefined], ['empty_anonymous_function', { line: 6, character: 32 }, 'generation'], ['non_empty_anonymous_function', { line: 10, character: 0 }, undefined], ['empty_method_definition', { line: 19, character: 25 }, 'generation'], ['non_empty_method_definition', { line: 23, character: 0 }, undefined], ], ], [ 'java', '.java', // ../../fixtures/intent/empty_function/java.java [ ['empty_function_declaration', { line: 0, character: 26 }, 'generation'], ['non_empty_function_declaration', { line: 3, character: 4 }, undefined], ['empty_anonymous_function', { line: 7, character: 0 }, 'generation'], ['non_empty_anonymous_function', { line: 10, character: 0 }, undefined], ['empty_class_declaration', { line: 15, character: 18 }, 'generation'], ['non_empty_class_declaration', { line: 19, character: 0 }, undefined], ['empty_class_constructor', { line: 18, character: 13 }, 'generation'], ['empty_method_definition', { line: 20, character: 18 }, 'generation'], ['non_empty_class_constructor', { line: 26, character: 18 }, undefined], ['non_empty_method_definition', { line: 30, character: 18 }, undefined], ], ], [ 'rust', '.rs', // ../../fixtures/intent/empty_function/rust.vue [ ['empty_function_declaration', { line: 0, character: 23 }, 'generation'], ['non_empty_function_declaration', { line: 3, character: 4 }, undefined], ['empty_implementation', { line: 8, character: 13 }, 'generation'], ['non_empty_implementation', { line: 11, character: 0 }, undefined], ['empty_class_constructor', { line: 13, character: 0 }, 'generation'], ['non_empty_class_constructor', { line: 23, character: 0 }, undefined], ['empty_method_definition', { line: 17, character: 0 }, 'generation'], ['non_empty_method_definition', { line: 26, character: 0 }, undefined], ['empty_closure_expression', { line: 32, character: 0 }, 'generation'], ['non_empty_closure_expression', { line: 36, character: 0 }, undefined], ['empty_macro', { line: 42, character: 11 }, 'generation'], ['non_empty_macro', { line: 45, character: 11 }, undefined], ['empty_macro', { line: 55, character: 0 }, 'generation'], ['non_empty_macro', { line: 62, character: 20 }, undefined], ], ], [ 'kotlin', '.kt', // ../../fixtures/intent/empty_function/kotlin.kt [ ['empty_function_declaration', { line: 0, character: 25 }, 'generation'], ['non_empty_function_declaration', { line: 4, character: 0 }, undefined], ['empty_anonymous_function', { line: 6, character: 32 }, 'generation'], ['non_empty_anonymous_function', { line: 9, character: 4 }, undefined], ['empty_class_declaration', { line: 12, character: 14 }, 'generation'], ['non_empty_class_declaration', { line: 15, character: 14 }, undefined], ['empty_method_definition', { line: 24, character: 0 }, 'generation'], ['non_empty_method_definition', { line: 28, character: 0 }, undefined], ], ], [ 'typescriptreact', '.tsx', // ../../fixtures/intent/empty_function/typescriptreact.tsx [ ['empty_function_declaration', { line: 0, character: 22 }, 'generation'], ['non_empty_function_declaration', { line: 3, character: 4 }, undefined], ['empty_function_expression', { line: 6, character: 32 }, 'generation'], ['non_empty_function_expression', { line: 10, character: 4 }, undefined], ['empty_arrow_function', { line: 12, character: 26 }, 'generation'], ['non_empty_arrow_function', { line: 15, character: 4 }, undefined], ['empty_class_constructor', { line: 19, character: 21 }, 'generation'], ['empty_method_definition', { line: 21, character: 11 }, 'generation'], ['non_empty_class_constructor', { line: 29, character: 7 }, undefined], ['non_empty_method_definition', { line: 33, character: 0 }, undefined], ['empty_class_declaration', { line: 36, character: 14 }, 'generation'], ['non_empty_arrow_function', { line: 40, character: 0 }, undefined], ['empty_arrow_function', { line: 41, character: 23 }, 'generation'], ['non_empty_arrow_function', { line: 44, character: 23 }, undefined], ['empty_generator', { line: 54, character: 31 }, 'generation'], ['non_empty_generator', { line: 57, character: 4 }, undefined], ], ], [ 'c', '.c', // ../../fixtures/intent/empty_function/c.c [ ['empty_function_declaration', { line: 0, character: 24 }, 'generation'], ['non_empty_function_declaration', { line: 3, character: 0 }, undefined], ], ], [ 'cpp', '.cpp', // ../../fixtures/intent/empty_function/cpp.cpp [ ['empty_function_declaration', { line: 0, character: 37 }, 'generation'], ['non_empty_function_declaration', { line: 3, character: 0 }, undefined], ['empty_function_expression', { line: 6, character: 43 }, 'generation'], ['non_empty_function_expression', { line: 10, character: 4 }, undefined], ['empty_class_constructor', { line: 15, character: 37 }, 'generation'], ['empty_method_definition', { line: 17, character: 18 }, 'generation'], ['non_empty_class_constructor', { line: 27, character: 7 }, undefined], ['non_empty_method_definition', { line: 31, character: 0 }, undefined], ['empty_class_declaration', { line: 35, character: 14 }, 'generation'], ], ], [ 'c_sharp', '.cs', // ../../fixtures/intent/empty_function/c_sharp.cs [ ['empty_function_expression', { line: 2, character: 48 }, 'generation'], ['empty_class_constructor', { line: 4, character: 31 }, 'generation'], ['empty_method_definition', { line: 6, character: 31 }, 'generation'], ['non_empty_class_constructor', { line: 15, character: 0 }, undefined], ['non_empty_method_definition', { line: 20, character: 0 }, undefined], ['empty_class_declaration', { line: 24, character: 22 }, 'generation'], ], ], [ 'bash', '.sh', // ../../fixtures/intent/empty_function/bash.sh [ ['empty_function_declaration', { line: 3, character: 48 }, 'generation'], ['non_empty_function_declaration', { line: 6, character: 31 }, undefined], ], ], [ 'scala', '.scala', // ../../fixtures/intent/empty_function/scala.scala [ ['empty_function_declaration', { line: 1, character: 4 }, 'generation'], ['non_empty_function_declaration', { line: 5, character: 4 }, undefined], ['empty_method_definition', { line: 28, character: 3 }, 'generation'], ['non_empty_method_definition', { line: 34, character: 3 }, undefined], ['empty_class_declaration', { line: 22, character: 4 }, 'generation'], ['non_empty_class_declaration', { line: 27, character: 0 }, undefined], ['empty_anonymous_function', { line: 13, character: 0 }, 'generation'], ['non_empty_anonymous_function', { line: 17, character: 0 }, undefined], ], ], [ 'ruby', '.rb', // ../../fixtures/intent/empty_function/ruby.rb [ ['empty_method_definition', { line: 0, character: 23 }, 'generation'], ['empty_method_definition', { line: 0, character: 6 }, undefined], ['non_empty_method_definition', { line: 3, character: 0 }, undefined], ['empty_anonymous_function', { line: 7, character: 27 }, 'generation'], ['non_empty_anonymous_function', { line: 9, character: 37 }, undefined], ['empty_anonymous_function', { line: 11, character: 25 }, 'generation'], ['empty_class_constructor', { line: 16, character: 22 }, 'generation'], ['non_empty_class_declaration', { line: 18, character: 0 }, undefined], ['empty_method_definition', { line: 20, character: 1 }, 'generation'], ['empty_class_declaration', { line: 33, character: 12 }, 'generation'], ], ], [ 'python', '.py', // ../../fixtures/intent/empty_function/python.py [ ['empty_function_declaration', { line: 1, character: 4 }, 'generation'], ['non_empty_function_declaration', { line: 5, character: 4 }, undefined], ['empty_class_constructor', { line: 10, character: 0 }, 'generation'], ['empty_method_definition', { line: 14, character: 0 }, 'generation'], ['non_empty_class_constructor', { line: 19, character: 0 }, undefined], ['non_empty_method_definition', { line: 23, character: 4 }, undefined], ['empty_class_declaration', { line: 27, character: 4 }, 'generation'], ['empty_function_declaration', { line: 31, character: 4 }, 'generation'], ['empty_class_constructor', { line: 36, character: 4 }, 'generation'], ['empty_method_definition', { line: 40, character: 4 }, 'generation'], ['empty_class_declaration', { line: 44, character: 4 }, 'generation'], ['empty_function_declaration', { line: 49, character: 4 }, 'generation'], ['empty_class_constructor', { line: 53, character: 4 }, 'generation'], ['empty_method_definition', { line: 56, character: 4 }, 'generation'], ['empty_class_declaration', { line: 59, character: 4 }, 'generation'], ], ], ]; describe.each(emptyFunctionTestCases)('%s', (language, fileExt, cases) => { it.each(cases)('should resolve %s intent correctly', async (_, position, expectedIntent) => { const fixturePath = getFixturePath('intent', `empty_function/${language}${fileExt}`); const { treeAndLanguage, prefix, suffix } = await getTreeAndTestFile({ fixturePath, position, languageId: language, }); const intent = await getIntent({ treeAndLanguage, position, prefix, suffix }); expect(intent.intent).toBe(expectedIntent); if (expectedIntent === 'generation') { expect(intent.generationType).toBe('empty_function'); } }); }); }); }); References:" You are a code assistant,Definition of 'getFixturePath' in file src/tests/unit/tree_sitter/test_utils.ts in project gitlab-lsp,"Definition: export const getFixturePath = (category: Category, filePath: string) => resolve(cwd(), 'src', 'tests', 'fixtures', category, filePath); /** * Use this function to get the test file and tree for a given fixture file * to be used for Tree Sitter testing purposes. */ 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:664 - src/tests/unit/tree_sitter/intent_resolver.test.ts:26 - src/tests/unit/tree_sitter/intent_resolver.test.ts:394 - src/tests/unit/tree_sitter/intent_resolver.test.ts:13" You are a code assistant,Definition of 'isCursorInEmptyFunction' in file src/common/tree_sitter/empty_function/empty_function_resolver.ts in project gitlab-lsp,"Definition: isCursorInEmptyFunction({ languageName, tree, cursorPosition, treeSitterLanguage, }: { languageName: TreeSitterLanguageName; tree: Tree; treeSitterLanguage: Language; cursorPosition: Point; }): boolean { const query = this.#getQueryByLanguage(languageName, treeSitterLanguage); if (!query) { return false; } const emptyBodyPositions = query.captures(tree.rootNode).map((capture) => { return EmptyFunctionResolver.#findEmptyBodyPosition(capture.node); }); const cursorInsideInOneOfTheCaptures = emptyBodyPositions.some( (emptyBody) => EmptyFunctionResolver.#isValidBodyPosition(emptyBody) && EmptyFunctionResolver.#isCursorInsideNode( cursorPosition, emptyBody.startPosition, emptyBody.endPosition, ), ); return ( cursorInsideInOneOfTheCaptures || EmptyFunctionResolver.isCursorAfterEmptyPythonFunction({ languageName, tree, treeSitterLanguage, cursorPosition, }) ); } static #isCursorInsideNode( cursorPosition: Point, startPosition: Point, endPosition: Point, ): boolean { const { row: cursorRow, column: cursorColumn } = cursorPosition; const isCursorAfterNodeStart = cursorRow > startPosition.row || (cursorRow === startPosition.row && cursorColumn >= startPosition.column); const isCursorBeforeNodeEnd = cursorRow < endPosition.row || (cursorRow === endPosition.row && cursorColumn <= endPosition.column); return isCursorAfterNodeStart && isCursorBeforeNodeEnd; } static #isCursorRightAfterNode(cursorPosition: Point, endPosition: Point): boolean { const { row: cursorRow, column: cursorColumn } = cursorPosition; const isCursorRightAfterNode = cursorRow - endPosition.row === 1 || (cursorRow === endPosition.row && cursorColumn > endPosition.column); return isCursorRightAfterNode; } static #findEmptyBodyPosition(node: SyntaxNode): { startPosition?: Point; endPosition?: Point } { const startPosition = node.lastChild?.previousSibling?.endPosition; const endPosition = node.lastChild?.startPosition; return { startPosition, endPosition }; } static #isValidBodyPosition(arg: { startPosition?: Point; endPosition?: Point; }): arg is { startPosition: Point; endPosition: Point } { return !isUndefined(arg.startPosition) && !isUndefined(arg.endPosition); } static isCursorAfterEmptyPythonFunction({ languageName, tree, cursorPosition, treeSitterLanguage, }: { languageName: TreeSitterLanguageName; tree: Tree; treeSitterLanguage: Language; cursorPosition: Point; }): boolean { if (languageName !== 'python') return false; const pythonQuery = treeSitterLanguage.query(`[ (function_definition) (class_definition) ] @function`); const captures = pythonQuery.captures(tree.rootNode); if (captures.length === 0) return false; // Check if any function or class body is empty and cursor is after it return captures.some((capture) => { const bodyNode = capture.node.childForFieldName('body'); return ( bodyNode?.childCount === 0 && EmptyFunctionResolver.#isCursorRightAfterNode(cursorPosition, capture.node.endPosition) ); }); } } let emptyFunctionResolver: EmptyFunctionResolver; export function getEmptyFunctionResolver(): EmptyFunctionResolver { if (!emptyFunctionResolver) { emptyFunctionResolver = new EmptyFunctionResolver(); } return emptyFunctionResolver; } References:" You are a code assistant,Definition of 'StateCheck' in file src/common/feature_state/state_check.ts in project gitlab-lsp,"Definition: export interface StateCheck { id: StateCheckId; engaged: boolean; /** registers a listener that's called when the policy changes */ onChanged: (listener: (data: StateCheckChangedEventData) => void) => Disposable; details?: string; } References:" You are a code assistant,Definition of 'onOpen' in file src/common/circuit_breaker/fixed_time_circuit_breaker.ts in project gitlab-lsp,"Definition: 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:" You are a code assistant,Definition of 'start' in file src/common/tracking/snowplow/emitter.ts in project gitlab-lsp,"Definition: 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:" You are a code assistant,Definition of 'updateCodeSuggestionsContext' in file src/common/tracking/multi_tracker.ts in project gitlab-lsp,"Definition: updateCodeSuggestionsContext( uniqueTrackingId: string, contextUpdate: Partial, ) { 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 'RequestHandler' in file packages/lib_webview/src/setup/plugin/webview_instance_message_bus.ts in project gitlab-lsp,"Definition: type RequestHandler = (requestId: RequestId, payload: unknown) => void; type ResponseHandler = (message: ResponseMessage) => void; export class WebviewInstanceMessageBus implements WebviewMessageBus, Disposable { #address: WebviewAddress; #runtimeMessageBus: WebviewRuntimeMessageBus; #eventSubscriptions = new CompositeDisposable(); #notificationEvents = new SimpleRegistry(); #requestEvents = new SimpleRegistry(); #pendingResponseEvents = new SimpleRegistry(); #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 { 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); } 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 'on' in file packages/lib_webview_transport_json_rpc/src/json_rpc_connection_transport.ts in project gitlab-lsp,"Definition: on( type: K, callback: TransportMessageHandler, ): Disposable { this.#messageEmitter.on(type, callback as WebviewTransportEventEmitterMessages[K]); return { dispose: () => this.#messageEmitter.off(type, callback as WebviewTransportEventEmitterMessages[K]), }; } publish(type: K, payload: MessagesToClient[K]): Promise { if (type === 'webview_instance_notification') { return this.#connection.sendNotification(this.#notificationChannel, payload); } throw new Error(`Unknown message type: ${type}`); } dispose(): void { this.#messageEmitter.removeAllListeners(); this.#disposables.forEach((disposable) => disposable.dispose()); this.#logger?.debug('JsonRpcConnectionTransport disposed'); } } References:" You are a code assistant,Definition of 'WORKFLOW_MESSAGE_NOTIFICATION' in file src/common/message_handler.ts in project gitlab-lsp,"Definition: 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 => { 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:" You are a code assistant,Definition of 'resolveMessageBus' in file packages/lib_webview_client/src/bus/resolve_message_bus.ts in project gitlab-lsp,"Definition: export function resolveMessageBus( params: ResolveMessageBusParams, ): MessageBus { const { webviewId } = params; const logger = params.logger || new NullLogger(); const providers = params.providers || getDefaultProviders(); for (const provider of providers) { const bus = getMessageBusFromProviderSafe(webviewId, provider, logger); if (bus) { return bus; } } throw new Error(`Unable to resolve a message bus for webviewId: ${webviewId}`); } function getMessageBusFromProviderSafe( webviewId: string, provider: MessageBusProvider, logger: Logger, ): MessageBus | null { try { logger.debug(`Trying to resolve message bus from provider: ${provider.name}`); const bus = provider.getMessageBus(webviewId); logger.debug(`Message bus resolved from provider: ${provider.name}`); return bus; } catch (error) { logger.debug('Failed to resolve message bus', error as Error); return null; } } References: - packages/webview-chat/src/app/index.ts:6 - packages/webview_duo_workflow/src/app/index.ts:6 - packages/webview_duo_workflow/src/app/message_bus.ts:4 - packages/lib_webview_client/src/bus/resolve_message_bus.test.ts:66 - packages/lib_webview_client/src/bus/resolve_message_bus.test.ts:31 - packages/webview_duo_chat/src/app/message_bus.ts:4 - packages/lib_webview_client/src/bus/resolve_message_bus.test.ts:48" You are a code assistant,Definition of 'WebviewInstanceNotificationEventData' in file packages/lib_webview_transport/src/types.ts in project gitlab-lsp,"Definition: export type WebviewInstanceNotificationEventData = WebviewAddress & WebviewEventInfo; export type WebviewInstanceRequestEventData = WebviewAddress & WebviewEventInfo & WebviewRequestInfo; export type SuccessfulResponse = { success: true; }; export type FailedResponse = { success: false; reason: string; }; export type WebviewInstanceResponseEventData = WebviewAddress & WebviewRequestInfo & WebviewEventInfo & (SuccessfulResponse | FailedResponse); export type MessagesToServer = { webview_instance_created: WebviewInstanceCreatedEventData; webview_instance_destroyed: WebviewInstanceDestroyedEventData; webview_instance_notification_received: WebviewInstanceNotificationEventData; webview_instance_request_received: WebviewInstanceRequestEventData; webview_instance_response_received: WebviewInstanceResponseEventData; }; export type MessagesToClient = { webview_instance_notification: WebviewInstanceNotificationEventData; webview_instance_request: WebviewInstanceRequestEventData; webview_instance_response: WebviewInstanceResponseEventData; }; export interface TransportMessageHandler { (payload: T): void; } export interface TransportListener { on( type: K, callback: TransportMessageHandler, ): Disposable; } export interface TransportPublisher { publish(type: K, payload: MessagesToClient[K]): Promise; } export interface Transport extends TransportListener, TransportPublisher {} References: - packages/lib_webview_transport/src/types.ts:48 - packages/lib_webview_transport/src/types.ts:42" 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 { 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 'isInvalidToken' in file src/common/fetch_error.ts in project gitlab-lsp,"Definition: 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:" You are a code assistant,Definition of 'WebviewAddress' in file packages/lib_webview_plugin/src/types.ts in project gitlab-lsp,"Definition: export type WebviewAddress = { webviewId: WebviewId; webviewInstanceId: WebviewInstanceId; }; export type WebviewMessageBusManagerHandler = ( webviewInstanceId: WebviewInstanceId, messageBus: MessageBus, // eslint-disable-next-line @typescript-eslint/no-invalid-void-type ) => Disposable | void; export interface WebviewConnection { broadcast: ( type: TMethod, payload: T['outbound']['notifications'][TMethod], ) => void; onInstanceConnected: (handler: WebviewMessageBusManagerHandler) => void; } References: - packages/lib_webview/src/setup/plugin/webview_controller.ts:88 - packages/lib_webview/src/setup/plugin/webview_instance_message_bus.test.ts:15 - packages/lib_webview/src/setup/plugin/webview_instance_message_bus.ts:33 - packages/lib_webview/src/setup/plugin/setup_plugins.ts:30 - packages/lib_webview/src/setup/plugin/utils/filters.ts:10 - packages/lib_webview/src/setup/plugin/webview_controller.test.ts:15 - packages/lib_webview/src/setup/transport/utils/setup_transport_event_handlers.ts:16 - packages/lib_webview/src/setup/plugin/webview_instance_message_bus.ts:18 - packages/lib_webview/src/events/webview_runtime_message_bus.ts:31 - packages/lib_webview/src/setup/transport/utils/setup_transport_event_handlers.ts:12 - packages/lib_webview/src/setup/plugin/webview_instance_message_bus.test.ts:8 - packages/lib_webview/src/setup/plugin/webview_controller.test.ts:175 - packages/lib_webview/src/events/webview_runtime_message_bus.ts:30 - packages/lib_webview/src/setup/plugin/webview_controller.test.ts:219 - packages/lib_webview/src/setup/plugin/webview_controller.ts:112 - packages/lib_webview/src/setup/plugin/webview_instance_message_bus.test.ts:331 - packages/lib_webview/src/setup/plugin/webview_controller.ts:21" You are a code assistant,Definition of 'DEFAULT_SCANNER_SERVICE_URL' in file src/common/security_diagnostics_publisher.ts in project gitlab-lsp,"Definition: export const DEFAULT_SCANNER_SERVICE_URL = ''; interface Vulnerability { name: string; description: string; severity: string; location: { start_line: number; end_line: number }; } export interface SecurityDiagnosticsPublisher extends DiagnosticsPublisher {} export const SecurityDiagnosticsPublisher = createInterfaceId( '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, 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:" You are a code assistant,Definition of 'WebviewMessageBusFactory' in file packages/lib_webview/src/setup/plugin/webview_controller.ts in project gitlab-lsp,"Definition: export interface WebviewMessageBusFactory { (webviewAddress: WebviewAddress): WebviewInstanceMessageBus; } export class WebviewController implements WebviewConnection, Disposable { readonly webviewId: WebviewId; #messageBusFactory: WebviewMessageBusFactory; #handlers = new Set>(); #instanceInfos = new Map(); #compositeDisposable = new CompositeDisposable(); #logger: Logger; constructor( webviewId: WebviewId, runtimeMessageBus: WebviewRuntimeMessageBus, messageBusFactory: WebviewMessageBusFactory, logger: Logger, ) { this.#logger = withPrefix(logger, `[WebviewController:${webviewId}]`); this.webviewId = webviewId; this.#messageBusFactory = messageBusFactory; this.#subscribeToEvents(runtimeMessageBus); } broadcast( type: TMethod, payload: T['outbound']['notifications'][TMethod], ) { for (const info of this.#instanceInfos.values()) { info.messageBus.sendNotification(type.toString(), payload); } } onInstanceConnected(handler: WebviewMessageBusManagerHandler) { this.#handlers.add(handler); for (const [instanceId, info] of this.#instanceInfos) { const disposable = handler(instanceId, info.messageBus); if (isDisposable(disposable)) { info.pluginCallbackDisposables.add(disposable); } } } dispose(): void { this.#compositeDisposable.dispose(); this.#instanceInfos.forEach((info) => info.messageBus.dispose()); this.#instanceInfos.clear(); } #subscribeToEvents(runtimeMessageBus: WebviewRuntimeMessageBus) { const eventFilter = buildWebviewIdFilter(this.webviewId); this.#compositeDisposable.add( runtimeMessageBus.subscribe('webview:connect', this.#handleConnected.bind(this), eventFilter), runtimeMessageBus.subscribe( 'webview:disconnect', this.#handleDisconnected.bind(this), eventFilter, ), ); } #handleConnected(address: WebviewAddress) { this.#logger.debug(`Instance connected: ${address.webviewInstanceId}`); if (this.#instanceInfos.has(address.webviewInstanceId)) { // we are already connected with this webview instance return; } const messageBus = this.#messageBusFactory(address); const pluginCallbackDisposables = new CompositeDisposable(); this.#instanceInfos.set(address.webviewInstanceId, { messageBus, pluginCallbackDisposables, }); this.#handlers.forEach((handler) => { const disposable = handler(address.webviewInstanceId, messageBus); if (isDisposable(disposable)) { pluginCallbackDisposables.add(disposable); } }); } #handleDisconnected(address: WebviewAddress) { this.#logger.debug(`Instance disconnected: ${address.webviewInstanceId}`); const instanceInfo = this.#instanceInfos.get(address.webviewInstanceId); if (!instanceInfo) { // we aren't tracking this instance return; } instanceInfo.pluginCallbackDisposables.dispose(); instanceInfo.messageBus.dispose(); this.#instanceInfos.delete(address.webviewInstanceId); } } References: - packages/lib_webview/src/setup/plugin/webview_controller.ts:40 - packages/lib_webview/src/setup/plugin/webview_controller.ts:27" You are a code assistant,Definition of 'filterContextResolutions' in file src/common/advanced_context/advanced_context_filters.ts in project gitlab-lsp,"Definition: export const filterContextResolutions = async ({ contextResolutions, dependencies, documentContext, byteSizeLimit, }: AdvancedContextFilterArgs): Promise => { return advancedContextFilters.reduce(async (prevPromise, filter) => { const resolutions = await prevPromise; return filter({ contextResolutions: resolutions, dependencies, documentContext, byteSizeLimit, }); }, Promise.resolve(contextResolutions)); }; References: - src/common/advanced_context/advanced_context_filters.test.ts:132 - src/common/advanced_context/advanced_context_filters.test.ts:176 - src/common/advanced_context/advanced_context_filters.test.ts:295 - src/common/advanced_context/advanced_context_filters.test.ts:75 - src/common/advanced_context/advanced_context_filters.test.ts:228 - src/common/advanced_context/advanced_context_factory.ts:35" 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 interface AiContextAggregator extends DefaultAiContextAggregator {} export const AiContextAggregator = createInterfaceId('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 { 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 { 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:66 - src/common/connection_service.ts:55" You are a code assistant,Definition of 'C' in file packages/lib_di/src/index.test.ts in project gitlab-lsp,"Definition: interface C { c(): string; } const A = createInterfaceId('A'); const B = createInterfaceId('B'); const C = createInterfaceId('C'); @Injectable(A, []) class AImpl implements A { a = () => 'a'; } @Injectable(B, [A]) class BImpl implements B { #a: A; constructor(a: A) { this.#a = a; } b = () => `B(${this.#a.a()})`; } @Injectable(C, [A, B]) class CImpl implements C { #a: A; #b: B; constructor(a: A, b: B) { this.#a = a; this.#b = b; } c = () => `C(${this.#b.b()}, ${this.#a.a()})`; } let container: Container; beforeEach(() => { container = new Container(); }); describe('addInstances', () => { const O = createInterfaceId('object'); it('fails if the instance is not branded', () => { expect(() => container.addInstances({ say: 'hello' } as BrandedInstance)).toThrow( /invoked without branded object/, ); }); it('fails if the instance is already present', () => { const a = brandInstance(O, { a: 'a' }); const b = brandInstance(O, { b: 'b' }); expect(() => container.addInstances(a, b)).toThrow(/this ID is already in the container/); }); it('adds instance', () => { const instance = { a: 'a' }; const a = brandInstance(O, instance); container.addInstances(a); expect(container.get(O)).toBe(instance); }); }); describe('instantiate', () => { it('can instantiate three classes A,B,C', () => { container.instantiate(AImpl, BImpl, CImpl); const cInstance = container.get(C); expect(cInstance.c()).toBe('C(B(a), a)'); }); it('instantiates dependencies in multiple instantiate calls', () => { container.instantiate(AImpl); // the order is important for this test // we want to make sure that the stack in circular dependency discovery is being cleared // to try why this order is necessary, remove the `inStack.delete()` from // the `if (!cwd && instanceIds.includes(id))` condition in prod code expect(() => container.instantiate(CImpl, BImpl)).not.toThrow(); }); it('detects duplicate ids', () => { @Injectable(A, []) 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: - packages/lib_di/src/index.test.ts:146" You are a code assistant,Definition of 'constructor' in file packages/lib_di/src/index.test.ts in project gitlab-lsp,"Definition: 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 'DefaultAiContextFileRetriever' in file src/common/ai_context_management_2/retrievers/ai_file_context_retriever.ts in project gitlab-lsp,"Definition: export class DefaultAiContextFileRetriever implements AiContextRetriever { constructor( private fileResolver: FileResolver, private secretRedactor: SecretRedactor, ) {} async retrieve(aiContextItem: AiContextItem): Promise { if (aiContextItem.type !== 'file') { return null; } try { log.info(`retrieving file ${aiContextItem.id}`); const fileContent = await this.fileResolver.readFile({ fileUri: aiContextItem.id, }); log.info(`redacting secrets for file ${aiContextItem.id}`); const redactedContent = this.secretRedactor.redactSecrets(fileContent); return redactedContent; } catch (e) { log.warn(`Failed to retrieve file ${aiContextItem.id}`, e); return null; } } } References:" You are a code assistant,Definition of 'Disposable' in file packages/lib_disposable/src/types.ts in project gitlab-lsp,"Definition: export interface Disposable { dispose(): void; } References: - packages/lib_message_bus/src/types/bus.ts:47 - src/common/circuit_breaker/circuit_breaker.ts:17 - src/common/circuit_breaker/exponential_backoff_circuit_breaker.ts:95 - src/common/feature_state/supported_language_check.ts:45 - packages/lib_webview_client/src/bus/provider/socket_io_message_bus.ts:72 - packages/lib_webview/src/setup/plugin/webview_instance_message_bus.ts:139 - packages/lib_message_bus/src/types/bus.ts:103 - packages/lib_webview/src/setup/setup_webview_runtime.ts:17 - packages/lib_webview_transport_socket_io/src/socket_io_webview_transport.ts:172 - src/common/services/duo_access/project_access_cache.ts:240 - packages/lib_webview/src/setup/transport/setup_transport.ts:12 - src/common/api.ts:149 - packages/lib_webview/src/events/message_bus.ts:18 - packages/lib_disposable/src/composite_disposable.test.ts:6 - packages/lib_webview/src/setup/plugin/webview_instance_message_bus.ts:99 - packages/lib_webview_transport_json_rpc/src/json_rpc_connection_transport.ts:105 - src/common/circuit_breaker/fixed_time_circuit_breaker.ts:75 - src/common/suggestion/supported_languages_service.ts:21 - src/common/suggestion/supported_languages_service.ts:107 - packages/lib_message_bus/src/types/bus.ts:51 - src/common/circuit_breaker/exponential_backoff_circuit_breaker.ts:90 - src/common/circuit_breaker/circuit_breaker.ts:18 - src/common/core/handlers/token_check_notifier.test.ts:18 - packages/lib_webview/src/setup/transport/setup_transport.ts:39 - packages/lib_handler_registry/src/registry/simple_registry.ts:14 - src/common/config_service.ts:142 - packages/lib_disposable/src/composite_disposable.test.ts:7 - src/common/api.ts:32 - packages/lib_handler_registry/src/types.ts:9 - src/common/webview/extension/extension_connection_message_bus.ts:37 - src/common/config_service.ts:94 - src/common/advanced_context/advanced_context_service.test.ts:24 - src/common/webview/extension/extension_connection_message_bus.ts:44 - src/common/circuit_breaker/fixed_time_circuit_breaker.ts:80 - packages/lib_webview_transport_json_rpc/src/json_rpc_connection_transport.test.ts:13 - src/common/services/duo_access/project_access_cache.ts:79 - packages/lib_message_bus/src/types/bus.ts:107 - packages/lib_webview_transport/src/types.ts:61 - src/common/feature_state/project_duo_acces_check.ts:68 - src/common/document_service.ts:19 - packages/lib_webview_client/src/bus/provider/socket_io_message_bus.ts:81 - packages/lib_webview/src/events/utils/subscribe.ts:8 - packages/lib_handler_registry/src/registry/hashed_registry.ts:23" You are a code assistant,Definition of 'cleanChat' in file packages/webview_duo_chat/src/plugin/port/chat/gitlab_chat_api.ts in project gitlab-lsp,"Definition: async cleanChat(): Promise { return this.#sendAiAction({ question: SPECIAL_MESSAGES.CLEAN }); } async #currentPlatform() { const platform = await this.#manager.getGitLabPlatform(); if (!platform) throw new Error('Platform is missing!'); return platform; } async #getAiMessage(requestId: string, role: string): Promise { const request: GraphQLRequest = { type: 'graphql', query: AI_MESSAGES_QUERY, variables: { requestIds: [requestId], roles: [role.toUpperCase()] }, }; const platform = await this.#currentPlatform(); const history = await platform.fetchFromApi(request); return history.aiMessages.nodes[0]; } async subscribeToUpdates( messageCallback: (message: AiCompletionResponseMessageType) => Promise, subscriptionId?: string, ) { const platform = await this.#currentPlatform(); const channel = new AiCompletionResponseChannel({ htmlResponse: true, userId: `gid://gitlab/User/${extractUserId(platform.account.id)}`, aiAction: 'CHAT', clientSubscriptionId: subscriptionId, }); const cable = await platform.connectToCable(); // we use this flag to fix https://gitlab.com/gitlab-org/gitlab-vscode-extension/-/issues/1397 // sometimes a chunk comes after the full message and it broke the chat let fullMessageReceived = false; channel.on('newChunk', async (msg) => { if (fullMessageReceived) { log.info(`CHAT-DEBUG: full message received, ignoring chunk`); return; } await messageCallback(msg); }); channel.on('fullMessage', async (message) => { fullMessageReceived = true; await messageCallback(message); if (subscriptionId) { cable.disconnect(); } }); cable.subscribe(channel); } async #sendAiAction(variables: object): Promise { const platform = await this.#currentPlatform(); const { query, defaultVariables } = await this.#actionQuery(); const projectGqlId = await this.#manager.getProjectGqlId(); const request: GraphQLRequest = { type: 'graphql', query, variables: { ...variables, ...defaultVariables, resourceId: projectGqlId ?? null, }, }; return platform.fetchFromApi(request); } async #actionQuery(): Promise { if (!this.#cachedActionQuery) { const platform = await this.#currentPlatform(); try { const { version } = await platform.fetchFromApi(versionRequest); this.#cachedActionQuery = ifVersionGte( version, MINIMUM_PLATFORM_ORIGIN_FIELD_VERSION, () => CHAT_INPUT_TEMPLATE_17_3_AND_LATER, () => CHAT_INPUT_TEMPLATE_17_2_AND_EARLIER, ); } catch (e) { log.debug(`GitLab version check for sending chat failed:`, e as Error); this.#cachedActionQuery = CHAT_INPUT_TEMPLATE_17_3_AND_LATER; } } return this.#cachedActionQuery; } } References:" You are a code assistant,Definition of 'getCodeSuggestions' in file src/common/api.ts in project gitlab-lsp,"Definition: async getCodeSuggestions( request: CodeSuggestionRequest, ): Promise { if (!this.#token) { throw new Error('Token needs to be provided to request Code Suggestions'); } const headers = { ...this.#getDefaultHeaders(this.#token), 'Content-Type': 'application/json', }; const response = await this.#lsFetch.post( `${this.#baseURL}/api/v4/code_suggestions/completions`, { headers, body: JSON.stringify(request) }, ); await handleFetchError(response, 'Code Suggestions'); const data = await response.json(); return { ...data, status: response.status }; } async *getStreamingCodeSuggestions( request: CodeSuggestionRequest, ): AsyncGenerator { if (!this.#token) { throw new Error('Token needs to be provided to stream code suggestions'); } const headers = { ...this.#getDefaultHeaders(this.#token), 'Content-Type': 'application/json', }; yield* this.#lsFetch.streamFetch( `${this.#baseURL}/api/v4/code_suggestions/completions`, JSON.stringify(request), headers, ); } async fetchFromApi(request: ApiRequest): Promise { if (!this.#token) { return Promise.reject(new Error('Token needs to be provided to authorise API request.')); } if ( request.supportedSinceInstanceVersion && !this.#instanceVersionHigherOrEqualThen(request.supportedSinceInstanceVersion.version) ) { return Promise.reject( new InvalidInstanceVersionError( `Can't ${request.supportedSinceInstanceVersion.resourceName} until your instance is upgraded to ${request.supportedSinceInstanceVersion.version} or higher.`, ), ); } if (request.type === 'graphql') { return this.#graphqlRequest(request.query, request.variables); } switch (request.method) { case 'GET': return this.#fetch(request.path, request.searchParams, 'resource', request.headers); case 'POST': return this.#postFetch(request.path, 'resource', request.body, request.headers); default: // the type assertion is necessary because TS doesn't expect any other types throw new Error(`Unknown request type ${(request as ApiRequest).type}`); } } async connectToCable(): Promise { const headers = this.#getDefaultHeaders(this.#token); const websocketOptions = { headers: { ...headers, Origin: this.#baseURL, }, }; return connectToCable(this.#baseURL, websocketOptions); } async #graphqlRequest( document: RequestDocument, variables?: V, ): Promise { const ensureEndsWithSlash = (url: string) => url.replace(/\/?$/, '/'); const endpoint = new URL('./api/graphql', ensureEndsWithSlash(this.#baseURL)).href; // supports GitLab instances that are on a custom path, e.g. ""https://example.com/gitlab"" const graphqlFetch = async ( input: RequestInfo | URL, init?: RequestInit, ): Promise => { const url = input instanceof URL ? input.toString() : input; return this.#lsFetch.post(url, { ...init, headers: { ...headers, ...init?.headers }, }); }; const headers = this.#getDefaultHeaders(this.#token); const client = new GraphQLClient(endpoint, { headers, fetch: graphqlFetch, }); return client.request(document, variables); } async #fetch( apiResourcePath: string, query: Record = {}, resourceName = 'resource', headers?: Record, ): Promise { const url = `${this.#baseURL}/api/v4${apiResourcePath}${createQueryString(query)}`; const result = await this.#lsFetch.get(url, { headers: { ...this.#getDefaultHeaders(this.#token), ...headers }, }); await handleFetchError(result, resourceName); return result.json() as Promise; } async #postFetch( apiResourcePath: string, resourceName = 'resource', body?: unknown, headers?: Record, ): Promise { const url = `${this.#baseURL}/api/v4${apiResourcePath}`; const response = await this.#lsFetch.post(url, { headers: { 'Content-Type': 'application/json', ...this.#getDefaultHeaders(this.#token), ...headers, }, body: JSON.stringify(body), }); await handleFetchError(response, resourceName); return response.json() as Promise; } #getDefaultHeaders(token?: string) { return { Authorization: `Bearer ${token}`, 'User-Agent': `code-completions-language-server-experiment (${this.#clientInfo?.name}:${this.#clientInfo?.version})`, 'X-Gitlab-Language-Server-Version': getLanguageServerVersion(), }; } #instanceVersionHigherOrEqualThen(version: string): boolean { if (!this.#instanceVersion) return false; return semverCompare(this.#instanceVersion, version) >= 0; } async #getGitLabInstanceVersion(): Promise { if (!this.#token) { return ''; } const headers = this.#getDefaultHeaders(this.#token); const response = await this.#lsFetch.get(`${this.#baseURL}/api/v4/version`, { headers, }); const { version } = await response.json(); return version; } get instanceVersion() { return this.#instanceVersion; } } References:" You are a code assistant,Definition of 'toEventuallyContainChildProcessConsoleOutput' in file src/tests/int/test_utils.ts in project gitlab-lsp,"Definition: async toEventuallyContainChildProcessConsoleOutput( lsClient: LspClient, expectedMessage: string, timeoutMs = 1000, intervalMs = 25, ) { const expectedResult = `Expected language service child process console output to contain ""${expectedMessage}""`; const checkOutput = () => lsClient.childProcessConsole.some((line) => line.includes(expectedMessage)); const sleep = () => new Promise((resolve) => { setTimeout(resolve, intervalMs); }); let remainingRetries = Math.ceil(timeoutMs / intervalMs); while (remainingRetries > 0) { if (checkOutput()) { return { message: () => expectedResult, pass: true, }; } // eslint-disable-next-line no-await-in-loop await sleep(); remainingRetries--; } return { message: () => `""${expectedResult}"", but it was not found within ${timeoutMs}ms`, pass: false, }; }, }); References:" You are a code assistant,Definition of 'startStream' in file src/common/suggestion/streaming_handler.ts in project gitlab-lsp,"Definition: async startStream() { return startStreaming(this.#params); } } const startStreaming = async ({ additionalContexts, api, circuitBreaker, connection, documentContext, parser, postProcessorPipeline, streamId, tracker, uniqueTrackingId, userInstruction, generationType, }: StartStreamParams) => { const language = parser.getLanguageNameForFile(documentContext.fileRelativePath); tracker.setCodeSuggestionsContext(uniqueTrackingId, { documentContext, additionalContexts, source: SuggestionSource.network, language, isStreaming: true, }); let streamShown = false; let suggestionProvided = false; let streamCancelledOrErrored = false; const cancellationTokenSource = new CancellationTokenSource(); const disposeStopStreaming = connection.onNotification(CancelStreaming, (stream) => { if (stream.id === streamId) { streamCancelledOrErrored = true; cancellationTokenSource.cancel(); if (streamShown) { tracker.updateSuggestionState(uniqueTrackingId, TRACKING_EVENTS.REJECTED); } else { tracker.updateSuggestionState(uniqueTrackingId, TRACKING_EVENTS.CANCELLED); } } }); const cancellationToken = cancellationTokenSource.token; const endStream = async () => { await connection.sendNotification(StreamingCompletionResponse, { id: streamId, done: true, }); if (!streamCancelledOrErrored) { tracker.updateSuggestionState(uniqueTrackingId, TRACKING_EVENTS.STREAM_COMPLETED); if (!suggestionProvided) { tracker.updateSuggestionState(uniqueTrackingId, TRACKING_EVENTS.NOT_PROVIDED); } } }; circuitBreaker.success(); const request: CodeSuggestionRequest = { prompt_version: 1, project_path: '', project_id: -1, current_file: { content_above_cursor: documentContext.prefix, content_below_cursor: documentContext.suffix, file_name: documentContext.fileRelativePath, }, intent: 'generation', stream: true, ...(additionalContexts?.length && { context: additionalContexts, }), ...(userInstruction && { user_instruction: userInstruction, }), generation_type: generationType, }; const trackStreamStarted = once(() => { tracker.updateSuggestionState(uniqueTrackingId, TRACKING_EVENTS.STREAM_STARTED); }); const trackStreamShown = once(() => { tracker.updateSuggestionState(uniqueTrackingId, TRACKING_EVENTS.SHOWN); streamShown = true; }); try { for await (const response of api.getStreamingCodeSuggestions(request)) { if (cancellationToken.isCancellationRequested) { break; } if (circuitBreaker.isOpen()) { break; } trackStreamStarted(); const processedCompletion = await postProcessorPipeline.run({ documentContext, input: { id: streamId, completion: response, done: false }, type: 'stream', }); await connection.sendNotification(StreamingCompletionResponse, processedCompletion); if (response.replace(/\s/g, '').length) { trackStreamShown(); suggestionProvided = true; } } } catch (err) { circuitBreaker.error(); if (isFetchError(err)) { tracker.updateCodeSuggestionsContext(uniqueTrackingId, { status: err.status }); } tracker.updateSuggestionState(uniqueTrackingId, TRACKING_EVENTS.ERRORED); streamCancelledOrErrored = true; log.error('Error streaming code suggestions.', err); } finally { await endStream(); disposeStopStreaming.dispose(); cancellationTokenSource.dispose(); } }; References: - src/common/suggestion/streaming_handler.test.ts:156 - src/common/suggestion/streaming_handler.test.ts:305 - src/common/suggestion/streaming_handler.test.ts:119 - src/common/suggestion/streaming_handler.test.ts:362 - src/common/suggestion/streaming_handler.test.ts:268 - src/common/suggestion/streaming_handler.test.ts:104 - src/common/suggestion/streaming_handler.test.ts:328 - src/common/suggestion/streaming_handler.test.ts:170 - src/common/suggestion/streaming_handler.test.ts:227 - src/common/suggestion/streaming_handler.test.ts:185 - src/common/suggestion/streaming_handler.test.ts:420 - src/common/suggestion/streaming_handler.test.ts:246 - src/common/suggestion/streaming_handler.test.ts:383 - src/common/suggestion/streaming_handler.test.ts:256" You are a code assistant,Definition of 'ExtensionConnectionMessageBusProviderProps' in file src/common/webview/extension/extension_connection_message_bus_provider.ts in project gitlab-lsp,"Definition: type ExtensionConnectionMessageBusProviderProps = { connection: Connection; logger: Logger; notificationRpcMethod?: string; requestRpcMethod?: string; }; export class ExtensionConnectionMessageBusProvider implements ExtensionMessageBusProvider, Disposable { #connection: Connection; #rpcMethods: RpcMethods; #handlers: Handlers; #logger: Logger; #notificationHandlers = new ExtensionMessageHandlerRegistry(); #requestHandlers = new ExtensionMessageHandlerRegistry(); #disposables = new CompositeDisposable(); constructor({ connection, logger, notificationRpcMethod = DEFAULT_NOTIFICATION_RPC_METHOD, requestRpcMethod = DEFAULT_REQUEST_RPC_METHOD, }: ExtensionConnectionMessageBusProviderProps) { this.#connection = connection; this.#logger = withPrefix(logger, '[ExtensionConnectionMessageBusProvider]'); this.#rpcMethods = { notification: notificationRpcMethod, request: requestRpcMethod, }; this.#handlers = { notification: new ExtensionMessageHandlerRegistry(), request: new ExtensionMessageHandlerRegistry(), }; this.#setupConnectionSubscriptions(); } getMessageBus(webviewId: WebviewId): MessageBus { return new ExtensionConnectionMessageBus({ webviewId, connection: this.#connection, rpcMethods: this.#rpcMethods, handlers: this.#handlers, }); } dispose(): void { this.#disposables.dispose(); } #setupConnectionSubscriptions() { this.#disposables.add( this.#connection.onNotification( this.#rpcMethods.notification, handleNotificationMessage(this.#notificationHandlers, this.#logger), ), ); this.#disposables.add( this.#connection.onRequest( this.#rpcMethods.request, handleRequestMessage(this.#requestHandlers, this.#logger), ), ); } } References: - src/common/webview/extension/extension_connection_message_bus_provider.ts:45" You are a code assistant,Definition of 'Listener' in file packages/lib_webview/src/events/message_bus.ts in project gitlab-lsp,"Definition: type Listener = (data: T) => void; type FilterFunction = (data: T) => boolean; interface Subscription { listener: Listener; filter?: FilterFunction; } export class MessageBus> implements Disposable { #subscriptions = new Map>>(); public subscribe( messageType: K, listener: Listener, filter?: FilterFunction, ): Disposable { const subscriptions = this.#subscriptions.get(messageType) ?? new Set>(); const subscription: Subscription = { listener: listener as Listener, filter: filter as FilterFunction | undefined, }; subscriptions.add(subscription); this.#subscriptions.set(messageType, subscriptions); return { dispose: () => { const targetSubscriptions = this.#subscriptions.get(messageType); if (targetSubscriptions) { targetSubscriptions.delete(subscription); if (targetSubscriptions.size === 0) { this.#subscriptions.delete(messageType); } } }, }; } public publish(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; if (!filter || filter(data)) { listener(data); } }); } } public hasListeners(messageType: K): boolean { return this.#subscriptions.has(messageType); } public listenerCount(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 'SPECIAL_MESSAGES' in file packages/webview_duo_chat/src/plugin/port/chat/constants.ts in project gitlab-lsp,"Definition: export const SPECIAL_MESSAGES = { RESET: '/reset', CLEAN: '/clean', }; export const PLATFORM_ORIGIN = 'vs_code_extension'; References:" You are a code assistant,Definition of 'processStream' in file src/common/suggestion_client/post_processors/post_processor_pipeline.test.ts in project gitlab-lsp,"Definition: async processStream( _context: IDocContext, input: StreamingCompletionResponse, ): Promise { return { ...input, completion: `${input.completion} [2]` }; } async processCompletion( _context: IDocContext, input: SuggestionOption[], ): Promise { return input; } } pipeline.addProcessor(new Processor1()); pipeline.addProcessor(new Processor2()); const streamInput: StreamingCompletionResponse = { id: '1', completion: 'test', done: false }; const result = await pipeline.run({ documentContext: mockContext, input: streamInput, type: 'stream', }); expect(result).toEqual({ id: '1', completion: 'test [1] [2]', done: false }); }); test('should chain multiple processors correctly for completion input', async () => { class Processor1 extends PostProcessor { async processStream( _context: IDocContext, input: StreamingCompletionResponse, ): Promise { return input; } async processCompletion( _context: IDocContext, input: SuggestionOption[], ): Promise { return input.map((option) => ({ ...option, text: `${option.text} [1]` })); } } class Processor2 extends PostProcessor { async processStream( _context: IDocContext, input: StreamingCompletionResponse, ): Promise { return input; } async processCompletion( _context: IDocContext, input: SuggestionOption[], ): Promise { return input.map((option) => ({ ...option, text: `${option.text} [2]` })); } } pipeline.addProcessor(new Processor1()); pipeline.addProcessor(new Processor2()); const completionInput: SuggestionOption[] = [{ text: 'option1', uniqueTrackingId: '1' }]; const result = await pipeline.run({ documentContext: mockContext, input: completionInput, type: 'completion', }); expect(result).toEqual([{ text: 'option1 [1] [2]', uniqueTrackingId: '1' }]); }); test('should throw an error for unexpected type', async () => { class TestProcessor extends PostProcessor { async processStream( _context: IDocContext, input: StreamingCompletionResponse, ): Promise { return input; } async processCompletion( _context: IDocContext, input: SuggestionOption[], ): Promise { 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 'streamFetch' in file src/common/fetch.ts in project gitlab-lsp,"Definition: async *streamFetch( /* eslint-disable @typescript-eslint/no-unused-vars */ _url: string, _body: string, _headers: FetchHeaders, /* eslint-enable @typescript-eslint/no-unused-vars */ ): AsyncGenerator { // Stub. Should delegate to the node or browser fetch implementations throw new Error('Not implemented'); yield ''; } async delete(input: RequestInfo | URL, init?: RequestInit): Promise { return this.fetch(input, this.updateRequestInit('DELETE', init)); } async get(input: RequestInfo | URL, init?: RequestInit): Promise { return this.fetch(input, this.updateRequestInit('GET', init)); } async post(input: RequestInfo | URL, init?: RequestInit): Promise { return this.fetch(input, this.updateRequestInit('POST', init)); } async put(input: RequestInfo | URL, init?: RequestInit): Promise { return this.fetch(input, this.updateRequestInit('PUT', init)); } async fetchBase(input: RequestInfo | URL, init?: RequestInit): Promise { // 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 'BImpl' in file packages/lib_di/src/index.test.ts in project gitlab-lsp,"Definition: class BImpl implements B { #a: A; constructor(a: A) { this.#a = a; } b = () => `B(${this.#a.a()})`; } @Injectable(C, [A, B]) class CImpl implements C { #a: A; #b: B; constructor(a: A, b: B) { this.#a = a; this.#b = b; } c = () => `C(${this.#b.b()}, ${this.#a.a()})`; } let container: Container; beforeEach(() => { container = new Container(); }); describe('addInstances', () => { const O = createInterfaceId('object'); it('fails if the instance is not branded', () => { expect(() => container.addInstances({ say: 'hello' } as BrandedInstance)).toThrow( /invoked without branded object/, ); }); it('fails if the instance is already present', () => { const a = brandInstance(O, { a: 'a' }); const b = brandInstance(O, { b: 'b' }); expect(() => container.addInstances(a, b)).toThrow(/this ID is already in the container/); }); it('adds instance', () => { const instance = { a: 'a' }; const a = brandInstance(O, instance); container.addInstances(a); expect(container.get(O)).toBe(instance); }); }); describe('instantiate', () => { it('can instantiate three classes A,B,C', () => { container.instantiate(AImpl, BImpl, CImpl); const cInstance = container.get(C); expect(cInstance.c()).toBe('C(B(a), a)'); }); it('instantiates dependencies in multiple instantiate calls', () => { container.instantiate(AImpl); // the order is important for this test // we want to make sure that the stack in circular dependency discovery is being cleared // to try why this order is necessary, remove the `inStack.delete()` from // the `if (!cwd && instanceIds.includes(id))` condition in prod code expect(() => container.instantiate(CImpl, BImpl)).not.toThrow(); }); it('detects duplicate ids', () => { @Injectable(A, []) 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 'mostRecentFiles' in file src/common/advanced_context/lru_cache.ts in project gitlab-lsp,"Definition: mostRecentFiles({ context, includeCurrentFile = true, }: { context?: IDocContext; includeCurrentFile?: boolean; }): IDocContext[] { const files = Array.from(this.#cache.values()); if (includeCurrentFile) { return files; } return files.filter( (file) => context?.workspaceFolder?.uri === file.workspaceFolder?.uri && file.uri !== context?.uri, ); } } References:" You are a code assistant,Definition of 'WebviewMetadataProvider' in file src/common/webview/webview_metadata_provider.ts in project gitlab-lsp,"Definition: export class WebviewMetadataProvider { #plugins: Set; #accessInfoProviders: WebviewLocationService; constructor(accessInfoProviders: WebviewLocationService, plugins: Set) { this.#accessInfoProviders = accessInfoProviders; this.#plugins = plugins; } getMetadata(): WebviewMetadata[] { return Array.from(this.#plugins).map((plugin) => ({ id: plugin.id, title: plugin.title, uris: this.#accessInfoProviders.resolveUris(plugin.id), })); } } References: - src/node/main.ts:178 - src/common/webview/webview_metadata_provider.test.ts:20 - src/common/webview/webview_metadata_provider.test.ts:25" You are a code assistant,Definition of 'sendRequest' in file packages/lib_message_bus/src/types/bus.ts in project gitlab-lsp,"Definition: sendRequest>( type: T, ): Promise>; sendRequest( type: T, payload: TRequests[T]['params'], ): Promise>; } /** * Interface for listening to requests. * @interface * @template {RequestMap} TRequests */ export interface RequestListener { onRequest>( type: T, handler: () => Promise>, ): Disposable; onRequest( type: T, handler: (payload: TRequests[T]['params']) => Promise>, ): Disposable; } /** * Defines the structure for message definitions, including notifications and requests. */ export type MessageDefinitions< TNotifications extends NotificationMap = NotificationMap, TRequests extends RequestMap = RequestMap, > = { notifications: TNotifications; requests: TRequests; }; export type MessageMap< TInboundMessageDefinitions extends MessageDefinitions = MessageDefinitions, TOutboundMessageDefinitions extends MessageDefinitions = MessageDefinitions, > = { inbound: TInboundMessageDefinitions; outbound: TOutboundMessageDefinitions; }; export interface MessageBus extends NotificationPublisher, NotificationListener, RequestPublisher, RequestListener {} References:" You are a code assistant,Definition of 'sendRequest' in file packages/lib_webview/src/setup/plugin/webview_instance_message_bus.ts in project gitlab-lsp,"Definition: async sendRequest(type: Method, payload?: unknown): Promise { 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); } 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 'getCommentForCursor' in file src/common/tree_sitter/comments/comment_resolver.ts in project gitlab-lsp,"Definition: getCommentForCursor({ languageName, tree, cursorPosition, treeSitterLanguage, }: { languageName: TreeSitterLanguageName; tree: Tree; treeSitterLanguage: Language; cursorPosition: Point; }): CommentResolution | undefined { const query = this.#getQueryByLanguage(languageName, treeSitterLanguage); if (!query) { return undefined; } const comments = query.captures(tree.rootNode).map((capture) => { return { start: capture.node.startPosition, end: capture.node.endPosition, content: capture.node.text, capture, }; }); const commentAtCursor = CommentResolver.#getCommentAtCursor(comments, cursorPosition); if (commentAtCursor) { // No need to further check for isPositionInNode etc. as cursor is directly on the comment return { commentAtCursor }; } const commentAboveCursor = CommentResolver.#getCommentAboveCursor(comments, cursorPosition); if (!commentAboveCursor) { return undefined; } const commentParentNode = commentAboveCursor.capture.node.parent; if (!commentParentNode) { return undefined; } if (!CommentResolver.#isPositionInNode(cursorPosition, commentParentNode)) { return undefined; } const directChildren = commentParentNode.children; for (const child of directChildren) { const hasNodeBetweenCursorAndComment = child.startPosition.row > commentAboveCursor.capture.node.endPosition.row && child.startPosition.row <= cursorPosition.row; if (hasNodeBetweenCursorAndComment) { return undefined; } } return { commentAboveCursor }; } static #isPositionInNode(position: Point, node: SyntaxNode): boolean { return position.row >= node.startPosition.row && position.row <= node.endPosition.row; } static #getCommentAboveCursor(comments: Comment[], cursorPosition: Point): Comment | undefined { return CommentResolver.#getLastComment( comments.filter((comment) => comment.end.row < cursorPosition.row), ); } static #getCommentAtCursor(comments: Comment[], cursorPosition: Point): Comment | undefined { return CommentResolver.#getLastComment( comments.filter( (comment) => comment.start.row <= cursorPosition.row && comment.end.row >= cursorPosition.row, ), ); } static #getLastComment(comments: Comment[]): Comment | undefined { return comments.sort((a, b) => b.end.row - a.end.row)[0]; } /** * Returns the total number of lines that are comments in a parsed syntax tree. * Uses a Set because we only want to count each line once. * @param {Object} params - Parameters for counting comment lines. * @param {TreeSitterLanguageName} params.languageName - The name of the programming language. * @param {Tree} params.tree - The syntax tree to analyze. * @param {Language} params.treeSitterLanguage - The Tree-sitter language instance. * @returns {number} - The total number of unique lines containing comments. */ getTotalCommentLines({ treeSitterLanguage, languageName, tree, }: { languageName: TreeSitterLanguageName; treeSitterLanguage: Language; tree: Tree; }): number { const query = this.#getQueryByLanguage(languageName, treeSitterLanguage); const captures = query ? query.captures(tree.rootNode) : []; // Note: in future, we could potentially re-use captures from getCommentForCursor() const commentLineSet = new Set(); // A Set is used to only count each line once (the same comment can span multiple lines) captures.forEach((capture) => { const { startPosition, endPosition } = capture.node; for (let { row } = startPosition; row <= endPosition.row; row++) { commentLineSet.add(row); } }); return commentLineSet.size; } static isCommentEmpty(comment: Comment): boolean { const trimmedContent = comment.content.trim().replace(/[\n\r\\]/g, ' '); // Count the number of alphanumeric characters in the trimmed content const alphanumericCount = (trimmedContent.match(/[a-zA-Z0-9]/g) || []).length; return alphanumericCount <= 2; } } let commentResolver: CommentResolver; export function getCommentResolver(): CommentResolver { if (!commentResolver) { commentResolver = new CommentResolver(); } return commentResolver; } References:" You are a code assistant,Definition of 'streamFetch' in file src/node/fetch.ts in project gitlab-lsp,"Definition: async *streamFetch( url: string, body: string, headers: FetchHeaders, ): AsyncGenerator { let buffer = ''; const decoder = new TextDecoder(); async function* readStream( stream: ReadableStream, ): AsyncGenerator { 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 { 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: '' } : {}), ...(cert ? { cert: '' } : {}), ...(key ? { key: '' } : {}), }; } } References:" You are a code assistant,Definition of 'getSocketEventHandler' in file packages/lib_webview_client/src/bus/provider/socket_io_message_bus.test.ts in project gitlab-lsp,"Definition: function getSocketEventHandler(socket: jest.Mocked, eventName: SocketEvents): Function { const [, handler] = socket.on.mock.calls.find((call) => call[0] === eventName)!; return handler; } References: - packages/lib_webview_client/src/bus/provider/socket_io_message_bus.test.ts:91 - packages/lib_webview_client/src/bus/provider/socket_io_message_bus.test.ts:147 - packages/lib_webview_client/src/bus/provider/socket_io_message_bus.test.ts:129" You are a code assistant,Definition of 'processStream' in file src/common/suggestion_client/post_processors/post_processor_pipeline.test.ts in project gitlab-lsp,"Definition: async processStream( _context: IDocContext, input: StreamingCompletionResponse, ): Promise { return { ...input, completion: `${input.completion} [1]` }; } async processCompletion( _context: IDocContext, input: SuggestionOption[], ): Promise { return input; } } class Processor2 extends PostProcessor { async processStream( _context: IDocContext, input: StreamingCompletionResponse, ): Promise { return { ...input, completion: `${input.completion} [2]` }; } async processCompletion( _context: IDocContext, input: SuggestionOption[], ): Promise { return input; } } pipeline.addProcessor(new Processor1()); pipeline.addProcessor(new Processor2()); const streamInput: StreamingCompletionResponse = { id: '1', completion: 'test', done: false }; const result = await pipeline.run({ documentContext: mockContext, input: streamInput, type: 'stream', }); expect(result).toEqual({ id: '1', completion: 'test [1] [2]', done: false }); }); test('should chain multiple processors correctly for completion input', async () => { class Processor1 extends PostProcessor { async processStream( _context: IDocContext, input: StreamingCompletionResponse, ): Promise { return input; } async processCompletion( _context: IDocContext, input: SuggestionOption[], ): Promise { return input.map((option) => ({ ...option, text: `${option.text} [1]` })); } } class Processor2 extends PostProcessor { async processStream( _context: IDocContext, input: StreamingCompletionResponse, ): Promise { return input; } async processCompletion( _context: IDocContext, input: SuggestionOption[], ): Promise { return input.map((option) => ({ ...option, text: `${option.text} [2]` })); } } pipeline.addProcessor(new Processor1()); pipeline.addProcessor(new Processor2()); const completionInput: SuggestionOption[] = [{ text: 'option1', uniqueTrackingId: '1' }]; const result = await pipeline.run({ documentContext: mockContext, input: completionInput, type: 'completion', }); expect(result).toEqual([{ text: 'option1 [1] [2]', uniqueTrackingId: '1' }]); }); test('should throw an error for unexpected type', async () => { class TestProcessor extends PostProcessor { async processStream( _context: IDocContext, input: StreamingCompletionResponse, ): Promise { return input; } async processCompletion( _context: IDocContext, input: SuggestionOption[], ): Promise { 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 'DefaultCodeSuggestionsSupportedLanguageCheck' in file src/common/feature_state/supported_language_check.ts in project gitlab-lsp,"Definition: export class DefaultCodeSuggestionsSupportedLanguageCheck implements StateCheck { #documentService: DocumentService; #isLanguageEnabled = false; #isLanguageSupported = false; #supportedLanguagesService: SupportedLanguagesService; #currentDocument?: TextDocument; #stateEmitter = new EventEmitter(); constructor( documentService: DocumentService, supportedLanguagesService: SupportedLanguagesService, ) { this.#documentService = documentService; this.#supportedLanguagesService = supportedLanguagesService; this.#documentService.onDocumentChange((event, handlerType) => { if (handlerType === TextDocumentChangeListenerType.onDidSetActive) { this.#updateWithDocument(event.document); } }); this.#supportedLanguagesService.onLanguageChange(() => this.#update()); } onChanged(listener: (data: StateCheckChangedEventData) => void): Disposable { this.#stateEmitter.on('change', listener); return { dispose: () => this.#stateEmitter.removeListener('change', listener), }; } #updateWithDocument(document: TextDocument) { this.#currentDocument = document; this.#update(); } get engaged() { return !this.#isLanguageEnabled; } get id() { return this.#isLanguageSupported && !this.#isLanguageEnabled ? DISABLED_LANGUAGE : UNSUPPORTED_LANGUAGE; } details = 'Code suggestions are not supported for this language'; #update() { this.#checkLanguage(); this.#stateEmitter.emit('change', this); } #checkLanguage() { if (!this.#currentDocument) { this.#isLanguageEnabled = false; this.#isLanguageSupported = false; return; } const { languageId } = this.#currentDocument; this.#isLanguageEnabled = this.#supportedLanguagesService.isLanguageEnabled(languageId); this.#isLanguageSupported = this.#supportedLanguagesService.isLanguageSupported(languageId); } } References: - src/common/feature_state/supported_language_check.test.ts:50" You are a code assistant,Definition of 'updateCodeSuggestionsContext' in file src/common/tracking/instance_tracker.ts in project gitlab-lsp,"Definition: async updateCodeSuggestionsContext( uniqueTrackingId: string, contextUpdate: Partial, ) { if (this.#circuitBreaker.isOpen()) { return; } if (this.#isStreamingSuggestion(uniqueTrackingId)) return; const context = this.#codeSuggestionsContextMap.get(uniqueTrackingId); const { model, suggestionOptions, isStreaming } = contextUpdate; if (context) { if (model) { context.language = model.lang ?? null; } if (suggestionOptions?.length) { context.suggestion_size = InstanceTracker.#suggestionSize(suggestionOptions); } if (typeof isStreaming === 'boolean') { context.is_streaming = isStreaming; } this.#codeSuggestionsContextMap.set(uniqueTrackingId, context); } } updateSuggestionState(uniqueTrackingId: string, newState: TRACKING_EVENTS): void { if (this.#circuitBreaker.isOpen()) { return; } if (!this.isEnabled()) return; if (this.#isStreamingSuggestion(uniqueTrackingId)) return; const state = this.#codeSuggestionStates.get(uniqueTrackingId); if (!state) { log.debug(`Instance telemetry: The suggestion with ${uniqueTrackingId} can't be found`); return; } const allowedTransitions = nonStreamingSuggestionStateGraph.get(state); if (!allowedTransitions) { log.debug( `Instance telemetry: The suggestion's ${uniqueTrackingId} state ${state} can't be found in state graph`, ); return; } if (!allowedTransitions.includes(newState)) { log.debug( `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( `Instance telemetry: Conditionally allowing transition to accepted state for ${uniqueTrackingId}`, ); } this.#codeSuggestionStates.set(uniqueTrackingId, newState); this.#trackCodeSuggestionsEvent(newState, uniqueTrackingId).catch((e) => log.warn('Instance telemetry: Could not track telemetry', e), ); log.debug(`Instance telemetry: ${uniqueTrackingId} transisted from ${state} to ${newState}`); } async #trackCodeSuggestionsEvent(eventType: TRACKING_EVENTS, uniqueTrackingId: string) { const event = INSTANCE_TRACKING_EVENTS_MAP[eventType]; if (!event) { return; } try { const { language, suggestion_size } = this.#codeSuggestionsContextMap.get(uniqueTrackingId) ?? {}; await this.#api.fetchFromApi({ type: 'rest', method: 'POST', path: '/usage_data/track_event', body: { event, additional_properties: { unique_tracking_id: uniqueTrackingId, timestamp: new Date().toISOString(), language, suggestion_size, }, }, supportedSinceInstanceVersion: { resourceName: 'track instance telemetry', version: '17.2.0', }, }); this.#circuitBreaker.success(); } catch (error) { if (error instanceof InvalidInstanceVersionError) { if (this.#invalidInstanceMsgLogged) return; this.#invalidInstanceMsgLogged = true; } log.warn(`Instance telemetry: Failed to track event: ${eventType}`, error); this.#circuitBreaker.error(); } } rejectOpenedSuggestions() { log.debug(`Instance Telemetry: Reject all opened suggestions`); this.#codeSuggestionStates.forEach((state, uniqueTrackingId) => { if (endStates.includes(state)) { return; } this.updateSuggestionState(uniqueTrackingId, TRACKING_EVENTS.REJECTED); }); } static #suggestionSize(options: SuggestionOption[]): number { const countLines = (text: string) => (text ? text.split('\n').length : 0); return Math.max(...options.map(({ text }) => countLines(text))); } #isStreamingSuggestion(uniqueTrackingId: string): boolean { return Boolean(this.#codeSuggestionsContextMap.get(uniqueTrackingId)?.is_streaming); } } References:" 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 { return input; } } pipeline.addProcessor(new TestStreamProcessor()); const streamInput: StreamingCompletionResponse = { id: '1', completion: 'test', done: false }; const result = await pipeline.run({ documentContext: mockContext, input: streamInput, type: 'stream', }); expect(result).toEqual({ id: '1', completion: 'test processed', done: false }); }); test('should process completion input correctly', async () => { class TestCompletionProcessor extends PostProcessor { async processStream( _context: IDocContext, input: StreamingCompletionResponse, ): Promise { return input; } async processCompletion( _context: IDocContext, input: SuggestionOption[], ): Promise { return input.map((option) => ({ ...option, text: `${option.text} processed` })); } } pipeline.addProcessor(new TestCompletionProcessor()); const completionInput: SuggestionOption[] = [{ text: 'option1', uniqueTrackingId: '1' }]; const result = await pipeline.run({ documentContext: mockContext, input: completionInput, type: 'completion', }); expect(result).toEqual([{ text: 'option1 processed', uniqueTrackingId: '1' }]); }); test('should chain multiple processors correctly for stream input', async () => { class Processor1 extends PostProcessor { async processStream( _context: IDocContext, input: StreamingCompletionResponse, ): Promise { return { ...input, completion: `${input.completion} [1]` }; } async processCompletion( _context: IDocContext, input: SuggestionOption[], ): Promise { return input; } } class Processor2 extends PostProcessor { async processStream( _context: IDocContext, input: StreamingCompletionResponse, ): Promise { return { ...input, completion: `${input.completion} [2]` }; } async processCompletion( _context: IDocContext, input: SuggestionOption[], ): Promise { return input; } } pipeline.addProcessor(new Processor1()); pipeline.addProcessor(new Processor2()); const streamInput: StreamingCompletionResponse = { id: '1', completion: 'test', done: false }; const result = await pipeline.run({ documentContext: mockContext, input: streamInput, type: 'stream', }); expect(result).toEqual({ id: '1', completion: 'test [1] [2]', done: false }); }); test('should chain multiple processors correctly for completion input', async () => { class Processor1 extends PostProcessor { async processStream( _context: IDocContext, input: StreamingCompletionResponse, ): Promise { return input; } async processCompletion( _context: IDocContext, input: SuggestionOption[], ): Promise { return input.map((option) => ({ ...option, text: `${option.text} [1]` })); } } class Processor2 extends PostProcessor { async processStream( _context: IDocContext, input: StreamingCompletionResponse, ): Promise { return input; } async processCompletion( _context: IDocContext, input: SuggestionOption[], ): Promise { return input.map((option) => ({ ...option, text: `${option.text} [2]` })); } } pipeline.addProcessor(new Processor1()); pipeline.addProcessor(new Processor2()); const completionInput: SuggestionOption[] = [{ text: 'option1', uniqueTrackingId: '1' }]; const result = await pipeline.run({ documentContext: mockContext, input: completionInput, type: 'completion', }); expect(result).toEqual([{ text: 'option1 [1] [2]', uniqueTrackingId: '1' }]); }); test('should throw an error for unexpected type', async () => { class TestProcessor extends PostProcessor { async processStream( _context: IDocContext, input: StreamingCompletionResponse, ): Promise { return input; } async processCompletion( _context: IDocContext, input: SuggestionOption[], ): Promise { 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 'getTotalNonEmptyLines' in file src/common/tree_sitter/small_files.ts in project gitlab-lsp,"Definition: function getTotalNonEmptyLines(textContent: string): number { return textContent.split('\n').filter((line) => line.trim() !== '').length; } export function isSmallFile(textContent: string, totalCommentLines: number): boolean { const minLinesOfCode = 5; // threshold to determine whether a source code file is considered 'small' const totalNonEmptyLines = getTotalNonEmptyLines(textContent); return totalNonEmptyLines - totalCommentLines < minLinesOfCode; } References: - src/common/tree_sitter/small_files.ts:7" You are a code assistant,Definition of 'constructor' in file src/common/webview/extension/extension_connection_message_bus_provider.ts in project gitlab-lsp,"Definition: constructor({ connection, logger, notificationRpcMethod = DEFAULT_NOTIFICATION_RPC_METHOD, requestRpcMethod = DEFAULT_REQUEST_RPC_METHOD, }: ExtensionConnectionMessageBusProviderProps) { this.#connection = connection; this.#logger = withPrefix(logger, '[ExtensionConnectionMessageBusProvider]'); this.#rpcMethods = { notification: notificationRpcMethod, request: requestRpcMethod, }; this.#handlers = { notification: new ExtensionMessageHandlerRegistry(), request: new ExtensionMessageHandlerRegistry(), }; this.#setupConnectionSubscriptions(); } getMessageBus(webviewId: WebviewId): MessageBus { return new ExtensionConnectionMessageBus({ webviewId, connection: this.#connection, rpcMethods: this.#rpcMethods, handlers: this.#handlers, }); } dispose(): void { this.#disposables.dispose(); } #setupConnectionSubscriptions() { this.#disposables.add( this.#connection.onNotification( this.#rpcMethods.notification, handleNotificationMessage(this.#notificationHandlers, this.#logger), ), ); this.#disposables.add( this.#connection.onRequest( this.#rpcMethods.request, handleRequestMessage(this.#requestHandlers, this.#logger), ), ); } } References:" You are a code assistant,Definition of 'CompositeDisposable' in file packages/lib_disposable/src/composite_disposable.ts in project gitlab-lsp,"Definition: export class CompositeDisposable implements Disposable { #disposables: Set = new Set(); get size() { return this.#disposables.size; } add(...disposables: Disposable[]): void { for (const disposable of disposables) { this.#disposables.add(disposable); } } dispose(): void { for (const disposable of this.#disposables) { disposable.dispose(); } this.#disposables.clear(); } } References: - packages/lib_disposable/src/composite_disposable.test.ts:10 - packages/lib_webview/src/setup/transport/setup_transport.ts:17 - packages/lib_webview/src/setup/plugin/setup_plugins.ts:24 - packages/lib_webview/src/setup/plugin/webview_controller.ts:98 - packages/lib_disposable/src/composite_disposable.test.ts:5 - packages/webview_duo_chat/src/plugin/chat_controller.ts:17 - src/common/webview/extension/extension_connection_message_bus_provider.ts:38 - packages/lib_webview/src/setup/plugin/webview_instance_message_bus.ts:22 - packages/lib_webview/src/setup/plugin/webview_controller.ts:17 - packages/lib_webview/src/setup/plugin/webview_controller.ts:33" You are a code assistant,Definition of 'LsTextDocuments' in file src/common/external_interfaces.ts in project gitlab-lsp,"Definition: export const LsTextDocuments = createInterfaceId('LsTextDocuments'); References: - src/common/document_transformer_service.ts:79 - src/common/document_transformer_service.ts:81" You are a code assistant,Definition of 'handle' in file packages/lib_handler_registry/src/registry/hashed_registry.ts in project gitlab-lsp,"Definition: async handle(key: TKey, ...args: Parameters): Promise> { const hash = this.#hashFunc(key); return this.#basicRegistry.handle(hash, ...args); } dispose() { this.#basicRegistry.dispose(); } } References:" You are a code assistant,Definition of 'DefaultDuoProjectAccessCache' in file src/common/services/duo_access/project_access_cache.ts in project gitlab-lsp,"Definition: export class DefaultDuoProjectAccessCache { #duoProjects: Map; #eventEmitter = new EventEmitter(); constructor( private readonly directoryWalker: DirectoryWalker, private readonly fileResolver: FileResolver, private readonly api: GitLabApiClient, ) { this.#duoProjects = new Map(); } getProjectsForWorkspaceFolder(workspaceFolder: WorkspaceFolder): DuoProject[] { return this.#duoProjects.get(workspaceFolder.uri) ?? []; } async updateCache({ baseUrl, workspaceFolders, }: { baseUrl: string; workspaceFolders: WorkspaceFolder[]; }) { try { this.#duoProjects.clear(); const duoProjects = await Promise.all( workspaceFolders.map(async (workspaceFolder) => { return { workspaceFolder, projects: await this.#duoProjectsForWorkspaceFolder({ workspaceFolder, baseUrl, }), }; }), ); for (const { workspaceFolder, projects } of duoProjects) { this.#logProjectsInfo(projects, workspaceFolder); this.#duoProjects.set(workspaceFolder.uri, projects); } this.#triggerChange(); } catch (err) { log.error('DuoProjectAccessCache: failed to update project access cache', err); } } #logProjectsInfo(projects: DuoProject[], workspaceFolder: WorkspaceFolder) { if (!projects.length) { log.warn( `DuoProjectAccessCache: no projects found for workspace folder ${workspaceFolder.uri}`, ); return; } log.debug( `DuoProjectAccessCache: found ${projects.length} projects for workspace folder ${workspaceFolder.uri}: ${JSON.stringify(projects, null, 2)}`, ); } async #duoProjectsForWorkspaceFolder({ workspaceFolder, baseUrl, }: { workspaceFolder: WorkspaceFolder; baseUrl: string; }): Promise { const remotes = await this.#gitlabRemotesForWorkspaceFolder(workspaceFolder, baseUrl); const projects = await Promise.all( remotes.map(async (remote) => { const enabled = await this.#checkDuoFeaturesEnabled(remote.namespaceWithPath); return { projectPath: remote.projectPath, uri: remote.fileUri, enabled, host: remote.host, namespace: remote.namespace, namespaceWithPath: remote.namespaceWithPath, } satisfies DuoProject; }), ); return projects; } async #gitlabRemotesForWorkspaceFolder( workspaceFolder: WorkspaceFolder, baseUrl: string, ): Promise { const paths = await this.directoryWalker.findFilesForDirectory({ directoryUri: workspaceFolder.uri, filters: { fileEndsWith: ['/.git/config'], }, }); const remotes = await Promise.all( paths.map(async (fileUri) => this.#gitlabRemotesForFileUri(fileUri.toString(), baseUrl)), ); return remotes.flat(); } async #gitlabRemotesForFileUri( fileUri: string, baseUrl: string, ): Promise { const remoteUrls = await this.#remoteUrlsFromGitConfig(fileUri); return remoteUrls.reduce((acc, remoteUrl) => { const remote = parseGitLabRemote(remoteUrl, baseUrl); if (remote) { acc.push({ ...remote, fileUri }); } return acc; }, []); } async #remoteUrlsFromGitConfig(fileUri: string): Promise { try { const fileString = await this.fileResolver.readFile({ fileUri }); const config = ini.parse(fileString); return this.#getRemoteUrls(config); } catch (error) { log.error(`DuoProjectAccessCache: Failed to read git config file: ${fileUri}`, error); return []; } } #getRemoteUrls(config: GitConfig): string[] { return Object.keys(config).reduce((acc, section) => { if (section.startsWith('remote ')) { acc.push(config[section].url); } return acc; }, []); } async #checkDuoFeaturesEnabled(projectPath: string): Promise { try { const response = await this.api.fetchFromApi<{ project: GqlProjectWithDuoEnabledInfo }>({ type: 'graphql', query: duoFeaturesEnabledQuery, variables: { projectPath, }, } satisfies ApiRequest<{ project: GqlProjectWithDuoEnabledInfo }>); return Boolean(response?.project?.duoFeaturesEnabled); } catch (error) { log.error( `DuoProjectAccessCache: Failed to check if Duo features are enabled for project: ${projectPath}`, error, ); return true; } } onDuoProjectCacheUpdate( listener: (duoProjectsCache: Map) => void, ): Disposable { this.#eventEmitter.on(DUO_PROJECT_CACHE_UPDATE_EVENT, listener); return { dispose: () => this.#eventEmitter.removeListener(DUO_PROJECT_CACHE_UPDATE_EVENT, listener), }; } #triggerChange() { this.#eventEmitter.emit(DUO_PROJECT_CACHE_UPDATE_EVENT, this.#duoProjects); } } References: - src/common/services/duo_access/project_access_cache.test.ts:157 - src/common/services/duo_access/project_access_cache.test.ts:53 - src/common/services/duo_access/project_access_cache.test.ts:125 - src/common/services/duo_access/project_access_cache.test.ts:88" You are a code assistant,Definition of 'GitLabApiClient' in file packages/webview_duo_chat/src/plugin/types.ts in project gitlab-lsp,"Definition: export interface GitLabApiClient { fetchFromApi(request: ApiRequest): Promise; connectToCable(): Promise; } References: - src/node/duo_workflow/desktop_workflow_runner.ts:49 - src/common/graphql/workflow/service.ts:14 - src/common/tracking/instance_tracker.ts:31 - src/common/feature_flags.test.ts:12 - src/common/core/handlers/token_check_notifier.ts:14 - src/node/duo_workflow/desktop_workflow_runner.ts:53 - src/common/suggestion/streaming_handler.ts:36 - src/common/core/handlers/token_check_notifier.test.ts:7 - packages/webview_duo_chat/src/plugin/chat_platform_manager.ts:10 - src/common/suggestion/suggestion_service.ts:119 - packages/webview_duo_chat/src/plugin/index.ts:9 - src/common/suggestion_client/direct_connection_client.ts:28 - src/common/suggestion/suggestion_service.ts:79 - packages/webview_duo_chat/src/plugin/chat_platform.ts:14 - src/common/feature_flags.ts:43 - src/common/graphql/workflow/service.test.ts:15 - src/common/suggestion_client/default_suggestion_client.ts:8 - src/common/services/duo_access/project_access_cache.ts:94 - src/common/suggestion_client/default_suggestion_client.ts:6 - src/common/graphql/workflow/service.ts:18 - src/common/tracking/instance_tracker.ts:51 - src/common/feature_flags.ts:49 - src/common/connection.ts:23 - packages/webview_duo_chat/src/plugin/chat_platform_manager.ts:12 - src/common/tracking/snowplow_tracker.ts:133 - src/common/suggestion_client/default_suggestion_client.test.ts:20 - src/common/suggestion_client/direct_connection_client.test.ts:23 - src/common/suggestion/streaming_handler.test.ts:30 - src/common/suggestion_client/direct_connection_client.ts:54 - src/common/tracking/snowplow_tracker.ts:162 - packages/webview_duo_chat/src/plugin/chat_platform.ts:16" You are a code assistant,Definition of 'fetchFromApi' in file packages/webview_duo_chat/src/plugin/port/platform/web_ide.ts in project gitlab-lsp,"Definition: 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; /* 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: - packages/webview_duo_chat/src/plugin/port/platform/gitlab_platform.ts:11 - packages/webview_duo_chat/src/plugin/port/test_utils/create_fake_fetch_from_api.ts:10" You are a code assistant,Definition of 'CodeSuggestionsSupportedLanguageCheck' in file src/common/feature_state/supported_language_check.ts in project gitlab-lsp,"Definition: export interface CodeSuggestionsSupportedLanguageCheck extends StateCheck {} export const CodeSuggestionsSupportedLanguageCheck = createInterfaceId('CodeSuggestionsSupportedLanguageCheck'); @Injectable(CodeSuggestionsSupportedLanguageCheck, [DocumentService, SupportedLanguagesService]) export class DefaultCodeSuggestionsSupportedLanguageCheck implements StateCheck { #documentService: DocumentService; #isLanguageEnabled = false; #isLanguageSupported = false; #supportedLanguagesService: SupportedLanguagesService; #currentDocument?: TextDocument; #stateEmitter = new EventEmitter(); constructor( documentService: DocumentService, supportedLanguagesService: SupportedLanguagesService, ) { this.#documentService = documentService; this.#supportedLanguagesService = supportedLanguagesService; this.#documentService.onDocumentChange((event, handlerType) => { if (handlerType === TextDocumentChangeListenerType.onDidSetActive) { this.#updateWithDocument(event.document); } }); this.#supportedLanguagesService.onLanguageChange(() => this.#update()); } onChanged(listener: (data: StateCheckChangedEventData) => void): Disposable { this.#stateEmitter.on('change', listener); return { dispose: () => this.#stateEmitter.removeListener('change', listener), }; } #updateWithDocument(document: TextDocument) { this.#currentDocument = document; this.#update(); } get engaged() { return !this.#isLanguageEnabled; } get id() { return this.#isLanguageSupported && !this.#isLanguageEnabled ? DISABLED_LANGUAGE : UNSUPPORTED_LANGUAGE; } details = 'Code suggestions are not supported for this language'; #update() { this.#checkLanguage(); this.#stateEmitter.emit('change', this); } #checkLanguage() { if (!this.#currentDocument) { this.#isLanguageEnabled = false; this.#isLanguageSupported = false; return; } const { languageId } = this.#currentDocument; this.#isLanguageEnabled = this.#supportedLanguagesService.isLanguageEnabled(languageId); this.#isLanguageSupported = this.#supportedLanguagesService.isLanguageSupported(languageId); } } References: - src/common/feature_state/supported_language_check.test.ts:22 - src/common/feature_state/feature_state_manager.ts:28" You are a code assistant,Definition of 'LsConnection' in file src/common/external_interfaces.ts in project gitlab-lsp,"Definition: export type LsConnection = Connection; export const LsConnection = createInterfaceId('LsConnection'); export type LsTextDocuments = TextDocuments; export const LsTextDocuments = createInterfaceId('LsTextDocuments'); References: - src/common/advanced_context/advanced_context_service.ts:34 - src/common/connection_service.ts:60 - src/common/connection_service.ts:53 - src/common/connection_service.ts:34 - src/common/connection_service.ts:38" You are a code assistant,Definition of 'AccountBase' in file packages/webview_duo_chat/src/plugin/port/platform/gitlab_account.ts in project gitlab-lsp,"Definition: interface AccountBase extends Credentials { username: string; id: string; } 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 'EnabledCallback' in file src/common/tracking/snowplow/snowplow.ts in project gitlab-lsp,"Definition: export type EnabledCallback = () => boolean; export type SnowplowOptions = { appId: string; endpoint: string; timeInterval: number; maxItems: number; enabled: EnabledCallback; }; /** * Adds the 'stm' parameter with the current time to the payload * Stringify all payload values * @param payload - The payload which will be mutated */ function preparePayload(payload: Payload): Record { const stringifiedPayload: Record = {}; Object.keys(payload).forEach((key) => { stringifiedPayload[key] = String(payload[key]); }); stringifiedPayload.stm = new Date().getTime().toString(); return stringifiedPayload; } export class Snowplow { /** Disable sending events when it's not possible. */ disabled: boolean = false; #emitter: Emitter; #lsFetch: LsFetch; #options: SnowplowOptions; #tracker: TrackerCore; static #instance?: Snowplow; // eslint-disable-next-line no-restricted-syntax private constructor(lsFetch: LsFetch, options: SnowplowOptions) { this.#lsFetch = lsFetch; this.#options = options; this.#emitter = new Emitter( this.#options.timeInterval, this.#options.maxItems, this.#sendEvent.bind(this), ); this.#emitter.start(); this.#tracker = trackerCore({ callback: this.#emitter.add.bind(this.#emitter) }); } public static getInstance(lsFetch: LsFetch, options?: SnowplowOptions): Snowplow { if (!this.#instance) { if (!options) { throw new Error('Snowplow should be instantiated'); } const sp = new Snowplow(lsFetch, options); Snowplow.#instance = sp; } // FIXME: this eslint violation was introduced before we set up linting // eslint-disable-next-line @typescript-eslint/no-non-null-assertion return Snowplow.#instance!; } async #sendEvent(events: PayloadBuilder[]): Promise { if (!this.#options.enabled() || this.disabled) { return; } try { const url = `${this.#options.endpoint}/com.snowplowanalytics.snowplow/tp2`; const data = { schema: 'iglu:com.snowplowanalytics.snowplow/payload_data/jsonschema/1-0-4', data: events.map((event) => { const eventId = uuidv4(); // All values prefilled below are part of snowplow tracker protocol // https://docs.snowplow.io/docs/collecting-data/collecting-from-own-applications/snowplow-tracker-protocol/#common-parameters // Values are set according to either common GitLab standard: // tna - representing tracker namespace and being set across GitLab to ""gl"" // tv - represents tracker value, to make it aligned with downstream system it has to be prefixed with ""js-*"""" // aid - represents app Id is configured via options to gitlab_ide_extension // eid - represents uuid for each emitted event event.add('eid', eventId); event.add('p', 'app'); event.add('tv', 'js-gitlab'); event.add('tna', 'gl'); event.add('aid', this.#options.appId); return preparePayload(event.build()); }), }; const config = { headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(data), }; const response = await this.#lsFetch.post(url, config); if (response.status !== 200) { log.warn( `Could not send telemetry to snowplow, this warning can be safely ignored. status=${response.status}`, ); } } catch (error) { let errorHandled = false; if (typeof error === 'object' && 'errno' in (error as object)) { const errObject = error as object; // ENOTFOUND occurs when the snowplow hostname cannot be resolved. if ('errno' in errObject && errObject.errno === 'ENOTFOUND') { this.disabled = true; errorHandled = true; log.info('Disabling telemetry, unable to resolve endpoint address.'); } else { log.warn(JSON.stringify(errObject)); } } if (!errorHandled) { log.warn('Failed to send telemetry event, this warning can be safely ignored'); log.warn(JSON.stringify(error)); } } } public async trackStructEvent( event: StructuredEvent, context?: SelfDescribingJson[] | null, ): Promise { this.#tracker.track(buildStructEvent(event), context); } async stop() { await this.#emitter.stop(); } public destroy() { Snowplow.#instance = undefined; } } References: - src/common/tracking/snowplow/snowplow.ts:22" You are a code assistant,Definition of 'isLanguageEnabled' in file src/common/suggestion/supported_languages_service.ts in project gitlab-lsp,"Definition: 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 'updateSuggestionState' in file src/common/tracking/snowplow_tracker.ts in project gitlab-lsp,"Definition: 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 'ManagedInstances' in file packages/lib_webview/src/setup/transport/utils/event_filters.ts in project gitlab-lsp,"Definition: export type ManagedInstances = Set; export type IsManagedEventFilter = ( event: TEvent, ) => boolean; export const createIsManagedFunc = (managedInstances: ManagedInstances): IsManagedEventFilter => (event: TEvent) => managedInstances.has(event.webviewInstanceId); References: - packages/lib_webview/src/setup/transport/utils/event_filters.ts:9 - packages/lib_webview/src/setup/transport/utils/setup_transport_event_handlers.ts:10 - packages/lib_webview/src/setup/transport/utils/setup_transport_event_handlers.test.ts:10" You are a code assistant,Definition of 'DefaultDirectoryWalker' in file src/common/services/fs/dir.ts in project gitlab-lsp,"Definition: export class DefaultDirectoryWalker { /** * Returns a list of files in the specified directory that match the specified criteria. * The returned files will be the full paths to the files, they also will be in the form of URIs. * Example: [' file:///path/to/file.txt', 'file:///path/to/another/file.js'] */ // eslint-disable-next-line @typescript-eslint/no-unused-vars findFilesForDirectory(_args: DirectoryToSearch): Promise { return Promise.resolve([]); } // eslint-disable-next-line @typescript-eslint/no-unused-vars setupFileWatcher(workspaceFolder: WorkspaceFolder, changeHandler: FileChangeHandler) { throw new Error(`${workspaceFolder} ${changeHandler} not implemented`); } } References:" You are a code assistant,Definition of 'SuggestionClientMiddleware' in file src/common/suggestion_client/suggestion_client.ts in project gitlab-lsp,"Definition: export type SuggestionClientMiddleware = ( context: SuggestionContext, next: SuggestionClientFn, ) => ReturnType; References: - src/common/suggestion_client/suggestion_client_pipeline.test.ts:39 - src/common/suggestion_client/tree_sitter_middleware.test.ts:19 - src/common/suggestion_client/tree_sitter_middleware.ts:12 - src/common/suggestion_client/client_to_middleware.ts:4 - src/common/suggestion_client/suggestion_client_pipeline.test.ts:36 - src/common/suggestion_client/suggestion_client_pipeline.ts:19" You are a code assistant,Definition of 'NotificationMessage' in file packages/lib_webview/src/events/webview_runtime_message_bus.ts in project gitlab-lsp,"Definition: export type NotificationMessage = WebviewAddress & { type: string; payload?: unknown; }; export type RequestMessage = NotificationMessage & { requestId: string; }; export type SuccessfulResponse = WebviewAddress & { requestId: string; success: true; type: string; payload?: unknown; }; 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 {} References: - packages/lib_webview/src/events/webview_runtime_message_bus.ts:35 - packages/lib_webview/src/events/webview_runtime_message_bus.ts:32" You are a code assistant,Definition of 'WebviewId' in file packages/lib_webview_plugin/src/types.ts in project gitlab-lsp,"Definition: export type WebviewId = string & { readonly _type: 'WebviewId' }; /** * Represents a unique identifier for instances of a webview. */ export type WebviewInstanceId = string & { readonly _type: 'WebviewInstanceId' }; export type WebviewAddress = { webviewId: WebviewId; webviewInstanceId: WebviewInstanceId; }; export type WebviewMessageBusManagerHandler = ( webviewInstanceId: WebviewInstanceId, messageBus: MessageBus, // eslint-disable-next-line @typescript-eslint/no-invalid-void-type ) => Disposable | void; export interface WebviewConnection { broadcast: ( type: TMethod, payload: T['outbound']['notifications'][TMethod], ) => void; onInstanceConnected: (handler: WebviewMessageBusManagerHandler) => void; } References: - src/common/webview/extension/extension_connection_message_bus.ts:8 - src/node/webview/handlers/webview_handler.test.ts:14 - src/common/webview/webview_resource_location_service.ts:20 - packages/lib_webview_transport/src/types.ts:5 - packages/lib_webview_plugin/src/types.ts:17 - src/common/webview/extension/utils/extension_message_handler_registry.ts:5 - src/common/webview/extension/extension_connection_message_bus_provider.ts:62 - src/common/webview/webview_resource_location_service.ts:6 - packages/lib_webview/src/setup/plugin/webview_controller.ts:38 - packages/lib_webview/src/setup/plugin/utils/filters.ts:4 - src/node/webview/http_access_info_provider.ts:12 - src/node/webview/webview_fastify_middleware.ts:21 - packages/lib_webview/src/setup/plugin/webview_controller.ts:25 - src/node/webview/handlers/webview_handler.ts:28 - src/node/webview/routes/webview_routes.ts:11 - src/node/webview/handlers/webview_handler.ts:7 - src/common/webview/webview_metadata_provider.test.ts:12 - packages/lib_webview_transport_socket_io/src/types.ts:4 - packages/lib_webview/src/types.ts:5 - src/common/webview/webview_metadata_provider.ts:5 - packages/lib_webview_plugin/src/webview_plugin.ts:62 - packages/lib_webview/src/setup/plugin/utils/filters.ts:5 - src/common/webview/extension/extension_connection_message_bus.ts:17 - src/common/webview/webview_resource_location_service.test.ts:17 - src/common/webview/webview_metadata_provider.test.ts:8 - src/node/webview/handlers/webview_handler.ts:11 - src/common/webview/extension/utils/extension_message.ts:4" You are a code assistant,Definition of 'ICodeSuggestionModel' in file src/common/tracking/tracking_types.ts in project gitlab-lsp,"Definition: 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, ): void; updateCodeSuggestionsContext( uniqueTrackingId: string, contextUpdate: Partial, ): void; rejectOpenedSuggestions(): void; updateSuggestionState(uniqueTrackingId: string, newState: TRACKING_EVENTS): void; } export const TelemetryTracker = createInterfaceId('TelemetryTracker'); References: - src/common/tracking/tracking_types.ts:12 - src/common/tracking/snowplow_tracker.test.ts:337 - src/common/tracking/instance_tracker.test.ts:171 - src/common/api.ts:66" You are a code assistant,Definition of 'IntentDetectionExamples' in file src/node/tree_sitter/test_examples/intent_detection/types.ts in project gitlab-lsp,"Definition: export type IntentDetectionExamples = { completion: Array; generation: Array; }; References: - src/node/tree_sitter/test_examples/intent_detection/java.ts:4 - src/node/tree_sitter/test_examples/intent_detection/go.ts:4 - src/node/tree_sitter/test_examples/intent_detection/python.ts:4 - src/node/tree_sitter/test_examples/intent_detection/ruby.ts:4 - src/node/tree_sitter/test_examples/intent_detection/javascript.ts:4 - src/node/tree_sitter/test_examples/intent_detection/typescript.ts:4" You are a code assistant,Definition of 'listenerCount' in file packages/lib_webview/src/events/message_bus.ts in project gitlab-lsp,"Definition: public listenerCount(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 'initialize' in file src/tests/fixtures/intent/empty_function/ruby.rb in project gitlab-lsp,"Definition: 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/ruby.rb:25 - src/tests/fixtures/intent/empty_function/ruby.rb:17" You are a code assistant,Definition of 'API_PULLING' in file packages/webview_duo_chat/src/plugin/port/chat/api/pulling.ts in project gitlab-lsp,"Definition: export const API_PULLING = { interval: 5000, maxRetries: 10, }; export const pullHandler = async ( handler: () => Promise, retry = API_PULLING.maxRetries, ): Promise => { if (retry <= 0) { log.debug('Pull handler: no retries left, exiting without return value.'); return undefined; } log.debug(`Pull handler: pulling, ${retry - 1} retries left.`); const response = await handler(); if (response) return response; await waitForMs(API_PULLING.interval); return pullHandler(handler, retry - 1); }; References:" You are a code assistant,Definition of 'sendTextDocumentCompletion' in file src/tests/int/lsp_client.ts in project gitlab-lsp,"Definition: public async sendTextDocumentCompletion( uri: string, line: number, character: number, ): Promise { 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 { await this.#connection.sendNotification(DidChangeDocumentInActiveEditor, uri); } public async getWebviewMetadata(): Promise { const result = await this.#connection.sendRequest( '$/gitlab/webview-metadata', ); return result; } } References:" You are a code assistant,Definition of 'getDocContext' in file src/common/document_transformer_service.ts in project gitlab-lsp,"Definition: 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: - src/common/document_transformer_service.test.ts:79 - src/common/document_transformer_service.test.ts:46 - src/common/document_transformer_service.test.ts:53 - src/common/document_transformer_service.ts:100" You are a code assistant,Definition of 'constructor' in file src/common/suggestion_client/direct_connection_client.ts in project gitlab-lsp,"Definition: constructor(api: GitLabApiClient, configService: ConfigService) { this.#api = api; this.#configService = configService; this.#api.onApiReconfigured(({ isInValidState }) => { this.#connectionDetails = undefined; this.#isValidApi = isInValidState; this.#directConnectionCircuitBreaker.success(); // resets the circuit breaker // TODO: fetch the direct connection details https://gitlab.com/gitlab-org/editor-extensions/gitlab-lsp/-/issues/239 }); } #fetchDirectConnectionDetails = async () => { if (this.#connectionDetailsCircuitBreaker.isOpen()) { return; } let details; try { details = await this.#api.fetchFromApi({ type: 'rest', method: 'POST', path: '/code_suggestions/direct_access', supportedSinceInstanceVersion: { version: '17.2.0', resourceName: 'get direct connection details', }, }); } catch (e) { // 401 indicates that the user has GitLab Duo disabled and shout result in longer periods of open circuit if (isFetchError(e) && e.status === 401) { this.#connectionDetailsCircuitBreaker.megaError(); } else { this.#connectionDetailsCircuitBreaker.error(); } log.info( `Failed to fetch direct connection details from GitLab instance. Code suggestion requests will be sent to your GitLab instance. Error ${e}`, ); } this.#connectionDetails = details; this.#configService.merge({ client: { snowplowTrackerOptions: transformHeadersToSnowplowOptions(details?.headers) }, }); }; async #fetchUsingDirectConnection(request: CodeSuggestionRequest): Promise { if (!this.#connectionDetails) { throw new Error('Assertion error: connection details are undefined'); } const suggestionEndpoint = `${this.#connectionDetails.base_url}/v2/completions`; const start = Date.now(); const response = await fetch(suggestionEndpoint, { method: 'post', body: JSON.stringify(request), keepalive: true, headers: { ...this.#connectionDetails.headers, Authorization: `Bearer ${this.#connectionDetails.token}`, 'X-Gitlab-Authentication-Type': 'oidc', 'X-Gitlab-Language-Server-Version': getLanguageServerVersion(), 'Content-Type': ' application/json', }, signal: AbortSignal.timeout(5 * SECOND), }); await handleFetchError(response, 'Direct Connection for code suggestions'); const data = await response.json(); const end = Date.now(); log.debug(`Direct connection (${suggestionEndpoint}) suggestion fetched in ${end - start}ms`); return data; } async getSuggestions(context: SuggestionContext): Promise { // TODO we would like to send direct request only for intent === COMPLETION // however, currently we are not certain that the intent is completion // when we finish the following two issues, we can be certain that the intent is COMPLETION // // https://gitlab.com/gitlab-org/editor-extensions/gitlab-lsp/-/issues/173 // https://gitlab.com/gitlab-org/editor-extensions/gitlab-lsp/-/issues/247 if (context.intent === GENERATION) { return undefined; } if (!this.#isValidApi) { return undefined; } if (this.#directConnectionCircuitBreaker.isOpen()) { return undefined; } if (!this.#connectionDetails || areExpired(this.#connectionDetails)) { this.#fetchDirectConnectionDetails().catch( (e) => log.error(`#fetchDirectConnectionDetails error: ${e}`), // this makes eslint happy, the method should never throw ); return undefined; } try { const response = await this.#fetchUsingDirectConnection( createV2Request(context, this.#connectionDetails.model_details), ); return response && { ...response, isDirectConnection: true }; } catch (e) { this.#directConnectionCircuitBreaker.error(); log.warn( 'Direct connection for code suggestions failed. Code suggestion requests will be sent to your GitLab instance.', e, ); } return undefined; } } References:" You are a code assistant,Definition of 'onDocumentChange' in file src/common/document_service.ts in project gitlab-lsp,"Definition: onDocumentChange(listener: TextDocumentChangeListener) { this.#emitter.on(DOCUMENT_CHANGE_EVENT_NAME, listener); return { dispose: () => this.#emitter.removeListener(DOCUMENT_CHANGE_EVENT_NAME, listener), }; } } References:" You are a code assistant,Definition of 'warn' in file src/common/log.ts in project gitlab-lsp,"Definition: warn(messageOrError: Error | string, trailingError?: Error | unknown) { this.#log(LOG_LEVEL.WARNING, messageOrError, trailingError); } error(messageOrError: Error | string, trailingError?: Error | unknown) { this.#log(LOG_LEVEL.ERROR, messageOrError, trailingError); } } // TODO: rename the export and replace usages of `log` with `Log`. export const log = new Log(); References:" You are a code assistant,Definition of 'isFetchError' in file src/common/fetch_error.ts in project gitlab-lsp,"Definition: 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/suggestion/streaming_handler.ts:177 - src/common/suggestion/suggestion_service.ts:338 - src/common/suggestion_client/direct_connection_client.ts:83 - src/common/fetch_error.test.ts:44 - src/common/fetch_error.test.ts:50" You are a code assistant,Definition of 'getProviderItems' in file src/common/ai_context_management_2/providers/ai_context_provider.ts in project gitlab-lsp,"Definition: getProviderItems( query: string, workspaceFolder: WorkspaceFolder[], ): Promise; } References:" You are a code assistant,Definition of 'AdditionalContext' in file src/common/api_types.ts in project gitlab-lsp,"Definition: export type AdditionalContext = { /** * The type of the context element. Options: `file` or `snippet`. */ type: 'file' | 'snippet'; /** * The name of the context element. A name of the file or a code snippet. */ name: string; /** * The content of the context element. The body of the file or a function. */ content: string; /** * Where the context was derived from */ resolution_strategy: ContextResolution['strategy']; }; // FIXME: Rename to SuggestionOptionText and then rename SuggestionOptionOrStream to SuggestionOption // this refactor can't be done now (2024-05-28) because all the conflicts it would cause with WIP export interface SuggestionOption { index?: number; text: string; uniqueTrackingId: string; lang?: string; } export interface TelemetryRequest { event: string; additional_properties: { unique_tracking_id: string; language?: string; suggestion_size?: number; timestamp: string; }; } References:" You are a code assistant,Definition of 'size' in file packages/lib_disposable/src/composite_disposable.ts in project gitlab-lsp,"Definition: get size() { return this.#disposables.size; } add(...disposables: Disposable[]): void { for (const disposable of disposables) { this.#disposables.add(disposable); } } dispose(): void { for (const disposable of this.#disposables) { disposable.dispose(); } this.#disposables.clear(); } } References:" You are a code assistant,Definition of 'addInstances' in file packages/lib_di/src/index.ts in project gitlab-lsp,"Definition: addInstances(...instances: BrandedInstance[]) { for (const instance of instances) { const metadata = injectableMetadata.get(instance); if (!metadata) { throw new Error( 'assertion error: addInstance invoked without branded object, make sure all arguments are branded with `brandInstance`', ); } if (this.#instances.has(metadata.id)) { throw new Error( `you are trying to add instance for interfaceId ${metadata.id}, but instance with this ID is already in the container.`, ); } this.#instances.set(metadata.id, instance); } } /** * instantiate accepts list of classes, validates that they can be managed by the container * and then initialized them in such order that dependencies of a class are initialized before the class */ instantiate(...classes: WithConstructor[]) { // ensure all classes have been decorated with @Injectable const undecorated = classes.filter((c) => !injectableMetadata.has(c)).map((c) => c.name); if (undecorated.length) { throw new Error(`Classes [${undecorated}] are not decorated with @Injectable.`); } const classesWithDeps: ClassWithDependencies[] = classes.map((cls) => { // we verified just above that all classes are present in the metadata map // eslint-disable-next-line @typescript-eslint/no-non-null-assertion const { id, dependencies } = injectableMetadata.get(cls)!; return { cls, id, dependencies }; }); const validators: Validator[] = [ interfaceUsedOnlyOnce, dependenciesArePresent, noCircularDependencies, ]; validators.forEach((v) => v(classesWithDeps, Array.from(this.#instances.keys()))); const classesById = new Map(); // Index classes by their interface id classesWithDeps.forEach((cwd) => { classesById.set(cwd.id, cwd); }); // Create instances in topological order for (const cwd of sortDependencies(classesById)) { const args = cwd.dependencies.map((dependencyId) => this.#instances.get(dependencyId)); // eslint-disable-next-line new-cap const instance = new cwd.cls(...args); this.#instances.set(cwd.id, instance); } } get(id: InterfaceId): T { const instance = this.#instances.get(id); if (!instance) { throw new Error(`Instance for interface '${sanitizeId(id)}' is not in the container.`); } return instance as T; } } References:" You are a code assistant,Definition of 'constructor' in file src/common/tree_sitter/empty_function/empty_function_resolver.ts in project gitlab-lsp,"Definition: constructor() { this.queryByLanguage = new Map(); } #getQueryByLanguage( language: TreeSitterLanguageName, treeSitterLanguage: Language, ): Query | undefined { const query = this.queryByLanguage.get(language); if (query) { return query; } const queryString = emptyFunctionQueries[language]; if (!queryString) { log.warn(`No empty function query found for: ${language}`); return undefined; } const newQuery = treeSitterLanguage.query(queryString); this.queryByLanguage.set(language, newQuery); return newQuery; } /** * Returns the comment that is directly above the cursor, if it exists. * To handle the case the comment may be several new lines above the cursor, * we traverse the tree to check if any nodes are between the comment and the cursor. */ isCursorInEmptyFunction({ languageName, tree, cursorPosition, treeSitterLanguage, }: { languageName: TreeSitterLanguageName; tree: Tree; treeSitterLanguage: Language; cursorPosition: Point; }): boolean { const query = this.#getQueryByLanguage(languageName, treeSitterLanguage); if (!query) { return false; } const emptyBodyPositions = query.captures(tree.rootNode).map((capture) => { return EmptyFunctionResolver.#findEmptyBodyPosition(capture.node); }); const cursorInsideInOneOfTheCaptures = emptyBodyPositions.some( (emptyBody) => EmptyFunctionResolver.#isValidBodyPosition(emptyBody) && EmptyFunctionResolver.#isCursorInsideNode( cursorPosition, emptyBody.startPosition, emptyBody.endPosition, ), ); return ( cursorInsideInOneOfTheCaptures || EmptyFunctionResolver.isCursorAfterEmptyPythonFunction({ languageName, tree, treeSitterLanguage, cursorPosition, }) ); } static #isCursorInsideNode( cursorPosition: Point, startPosition: Point, endPosition: Point, ): boolean { const { row: cursorRow, column: cursorColumn } = cursorPosition; const isCursorAfterNodeStart = cursorRow > startPosition.row || (cursorRow === startPosition.row && cursorColumn >= startPosition.column); const isCursorBeforeNodeEnd = cursorRow < endPosition.row || (cursorRow === endPosition.row && cursorColumn <= endPosition.column); return isCursorAfterNodeStart && isCursorBeforeNodeEnd; } static #isCursorRightAfterNode(cursorPosition: Point, endPosition: Point): boolean { const { row: cursorRow, column: cursorColumn } = cursorPosition; const isCursorRightAfterNode = cursorRow - endPosition.row === 1 || (cursorRow === endPosition.row && cursorColumn > endPosition.column); return isCursorRightAfterNode; } static #findEmptyBodyPosition(node: SyntaxNode): { startPosition?: Point; endPosition?: Point } { const startPosition = node.lastChild?.previousSibling?.endPosition; const endPosition = node.lastChild?.startPosition; return { startPosition, endPosition }; } static #isValidBodyPosition(arg: { startPosition?: Point; endPosition?: Point; }): arg is { startPosition: Point; endPosition: Point } { return !isUndefined(arg.startPosition) && !isUndefined(arg.endPosition); } static isCursorAfterEmptyPythonFunction({ languageName, tree, cursorPosition, treeSitterLanguage, }: { languageName: TreeSitterLanguageName; tree: Tree; treeSitterLanguage: Language; cursorPosition: Point; }): boolean { if (languageName !== 'python') return false; const pythonQuery = treeSitterLanguage.query(`[ (function_definition) (class_definition) ] @function`); const captures = pythonQuery.captures(tree.rootNode); if (captures.length === 0) return false; // Check if any function or class body is empty and cursor is after it return captures.some((capture) => { const bodyNode = capture.node.childForFieldName('body'); return ( bodyNode?.childCount === 0 && EmptyFunctionResolver.#isCursorRightAfterNode(cursorPosition, capture.node.endPosition) ); }); } } let emptyFunctionResolver: EmptyFunctionResolver; export function getEmptyFunctionResolver(): EmptyFunctionResolver { if (!emptyFunctionResolver) { emptyFunctionResolver = new EmptyFunctionResolver(); } return emptyFunctionResolver; } References:" You are a code assistant,Definition of 'CHAT_INPUT_TEMPLATE_17_2_AND_EARLIER' in file packages/webview_duo_chat/src/plugin/port/chat/gitlab_chat_api.ts in project gitlab-lsp,"Definition: export const CHAT_INPUT_TEMPLATE_17_2_AND_EARLIER = { query: gql` mutation chat( $question: String! $resourceId: AiModelID $currentFileContext: AiCurrentFileInput $clientSubscriptionId: String ) { aiAction( input: { chat: { resourceId: $resourceId, content: $question, currentFile: $currentFileContext } clientSubscriptionId: $clientSubscriptionId } ) { requestId errors } } `, defaultVariables: {}, }; export const CHAT_INPUT_TEMPLATE_17_3_AND_LATER = { query: gql` mutation chat( $question: String! $resourceId: AiModelID $currentFileContext: AiCurrentFileInput $clientSubscriptionId: String $platformOrigin: String! ) { aiAction( input: { chat: { resourceId: $resourceId, content: $question, currentFile: $currentFileContext } clientSubscriptionId: $clientSubscriptionId platformOrigin: $platformOrigin } ) { requestId errors } } `, defaultVariables: { platformOrigin: PLATFORM_ORIGIN, }, }; export type AiActionResponseType = { aiAction: { requestId: string; errors: string[] }; }; export const AI_MESSAGES_QUERY = gql` query getAiMessages($requestIds: [ID!], $roles: [AiMessageRole!]) { aiMessages(requestIds: $requestIds, roles: $roles) { nodes { requestId role content contentHtml timestamp errors extras { sources } } } } `; type AiMessageResponseType = { requestId: string; role: string; content: string; contentHtml: string; timestamp: string; errors: string[]; extras?: { sources: object[]; }; }; type AiMessagesResponseType = { aiMessages: { nodes: AiMessageResponseType[]; }; }; interface ErrorMessage { type: 'error'; requestId: string; role: 'system'; errors: string[]; } const errorResponse = (requestId: string, errors: string[]): ErrorMessage => ({ requestId, errors, role: 'system', type: 'error', }); interface SuccessMessage { type: 'message'; requestId: string; role: string; content: string; contentHtml: string; timestamp: string; errors: string[]; extras?: { sources: object[]; }; } const successResponse = (response: AiMessageResponseType): SuccessMessage => ({ type: 'message', ...response, }); type AiMessage = SuccessMessage | ErrorMessage; type ChatInputTemplate = { query: string; defaultVariables: { platformOrigin?: string; }; }; export class GitLabChatApi { #cachedActionQuery?: ChatInputTemplate = undefined; #manager: GitLabPlatformManagerForChat; constructor(manager: GitLabPlatformManagerForChat) { this.#manager = manager; } async processNewUserPrompt( question: string, subscriptionId?: string, currentFileContext?: GitLabChatFileContext, ): Promise { return this.#sendAiAction({ question, currentFileContext, clientSubscriptionId: subscriptionId, }); } async pullAiMessage(requestId: string, role: string): Promise { const response = await pullHandler(() => this.#getAiMessage(requestId, role)); if (!response) return errorResponse(requestId, ['Reached timeout while fetching response.']); return successResponse(response); } async cleanChat(): Promise { return this.#sendAiAction({ question: SPECIAL_MESSAGES.CLEAN }); } async #currentPlatform() { const platform = await this.#manager.getGitLabPlatform(); if (!platform) throw new Error('Platform is missing!'); return platform; } async #getAiMessage(requestId: string, role: string): Promise { const request: GraphQLRequest = { type: 'graphql', query: AI_MESSAGES_QUERY, variables: { requestIds: [requestId], roles: [role.toUpperCase()] }, }; const platform = await this.#currentPlatform(); const history = await platform.fetchFromApi(request); return history.aiMessages.nodes[0]; } async subscribeToUpdates( messageCallback: (message: AiCompletionResponseMessageType) => Promise, subscriptionId?: string, ) { const platform = await this.#currentPlatform(); const channel = new AiCompletionResponseChannel({ htmlResponse: true, userId: `gid://gitlab/User/${extractUserId(platform.account.id)}`, aiAction: 'CHAT', clientSubscriptionId: subscriptionId, }); const cable = await platform.connectToCable(); // we use this flag to fix https://gitlab.com/gitlab-org/gitlab-vscode-extension/-/issues/1397 // sometimes a chunk comes after the full message and it broke the chat let fullMessageReceived = false; channel.on('newChunk', async (msg) => { if (fullMessageReceived) { log.info(`CHAT-DEBUG: full message received, ignoring chunk`); return; } await messageCallback(msg); }); channel.on('fullMessage', async (message) => { fullMessageReceived = true; await messageCallback(message); if (subscriptionId) { cable.disconnect(); } }); cable.subscribe(channel); } async #sendAiAction(variables: object): Promise { const platform = await this.#currentPlatform(); const { query, defaultVariables } = await this.#actionQuery(); const projectGqlId = await this.#manager.getProjectGqlId(); const request: GraphQLRequest = { type: 'graphql', query, variables: { ...variables, ...defaultVariables, resourceId: projectGqlId ?? null, }, }; return platform.fetchFromApi(request); } async #actionQuery(): Promise { if (!this.#cachedActionQuery) { const platform = await this.#currentPlatform(); try { const { version } = await platform.fetchFromApi(versionRequest); this.#cachedActionQuery = ifVersionGte( version, MINIMUM_PLATFORM_ORIGIN_FIELD_VERSION, () => CHAT_INPUT_TEMPLATE_17_3_AND_LATER, () => CHAT_INPUT_TEMPLATE_17_2_AND_EARLIER, ); } catch (e) { log.debug(`GitLab version check for sending chat failed:`, e as Error); this.#cachedActionQuery = CHAT_INPUT_TEMPLATE_17_3_AND_LATER; } } return this.#cachedActionQuery; } } References:" You are a code assistant,Definition of 'hasbinSync' in file src/tests/int/hasbin.ts in project gitlab-lsp,"Definition: export function hasbinSync(bin: string) { return getPaths(bin).some(fileExistsSync); } export function hasbinAll(bins: string[], done: (result: boolean) => void) { async.every(bins, hasbin.async, done); } export function hasbinAllSync(bins: string[]) { return bins.every(hasbin.sync); } export function hasbinSome(bins: string[], done: (result: boolean) => void) { async.some(bins, hasbin.async, done); } export function hasbinSomeSync(bins: string[]) { return bins.some(hasbin.sync); } export function hasbinFirst(bins: string[], done: (result: boolean) => void) { async.detect(bins, hasbin.async, function (result) { done(result || false); }); } export function hasbinFirstSync(bins: string[]) { const matched = bins.filter(hasbin.sync); return matched.length ? matched[0] : false; } export function getPaths(bin: string) { const envPath = process.env.PATH || ''; const envExt = process.env.PATHEXT || ''; return envPath .replace(/[""]+/g, '') .split(delimiter) .map(function (chunk) { return envExt.split(delimiter).map(function (ext) { return join(chunk, bin + ext); }); }) .reduce(function (a, b) { return a.concat(b); }); } 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: - src/tests/int/fetch.test.ts:91" You are a code assistant,Definition of 'Container' in file packages/lib_di/src/index.ts in project gitlab-lsp,"Definition: export class Container { #instances = new Map(); /** * addInstances allows you to add pre-initialized objects to the container. * This is useful when you want to keep mandatory parameters in class' constructor (e.g. some runtime objects like server connection). * addInstances accepts a list of any objects that have been ""branded"" by the `brandInstance` method */ addInstances(...instances: BrandedInstance[]) { for (const instance of instances) { const metadata = injectableMetadata.get(instance); if (!metadata) { throw new Error( 'assertion error: addInstance invoked without branded object, make sure all arguments are branded with `brandInstance`', ); } if (this.#instances.has(metadata.id)) { throw new Error( `you are trying to add instance for interfaceId ${metadata.id}, but instance with this ID is already in the container.`, ); } this.#instances.set(metadata.id, instance); } } /** * instantiate accepts list of classes, validates that they can be managed by the container * and then initialized them in such order that dependencies of a class are initialized before the class */ instantiate(...classes: WithConstructor[]) { // ensure all classes have been decorated with @Injectable const undecorated = classes.filter((c) => !injectableMetadata.has(c)).map((c) => c.name); if (undecorated.length) { throw new Error(`Classes [${undecorated}] are not decorated with @Injectable.`); } const classesWithDeps: ClassWithDependencies[] = classes.map((cls) => { // we verified just above that all classes are present in the metadata map // eslint-disable-next-line @typescript-eslint/no-non-null-assertion const { id, dependencies } = injectableMetadata.get(cls)!; return { cls, id, dependencies }; }); const validators: Validator[] = [ interfaceUsedOnlyOnce, dependenciesArePresent, noCircularDependencies, ]; validators.forEach((v) => v(classesWithDeps, Array.from(this.#instances.keys()))); const classesById = new Map(); // Index classes by their interface id classesWithDeps.forEach((cwd) => { classesById.set(cwd.id, cwd); }); // Create instances in topological order for (const cwd of sortDependencies(classesById)) { const args = cwd.dependencies.map((dependencyId) => this.#instances.get(dependencyId)); // eslint-disable-next-line new-cap const instance = new cwd.cls(...args); this.#instances.set(cwd.id, instance); } } get(id: InterfaceId): T { const instance = this.#instances.get(id); if (!instance) { throw new Error(`Instance for interface '${sanitizeId(id)}' is not in the container.`); } return instance as T; } } References: - src/node/main.ts:92 - packages/lib_di/src/index.test.ts:50 - packages/lib_di/src/index.test.ts:53 - src/browser/main.ts:65" You are a code assistant,Definition of 'constructor' in file src/common/fetch_error.ts in project gitlab-lsp,"Definition: 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:" You are a code assistant,Definition of 'buildConnectionId' in file packages/lib_webview_transport_socket_io/src/utils/connection_utils.ts in project gitlab-lsp,"Definition: export function buildConnectionId( webviewInstanceInfo: WebviewInstanceInfo, ): WebviewSocketConnectionId { return `${webviewInstanceInfo.webviewId}:${webviewInstanceInfo.webviewInstanceId}` as WebviewSocketConnectionId; } References: - packages/lib_webview_transport_socket_io/src/socket_io_webview_transport.ts:63 - packages/lib_webview_transport_socket_io/src/socket_io_webview_transport.ts:132" You are a code assistant,Definition of 'getWorkspaceFiles' in file src/common/workspace/workspace_service.ts in project gitlab-lsp,"Definition: getWorkspaceFiles(workspaceFolder: WorkspaceFolder): FileSet | undefined { return this.#workspaceFilesMap.get(workspaceFolder.uri); } dispose() { this.#disposable.dispose(); } } References:" You are a code assistant,Definition of 'onRequest' in file packages/lib_webview/src/setup/plugin/webview_instance_message_bus.ts in project gitlab-lsp,"Definition: 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 'setupFileWatcher' in file src/common/services/fs/dir.ts in project gitlab-lsp,"Definition: setupFileWatcher(workspaceFolder: WorkspaceFolder, changeHandler: FileChangeHandler): void; } export const DirectoryWalker = createInterfaceId('DirectoryWalker'); @Injectable(DirectoryWalker, []) export class DefaultDirectoryWalker { /** * Returns a list of files in the specified directory that match the specified criteria. * The returned files will be the full paths to the files, they also will be in the form of URIs. * Example: [' file:///path/to/file.txt', 'file:///path/to/another/file.js'] */ // eslint-disable-next-line @typescript-eslint/no-unused-vars findFilesForDirectory(_args: DirectoryToSearch): Promise { return Promise.resolve([]); } // eslint-disable-next-line @typescript-eslint/no-unused-vars setupFileWatcher(workspaceFolder: WorkspaceFolder, changeHandler: FileChangeHandler) { throw new Error(`${workspaceFolder} ${changeHandler} not implemented`); } } References:" You are a code assistant,Definition of 'initialize' in file src/node/fetch.ts in project gitlab-lsp,"Definition: async initialize(): Promise { // Set http_proxy and https_proxy environment variables // which will then get picked up by the ProxyAgent and // used. try { const proxy = await getProxySettings(); if (proxy?.http) { process.env.http_proxy = `${proxy.http.protocol}://${proxy.http.host}:${proxy.http.port}`; log.debug(`fetch: Detected http proxy through settings: ${process.env.http_proxy}`); } if (proxy?.https) { process.env.https_proxy = `${proxy.https.protocol}://${proxy.https.host}:${proxy.https.port}`; log.debug(`fetch: Detected https proxy through settings: ${process.env.https_proxy}`); } if (!proxy?.http && !proxy?.https) { log.debug(`fetch: Detected no proxy settings`); } } catch (err) { log.warn('Unable to load proxy settings', err); } if (this.#userProxy) { log.debug(`fetch: Detected user proxy ${this.#userProxy}`); process.env.http_proxy = this.#userProxy; process.env.https_proxy = this.#userProxy; } if (process.env.http_proxy || process.env.https_proxy) { log.info( `fetch: Setting proxy to https_proxy=${process.env.https_proxy}; http_proxy=${process.env.http_proxy}`, ); this.#proxy = this.#createProxyAgent(); } this.#initialized = true; } async destroy(): Promise { this.#proxy?.destroy(); } async fetch(input: RequestInfo | URL, init?: RequestInit): Promise { 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 { let buffer = ''; const decoder = new TextDecoder(); async function* readStream( stream: ReadableStream, ): AsyncGenerator { 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 { 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: '' } : {}), ...(cert ? { cert: '' } : {}), ...(key ? { key: '' } : {}), }; } } References: - src/tests/fixtures/intent/empty_function/ruby.rb:17 - src/tests/fixtures/intent/empty_function/ruby.rb:25" You are a code assistant,Definition of 'versionRequest' in file packages/webview_duo_chat/src/plugin/port/gilab/check_version.ts in project gitlab-lsp,"Definition: export const versionRequest: ApiRequest = { type: 'rest', method: 'GET', path: '/version', }; References:" You are a code assistant,Definition of 'constructor' in file src/node/fetch.ts in project gitlab-lsp,"Definition: constructor(userProxy?: string) { super(); this.#agentOptions = { rejectUnauthorized: true, }; this.#userProxy = userProxy; this.#httpsAgent = this.#createHttpsAgent(); } async initialize(): Promise { // Set http_proxy and https_proxy environment variables // which will then get picked up by the ProxyAgent and // used. try { const proxy = await getProxySettings(); if (proxy?.http) { process.env.http_proxy = `${proxy.http.protocol}://${proxy.http.host}:${proxy.http.port}`; log.debug(`fetch: Detected http proxy through settings: ${process.env.http_proxy}`); } if (proxy?.https) { process.env.https_proxy = `${proxy.https.protocol}://${proxy.https.host}:${proxy.https.port}`; log.debug(`fetch: Detected https proxy through settings: ${process.env.https_proxy}`); } if (!proxy?.http && !proxy?.https) { log.debug(`fetch: Detected no proxy settings`); } } catch (err) { log.warn('Unable to load proxy settings', err); } if (this.#userProxy) { log.debug(`fetch: Detected user proxy ${this.#userProxy}`); process.env.http_proxy = this.#userProxy; process.env.https_proxy = this.#userProxy; } if (process.env.http_proxy || process.env.https_proxy) { log.info( `fetch: Setting proxy to https_proxy=${process.env.https_proxy}; http_proxy=${process.env.http_proxy}`, ); this.#proxy = this.#createProxyAgent(); } this.#initialized = true; } async destroy(): Promise { this.#proxy?.destroy(); } async fetch(input: RequestInfo | URL, init?: RequestInit): Promise { 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 { let buffer = ''; const decoder = new TextDecoder(); async function* readStream( stream: ReadableStream, ): AsyncGenerator { 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 { 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: '' } : {}), ...(cert ? { cert: '' } : {}), ...(key ? { key: '' } : {}), }; } } References:" You are a code assistant,Definition of 'DuoProjectAccessCache' in file src/common/services/duo_access/project_access_cache.ts in project gitlab-lsp,"Definition: export const DuoProjectAccessCache = createInterfaceId('DuoProjectAccessCache'); @Injectable(DuoProjectAccessCache, [DirectoryWalker, FileResolver, GitLabApiClient]) export class DefaultDuoProjectAccessCache { #duoProjects: Map; #eventEmitter = new EventEmitter(); constructor( private readonly directoryWalker: DirectoryWalker, private readonly fileResolver: FileResolver, private readonly api: GitLabApiClient, ) { this.#duoProjects = new Map(); } getProjectsForWorkspaceFolder(workspaceFolder: WorkspaceFolder): DuoProject[] { return this.#duoProjects.get(workspaceFolder.uri) ?? []; } async updateCache({ baseUrl, workspaceFolders, }: { baseUrl: string; workspaceFolders: WorkspaceFolder[]; }) { try { this.#duoProjects.clear(); const duoProjects = await Promise.all( workspaceFolders.map(async (workspaceFolder) => { return { workspaceFolder, projects: await this.#duoProjectsForWorkspaceFolder({ workspaceFolder, baseUrl, }), }; }), ); for (const { workspaceFolder, projects } of duoProjects) { this.#logProjectsInfo(projects, workspaceFolder); this.#duoProjects.set(workspaceFolder.uri, projects); } this.#triggerChange(); } catch (err) { log.error('DuoProjectAccessCache: failed to update project access cache', err); } } #logProjectsInfo(projects: DuoProject[], workspaceFolder: WorkspaceFolder) { if (!projects.length) { log.warn( `DuoProjectAccessCache: no projects found for workspace folder ${workspaceFolder.uri}`, ); return; } log.debug( `DuoProjectAccessCache: found ${projects.length} projects for workspace folder ${workspaceFolder.uri}: ${JSON.stringify(projects, null, 2)}`, ); } async #duoProjectsForWorkspaceFolder({ workspaceFolder, baseUrl, }: { workspaceFolder: WorkspaceFolder; baseUrl: string; }): Promise { const remotes = await this.#gitlabRemotesForWorkspaceFolder(workspaceFolder, baseUrl); const projects = await Promise.all( remotes.map(async (remote) => { const enabled = await this.#checkDuoFeaturesEnabled(remote.namespaceWithPath); return { projectPath: remote.projectPath, uri: remote.fileUri, enabled, host: remote.host, namespace: remote.namespace, namespaceWithPath: remote.namespaceWithPath, } satisfies DuoProject; }), ); return projects; } async #gitlabRemotesForWorkspaceFolder( workspaceFolder: WorkspaceFolder, baseUrl: string, ): Promise { const paths = await this.directoryWalker.findFilesForDirectory({ directoryUri: workspaceFolder.uri, filters: { fileEndsWith: ['/.git/config'], }, }); const remotes = await Promise.all( paths.map(async (fileUri) => this.#gitlabRemotesForFileUri(fileUri.toString(), baseUrl)), ); return remotes.flat(); } async #gitlabRemotesForFileUri( fileUri: string, baseUrl: string, ): Promise { const remoteUrls = await this.#remoteUrlsFromGitConfig(fileUri); return remoteUrls.reduce((acc, remoteUrl) => { const remote = parseGitLabRemote(remoteUrl, baseUrl); if (remote) { acc.push({ ...remote, fileUri }); } return acc; }, []); } async #remoteUrlsFromGitConfig(fileUri: string): Promise { try { const fileString = await this.fileResolver.readFile({ fileUri }); const config = ini.parse(fileString); return this.#getRemoteUrls(config); } catch (error) { log.error(`DuoProjectAccessCache: Failed to read git config file: ${fileUri}`, error); return []; } } #getRemoteUrls(config: GitConfig): string[] { return Object.keys(config).reduce((acc, section) => { if (section.startsWith('remote ')) { acc.push(config[section].url); } return acc; }, []); } async #checkDuoFeaturesEnabled(projectPath: string): Promise { try { const response = await this.api.fetchFromApi<{ project: GqlProjectWithDuoEnabledInfo }>({ type: 'graphql', query: duoFeaturesEnabledQuery, variables: { projectPath, }, } satisfies ApiRequest<{ project: GqlProjectWithDuoEnabledInfo }>); return Boolean(response?.project?.duoFeaturesEnabled); } catch (error) { log.error( `DuoProjectAccessCache: Failed to check if Duo features are enabled for project: ${projectPath}`, error, ); return true; } } onDuoProjectCacheUpdate( listener: (duoProjectsCache: Map) => void, ): Disposable { this.#eventEmitter.on(DUO_PROJECT_CACHE_UPDATE_EVENT, listener); return { dispose: () => this.#eventEmitter.removeListener(DUO_PROJECT_CACHE_UPDATE_EVENT, listener), }; } #triggerChange() { this.#eventEmitter.emit(DUO_PROJECT_CACHE_UPDATE_EVENT, this.#duoProjects); } } References: - src/common/services/duo_access/project_access_checker.test.ts:11 - src/common/feature_state/project_duo_acces_check.ts:44 - src/common/services/duo_access/project_access_checker.ts:20 - src/common/message_handler.ts:38 - src/common/connection.ts:34 - src/common/services/duo_access/project_access_checker.ts:22 - src/common/message_handler.ts:81" You are a code assistant,Definition of 'OAuthAccount' in file packages/webview_duo_chat/src/plugin/port/platform/gitlab_account.ts in project gitlab-lsp,"Definition: 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 'isWebviewInstanceDestroyedEventData' in file packages/lib_webview_transport/src/utils/message_validators.ts in project gitlab-lsp,"Definition: export const isWebviewInstanceDestroyedEventData: MessageValidator< WebviewInstanceDestroyedEventData > = (message: unknown): message is WebviewInstanceDestroyedEventData => isWebviewAddress(message); export const isWebviewInstanceMessageEventData: MessageValidator< WebviewInstanceNotificationEventData > = (message: unknown): message is WebviewInstanceNotificationEventData => isWebviewAddress(message) && 'type' in message; References:" You are a code assistant,Definition of 'TokenCheckNotificationType' in file src/common/notifications.ts in project gitlab-lsp,"Definition: export const TokenCheckNotificationType = new NotificationType( 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( '$/gitlab/didChangeDocumentInActiveEditor', ); References:" You are a code assistant,Definition of 'DefaultProjectDuoAccessCheck' in file src/common/feature_state/project_duo_acces_check.ts in project gitlab-lsp,"Definition: export class DefaultProjectDuoAccessCheck implements StateCheck { #subscriptions: Disposable[] = []; #stateEmitter = new EventEmitter(); #hasDuoAccess?: boolean; #duoProjectAccessChecker: DuoProjectAccessChecker; #configService: ConfigService; #currentDocument?: TextDocument; #isEnabledInSettings = true; constructor( documentService: DocumentService, configService: ConfigService, duoProjectAccessChecker: DuoProjectAccessChecker, duoProjectAccessCache: DuoProjectAccessCache, ) { this.#configService = configService; this.#duoProjectAccessChecker = duoProjectAccessChecker; this.#subscriptions.push( documentService.onDocumentChange(async (event, handlerType) => { if (handlerType === TextDocumentChangeListenerType.onDidSetActive) { this.#currentDocument = event.document; await this.#checkIfProjectHasDuoAccess(); } }), configService.onConfigChange(async (config) => { this.#isEnabledInSettings = config.client.duo?.enabledWithoutGitlabProject ?? true; await this.#checkIfProjectHasDuoAccess(); }), duoProjectAccessCache.onDuoProjectCacheUpdate(() => this.#checkIfProjectHasDuoAccess()), ); } onChanged(listener: (data: StateCheckChangedEventData) => void): Disposable { this.#stateEmitter.on('change', listener); return { dispose: () => this.#stateEmitter.removeListener('change', listener), }; } get engaged() { return !this.#hasDuoAccess; } async #checkIfProjectHasDuoAccess(): Promise { this.#hasDuoAccess = this.#isEnabledInSettings; if (!this.#currentDocument) { this.#stateEmitter.emit('change', this); return; } const workspaceFolder = await this.#getWorkspaceFolderForUri(this.#currentDocument.uri); if (workspaceFolder) { const status = this.#duoProjectAccessChecker.checkProjectStatus( this.#currentDocument.uri, workspaceFolder, ); if (status === DuoProjectStatus.DuoEnabled) { this.#hasDuoAccess = true; } else if (status === DuoProjectStatus.DuoDisabled) { this.#hasDuoAccess = false; } } this.#stateEmitter.emit('change', this); } id = DUO_DISABLED_FOR_PROJECT; details = 'Duo features are disabled for this project'; async #getWorkspaceFolderForUri(uri: URI): Promise { const workspaceFolders = await this.#configService.get('client.workspaceFolders'); return workspaceFolders?.find((folder) => uri.startsWith(folder.uri)); } dispose() { this.#subscriptions.forEach((s) => s.dispose()); } } References: - src/common/feature_state/project_duo_acces_check.test.ts:54" You are a code assistant,Definition of 'InlineSvgPlugin' in file packages/lib_vite_common_config/vite.config.shared.ts in project gitlab-lsp,"Definition: export const InlineSvgPlugin = { name: 'inline-svg', transform(code, id) { if (id.endsWith('@gitlab/svgs/dist/icons.svg')) { svgSpriteContent = fs.readFileSync(id, 'utf-8'); return 'export default """"'; } if (id.match(/@gitlab\/svgs\/dist\/illustrations\/.*\.svg$/)) { const base64Data = imageToBase64(id); return `export default ""data:image/svg+xml;base64,${base64Data}""`; } return code; }, }; export function createViteConfigForWebview(name): UserConfig { const outDir = path.resolve(__dirname, `../../../../out/webviews/${name}`); return { plugins: [vue2(), InlineSvgPlugin, SyncLoadScriptsPlugin, HtmlTransformPlugin], resolve: { alias: { '@': fileURLToPath(new URL('./src/app', import.meta.url)), }, }, root: './src/app', base: '', build: { target: 'es2022', emptyOutDir: true, outDir, rollupOptions: { input: [path.join('src', 'app', 'index.html')], }, }, }; } References:" You are a code assistant,Definition of 'getAdvancedContext' in file src/common/advanced_context/advanced_context_factory.ts in project gitlab-lsp,"Definition: export const getAdvancedContext = async ({ documentContext, dependencies: { duoProjectAccessChecker }, }: { documentContext: IDocContext; dependencies: { duoProjectAccessChecker: DuoProjectAccessChecker }; }): Promise => { try { const resolvers = advancedContextResolverFactories.map((factory) => factory()); const resolutions: ContextResolution[] = []; for (const resolver of resolvers) { // eslint-disable-next-line no-await-in-loop for await (const resolution of resolver.buildContext({ documentContext })) { resolutions.push(resolution); } } const filteredResolutions = await filterContextResolutions({ contextResolutions: resolutions, documentContext, dependencies: { duoProjectAccessChecker }, byteSizeLimit: CODE_SUGGESTIONS_REQUEST_BYTE_SIZE_LIMIT, }); log.debug(`Advanced Context Factory: using ${filteredResolutions.length} context resolutions `); return filteredResolutions; } catch (e) { log.error('Advanced Context: Error while getting advanced context', e); return []; } }; /** * Maps `ContextResolution` to the request body format `AdditionalContext`. * Note: We intentionally keep these two separate to avoid coupling the request body * format to the advanced context resolver internal data. */ export function advancedContextToRequestBody( advancedContext: ContextResolution[], ): AdditionalContext[] { return advancedContext.map((ac) => ({ type: ac.type, name: ac.fileRelativePath, content: ac.content, resolution_strategy: ac.strategy, })); } References: - src/common/suggestion/suggestion_service.ts:550 - src/common/advanced_context/advanced_context_factory.test.ts:75" You are a code assistant,Definition of 'getForSaaSAccount' in file packages/webview_duo_chat/src/plugin/port/platform/gitlab_platform.ts in project gitlab-lsp,"Definition: getForSaaSAccount(): Promise; } References:" You are a code assistant,Definition of 'render' in file packages/webview_duo_workflow/src/app/index.ts in project gitlab-lsp,"Definition: render(createElement) { return createElement(App); }, }).$mount(); } References:" You are a code assistant,Definition of 'FileExtension' in file src/tests/unit/tree_sitter/intent_resolver.test.ts in project gitlab-lsp,"Definition: type FileExtension = string; /** * Position refers to the position of the cursor in the test file. */ type IntentTestCase = [TestType, Position, Intent]; /** * Note: We use the language server procotol Ids here because `IDocContext` expects * these Ids (which is passed into `ParseFile`) and because they are unique. * `ParseFile` derives the tree sitter gramamr from the file's extension. * Some grammars apply to multiple extensions, eg. `typescript` applies * to both `.ts` and `.tsx`. */ const testCases: Array<[LanguageServerLanguageId, FileExtension, IntentTestCase[]]> = [ /* [ FIXME: add back support for vue 'vue', '.vue', // ../../fixtures/intent/vue_comments.vue [ ['on_empty_comment', { line: 2, character: 9 }, 'completion'], ['after_empty_comment', { line: 3, character: 0 }, 'completion'], ['on_non_empty_comment', { line: 4, character: 30 }, 'completion'], ['after_non_empty_comment', { line: 5, character: 0 }, 'generation'], ['in_block_comment', { line: 8, character: 23 }, 'completion'], ['on_block_comment', { line: 9, character: 2 }, 'completion'], ['after_block_comment', { line: 10, character: 0 }, 'generation'], ['no_comment_large_file', { line: 30, character: 0 }, undefined], // TODO: comments in the Vue `script` are not captured // ['on_comment_in_empty_function', { line: 34, character: 33 }, 'completion'], // ['after_comment_in_empty_function', { line: 35, character: 0 }, 'generation'], ], ], */ [ 'typescript', '.ts', // ../../fixtures/intent/typescript_comments.ts [ ['on_empty_comment', { line: 1, character: 3 }, 'completion'], ['after_empty_comment', { line: 2, character: 0 }, 'completion'], ['on_non_empty_comment', { line: 4, character: 30 }, 'completion'], ['after_non_empty_comment', { line: 5, character: 0 }, 'generation'], ['in_block_comment', { line: 8, character: 23 }, 'completion'], ['on_block_comment', { line: 9, character: 2 }, 'completion'], ['after_block_comment', { line: 10, character: 0 }, 'generation'], ['in_jsdoc_comment', { line: 14, character: 21 }, 'completion'], ['on_jsdoc_comment', { line: 15, character: 3 }, 'completion'], ['after_jsdoc_comment', { line: 16, character: 0 }, 'generation'], ['no_comment_large_file', { line: 24, character: 0 }, undefined], ['on_comment_in_empty_function', { line: 30, character: 31 }, 'completion'], ['after_comment_in_empty_function', { line: 31, character: 0 }, 'generation'], ], ], [ 'typescriptreact', '.tsx', // ../../fixtures/intent/typescriptreact_comments.tsx [ ['on_empty_comment', { line: 1, character: 3 }, 'completion'], ['after_empty_comment', { line: 2, character: 0 }, 'completion'], ['on_non_empty_comment', { line: 4, character: 30 }, 'completion'], ['after_non_empty_comment', { line: 5, character: 0 }, 'generation'], ['in_block_comment', { line: 8, character: 23 }, 'completion'], ['on_block_comment', { line: 9, character: 2 }, 'completion'], ['after_block_comment', { line: 10, character: 0 }, 'generation'], ['in_jsdoc_comment', { line: 14, character: 21 }, 'completion'], ['on_jsdoc_comment', { line: 15, character: 3 }, 'completion'], ['after_jsdoc_comment', { line: 16, character: 0 }, 'generation'], ['no_comment_large_file', { line: 24, character: 0 }, undefined], ['on_comment_in_empty_function', { line: 30, character: 31 }, 'completion'], ['after_comment_in_empty_function', { line: 31, character: 0 }, 'generation'], ], ], [ 'javascript', '.js', // ../../fixtures/intent/javascript_comments.js [ ['on_empty_comment', { line: 1, character: 3 }, 'completion'], ['after_empty_comment', { line: 2, character: 0 }, 'completion'], ['on_non_empty_comment', { line: 4, character: 30 }, 'completion'], ['after_non_empty_comment', { line: 5, character: 0 }, 'generation'], ['in_block_comment', { line: 8, character: 23 }, 'completion'], ['on_block_comment', { line: 9, character: 2 }, 'completion'], ['after_block_comment', { line: 10, character: 0 }, 'generation'], ['in_jsdoc_comment', { line: 14, character: 21 }, 'completion'], ['on_jsdoc_comment', { line: 15, character: 3 }, 'completion'], ['after_jsdoc_comment', { line: 16, character: 0 }, 'generation'], ['no_comment_large_file', { line: 24, character: 0 }, undefined], ['on_comment_in_empty_function', { line: 30, character: 31 }, 'completion'], ['after_comment_in_empty_function', { line: 31, character: 0 }, 'generation'], ], ], [ 'javascriptreact', '.jsx', // ../../fixtures/intent/javascriptreact_comments.jsx [ ['on_empty_comment', { line: 1, character: 3 }, 'completion'], ['after_empty_comment', { line: 2, character: 0 }, 'completion'], ['on_non_empty_comment', { line: 4, character: 30 }, 'completion'], ['after_non_empty_comment', { line: 5, character: 0 }, 'generation'], ['in_block_comment', { line: 8, character: 23 }, 'completion'], ['on_block_comment', { line: 9, character: 2 }, 'completion'], ['after_block_comment', { line: 10, character: 0 }, 'generation'], ['in_jsdoc_comment', { line: 15, character: 25 }, 'completion'], ['on_jsdoc_comment', { line: 16, character: 3 }, 'completion'], ['after_jsdoc_comment', { line: 17, character: 0 }, 'generation'], ['no_comment_large_file', { line: 24, character: 0 }, undefined], ['on_comment_in_empty_function', { line: 31, character: 31 }, 'completion'], ['after_comment_in_empty_function', { line: 32, character: 0 }, 'generation'], ], ], [ 'ruby', '.rb', // ../../fixtures/intent/ruby_comments.rb [ ['on_empty_comment', { line: 1, character: 3 }, 'completion'], ['after_empty_comment', { line: 2, character: 0 }, 'completion'], ['on_non_empty_comment', { line: 4, character: 30 }, 'completion'], ['after_non_empty_comment', { line: 5, character: 0 }, 'generation'], ['in_block_comment', { line: 9, character: 23 }, 'completion'], ['on_block_comment', { line: 10, character: 4 }, 'completion'], ['after_block_comment', { line: 11, character: 0 }, 'generation'], ['no_comment_large_file', { line: 17, character: 0 }, undefined], ['on_comment_in_empty_function', { line: 21, character: 30 }, 'completion'], ['after_comment_in_empty_function', { line: 22, character: 22 }, 'generation'], ], ], [ 'go', '.go', // ../../fixtures/intent/go_comments.go [ ['on_empty_comment', { line: 1, character: 3 }, 'completion'], ['after_empty_comment', { line: 2, character: 0 }, 'completion'], ['on_non_empty_comment', { line: 4, character: 30 }, 'completion'], ['after_non_empty_comment', { line: 5, character: 0 }, 'generation'], ['in_block_comment', { line: 8, character: 23 }, 'completion'], ['on_block_comment', { line: 9, character: 2 }, 'completion'], ['after_block_comment', { line: 10, character: 0 }, 'generation'], ['no_comment_large_file', { line: 20, character: 0 }, undefined], ['on_comment_in_empty_function', { line: 24, character: 31 }, 'completion'], ['after_comment_in_empty_function', { line: 25, character: 0 }, 'generation'], ], ], [ 'java', '.java', // ../../fixtures/intent/java_comments.java [ ['on_empty_comment', { line: 1, character: 3 }, 'completion'], ['after_empty_comment', { line: 2, character: 0 }, 'completion'], ['on_non_empty_comment', { line: 4, character: 30 }, 'completion'], ['after_non_empty_comment', { line: 5, character: 0 }, 'generation'], ['in_block_comment', { line: 8, character: 23 }, 'completion'], ['on_block_comment', { line: 9, character: 2 }, 'completion'], ['after_block_comment', { line: 10, character: 0 }, 'generation'], ['in_doc_comment', { line: 14, character: 29 }, 'completion'], ['on_doc_comment', { line: 15, character: 3 }, 'completion'], ['after_doc_comment', { line: 16, character: 0 }, 'generation'], ['no_comment_large_file', { line: 23, character: 0 }, undefined], ['on_comment_in_empty_function', { line: 30, character: 31 }, 'completion'], ['after_comment_in_empty_function', { line: 31, character: 0 }, 'generation'], ], ], [ 'kotlin', '.kt', // ../../fixtures/intent/kotlin_comments.kt [ ['on_empty_comment', { line: 1, character: 3 }, 'completion'], ['after_empty_comment', { line: 2, character: 0 }, 'completion'], ['on_non_empty_comment', { line: 4, character: 30 }, 'completion'], ['after_non_empty_comment', { line: 5, character: 0 }, 'generation'], ['in_block_comment', { line: 8, character: 23 }, 'completion'], ['on_block_comment', { line: 9, character: 2 }, 'completion'], ['after_block_comment', { line: 10, character: 0 }, 'generation'], ['in_doc_comment', { line: 14, character: 29 }, 'completion'], ['on_doc_comment', { line: 15, character: 3 }, 'completion'], ['after_doc_comment', { line: 16, character: 0 }, 'generation'], ['no_comment_large_file', { line: 23, character: 0 }, undefined], ['on_comment_in_empty_function', { line: 30, character: 31 }, 'completion'], ['after_comment_in_empty_function', { line: 31, character: 0 }, 'generation'], ], ], [ 'rust', '.rs', // ../../fixtures/intent/rust_comments.rs [ ['on_empty_comment', { line: 1, character: 3 }, 'completion'], ['after_empty_comment', { line: 2, character: 0 }, 'completion'], ['on_non_empty_comment', { line: 4, character: 30 }, 'completion'], ['after_non_empty_comment', { line: 5, character: 0 }, 'generation'], ['in_block_comment', { line: 8, character: 23 }, 'completion'], ['on_block_comment', { line: 9, character: 2 }, 'completion'], ['after_block_comment', { line: 10, character: 0 }, 'generation'], ['in_doc_comment', { line: 11, character: 25 }, 'completion'], ['on_doc_comment', { line: 12, character: 42 }, 'completion'], ['after_doc_comment', { line: 15, character: 0 }, 'generation'], ['no_comment_large_file', { line: 23, character: 0 }, undefined], ['on_comment_in_empty_function', { line: 26, character: 31 }, 'completion'], ['after_comment_in_empty_function', { line: 27, character: 0 }, 'generation'], ], ], [ 'yaml', '.yaml', // ../../fixtures/intent/yaml_comments.yaml [ ['on_empty_comment', { line: 1, character: 3 }, 'completion'], ['after_empty_comment', { line: 2, character: 0 }, 'completion'], ['on_non_empty_comment', { line: 4, character: 30 }, 'completion'], ['after_non_empty_comment', { line: 5, character: 0 }, 'generation'], ['no_comment_large_file', { line: 17, character: 0 }, undefined], ], ], [ 'html', '.html', // ../../fixtures/intent/html_comments.html [ ['on_empty_comment', { line: 14, character: 12 }, 'completion'], ['after_empty_comment', { line: 15, character: 0 }, 'completion'], ['on_non_empty_comment', { line: 8, character: 91 }, 'completion'], ['after_non_empty_comment', { line: 9, character: 0 }, 'generation'], ['in_block_comment', { line: 18, character: 29 }, 'completion'], ['on_block_comment', { line: 19, character: 7 }, 'completion'], ['after_block_comment', { line: 20, character: 0 }, 'generation'], ['no_comment_large_file', { line: 12, character: 66 }, undefined], ], ], [ 'c', '.c', // ../../fixtures/intent/c_comments.c [ ['on_empty_comment', { line: 1, character: 3 }, 'completion'], ['after_empty_comment', { line: 2, character: 0 }, 'completion'], ['on_non_empty_comment', { line: 4, character: 30 }, 'completion'], ['after_non_empty_comment', { line: 5, character: 0 }, 'generation'], ['in_block_comment', { line: 8, character: 23 }, 'completion'], ['on_block_comment', { line: 9, character: 2 }, 'completion'], ['after_block_comment', { line: 10, character: 0 }, 'generation'], ['no_comment_large_file', { line: 17, character: 0 }, undefined], ['on_comment_in_empty_function', { line: 20, character: 31 }, 'completion'], ['after_comment_in_empty_function', { line: 21, character: 0 }, 'generation'], ], ], [ 'cpp', '.cpp', // ../../fixtures/intent/cpp_comments.cpp [ ['on_empty_comment', { line: 1, character: 3 }, 'completion'], ['after_empty_comment', { line: 2, character: 0 }, 'completion'], ['on_non_empty_comment', { line: 4, character: 30 }, 'completion'], ['after_non_empty_comment', { line: 5, character: 0 }, 'generation'], ['in_block_comment', { line: 8, character: 23 }, 'completion'], ['on_block_comment', { line: 9, character: 2 }, 'completion'], ['after_block_comment', { line: 10, character: 0 }, 'generation'], ['no_comment_large_file', { line: 17, character: 0 }, undefined], ['on_comment_in_empty_function', { line: 20, character: 31 }, 'completion'], ['after_comment_in_empty_function', { line: 21, character: 0 }, 'generation'], ], ], [ 'c_sharp', '.cs', // ../../fixtures/intent/c_sharp_comments.cs [ ['on_empty_comment', { line: 1, character: 3 }, 'completion'], ['after_empty_comment', { line: 2, character: 0 }, 'completion'], ['on_non_empty_comment', { line: 4, character: 30 }, 'completion'], ['after_non_empty_comment', { line: 5, character: 0 }, 'generation'], ['in_block_comment', { line: 8, character: 23 }, 'completion'], ['on_block_comment', { line: 9, character: 2 }, 'completion'], ['after_block_comment', { line: 10, character: 0 }, 'generation'], ['no_comment_large_file', { line: 17, character: 0 }, undefined], ['on_comment_in_empty_function', { line: 20, character: 31 }, 'completion'], ['after_comment_in_empty_function', { line: 21, character: 22 }, 'generation'], ], ], [ 'css', '.css', // ../../fixtures/intent/css_comments.css [ ['on_empty_comment', { line: 1, character: 3 }, 'completion'], ['after_empty_comment', { line: 2, character: 0 }, 'completion'], ['on_non_empty_comment', { line: 3, character: 31 }, 'completion'], ['after_non_empty_comment', { line: 4, character: 0 }, 'generation'], ['in_block_comment', { line: 7, character: 23 }, 'completion'], ['on_block_comment', { line: 8, character: 2 }, 'completion'], ['after_block_comment', { line: 9, character: 0 }, 'generation'], ['no_comment_large_file', { line: 17, character: 0 }, undefined], ], ], [ 'bash', '.sh', // ../../fixtures/intent/bash_comments.css [ ['on_empty_comment', { line: 4, character: 1 }, 'completion'], ['after_empty_comment', { line: 5, character: 0 }, 'completion'], ['on_non_empty_comment', { line: 2, character: 65 }, 'completion'], ['after_non_empty_comment', { line: 3, character: 0 }, 'generation'], ['no_comment_large_file', { line: 10, character: 0 }, undefined], ['on_comment_in_empty_function', { line: 19, character: 12 }, 'completion'], ['after_comment_in_empty_function', { line: 20, character: 0 }, 'generation'], ], ], [ 'json', '.json', // ../../fixtures/intent/json_comments.css [ ['on_empty_comment', { line: 20, character: 3 }, 'completion'], ['after_empty_comment', { line: 21, character: 0 }, 'completion'], ['on_non_empty_comment', { line: 0, character: 38 }, 'completion'], ['after_non_empty_comment', { line: 1, character: 0 }, 'generation'], ['no_comment_large_file', { line: 10, character: 0 }, undefined], ], ], [ 'scala', '.scala', // ../../fixtures/intent/scala_comments.scala [ ['on_empty_comment', { line: 1, character: 3 }, 'completion'], ['after_empty_comment', { line: 2, character: 3 }, 'completion'], ['after_non_empty_comment', { line: 5, character: 0 }, 'generation'], ['after_block_comment', { line: 10, character: 0 }, 'generation'], ['no_comment_large_file', { line: 12, character: 0 }, undefined], ['after_comment_in_empty_function', { line: 21, character: 0 }, 'generation'], ], ], [ 'powersell', '.ps1', // ../../fixtures/intent/powershell_comments.ps1 [ ['on_empty_comment', { line: 20, character: 3 }, 'completion'], ['after_empty_comment', { line: 21, character: 3 }, 'completion'], ['after_non_empty_comment', { line: 10, character: 0 }, 'generation'], ['after_block_comment', { line: 8, character: 0 }, 'generation'], ['no_comment_large_file', { line: 22, character: 0 }, undefined], ['after_comment_in_empty_function', { line: 26, character: 0 }, 'generation'], ], ], ]; describe.each(testCases)('%s', (language, fileExt, cases) => { it.each(cases)('should resolve %s intent correctly', async (_, position, expectedIntent) => { const fixturePath = getFixturePath('intent', `${language}_comments${fileExt}`); const { treeAndLanguage, prefix, suffix } = await getTreeAndTestFile({ fixturePath, position, languageId: language, }); const intent = await getIntent({ treeAndLanguage, position, prefix, suffix }); expect(intent.intent).toBe(expectedIntent); if (expectedIntent === 'generation') { expect(intent.generationType).toBe('comment'); } }); }); }); describe('Empty Function Intent', () => { type TestType = | 'empty_function_declaration' | 'non_empty_function_declaration' | 'empty_function_expression' | 'non_empty_function_expression' | 'empty_arrow_function' | 'non_empty_arrow_function' | 'empty_method_definition' | 'non_empty_method_definition' | 'empty_class_constructor' | 'non_empty_class_constructor' | 'empty_class_declaration' | 'non_empty_class_declaration' | 'empty_anonymous_function' | 'non_empty_anonymous_function' | 'empty_implementation' | 'non_empty_implementation' | 'empty_closure_expression' | 'non_empty_closure_expression' | 'empty_generator' | 'non_empty_generator' | 'empty_macro' | 'non_empty_macro'; type FileExtension = string; /** * Position refers to the position of the cursor in the test file. */ type IntentTestCase = [TestType, Position, Intent]; const emptyFunctionTestCases: Array< [LanguageServerLanguageId, FileExtension, IntentTestCase[]] > = [ [ 'typescript', '.ts', // ../../fixtures/intent/empty_function/typescript.ts [ ['empty_function_declaration', { line: 0, character: 22 }, 'generation'], ['non_empty_function_declaration', { line: 3, character: 4 }, undefined], ['empty_function_expression', { line: 6, character: 32 }, 'generation'], ['non_empty_function_expression', { line: 10, character: 4 }, undefined], ['empty_arrow_function', { line: 12, character: 26 }, 'generation'], ['non_empty_arrow_function', { line: 15, character: 4 }, undefined], ['empty_class_constructor', { line: 19, character: 21 }, 'generation'], ['empty_method_definition', { line: 21, character: 11 }, 'generation'], ['non_empty_class_constructor', { line: 29, character: 7 }, undefined], ['non_empty_method_definition', { line: 33, character: 0 }, undefined], ['empty_class_declaration', { line: 36, character: 14 }, 'generation'], ['empty_generator', { line: 38, character: 31 }, 'generation'], ['non_empty_generator', { line: 41, character: 4 }, undefined], ], ], [ 'javascript', '.js', // ../../fixtures/intent/empty_function/javascript.js [ ['empty_function_declaration', { line: 0, character: 22 }, 'generation'], ['non_empty_function_declaration', { line: 3, character: 4 }, undefined], ['empty_function_expression', { line: 6, character: 32 }, 'generation'], ['non_empty_function_expression', { line: 10, character: 4 }, undefined], ['empty_arrow_function', { line: 12, character: 26 }, 'generation'], ['non_empty_arrow_function', { line: 15, character: 4 }, undefined], ['empty_class_constructor', { line: 19, character: 21 }, 'generation'], ['empty_method_definition', { line: 21, character: 11 }, 'generation'], ['non_empty_class_constructor', { line: 27, character: 7 }, undefined], ['non_empty_method_definition', { line: 31, character: 0 }, undefined], ['empty_class_declaration', { line: 34, character: 14 }, 'generation'], ['empty_generator', { line: 36, character: 31 }, 'generation'], ['non_empty_generator', { line: 39, character: 4 }, undefined], ], ], [ 'go', '.go', // ../../fixtures/intent/empty_function/go.go [ ['empty_function_declaration', { line: 0, character: 25 }, 'generation'], ['non_empty_function_declaration', { line: 3, character: 4 }, undefined], ['empty_anonymous_function', { line: 6, character: 32 }, 'generation'], ['non_empty_anonymous_function', { line: 10, character: 0 }, undefined], ['empty_method_definition', { line: 19, character: 25 }, 'generation'], ['non_empty_method_definition', { line: 23, character: 0 }, undefined], ], ], [ 'java', '.java', // ../../fixtures/intent/empty_function/java.java [ ['empty_function_declaration', { line: 0, character: 26 }, 'generation'], ['non_empty_function_declaration', { line: 3, character: 4 }, undefined], ['empty_anonymous_function', { line: 7, character: 0 }, 'generation'], ['non_empty_anonymous_function', { line: 10, character: 0 }, undefined], ['empty_class_declaration', { line: 15, character: 18 }, 'generation'], ['non_empty_class_declaration', { line: 19, character: 0 }, undefined], ['empty_class_constructor', { line: 18, character: 13 }, 'generation'], ['empty_method_definition', { line: 20, character: 18 }, 'generation'], ['non_empty_class_constructor', { line: 26, character: 18 }, undefined], ['non_empty_method_definition', { line: 30, character: 18 }, undefined], ], ], [ 'rust', '.rs', // ../../fixtures/intent/empty_function/rust.vue [ ['empty_function_declaration', { line: 0, character: 23 }, 'generation'], ['non_empty_function_declaration', { line: 3, character: 4 }, undefined], ['empty_implementation', { line: 8, character: 13 }, 'generation'], ['non_empty_implementation', { line: 11, character: 0 }, undefined], ['empty_class_constructor', { line: 13, character: 0 }, 'generation'], ['non_empty_class_constructor', { line: 23, character: 0 }, undefined], ['empty_method_definition', { line: 17, character: 0 }, 'generation'], ['non_empty_method_definition', { line: 26, character: 0 }, undefined], ['empty_closure_expression', { line: 32, character: 0 }, 'generation'], ['non_empty_closure_expression', { line: 36, character: 0 }, undefined], ['empty_macro', { line: 42, character: 11 }, 'generation'], ['non_empty_macro', { line: 45, character: 11 }, undefined], ['empty_macro', { line: 55, character: 0 }, 'generation'], ['non_empty_macro', { line: 62, character: 20 }, undefined], ], ], [ 'kotlin', '.kt', // ../../fixtures/intent/empty_function/kotlin.kt [ ['empty_function_declaration', { line: 0, character: 25 }, 'generation'], ['non_empty_function_declaration', { line: 4, character: 0 }, undefined], ['empty_anonymous_function', { line: 6, character: 32 }, 'generation'], ['non_empty_anonymous_function', { line: 9, character: 4 }, undefined], ['empty_class_declaration', { line: 12, character: 14 }, 'generation'], ['non_empty_class_declaration', { line: 15, character: 14 }, undefined], ['empty_method_definition', { line: 24, character: 0 }, 'generation'], ['non_empty_method_definition', { line: 28, character: 0 }, undefined], ], ], [ 'typescriptreact', '.tsx', // ../../fixtures/intent/empty_function/typescriptreact.tsx [ ['empty_function_declaration', { line: 0, character: 22 }, 'generation'], ['non_empty_function_declaration', { line: 3, character: 4 }, undefined], ['empty_function_expression', { line: 6, character: 32 }, 'generation'], ['non_empty_function_expression', { line: 10, character: 4 }, undefined], ['empty_arrow_function', { line: 12, character: 26 }, 'generation'], ['non_empty_arrow_function', { line: 15, character: 4 }, undefined], ['empty_class_constructor', { line: 19, character: 21 }, 'generation'], ['empty_method_definition', { line: 21, character: 11 }, 'generation'], ['non_empty_class_constructor', { line: 29, character: 7 }, undefined], ['non_empty_method_definition', { line: 33, character: 0 }, undefined], ['empty_class_declaration', { line: 36, character: 14 }, 'generation'], ['non_empty_arrow_function', { line: 40, character: 0 }, undefined], ['empty_arrow_function', { line: 41, character: 23 }, 'generation'], ['non_empty_arrow_function', { line: 44, character: 23 }, undefined], ['empty_generator', { line: 54, character: 31 }, 'generation'], ['non_empty_generator', { line: 57, character: 4 }, undefined], ], ], [ 'c', '.c', // ../../fixtures/intent/empty_function/c.c [ ['empty_function_declaration', { line: 0, character: 24 }, 'generation'], ['non_empty_function_declaration', { line: 3, character: 0 }, undefined], ], ], [ 'cpp', '.cpp', // ../../fixtures/intent/empty_function/cpp.cpp [ ['empty_function_declaration', { line: 0, character: 37 }, 'generation'], ['non_empty_function_declaration', { line: 3, character: 0 }, undefined], ['empty_function_expression', { line: 6, character: 43 }, 'generation'], ['non_empty_function_expression', { line: 10, character: 4 }, undefined], ['empty_class_constructor', { line: 15, character: 37 }, 'generation'], ['empty_method_definition', { line: 17, character: 18 }, 'generation'], ['non_empty_class_constructor', { line: 27, character: 7 }, undefined], ['non_empty_method_definition', { line: 31, character: 0 }, undefined], ['empty_class_declaration', { line: 35, character: 14 }, 'generation'], ], ], [ 'c_sharp', '.cs', // ../../fixtures/intent/empty_function/c_sharp.cs [ ['empty_function_expression', { line: 2, character: 48 }, 'generation'], ['empty_class_constructor', { line: 4, character: 31 }, 'generation'], ['empty_method_definition', { line: 6, character: 31 }, 'generation'], ['non_empty_class_constructor', { line: 15, character: 0 }, undefined], ['non_empty_method_definition', { line: 20, character: 0 }, undefined], ['empty_class_declaration', { line: 24, character: 22 }, 'generation'], ], ], [ 'bash', '.sh', // ../../fixtures/intent/empty_function/bash.sh [ ['empty_function_declaration', { line: 3, character: 48 }, 'generation'], ['non_empty_function_declaration', { line: 6, character: 31 }, undefined], ], ], [ 'scala', '.scala', // ../../fixtures/intent/empty_function/scala.scala [ ['empty_function_declaration', { line: 1, character: 4 }, 'generation'], ['non_empty_function_declaration', { line: 5, character: 4 }, undefined], ['empty_method_definition', { line: 28, character: 3 }, 'generation'], ['non_empty_method_definition', { line: 34, character: 3 }, undefined], ['empty_class_declaration', { line: 22, character: 4 }, 'generation'], ['non_empty_class_declaration', { line: 27, character: 0 }, undefined], ['empty_anonymous_function', { line: 13, character: 0 }, 'generation'], ['non_empty_anonymous_function', { line: 17, character: 0 }, undefined], ], ], [ 'ruby', '.rb', // ../../fixtures/intent/empty_function/ruby.rb [ ['empty_method_definition', { line: 0, character: 23 }, 'generation'], ['empty_method_definition', { line: 0, character: 6 }, undefined], ['non_empty_method_definition', { line: 3, character: 0 }, undefined], ['empty_anonymous_function', { line: 7, character: 27 }, 'generation'], ['non_empty_anonymous_function', { line: 9, character: 37 }, undefined], ['empty_anonymous_function', { line: 11, character: 25 }, 'generation'], ['empty_class_constructor', { line: 16, character: 22 }, 'generation'], ['non_empty_class_declaration', { line: 18, character: 0 }, undefined], ['empty_method_definition', { line: 20, character: 1 }, 'generation'], ['empty_class_declaration', { line: 33, character: 12 }, 'generation'], ], ], [ 'python', '.py', // ../../fixtures/intent/empty_function/python.py [ ['empty_function_declaration', { line: 1, character: 4 }, 'generation'], ['non_empty_function_declaration', { line: 5, character: 4 }, undefined], ['empty_class_constructor', { line: 10, character: 0 }, 'generation'], ['empty_method_definition', { line: 14, character: 0 }, 'generation'], ['non_empty_class_constructor', { line: 19, character: 0 }, undefined], ['non_empty_method_definition', { line: 23, character: 4 }, undefined], ['empty_class_declaration', { line: 27, character: 4 }, 'generation'], ['empty_function_declaration', { line: 31, character: 4 }, 'generation'], ['empty_class_constructor', { line: 36, character: 4 }, 'generation'], ['empty_method_definition', { line: 40, character: 4 }, 'generation'], ['empty_class_declaration', { line: 44, character: 4 }, 'generation'], ['empty_function_declaration', { line: 49, character: 4 }, 'generation'], ['empty_class_constructor', { line: 53, character: 4 }, 'generation'], ['empty_method_definition', { line: 56, character: 4 }, 'generation'], ['empty_class_declaration', { line: 59, character: 4 }, 'generation'], ], ], ]; describe.each(emptyFunctionTestCases)('%s', (language, fileExt, cases) => { it.each(cases)('should resolve %s intent correctly', async (_, position, expectedIntent) => { const fixturePath = getFixturePath('intent', `empty_function/${language}${fileExt}`); const { treeAndLanguage, prefix, suffix } = await getTreeAndTestFile({ fixturePath, position, languageId: language, }); const intent = await getIntent({ treeAndLanguage, position, prefix, suffix }); expect(intent.intent).toBe(expectedIntent); if (expectedIntent === 'generation') { expect(intent.generationType).toBe('empty_function'); } }); }); }); }); References:" You are a code assistant,Definition of 'getByteSize' in file src/common/utils/byte_size.ts in project gitlab-lsp,"Definition: export function getByteSize(str: string): number { return Buffer.from(str).byteLength; } References: - src/common/tracking/snowplow_tracker.test.ts:601 - src/common/tracking/snowplow_tracker.ts:489 - src/common/advanced_context/advanced_context_filters.ts:72 - src/common/advanced_context/lru_cache.test.ts:9 - src/common/tracking/snowplow_tracker.ts:492 - src/common/tracking/snowplow_tracker.test.ts:587 - src/common/tracking/snowplow_tracker.test.ts:588 - src/common/tracking/snowplow_tracker.test.ts:604 - src/common/tracking/snowplow_tracker.ts:500 - src/common/advanced_context/advanced_context_filters.ts:65 - src/common/advanced_context/lru_cache.ts:43 - src/common/tracking/snowplow_tracker.test.ts:589" You are a code assistant,Definition of 'Vulnerability' in file src/common/security_diagnostics_publisher.ts in project gitlab-lsp,"Definition: interface Vulnerability { name: string; description: string; severity: string; location: { start_line: number; end_line: number }; } export interface SecurityDiagnosticsPublisher extends DiagnosticsPublisher {} export const SecurityDiagnosticsPublisher = createInterfaceId( '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, 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/security_diagnostics_publisher.ts:110" You are a code assistant,Definition of 'WebviewInstanceResponseEventData' in file packages/lib_webview_transport/src/types.ts in project gitlab-lsp,"Definition: export type WebviewInstanceResponseEventData = WebviewAddress & WebviewRequestInfo & WebviewEventInfo & (SuccessfulResponse | FailedResponse); export type MessagesToServer = { webview_instance_created: WebviewInstanceCreatedEventData; webview_instance_destroyed: WebviewInstanceDestroyedEventData; webview_instance_notification_received: WebviewInstanceNotificationEventData; webview_instance_request_received: WebviewInstanceRequestEventData; webview_instance_response_received: WebviewInstanceResponseEventData; }; export type MessagesToClient = { webview_instance_notification: WebviewInstanceNotificationEventData; webview_instance_request: WebviewInstanceRequestEventData; webview_instance_response: WebviewInstanceResponseEventData; }; export interface TransportMessageHandler { (payload: T): void; } export interface TransportListener { on( type: K, callback: TransportMessageHandler, ): Disposable; } export interface TransportPublisher { publish(type: K, payload: MessagesToClient[K]): Promise; } export interface Transport extends TransportListener, TransportPublisher {} References: - packages/lib_webview_transport/src/types.ts:50 - packages/lib_webview_transport/src/types.ts:44" You are a code assistant,Definition of 'Category' in file src/tests/unit/tree_sitter/test_utils.ts in project gitlab-lsp,"Definition: export type Category = 'intent'; // add any more languages not in base languages (but supported by tree sitter) export type LanguageServerLanguageId = | (typeof BASE_SUPPORTED_CODE_SUGGESTIONS_LANGUAGES)[number] | 'yaml'; /** * Use this function to get the path of a fixture file. * Pulls from the `src/tests/fixtures` directory. */ export const getFixturePath = (category: Category, filePath: string) => resolve(cwd(), 'src', 'tests', 'fixtures', category, filePath); /** * Use this function to get the test file and tree for a given fixture file * to be used for Tree Sitter testing purposes. */ 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/test_utils.ts:21" You are a code assistant,Definition of 'advancedContextToRequestBody' in file src/common/advanced_context/advanced_context_factory.ts in project gitlab-lsp,"Definition: export function advancedContextToRequestBody( advancedContext: ContextResolution[], ): AdditionalContext[] { return advancedContext.map((ac) => ({ type: ac.type, name: ac.fileRelativePath, content: ac.content, resolution_strategy: ac.strategy, })); } References: - src/common/suggestion/suggestion_service.ts:555 - src/common/advanced_context/advanced_context_factory.test.ts:38" You are a code assistant,Definition of 'DocumentTransformerService' in file src/common/document_transformer_service.ts in project gitlab-lsp,"Definition: export interface DocumentTransformerService { get(uri: string): TextDocument | undefined; getContext( uri: string, position: Position, workspaceFolders: WorkspaceFolder[], completionContext?: InlineCompletionContext, ): IDocContext | undefined; transform(context: IDocContext): IDocContext; } export const DocumentTransformerService = createInterfaceId( 'DocumentTransformerService', ); @Injectable(DocumentTransformerService, [LsTextDocuments, SecretRedactor]) export class DefaultDocumentTransformerService implements DocumentTransformerService { #transformers: IDocTransformer[] = []; #documents: LsTextDocuments; 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: - src/common/advanced_context/advanced_context_service.ts:28 - src/common/suggestion/suggestion_service.ts:81 - src/common/advanced_context/advanced_context_service.ts:36 - src/common/suggestion/suggestion_service.ts:125 - src/common/connection.ts:22" You are a code assistant,Definition of 'checkToken' in file src/common/api.ts in project gitlab-lsp,"Definition: async checkToken(token: string = ''): Promise { try { if (this.#looksLikePatToken(token)) { log.info('Checking token for PAT validity'); return await this.#checkPatToken(token); } log.info('Checking token for OAuth validity'); return await this.#checkOAuthToken(token); } catch (err) { log.error('Error performing token check', err); return { valid: false, reason: 'unknown', message: `Failed to check token: ${err}`, }; } } #hasValidScopes(scopes: string[]): boolean { return scopes.includes('api'); } async getCodeSuggestions( request: CodeSuggestionRequest, ): Promise { if (!this.#token) { throw new Error('Token needs to be provided to request Code Suggestions'); } const headers = { ...this.#getDefaultHeaders(this.#token), 'Content-Type': 'application/json', }; const response = await this.#lsFetch.post( `${this.#baseURL}/api/v4/code_suggestions/completions`, { headers, body: JSON.stringify(request) }, ); await handleFetchError(response, 'Code Suggestions'); const data = await response.json(); return { ...data, status: response.status }; } async *getStreamingCodeSuggestions( request: CodeSuggestionRequest, ): AsyncGenerator { if (!this.#token) { throw new Error('Token needs to be provided to stream code suggestions'); } const headers = { ...this.#getDefaultHeaders(this.#token), 'Content-Type': 'application/json', }; yield* this.#lsFetch.streamFetch( `${this.#baseURL}/api/v4/code_suggestions/completions`, JSON.stringify(request), headers, ); } async fetchFromApi(request: ApiRequest): Promise { if (!this.#token) { return Promise.reject(new Error('Token needs to be provided to authorise API request.')); } if ( request.supportedSinceInstanceVersion && !this.#instanceVersionHigherOrEqualThen(request.supportedSinceInstanceVersion.version) ) { return Promise.reject( new InvalidInstanceVersionError( `Can't ${request.supportedSinceInstanceVersion.resourceName} until your instance is upgraded to ${request.supportedSinceInstanceVersion.version} or higher.`, ), ); } if (request.type === 'graphql') { return this.#graphqlRequest(request.query, request.variables); } switch (request.method) { case 'GET': return this.#fetch(request.path, request.searchParams, 'resource', request.headers); case 'POST': return this.#postFetch(request.path, 'resource', request.body, request.headers); default: // the type assertion is necessary because TS doesn't expect any other types throw new Error(`Unknown request type ${(request as ApiRequest).type}`); } } async connectToCable(): Promise { const headers = this.#getDefaultHeaders(this.#token); const websocketOptions = { headers: { ...headers, Origin: this.#baseURL, }, }; return connectToCable(this.#baseURL, websocketOptions); } async #graphqlRequest( document: RequestDocument, variables?: V, ): Promise { const ensureEndsWithSlash = (url: string) => url.replace(/\/?$/, '/'); const endpoint = new URL('./api/graphql', ensureEndsWithSlash(this.#baseURL)).href; // supports GitLab instances that are on a custom path, e.g. ""https://example.com/gitlab"" const graphqlFetch = async ( input: RequestInfo | URL, init?: RequestInit, ): Promise => { const url = input instanceof URL ? input.toString() : input; return this.#lsFetch.post(url, { ...init, headers: { ...headers, ...init?.headers }, }); }; const headers = this.#getDefaultHeaders(this.#token); const client = new GraphQLClient(endpoint, { headers, fetch: graphqlFetch, }); return client.request(document, variables); } async #fetch( apiResourcePath: string, query: Record = {}, resourceName = 'resource', headers?: Record, ): Promise { const url = `${this.#baseURL}/api/v4${apiResourcePath}${createQueryString(query)}`; const result = await this.#lsFetch.get(url, { headers: { ...this.#getDefaultHeaders(this.#token), ...headers }, }); await handleFetchError(result, resourceName); return result.json() as Promise; } async #postFetch( apiResourcePath: string, resourceName = 'resource', body?: unknown, headers?: Record, ): Promise { const url = `${this.#baseURL}/api/v4${apiResourcePath}`; const response = await this.#lsFetch.post(url, { headers: { 'Content-Type': 'application/json', ...this.#getDefaultHeaders(this.#token), ...headers, }, body: JSON.stringify(body), }); await handleFetchError(response, resourceName); return response.json() as Promise; } #getDefaultHeaders(token?: string) { return { Authorization: `Bearer ${token}`, 'User-Agent': `code-completions-language-server-experiment (${this.#clientInfo?.name}:${this.#clientInfo?.version})`, 'X-Gitlab-Language-Server-Version': getLanguageServerVersion(), }; } #instanceVersionHigherOrEqualThen(version: string): boolean { if (!this.#instanceVersion) return false; return semverCompare(this.#instanceVersion, version) >= 0; } async #getGitLabInstanceVersion(): Promise { if (!this.#token) { return ''; } const headers = this.#getDefaultHeaders(this.#token); const response = await this.#lsFetch.get(`${this.#baseURL}/api/v4/version`, { headers, }); const { version } = await response.json(); return version; } get instanceVersion() { return this.#instanceVersion; } } References:" You are a code assistant,Definition of 'transformIndexHtml' in file packages/lib_vite_common_config/vite.config.shared.ts in project gitlab-lsp,"Definition: transformIndexHtml(html) { const doc = NodeHtmlParser.parse(html); const body = doc.querySelector('body'); doc.querySelectorAll('head script').forEach((script) => { script.removeAttribute('type'); script.removeAttribute('crossorigin'); body?.appendChild(script); }); return doc.toString(); }, }; export const HtmlTransformPlugin = { name: 'html-transform', transformIndexHtml(html) { return html.replace('{{ svg placeholder }}', svgSpriteContent); }, }; export const InlineSvgPlugin = { name: 'inline-svg', transform(code, id) { if (id.endsWith('@gitlab/svgs/dist/icons.svg')) { svgSpriteContent = fs.readFileSync(id, 'utf-8'); return 'export default """"'; } if (id.match(/@gitlab\/svgs\/dist\/illustrations\/.*\.svg$/)) { const base64Data = imageToBase64(id); return `export default ""data:image/svg+xml;base64,${base64Data}""`; } return code; }, }; export function createViteConfigForWebview(name): UserConfig { const outDir = path.resolve(__dirname, `../../../../out/webviews/${name}`); return { plugins: [vue2(), InlineSvgPlugin, SyncLoadScriptsPlugin, HtmlTransformPlugin], resolve: { alias: { '@': fileURLToPath(new URL('./src/app', import.meta.url)), }, }, root: './src/app', base: '', build: { target: 'es2022', emptyOutDir: true, outDir, rollupOptions: { input: [path.join('src', 'app', 'index.html')], }, }, }; } References:" You are a code assistant,Definition of 'DirectoryWalker' in file src/common/services/fs/dir.ts in project gitlab-lsp,"Definition: export const DirectoryWalker = createInterfaceId('DirectoryWalker'); @Injectable(DirectoryWalker, []) export class DefaultDirectoryWalker { /** * Returns a list of files in the specified directory that match the specified criteria. * The returned files will be the full paths to the files, they also will be in the form of URIs. * Example: [' file:///path/to/file.txt', 'file:///path/to/another/file.js'] */ // eslint-disable-next-line @typescript-eslint/no-unused-vars findFilesForDirectory(_args: DirectoryToSearch): Promise { return Promise.resolve([]); } // eslint-disable-next-line @typescript-eslint/no-unused-vars setupFileWatcher(workspaceFolder: WorkspaceFolder, changeHandler: FileChangeHandler) { throw new Error(`${workspaceFolder} ${changeHandler} not implemented`); } } References: - src/common/services/duo_access/project_access_cache.ts:92 - src/common/services/fs/virtual_file_service.ts:46 - src/common/services/fs/virtual_file_service.ts:42" You are a code assistant,Definition of 'register' in file packages/lib_handler_registry/src/types.ts in project gitlab-lsp,"Definition: register(key: TKey, handler: THandler): Disposable; handle(key: TKey, ...args: Parameters): Promise>; dispose(): void; } References:" You are a code assistant,Definition of 'has' in file packages/lib_handler_registry/src/types.ts in project gitlab-lsp,"Definition: has(key: TKey): boolean; register(key: TKey, handler: THandler): Disposable; handle(key: TKey, ...args: Parameters): Promise>; dispose(): void; } References:" You are a code assistant,Definition of 'DisposeFunc' in file packages/lib_webview_plugin/src/webview_plugin.ts in project gitlab-lsp,"Definition: export type DisposeFunc = () => void; /** * Represents a structured message map for a webview plugin. */ export type PluginMessageMap = { extensionToPlugin: MessageDefinitions; pluginToExtension: MessageDefinitions; webviewToPlugin: MessageDefinitions; pluginToWebview: MessageDefinitions; }; /** * Utility type for creating a plugin message map with default values. This utility type helps plugin authors define the message map for their plugins without needing to specify every detail. It ensures that the required message structures are in place and provides sensible defaults for any unspecified parts. * * @template T - The partial message map provided by the plugin author. This type should extend `PartialDeep`. */ export type CreatePluginMessageMap> = { extensionToPlugin: CreateMessageDefinitions; pluginToExtension: CreateMessageDefinitions; webviewToPlugin: CreateMessageDefinitions; pluginToWebview: CreateMessageDefinitions; }; type WebviewPluginSetupParams = { webview: WebviewConnection<{ inbound: T['webviewToPlugin']; outbound: T['pluginToWebview']; }>; extension: MessageBus<{ inbound: T['extensionToPlugin']; outbound: T['pluginToExtension']; }>; }; /** * The `WebviewPluginSetupFunc` is responsible for setting up the communication between the webview plugin and the extension, as well as between the webview plugin and individual webview instances. * * @template TWebviewPluginMessageMap - Message types recognized by the plugin. * @param webviewMessageBus - The message bus for communication with individual webview instances. * @param extensionMessageBus - The message bus for communication with the webview host (extension). * @returns An optional function to dispose of resources when the plugin is unloaded. */ type WebviewPluginSetupFunc = ( context: WebviewPluginSetupParams, // eslint-disable-next-line @typescript-eslint/no-invalid-void-type ) => Disposable | void; /** * The `WebviewPlugin` is a user implemented type defining the integration of the webview plugin with a webview host (extension) and webview instances. * * @template TWebviewPluginMessageMap - Message types recognized by the plugin. */ export type WebviewPlugin< TWebviewPluginMessageMap extends PartialDeep = PluginMessageMap, > = { id: WebviewId; title: string; setup: WebviewPluginSetupFunc>; }; References:" You are a code assistant,Definition of 'canClientTrackEvent' in file src/common/tracking/utils.ts in project gitlab-lsp,"Definition: export const canClientTrackEvent = ( actions: Array<{ action: TRACKING_EVENTS }> = [], event: TRACKING_EVENTS, ) => { return actions.some(({ action }) => action === event); }; export const generateUniqueTrackingId = (): string => { return uuidv4(); }; References: - src/common/tracking/snowplow_tracker.ts:270 - src/common/tracking/instance_tracker.ts:97 - src/common/tracking/snowplow_tracker.ts:271 - src/common/message_handler.ts:137 - src/common/tracking/instance_tracker.ts:98 - src/common/suggestion/suggestion_service.ts:372" You are a code assistant,Definition of 'CODE_SUGGESTIONS_REQUEST_BYTE_SIZE_LIMIT' in file src/common/advanced_context/helpers.ts in project gitlab-lsp,"Definition: export const CODE_SUGGESTIONS_REQUEST_BYTE_SIZE_LIMIT = 50000; // 50KB /** * This is the maxium byte size of the LRU cache used for Open Tabs */ export const LRU_CACHE_BYTE_SIZE_LIMIT = 24 * 1024 * 1024; // 24MB /** * Determines if the advanced context resolver should be used for code suggestions. * Because the Code Suggestions API has other consumers than the language server, * we gate the advanced context resolver behind a feature flag separately. */ export const shouldUseAdvancedContext = ( featureFlagService: FeatureFlagService, configService: ConfigService, ) => { const isEditorAdvancedContextEnabled = featureFlagService.isInstanceFlagEnabled( InstanceFeatureFlags.EditorAdvancedContext, ); const isGenericContextEnabled = featureFlagService.isInstanceFlagEnabled( InstanceFeatureFlags.CodeSuggestionsContext, ); let isEditorOpenTabsContextEnabled = configService.get('client.openTabsContext'); if (isEditorOpenTabsContextEnabled === undefined) { isEditorOpenTabsContextEnabled = true; } /** * TODO - when we introduce other context resolution strategies, * have `isEditorOpenTabsContextEnabled` only disable the corresponding resolver (`lruResolver`) * https://gitlab.com/gitlab-org/editor-extensions/gitlab-lsp/-/issues/298 * https://gitlab.com/groups/gitlab-org/editor-extensions/-/epics/59#note_1981542181 */ return ( isEditorAdvancedContextEnabled && isGenericContextEnabled && isEditorOpenTabsContextEnabled ); }; References:" You are a code assistant,Definition of 'getCodeSuggestions' in file src/common/api.ts in project gitlab-lsp,"Definition: getCodeSuggestions(request: CodeSuggestionRequest): Promise; getStreamingCodeSuggestions(request: CodeSuggestionRequest): AsyncGenerator; fetchFromApi(request: ApiRequest): Promise; connectToCable(): Promise; onApiReconfigured(listener: (data: ApiReconfiguredData) => void): Disposable; readonly instanceVersion?: string; } export const GitLabApiClient = createInterfaceId('GitLabApiClient'); export type GenerationType = 'comment' | 'small_file' | 'empty_function' | undefined; export interface CodeSuggestionRequest { prompt_version: number; project_path: string; model_provider?: string; project_id: number; current_file: CodeSuggestionRequestCurrentFile; intent?: 'completion' | 'generation'; stream?: boolean; /** how many suggestion options should the API return */ choices_count?: number; /** additional context to provide to the model */ context?: AdditionalContext[]; /* A user's instructions for code suggestions. */ user_instruction?: string; /* The backend can add additional prompt info based on the type of event */ generation_type?: GenerationType; } export interface CodeSuggestionRequestCurrentFile { file_name: string; content_above_cursor: string; content_below_cursor: string; } export interface CodeSuggestionResponse { choices?: SuggestionOption[]; model?: ICodeSuggestionModel; status: number; error?: string; isDirectConnection?: boolean; } // FIXME: Rename to SuggestionOptionStream when renaming the SuggestionOption export interface StartStreamOption { uniqueTrackingId: string; /** the streamId represents the beginning of a stream * */ streamId: string; } export type SuggestionOptionOrStream = SuggestionOption | StartStreamOption; export interface PersonalAccessToken { name: string; scopes: string[]; active: boolean; } export interface OAuthToken { scope: string[]; } export interface TokenCheckResponse { valid: boolean; reason?: 'unknown' | 'not_active' | 'invalid_scopes'; message?: string; } export interface IDirectConnectionDetailsHeaders { 'X-Gitlab-Global-User-Id': string; 'X-Gitlab-Instance-Id': string; 'X-Gitlab-Host-Name': string; 'X-Gitlab-Saas-Duo-Pro-Namespace-Ids': string; } export interface IDirectConnectionModelDetails { model_provider: string; model_name: string; } export interface IDirectConnectionDetails { base_url: string; token: string; expires_at: number; headers: IDirectConnectionDetailsHeaders; model_details: IDirectConnectionModelDetails; } const CONFIG_CHANGE_EVENT_NAME = 'apiReconfigured'; @Injectable(GitLabApiClient, [LsFetch, ConfigService]) export class GitLabAPI implements GitLabApiClient { #token: string | undefined; #baseURL: string; #clientInfo?: IClientInfo; #lsFetch: LsFetch; #eventEmitter = new EventEmitter(); #configService: ConfigService; #instanceVersion?: string; constructor(lsFetch: LsFetch, configService: ConfigService) { this.#baseURL = GITLAB_API_BASE_URL; this.#lsFetch = lsFetch; this.#configService = configService; this.#configService.onConfigChange(async (config) => { this.#clientInfo = configService.get('client.clientInfo'); this.#lsFetch.updateAgentOptions({ ignoreCertificateErrors: this.#configService.get('client.ignoreCertificateErrors') ?? false, ...(this.#configService.get('client.httpAgentOptions') ?? {}), }); await this.configureApi(config.client); }); } onApiReconfigured(listener: (data: ApiReconfiguredData) => void): Disposable { this.#eventEmitter.on(CONFIG_CHANGE_EVENT_NAME, listener); return { dispose: () => this.#eventEmitter.removeListener(CONFIG_CHANGE_EVENT_NAME, listener) }; } #fireApiReconfigured(isInValidState: boolean, validationMessage?: string) { const data: ApiReconfiguredData = { isInValidState, validationMessage }; this.#eventEmitter.emit(CONFIG_CHANGE_EVENT_NAME, data); } async configureApi({ token, baseUrl = GITLAB_API_BASE_URL, }: { token?: string; baseUrl?: string; }) { if (this.#token === token && this.#baseURL === baseUrl) return; this.#token = token; this.#baseURL = baseUrl; const { valid, reason, message } = await this.checkToken(this.#token); let validationMessage; if (!valid) { this.#configService.set('client.token', undefined); validationMessage = `Token is invalid. ${message}. Reason: ${reason}`; log.warn(validationMessage); } else { log.info('Token is valid'); } this.#instanceVersion = await this.#getGitLabInstanceVersion(); this.#fireApiReconfigured(valid, validationMessage); } #looksLikePatToken(token: string): boolean { // OAuth tokens will be longer than 42 characters and PATs will be shorter. return token.length < 42; } async #checkPatToken(token: string): Promise { const headers = this.#getDefaultHeaders(token); const response = await this.#lsFetch.get( `${this.#baseURL}/api/v4/personal_access_tokens/self`, { headers }, ); await handleFetchError(response, 'Information about personal access token'); const { active, scopes } = (await response.json()) as PersonalAccessToken; if (!active) { return { valid: false, reason: 'not_active', message: 'Token is not active.', }; } if (!this.#hasValidScopes(scopes)) { const joinedScopes = scopes.map((scope) => `'${scope}'`).join(', '); return { valid: false, reason: 'invalid_scopes', message: `Token has scope(s) ${joinedScopes} (needs 'api').`, }; } return { valid: true }; } async #checkOAuthToken(token: string): Promise { const headers = this.#getDefaultHeaders(token); const response = await this.#lsFetch.get(`${this.#baseURL}/oauth/token/info`, { headers, }); await handleFetchError(response, 'Information about OAuth token'); const { scope: scopes } = (await response.json()) as OAuthToken; if (!this.#hasValidScopes(scopes)) { const joinedScopes = scopes.map((scope) => `'${scope}'`).join(', '); return { valid: false, reason: 'invalid_scopes', message: `Token has scope(s) ${joinedScopes} (needs 'api').`, }; } return { valid: true }; } async checkToken(token: string = ''): Promise { try { if (this.#looksLikePatToken(token)) { log.info('Checking token for PAT validity'); return await this.#checkPatToken(token); } log.info('Checking token for OAuth validity'); return await this.#checkOAuthToken(token); } catch (err) { log.error('Error performing token check', err); return { valid: false, reason: 'unknown', message: `Failed to check token: ${err}`, }; } } #hasValidScopes(scopes: string[]): boolean { return scopes.includes('api'); } async getCodeSuggestions( request: CodeSuggestionRequest, ): Promise { if (!this.#token) { throw new Error('Token needs to be provided to request Code Suggestions'); } const headers = { ...this.#getDefaultHeaders(this.#token), 'Content-Type': 'application/json', }; const response = await this.#lsFetch.post( `${this.#baseURL}/api/v4/code_suggestions/completions`, { headers, body: JSON.stringify(request) }, ); await handleFetchError(response, 'Code Suggestions'); const data = await response.json(); return { ...data, status: response.status }; } async *getStreamingCodeSuggestions( request: CodeSuggestionRequest, ): AsyncGenerator { if (!this.#token) { throw new Error('Token needs to be provided to stream code suggestions'); } const headers = { ...this.#getDefaultHeaders(this.#token), 'Content-Type': 'application/json', }; yield* this.#lsFetch.streamFetch( `${this.#baseURL}/api/v4/code_suggestions/completions`, JSON.stringify(request), headers, ); } async fetchFromApi(request: ApiRequest): Promise { if (!this.#token) { return Promise.reject(new Error('Token needs to be provided to authorise API request.')); } if ( request.supportedSinceInstanceVersion && !this.#instanceVersionHigherOrEqualThen(request.supportedSinceInstanceVersion.version) ) { return Promise.reject( new InvalidInstanceVersionError( `Can't ${request.supportedSinceInstanceVersion.resourceName} until your instance is upgraded to ${request.supportedSinceInstanceVersion.version} or higher.`, ), ); } if (request.type === 'graphql') { return this.#graphqlRequest(request.query, request.variables); } switch (request.method) { case 'GET': return this.#fetch(request.path, request.searchParams, 'resource', request.headers); case 'POST': return this.#postFetch(request.path, 'resource', request.body, request.headers); default: // the type assertion is necessary because TS doesn't expect any other types throw new Error(`Unknown request type ${(request as ApiRequest).type}`); } } async connectToCable(): Promise { const headers = this.#getDefaultHeaders(this.#token); const websocketOptions = { headers: { ...headers, Origin: this.#baseURL, }, }; return connectToCable(this.#baseURL, websocketOptions); } async #graphqlRequest( document: RequestDocument, variables?: V, ): Promise { const ensureEndsWithSlash = (url: string) => url.replace(/\/?$/, '/'); const endpoint = new URL('./api/graphql', ensureEndsWithSlash(this.#baseURL)).href; // supports GitLab instances that are on a custom path, e.g. ""https://example.com/gitlab"" const graphqlFetch = async ( input: RequestInfo | URL, init?: RequestInit, ): Promise => { const url = input instanceof URL ? input.toString() : input; return this.#lsFetch.post(url, { ...init, headers: { ...headers, ...init?.headers }, }); }; const headers = this.#getDefaultHeaders(this.#token); const client = new GraphQLClient(endpoint, { headers, fetch: graphqlFetch, }); return client.request(document, variables); } async #fetch( apiResourcePath: string, query: Record = {}, resourceName = 'resource', headers?: Record, ): Promise { const url = `${this.#baseURL}/api/v4${apiResourcePath}${createQueryString(query)}`; const result = await this.#lsFetch.get(url, { headers: { ...this.#getDefaultHeaders(this.#token), ...headers }, }); await handleFetchError(result, resourceName); return result.json() as Promise; } async #postFetch( apiResourcePath: string, resourceName = 'resource', body?: unknown, headers?: Record, ): Promise { const url = `${this.#baseURL}/api/v4${apiResourcePath}`; const response = await this.#lsFetch.post(url, { headers: { 'Content-Type': 'application/json', ...this.#getDefaultHeaders(this.#token), ...headers, }, body: JSON.stringify(body), }); await handleFetchError(response, resourceName); return response.json() as Promise; } #getDefaultHeaders(token?: string) { return { Authorization: `Bearer ${token}`, 'User-Agent': `code-completions-language-server-experiment (${this.#clientInfo?.name}:${this.#clientInfo?.version})`, 'X-Gitlab-Language-Server-Version': getLanguageServerVersion(), }; } #instanceVersionHigherOrEqualThen(version: string): boolean { if (!this.#instanceVersion) return false; return semverCompare(this.#instanceVersion, version) >= 0; } async #getGitLabInstanceVersion(): Promise { if (!this.#token) { return ''; } const headers = this.#getDefaultHeaders(this.#token); const response = await this.#lsFetch.get(`${this.#baseURL}/api/v4/version`, { headers, }); const { version } = await response.json(); return version; } get instanceVersion() { return this.#instanceVersion; } } References:" You are a code assistant,Definition of 'SocketIoRequestMessage' in file packages/lib_webview_transport_socket_io/src/utils/message_utils.ts in project gitlab-lsp,"Definition: 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 'SOCKET_REQUEST_CHANNEL' in file packages/lib_webview_client/src/bus/provider/socket_io_message_bus.ts in project gitlab-lsp,"Definition: export const SOCKET_REQUEST_CHANNEL = 'request'; export const SOCKET_RESPONSE_CHANNEL = 'response'; export type SocketEvents = | typeof SOCKET_NOTIFICATION_CHANNEL | typeof SOCKET_REQUEST_CHANNEL | typeof SOCKET_RESPONSE_CHANNEL; export class SocketIoMessageBus implements MessageBus { #notificationHandlers = new SimpleRegistry(); #requestHandlers = new SimpleRegistry(); #pendingRequests = new SimpleRegistry(); #socket: Socket; constructor(socket: Socket) { this.#socket = socket; this.#setupSocketEventHandlers(); } async sendNotification( messageType: T, payload?: TMessages['outbound']['notifications'][T], ): Promise { this.#socket.emit(SOCKET_NOTIFICATION_CHANNEL, { type: messageType, payload }); } sendRequest( type: T, payload?: TMessages['outbound']['requests'][T]['params'], ): Promise> { const requestId = generateRequestId(); let timeout: NodeJS.Timeout | undefined; return new Promise((resolve, reject) => { const pendingRequestDisposable = this.#pendingRequests.register( requestId, (value: ExtractRequestResult) => { resolve(value); clearTimeout(timeout); pendingRequestDisposable.dispose(); }, ); timeout = setTimeout(() => { pendingRequestDisposable.dispose(); reject(new Error('Request timed out')); }, REQUEST_TIMEOUT_MS); this.#socket.emit(SOCKET_REQUEST_CHANNEL, { requestId, type, payload, }); }); } onNotification( messageType: T, callback: (payload: TMessages['inbound']['notifications'][T]) => void, ): Disposable { return this.#notificationHandlers.register(messageType, callback); } onRequest( type: T, handler: ( payload: TMessages['inbound']['requests'][T]['params'], ) => Promise>, ): Disposable { return this.#requestHandlers.register(type, handler); } dispose() { this.#socket.off(SOCKET_NOTIFICATION_CHANNEL, this.#handleNotificationMessage); this.#socket.off(SOCKET_REQUEST_CHANNEL, this.#handleRequestMessage); this.#socket.off(SOCKET_RESPONSE_CHANNEL, this.#handleResponseMessage); this.#notificationHandlers.dispose(); this.#requestHandlers.dispose(); this.#pendingRequests.dispose(); } #setupSocketEventHandlers = () => { this.#socket.on(SOCKET_NOTIFICATION_CHANNEL, this.#handleNotificationMessage); this.#socket.on(SOCKET_REQUEST_CHANNEL, this.#handleRequestMessage); this.#socket.on(SOCKET_RESPONSE_CHANNEL, this.#handleResponseMessage); }; #handleNotificationMessage = async (message: { type: keyof TMessages['inbound']['notifications'] & string; payload: unknown; }) => { await this.#notificationHandlers.handle(message.type, message.payload); }; #handleRequestMessage = async (message: { requestId: string; event: keyof TMessages['inbound']['requests'] & string; payload: unknown; }) => { const response = await this.#requestHandlers.handle(message.event, message.payload); this.#socket.emit(SOCKET_RESPONSE_CHANNEL, { requestId: message.requestId, payload: response, }); }; #handleResponseMessage = async (message: { requestId: string; payload: unknown }) => { await this.#pendingRequests.handle(message.requestId, message.payload); }; } References:" You are a code assistant,Definition of 'publish' in file packages/lib_webview_transport_json_rpc/src/json_rpc_connection_transport.ts in project gitlab-lsp,"Definition: publish(type: K, payload: MessagesToClient[K]): Promise { if (type === 'webview_instance_notification') { return this.#connection.sendNotification(this.#notificationChannel, payload); } throw new Error(`Unknown message type: ${type}`); } dispose(): void { this.#messageEmitter.removeAllListeners(); this.#disposables.forEach((disposable) => disposable.dispose()); this.#logger?.debug('JsonRpcConnectionTransport disposed'); } } References:" You are a code assistant,Definition of 'dispose' in file src/common/git/ignore_manager.ts in project gitlab-lsp,"Definition: dispose(): void { this.#ignoreTrie.dispose(); } } References:" You are a code assistant,Definition of 'GITLAB_ORG_URL' in file packages/webview_duo_chat/src/plugin/port/chat/get_platform_manager_for_chat.ts in project gitlab-lsp,"Definition: export const GITLAB_ORG_URL: string = 'https://dev.gitlab.org'; export const GITLAB_DEVELOPMENT_URL: string = 'http://localhost'; export enum GitLabEnvironment { GITLAB_COM = 'production', GITLAB_STAGING = 'staging', GITLAB_ORG = 'org', GITLAB_DEVELOPMENT = 'development', GITLAB_SELF_MANAGED = 'self-managed', } export class GitLabPlatformManagerForChat { readonly #platformManager: GitLabPlatformManager; constructor(platformManager: GitLabPlatformManager) { this.#platformManager = platformManager; } async getProjectGqlId(): Promise { const projectManager = await this.#platformManager.getForActiveProject(false); return projectManager?.project.gqlId; } /** * Obtains a GitLab Platform to send API requests to the GitLab API * for the Duo Chat feature. * * - It returns a GitLabPlatformForAccount for the first linked account. * - It returns undefined if there are no accounts linked */ async getGitLabPlatform(): Promise { const platforms = await this.#platformManager.getForAllAccounts(); if (!platforms.length) { return undefined; } let platform: GitLabPlatformForAccount | undefined; // Using a for await loop in this context because we want to stop // evaluating accounts as soon as we find one with code suggestions enabled for await (const result of platforms.map(getChatSupport)) { if (result.hasSupportForChat) { platform = result.platform; break; } } return platform; } async getGitLabEnvironment(): Promise { const platform = await this.getGitLabPlatform(); const instanceUrl = platform?.account.instanceUrl; switch (instanceUrl) { case GITLAB_COM_URL: return GitLabEnvironment.GITLAB_COM; case GITLAB_DEVELOPMENT_URL: return GitLabEnvironment.GITLAB_DEVELOPMENT; case GITLAB_STAGING_URL: return GitLabEnvironment.GITLAB_STAGING; case GITLAB_ORG_URL: return GitLabEnvironment.GITLAB_ORG; default: return GitLabEnvironment.GITLAB_SELF_MANAGED; } } } References:" You are a code assistant,Definition of 'runWorkflow' in file packages/lib_workflow_api/src/index.ts in project gitlab-lsp,"Definition: runWorkflow(goal: string, image: string): Promise; } References:" You are a code assistant,Definition of 'WebviewPluginSetupFunc' in file packages/lib_webview_plugin/src/webview_plugin.ts in project gitlab-lsp,"Definition: type WebviewPluginSetupFunc = ( context: WebviewPluginSetupParams, // eslint-disable-next-line @typescript-eslint/no-invalid-void-type ) => Disposable | void; /** * The `WebviewPlugin` is a user implemented type defining the integration of the webview plugin with a webview host (extension) and webview instances. * * @template TWebviewPluginMessageMap - Message types recognized by the plugin. */ export type WebviewPlugin< TWebviewPluginMessageMap extends PartialDeep = PluginMessageMap, > = { id: WebviewId; title: string; setup: WebviewPluginSetupFunc>; }; References:" You are a code assistant,Definition of 'dispose' in file packages/lib_disposable/src/types.ts in project gitlab-lsp,"Definition: dispose(): void; } References:" You are a code assistant,Definition of 'WorkspaceFolderUri' in file src/common/git/repository_service.ts in project gitlab-lsp,"Definition: type WorkspaceFolderUri = string; type RepositoryMap = Map; export type RepositoryService = typeof DefaultRepositoryService.prototype; export const RepositoryService = createInterfaceId('RepositoryService'); @Injectable(RepositoryService, [VirtualFileSystemService]) export class DefaultRepositoryService { #virtualFileSystemService: DefaultVirtualFileSystemService; constructor(virtualFileSystemService: DefaultVirtualFileSystemService) { this.#virtualFileSystemService = virtualFileSystemService; this.#setupEventListeners(); } #setupEventListeners() { return this.#virtualFileSystemService.onFileSystemEvent(async (eventType, data) => { switch (eventType) { case VirtualFileSystemEvents.WorkspaceFilesUpdate: await this.#handleWorkspaceFilesUpdate(data as WorkspaceFilesUpdate); break; case VirtualFileSystemEvents.WorkspaceFileUpdate: await this.#handleWorkspaceFileUpdate(data as WorkspaceFileUpdate); break; default: break; } }); } async #handleWorkspaceFilesUpdate(update: WorkspaceFilesUpdate) { log.info(`Workspace files update: ${update.files.length}`); const perf1 = performance.now(); await this.handleWorkspaceFilesUpdate({ ...update, }); const perf2 = performance.now(); log.info(`Workspace files initialization took ${perf2 - perf1}ms`); const perf3 = performance.now(); const files = this.getFilesForWorkspace(update.workspaceFolder.uri, { excludeGitFolder: true, excludeIgnored: true, }); const perf4 = performance.now(); log.info(`Fetched workspace files in ${perf4 - perf3}ms`); log.info(`Workspace git files: ${files.length}`); // const treeFile = await readFile( // '/Users/angelo.rivera/gitlab/gitlab-development-kit/gitlab/tree.txt', // 'utf-8', // ); // const treeFiles = treeFile.split('\n').filter(Boolean); // // get the set difference between the files in the tree and the non-ignored files // // we need the difference between the two sets to know which files are not in the tree // const diff = new Set( // files.map((file) => // relative('/Users/angelo.rivera/gitlab/gitlab-development-kit/gitlab', file.uri.fsPath), // ), // ); // for (const file of treeFiles) { // diff.delete(file); // } // log.info(`Files not in the tree.txt: ${JSON.stringify(Array.from(diff))}`); } async #handleWorkspaceFileUpdate(update: WorkspaceFileUpdate) { log.info(`Workspace file update: ${JSON.stringify(update)}`); await this.handleWorkspaceFileUpdate({ ...update, }); const perf1 = performance.now(); const files = this.getFilesForWorkspace(update.workspaceFolder.uri, { excludeGitFolder: true, excludeIgnored: true, }); const perf2 = performance.now(); log.info(`Fetched workspace files in ${perf2 - perf1}ms`); log.info(`Workspace git files: ${files.length}`); } /** * unique map of workspace folders that point to a map of repositories * We store separate repository maps for each workspace because * the events from the VFS service are at the workspace level. * If we combined them, we may get race conditions */ #workspaces: Map = new Map(); #workspaceRepositoryTries: Map = new Map(); #buildRepositoryTrie(repositories: Repository[]): RepositoryTrie { const root = new RepositoryTrie(); for (const repo of repositories) { let node = root; const parts = repo.uri.path.split('/').filter(Boolean); for (const part of parts) { if (!node.children.has(part)) { node.children.set(part, new RepositoryTrie()); } node = node.children.get(part) as RepositoryTrie; } node.repository = repo.uri; } return root; } findMatchingRepositoryUri(fileUri: URI, workspaceFolderUri: WorkspaceFolder): URI | null { const trie = this.#workspaceRepositoryTries.get(workspaceFolderUri.uri); if (!trie) return null; let node = trie; let lastMatchingRepo: URI | null = null; const parts = fileUri.path.split('/').filter(Boolean); for (const part of parts) { if (node.repository) { lastMatchingRepo = node.repository; } if (!node.children.has(part)) break; node = node.children.get(part) as RepositoryTrie; } return node.repository || lastMatchingRepo; } getRepositoryFileForUri( fileUri: URI, repositoryUri: URI, workspaceFolder: WorkspaceFolder, ): RepositoryFile | null { const repository = this.#getRepositoriesForWorkspace(workspaceFolder.uri).get( repositoryUri.toString(), ); if (!repository) { return null; } return repository.getFile(fileUri.toString()) ?? null; } #updateRepositoriesForFolder( workspaceFolder: WorkspaceFolder, repositoryMap: RepositoryMap, repositoryTrie: RepositoryTrie, ) { this.#workspaces.set(workspaceFolder.uri, repositoryMap); this.#workspaceRepositoryTries.set(workspaceFolder.uri, repositoryTrie); } async handleWorkspaceFilesUpdate({ workspaceFolder, files }: WorkspaceFilesUpdate) { // clear existing repositories from workspace this.#emptyRepositoriesForWorkspace(workspaceFolder.uri); const repositories = this.#detectRepositories(files, workspaceFolder); const repositoryMap = new Map(repositories.map((repo) => [repo.uri.toString(), repo])); // Build and cache the repository trie for this workspace const trie = this.#buildRepositoryTrie(repositories); this.#updateRepositoriesForFolder(workspaceFolder, repositoryMap, trie); await Promise.all( repositories.map((repo) => repo.addFilesAndLoadGitIgnore( files.filter((file) => { const matchingRepo = this.findMatchingRepositoryUri(file, workspaceFolder); return matchingRepo && matchingRepo.toString() === repo.uri.toString(); }), ), ), ); } async handleWorkspaceFileUpdate({ fileUri, workspaceFolder, event }: WorkspaceFileUpdate) { const repoUri = this.findMatchingRepositoryUri(fileUri, workspaceFolder); if (!repoUri) { log.debug(`No matching repository found for file ${fileUri.toString()}`); return; } const repositoryMap = this.#getRepositoriesForWorkspace(workspaceFolder.uri); const repository = repositoryMap.get(repoUri.toString()); if (!repository) { log.debug(`Repository not found for URI ${repoUri.toString()}`); return; } if (repository.isFileIgnored(fileUri)) { log.debug(`File ${fileUri.toString()} is ignored`); return; } switch (event) { case 'add': repository.setFile(fileUri); log.debug(`File ${fileUri.toString()} added to repository ${repoUri.toString()}`); break; case 'change': repository.setFile(fileUri); log.debug(`File ${fileUri.toString()} updated in repository ${repoUri.toString()}`); break; case 'unlink': repository.removeFile(fileUri.toString()); log.debug(`File ${fileUri.toString()} removed from repository ${repoUri.toString()}`); break; default: log.warn(`Unknown file event ${event} for file ${fileUri.toString()}`); } } #getRepositoriesForWorkspace(workspaceFolderUri: WorkspaceFolderUri): RepositoryMap { return this.#workspaces.get(workspaceFolderUri) || new Map(); } #emptyRepositoriesForWorkspace(workspaceFolderUri: WorkspaceFolderUri): void { log.debug(`Emptying repositories for workspace ${workspaceFolderUri}`); const repos = this.#workspaces.get(workspaceFolderUri); if (!repos || repos.size === 0) return; // clear up ignore manager trie from memory repos.forEach((repo) => { repo.dispose(); log.debug(`Repository ${repo.uri} has been disposed`); }); repos.clear(); const trie = this.#workspaceRepositoryTries.get(workspaceFolderUri); if (trie) { trie.dispose(); this.#workspaceRepositoryTries.delete(workspaceFolderUri); } this.#workspaces.delete(workspaceFolderUri); log.debug(`Repositories for workspace ${workspaceFolderUri} have been emptied`); } #detectRepositories(files: URI[], workspaceFolder: WorkspaceFolder): Repository[] { const gitConfigFiles = files.filter((file) => file.toString().endsWith('.git/config')); return gitConfigFiles.map((file) => { const projectUri = fsPathToUri(file.path.replace('.git/config', '')); const ignoreManager = new IgnoreManager(projectUri.fsPath); log.info(`Detected repository at ${projectUri.path}`); return new Repository({ ignoreManager, uri: projectUri, configFileUri: file, workspaceFolder, }); }); } getFilesForWorkspace( workspaceFolderUri: WorkspaceFolderUri, options: { excludeGitFolder?: boolean; excludeIgnored?: boolean } = {}, ): RepositoryFile[] { const repositories = this.#getRepositoriesForWorkspace(workspaceFolderUri); const allFiles: RepositoryFile[] = []; repositories.forEach((repository) => { repository.getFiles().forEach((file) => { // apply the filters if (options.excludeGitFolder && this.#isInGitFolder(file.uri, repository.uri)) { return; } if (options.excludeIgnored && file.isIgnored) { return; } allFiles.push(file); }); }); return allFiles; } // Helper method to check if a file is in the .git folder #isInGitFolder(fileUri: URI, repositoryUri: URI): boolean { const relativePath = fileUri.path.slice(repositoryUri.path.length); return relativePath.split('/').some((part) => part === '.git'); } } References: - src/common/git/repository_service.ts:280 - src/common/git/repository_service.ts:245 - src/common/git/repository_service.ts:241" You are a code assistant,Definition of 'SuggestionServiceOptions' in file src/common/suggestion/suggestion_service.ts in project gitlab-lsp,"Definition: 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 => { 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 => { 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 => { 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 { 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 { 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 { 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 { 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 { 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/suggestion/suggestion_service.ts:150" You are a code assistant,Definition of 'constructor' in file src/tests/fixtures/intent/empty_function/javascript.js in project gitlab-lsp,"Definition: 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:" You are a code assistant,Definition of 'stop' in file src/common/tracking/snowplow/emitter.ts in project gitlab-lsp,"Definition: async stop() { this.#currentState = EmitterState.STOPPING; if (this.#timeout) { clearTimeout(this.#timeout); } this.#timeout = undefined; await this.#drainQueue(); } } References:" You are a code assistant,Definition of 'IClientConfig' in file src/common/config_service.ts in project gitlab-lsp,"Definition: export interface IClientConfig { /** GitLab API URL used for getting code suggestions */ baseUrl?: string; /** Full project path. */ projectPath?: string; /** PAT or OAuth token used to authenticate to GitLab API */ token?: string; /** The base URL for language server assets in the client-side extension */ baseAssetsUrl?: string; clientInfo?: IClientInfo; // FIXME: this key should be codeSuggestions (we have code completion and code generation) codeCompletion?: ICodeCompletionConfig; openTabsContext?: boolean; telemetry?: ITelemetryOptions; /** Config used for caching code suggestions */ suggestionsCache?: ISuggestionsCacheOptions; workspaceFolders?: WorkspaceFolder[] | null; /** Collection of Feature Flag values which are sent from the client */ featureFlags?: Record; logLevel?: LogLevel; ignoreCertificateErrors?: boolean; httpAgentOptions?: IHttpAgentOptions; snowplowTrackerOptions?: ISnowplowTrackerOptions; // TODO: move to `duo` duoWorkflowSettings?: IWorkflowSettings; securityScannerOptions?: ISecurityScannerOptions; duo?: IDuoConfig; } export interface IConfig { // TODO: we can possibly remove this extra level of config and move all IClientConfig properties to IConfig client: IClientConfig; } /** * ConfigService manages user configuration (e.g. baseUrl) and application state (e.g. codeCompletion.enabled) * TODO: Maybe in the future we would like to separate these two */ export interface ConfigService { get: TypedGetter; /** * set sets the property of the config * the new value completely overrides the old one */ set: TypedSetter; onConfigChange(listener: (config: IConfig) => void): Disposable; /** * merge adds `newConfig` properties into existing config, if the * property is present in both old and new config, `newConfig` * properties take precedence unless not defined * * This method performs deep merge * * **Arrays are not merged; they are replaced with the new value.** * */ merge(newConfig: Partial): void; } export const ConfigService = createInterfaceId('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 = (key?: string) => { return key ? get(this.#config, key) : this.#config; }; set: TypedSetter = (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) { mergeWith(this.#config, newConfig, (target, src) => (isArray(target) ? src : undefined)); this.#triggerChange(); } } References: - src/common/message_handler.ts:25 - src/common/message_handler.test.ts:112 - src/common/suggestion/suggestion_service.ts:68 - src/common/config_service.ts:80" You are a code assistant,Definition of 'destroyInstance' in file src/common/advanced_context/lru_cache.ts in project gitlab-lsp,"Definition: public static destroyInstance(): void { LruCache.#instance = undefined; } get openFiles() { return this.#cache; } #getDocumentSize(context: IDocContext): number { const size = getByteSize(`${context.prefix}${context.suffix}`); return Math.max(1, size); } /** * Update the file in the cache. * Uses lru-cache under the hood. */ updateFile(context: IDocContext) { return this.#cache.set(context.uri, context); } /** * @returns `true` if the file was deleted, `false` if the file was not found */ deleteFile(uri: DocumentUri): boolean { return this.#cache.delete(uri); } /** * Get the most recently accessed files in the workspace * @param context - The current document context `IDocContext` * @param includeCurrentFile - Include the current file in the list of most recent files, default is `true` */ mostRecentFiles({ context, includeCurrentFile = true, }: { context?: IDocContext; includeCurrentFile?: boolean; }): IDocContext[] { const files = Array.from(this.#cache.values()); if (includeCurrentFile) { return files; } return files.filter( (file) => context?.workspaceFolder?.uri === file.workspaceFolder?.uri && file.uri !== context?.uri, ); } } References:" You are a code assistant,Definition of 'WebviewInstanceMessageBus' in file packages/lib_webview/src/setup/plugin/webview_instance_message_bus.ts in project gitlab-lsp,"Definition: export class WebviewInstanceMessageBus implements WebviewMessageBus, Disposable { #address: WebviewAddress; #runtimeMessageBus: WebviewRuntimeMessageBus; #eventSubscriptions = new CompositeDisposable(); #notificationEvents = new SimpleRegistry(); #requestEvents = new SimpleRegistry(); #pendingResponseEvents = new SimpleRegistry(); #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 { 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); } 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: - packages/lib_webview/src/setup/plugin/webview_instance_message_bus.test.ts:16 - packages/lib_webview/src/setup/plugin/webview_instance_message_bus.test.ts:21 - packages/lib_webview/src/setup/plugin/setup_plugins.ts:31 - packages/lib_webview/src/setup/plugin/webview_instance_message_bus.test.ts:335" You are a code assistant,Definition of 'PluginMessageMap' in file packages/lib_webview_plugin/src/webview_plugin.ts in project gitlab-lsp,"Definition: export type PluginMessageMap = { extensionToPlugin: MessageDefinitions; pluginToExtension: MessageDefinitions; webviewToPlugin: MessageDefinitions; pluginToWebview: MessageDefinitions; }; /** * Utility type for creating a plugin message map with default values. This utility type helps plugin authors define the message map for their plugins without needing to specify every detail. It ensures that the required message structures are in place and provides sensible defaults for any unspecified parts. * * @template T - The partial message map provided by the plugin author. This type should extend `PartialDeep`. */ export type CreatePluginMessageMap> = { extensionToPlugin: CreateMessageDefinitions; pluginToExtension: CreateMessageDefinitions; webviewToPlugin: CreateMessageDefinitions; pluginToWebview: CreateMessageDefinitions; }; type WebviewPluginSetupParams = { webview: WebviewConnection<{ inbound: T['webviewToPlugin']; outbound: T['pluginToWebview']; }>; extension: MessageBus<{ inbound: T['extensionToPlugin']; outbound: T['pluginToExtension']; }>; }; /** * The `WebviewPluginSetupFunc` is responsible for setting up the communication between the webview plugin and the extension, as well as between the webview plugin and individual webview instances. * * @template TWebviewPluginMessageMap - Message types recognized by the plugin. * @param webviewMessageBus - The message bus for communication with individual webview instances. * @param extensionMessageBus - The message bus for communication with the webview host (extension). * @returns An optional function to dispose of resources when the plugin is unloaded. */ type WebviewPluginSetupFunc = ( context: WebviewPluginSetupParams, // eslint-disable-next-line @typescript-eslint/no-invalid-void-type ) => Disposable | void; /** * The `WebviewPlugin` is a user implemented type defining the integration of the webview plugin with a webview host (extension) and webview instances. * * @template TWebviewPluginMessageMap - Message types recognized by the plugin. */ export type WebviewPlugin< TWebviewPluginMessageMap extends PartialDeep = PluginMessageMap, > = { id: WebviewId; title: string; setup: WebviewPluginSetupFunc>; }; References:" You are a code assistant,Definition of 'onDocumentChange' in file src/common/document_service.ts in project gitlab-lsp,"Definition: onDocumentChange(listener: TextDocumentChangeListener): Disposable; notificationHandler(params: DidChangeDocumentInActiveEditorParams): void; } export const DocumentService = createInterfaceId('DocumentsWrapper'); const DOCUMENT_CHANGE_EVENT_NAME = 'documentChange'; export class DefaultDocumentService implements DocumentService, HandlesNotification { #subscriptions: Disposable[] = []; #emitter = new EventEmitter(); #documents: TextDocuments; constructor(documents: TextDocuments) { 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 = { document }; this.#emitter.emit( DOCUMENT_CHANGE_EVENT_NAME, event, TextDocumentChangeListenerType.onDidSetActive, ); }; #createMediatorListener = (type: TextDocumentChangeListenerType) => (event: TextDocumentChangeEvent) => { 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:" You are a code assistant,Definition of 'constructor' in file src/common/tree_sitter/comments/comment_resolver.ts in project gitlab-lsp,"Definition: constructor() { this.queryByLanguage = new Map(); } #getQueryByLanguage( language: TreeSitterLanguageName, treeSitterLanguage: Language, ): Query | undefined { const query = this.queryByLanguage.get(language); if (query) { return query; } const queryString = commentQueries[language]; if (!queryString) { log.warn(`No comment query found for language: ${language}`); return undefined; } const newQuery = treeSitterLanguage.query(queryString); this.queryByLanguage.set(language, newQuery); return newQuery; } /** * Returns the comment that is on or directly above the cursor, if it exists. * To handle the case the comment may be several new lines above the cursor, * we traverse the tree to check if any nodes are between the comment and the cursor. */ getCommentForCursor({ languageName, tree, cursorPosition, treeSitterLanguage, }: { languageName: TreeSitterLanguageName; tree: Tree; treeSitterLanguage: Language; cursorPosition: Point; }): CommentResolution | undefined { const query = this.#getQueryByLanguage(languageName, treeSitterLanguage); if (!query) { return undefined; } const comments = query.captures(tree.rootNode).map((capture) => { return { start: capture.node.startPosition, end: capture.node.endPosition, content: capture.node.text, capture, }; }); const commentAtCursor = CommentResolver.#getCommentAtCursor(comments, cursorPosition); if (commentAtCursor) { // No need to further check for isPositionInNode etc. as cursor is directly on the comment return { commentAtCursor }; } const commentAboveCursor = CommentResolver.#getCommentAboveCursor(comments, cursorPosition); if (!commentAboveCursor) { return undefined; } const commentParentNode = commentAboveCursor.capture.node.parent; if (!commentParentNode) { return undefined; } if (!CommentResolver.#isPositionInNode(cursorPosition, commentParentNode)) { return undefined; } const directChildren = commentParentNode.children; for (const child of directChildren) { const hasNodeBetweenCursorAndComment = child.startPosition.row > commentAboveCursor.capture.node.endPosition.row && child.startPosition.row <= cursorPosition.row; if (hasNodeBetweenCursorAndComment) { return undefined; } } return { commentAboveCursor }; } static #isPositionInNode(position: Point, node: SyntaxNode): boolean { return position.row >= node.startPosition.row && position.row <= node.endPosition.row; } static #getCommentAboveCursor(comments: Comment[], cursorPosition: Point): Comment | undefined { return CommentResolver.#getLastComment( comments.filter((comment) => comment.end.row < cursorPosition.row), ); } static #getCommentAtCursor(comments: Comment[], cursorPosition: Point): Comment | undefined { return CommentResolver.#getLastComment( comments.filter( (comment) => comment.start.row <= cursorPosition.row && comment.end.row >= cursorPosition.row, ), ); } static #getLastComment(comments: Comment[]): Comment | undefined { return comments.sort((a, b) => b.end.row - a.end.row)[0]; } /** * Returns the total number of lines that are comments in a parsed syntax tree. * Uses a Set because we only want to count each line once. * @param {Object} params - Parameters for counting comment lines. * @param {TreeSitterLanguageName} params.languageName - The name of the programming language. * @param {Tree} params.tree - The syntax tree to analyze. * @param {Language} params.treeSitterLanguage - The Tree-sitter language instance. * @returns {number} - The total number of unique lines containing comments. */ getTotalCommentLines({ treeSitterLanguage, languageName, tree, }: { languageName: TreeSitterLanguageName; treeSitterLanguage: Language; tree: Tree; }): number { const query = this.#getQueryByLanguage(languageName, treeSitterLanguage); const captures = query ? query.captures(tree.rootNode) : []; // Note: in future, we could potentially re-use captures from getCommentForCursor() const commentLineSet = new Set(); // A Set is used to only count each line once (the same comment can span multiple lines) captures.forEach((capture) => { const { startPosition, endPosition } = capture.node; for (let { row } = startPosition; row <= endPosition.row; row++) { commentLineSet.add(row); } }); return commentLineSet.size; } static isCommentEmpty(comment: Comment): boolean { const trimmedContent = comment.content.trim().replace(/[\n\r\\]/g, ' '); // Count the number of alphanumeric characters in the trimmed content const alphanumericCount = (trimmedContent.match(/[a-zA-Z0-9]/g) || []).length; return alphanumericCount <= 2; } } let commentResolver: CommentResolver; export function getCommentResolver(): CommentResolver { if (!commentResolver) { commentResolver = new CommentResolver(); } return commentResolver; } References:" You are a code assistant,Definition of 'AiContextItemType' in file src/common/ai_context_management_2/ai_context_item.ts in project gitlab-lsp,"Definition: export type AiContextItemType = 'issue' | 'merge_request' | 'file'; export type AiContextItemSubType = 'open_tab' | 'local_file_search'; export type AiContextItem = { id: string; name: string; isEnabled: boolean; info: AiContextItemInfo; type: AiContextItemType; } & ( | { type: 'issue' | 'merge_request'; subType?: never } | { type: 'file'; subType: AiContextItemSubType } ); export type AiContextItemWithContent = AiContextItem & { content: string; }; References: - src/common/ai_context_management_2/ai_context_item.ts:17" You are a code assistant,Definition of 'constructor' in file src/common/security_diagnostics_publisher.ts in project gitlab-lsp,"Definition: constructor( featureFlagService: FeatureFlagService, configService: ConfigService, documentService: DocumentService, ) { this.#featureFlagService = featureFlagService; configService.onConfigChange((config: IConfig) => { this.#opts = config.client.securityScannerOptions; }); documentService.onDocumentChange( async ( event: TextDocumentChangeEvent, 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:" You are a code assistant,Definition of 'ResolveMessageBusParams' in file packages/lib_webview_client/src/bus/resolve_message_bus.ts in project gitlab-lsp,"Definition: type ResolveMessageBusParams = { webviewId: string; providers?: MessageBusProvider[]; logger?: Logger; }; export function resolveMessageBus( params: ResolveMessageBusParams, ): MessageBus { const { webviewId } = params; const logger = params.logger || new NullLogger(); const providers = params.providers || getDefaultProviders(); for (const provider of providers) { const bus = getMessageBusFromProviderSafe(webviewId, provider, logger); if (bus) { return bus; } } throw new Error(`Unable to resolve a message bus for webviewId: ${webviewId}`); } function getMessageBusFromProviderSafe( webviewId: string, provider: MessageBusProvider, logger: Logger, ): MessageBus | null { try { logger.debug(`Trying to resolve message bus from provider: ${provider.name}`); const bus = provider.getMessageBus(webviewId); logger.debug(`Message bus resolved from provider: ${provider.name}`); return bus; } catch (error) { logger.debug('Failed to resolve message bus', error as Error); return null; } } References: - packages/lib_webview_client/src/bus/resolve_message_bus.ts:12" You are a code assistant,Definition of 'constructor' in file packages/webview_duo_chat/src/plugin/chat_platform_manager.ts in project gitlab-lsp,"Definition: constructor(client: GitLabApiClient) { this.#client = client; } async getForActiveProject(): Promise { // return new ChatPlatformForProject(this.#client); return undefined; } async getForActiveAccount(): Promise { return new ChatPlatformForAccount(this.#client); } async getForAllAccounts(): Promise { return [new ChatPlatformForAccount(this.#client)]; } async getForSaaSAccount(): Promise { return new ChatPlatformForAccount(this.#client); } } References:" You are a code assistant,Definition of 'DefaultSuggestionService' in file src/common/suggestion/suggestion_service.ts in project gitlab-lsp,"Definition: 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 => { 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 => { 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 => { 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 { 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 { 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 { 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 { 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 { 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/suggestion/suggestion_service.test.ts:74 - src/common/connection.ts:37 - src/common/suggestion/suggestion_service.test.ts:207 - src/common/suggestion/suggestion_service.test.ts:478" You are a code assistant,Definition of 'DesktopFileResolver' in file src/node/services/fs/file.ts in project gitlab-lsp,"Definition: export class DesktopFileResolver extends EmptyFileResolver { async readFile({ fileUri }: ReadFile): Promise { return readFile(fsPathFromUri(fileUri), 'utf8'); } } References: - src/node/services/fs/file.test.ts:9 - src/node/services/fs/file.test.ts:12" You are a code assistant,Definition of 'dispose' in file packages/lib_handler_registry/src/registry/simple_registry.ts in project gitlab-lsp,"Definition: dispose() { this.#handlers.clear(); } } function resolveError(e: unknown): Error { if (e instanceof Error) { return e; } if (typeof e === 'string') { return new Error(e); } return new Error('Unknown error'); } References:" You are a code assistant,Definition of 'setupEventSubscriptions' in file packages/lib_webview/src/setup/transport/utils/setup_event_subscriptions.ts in project gitlab-lsp,"Definition: export const setupEventSubscriptions = ( runtimeMessageBus: WebviewRuntimeMessageBus, transport: Transport, isManaged: IsManagedEventFilter, ): Disposable[] => [ runtimeMessageBus.subscribe( 'plugin:notification', async (message) => { await transport.publish('webview_instance_notification', message); }, isManaged, ), runtimeMessageBus.subscribe( 'plugin:request', async (message) => { await transport.publish('webview_instance_request', message); }, isManaged, ), runtimeMessageBus.subscribe( 'plugin:response', async (message) => { await transport.publish('webview_instance_response', message); }, isManaged, ), ]; References: - packages/lib_webview/src/setup/transport/setup_transport.ts:21 - packages/lib_webview/src/setup/transport/utils/setup_event_subscriptions.test.ts:36 - packages/lib_webview/src/setup/transport/utils/setup_event_subscriptions.test.ts:45 - packages/lib_webview/src/setup/transport/utils/setup_event_subscriptions.test.ts:67 - packages/lib_webview/src/setup/transport/utils/setup_event_subscriptions.test.ts:95 - packages/lib_webview/src/setup/transport/utils/setup_event_subscriptions.test.ts:26 - packages/lib_webview/src/setup/transport/utils/setup_event_subscriptions.test.ts:82" You are a code assistant,Definition of 'DesktopWorkflowRunner' in file src/node/duo_workflow/desktop_workflow_runner.ts in project gitlab-lsp,"Definition: export class DesktopWorkflowRunner implements WorkflowAPI { #dockerSocket?: string; #folders?: WorkspaceFolder[]; #fetch: LsFetch; #api: GitLabApiClient; #projectPath: string | undefined; constructor(configService: ConfigService, fetch: LsFetch, api: GitLabApiClient) { this.#fetch = fetch; this.#api = api; configService.onConfigChange((config) => this.#reconfigure(config)); } #reconfigure(config: IConfig) { this.#dockerSocket = config.client.duoWorkflowSettings?.dockerSocket; this.#folders = config.client.workspaceFolders || []; this.#projectPath = config.client.projectPath; } async runWorkflow(goal: string, image: string): Promise { if (!this.#dockerSocket) { throw new Error('Docker socket not configured'); } if (!this.#folders || this.#folders.length === 0) { throw new Error('No workspace folders'); } const executorPath = path.join( __dirname, `../vendor/duo_workflow_executor-${WORKFLOW_EXECUTOR_VERSION}.tar.gz`, ); await this.#downloadWorkflowExecutor(executorPath); const folderName = this.#folders[0].uri.replace(/^file:\/\//, ''); if (this.#folders.length > 0) { log.info(`More than one workspace folder detected. Using workspace folder ${folderName}`); } const workflowID = await this.#createWorkflow(); const workflowToken = await this.#getWorkflowToken(); const containerOptions = { Image: image, Cmd: [ '/duo-workflow-executor', `--workflow-id=${workflowID}`, '--server', workflowToken.duo_workflow_service.base_url || 'localhost:50052', '--goal', goal, '--base-url', workflowToken.gitlab_rails.base_url, '--token', workflowToken.gitlab_rails.token, '--duo-workflow-service-token', workflowToken.duo_workflow_service.token, '--realm', workflowToken.duo_workflow_service.headers['X-Gitlab-Realm'], '--user-id', workflowToken.duo_workflow_service.headers['X-Gitlab-Global-User-Id'], ], HostConfig: { Binds: [`${folderName}:/workspace`], }, }; // Create a container const createResponse = JSON.parse( await this.#makeRequest('/v1.43/containers/create', 'POST', JSON.stringify(containerOptions)), ); // Check if Id in createResponse if (!createResponse.Id) { throw new Error('Failed to create container: No Id in response'); } const containerID = createResponse.Id; // Copy the executor into the container await this.#copyExecutor(containerID, executorPath); // Start the container await this.#makeRequest(`/v1.43/containers/${containerID}/start`, 'POST', ''); return workflowID; } async #copyExecutor(containerID: string, executorPath: string) { const fileContents = await readFile(executorPath); await this.#makeRequest( `/v1.43/containers/${containerID}/archive?path=/`, 'PUT', fileContents, 'application/x-tar', ); } #makeRequest( apiPath: string, method: string, data: string | Buffer, contentType = 'application/json', ): Promise { return new Promise((resolve, reject) => { if (!this.#dockerSocket) { throw new Error('Docker socket not set'); } const options: http.RequestOptions = { socketPath: this.#dockerSocket, path: apiPath, method, headers: { 'Content-Type': contentType, 'Content-Length': Buffer.byteLength(data), }, }; const callback = (res: http.IncomingMessage) => { res.setEncoding('utf-8'); res.on('data', (content) => resolve(content)); res.on('error', (err) => reject(err)); res.on('end', () => { resolve(''); }); }; const clientRequest = http.request(options, callback); clientRequest.write(data); clientRequest.end(); }); } async #downloadWorkflowExecutor(executorPath: string): Promise { try { await readFile(executorPath); } catch (error) { log.info('Downloading workflow executor...'); await this.#downloadFile(executorPath); } } async #downloadFile(outputPath: string): Promise { const response = await this.#fetch.fetch(WORKFLOW_EXECUTOR_DOWNLOAD_PATH, { method: 'GET', headers: { 'Content-Type': 'application/octet-stream', }, }); if (!response.ok) { throw new Error(`Failed to download file: ${response.statusText}`); } const buffer = await response.arrayBuffer(); await writeFile(outputPath, Buffer.from(buffer)); } async #createWorkflow(): Promise { const response = await this.#api?.fetchFromApi({ type: 'rest', method: 'POST', path: '/ai/duo_workflows/workflows', body: { project_id: this.#projectPath, }, supportedSinceInstanceVersion: { resourceName: 'create a workflow', version: '17.3.0', }, }); if (!response) { throw new Error('Failed to create workflow'); } return response.id; } async #getWorkflowToken(): Promise { const token = await this.#api?.fetchFromApi({ type: 'rest', method: 'POST', path: '/ai/duo_workflows/direct_access', supportedSinceInstanceVersion: { resourceName: 'get workflow direct access', version: '17.3.0', }, }); if (!token) { throw new Error('Failed to get workflow token'); } return token; } } References: - src/node/duo_workflow/desktop_workflow_runner.test.ts:14 - src/node/main.ts:169 - src/node/duo_workflow/desktop_workflow_runner.test.ts:28" You are a code assistant,Definition of 'destroy' in file src/common/fetch.ts in project gitlab-lsp,"Definition: async destroy(): Promise {} async fetch(input: RequestInfo | URL, init?: RequestInit): Promise { 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 { // Stub. Should delegate to the node or browser fetch implementations throw new Error('Not implemented'); yield ''; } async delete(input: RequestInfo | URL, init?: RequestInit): Promise { return this.fetch(input, this.updateRequestInit('DELETE', init)); } async get(input: RequestInfo | URL, init?: RequestInit): Promise { return this.fetch(input, this.updateRequestInit('GET', init)); } async post(input: RequestInfo | URL, init?: RequestInit): Promise { return this.fetch(input, this.updateRequestInit('POST', init)); } async put(input: RequestInfo | URL, init?: RequestInit): Promise { return this.fetch(input, this.updateRequestInit('PUT', init)); } async fetchBase(input: RequestInfo | URL, init?: RequestInit): Promise { // 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 'ExponentialBackoffCircuitBreakerOptions' in file src/common/circuit_breaker/exponential_backoff_circuit_breaker.ts in project gitlab-lsp,"Definition: export interface ExponentialBackoffCircuitBreakerOptions { maxErrorsBeforeBreaking?: number; initialBackoffMs?: number; maxBackoffMs?: number; backoffMultiplier?: number; } export class ExponentialBackoffCircuitBreaker implements CircuitBreaker { #name: string; #state: CircuitBreakerState = CircuitBreakerState.CLOSED; readonly #initialBackoffMs: number; readonly #maxBackoffMs: number; readonly #backoffMultiplier: number; #errorCount = 0; #eventEmitter = new EventEmitter(); #timeoutId: NodeJS.Timeout | null = null; constructor( name: string, { initialBackoffMs = DEFAULT_INITIAL_BACKOFF_MS, maxBackoffMs = DEFAULT_MAX_BACKOFF_MS, backoffMultiplier = DEFAULT_BACKOFF_MULTIPLIER, }: ExponentialBackoffCircuitBreakerOptions = {}, ) { this.#name = name; this.#initialBackoffMs = initialBackoffMs; this.#maxBackoffMs = maxBackoffMs; this.#backoffMultiplier = backoffMultiplier; } error() { this.#errorCount += 1; this.#open(); } megaError() { this.#errorCount += 3; this.#open(); } #open() { if (this.#state === CircuitBreakerState.OPEN) { return; } this.#state = CircuitBreakerState.OPEN; log.warn( `Excess errors detected, opening '${this.#name}' circuit breaker for ${this.#getBackoffTime() / 1000} second(s).`, ); this.#timeoutId = setTimeout(() => this.#close(), this.#getBackoffTime()); this.#eventEmitter.emit('open'); } #close() { if (this.#state === CircuitBreakerState.CLOSED) { return; } if (this.#timeoutId) { clearTimeout(this.#timeoutId); } this.#state = CircuitBreakerState.CLOSED; this.#eventEmitter.emit('close'); } isOpen() { return this.#state === CircuitBreakerState.OPEN; } 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) }; } #getBackoffTime() { return Math.min( this.#initialBackoffMs * this.#backoffMultiplier ** (this.#errorCount - 1), this.#maxBackoffMs, ); } } References: - src/common/circuit_breaker/exponential_backoff_circuit_breaker.ts:40" You are a code assistant,Definition of 'OptionsCount' in file src/common/suggestion_client/suggestion_client.ts in project gitlab-lsp,"Definition: export type OptionsCount = 1 | typeof MANUAL_REQUEST_OPTIONS_COUNT; export const GENERATION = 'generation'; export const COMPLETION = 'completion'; export type Intent = typeof GENERATION | typeof COMPLETION | undefined; export interface SuggestionContext { document: IDocContext; intent?: Intent; projectPath?: string; optionsCount?: OptionsCount; additionalContexts?: AdditionalContext[]; } export interface SuggestionResponse { choices?: SuggestionResponseChoice[]; model?: SuggestionModel; status: number; error?: string; isDirectConnection?: boolean; } export interface SuggestionResponseChoice { text: string; } export interface SuggestionClient { getSuggestions(context: SuggestionContext): Promise; } export type SuggestionClientFn = SuggestionClient['getSuggestions']; export type SuggestionClientMiddleware = ( context: SuggestionContext, next: SuggestionClientFn, ) => ReturnType; References: - src/common/suggestion_client/suggestion_client.ts:23 - src/common/suggestion/suggestion_service.ts:425" You are a code assistant,Definition of 'greet' in file src/tests/fixtures/intent/go_comments.go in project gitlab-lsp,"Definition: func greet(name string) string { return ""Hello, "" + name + ""!"" } // This file has more than 5 non-comment lines var a = 1 var b = 2 var c = 3 var d = 4 var e = 5 var f = 6 func (g Greet) greet() { // function to greet the user } 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 'CodeSuggestionRequest' in file src/common/api.ts in project gitlab-lsp,"Definition: export interface CodeSuggestionRequest { prompt_version: number; project_path: string; model_provider?: string; project_id: number; current_file: CodeSuggestionRequestCurrentFile; intent?: 'completion' | 'generation'; stream?: boolean; /** how many suggestion options should the API return */ choices_count?: number; /** additional context to provide to the model */ context?: AdditionalContext[]; /* A user's instructions for code suggestions. */ user_instruction?: string; /* The backend can add additional prompt info based on the type of event */ generation_type?: GenerationType; } export interface CodeSuggestionRequestCurrentFile { file_name: string; content_above_cursor: string; content_below_cursor: string; } export interface CodeSuggestionResponse { choices?: SuggestionOption[]; model?: ICodeSuggestionModel; status: number; error?: string; isDirectConnection?: boolean; } // FIXME: Rename to SuggestionOptionStream when renaming the SuggestionOption export interface StartStreamOption { uniqueTrackingId: string; /** the streamId represents the beginning of a stream * */ streamId: string; } export type SuggestionOptionOrStream = SuggestionOption | StartStreamOption; export interface PersonalAccessToken { name: string; scopes: string[]; active: boolean; } export interface OAuthToken { scope: string[]; } export interface TokenCheckResponse { valid: boolean; reason?: 'unknown' | 'not_active' | 'invalid_scopes'; message?: string; } export interface IDirectConnectionDetailsHeaders { 'X-Gitlab-Global-User-Id': string; 'X-Gitlab-Instance-Id': string; 'X-Gitlab-Host-Name': string; 'X-Gitlab-Saas-Duo-Pro-Namespace-Ids': string; } export interface IDirectConnectionModelDetails { model_provider: string; model_name: string; } export interface IDirectConnectionDetails { base_url: string; token: string; expires_at: number; headers: IDirectConnectionDetailsHeaders; model_details: IDirectConnectionModelDetails; } const CONFIG_CHANGE_EVENT_NAME = 'apiReconfigured'; @Injectable(GitLabApiClient, [LsFetch, ConfigService]) export class GitLabAPI implements GitLabApiClient { #token: string | undefined; #baseURL: string; #clientInfo?: IClientInfo; #lsFetch: LsFetch; #eventEmitter = new EventEmitter(); #configService: ConfigService; #instanceVersion?: string; constructor(lsFetch: LsFetch, configService: ConfigService) { this.#baseURL = GITLAB_API_BASE_URL; this.#lsFetch = lsFetch; this.#configService = configService; this.#configService.onConfigChange(async (config) => { this.#clientInfo = configService.get('client.clientInfo'); this.#lsFetch.updateAgentOptions({ ignoreCertificateErrors: this.#configService.get('client.ignoreCertificateErrors') ?? false, ...(this.#configService.get('client.httpAgentOptions') ?? {}), }); await this.configureApi(config.client); }); } onApiReconfigured(listener: (data: ApiReconfiguredData) => void): Disposable { this.#eventEmitter.on(CONFIG_CHANGE_EVENT_NAME, listener); return { dispose: () => this.#eventEmitter.removeListener(CONFIG_CHANGE_EVENT_NAME, listener) }; } #fireApiReconfigured(isInValidState: boolean, validationMessage?: string) { const data: ApiReconfiguredData = { isInValidState, validationMessage }; this.#eventEmitter.emit(CONFIG_CHANGE_EVENT_NAME, data); } async configureApi({ token, baseUrl = GITLAB_API_BASE_URL, }: { token?: string; baseUrl?: string; }) { if (this.#token === token && this.#baseURL === baseUrl) return; this.#token = token; this.#baseURL = baseUrl; const { valid, reason, message } = await this.checkToken(this.#token); let validationMessage; if (!valid) { this.#configService.set('client.token', undefined); validationMessage = `Token is invalid. ${message}. Reason: ${reason}`; log.warn(validationMessage); } else { log.info('Token is valid'); } this.#instanceVersion = await this.#getGitLabInstanceVersion(); this.#fireApiReconfigured(valid, validationMessage); } #looksLikePatToken(token: string): boolean { // OAuth tokens will be longer than 42 characters and PATs will be shorter. return token.length < 42; } async #checkPatToken(token: string): Promise { const headers = this.#getDefaultHeaders(token); const response = await this.#lsFetch.get( `${this.#baseURL}/api/v4/personal_access_tokens/self`, { headers }, ); await handleFetchError(response, 'Information about personal access token'); const { active, scopes } = (await response.json()) as PersonalAccessToken; if (!active) { return { valid: false, reason: 'not_active', message: 'Token is not active.', }; } if (!this.#hasValidScopes(scopes)) { const joinedScopes = scopes.map((scope) => `'${scope}'`).join(', '); return { valid: false, reason: 'invalid_scopes', message: `Token has scope(s) ${joinedScopes} (needs 'api').`, }; } return { valid: true }; } async #checkOAuthToken(token: string): Promise { const headers = this.#getDefaultHeaders(token); const response = await this.#lsFetch.get(`${this.#baseURL}/oauth/token/info`, { headers, }); await handleFetchError(response, 'Information about OAuth token'); const { scope: scopes } = (await response.json()) as OAuthToken; if (!this.#hasValidScopes(scopes)) { const joinedScopes = scopes.map((scope) => `'${scope}'`).join(', '); return { valid: false, reason: 'invalid_scopes', message: `Token has scope(s) ${joinedScopes} (needs 'api').`, }; } return { valid: true }; } async checkToken(token: string = ''): Promise { try { if (this.#looksLikePatToken(token)) { log.info('Checking token for PAT validity'); return await this.#checkPatToken(token); } log.info('Checking token for OAuth validity'); return await this.#checkOAuthToken(token); } catch (err) { log.error('Error performing token check', err); return { valid: false, reason: 'unknown', message: `Failed to check token: ${err}`, }; } } #hasValidScopes(scopes: string[]): boolean { return scopes.includes('api'); } async getCodeSuggestions( request: CodeSuggestionRequest, ): Promise { if (!this.#token) { throw new Error('Token needs to be provided to request Code Suggestions'); } const headers = { ...this.#getDefaultHeaders(this.#token), 'Content-Type': 'application/json', }; const response = await this.#lsFetch.post( `${this.#baseURL}/api/v4/code_suggestions/completions`, { headers, body: JSON.stringify(request) }, ); await handleFetchError(response, 'Code Suggestions'); const data = await response.json(); return { ...data, status: response.status }; } async *getStreamingCodeSuggestions( request: CodeSuggestionRequest, ): AsyncGenerator { if (!this.#token) { throw new Error('Token needs to be provided to stream code suggestions'); } const headers = { ...this.#getDefaultHeaders(this.#token), 'Content-Type': 'application/json', }; yield* this.#lsFetch.streamFetch( `${this.#baseURL}/api/v4/code_suggestions/completions`, JSON.stringify(request), headers, ); } async fetchFromApi(request: ApiRequest): Promise { if (!this.#token) { return Promise.reject(new Error('Token needs to be provided to authorise API request.')); } if ( request.supportedSinceInstanceVersion && !this.#instanceVersionHigherOrEqualThen(request.supportedSinceInstanceVersion.version) ) { return Promise.reject( new InvalidInstanceVersionError( `Can't ${request.supportedSinceInstanceVersion.resourceName} until your instance is upgraded to ${request.supportedSinceInstanceVersion.version} or higher.`, ), ); } if (request.type === 'graphql') { return this.#graphqlRequest(request.query, request.variables); } switch (request.method) { case 'GET': return this.#fetch(request.path, request.searchParams, 'resource', request.headers); case 'POST': return this.#postFetch(request.path, 'resource', request.body, request.headers); default: // the type assertion is necessary because TS doesn't expect any other types throw new Error(`Unknown request type ${(request as ApiRequest).type}`); } } async connectToCable(): Promise { const headers = this.#getDefaultHeaders(this.#token); const websocketOptions = { headers: { ...headers, Origin: this.#baseURL, }, }; return connectToCable(this.#baseURL, websocketOptions); } async #graphqlRequest( document: RequestDocument, variables?: V, ): Promise { const ensureEndsWithSlash = (url: string) => url.replace(/\/?$/, '/'); const endpoint = new URL('./api/graphql', ensureEndsWithSlash(this.#baseURL)).href; // supports GitLab instances that are on a custom path, e.g. ""https://example.com/gitlab"" const graphqlFetch = async ( input: RequestInfo | URL, init?: RequestInit, ): Promise => { const url = input instanceof URL ? input.toString() : input; return this.#lsFetch.post(url, { ...init, headers: { ...headers, ...init?.headers }, }); }; const headers = this.#getDefaultHeaders(this.#token); const client = new GraphQLClient(endpoint, { headers, fetch: graphqlFetch, }); return client.request(document, variables); } async #fetch( apiResourcePath: string, query: Record = {}, resourceName = 'resource', headers?: Record, ): Promise { const url = `${this.#baseURL}/api/v4${apiResourcePath}${createQueryString(query)}`; const result = await this.#lsFetch.get(url, { headers: { ...this.#getDefaultHeaders(this.#token), ...headers }, }); await handleFetchError(result, resourceName); return result.json() as Promise; } async #postFetch( apiResourcePath: string, resourceName = 'resource', body?: unknown, headers?: Record, ): Promise { const url = `${this.#baseURL}/api/v4${apiResourcePath}`; const response = await this.#lsFetch.post(url, { headers: { 'Content-Type': 'application/json', ...this.#getDefaultHeaders(this.#token), ...headers, }, body: JSON.stringify(body), }); await handleFetchError(response, resourceName); return response.json() as Promise; } #getDefaultHeaders(token?: string) { return { Authorization: `Bearer ${token}`, 'User-Agent': `code-completions-language-server-experiment (${this.#clientInfo?.name}:${this.#clientInfo?.version})`, 'X-Gitlab-Language-Server-Version': getLanguageServerVersion(), }; } #instanceVersionHigherOrEqualThen(version: string): boolean { if (!this.#instanceVersion) return false; return semverCompare(this.#instanceVersion, version) >= 0; } async #getGitLabInstanceVersion(): Promise { if (!this.#token) { return ''; } const headers = this.#getDefaultHeaders(this.#token); const response = await this.#lsFetch.get(`${this.#baseURL}/api/v4/version`, { headers, }); const { version } = await response.json(); return version; } get instanceVersion() { return this.#instanceVersion; } } References: - src/common/api.ts:291 - src/common/suggestion_client/create_v2_request.ts:7 - src/common/suggestion/streaming_handler.ts:121 - src/common/api.ts:268 - src/common/api.ts:28 - src/common/suggestion_client/direct_connection_client.ts:98 - src/common/api.ts:29" You are a code assistant,Definition of 'ClassWithDependencies' in file packages/lib_di/src/index.ts in project gitlab-lsp,"Definition: type ClassWithDependencies = { cls: WithConstructor; id: string; dependencies: string[] }; type Validator = (cwds: ClassWithDependencies[], instanceIds: string[]) => void; const sanitizeId = (idWithRandom: string) => idWithRandom.replace(/-[^-]+$/, ''); /** ensures that only one interface ID implementation is present */ const interfaceUsedOnlyOnce: Validator = (cwds, instanceIds) => { const clashingWithExistingInstance = cwds.filter((cwd) => instanceIds.includes(cwd.id)); if (clashingWithExistingInstance.length > 0) { throw new Error( `The following classes are clashing (have duplicate ID) with instances already present in the container: ${clashingWithExistingInstance.map((cwd) => cwd.cls.name)}`, ); } const groupedById = groupBy(cwds, (cwd) => cwd.id); if (Object.values(groupedById).every((groupedCwds) => groupedCwds.length === 1)) { return; } const messages = Object.entries(groupedById).map( ([id, groupedCwds]) => `'${sanitizeId(id)}' (classes: ${groupedCwds.map((cwd) => cwd.cls.name).join(',')})`, ); throw new Error(`The following interface IDs were used multiple times ${messages.join(',')}`); }; /** throws an error if any class depends on an interface that is not available */ const dependenciesArePresent: Validator = (cwds, instanceIds) => { const allIds = new Set([...cwds.map((cwd) => cwd.id), ...instanceIds]); const cwsWithUnmetDeps = cwds.filter((cwd) => !cwd.dependencies.every((d) => allIds.has(d))); if (cwsWithUnmetDeps.length === 0) { return; } const messages = cwsWithUnmetDeps.map((cwd) => { const unmetDeps = cwd.dependencies.filter((d) => !allIds.has(d)).map(sanitizeId); return `Class ${cwd.cls.name} (interface ${sanitizeId(cwd.id)}) depends on interfaces [${unmetDeps}] that weren't added to the init method.`; }); throw new Error(messages.join('\n')); }; /** uses depth first search to find out if the classes have circular dependency */ const noCircularDependencies: Validator = (cwds, instanceIds) => { const inStack = new Set(); const hasCircularDependency = (id: string): boolean => { if (inStack.has(id)) { return true; } inStack.add(id); const cwd = cwds.find((c) => c.id === id); // we reference existing instance, there won't be circular dependency past this one because instances don't have any dependencies if (!cwd && instanceIds.includes(id)) { inStack.delete(id); return false; } if (!cwd) throw new Error(`assertion error: dependency ID missing ${sanitizeId(id)}`); for (const dependencyId of cwd.dependencies) { if (hasCircularDependency(dependencyId)) { return true; } } inStack.delete(id); return false; }; for (const cwd of cwds) { if (hasCircularDependency(cwd.id)) { throw new Error( `Circular dependency detected between interfaces (${Array.from(inStack).map(sanitizeId)}), starting with '${sanitizeId(cwd.id)}' (class: ${cwd.cls.name}).`, ); } } }; /** * Topological sort of the dependencies - returns array of classes. The classes should be initialized in order given by the array. * https://en.wikipedia.org/wiki/Topological_sorting */ const sortDependencies = (classes: Map): ClassWithDependencies[] => { const visited = new Set(); const sortedClasses: ClassWithDependencies[] = []; const topologicalSort = (interfaceId: string) => { if (visited.has(interfaceId)) { return; } visited.add(interfaceId); const cwd = classes.get(interfaceId); if (!cwd) { // the instance for this ID is already initiated return; } for (const d of cwd.dependencies || []) { topologicalSort(d); } sortedClasses.push(cwd); }; for (const id of classes.keys()) { topologicalSort(id); } return sortedClasses; }; /** * Helper type used by the brandInstance function to ensure that all container.addInstances parameters are branded */ export type BrandedInstance = T; /** * use brandInstance to be able to pass this instance to the container.addInstances method */ export const brandInstance = ( id: InterfaceId, instance: T, ): BrandedInstance => { injectableMetadata.set(instance, { id, dependencies: [] }); return instance; }; /** * Container is responsible for initializing a dependency tree. * * It receives a list of classes decorated with the `@Injectable` decorator * and it constructs instances of these classes in an order that ensures class' dependencies * are initialized before the class itself. * * check https://gitlab.com/viktomas/needle for full documentation of this mini-framework */ export class Container { #instances = new Map(); /** * addInstances allows you to add pre-initialized objects to the container. * This is useful when you want to keep mandatory parameters in class' constructor (e.g. some runtime objects like server connection). * addInstances accepts a list of any objects that have been ""branded"" by the `brandInstance` method */ addInstances(...instances: BrandedInstance[]) { for (const instance of instances) { const metadata = injectableMetadata.get(instance); if (!metadata) { throw new Error( 'assertion error: addInstance invoked without branded object, make sure all arguments are branded with `brandInstance`', ); } if (this.#instances.has(metadata.id)) { throw new Error( `you are trying to add instance for interfaceId ${metadata.id}, but instance with this ID is already in the container.`, ); } this.#instances.set(metadata.id, instance); } } /** * instantiate accepts list of classes, validates that they can be managed by the container * and then initialized them in such order that dependencies of a class are initialized before the class */ instantiate(...classes: WithConstructor[]) { // ensure all classes have been decorated with @Injectable const undecorated = classes.filter((c) => !injectableMetadata.has(c)).map((c) => c.name); if (undecorated.length) { throw new Error(`Classes [${undecorated}] are not decorated with @Injectable.`); } const classesWithDeps: ClassWithDependencies[] = classes.map((cls) => { // we verified just above that all classes are present in the metadata map // eslint-disable-next-line @typescript-eslint/no-non-null-assertion const { id, dependencies } = injectableMetadata.get(cls)!; return { cls, id, dependencies }; }); const validators: Validator[] = [ interfaceUsedOnlyOnce, dependenciesArePresent, noCircularDependencies, ]; validators.forEach((v) => v(classesWithDeps, Array.from(this.#instances.keys()))); const classesById = new Map(); // Index classes by their interface id classesWithDeps.forEach((cwd) => { classesById.set(cwd.id, cwd); }); // Create instances in topological order for (const cwd of sortDependencies(classesById)) { const args = cwd.dependencies.map((dependencyId) => this.#instances.get(dependencyId)); // eslint-disable-next-line new-cap const instance = new cwd.cls(...args); this.#instances.set(cwd.id, instance); } } get(id: InterfaceId): T { const instance = this.#instances.get(id); if (!instance) { throw new Error(`Instance for interface '${sanitizeId(id)}' is not in the container.`); } return instance as T; } } References:" You are a code assistant,Definition of 'SecretRedactor' in file src/common/secret_redaction/index.ts in project gitlab-lsp,"Definition: export const SecretRedactor = createInterfaceId('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/document_transformer_service.ts:81 - src/common/secret_redaction/redactor.test.ts:20 - src/common/ai_context_management_2/retrievers/ai_file_context_retriever.ts:18" You are a code assistant,Definition of 'setCodeSuggestionsContext' in file src/common/tracking/instance_tracker.ts in project gitlab-lsp,"Definition: public setCodeSuggestionsContext( uniqueTrackingId: string, context: Partial, ) { if (this.#circuitBreaker.isOpen()) { return; } const { language, isStreaming } = context; // 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); this.#codeSuggestionsContextMap.set(uniqueTrackingId, { is_streaming: isStreaming, language, timestamp: new Date().toISOString(), }); if (this.#isStreamingSuggestion(uniqueTrackingId)) return; this.#codeSuggestionStates.set(uniqueTrackingId, TRACKING_EVENTS.REQUESTED); this.#trackCodeSuggestionsEvent(TRACKING_EVENTS.REQUESTED, uniqueTrackingId).catch((e) => log.warn('Instance telemetry: Could not track telemetry', e), ); log.debug(`Instance telemetry: New suggestion ${uniqueTrackingId} has been requested`); } async updateCodeSuggestionsContext( uniqueTrackingId: string, contextUpdate: Partial, ) { if (this.#circuitBreaker.isOpen()) { return; } if (this.#isStreamingSuggestion(uniqueTrackingId)) return; const context = this.#codeSuggestionsContextMap.get(uniqueTrackingId); const { model, suggestionOptions, isStreaming } = contextUpdate; if (context) { if (model) { context.language = model.lang ?? null; } if (suggestionOptions?.length) { context.suggestion_size = InstanceTracker.#suggestionSize(suggestionOptions); } if (typeof isStreaming === 'boolean') { context.is_streaming = isStreaming; } this.#codeSuggestionsContextMap.set(uniqueTrackingId, context); } } updateSuggestionState(uniqueTrackingId: string, newState: TRACKING_EVENTS): void { if (this.#circuitBreaker.isOpen()) { return; } if (!this.isEnabled()) return; if (this.#isStreamingSuggestion(uniqueTrackingId)) return; const state = this.#codeSuggestionStates.get(uniqueTrackingId); if (!state) { log.debug(`Instance telemetry: The suggestion with ${uniqueTrackingId} can't be found`); return; } const allowedTransitions = nonStreamingSuggestionStateGraph.get(state); if (!allowedTransitions) { log.debug( `Instance telemetry: The suggestion's ${uniqueTrackingId} state ${state} can't be found in state graph`, ); return; } if (!allowedTransitions.includes(newState)) { log.debug( `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( `Instance telemetry: Conditionally allowing transition to accepted state for ${uniqueTrackingId}`, ); } this.#codeSuggestionStates.set(uniqueTrackingId, newState); this.#trackCodeSuggestionsEvent(newState, uniqueTrackingId).catch((e) => log.warn('Instance telemetry: Could not track telemetry', e), ); log.debug(`Instance telemetry: ${uniqueTrackingId} transisted from ${state} to ${newState}`); } async #trackCodeSuggestionsEvent(eventType: TRACKING_EVENTS, uniqueTrackingId: string) { const event = INSTANCE_TRACKING_EVENTS_MAP[eventType]; if (!event) { return; } try { const { language, suggestion_size } = this.#codeSuggestionsContextMap.get(uniqueTrackingId) ?? {}; await this.#api.fetchFromApi({ type: 'rest', method: 'POST', path: '/usage_data/track_event', body: { event, additional_properties: { unique_tracking_id: uniqueTrackingId, timestamp: new Date().toISOString(), language, suggestion_size, }, }, supportedSinceInstanceVersion: { resourceName: 'track instance telemetry', version: '17.2.0', }, }); this.#circuitBreaker.success(); } catch (error) { if (error instanceof InvalidInstanceVersionError) { if (this.#invalidInstanceMsgLogged) return; this.#invalidInstanceMsgLogged = true; } log.warn(`Instance telemetry: Failed to track event: ${eventType}`, error); this.#circuitBreaker.error(); } } rejectOpenedSuggestions() { log.debug(`Instance Telemetry: Reject all opened suggestions`); this.#codeSuggestionStates.forEach((state, uniqueTrackingId) => { if (endStates.includes(state)) { return; } this.updateSuggestionState(uniqueTrackingId, TRACKING_EVENTS.REJECTED); }); } static #suggestionSize(options: SuggestionOption[]): number { const countLines = (text: string) => (text ? text.split('\n').length : 0); return Math.max(...options.map(({ text }) => countLines(text))); } #isStreamingSuggestion(uniqueTrackingId: string): boolean { return Boolean(this.#codeSuggestionsContextMap.get(uniqueTrackingId)?.is_streaming); } } References:" You are a code assistant,Definition of 'PostRequest' in file src/common/api_types.ts in project gitlab-lsp,"Definition: 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; supportedSinceInstanceVersion?: SupportedSinceInstanceVersion; } export type ApiRequest<_TReturnType> = | GetRequest<_TReturnType> | PostRequest<_TReturnType> | GraphQLRequest<_TReturnType>; export type AdditionalContext = { /** * The type of the context element. Options: `file` or `snippet`. */ type: 'file' | 'snippet'; /** * The name of the context element. A name of the file or a code snippet. */ name: string; /** * The content of the context element. The body of the file or a function. */ content: string; /** * Where the context was derived from */ resolution_strategy: ContextResolution['strategy']; }; // FIXME: Rename to SuggestionOptionText and then rename SuggestionOptionOrStream to SuggestionOption // this refactor can't be done now (2024-05-28) because all the conflicts it would cause with WIP export interface SuggestionOption { index?: number; text: string; uniqueTrackingId: string; lang?: string; } export interface TelemetryRequest { event: string; additional_properties: { unique_tracking_id: string; language?: string; suggestion_size?: number; timestamp: string; }; } References:" You are a code assistant,Definition of 'TreeSitterParserLoadState' in file src/common/tree_sitter/parser.ts in project gitlab-lsp,"Definition: export enum TreeSitterParserLoadState { INIT = 'init', ERRORED = 'errored', READY = 'ready', UNIMPLEMENTED = 'unimplemented', } export type TreeAndLanguage = { tree: Parser.Tree; languageInfo: TreeSitterLanguageInfo; language: Language; }; export abstract class TreeSitterParser { protected loadState: TreeSitterParserLoadState; protected languages: Map; protected readonly parsers = new Map(); abstract init(): Promise; constructor({ languages }: { languages: TreeSitterLanguageInfo[] }) { this.languages = this.buildTreeSitterInfoByExtMap(languages); this.loadState = TreeSitterParserLoadState.INIT; } get loadStateValue(): TreeSitterParserLoadState { return this.loadState; } async parseFile(context: IDocContext): Promise { 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 { 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 { 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 { return languages.reduce((map, language) => { for (const extension of language.extensions) { map.set(extension, language); } return map; }, new Map()); } } References: - src/common/tree_sitter/parser.ts:20 - src/common/tree_sitter/parser.ts:33" You are a code assistant,Definition of 'installLanguage' in file scripts/wasm/build_tree_sitter_wasm.ts in project gitlab-lsp,"Definition: async function installLanguage(language: TreeSitterLanguageInfo) { const grammarsDir = resolve(cwd(), 'vendor', 'grammars'); try { await mkdir(grammarsDir, { recursive: true }); if (!language.nodeModulesPath) { console.warn('nodeModulesPath undefined for grammar!'); return; } await execaCommand( `npm run tree-sitter -- build --wasm node_modules/${language.nodeModulesPath}`, ); const wasmLanguageFile = path.join(cwd(), `tree-sitter-${language.name}.wasm`); console.log(`Installed ${language.name} parser successfully.`); await copyFile(wasmLanguageFile, path.join(grammarsDir, `tree-sitter-${language.name}.wasm`)); await execaCommand(`rm ${wasmLanguageFile}`); } catch (error) { console.error(`Error installing ${language.name} parser:`, error); } } async function installLanguages() { const installPromises = TREE_SITTER_LANGUAGES.map(installLanguage); await Promise.all(installPromises); } installLanguages() .then(() => { console.log('Language parsers installed successfully.'); }) .catch((error) => { console.error('Error installing language parsers:', error); }); References:" You are a code assistant,Definition of 'info' in file src/common/log_types.ts in project gitlab-lsp,"Definition: 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; } 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 'greet' in file src/tests/fixtures/intent/empty_function/go.go in project gitlab-lsp,"Definition: func greet(name string) {} func greet(name string) { fmt.Println(name) } var greet = func(name string) { } var greet = func(name string) { fmt.Println(name) } type Greet struct{} type Greet struct { name string } // empty method declaration func (g Greet) greet() { } // non-empty method declaration func (g Greet) greet() { fmt.Printf(""Hello %s\n"", g.name) } References: - src/tests/fixtures/intent/empty_function/ruby.rb:20 - 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" You are a code assistant,Definition of 'write' in file src/node/http/utils/create_logger_transport.ts in project gitlab-lsp,"Definition: write(chunk, _encoding, callback) { logger[level](chunk.toString()); callback(); }, }); References:" You are a code assistant,Definition of 'WEBVIEW_BASE_PATH' in file src/node/webview/constants.ts in project gitlab-lsp,"Definition: export const WEBVIEW_BASE_PATH = path.join(__dirname, '../../../out/webviews/'); References:" You are a code assistant,Definition of 'constructor' in file packages/lib_webview_transport_socket_io/src/socket_io_webview_transport.ts in project gitlab-lsp,"Definition: constructor(server: Server, logger?: Logger) { this.#server = server; this.#logger = logger ? withPrefix(logger, LOGGER_PREFIX) : undefined; this.#initialize(); } #initialize(): void { this.#logger?.debug('Initializing webview transport'); const namespace = this.#server.of(NAMESPACE_REGEX_PATTERN); namespace.on('connection', (socket) => { const match = socket.nsp.name.match(NAMESPACE_REGEX_PATTERN); if (!match) { this.#logger?.error('Failed to parse namespace for socket connection'); return; } const webviewId = match[1] as WebviewId; const webviewInstanceId = randomUUID() as WebviewInstanceId; const webviewInstanceInfo: WebviewInstanceInfo = { webviewId, webviewInstanceId, }; const connectionId = buildConnectionId(webviewInstanceInfo); this.#connections.set(connectionId, socket); this.#messageEmitter.emit('webview_instance_created', webviewInstanceInfo); socket.on(SOCKET_NOTIFICATION_CHANNEL, (message: unknown) => { if (!isSocketNotificationMessage(message)) { this.#logger?.debug(`[${connectionId}] received notification with invalid format`); return; } this.#logger?.debug(`[${connectionId}] received notification`); this.#messageEmitter.emit('webview_instance_notification_received', { ...webviewInstanceInfo, type: message.type, payload: message.payload, }); }); socket.on(SOCKET_REQUEST_CHANNEL, (message: unknown) => { if (!isSocketRequestMessage(message)) { this.#logger?.debug(`[${connectionId}] received request with invalid format`); return; } this.#logger?.debug(`[${connectionId}] received request`); this.#messageEmitter.emit('webview_instance_request_received', { ...webviewInstanceInfo, type: message.type, payload: message.payload, requestId: message.requestId, }); }); socket.on(SOCKET_RESPONSE_CHANNEL, (message: unknown) => { if (!isSocketResponseMessage(message)) { this.#logger?.debug(`[${connectionId}] received response with invalid format`); return; } this.#logger?.debug(`[${connectionId}] received response`); this.#messageEmitter.emit('webview_instance_response_received', { ...webviewInstanceInfo, type: message.type, payload: message.payload, requestId: message.requestId, success: message.success, reason: message.reason ?? '', }); }); socket.on('error', (error) => { this.#logger?.debug(`[${connectionId}] error`, error); }); socket.on('disconnect', (reason) => { this.#logger?.debug(`[${connectionId}] disconnected with reason: ${reason}`); this.#connections.delete(connectionId); this.#messageEmitter.emit('webview_instance_destroyed', webviewInstanceInfo); }); }); this.#logger?.debug('transport initialized'); } async publish( type: K, message: MessagesToClient[K], ): Promise { const connectionId = buildConnectionId({ webviewId: message.webviewId, webviewInstanceId: message.webviewInstanceId, }); const connection = this.#connections.get(connectionId); if (!connection) { this.#logger?.error(`No active socket found for ID ${connectionId}`); return; } switch (type) { case 'webview_instance_notification': connection.emit(SOCKET_NOTIFICATION_CHANNEL, { type: message.type, payload: message.payload, }); return; case 'webview_instance_request': connection.emit(SOCKET_REQUEST_CHANNEL, { type: message.type, payload: message.payload, requestId: (message as MessagesToClient['webview_instance_request']).requestId, }); return; case 'webview_instance_response': connection.emit(SOCKET_RESPONSE_CHANNEL, { type: message.type, payload: message.payload, requestId: (message as MessagesToClient['webview_instance_response']).requestId, }); return; default: this.#logger?.error(`Unknown message type ${type}`); } } on( type: K, callback: TransportMessageHandler, ): 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 'GitLabApiClient' in file src/common/api.ts in project gitlab-lsp,"Definition: export const GitLabApiClient = createInterfaceId('GitLabApiClient'); export type GenerationType = 'comment' | 'small_file' | 'empty_function' | undefined; export interface CodeSuggestionRequest { prompt_version: number; project_path: string; model_provider?: string; project_id: number; current_file: CodeSuggestionRequestCurrentFile; intent?: 'completion' | 'generation'; stream?: boolean; /** how many suggestion options should the API return */ choices_count?: number; /** additional context to provide to the model */ context?: AdditionalContext[]; /* A user's instructions for code suggestions. */ user_instruction?: string; /* The backend can add additional prompt info based on the type of event */ generation_type?: GenerationType; } export interface CodeSuggestionRequestCurrentFile { file_name: string; content_above_cursor: string; content_below_cursor: string; } export interface CodeSuggestionResponse { choices?: SuggestionOption[]; model?: ICodeSuggestionModel; status: number; error?: string; isDirectConnection?: boolean; } // FIXME: Rename to SuggestionOptionStream when renaming the SuggestionOption export interface StartStreamOption { uniqueTrackingId: string; /** the streamId represents the beginning of a stream * */ streamId: string; } export type SuggestionOptionOrStream = SuggestionOption | StartStreamOption; export interface PersonalAccessToken { name: string; scopes: string[]; active: boolean; } export interface OAuthToken { scope: string[]; } export interface TokenCheckResponse { valid: boolean; reason?: 'unknown' | 'not_active' | 'invalid_scopes'; message?: string; } export interface IDirectConnectionDetailsHeaders { 'X-Gitlab-Global-User-Id': string; 'X-Gitlab-Instance-Id': string; 'X-Gitlab-Host-Name': string; 'X-Gitlab-Saas-Duo-Pro-Namespace-Ids': string; } export interface IDirectConnectionModelDetails { model_provider: string; model_name: string; } export interface IDirectConnectionDetails { base_url: string; token: string; expires_at: number; headers: IDirectConnectionDetailsHeaders; model_details: IDirectConnectionModelDetails; } const CONFIG_CHANGE_EVENT_NAME = 'apiReconfigured'; @Injectable(GitLabApiClient, [LsFetch, ConfigService]) export class GitLabAPI implements GitLabApiClient { #token: string | undefined; #baseURL: string; #clientInfo?: IClientInfo; #lsFetch: LsFetch; #eventEmitter = new EventEmitter(); #configService: ConfigService; #instanceVersion?: string; constructor(lsFetch: LsFetch, configService: ConfigService) { this.#baseURL = GITLAB_API_BASE_URL; this.#lsFetch = lsFetch; this.#configService = configService; this.#configService.onConfigChange(async (config) => { this.#clientInfo = configService.get('client.clientInfo'); this.#lsFetch.updateAgentOptions({ ignoreCertificateErrors: this.#configService.get('client.ignoreCertificateErrors') ?? false, ...(this.#configService.get('client.httpAgentOptions') ?? {}), }); await this.configureApi(config.client); }); } onApiReconfigured(listener: (data: ApiReconfiguredData) => void): Disposable { this.#eventEmitter.on(CONFIG_CHANGE_EVENT_NAME, listener); return { dispose: () => this.#eventEmitter.removeListener(CONFIG_CHANGE_EVENT_NAME, listener) }; } #fireApiReconfigured(isInValidState: boolean, validationMessage?: string) { const data: ApiReconfiguredData = { isInValidState, validationMessage }; this.#eventEmitter.emit(CONFIG_CHANGE_EVENT_NAME, data); } async configureApi({ token, baseUrl = GITLAB_API_BASE_URL, }: { token?: string; baseUrl?: string; }) { if (this.#token === token && this.#baseURL === baseUrl) return; this.#token = token; this.#baseURL = baseUrl; const { valid, reason, message } = await this.checkToken(this.#token); let validationMessage; if (!valid) { this.#configService.set('client.token', undefined); validationMessage = `Token is invalid. ${message}. Reason: ${reason}`; log.warn(validationMessage); } else { log.info('Token is valid'); } this.#instanceVersion = await this.#getGitLabInstanceVersion(); this.#fireApiReconfigured(valid, validationMessage); } #looksLikePatToken(token: string): boolean { // OAuth tokens will be longer than 42 characters and PATs will be shorter. return token.length < 42; } async #checkPatToken(token: string): Promise { const headers = this.#getDefaultHeaders(token); const response = await this.#lsFetch.get( `${this.#baseURL}/api/v4/personal_access_tokens/self`, { headers }, ); await handleFetchError(response, 'Information about personal access token'); const { active, scopes } = (await response.json()) as PersonalAccessToken; if (!active) { return { valid: false, reason: 'not_active', message: 'Token is not active.', }; } if (!this.#hasValidScopes(scopes)) { const joinedScopes = scopes.map((scope) => `'${scope}'`).join(', '); return { valid: false, reason: 'invalid_scopes', message: `Token has scope(s) ${joinedScopes} (needs 'api').`, }; } return { valid: true }; } async #checkOAuthToken(token: string): Promise { const headers = this.#getDefaultHeaders(token); const response = await this.#lsFetch.get(`${this.#baseURL}/oauth/token/info`, { headers, }); await handleFetchError(response, 'Information about OAuth token'); const { scope: scopes } = (await response.json()) as OAuthToken; if (!this.#hasValidScopes(scopes)) { const joinedScopes = scopes.map((scope) => `'${scope}'`).join(', '); return { valid: false, reason: 'invalid_scopes', message: `Token has scope(s) ${joinedScopes} (needs 'api').`, }; } return { valid: true }; } async checkToken(token: string = ''): Promise { try { if (this.#looksLikePatToken(token)) { log.info('Checking token for PAT validity'); return await this.#checkPatToken(token); } log.info('Checking token for OAuth validity'); return await this.#checkOAuthToken(token); } catch (err) { log.error('Error performing token check', err); return { valid: false, reason: 'unknown', message: `Failed to check token: ${err}`, }; } } #hasValidScopes(scopes: string[]): boolean { return scopes.includes('api'); } async getCodeSuggestions( request: CodeSuggestionRequest, ): Promise { if (!this.#token) { throw new Error('Token needs to be provided to request Code Suggestions'); } const headers = { ...this.#getDefaultHeaders(this.#token), 'Content-Type': 'application/json', }; const response = await this.#lsFetch.post( `${this.#baseURL}/api/v4/code_suggestions/completions`, { headers, body: JSON.stringify(request) }, ); await handleFetchError(response, 'Code Suggestions'); const data = await response.json(); return { ...data, status: response.status }; } async *getStreamingCodeSuggestions( request: CodeSuggestionRequest, ): AsyncGenerator { if (!this.#token) { throw new Error('Token needs to be provided to stream code suggestions'); } const headers = { ...this.#getDefaultHeaders(this.#token), 'Content-Type': 'application/json', }; yield* this.#lsFetch.streamFetch( `${this.#baseURL}/api/v4/code_suggestions/completions`, JSON.stringify(request), headers, ); } async fetchFromApi(request: ApiRequest): Promise { if (!this.#token) { return Promise.reject(new Error('Token needs to be provided to authorise API request.')); } if ( request.supportedSinceInstanceVersion && !this.#instanceVersionHigherOrEqualThen(request.supportedSinceInstanceVersion.version) ) { return Promise.reject( new InvalidInstanceVersionError( `Can't ${request.supportedSinceInstanceVersion.resourceName} until your instance is upgraded to ${request.supportedSinceInstanceVersion.version} or higher.`, ), ); } if (request.type === 'graphql') { return this.#graphqlRequest(request.query, request.variables); } switch (request.method) { case 'GET': return this.#fetch(request.path, request.searchParams, 'resource', request.headers); case 'POST': return this.#postFetch(request.path, 'resource', request.body, request.headers); default: // the type assertion is necessary because TS doesn't expect any other types throw new Error(`Unknown request type ${(request as ApiRequest).type}`); } } async connectToCable(): Promise { const headers = this.#getDefaultHeaders(this.#token); const websocketOptions = { headers: { ...headers, Origin: this.#baseURL, }, }; return connectToCable(this.#baseURL, websocketOptions); } async #graphqlRequest( document: RequestDocument, variables?: V, ): Promise { const ensureEndsWithSlash = (url: string) => url.replace(/\/?$/, '/'); const endpoint = new URL('./api/graphql', ensureEndsWithSlash(this.#baseURL)).href; // supports GitLab instances that are on a custom path, e.g. ""https://example.com/gitlab"" const graphqlFetch = async ( input: RequestInfo | URL, init?: RequestInit, ): Promise => { const url = input instanceof URL ? input.toString() : input; return this.#lsFetch.post(url, { ...init, headers: { ...headers, ...init?.headers }, }); }; const headers = this.#getDefaultHeaders(this.#token); const client = new GraphQLClient(endpoint, { headers, fetch: graphqlFetch, }); return client.request(document, variables); } async #fetch( apiResourcePath: string, query: Record = {}, resourceName = 'resource', headers?: Record, ): Promise { const url = `${this.#baseURL}/api/v4${apiResourcePath}${createQueryString(query)}`; const result = await this.#lsFetch.get(url, { headers: { ...this.#getDefaultHeaders(this.#token), ...headers }, }); await handleFetchError(result, resourceName); return result.json() as Promise; } async #postFetch( apiResourcePath: string, resourceName = 'resource', body?: unknown, headers?: Record, ): Promise { const url = `${this.#baseURL}/api/v4${apiResourcePath}`; const response = await this.#lsFetch.post(url, { headers: { 'Content-Type': 'application/json', ...this.#getDefaultHeaders(this.#token), ...headers, }, body: JSON.stringify(body), }); await handleFetchError(response, resourceName); return response.json() as Promise; } #getDefaultHeaders(token?: string) { return { Authorization: `Bearer ${token}`, 'User-Agent': `code-completions-language-server-experiment (${this.#clientInfo?.name}:${this.#clientInfo?.version})`, 'X-Gitlab-Language-Server-Version': getLanguageServerVersion(), }; } #instanceVersionHigherOrEqualThen(version: string): boolean { if (!this.#instanceVersion) return false; return semverCompare(this.#instanceVersion, version) >= 0; } async #getGitLabInstanceVersion(): Promise { if (!this.#token) { return ''; } const headers = this.#getDefaultHeaders(this.#token); const response = await this.#lsFetch.get(`${this.#baseURL}/api/v4/version`, { headers, }); const { version } = await response.json(); return version; } get instanceVersion() { return this.#instanceVersion; } } References: - src/common/suggestion/streaming_handler.ts:36 - src/common/core/handlers/token_check_notifier.test.ts:7 - packages/webview_duo_chat/src/plugin/chat_platform_manager.ts:10 - src/common/suggestion/suggestion_service.ts:119 - packages/webview_duo_chat/src/plugin/index.ts:9 - src/common/suggestion_client/direct_connection_client.ts:28 - src/common/suggestion/suggestion_service.ts:79 - packages/webview_duo_chat/src/plugin/chat_platform.ts:14 - src/common/feature_flags.ts:43 - src/common/graphql/workflow/service.test.ts:15 - src/common/suggestion_client/default_suggestion_client.ts:8 - src/common/services/duo_access/project_access_cache.ts:94 - src/common/suggestion_client/default_suggestion_client.ts:6 - src/common/graphql/workflow/service.ts:18 - src/common/tracking/instance_tracker.ts:51 - src/common/feature_flags.ts:49 - src/common/connection.ts:23 - packages/webview_duo_chat/src/plugin/chat_platform_manager.ts:12 - src/common/tracking/snowplow_tracker.ts:133 - src/common/suggestion_client/default_suggestion_client.test.ts:20 - src/common/suggestion_client/direct_connection_client.test.ts:23 - src/common/suggestion/streaming_handler.test.ts:30 - src/common/suggestion_client/direct_connection_client.ts:54 - src/common/tracking/snowplow_tracker.ts:162 - packages/webview_duo_chat/src/plugin/chat_platform.ts:16 - src/node/duo_workflow/desktop_workflow_runner.ts:49 - src/common/graphql/workflow/service.ts:14 - src/common/tracking/instance_tracker.ts:31 - src/common/feature_flags.test.ts:12 - src/common/core/handlers/token_check_notifier.ts:14 - src/node/duo_workflow/desktop_workflow_runner.ts:53" You are a code assistant,Definition of 'getSuggestions' in file src/common/suggestion_client/suggestion_client_pipeline.ts in project gitlab-lsp,"Definition: getSuggestions(context: SuggestionContext): Promise { return this.#pipeline(context); } } References:" You are a code assistant,Definition of 'JsonRpcConnectionTransportProps' in file packages/lib_webview_transport_json_rpc/src/json_rpc_connection_transport.ts in project gitlab-lsp,"Definition: export type JsonRpcConnectionTransportProps = { connection: Connection; logger: Logger; notificationRpcMethod?: string; webviewCreatedRpcMethod?: string; webviewDestroyedRpcMethod?: string; }; export class JsonRpcConnectionTransport implements Transport { #messageEmitter = createWebviewTransportEventEmitter(); #connection: Connection; #notificationChannel: string; #webviewCreatedChannel: string; #webviewDestroyedChannel: string; #logger?: Logger; #disposables: Disposable[] = []; constructor({ connection, logger, notificationRpcMethod: notificationChannel = DEFAULT_NOTIFICATION_RPC_METHOD, webviewCreatedRpcMethod: webviewCreatedChannel = DEFAULT_WEBVIEW_CREATED_RPC_METHOD, webviewDestroyedRpcMethod: webviewDestroyedChannel = DEFAULT_WEBVIEW_DESTROYED_RPC_METHOD, }: JsonRpcConnectionTransportProps) { this.#connection = connection; this.#logger = logger ? withPrefix(logger, LOGGER_PREFIX) : undefined; this.#notificationChannel = notificationChannel; this.#webviewCreatedChannel = webviewCreatedChannel; this.#webviewDestroyedChannel = webviewDestroyedChannel; this.#subscribeToConnection(); } #subscribeToConnection() { const channelToNotificationHandlerMap = { [this.#webviewCreatedChannel]: handleWebviewCreated(this.#messageEmitter, this.#logger), [this.#webviewDestroyedChannel]: handleWebviewDestroyed(this.#messageEmitter, this.#logger), [this.#notificationChannel]: handleWebviewMessage(this.#messageEmitter, this.#logger), }; Object.entries(channelToNotificationHandlerMap).forEach(([channel, handler]) => { const disposable = this.#connection.onNotification(channel, handler); this.#disposables.push(disposable); }); } on( type: K, callback: TransportMessageHandler, ): Disposable { this.#messageEmitter.on(type, callback as WebviewTransportEventEmitterMessages[K]); return { dispose: () => this.#messageEmitter.off(type, callback as WebviewTransportEventEmitterMessages[K]), }; } publish(type: K, payload: MessagesToClient[K]): Promise { if (type === 'webview_instance_notification') { return this.#connection.sendNotification(this.#notificationChannel, payload); } throw new Error(`Unknown message type: ${type}`); } dispose(): void { this.#messageEmitter.removeAllListeners(); this.#disposables.forEach((disposable) => disposable.dispose()); this.#logger?.debug('JsonRpcConnectionTransport disposed'); } } References: - packages/lib_webview_transport_json_rpc/src/json_rpc_connection_transport.ts:79" You are a code assistant,Definition of 'WebviewUriProvider' in file src/common/webview/webview_resource_location_service.ts in project gitlab-lsp,"Definition: export interface WebviewUriProvider { getUri(webviewId: WebviewId): Uri; } export interface WebviewUriProviderRegistry { register(provider: WebviewUriProvider): void; } export class WebviewLocationService implements WebviewUriProviderRegistry { #uriProviders = new Set(); 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: - src/common/webview/webview_resource_location_service.ts:16 - src/common/webview/webview_resource_location_service.ts:10" You are a code assistant,Definition of 'buildWebviewIdFilter' in file packages/lib_webview/src/setup/plugin/utils/filters.ts in project gitlab-lsp,"Definition: export const buildWebviewIdFilter = (webviewId: WebviewId) => (event: T): boolean => { return event.webviewId === webviewId; }; export const buildWebviewAddressFilter = (address: WebviewAddress) => (event: T): boolean => { return ( event.webviewId === address.webviewId && event.webviewInstanceId === address.webviewInstanceId ); }; References: - packages/lib_webview/src/setup/plugin/webview_controller.ts:76" You are a code assistant,Definition of 'TokenCheckNotifier' in file src/common/core/handlers/token_check_notifier.ts in project gitlab-lsp,"Definition: export interface TokenCheckNotifier extends Notifier {} export const TokenCheckNotifier = createInterfaceId('TokenCheckNotifier'); @Injectable(TokenCheckNotifier, [GitLabApiClient]) export class DefaultTokenCheckNotifier implements TokenCheckNotifier { #notify: NotifyFn | undefined; constructor(api: GitLabApiClient) { api.onApiReconfigured(async ({ isInValidState, validationMessage }) => { if (!isInValidState) { if (!this.#notify) { throw new Error( 'The DefaultTokenCheckNotifier has not been initialized. Call init first.', ); } await this.#notify({ message: validationMessage, }); } }); } init(callback: NotifyFn) { this.#notify = callback; } } References: - src/common/core/handlers/token_check_notifier.test.ts:8 - src/common/connection_service.ts:61" You are a code assistant,Definition of 'get' in file src/common/fetch.ts in project gitlab-lsp,"Definition: get(input: RequestInfo | URL, init?: RequestInit): Promise; post(input: RequestInfo | URL, init?: RequestInit): Promise; put(input: RequestInfo | URL, init?: RequestInit): Promise; updateAgentOptions(options: FetchAgentOptions): void; streamFetch(url: string, body: string, headers: FetchHeaders): AsyncGenerator; } export const LsFetch = createInterfaceId('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 {} async destroy(): Promise {} async fetch(input: RequestInfo | URL, init?: RequestInit): Promise { 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 { // Stub. Should delegate to the node or browser fetch implementations throw new Error('Not implemented'); yield ''; } async delete(input: RequestInfo | URL, init?: RequestInit): Promise { return this.fetch(input, this.updateRequestInit('DELETE', init)); } async get(input: RequestInfo | URL, init?: RequestInit): Promise { return this.fetch(input, this.updateRequestInit('GET', init)); } async post(input: RequestInfo | URL, init?: RequestInit): Promise { return this.fetch(input, this.updateRequestInit('POST', init)); } async put(input: RequestInfo | URL, init?: RequestInit): Promise { return this.fetch(input, this.updateRequestInit('PUT', init)); } async fetchBase(input: RequestInfo | URL, init?: RequestInit): Promise { // 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/utils/headers_to_snowplow_options.ts:22 - src/common/utils/headers_to_snowplow_options.ts:21 - src/common/config_service.ts:134 - src/common/utils/headers_to_snowplow_options.ts:12 - src/common/utils/headers_to_snowplow_options.ts:20" You are a code assistant,Definition of 'getLanguageServerVersion' in file src/common/utils/get_language_server_version.ts in project gitlab-lsp,"Definition: export function getLanguageServerVersion(): string { return '{{GITLAB_LANGUAGE_SERVER_VERSION}}'; } References: - src/node/main.ts:84 - src/common/api.ts:419 - src/browser/main.ts:117 - src/common/suggestion_client/direct_connection_client.ts:112" You are a code assistant,Definition of 'constructor' in file src/common/webview/extension/utils/extension_message_handler_registry.ts in project gitlab-lsp,"Definition: constructor() { super((key) => `${key.webviewId}:${key.type}`); } } References:" You are a code assistant,Definition of 'getMetadata' in file src/common/webview/webview_metadata_provider.ts in project gitlab-lsp,"Definition: getMetadata(): WebviewMetadata[] { return Array.from(this.#plugins).map((plugin) => ({ id: plugin.id, title: plugin.title, uris: this.#accessInfoProviders.resolveUris(plugin.id), })); } } References:" You are a code assistant,Definition of 'triggerDocumentEvent' in file src/common/feature_state/supported_language_check.test.ts in project gitlab-lsp,"Definition: function triggerDocumentEvent( languageId: string, handlerType: TextDocumentChangeListenerType = TextDocumentChangeListenerType.onDidSetActive, ) { const document = createFakePartial({ languageId }); const event = createFakePartial>({ document }); documentEventListener(event, handlerType); } beforeEach(async () => { onDocumentChange.mockImplementation((_listener) => { documentEventListener = _listener; }); configService.set('client.codeCompletion.disabledSupportedLanguages', []); configService.set('client.codeCompletion.additionalLanguages', []); listener.mockReset(); check = new DefaultCodeSuggestionsSupportedLanguageCheck(documents, supportedLanguagesService); disposables.push(check.onChanged(listener)); }); afterEach(() => { while (disposables.length > 0) { disposables.pop()!.dispose(); } }); describe('is updated on ""TextDocumentChangeListenerType.onDidSetActive"" document change event', () => { it('should NOT be engaged when document language is supported', () => { BASE_SUPPORTED_CODE_SUGGESTIONS_LANGUAGES.forEach((languageId: string) => { triggerDocumentEvent(languageId); expect(check.engaged).toBe(false); expect(check.id).toEqual(expect.any(String)); }); }); it('should NOT be engaged when document language is enabled but not supported', () => { configService.set('client.codeCompletion.additionalLanguages', [mockUnsupportedLanguage]); triggerDocumentEvent(mockUnsupportedLanguage); expect(check.engaged).toBe(false); expect(check.id).toEqual(expect.any(String)); }); it('should be engaged when document language is disabled', () => { const languageId = 'python'; configService.set('client.codeCompletion.disabledSupportedLanguages', [languageId]); triggerDocumentEvent(languageId); expect(check.engaged).toBe(true); expect(check.id).toBe(DISABLED_LANGUAGE); }); it('should be engaged when document language is NOT supported', () => { triggerDocumentEvent(mockUnsupportedLanguage); expect(check.engaged).toBe(true); expect(check.id).toBe(UNSUPPORTED_LANGUAGE); }); }); describe('change event', () => { let initialEngaged: boolean; let initialId: string; beforeEach(() => { initialEngaged = check.engaged; initialId = check.id; }); it('emits after check is updated', () => { listener.mockImplementation(() => { expect(check.engaged).toBe(!initialEngaged); }); triggerDocumentEvent('python'); expect(listener).toHaveBeenCalledTimes(1); }); it('emits when only engaged property changes', () => { triggerDocumentEvent('python'); expect(listener).toHaveBeenCalledTimes(1); expect(check.engaged).toBe(!initialEngaged); expect(check.id).toBe(initialId); }); }); }); References: - src/common/feature_state/project_duo_acces_check.test.ts:117 - src/common/feature_state/supported_language_check.test.ts:109 - src/common/feature_state/project_duo_acces_check.test.ts:134 - src/common/feature_state/supported_language_check.test.ts:81 - src/common/feature_state/project_duo_acces_check.test.ts:96 - src/common/feature_state/project_duo_acces_check.test.ts:106 - src/common/feature_state/supported_language_check.test.ts:115 - src/common/feature_state/supported_language_check.test.ts:72 - src/common/feature_state/supported_language_check.test.ts:88 - src/common/feature_state/supported_language_check.test.ts:63" You are a code assistant,Definition of 'NotifyFn' in file src/common/notifier.ts in project gitlab-lsp,"Definition: export type NotifyFn = (data: T) => Promise; export interface Notifier { init(notify: NotifyFn): void; } References:" You are a code assistant,Definition of 'SuccessMessage' in file packages/webview_duo_chat/src/plugin/port/chat/gitlab_chat_api.ts in project gitlab-lsp,"Definition: interface SuccessMessage { type: 'message'; requestId: string; role: string; content: string; contentHtml: string; timestamp: string; errors: string[]; extras?: { sources: object[]; }; } const successResponse = (response: AiMessageResponseType): SuccessMessage => ({ type: 'message', ...response, }); type AiMessage = SuccessMessage | ErrorMessage; type ChatInputTemplate = { query: string; defaultVariables: { platformOrigin?: string; }; }; export class GitLabChatApi { #cachedActionQuery?: ChatInputTemplate = undefined; #manager: GitLabPlatformManagerForChat; constructor(manager: GitLabPlatformManagerForChat) { this.#manager = manager; } async processNewUserPrompt( question: string, subscriptionId?: string, currentFileContext?: GitLabChatFileContext, ): Promise { return this.#sendAiAction({ question, currentFileContext, clientSubscriptionId: subscriptionId, }); } async pullAiMessage(requestId: string, role: string): Promise { const response = await pullHandler(() => this.#getAiMessage(requestId, role)); if (!response) return errorResponse(requestId, ['Reached timeout while fetching response.']); return successResponse(response); } async cleanChat(): Promise { return this.#sendAiAction({ question: SPECIAL_MESSAGES.CLEAN }); } async #currentPlatform() { const platform = await this.#manager.getGitLabPlatform(); if (!platform) throw new Error('Platform is missing!'); return platform; } async #getAiMessage(requestId: string, role: string): Promise { const request: GraphQLRequest = { type: 'graphql', query: AI_MESSAGES_QUERY, variables: { requestIds: [requestId], roles: [role.toUpperCase()] }, }; const platform = await this.#currentPlatform(); const history = await platform.fetchFromApi(request); return history.aiMessages.nodes[0]; } async subscribeToUpdates( messageCallback: (message: AiCompletionResponseMessageType) => Promise, subscriptionId?: string, ) { const platform = await this.#currentPlatform(); const channel = new AiCompletionResponseChannel({ htmlResponse: true, userId: `gid://gitlab/User/${extractUserId(platform.account.id)}`, aiAction: 'CHAT', clientSubscriptionId: subscriptionId, }); const cable = await platform.connectToCable(); // we use this flag to fix https://gitlab.com/gitlab-org/gitlab-vscode-extension/-/issues/1397 // sometimes a chunk comes after the full message and it broke the chat let fullMessageReceived = false; channel.on('newChunk', async (msg) => { if (fullMessageReceived) { log.info(`CHAT-DEBUG: full message received, ignoring chunk`); return; } await messageCallback(msg); }); channel.on('fullMessage', async (message) => { fullMessageReceived = true; await messageCallback(message); if (subscriptionId) { cable.disconnect(); } }); cable.subscribe(channel); } async #sendAiAction(variables: object): Promise { const platform = await this.#currentPlatform(); const { query, defaultVariables } = await this.#actionQuery(); const projectGqlId = await this.#manager.getProjectGqlId(); const request: GraphQLRequest = { type: 'graphql', query, variables: { ...variables, ...defaultVariables, resourceId: projectGqlId ?? null, }, }; return platform.fetchFromApi(request); } async #actionQuery(): Promise { if (!this.#cachedActionQuery) { const platform = await this.#currentPlatform(); try { const { version } = await platform.fetchFromApi(versionRequest); this.#cachedActionQuery = ifVersionGte( version, MINIMUM_PLATFORM_ORIGIN_FIELD_VERSION, () => CHAT_INPUT_TEMPLATE_17_3_AND_LATER, () => CHAT_INPUT_TEMPLATE_17_2_AND_EARLIER, ); } catch (e) { log.debug(`GitLab version check for sending chat failed:`, e as Error); this.#cachedActionQuery = CHAT_INPUT_TEMPLATE_17_3_AND_LATER; } } return this.#cachedActionQuery; } } References: - packages/webview_duo_chat/src/plugin/port/chat/gitlab_chat_api.ts:133" You are a code assistant,Definition of 'dispose' in file src/common/suggestion/suggestion_service.ts in project gitlab-lsp,"Definition: 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 { 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:" You are a code assistant,Definition of 'workflowPluginFactory' in file packages/webview_duo_workflow/src/plugin/index.ts in project gitlab-lsp,"Definition: export const workflowPluginFactory = ( graphqlApi: WorkflowGraphQLService, workflowApi: WorkflowAPI, connection: Connection, ): WebviewPlugin => { 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: - src/node/main.ts:219" You are a code assistant,Definition of 'DefaultDuoProjectPolicy' in file src/common/ai_context_management_2/policies/duo_project_policy.ts in project gitlab-lsp,"Definition: export class DefaultDuoProjectPolicy implements AiContextPolicy { constructor(private duoProjectAccessChecker: DuoProjectAccessChecker) {} 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 'greet' in file src/tests/fixtures/intent/empty_function/typescript.ts 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 { 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:20 - 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" You are a code assistant,Definition of 'DiagnosticsPublisher' in file src/common/diagnostics_publisher.ts in project gitlab-lsp,"Definition: export interface DiagnosticsPublisher { init(publish: DiagnosticsPublisherFn): void; } References: - src/common/connection_service.ts:100" You are a code assistant,Definition of 'sendInitialize' in file src/tests/int/lsp_client.ts in project gitlab-lsp,"Definition: public async sendInitialize( initializeParams?: CustomInitializeParams, ): Promise { const params = { ...DEFAULT_INITIALIZE_PARAMS, ...initializeParams }; const request = new RequestType( 'initialize', ); const response = await this.#connection.sendRequest(request, params); return response; } /** * Send the LSP 'initialized' notification */ public async sendInitialized(options?: InitializedParams | undefined): Promise { const defaults = {}; const params = { ...defaults, ...options }; const request = new NotificationType('initialized'); await this.#connection.sendNotification(request, params); } /** * Send the LSP 'workspace/didChangeConfiguration' notification */ public async sendDidChangeConfiguration( options?: ChangeConfigOptions | undefined, ): Promise { const defaults = createFakePartial({ settings: { token: this.#gitlabToken, baseUrl: this.#gitlabBaseUrl, codeCompletion: { enableSecretRedaction: true, }, telemetry: { enabled: false, }, }, }); const params = { ...defaults, ...options }; const request = new NotificationType( 'workspace/didChangeConfiguration', ); await this.#connection.sendNotification(request, params); } public async sendTextDocumentDidOpen( uri: string, languageId: string, version: number, text: string, ): Promise { const params = { textDocument: { uri, languageId, version, text, }, }; const request = new NotificationType('textDocument/didOpen'); await this.#connection.sendNotification(request, params); } public async sendTextDocumentDidClose(uri: string): Promise { const params = { textDocument: { uri, }, }; const request = new NotificationType('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 { const params = { textDocument: { uri, version, }, contentChanges: [{ text }], }; const request = new NotificationType('textDocument/didChange'); await this.#connection.sendNotification(request, params); } public async sendTextDocumentCompletion( uri: string, line: number, character: number, ): Promise { 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 { await this.#connection.sendNotification(DidChangeDocumentInActiveEditor, uri); } public async getWebviewMetadata(): Promise { const result = await this.#connection.sendRequest( '$/gitlab/webview-metadata', ); return result; } } References:" You are a code assistant,Definition of 'ResponseMessage' in file packages/lib_webview/src/events/webview_runtime_message_bus.ts in project gitlab-lsp,"Definition: 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 {} References: - packages/lib_webview/src/events/webview_runtime_message_bus.ts:37 - packages/lib_webview/src/setup/plugin/webview_instance_message_bus.ts:112 - packages/lib_webview/src/events/webview_runtime_message_bus.ts:34 - packages/lib_webview/src/setup/plugin/webview_instance_message_bus.ts:13" You are a code assistant,Definition of 'CancelStreaming' in file src/common/suggestion/streaming_handler.ts in project gitlab-lsp,"Definition: export const CancelStreaming = new NotificationType( CANCEL_STREAMING_COMPLETION_NOTIFICATION, ); export interface StartStreamParams { api: GitLabApiClient; circuitBreaker: CircuitBreaker; connection: Connection; documentContext: IDocContext; parser: TreeSitterParser; postProcessorPipeline: PostProcessorPipeline; streamId: string; tracker: TelemetryTracker; uniqueTrackingId: string; userInstruction?: string; generationType?: GenerationType; additionalContexts?: AdditionalContext[]; } export class DefaultStreamingHandler { #params: StartStreamParams; constructor(params: StartStreamParams) { this.#params = params; } async startStream() { return startStreaming(this.#params); } } const startStreaming = async ({ additionalContexts, api, circuitBreaker, connection, documentContext, parser, postProcessorPipeline, streamId, tracker, uniqueTrackingId, userInstruction, generationType, }: StartStreamParams) => { const language = parser.getLanguageNameForFile(documentContext.fileRelativePath); tracker.setCodeSuggestionsContext(uniqueTrackingId, { documentContext, additionalContexts, source: SuggestionSource.network, language, isStreaming: true, }); let streamShown = false; let suggestionProvided = false; let streamCancelledOrErrored = false; const cancellationTokenSource = new CancellationTokenSource(); const disposeStopStreaming = connection.onNotification(CancelStreaming, (stream) => { if (stream.id === streamId) { streamCancelledOrErrored = true; cancellationTokenSource.cancel(); if (streamShown) { tracker.updateSuggestionState(uniqueTrackingId, TRACKING_EVENTS.REJECTED); } else { tracker.updateSuggestionState(uniqueTrackingId, TRACKING_EVENTS.CANCELLED); } } }); const cancellationToken = cancellationTokenSource.token; const endStream = async () => { await connection.sendNotification(StreamingCompletionResponse, { id: streamId, done: true, }); if (!streamCancelledOrErrored) { tracker.updateSuggestionState(uniqueTrackingId, TRACKING_EVENTS.STREAM_COMPLETED); if (!suggestionProvided) { tracker.updateSuggestionState(uniqueTrackingId, TRACKING_EVENTS.NOT_PROVIDED); } } }; circuitBreaker.success(); const request: CodeSuggestionRequest = { prompt_version: 1, project_path: '', project_id: -1, current_file: { content_above_cursor: documentContext.prefix, content_below_cursor: documentContext.suffix, file_name: documentContext.fileRelativePath, }, intent: 'generation', stream: true, ...(additionalContexts?.length && { context: additionalContexts, }), ...(userInstruction && { user_instruction: userInstruction, }), generation_type: generationType, }; const trackStreamStarted = once(() => { tracker.updateSuggestionState(uniqueTrackingId, TRACKING_EVENTS.STREAM_STARTED); }); const trackStreamShown = once(() => { tracker.updateSuggestionState(uniqueTrackingId, TRACKING_EVENTS.SHOWN); streamShown = true; }); try { for await (const response of api.getStreamingCodeSuggestions(request)) { if (cancellationToken.isCancellationRequested) { break; } if (circuitBreaker.isOpen()) { break; } trackStreamStarted(); const processedCompletion = await postProcessorPipeline.run({ documentContext, input: { id: streamId, completion: response, done: false }, type: 'stream', }); await connection.sendNotification(StreamingCompletionResponse, processedCompletion); if (response.replace(/\s/g, '').length) { trackStreamShown(); suggestionProvided = true; } } } catch (err) { circuitBreaker.error(); if (isFetchError(err)) { tracker.updateCodeSuggestionsContext(uniqueTrackingId, { status: err.status }); } tracker.updateSuggestionState(uniqueTrackingId, TRACKING_EVENTS.ERRORED); streamCancelledOrErrored = true; log.error('Error streaming code suggestions.', err); } finally { await endStream(); disposeStopStreaming.dispose(); cancellationTokenSource.dispose(); } }; References:" You are a code assistant,Definition of 'handle' in file packages/lib_handler_registry/src/types.ts in project gitlab-lsp,"Definition: handle(key: TKey, ...args: Parameters): Promise>; dispose(): void; } References:" You are a code assistant,Definition of 'TOKEN_CHECK_NOTIFICATION' in file src/common/notifications.ts in project gitlab-lsp,"Definition: export const TOKEN_CHECK_NOTIFICATION = '$/gitlab/token/check'; export const FEATURE_STATE_CHANGE = '$/gitlab/featureStateChange'; export type FeatureStateNotificationParams = FeatureState[]; export const FeatureStateChangeNotificationType = new NotificationType(FEATURE_STATE_CHANGE); export interface TokenCheckNotificationParams { message?: string; } export const TokenCheckNotificationType = new NotificationType( 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( '$/gitlab/didChangeDocumentInActiveEditor', ); References:" You are a code assistant,Definition of 'KeysWithOptionalValues' in file packages/lib_message_bus/src/types/bus.ts in project gitlab-lsp,"Definition: export type KeysWithOptionalValues = { [K in keyof T]: undefined extends T[K] ? K : never; }[keyof T]; /** * Maps notification message types to their corresponding payloads. * @typedef {Record} NotificationMap */ export type NotificationMap = Record; /** * Interface for publishing notifications. * @interface * @template {NotificationMap} TNotifications */ export interface NotificationPublisher { sendNotification>(type: T): void; sendNotification(type: T, payload: TNotifications[T]): void; } /** * Interface for listening to notifications. * @interface * @template {NotificationMap} TNotifications */ export interface NotificationListener { onNotification>( type: T, handler: () => void, ): Disposable; onNotification( type: T, handler: (payload: TNotifications[T]) => void, ): Disposable; } /** * Maps request message types to their corresponding request/response payloads. * @typedef {Record} RequestMap */ export type RequestMap = Record< Method, { params: MessagePayload; result: MessagePayload; } >; type KeysWithOptionalParams = { [K in keyof R]: R[K]['params'] extends undefined ? never : K; }[keyof R]; /** * Extracts the response payload type from a request type. * @template {MessagePayload} T * @typedef {T extends [never] ? void : T[0]} ExtractRequestResponse */ export type ExtractRequestResult = // eslint-disable-next-line @typescript-eslint/no-invalid-void-type T['result'] extends undefined ? void : T; /** * Interface for publishing requests. * @interface * @template {RequestMap} TRequests */ export interface RequestPublisher { sendRequest>( type: T, ): Promise>; sendRequest( type: T, payload: TRequests[T]['params'], ): Promise>; } /** * Interface for listening to requests. * @interface * @template {RequestMap} TRequests */ export interface RequestListener { onRequest>( type: T, handler: () => Promise>, ): Disposable; onRequest( type: T, handler: (payload: TRequests[T]['params']) => Promise>, ): Disposable; } /** * Defines the structure for message definitions, including notifications and requests. */ export type MessageDefinitions< TNotifications extends NotificationMap = NotificationMap, TRequests extends RequestMap = RequestMap, > = { notifications: TNotifications; requests: TRequests; }; export type MessageMap< TInboundMessageDefinitions extends MessageDefinitions = MessageDefinitions, TOutboundMessageDefinitions extends MessageDefinitions = MessageDefinitions, > = { inbound: TInboundMessageDefinitions; outbound: TOutboundMessageDefinitions; }; export interface MessageBus extends NotificationPublisher, NotificationListener, RequestPublisher, RequestListener {} References:" You are a code assistant,Definition of 'getWorkflowEvents' in file src/common/graphql/workflow/service.ts in project gitlab-lsp,"Definition: async getWorkflowEvents(id: string): Promise { 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 'engaged' in file src/common/feature_state/feature_state_manager.test.ts in project gitlab-lsp,"Definition: get engaged() { return duoProjectAccessCheckEngaged; }, id: DUO_DISABLED_FOR_PROJECT, details: 'DUO is disabled for this project', onChanged: mockOn, }); // the CodeSuggestionStateManager is a top-level service that orchestrates the feature checks and sends out notifications, it doesn't have public API const stateManager = new DefaultFeatureStateManager( supportedLanguageCheck, duoProjectAccessCheck, ); stateManager.init(mockSendNotification); mockSendNotification.mockReset(); }); describe('on check engage', () => { it('should notify the client', async () => { const mockChecksEngagedState = createFakePartial([ { featureId: CODE_SUGGESTIONS, engagedChecks: [ { checkId: UNSUPPORTED_LANGUAGE, details: 'Language is not supported', }, ], }, { featureId: CHAT, engagedChecks: [], }, ]); notifyClient(); expect(mockSendNotification).toHaveBeenCalledWith( expect.arrayContaining(mockChecksEngagedState), ); }); }); describe('on check disengage', () => { const mockNoCheckEngagedState = createFakePartial([ { featureId: CODE_SUGGESTIONS, engagedChecks: [], }, { featureId: CHAT, engagedChecks: [], }, ]); it('should notify the client', () => { languageCheckEngaged = false; notifyClient(); expect(mockSendNotification).toHaveBeenCalledWith(mockNoCheckEngagedState); }); }); }); References:" You are a code assistant,Definition of 'createWebviewTransportEventEmitter' in file packages/lib_webview_transport_json_rpc/src/utils/webview_transport_event_emitter.ts in project gitlab-lsp,"Definition: export const createWebviewTransportEventEmitter = (): WebviewTransportEventEmitter => new EventEmitter() as WebviewTransportEventEmitter; References: - packages/lib_webview_transport_json_rpc/src/json_rpc_connection_transport.ts:59 - packages/lib_webview_transport_socket_io/src/socket_io_webview_transport.ts:34" You are a code assistant,Definition of 'info' in file packages/lib_logging/src/null_logger.ts in project gitlab-lsp,"Definition: info(): void { // NOOP } warn(e: Error): void; warn(message: string, e?: Error | undefined): void; warn(): void { // NOOP } error(e: Error): void; error(message: string, e?: Error | undefined): void; error(): void { // NOOP } } References:" You are a code assistant,Definition of 'AiActionResponseType' in file packages/webview_duo_chat/src/plugin/port/chat/gitlab_chat_api.ts in project gitlab-lsp,"Definition: export type AiActionResponseType = { aiAction: { requestId: string; errors: string[] }; }; export const AI_MESSAGES_QUERY = gql` query getAiMessages($requestIds: [ID!], $roles: [AiMessageRole!]) { aiMessages(requestIds: $requestIds, roles: $roles) { nodes { requestId role content contentHtml timestamp errors extras { sources } } } } `; type AiMessageResponseType = { requestId: string; role: string; content: string; contentHtml: string; timestamp: string; errors: string[]; extras?: { sources: object[]; }; }; type AiMessagesResponseType = { aiMessages: { nodes: AiMessageResponseType[]; }; }; interface ErrorMessage { type: 'error'; requestId: string; role: 'system'; errors: string[]; } const errorResponse = (requestId: string, errors: string[]): ErrorMessage => ({ requestId, errors, role: 'system', type: 'error', }); interface SuccessMessage { type: 'message'; requestId: string; role: string; content: string; contentHtml: string; timestamp: string; errors: string[]; extras?: { sources: object[]; }; } const successResponse = (response: AiMessageResponseType): SuccessMessage => ({ type: 'message', ...response, }); type AiMessage = SuccessMessage | ErrorMessage; type ChatInputTemplate = { query: string; defaultVariables: { platformOrigin?: string; }; }; export class GitLabChatApi { #cachedActionQuery?: ChatInputTemplate = undefined; #manager: GitLabPlatformManagerForChat; constructor(manager: GitLabPlatformManagerForChat) { this.#manager = manager; } async processNewUserPrompt( question: string, subscriptionId?: string, currentFileContext?: GitLabChatFileContext, ): Promise { return this.#sendAiAction({ question, currentFileContext, clientSubscriptionId: subscriptionId, }); } async pullAiMessage(requestId: string, role: string): Promise { const response = await pullHandler(() => this.#getAiMessage(requestId, role)); if (!response) return errorResponse(requestId, ['Reached timeout while fetching response.']); return successResponse(response); } async cleanChat(): Promise { return this.#sendAiAction({ question: SPECIAL_MESSAGES.CLEAN }); } async #currentPlatform() { const platform = await this.#manager.getGitLabPlatform(); if (!platform) throw new Error('Platform is missing!'); return platform; } async #getAiMessage(requestId: string, role: string): Promise { const request: GraphQLRequest = { type: 'graphql', query: AI_MESSAGES_QUERY, variables: { requestIds: [requestId], roles: [role.toUpperCase()] }, }; const platform = await this.#currentPlatform(); const history = await platform.fetchFromApi(request); return history.aiMessages.nodes[0]; } async subscribeToUpdates( messageCallback: (message: AiCompletionResponseMessageType) => Promise, subscriptionId?: string, ) { const platform = await this.#currentPlatform(); const channel = new AiCompletionResponseChannel({ htmlResponse: true, userId: `gid://gitlab/User/${extractUserId(platform.account.id)}`, aiAction: 'CHAT', clientSubscriptionId: subscriptionId, }); const cable = await platform.connectToCable(); // we use this flag to fix https://gitlab.com/gitlab-org/gitlab-vscode-extension/-/issues/1397 // sometimes a chunk comes after the full message and it broke the chat let fullMessageReceived = false; channel.on('newChunk', async (msg) => { if (fullMessageReceived) { log.info(`CHAT-DEBUG: full message received, ignoring chunk`); return; } await messageCallback(msg); }); channel.on('fullMessage', async (message) => { fullMessageReceived = true; await messageCallback(message); if (subscriptionId) { cable.disconnect(); } }); cable.subscribe(channel); } async #sendAiAction(variables: object): Promise { const platform = await this.#currentPlatform(); const { query, defaultVariables } = await this.#actionQuery(); const projectGqlId = await this.#manager.getProjectGqlId(); const request: GraphQLRequest = { type: 'graphql', query, variables: { ...variables, ...defaultVariables, resourceId: projectGqlId ?? null, }, }; return platform.fetchFromApi(request); } async #actionQuery(): Promise { if (!this.#cachedActionQuery) { const platform = await this.#currentPlatform(); try { const { version } = await platform.fetchFromApi(versionRequest); this.#cachedActionQuery = ifVersionGte( version, MINIMUM_PLATFORM_ORIGIN_FIELD_VERSION, () => CHAT_INPUT_TEMPLATE_17_3_AND_LATER, () => CHAT_INPUT_TEMPLATE_17_2_AND_EARLIER, ); } catch (e) { log.debug(`GitLab version check for sending chat failed:`, e as Error); this.#cachedActionQuery = CHAT_INPUT_TEMPLATE_17_3_AND_LATER; } } return this.#cachedActionQuery; } } References:" You are a code assistant,Definition of 'sendNotification' in file packages/lib_webview_client/src/bus/provider/socket_io_message_bus.ts in project gitlab-lsp,"Definition: async sendNotification( messageType: T, payload?: TMessages['outbound']['notifications'][T], ): Promise { this.#socket.emit(SOCKET_NOTIFICATION_CHANNEL, { type: messageType, payload }); } sendRequest( type: T, payload?: TMessages['outbound']['requests'][T]['params'], ): Promise> { const requestId = generateRequestId(); let timeout: NodeJS.Timeout | undefined; return new Promise((resolve, reject) => { const pendingRequestDisposable = this.#pendingRequests.register( requestId, (value: ExtractRequestResult) => { resolve(value); clearTimeout(timeout); pendingRequestDisposable.dispose(); }, ); timeout = setTimeout(() => { pendingRequestDisposable.dispose(); reject(new Error('Request timed out')); }, REQUEST_TIMEOUT_MS); this.#socket.emit(SOCKET_REQUEST_CHANNEL, { requestId, type, payload, }); }); } onNotification( messageType: T, callback: (payload: TMessages['inbound']['notifications'][T]) => void, ): Disposable { return this.#notificationHandlers.register(messageType, callback); } onRequest( type: T, handler: ( payload: TMessages['inbound']['requests'][T]['params'], ) => Promise>, ): Disposable { return this.#requestHandlers.register(type, handler); } dispose() { this.#socket.off(SOCKET_NOTIFICATION_CHANNEL, this.#handleNotificationMessage); this.#socket.off(SOCKET_REQUEST_CHANNEL, this.#handleRequestMessage); this.#socket.off(SOCKET_RESPONSE_CHANNEL, this.#handleResponseMessage); this.#notificationHandlers.dispose(); this.#requestHandlers.dispose(); this.#pendingRequests.dispose(); } #setupSocketEventHandlers = () => { this.#socket.on(SOCKET_NOTIFICATION_CHANNEL, this.#handleNotificationMessage); this.#socket.on(SOCKET_REQUEST_CHANNEL, this.#handleRequestMessage); this.#socket.on(SOCKET_RESPONSE_CHANNEL, this.#handleResponseMessage); }; #handleNotificationMessage = async (message: { type: keyof TMessages['inbound']['notifications'] & string; payload: unknown; }) => { await this.#notificationHandlers.handle(message.type, message.payload); }; #handleRequestMessage = async (message: { requestId: string; event: keyof TMessages['inbound']['requests'] & string; payload: unknown; }) => { const response = await this.#requestHandlers.handle(message.event, message.payload); this.#socket.emit(SOCKET_RESPONSE_CHANNEL, { requestId: message.requestId, payload: response, }); }; #handleResponseMessage = async (message: { requestId: string; payload: unknown }) => { await this.#pendingRequests.handle(message.requestId, message.payload); }; } References:" You are a code assistant,Definition of 'Comment' in file src/common/tree_sitter/comments/comment_resolver.ts in project gitlab-lsp,"Definition: export type Comment = { start: Point; end: Point; content: string; capture: QueryCapture; }; export type CommentResolution = | { commentAtCursor: Comment; commentAboveCursor?: never } | { commentAtCursor?: never; commentAboveCursor: Comment }; export class CommentResolver { protected queryByLanguage: Map; constructor() { this.queryByLanguage = new Map(); } #getQueryByLanguage( language: TreeSitterLanguageName, treeSitterLanguage: Language, ): Query | undefined { const query = this.queryByLanguage.get(language); if (query) { return query; } const queryString = commentQueries[language]; if (!queryString) { log.warn(`No comment query found for language: ${language}`); return undefined; } const newQuery = treeSitterLanguage.query(queryString); this.queryByLanguage.set(language, newQuery); return newQuery; } /** * Returns the comment that is on or directly above the cursor, if it exists. * To handle the case the comment may be several new lines above the cursor, * we traverse the tree to check if any nodes are between the comment and the cursor. */ getCommentForCursor({ languageName, tree, cursorPosition, treeSitterLanguage, }: { languageName: TreeSitterLanguageName; tree: Tree; treeSitterLanguage: Language; cursorPosition: Point; }): CommentResolution | undefined { const query = this.#getQueryByLanguage(languageName, treeSitterLanguage); if (!query) { return undefined; } const comments = query.captures(tree.rootNode).map((capture) => { return { start: capture.node.startPosition, end: capture.node.endPosition, content: capture.node.text, capture, }; }); const commentAtCursor = CommentResolver.#getCommentAtCursor(comments, cursorPosition); if (commentAtCursor) { // No need to further check for isPositionInNode etc. as cursor is directly on the comment return { commentAtCursor }; } const commentAboveCursor = CommentResolver.#getCommentAboveCursor(comments, cursorPosition); if (!commentAboveCursor) { return undefined; } const commentParentNode = commentAboveCursor.capture.node.parent; if (!commentParentNode) { return undefined; } if (!CommentResolver.#isPositionInNode(cursorPosition, commentParentNode)) { return undefined; } const directChildren = commentParentNode.children; for (const child of directChildren) { const hasNodeBetweenCursorAndComment = child.startPosition.row > commentAboveCursor.capture.node.endPosition.row && child.startPosition.row <= cursorPosition.row; if (hasNodeBetweenCursorAndComment) { return undefined; } } return { commentAboveCursor }; } static #isPositionInNode(position: Point, node: SyntaxNode): boolean { return position.row >= node.startPosition.row && position.row <= node.endPosition.row; } static #getCommentAboveCursor(comments: Comment[], cursorPosition: Point): Comment | undefined { return CommentResolver.#getLastComment( comments.filter((comment) => comment.end.row < cursorPosition.row), ); } static #getCommentAtCursor(comments: Comment[], cursorPosition: Point): Comment | undefined { return CommentResolver.#getLastComment( comments.filter( (comment) => comment.start.row <= cursorPosition.row && comment.end.row >= cursorPosition.row, ), ); } static #getLastComment(comments: Comment[]): Comment | undefined { return comments.sort((a, b) => b.end.row - a.end.row)[0]; } /** * Returns the total number of lines that are comments in a parsed syntax tree. * Uses a Set because we only want to count each line once. * @param {Object} params - Parameters for counting comment lines. * @param {TreeSitterLanguageName} params.languageName - The name of the programming language. * @param {Tree} params.tree - The syntax tree to analyze. * @param {Language} params.treeSitterLanguage - The Tree-sitter language instance. * @returns {number} - The total number of unique lines containing comments. */ getTotalCommentLines({ treeSitterLanguage, languageName, tree, }: { languageName: TreeSitterLanguageName; treeSitterLanguage: Language; tree: Tree; }): number { const query = this.#getQueryByLanguage(languageName, treeSitterLanguage); const captures = query ? query.captures(tree.rootNode) : []; // Note: in future, we could potentially re-use captures from getCommentForCursor() const commentLineSet = new Set(); // A Set is used to only count each line once (the same comment can span multiple lines) captures.forEach((capture) => { const { startPosition, endPosition } = capture.node; for (let { row } = startPosition; row <= endPosition.row; row++) { commentLineSet.add(row); } }); return commentLineSet.size; } static isCommentEmpty(comment: Comment): boolean { const trimmedContent = comment.content.trim().replace(/[\n\r\\]/g, ' '); // Count the number of alphanumeric characters in the trimmed content const alphanumericCount = (trimmedContent.match(/[a-zA-Z0-9]/g) || []).length; return alphanumericCount <= 2; } } let commentResolver: CommentResolver; export function getCommentResolver(): CommentResolver { if (!commentResolver) { commentResolver = new CommentResolver(); } return commentResolver; } References: - src/common/tree_sitter/comments/comment_resolver.ts:14 - src/common/tree_sitter/comments/comment_resolver.ts:15 - src/common/tree_sitter/intent_resolver.ts:13 - src/common/tree_sitter/comments/comment_resolver.ts:159" You are a code assistant,Definition of 'LRU_CACHE_BYTE_SIZE_LIMIT' in file src/common/advanced_context/helpers.ts in project gitlab-lsp,"Definition: export const LRU_CACHE_BYTE_SIZE_LIMIT = 24 * 1024 * 1024; // 24MB /** * Determines if the advanced context resolver should be used for code suggestions. * Because the Code Suggestions API has other consumers than the language server, * we gate the advanced context resolver behind a feature flag separately. */ export const shouldUseAdvancedContext = ( featureFlagService: FeatureFlagService, configService: ConfigService, ) => { const isEditorAdvancedContextEnabled = featureFlagService.isInstanceFlagEnabled( InstanceFeatureFlags.EditorAdvancedContext, ); const isGenericContextEnabled = featureFlagService.isInstanceFlagEnabled( InstanceFeatureFlags.CodeSuggestionsContext, ); let isEditorOpenTabsContextEnabled = configService.get('client.openTabsContext'); if (isEditorOpenTabsContextEnabled === undefined) { isEditorOpenTabsContextEnabled = true; } /** * TODO - when we introduce other context resolution strategies, * have `isEditorOpenTabsContextEnabled` only disable the corresponding resolver (`lruResolver`) * https://gitlab.com/gitlab-org/editor-extensions/gitlab-lsp/-/issues/298 * https://gitlab.com/groups/gitlab-org/editor-extensions/-/epics/59#note_1981542181 */ return ( isEditorAdvancedContextEnabled && isGenericContextEnabled && isEditorOpenTabsContextEnabled ); }; References:" You are a code assistant,Definition of 'TreeSitterLanguageInfo' in file src/common/tree_sitter/languages.ts in project gitlab-lsp,"Definition: export interface TreeSitterLanguageInfo { name: TreeSitterLanguageName; extensions: string[]; wasmPath: string; nodeModulesPath?: string; } References: - scripts/wasm/build_tree_sitter_wasm.ts:8 - src/common/tree_sitter/parser.ts:78 - src/common/tree_sitter/parser.ts:15" You are a code assistant,Definition of 'build' in file scripts/esbuild/browser.ts in project gitlab-lsp,"Definition: async function build() { await esbuild.build(config); } void build(); References: - scripts/esbuild/desktop.ts:41 - scripts/esbuild/common.ts:31 - scripts/esbuild/browser.ts:26" You are a code assistant,Definition of 'init' in file src/common/tree_sitter/parser.test.ts in project gitlab-lsp,"Definition: async init() { this.loadState = TreeSitterParserLoadState.READY; } })({ languages }); }); afterEach(() => { jest.resetAllMocks(); }); describe('init', () => { it('should initialize the parser', async () => { await treeSitterParser.init(); expect(treeSitterParser.loadStateValue).toBe(TreeSitterParserLoadState.READY); }); it('should handle initialization error', async () => { treeSitterParser.init = async () => { throw new Error('Initialization error'); }; await treeSitterParser.parseFile({} as IDocContext); expect(treeSitterParser.loadStateValue).toBe(TreeSitterParserLoadState.ERRORED); }); }); describe('parseFile', () => { it('should parse a file with a valid parser', async () => { const iDocContext: IDocContext = { fileRelativePath: 'test.ts', prefix: 'function test() {}', suffix: '', position: { line: 0, character: 0 }, languageId: 'typescript', uri: 'file:///test.ts', }; const parseFn = jest.fn().mockReturnValue({}); const getLanguageFn = jest.fn().mockReturnValue(createFakePartial({})); jest.spyOn(treeSitterParser, 'getLanguageInfoForFile').mockReturnValue(languages[0]); jest.spyOn(treeSitterParser, 'getParser').mockResolvedValue( createFakePartial({ parse: parseFn, getLanguage: getLanguageFn, }), ); const result = await treeSitterParser.parseFile(iDocContext); expect(parseFn).toHaveBeenCalled(); expect(result).toEqual({ tree: expect.any(Object), language: expect.any(Object), languageInfo: languages[0], }); }); it('should return undefined when no parser is available for the file', async () => { const iDocContext: IDocContext = { fileRelativePath: 'test.txt', prefix: 'Some text', suffix: '', position: { line: 0, character: 0 }, languageId: 'plaintext', uri: 'file:///test.txt', }; const result = await treeSitterParser.parseFile(iDocContext); expect(result).toBeUndefined(); }); }); describe('getParser', () => { it('should return the parser for languageInfo', async () => { // mock namespace Parser.Language (Parser as unknown as Record).Language = { load: jest.fn().mockResolvedValue({}), }; class FakeParser { setLanguage = jest.fn(); } jest.mocked(Parser).mockImplementation(() => createFakePartial(new FakeParser())); const loadSpy = jest.spyOn(Parser.Language, 'load'); const result = await treeSitterParser.getParser({ name: 'typescript', extensions: ['.ts'], wasmPath: '/path/to/tree-sitter-typescript.wasm', nodeModulesPath: '/path/to/node_modules', }); expect(loadSpy).toHaveBeenCalledWith('/path/to/tree-sitter-typescript.wasm'); expect(result).toBeInstanceOf(FakeParser); }); it('should handle parser loading error', async () => { (Parser.Language.load as jest.Mock).mockRejectedValue(new Error('Loading error')); const result = await treeSitterParser.getParser({ name: 'typescript', extensions: ['.ts'], wasmPath: '/path/to/tree-sitter-typescript.wasm', nodeModulesPath: '/path/to/node_modules', }); expect(treeSitterParser.loadStateValue).toBe(TreeSitterParserLoadState.ERRORED); expect(result).toBeUndefined(); }); }); describe('getLanguageNameForFile', () => { it('should return the language name for a given file', () => { const result = treeSitterParser.getLanguageNameForFile('test.ts'); expect(result).toBe('typescript'); }); it('should return undefined when no language is found for a file', () => { const result = treeSitterParser.getLanguageNameForFile('test.txt'); expect(result).toBeUndefined(); }); }); describe('buildTreeSitterInfoByExtMap', () => { it('should build the language info map by extension', () => { const result = treeSitterParser.buildTreeSitterInfoByExtMap(languages); expect(result).toEqual( new Map([ ['.ts', languages[0]], ['.js', languages[1]], ]), ); }); }); }); References:" You are a code assistant,Definition of 'createFastifyHttpServer' in file src/node/http/create_fastify_http_server.ts in project gitlab-lsp,"Definition: export const createFastifyHttpServer = async ( props: Partial, ): Promise => { const { port = 0, plugins = [] } = props; const logger = props.logger && loggerWithPrefix(props.logger, '[HttpServer]:'); const server = fastify({ forceCloseConnections: true, ignoreTrailingSlash: true, logger: createFastifyLogger(logger), }); try { await registerPlugins(server, plugins, logger); const address = await startFastifyServer(server, port, logger); await server.ready(); logger?.info(`server listening on ${address}`); return { address, server, shutdown: async () => { try { await server.close(); logger?.info('server shutdown'); } catch (err) { logger?.error('error during server shutdown', err as Error); } }, }; } catch (err) { logger?.error('error during server setup', err as Error); throw err; } }; const registerPlugins = async ( server: FastifyInstance, plugins: FastifyPluginRegistration[], logger?: ILog, ) => { await Promise.all( plugins.map(async ({ plugin, options }) => { try { await server.register(plugin, options); } catch (err) { logger?.error('Error during plugin registration', err as Error); throw err; } }), ); }; const startFastifyServer = (server: FastifyInstance, port: number, logger?: ILog): Promise => new Promise((resolve, reject) => { try { server.listen({ port, host: '127.0.0.1' }, (err, address) => { if (err) { logger?.error(err); reject(err); return; } resolve(new URL(address)); }); } catch (error) { reject(error); } }); const createFastifyLogger = (logger?: ILog): FastifyBaseLogger | undefined => logger ? pino(createLoggerTransport(logger)) : undefined; References: - src/node/http/create_fastify_http_server.test.ts:78 - src/node/http/create_fastify_http_server.test.ts:51 - src/node/http/create_fastify_http_server.test.ts:104 - src/node/setup_http.ts:25 - src/node/http/create_fastify_http_server.test.ts:36 - src/node/http/create_fastify_http_server.test.ts:62 - src/node/http/create_fastify_http_server.test.ts:89" You are a code assistant,Definition of 'getCachedSuggestions' in file src/common/suggestion/suggestions_cache.ts in project gitlab-lsp,"Definition: 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 'greet' in file src/tests/fixtures/intent/empty_function/ruby.rb in project gitlab-lsp,"Definition: 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/ruby.rb:20 - 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" You are a code assistant,Definition of 'getLoadState' in file src/browser/tree_sitter/index.ts in project gitlab-lsp,"Definition: getLoadState() { return this.loadState; } async init(): Promise { 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:" You are a code assistant,Definition of 'isOpen' in file src/common/circuit_breaker/circuit_breaker.ts in project gitlab-lsp,"Definition: isOpen(): boolean; onOpen(listener: () => void): Disposable; onClose(listener: () => void): Disposable; } References:" You are a code assistant,Definition of 'stackToArray' in file src/common/fetch_error.ts in project gitlab-lsp,"Definition: 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/fetch_error.ts:68" You are a code assistant,Definition of 'ChatSupportResponseInterface' in file packages/webview_duo_chat/src/plugin/port/chat/api/get_chat_support.ts in project gitlab-lsp,"Definition: export interface ChatSupportResponseInterface { hasSupportForChat: boolean; platform?: GitLabPlatformForAccount; } export type ChatAvailableResponseType = { currentUser: { duoChatAvailable: boolean; }; }; export async function getChatSupport( platform?: GitLabPlatformForAccount | undefined, ): Promise { const request: GraphQLRequest = { type: 'graphql', query: queryGetChatAvailability, variables: {}, }; const noSupportResponse: ChatSupportResponseInterface = { hasSupportForChat: false }; if (!platform) { return noSupportResponse; } try { const { currentUser: { duoChatAvailable }, } = await platform.fetchFromApi(request); if (duoChatAvailable) { return { hasSupportForChat: duoChatAvailable, platform, }; } return noSupportResponse; } catch (e) { log.error(e as Error); return noSupportResponse; } } References: - packages/webview_duo_chat/src/plugin/port/chat/api/get_chat_support.ts:33 - packages/webview_duo_chat/src/plugin/port/chat/get_platform_manager_for_chat.test.ts:94 - packages/webview_duo_chat/src/plugin/port/chat/get_platform_manager_for_chat.test.ts:98 - packages/webview_duo_chat/src/plugin/port/chat/api/get_chat_support.test.ts:19 - packages/webview_duo_chat/src/plugin/port/chat/get_platform_manager_for_chat.test.ts:102" You are a code assistant,Definition of 'initialize' in file src/tests/fixtures/intent/empty_function/ruby.rb in project gitlab-lsp,"Definition: 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/ruby.rb:17 - src/tests/fixtures/intent/empty_function/ruby.rb:25" You are a code assistant,Definition of 'sendRequest' in file src/common/webview/extension/extension_connection_message_bus.ts in project gitlab-lsp,"Definition: sendRequest( type: T, payload?: TMessageMap['outbound']['requests'][T]['params'], ): Promise> { return this.#connection.sendRequest(this.#rpcMethods.request, { webviewId: this.#webviewId, type, payload, }); } async sendNotification( type: T, payload?: TMessageMap['outbound']['notifications'][T], ): Promise { await this.#connection.sendNotification(this.#rpcMethods.notification, { webviewId: this.#webviewId, type, payload, }); } } References:" You are a code assistant,Definition of 'addProcessor' in file src/common/suggestion_client/post_processors/post_processor_pipeline.ts in project gitlab-lsp,"Definition: addProcessor(processor: PostProcessor): void { this.#processors.push(processor); } async run({ documentContext, input, type, }: { documentContext: IDocContext; input: ProcessorInputMap[T]; type: T; }): Promise { if (!this.#processors.length) return input as ProcessorInputMap[T]; return this.#processors.reduce( async (prevPromise, processor) => { const result = await prevPromise; // eslint-disable-next-line default-case switch (type) { case 'stream': return processor.processStream( documentContext, result as StreamingCompletionResponse, ) as Promise; case 'completion': return processor.processCompletion( documentContext, result as SuggestionOption[], ) as Promise; } throw new Error('Unexpected type in pipeline processing'); }, Promise.resolve(input) as Promise, ); } } References:" You are a code assistant,Definition of 'setupHttp' in file src/node/setup_http.ts in project gitlab-lsp,"Definition: export async function setupHttp( plugins: WebviewPlugin[], uriProviderRegistry: WebviewUriProviderRegistry, transportRegistry: Set, logger: Logger, ): Promise { const server = await initializeHttpServer( plugins.map((x) => x.id), logger, ); uriProviderRegistry.register(new WebviewHttpAccessInfoProvider(server.addresses()?.[0])); transportRegistry.add(new SocketIOWebViewTransport(server.io)); } async function initializeHttpServer(webviewIds: WebviewId[], logger: Logger) { const { shutdown: fastifyShutdown, server } = await createFastifyHttpServer({ plugins: [ createFastifySocketIoPlugin(), createWebviewPlugin({ webviewIds, }), { plugin: async (app) => { app.get('/', () => { return { message: 'Hello, world!' }; }); }, }, ], logger, }); const handleGracefulShutdown = async (signal: string) => { logger.info(`Received ${signal}. Shutting down...`); server.io.close(); await fastifyShutdown(); logger.info('Shutdown complete. Exiting process.'); process.exit(0); }; process.on('SIGTERM', handleGracefulShutdown); process.on('SIGINT', handleGracefulShutdown); return server; } References: - src/node/main.ts:226" You are a code assistant,Definition of 'add' in file src/common/tracking/snowplow/emitter.ts in project gitlab-lsp,"Definition: add(data: PayloadBuilder) { this.#trackingQueue.push(data); if (this.#trackingQueue.length >= this.#maxItems) { this.#drainQueue().catch(() => {}); } } async #drainQueue(): Promise { 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:" You are a code assistant,Definition of 'onNotification' in file packages/lib_webview/src/setup/plugin/webview_instance_message_bus.ts in project gitlab-lsp,"Definition: onNotification(type: Method, handler: Handler): Disposable { return this.#notificationEvents.register(type, handler); } async sendRequest(type: Method, payload?: unknown): Promise { 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); } 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 'FibonacciSolver' in file packages/lib-pkg-1/src/types/fibonacci_solver.ts in project gitlab-lsp,"Definition: export interface FibonacciSolver { solve: (index: number) => number; } References:" You are a code assistant,Definition of 'onApiReconfigured' in file src/common/api.ts in project gitlab-lsp,"Definition: onApiReconfigured(listener: (data: ApiReconfiguredData) => void): Disposable; readonly instanceVersion?: string; } export const GitLabApiClient = createInterfaceId('GitLabApiClient'); export type GenerationType = 'comment' | 'small_file' | 'empty_function' | undefined; export interface CodeSuggestionRequest { prompt_version: number; project_path: string; model_provider?: string; project_id: number; current_file: CodeSuggestionRequestCurrentFile; intent?: 'completion' | 'generation'; stream?: boolean; /** how many suggestion options should the API return */ choices_count?: number; /** additional context to provide to the model */ context?: AdditionalContext[]; /* A user's instructions for code suggestions. */ user_instruction?: string; /* The backend can add additional prompt info based on the type of event */ generation_type?: GenerationType; } export interface CodeSuggestionRequestCurrentFile { file_name: string; content_above_cursor: string; content_below_cursor: string; } export interface CodeSuggestionResponse { choices?: SuggestionOption[]; model?: ICodeSuggestionModel; status: number; error?: string; isDirectConnection?: boolean; } // FIXME: Rename to SuggestionOptionStream when renaming the SuggestionOption export interface StartStreamOption { uniqueTrackingId: string; /** the streamId represents the beginning of a stream * */ streamId: string; } export type SuggestionOptionOrStream = SuggestionOption | StartStreamOption; export interface PersonalAccessToken { name: string; scopes: string[]; active: boolean; } export interface OAuthToken { scope: string[]; } export interface TokenCheckResponse { valid: boolean; reason?: 'unknown' | 'not_active' | 'invalid_scopes'; message?: string; } export interface IDirectConnectionDetailsHeaders { 'X-Gitlab-Global-User-Id': string; 'X-Gitlab-Instance-Id': string; 'X-Gitlab-Host-Name': string; 'X-Gitlab-Saas-Duo-Pro-Namespace-Ids': string; } export interface IDirectConnectionModelDetails { model_provider: string; model_name: string; } export interface IDirectConnectionDetails { base_url: string; token: string; expires_at: number; headers: IDirectConnectionDetailsHeaders; model_details: IDirectConnectionModelDetails; } const CONFIG_CHANGE_EVENT_NAME = 'apiReconfigured'; @Injectable(GitLabApiClient, [LsFetch, ConfigService]) export class GitLabAPI implements GitLabApiClient { #token: string | undefined; #baseURL: string; #clientInfo?: IClientInfo; #lsFetch: LsFetch; #eventEmitter = new EventEmitter(); #configService: ConfigService; #instanceVersion?: string; constructor(lsFetch: LsFetch, configService: ConfigService) { this.#baseURL = GITLAB_API_BASE_URL; this.#lsFetch = lsFetch; this.#configService = configService; this.#configService.onConfigChange(async (config) => { this.#clientInfo = configService.get('client.clientInfo'); this.#lsFetch.updateAgentOptions({ ignoreCertificateErrors: this.#configService.get('client.ignoreCertificateErrors') ?? false, ...(this.#configService.get('client.httpAgentOptions') ?? {}), }); await this.configureApi(config.client); }); } onApiReconfigured(listener: (data: ApiReconfiguredData) => void): Disposable { this.#eventEmitter.on(CONFIG_CHANGE_EVENT_NAME, listener); return { dispose: () => this.#eventEmitter.removeListener(CONFIG_CHANGE_EVENT_NAME, listener) }; } #fireApiReconfigured(isInValidState: boolean, validationMessage?: string) { const data: ApiReconfiguredData = { isInValidState, validationMessage }; this.#eventEmitter.emit(CONFIG_CHANGE_EVENT_NAME, data); } async configureApi({ token, baseUrl = GITLAB_API_BASE_URL, }: { token?: string; baseUrl?: string; }) { if (this.#token === token && this.#baseURL === baseUrl) return; this.#token = token; this.#baseURL = baseUrl; const { valid, reason, message } = await this.checkToken(this.#token); let validationMessage; if (!valid) { this.#configService.set('client.token', undefined); validationMessage = `Token is invalid. ${message}. Reason: ${reason}`; log.warn(validationMessage); } else { log.info('Token is valid'); } this.#instanceVersion = await this.#getGitLabInstanceVersion(); this.#fireApiReconfigured(valid, validationMessage); } #looksLikePatToken(token: string): boolean { // OAuth tokens will be longer than 42 characters and PATs will be shorter. return token.length < 42; } async #checkPatToken(token: string): Promise { const headers = this.#getDefaultHeaders(token); const response = await this.#lsFetch.get( `${this.#baseURL}/api/v4/personal_access_tokens/self`, { headers }, ); await handleFetchError(response, 'Information about personal access token'); const { active, scopes } = (await response.json()) as PersonalAccessToken; if (!active) { return { valid: false, reason: 'not_active', message: 'Token is not active.', }; } if (!this.#hasValidScopes(scopes)) { const joinedScopes = scopes.map((scope) => `'${scope}'`).join(', '); return { valid: false, reason: 'invalid_scopes', message: `Token has scope(s) ${joinedScopes} (needs 'api').`, }; } return { valid: true }; } async #checkOAuthToken(token: string): Promise { const headers = this.#getDefaultHeaders(token); const response = await this.#lsFetch.get(`${this.#baseURL}/oauth/token/info`, { headers, }); await handleFetchError(response, 'Information about OAuth token'); const { scope: scopes } = (await response.json()) as OAuthToken; if (!this.#hasValidScopes(scopes)) { const joinedScopes = scopes.map((scope) => `'${scope}'`).join(', '); return { valid: false, reason: 'invalid_scopes', message: `Token has scope(s) ${joinedScopes} (needs 'api').`, }; } return { valid: true }; } async checkToken(token: string = ''): Promise { try { if (this.#looksLikePatToken(token)) { log.info('Checking token for PAT validity'); return await this.#checkPatToken(token); } log.info('Checking token for OAuth validity'); return await this.#checkOAuthToken(token); } catch (err) { log.error('Error performing token check', err); return { valid: false, reason: 'unknown', message: `Failed to check token: ${err}`, }; } } #hasValidScopes(scopes: string[]): boolean { return scopes.includes('api'); } async getCodeSuggestions( request: CodeSuggestionRequest, ): Promise { if (!this.#token) { throw new Error('Token needs to be provided to request Code Suggestions'); } const headers = { ...this.#getDefaultHeaders(this.#token), 'Content-Type': 'application/json', }; const response = await this.#lsFetch.post( `${this.#baseURL}/api/v4/code_suggestions/completions`, { headers, body: JSON.stringify(request) }, ); await handleFetchError(response, 'Code Suggestions'); const data = await response.json(); return { ...data, status: response.status }; } async *getStreamingCodeSuggestions( request: CodeSuggestionRequest, ): AsyncGenerator { if (!this.#token) { throw new Error('Token needs to be provided to stream code suggestions'); } const headers = { ...this.#getDefaultHeaders(this.#token), 'Content-Type': 'application/json', }; yield* this.#lsFetch.streamFetch( `${this.#baseURL}/api/v4/code_suggestions/completions`, JSON.stringify(request), headers, ); } async fetchFromApi(request: ApiRequest): Promise { if (!this.#token) { return Promise.reject(new Error('Token needs to be provided to authorise API request.')); } if ( request.supportedSinceInstanceVersion && !this.#instanceVersionHigherOrEqualThen(request.supportedSinceInstanceVersion.version) ) { return Promise.reject( new InvalidInstanceVersionError( `Can't ${request.supportedSinceInstanceVersion.resourceName} until your instance is upgraded to ${request.supportedSinceInstanceVersion.version} or higher.`, ), ); } if (request.type === 'graphql') { return this.#graphqlRequest(request.query, request.variables); } switch (request.method) { case 'GET': return this.#fetch(request.path, request.searchParams, 'resource', request.headers); case 'POST': return this.#postFetch(request.path, 'resource', request.body, request.headers); default: // the type assertion is necessary because TS doesn't expect any other types throw new Error(`Unknown request type ${(request as ApiRequest).type}`); } } async connectToCable(): Promise { const headers = this.#getDefaultHeaders(this.#token); const websocketOptions = { headers: { ...headers, Origin: this.#baseURL, }, }; return connectToCable(this.#baseURL, websocketOptions); } async #graphqlRequest( document: RequestDocument, variables?: V, ): Promise { const ensureEndsWithSlash = (url: string) => url.replace(/\/?$/, '/'); const endpoint = new URL('./api/graphql', ensureEndsWithSlash(this.#baseURL)).href; // supports GitLab instances that are on a custom path, e.g. ""https://example.com/gitlab"" const graphqlFetch = async ( input: RequestInfo | URL, init?: RequestInit, ): Promise => { const url = input instanceof URL ? input.toString() : input; return this.#lsFetch.post(url, { ...init, headers: { ...headers, ...init?.headers }, }); }; const headers = this.#getDefaultHeaders(this.#token); const client = new GraphQLClient(endpoint, { headers, fetch: graphqlFetch, }); return client.request(document, variables); } async #fetch( apiResourcePath: string, query: Record = {}, resourceName = 'resource', headers?: Record, ): Promise { const url = `${this.#baseURL}/api/v4${apiResourcePath}${createQueryString(query)}`; const result = await this.#lsFetch.get(url, { headers: { ...this.#getDefaultHeaders(this.#token), ...headers }, }); await handleFetchError(result, resourceName); return result.json() as Promise; } async #postFetch( apiResourcePath: string, resourceName = 'resource', body?: unknown, headers?: Record, ): Promise { const url = `${this.#baseURL}/api/v4${apiResourcePath}`; const response = await this.#lsFetch.post(url, { headers: { 'Content-Type': 'application/json', ...this.#getDefaultHeaders(this.#token), ...headers, }, body: JSON.stringify(body), }); await handleFetchError(response, resourceName); return response.json() as Promise; } #getDefaultHeaders(token?: string) { return { Authorization: `Bearer ${token}`, 'User-Agent': `code-completions-language-server-experiment (${this.#clientInfo?.name}:${this.#clientInfo?.version})`, 'X-Gitlab-Language-Server-Version': getLanguageServerVersion(), }; } #instanceVersionHigherOrEqualThen(version: string): boolean { if (!this.#instanceVersion) return false; return semverCompare(this.#instanceVersion, version) >= 0; } async #getGitLabInstanceVersion(): Promise { if (!this.#token) { return ''; } const headers = this.#getDefaultHeaders(this.#token); const response = await this.#lsFetch.get(`${this.#baseURL}/api/v4/version`, { headers, }); const { version } = await response.json(); return version; } get instanceVersion() { return this.#instanceVersion; } } References:" You are a code assistant,Definition of 'SocketIoMessageBus' in file packages/lib_webview_client/src/bus/provider/socket_io_message_bus.ts in project gitlab-lsp,"Definition: export class SocketIoMessageBus implements MessageBus { #notificationHandlers = new SimpleRegistry(); #requestHandlers = new SimpleRegistry(); #pendingRequests = new SimpleRegistry(); #socket: Socket; constructor(socket: Socket) { this.#socket = socket; this.#setupSocketEventHandlers(); } async sendNotification( messageType: T, payload?: TMessages['outbound']['notifications'][T], ): Promise { this.#socket.emit(SOCKET_NOTIFICATION_CHANNEL, { type: messageType, payload }); } sendRequest( type: T, payload?: TMessages['outbound']['requests'][T]['params'], ): Promise> { const requestId = generateRequestId(); let timeout: NodeJS.Timeout | undefined; return new Promise((resolve, reject) => { const pendingRequestDisposable = this.#pendingRequests.register( requestId, (value: ExtractRequestResult) => { resolve(value); clearTimeout(timeout); pendingRequestDisposable.dispose(); }, ); timeout = setTimeout(() => { pendingRequestDisposable.dispose(); reject(new Error('Request timed out')); }, REQUEST_TIMEOUT_MS); this.#socket.emit(SOCKET_REQUEST_CHANNEL, { requestId, type, payload, }); }); } onNotification( messageType: T, callback: (payload: TMessages['inbound']['notifications'][T]) => void, ): Disposable { return this.#notificationHandlers.register(messageType, callback); } onRequest( type: T, handler: ( payload: TMessages['inbound']['requests'][T]['params'], ) => Promise>, ): Disposable { return this.#requestHandlers.register(type, handler); } dispose() { this.#socket.off(SOCKET_NOTIFICATION_CHANNEL, this.#handleNotificationMessage); this.#socket.off(SOCKET_REQUEST_CHANNEL, this.#handleRequestMessage); this.#socket.off(SOCKET_RESPONSE_CHANNEL, this.#handleResponseMessage); this.#notificationHandlers.dispose(); this.#requestHandlers.dispose(); this.#pendingRequests.dispose(); } #setupSocketEventHandlers = () => { this.#socket.on(SOCKET_NOTIFICATION_CHANNEL, this.#handleNotificationMessage); this.#socket.on(SOCKET_REQUEST_CHANNEL, this.#handleRequestMessage); this.#socket.on(SOCKET_RESPONSE_CHANNEL, this.#handleResponseMessage); }; #handleNotificationMessage = async (message: { type: keyof TMessages['inbound']['notifications'] & string; payload: unknown; }) => { await this.#notificationHandlers.handle(message.type, message.payload); }; #handleRequestMessage = async (message: { requestId: string; event: keyof TMessages['inbound']['requests'] & string; payload: unknown; }) => { const response = await this.#requestHandlers.handle(message.event, message.payload); this.#socket.emit(SOCKET_RESPONSE_CHANNEL, { requestId: message.requestId, payload: response, }); }; #handleResponseMessage = async (message: { requestId: string; payload: unknown }) => { await this.#pendingRequests.handle(message.requestId, message.payload); }; } References: - packages/lib_webview_client/src/bus/provider/socket_io_message_bus_provider.ts:18 - packages/lib_webview_client/src/bus/provider/socket_io_message_bus.test.ts:56" You are a code assistant,Definition of 'FeatureFlagService' in file src/common/feature_flags.ts in project gitlab-lsp,"Definition: export interface FeatureFlagService { /** * Checks if a feature flag is enabled on the GitLab instance. * @see `IGitLabAPI` for how the instance is determined. * @requires `updateInstanceFeatureFlags` to be called first. */ isInstanceFlagEnabled(name: InstanceFeatureFlags): boolean; /** * Checks if a feature flag is enabled on the client. * @see `ConfigService` for client configuration. */ isClientFlagEnabled(name: ClientFeatureFlags): boolean; } @Injectable(FeatureFlagService, [GitLabApiClient, ConfigService]) export class DefaultFeatureFlagService { #api: GitLabApiClient; #configService: ConfigService; #featureFlags: Map = 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 { 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 { 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: - src/common/suggestion/suggestion_service.ts:83 - src/common/tracking/snowplow_tracker.ts:152 - src/common/connection.ts:24 - src/common/message_handler.ts:37 - src/common/security_diagnostics_publisher.ts:40 - src/common/suggestion/suggestion_service.ts:137 - src/common/advanced_context/helpers.ts:21 - src/common/security_diagnostics_publisher.ts:37 - src/common/message_handler.ts:83 - src/common/feature_flags.test.ts:13 - src/common/security_diagnostics_publisher.test.ts:19 - src/common/tracking/snowplow_tracker.ts:161 - src/common/tracking/snowplow_tracker.test.ts:76" You are a code assistant,Definition of 'log' in file packages/webview_duo_chat/src/plugin/port/log.ts in project gitlab-lsp,"Definition: export const log: Logger = new NullLogger(); References: - scripts/set_ls_version.js:17 - scripts/commit-lint/lint.js:66 - src/tests/fixtures/intent/empty_function/javascript.js:4 - src/tests/fixtures/intent/empty_function/javascript.js:31 - scripts/commit-lint/lint.js:61 - src/tests/fixtures/intent/empty_function/javascript.js:16 - src/tests/fixtures/intent/empty_function/javascript.js:10" You are a code assistant,Definition of 'DuoChatWebviewMessageBus' in file packages/webview_duo_chat/src/plugin/types.ts in project gitlab-lsp,"Definition: export type DuoChatWebviewMessageBus = MessageBus<{ inbound: Messages['webviewToPlugin']; outbound: Messages['pluginToWebview']; }>; export type DuoChatExtensionMessageBus = MessageBus<{ inbound: Messages['extensionToPlugin']; outbound: Messages['pluginToExtension']; }>; /** * These types are copied from ./src/common/api_types.ts * TODO: move these types to a common package */ // why: `_TReturnType` helps encapsulate the full request type when used with `fetchFromApi` /* eslint @typescript-eslint/no-unused-vars: [""error"", { ""varsIgnorePattern"": ""TReturnType"" }] */ /** * The response body is parsed as JSON and it's up to the client to ensure it * matches the TReturnType */ interface SupportedSinceInstanceVersion { version: string; resourceName: string; } interface BaseRestRequest<_TReturnType> { type: 'rest'; /** * 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; headers?: Record; supportedSinceInstanceVersion?: SupportedSinceInstanceVersion; } interface GraphQLRequest<_TReturnType> { type: 'graphql'; query: string; /** Options passed to the GraphQL query */ variables: Record; 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; supportedSinceInstanceVersion?: SupportedSinceInstanceVersion; } export type ApiRequest<_TReturnType> = | GetRequest<_TReturnType> | PostRequest<_TReturnType> | GraphQLRequest<_TReturnType>; export interface GitLabApiClient { fetchFromApi(request: ApiRequest): Promise; connectToCable(): Promise; } References: - packages/webview_duo_chat/src/plugin/chat_controller.ts:21 - packages/webview_duo_chat/src/plugin/chat_controller.ts:15" You are a code assistant,Definition of 'SuccessfulResponse' in file packages/lib_webview_transport/src/types.ts in project gitlab-lsp,"Definition: export type SuccessfulResponse = { success: true; }; export type FailedResponse = { success: false; reason: string; }; export type WebviewInstanceResponseEventData = WebviewAddress & WebviewRequestInfo & WebviewEventInfo & (SuccessfulResponse | FailedResponse); export type MessagesToServer = { webview_instance_created: WebviewInstanceCreatedEventData; webview_instance_destroyed: WebviewInstanceDestroyedEventData; webview_instance_notification_received: WebviewInstanceNotificationEventData; webview_instance_request_received: WebviewInstanceRequestEventData; webview_instance_response_received: WebviewInstanceResponseEventData; }; export type MessagesToClient = { webview_instance_notification: WebviewInstanceNotificationEventData; webview_instance_request: WebviewInstanceRequestEventData; webview_instance_response: WebviewInstanceResponseEventData; }; export interface TransportMessageHandler { (payload: T): void; } export interface TransportListener { on( type: K, callback: TransportMessageHandler, ): Disposable; } export interface TransportPublisher { publish(type: K, payload: MessagesToClient[K]): Promise; } export interface Transport extends TransportListener, TransportPublisher {} References:" You are a code assistant,Definition of 'createWebviewTransportEventEmitter' in file packages/lib_webview_transport_socket_io/src/utils/webview_transport_event_emitter.ts in project gitlab-lsp,"Definition: export const createWebviewTransportEventEmitter = (): WebviewTransportEventEmitter => new EventEmitter() as WebviewTransportEventEmitter; References: - packages/lib_webview_transport_json_rpc/src/json_rpc_connection_transport.ts:59 - packages/lib_webview_transport_socket_io/src/socket_io_webview_transport.ts:34" You are a code assistant,Definition of 'DUO_DISABLED_FOR_PROJECT' in file src/common/feature_state/feature_state_management_types.ts in project gitlab-lsp,"Definition: export const DUO_DISABLED_FOR_PROJECT = 'duo-disabled-for-project' as const; export const UNSUPPORTED_GITLAB_VERSION = 'unsupported-gitlab-version' as const; export const UNSUPPORTED_LANGUAGE = 'code-suggestions-document-unsupported-language' as const; export const DISABLED_LANGUAGE = 'code-suggestions-document-disabled-language' as const; export type StateCheckId = | typeof NO_LICENSE | typeof DUO_DISABLED_FOR_PROJECT | typeof UNSUPPORTED_GITLAB_VERSION | typeof UNSUPPORTED_LANGUAGE | typeof DISABLED_LANGUAGE; export interface FeatureStateCheck { checkId: StateCheckId; details?: string; } export interface FeatureState { featureId: Feature; engagedChecks: FeatureStateCheck[]; } const CODE_SUGGESTIONS_CHECKS_PRIORITY_ORDERED = [ DUO_DISABLED_FOR_PROJECT, UNSUPPORTED_LANGUAGE, DISABLED_LANGUAGE, ]; const CHAT_CHECKS_PRIORITY_ORDERED = [DUO_DISABLED_FOR_PROJECT]; export const CHECKS_PER_FEATURE: { [key in Feature]: StateCheckId[] } = { [CODE_SUGGESTIONS]: CODE_SUGGESTIONS_CHECKS_PRIORITY_ORDERED, [CHAT]: CHAT_CHECKS_PRIORITY_ORDERED, // [WORKFLOW]: [], }; References:" You are a code assistant,Definition of 'duoChatPluginFactory' in file packages/webview_duo_chat/src/plugin/index.ts in project gitlab-lsp,"Definition: export const duoChatPluginFactory = ({ gitlabApiClient, }: DuoChatPluginFactoryParams): WebviewPlugin => ({ id: WEBVIEW_ID, title: WEBVIEW_TITLE, setup: ({ webview, extension }) => { const platformManager = new ChatPlatformManager(gitlabApiClient); const gitlabPlatformManagerForChat = new GitLabPlatformManagerForChat(platformManager); webview.onInstanceConnected((_, webviewMessageBus) => { const controller = new GitLabChatController( gitlabPlatformManagerForChat, webviewMessageBus, extension, ); return { dispose: () => { controller.dispose(); }, }; }); }, }); References: - src/node/main.ts:221" You are a code assistant,Definition of 'buildWebviewRequestHandler' in file src/node/webview/handlers/webview_handler.ts in project gitlab-lsp,"Definition: export const buildWebviewRequestHandler = ( webviewIds: WebviewId[], getWebviewResourcePath: (webviewId: WebviewId) => string, ): RouteHandlerMethod => { return withTrailingSlashRedirect( withKnownWebview(webviewIds, async (request: FastifyRequest, reply: FastifyReply) => { const { webviewId } = request.params as { webviewId: WebviewId }; const webviewPath = getWebviewResourcePath(webviewId); try { await reply.sendFile('index.html', webviewPath); } catch (error) { request.log.error(error, 'Error loading webview content'); await reply.status(500).send('Failed to load the webview content.'); } }), ); }; export const withKnownWebview = ( webviewIds: WebviewId[], handler: RouteHandlerMethod, ): RouteHandlerMethod => { return function (this: FastifyInstance, request: FastifyRequest, reply: FastifyReply) { const { webviewId } = request.params as { webviewId: WebviewId }; if (!webviewIds.includes(webviewId)) { return reply.status(404).send(`Unknown webview: ${webviewId}`); } return handler.call(this, request, reply); }; }; References: - src/node/webview/routes/webview_routes.ts:21 - src/node/webview/handlers/webview_handler.test.ts:11" You are a code assistant,Definition of 'getPaths' in file src/tests/int/hasbin.ts in project gitlab-lsp,"Definition: export function getPaths(bin: string) { const envPath = process.env.PATH || ''; const envExt = process.env.PATHEXT || ''; return envPath .replace(/[""]+/g, '') .split(delimiter) .map(function (chunk) { return envExt.split(delimiter).map(function (ext) { return join(chunk, bin + ext); }); }) .reduce(function (a, b) { return a.concat(b); }); } 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: - src/tests/int/hasbin.ts:8 - src/tests/int/hasbin.ts:12" You are a code assistant,Definition of 'debug' in file packages/lib_logging/src/null_logger.ts in project gitlab-lsp,"Definition: debug(message: string, e?: Error | undefined): void; debug(): void { // NOOP } info(e: Error): void; info(message: string, e?: Error | undefined): void; info(): void { // NOOP } warn(e: Error): void; warn(message: string, e?: Error | undefined): void; warn(): void { // NOOP } error(e: Error): void; error(message: string, e?: Error | undefined): void; error(): void { // NOOP } } References:" You are a code assistant,Definition of 'CreateMessageDefinitions' in file packages/lib_message_bus/src/types/utils.ts in project gitlab-lsp,"Definition: export type CreateMessageDefinitions | undefined> = { notifications: T extends { notifications: infer M } ? MergeDeep<{}, M> : {}; requests: T extends { requests: infer M } ? MergeDeep<{}, M> : {}; }; /** * Utility type to create a message map. */ export type CreateMessageMap> = MessageMap< CreateMessageDefinitions, CreateMessageDefinitions >; References:" You are a code assistant,Definition of 'IntentTestCase' in file src/tests/unit/tree_sitter/intent_resolver.test.ts in project gitlab-lsp,"Definition: type IntentTestCase = [TestType, Position, Intent]; const emptyFunctionTestCases: Array< [LanguageServerLanguageId, FileExtension, IntentTestCase[]] > = [ [ 'typescript', '.ts', // ../../fixtures/intent/empty_function/typescript.ts [ ['empty_function_declaration', { line: 0, character: 22 }, 'generation'], ['non_empty_function_declaration', { line: 3, character: 4 }, undefined], ['empty_function_expression', { line: 6, character: 32 }, 'generation'], ['non_empty_function_expression', { line: 10, character: 4 }, undefined], ['empty_arrow_function', { line: 12, character: 26 }, 'generation'], ['non_empty_arrow_function', { line: 15, character: 4 }, undefined], ['empty_class_constructor', { line: 19, character: 21 }, 'generation'], ['empty_method_definition', { line: 21, character: 11 }, 'generation'], ['non_empty_class_constructor', { line: 29, character: 7 }, undefined], ['non_empty_method_definition', { line: 33, character: 0 }, undefined], ['empty_class_declaration', { line: 36, character: 14 }, 'generation'], ['empty_generator', { line: 38, character: 31 }, 'generation'], ['non_empty_generator', { line: 41, character: 4 }, undefined], ], ], [ 'javascript', '.js', // ../../fixtures/intent/empty_function/javascript.js [ ['empty_function_declaration', { line: 0, character: 22 }, 'generation'], ['non_empty_function_declaration', { line: 3, character: 4 }, undefined], ['empty_function_expression', { line: 6, character: 32 }, 'generation'], ['non_empty_function_expression', { line: 10, character: 4 }, undefined], ['empty_arrow_function', { line: 12, character: 26 }, 'generation'], ['non_empty_arrow_function', { line: 15, character: 4 }, undefined], ['empty_class_constructor', { line: 19, character: 21 }, 'generation'], ['empty_method_definition', { line: 21, character: 11 }, 'generation'], ['non_empty_class_constructor', { line: 27, character: 7 }, undefined], ['non_empty_method_definition', { line: 31, character: 0 }, undefined], ['empty_class_declaration', { line: 34, character: 14 }, 'generation'], ['empty_generator', { line: 36, character: 31 }, 'generation'], ['non_empty_generator', { line: 39, character: 4 }, undefined], ], ], [ 'go', '.go', // ../../fixtures/intent/empty_function/go.go [ ['empty_function_declaration', { line: 0, character: 25 }, 'generation'], ['non_empty_function_declaration', { line: 3, character: 4 }, undefined], ['empty_anonymous_function', { line: 6, character: 32 }, 'generation'], ['non_empty_anonymous_function', { line: 10, character: 0 }, undefined], ['empty_method_definition', { line: 19, character: 25 }, 'generation'], ['non_empty_method_definition', { line: 23, character: 0 }, undefined], ], ], [ 'java', '.java', // ../../fixtures/intent/empty_function/java.java [ ['empty_function_declaration', { line: 0, character: 26 }, 'generation'], ['non_empty_function_declaration', { line: 3, character: 4 }, undefined], ['empty_anonymous_function', { line: 7, character: 0 }, 'generation'], ['non_empty_anonymous_function', { line: 10, character: 0 }, undefined], ['empty_class_declaration', { line: 15, character: 18 }, 'generation'], ['non_empty_class_declaration', { line: 19, character: 0 }, undefined], ['empty_class_constructor', { line: 18, character: 13 }, 'generation'], ['empty_method_definition', { line: 20, character: 18 }, 'generation'], ['non_empty_class_constructor', { line: 26, character: 18 }, undefined], ['non_empty_method_definition', { line: 30, character: 18 }, undefined], ], ], [ 'rust', '.rs', // ../../fixtures/intent/empty_function/rust.vue [ ['empty_function_declaration', { line: 0, character: 23 }, 'generation'], ['non_empty_function_declaration', { line: 3, character: 4 }, undefined], ['empty_implementation', { line: 8, character: 13 }, 'generation'], ['non_empty_implementation', { line: 11, character: 0 }, undefined], ['empty_class_constructor', { line: 13, character: 0 }, 'generation'], ['non_empty_class_constructor', { line: 23, character: 0 }, undefined], ['empty_method_definition', { line: 17, character: 0 }, 'generation'], ['non_empty_method_definition', { line: 26, character: 0 }, undefined], ['empty_closure_expression', { line: 32, character: 0 }, 'generation'], ['non_empty_closure_expression', { line: 36, character: 0 }, undefined], ['empty_macro', { line: 42, character: 11 }, 'generation'], ['non_empty_macro', { line: 45, character: 11 }, undefined], ['empty_macro', { line: 55, character: 0 }, 'generation'], ['non_empty_macro', { line: 62, character: 20 }, undefined], ], ], [ 'kotlin', '.kt', // ../../fixtures/intent/empty_function/kotlin.kt [ ['empty_function_declaration', { line: 0, character: 25 }, 'generation'], ['non_empty_function_declaration', { line: 4, character: 0 }, undefined], ['empty_anonymous_function', { line: 6, character: 32 }, 'generation'], ['non_empty_anonymous_function', { line: 9, character: 4 }, undefined], ['empty_class_declaration', { line: 12, character: 14 }, 'generation'], ['non_empty_class_declaration', { line: 15, character: 14 }, undefined], ['empty_method_definition', { line: 24, character: 0 }, 'generation'], ['non_empty_method_definition', { line: 28, character: 0 }, undefined], ], ], [ 'typescriptreact', '.tsx', // ../../fixtures/intent/empty_function/typescriptreact.tsx [ ['empty_function_declaration', { line: 0, character: 22 }, 'generation'], ['non_empty_function_declaration', { line: 3, character: 4 }, undefined], ['empty_function_expression', { line: 6, character: 32 }, 'generation'], ['non_empty_function_expression', { line: 10, character: 4 }, undefined], ['empty_arrow_function', { line: 12, character: 26 }, 'generation'], ['non_empty_arrow_function', { line: 15, character: 4 }, undefined], ['empty_class_constructor', { line: 19, character: 21 }, 'generation'], ['empty_method_definition', { line: 21, character: 11 }, 'generation'], ['non_empty_class_constructor', { line: 29, character: 7 }, undefined], ['non_empty_method_definition', { line: 33, character: 0 }, undefined], ['empty_class_declaration', { line: 36, character: 14 }, 'generation'], ['non_empty_arrow_function', { line: 40, character: 0 }, undefined], ['empty_arrow_function', { line: 41, character: 23 }, 'generation'], ['non_empty_arrow_function', { line: 44, character: 23 }, undefined], ['empty_generator', { line: 54, character: 31 }, 'generation'], ['non_empty_generator', { line: 57, character: 4 }, undefined], ], ], [ 'c', '.c', // ../../fixtures/intent/empty_function/c.c [ ['empty_function_declaration', { line: 0, character: 24 }, 'generation'], ['non_empty_function_declaration', { line: 3, character: 0 }, undefined], ], ], [ 'cpp', '.cpp', // ../../fixtures/intent/empty_function/cpp.cpp [ ['empty_function_declaration', { line: 0, character: 37 }, 'generation'], ['non_empty_function_declaration', { line: 3, character: 0 }, undefined], ['empty_function_expression', { line: 6, character: 43 }, 'generation'], ['non_empty_function_expression', { line: 10, character: 4 }, undefined], ['empty_class_constructor', { line: 15, character: 37 }, 'generation'], ['empty_method_definition', { line: 17, character: 18 }, 'generation'], ['non_empty_class_constructor', { line: 27, character: 7 }, undefined], ['non_empty_method_definition', { line: 31, character: 0 }, undefined], ['empty_class_declaration', { line: 35, character: 14 }, 'generation'], ], ], [ 'c_sharp', '.cs', // ../../fixtures/intent/empty_function/c_sharp.cs [ ['empty_function_expression', { line: 2, character: 48 }, 'generation'], ['empty_class_constructor', { line: 4, character: 31 }, 'generation'], ['empty_method_definition', { line: 6, character: 31 }, 'generation'], ['non_empty_class_constructor', { line: 15, character: 0 }, undefined], ['non_empty_method_definition', { line: 20, character: 0 }, undefined], ['empty_class_declaration', { line: 24, character: 22 }, 'generation'], ], ], [ 'bash', '.sh', // ../../fixtures/intent/empty_function/bash.sh [ ['empty_function_declaration', { line: 3, character: 48 }, 'generation'], ['non_empty_function_declaration', { line: 6, character: 31 }, undefined], ], ], [ 'scala', '.scala', // ../../fixtures/intent/empty_function/scala.scala [ ['empty_function_declaration', { line: 1, character: 4 }, 'generation'], ['non_empty_function_declaration', { line: 5, character: 4 }, undefined], ['empty_method_definition', { line: 28, character: 3 }, 'generation'], ['non_empty_method_definition', { line: 34, character: 3 }, undefined], ['empty_class_declaration', { line: 22, character: 4 }, 'generation'], ['non_empty_class_declaration', { line: 27, character: 0 }, undefined], ['empty_anonymous_function', { line: 13, character: 0 }, 'generation'], ['non_empty_anonymous_function', { line: 17, character: 0 }, undefined], ], ], [ 'ruby', '.rb', // ../../fixtures/intent/empty_function/ruby.rb [ ['empty_method_definition', { line: 0, character: 23 }, 'generation'], ['empty_method_definition', { line: 0, character: 6 }, undefined], ['non_empty_method_definition', { line: 3, character: 0 }, undefined], ['empty_anonymous_function', { line: 7, character: 27 }, 'generation'], ['non_empty_anonymous_function', { line: 9, character: 37 }, undefined], ['empty_anonymous_function', { line: 11, character: 25 }, 'generation'], ['empty_class_constructor', { line: 16, character: 22 }, 'generation'], ['non_empty_class_declaration', { line: 18, character: 0 }, undefined], ['empty_method_definition', { line: 20, character: 1 }, 'generation'], ['empty_class_declaration', { line: 33, character: 12 }, 'generation'], ], ], [ 'python', '.py', // ../../fixtures/intent/empty_function/python.py [ ['empty_function_declaration', { line: 1, character: 4 }, 'generation'], ['non_empty_function_declaration', { line: 5, character: 4 }, undefined], ['empty_class_constructor', { line: 10, character: 0 }, 'generation'], ['empty_method_definition', { line: 14, character: 0 }, 'generation'], ['non_empty_class_constructor', { line: 19, character: 0 }, undefined], ['non_empty_method_definition', { line: 23, character: 4 }, undefined], ['empty_class_declaration', { line: 27, character: 4 }, 'generation'], ['empty_function_declaration', { line: 31, character: 4 }, 'generation'], ['empty_class_constructor', { line: 36, character: 4 }, 'generation'], ['empty_method_definition', { line: 40, character: 4 }, 'generation'], ['empty_class_declaration', { line: 44, character: 4 }, 'generation'], ['empty_function_declaration', { line: 49, character: 4 }, 'generation'], ['empty_class_constructor', { line: 53, character: 4 }, 'generation'], ['empty_method_definition', { line: 56, character: 4 }, 'generation'], ['empty_class_declaration', { line: 59, character: 4 }, 'generation'], ], ], ]; describe.each(emptyFunctionTestCases)('%s', (language, fileExt, cases) => { it.each(cases)('should resolve %s intent correctly', async (_, position, expectedIntent) => { const fixturePath = getFixturePath('intent', `empty_function/${language}${fileExt}`); const { treeAndLanguage, prefix, suffix } = await getTreeAndTestFile({ fixturePath, position, languageId: language, }); const intent = await getIntent({ treeAndLanguage, position, prefix, suffix }); expect(intent.intent).toBe(expectedIntent); if (expectedIntent === 'generation') { expect(intent.generationType).toBe('empty_function'); } }); }); }); }); References:" You are a code assistant,Definition of 'constructor' in file packages/lib_webview/src/setup/plugin/webview_controller.ts in project gitlab-lsp,"Definition: constructor( webviewId: WebviewId, runtimeMessageBus: WebviewRuntimeMessageBus, messageBusFactory: WebviewMessageBusFactory, logger: Logger, ) { this.#logger = withPrefix(logger, `[WebviewController:${webviewId}]`); this.webviewId = webviewId; this.#messageBusFactory = messageBusFactory; this.#subscribeToEvents(runtimeMessageBus); } broadcast( type: TMethod, payload: T['outbound']['notifications'][TMethod], ) { for (const info of this.#instanceInfos.values()) { info.messageBus.sendNotification(type.toString(), payload); } } onInstanceConnected(handler: WebviewMessageBusManagerHandler) { this.#handlers.add(handler); for (const [instanceId, info] of this.#instanceInfos) { const disposable = handler(instanceId, info.messageBus); if (isDisposable(disposable)) { info.pluginCallbackDisposables.add(disposable); } } } dispose(): void { this.#compositeDisposable.dispose(); this.#instanceInfos.forEach((info) => info.messageBus.dispose()); this.#instanceInfos.clear(); } #subscribeToEvents(runtimeMessageBus: WebviewRuntimeMessageBus) { const eventFilter = buildWebviewIdFilter(this.webviewId); this.#compositeDisposable.add( runtimeMessageBus.subscribe('webview:connect', this.#handleConnected.bind(this), eventFilter), runtimeMessageBus.subscribe( 'webview:disconnect', this.#handleDisconnected.bind(this), eventFilter, ), ); } #handleConnected(address: WebviewAddress) { this.#logger.debug(`Instance connected: ${address.webviewInstanceId}`); if (this.#instanceInfos.has(address.webviewInstanceId)) { // we are already connected with this webview instance return; } const messageBus = this.#messageBusFactory(address); const pluginCallbackDisposables = new CompositeDisposable(); this.#instanceInfos.set(address.webviewInstanceId, { messageBus, pluginCallbackDisposables, }); this.#handlers.forEach((handler) => { const disposable = handler(address.webviewInstanceId, messageBus); if (isDisposable(disposable)) { pluginCallbackDisposables.add(disposable); } }); } #handleDisconnected(address: WebviewAddress) { this.#logger.debug(`Instance disconnected: ${address.webviewInstanceId}`); const instanceInfo = this.#instanceInfos.get(address.webviewInstanceId); if (!instanceInfo) { // we aren't tracking this instance return; } instanceInfo.pluginCallbackDisposables.dispose(); instanceInfo.messageBus.dispose(); this.#instanceInfos.delete(address.webviewInstanceId); } } References:" You are a code assistant,Definition of 'createStringOfByteLength' in file src/common/advanced_context/lru_cache.test.ts in project gitlab-lsp,"Definition: function createStringOfByteLength(char: string, byteLength: number): string { let result = ''; while (getByteSize(result) < byteLength) { result += char; } return result.slice(0, -1); // Remove last char as it might have pushed over the limit } const SMALL_SIZE = 200; const LARGE_SIZE = 400; const EXTRA_SMALL_SIZE = 50; const smallString = createStringOfByteLength('A', SMALL_SIZE); const largeString = createStringOfByteLength('C', LARGE_SIZE); const extraSmallString = createStringOfByteLength('D', EXTRA_SMALL_SIZE); export function createFakeContext(overrides: Partial = {}): IDocContext { return { prefix: '', suffix: '', fileRelativePath: 'file:///test.ts', position: { line: 0, character: 0 }, uri: 'file:///test.ts', languageId: 'typescript', workspaceFolder: { uri: 'file:///workspace', name: 'test-workspace', }, ...overrides, }; } describe('LruCache', () => { let lruCache: LruCache; beforeEach(() => { lruCache = LruCache.getInstance(TEST_BYTE_LIMIT); }); afterEach(() => { LruCache.destroyInstance(); }); describe('getInstance', () => { it('should return a singleton instance of LruCache', () => { const cache1 = LruCache.getInstance(TEST_BYTE_LIMIT); const cache2 = LruCache.getInstance(TEST_BYTE_LIMIT); expect(cache1).toBe(cache2); expect(cache1).toBeInstanceOf(LruCache); }); }); describe('updateFile', () => { it('should add a new file to the cache', () => { const context = createFakeContext(); lruCache.updateFile(context); expect(lruCache.openFiles.size).toBe(1); expect(lruCache.openFiles.get(context.uri)).toEqual(context); }); it('should update an existing file in the cache', () => { const context1 = createFakeContext(); const context2 = { ...context1, text: 'Updated text' }; lruCache.updateFile(context1); lruCache.updateFile(context2); expect(lruCache.openFiles.size).toBe(1); expect(lruCache.openFiles.get(context1.uri)).toEqual(context2); }); }); describe('deleteFile', () => { it('should remove a file from the cache', () => { const context = createFakeContext(); lruCache.updateFile(context); const isDeleted = lruCache.deleteFile(context.uri); expect(lruCache.openFiles.size).toBe(0); expect(isDeleted).toBe(true); }); it(`should not remove a file that doesn't exist`, () => { const context = createFakeContext(); lruCache.updateFile(context); const isDeleted = lruCache.deleteFile('fake/uri/that/does/not.exist'); expect(lruCache.openFiles.size).toBe(1); expect(isDeleted).toBe(false); }); it('should return correct order of files after deletion', () => { const workspaceFolder = { uri: 'file:///workspace', name: 'test-workspace' }; const context1 = createFakeContext({ uri: 'file:///workspace/file1.ts', workspaceFolder }); const context2 = createFakeContext({ uri: 'file:///workspace/file2.ts', workspaceFolder }); const context3 = createFakeContext({ uri: 'file:///workspace/file3.ts', workspaceFolder }); lruCache.updateFile(context1); lruCache.updateFile(context2); lruCache.updateFile(context3); lruCache.deleteFile(context2.uri); expect(lruCache.mostRecentFiles({ context: context1 })).toEqual([context3, context1]); }); }); describe('mostRecentFiles', () => { it('should return ordered files', () => { const workspaceFolder = { uri: 'file:///workspace', name: 'test-workspace' }; const context1 = createFakeContext({ uri: 'file:///workspace/file1.ts', workspaceFolder }); const context2 = createFakeContext({ uri: 'file:///workspace/file2.ts', workspaceFolder }); const context3 = createFakeContext({ uri: 'file:///workspace/file3.ts', workspaceFolder }); lruCache.updateFile(context1); lruCache.updateFile(context2); lruCache.updateFile(context3); lruCache.updateFile(context2); const result = lruCache.mostRecentFiles({ context: context2 }); expect(result).toEqual([context2, context3, context1]); }); it('should return the most recently accessed files in the same workspace', () => { const workspaceFolder = { uri: 'file:///workspace', name: 'test-workspace' }; const otherWorkspaceFolder = { uri: 'file:///other', name: 'other-workspace' }; const context1 = createFakeContext({ uri: 'file:///workspace/file1.ts', workspaceFolder }); const context2 = createFakeContext({ uri: 'file:///workspace/file2.ts', workspaceFolder }); const context3 = createFakeContext({ uri: 'file:///workspace/file3.ts', workspaceFolder }); const context4 = createFakeContext({ uri: 'file:///other/file4.ts', workspaceFolder: otherWorkspaceFolder, }); lruCache.updateFile(context1); lruCache.updateFile(context2); lruCache.updateFile(context3); lruCache.updateFile(context4); const result = lruCache.mostRecentFiles({ context: context2 }); expect(result.find((file) => file.uri === context4.uri)).toBeUndefined(); }); it('should include the current file if includeCurrentFile is true', () => { const workspaceFolder = { uri: 'file:///workspace', name: 'test-workspace' }; const context1 = createFakeContext({ uri: 'file:///workspace/file1.ts', workspaceFolder }); const context2 = createFakeContext({ uri: 'file:///workspace/file2.ts', workspaceFolder }); lruCache.updateFile(context1); lruCache.updateFile(context2); const result = lruCache.mostRecentFiles({ context: context2, includeCurrentFile: true }); expect(result).toEqual([context2, context1]); }); it('should not include the current file if includeCurrentFile is false', () => { const workspaceFolder = { uri: 'file:///workspace', name: 'test-workspace' }; const context1 = createFakeContext({ uri: 'file:///workspace/file1.ts', workspaceFolder }); const context2 = createFakeContext({ uri: 'file:///workspace/file2.ts', workspaceFolder }); lruCache.updateFile(context1); lruCache.updateFile(context2); const result = lruCache.mostRecentFiles({ context: context2, includeCurrentFile: false }); expect(result).toEqual([context1]); }); it('should return an empty array if no files match the criteria', () => { const context = createFakeContext(); const result = lruCache.mostRecentFiles({ context }); expect(result).toEqual([]); }); }); describe('updateFile with size limit', () => { it('should evict least recently used items when limit is reached', () => { const context1 = createFakeContext({ uri: 'file:///workspace/file1.ts', prefix: smallString, // 200 bytes suffix: smallString, // 200 bytes }); const context2 = createFakeContext({ uri: 'file:///workspace/file2.ts', prefix: smallString, // 200 bytes suffix: smallString, // 200 bytes }); const context3 = createFakeContext({ uri: 'file:///workspace/file3.ts', prefix: largeString, // 400 bytes suffix: '', }); const context4 = createFakeContext({ uri: 'file:///workspace/file4.ts', prefix: extraSmallString, // 50 bytes suffix: extraSmallString, // 50 bytes }); expect(lruCache.updateFile(context1)).toBeTruthy(); expect(lruCache.updateFile(context2)).toBeTruthy(); expect(lruCache.updateFile(context3)).toBeTruthy(); expect(lruCache.updateFile(context4)).toBeTruthy(); // The least recently used item (context1) should have been evicted expect(lruCache.openFiles.size).toBe(3); expect(lruCache.openFiles.has(context1.uri)).toBe(false); expect(lruCache.openFiles.has(context2.uri)).toBe(true); expect(lruCache.openFiles.has(context3.uri)).toBe(true); expect(lruCache.openFiles.has(context4.uri)).toBe(true); }); }); }); References: - src/common/advanced_context/lru_cache.test.ts:20 - src/common/advanced_context/lru_cache.test.ts:19 - src/common/advanced_context/lru_cache.test.ts:21" You are a code assistant,Definition of 'greet' in file src/tests/fixtures/intent/empty_function/javascript.js in project gitlab-lsp,"Definition: greet() { console.log(`Hello ${this.name}`); } } class Greet3 {} function* generateGreetings() {} function* greetGenerator() { yield 'Hello'; } References: - 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 - src/tests/fixtures/intent/empty_function/ruby.rb:29" You are a code assistant,Definition of 'getMessageBus' in file packages/lib_webview_client/src/bus/provider/types.ts in project gitlab-lsp,"Definition: getMessageBus(webviewId: string): MessageBus | null; } References:" You are a code assistant,Definition of 'findFilesForDirectory' in file src/common/services/fs/dir.ts in project gitlab-lsp,"Definition: findFilesForDirectory(_args: DirectoryToSearch): Promise { return Promise.resolve([]); } // eslint-disable-next-line @typescript-eslint/no-unused-vars setupFileWatcher(workspaceFolder: WorkspaceFolder, changeHandler: FileChangeHandler) { throw new Error(`${workspaceFolder} ${changeHandler} not implemented`); } } References:" You are a code assistant,Definition of 'TELEMETRY_ENABLED_MSG' in file src/common/tracking/constants.ts in project gitlab-lsp,"Definition: export const TELEMETRY_ENABLED_MSG = 'GitLab Duo Code Suggestions telemetry is enabled.'; References:" You are a code assistant,Definition of 'onNotification' in file packages/lib_message_bus/src/types/bus.ts in project gitlab-lsp,"Definition: onNotification( type: T, handler: (payload: TNotifications[T]) => void, ): Disposable; } /** * Maps request message types to their corresponding request/response payloads. * @typedef {Record} RequestMap */ export type RequestMap = Record< Method, { params: MessagePayload; result: MessagePayload; } >; type KeysWithOptionalParams = { [K in keyof R]: R[K]['params'] extends undefined ? never : K; }[keyof R]; /** * Extracts the response payload type from a request type. * @template {MessagePayload} T * @typedef {T extends [never] ? void : T[0]} ExtractRequestResponse */ export type ExtractRequestResult = // eslint-disable-next-line @typescript-eslint/no-invalid-void-type T['result'] extends undefined ? void : T; /** * Interface for publishing requests. * @interface * @template {RequestMap} TRequests */ export interface RequestPublisher { sendRequest>( type: T, ): Promise>; sendRequest( type: T, payload: TRequests[T]['params'], ): Promise>; } /** * Interface for listening to requests. * @interface * @template {RequestMap} TRequests */ export interface RequestListener { onRequest>( type: T, handler: () => Promise>, ): Disposable; onRequest( type: T, handler: (payload: TRequests[T]['params']) => Promise>, ): Disposable; } /** * Defines the structure for message definitions, including notifications and requests. */ export type MessageDefinitions< TNotifications extends NotificationMap = NotificationMap, TRequests extends RequestMap = RequestMap, > = { notifications: TNotifications; requests: TRequests; }; export type MessageMap< TInboundMessageDefinitions extends MessageDefinitions = MessageDefinitions, TOutboundMessageDefinitions extends MessageDefinitions = MessageDefinitions, > = { inbound: TInboundMessageDefinitions; outbound: TOutboundMessageDefinitions; }; export interface MessageBus extends NotificationPublisher, NotificationListener, RequestPublisher, RequestListener {} References:" You are a code assistant,Definition of 'createMockLogger' in file packages/lib_webview/src/test_utils/mocks.ts in project gitlab-lsp,"Definition: export const createMockLogger = (): jest.Mocked => ({ debug: jest.fn(), info: jest.fn(), warn: jest.fn(), error: jest.fn(), }); export const createMockTransport = (): jest.Mocked => ({ publish: jest.fn(), on: jest.fn(), }); References: - packages/lib_webview/src/setup/plugin/webview_controller.test.ts:27 - packages/lib_webview/src/setup/plugin/webview_instance_message_bus.test.ts:338 - packages/lib_webview/src/setup/plugin/webview_instance_message_bus.test.ts:21" You are a code assistant,Definition of 'constructor' in file src/node/duo_workflow/desktop_workflow_runner.ts in project gitlab-lsp,"Definition: constructor(configService: ConfigService, fetch: LsFetch, api: GitLabApiClient) { this.#fetch = fetch; this.#api = api; configService.onConfigChange((config) => this.#reconfigure(config)); } #reconfigure(config: IConfig) { this.#dockerSocket = config.client.duoWorkflowSettings?.dockerSocket; this.#folders = config.client.workspaceFolders || []; this.#projectPath = config.client.projectPath; } async runWorkflow(goal: string, image: string): Promise { if (!this.#dockerSocket) { throw new Error('Docker socket not configured'); } if (!this.#folders || this.#folders.length === 0) { throw new Error('No workspace folders'); } const executorPath = path.join( __dirname, `../vendor/duo_workflow_executor-${WORKFLOW_EXECUTOR_VERSION}.tar.gz`, ); await this.#downloadWorkflowExecutor(executorPath); const folderName = this.#folders[0].uri.replace(/^file:\/\//, ''); if (this.#folders.length > 0) { log.info(`More than one workspace folder detected. Using workspace folder ${folderName}`); } const workflowID = await this.#createWorkflow(); const workflowToken = await this.#getWorkflowToken(); const containerOptions = { Image: image, Cmd: [ '/duo-workflow-executor', `--workflow-id=${workflowID}`, '--server', workflowToken.duo_workflow_service.base_url || 'localhost:50052', '--goal', goal, '--base-url', workflowToken.gitlab_rails.base_url, '--token', workflowToken.gitlab_rails.token, '--duo-workflow-service-token', workflowToken.duo_workflow_service.token, '--realm', workflowToken.duo_workflow_service.headers['X-Gitlab-Realm'], '--user-id', workflowToken.duo_workflow_service.headers['X-Gitlab-Global-User-Id'], ], HostConfig: { Binds: [`${folderName}:/workspace`], }, }; // Create a container const createResponse = JSON.parse( await this.#makeRequest('/v1.43/containers/create', 'POST', JSON.stringify(containerOptions)), ); // Check if Id in createResponse if (!createResponse.Id) { throw new Error('Failed to create container: No Id in response'); } const containerID = createResponse.Id; // Copy the executor into the container await this.#copyExecutor(containerID, executorPath); // Start the container await this.#makeRequest(`/v1.43/containers/${containerID}/start`, 'POST', ''); return workflowID; } async #copyExecutor(containerID: string, executorPath: string) { const fileContents = await readFile(executorPath); await this.#makeRequest( `/v1.43/containers/${containerID}/archive?path=/`, 'PUT', fileContents, 'application/x-tar', ); } #makeRequest( apiPath: string, method: string, data: string | Buffer, contentType = 'application/json', ): Promise { return new Promise((resolve, reject) => { if (!this.#dockerSocket) { throw new Error('Docker socket not set'); } const options: http.RequestOptions = { socketPath: this.#dockerSocket, path: apiPath, method, headers: { 'Content-Type': contentType, 'Content-Length': Buffer.byteLength(data), }, }; const callback = (res: http.IncomingMessage) => { res.setEncoding('utf-8'); res.on('data', (content) => resolve(content)); res.on('error', (err) => reject(err)); res.on('end', () => { resolve(''); }); }; const clientRequest = http.request(options, callback); clientRequest.write(data); clientRequest.end(); }); } async #downloadWorkflowExecutor(executorPath: string): Promise { try { await readFile(executorPath); } catch (error) { log.info('Downloading workflow executor...'); await this.#downloadFile(executorPath); } } async #downloadFile(outputPath: string): Promise { const response = await this.#fetch.fetch(WORKFLOW_EXECUTOR_DOWNLOAD_PATH, { method: 'GET', headers: { 'Content-Type': 'application/octet-stream', }, }); if (!response.ok) { throw new Error(`Failed to download file: ${response.statusText}`); } const buffer = await response.arrayBuffer(); await writeFile(outputPath, Buffer.from(buffer)); } async #createWorkflow(): Promise { const response = await this.#api?.fetchFromApi({ type: 'rest', method: 'POST', path: '/ai/duo_workflows/workflows', body: { project_id: this.#projectPath, }, supportedSinceInstanceVersion: { resourceName: 'create a workflow', version: '17.3.0', }, }); if (!response) { throw new Error('Failed to create workflow'); } return response.id; } async #getWorkflowToken(): Promise { const token = await this.#api?.fetchFromApi({ type: 'rest', method: 'POST', path: '/ai/duo_workflows/direct_access', supportedSinceInstanceVersion: { resourceName: 'get workflow direct access', version: '17.3.0', }, }); if (!token) { throw new Error('Failed to get workflow token'); } return token; } } References:" You are a code assistant,Definition of 'transform' in file src/common/document_transformer_service.ts in project gitlab-lsp,"Definition: 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 'goIntoCompletionMode' in file src/common/suggestion/suggestion_service.test.ts in project gitlab-lsp,"Definition: function goIntoCompletionMode() { mockParseFile.mockReset(); jest.mocked(featureFlagService.isClientFlagEnabled).mockReturnValueOnce(false); mockParseFile.mockResolvedValue('completion'); } it('starts breaking after 4 errors', async () => { jest.mocked(DefaultStreamingHandler).mockClear(); jest.mocked(DefaultStreamingHandler).mockReturnValue( createFakePartial({ startStream: jest.fn().mockResolvedValue([]), }), ); goIntoStreamingMode(); const successResult = await getCompletions(); expect(successResult.items.length).toEqual(1); jest.runOnlyPendingTimers(); expect(DefaultStreamingHandler).toHaveBeenCalled(); jest.mocked(DefaultStreamingHandler).mockClear(); goIntoCompletionMode(); mockGetCodeSuggestions.mockRejectedValue('test problem'); await turnOnCircuitBreaker(); goIntoStreamingMode(); const result = await getCompletions(); expect(result?.items).toEqual([]); expect(DefaultStreamingHandler).not.toHaveBeenCalled(); }); it(`starts the stream after circuit breaker's break time elapses`, async () => { jest.useFakeTimers().setSystemTime(new Date(Date.now())); goIntoCompletionMode(); mockGetCodeSuggestions.mockRejectedValue(new Error('test problem')); await turnOnCircuitBreaker(); jest.advanceTimersByTime(CIRCUIT_BREAK_INTERVAL_MS + 1); goIntoStreamingMode(); const result = await getCompletions(); expect(result?.items).toHaveLength(1); jest.runOnlyPendingTimers(); expect(DefaultStreamingHandler).toHaveBeenCalled(); }); }); }); describe('selection completion info', () => { beforeEach(() => { mockGetCodeSuggestions.mockReset(); mockGetCodeSuggestions.mockResolvedValue({ choices: [{ text: 'log(""Hello world"")' }], model: { lang: 'js', }, }); }); describe('when undefined', () => { it('does not update choices', async () => { const { items } = await requestInlineCompletionNoDebounce( { ...inlineCompletionParams, context: createFakePartial({ selectedCompletionInfo: undefined, }), }, token, ); expect(items[0].insertText).toBe('log(""Hello world"")'); }); }); describe('with range and text', () => { it('prepends text to suggestion choices', async () => { const { items } = await requestInlineCompletionNoDebounce( { ...inlineCompletionParams, context: createFakePartial({ selectedCompletionInfo: { text: 'console.', range: { start: { line: 1, character: 0 }, end: { line: 1, character: 2 } }, }, }), }, token, ); expect(items[0].insertText).toBe('nsole.log(""Hello world"")'); }); }); describe('with range (Array) and text', () => { it('prepends text to suggestion choices', async () => { const { items } = await requestInlineCompletionNoDebounce( { ...inlineCompletionParams, context: createFakePartial({ selectedCompletionInfo: { text: 'console.', // NOTE: This forcefully simulates the behavior we see where range is an Array at runtime. range: [ { line: 1, character: 0 }, { line: 1, character: 2 }, ] as unknown as Range, }, }), }, token, ); expect(items[0].insertText).toBe('nsole.log(""Hello world"")'); }); }); }); describe('Additional Context', () => { beforeEach(async () => { jest.mocked(shouldUseAdvancedContext).mockReturnValueOnce(true); getAdvancedContextSpy.mockResolvedValue(sampleAdvancedContext); contextBodySpy.mockReturnValue(sampleAdditionalContexts); await requestInlineCompletionNoDebounce(inlineCompletionParams, token); }); it('getCodeSuggestions should have additional context passed if feature is enabled', async () => { expect(getAdvancedContextSpy).toHaveBeenCalled(); expect(contextBodySpy).toHaveBeenCalledWith(sampleAdvancedContext); expect(api.getCodeSuggestions).toHaveBeenCalledWith( expect.objectContaining({ context: sampleAdditionalContexts }), ); }); it('should be tracked with telemetry', () => { expect(tracker.setCodeSuggestionsContext).toHaveBeenCalledWith( TRACKING_ID, expect.objectContaining({ additionalContexts: sampleAdditionalContexts }), ); }); }); }); }); }); References: - src/common/suggestion/suggestion_service.test.ts:1008 - src/common/suggestion/suggestion_service.test.ts:993" You are a code assistant,Definition of 'buildWebviewAddressFilter' in file packages/lib_webview/src/setup/plugin/utils/filters.ts in project gitlab-lsp,"Definition: export const buildWebviewAddressFilter = (address: WebviewAddress) => (event: T): boolean => { return ( event.webviewId === address.webviewId && event.webviewInstanceId === address.webviewInstanceId ); }; References: - packages/lib_webview/src/setup/plugin/webview_instance_message_bus.ts:46" You are a code assistant,Definition of 'EmptyFileResolver' in file src/common/services/fs/file.ts in project gitlab-lsp,"Definition: export class EmptyFileResolver { // eslint-disable-next-line @typescript-eslint/no-unused-vars readFile(_args: ReadFile): Promise { return Promise.resolve(''); } } References:" You are a code assistant,Definition of 'processStream' in file src/common/suggestion_client/post_processors/post_processor_pipeline.ts in project gitlab-lsp,"Definition: processStream( _context: IDocContext, input: StreamingCompletionResponse, ): Promise { return Promise.resolve(input); } processCompletion(_context: IDocContext, input: SuggestionOption[]): Promise { return Promise.resolve(input); } } /** * Pipeline for running post-processors on completion and streaming (generation) responses. * Post-processors are used to modify completion responses before they are sent to the client. * They can be used to filter, sort, or modify completion suggestions. */ export class PostProcessorPipeline { #processors: PostProcessor[] = []; addProcessor(processor: PostProcessor): void { this.#processors.push(processor); } async run({ documentContext, input, type, }: { documentContext: IDocContext; input: ProcessorInputMap[T]; type: T; }): Promise { if (!this.#processors.length) return input as ProcessorInputMap[T]; return this.#processors.reduce( async (prevPromise, processor) => { const result = await prevPromise; // eslint-disable-next-line default-case switch (type) { case 'stream': return processor.processStream( documentContext, result as StreamingCompletionResponse, ) as Promise; case 'completion': return processor.processCompletion( documentContext, result as SuggestionOption[], ) as Promise; } throw new Error('Unexpected type in pipeline processing'); }, Promise.resolve(input) as Promise, ); } } References:" You are a code assistant,Definition of 'initialize' in file src/common/services/fs/virtual_file_service.ts in project gitlab-lsp,"Definition: async initialize(workspaceFolders: WorkspaceFolder[]): Promise { 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( 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/tests/fixtures/intent/empty_function/ruby.rb:17 - src/tests/fixtures/intent/empty_function/ruby.rb:25" You are a code assistant,Definition of 'connectToCable' in file packages/webview_duo_chat/src/plugin/types.ts in project gitlab-lsp,"Definition: connectToCable(): Promise; } References: - src/common/action_cable.test.ts:32 - src/common/action_cable.test.ts:21 - src/common/action_cable.test.ts:40 - src/common/api.ts:348 - src/common/action_cable.test.ts:54" You are a code assistant,Definition of 'AI_MESSAGES_QUERY' in file packages/webview_duo_chat/src/plugin/port/chat/gitlab_chat_api.ts in project gitlab-lsp,"Definition: export const AI_MESSAGES_QUERY = gql` query getAiMessages($requestIds: [ID!], $roles: [AiMessageRole!]) { aiMessages(requestIds: $requestIds, roles: $roles) { nodes { requestId role content contentHtml timestamp errors extras { sources } } } } `; type AiMessageResponseType = { requestId: string; role: string; content: string; contentHtml: string; timestamp: string; errors: string[]; extras?: { sources: object[]; }; }; type AiMessagesResponseType = { aiMessages: { nodes: AiMessageResponseType[]; }; }; interface ErrorMessage { type: 'error'; requestId: string; role: 'system'; errors: string[]; } const errorResponse = (requestId: string, errors: string[]): ErrorMessage => ({ requestId, errors, role: 'system', type: 'error', }); interface SuccessMessage { type: 'message'; requestId: string; role: string; content: string; contentHtml: string; timestamp: string; errors: string[]; extras?: { sources: object[]; }; } const successResponse = (response: AiMessageResponseType): SuccessMessage => ({ type: 'message', ...response, }); type AiMessage = SuccessMessage | ErrorMessage; type ChatInputTemplate = { query: string; defaultVariables: { platformOrigin?: string; }; }; export class GitLabChatApi { #cachedActionQuery?: ChatInputTemplate = undefined; #manager: GitLabPlatformManagerForChat; constructor(manager: GitLabPlatformManagerForChat) { this.#manager = manager; } async processNewUserPrompt( question: string, subscriptionId?: string, currentFileContext?: GitLabChatFileContext, ): Promise { return this.#sendAiAction({ question, currentFileContext, clientSubscriptionId: subscriptionId, }); } async pullAiMessage(requestId: string, role: string): Promise { const response = await pullHandler(() => this.#getAiMessage(requestId, role)); if (!response) return errorResponse(requestId, ['Reached timeout while fetching response.']); return successResponse(response); } async cleanChat(): Promise { return this.#sendAiAction({ question: SPECIAL_MESSAGES.CLEAN }); } async #currentPlatform() { const platform = await this.#manager.getGitLabPlatform(); if (!platform) throw new Error('Platform is missing!'); return platform; } async #getAiMessage(requestId: string, role: string): Promise { const request: GraphQLRequest = { type: 'graphql', query: AI_MESSAGES_QUERY, variables: { requestIds: [requestId], roles: [role.toUpperCase()] }, }; const platform = await this.#currentPlatform(); const history = await platform.fetchFromApi(request); return history.aiMessages.nodes[0]; } async subscribeToUpdates( messageCallback: (message: AiCompletionResponseMessageType) => Promise, subscriptionId?: string, ) { const platform = await this.#currentPlatform(); const channel = new AiCompletionResponseChannel({ htmlResponse: true, userId: `gid://gitlab/User/${extractUserId(platform.account.id)}`, aiAction: 'CHAT', clientSubscriptionId: subscriptionId, }); const cable = await platform.connectToCable(); // we use this flag to fix https://gitlab.com/gitlab-org/gitlab-vscode-extension/-/issues/1397 // sometimes a chunk comes after the full message and it broke the chat let fullMessageReceived = false; channel.on('newChunk', async (msg) => { if (fullMessageReceived) { log.info(`CHAT-DEBUG: full message received, ignoring chunk`); return; } await messageCallback(msg); }); channel.on('fullMessage', async (message) => { fullMessageReceived = true; await messageCallback(message); if (subscriptionId) { cable.disconnect(); } }); cable.subscribe(channel); } async #sendAiAction(variables: object): Promise { const platform = await this.#currentPlatform(); const { query, defaultVariables } = await this.#actionQuery(); const projectGqlId = await this.#manager.getProjectGqlId(); const request: GraphQLRequest = { type: 'graphql', query, variables: { ...variables, ...defaultVariables, resourceId: projectGqlId ?? null, }, }; return platform.fetchFromApi(request); } async #actionQuery(): Promise { if (!this.#cachedActionQuery) { const platform = await this.#currentPlatform(); try { const { version } = await platform.fetchFromApi(versionRequest); this.#cachedActionQuery = ifVersionGte( version, MINIMUM_PLATFORM_ORIGIN_FIELD_VERSION, () => CHAT_INPUT_TEMPLATE_17_3_AND_LATER, () => CHAT_INPUT_TEMPLATE_17_2_AND_EARLIER, ); } catch (e) { log.debug(`GitLab version check for sending chat failed:`, e as Error); this.#cachedActionQuery = CHAT_INPUT_TEMPLATE_17_3_AND_LATER; } } return this.#cachedActionQuery; } } References:" You are a code assistant,Definition of 'connectToCable' in file src/common/api.ts in project gitlab-lsp,"Definition: async connectToCable(): Promise { const headers = this.#getDefaultHeaders(this.#token); const websocketOptions = { headers: { ...headers, Origin: this.#baseURL, }, }; return connectToCable(this.#baseURL, websocketOptions); } async #graphqlRequest( document: RequestDocument, variables?: V, ): Promise { const ensureEndsWithSlash = (url: string) => url.replace(/\/?$/, '/'); const endpoint = new URL('./api/graphql', ensureEndsWithSlash(this.#baseURL)).href; // supports GitLab instances that are on a custom path, e.g. ""https://example.com/gitlab"" const graphqlFetch = async ( input: RequestInfo | URL, init?: RequestInit, ): Promise => { const url = input instanceof URL ? input.toString() : input; return this.#lsFetch.post(url, { ...init, headers: { ...headers, ...init?.headers }, }); }; const headers = this.#getDefaultHeaders(this.#token); const client = new GraphQLClient(endpoint, { headers, fetch: graphqlFetch, }); return client.request(document, variables); } async #fetch( apiResourcePath: string, query: Record = {}, resourceName = 'resource', headers?: Record, ): Promise { const url = `${this.#baseURL}/api/v4${apiResourcePath}${createQueryString(query)}`; const result = await this.#lsFetch.get(url, { headers: { ...this.#getDefaultHeaders(this.#token), ...headers }, }); await handleFetchError(result, resourceName); return result.json() as Promise; } async #postFetch( apiResourcePath: string, resourceName = 'resource', body?: unknown, headers?: Record, ): Promise { const url = `${this.#baseURL}/api/v4${apiResourcePath}`; const response = await this.#lsFetch.post(url, { headers: { 'Content-Type': 'application/json', ...this.#getDefaultHeaders(this.#token), ...headers, }, body: JSON.stringify(body), }); await handleFetchError(response, resourceName); return response.json() as Promise; } #getDefaultHeaders(token?: string) { return { Authorization: `Bearer ${token}`, 'User-Agent': `code-completions-language-server-experiment (${this.#clientInfo?.name}:${this.#clientInfo?.version})`, 'X-Gitlab-Language-Server-Version': getLanguageServerVersion(), }; } #instanceVersionHigherOrEqualThen(version: string): boolean { if (!this.#instanceVersion) return false; return semverCompare(this.#instanceVersion, version) >= 0; } async #getGitLabInstanceVersion(): Promise { if (!this.#token) { return ''; } const headers = this.#getDefaultHeaders(this.#token); const response = await this.#lsFetch.get(`${this.#baseURL}/api/v4/version`, { headers, }); const { version } = await response.json(); return version; } get instanceVersion() { return this.#instanceVersion; } } References: - src/common/action_cable.test.ts:21 - src/common/action_cable.test.ts:40 - src/common/api.ts:348 - src/common/action_cable.test.ts:54 - src/common/action_cable.test.ts:32" You are a code assistant,Definition of 'FastFibonacciSolver' in file packages/lib-pkg-2/src/fast_fibonacci_solver.ts in project gitlab-lsp,"Definition: export class FastFibonacciSolver implements FibonacciSolver { #memo: Map = new Map(); #lastComputedIndex: number = 1; constructor() { this.#memo.set(0, 0); this.#memo.set(1, 1); } 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: - packages/lib-pkg-2/src/fast_fibonacci_solver.test.ts:4 - packages/webview-chat/src/app/index.ts:11 - packages/lib-pkg-2/src/fast_fibonacci_solver.test.ts:7" You are a code assistant,Definition of 'RepositoryUri' in file src/common/git/repository.ts in project gitlab-lsp,"Definition: type RepositoryUri = URI; export type RepositoryFile = { uri: RepoFileUri; repositoryUri: RepositoryUri; isIgnored: boolean; workspaceFolder: WorkspaceFolder; }; export class Repository { workspaceFolder: WorkspaceFolder; uri: URI; configFileUri: URI; #files: Map; #ignoreManager: IgnoreManager; constructor({ configFileUri, workspaceFolder, uri, ignoreManager, }: { workspaceFolder: WorkspaceFolder; uri: RepositoryUri; configFileUri: URI; ignoreManager: IgnoreManager; }) { this.workspaceFolder = workspaceFolder; this.uri = uri; this.configFileUri = configFileUri; this.#files = new Map(); this.#ignoreManager = ignoreManager; } async addFilesAndLoadGitIgnore(files: URI[]): Promise { log.info(`Adding ${files.length} files to repository ${this.uri.toString()}`); await this.#ignoreManager.loadIgnoreFiles(files.map((uri) => uri.fsPath)); for (const file of files) { if (!this.#ignoreManager.isIgnored(file.fsPath)) { this.#files.set(file.toString(), { uri: file, isIgnored: false, repositoryUri: this.uri, workspaceFolder: this.workspaceFolder, }); } else { this.#files.set(file.toString(), { uri: file, isIgnored: true, repositoryUri: this.uri, workspaceFolder: this.workspaceFolder, }); } } } isFileIgnored(filePath: URI): boolean { return this.#ignoreManager.isIgnored(filePath.fsPath); } setFile(fileUri: URI): void { if (!this.isFileIgnored(fileUri)) { this.#files.set(fileUri.toString(), { uri: fileUri, isIgnored: false, repositoryUri: this.uri, workspaceFolder: this.workspaceFolder, }); } else { this.#files.set(fileUri.toString(), { uri: fileUri, isIgnored: true, repositoryUri: this.uri, workspaceFolder: this.workspaceFolder, }); } } getFile(fileUri: string): RepositoryFile | undefined { return this.#files.get(fileUri); } removeFile(fileUri: string): void { this.#files.delete(fileUri); } getFiles(): Map { return this.#files; } dispose(): void { this.#ignoreManager.dispose(); this.#files.clear(); } } References: - src/common/git/repository.ts:11 - src/common/git/repository.ts:34" You are a code assistant,Definition of 'Entries' in file src/common/utils/get_entries.ts in project gitlab-lsp,"Definition: type Entries = { [K in keyof T]: [K, T[K]] }[keyof T][]; export const getEntries = (obj: T): Entries => Object.entries(obj) as Entries; References:" You are a code assistant,Definition of 'isSocketRequestMessage' in file packages/lib_webview_transport_socket_io/src/utils/message_utils.ts in project gitlab-lsp,"Definition: 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: - packages/lib_webview_transport_socket_io/src/socket_io_webview_transport.ts:83" You are a code assistant,Definition of 'TextDocumentChangeListener' in file src/common/document_service.ts in project gitlab-lsp,"Definition: export interface TextDocumentChangeListener { (event: TextDocumentChangeEvent, handlerType: TextDocumentChangeListenerType): void; } export interface DocumentService { onDocumentChange(listener: TextDocumentChangeListener): Disposable; notificationHandler(params: DidChangeDocumentInActiveEditorParams): void; } export const DocumentService = createInterfaceId('DocumentsWrapper'); const DOCUMENT_CHANGE_EVENT_NAME = 'documentChange'; export class DefaultDocumentService implements DocumentService, HandlesNotification { #subscriptions: Disposable[] = []; #emitter = new EventEmitter(); #documents: TextDocuments; constructor(documents: TextDocuments) { 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 = { document }; this.#emitter.emit( DOCUMENT_CHANGE_EVENT_NAME, event, TextDocumentChangeListenerType.onDidSetActive, ); }; #createMediatorListener = (type: TextDocumentChangeListenerType) => (event: TextDocumentChangeEvent) => { 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.test.ts:18 - src/common/feature_state/supported_language_check.test.ts:25 - src/common/advanced_context/advanced_context_service.test.ts:23 - src/common/document_service.ts:19 - src/common/document_service.ts:73" You are a code assistant,Definition of 'FeatureStateCheck' in file src/common/feature_state/feature_state_management_types.ts in project gitlab-lsp,"Definition: export interface FeatureStateCheck { checkId: StateCheckId; details?: string; } export interface FeatureState { featureId: Feature; engagedChecks: FeatureStateCheck[]; } const CODE_SUGGESTIONS_CHECKS_PRIORITY_ORDERED = [ DUO_DISABLED_FOR_PROJECT, UNSUPPORTED_LANGUAGE, DISABLED_LANGUAGE, ]; const CHAT_CHECKS_PRIORITY_ORDERED = [DUO_DISABLED_FOR_PROJECT]; export const CHECKS_PER_FEATURE: { [key in Feature]: StateCheckId[] } = { [CODE_SUGGESTIONS]: CODE_SUGGESTIONS_CHECKS_PRIORITY_ORDERED, [CHAT]: CHAT_CHECKS_PRIORITY_ORDERED, // [WORKFLOW]: [], }; References:" You are a code assistant,Definition of 'MessagesToServer' in file packages/lib_webview_transport/src/types.ts in project gitlab-lsp,"Definition: export type MessagesToServer = { webview_instance_created: WebviewInstanceCreatedEventData; webview_instance_destroyed: WebviewInstanceDestroyedEventData; webview_instance_notification_received: WebviewInstanceNotificationEventData; webview_instance_request_received: WebviewInstanceRequestEventData; webview_instance_response_received: WebviewInstanceResponseEventData; }; export type MessagesToClient = { webview_instance_notification: WebviewInstanceNotificationEventData; webview_instance_request: WebviewInstanceRequestEventData; webview_instance_response: WebviewInstanceResponseEventData; }; export interface TransportMessageHandler { (payload: T): void; } export interface TransportListener { on( type: K, callback: TransportMessageHandler, ): Disposable; } export interface TransportPublisher { publish(type: K, payload: MessagesToClient[K]): Promise; } export interface Transport extends TransportListener, TransportPublisher {} References:" You are a code assistant,Definition of 'StateCheckId' in file src/common/feature_state/feature_state_management_types.ts in project gitlab-lsp,"Definition: export type StateCheckId = | typeof NO_LICENSE | typeof DUO_DISABLED_FOR_PROJECT | typeof UNSUPPORTED_GITLAB_VERSION | typeof UNSUPPORTED_LANGUAGE | typeof DISABLED_LANGUAGE; export interface FeatureStateCheck { checkId: StateCheckId; details?: string; } export interface FeatureState { featureId: Feature; engagedChecks: FeatureStateCheck[]; } const CODE_SUGGESTIONS_CHECKS_PRIORITY_ORDERED = [ DUO_DISABLED_FOR_PROJECT, UNSUPPORTED_LANGUAGE, DISABLED_LANGUAGE, ]; const CHAT_CHECKS_PRIORITY_ORDERED = [DUO_DISABLED_FOR_PROJECT]; export const CHECKS_PER_FEATURE: { [key in Feature]: StateCheckId[] } = { [CODE_SUGGESTIONS]: CODE_SUGGESTIONS_CHECKS_PRIORITY_ORDERED, [CHAT]: CHAT_CHECKS_PRIORITY_ORDERED, // [WORKFLOW]: [], }; References: - src/common/feature_state/state_check.ts:5 - src/common/feature_state/state_check.ts:11 - src/common/feature_state/feature_state_management_types.ts:21" You are a code assistant,Definition of 'greet' in file src/tests/fixtures/intent/empty_function/go.go in project gitlab-lsp,"Definition: func (g Greet) greet() { } // non-empty method declaration func (g Greet) greet() { fmt.Printf(""Hello %s\n"", g.name) } References: - src/tests/fixtures/intent/empty_function/ruby.rb:20 - 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" You are a code assistant,Definition of 'WORKFLOW_EXECUTOR_VERSION' in file src/common/constants.ts in project gitlab-lsp,"Definition: 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 'TokenCheckNotifier' in file src/common/core/handlers/token_check_notifier.ts in project gitlab-lsp,"Definition: export const TokenCheckNotifier = createInterfaceId('TokenCheckNotifier'); @Injectable(TokenCheckNotifier, [GitLabApiClient]) export class DefaultTokenCheckNotifier implements TokenCheckNotifier { #notify: NotifyFn | undefined; constructor(api: GitLabApiClient) { api.onApiReconfigured(async ({ isInValidState, validationMessage }) => { if (!isInValidState) { if (!this.#notify) { throw new Error( 'The DefaultTokenCheckNotifier has not been initialized. Call init first.', ); } await this.#notify({ message: validationMessage, }); } }); } init(callback: NotifyFn) { this.#notify = callback; } } References: - src/common/core/handlers/token_check_notifier.test.ts:8 - src/common/connection_service.ts:61" You are a code assistant,Definition of 'DefaultSecurityDiagnosticsPublisher' in file src/common/security_diagnostics_publisher.ts in project gitlab-lsp,"Definition: 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, 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/security_diagnostics_publisher.test.ts:55" You are a code assistant,Definition of 'fsPathToUri' in file src/common/services/fs/utils.ts in project gitlab-lsp,"Definition: export const fsPathToUri = (fsPath: string): URI => { return URI.file(fsPath); }; export const parseURIString = (uri: string): URI => { return URI.parse(uri); }; References: - src/common/services/duo_access/project_access_cache.test.ts:114 - src/common/services/duo_access/project_access_cache.test.ts:43 - src/common/services/duo_access/project_access_cache.test.ts:113 - src/common/services/duo_access/project_access_cache.test.ts:42 - src/tests/unit/tree_sitter/test_utils.ts:41 - src/common/services/duo_access/project_access_cache.test.ts:45 - src/node/services/fs/dir.ts:43 - src/common/services/duo_access/project_access_cache.test.ts:80 - src/common/services/duo_access/project_access_cache.test.ts:147 - src/common/services/duo_access/project_access_cache.test.ts:148 - src/common/services/fs/virtual_file_service.ts:51 - src/common/git/repository_service.ts:267" You are a code assistant,Definition of 'constructor' in file packages/lib_webview_transport_json_rpc/src/json_rpc_connection_transport.ts in project gitlab-lsp,"Definition: constructor({ connection, logger, notificationRpcMethod: notificationChannel = DEFAULT_NOTIFICATION_RPC_METHOD, webviewCreatedRpcMethod: webviewCreatedChannel = DEFAULT_WEBVIEW_CREATED_RPC_METHOD, webviewDestroyedRpcMethod: webviewDestroyedChannel = DEFAULT_WEBVIEW_DESTROYED_RPC_METHOD, }: JsonRpcConnectionTransportProps) { this.#connection = connection; this.#logger = logger ? withPrefix(logger, LOGGER_PREFIX) : undefined; this.#notificationChannel = notificationChannel; this.#webviewCreatedChannel = webviewCreatedChannel; this.#webviewDestroyedChannel = webviewDestroyedChannel; this.#subscribeToConnection(); } #subscribeToConnection() { const channelToNotificationHandlerMap = { [this.#webviewCreatedChannel]: handleWebviewCreated(this.#messageEmitter, this.#logger), [this.#webviewDestroyedChannel]: handleWebviewDestroyed(this.#messageEmitter, this.#logger), [this.#notificationChannel]: handleWebviewMessage(this.#messageEmitter, this.#logger), }; Object.entries(channelToNotificationHandlerMap).forEach(([channel, handler]) => { const disposable = this.#connection.onNotification(channel, handler); this.#disposables.push(disposable); }); } on( type: K, callback: TransportMessageHandler, ): Disposable { this.#messageEmitter.on(type, callback as WebviewTransportEventEmitterMessages[K]); return { dispose: () => this.#messageEmitter.off(type, callback as WebviewTransportEventEmitterMessages[K]), }; } publish(type: K, payload: MessagesToClient[K]): Promise { if (type === 'webview_instance_notification') { return this.#connection.sendNotification(this.#notificationChannel, payload); } throw new Error(`Unknown message type: ${type}`); } dispose(): void { this.#messageEmitter.removeAllListeners(); this.#disposables.forEach((disposable) => disposable.dispose()); this.#logger?.debug('JsonRpcConnectionTransport disposed'); } } References:" You are a code assistant,Definition of 'MessagePayload' in file packages/lib_message_bus/src/types/bus.ts in project gitlab-lsp,"Definition: export type MessagePayload = unknown | undefined; export type KeysWithOptionalValues = { [K in keyof T]: undefined extends T[K] ? K : never; }[keyof T]; /** * Maps notification message types to their corresponding payloads. * @typedef {Record} NotificationMap */ export type NotificationMap = Record; /** * Interface for publishing notifications. * @interface * @template {NotificationMap} TNotifications */ export interface NotificationPublisher { sendNotification>(type: T): void; sendNotification(type: T, payload: TNotifications[T]): void; } /** * Interface for listening to notifications. * @interface * @template {NotificationMap} TNotifications */ export interface NotificationListener { onNotification>( type: T, handler: () => void, ): Disposable; onNotification( type: T, handler: (payload: TNotifications[T]) => void, ): Disposable; } /** * Maps request message types to their corresponding request/response payloads. * @typedef {Record} RequestMap */ export type RequestMap = Record< Method, { params: MessagePayload; result: MessagePayload; } >; type KeysWithOptionalParams = { [K in keyof R]: R[K]['params'] extends undefined ? never : K; }[keyof R]; /** * Extracts the response payload type from a request type. * @template {MessagePayload} T * @typedef {T extends [never] ? void : T[0]} ExtractRequestResponse */ export type ExtractRequestResult = // eslint-disable-next-line @typescript-eslint/no-invalid-void-type T['result'] extends undefined ? void : T; /** * Interface for publishing requests. * @interface * @template {RequestMap} TRequests */ export interface RequestPublisher { sendRequest>( type: T, ): Promise>; sendRequest( type: T, payload: TRequests[T]['params'], ): Promise>; } /** * Interface for listening to requests. * @interface * @template {RequestMap} TRequests */ export interface RequestListener { onRequest>( type: T, handler: () => Promise>, ): Disposable; onRequest( type: T, handler: (payload: TRequests[T]['params']) => Promise>, ): Disposable; } /** * Defines the structure for message definitions, including notifications and requests. */ export type MessageDefinitions< TNotifications extends NotificationMap = NotificationMap, TRequests extends RequestMap = RequestMap, > = { notifications: TNotifications; requests: TRequests; }; export type MessageMap< TInboundMessageDefinitions extends MessageDefinitions = MessageDefinitions, TOutboundMessageDefinitions extends MessageDefinitions = MessageDefinitions, > = { inbound: TInboundMessageDefinitions; outbound: TOutboundMessageDefinitions; }; export interface MessageBus extends NotificationPublisher, NotificationListener, RequestPublisher, RequestListener {} References: - packages/lib_message_bus/src/types/bus.ts:61 - packages/lib_message_bus/src/types/bus.ts:62" You are a code assistant,Definition of 'getContext' in file src/common/document_transformer_service.ts in project gitlab-lsp,"Definition: 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 'hasbinSomeSync' in file src/tests/int/hasbin.ts in project gitlab-lsp,"Definition: export function hasbinSomeSync(bins: string[]) { return bins.some(hasbin.sync); } export function hasbinFirst(bins: string[], done: (result: boolean) => void) { async.detect(bins, hasbin.async, function (result) { done(result || false); }); } export function hasbinFirstSync(bins: string[]) { const matched = bins.filter(hasbin.sync); return matched.length ? matched[0] : false; } export function getPaths(bin: string) { const envPath = process.env.PATH || ''; const envExt = process.env.PATHEXT || ''; return envPath .replace(/[""]+/g, '') .split(delimiter) .map(function (chunk) { return envExt.split(delimiter).map(function (ext) { return join(chunk, bin + ext); }); }) .reduce(function (a, b) { return a.concat(b); }); } 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 'NotificationCall' in file packages/lib_webview_transport_json_rpc/src/json_rpc_connection_transport.test.ts in project gitlab-lsp,"Definition: type NotificationCall = [string, (message: unknown) => void]; return (connection.onNotification.mock.calls as unknown as NotificationCall[]).find( ([notificationMethod]) => notificationMethod === method, )?.[1]; } References:" You are a code assistant,Definition of 'instantiate' in file packages/lib_di/src/index.ts in project gitlab-lsp,"Definition: instantiate(...classes: WithConstructor[]) { // ensure all classes have been decorated with @Injectable const undecorated = classes.filter((c) => !injectableMetadata.has(c)).map((c) => c.name); if (undecorated.length) { throw new Error(`Classes [${undecorated}] are not decorated with @Injectable.`); } const classesWithDeps: ClassWithDependencies[] = classes.map((cls) => { // we verified just above that all classes are present in the metadata map // eslint-disable-next-line @typescript-eslint/no-non-null-assertion const { id, dependencies } = injectableMetadata.get(cls)!; return { cls, id, dependencies }; }); const validators: Validator[] = [ interfaceUsedOnlyOnce, dependenciesArePresent, noCircularDependencies, ]; validators.forEach((v) => v(classesWithDeps, Array.from(this.#instances.keys()))); const classesById = new Map(); // Index classes by their interface id classesWithDeps.forEach((cwd) => { classesById.set(cwd.id, cwd); }); // Create instances in topological order for (const cwd of sortDependencies(classesById)) { const args = cwd.dependencies.map((dependencyId) => this.#instances.get(dependencyId)); // eslint-disable-next-line new-cap const instance = new cwd.cls(...args); this.#instances.set(cwd.id, instance); } } get(id: InterfaceId): T { const instance = this.#instances.get(id); if (!instance) { throw new Error(`Instance for interface '${sanitizeId(id)}' is not in the container.`); } return instance as T; } } References:" You are a code assistant,Definition of 'chatWebviewPlugin' in file packages/webview-chat/src/plugin/index.ts in project gitlab-lsp,"Definition: export const chatWebviewPlugin: WebviewPlugin = { id: WEBVIEW_ID, title: WEBVIEW_TITLE, setup: ({ webview }) => { webview.onInstanceConnected((_webviewInstanceId, messageBus) => { messageBus.sendNotification('newUserPrompt', { prompt: 'This is a new prompt', }); }); }, }; References:" You are a code assistant,Definition of 'constructor' in file packages/webview_duo_chat/src/plugin/chat_controller.ts in project gitlab-lsp,"Definition: constructor( manager: GitLabPlatformManagerForChat, webviewMessageBus: DuoChatWebviewMessageBus, extensionMessageBus: DuoChatExtensionMessageBus, ) { this.#api = new GitLabChatApi(manager); this.chatHistory = []; this.#webviewMessageBus = webviewMessageBus; this.#extensionMessageBus = extensionMessageBus; this.#setupMessageHandlers.bind(this)(); } dispose(): void { this.#subscriptions.dispose(); } #setupMessageHandlers() { this.#subscriptions.add( this.#webviewMessageBus.onNotification('newPrompt', async (message) => { const record = GitLabChatRecord.buildWithContext({ role: 'user', content: message.record.content, }); await this.#processNewUserRecord(record); }), ); } async #processNewUserRecord(record: GitLabChatRecord) { if (!record.content) return; await this.#sendNewPrompt(record); if (record.errors.length > 0) { this.#extensionMessageBus.sendNotification('showErrorMessage', { message: record.errors[0], }); return; } await this.#addToChat(record); if (record.type === 'newConversation') return; const responseRecord = new GitLabChatRecord({ role: 'assistant', state: 'pending', requestId: record.requestId, }); await this.#addToChat(responseRecord); try { await this.#api.subscribeToUpdates(this.#subscriptionUpdateHandler.bind(this), record.id); } catch (err) { // TODO: log error } // Fallback if websocket fails or disabled. await Promise.all([this.#refreshRecord(record), this.#refreshRecord(responseRecord)]); } async #subscriptionUpdateHandler(data: AiCompletionResponseMessageType) { const record = this.#findRecord(data); if (!record) return; record.update({ chunkId: data.chunkId, content: data.content, contentHtml: data.contentHtml, extras: data.extras, timestamp: data.timestamp, errors: data.errors, }); record.state = 'ready'; this.#webviewMessageBus.sendNotification('updateRecord', record); } // async #restoreHistory() { // this.chatHistory.forEach((record) => { // this.#webviewMessageBus.sendNotification('newRecord', record); // }, this); // } async #addToChat(record: GitLabChatRecord) { this.chatHistory.push(record); this.#webviewMessageBus.sendNotification('newRecord', record); } async #sendNewPrompt(record: GitLabChatRecord) { if (!record.content) throw new Error('Trying to send prompt without content.'); try { const actionResponse = await this.#api.processNewUserPrompt( record.content, record.id, record.context?.currentFile, ); record.update(actionResponse.aiAction); } catch (err) { // eslint-disable-next-line @typescript-eslint/no-explicit-any record.update({ errors: [`API error: ${(err as any).response.errors[0].message}`] }); } } async #refreshRecord(record: GitLabChatRecord) { if (!record.requestId) { throw Error('requestId must be present!'); } const apiResponse = await this.#api.pullAiMessage(record.requestId, record.role); if (apiResponse.type !== 'error') { record.update({ content: apiResponse.content, contentHtml: apiResponse.contentHtml, extras: apiResponse.extras, timestamp: apiResponse.timestamp, }); } record.update({ errors: apiResponse.errors, state: 'ready' }); this.#webviewMessageBus.sendNotification('updateRecord', record); } #findRecord(data: { requestId: string; role: string }) { return this.chatHistory.find( (r) => r.requestId === data.requestId && r.role.toLowerCase() === data.role.toLowerCase(), ); } } References:" You are a code assistant,Definition of 'GitLabAPI' in file src/common/api.ts in project gitlab-lsp,"Definition: export class GitLabAPI implements GitLabApiClient { #token: string | undefined; #baseURL: string; #clientInfo?: IClientInfo; #lsFetch: LsFetch; #eventEmitter = new EventEmitter(); #configService: ConfigService; #instanceVersion?: string; constructor(lsFetch: LsFetch, configService: ConfigService) { this.#baseURL = GITLAB_API_BASE_URL; this.#lsFetch = lsFetch; this.#configService = configService; this.#configService.onConfigChange(async (config) => { this.#clientInfo = configService.get('client.clientInfo'); this.#lsFetch.updateAgentOptions({ ignoreCertificateErrors: this.#configService.get('client.ignoreCertificateErrors') ?? false, ...(this.#configService.get('client.httpAgentOptions') ?? {}), }); await this.configureApi(config.client); }); } onApiReconfigured(listener: (data: ApiReconfiguredData) => void): Disposable { this.#eventEmitter.on(CONFIG_CHANGE_EVENT_NAME, listener); return { dispose: () => this.#eventEmitter.removeListener(CONFIG_CHANGE_EVENT_NAME, listener) }; } #fireApiReconfigured(isInValidState: boolean, validationMessage?: string) { const data: ApiReconfiguredData = { isInValidState, validationMessage }; this.#eventEmitter.emit(CONFIG_CHANGE_EVENT_NAME, data); } async configureApi({ token, baseUrl = GITLAB_API_BASE_URL, }: { token?: string; baseUrl?: string; }) { if (this.#token === token && this.#baseURL === baseUrl) return; this.#token = token; this.#baseURL = baseUrl; const { valid, reason, message } = await this.checkToken(this.#token); let validationMessage; if (!valid) { this.#configService.set('client.token', undefined); validationMessage = `Token is invalid. ${message}. Reason: ${reason}`; log.warn(validationMessage); } else { log.info('Token is valid'); } this.#instanceVersion = await this.#getGitLabInstanceVersion(); this.#fireApiReconfigured(valid, validationMessage); } #looksLikePatToken(token: string): boolean { // OAuth tokens will be longer than 42 characters and PATs will be shorter. return token.length < 42; } async #checkPatToken(token: string): Promise { const headers = this.#getDefaultHeaders(token); const response = await this.#lsFetch.get( `${this.#baseURL}/api/v4/personal_access_tokens/self`, { headers }, ); await handleFetchError(response, 'Information about personal access token'); const { active, scopes } = (await response.json()) as PersonalAccessToken; if (!active) { return { valid: false, reason: 'not_active', message: 'Token is not active.', }; } if (!this.#hasValidScopes(scopes)) { const joinedScopes = scopes.map((scope) => `'${scope}'`).join(', '); return { valid: false, reason: 'invalid_scopes', message: `Token has scope(s) ${joinedScopes} (needs 'api').`, }; } return { valid: true }; } async #checkOAuthToken(token: string): Promise { const headers = this.#getDefaultHeaders(token); const response = await this.#lsFetch.get(`${this.#baseURL}/oauth/token/info`, { headers, }); await handleFetchError(response, 'Information about OAuth token'); const { scope: scopes } = (await response.json()) as OAuthToken; if (!this.#hasValidScopes(scopes)) { const joinedScopes = scopes.map((scope) => `'${scope}'`).join(', '); return { valid: false, reason: 'invalid_scopes', message: `Token has scope(s) ${joinedScopes} (needs 'api').`, }; } return { valid: true }; } async checkToken(token: string = ''): Promise { try { if (this.#looksLikePatToken(token)) { log.info('Checking token for PAT validity'); return await this.#checkPatToken(token); } log.info('Checking token for OAuth validity'); return await this.#checkOAuthToken(token); } catch (err) { log.error('Error performing token check', err); return { valid: false, reason: 'unknown', message: `Failed to check token: ${err}`, }; } } #hasValidScopes(scopes: string[]): boolean { return scopes.includes('api'); } async getCodeSuggestions( request: CodeSuggestionRequest, ): Promise { if (!this.#token) { throw new Error('Token needs to be provided to request Code Suggestions'); } const headers = { ...this.#getDefaultHeaders(this.#token), 'Content-Type': 'application/json', }; const response = await this.#lsFetch.post( `${this.#baseURL}/api/v4/code_suggestions/completions`, { headers, body: JSON.stringify(request) }, ); await handleFetchError(response, 'Code Suggestions'); const data = await response.json(); return { ...data, status: response.status }; } async *getStreamingCodeSuggestions( request: CodeSuggestionRequest, ): AsyncGenerator { if (!this.#token) { throw new Error('Token needs to be provided to stream code suggestions'); } const headers = { ...this.#getDefaultHeaders(this.#token), 'Content-Type': 'application/json', }; yield* this.#lsFetch.streamFetch( `${this.#baseURL}/api/v4/code_suggestions/completions`, JSON.stringify(request), headers, ); } async fetchFromApi(request: ApiRequest): Promise { if (!this.#token) { return Promise.reject(new Error('Token needs to be provided to authorise API request.')); } if ( request.supportedSinceInstanceVersion && !this.#instanceVersionHigherOrEqualThen(request.supportedSinceInstanceVersion.version) ) { return Promise.reject( new InvalidInstanceVersionError( `Can't ${request.supportedSinceInstanceVersion.resourceName} until your instance is upgraded to ${request.supportedSinceInstanceVersion.version} or higher.`, ), ); } if (request.type === 'graphql') { return this.#graphqlRequest(request.query, request.variables); } switch (request.method) { case 'GET': return this.#fetch(request.path, request.searchParams, 'resource', request.headers); case 'POST': return this.#postFetch(request.path, 'resource', request.body, request.headers); default: // the type assertion is necessary because TS doesn't expect any other types throw new Error(`Unknown request type ${(request as ApiRequest).type}`); } } async connectToCable(): Promise { const headers = this.#getDefaultHeaders(this.#token); const websocketOptions = { headers: { ...headers, Origin: this.#baseURL, }, }; return connectToCable(this.#baseURL, websocketOptions); } async #graphqlRequest( document: RequestDocument, variables?: V, ): Promise { const ensureEndsWithSlash = (url: string) => url.replace(/\/?$/, '/'); const endpoint = new URL('./api/graphql', ensureEndsWithSlash(this.#baseURL)).href; // supports GitLab instances that are on a custom path, e.g. ""https://example.com/gitlab"" const graphqlFetch = async ( input: RequestInfo | URL, init?: RequestInit, ): Promise => { const url = input instanceof URL ? input.toString() : input; return this.#lsFetch.post(url, { ...init, headers: { ...headers, ...init?.headers }, }); }; const headers = this.#getDefaultHeaders(this.#token); const client = new GraphQLClient(endpoint, { headers, fetch: graphqlFetch, }); return client.request(document, variables); } async #fetch( apiResourcePath: string, query: Record = {}, resourceName = 'resource', headers?: Record, ): Promise { const url = `${this.#baseURL}/api/v4${apiResourcePath}${createQueryString(query)}`; const result = await this.#lsFetch.get(url, { headers: { ...this.#getDefaultHeaders(this.#token), ...headers }, }); await handleFetchError(result, resourceName); return result.json() as Promise; } async #postFetch( apiResourcePath: string, resourceName = 'resource', body?: unknown, headers?: Record, ): Promise { const url = `${this.#baseURL}/api/v4${apiResourcePath}`; const response = await this.#lsFetch.post(url, { headers: { 'Content-Type': 'application/json', ...this.#getDefaultHeaders(this.#token), ...headers, }, body: JSON.stringify(body), }); await handleFetchError(response, resourceName); return response.json() as Promise; } #getDefaultHeaders(token?: string) { return { Authorization: `Bearer ${token}`, 'User-Agent': `code-completions-language-server-experiment (${this.#clientInfo?.name}:${this.#clientInfo?.version})`, 'X-Gitlab-Language-Server-Version': getLanguageServerVersion(), }; } #instanceVersionHigherOrEqualThen(version: string): boolean { if (!this.#instanceVersion) return false; return semverCompare(this.#instanceVersion, version) >= 0; } async #getGitLabInstanceVersion(): Promise { if (!this.#token) { return ''; } const headers = this.#getDefaultHeaders(this.#token); const response = await this.#lsFetch.get(`${this.#baseURL}/api/v4/version`, { headers, }); const { version } = await response.json(); return version; } get instanceVersion() { return this.#instanceVersion; } } References: - src/common/api.test.ts:39 - src/common/api.test.ts:486 - src/common/api.test.ts:83" You are a code assistant,Definition of 'stop' in file src/common/tracking/snowplow/snowplow.ts in project gitlab-lsp,"Definition: async stop() { await this.#emitter.stop(); } public destroy() { Snowplow.#instance = undefined; } } References:" You are a code assistant,Definition of 'HandlerNotFoundError' in file packages/lib_handler_registry/src/errors/handler_not_found_error.ts in project gitlab-lsp,"Definition: export class HandlerNotFoundError extends Error { readonly type = 'HandlerNotFoundError'; constructor(key: string) { const message = `Handler not found for key ${key}`; super(message); } } References: - packages/lib_handler_registry/src/registry/simple_registry.ts:32" You are a code assistant,Definition of 'InstanceFeatureFlags' in file src/common/feature_flags.ts in project gitlab-lsp,"Definition: export enum InstanceFeatureFlags { EditorAdvancedContext = 'advanced_context_resolver', CodeSuggestionsContext = 'code_suggestions_context', } export const INSTANCE_FEATURE_FLAG_QUERY = gql` query featureFlagsEnabled($name: String!) { featureFlagEnabled(name: $name) } `; export const FeatureFlagService = createInterfaceId('FeatureFlagService'); export interface FeatureFlagService { /** * Checks if a feature flag is enabled on the GitLab instance. * @see `IGitLabAPI` for how the instance is determined. * @requires `updateInstanceFeatureFlags` to be called first. */ isInstanceFlagEnabled(name: InstanceFeatureFlags): boolean; /** * Checks if a feature flag is enabled on the client. * @see `ConfigService` for client configuration. */ isClientFlagEnabled(name: ClientFeatureFlags): boolean; } @Injectable(FeatureFlagService, [GitLabApiClient, ConfigService]) export class DefaultFeatureFlagService { #api: GitLabApiClient; #configService: ConfigService; #featureFlags: Map = 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 { 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 { 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: - src/common/feature_flags.ts:32 - src/common/feature_flags.ts:107" You are a code assistant,Definition of 'SuggestionOption' in file src/common/api_types.ts in project gitlab-lsp,"Definition: export interface SuggestionOption { index?: number; text: string; uniqueTrackingId: string; lang?: string; } export interface TelemetryRequest { event: string; additional_properties: { unique_tracking_id: string; language?: string; suggestion_size?: number; timestamp: string; }; } References: - src/common/utils/suggestion_mapper.test.ts:59 - src/common/utils/suggestion_mapper.test.ts:51 - src/common/utils/suggestion_mappers.ts:37 - src/common/utils/suggestion_mapper.test.ts:12" You are a code assistant,Definition of 'HtmlTransformPlugin' in file packages/lib_vite_common_config/vite.config.shared.ts in project gitlab-lsp,"Definition: export const HtmlTransformPlugin = { name: 'html-transform', transformIndexHtml(html) { return html.replace('{{ svg placeholder }}', svgSpriteContent); }, }; export const InlineSvgPlugin = { name: 'inline-svg', transform(code, id) { if (id.endsWith('@gitlab/svgs/dist/icons.svg')) { svgSpriteContent = fs.readFileSync(id, 'utf-8'); return 'export default """"'; } if (id.match(/@gitlab\/svgs\/dist\/illustrations\/.*\.svg$/)) { const base64Data = imageToBase64(id); return `export default ""data:image/svg+xml;base64,${base64Data}""`; } return code; }, }; export function createViteConfigForWebview(name): UserConfig { const outDir = path.resolve(__dirname, `../../../../out/webviews/${name}`); return { plugins: [vue2(), InlineSvgPlugin, SyncLoadScriptsPlugin, HtmlTransformPlugin], resolve: { alias: { '@': fileURLToPath(new URL('./src/app', import.meta.url)), }, }, root: './src/app', base: '', build: { target: 'es2022', emptyOutDir: true, outDir, rollupOptions: { input: [path.join('src', 'app', 'index.html')], }, }, }; } References:" You are a code assistant,Definition of 'isWebviewAddress' in file packages/lib_webview_transport/src/utils/message_validators.ts in project gitlab-lsp,"Definition: export const isWebviewAddress: MessageValidator = ( message: unknown, ): message is WebviewAddress => typeof message === 'object' && message !== null && 'webviewId' in message && 'webviewInstanceId' in message; export const isWebviewInstanceCreatedEventData: MessageValidator< WebviewInstanceCreatedEventData > = (message: unknown): message is WebviewInstanceCreatedEventData => isWebviewAddress(message); export const isWebviewInstanceDestroyedEventData: MessageValidator< WebviewInstanceDestroyedEventData > = (message: unknown): message is WebviewInstanceDestroyedEventData => isWebviewAddress(message); export const isWebviewInstanceMessageEventData: MessageValidator< WebviewInstanceNotificationEventData > = (message: unknown): message is WebviewInstanceNotificationEventData => isWebviewAddress(message) && 'type' in message; References: - packages/lib_webview_transport/src/utils/message_validators.ts:24 - packages/lib_webview_transport/src/utils/message_validators.ts:29 - packages/lib_webview_transport/src/utils/message_validators.ts:20" You are a code assistant,Definition of 'getProjectGqlId' in file packages/webview_duo_chat/src/plugin/port/chat/get_platform_manager_for_chat.ts in project gitlab-lsp,"Definition: async getProjectGqlId(): Promise { const projectManager = await this.#platformManager.getForActiveProject(false); return projectManager?.project.gqlId; } /** * Obtains a GitLab Platform to send API requests to the GitLab API * for the Duo Chat feature. * * - It returns a GitLabPlatformForAccount for the first linked account. * - It returns undefined if there are no accounts linked */ async getGitLabPlatform(): Promise { const platforms = await this.#platformManager.getForAllAccounts(); if (!platforms.length) { return undefined; } let platform: GitLabPlatformForAccount | undefined; // Using a for await loop in this context because we want to stop // evaluating accounts as soon as we find one with code suggestions enabled for await (const result of platforms.map(getChatSupport)) { if (result.hasSupportForChat) { platform = result.platform; break; } } return platform; } async getGitLabEnvironment(): Promise { const platform = await this.getGitLabPlatform(); const instanceUrl = platform?.account.instanceUrl; switch (instanceUrl) { case GITLAB_COM_URL: return GitLabEnvironment.GITLAB_COM; case GITLAB_DEVELOPMENT_URL: return GitLabEnvironment.GITLAB_DEVELOPMENT; case GITLAB_STAGING_URL: return GitLabEnvironment.GITLAB_STAGING; case GITLAB_ORG_URL: return GitLabEnvironment.GITLAB_ORG; default: return GitLabEnvironment.GITLAB_SELF_MANAGED; } } } References:" You are a code assistant,Definition of 'DuoChatExtensionMessageBus' in file packages/webview_duo_chat/src/plugin/types.ts in project gitlab-lsp,"Definition: export type DuoChatExtensionMessageBus = MessageBus<{ inbound: Messages['extensionToPlugin']; outbound: Messages['pluginToExtension']; }>; /** * These types are copied from ./src/common/api_types.ts * TODO: move these types to a common package */ // why: `_TReturnType` helps encapsulate the full request type when used with `fetchFromApi` /* eslint @typescript-eslint/no-unused-vars: [""error"", { ""varsIgnorePattern"": ""TReturnType"" }] */ /** * The response body is parsed as JSON and it's up to the client to ensure it * matches the TReturnType */ interface SupportedSinceInstanceVersion { version: string; resourceName: string; } interface BaseRestRequest<_TReturnType> { type: 'rest'; /** * 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; headers?: Record; supportedSinceInstanceVersion?: SupportedSinceInstanceVersion; } interface GraphQLRequest<_TReturnType> { type: 'graphql'; query: string; /** Options passed to the GraphQL query */ variables: Record; 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; supportedSinceInstanceVersion?: SupportedSinceInstanceVersion; } export type ApiRequest<_TReturnType> = | GetRequest<_TReturnType> | PostRequest<_TReturnType> | GraphQLRequest<_TReturnType>; export interface GitLabApiClient { fetchFromApi(request: ApiRequest): Promise; connectToCable(): Promise; } References: - packages/webview_duo_chat/src/plugin/chat_controller.ts:13 - packages/webview_duo_chat/src/plugin/chat_controller.ts:22" You are a code assistant,Definition of 'CreateMessageMap' in file packages/lib_message_bus/src/types/utils.ts in project gitlab-lsp,"Definition: export type CreateMessageMap> = MessageMap< CreateMessageDefinitions, CreateMessageDefinitions >; References:" You are a code assistant,Definition of 'AiContextProvider' in file src/common/ai_context_management_2/providers/ai_context_provider.ts in project gitlab-lsp,"Definition: export interface AiContextProvider { getProviderItems( query: string, workspaceFolder: WorkspaceFolder[], ): Promise; } References:" You are a code assistant,Definition of 'CompletionRequest' in file src/common/message_handler.ts in project gitlab-lsp,"Definition: 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 => { 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/suggestion/suggestion_service.ts:389 - src/common/suggestion/suggestion_service.ts:324 - src/common/suggestion/suggestion_service.ts:193" You are a code assistant,Definition of 'SupportedLanguagesService' in file src/common/suggestion/supported_languages_service.ts in project gitlab-lsp,"Definition: export interface SupportedLanguagesService { isLanguageEnabled(languageId: string): boolean; isLanguageSupported(languageId: string): boolean; onLanguageChange(listener: () => void): Disposable; } export const SupportedLanguagesService = createInterfaceId( 'SupportedLanguagesService', ); @Injectable(SupportedLanguagesService, [ConfigService]) export class DefaultSupportedLanguagesService implements SupportedLanguagesService { #enabledLanguages: Set; #supportedLanguages: Set; #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 = 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: - src/common/advanced_context/advanced_context_service.ts:30 - src/common/feature_state/supported_language_check.ts:24 - src/common/feature_state/supported_language_check.ts:32 - src/common/advanced_context/advanced_context_service.ts:37" You are a code assistant,Definition of 'dispose' in file packages/lib_webview_client/src/bus/provider/socket_io_message_bus.ts in project gitlab-lsp,"Definition: dispose() { this.#socket.off(SOCKET_NOTIFICATION_CHANNEL, this.#handleNotificationMessage); this.#socket.off(SOCKET_REQUEST_CHANNEL, this.#handleRequestMessage); this.#socket.off(SOCKET_RESPONSE_CHANNEL, this.#handleResponseMessage); this.#notificationHandlers.dispose(); this.#requestHandlers.dispose(); this.#pendingRequests.dispose(); } #setupSocketEventHandlers = () => { this.#socket.on(SOCKET_NOTIFICATION_CHANNEL, this.#handleNotificationMessage); this.#socket.on(SOCKET_REQUEST_CHANNEL, this.#handleRequestMessage); this.#socket.on(SOCKET_RESPONSE_CHANNEL, this.#handleResponseMessage); }; #handleNotificationMessage = async (message: { type: keyof TMessages['inbound']['notifications'] & string; payload: unknown; }) => { await this.#notificationHandlers.handle(message.type, message.payload); }; #handleRequestMessage = async (message: { requestId: string; event: keyof TMessages['inbound']['requests'] & string; payload: unknown; }) => { const response = await this.#requestHandlers.handle(message.event, message.payload); this.#socket.emit(SOCKET_RESPONSE_CHANNEL, { requestId: message.requestId, payload: response, }); }; #handleResponseMessage = async (message: { requestId: string; payload: unknown }) => { await this.#pendingRequests.handle(message.requestId, message.payload); }; } References:" You are a code assistant,Definition of 'postBuildVscCodeYalcPublish' in file scripts/watcher/watch.ts in project gitlab-lsp,"Definition: async function postBuildVscCodeYalcPublish(vsCodePath: string) { const commandCwd = resolvePath(cwd(), vsCodePath); await runScript('npx yalc@1.0.0-pre.53 publish'); console.log(successColor, 'Pushed to yalc'); await runScript('npx yalc@1.0.0-pre.53 add @gitlab-org/gitlab-lsp', commandCwd); } /** * additionally copy to desktop assets so the developer * does not need to restart the extension host */ async function postBuildVSCodeCopyFiles(vsCodePath: string) { const desktopAssetsDir = `${vsCodePath}/dist-desktop/assets/language-server`; try { await copy(resolvePath(`${cwd()}/out`), desktopAssetsDir); console.log(successColor, 'Copied files to vscode extension'); } catch (error) { console.error(errorColor, 'Whoops, something went wrong...'); console.error(error); } } function postBuild() { const editor = process.argv.find((arg) => arg.startsWith('--editor='))?.split('=')[1]; if (editor === 'vscode') { const vsCodePath = process.env.VSCODE_EXTENSION_RELATIVE_PATH ?? '../gitlab-vscode-extension'; return [postBuildVscCodeYalcPublish(vsCodePath), postBuildVSCodeCopyFiles(vsCodePath)]; } console.warn('No editor specified, skipping post-build steps'); return [new Promise((resolve) => resolve())]; } async function run() { const watchMsg = () => console.log(textColor, `Watching for file changes on ${dir}`); const now = performance.now(); const buildSuccessful = await runBuild(); if (!buildSuccessful) return watchMsg(); await Promise.all(postBuild()); console.log(successColor, `Finished in ${Math.round(performance.now() - now)}ms`); watchMsg(); } let timeout: NodeJS.Timeout | null = null; const dir = './src'; const watcher = chokidar.watch(dir, { ignored: /(^|[/\\])\../, // ignore dotfiles persistent: true, }); let isReady = false; watcher .on('add', async (filePath) => { if (!isReady) return; console.log(`File ${filePath} has been added`); await run(); }) .on('change', async (filePath) => { if (!isReady) return; console.log(`File ${filePath} has been changed`); if (timeout) clearTimeout(timeout); // We debounce the run function on change events in the case of many files being changed at once timeout = setTimeout(async () => { await run(); }, 1000); }) .on('ready', async () => { await run(); isReady = true; }) .on('unlink', (filePath) => console.log(`File ${filePath} has been removed`)); console.log(textColor, 'Starting watcher...'); References: - scripts/watcher/watch.ts:55" You are a code assistant,Definition of 'MessageDefinitions' in file packages/lib_message_bus/src/types/bus.ts in project gitlab-lsp,"Definition: export type MessageDefinitions< TNotifications extends NotificationMap = NotificationMap, TRequests extends RequestMap = RequestMap, > = { notifications: TNotifications; requests: TRequests; }; export type MessageMap< TInboundMessageDefinitions extends MessageDefinitions = MessageDefinitions, TOutboundMessageDefinitions extends MessageDefinitions = MessageDefinitions, > = { inbound: TInboundMessageDefinitions; outbound: TOutboundMessageDefinitions; }; export interface MessageBus extends NotificationPublisher, NotificationListener, RequestPublisher, RequestListener {} References: - packages/lib_webview_plugin/src/webview_plugin.ts:13 - packages/lib_webview_plugin/src/webview_plugin.ts:14 - packages/lib_webview_plugin/src/webview_plugin.ts:15 - packages/lib_webview_plugin/src/webview_plugin.ts:12" You are a code assistant,Definition of 'getProjectsForWorkspaceFolder' in file src/common/services/duo_access/project_access_cache.ts in project gitlab-lsp,"Definition: getProjectsForWorkspaceFolder(workspaceFolder: WorkspaceFolder): DuoProject[]; updateCache({ baseUrl, workspaceFolders, }: { baseUrl: string; workspaceFolders: WorkspaceFolder[]; }): Promise; onDuoProjectCacheUpdate(listener: () => void): Disposable; } export const DuoProjectAccessCache = createInterfaceId('DuoProjectAccessCache'); @Injectable(DuoProjectAccessCache, [DirectoryWalker, FileResolver, GitLabApiClient]) export class DefaultDuoProjectAccessCache { #duoProjects: Map; #eventEmitter = new EventEmitter(); constructor( private readonly directoryWalker: DirectoryWalker, private readonly fileResolver: FileResolver, private readonly api: GitLabApiClient, ) { this.#duoProjects = new Map(); } getProjectsForWorkspaceFolder(workspaceFolder: WorkspaceFolder): DuoProject[] { return this.#duoProjects.get(workspaceFolder.uri) ?? []; } async updateCache({ baseUrl, workspaceFolders, }: { baseUrl: string; workspaceFolders: WorkspaceFolder[]; }) { try { this.#duoProjects.clear(); const duoProjects = await Promise.all( workspaceFolders.map(async (workspaceFolder) => { return { workspaceFolder, projects: await this.#duoProjectsForWorkspaceFolder({ workspaceFolder, baseUrl, }), }; }), ); for (const { workspaceFolder, projects } of duoProjects) { this.#logProjectsInfo(projects, workspaceFolder); this.#duoProjects.set(workspaceFolder.uri, projects); } this.#triggerChange(); } catch (err) { log.error('DuoProjectAccessCache: failed to update project access cache', err); } } #logProjectsInfo(projects: DuoProject[], workspaceFolder: WorkspaceFolder) { if (!projects.length) { log.warn( `DuoProjectAccessCache: no projects found for workspace folder ${workspaceFolder.uri}`, ); return; } log.debug( `DuoProjectAccessCache: found ${projects.length} projects for workspace folder ${workspaceFolder.uri}: ${JSON.stringify(projects, null, 2)}`, ); } async #duoProjectsForWorkspaceFolder({ workspaceFolder, baseUrl, }: { workspaceFolder: WorkspaceFolder; baseUrl: string; }): Promise { const remotes = await this.#gitlabRemotesForWorkspaceFolder(workspaceFolder, baseUrl); const projects = await Promise.all( remotes.map(async (remote) => { const enabled = await this.#checkDuoFeaturesEnabled(remote.namespaceWithPath); return { projectPath: remote.projectPath, uri: remote.fileUri, enabled, host: remote.host, namespace: remote.namespace, namespaceWithPath: remote.namespaceWithPath, } satisfies DuoProject; }), ); return projects; } async #gitlabRemotesForWorkspaceFolder( workspaceFolder: WorkspaceFolder, baseUrl: string, ): Promise { const paths = await this.directoryWalker.findFilesForDirectory({ directoryUri: workspaceFolder.uri, filters: { fileEndsWith: ['/.git/config'], }, }); const remotes = await Promise.all( paths.map(async (fileUri) => this.#gitlabRemotesForFileUri(fileUri.toString(), baseUrl)), ); return remotes.flat(); } async #gitlabRemotesForFileUri( fileUri: string, baseUrl: string, ): Promise { const remoteUrls = await this.#remoteUrlsFromGitConfig(fileUri); return remoteUrls.reduce((acc, remoteUrl) => { const remote = parseGitLabRemote(remoteUrl, baseUrl); if (remote) { acc.push({ ...remote, fileUri }); } return acc; }, []); } async #remoteUrlsFromGitConfig(fileUri: string): Promise { try { const fileString = await this.fileResolver.readFile({ fileUri }); const config = ini.parse(fileString); return this.#getRemoteUrls(config); } catch (error) { log.error(`DuoProjectAccessCache: Failed to read git config file: ${fileUri}`, error); return []; } } #getRemoteUrls(config: GitConfig): string[] { return Object.keys(config).reduce((acc, section) => { if (section.startsWith('remote ')) { acc.push(config[section].url); } return acc; }, []); } async #checkDuoFeaturesEnabled(projectPath: string): Promise { try { const response = await this.api.fetchFromApi<{ project: GqlProjectWithDuoEnabledInfo }>({ type: 'graphql', query: duoFeaturesEnabledQuery, variables: { projectPath, }, } satisfies ApiRequest<{ project: GqlProjectWithDuoEnabledInfo }>); return Boolean(response?.project?.duoFeaturesEnabled); } catch (error) { log.error( `DuoProjectAccessCache: Failed to check if Duo features are enabled for project: ${projectPath}`, error, ); return true; } } onDuoProjectCacheUpdate( listener: (duoProjectsCache: Map) => void, ): Disposable { this.#eventEmitter.on(DUO_PROJECT_CACHE_UPDATE_EVENT, listener); return { dispose: () => this.#eventEmitter.removeListener(DUO_PROJECT_CACHE_UPDATE_EVENT, listener), }; } #triggerChange() { this.#eventEmitter.emit(DUO_PROJECT_CACHE_UPDATE_EVENT, this.#duoProjects); } } References:" You are a code assistant,Definition of 'setup' in file scripts/esbuild/helpers.ts in project gitlab-lsp,"Definition: setup(build) { build.onLoad({ filter: treeSitterLanguagesRegex }, ({ path: filePath }) => { if (!filePath.match(nodeModulesRegex)) { let contents = readFileSync(filePath, 'utf8'); contents = contents.replaceAll( ""path.join(__dirname, '../../../vendor/grammars"", ""path.join(__dirname, '../vendor/grammars"", ); return { contents, loader: extname(filePath).substring(1) as Loader, }; } return null; }); }, } satisfies Plugin; const fixWebviewPathPlugin = { name: 'fixWebviewPath', setup(build) { console.log('[fixWebviewPath] plugin initialized'); build.onLoad({ filter: /.*[/\\]webview[/\\]constants\.ts/ }, ({ path: filePath }) => { console.log('[fixWebviewPath] File load attempt:', filePath); if (!filePath.match(/.*[/\\]?node_modules[/\\].*?/)) { console.log('[fixWebviewPath] Modifying file:', filePath); let contents = readFileSync(filePath, 'utf8'); contents = contents.replaceAll( ""WEBVIEW_BASE_PATH = path.join(__dirname, '../../../out/webviews/');"", ""WEBVIEW_BASE_PATH = path.join(__dirname, '../webviews/');"", ); return { contents, loader: extname(filePath).substring(1) as Loader, }; } else { console.log('[fixWebviewPath] Skipping file:', filePath); } return null; }); }, } satisfies Plugin; const setLanguageServerVersionPlugin = { name: 'setLanguageServerVersion', setup(build) { build.onLoad({ filter: /[/\\]get_language_server_version\.ts$/ }, ({ path: filePath }) => { if (!filePath.match(nodeModulesRegex)) { let contents = readFileSync(filePath, 'utf8'); contents = contents.replaceAll( '{{GITLAB_LANGUAGE_SERVER_VERSION}}', packageJson['version'], ); return { contents, loader: extname(filePath).substring(1) as Loader, }; } return null; }); }, } satisfies Plugin; export { fixVendorGrammarsPlugin, fixWebviewPathPlugin, setLanguageServerVersionPlugin, wasmEntryPoints, }; References: - src/common/connection.test.ts:43 - src/browser/main.ts:122 - src/node/main.ts:197" You are a code assistant,Definition of 'generateUniqueTrackingId' in file src/common/tracking/utils.ts in project gitlab-lsp,"Definition: export const generateUniqueTrackingId = (): string => { return uuidv4(); }; References: - src/common/suggestion/suggestion_service.ts:328 - src/common/tracking/instance_tracker.test.ts:38 - src/common/tracking/snowplow_tracker.test.ts:83 - src/common/suggestion/suggestion_service.ts:298 - src/common/tracking/snowplow_tracker.test.ts:722 - src/common/tracking/instance_tracker.test.ts:286 - src/common/suggestion/suggestions_cache.ts:169 - src/common/tracking/snowplow_tracker.test.ts:746 - src/common/tracking/instance_tracker.test.ts:277 - src/common/suggestion/streaming_handler.test.ts:25" You are a code assistant,Definition of 'constructor' in file packages/lib_di/src/index.test.ts in project gitlab-lsp,"Definition: constructor(a: A, b: B) { this.#a = a; this.#b = b; } c = () => `C(${this.#b.b()}, ${this.#a.a()})`; } let container: Container; beforeEach(() => { container = new Container(); }); describe('addInstances', () => { const O = createInterfaceId('object'); it('fails if the instance is not branded', () => { expect(() => container.addInstances({ say: 'hello' } as BrandedInstance)).toThrow( /invoked without branded object/, ); }); it('fails if the instance is already present', () => { const a = brandInstance(O, { a: 'a' }); const b = brandInstance(O, { b: 'b' }); expect(() => container.addInstances(a, b)).toThrow(/this ID is already in the container/); }); it('adds instance', () => { const instance = { a: 'a' }; const a = brandInstance(O, instance); container.addInstances(a); expect(container.get(O)).toBe(instance); }); }); describe('instantiate', () => { it('can instantiate three classes A,B,C', () => { container.instantiate(AImpl, BImpl, CImpl); const cInstance = container.get(C); expect(cInstance.c()).toBe('C(B(a), a)'); }); it('instantiates dependencies in multiple instantiate calls', () => { container.instantiate(AImpl); // the order is important for this test // we want to make sure that the stack in circular dependency discovery is being cleared // to try why this order is necessary, remove the `inStack.delete()` from // the `if (!cwd && instanceIds.includes(id))` condition in prod code expect(() => container.instantiate(CImpl, BImpl)).not.toThrow(); }); it('detects duplicate ids', () => { @Injectable(A, []) 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 'createMockFastifyReply' in file src/node/webview/test-utils/mock_fastify_reply.ts in project gitlab-lsp,"Definition: export const createMockFastifyReply = (): MockFastifyReply & FastifyReply => { const reply: Partial = {}; reply.send = jest.fn().mockReturnThis(); reply.status = jest.fn().mockReturnThis(); reply.redirect = jest.fn().mockReturnThis(); reply.sendFile = jest.fn().mockReturnThis(); reply.code = jest.fn().mockReturnThis(); reply.header = jest.fn().mockReturnThis(); reply.type = jest.fn().mockReturnThis(); return reply as MockFastifyReply & FastifyReply; }; References: - src/node/webview/handlers/webview_handler.test.ts:39 - src/node/webview/handlers/webview_handler.test.ts:53 - src/node/webview/handlers/webview_handler.test.ts:20 - src/node/webview/routes/webview_routes.test.ts:65 - src/node/webview/handlers/build_webview_metadata_request_handler.test.ts:12" You are a code assistant,Definition of 'fetchFromApi' in file src/common/api.ts in project gitlab-lsp,"Definition: fetchFromApi(request: ApiRequest): Promise; connectToCable(): Promise; onApiReconfigured(listener: (data: ApiReconfiguredData) => void): Disposable; readonly instanceVersion?: string; } export const GitLabApiClient = createInterfaceId('GitLabApiClient'); export type GenerationType = 'comment' | 'small_file' | 'empty_function' | undefined; export interface CodeSuggestionRequest { prompt_version: number; project_path: string; model_provider?: string; project_id: number; current_file: CodeSuggestionRequestCurrentFile; intent?: 'completion' | 'generation'; stream?: boolean; /** how many suggestion options should the API return */ choices_count?: number; /** additional context to provide to the model */ context?: AdditionalContext[]; /* A user's instructions for code suggestions. */ user_instruction?: string; /* The backend can add additional prompt info based on the type of event */ generation_type?: GenerationType; } export interface CodeSuggestionRequestCurrentFile { file_name: string; content_above_cursor: string; content_below_cursor: string; } export interface CodeSuggestionResponse { choices?: SuggestionOption[]; model?: ICodeSuggestionModel; status: number; error?: string; isDirectConnection?: boolean; } // FIXME: Rename to SuggestionOptionStream when renaming the SuggestionOption export interface StartStreamOption { uniqueTrackingId: string; /** the streamId represents the beginning of a stream * */ streamId: string; } export type SuggestionOptionOrStream = SuggestionOption | StartStreamOption; export interface PersonalAccessToken { name: string; scopes: string[]; active: boolean; } export interface OAuthToken { scope: string[]; } export interface TokenCheckResponse { valid: boolean; reason?: 'unknown' | 'not_active' | 'invalid_scopes'; message?: string; } export interface IDirectConnectionDetailsHeaders { 'X-Gitlab-Global-User-Id': string; 'X-Gitlab-Instance-Id': string; 'X-Gitlab-Host-Name': string; 'X-Gitlab-Saas-Duo-Pro-Namespace-Ids': string; } export interface IDirectConnectionModelDetails { model_provider: string; model_name: string; } export interface IDirectConnectionDetails { base_url: string; token: string; expires_at: number; headers: IDirectConnectionDetailsHeaders; model_details: IDirectConnectionModelDetails; } const CONFIG_CHANGE_EVENT_NAME = 'apiReconfigured'; @Injectable(GitLabApiClient, [LsFetch, ConfigService]) export class GitLabAPI implements GitLabApiClient { #token: string | undefined; #baseURL: string; #clientInfo?: IClientInfo; #lsFetch: LsFetch; #eventEmitter = new EventEmitter(); #configService: ConfigService; #instanceVersion?: string; constructor(lsFetch: LsFetch, configService: ConfigService) { this.#baseURL = GITLAB_API_BASE_URL; this.#lsFetch = lsFetch; this.#configService = configService; this.#configService.onConfigChange(async (config) => { this.#clientInfo = configService.get('client.clientInfo'); this.#lsFetch.updateAgentOptions({ ignoreCertificateErrors: this.#configService.get('client.ignoreCertificateErrors') ?? false, ...(this.#configService.get('client.httpAgentOptions') ?? {}), }); await this.configureApi(config.client); }); } onApiReconfigured(listener: (data: ApiReconfiguredData) => void): Disposable { this.#eventEmitter.on(CONFIG_CHANGE_EVENT_NAME, listener); return { dispose: () => this.#eventEmitter.removeListener(CONFIG_CHANGE_EVENT_NAME, listener) }; } #fireApiReconfigured(isInValidState: boolean, validationMessage?: string) { const data: ApiReconfiguredData = { isInValidState, validationMessage }; this.#eventEmitter.emit(CONFIG_CHANGE_EVENT_NAME, data); } async configureApi({ token, baseUrl = GITLAB_API_BASE_URL, }: { token?: string; baseUrl?: string; }) { if (this.#token === token && this.#baseURL === baseUrl) return; this.#token = token; this.#baseURL = baseUrl; const { valid, reason, message } = await this.checkToken(this.#token); let validationMessage; if (!valid) { this.#configService.set('client.token', undefined); validationMessage = `Token is invalid. ${message}. Reason: ${reason}`; log.warn(validationMessage); } else { log.info('Token is valid'); } this.#instanceVersion = await this.#getGitLabInstanceVersion(); this.#fireApiReconfigured(valid, validationMessage); } #looksLikePatToken(token: string): boolean { // OAuth tokens will be longer than 42 characters and PATs will be shorter. return token.length < 42; } async #checkPatToken(token: string): Promise { const headers = this.#getDefaultHeaders(token); const response = await this.#lsFetch.get( `${this.#baseURL}/api/v4/personal_access_tokens/self`, { headers }, ); await handleFetchError(response, 'Information about personal access token'); const { active, scopes } = (await response.json()) as PersonalAccessToken; if (!active) { return { valid: false, reason: 'not_active', message: 'Token is not active.', }; } if (!this.#hasValidScopes(scopes)) { const joinedScopes = scopes.map((scope) => `'${scope}'`).join(', '); return { valid: false, reason: 'invalid_scopes', message: `Token has scope(s) ${joinedScopes} (needs 'api').`, }; } return { valid: true }; } async #checkOAuthToken(token: string): Promise { const headers = this.#getDefaultHeaders(token); const response = await this.#lsFetch.get(`${this.#baseURL}/oauth/token/info`, { headers, }); await handleFetchError(response, 'Information about OAuth token'); const { scope: scopes } = (await response.json()) as OAuthToken; if (!this.#hasValidScopes(scopes)) { const joinedScopes = scopes.map((scope) => `'${scope}'`).join(', '); return { valid: false, reason: 'invalid_scopes', message: `Token has scope(s) ${joinedScopes} (needs 'api').`, }; } return { valid: true }; } async checkToken(token: string = ''): Promise { try { if (this.#looksLikePatToken(token)) { log.info('Checking token for PAT validity'); return await this.#checkPatToken(token); } log.info('Checking token for OAuth validity'); return await this.#checkOAuthToken(token); } catch (err) { log.error('Error performing token check', err); return { valid: false, reason: 'unknown', message: `Failed to check token: ${err}`, }; } } #hasValidScopes(scopes: string[]): boolean { return scopes.includes('api'); } async getCodeSuggestions( request: CodeSuggestionRequest, ): Promise { if (!this.#token) { throw new Error('Token needs to be provided to request Code Suggestions'); } const headers = { ...this.#getDefaultHeaders(this.#token), 'Content-Type': 'application/json', }; const response = await this.#lsFetch.post( `${this.#baseURL}/api/v4/code_suggestions/completions`, { headers, body: JSON.stringify(request) }, ); await handleFetchError(response, 'Code Suggestions'); const data = await response.json(); return { ...data, status: response.status }; } async *getStreamingCodeSuggestions( request: CodeSuggestionRequest, ): AsyncGenerator { if (!this.#token) { throw new Error('Token needs to be provided to stream code suggestions'); } const headers = { ...this.#getDefaultHeaders(this.#token), 'Content-Type': 'application/json', }; yield* this.#lsFetch.streamFetch( `${this.#baseURL}/api/v4/code_suggestions/completions`, JSON.stringify(request), headers, ); } async fetchFromApi(request: ApiRequest): Promise { if (!this.#token) { return Promise.reject(new Error('Token needs to be provided to authorise API request.')); } if ( request.supportedSinceInstanceVersion && !this.#instanceVersionHigherOrEqualThen(request.supportedSinceInstanceVersion.version) ) { return Promise.reject( new InvalidInstanceVersionError( `Can't ${request.supportedSinceInstanceVersion.resourceName} until your instance is upgraded to ${request.supportedSinceInstanceVersion.version} or higher.`, ), ); } if (request.type === 'graphql') { return this.#graphqlRequest(request.query, request.variables); } switch (request.method) { case 'GET': return this.#fetch(request.path, request.searchParams, 'resource', request.headers); case 'POST': return this.#postFetch(request.path, 'resource', request.body, request.headers); default: // the type assertion is necessary because TS doesn't expect any other types throw new Error(`Unknown request type ${(request as ApiRequest).type}`); } } async connectToCable(): Promise { const headers = this.#getDefaultHeaders(this.#token); const websocketOptions = { headers: { ...headers, Origin: this.#baseURL, }, }; return connectToCable(this.#baseURL, websocketOptions); } async #graphqlRequest( document: RequestDocument, variables?: V, ): Promise { const ensureEndsWithSlash = (url: string) => url.replace(/\/?$/, '/'); const endpoint = new URL('./api/graphql', ensureEndsWithSlash(this.#baseURL)).href; // supports GitLab instances that are on a custom path, e.g. ""https://example.com/gitlab"" const graphqlFetch = async ( input: RequestInfo | URL, init?: RequestInit, ): Promise => { const url = input instanceof URL ? input.toString() : input; return this.#lsFetch.post(url, { ...init, headers: { ...headers, ...init?.headers }, }); }; const headers = this.#getDefaultHeaders(this.#token); const client = new GraphQLClient(endpoint, { headers, fetch: graphqlFetch, }); return client.request(document, variables); } async #fetch( apiResourcePath: string, query: Record = {}, resourceName = 'resource', headers?: Record, ): Promise { const url = `${this.#baseURL}/api/v4${apiResourcePath}${createQueryString(query)}`; const result = await this.#lsFetch.get(url, { headers: { ...this.#getDefaultHeaders(this.#token), ...headers }, }); await handleFetchError(result, resourceName); return result.json() as Promise; } async #postFetch( apiResourcePath: string, resourceName = 'resource', body?: unknown, headers?: Record, ): Promise { const url = `${this.#baseURL}/api/v4${apiResourcePath}`; const response = await this.#lsFetch.post(url, { headers: { 'Content-Type': 'application/json', ...this.#getDefaultHeaders(this.#token), ...headers, }, body: JSON.stringify(body), }); await handleFetchError(response, resourceName); return response.json() as Promise; } #getDefaultHeaders(token?: string) { return { Authorization: `Bearer ${token}`, 'User-Agent': `code-completions-language-server-experiment (${this.#clientInfo?.name}:${this.#clientInfo?.version})`, 'X-Gitlab-Language-Server-Version': getLanguageServerVersion(), }; } #instanceVersionHigherOrEqualThen(version: string): boolean { if (!this.#instanceVersion) return false; return semverCompare(this.#instanceVersion, version) >= 0; } async #getGitLabInstanceVersion(): Promise { if (!this.#token) { return ''; } const headers = this.#getDefaultHeaders(this.#token); const response = await this.#lsFetch.get(`${this.#baseURL}/api/v4/version`, { headers, }); const { version } = await response.json(); return version; } get instanceVersion() { return this.#instanceVersion; } } References: - packages/webview_duo_chat/src/plugin/port/platform/gitlab_platform.ts:11 - packages/webview_duo_chat/src/plugin/port/test_utils/create_fake_fetch_from_api.ts:10" You are a code assistant,Definition of 'getForActiveAccount' in file packages/webview_duo_chat/src/plugin/port/platform/gitlab_platform.ts in project gitlab-lsp,"Definition: getForActiveAccount(): Promise; /** * 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; getForAllAccounts(): Promise; /** * Returns GitLabPlatformForAccount if there is a SaaS account added. Otherwise returns undefined. */ getForSaaSAccount(): Promise; } References:" You are a code assistant,Definition of 'TestCompletionProcessor' in file src/common/suggestion_client/post_processors/post_processor_pipeline.test.ts in project gitlab-lsp,"Definition: class TestCompletionProcessor extends PostProcessor { async processStream( _context: IDocContext, input: StreamingCompletionResponse, ): Promise { return input; } async processCompletion( _context: IDocContext, input: SuggestionOption[], ): Promise { return input.map((option) => ({ ...option, text: `${option.text} processed` })); } } pipeline.addProcessor(new TestCompletionProcessor()); const completionInput: SuggestionOption[] = [{ text: 'option1', uniqueTrackingId: '1' }]; const result = await pipeline.run({ documentContext: mockContext, input: completionInput, type: 'completion', }); expect(result).toEqual([{ text: 'option1 processed', uniqueTrackingId: '1' }]); }); test('should chain multiple processors correctly for stream input', async () => { class Processor1 extends PostProcessor { async processStream( _context: IDocContext, input: StreamingCompletionResponse, ): Promise { return { ...input, completion: `${input.completion} [1]` }; } async processCompletion( _context: IDocContext, input: SuggestionOption[], ): Promise { return input; } } class Processor2 extends PostProcessor { async processStream( _context: IDocContext, input: StreamingCompletionResponse, ): Promise { return { ...input, completion: `${input.completion} [2]` }; } async processCompletion( _context: IDocContext, input: SuggestionOption[], ): Promise { return input; } } pipeline.addProcessor(new Processor1()); pipeline.addProcessor(new Processor2()); const streamInput: StreamingCompletionResponse = { id: '1', completion: 'test', done: false }; const result = await pipeline.run({ documentContext: mockContext, input: streamInput, type: 'stream', }); expect(result).toEqual({ id: '1', completion: 'test [1] [2]', done: false }); }); test('should chain multiple processors correctly for completion input', async () => { class Processor1 extends PostProcessor { async processStream( _context: IDocContext, input: StreamingCompletionResponse, ): Promise { return input; } async processCompletion( _context: IDocContext, input: SuggestionOption[], ): Promise { return input.map((option) => ({ ...option, text: `${option.text} [1]` })); } } class Processor2 extends PostProcessor { async processStream( _context: IDocContext, input: StreamingCompletionResponse, ): Promise { return input; } async processCompletion( _context: IDocContext, input: SuggestionOption[], ): Promise { return input.map((option) => ({ ...option, text: `${option.text} [2]` })); } } pipeline.addProcessor(new Processor1()); pipeline.addProcessor(new Processor2()); const completionInput: SuggestionOption[] = [{ text: 'option1', uniqueTrackingId: '1' }]; const result = await pipeline.run({ documentContext: mockContext, input: completionInput, type: 'completion', }); expect(result).toEqual([{ text: 'option1 [1] [2]', uniqueTrackingId: '1' }]); }); test('should throw an error for unexpected type', async () => { class TestProcessor extends PostProcessor { async processStream( _context: IDocContext, input: StreamingCompletionResponse, ): Promise { return input; } async processCompletion( _context: IDocContext, input: SuggestionOption[], ): Promise { 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: - src/common/suggestion_client/post_processors/post_processor_pipeline.test.ts:71" You are a code assistant,Definition of 'destroy' in file src/node/fetch.ts in project gitlab-lsp,"Definition: async destroy(): Promise { this.#proxy?.destroy(); } async fetch(input: RequestInfo | URL, init?: RequestInit): Promise { 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 { let buffer = ''; const decoder = new TextDecoder(); async function* readStream( stream: ReadableStream, ): AsyncGenerator { 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 { 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: '' } : {}), ...(cert ? { cert: '' } : {}), ...(key ? { key: '' } : {}), }; } } References:" You are a code assistant,Definition of 'constructor' in file src/common/webview/webview_metadata_provider.ts in project gitlab-lsp,"Definition: constructor(accessInfoProviders: WebviewLocationService, plugins: Set) { this.#accessInfoProviders = accessInfoProviders; this.#plugins = plugins; } getMetadata(): WebviewMetadata[] { return Array.from(this.#plugins).map((plugin) => ({ id: plugin.id, title: plugin.title, uris: this.#accessInfoProviders.resolveUris(plugin.id), })); } } References:" You are a code assistant,Definition of 'findFilesForDirectory' in file src/common/services/fs/dir.ts in project gitlab-lsp,"Definition: findFilesForDirectory(_args: DirectoryToSearch): Promise; setupFileWatcher(workspaceFolder: WorkspaceFolder, changeHandler: FileChangeHandler): void; } export const DirectoryWalker = createInterfaceId('DirectoryWalker'); @Injectable(DirectoryWalker, []) export class DefaultDirectoryWalker { /** * Returns a list of files in the specified directory that match the specified criteria. * The returned files will be the full paths to the files, they also will be in the form of URIs. * Example: [' file:///path/to/file.txt', 'file:///path/to/another/file.js'] */ // eslint-disable-next-line @typescript-eslint/no-unused-vars findFilesForDirectory(_args: DirectoryToSearch): Promise { return Promise.resolve([]); } // eslint-disable-next-line @typescript-eslint/no-unused-vars setupFileWatcher(workspaceFolder: WorkspaceFolder, changeHandler: FileChangeHandler) { throw new Error(`${workspaceFolder} ${changeHandler} not implemented`); } } References:" You are a code assistant,Definition of 'CHECKS_PER_FEATURE' in file src/common/feature_state/feature_state_management_types.ts in project gitlab-lsp,"Definition: export const CHECKS_PER_FEATURE: { [key in Feature]: StateCheckId[] } = { [CODE_SUGGESTIONS]: CODE_SUGGESTIONS_CHECKS_PRIORITY_ORDERED, [CHAT]: CHAT_CHECKS_PRIORITY_ORDERED, // [WORKFLOW]: [], }; References:" You are a code assistant,Definition of 'isClientFlagEnabled' in file src/common/feature_flags.ts in project gitlab-lsp,"Definition: isClientFlagEnabled(name: ClientFeatureFlags): boolean { const value = this.#configService.get('client.featureFlags')?.[name]; return value ?? false; } } References:" You are a code assistant,Definition of 'GetRequest' in file packages/webview_duo_chat/src/plugin/port/platform/web_ide.ts in project gitlab-lsp,"Definition: export interface GetRequest<_TReturnType> extends GetRequestBase<_TReturnType> { type: 'rest'; } export interface GetBufferRequest extends GetRequestBase { type: 'rest-buffer'; } export interface GraphQLRequest<_TReturnType> { type: 'graphql'; query: string; /** Options passed to the GraphQL query */ variables: Record; } 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; /* 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 'constructor' in file src/common/tracking/instance_tracker.ts in project gitlab-lsp,"Definition: constructor(api: GitLabApiClient, configService: ConfigService) { this.#configService = configService; this.#configService.onConfigChange((config) => this.#reconfigure(config)); this.#api = api; } #reconfigure(config: IConfig) { const { baseUrl } = config.client; 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(`Instance Telemetry: ${TELEMETRY_DISABLED_WARNING_MSG}`); } else if (enabled === true) { log.info(`Instance Telemetry: ${TELEMETRY_ENABLED_MSG}`); } } if (baseUrl) { this.#options.baseUrl = baseUrl; } if (actions) { this.#options.actions = actions; } } isEnabled(): boolean { return Boolean(this.#options.enabled); } public setCodeSuggestionsContext( uniqueTrackingId: string, context: Partial, ) { if (this.#circuitBreaker.isOpen()) { return; } const { language, isStreaming } = context; // 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); this.#codeSuggestionsContextMap.set(uniqueTrackingId, { is_streaming: isStreaming, language, timestamp: new Date().toISOString(), }); if (this.#isStreamingSuggestion(uniqueTrackingId)) return; this.#codeSuggestionStates.set(uniqueTrackingId, TRACKING_EVENTS.REQUESTED); this.#trackCodeSuggestionsEvent(TRACKING_EVENTS.REQUESTED, uniqueTrackingId).catch((e) => log.warn('Instance telemetry: Could not track telemetry', e), ); log.debug(`Instance telemetry: New suggestion ${uniqueTrackingId} has been requested`); } async updateCodeSuggestionsContext( uniqueTrackingId: string, contextUpdate: Partial, ) { if (this.#circuitBreaker.isOpen()) { return; } if (this.#isStreamingSuggestion(uniqueTrackingId)) return; const context = this.#codeSuggestionsContextMap.get(uniqueTrackingId); const { model, suggestionOptions, isStreaming } = contextUpdate; if (context) { if (model) { context.language = model.lang ?? null; } if (suggestionOptions?.length) { context.suggestion_size = InstanceTracker.#suggestionSize(suggestionOptions); } if (typeof isStreaming === 'boolean') { context.is_streaming = isStreaming; } this.#codeSuggestionsContextMap.set(uniqueTrackingId, context); } } updateSuggestionState(uniqueTrackingId: string, newState: TRACKING_EVENTS): void { if (this.#circuitBreaker.isOpen()) { return; } if (!this.isEnabled()) return; if (this.#isStreamingSuggestion(uniqueTrackingId)) return; const state = this.#codeSuggestionStates.get(uniqueTrackingId); if (!state) { log.debug(`Instance telemetry: The suggestion with ${uniqueTrackingId} can't be found`); return; } const allowedTransitions = nonStreamingSuggestionStateGraph.get(state); if (!allowedTransitions) { log.debug( `Instance telemetry: The suggestion's ${uniqueTrackingId} state ${state} can't be found in state graph`, ); return; } if (!allowedTransitions.includes(newState)) { log.debug( `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( `Instance telemetry: Conditionally allowing transition to accepted state for ${uniqueTrackingId}`, ); } this.#codeSuggestionStates.set(uniqueTrackingId, newState); this.#trackCodeSuggestionsEvent(newState, uniqueTrackingId).catch((e) => log.warn('Instance telemetry: Could not track telemetry', e), ); log.debug(`Instance telemetry: ${uniqueTrackingId} transisted from ${state} to ${newState}`); } async #trackCodeSuggestionsEvent(eventType: TRACKING_EVENTS, uniqueTrackingId: string) { const event = INSTANCE_TRACKING_EVENTS_MAP[eventType]; if (!event) { return; } try { const { language, suggestion_size } = this.#codeSuggestionsContextMap.get(uniqueTrackingId) ?? {}; await this.#api.fetchFromApi({ type: 'rest', method: 'POST', path: '/usage_data/track_event', body: { event, additional_properties: { unique_tracking_id: uniqueTrackingId, timestamp: new Date().toISOString(), language, suggestion_size, }, }, supportedSinceInstanceVersion: { resourceName: 'track instance telemetry', version: '17.2.0', }, }); this.#circuitBreaker.success(); } catch (error) { if (error instanceof InvalidInstanceVersionError) { if (this.#invalidInstanceMsgLogged) return; this.#invalidInstanceMsgLogged = true; } log.warn(`Instance telemetry: Failed to track event: ${eventType}`, error); this.#circuitBreaker.error(); } } rejectOpenedSuggestions() { log.debug(`Instance Telemetry: Reject all opened suggestions`); this.#codeSuggestionStates.forEach((state, uniqueTrackingId) => { if (endStates.includes(state)) { return; } this.updateSuggestionState(uniqueTrackingId, TRACKING_EVENTS.REJECTED); }); } static #suggestionSize(options: SuggestionOption[]): number { const countLines = (text: string) => (text ? text.split('\n').length : 0); return Math.max(...options.map(({ text }) => countLines(text))); } #isStreamingSuggestion(uniqueTrackingId: string): boolean { return Boolean(this.#codeSuggestionsContextMap.get(uniqueTrackingId)?.is_streaming); } } References:" You are a code assistant,Definition of 'runBuild' in file scripts/watcher/watch.ts in project gitlab-lsp,"Definition: async function runBuild() { try { await runScript('npm run build'); } catch (e) { console.error(errorColor, 'Script execution failed'); console.error(e); return false; } console.log(successColor, 'Compiled successfully'); return true; } /** * Publish to yalc so the vscode extension can consume the language * server changes. */ async function postBuildVscCodeYalcPublish(vsCodePath: string) { const commandCwd = resolvePath(cwd(), vsCodePath); await runScript('npx yalc@1.0.0-pre.53 publish'); console.log(successColor, 'Pushed to yalc'); await runScript('npx yalc@1.0.0-pre.53 add @gitlab-org/gitlab-lsp', commandCwd); } /** * additionally copy to desktop assets so the developer * does not need to restart the extension host */ async function postBuildVSCodeCopyFiles(vsCodePath: string) { const desktopAssetsDir = `${vsCodePath}/dist-desktop/assets/language-server`; try { await copy(resolvePath(`${cwd()}/out`), desktopAssetsDir); console.log(successColor, 'Copied files to vscode extension'); } catch (error) { console.error(errorColor, 'Whoops, something went wrong...'); console.error(error); } } function postBuild() { const editor = process.argv.find((arg) => arg.startsWith('--editor='))?.split('=')[1]; if (editor === 'vscode') { const vsCodePath = process.env.VSCODE_EXTENSION_RELATIVE_PATH ?? '../gitlab-vscode-extension'; return [postBuildVscCodeYalcPublish(vsCodePath), postBuildVSCodeCopyFiles(vsCodePath)]; } console.warn('No editor specified, skipping post-build steps'); return [new Promise((resolve) => resolve())]; } async function run() { const watchMsg = () => console.log(textColor, `Watching for file changes on ${dir}`); const now = performance.now(); const buildSuccessful = await runBuild(); if (!buildSuccessful) return watchMsg(); await Promise.all(postBuild()); console.log(successColor, `Finished in ${Math.round(performance.now() - now)}ms`); watchMsg(); } let timeout: NodeJS.Timeout | null = null; const dir = './src'; const watcher = chokidar.watch(dir, { ignored: /(^|[/\\])\../, // ignore dotfiles persistent: true, }); let isReady = false; watcher .on('add', async (filePath) => { if (!isReady) return; console.log(`File ${filePath} has been added`); await run(); }) .on('change', async (filePath) => { if (!isReady) return; console.log(`File ${filePath} has been changed`); if (timeout) clearTimeout(timeout); // We debounce the run function on change events in the case of many files being changed at once timeout = setTimeout(async () => { await run(); }, 1000); }) .on('ready', async () => { await run(); isReady = true; }) .on('unlink', (filePath) => console.log(`File ${filePath} has been removed`)); console.log(textColor, 'Starting watcher...'); References: - scripts/watcher/watch.ts:65" You are a code assistant,Definition of 'dispose' in file packages/webview_duo_chat/src/plugin/chat_controller.ts in project gitlab-lsp,"Definition: dispose(): void { this.#subscriptions.dispose(); } #setupMessageHandlers() { this.#subscriptions.add( this.#webviewMessageBus.onNotification('newPrompt', async (message) => { const record = GitLabChatRecord.buildWithContext({ role: 'user', content: message.record.content, }); await this.#processNewUserRecord(record); }), ); } async #processNewUserRecord(record: GitLabChatRecord) { if (!record.content) return; await this.#sendNewPrompt(record); if (record.errors.length > 0) { this.#extensionMessageBus.sendNotification('showErrorMessage', { message: record.errors[0], }); return; } await this.#addToChat(record); if (record.type === 'newConversation') return; const responseRecord = new GitLabChatRecord({ role: 'assistant', state: 'pending', requestId: record.requestId, }); await this.#addToChat(responseRecord); try { await this.#api.subscribeToUpdates(this.#subscriptionUpdateHandler.bind(this), record.id); } catch (err) { // TODO: log error } // Fallback if websocket fails or disabled. await Promise.all([this.#refreshRecord(record), this.#refreshRecord(responseRecord)]); } async #subscriptionUpdateHandler(data: AiCompletionResponseMessageType) { const record = this.#findRecord(data); if (!record) return; record.update({ chunkId: data.chunkId, content: data.content, contentHtml: data.contentHtml, extras: data.extras, timestamp: data.timestamp, errors: data.errors, }); record.state = 'ready'; this.#webviewMessageBus.sendNotification('updateRecord', record); } // async #restoreHistory() { // this.chatHistory.forEach((record) => { // this.#webviewMessageBus.sendNotification('newRecord', record); // }, this); // } async #addToChat(record: GitLabChatRecord) { this.chatHistory.push(record); this.#webviewMessageBus.sendNotification('newRecord', record); } async #sendNewPrompt(record: GitLabChatRecord) { if (!record.content) throw new Error('Trying to send prompt without content.'); try { const actionResponse = await this.#api.processNewUserPrompt( record.content, record.id, record.context?.currentFile, ); record.update(actionResponse.aiAction); } catch (err) { // eslint-disable-next-line @typescript-eslint/no-explicit-any record.update({ errors: [`API error: ${(err as any).response.errors[0].message}`] }); } } async #refreshRecord(record: GitLabChatRecord) { if (!record.requestId) { throw Error('requestId must be present!'); } const apiResponse = await this.#api.pullAiMessage(record.requestId, record.role); if (apiResponse.type !== 'error') { record.update({ content: apiResponse.content, contentHtml: apiResponse.contentHtml, extras: apiResponse.extras, timestamp: apiResponse.timestamp, }); } record.update({ errors: apiResponse.errors, state: 'ready' }); this.#webviewMessageBus.sendNotification('updateRecord', record); } #findRecord(data: { requestId: string; role: string }) { return this.chatHistory.find( (r) => r.requestId === data.requestId && r.role.toLowerCase() === data.role.toLowerCase(), ); } } References:" You are a code assistant,Definition of 'streamFetch' in file src/common/fetch.ts in project gitlab-lsp,"Definition: streamFetch(url: string, body: string, headers: FetchHeaders): AsyncGenerator; } export const LsFetch = createInterfaceId('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 {} async destroy(): Promise {} async fetch(input: RequestInfo | URL, init?: RequestInit): Promise { 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 { // Stub. Should delegate to the node or browser fetch implementations throw new Error('Not implemented'); yield ''; } async delete(input: RequestInfo | URL, init?: RequestInit): Promise { return this.fetch(input, this.updateRequestInit('DELETE', init)); } async get(input: RequestInfo | URL, init?: RequestInit): Promise { return this.fetch(input, this.updateRequestInit('GET', init)); } async post(input: RequestInfo | URL, init?: RequestInit): Promise { return this.fetch(input, this.updateRequestInit('POST', init)); } async put(input: RequestInfo | URL, init?: RequestInit): Promise { return this.fetch(input, this.updateRequestInit('PUT', init)); } async fetchBase(input: RequestInfo | URL, init?: RequestInit): Promise { // 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 'Messages' in file packages/webview_duo_chat/src/contract.ts in project gitlab-lsp,"Definition: export type Messages = CreatePluginMessageMap<{ pluginToWebview: { notifications: { newRecord: Record; updateRecord: Record; setLoadingState: boolean; cleanChat: undefined; }; }; webviewToPlugin: { notifications: { onReady: undefined; cleanChat: undefined; newPrompt: { record: { content: string; }; }; trackFeedback: { data?: { extendedTextFeedback: string | null; feedbackChoices: Array | null; }; }; }; }; pluginToExtension: { notifications: { showErrorMessage: { message: string; }; }; }; }>; References:" You are a code assistant,Definition of 'constructor' in file packages/lib_webview_client/src/bus/provider/socket_io_message_bus.ts in project gitlab-lsp,"Definition: constructor(socket: Socket) { this.#socket = socket; this.#setupSocketEventHandlers(); } async sendNotification( messageType: T, payload?: TMessages['outbound']['notifications'][T], ): Promise { this.#socket.emit(SOCKET_NOTIFICATION_CHANNEL, { type: messageType, payload }); } sendRequest( type: T, payload?: TMessages['outbound']['requests'][T]['params'], ): Promise> { const requestId = generateRequestId(); let timeout: NodeJS.Timeout | undefined; return new Promise((resolve, reject) => { const pendingRequestDisposable = this.#pendingRequests.register( requestId, (value: ExtractRequestResult) => { resolve(value); clearTimeout(timeout); pendingRequestDisposable.dispose(); }, ); timeout = setTimeout(() => { pendingRequestDisposable.dispose(); reject(new Error('Request timed out')); }, REQUEST_TIMEOUT_MS); this.#socket.emit(SOCKET_REQUEST_CHANNEL, { requestId, type, payload, }); }); } onNotification( messageType: T, callback: (payload: TMessages['inbound']['notifications'][T]) => void, ): Disposable { return this.#notificationHandlers.register(messageType, callback); } onRequest( type: T, handler: ( payload: TMessages['inbound']['requests'][T]['params'], ) => Promise>, ): Disposable { return this.#requestHandlers.register(type, handler); } dispose() { this.#socket.off(SOCKET_NOTIFICATION_CHANNEL, this.#handleNotificationMessage); this.#socket.off(SOCKET_REQUEST_CHANNEL, this.#handleRequestMessage); this.#socket.off(SOCKET_RESPONSE_CHANNEL, this.#handleResponseMessage); this.#notificationHandlers.dispose(); this.#requestHandlers.dispose(); this.#pendingRequests.dispose(); } #setupSocketEventHandlers = () => { this.#socket.on(SOCKET_NOTIFICATION_CHANNEL, this.#handleNotificationMessage); this.#socket.on(SOCKET_REQUEST_CHANNEL, this.#handleRequestMessage); this.#socket.on(SOCKET_RESPONSE_CHANNEL, this.#handleResponseMessage); }; #handleNotificationMessage = async (message: { type: keyof TMessages['inbound']['notifications'] & string; payload: unknown; }) => { await this.#notificationHandlers.handle(message.type, message.payload); }; #handleRequestMessage = async (message: { requestId: string; event: keyof TMessages['inbound']['requests'] & string; payload: unknown; }) => { const response = await this.#requestHandlers.handle(message.event, message.payload); this.#socket.emit(SOCKET_RESPONSE_CHANNEL, { requestId: message.requestId, payload: response, }); }; #handleResponseMessage = async (message: { requestId: string; payload: unknown }) => { await this.#pendingRequests.handle(message.requestId, message.payload); }; } References:" You are a code assistant,Definition of 'register' in file packages/lib_handler_registry/src/registry/hashed_registry.ts in project gitlab-lsp,"Definition: 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): Promise> { const hash = this.#hashFunc(key); return this.#basicRegistry.handle(hash, ...args); } dispose() { this.#basicRegistry.dispose(); } } References:" You are a code assistant,Definition of 'getFile' in file src/common/git/repository.ts in project gitlab-lsp,"Definition: getFile(fileUri: string): RepositoryFile | undefined { return this.#files.get(fileUri); } removeFile(fileUri: string): void { this.#files.delete(fileUri); } getFiles(): Map { return this.#files; } dispose(): void { this.#ignoreManager.dispose(); this.#files.clear(); } } References:" You are a code assistant,Definition of 'DetailedError' in file src/common/fetch_error.ts in project gitlab-lsp,"Definition: export interface DetailedError extends Error { readonly details: Record; } 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:" You are a code assistant,Definition of 'initializeHttpServer' in file src/node/setup_http.ts in project gitlab-lsp,"Definition: async function initializeHttpServer(webviewIds: WebviewId[], logger: Logger) { const { shutdown: fastifyShutdown, server } = await createFastifyHttpServer({ plugins: [ createFastifySocketIoPlugin(), createWebviewPlugin({ webviewIds, }), { plugin: async (app) => { app.get('/', () => { return { message: 'Hello, world!' }; }); }, }, ], logger, }); const handleGracefulShutdown = async (signal: string) => { logger.info(`Received ${signal}. Shutting down...`); server.io.close(); await fastifyShutdown(); logger.info('Shutdown complete. Exiting process.'); process.exit(0); }; process.on('SIGTERM', handleGracefulShutdown); process.on('SIGINT', handleGracefulShutdown); return server; } References: - src/node/setup_http.ts:15" You are a code assistant,Definition of 'withKnownWebview' in file src/node/webview/handlers/webview_handler.ts in project gitlab-lsp,"Definition: export const withKnownWebview = ( webviewIds: WebviewId[], handler: RouteHandlerMethod, ): RouteHandlerMethod => { return function (this: FastifyInstance, request: FastifyRequest, reply: FastifyReply) { const { webviewId } = request.params as { webviewId: WebviewId }; if (!webviewIds.includes(webviewId)) { return reply.status(404).send(`Unknown webview: ${webviewId}`); } return handler.call(this, request, reply); }; }; References: - src/node/webview/handlers/webview_handler.ts:10" You are a code assistant,Definition of 'ExtensionMessageHandlerRegistry' in file src/common/webview/extension/utils/extension_message_handler_registry.ts in project gitlab-lsp,"Definition: export class ExtensionMessageHandlerRegistry extends HashedRegistry { constructor() { super((key) => `${key.webviewId}:${key.type}`); } } References: - src/common/webview/extension/types.ts:9 - src/common/webview/extension/extension_connection_message_bus_provider.ts:56 - src/common/webview/extension/extension_connection_message_bus_provider.ts:55 - src/common/webview/extension/extension_connection_message_bus.test.ts:25 - src/common/webview/extension/extension_connection_message_bus_provider.ts:36 - src/common/webview/extension/types.ts:10 - src/common/webview/extension/extension_connection_message_bus.test.ts:24 - src/common/webview/extension/extension_connection_message_bus.test.ts:16 - src/common/webview/extension/handlers/handle_notification_message.ts:6 - src/common/webview/extension/extension_connection_message_bus.test.ts:15 - src/common/webview/extension/handlers/handle_request_message.ts:6 - src/common/webview/extension/extension_connection_message_bus_provider.ts:34" You are a code assistant,Definition of 'SocketEvents' in file packages/lib_webview_client/src/bus/provider/socket_io_message_bus.ts in project gitlab-lsp,"Definition: export type SocketEvents = | typeof SOCKET_NOTIFICATION_CHANNEL | typeof SOCKET_REQUEST_CHANNEL | typeof SOCKET_RESPONSE_CHANNEL; export class SocketIoMessageBus implements MessageBus { #notificationHandlers = new SimpleRegistry(); #requestHandlers = new SimpleRegistry(); #pendingRequests = new SimpleRegistry(); #socket: Socket; constructor(socket: Socket) { this.#socket = socket; this.#setupSocketEventHandlers(); } async sendNotification( messageType: T, payload?: TMessages['outbound']['notifications'][T], ): Promise { this.#socket.emit(SOCKET_NOTIFICATION_CHANNEL, { type: messageType, payload }); } sendRequest( type: T, payload?: TMessages['outbound']['requests'][T]['params'], ): Promise> { const requestId = generateRequestId(); let timeout: NodeJS.Timeout | undefined; return new Promise((resolve, reject) => { const pendingRequestDisposable = this.#pendingRequests.register( requestId, (value: ExtractRequestResult) => { resolve(value); clearTimeout(timeout); pendingRequestDisposable.dispose(); }, ); timeout = setTimeout(() => { pendingRequestDisposable.dispose(); reject(new Error('Request timed out')); }, REQUEST_TIMEOUT_MS); this.#socket.emit(SOCKET_REQUEST_CHANNEL, { requestId, type, payload, }); }); } onNotification( messageType: T, callback: (payload: TMessages['inbound']['notifications'][T]) => void, ): Disposable { return this.#notificationHandlers.register(messageType, callback); } onRequest( type: T, handler: ( payload: TMessages['inbound']['requests'][T]['params'], ) => Promise>, ): Disposable { return this.#requestHandlers.register(type, handler); } dispose() { this.#socket.off(SOCKET_NOTIFICATION_CHANNEL, this.#handleNotificationMessage); this.#socket.off(SOCKET_REQUEST_CHANNEL, this.#handleRequestMessage); this.#socket.off(SOCKET_RESPONSE_CHANNEL, this.#handleResponseMessage); this.#notificationHandlers.dispose(); this.#requestHandlers.dispose(); this.#pendingRequests.dispose(); } #setupSocketEventHandlers = () => { this.#socket.on(SOCKET_NOTIFICATION_CHANNEL, this.#handleNotificationMessage); this.#socket.on(SOCKET_REQUEST_CHANNEL, this.#handleRequestMessage); this.#socket.on(SOCKET_RESPONSE_CHANNEL, this.#handleResponseMessage); }; #handleNotificationMessage = async (message: { type: keyof TMessages['inbound']['notifications'] & string; payload: unknown; }) => { await this.#notificationHandlers.handle(message.type, message.payload); }; #handleRequestMessage = async (message: { requestId: string; event: keyof TMessages['inbound']['requests'] & string; payload: unknown; }) => { const response = await this.#requestHandlers.handle(message.event, message.payload); this.#socket.emit(SOCKET_RESPONSE_CHANNEL, { requestId: message.requestId, payload: response, }); }; #handleResponseMessage = async (message: { requestId: string; payload: unknown }) => { await this.#pendingRequests.handle(message.requestId, message.payload); }; } References: - packages/lib_webview_client/src/bus/provider/socket_io_message_bus.test.ts:178" You are a code assistant,Definition of 'getSuggestions' in file src/common/suggestion_client/suggestion_client.ts in project gitlab-lsp,"Definition: getSuggestions(context: SuggestionContext): Promise; } export type SuggestionClientFn = SuggestionClient['getSuggestions']; export type SuggestionClientMiddleware = ( context: SuggestionContext, next: SuggestionClientFn, ) => ReturnType; References:" You are a code assistant,Definition of 'isOpen' in file src/common/circuit_breaker/exponential_backoff_circuit_breaker.ts in project gitlab-lsp,"Definition: isOpen() { return this.#state === CircuitBreakerState.OPEN; } 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) }; } #getBackoffTime() { return Math.min( this.#initialBackoffMs * this.#backoffMultiplier ** (this.#errorCount - 1), this.#maxBackoffMs, ); } } References:" You are a code assistant,Definition of 'Messages' in file packages/lib_webview/src/events/webview_runtime_message_bus.ts in project gitlab-lsp,"Definition: 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 {} References:" You are a code assistant,Definition of 'TelemetryRequest' in file src/common/api_types.ts in project gitlab-lsp,"Definition: export interface TelemetryRequest { event: string; additional_properties: { unique_tracking_id: string; language?: string; suggestion_size?: number; timestamp: string; }; } References:" You are a code assistant,Definition of 'StreamWithId' in file src/common/suggestion/streaming_handler.ts in project gitlab-lsp,"Definition: export interface StreamWithId { /** unique stream ID */ id: string; } export interface StreamingCompletionResponse { /** stream ID taken from the request, all stream responses for one request will have the request's stream ID */ id: string; /** most up-to-date generated suggestion, each time LS receives a chunk from LLM, it adds it to this string -> the client doesn't have to join the stream */ completion?: string; done: boolean; } export const STREAMING_COMPLETION_RESPONSE_NOTIFICATION = 'streamingCompletionResponse'; export const CANCEL_STREAMING_COMPLETION_NOTIFICATION = 'cancelStreaming'; export const StreamingCompletionResponse = new NotificationType( STREAMING_COMPLETION_RESPONSE_NOTIFICATION, ); export const CancelStreaming = new NotificationType( CANCEL_STREAMING_COMPLETION_NOTIFICATION, ); export interface StartStreamParams { api: GitLabApiClient; circuitBreaker: CircuitBreaker; connection: Connection; documentContext: IDocContext; parser: TreeSitterParser; postProcessorPipeline: PostProcessorPipeline; streamId: string; tracker: TelemetryTracker; uniqueTrackingId: string; userInstruction?: string; generationType?: GenerationType; additionalContexts?: AdditionalContext[]; } export class DefaultStreamingHandler { #params: StartStreamParams; constructor(params: StartStreamParams) { this.#params = params; } async startStream() { return startStreaming(this.#params); } } const startStreaming = async ({ additionalContexts, api, circuitBreaker, connection, documentContext, parser, postProcessorPipeline, streamId, tracker, uniqueTrackingId, userInstruction, generationType, }: StartStreamParams) => { const language = parser.getLanguageNameForFile(documentContext.fileRelativePath); tracker.setCodeSuggestionsContext(uniqueTrackingId, { documentContext, additionalContexts, source: SuggestionSource.network, language, isStreaming: true, }); let streamShown = false; let suggestionProvided = false; let streamCancelledOrErrored = false; const cancellationTokenSource = new CancellationTokenSource(); const disposeStopStreaming = connection.onNotification(CancelStreaming, (stream) => { if (stream.id === streamId) { streamCancelledOrErrored = true; cancellationTokenSource.cancel(); if (streamShown) { tracker.updateSuggestionState(uniqueTrackingId, TRACKING_EVENTS.REJECTED); } else { tracker.updateSuggestionState(uniqueTrackingId, TRACKING_EVENTS.CANCELLED); } } }); const cancellationToken = cancellationTokenSource.token; const endStream = async () => { await connection.sendNotification(StreamingCompletionResponse, { id: streamId, done: true, }); if (!streamCancelledOrErrored) { tracker.updateSuggestionState(uniqueTrackingId, TRACKING_EVENTS.STREAM_COMPLETED); if (!suggestionProvided) { tracker.updateSuggestionState(uniqueTrackingId, TRACKING_EVENTS.NOT_PROVIDED); } } }; circuitBreaker.success(); const request: CodeSuggestionRequest = { prompt_version: 1, project_path: '', project_id: -1, current_file: { content_above_cursor: documentContext.prefix, content_below_cursor: documentContext.suffix, file_name: documentContext.fileRelativePath, }, intent: 'generation', stream: true, ...(additionalContexts?.length && { context: additionalContexts, }), ...(userInstruction && { user_instruction: userInstruction, }), generation_type: generationType, }; const trackStreamStarted = once(() => { tracker.updateSuggestionState(uniqueTrackingId, TRACKING_EVENTS.STREAM_STARTED); }); const trackStreamShown = once(() => { tracker.updateSuggestionState(uniqueTrackingId, TRACKING_EVENTS.SHOWN); streamShown = true; }); try { for await (const response of api.getStreamingCodeSuggestions(request)) { if (cancellationToken.isCancellationRequested) { break; } if (circuitBreaker.isOpen()) { break; } trackStreamStarted(); const processedCompletion = await postProcessorPipeline.run({ documentContext, input: { id: streamId, completion: response, done: false }, type: 'stream', }); await connection.sendNotification(StreamingCompletionResponse, processedCompletion); if (response.replace(/\s/g, '').length) { trackStreamShown(); suggestionProvided = true; } } } catch (err) { circuitBreaker.error(); if (isFetchError(err)) { tracker.updateCodeSuggestionsContext(uniqueTrackingId, { status: err.status }); } tracker.updateSuggestionState(uniqueTrackingId, TRACKING_EVENTS.ERRORED); streamCancelledOrErrored = true; log.error('Error streaming code suggestions.', err); } finally { await endStream(); disposeStopStreaming.dispose(); cancellationTokenSource.dispose(); } }; References: - src/common/suggestion/streaming_handler.test.ts:343 - src/common/suggestion/streaming_handler.test.ts:395 - src/common/suggestion/streaming_handler.test.ts:212" You are a code assistant,Definition of 'B' in file packages/lib_di/src/index.test.ts in project gitlab-lsp,"Definition: interface B { b(): string; } interface C { c(): string; } const A = createInterfaceId('A'); const B = createInterfaceId('B'); const C = createInterfaceId('C'); @Injectable(A, []) class AImpl implements A { a = () => 'a'; } @Injectable(B, [A]) class BImpl implements B { #a: A; constructor(a: A) { this.#a = a; } b = () => `B(${this.#a.a()})`; } @Injectable(C, [A, B]) class CImpl implements C { #a: A; #b: B; constructor(a: A, b: B) { this.#a = a; this.#b = b; } c = () => `C(${this.#b.b()}, ${this.#a.a()})`; } let container: Container; beforeEach(() => { container = new Container(); }); describe('addInstances', () => { const O = createInterfaceId('object'); it('fails if the instance is not branded', () => { expect(() => container.addInstances({ say: 'hello' } as BrandedInstance)).toThrow( /invoked without branded object/, ); }); it('fails if the instance is already present', () => { const a = brandInstance(O, { a: 'a' }); const b = brandInstance(O, { b: 'b' }); expect(() => container.addInstances(a, b)).toThrow(/this ID is already in the container/); }); it('adds instance', () => { const instance = { a: 'a' }; const a = brandInstance(O, instance); container.addInstances(a); expect(container.get(O)).toBe(instance); }); }); describe('instantiate', () => { it('can instantiate three classes A,B,C', () => { container.instantiate(AImpl, BImpl, CImpl); const cInstance = container.get(C); expect(cInstance.c()).toBe('C(B(a), a)'); }); it('instantiates dependencies in multiple instantiate calls', () => { container.instantiate(AImpl); // the order is important for this test // we want to make sure that the stack in circular dependency discovery is being cleared // to try why this order is necessary, remove the `inStack.delete()` from // the `if (!cwd && instanceIds.includes(id))` condition in prod code expect(() => container.instantiate(CImpl, BImpl)).not.toThrow(); }); it('detects duplicate ids', () => { @Injectable(A, []) 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: - packages/lib_di/src/index.test.ts:40 - packages/lib_di/src/index.test.ts:42" You are a code assistant,Definition of 'createIsManagedFunc' in file packages/lib_webview/src/setup/transport/utils/event_filters.ts in project gitlab-lsp,"Definition: export const createIsManagedFunc = (managedInstances: ManagedInstances): IsManagedEventFilter => (event: TEvent) => managedInstances.has(event.webviewInstanceId); References: - packages/lib_webview/src/setup/transport/setup_transport.ts:15" You are a code assistant,Definition of 'ChatPlatformManager' in file packages/webview_duo_chat/src/plugin/chat_platform_manager.ts in project gitlab-lsp,"Definition: export class ChatPlatformManager implements GitLabPlatformManager { #client: GitLabApiClient; constructor(client: GitLabApiClient) { this.#client = client; } async getForActiveProject(): Promise { // return new ChatPlatformForProject(this.#client); return undefined; } async getForActiveAccount(): Promise { return new ChatPlatformForAccount(this.#client); } async getForAllAccounts(): Promise { return [new ChatPlatformForAccount(this.#client)]; } async getForSaaSAccount(): Promise { return new ChatPlatformForAccount(this.#client); } } References: - packages/webview_duo_chat/src/plugin/index.ts:18" You are a code assistant,Definition of 'FEATURE_STATE_CHANGE' in file src/common/notifications.ts in project gitlab-lsp,"Definition: export const FEATURE_STATE_CHANGE = '$/gitlab/featureStateChange'; export type FeatureStateNotificationParams = FeatureState[]; export const FeatureStateChangeNotificationType = new NotificationType(FEATURE_STATE_CHANGE); export interface TokenCheckNotificationParams { message?: string; } export const TokenCheckNotificationType = new NotificationType( 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( '$/gitlab/didChangeDocumentInActiveEditor', ); References:" You are a code assistant,Definition of 'DuoProjectPolicy' in file src/common/ai_context_management_2/policies/duo_project_policy.ts in project gitlab-lsp,"Definition: export const DuoProjectPolicy = createInterfaceId('AiFileContextProvider'); @Injectable(DuoProjectPolicy, [DuoProjectAccessChecker]) export class DefaultDuoProjectPolicy implements AiContextPolicy { constructor(private duoProjectAccessChecker: DuoProjectAccessChecker) {} 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: - src/common/ai_context_management_2/ai_policy_management.ts:24" You are a code assistant,Definition of 'greet' in file src/tests/fixtures/intent/empty_function/javascript.js in project gitlab-lsp,"Definition: 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:20 - 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" You are a code assistant,Definition of 'SetupWebviewRoutesOptions' in file src/node/webview/routes/webview_routes.ts in project gitlab-lsp,"Definition: type SetupWebviewRoutesOptions = { webviewIds: WebviewId[]; getWebviewResourcePath: (webviewId: WebviewId) => string; }; export const setupWebviewRoutes = async ( fastify: FastifyInstance, { webviewIds, getWebviewResourcePath }: SetupWebviewRoutesOptions, ): Promise => { await fastify.register( async (instance) => { instance.get('/', buildWebviewCollectionMetadataRequestHandler(webviewIds)); instance.get('/:webviewId', buildWebviewRequestHandler(webviewIds, getWebviewResourcePath)); // registering static resources across multiple webviews should not be done in parallel since we need to ensure that the fastify instance has been modified by the static files plugin for (const webviewId of webviewIds) { // eslint-disable-next-line no-await-in-loop await registerStaticPluginSafely(instance, { root: getWebviewResourcePath(webviewId), prefix: `/${webviewId}/`, }); } }, { prefix: '/webview' }, ); }; References: - src/node/webview/routes/webview_routes.ts:16" You are a code assistant,Definition of 'InterfaceId' in file packages/lib_di/src/index.ts in project gitlab-lsp,"Definition: export type InterfaceId = string & { __type: T }; const getRandomString = () => Math.random().toString(36).substring(2, 15); /** * Creates a runtime identifier of an interface used for dependency injection. * * Every call to this function produces unique identifier, you can't call this method twice for the same Type! */ export const createInterfaceId = (id: string): InterfaceId => `${id}-${getRandomString()}` as InterfaceId; /* * Takes an array of InterfaceIDs with unknown type and turn them into an array of the types that the InterfaceIds wrap * * e.g. `UnwrapInterfaceIds<[InterfaceId, InterfaceId]>` equals to `[string, number]` * * this type is used to enforce dependency types in the constructor of the injected class */ type UnwrapInterfaceIds[]> = { [K in keyof T]: T[K] extends InterfaceId ? U : never; }; interface Metadata { id: string; dependencies: string[]; } /** * Here we store the id and dependencies for all classes decorated with @Injectable */ const injectableMetadata = new WeakMap(); /** * Decorate your class with @Injectable(id, dependencies) * param id = InterfaceId of the interface implemented by your class (use createInterfaceId to create one) * param dependencies = List of InterfaceIds that will be injected into class' constructor */ export function Injectable[]>( id: InterfaceId, dependencies: [...TDependencies], // we can add `| [] = [],` to make dependencies optional, but the type checker messages are quite cryptic when the decorated class has some constructor arguments ) { // this is the trickiest part of the whole DI framework // we say, this decorator takes // - id (the interface that the injectable implements) // - dependencies (list of interface ids that will be injected to constructor) // // With then we return function that ensures that the decorated class implements the id interface // and its constructor has arguments of same type and order as the dependencies argument to the decorator return function ): I }>( constructor: T, { kind }: ClassDecoratorContext, ) { if (kind === 'class') { injectableMetadata.set(constructor, { id, dependencies: dependencies || [] }); return constructor; } throw new Error('Injectable decorator can only be used on a class.'); }; } // new (...args: any[]): any is actually how TS defines type of a class // eslint-disable-next-line @typescript-eslint/no-explicit-any type WithConstructor = { new (...args: any[]): any; name: string }; type ClassWithDependencies = { cls: WithConstructor; id: string; dependencies: string[] }; type Validator = (cwds: ClassWithDependencies[], instanceIds: string[]) => void; const sanitizeId = (idWithRandom: string) => idWithRandom.replace(/-[^-]+$/, ''); /** ensures that only one interface ID implementation is present */ const interfaceUsedOnlyOnce: Validator = (cwds, instanceIds) => { const clashingWithExistingInstance = cwds.filter((cwd) => instanceIds.includes(cwd.id)); if (clashingWithExistingInstance.length > 0) { throw new Error( `The following classes are clashing (have duplicate ID) with instances already present in the container: ${clashingWithExistingInstance.map((cwd) => cwd.cls.name)}`, ); } const groupedById = groupBy(cwds, (cwd) => cwd.id); if (Object.values(groupedById).every((groupedCwds) => groupedCwds.length === 1)) { return; } const messages = Object.entries(groupedById).map( ([id, groupedCwds]) => `'${sanitizeId(id)}' (classes: ${groupedCwds.map((cwd) => cwd.cls.name).join(',')})`, ); throw new Error(`The following interface IDs were used multiple times ${messages.join(',')}`); }; /** throws an error if any class depends on an interface that is not available */ const dependenciesArePresent: Validator = (cwds, instanceIds) => { const allIds = new Set([...cwds.map((cwd) => cwd.id), ...instanceIds]); const cwsWithUnmetDeps = cwds.filter((cwd) => !cwd.dependencies.every((d) => allIds.has(d))); if (cwsWithUnmetDeps.length === 0) { return; } const messages = cwsWithUnmetDeps.map((cwd) => { const unmetDeps = cwd.dependencies.filter((d) => !allIds.has(d)).map(sanitizeId); return `Class ${cwd.cls.name} (interface ${sanitizeId(cwd.id)}) depends on interfaces [${unmetDeps}] that weren't added to the init method.`; }); throw new Error(messages.join('\n')); }; /** uses depth first search to find out if the classes have circular dependency */ const noCircularDependencies: Validator = (cwds, instanceIds) => { const inStack = new Set(); const hasCircularDependency = (id: string): boolean => { if (inStack.has(id)) { return true; } inStack.add(id); const cwd = cwds.find((c) => c.id === id); // we reference existing instance, there won't be circular dependency past this one because instances don't have any dependencies if (!cwd && instanceIds.includes(id)) { inStack.delete(id); return false; } if (!cwd) throw new Error(`assertion error: dependency ID missing ${sanitizeId(id)}`); for (const dependencyId of cwd.dependencies) { if (hasCircularDependency(dependencyId)) { return true; } } inStack.delete(id); return false; }; for (const cwd of cwds) { if (hasCircularDependency(cwd.id)) { throw new Error( `Circular dependency detected between interfaces (${Array.from(inStack).map(sanitizeId)}), starting with '${sanitizeId(cwd.id)}' (class: ${cwd.cls.name}).`, ); } } }; /** * Topological sort of the dependencies - returns array of classes. The classes should be initialized in order given by the array. * https://en.wikipedia.org/wiki/Topological_sorting */ const sortDependencies = (classes: Map): ClassWithDependencies[] => { const visited = new Set(); const sortedClasses: ClassWithDependencies[] = []; const topologicalSort = (interfaceId: string) => { if (visited.has(interfaceId)) { return; } visited.add(interfaceId); const cwd = classes.get(interfaceId); if (!cwd) { // the instance for this ID is already initiated return; } for (const d of cwd.dependencies || []) { topologicalSort(d); } sortedClasses.push(cwd); }; for (const id of classes.keys()) { topologicalSort(id); } return sortedClasses; }; /** * Helper type used by the brandInstance function to ensure that all container.addInstances parameters are branded */ export type BrandedInstance = T; /** * use brandInstance to be able to pass this instance to the container.addInstances method */ export const brandInstance = ( id: InterfaceId, instance: T, ): BrandedInstance => { injectableMetadata.set(instance, { id, dependencies: [] }); return instance; }; /** * Container is responsible for initializing a dependency tree. * * It receives a list of classes decorated with the `@Injectable` decorator * and it constructs instances of these classes in an order that ensures class' dependencies * are initialized before the class itself. * * check https://gitlab.com/viktomas/needle for full documentation of this mini-framework */ export class Container { #instances = new Map(); /** * addInstances allows you to add pre-initialized objects to the container. * This is useful when you want to keep mandatory parameters in class' constructor (e.g. some runtime objects like server connection). * addInstances accepts a list of any objects that have been ""branded"" by the `brandInstance` method */ addInstances(...instances: BrandedInstance[]) { for (const instance of instances) { const metadata = injectableMetadata.get(instance); if (!metadata) { throw new Error( 'assertion error: addInstance invoked without branded object, make sure all arguments are branded with `brandInstance`', ); } if (this.#instances.has(metadata.id)) { throw new Error( `you are trying to add instance for interfaceId ${metadata.id}, but instance with this ID is already in the container.`, ); } this.#instances.set(metadata.id, instance); } } /** * instantiate accepts list of classes, validates that they can be managed by the container * and then initialized them in such order that dependencies of a class are initialized before the class */ instantiate(...classes: WithConstructor[]) { // ensure all classes have been decorated with @Injectable const undecorated = classes.filter((c) => !injectableMetadata.has(c)).map((c) => c.name); if (undecorated.length) { throw new Error(`Classes [${undecorated}] are not decorated with @Injectable.`); } const classesWithDeps: ClassWithDependencies[] = classes.map((cls) => { // we verified just above that all classes are present in the metadata map // eslint-disable-next-line @typescript-eslint/no-non-null-assertion const { id, dependencies } = injectableMetadata.get(cls)!; return { cls, id, dependencies }; }); const validators: Validator[] = [ interfaceUsedOnlyOnce, dependenciesArePresent, noCircularDependencies, ]; validators.forEach((v) => v(classesWithDeps, Array.from(this.#instances.keys()))); const classesById = new Map(); // Index classes by their interface id classesWithDeps.forEach((cwd) => { classesById.set(cwd.id, cwd); }); // Create instances in topological order for (const cwd of sortDependencies(classesById)) { const args = cwd.dependencies.map((dependencyId) => this.#instances.get(dependencyId)); // eslint-disable-next-line new-cap const instance = new cwd.cls(...args); this.#instances.set(cwd.id, instance); } } get(id: InterfaceId): T { const instance = this.#instances.get(id); if (!instance) { throw new Error(`Instance for interface '${sanitizeId(id)}' is not in the container.`); } return instance as T; } } References:" You are a code assistant,Definition of 'StartStreamOption' in file src/common/api.ts in project gitlab-lsp,"Definition: export interface StartStreamOption { uniqueTrackingId: string; /** the streamId represents the beginning of a stream * */ streamId: string; } export type SuggestionOptionOrStream = SuggestionOption | StartStreamOption; export interface PersonalAccessToken { name: string; scopes: string[]; active: boolean; } export interface OAuthToken { scope: string[]; } export interface TokenCheckResponse { valid: boolean; reason?: 'unknown' | 'not_active' | 'invalid_scopes'; message?: string; } export interface IDirectConnectionDetailsHeaders { 'X-Gitlab-Global-User-Id': string; 'X-Gitlab-Instance-Id': string; 'X-Gitlab-Host-Name': string; 'X-Gitlab-Saas-Duo-Pro-Namespace-Ids': string; } export interface IDirectConnectionModelDetails { model_provider: string; model_name: string; } export interface IDirectConnectionDetails { base_url: string; token: string; expires_at: number; headers: IDirectConnectionDetailsHeaders; model_details: IDirectConnectionModelDetails; } const CONFIG_CHANGE_EVENT_NAME = 'apiReconfigured'; @Injectable(GitLabApiClient, [LsFetch, ConfigService]) export class GitLabAPI implements GitLabApiClient { #token: string | undefined; #baseURL: string; #clientInfo?: IClientInfo; #lsFetch: LsFetch; #eventEmitter = new EventEmitter(); #configService: ConfigService; #instanceVersion?: string; constructor(lsFetch: LsFetch, configService: ConfigService) { this.#baseURL = GITLAB_API_BASE_URL; this.#lsFetch = lsFetch; this.#configService = configService; this.#configService.onConfigChange(async (config) => { this.#clientInfo = configService.get('client.clientInfo'); this.#lsFetch.updateAgentOptions({ ignoreCertificateErrors: this.#configService.get('client.ignoreCertificateErrors') ?? false, ...(this.#configService.get('client.httpAgentOptions') ?? {}), }); await this.configureApi(config.client); }); } onApiReconfigured(listener: (data: ApiReconfiguredData) => void): Disposable { this.#eventEmitter.on(CONFIG_CHANGE_EVENT_NAME, listener); return { dispose: () => this.#eventEmitter.removeListener(CONFIG_CHANGE_EVENT_NAME, listener) }; } #fireApiReconfigured(isInValidState: boolean, validationMessage?: string) { const data: ApiReconfiguredData = { isInValidState, validationMessage }; this.#eventEmitter.emit(CONFIG_CHANGE_EVENT_NAME, data); } async configureApi({ token, baseUrl = GITLAB_API_BASE_URL, }: { token?: string; baseUrl?: string; }) { if (this.#token === token && this.#baseURL === baseUrl) return; this.#token = token; this.#baseURL = baseUrl; const { valid, reason, message } = await this.checkToken(this.#token); let validationMessage; if (!valid) { this.#configService.set('client.token', undefined); validationMessage = `Token is invalid. ${message}. Reason: ${reason}`; log.warn(validationMessage); } else { log.info('Token is valid'); } this.#instanceVersion = await this.#getGitLabInstanceVersion(); this.#fireApiReconfigured(valid, validationMessage); } #looksLikePatToken(token: string): boolean { // OAuth tokens will be longer than 42 characters and PATs will be shorter. return token.length < 42; } async #checkPatToken(token: string): Promise { const headers = this.#getDefaultHeaders(token); const response = await this.#lsFetch.get( `${this.#baseURL}/api/v4/personal_access_tokens/self`, { headers }, ); await handleFetchError(response, 'Information about personal access token'); const { active, scopes } = (await response.json()) as PersonalAccessToken; if (!active) { return { valid: false, reason: 'not_active', message: 'Token is not active.', }; } if (!this.#hasValidScopes(scopes)) { const joinedScopes = scopes.map((scope) => `'${scope}'`).join(', '); return { valid: false, reason: 'invalid_scopes', message: `Token has scope(s) ${joinedScopes} (needs 'api').`, }; } return { valid: true }; } async #checkOAuthToken(token: string): Promise { const headers = this.#getDefaultHeaders(token); const response = await this.#lsFetch.get(`${this.#baseURL}/oauth/token/info`, { headers, }); await handleFetchError(response, 'Information about OAuth token'); const { scope: scopes } = (await response.json()) as OAuthToken; if (!this.#hasValidScopes(scopes)) { const joinedScopes = scopes.map((scope) => `'${scope}'`).join(', '); return { valid: false, reason: 'invalid_scopes', message: `Token has scope(s) ${joinedScopes} (needs 'api').`, }; } return { valid: true }; } async checkToken(token: string = ''): Promise { try { if (this.#looksLikePatToken(token)) { log.info('Checking token for PAT validity'); return await this.#checkPatToken(token); } log.info('Checking token for OAuth validity'); return await this.#checkOAuthToken(token); } catch (err) { log.error('Error performing token check', err); return { valid: false, reason: 'unknown', message: `Failed to check token: ${err}`, }; } } #hasValidScopes(scopes: string[]): boolean { return scopes.includes('api'); } async getCodeSuggestions( request: CodeSuggestionRequest, ): Promise { if (!this.#token) { throw new Error('Token needs to be provided to request Code Suggestions'); } const headers = { ...this.#getDefaultHeaders(this.#token), 'Content-Type': 'application/json', }; const response = await this.#lsFetch.post( `${this.#baseURL}/api/v4/code_suggestions/completions`, { headers, body: JSON.stringify(request) }, ); await handleFetchError(response, 'Code Suggestions'); const data = await response.json(); return { ...data, status: response.status }; } async *getStreamingCodeSuggestions( request: CodeSuggestionRequest, ): AsyncGenerator { if (!this.#token) { throw new Error('Token needs to be provided to stream code suggestions'); } const headers = { ...this.#getDefaultHeaders(this.#token), 'Content-Type': 'application/json', }; yield* this.#lsFetch.streamFetch( `${this.#baseURL}/api/v4/code_suggestions/completions`, JSON.stringify(request), headers, ); } async fetchFromApi(request: ApiRequest): Promise { if (!this.#token) { return Promise.reject(new Error('Token needs to be provided to authorise API request.')); } if ( request.supportedSinceInstanceVersion && !this.#instanceVersionHigherOrEqualThen(request.supportedSinceInstanceVersion.version) ) { return Promise.reject( new InvalidInstanceVersionError( `Can't ${request.supportedSinceInstanceVersion.resourceName} until your instance is upgraded to ${request.supportedSinceInstanceVersion.version} or higher.`, ), ); } if (request.type === 'graphql') { return this.#graphqlRequest(request.query, request.variables); } switch (request.method) { case 'GET': return this.#fetch(request.path, request.searchParams, 'resource', request.headers); case 'POST': return this.#postFetch(request.path, 'resource', request.body, request.headers); default: // the type assertion is necessary because TS doesn't expect any other types throw new Error(`Unknown request type ${(request as ApiRequest).type}`); } } async connectToCable(): Promise { const headers = this.#getDefaultHeaders(this.#token); const websocketOptions = { headers: { ...headers, Origin: this.#baseURL, }, }; return connectToCable(this.#baseURL, websocketOptions); } async #graphqlRequest( document: RequestDocument, variables?: V, ): Promise { const ensureEndsWithSlash = (url: string) => url.replace(/\/?$/, '/'); const endpoint = new URL('./api/graphql', ensureEndsWithSlash(this.#baseURL)).href; // supports GitLab instances that are on a custom path, e.g. ""https://example.com/gitlab"" const graphqlFetch = async ( input: RequestInfo | URL, init?: RequestInit, ): Promise => { const url = input instanceof URL ? input.toString() : input; return this.#lsFetch.post(url, { ...init, headers: { ...headers, ...init?.headers }, }); }; const headers = this.#getDefaultHeaders(this.#token); const client = new GraphQLClient(endpoint, { headers, fetch: graphqlFetch, }); return client.request(document, variables); } async #fetch( apiResourcePath: string, query: Record = {}, resourceName = 'resource', headers?: Record, ): Promise { const url = `${this.#baseURL}/api/v4${apiResourcePath}${createQueryString(query)}`; const result = await this.#lsFetch.get(url, { headers: { ...this.#getDefaultHeaders(this.#token), ...headers }, }); await handleFetchError(result, resourceName); return result.json() as Promise; } async #postFetch( apiResourcePath: string, resourceName = 'resource', body?: unknown, headers?: Record, ): Promise { const url = `${this.#baseURL}/api/v4${apiResourcePath}`; const response = await this.#lsFetch.post(url, { headers: { 'Content-Type': 'application/json', ...this.#getDefaultHeaders(this.#token), ...headers, }, body: JSON.stringify(body), }); await handleFetchError(response, resourceName); return response.json() as Promise; } #getDefaultHeaders(token?: string) { return { Authorization: `Bearer ${token}`, 'User-Agent': `code-completions-language-server-experiment (${this.#clientInfo?.name}:${this.#clientInfo?.version})`, 'X-Gitlab-Language-Server-Version': getLanguageServerVersion(), }; } #instanceVersionHigherOrEqualThen(version: string): boolean { if (!this.#instanceVersion) return false; return semverCompare(this.#instanceVersion, version) >= 0; } async #getGitLabInstanceVersion(): Promise { if (!this.#token) { return ''; } const headers = this.#getDefaultHeaders(this.#token); const response = await this.#lsFetch.get(`${this.#baseURL}/api/v4/version`, { headers, }); const { version } = await response.json(); return version; } get instanceVersion() { return this.#instanceVersion; } } References: - src/common/utils/suggestion_mapper.test.ts:95" You are a code assistant,Definition of 'DefaultAiFileContextProvider' in file src/common/ai_context_management_2/providers/ai_file_context_provider.ts in project gitlab-lsp,"Definition: export class DefaultAiFileContextProvider implements AiContextProvider { #repositoryService: DefaultRepositoryService; constructor(repositoryService: DefaultRepositoryService) { this.#repositoryService = repositoryService; } async getProviderItems( query: string, workspaceFolders: WorkspaceFolder[], ): Promise { const items = query.trim() === '' ? await this.#getOpenTabsItems() : await this.#getSearchedItems(query, workspaceFolders); log.info(`Found ${items.length} results for ${query}`); return items; } async #getOpenTabsItems(): Promise { const resolutions: ContextResolution[] = []; for await (const resolution of OpenTabsResolver.getInstance().buildContext({ includeCurrentFile: true, })) { resolutions.push(resolution); } return resolutions.map((resolution) => this.#providerItemForOpenTab(resolution)); } async #getSearchedItems( query: string, workspaceFolders: WorkspaceFolder[], ): Promise { const allFiles: RepositoryFile[] = []; for (const folder of workspaceFolders) { const files = this.#repositoryService.getFilesForWorkspace(folder.uri, { excludeGitFolder: true, excludeIgnored: true, }); allFiles.push(...files); } const fileNames = allFiles.map((file) => file.uri.fsPath); const allFilesMap = new Map(allFiles.map((file) => [file.uri.fsPath, file])); const results = filter(fileNames, query, { maxResults: 100 }); const resultFiles: RepositoryFile[] = []; for (const result of results) { if (allFilesMap.has(result)) { resultFiles.push(allFilesMap.get(result) as RepositoryFile); } } return resultFiles.map((file) => this.#providerItemForSearchResult(file)); } #openTabResolutionToRepositoryFile(resolution: ContextResolution): [URI, RepositoryFile | null] { const fileUri = parseURIString(resolution.uri); const repo = this.#repositoryService.findMatchingRepositoryUri( fileUri, resolution.workspaceFolder, ); if (!repo) { log.warn(`Could not find repository for ${resolution.uri}`); return [fileUri, null]; } const repositoryFile = this.#repositoryService.getRepositoryFileForUri( fileUri, repo, resolution.workspaceFolder, ); if (!repositoryFile) { log.warn(`Could not find repository file for ${resolution.uri}`); return [fileUri, null]; } return [fileUri, repositoryFile]; } #providerItemForOpenTab(resolution: ContextResolution): AiContextProviderItem { const [fileUri, repositoryFile] = this.#openTabResolutionToRepositoryFile(resolution); return { fileUri, workspaceFolder: resolution.workspaceFolder, providerType: 'file', subType: 'open_tab', repositoryFile, }; } #providerItemForSearchResult(repositoryFile: RepositoryFile): AiContextProviderItem { return { fileUri: repositoryFile.uri, workspaceFolder: repositoryFile.workspaceFolder, providerType: 'file', subType: 'local_file_search', repositoryFile, }; } } References:" You are a code assistant,Definition of 'CodeSuggestionRequestCurrentFile' in file src/common/api.ts in project gitlab-lsp,"Definition: export interface CodeSuggestionRequestCurrentFile { file_name: string; content_above_cursor: string; content_below_cursor: string; } export interface CodeSuggestionResponse { choices?: SuggestionOption[]; model?: ICodeSuggestionModel; status: number; error?: string; isDirectConnection?: boolean; } // FIXME: Rename to SuggestionOptionStream when renaming the SuggestionOption export interface StartStreamOption { uniqueTrackingId: string; /** the streamId represents the beginning of a stream * */ streamId: string; } export type SuggestionOptionOrStream = SuggestionOption | StartStreamOption; export interface PersonalAccessToken { name: string; scopes: string[]; active: boolean; } export interface OAuthToken { scope: string[]; } export interface TokenCheckResponse { valid: boolean; reason?: 'unknown' | 'not_active' | 'invalid_scopes'; message?: string; } export interface IDirectConnectionDetailsHeaders { 'X-Gitlab-Global-User-Id': string; 'X-Gitlab-Instance-Id': string; 'X-Gitlab-Host-Name': string; 'X-Gitlab-Saas-Duo-Pro-Namespace-Ids': string; } export interface IDirectConnectionModelDetails { model_provider: string; model_name: string; } export interface IDirectConnectionDetails { base_url: string; token: string; expires_at: number; headers: IDirectConnectionDetailsHeaders; model_details: IDirectConnectionModelDetails; } const CONFIG_CHANGE_EVENT_NAME = 'apiReconfigured'; @Injectable(GitLabApiClient, [LsFetch, ConfigService]) export class GitLabAPI implements GitLabApiClient { #token: string | undefined; #baseURL: string; #clientInfo?: IClientInfo; #lsFetch: LsFetch; #eventEmitter = new EventEmitter(); #configService: ConfigService; #instanceVersion?: string; constructor(lsFetch: LsFetch, configService: ConfigService) { this.#baseURL = GITLAB_API_BASE_URL; this.#lsFetch = lsFetch; this.#configService = configService; this.#configService.onConfigChange(async (config) => { this.#clientInfo = configService.get('client.clientInfo'); this.#lsFetch.updateAgentOptions({ ignoreCertificateErrors: this.#configService.get('client.ignoreCertificateErrors') ?? false, ...(this.#configService.get('client.httpAgentOptions') ?? {}), }); await this.configureApi(config.client); }); } onApiReconfigured(listener: (data: ApiReconfiguredData) => void): Disposable { this.#eventEmitter.on(CONFIG_CHANGE_EVENT_NAME, listener); return { dispose: () => this.#eventEmitter.removeListener(CONFIG_CHANGE_EVENT_NAME, listener) }; } #fireApiReconfigured(isInValidState: boolean, validationMessage?: string) { const data: ApiReconfiguredData = { isInValidState, validationMessage }; this.#eventEmitter.emit(CONFIG_CHANGE_EVENT_NAME, data); } async configureApi({ token, baseUrl = GITLAB_API_BASE_URL, }: { token?: string; baseUrl?: string; }) { if (this.#token === token && this.#baseURL === baseUrl) return; this.#token = token; this.#baseURL = baseUrl; const { valid, reason, message } = await this.checkToken(this.#token); let validationMessage; if (!valid) { this.#configService.set('client.token', undefined); validationMessage = `Token is invalid. ${message}. Reason: ${reason}`; log.warn(validationMessage); } else { log.info('Token is valid'); } this.#instanceVersion = await this.#getGitLabInstanceVersion(); this.#fireApiReconfigured(valid, validationMessage); } #looksLikePatToken(token: string): boolean { // OAuth tokens will be longer than 42 characters and PATs will be shorter. return token.length < 42; } async #checkPatToken(token: string): Promise { const headers = this.#getDefaultHeaders(token); const response = await this.#lsFetch.get( `${this.#baseURL}/api/v4/personal_access_tokens/self`, { headers }, ); await handleFetchError(response, 'Information about personal access token'); const { active, scopes } = (await response.json()) as PersonalAccessToken; if (!active) { return { valid: false, reason: 'not_active', message: 'Token is not active.', }; } if (!this.#hasValidScopes(scopes)) { const joinedScopes = scopes.map((scope) => `'${scope}'`).join(', '); return { valid: false, reason: 'invalid_scopes', message: `Token has scope(s) ${joinedScopes} (needs 'api').`, }; } return { valid: true }; } async #checkOAuthToken(token: string): Promise { const headers = this.#getDefaultHeaders(token); const response = await this.#lsFetch.get(`${this.#baseURL}/oauth/token/info`, { headers, }); await handleFetchError(response, 'Information about OAuth token'); const { scope: scopes } = (await response.json()) as OAuthToken; if (!this.#hasValidScopes(scopes)) { const joinedScopes = scopes.map((scope) => `'${scope}'`).join(', '); return { valid: false, reason: 'invalid_scopes', message: `Token has scope(s) ${joinedScopes} (needs 'api').`, }; } return { valid: true }; } async checkToken(token: string = ''): Promise { try { if (this.#looksLikePatToken(token)) { log.info('Checking token for PAT validity'); return await this.#checkPatToken(token); } log.info('Checking token for OAuth validity'); return await this.#checkOAuthToken(token); } catch (err) { log.error('Error performing token check', err); return { valid: false, reason: 'unknown', message: `Failed to check token: ${err}`, }; } } #hasValidScopes(scopes: string[]): boolean { return scopes.includes('api'); } async getCodeSuggestions( request: CodeSuggestionRequest, ): Promise { if (!this.#token) { throw new Error('Token needs to be provided to request Code Suggestions'); } const headers = { ...this.#getDefaultHeaders(this.#token), 'Content-Type': 'application/json', }; const response = await this.#lsFetch.post( `${this.#baseURL}/api/v4/code_suggestions/completions`, { headers, body: JSON.stringify(request) }, ); await handleFetchError(response, 'Code Suggestions'); const data = await response.json(); return { ...data, status: response.status }; } async *getStreamingCodeSuggestions( request: CodeSuggestionRequest, ): AsyncGenerator { if (!this.#token) { throw new Error('Token needs to be provided to stream code suggestions'); } const headers = { ...this.#getDefaultHeaders(this.#token), 'Content-Type': 'application/json', }; yield* this.#lsFetch.streamFetch( `${this.#baseURL}/api/v4/code_suggestions/completions`, JSON.stringify(request), headers, ); } async fetchFromApi(request: ApiRequest): Promise { if (!this.#token) { return Promise.reject(new Error('Token needs to be provided to authorise API request.')); } if ( request.supportedSinceInstanceVersion && !this.#instanceVersionHigherOrEqualThen(request.supportedSinceInstanceVersion.version) ) { return Promise.reject( new InvalidInstanceVersionError( `Can't ${request.supportedSinceInstanceVersion.resourceName} until your instance is upgraded to ${request.supportedSinceInstanceVersion.version} or higher.`, ), ); } if (request.type === 'graphql') { return this.#graphqlRequest(request.query, request.variables); } switch (request.method) { case 'GET': return this.#fetch(request.path, request.searchParams, 'resource', request.headers); case 'POST': return this.#postFetch(request.path, 'resource', request.body, request.headers); default: // the type assertion is necessary because TS doesn't expect any other types throw new Error(`Unknown request type ${(request as ApiRequest).type}`); } } async connectToCable(): Promise { const headers = this.#getDefaultHeaders(this.#token); const websocketOptions = { headers: { ...headers, Origin: this.#baseURL, }, }; return connectToCable(this.#baseURL, websocketOptions); } async #graphqlRequest( document: RequestDocument, variables?: V, ): Promise { const ensureEndsWithSlash = (url: string) => url.replace(/\/?$/, '/'); const endpoint = new URL('./api/graphql', ensureEndsWithSlash(this.#baseURL)).href; // supports GitLab instances that are on a custom path, e.g. ""https://example.com/gitlab"" const graphqlFetch = async ( input: RequestInfo | URL, init?: RequestInit, ): Promise => { const url = input instanceof URL ? input.toString() : input; return this.#lsFetch.post(url, { ...init, headers: { ...headers, ...init?.headers }, }); }; const headers = this.#getDefaultHeaders(this.#token); const client = new GraphQLClient(endpoint, { headers, fetch: graphqlFetch, }); return client.request(document, variables); } async #fetch( apiResourcePath: string, query: Record = {}, resourceName = 'resource', headers?: Record, ): Promise { const url = `${this.#baseURL}/api/v4${apiResourcePath}${createQueryString(query)}`; const result = await this.#lsFetch.get(url, { headers: { ...this.#getDefaultHeaders(this.#token), ...headers }, }); await handleFetchError(result, resourceName); return result.json() as Promise; } async #postFetch( apiResourcePath: string, resourceName = 'resource', body?: unknown, headers?: Record, ): Promise { const url = `${this.#baseURL}/api/v4${apiResourcePath}`; const response = await this.#lsFetch.post(url, { headers: { 'Content-Type': 'application/json', ...this.#getDefaultHeaders(this.#token), ...headers, }, body: JSON.stringify(body), }); await handleFetchError(response, resourceName); return response.json() as Promise; } #getDefaultHeaders(token?: string) { return { Authorization: `Bearer ${token}`, 'User-Agent': `code-completions-language-server-experiment (${this.#clientInfo?.name}:${this.#clientInfo?.version})`, 'X-Gitlab-Language-Server-Version': getLanguageServerVersion(), }; } #instanceVersionHigherOrEqualThen(version: string): boolean { if (!this.#instanceVersion) return false; return semverCompare(this.#instanceVersion, version) >= 0; } async #getGitLabInstanceVersion(): Promise { if (!this.#token) { return ''; } const headers = this.#getDefaultHeaders(this.#token); const response = await this.#lsFetch.get(`${this.#baseURL}/api/v4/version`, { headers, }); const { version } = await response.json(); return version; } get instanceVersion() { return this.#instanceVersion; } } References: - src/common/api.ts:45" You are a code assistant,Definition of 'SPECIAL_MESSAGES' in file packages/webview_duo_chat/src/app/constants.ts in project gitlab-lsp,"Definition: export const SPECIAL_MESSAGES = { CLEAN: '/clean', CLEAR: '/clear', RESET: '/reset', }; References:" You are a code assistant,Definition of 'AiContextQuery' in file src/common/ai_context_management_2/ai_policy_management.ts in project gitlab-lsp,"Definition: 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:36 - src/common/connection_service.ts:105" You are a code assistant,Definition of 'onNotification' in file packages/lib_message_bus/src/types/bus.ts in project gitlab-lsp,"Definition: onNotification>( type: T, handler: () => void, ): Disposable; onNotification( type: T, handler: (payload: TNotifications[T]) => void, ): Disposable; } /** * Maps request message types to their corresponding request/response payloads. * @typedef {Record} RequestMap */ export type RequestMap = Record< Method, { params: MessagePayload; result: MessagePayload; } >; type KeysWithOptionalParams = { [K in keyof R]: R[K]['params'] extends undefined ? never : K; }[keyof R]; /** * Extracts the response payload type from a request type. * @template {MessagePayload} T * @typedef {T extends [never] ? void : T[0]} ExtractRequestResponse */ export type ExtractRequestResult = // eslint-disable-next-line @typescript-eslint/no-invalid-void-type T['result'] extends undefined ? void : T; /** * Interface for publishing requests. * @interface * @template {RequestMap} TRequests */ export interface RequestPublisher { sendRequest>( type: T, ): Promise>; sendRequest( type: T, payload: TRequests[T]['params'], ): Promise>; } /** * Interface for listening to requests. * @interface * @template {RequestMap} TRequests */ export interface RequestListener { onRequest>( type: T, handler: () => Promise>, ): Disposable; onRequest( type: T, handler: (payload: TRequests[T]['params']) => Promise>, ): Disposable; } /** * Defines the structure for message definitions, including notifications and requests. */ export type MessageDefinitions< TNotifications extends NotificationMap = NotificationMap, TRequests extends RequestMap = RequestMap, > = { notifications: TNotifications; requests: TRequests; }; export type MessageMap< TInboundMessageDefinitions extends MessageDefinitions = MessageDefinitions, TOutboundMessageDefinitions extends MessageDefinitions = MessageDefinitions, > = { inbound: TInboundMessageDefinitions; outbound: TOutboundMessageDefinitions; }; export interface MessageBus extends NotificationPublisher, NotificationListener, RequestPublisher, RequestListener {} References:" You are a code assistant,Definition of 'MessageBus' in file packages/lib_webview/src/events/message_bus.ts in project gitlab-lsp,"Definition: export class MessageBus> implements Disposable { #subscriptions = new Map>>(); public subscribe( messageType: K, listener: Listener, filter?: FilterFunction, ): Disposable { const subscriptions = this.#subscriptions.get(messageType) ?? new Set>(); const subscription: Subscription = { listener: listener as Listener, filter: filter as FilterFunction | undefined, }; subscriptions.add(subscription); this.#subscriptions.set(messageType, subscriptions); return { dispose: () => { const targetSubscriptions = this.#subscriptions.get(messageType); if (targetSubscriptions) { targetSubscriptions.delete(subscription); if (targetSubscriptions.size === 0) { this.#subscriptions.delete(messageType); } } }, }; } public publish(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; if (!filter || filter(data)) { listener(data); } }); } } public hasListeners(messageType: K): boolean { return this.#subscriptions.has(messageType); } public listenerCount(messageType: K): number { return this.#subscriptions.get(messageType)?.size ?? 0; } public clear(): void { this.#subscriptions.clear(); } public dispose(): void { this.clear(); } } References: - packages/lib_webview_client/src/bus/provider/host_application_message_bus_provider.test.ts:4 - src/common/graphql/workflow/service.ts:45 - src/common/graphql/workflow/service.test.ts:17 - packages/webview_duo_workflow/src/plugin/index.ts:9" You are a code assistant,Definition of 'constructor' in file src/common/feature_state/project_duo_acces_check.ts in project gitlab-lsp,"Definition: constructor( documentService: DocumentService, configService: ConfigService, duoProjectAccessChecker: DuoProjectAccessChecker, duoProjectAccessCache: DuoProjectAccessCache, ) { this.#configService = configService; this.#duoProjectAccessChecker = duoProjectAccessChecker; this.#subscriptions.push( documentService.onDocumentChange(async (event, handlerType) => { if (handlerType === TextDocumentChangeListenerType.onDidSetActive) { this.#currentDocument = event.document; await this.#checkIfProjectHasDuoAccess(); } }), configService.onConfigChange(async (config) => { this.#isEnabledInSettings = config.client.duo?.enabledWithoutGitlabProject ?? true; await this.#checkIfProjectHasDuoAccess(); }), duoProjectAccessCache.onDuoProjectCacheUpdate(() => this.#checkIfProjectHasDuoAccess()), ); } onChanged(listener: (data: StateCheckChangedEventData) => void): Disposable { this.#stateEmitter.on('change', listener); return { dispose: () => this.#stateEmitter.removeListener('change', listener), }; } get engaged() { return !this.#hasDuoAccess; } async #checkIfProjectHasDuoAccess(): Promise { this.#hasDuoAccess = this.#isEnabledInSettings; if (!this.#currentDocument) { this.#stateEmitter.emit('change', this); return; } const workspaceFolder = await this.#getWorkspaceFolderForUri(this.#currentDocument.uri); if (workspaceFolder) { const status = this.#duoProjectAccessChecker.checkProjectStatus( this.#currentDocument.uri, workspaceFolder, ); if (status === DuoProjectStatus.DuoEnabled) { this.#hasDuoAccess = true; } else if (status === DuoProjectStatus.DuoDisabled) { this.#hasDuoAccess = false; } } this.#stateEmitter.emit('change', this); } id = DUO_DISABLED_FOR_PROJECT; details = 'Duo features are disabled for this project'; async #getWorkspaceFolderForUri(uri: URI): Promise { const workspaceFolders = await this.#configService.get('client.workspaceFolders'); return workspaceFolders?.find((folder) => uri.startsWith(folder.uri)); } dispose() { this.#subscriptions.forEach((s) => s.dispose()); } } References:" You are a code assistant,Definition of 'NO_LICENSE' in file src/common/feature_state/feature_state_management_types.ts in project gitlab-lsp,"Definition: export const NO_LICENSE = 'code-suggestions-no-license' as const; export const DUO_DISABLED_FOR_PROJECT = 'duo-disabled-for-project' as const; export const UNSUPPORTED_GITLAB_VERSION = 'unsupported-gitlab-version' as const; export const UNSUPPORTED_LANGUAGE = 'code-suggestions-document-unsupported-language' as const; export const DISABLED_LANGUAGE = 'code-suggestions-document-disabled-language' as const; export type StateCheckId = | typeof NO_LICENSE | typeof DUO_DISABLED_FOR_PROJECT | typeof UNSUPPORTED_GITLAB_VERSION | typeof UNSUPPORTED_LANGUAGE | typeof DISABLED_LANGUAGE; export interface FeatureStateCheck { checkId: StateCheckId; details?: string; } export interface FeatureState { featureId: Feature; engagedChecks: FeatureStateCheck[]; } const CODE_SUGGESTIONS_CHECKS_PRIORITY_ORDERED = [ DUO_DISABLED_FOR_PROJECT, UNSUPPORTED_LANGUAGE, DISABLED_LANGUAGE, ]; const CHAT_CHECKS_PRIORITY_ORDERED = [DUO_DISABLED_FOR_PROJECT]; export const CHECKS_PER_FEATURE: { [key in Feature]: StateCheckId[] } = { [CODE_SUGGESTIONS]: CODE_SUGGESTIONS_CHECKS_PRIORITY_ORDERED, [CHAT]: CHAT_CHECKS_PRIORITY_ORDERED, // [WORKFLOW]: [], }; References:" You are a code assistant,Definition of 'NotificationListener' in file packages/lib_message_bus/src/types/bus.ts in project gitlab-lsp,"Definition: export interface NotificationListener { onNotification>( type: T, handler: () => void, ): Disposable; onNotification( type: T, handler: (payload: TNotifications[T]) => void, ): Disposable; } /** * Maps request message types to their corresponding request/response payloads. * @typedef {Record} RequestMap */ export type RequestMap = Record< Method, { params: MessagePayload; result: MessagePayload; } >; type KeysWithOptionalParams = { [K in keyof R]: R[K]['params'] extends undefined ? never : K; }[keyof R]; /** * Extracts the response payload type from a request type. * @template {MessagePayload} T * @typedef {T extends [never] ? void : T[0]} ExtractRequestResponse */ export type ExtractRequestResult = // eslint-disable-next-line @typescript-eslint/no-invalid-void-type T['result'] extends undefined ? void : T; /** * Interface for publishing requests. * @interface * @template {RequestMap} TRequests */ export interface RequestPublisher { sendRequest>( type: T, ): Promise>; sendRequest( type: T, payload: TRequests[T]['params'], ): Promise>; } /** * Interface for listening to requests. * @interface * @template {RequestMap} TRequests */ export interface RequestListener { onRequest>( type: T, handler: () => Promise>, ): Disposable; onRequest( type: T, handler: (payload: TRequests[T]['params']) => Promise>, ): Disposable; } /** * Defines the structure for message definitions, including notifications and requests. */ export type MessageDefinitions< TNotifications extends NotificationMap = NotificationMap, TRequests extends RequestMap = RequestMap, > = { notifications: TNotifications; requests: TRequests; }; export type MessageMap< TInboundMessageDefinitions extends MessageDefinitions = MessageDefinitions, TOutboundMessageDefinitions extends MessageDefinitions = MessageDefinitions, > = { inbound: TInboundMessageDefinitions; outbound: TOutboundMessageDefinitions; }; export interface MessageBus extends NotificationPublisher, NotificationListener, RequestPublisher, RequestListener {} References:" You are a code assistant,Definition of 'isWebviewInstanceMessageEventData' in file packages/lib_webview_transport/src/utils/message_validators.ts in project gitlab-lsp,"Definition: export const isWebviewInstanceMessageEventData: MessageValidator< WebviewInstanceNotificationEventData > = (message: unknown): message is WebviewInstanceNotificationEventData => isWebviewAddress(message) && 'type' in message; References:" You are a code assistant,Definition of 'setUris' in file src/common/webview/webview_metadata_provider.test.ts in project gitlab-lsp,"Definition: setUris(webviewId: WebviewId, uris: string[]) { this.#uriMap.set(webviewId, uris); } resolveUris(webviewId: WebviewId): string[] { return this.#uriMap.get(webviewId) || []; } } describe('WebviewMetadataProvider', () => { let accessInfoProviders: MockWebviewLocationService; let plugins: Set; let provider: WebviewMetadataProvider; beforeEach(() => { accessInfoProviders = new MockWebviewLocationService(); plugins = new Set(); provider = new WebviewMetadataProvider(accessInfoProviders, plugins); }); describe('getMetadata', () => { it('should return an empty array if no plugins are registered', () => { const metadata = provider.getMetadata(); expect(metadata).toEqual([]); }); it('should return metadata for registered plugins', () => { // write test const plugin1: WebviewPlugin = { id: 'plugin1' as WebviewId, title: 'Plugin 1', setup: () => {}, }; const plugin2: WebviewPlugin = { id: 'plugin2' as WebviewId, title: 'Plugin 2', setup: () => {}, }; plugins.add(plugin1); plugins.add(plugin2); accessInfoProviders.setUris(plugin1.id, ['uri1', 'uri2']); accessInfoProviders.setUris(plugin2.id, ['uri3', 'uri4']); const metadata = provider.getMetadata(); expect(metadata).toEqual([ { id: 'plugin1', title: 'Plugin 1', uris: ['uri1', 'uri2'], }, { id: 'plugin2', title: 'Plugin 2', uris: ['uri3', 'uri4'], }, ]); }); }); }); References:" You are a code assistant,Definition of 'getUri' in file src/node/webview/http_access_info_provider.ts in project gitlab-lsp,"Definition: getUri(webviewId: WebviewId): string { return `http://${this.#addressInfo.address}:${this.#addressInfo.port}/webview/${webviewId}`; } } References:" You are a code assistant,Definition of 'WEBVIEW_ID' in file packages/webview_duo_workflow/src/contract.ts in project gitlab-lsp,"Definition: export const WEBVIEW_ID = 'duo-workflow' as WebviewId; export const WEBVIEW_TITLE = 'GitLab Duo Workflow'; export type DuoWorkflowMessages = CreatePluginMessageMap<{ webviewToPlugin: { notifications: { startWorkflow: { goal: string; image: string; }; stopWorkflow: []; openUrl: { url: string; }; }; }; pluginToWebview: { notifications: { workflowCheckpoints: LangGraphCheckpoint[]; workflowError: string; workflowStarted: string; workflowStatus: string; }; }; }>; References:" You are a code assistant,Definition of 'DefaultDidChangeWorkspaceFoldersHandler' in file src/common/core/handlers/did_change_workspace_folders_handler.ts in project gitlab-lsp,"Definition: export class DefaultDidChangeWorkspaceFoldersHandler implements DidChangeWorkspaceFoldersHandler { #configService: ConfigService; constructor(configService: ConfigService) { this.#configService = configService; } notificationHandler: NotificationHandler = ( 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/core/handlers/did_change_workspace_folders_handler.test.ts:19" You are a code assistant,Definition of 'TreeSitterParser' in file src/common/tree_sitter/parser.ts in project gitlab-lsp,"Definition: export abstract class TreeSitterParser { protected loadState: TreeSitterParserLoadState; protected languages: Map; protected readonly parsers = new Map(); abstract init(): Promise; constructor({ languages }: { languages: TreeSitterLanguageInfo[] }) { this.languages = this.buildTreeSitterInfoByExtMap(languages); this.loadState = TreeSitterParserLoadState.INIT; } get loadStateValue(): TreeSitterParserLoadState { return this.loadState; } async parseFile(context: IDocContext): Promise { 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 { 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 { 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 { return languages.reduce((map, language) => { for (const extension of language.extensions) { map.set(extension, language); } return map; }, new Map()); } } References: - src/common/connection.ts:29 - src/common/tree_sitter/parser.test.ts:28 - src/common/suggestion/suggestion_service.ts:133 - src/common/suggestion_client/tree_sitter_middleware.ts:10 - src/common/suggestion/streaming_handler.test.ts:32 - src/common/suggestion/streaming_handler.ts:40 - src/common/suggestion/suggestion_service.ts:82 - src/common/suggestion_client/tree_sitter_middleware.test.ts:20" You are a code assistant,Definition of 'publish' in file packages/lib_webview_transport/src/types.ts in project gitlab-lsp,"Definition: publish(type: K, payload: MessagesToClient[K]): Promise; } export interface Transport extends TransportListener, TransportPublisher {} References:" You are a code assistant,Definition of 'GitLabEnvironment' in file packages/webview_duo_chat/src/plugin/port/chat/get_platform_manager_for_chat.ts in project gitlab-lsp,"Definition: export enum GitLabEnvironment { GITLAB_COM = 'production', GITLAB_STAGING = 'staging', GITLAB_ORG = 'org', GITLAB_DEVELOPMENT = 'development', GITLAB_SELF_MANAGED = 'self-managed', } export class GitLabPlatformManagerForChat { readonly #platformManager: GitLabPlatformManager; constructor(platformManager: GitLabPlatformManager) { this.#platformManager = platformManager; } async getProjectGqlId(): Promise { const projectManager = await this.#platformManager.getForActiveProject(false); return projectManager?.project.gqlId; } /** * Obtains a GitLab Platform to send API requests to the GitLab API * for the Duo Chat feature. * * - It returns a GitLabPlatformForAccount for the first linked account. * - It returns undefined if there are no accounts linked */ async getGitLabPlatform(): Promise { const platforms = await this.#platformManager.getForAllAccounts(); if (!platforms.length) { return undefined; } let platform: GitLabPlatformForAccount | undefined; // Using a for await loop in this context because we want to stop // evaluating accounts as soon as we find one with code suggestions enabled for await (const result of platforms.map(getChatSupport)) { if (result.hasSupportForChat) { platform = result.platform; break; } } return platform; } async getGitLabEnvironment(): Promise { const platform = await this.getGitLabPlatform(); const instanceUrl = platform?.account.instanceUrl; switch (instanceUrl) { case GITLAB_COM_URL: return GitLabEnvironment.GITLAB_COM; case GITLAB_DEVELOPMENT_URL: return GitLabEnvironment.GITLAB_DEVELOPMENT; case GITLAB_STAGING_URL: return GitLabEnvironment.GITLAB_STAGING; case GITLAB_ORG_URL: return GitLabEnvironment.GITLAB_ORG; default: return GitLabEnvironment.GITLAB_SELF_MANAGED; } } } References: - packages/webview_duo_chat/src/plugin/port/chat/utils/submit_feedback.ts:42" You are a code assistant,Definition of 'MAX_ERRORS_BEFORE_CIRCUIT_BREAK' in file src/common/circuit_breaker/circuit_breaker.ts in project gitlab-lsp,"Definition: export const MAX_ERRORS_BEFORE_CIRCUIT_BREAK = 4; export const API_ERROR_NOTIFICATION = '$/gitlab/api/error'; export const API_RECOVERY_NOTIFICATION = '$/gitlab/api/recovered'; export enum CircuitBreakerState { OPEN = 'Open', CLOSED = 'Closed', } export interface CircuitBreaker { error(): void; success(): void; isOpen(): boolean; onOpen(listener: () => void): Disposable; onClose(listener: () => void): Disposable; } References:" You are a code assistant,Definition of 'getMessageBusFromProviderSafe' in file packages/lib_webview_client/src/bus/resolve_message_bus.ts in project gitlab-lsp,"Definition: function getMessageBusFromProviderSafe( webviewId: string, provider: MessageBusProvider, logger: Logger, ): MessageBus | null { try { logger.debug(`Trying to resolve message bus from provider: ${provider.name}`); const bus = provider.getMessageBus(webviewId); logger.debug(`Message bus resolved from provider: ${provider.name}`); return bus; } catch (error) { logger.debug('Failed to resolve message bus', error as Error); return null; } } References: - packages/lib_webview_client/src/bus/resolve_message_bus.ts:19" You are a code assistant,Definition of 'updateFile' in file src/common/advanced_context/lru_cache.ts in project gitlab-lsp,"Definition: updateFile(context: IDocContext) { return this.#cache.set(context.uri, context); } /** * @returns `true` if the file was deleted, `false` if the file was not found */ deleteFile(uri: DocumentUri): boolean { return this.#cache.delete(uri); } /** * Get the most recently accessed files in the workspace * @param context - The current document context `IDocContext` * @param includeCurrentFile - Include the current file in the list of most recent files, default is `true` */ mostRecentFiles({ context, includeCurrentFile = true, }: { context?: IDocContext; includeCurrentFile?: boolean; }): IDocContext[] { const files = Array.from(this.#cache.values()); if (includeCurrentFile) { return files; } return files.filter( (file) => context?.workspaceFolder?.uri === file.workspaceFolder?.uri && file.uri !== context?.uri, ); } } References:" You are a code assistant,Definition of 'RepositoryTrie' in file src/common/git/repository_trie.ts in project gitlab-lsp,"Definition: export class RepositoryTrie { children: Map; repository: URI | null; constructor() { this.children = new Map(); this.repository = null; } dispose(): void { this.children.forEach((child) => child.dispose()); this.children.clear(); this.repository = null; } } References: - src/common/git/repository_service.ts:124 - src/common/git/repository_service.ts:123 - src/common/git/repository_service.ts:176 - src/common/git/repository_service.ts:130" You are a code assistant,Definition of 'greet2' in file src/tests/fixtures/intent/empty_function/python.py in project gitlab-lsp,"Definition: def greet2(name): print(name) class Greet: def __init__(self, name): pass def greet(self): pass 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:4" You are a code assistant,Definition of 'DuoProject' in file src/common/services/duo_access/project_access_cache.ts in project gitlab-lsp,"Definition: export type DuoProject = GitLabRemote & { /** * This is the pointer on the file system to the project. * eg. file:///User/username/gitlab-development-kit/gitlab/.git/config * This should match the `DocumentUri` of the document to check. * * @reference `DocumentUri` is the URI of the document to check. Comes from * the `TextDocument` object. */ uri: string; /** * enabled: true if the project has Duo features enabled */ enabled: boolean; }; type WorkspaceFolderUri = string; const duoFeaturesEnabledQuery = gql` query GetProject($projectPath: ID!) { project(fullPath: $projectPath) { duoFeaturesEnabled } } `; interface GitConfig { [section: string]: { [key: string]: string }; } type GitlabRemoteAndFileUri = GitLabRemote & { fileUri: string }; export interface GqlProjectWithDuoEnabledInfo { duoFeaturesEnabled: boolean; } export interface DuoProjectAccessCache { getProjectsForWorkspaceFolder(workspaceFolder: WorkspaceFolder): DuoProject[]; updateCache({ baseUrl, workspaceFolders, }: { baseUrl: string; workspaceFolders: WorkspaceFolder[]; }): Promise; onDuoProjectCacheUpdate(listener: () => void): Disposable; } export const DuoProjectAccessCache = createInterfaceId('DuoProjectAccessCache'); @Injectable(DuoProjectAccessCache, [DirectoryWalker, FileResolver, GitLabApiClient]) export class DefaultDuoProjectAccessCache { #duoProjects: Map; #eventEmitter = new EventEmitter(); constructor( private readonly directoryWalker: DirectoryWalker, private readonly fileResolver: FileResolver, private readonly api: GitLabApiClient, ) { this.#duoProjects = new Map(); } getProjectsForWorkspaceFolder(workspaceFolder: WorkspaceFolder): DuoProject[] { return this.#duoProjects.get(workspaceFolder.uri) ?? []; } async updateCache({ baseUrl, workspaceFolders, }: { baseUrl: string; workspaceFolders: WorkspaceFolder[]; }) { try { this.#duoProjects.clear(); const duoProjects = await Promise.all( workspaceFolders.map(async (workspaceFolder) => { return { workspaceFolder, projects: await this.#duoProjectsForWorkspaceFolder({ workspaceFolder, baseUrl, }), }; }), ); for (const { workspaceFolder, projects } of duoProjects) { this.#logProjectsInfo(projects, workspaceFolder); this.#duoProjects.set(workspaceFolder.uri, projects); } this.#triggerChange(); } catch (err) { log.error('DuoProjectAccessCache: failed to update project access cache', err); } } #logProjectsInfo(projects: DuoProject[], workspaceFolder: WorkspaceFolder) { if (!projects.length) { log.warn( `DuoProjectAccessCache: no projects found for workspace folder ${workspaceFolder.uri}`, ); return; } log.debug( `DuoProjectAccessCache: found ${projects.length} projects for workspace folder ${workspaceFolder.uri}: ${JSON.stringify(projects, null, 2)}`, ); } async #duoProjectsForWorkspaceFolder({ workspaceFolder, baseUrl, }: { workspaceFolder: WorkspaceFolder; baseUrl: string; }): Promise { const remotes = await this.#gitlabRemotesForWorkspaceFolder(workspaceFolder, baseUrl); const projects = await Promise.all( remotes.map(async (remote) => { const enabled = await this.#checkDuoFeaturesEnabled(remote.namespaceWithPath); return { projectPath: remote.projectPath, uri: remote.fileUri, enabled, host: remote.host, namespace: remote.namespace, namespaceWithPath: remote.namespaceWithPath, } satisfies DuoProject; }), ); return projects; } async #gitlabRemotesForWorkspaceFolder( workspaceFolder: WorkspaceFolder, baseUrl: string, ): Promise { const paths = await this.directoryWalker.findFilesForDirectory({ directoryUri: workspaceFolder.uri, filters: { fileEndsWith: ['/.git/config'], }, }); const remotes = await Promise.all( paths.map(async (fileUri) => this.#gitlabRemotesForFileUri(fileUri.toString(), baseUrl)), ); return remotes.flat(); } async #gitlabRemotesForFileUri( fileUri: string, baseUrl: string, ): Promise { const remoteUrls = await this.#remoteUrlsFromGitConfig(fileUri); return remoteUrls.reduce((acc, remoteUrl) => { const remote = parseGitLabRemote(remoteUrl, baseUrl); if (remote) { acc.push({ ...remote, fileUri }); } return acc; }, []); } async #remoteUrlsFromGitConfig(fileUri: string): Promise { try { const fileString = await this.fileResolver.readFile({ fileUri }); const config = ini.parse(fileString); return this.#getRemoteUrls(config); } catch (error) { log.error(`DuoProjectAccessCache: Failed to read git config file: ${fileUri}`, error); return []; } } #getRemoteUrls(config: GitConfig): string[] { return Object.keys(config).reduce((acc, section) => { if (section.startsWith('remote ')) { acc.push(config[section].url); } return acc; }, []); } async #checkDuoFeaturesEnabled(projectPath: string): Promise { try { const response = await this.api.fetchFromApi<{ project: GqlProjectWithDuoEnabledInfo }>({ type: 'graphql', query: duoFeaturesEnabledQuery, variables: { projectPath, }, } satisfies ApiRequest<{ project: GqlProjectWithDuoEnabledInfo }>); return Boolean(response?.project?.duoFeaturesEnabled); } catch (error) { log.error( `DuoProjectAccessCache: Failed to check if Duo features are enabled for project: ${projectPath}`, error, ); return true; } } onDuoProjectCacheUpdate( listener: (duoProjectsCache: Map) => void, ): Disposable { this.#eventEmitter.on(DUO_PROJECT_CACHE_UPDATE_EVENT, listener); return { dispose: () => this.#eventEmitter.removeListener(DUO_PROJECT_CACHE_UPDATE_EVENT, listener), }; } #triggerChange() { this.#eventEmitter.emit(DUO_PROJECT_CACHE_UPDATE_EVENT, this.#duoProjects); } } References:" You are a code assistant,Definition of 'subscribe' in file packages/lib_webview/src/events/utils/subscribe.ts in project gitlab-lsp,"Definition: export function subscribe( eventEmitter: TypedEventEmitter, eventName: TEventName, handler: TEvents[TEventName], ): Disposable { eventEmitter.on(eventName, handler); return { dispose: () => { eventEmitter.off(eventName, handler); }, }; } References:" You are a code assistant,Definition of 'AiCompletionResponseChannel' in file packages/webview_duo_chat/src/plugin/port/api/graphql/ai_completion_response_channel.ts in project gitlab-lsp,"Definition: export class AiCompletionResponseChannel extends Channel< AiCompletionResponseParams, AiCompletionResponseResponseType, AiCompletionResponseChannelEvents > { static identifier = 'GraphqlChannel'; constructor(params: AiCompletionResponseInput) { super({ channel: 'GraphqlChannel', operationName: 'aiCompletionResponse', query: AI_MESSAGE_SUBSCRIPTION_QUERY, variables: JSON.stringify(params), }); } receive(message: AiCompletionResponseResponseType) { if (!message.result.data.aiCompletionResponse) return; const data = message.result.data.aiCompletionResponse; if (data.role.toLowerCase() === 'system') { this.emit('systemMessage', data); } else if (data.chunkId) { this.emit('newChunk', data); } else { this.emit('fullMessage', data); } } } References: - packages/webview_duo_chat/src/plugin/port/api/graphql/ai_completion_response_channel.test.ts:4 - packages/webview_duo_chat/src/plugin/port/api/graphql/ai_completion_response_channel.test.ts:16 - packages/webview_duo_chat/src/plugin/port/chat/gitlab_chat_api.ts:205" 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): 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:"