Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
110 changes: 58 additions & 52 deletions packages/core/src/plugin/provider/chatgpt.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,15 @@
import type { IntegrationOAuthMethodRegistration } from "@opencode/plugin/effect/integration"
import type { Context } from "@opencode/plugin/effect/plugin"
import { define } from "@opencode/plugin/effect/plugin"
import { Deferred, Duration, Effect, Option, Schema, Semaphore, Stream } from "effect"
// import { Deferred, Duration, Effect, Option, Schema, Semaphore, Stream } from "effect"
import { Deferred, Effect, Option, Schema, Semaphore, Stream } from "effect"
import { HttpClient, HttpClientRequest, HttpClientResponse } from "effect/unstable/http"
import type { Server, ServerResponse } from "node:http"
import { App } from "../../app.js"
import { Credential } from "../../credential.js"
import { Bus } from "../../bus.js"
import { Integration } from "../../integration.js"
import { IntegrationConnection } from "../../integration/connection.js"
// import { IntegrationConnection } from "../../integration/connection.js"
import { Model } from "../../model.js"
import { OauthCallbackPage } from "../../oauth/page.js"
import { Provider } from "../../provider.js"
Expand Down Expand Up @@ -36,6 +37,12 @@ const fallbackModels = new Set([
"gpt-5.6-terra-fast",
"gpt-6-astra",
"gpt-6-astra-fast",
"gpt-6-luna",
"gpt-6-luna-fast",
"gpt-6-sol",
"gpt-6-sol-fast",
"gpt-6.1-sol",
"gpt-6.1-sol-fast",
])
const nonRetryableSharingCodes = [
"subscription_sharing_usage_limit_exceeded",
Expand Down Expand Up @@ -204,22 +211,22 @@ export const ChatGPTPlugin = define({
const credentials = yield* Credential.Service
const loading = Semaphore.makeUnsafe(1)
let chatgpt: Credential.OAuth | undefined
let available: ReadonlyArray<RemoteModel> | undefined
// let available: ReadonlyArray<RemoteModel> | undefined
let source: Effect.Success<ReturnType<typeof ctx.integration.connection.active>>

const load = Effect.fn("ChatGPTPlugin.load")(function* () {
const previous = IntegrationConnection.key(source)
// const previous = IntegrationConnection.key(source)
const connection = yield* ctx.integration.connection.active(integrationID)
const credential = connection
? yield* ctx.integration.connection.resolve(connection).pipe(Effect.orElseSucceed(() => undefined))
: undefined
chatgpt = credential?.type === "oauth" && credential.methodID === methodID ? credential : undefined
source = chatgpt ? connection : undefined
if (previous !== IntegrationConnection.key(source)) {
const metadata = Option.getOrUndefined(decodeMetadata(chatgpt?.metadata))
const stored = metadata ? yield* ctx.storage.get(modelCacheKey(metadata.clientID)) : undefined
available = Option.getOrUndefined(decodeCachedModels(stored))
}
// if (previous !== IntegrationConnection.key(source)) {
// const metadata = Option.getOrUndefined(decodeMetadata(chatgpt?.metadata))
// const stored = metadata ? yield* ctx.storage.get(modelCacheKey(metadata.clientID)) : undefined
// available = Option.getOrUndefined(decodeCachedModels(stored))
// }
})

yield* ctx.integration.transform((editor) => {
Expand Down Expand Up @@ -272,9 +279,10 @@ export const ChatGPTPlugin = define({
if (!updated) return
providers.add({
info: updated.provider,
models: available
? deriveModels(available, Array.from(item.models.values()))
: Array.from(item.models.values()).filter((model) => fallbackModels.has(model.id)),
// models: available
// ? deriveModels(available, Array.from(item.models.values()))
// : Array.from(item.models.values()).filter((model) => fallbackModels.has(model.id)),
models: Array.from(item.models.values()).filter((model) => fallbackModels.has(model.id)),
sourceConnection: source,
})
})
Expand All @@ -288,55 +296,53 @@ export const ChatGPTPlugin = define({
draft.enabled = false
return
}
if (available && !available.some((remote) => remote.slug === (draft.modelID ?? draft.id))) {
draft.enabled = false
return
}
// if (available && !available.some((remote) => remote.slug === (draft.modelID ?? draft.id))) {
// draft.enabled = false
// return
// }
draft.cost = []
})
}
})
const refreshModels = Effect.fn("ChatGPTPlugin.refreshModels")(function* () {
const connection = source
const credential =
connection?.type === "credential"
? (yield* credentials.get(Credential.ID.make(connection.id)))?.value
: undefined
if (credential?.type !== "oauth" || credential.methodID !== methodID || credential.expires <= Date.now() + 60_000)
return
const metadata = Option.getOrUndefined(decodeMetadata(credential.metadata))
if (!metadata) return
const models = yield* fetchModels(credential.access, ctx.app).pipe(
Effect.timeout(15_000),
Effect.catch(() => Effect.logWarning("failed to refresh ChatGPT models").pipe(Effect.as(undefined))),
)
if (!models) return
yield* loading.withPermit(
Effect.gen(function* () {
if (
IntegrationConnection.key(connection) !== IntegrationConnection.key(source) ||
IntegrationConnection.key(connection) !==
IntegrationConnection.key(yield* ctx.integration.connection.active(integrationID))
)
return
if (JSON.stringify(models) === JSON.stringify(available)) return
yield* ctx.storage.set(modelCacheKey(metadata.clientID), models)
available = models
yield* ctx.provider.reload()
}),
)
})
const reload = () =>
loading
.withPermit(load().pipe(Effect.andThen(ctx.provider.reload())))
.pipe(Effect.andThen(refreshModels().pipe(Effect.forkScoped, Effect.asVoid)))
// const refreshModels = Effect.fn("ChatGPTPlugin.refreshModels")(function* () {
// const connection = source
// const credential =
// connection?.type === "credential"
// ? (yield* credentials.get(Credential.ID.make(connection.id)))?.value
// : undefined
// if (credential?.type !== "oauth" || credential.methodID !== methodID || credential.expires <= Date.now() + 60_000)
// return
// const metadata = Option.getOrUndefined(decodeMetadata(credential.metadata))
// if (!metadata) return
// const models = yield* fetchModels(credential.access, ctx.app).pipe(
// Effect.timeout(15_000),
// Effect.catch(() => Effect.logWarning("failed to refresh ChatGPT models").pipe(Effect.as(undefined))),
// )
// if (!models) return
// yield* loading.withPermit(
// Effect.gen(function* () {
// if (
// IntegrationConnection.key(connection) !== IntegrationConnection.key(source) ||
// IntegrationConnection.key(connection) !==
// IntegrationConnection.key(yield* ctx.integration.connection.active(integrationID))
// )
// return
// if (JSON.stringify(models) === JSON.stringify(available)) return
// yield* ctx.storage.set(modelCacheKey(metadata.clientID), models)
// available = models
// yield* ctx.provider.reload()
// }),
// )
// })
const reload = () => loading.withPermit(load().pipe(Effect.andThen(ctx.provider.reload())))
// .pipe(Effect.andThen(refreshModels().pipe(Effect.forkScoped, Effect.asVoid)))
yield* bus.subscribe(Credential.Event.Switched).pipe(
Stream.filter((event) => event.data.integrationID === integrationID),
Stream.runForEach(reload),
Effect.forkScoped({ startImmediately: true }),
)
yield* refreshModels().pipe(Effect.forkScoped)
yield* Effect.sleep(Duration.minutes(15)).pipe(Effect.andThen(refreshModels), Effect.forever, Effect.forkScoped)
// yield* refreshModels().pipe(Effect.forkScoped)
// yield* Effect.sleep(Duration.minutes(15)).pipe(Effect.andThen(refreshModels), Effect.forever, Effect.forkScoped)
}),
} satisfies PluginInternal.InternalPlugin)

Expand Down
Loading
Loading