mirror of
https://github.com/bitbaum/openclaw.git
synced 2026-12-04 14:29:45 +01:00
* fix(github-copilot): honor configured request identity Honor existing provider request headers consistently across model discovery, setup, inference, and embeddings. Preserve the default identity and partition the live catalog by the configured identity. Co-authored-by: Finn763 <165816600+Finn763@users.noreply.github.com> * test(github-copilot): real-behavior wire-trace proof for #127965 * fix(github-copilot proof): print on-disk wire-trace.json sha256 * chore(github-copilot proof): drop pr-body.md from PR diff * fix(github-copilot): finish identity checks and consolidate proof Complete the typed provider fixture and keep the identity constant private. Retain canonical owner tests and real provider evidence; remove parallel copied mock implementations and generated PR-only traces while preserving the diagnostic commits in ancestry. Co-authored-by: Finn763 <165816600+Finn763@users.noreply.github.com> --------- Co-authored-by: Peter Steinberger <steipete@gmail.com> Co-authored-by: Finn763 <Finn763@users.noreply.github.com>
530 lines
18 KiB
TypeScript
530 lines
18 KiB
TypeScript
// Github Copilot tests cover embeddings plugin behavior.
|
|
import { afterAll, afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
|
import { CopilotRuntimeAuthError } from "./runtime-auth-error.js";
|
|
|
|
const resolveFirstGithubTokenMock = vi.hoisted(() => vi.fn());
|
|
const resolveCopilotRuntimeAuthMock = vi.hoisted(() => vi.fn());
|
|
const resolveConfiguredSecretInputStringMock = vi.hoisted(() => vi.fn());
|
|
const fetchWithSsrFGuardMock = vi.hoisted(() => vi.fn());
|
|
|
|
vi.mock("./auth.js", () => ({
|
|
resolveFirstGithubToken: resolveFirstGithubTokenMock,
|
|
}));
|
|
|
|
vi.mock("openclaw/plugin-sdk/secret-input-runtime", () => ({
|
|
resolveConfiguredSecretInputString: resolveConfiguredSecretInputStringMock,
|
|
}));
|
|
|
|
vi.mock("./runtime-auth.js", () => ({
|
|
DEFAULT_COPILOT_API_BASE_URL: "https://example.test",
|
|
resolveCopilotRuntimeAuth: resolveCopilotRuntimeAuthMock,
|
|
}));
|
|
|
|
vi.mock("openclaw/plugin-sdk/ssrf-runtime", () => ({
|
|
fetchWithSsrFGuard: fetchWithSsrFGuardMock,
|
|
}));
|
|
|
|
import { githubCopilotMemoryEmbeddingProviderAdapter } from "./embeddings.js";
|
|
|
|
afterAll(() => {
|
|
vi.doUnmock("./auth.js");
|
|
vi.doUnmock("openclaw/plugin-sdk/secret-input-runtime");
|
|
vi.doUnmock("./runtime-auth.js");
|
|
vi.doUnmock("openclaw/plugin-sdk/ssrf-runtime");
|
|
vi.resetModules();
|
|
});
|
|
|
|
const TEST_BASE_URL = "https://example.test";
|
|
|
|
function shouldContinueAutoSelection(error: Error): boolean {
|
|
const shouldContinue = githubCopilotMemoryEmbeddingProviderAdapter.shouldContinueAutoSelection;
|
|
if (!shouldContinue) {
|
|
throw new Error("GitHub Copilot embedding adapter did not expose auto-selection fallback");
|
|
}
|
|
return shouldContinue(error);
|
|
}
|
|
|
|
function buildModelsResponse(models: Array<{ id: string; supported_endpoints?: unknown }>) {
|
|
return { data: models };
|
|
}
|
|
|
|
function cancelTrackedResponse(
|
|
text: string,
|
|
init: ResponseInit,
|
|
): {
|
|
response: Response;
|
|
wasCanceled: () => boolean;
|
|
} {
|
|
let canceled = false;
|
|
const stream = new ReadableStream<Uint8Array>({
|
|
start(controller) {
|
|
controller.enqueue(new TextEncoder().encode(text));
|
|
},
|
|
cancel() {
|
|
canceled = true;
|
|
},
|
|
});
|
|
return {
|
|
response: new Response(stream, init),
|
|
wasCanceled: () => canceled,
|
|
};
|
|
}
|
|
|
|
function mockDiscoveryResponse(spec: {
|
|
ok: boolean;
|
|
status?: number;
|
|
json?: unknown;
|
|
text?: string;
|
|
}) {
|
|
const status = spec.status ?? (spec.ok ? 200 : 500);
|
|
const response =
|
|
spec.json !== undefined
|
|
? new Response(JSON.stringify(spec.json), {
|
|
status,
|
|
headers: { "Content-Type": "application/json" },
|
|
})
|
|
: new Response(spec.text ?? "", { status });
|
|
fetchWithSsrFGuardMock.mockImplementationOnce(async () => ({
|
|
response,
|
|
release: vi.fn(async () => {}),
|
|
}));
|
|
}
|
|
|
|
function defaultCreateOptions() {
|
|
return {
|
|
config: {} as Record<string, unknown>,
|
|
agentDir: "/tmp/test-agent",
|
|
model: "",
|
|
};
|
|
}
|
|
|
|
function firstCopilotRuntimeAuthRequest() {
|
|
const [call] = resolveCopilotRuntimeAuthMock.mock.calls;
|
|
if (!call) {
|
|
throw new Error("expected resolveCopilotRuntimeAuth call");
|
|
}
|
|
const [request] = call;
|
|
if (!request || typeof request !== "object") {
|
|
throw new Error("expected resolveCopilotRuntimeAuth request");
|
|
}
|
|
return request as { env?: typeof process.env; githubToken?: string };
|
|
}
|
|
|
|
function firstDiscoveryRequest() {
|
|
const [call] = fetchWithSsrFGuardMock.mock.calls;
|
|
if (!call) {
|
|
throw new Error("expected GitHub Copilot discovery request");
|
|
}
|
|
const [request] = call;
|
|
if (!request || typeof request !== "object") {
|
|
throw new Error("expected GitHub Copilot discovery request options");
|
|
}
|
|
return request as {
|
|
init: { headers: Record<string, string> };
|
|
url: string;
|
|
};
|
|
}
|
|
|
|
describe("githubCopilotMemoryEmbeddingProviderAdapter", () => {
|
|
beforeEach(() => {
|
|
resolveConfiguredSecretInputStringMock.mockResolvedValue({});
|
|
resolveFirstGithubTokenMock.mockResolvedValue({
|
|
githubToken: "test-token-placeholder",
|
|
hasProfile: false,
|
|
});
|
|
resolveCopilotRuntimeAuthMock.mockResolvedValue({
|
|
apiKey: "test-token-placeholder",
|
|
source: "test",
|
|
baseUrl: TEST_BASE_URL,
|
|
});
|
|
});
|
|
|
|
afterEach(() => {
|
|
vi.restoreAllMocks();
|
|
vi.unstubAllGlobals();
|
|
resolveConfiguredSecretInputStringMock.mockReset();
|
|
resolveFirstGithubTokenMock.mockReset();
|
|
resolveCopilotRuntimeAuthMock.mockReset();
|
|
fetchWithSsrFGuardMock.mockReset();
|
|
});
|
|
|
|
it("registers the expected adapter metadata", () => {
|
|
expect(githubCopilotMemoryEmbeddingProviderAdapter.id).toBe("github-copilot");
|
|
expect(githubCopilotMemoryEmbeddingProviderAdapter.transport).toBe("remote");
|
|
expect(githubCopilotMemoryEmbeddingProviderAdapter.autoSelectPriority).toBe(15);
|
|
expect(githubCopilotMemoryEmbeddingProviderAdapter.allowExplicitWhenConfiguredAuto).toBe(true);
|
|
});
|
|
|
|
it("picks text-embedding-3-small when available", async () => {
|
|
mockDiscoveryResponse({
|
|
ok: true,
|
|
json: buildModelsResponse([
|
|
{ id: "text-embedding-3-large", supported_endpoints: ["/v1/embeddings"] },
|
|
{ id: "text-embedding-3-small", supported_endpoints: ["/v1/embeddings"] },
|
|
{ id: "gpt-4o", supported_endpoints: ["/v1/chat/completions"] },
|
|
]),
|
|
});
|
|
|
|
const result = await githubCopilotMemoryEmbeddingProviderAdapter.create(defaultCreateOptions());
|
|
|
|
expect(result.provider?.model).toBe("text-embedding-3-small");
|
|
expect(firstCopilotRuntimeAuthRequest().githubToken).toBe("test-token-placeholder");
|
|
});
|
|
|
|
it.each([
|
|
{ label: "enterprise", profileDomain: "acme.ghe.com" },
|
|
{ label: "public", profileDomain: "github.com" },
|
|
])(
|
|
"preserves the selected $label OAuth account's domain for embedding auth",
|
|
async (testCase) => {
|
|
resolveFirstGithubTokenMock.mockResolvedValueOnce({
|
|
githubToken: "durable-github-token",
|
|
githubDomain: testCase.profileDomain,
|
|
hasProfile: true,
|
|
});
|
|
mockDiscoveryResponse({
|
|
ok: true,
|
|
json: buildModelsResponse([
|
|
{ id: "text-embedding-3-small", supported_endpoints: ["/v1/embeddings"] },
|
|
]),
|
|
});
|
|
|
|
await githubCopilotMemoryEmbeddingProviderAdapter.create({
|
|
...defaultCreateOptions(),
|
|
config: {
|
|
models: {
|
|
providers: {
|
|
"github-copilot": {
|
|
baseUrl: "https://api.githubcopilot.com",
|
|
models: [],
|
|
params: { githubDomain: "other.ghe.com" },
|
|
},
|
|
},
|
|
},
|
|
},
|
|
});
|
|
|
|
expect(firstCopilotRuntimeAuthRequest()).toMatchObject({
|
|
githubToken: "durable-github-token",
|
|
githubDomain: testCase.profileDomain,
|
|
});
|
|
},
|
|
);
|
|
|
|
it("matches embedding-capable models when supported_endpoints is missing or malformed", async () => {
|
|
mockDiscoveryResponse({
|
|
ok: true,
|
|
json: buildModelsResponse([
|
|
{ id: "gpt-4o", supported_endpoints: { broken: true } },
|
|
{ id: "text-embedding-3-small", supported_endpoints: [] },
|
|
{ id: "text-embedding-ada-002" },
|
|
]),
|
|
});
|
|
|
|
const result = await githubCopilotMemoryEmbeddingProviderAdapter.create(defaultCreateOptions());
|
|
|
|
expect(result.provider?.model).toBe("text-embedding-3-small");
|
|
});
|
|
|
|
it("strips the provider prefix from a user-selected model", async () => {
|
|
const options = {
|
|
...defaultCreateOptions(),
|
|
model: "github-copilot/text-embedding-3-small",
|
|
};
|
|
expect(githubCopilotMemoryEmbeddingProviderAdapter.normalizeModel?.(options)).toBe(
|
|
"text-embedding-3-small",
|
|
);
|
|
expect(resolveFirstGithubTokenMock).not.toHaveBeenCalled();
|
|
expect(resolveCopilotRuntimeAuthMock).not.toHaveBeenCalled();
|
|
expect(fetchWithSsrFGuardMock).not.toHaveBeenCalled();
|
|
mockDiscoveryResponse({
|
|
ok: true,
|
|
json: buildModelsResponse([
|
|
{ id: "text-embedding-3-small", supported_endpoints: ["/v1/embeddings"] },
|
|
]),
|
|
});
|
|
|
|
const result = await githubCopilotMemoryEmbeddingProviderAdapter.create(options);
|
|
|
|
expect(result.provider?.model).toBe("text-embedding-3-small");
|
|
});
|
|
|
|
it.each([
|
|
"gpt-4o",
|
|
"github-copilot/",
|
|
"github-copilot/github-copilot/text-embedding-3-small",
|
|
"github-copilot/ text-embedding-3-small",
|
|
"github-copilot/\tgithub-copilot/text-embedding-3-small",
|
|
"other/text-embedding-3-small",
|
|
])("rejects the unavailable explicit model %s", async (model) => {
|
|
mockDiscoveryResponse({
|
|
ok: true,
|
|
json: buildModelsResponse([
|
|
{ id: "text-embedding-3-small", supported_endpoints: ["/v1/embeddings"] },
|
|
]),
|
|
});
|
|
|
|
await expect(
|
|
githubCopilotMemoryEmbeddingProviderAdapter.create({
|
|
...defaultCreateOptions(),
|
|
model:
|
|
githubCopilotMemoryEmbeddingProviderAdapter.normalizeModel?.({
|
|
...defaultCreateOptions(),
|
|
model,
|
|
}) ?? model,
|
|
} as never),
|
|
).rejects.toThrow(`GitHub Copilot embedding model "${model}" is not available`);
|
|
});
|
|
|
|
it("throws when discovery finds no embedding models", async () => {
|
|
mockDiscoveryResponse({
|
|
ok: true,
|
|
json: buildModelsResponse([{ id: "gpt-4o", supported_endpoints: ["/v1/chat/completions"] }]),
|
|
});
|
|
|
|
await expect(
|
|
githubCopilotMemoryEmbeddingProviderAdapter.create(defaultCreateOptions()),
|
|
).rejects.toThrow("No embedding models available from GitHub Copilot");
|
|
});
|
|
|
|
it("wraps invalid discovery JSON as a setup error", async () => {
|
|
fetchWithSsrFGuardMock.mockImplementationOnce(async () => ({
|
|
response: new Response("not-valid-json{{{", {
|
|
status: 200,
|
|
headers: { "Content-Type": "application/json" },
|
|
}),
|
|
release: vi.fn(async () => {}),
|
|
}));
|
|
|
|
await expect(
|
|
githubCopilotMemoryEmbeddingProviderAdapter.create(defaultCreateOptions()),
|
|
).rejects.toThrow("github-copilot.model-discovery: malformed JSON response");
|
|
});
|
|
|
|
it("bounds model discovery error bodies", async () => {
|
|
const tracked = cancelTrackedResponse(`${"discovery denied ".repeat(1024)}tail`, {
|
|
status: 503,
|
|
headers: { "content-type": "text/plain" },
|
|
});
|
|
const textSpy = vi.spyOn(tracked.response, "text").mockRejectedValue(new Error("unbounded"));
|
|
fetchWithSsrFGuardMock.mockImplementationOnce(async () => ({
|
|
response: tracked.response,
|
|
release: vi.fn(async () => {}),
|
|
}));
|
|
|
|
let caught: Error | undefined;
|
|
try {
|
|
await githubCopilotMemoryEmbeddingProviderAdapter.create(defaultCreateOptions());
|
|
} catch (error) {
|
|
caught = error as Error;
|
|
}
|
|
|
|
expect(caught?.message).toContain("GitHub Copilot model discovery HTTP 503");
|
|
expect(caught?.message).toContain("discovery denied");
|
|
expect(caught?.message).not.toContain("tail");
|
|
expect(caught?.message.length).toBeLessThan(8_300);
|
|
expect(tracked.wasCanceled()).toBe(true);
|
|
expect(textSpy).not.toHaveBeenCalled();
|
|
expect(resolveCopilotRuntimeAuthMock).toHaveBeenCalledTimes(1);
|
|
});
|
|
|
|
it("bounds embeddings error bodies", async () => {
|
|
mockDiscoveryResponse({
|
|
ok: true,
|
|
json: buildModelsResponse([
|
|
{ id: "text-embedding-3-small", supported_endpoints: ["/v1/embeddings"] },
|
|
]),
|
|
});
|
|
const tracked = cancelTrackedResponse(`${"embedding denied ".repeat(1024)}tail`, {
|
|
status: 429,
|
|
headers: { "content-type": "text/plain" },
|
|
});
|
|
const textSpy = vi.spyOn(tracked.response, "text").mockRejectedValue(new Error("unbounded"));
|
|
const fetchImpl = vi.fn(async () => tracked.response);
|
|
vi.stubGlobal("fetch", fetchImpl);
|
|
const result = await githubCopilotMemoryEmbeddingProviderAdapter.create(defaultCreateOptions());
|
|
|
|
let caught: Error | undefined;
|
|
try {
|
|
await result.provider?.embed("hello", { inputType: "query" });
|
|
} catch (error) {
|
|
caught = error as Error;
|
|
}
|
|
|
|
expect(caught?.message).toContain("GitHub Copilot embeddings HTTP 429");
|
|
expect(caught?.message).toContain("embedding denied");
|
|
expect(caught?.message).not.toContain("tail");
|
|
expect(caught?.message.length).toBeLessThan(8_300);
|
|
expect(tracked.wasCanceled()).toBe(true);
|
|
expect(textSpy).not.toHaveBeenCalled();
|
|
expect(resolveCopilotRuntimeAuthMock).toHaveBeenCalledTimes(1);
|
|
});
|
|
|
|
it.each([
|
|
{ remote: undefined, expected: "vscode-chat" },
|
|
{
|
|
remote: { headers: { "COPILOT-INTEGRATION-ID": "remote-identity" } },
|
|
expected: "remote-identity",
|
|
},
|
|
])(
|
|
"uses the configured integration identity for discovery and embedding requests: $expected",
|
|
async ({ remote, expected }) => {
|
|
mockDiscoveryResponse({
|
|
ok: true,
|
|
json: buildModelsResponse([{ id: "text-embedding-3-small" }]),
|
|
});
|
|
const fetchImpl = vi.fn<typeof fetch>(async () =>
|
|
Response.json({
|
|
data: [{ index: 0, embedding: [1, 0] }],
|
|
}),
|
|
);
|
|
vi.stubGlobal("fetch", fetchImpl);
|
|
const result = await githubCopilotMemoryEmbeddingProviderAdapter.create({
|
|
...defaultCreateOptions(),
|
|
remote,
|
|
config: {
|
|
models: {
|
|
providers: {
|
|
"github-copilot": {
|
|
baseUrl: TEST_BASE_URL,
|
|
models: [],
|
|
headers: {
|
|
"copilot-integration-id": "vscode-chat",
|
|
"X-Private-Header": "not-for-embeddings",
|
|
},
|
|
},
|
|
},
|
|
},
|
|
},
|
|
});
|
|
await result.provider?.embed("hello", { inputType: "query" });
|
|
const discoveryHeaders = new Headers(firstDiscoveryRequest().init.headers);
|
|
const requestHeaders = new Headers(fetchImpl.mock.calls[0]?.[1]?.headers);
|
|
expect(
|
|
[discoveryHeaders, requestHeaders].map((headers) => headers.get("copilot-integration-id")),
|
|
).toEqual([expected, expected]);
|
|
expect(
|
|
[discoveryHeaders, requestHeaders].every((headers) => !headers.has("x-private-header")),
|
|
).toBe(true);
|
|
},
|
|
);
|
|
|
|
it("honors remote overrides when creating the provider", async () => {
|
|
mockDiscoveryResponse({
|
|
ok: true,
|
|
json: buildModelsResponse([
|
|
{ id: "text-embedding-3-small", supported_endpoints: ["/v1/embeddings"] },
|
|
]),
|
|
});
|
|
|
|
await githubCopilotMemoryEmbeddingProviderAdapter.create({
|
|
...defaultCreateOptions(),
|
|
remote: {
|
|
apiKey: "test-token-placeholder",
|
|
baseUrl: "https://proxy.example/v1",
|
|
headers: { "X-Proxy-Token": "test-token-placeholder" },
|
|
},
|
|
} as never);
|
|
|
|
expect(resolveFirstGithubTokenMock).not.toHaveBeenCalled();
|
|
expect(resolveConfiguredSecretInputStringMock).not.toHaveBeenCalled();
|
|
expect(resolveCopilotRuntimeAuthMock).not.toHaveBeenCalled();
|
|
|
|
const discoveryCall = firstDiscoveryRequest();
|
|
expect(discoveryCall.url).toBe("https://proxy.example/v1/models");
|
|
expect(discoveryCall.init.headers["Accept-Encoding"]).toBe("identity");
|
|
expect(discoveryCall.init.headers["Copilot-Integration-Id"]).toBe("copilot-developer-cli");
|
|
expect(discoveryCall.init.headers["X-Proxy-Token"]).toBe("test-token-placeholder");
|
|
});
|
|
|
|
it("does not forward a stored GitHub token to a custom remote endpoint", async () => {
|
|
await expect(
|
|
githubCopilotMemoryEmbeddingProviderAdapter.create({
|
|
...defaultCreateOptions(),
|
|
remote: { baseUrl: "https://proxy.example/v1" },
|
|
} as never),
|
|
).rejects.toThrow("custom baseUrl requires an explicit memory.search.remote.apiKey");
|
|
|
|
expect(resolveFirstGithubTokenMock).not.toHaveBeenCalled();
|
|
expect(resolveCopilotRuntimeAuthMock).not.toHaveBeenCalled();
|
|
expect(fetchWithSsrFGuardMock).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it("does not exchange auth, discover models, or embed after an unavailable owner credential", async () => {
|
|
const fetchMock = vi.fn();
|
|
vi.stubGlobal("fetch", fetchMock);
|
|
resolveFirstGithubTokenMock.mockRejectedValue(
|
|
new Error(
|
|
"providers.github-copilot.authProfiles.github-copilot:github.tokenRef is unresolved",
|
|
),
|
|
);
|
|
|
|
await expect(
|
|
githubCopilotMemoryEmbeddingProviderAdapter.create(defaultCreateOptions()),
|
|
).rejects.toThrow("github-copilot:github.tokenRef is unresolved");
|
|
|
|
expect(resolveCopilotRuntimeAuthMock).not.toHaveBeenCalled();
|
|
expect(fetchWithSsrFGuardMock).not.toHaveBeenCalled();
|
|
expect(fetchMock).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it("rejects an unresolved remote ref without falling back to another profile", async () => {
|
|
await expect(
|
|
githubCopilotMemoryEmbeddingProviderAdapter.create({
|
|
...defaultCreateOptions(),
|
|
remote: {
|
|
apiKey: { source: "env", provider: "default", id: "MISSING_TEST_VALUE" },
|
|
},
|
|
} as never),
|
|
).rejects.toMatchObject({
|
|
name: "UnresolvedSecretInputError",
|
|
path: "memory.search.remote.apiKey",
|
|
});
|
|
expect(resolveFirstGithubTokenMock).not.toHaveBeenCalled();
|
|
expect(resolveCopilotRuntimeAuthMock).not.toHaveBeenCalled();
|
|
expect(resolveConfiguredSecretInputStringMock).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it("includes provider, baseUrl, and model in runtime cache data", async () => {
|
|
mockDiscoveryResponse({
|
|
ok: true,
|
|
json: buildModelsResponse([
|
|
{ id: "text-embedding-3-small", supported_endpoints: ["/v1/embeddings"] },
|
|
]),
|
|
});
|
|
|
|
const result = await githubCopilotMemoryEmbeddingProviderAdapter.create(defaultCreateOptions());
|
|
|
|
expect(result.runtime).toEqual({
|
|
id: "github-copilot",
|
|
cacheKeyData: {
|
|
provider: "github-copilot",
|
|
baseUrl: TEST_BASE_URL,
|
|
model: "text-embedding-3-small",
|
|
},
|
|
});
|
|
});
|
|
|
|
it("treats authentication and discovery failures as auto-fallback errors", () => {
|
|
expect(
|
|
shouldContinueAutoSelection(new Error("Copilot user response missing endpoints.api")),
|
|
).toBe(true);
|
|
expect(
|
|
shouldContinueAutoSelection(
|
|
new Error("Unexpected response from GitHub Copilot user endpoint"),
|
|
),
|
|
).toBe(true);
|
|
expect(
|
|
shouldContinueAutoSelection(
|
|
new Error("github-copilot.model-discovery: malformed JSON response"),
|
|
),
|
|
).toBe(true);
|
|
expect(
|
|
shouldContinueAutoSelection(
|
|
new CopilotRuntimeAuthError({ reason: "timeout", timeoutMs: 30_000 }),
|
|
),
|
|
).toBe(true);
|
|
expect(shouldContinueAutoSelection(new Error("Network timeout"))).toBe(false);
|
|
});
|
|
});
|