mirror of
https://github.com/anomalyco/opencode.git
synced 2026-11-18 07:12:47 +03:00
fix(core): refresh the Copilot API endpoint with the model list
This commit is contained in:
@@ -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,9 +104,7 @@ 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`,
|
||||
{
|
||||
return request(userURL(domain), {
|
||||
headers: {
|
||||
Accept: "application/json",
|
||||
Authorization: `Bearer ${access}`,
|
||||
@@ -180,7 +178,37 @@ 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(enterpriseDomain(credential.metadata))).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 +394,14 @@ function oauthURLs(domain: string) {
|
||||
}
|
||||
}
|
||||
|
||||
function userURL(domain: string) {
|
||||
return `${domain === "github.com" ? "https://api.github.com" : `https://api.${domain}`}/copilot_internal/user`
|
||||
}
|
||||
|
||||
function enterpriseDomain(metadata?: Readonly<Record<string, unknown>>) {
|
||||
return typeof metadata?.enterpriseUrl === "string" ? normalizeDomain(metadata.enterpriseUrl) : "github.com"
|
||||
}
|
||||
|
||||
function baseURL(enterprise?: string) {
|
||||
return enterprise ? `https://copilot-api.${normalizeDomain(enterprise)}` : "https://api.githubcopilot.com"
|
||||
}
|
||||
|
||||
@@ -85,48 +85,58 @@ 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<string, string>) {
|
||||
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()
|
||||
yield* addPlugin().pipe(Effect.provideService(HttpClient.HttpClient, copilotAPI(requests)))
|
||||
yield* drain
|
||||
const folds = { count: 0 }
|
||||
yield* providers.transform(() => {
|
||||
@@ -136,11 +146,48 @@ describe("GithubCopilotPlugin", () => {
|
||||
|
||||
yield* TestClock.adjust("10 minutes")
|
||||
yield* drain
|
||||
expect(requests.count).toBe(2)
|
||||
expect(requests.filter((url) => url.endsWith("/models"))).toHaveLength(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* 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* drain
|
||||
|
||||
expect(requests.at(-1)).toBe("https://api.individual.githubcopilot.com/models")
|
||||
}),
|
||||
)
|
||||
|
||||
it.effect("registers GitHub Copilot device OAuth", () =>
|
||||
Effect.gen(function* () {
|
||||
yield* addPlugin()
|
||||
|
||||
Reference in New Issue
Block a user