Skip to content

Commit d77e2a5

Browse files
authored
refactor(github-copilot): reuse prepared embedding credentials (#130703)
1 parent 958111c commit d77e2a5

2 files changed

Lines changed: 107 additions & 89 deletions

File tree

‎extensions/github-copilot/embeddings.transport.test.ts‎

Lines changed: 77 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -34,16 +34,19 @@ const DISCOVERY_MODELS_BODY = JSON.stringify({
3434

3535
async function startCopilotServer(handle: {
3636
models: { status: number; body: string } | ((response: ServerResponse) => void);
37-
embeddings?: { status: number; body: string };
37+
embeddings?: { status: number; body: string } | ((response: ServerResponse) => void);
38+
observeRequest?: (request: IncomingMessage, body: string) => void;
3839
}): Promise<CopilotServer> {
3940
const requests: CopilotServer["requests"] = [];
4041
const server = createServer((req: IncomingMessage, res: ServerResponse) => {
4142
void (async () => {
4243
// Drain the request body so keep-alive sockets close cleanly.
43-
await new Promise<void>((resolve) => {
44-
req.resume();
45-
req.on("end", resolve);
44+
const body = await new Promise<string>((resolve) => {
45+
const chunks: Buffer[] = [];
46+
req.on("data", (chunk: Buffer) => chunks.push(chunk));
47+
req.on("end", () => resolve(Buffer.concat(chunks).toString("utf8")));
4648
});
49+
handle.observeRequest?.(req, body);
4750
requests.push({ method: req.method, url: req.url });
4851
const isEmbeddings = req.method === "POST" && req.url === "/embeddings";
4952
const route = isEmbeddings && handle.embeddings ? handle.embeddings : handle.models;
@@ -241,25 +244,75 @@ describe("githubCopilotMemoryEmbeddingProviderAdapter real transport", () => {
241244
}
242245
});
243246

244-
it("returns embedding vectors on a successful response over real transport", async () => {
245-
const server = await startCopilotServer({
246-
models: { status: 200, body: DISCOVERY_MODELS_BODY },
247-
embeddings: {
248-
status: 200,
249-
body: JSON.stringify({ data: [{ index: 0, embedding: [0.1, 0.2, 0.3] }] }),
250-
},
251-
});
252-
pointTokenAt(server.baseUrl);
253-
254-
const result = await githubCopilotMemoryEmbeddingProviderAdapter.create(defaultCreateOptions());
255-
const vector = await result.provider?.embed("hello", { inputType: "query" });
247+
it.each(["profile", "custom"])(
248+
"preserves %s authentication and embedding wire requests",
249+
async (auth) => {
250+
const observed: Array<{
251+
authorization: string | undefined;
252+
integration: unknown;
253+
custom: unknown;
254+
body: string;
255+
}> = [];
256+
const server = await startCopilotServer({
257+
models: { status: 200, body: DISCOVERY_MODELS_BODY },
258+
observeRequest: (request, body) => {
259+
observed.push({
260+
authorization: request.headers.authorization,
261+
integration: request.headers["copilot-integration-id"],
262+
custom: request.headers["x-proof"],
263+
body,
264+
});
265+
},
266+
embeddings: (response) => {
267+
response.writeHead(200, { "content-type": "application/json" });
268+
response.end(
269+
JSON.stringify({
270+
data:
271+
server.requests.length === 2
272+
? [{ index: 0, embedding: [3, 4] }]
273+
: [
274+
{ index: 1, embedding: [0, 2] },
275+
{ index: 0, embedding: [3, 0] },
276+
],
277+
}),
278+
);
279+
},
280+
});
281+
pointTokenAt(server.baseUrl);
256282

257-
expect(server.requests).toEqual([
258-
{ method: "GET", url: "/models" },
259-
{ method: "POST", url: "/embeddings" },
260-
]);
261-
expect(Array.isArray(vector)).toBe(true);
262-
expect(vector).toHaveLength(3);
263-
expect(vector?.every((value) => typeof value === "number")).toBe(true);
264-
});
283+
const result = await githubCopilotMemoryEmbeddingProviderAdapter.create({
284+
...defaultCreateOptions(),
285+
remote: {
286+
...(auth === "custom" ? { baseUrl: server.baseUrl, apiKey: "explicit-test-token" } : {}),
287+
headers: { Authorization: "replaced-test-token", "X-Proof": "forwarded" },
288+
},
289+
});
290+
expect(await result.provider?.embed("hello", { inputType: "query" })).toEqual([0.6, 0.8]);
291+
expect(await result.provider?.embedBatch(["first", { text: "second" }])).toEqual([
292+
[1, 0],
293+
[0, 1],
294+
]);
295+
296+
expect(server.requests).toEqual([
297+
{ method: "GET", url: "/models" },
298+
{ method: "POST", url: "/embeddings" },
299+
{ method: "POST", url: "/embeddings" },
300+
]);
301+
const authorization = `Bearer ${auth === "custom" ? "explicit-test-token" : "copilot_test_token_abc"}`;
302+
expect(observed).toEqual(
303+
[
304+
"",
305+
JSON.stringify({ model: "text-embedding-3-small", input: ["hello"] }),
306+
JSON.stringify({ model: "text-embedding-3-small", input: ["first", "second"] }),
307+
].map((body) => ({
308+
authorization,
309+
integration: "copilot-developer-cli",
310+
custom: "forwarded",
311+
body,
312+
})),
313+
);
314+
expect(resolveFirstGithubTokenMock).toHaveBeenCalledTimes(auth === "custom" ? 0 : 1);
315+
expect(resolveCopilotRuntimeAuthMock).toHaveBeenCalledTimes(auth === "custom" ? 0 : 1);
316+
},
317+
);
265318
});

‎extensions/github-copilot/embeddings.ts‎

Lines changed: 30 additions & 65 deletions
Original file line numberDiff line numberDiff line change
@@ -58,14 +58,10 @@ type CopilotModelEntry = {
5858
};
5959

6060
type GitHubCopilotEmbeddingClient = {
61-
githubToken: string;
6261
model: string;
63-
runtimeAuth?: { apiKey: string; baseUrl: string };
64-
baseUrl?: string;
65-
headers?: Record<string, string>;
66-
env?: NodeJS.ProcessEnv;
67-
fetchImpl?: typeof fetch;
68-
githubDomain?: string;
62+
baseUrl: string;
63+
headers: Record<string, string>;
64+
fetchImpl: typeof fetch;
6965
};
7066

7167
function isCopilotSetupError(err: unknown): boolean {
@@ -221,48 +217,23 @@ function parseGitHubCopilotEmbeddingPayload(payload: unknown, expectedCount: num
221217
return vectors as number[][];
222218
}
223219

224-
async function resolveGitHubCopilotEmbeddingSession(client: GitHubCopilotEmbeddingClient): Promise<{
225-
baseUrl: string;
226-
headers: Record<string, string>;
227-
}> {
228-
const auth =
229-
client.runtimeAuth ??
230-
(await resolveCopilotRuntimeAuth({
231-
githubToken: client.githubToken,
232-
env: client.env,
233-
fetchImpl: client.fetchImpl,
234-
githubDomain: client.githubDomain,
235-
}));
236-
const baseUrl = client.baseUrl?.trim() || auth.baseUrl || DEFAULT_COPILOT_API_BASE_URL;
237-
return {
238-
baseUrl,
239-
headers: {
240-
...COPILOT_HEADERS_STATIC,
241-
...client.headers,
242-
Authorization: `Bearer ${auth.apiKey}`,
243-
},
244-
};
245-
}
246-
247-
async function createGitHubCopilotEmbeddingProvider(
220+
function createGitHubCopilotEmbeddingProvider(
248221
client: GitHubCopilotEmbeddingClient,
249-
): Promise<{ provider: MemoryEmbeddingProvider; client: GitHubCopilotEmbeddingClient }> {
250-
const initialSession = await resolveGitHubCopilotEmbeddingSession(client);
251-
222+
): MemoryEmbeddingProvider {
252223
const embedMany = async (input: string[], signal?: AbortSignal): Promise<number[][]> => {
253224
if (input.length === 0) {
254225
return [];
255226
}
256227

257-
const url = `${initialSession.baseUrl.replace(/\/$/, "")}/embeddings`;
228+
const url = `${client.baseUrl.replace(/\/$/, "")}/embeddings`;
258229
return await withRemoteHttpResponse({
259230
url,
260231
fetchImpl: client.fetchImpl,
261-
ssrfPolicy: buildRemoteBaseUrlPolicy(initialSession.baseUrl),
232+
ssrfPolicy: buildRemoteBaseUrlPolicy(client.baseUrl),
262233
signal,
263234
init: {
264235
method: "POST",
265-
headers: initialSession.headers,
236+
headers: client.headers,
266237
body: JSON.stringify({ model: client.model, input }),
267238
},
268239
onResponse: async (response) => {
@@ -282,29 +253,23 @@ async function createGitHubCopilotEmbeddingProvider(
282253
};
283254

284255
return {
285-
provider: {
286-
id: COPILOT_EMBEDDING_PROVIDER_ID,
287-
model: client.model,
288-
embed: async (input, options) => {
289-
const [vector] = await embedMany(
290-
[typeof input === "string" ? input : input.text],
291-
options?.signal,
292-
);
293-
return vector ?? [];
294-
},
295-
embedBatch: async (inputs, options) => {
296-
const texts = inputs.map((input) => (typeof input === "string" ? input : input.text));
297-
if (options?.inputType === "query") {
298-
return await Promise.all(
299-
texts.map(async (text) => (await embedMany([text], options.signal))[0] ?? []),
300-
);
301-
}
302-
return await embedMany(texts, options?.signal);
303-
},
256+
id: COPILOT_EMBEDDING_PROVIDER_ID,
257+
model: client.model,
258+
embed: async (input, options) => {
259+
const [vector] = await embedMany(
260+
[typeof input === "string" ? input : input.text],
261+
options?.signal,
262+
);
263+
return vector ?? [];
304264
},
305-
client: {
306-
...client,
307-
baseUrl: initialSession.baseUrl,
265+
embedBatch: async (inputs, options) => {
266+
const texts = inputs.map((input) => (typeof input === "string" ? input : input.text));
267+
if (options?.inputType === "query") {
268+
return await Promise.all(
269+
texts.map(async (text) => (await embedMany([text], options.signal))[0] ?? []),
270+
);
271+
}
272+
return await embedMany(texts, options?.signal);
308273
},
309274
};
310275
}
@@ -375,14 +340,14 @@ export const githubCopilotMemoryEmbeddingProviderAdapter: MemoryEmbeddingProvide
375340
const userModel = options.model?.trim() || undefined;
376341
const model = pickBestModel(availableModels, userModel);
377342

378-
const { provider } = await createGitHubCopilotEmbeddingProvider({
343+
const provider = createGitHubCopilotEmbeddingProvider({
379344
baseUrl,
380-
env: process.env,
381345
fetchImpl: fetch,
382-
githubToken: value,
383-
runtimeAuth,
384-
githubDomain,
385-
headers: options.remote?.headers,
346+
headers: {
347+
...COPILOT_HEADERS_STATIC,
348+
...options.remote?.headers,
349+
Authorization: `Bearer ${runtimeAuth.apiKey}`,
350+
},
386351
model,
387352
});
388353

0 commit comments

Comments
 (0)