diff --git a/core/config/handler.ts b/core/config/handler.ts index 6e87b655b..0b93cbe78 100644 --- a/core/config/handler.ts +++ b/core/config/handler.ts @@ -1,8 +1,3 @@ -import { http, https } from "follow-redirects"; -import * as fs from "fs"; -import { HttpProxyAgent } from "http-proxy-agent"; -import { HttpsProxyAgent } from "https-proxy-agent"; -import fetch from "node-fetch"; import { ContinueConfig, ContinueRcJson, IDE, ILLM } from ".."; import { IdeSettings } from "../protocol"; import { Telemetry } from "../util/posthog"; @@ -11,7 +6,8 @@ import { finalToBrowserConfig, loadFullConfigNode, } from "./load"; -const tls = require("tls"); +import { fetchwithRequestOptions } from "../util/fetchWithOptions"; + export class ConfigHandler { private savedConfig: ContinueConfig | undefined; private savedBrowserConfig?: BrowserSerializedContinueConfig; @@ -20,7 +16,7 @@ export class ConfigHandler { private readonly ide: IDE, private ideSettingsPromise: Promise, private readonly writeLog: (text: string) => void, - private readonly onConfigUpdate: () => void, + private readonly onConfigUpdate: () => void ) { this.ide = ide; this.ideSettingsPromise = ideSettingsPromise; @@ -80,7 +76,7 @@ export class ConfigHandler { this.ide.readFile, workspaceConfigs, remoteConfigServerUrl, - ideInfo.ideType, + ideInfo.ideType ); this.savedConfig.allowAnonymousTelemetry = this.savedConfig.allowAnonymousTelemetry && @@ -90,86 +86,19 @@ export class ConfigHandler { await Telemetry.setup( this.savedConfig.allowAnonymousTelemetry ?? true, await this.ide.getUniqueId(), - ideInfo.extensionVersion, + ideInfo.extensionVersion ); return this.savedConfig; } setupLlm(llm: ILLM): ILLM { - const TIMEOUT = 7200; // 7200 seconds = 2 hours - // Since we know this is happening in Node.js, we can add requestOptions through a custom agent - const ca = [...tls.rootCertificates]; - const customCerts = - typeof llm.requestOptions?.caBundlePath === "string" - ? [llm.requestOptions?.caBundlePath] - : llm.requestOptions?.caBundlePath; - if (customCerts) { - ca.push( - ...customCerts.map((customCert) => fs.readFileSync(customCert, "utf8")), - ); - } - - let timeout = (llm.requestOptions?.timeout ?? TIMEOUT) * 1000; // measured in ms - - const agentOptions = { - ca, - rejectUnauthorized: llm.requestOptions?.verifySsl, - timeout, - sessionTimeout: timeout, - keepAlive: true, - keepAliveMsecs: timeout, - }; - - const proxy = llm.requestOptions?.proxy; - llm._fetch = async (input, init) => { - if (agentOptions.rejectUnauthorized === false) { - console.log("SSL verification is disabled"); - } - - // Create agent - const protocol = new URL(input).protocol === "https:" ? https : http; - const agent = proxy - ? new URL(input).protocol === "https:" - ? new HttpsProxyAgent(proxy, agentOptions) - : new HttpProxyAgent(proxy, agentOptions) - : new protocol.Agent(agentOptions); - - const headers: { [key: string]: string } = - llm!.requestOptions?.headers || {}; - for (const [key, value] of Object.entries(init?.headers || {})) { - headers[key] = value as string; - } - - // Replace localhost with 127.0.0.1 - input = new URL(input); - if (input.hostname === "localhost") { - input.hostname = "127.0.0.1"; - } - - let updatedBody: string | undefined = undefined; - try { - if ( - llm.requestOptions?.extraBodyProperties && - typeof init.body === "string" - ) { - const parsedBody = JSON.parse(init.body); - updatedBody = JSON.stringify({ - ...parsedBody, - ...llm.requestOptions.extraBodyProperties, - }); - } - } catch (e) { - console.log("Unable to parse HTTP request body: ", e); - } - - const resp = await fetch(input, { - ...init, - body: updatedBody ?? init.body, - headers, - agent, - }); + const resp = await fetchwithRequestOptions( + new URL(input), + { ...init }, + llm.requestOptions + ); if (!resp.ok) { let text = await resp.text(); @@ -186,7 +115,7 @@ export class ConfigHandler { } } throw new Error( - `HTTP ${resp.status} ${resp.statusText} from ${resp.url}\n\n${text}`, + `HTTP ${resp.status} ${resp.statusText} from ${resp.url}\n\n${text}` ); } diff --git a/core/context/providers/JiraIssuesContextProvider/JiraClient.ts b/core/context/providers/JiraIssuesContextProvider/JiraClient.ts index b1915d767..573c5549f 100644 --- a/core/context/providers/JiraIssuesContextProvider/JiraClient.ts +++ b/core/context/providers/JiraIssuesContextProvider/JiraClient.ts @@ -1,5 +1,5 @@ - -import type { AxiosInstance } from "axios"; +import { RequestOptions } from "../../.."; +import { fetchwithRequestOptions } from "../../../util/fetchWithOptions"; const { convert: adf2md } = require("adf-to-md"); interface JiraClientOptions { @@ -8,6 +8,7 @@ interface JiraClientOptions { password: string; issueQuery?: string; apiVersion?: string; + requestOptions?: RequestOptions; } interface JiraComment { @@ -63,95 +64,110 @@ export interface Issue { export class JiraClient { private readonly options: Required; - private _api: AxiosInstance | null = null; + private baseUrl: string; + private authHeader; constructor(options: JiraClientOptions) { this.options = { issueQuery: `assignee = currentUser() AND resolution = Unresolved order by updated DESC`, - apiVersion: '3', - ...options + apiVersion: "3", + requestOptions: {}, + ...options, }; - } - - private async getApi() { - if (!this._api) { - - const { default: Axios } = await import("axios"); - - this._api = Axios.create({ - baseURL: `https://${this.options.domain}/rest/api/${this.options.apiVersion}/`, - ...(this.options.username - ? { - auth: { - username: this.options.username, - password: this.options.password, - }, - } - : { - headers: { - Authorization: `Bearer ${this.options.password}`, - }, - }), - }); - } - - return this._api; + this.baseUrl = `https://${this.options.domain}/rest/api/${this.options.apiVersion}`; + this.authHeader = this.options.username + ? { + Authorization: + "Basic " + + btoa(this.options.username + ":" + this.options.password), + } + : { + Authorization: `Bearer ${this.options.password}`, + }; } async issue(issueId: string): Promise { - const api = await this.getApi(); const result = {} as Issue; - const issue = await api - .get(`/issue/${issueId}`, { - params: { - fields: "description,comment,summary", + const response = await fetchwithRequestOptions( + new URL( + this.baseUrl + `/issue/${issueId}?fields=description,comment,summary` + ), + { + method: "GET", + headers: { + "Content-Type": "application/json", + ...this.authHeader, }, - }) - .then((result) => result.data); - + }, + this.options.requestOptions + ); + + const issue = (await response.json()) as any; + result.key = issue.key; result.summary = issue.fields.summary; - - if (typeof issue.fields.description === 'string') { + if (typeof issue.fields.description === "string") { result.description = issue.fields.description; - } else if(issue.fields.description) { + } else if (issue.fields.description) { result.description = adf2md(issue.fields.description).result; } else { result.description = ""; } - result.comments = issue.fields.comment?.comments?.map((comment) => { - const body = typeof comment.body === 'string' ? comment.body : adf2md(comment.body).result; - - return { - body, - author: comment.author, - created: comment.created, - updated: comment.updated, - }; - }) ?? []; + result.comments = + issue.fields.comment?.comments?.map((comment: any) => { + const body = + typeof comment.body === "string" + ? comment.body + : adf2md(comment.body).result; + return { + body, + author: comment.author, + created: comment.created, + updated: comment.updated, + }; + }) ?? []; return result; } async listIssues(): Promise> { - const api = await this.getApi(); - - const results = await api.get("/search", { - params: { - jql: - this.options.issueQuery ?? - `assignee = currentUser() AND resolution = Unresolved order by updated DESC`, - fields: "summary", + const response = await fetchwithRequestOptions( + new URL( + this.baseUrl + + `/search?fields=summary&jql=${ + this.options.issueQuery ?? + `assignee = currentUser() AND resolution = Unresolved order by updated DESC` + }` + ), + { + method: "GET", + headers: { + "Content-Type": "application/json", + ...this.authHeader, + }, }, - }); + this.options.requestOptions + ); - return results.data?.issues?.map((issue) => ({ - id: issue.id, - key: issue.key, - summary: issue.fields.summary, - })) ?? []; + if (response.status != 200) { + console.warn( + "Unable to get jira tickets. Response code from API is", + response.status + ); + return Promise.resolve([]); + } + + const data = (await response.json()) as any; + + return ( + data.issues?.map((issue: any) => ({ + id: issue.id, + key: issue.key, + summary: issue.fields.summary, + })) ?? [] + ); } } diff --git a/core/context/providers/JiraIssuesContextProvider/index.ts b/core/context/providers/JiraIssuesContextProvider/index.ts index be35b22ee..4ee7a4b6a 100644 --- a/core/context/providers/JiraIssuesContextProvider/index.ts +++ b/core/context/providers/JiraIssuesContextProvider/index.ts @@ -23,6 +23,7 @@ class JiraIssuesContextProvider extends BaseContextProvider { password: this.options.token, issueQuery: this.options.issueQuery, apiVersion: this.options.apiVersion, + requestOptions: this.options.requestOptions, }); } diff --git a/core/util/fetchWithOptions.ts b/core/util/fetchWithOptions.ts new file mode 100644 index 000000000..3cac13860 --- /dev/null +++ b/core/util/fetchWithOptions.ts @@ -0,0 +1,81 @@ +import * as fs from "fs"; +import fetch, { RequestInit, Response } from "node-fetch"; +import { http, https } from "follow-redirects"; +import { HttpProxyAgent } from "http-proxy-agent"; +import { HttpsProxyAgent } from "https-proxy-agent"; +import { RequestOptions } from ".."; +import tls from "tls"; + +export function fetchwithRequestOptions( + url: URL, + init: RequestInit, + requestOptions?: RequestOptions +): Promise { + const TIMEOUT = 7200; // 7200 seconds = 2 hours + + const ca = [...tls.rootCertificates]; + const customCerts = + typeof requestOptions?.caBundlePath === "string" + ? [requestOptions?.caBundlePath] + : requestOptions?.caBundlePath; + if (customCerts) { + ca.push( + ...customCerts.map((customCert) => fs.readFileSync(customCert, "utf8")) + ); + } + + let timeout = (requestOptions?.timeout ?? TIMEOUT) * 1000; // measured in ms + + const agentOptions = { + ca, + rejectUnauthorized: requestOptions?.verifySsl, + timeout, + sessionTimeout: timeout, + keepAlive: true, + keepAliveMsecs: timeout, + }; + + const proxy = requestOptions?.proxy; + + // Create agent + const protocol = url.protocol === "https:" ? https : http; + const agent = proxy + ? protocol === https + ? new HttpsProxyAgent(proxy, agentOptions) + : new HttpProxyAgent(proxy, agentOptions) + : new protocol.Agent(agentOptions); + + const headers: { [key: string]: string } = requestOptions?.headers || {}; + for (const [key, value] of Object.entries(init.headers || {})) { + headers[key] = value as string; + } + + // Replace localhost with 127.0.0.1 + if (url.hostname === "localhost") { + url.hostname = "127.0.0.1"; + } + + // add extra body properties if provided + let updatedBody: string | undefined = undefined; + try { + if (requestOptions?.extraBodyProperties && typeof init.body === "string") { + const parsedBody = JSON.parse(init.body); + updatedBody = JSON.stringify({ + ...parsedBody, + ...requestOptions.extraBodyProperties, + }); + } + } catch (e) { + console.log("Unable to parse HTTP request body: ", e); + } + + // fetch the request with the provided options + let resp = fetch(url, { + ...init, + body: updatedBody ?? init.body, + headers: headers, + agent: agent, + }); + + return resp; +} diff --git a/docs/static/schemas/config.json b/docs/static/schemas/config.json index 2e6ffd6b1..2454df1f9 100644 --- a/docs/static/schemas/config.json +++ b/docs/static/schemas/config.json @@ -1362,9 +1362,26 @@ "apiVersion": { "type": "integer", "markdownDescription": "This context provider supports both Jira API version 2 and 3. It will use version 3 by default since that's what the cloud version uses, but if you have the datacenter version of Jira, you'll need to set the API Version to 2 using the `apiVersion` property." + }, + "requestOptions": { + "title": "Request Options", + "description": "Options for the HTTPS request to Jira.", + "default": { + "timeout": 7200, + "verifySsl": null, + "caBundlePath": null, + "proxy": null, + "headers": null, + "extraBodyProperties": null + }, + "allOf": [ + { + "$ref": "#/definitions/RequestOptions" + } + ] } }, - "required": ["domain", "email", "token"] + "required": ["domain", "token"] } }, "required": ["params"] diff --git a/extensions/intellij/src/main/resources/config_schema.json b/extensions/intellij/src/main/resources/config_schema.json index 2e6ffd6b1..2454df1f9 100644 --- a/extensions/intellij/src/main/resources/config_schema.json +++ b/extensions/intellij/src/main/resources/config_schema.json @@ -1362,9 +1362,26 @@ "apiVersion": { "type": "integer", "markdownDescription": "This context provider supports both Jira API version 2 and 3. It will use version 3 by default since that's what the cloud version uses, but if you have the datacenter version of Jira, you'll need to set the API Version to 2 using the `apiVersion` property." + }, + "requestOptions": { + "title": "Request Options", + "description": "Options for the HTTPS request to Jira.", + "default": { + "timeout": 7200, + "verifySsl": null, + "caBundlePath": null, + "proxy": null, + "headers": null, + "extraBodyProperties": null + }, + "allOf": [ + { + "$ref": "#/definitions/RequestOptions" + } + ] } }, - "required": ["domain", "email", "token"] + "required": ["domain", "token"] } }, "required": ["params"] diff --git a/extensions/vscode/config_schema.json b/extensions/vscode/config_schema.json index 2e6ffd6b1..2454df1f9 100644 --- a/extensions/vscode/config_schema.json +++ b/extensions/vscode/config_schema.json @@ -1362,9 +1362,26 @@ "apiVersion": { "type": "integer", "markdownDescription": "This context provider supports both Jira API version 2 and 3. It will use version 3 by default since that's what the cloud version uses, but if you have the datacenter version of Jira, you'll need to set the API Version to 2 using the `apiVersion` property." + }, + "requestOptions": { + "title": "Request Options", + "description": "Options for the HTTPS request to Jira.", + "default": { + "timeout": 7200, + "verifySsl": null, + "caBundlePath": null, + "proxy": null, + "headers": null, + "extraBodyProperties": null + }, + "allOf": [ + { + "$ref": "#/definitions/RequestOptions" + } + ] } }, - "required": ["domain", "email", "token"] + "required": ["domain", "token"] } }, "required": ["params"] diff --git a/extensions/vscode/continue_rc_schema.json b/extensions/vscode/continue_rc_schema.json index 08cdc037c..0cf246324 100644 --- a/extensions/vscode/continue_rc_schema.json +++ b/extensions/vscode/continue_rc_schema.json @@ -1531,11 +1531,27 @@ "apiVersion": { "type": "integer", "markdownDescription": "This context provider supports both Jira API version 2 and 3. It will use version 3 by default since that's what the cloud version uses, but if you have the datacenter version of Jira, you'll need to set the API Version to 2 using the `apiVersion` property." + }, + "requestOptions": { + "title": "Request Options", + "description": "Options for the HTTPS request to Jira.", + "default": { + "timeout": 7200, + "verifySsl": null, + "caBundlePath": null, + "proxy": null, + "headers": null, + "extraBodyProperties": null + }, + "allOf": [ + { + "$ref": "#/definitions/RequestOptions" + } + ] } }, "required": [ "domain", - "email", "token" ] }