diff --git a/packages/core/src/plugin/provider/github-copilot.ts b/packages/core/src/plugin/provider/github-copilot.ts index efb1d43a7f2..61f96a29fb4 100644 --- a/packages/core/src/plugin/provider/github-copilot.ts +++ b/packages/core/src/plugin/provider/github-copilot.ts @@ -2,7 +2,7 @@ import type { IntegrationOAuthMethodRegistration } from "@opencode/plugin/effect import type { SessionRequestKind, SessionTitle } from "@opencode/plugin/effect/session" import { isRecord } from "@opencode/util/record" import { Effect, Option, Schema } from "effect" -import { FetchHttpClient, HttpClient } from "effect/http" +import { FetchHttpClient, HttpClient, HttpClientRequest, HttpClientResponse } from "effect/http" import { IntegrationConnection } from "../../integration/connection.js" import { Credential } from "../../credential.js" import { CopilotModels } from "../../github-copilot/models.js" @@ -104,17 +104,14 @@ const oauth = (app: App.Info) => Effect.flatMap((token) => { if (token.access_token) { const access = token.access_token - return request( - `${domain === "github.com" ? "https://api.github.com" : `https://api.${domain}`}/copilot_internal/user`, - { - headers: { - Accept: "application/json", - Authorization: `Bearer ${access}`, - "User-Agent": App.useragent(app), - "X-GitHub-Api-Version": userApiVersion, - }, + return request(userURL(enterprise ? domain : undefined), { + headers: { + Accept: "application/json", + Authorization: `Bearer ${access}`, + "User-Agent": App.useragent(app), + "X-GitHub-Api-Version": userApiVersion, }, - ).pipe( + }).pipe( Effect.map((user) => Option.getOrUndefined(decodeUser(user))), // Only an explicit entitlement answer blocks login; a failed // or malformed lookup must not turn a GitHub hiccup into a denial. @@ -180,7 +177,43 @@ export const GithubCopilotPlugin = define({ load: Effect.fn("GithubCopilotPlugin.load")(function* (_, options) { const { connection, credential } = yield* activeCredential(ctx, "github-copilot") if (!connection || credential?.type !== "oauth") return { connection, value: {} } - const url = copilotBaseURL(credential.metadata) ?? baseURL() + // The account's API endpoint changes with its plan, so read it again on every refresh; the one stored at + // login is the fallback. + const endpoint = yield* cache + .get({ + key: `github-copilot-endpoint:${IntegrationConnection.key(connection)}`, + ...options, + load: ctx.integration.connection.resolve(connection).pipe( + Effect.flatMap((current) => + current?.type === "oauth" + ? HttpClient.filterStatusOk(http) + .execute( + HttpClientRequest.get( + userURL( + typeof current.metadata?.enterpriseUrl === "string" + ? current.metadata.enterpriseUrl + : undefined, + ), + ).pipe( + HttpClientRequest.setHeaders({ + Accept: "application/json", + Authorization: `Bearer ${current.refresh}`, + "User-Agent": App.useragent(ctx.app), + "X-GitHub-Api-Version": userApiVersion, + }), + ), + ) + .pipe( + Effect.flatMap(HttpClientResponse.schemaBodyJson(User)), + Effect.map((user) => user.endpoints?.api?.replace(/\/+$/, "")), + Effect.timeout("5 seconds"), + ) + : Effect.fail(new Error("GitHub Copilot connection has no OAuth credential")), + ), + ), + }) + .pipe(Effect.orElseSucceed(() => undefined)) + const url = endpoint || copilotBaseURL(credential.metadata) const headers = (yield* providers.get(Provider.ID.githubCopilot))?.headers ?? {} const models = yield* cache .get({ @@ -366,6 +399,10 @@ function oauthURLs(domain: string) { } } +function userURL(enterprise?: string) { + return `${enterprise ? `https://api.${normalizeDomain(enterprise)}` : "https://api.github.com"}/copilot_internal/user` +} + function baseURL(enterprise?: string) { return enterprise ? `https://copilot-api.${normalizeDomain(enterprise)}` : "https://api.githubcopilot.com" } diff --git a/packages/core/test/plugin/provider-github-copilot.test.ts b/packages/core/test/plugin/provider-github-copilot.test.ts index 32635f3cb8f..3a20251627e 100644 --- a/packages/core/test/plugin/provider-github-copilot.test.ts +++ b/packages/core/test/plugin/provider-github-copilot.test.ts @@ -23,7 +23,7 @@ import { Message, SystemPart } from "@opencode/ai/effect" import { Provider } from "@opencode/core/provider" import { Integration } from "@opencode/core/integration" import { Credential } from "@opencode/core/credential" -import { drain } from "../lib/clock" +import { advance, drain } from "../lib/clock" import type { SessionRequestKind } from "@opencode/plugin/effect/session" import { fakeSelectorSdk } from "../fixture/selector" import { testEffect } from "../lib/effect" @@ -85,48 +85,60 @@ describe("GithubCopilotPlugin", () => { expect(copilotEntitlementError({})).toBeUndefined() }) + const copilotAPI = (requests: string[], endpoint = "https://api.business.githubcopilot.com/") => + HttpClient.make((request) => + Effect.sync(() => { + requests.push(request.url) + if (request.url.endsWith("/copilot_internal/user")) + return HttpClientResponse.fromWeb(request, Response.json({ endpoints: { api: endpoint } })) + return HttpClientResponse.fromWeb( + request, + Response.json({ + data: [ + { + model_picker_enabled: true, + id: "gpt-5", + name: "GPT-5", + version: "gpt-5", + capabilities: { + family: "gpt-5", + limits: { max_output_tokens: 1, max_prompt_tokens: 1 }, + supports: { tool_calls: true }, + }, + }, + ], + }), + ) + }), + ) + + const connect = Effect.fn(function* (metadata?: Record) { + const credentials = yield* Credential.Service + const providers = yield* Provider.Service + yield* providers.transform((draft) => { + draft.update(Provider.ID.githubCopilot, () => {}) + }) + yield* credentials.create({ + integrationID: Integration.ID.make("github-copilot"), + value: Credential.OAuth.make({ + type: "oauth", + methodID: Integration.MethodID.make("device"), + access: "token", + refresh: "token", + expires: 0, + ...(metadata ? { metadata } : {}), + }), + }) + }) + it.effect("reloads providers only when a refreshed model list changes", () => Effect.gen(function* () { - const credentials = yield* Credential.Service const providers = yield* Provider.Service - const requests = { count: 0 } - const http = HttpClient.make((request) => - Effect.sync(() => { - requests.count++ - return HttpClientResponse.fromWeb( - request, - Response.json({ - data: [ - { - model_picker_enabled: true, - id: "gpt-5", - name: "GPT-5", - version: "gpt-5", - capabilities: { - family: "gpt-5", - limits: { max_output_tokens: 1, max_prompt_tokens: 1 }, - supports: { tool_calls: true }, - }, - }, - ], - }), - ) - }), - ) - yield* providers.transform((draft) => { - draft.update(Provider.ID.githubCopilot, () => {}) - }) - yield* credentials.create({ - integrationID: Integration.ID.make("github-copilot"), - value: Credential.OAuth.make({ - type: "oauth", - methodID: Integration.MethodID.make("device"), - access: "token", - refresh: "token", - expires: 0, - }), - }) - yield* addPlugin().pipe(Effect.provideService(HttpClient.HttpClient, http)) + const requests: string[] = [] + yield* connect() + const models = () => requests.filter((url) => url.endsWith("/models")) + yield* addPlugin().pipe(Effect.provideService(HttpClient.HttpClient, copilotAPI(requests))) + yield* advance(() => models().length === 1) yield* drain const folds = { count: 0 } yield* providers.transform(() => { @@ -135,12 +147,50 @@ describe("GithubCopilotPlugin", () => { const before = folds.count yield* TestClock.adjust("10 minutes") + yield* advance(() => models().length === 2) yield* drain - expect(requests.count).toBe(2) expect(folds.count).toBe(before) }), ) + it.effect("refreshes the account's API endpoint instead of keeping the one stored at login", () => + Effect.gen(function* () { + const models = yield* Model.Service + const requests: string[] = [] + yield* connect({ apiEndpoint: "https://api.individual.githubcopilot.com" }) + yield* addPlugin().pipe(Effect.provideService(HttpClient.HttpClient, copilotAPI(requests))) + yield* advance(() => requests.some((url) => url.endsWith("/models"))) + yield* drain + + expect(requests).toEqual([ + "https://api.github.com/copilot_internal/user", + "https://api.business.githubcopilot.com/models", + ]) + expect(required(yield* models.get(Provider.ID.githubCopilot, Model.ID.make("gpt-5"))).settings).toMatchObject({ + baseURL: "https://api.business.githubcopilot.com", + }) + }), + ) + + it.effect("keeps the stored endpoint when the account lookup fails", () => + Effect.gen(function* () { + const requests: string[] = [] + yield* connect({ apiEndpoint: "https://api.individual.githubcopilot.com" }) + const failing = HttpClient.make((request) => + request.url.endsWith("/copilot_internal/user") + ? Effect.sync(() => { + requests.push(request.url) + return HttpClientResponse.fromWeb(request, new Response("unavailable", { status: 404 })) + }) + : copilotAPI(requests).execute(request), + ) + yield* addPlugin().pipe(Effect.provideService(HttpClient.HttpClient, failing)) + yield* advance(() => requests.some((url) => url.endsWith("/models"))) + + expect(requests.at(-1)).toBe("https://api.individual.githubcopilot.com/models") + }), + ) + it.effect("registers GitHub Copilot device OAuth", () => Effect.gen(function* () { yield* addPlugin() @@ -359,9 +409,11 @@ describe("GithubCopilotPlugin", () => { const credentials = yield* Credential.Service const providers = yield* Provider.Service const hooks = yield* PluginHooks.Service + const requests: string[] = [] const http = HttpClient.make((request) => - Effect.succeed( - HttpClientResponse.fromWeb( + Effect.sync(() => { + requests.push(request.url) + return HttpClientResponse.fromWeb( request, Response.json({ data: [ @@ -378,8 +430,8 @@ describe("GithubCopilotPlugin", () => { }, ], }), - ), - ), + ) + }), ) const sent: string[] = [] const outbound = Object.assign( @@ -406,6 +458,7 @@ describe("GithubCopilotPlugin", () => { Effect.provideService(HttpClient.HttpClient, http), Effect.provideService(FetchHttpClient.Fetch, outbound), ) + yield* advance(() => requests.some((url) => url.endsWith("/models"))) yield* drain const event = yield* hooks.trigger("session", "title", {