mirror of
https://github.com/anomalyco/opencode.git
synced 2026-09-29 20:17:40 +00:00
Compare commits
12
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
0f83038253 | ||
|
|
4c33a253aa | ||
|
|
135995d4fc | ||
|
|
4d9090790b | ||
|
|
621a5b0706 | ||
|
|
16ef62c851 | ||
|
|
b694d2bf26 | ||
|
|
89d37a0f6d | ||
|
|
bc5ff1cfd9 | ||
|
|
c14a1f5acf | ||
|
|
7db941a892 | ||
|
|
83fafda63a |
@@ -377,6 +377,7 @@
|
||||
"https-proxy-agent": "7.0.6",
|
||||
"ignore": "7.0.5",
|
||||
"immer": "11.1.4",
|
||||
"jose": "6.0.11",
|
||||
"jsonc-parser": "3.3.1",
|
||||
"mime-types": "3.0.2",
|
||||
"tree-sitter-bash": "0.25.0",
|
||||
|
||||
@@ -4996,6 +4996,42 @@ describe("OpenAI Responses route", () => {
|
||||
}),
|
||||
)
|
||||
|
||||
it.effect("retains the token-sharing HTTP 429 body for retry hooks", () =>
|
||||
Effect.gen(function* () {
|
||||
const body = JSON.stringify({ error: { code: "subscription_sharing_usage_limit_exceeded", message: "Rate limit exceeded" } })
|
||||
const error = yield* LLMClient.generate(request).pipe(
|
||||
Effect.provide(
|
||||
fixedResponse(body, { status: 429, headers: { "content-type": "application/json" } }),
|
||||
),
|
||||
Effect.flip,
|
||||
)
|
||||
|
||||
expect(error).toMatchObject({ reason: { _tag: "RateLimit", http: { status: 429 }, body } })
|
||||
}),
|
||||
)
|
||||
|
||||
it.effect("retains the token-sharing response.failed event for retry hooks", () =>
|
||||
Effect.gen(function* () {
|
||||
const error = yield* LLMClient.generate(request).pipe(
|
||||
Effect.provide(
|
||||
fixedResponse(
|
||||
sseEvents({
|
||||
type: "response.failed",
|
||||
response: {
|
||||
id: "resp_usage_limit",
|
||||
error: { code: "subscription_sharing_usage_limit_exceeded", message: "Rate limit exceeded" },
|
||||
},
|
||||
}),
|
||||
),
|
||||
),
|
||||
Effect.flip,
|
||||
)
|
||||
|
||||
expect(error).toMatchObject({ reason: { _tag: "RateLimit" } })
|
||||
expect(error.reason.body).toContain("subscription_sharing_usage_limit_exceeded")
|
||||
}),
|
||||
)
|
||||
|
||||
it.effect("surfaces response.failed code when no nested message is present", () =>
|
||||
Effect.gen(function* () {
|
||||
const error = yield* LLMClient.generate(request).pipe(
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
import { Button } from "@opencode/ui/button"
|
||||
import { useDialog } from "@opencode/ui/context/dialog"
|
||||
import { onMount } from "solid-js"
|
||||
import { DialogChatGPTUsageLimit } from "./chatgpt-usage-limit"
|
||||
|
||||
function UsageLimitStory() {
|
||||
const dialog = useDialog()
|
||||
const open = () => dialog.show(() => <DialogChatGPTUsageLimit />)
|
||||
onMount(open)
|
||||
|
||||
return (
|
||||
<Button variant="neutral" onClick={open}>
|
||||
Open ChatGPT usage limit
|
||||
</Button>
|
||||
)
|
||||
}
|
||||
|
||||
export default {
|
||||
title: "App/Dialogs/Connect Provider",
|
||||
id: "app-dialog-chatgpt-usage-limit",
|
||||
}
|
||||
|
||||
export const ChatGPTUsageLimit = { render: () => <UsageLimitStory /> }
|
||||
@@ -0,0 +1,48 @@
|
||||
import { Button } from "@opencode/ui/button"
|
||||
import { useDialog } from "@opencode/ui/context/dialog"
|
||||
import { Dialog, DialogTitle } from "@opencode/ui/dialog"
|
||||
import { ProviderIcon } from "@opencode/ui/provider-icon"
|
||||
import { useLanguage } from "@/runtime/i18n/language"
|
||||
import { usePlatform } from "@/runtime/platform/platform"
|
||||
|
||||
export function DialogChatGPTUsageLimit() {
|
||||
const dialog = useDialog()
|
||||
const language = useLanguage()
|
||||
const platform = usePlatform()
|
||||
|
||||
return (
|
||||
<Dialog fit containerClass="!w-[min(calc(100vw_-_32px),390px)] !rounded-xl">
|
||||
<div class="flex w-full flex-col items-center px-8 pb-8 pt-9 text-center [font-family:var(--v2-font-family-sans)]">
|
||||
<ProviderIcon id="openai" class="!size-12 text-v2-icon-icon-base" aria-hidden="true" />
|
||||
<div class="mt-6 max-w-[270px] text-[20px] font-[530] leading-7 tracking-[-0.3px] text-v2-text-text-base">
|
||||
<DialogTitle>
|
||||
<bdi dir="auto">{language.t("provider.connect.chatgptUsageLimit.title")}</bdi>
|
||||
</DialogTitle>
|
||||
</div>
|
||||
<p class="mt-3 text-[13px] leading-5 text-v2-text-text-muted">
|
||||
<bdi dir="auto">{language.t("provider.connect.chatgptUsageLimit.description")}</bdi>
|
||||
</p>
|
||||
<Button
|
||||
variant="contrast"
|
||||
size="large"
|
||||
class="mt-8 w-full"
|
||||
autofocus
|
||||
onClick={() => {
|
||||
platform.openExternal("https://chatgpt.com/#settings/Usage")
|
||||
dialog.close()
|
||||
}}
|
||||
>
|
||||
{language.t("provider.connect.chatgptUsageLimit.manage")}
|
||||
</Button>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="large"
|
||||
class="mt-2 w-full"
|
||||
onClick={() => dialog.close()}
|
||||
>
|
||||
{language.t("provider.connect.chatgptUsageLimit.close")}
|
||||
</Button>
|
||||
</div>
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
import { Button } from "@opencode/ui/button"
|
||||
import { useDialog } from "@opencode/ui/context/dialog"
|
||||
import { onMount } from "solid-js"
|
||||
import { DialogChatGPTPlanWelcome } from "./chatgpt-welcome"
|
||||
|
||||
function WelcomeStory() {
|
||||
const dialog = useDialog()
|
||||
const open = () => dialog.show(() => <DialogChatGPTPlanWelcome />)
|
||||
onMount(open)
|
||||
|
||||
return (
|
||||
<Button variant="neutral" onClick={open}>
|
||||
Open ChatGPT plan welcome
|
||||
</Button>
|
||||
)
|
||||
}
|
||||
|
||||
export default {
|
||||
title: "App/Dialogs/Connect Provider",
|
||||
id: "app-dialog-chatgpt-welcome",
|
||||
}
|
||||
|
||||
export const ChatGPTPlanWelcome = { render: () => <WelcomeStory /> }
|
||||
@@ -0,0 +1,37 @@
|
||||
import { Button } from "@opencode/ui/button"
|
||||
import { useDialog } from "@opencode/ui/context/dialog"
|
||||
import { Dialog, DialogTitle } from "@opencode/ui/dialog"
|
||||
import { ProviderIcon } from "@opencode/ui/provider-icon"
|
||||
import { useLanguage } from "@/runtime/i18n/language"
|
||||
import { ExternalLink } from "@/runtime/platform/external-link"
|
||||
|
||||
export function DialogChatGPTPlanWelcome() {
|
||||
const dialog = useDialog()
|
||||
const language = useLanguage()
|
||||
|
||||
return (
|
||||
<Dialog fit containerClass="!w-[min(calc(100vw_-_32px),390px)] !rounded-xl">
|
||||
<div class="flex w-full flex-col items-center px-8 pb-8 pt-9 text-center [font-family:var(--v2-font-family-sans)]">
|
||||
<ProviderIcon id="openai" class="!size-12 text-v2-icon-icon-base" aria-hidden="true" />
|
||||
<div class="mt-6 max-w-[270px] text-[20px] font-[530] leading-7 tracking-[-0.3px] text-v2-text-text-base">
|
||||
<DialogTitle>
|
||||
<bdi dir="auto">{language.t("provider.connect.chatgptWelcome.title")}</bdi>
|
||||
</DialogTitle>
|
||||
</div>
|
||||
<p class="mt-3 text-[13px] leading-5 text-v2-text-text-muted">
|
||||
<bdi dir="auto">{language.t("provider.connect.chatgptWelcome.description")}</bdi>
|
||||
</p>
|
||||
<ExternalLink
|
||||
href="https://chatgpt.com/#settings/Usage"
|
||||
dir="auto"
|
||||
class="mt-1 rounded-sm text-[13px] leading-5 text-v2-text-text-muted underline-offset-2 hover:text-v2-text-text-base focus-visible:outline focus-visible:outline-2"
|
||||
>
|
||||
{language.t("provider.connect.chatgptWelcome.usage")}
|
||||
</ExternalLink>
|
||||
<Button variant="contrast" size="large" class="mt-8 w-full" autofocus onClick={() => dialog.close()}>
|
||||
{language.t("provider.connect.chatgptWelcome.confirm")}
|
||||
</Button>
|
||||
</div>
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
@@ -39,6 +39,9 @@ import { OpenCodeLogo } from "@/providers/opencode-logo"
|
||||
import { decode64 } from "@/runtime/persistence/base64"
|
||||
import { SettingsList } from "@/settings/list"
|
||||
import { useTabs } from "@/shell/tabs/tabs"
|
||||
import { Persist, persisted } from "@/runtime/persistence/storage"
|
||||
import { Persistence } from "@/runtime/persistence/schema"
|
||||
import { Schema } from "effect"
|
||||
import {
|
||||
CONSOLE_INTEGRATION,
|
||||
CONSOLE_PROVIDERS,
|
||||
@@ -48,6 +51,7 @@ import {
|
||||
type ProviderConnectMethod,
|
||||
} from "./controller"
|
||||
import { ConsoleAuthorization } from "./console"
|
||||
import { DialogChatGPTPlanWelcome } from "./chatgpt-welcome"
|
||||
import { authServerName, RemoteAuthNotice } from "./remote"
|
||||
import "./models.css"
|
||||
|
||||
@@ -81,8 +85,15 @@ export const DialogConnectProvider: Component<{
|
||||
completed: false,
|
||||
modelProvider: undefined as { id: string; name: string } | undefined,
|
||||
authorization: false,
|
||||
chatgptWelcome: false,
|
||||
})
|
||||
const language = useLanguage()
|
||||
const dialog = useDialog()
|
||||
const [welcome, setWelcome, , welcomeReady] = persisted(
|
||||
Persist.global("chatgpt-plan-welcome.v1"),
|
||||
Persistence.struct({ seen: Schema.Boolean }),
|
||||
{ seen: false },
|
||||
)
|
||||
const reset = controller.reset
|
||||
const back = { current: reset }
|
||||
const consoleSelected = () => CONSOLE_PROVIDERS.has(controller.selected() ?? "")
|
||||
@@ -112,7 +123,11 @@ export const DialogConnectProvider: Component<{
|
||||
setBack={(handler) => (back.current = handler)}
|
||||
selection={props.selection}
|
||||
onDone={props.onDone ? () => setState("completed", true) : undefined}
|
||||
onConnected={() => props.onConnected?.(provider)}
|
||||
onConnected={(methodID) => {
|
||||
props.onConnected?.(provider)
|
||||
if (provider === "openai" && methodID === "chatgpt-token-sharing")
|
||||
setState("chatgptWelcome", true)
|
||||
}}
|
||||
onFirstConnection={(provider) => setState("modelProvider", provider)}
|
||||
onAuthorization={(authorization) => setState("authorization", authorization)}
|
||||
/>
|
||||
@@ -136,9 +151,16 @@ export const DialogConnectProvider: Component<{
|
||||
: "!h-[min(calc(100vh_-_16px),512px)] !w-[min(calc(100vw_-_16px),640px)]"
|
||||
}
|
||||
onCloseAutoFocus={(event) => {
|
||||
if (!state.completed || !props.onDone) return
|
||||
event.preventDefault()
|
||||
props.onDone()
|
||||
if (state.completed && props.onDone) {
|
||||
event.preventDefault()
|
||||
props.onDone()
|
||||
}
|
||||
if (!state.chatgptWelcome) return
|
||||
void Promise.resolve(welcomeReady.promise).then(() => {
|
||||
if (welcome.seen) return
|
||||
setWelcome("seen", true)
|
||||
void dialog.show(() => <DialogChatGPTPlanWelcome />)
|
||||
})
|
||||
}}
|
||||
class="[font-family:var(--v2-font-family-sans)] [&_[data-slot=dialog-header]]:!px-5 [&_[data-slot=dialog-header-title]]:!text-[15px] [&_[data-slot=dialog-header-title]]:!tracking-[-0.13px]"
|
||||
classList={{
|
||||
@@ -354,7 +376,7 @@ function ProviderConnection(props: {
|
||||
setBack: (handler: () => void) => void
|
||||
selection?: ModelSelection
|
||||
onDone?: () => void
|
||||
onConnected?: () => void
|
||||
onConnected?: (methodID?: string) => void
|
||||
onFirstConnection: (provider: { id: string; name: string }) => void
|
||||
onAuthorization: (authorization: boolean) => void
|
||||
}) {
|
||||
@@ -401,7 +423,8 @@ function ProviderConnection(props: {
|
||||
prepare: isConsole ? prepareConsoleCatalog : undefined,
|
||||
pollInterval: isConsole ? 500 : undefined,
|
||||
onComplete: () => {
|
||||
props.onConnected?.()
|
||||
const method = controller.currentMethod()
|
||||
props.onConnected?.(method?.type === "oauth" ? method.id : undefined)
|
||||
// The picker only lists the newest model per family by default, which hides most of
|
||||
// what a new connection just unlocked. Show everything the connected integration offers.
|
||||
global.models.show(
|
||||
|
||||
@@ -0,0 +1,78 @@
|
||||
import { Button } from "@opencode/ui/button"
|
||||
import { createSignal } from "solid-js"
|
||||
import type { ModelSelection } from "./selection"
|
||||
import { ModelSelectorPopoverView } from "./select-dialog"
|
||||
|
||||
const chatgpt = {
|
||||
id: "gpt-5.6-sol",
|
||||
providerID: "openai",
|
||||
api: { id: "gpt-5.6-sol", url: "https://api.openai.com/v1", npm: "@opencode/ai/providers/openai" },
|
||||
name: "GPT-5.6 Sol",
|
||||
family: "gpt",
|
||||
capabilities: {
|
||||
temperature: true,
|
||||
reasoning: true,
|
||||
attachment: true,
|
||||
toolcall: true,
|
||||
input: { text: true, audio: false, image: true, video: false, pdf: false },
|
||||
output: { text: true, audio: false, image: false, video: false, pdf: false },
|
||||
interleaved: true,
|
||||
},
|
||||
cost: { input: 0, output: 0, cache: { read: 0, write: 0 } },
|
||||
limit: { context: 400_000, output: 64_000 },
|
||||
status: "active",
|
||||
options: {},
|
||||
headers: {},
|
||||
release_date: "2026-09-01",
|
||||
variants: {},
|
||||
provider: {
|
||||
id: "openai",
|
||||
name: "OpenAI",
|
||||
source: "custom",
|
||||
env: [],
|
||||
options: {},
|
||||
models: {},
|
||||
},
|
||||
latest: true,
|
||||
} satisfies NonNullable<ReturnType<ModelSelection["current"]>>
|
||||
|
||||
const models = [
|
||||
chatgpt,
|
||||
{
|
||||
...chatgpt,
|
||||
id: "gpt-5.6-terra",
|
||||
api: { ...chatgpt.api, id: "gpt-5.6-terra" },
|
||||
name: "GPT-5.6 Terra",
|
||||
latest: false,
|
||||
},
|
||||
]
|
||||
|
||||
function SelectorStory(props: { plan: boolean }) {
|
||||
const [current, setCurrent] = createSignal(models[0].id)
|
||||
return (
|
||||
<div class="flex min-h-[280px] items-end justify-center">
|
||||
<ModelSelectorPopoverView
|
||||
trigger={(trigger) => (
|
||||
<Button {...trigger} variant="ghost-muted">
|
||||
{models.find((model) => model.id === current())?.name}
|
||||
</Button>
|
||||
)}
|
||||
models={(search) => models.filter((model) => model.name.toLowerCase().includes(search.toLowerCase()))}
|
||||
groups={(items) => [{ category: "openai", items }]}
|
||||
current={`openai:${current()}`}
|
||||
chatgptPlan={props.plan}
|
||||
select={(item) => setCurrent(item.id)}
|
||||
onManage={() => undefined}
|
||||
onClose={() => undefined}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default {
|
||||
title: "App/Dialogs/Model Selector",
|
||||
id: "app-dialog-model-selector",
|
||||
}
|
||||
|
||||
export const ChatGPTPlan = { render: () => <SelectorStory plan /> }
|
||||
export const ApiKey = { render: () => <SelectorStory plan={false} /> }
|
||||
@@ -15,13 +15,16 @@ import { Menu } from "@opencode/ui/menu"
|
||||
import { TextInput } from "@opencode/ui/text-input"
|
||||
import { ModelTooltip } from "./tooltip"
|
||||
import { useLanguage } from "@/runtime/i18n/language"
|
||||
import { ExternalLink } from "@/runtime/platform/external-link"
|
||||
import { useData } from "@/runtime/server/current"
|
||||
import { useWorkspaceLocation } from "@/workspaces/location"
|
||||
import { decode64 } from "@/runtime/persistence/base64"
|
||||
import { handleDocumentSearchKeydown } from "@/shell/commands/search-keydown"
|
||||
import { createMenuDismissController } from "@/shell/commands/menu-dismiss"
|
||||
import { createEventListener } from "@solid-primitives/event-listener"
|
||||
import { matchesModelSearch } from "./search"
|
||||
import { SettingsList } from "@/settings/list"
|
||||
import { CONSOLE_GROUP_KEY, consoleModelGroup, ProviderModelSections } from "@/providers/models/provider-group"
|
||||
import { CONSOLE_GROUP_KEY, consoleModelGroup, ProviderModelIcon, ProviderModelSections } from "@/providers/models/provider-group"
|
||||
import "@/settings/settings.css"
|
||||
|
||||
const isFree = (provider: string, cost: { input: number } | undefined) =>
|
||||
@@ -218,11 +221,21 @@ export function ModelSelectorPopover(props: {
|
||||
onClose?: () => void
|
||||
}) {
|
||||
const dialog = useDialog()
|
||||
const data = useData()
|
||||
const location = useWorkspaceLocation()
|
||||
const controller = createModelSelectorController({
|
||||
model: props.model,
|
||||
provider: () => props.provider,
|
||||
onSelect: () => props.onClose?.(),
|
||||
})
|
||||
const chatgptPlan = () => {
|
||||
if (!controller.current()?.startsWith("openai:")) return false
|
||||
const connection = data.location.integration
|
||||
.list(location().ref)
|
||||
?.find((integration) => integration.id === "openai")
|
||||
?.connections[0]
|
||||
return connection?.type === "credential" && connection.method === "oauth"
|
||||
}
|
||||
|
||||
return (
|
||||
<ModelSelectorPopoverView
|
||||
@@ -230,6 +243,7 @@ export function ModelSelectorPopover(props: {
|
||||
models={controller.models}
|
||||
groups={controller.groups}
|
||||
current={controller.current()}
|
||||
chatgptPlan={chatgptPlan()}
|
||||
select={controller.select}
|
||||
onManage={() => {
|
||||
void import("./manage").then((module) => {
|
||||
@@ -281,11 +295,12 @@ function createModelSelectorController(input: {
|
||||
}
|
||||
}
|
||||
|
||||
function ModelSelectorPopoverView(props: {
|
||||
export function ModelSelectorPopoverView(props: {
|
||||
trigger: ModelSelectorTrigger
|
||||
models: (search: string) => ModelItem[]
|
||||
groups: (models: ModelItem[]) => { category: string; items: ModelItem[] }[]
|
||||
current: string | undefined
|
||||
chatgptPlan?: boolean
|
||||
select: (item: ModelItem) => void
|
||||
onManage: () => void
|
||||
onClose: () => void
|
||||
@@ -368,7 +383,8 @@ function ModelSelectorPopoverView(props: {
|
||||
<Menu.Portal>
|
||||
<Menu.Content
|
||||
ref={(element: HTMLDivElement) => (contentRef = element)}
|
||||
class="w-[284px] overflow-hidden rounded-md border-0 bg-v2-background-bg-layer-01 !p-0 shadow-[var(--v2-elevation-floating)] focus:outline-none"
|
||||
class="w-[284px] max-w-[calc(100vw-16px)] overflow-hidden rounded-md border-0 bg-v2-background-bg-layer-01 !p-0 shadow-[var(--v2-elevation-floating)] focus:outline-none"
|
||||
classList={{ "!w-[320px]": props.chatgptPlan }}
|
||||
onPointerDownOutside={dismiss.preventTriggerRestore}
|
||||
onFocusOutside={dismiss.preventTriggerRestore}
|
||||
onCloseAutoFocus={dismiss.onCloseAutoFocus}
|
||||
@@ -505,6 +521,20 @@ function ModelSelectorPopoverView(props: {
|
||||
<span class="min-w-0 flex-1 truncate leading-5">{language.t("dialog.model.manage")}</span>
|
||||
</Menu.Item>
|
||||
</div>
|
||||
<Show when={props.chatgptPlan}>
|
||||
<div class="h-px bg-v2-border-border-muted" />
|
||||
<div class="flex min-h-10 items-center gap-2 px-3 py-2 text-[13px] leading-5 text-v2-text-text-base">
|
||||
<ProviderModelIcon provider={{ id: "openai", name: "OpenAI" }} class="shrink-0" />
|
||||
<span class="min-w-0 flex-1 truncate">{language.t("dialog.model.chatgptPlan")}</span>
|
||||
<ExternalLink
|
||||
href="https://chatgpt.com/#settings/Usage"
|
||||
class="flex shrink-0 items-center gap-1 rounded-sm text-v2-text-text-muted no-underline hover:text-v2-text-text-base focus-visible:outline focus-visible:outline-2"
|
||||
>
|
||||
{language.t("dialog.model.chatgptManageUsage")}
|
||||
<Icon name="arrow-up-right" size="small" />
|
||||
</ExternalLink>
|
||||
</div>
|
||||
</Show>
|
||||
</Menu.Content>
|
||||
</Menu.Portal>
|
||||
</Menu>
|
||||
|
||||
@@ -186,6 +186,8 @@ export const dict = {
|
||||
"dialog.model.empty": "No model results",
|
||||
"dialog.model.manage": "Manage models",
|
||||
"dialog.model.manage.description": "Customize which models appear in the model selector.",
|
||||
"dialog.model.chatgptPlan": "Using ChatGPT plan",
|
||||
"dialog.model.chatgptManageUsage": "Manage usage",
|
||||
"dialog.model.manage.provider.toggle": "Toggle all {{provider}} models",
|
||||
|
||||
"dialog.model.unpaid.freeModels.title": "Free models provided by OpenCode",
|
||||
@@ -217,7 +219,15 @@ export const dict = {
|
||||
"provider.connect.models.title": "Connected to {{provider}}",
|
||||
"provider.connect.models.description": "Choose a model to start with. You can switch models anytime.",
|
||||
"provider.connect.models.available": "Available models",
|
||||
"provider.connect.chatgptWelcome.title": "You're using your ChatGPT plan",
|
||||
"provider.connect.chatgptWelcome.description": "Eligible requests in OpenCode use your ChatGPT plan.",
|
||||
"provider.connect.chatgptWelcome.usage": "Manage usage in ChatGPT settings",
|
||||
"provider.connect.chatgptWelcome.confirm": "Got it",
|
||||
"provider.connect.models.list": "Models available from {{provider}}",
|
||||
"provider.connect.chatgptUsageLimit.title": "ChatGPT usage limit reached",
|
||||
"provider.connect.chatgptUsageLimit.description": "Review your usage settings in ChatGPT.",
|
||||
"provider.connect.chatgptUsageLimit.manage": "Manage usage",
|
||||
"provider.connect.chatgptUsageLimit.close": "Close",
|
||||
"provider.connect.console.refreshFailed":
|
||||
"Your account is connected, but we couldn't load your models. Try again to refresh them.",
|
||||
"provider.connect.console.connected": "OpenCode connected",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { describe, expect, test } from "bun:test"
|
||||
import { Schema } from "effect"
|
||||
import { GoUpsellState } from "./usage-exceeded-dialogs"
|
||||
import { GoUpsellState, isChatGPTUsageLimit } from "./usage-exceeded-dialogs"
|
||||
import { Persistence } from "@/runtime/persistence/schema"
|
||||
|
||||
const decode = Schema.decodeUnknownSync(
|
||||
@@ -38,3 +38,31 @@ describe("usage exceeded preferences", () => {
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe("ChatGPT usage limit", () => {
|
||||
const message =
|
||||
"ChatGPT usage limit reached. Try again after your allowance resets; check ChatGPT Settings → Usage for details."
|
||||
|
||||
test("detects the mapped message regardless of failure type", () => {
|
||||
expect(
|
||||
isChatGPTUsageLimit({
|
||||
type: "provider.rate-limit",
|
||||
message,
|
||||
status: 429,
|
||||
}),
|
||||
).toBe(true)
|
||||
expect(isChatGPTUsageLimit({ type: "provider.unknown", message })).toBe(true)
|
||||
})
|
||||
|
||||
test("ignores other rate limits and similar messages", () => {
|
||||
expect(isChatGPTUsageLimit({ type: "provider.rate-limit", message: "Rate limit exceeded", status: 429 })).toBe(
|
||||
false,
|
||||
)
|
||||
expect(
|
||||
isChatGPTUsageLimit({
|
||||
type: "provider.rate-limit",
|
||||
message: "ChatGPT usage limit reached",
|
||||
}),
|
||||
).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { useWorkspaceLocation } from "@/workspaces/location"
|
||||
import { Persist, persisted } from "@/runtime/persistence/storage"
|
||||
import type { SessionStatus } from "@opencode/client/promise"
|
||||
import type { SessionStatus, SessionStepFailed } from "@opencode/client/promise"
|
||||
import { onCleanup } from "solid-js"
|
||||
import { Schema } from "effect"
|
||||
import { Persistence } from "@/runtime/persistence/schema"
|
||||
@@ -14,6 +14,14 @@ const GO_UPSELL_ACCOUNT_RATE_LIMIT_LAST_SEEN_AT = "go_upsell_account_rate_limit_
|
||||
const GO_UPSELL_ACCOUNT_RATE_LIMIT_DONT_SHOW = "go_upsell_account_rate_limit_dont_show"
|
||||
const GO_UPSELL_WINDOW = 86_400_000 // 24 hrs
|
||||
const GO_UPSELL_PROVIDERS = new Set(["opencode", "opencode-go"])
|
||||
const CHATGPT_USAGE_LIMIT_WINDOW = 86_400_000 // 24 hrs
|
||||
|
||||
export function isChatGPTUsageLimit(error: SessionStepFailed["data"]["error"]) {
|
||||
return (
|
||||
error.message ===
|
||||
"ChatGPT usage limit reached. Try again after your allowance resets; check ChatGPT Settings → Usage for details."
|
||||
)
|
||||
}
|
||||
|
||||
export const GoUpsellState = Persistence.struct({
|
||||
[GO_UPSELL_FREE_TIER_LAST_SEEN_AT]: Schema.NullOr(Schema.Finite),
|
||||
@@ -52,6 +60,25 @@ export function useUsageExceededDialogs() {
|
||||
[GO_UPSELL_ACCOUNT_RATE_LIMIT_LAST_SEEN_AT]: null,
|
||||
[GO_UPSELL_ACCOUNT_RATE_LIMIT_DONT_SHOW]: null,
|
||||
})
|
||||
const [chatgptUsageLimit, setChatGPTUsageLimit] = persisted(
|
||||
Persist.global("chatgpt-usage-limit"),
|
||||
Persistence.struct({ lastSeenAt: Schema.NullOr(Schema.Finite) }),
|
||||
{ lastSeenAt: null },
|
||||
)
|
||||
|
||||
onCleanup(
|
||||
sdk().event.on("session.step.failed", (evt) => {
|
||||
if (evt.data.sessionID !== params.id) return
|
||||
if (!isChatGPTUsageLimit(evt.data.error) || dialog.active) return
|
||||
if (chatgptUsageLimit.lastSeenAt && Date.now() - chatgptUsageLimit.lastSeenAt < CHATGPT_USAGE_LIMIT_WINDOW) return
|
||||
|
||||
void import("@/providers/connect/chatgpt-usage-limit").then((usage) => {
|
||||
if (dialog.active) return
|
||||
setChatGPTUsageLimit("lastSeenAt", Date.now())
|
||||
dialog.show(() => <usage.DialogChatGPTUsageLimit />)
|
||||
})
|
||||
}),
|
||||
)
|
||||
|
||||
onCleanup(
|
||||
sdk().event.on("session.status", (evt) => {
|
||||
|
||||
@@ -183,6 +183,26 @@ const Root = Spec.make(typeof OPENCODE_CLI_NAME === "string" ? OPENCODE_CLI_NAME
|
||||
),
|
||||
},
|
||||
}),
|
||||
Spec.make("export", {
|
||||
description: "print stored credentials, including secrets, as JSON",
|
||||
params: {
|
||||
...ServerParams,
|
||||
target: Argument.string("target").pipe(
|
||||
Argument.withDescription("Integration ID or name (exports every integration when omitted)"),
|
||||
Argument.optional,
|
||||
),
|
||||
},
|
||||
}),
|
||||
Spec.make("import", {
|
||||
description: "import credentials exported by auth export",
|
||||
params: {
|
||||
...ServerParams,
|
||||
file: Argument.string("file").pipe(
|
||||
Argument.withDescription("JSON file to import (reads stdin when omitted)"),
|
||||
Argument.optional,
|
||||
),
|
||||
},
|
||||
}),
|
||||
Spec.make("switch", {
|
||||
description: "switch the active account for an integration",
|
||||
params: {
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
import { EOL } from "node:os"
|
||||
import { Effect, Option } from "effect"
|
||||
import { Commands } from "../../commands"
|
||||
import { Runtime } from "../../../framework/runtime"
|
||||
import { createClient, loadIntegrations, request, resolveIntegration } from "./shared"
|
||||
import { errorMessage } from "../../../util/error"
|
||||
|
||||
export default Runtime.handler(
|
||||
Commands.commands.auth.commands.export,
|
||||
Effect.fn("cli.auth.export")(
|
||||
function* (input) {
|
||||
const client = yield* createClient({ server: Option.getOrUndefined(input.server), standalone: input.standalone })
|
||||
const target = Option.getOrUndefined(input.target)
|
||||
const integrationID = target ? (yield* resolveIntegration(yield* loadIntegrations(client), target)).id : undefined
|
||||
const credentials = (yield* request((signal) => client.credential.list({ signal }))).filter(
|
||||
(credential) => !integrationID || credential.integrationID === integrationID,
|
||||
)
|
||||
if (process.stdout.isTTY)
|
||||
process.stderr.write(
|
||||
"Warning: the output contains secrets; redirect it to a file or pipe it to auth import" + EOL,
|
||||
)
|
||||
process.stdout.write(JSON.stringify(credentials, null, 2) + EOL)
|
||||
},
|
||||
Effect.catch((error) =>
|
||||
Effect.sync(() => {
|
||||
process.stderr.write(errorMessage(error) + EOL)
|
||||
process.exitCode = 1
|
||||
}),
|
||||
),
|
||||
),
|
||||
)
|
||||
@@ -0,0 +1,58 @@
|
||||
import { EOL } from "node:os"
|
||||
import { isConflictError, type CredentialCreateInput } from "@opencode/client"
|
||||
import { Credential } from "@opencode/schema/credential"
|
||||
import { Effect, Option, Schema } from "effect"
|
||||
import { Commands } from "../../commands"
|
||||
import { Runtime } from "../../../framework/runtime"
|
||||
import { createClient, request } from "./shared"
|
||||
import { errorMessage } from "../../../util/error"
|
||||
import { readStdin } from "../../../util/io"
|
||||
|
||||
export default Runtime.handler(
|
||||
Commands.commands.auth.commands.import,
|
||||
Effect.fn("cli.auth.import")(
|
||||
function* (input) {
|
||||
const file = Option.getOrUndefined(input.file)
|
||||
if (!file && process.stdin.isTTY)
|
||||
return yield* Effect.fail(new Error("Pipe auth export output into stdin or pass a file to import"))
|
||||
const text = yield* request(() => (file ? Bun.file(file).text() : readStdin()))
|
||||
const credentials = yield* Schema.decodeUnknownEffect(Schema.fromJsonString(Schema.Array(Credential.Entry)))(text)
|
||||
const client = yield* createClient({ server: Option.getOrUndefined(input.server), standalone: input.standalone })
|
||||
const existing = yield* request((signal) => client.credential.list({ signal }))
|
||||
const ids = new Set(existing.map((credential) => credential.id))
|
||||
const integrations = new Set(existing.map((credential) => credential.integrationID))
|
||||
const results = yield* Effect.forEach(credentials, (credential) => {
|
||||
if (ids.has(credential.id)) return Effect.succeed(false)
|
||||
return request((signal) =>
|
||||
client.credential.create(
|
||||
{
|
||||
id: credential.id,
|
||||
integrationID: credential.integrationID,
|
||||
label: credential.label,
|
||||
// Stored metadata is JSON, but the credential schema types it as unknown while the generated client expects JSON.
|
||||
value: credential.value as CredentialCreateInput["value"],
|
||||
// Keep the destination's current selections; only integrations new to it adopt the exported selection.
|
||||
activate: credential.active && !integrations.has(credential.integrationID),
|
||||
},
|
||||
{ signal },
|
||||
),
|
||||
).pipe(
|
||||
Effect.as(true),
|
||||
Effect.catchIf(isConflictError, () => Effect.succeed(false)),
|
||||
)
|
||||
})
|
||||
const imported = results.filter(Boolean).length
|
||||
process.stderr.write(
|
||||
`Imported ${imported} ${imported === 1 ? "credential" : "credentials"}` +
|
||||
(results.length > imported ? `, skipped ${results.length - imported} already present` : "") +
|
||||
EOL,
|
||||
)
|
||||
},
|
||||
Effect.catch((error) =>
|
||||
Effect.sync(() => {
|
||||
process.stderr.write(errorMessage(error) + EOL)
|
||||
process.exitCode = 1
|
||||
}),
|
||||
),
|
||||
),
|
||||
)
|
||||
@@ -31,6 +31,8 @@ const Handlers = Runtime.handlers(Commands, {
|
||||
list: () => import("./commands/handlers/auth/list"),
|
||||
login: () => import("./commands/handlers/auth/login"),
|
||||
logout: () => import("./commands/handlers/auth/logout"),
|
||||
export: () => import("./commands/handlers/auth/export"),
|
||||
import: () => import("./commands/handlers/auth/import"),
|
||||
switch: () => import("./commands/handlers/auth/switch"),
|
||||
},
|
||||
debug: {
|
||||
|
||||
@@ -67,6 +67,9 @@ type FormRequest = Extract<V2Event, { type: "form.created" }>["data"]["form"]
|
||||
// attached client must not cancel input that may belong to another session.
|
||||
const GLOBAL_FORM_SESSION_ID = "global"
|
||||
|
||||
const PERMISSION_REJECTED_FEEDBACK =
|
||||
"This non-interactive run cannot ask the user for permission, so the request was rejected. Continue without this action."
|
||||
|
||||
export async function runNonInteractivePrompt(input: Input) {
|
||||
const controller = new AbortController()
|
||||
const stream = input.client.event.subscribe({ signal: controller.signal })[Symbol.asyncIterator]()
|
||||
@@ -132,10 +135,34 @@ export async function runNonInteractivePrompt(input: Input) {
|
||||
}
|
||||
}
|
||||
|
||||
const replyPermission = async (request: { id: string; action: string; resources: ReadonlyArray<string> }) => {
|
||||
// Subagents run in child sessions; their asks and questions belong to this run too. Other
|
||||
// sessions on a shared server (e.g. the TUI's) must be left alone.
|
||||
const owned = new Map<string, Promise<boolean>>([[input.sessionID, Promise.resolve(true)]])
|
||||
const ownsSession = (sessionID: string): Promise<boolean> => {
|
||||
const known = owned.get(sessionID)
|
||||
if (known) return known
|
||||
const result =
|
||||
sessionID === GLOBAL_FORM_SESSION_ID
|
||||
? Promise.resolve(false)
|
||||
: input.client.session
|
||||
.get({ sessionID })
|
||||
.then((session) => (session.parentID ? ownsSession(session.parentID) : false))
|
||||
.catch(() => false)
|
||||
owned.set(sessionID, result)
|
||||
return result
|
||||
}
|
||||
|
||||
const replyPermission = async (request: {
|
||||
id: string
|
||||
sessionID: string
|
||||
action: string
|
||||
resources: ReadonlyArray<string>
|
||||
}) => {
|
||||
// Nobody can approve here. Outside V1 compatibility, reject with feedback so the tool fails
|
||||
// as ordinary model-visible output and the model continues without the action.
|
||||
const continuing = !input.auto && input.compatibility !== "v1"
|
||||
if (!input.auto) {
|
||||
permissionRejected = true
|
||||
if (input.compatibility !== "v1") process.exitCode = 1
|
||||
if (!continuing) permissionRejected = true
|
||||
UI.println(
|
||||
UI.Style.TEXT_WARNING_BOLD + "!",
|
||||
UI.Style.TEXT_NORMAL +
|
||||
@@ -144,12 +171,13 @@ export async function runNonInteractivePrompt(input: Input) {
|
||||
}
|
||||
await input.client.permission
|
||||
.reply({
|
||||
sessionID: input.sessionID,
|
||||
sessionID: request.sessionID,
|
||||
requestID: request.id,
|
||||
decision: input.auto ? "once" : "reject",
|
||||
...(continuing ? { message: PERMISSION_REJECTED_FEEDBACK } : {}),
|
||||
})
|
||||
.catch(() => {})
|
||||
if (!input.auto) {
|
||||
if (!input.auto && !continuing) {
|
||||
await input.client.session.interrupt({ sessionID: input.sessionID }).catch(() => {})
|
||||
}
|
||||
}
|
||||
@@ -179,14 +207,14 @@ export async function runNonInteractivePrompt(input: Input) {
|
||||
}
|
||||
const event = next.value
|
||||
|
||||
if (event.type === "permission.asked" && submitted && event.data.sessionID === input.sessionID) {
|
||||
if (event.type === "permission.asked" && submitted && (await ownsSession(event.data.sessionID))) {
|
||||
await replyPermission(event.data)
|
||||
continue
|
||||
}
|
||||
if (
|
||||
event.type === "form.created" &&
|
||||
submitted &&
|
||||
(event.data.form.sessionID === input.sessionID ||
|
||||
((await ownsSession(event.data.form.sessionID)) ||
|
||||
(!input.attached &&
|
||||
event.data.form.sessionID === GLOBAL_FORM_SESSION_ID &&
|
||||
sameLocation(event.location, input.location)))
|
||||
|
||||
@@ -8,7 +8,6 @@ import os from "node:os"
|
||||
import path from "node:path"
|
||||
import { ServerConnection } from "../src/services/server-connection"
|
||||
import { ServiceConfig } from "../src/services/service-config"
|
||||
import { isolatedEnv } from "./fixture/environment"
|
||||
|
||||
test("resolution groups Effect-native lifecycle operations only for the managed service", async () => {
|
||||
const root = await fs.mkdtemp(path.join(os.tmpdir(), "opencode-server-resolution-"))
|
||||
@@ -70,61 +69,3 @@ test("service options only require a matching version when requested", async ()
|
||||
await fs.rm(root, { recursive: true, force: true })
|
||||
}
|
||||
})
|
||||
|
||||
test("disabled background service creates a private server per CLI call without registering a daemon", async () => {
|
||||
const root = await fs.mkdtemp(path.join(os.tmpdir(), "opencode-service-disabled-"))
|
||||
const env = isolatedEnv(root)
|
||||
const command = [process.execPath, path.join(import.meta.dir, "../src/index.ts")]
|
||||
const execute = async (...args: string[]) => {
|
||||
const child = Bun.spawn([...command, ...args], {
|
||||
cwd: path.join(import.meta.dir, ".."),
|
||||
env,
|
||||
stdout: "pipe",
|
||||
stderr: "pipe",
|
||||
})
|
||||
const [stdout, stderr, exit] = await Promise.all([
|
||||
new Response(child.stdout).text(),
|
||||
new Response(child.stderr).text(),
|
||||
child.exited,
|
||||
])
|
||||
return { stdout, stderr, exit }
|
||||
}
|
||||
const run = async (...args: string[]) => {
|
||||
const { stdout, stderr, exit } = await execute(...args)
|
||||
expect(exit, stderr).toBe(0)
|
||||
expect(stderr).not.toContain("Starting background server")
|
||||
return stdout
|
||||
}
|
||||
|
||||
try {
|
||||
await run("service", "set", "disabled", "true")
|
||||
expect(await run("service", "get", "disabled")).toBe("true\n")
|
||||
const first = JSON.parse(await run("api", "get", "/api/info"))
|
||||
const second = JSON.parse(await run("api", "get", "/api/info"))
|
||||
expect(first.pid).toBeGreaterThan(0)
|
||||
expect(second.pid).toBeGreaterThan(0)
|
||||
expect(second.pid).not.toBe(first.pid)
|
||||
expect(await run("mcp", "list")).toContain("No MCP servers configured")
|
||||
const pairing = await execute("pair")
|
||||
expect(pairing.exit).not.toBe(0)
|
||||
expect(pairing.stderr).toContain("Pairing requires the background service")
|
||||
|
||||
const explicit = Bun.serve({
|
||||
port: 0,
|
||||
fetch() {
|
||||
return Response.json({ version: OPENCODE_VERSION, pid: 12345, urls: [] })
|
||||
},
|
||||
})
|
||||
try {
|
||||
expect(JSON.parse(await run("api", "--server", explicit.url.toString(), "get", "/api/info")).pid).toBe(12345)
|
||||
} finally {
|
||||
await explicit.stop(true)
|
||||
}
|
||||
expect(await fs.readdir(path.join(root, "state", "opencode")).catch(() => [])).toEqual([])
|
||||
|
||||
await run("service", "unset", "disabled")
|
||||
expect(await run("service", "get", "disabled")).toBe("false\n")
|
||||
} finally {
|
||||
await fs.rm(root, { recursive: true, force: true })
|
||||
}
|
||||
}, 30_000)
|
||||
|
||||
@@ -710,7 +710,12 @@ export type SessionLogOutput =
|
||||
| undefined
|
||||
readonly data: {
|
||||
readonly sessionID: Session.ID
|
||||
readonly error: { readonly type: string; readonly message: string; readonly status?: number | undefined }
|
||||
readonly error: {
|
||||
readonly type: string
|
||||
readonly message: string
|
||||
readonly status?: number | undefined
|
||||
readonly response?: { readonly body: string } | undefined
|
||||
}
|
||||
}
|
||||
}
|
||||
| {
|
||||
@@ -902,7 +907,12 @@ export type SessionLogOutput =
|
||||
readonly data: {
|
||||
readonly sessionID: Session.ID
|
||||
readonly assistantMessageID: SessionMessage.ID
|
||||
readonly error: { readonly type: string; readonly message: string; readonly status?: number | undefined }
|
||||
readonly error: {
|
||||
readonly type: string
|
||||
readonly message: string
|
||||
readonly status?: number | undefined
|
||||
readonly response?: { readonly body: string } | undefined
|
||||
}
|
||||
readonly finish?: "content-filter" | undefined
|
||||
readonly rawFinish?: string | undefined
|
||||
readonly providerState?: SessionMessage.ProviderState | undefined
|
||||
@@ -1112,7 +1122,12 @@ export type SessionLogOutput =
|
||||
readonly sessionID: Session.ID
|
||||
readonly assistantMessageID: SessionMessage.ID
|
||||
readonly id: string
|
||||
readonly error: { readonly type: string; readonly message: string; readonly status?: number | undefined }
|
||||
readonly error: {
|
||||
readonly type: string
|
||||
readonly message: string
|
||||
readonly status?: number | undefined
|
||||
readonly response?: { readonly body: string } | undefined
|
||||
}
|
||||
readonly content?:
|
||||
| readonly [
|
||||
(
|
||||
@@ -1157,7 +1172,12 @@ export type SessionLogOutput =
|
||||
readonly assistantMessageID: SessionMessage.ID
|
||||
readonly attempt: number
|
||||
readonly at: number
|
||||
readonly error: { readonly type: string; readonly message: string; readonly status?: number | undefined }
|
||||
readonly error: {
|
||||
readonly type: string
|
||||
readonly message: string
|
||||
readonly status?: number | undefined
|
||||
readonly response?: { readonly body: string } | undefined
|
||||
}
|
||||
}
|
||||
}
|
||||
| {
|
||||
@@ -1238,7 +1258,12 @@ export type SessionLogOutput =
|
||||
readonly data: {
|
||||
readonly sessionID: Session.ID
|
||||
readonly reason: "auto" | "manual"
|
||||
readonly error: { readonly type: string; readonly message: string; readonly status?: number | undefined }
|
||||
readonly error: {
|
||||
readonly type: string
|
||||
readonly message: string
|
||||
readonly status?: number | undefined
|
||||
readonly response?: { readonly body: string } | undefined
|
||||
}
|
||||
readonly inputID?: SessionMessage.ID | undefined
|
||||
readonly cost?: (number & Brand.Brand<"Money.USD">) | undefined
|
||||
readonly tokens?:
|
||||
@@ -1718,6 +1743,21 @@ export interface McpApi<E = never> {
|
||||
readonly resource: { readonly catalog: McpResourceCatalogOperation<E> }
|
||||
}
|
||||
|
||||
export type CredentialListOutput = ReadonlyArray<Credential.Entry>
|
||||
export type CredentialListOperation<E = never> = () => Effect.Effect<CredentialListOutput, E>
|
||||
|
||||
export type CredentialCreateInput = {
|
||||
readonly id?: Credential.ID | undefined
|
||||
readonly integrationID: Integration.ID
|
||||
readonly label?: string | undefined
|
||||
readonly value: Credential.Value
|
||||
readonly activate?: boolean | undefined
|
||||
}
|
||||
export type CredentialCreateOutput = Credential.Entry
|
||||
export type CredentialCreateOperation<E = never> = (
|
||||
input: CredentialCreateInput,
|
||||
) => Effect.Effect<CredentialCreateOutput, E>
|
||||
|
||||
export type CredentialUpdateInput = { readonly credentialID: Credential.ID; readonly label: string }
|
||||
export type CredentialUpdateOutput = void
|
||||
export type CredentialUpdateOperation<E = never> = (
|
||||
@@ -1737,6 +1777,8 @@ export type CredentialRemoveOperation<E = never> = (
|
||||
) => Effect.Effect<CredentialRemoveOutput, E>
|
||||
|
||||
export interface CredentialApi<E = never> {
|
||||
readonly list: CredentialListOperation<E>
|
||||
readonly create: CredentialCreateOperation<E>
|
||||
readonly update: CredentialUpdateOperation<E>
|
||||
readonly activate: CredentialActivateOperation<E>
|
||||
readonly remove: CredentialRemoveOperation<E>
|
||||
|
||||
@@ -153,6 +153,9 @@ import type {
|
||||
McpDisconnectOutput,
|
||||
McpResourceCatalogInput,
|
||||
McpResourceCatalogOutput,
|
||||
CredentialListOutput,
|
||||
CredentialCreateInput,
|
||||
CredentialCreateOutput,
|
||||
CredentialUpdateInput,
|
||||
CredentialUpdateOutput,
|
||||
CredentialActivateInput,
|
||||
@@ -1021,6 +1024,30 @@ const adaptGroupMcp = (raw: RawClient["server.mcp"]) => ({
|
||||
resource: { catalog: EndpointMcpResourceCatalog(raw) },
|
||||
})
|
||||
|
||||
const EndpointCredentialList = (raw: RawClient["server.credential"]) => () =>
|
||||
preserveEffect<CredentialListOutput>()(
|
||||
raw["credential.list"]({}).pipe(
|
||||
Effect.mapError(mapClientError),
|
||||
Effect.map((value) => value.data),
|
||||
),
|
||||
)
|
||||
|
||||
const EndpointCredentialCreate = (raw: RawClient["server.credential"]) => (input: CredentialCreateInput) =>
|
||||
preserveEffect<CredentialCreateOutput>()(
|
||||
raw["credential.create"]({
|
||||
payload: {
|
||||
id: input["id"],
|
||||
integrationID: input["integrationID"],
|
||||
label: input["label"],
|
||||
value: input["value"],
|
||||
activate: input["activate"],
|
||||
},
|
||||
}).pipe(
|
||||
Effect.mapError(mapClientError),
|
||||
Effect.map((value) => value.data),
|
||||
),
|
||||
)
|
||||
|
||||
const EndpointCredentialUpdate = (raw: RawClient["server.credential"]) => (input: CredentialUpdateInput) =>
|
||||
preserveEffect<CredentialUpdateOutput>()(
|
||||
raw["credential.update"]({
|
||||
@@ -1042,6 +1069,8 @@ const EndpointCredentialRemove = (raw: RawClient["server.credential"]) => (input
|
||||
)
|
||||
|
||||
const adaptGroupCredential = (raw: RawClient["server.credential"]) => ({
|
||||
list: EndpointCredentialList(raw),
|
||||
create: EndpointCredentialCreate(raw),
|
||||
update: EndpointCredentialUpdate(raw),
|
||||
activate: EndpointCredentialActivate(raw),
|
||||
remove: EndpointCredentialRemove(raw),
|
||||
|
||||
@@ -147,6 +147,9 @@ import type {
|
||||
McpDisconnectOutput,
|
||||
McpResourceCatalogInput,
|
||||
McpResourceCatalogOutput,
|
||||
CredentialListOutput,
|
||||
CredentialCreateInput,
|
||||
CredentialCreateOutput,
|
||||
CredentialUpdateInput,
|
||||
CredentialUpdateOutput,
|
||||
CredentialActivateInput,
|
||||
@@ -1392,6 +1395,29 @@ export function make(options: ClientOptions) {
|
||||
},
|
||||
},
|
||||
credential: {
|
||||
list: (requestOptions?: RequestOptions) =>
|
||||
request<{ readonly data: CredentialListOutput }>(
|
||||
{ method: "GET", path: `/api/credential`, successStatus: 200, declaredStatuses: [400, 401], empty: false },
|
||||
requestOptions,
|
||||
).then((value) => value.data),
|
||||
create: (input: CredentialCreateInput, requestOptions?: RequestOptions) =>
|
||||
request<{ readonly data: CredentialCreateOutput }>(
|
||||
{
|
||||
method: "POST",
|
||||
path: `/api/credential`,
|
||||
body: {
|
||||
id: input["id"],
|
||||
integrationID: input["integrationID"],
|
||||
label: input["label"],
|
||||
value: input["value"],
|
||||
activate: input["activate"],
|
||||
},
|
||||
successStatus: 200,
|
||||
declaredStatuses: [400, 401, 409],
|
||||
empty: false,
|
||||
},
|
||||
requestOptions,
|
||||
).then((value) => value.data),
|
||||
update: (input: CredentialUpdateInput, requestOptions?: RequestOptions) =>
|
||||
request<CredentialUpdateOutput>(
|
||||
{
|
||||
|
||||
@@ -133,7 +133,7 @@ export type ToolTextContent = { type: "text"; text: string }
|
||||
|
||||
export type ToolFileContent = { type: "file"; uri: string; mime: string; name?: string | null }
|
||||
|
||||
export type SessionStructuredError = { type: string; message: string; status?: number }
|
||||
export type SessionStructuredError = { type: string; message: string; status?: number; response?: { body: string } }
|
||||
|
||||
export type SessionMessageCompactionRunning = {
|
||||
type: "compaction"
|
||||
@@ -293,6 +293,15 @@ export type McpResourceTemplate = {
|
||||
mimeType?: string
|
||||
}
|
||||
|
||||
export type CredentialOAuth = {
|
||||
type: "oauth"
|
||||
methodID: string
|
||||
refresh: string
|
||||
access: string
|
||||
expires: number
|
||||
metadata?: { [x: string]: JsonValue }
|
||||
}
|
||||
|
||||
export type ProjectVcs = string
|
||||
|
||||
export type ProjectIcon = { url?: string; override?: string; color?: string }
|
||||
@@ -1656,7 +1665,7 @@ export type FormMultiselectField1 = {
|
||||
default?: Array<string>
|
||||
}
|
||||
|
||||
export type FormAnswer1 = { [x: string]: FormValue1 }
|
||||
export type FormAnswer2 = { [x: string]: FormValue1 }
|
||||
|
||||
export type SessionStatusUpdated = {
|
||||
id: string
|
||||
@@ -1890,6 +1899,13 @@ export type FormField =
|
||||
|
||||
export type FormState = { status: "pending" } | { status: "answered"; answer: FormAnswer } | { status: "cancelled" }
|
||||
|
||||
export type CredentialKey = {
|
||||
type: "key"
|
||||
key: string
|
||||
metadata?: { [x: string]: JsonValue }
|
||||
configuration?: FormAnswer
|
||||
}
|
||||
|
||||
export type ConnectionInfo = ConnectionCredentialInfo | ConnectionEnvInfo
|
||||
|
||||
export type FormField1 =
|
||||
@@ -1906,7 +1922,7 @@ export type FormReplied = {
|
||||
metadata?: { [x: string]: any }
|
||||
type: "form.replied"
|
||||
location?: LocationRef
|
||||
data: { id: string; sessionID: string; answer: FormAnswer1 }
|
||||
data: { id: string; sessionID: string; answer: FormAnswer2 }
|
||||
}
|
||||
|
||||
export type ReferenceInfo = {
|
||||
@@ -2225,6 +2241,8 @@ export type SessionMessageAssistantTool1 = {
|
||||
|
||||
export type FormFields = [FormField, ...Array<FormField>]
|
||||
|
||||
export type CredentialValue = CredentialOAuth | CredentialKey
|
||||
|
||||
export type FormFields2 = [FormField1, ...Array<FormField1>]
|
||||
|
||||
export type SessionsResponse = { data: Array<SessionInfo>; cursor: { previous?: string | null; next?: string | null } }
|
||||
@@ -2279,6 +2297,14 @@ export type IntegrationOAuthMethod = { id: string; type: "oauth"; label: string;
|
||||
|
||||
export type IntegrationKeyMethod = { type: "key"; label?: string; form?: FormFields }
|
||||
|
||||
export type CredentialEntry = {
|
||||
id: string
|
||||
integrationID: string
|
||||
label: string
|
||||
active: boolean
|
||||
value: CredentialValue
|
||||
}
|
||||
|
||||
export type FormInfo1 = { id: string; sessionID: string; title: string; metadata?: FormMetadata1; fields: FormFields2 }
|
||||
|
||||
export type SessionMessageInfo =
|
||||
@@ -3183,7 +3209,12 @@ export type SessionImportInput = {
|
||||
| {
|
||||
readonly status: "error"
|
||||
readonly input: { readonly [x: string]: JsonValue }
|
||||
readonly error: { readonly type: string; readonly message: string; readonly status?: number }
|
||||
readonly error: {
|
||||
readonly type: string
|
||||
readonly message: string
|
||||
readonly status?: number
|
||||
readonly response?: { readonly body: string }
|
||||
}
|
||||
readonly content?: readonly [
|
||||
(
|
||||
| { readonly type: "text"; readonly text: string }
|
||||
@@ -3220,11 +3251,21 @@ export type SessionImportInput = {
|
||||
readonly reasoning: number
|
||||
readonly cache: { readonly read: number; readonly write: number }
|
||||
}
|
||||
readonly error?: { readonly type: string; readonly message: string; readonly status?: number }
|
||||
readonly error?: {
|
||||
readonly type: string
|
||||
readonly message: string
|
||||
readonly status?: number
|
||||
readonly response?: { readonly body: string }
|
||||
}
|
||||
readonly retry?: {
|
||||
readonly attempt: number
|
||||
readonly at: number
|
||||
readonly error: { readonly type: string; readonly message: string; readonly status?: number }
|
||||
readonly error: {
|
||||
readonly type: string
|
||||
readonly message: string
|
||||
readonly status?: number
|
||||
readonly response?: { readonly body: string }
|
||||
}
|
||||
}
|
||||
}
|
||||
| (
|
||||
@@ -3276,7 +3317,12 @@ export type SessionImportInput = {
|
||||
readonly time: { readonly created: number }
|
||||
readonly status: "failed"
|
||||
readonly reason: "auto" | "manual"
|
||||
readonly error: { readonly type: string; readonly message: string; readonly status?: number }
|
||||
readonly error: {
|
||||
readonly type: string
|
||||
readonly message: string
|
||||
readonly status?: number
|
||||
readonly response?: { readonly body: string }
|
||||
}
|
||||
readonly cost?: number
|
||||
readonly tokens?: {
|
||||
readonly input: number
|
||||
@@ -3500,7 +3546,12 @@ export type SessionImportInput = {
|
||||
| {
|
||||
readonly status: "error"
|
||||
readonly input: { readonly [x: string]: JsonValue }
|
||||
readonly error: { readonly type: string; readonly message: string; readonly status?: number }
|
||||
readonly error: {
|
||||
readonly type: string
|
||||
readonly message: string
|
||||
readonly status?: number
|
||||
readonly response?: { readonly body: string }
|
||||
}
|
||||
readonly content?: readonly [
|
||||
(
|
||||
| { readonly type: "text"; readonly text: string }
|
||||
@@ -3537,11 +3588,21 @@ export type SessionImportInput = {
|
||||
readonly reasoning: number
|
||||
readonly cache: { readonly read: number; readonly write: number }
|
||||
}
|
||||
readonly error?: { readonly type: string; readonly message: string; readonly status?: number }
|
||||
readonly error?: {
|
||||
readonly type: string
|
||||
readonly message: string
|
||||
readonly status?: number
|
||||
readonly response?: { readonly body: string }
|
||||
}
|
||||
readonly retry?: {
|
||||
readonly attempt: number
|
||||
readonly at: number
|
||||
readonly error: { readonly type: string; readonly message: string; readonly status?: number }
|
||||
readonly error: {
|
||||
readonly type: string
|
||||
readonly message: string
|
||||
readonly status?: number
|
||||
readonly response?: { readonly body: string }
|
||||
}
|
||||
}
|
||||
}
|
||||
| (
|
||||
@@ -3593,7 +3654,12 @@ export type SessionImportInput = {
|
||||
readonly time: { readonly created: number }
|
||||
readonly status: "failed"
|
||||
readonly reason: "auto" | "manual"
|
||||
readonly error: { readonly type: string; readonly message: string; readonly status?: number }
|
||||
readonly error: {
|
||||
readonly type: string
|
||||
readonly message: string
|
||||
readonly status?: number
|
||||
readonly response?: { readonly body: string }
|
||||
}
|
||||
readonly cost?: number
|
||||
readonly tokens?: {
|
||||
readonly input: number
|
||||
@@ -3817,7 +3883,12 @@ export type SessionImportInput = {
|
||||
| {
|
||||
readonly status: "error"
|
||||
readonly input: { readonly [x: string]: JsonValue }
|
||||
readonly error: { readonly type: string; readonly message: string; readonly status?: number }
|
||||
readonly error: {
|
||||
readonly type: string
|
||||
readonly message: string
|
||||
readonly status?: number
|
||||
readonly response?: { readonly body: string }
|
||||
}
|
||||
readonly content?: readonly [
|
||||
(
|
||||
| { readonly type: "text"; readonly text: string }
|
||||
@@ -3854,11 +3925,21 @@ export type SessionImportInput = {
|
||||
readonly reasoning: number
|
||||
readonly cache: { readonly read: number; readonly write: number }
|
||||
}
|
||||
readonly error?: { readonly type: string; readonly message: string; readonly status?: number }
|
||||
readonly error?: {
|
||||
readonly type: string
|
||||
readonly message: string
|
||||
readonly status?: number
|
||||
readonly response?: { readonly body: string }
|
||||
}
|
||||
readonly retry?: {
|
||||
readonly attempt: number
|
||||
readonly at: number
|
||||
readonly error: { readonly type: string; readonly message: string; readonly status?: number }
|
||||
readonly error: {
|
||||
readonly type: string
|
||||
readonly message: string
|
||||
readonly status?: number
|
||||
readonly response?: { readonly body: string }
|
||||
}
|
||||
}
|
||||
}
|
||||
| (
|
||||
@@ -3910,7 +3991,12 @@ export type SessionImportInput = {
|
||||
readonly time: { readonly created: number }
|
||||
readonly status: "failed"
|
||||
readonly reason: "auto" | "manual"
|
||||
readonly error: { readonly type: string; readonly message: string; readonly status?: number }
|
||||
readonly error: {
|
||||
readonly type: string
|
||||
readonly message: string
|
||||
readonly status?: number
|
||||
readonly response?: { readonly body: string }
|
||||
}
|
||||
readonly cost?: number
|
||||
readonly tokens?: {
|
||||
readonly input: number
|
||||
@@ -5690,6 +5776,128 @@ export type McpResourceCatalogInput = {
|
||||
|
||||
export type McpResourceCatalogOutput = { location: LocationPublicRef; data: McpResourceCatalog }
|
||||
|
||||
export type CredentialListOutput = { data: Array<CredentialEntry> }["data"]
|
||||
|
||||
export type CredentialCreateInput = {
|
||||
readonly id?: {
|
||||
readonly id?: string
|
||||
readonly integrationID: string
|
||||
readonly label?: string
|
||||
readonly value:
|
||||
| {
|
||||
readonly type: "oauth"
|
||||
readonly methodID: string
|
||||
readonly refresh: string
|
||||
readonly access: string
|
||||
readonly expires: number
|
||||
readonly metadata?: { readonly [x: string]: JsonValue }
|
||||
}
|
||||
| {
|
||||
readonly type: "key"
|
||||
readonly key: string
|
||||
readonly metadata?: { readonly [x: string]: JsonValue }
|
||||
readonly configuration?: {
|
||||
readonly [x: string]: string | number | "Infinity" | "-Infinity" | "NaN" | boolean | ReadonlyArray<string>
|
||||
}
|
||||
}
|
||||
readonly activate?: boolean
|
||||
}["id"]
|
||||
readonly integrationID: {
|
||||
readonly id?: string
|
||||
readonly integrationID: string
|
||||
readonly label?: string
|
||||
readonly value:
|
||||
| {
|
||||
readonly type: "oauth"
|
||||
readonly methodID: string
|
||||
readonly refresh: string
|
||||
readonly access: string
|
||||
readonly expires: number
|
||||
readonly metadata?: { readonly [x: string]: JsonValue }
|
||||
}
|
||||
| {
|
||||
readonly type: "key"
|
||||
readonly key: string
|
||||
readonly metadata?: { readonly [x: string]: JsonValue }
|
||||
readonly configuration?: {
|
||||
readonly [x: string]: string | number | "Infinity" | "-Infinity" | "NaN" | boolean | ReadonlyArray<string>
|
||||
}
|
||||
}
|
||||
readonly activate?: boolean
|
||||
}["integrationID"]
|
||||
readonly label?: {
|
||||
readonly id?: string
|
||||
readonly integrationID: string
|
||||
readonly label?: string
|
||||
readonly value:
|
||||
| {
|
||||
readonly type: "oauth"
|
||||
readonly methodID: string
|
||||
readonly refresh: string
|
||||
readonly access: string
|
||||
readonly expires: number
|
||||
readonly metadata?: { readonly [x: string]: JsonValue }
|
||||
}
|
||||
| {
|
||||
readonly type: "key"
|
||||
readonly key: string
|
||||
readonly metadata?: { readonly [x: string]: JsonValue }
|
||||
readonly configuration?: {
|
||||
readonly [x: string]: string | number | "Infinity" | "-Infinity" | "NaN" | boolean | ReadonlyArray<string>
|
||||
}
|
||||
}
|
||||
readonly activate?: boolean
|
||||
}["label"]
|
||||
readonly value: {
|
||||
readonly id?: string
|
||||
readonly integrationID: string
|
||||
readonly label?: string
|
||||
readonly value:
|
||||
| {
|
||||
readonly type: "oauth"
|
||||
readonly methodID: string
|
||||
readonly refresh: string
|
||||
readonly access: string
|
||||
readonly expires: number
|
||||
readonly metadata?: { readonly [x: string]: JsonValue }
|
||||
}
|
||||
| {
|
||||
readonly type: "key"
|
||||
readonly key: string
|
||||
readonly metadata?: { readonly [x: string]: JsonValue }
|
||||
readonly configuration?: {
|
||||
readonly [x: string]: string | number | "Infinity" | "-Infinity" | "NaN" | boolean | ReadonlyArray<string>
|
||||
}
|
||||
}
|
||||
readonly activate?: boolean
|
||||
}["value"]
|
||||
readonly activate?: {
|
||||
readonly id?: string
|
||||
readonly integrationID: string
|
||||
readonly label?: string
|
||||
readonly value:
|
||||
| {
|
||||
readonly type: "oauth"
|
||||
readonly methodID: string
|
||||
readonly refresh: string
|
||||
readonly access: string
|
||||
readonly expires: number
|
||||
readonly metadata?: { readonly [x: string]: JsonValue }
|
||||
}
|
||||
| {
|
||||
readonly type: "key"
|
||||
readonly key: string
|
||||
readonly metadata?: { readonly [x: string]: JsonValue }
|
||||
readonly configuration?: {
|
||||
readonly [x: string]: string | number | "Infinity" | "-Infinity" | "NaN" | boolean | ReadonlyArray<string>
|
||||
}
|
||||
}
|
||||
readonly activate?: boolean
|
||||
}["activate"]
|
||||
}
|
||||
|
||||
export type CredentialCreateOutput = { data: CredentialEntry }["data"]
|
||||
|
||||
export type CredentialUpdateInput = {
|
||||
readonly credentialID: { readonly credentialID: string }["credentialID"]
|
||||
readonly label: { readonly label: string }["label"]
|
||||
|
||||
@@ -129,6 +129,7 @@
|
||||
"https-proxy-agent": "7.0.6",
|
||||
"ignore": "7.0.5",
|
||||
"immer": "11.1.4",
|
||||
"jose": "6.0.11",
|
||||
"jsonc-parser": "3.3.1",
|
||||
"mime-types": "3.0.2",
|
||||
"tree-sitter-bash": "0.25.0",
|
||||
|
||||
@@ -38,11 +38,16 @@ export interface Interface {
|
||||
readonly list: (integrationID: Integration.ID) => Effect.Effect<Info[]>
|
||||
/** Returns one stored credential by ID. */
|
||||
readonly get: (id: ID) => Effect.Effect<Info | undefined>
|
||||
/** Creates a credential for an integration and returns the new record. */
|
||||
/**
|
||||
* Creates a credential for an integration and returns the new record. The new credential becomes the
|
||||
* integration's selection unless `activate` is false and the integration already has a credential.
|
||||
*/
|
||||
readonly create: (input: {
|
||||
readonly id?: ID
|
||||
readonly integrationID: Integration.ID
|
||||
readonly value: Value
|
||||
readonly label?: string
|
||||
readonly activate?: boolean
|
||||
}) => Effect.Effect<Info>
|
||||
/** Selects a stored credential for its integration. */
|
||||
readonly activate: (id: ID) => Effect.Effect<void>
|
||||
@@ -99,19 +104,30 @@ const layer = Layer.effect(
|
||||
}),
|
||||
create: Effect.fn("Credential.create")(function* (input) {
|
||||
const credential = new Info({
|
||||
id: ID.create(),
|
||||
id: input.id ?? ID.create(),
|
||||
integrationID: input.integrationID,
|
||||
label: input.label ?? "default",
|
||||
value: input.value,
|
||||
})
|
||||
yield* db
|
||||
const activated = yield* db
|
||||
.transaction((tx) =>
|
||||
Effect.gen(function* () {
|
||||
yield* tx
|
||||
.update(CredentialTable)
|
||||
.set({ active: false })
|
||||
const current = yield* tx
|
||||
.select({ id: CredentialTable.id, active: CredentialTable.active })
|
||||
.from(CredentialTable)
|
||||
.where(eq(CredentialTable.integration_id, credential.integrationID))
|
||||
.run()
|
||||
.orderBy(desc(CredentialTable.active), desc(CredentialTable.time_created), desc(CredentialTable.id))
|
||||
.get()
|
||||
const activate = input.activate !== false || !current
|
||||
if (activate)
|
||||
yield* tx
|
||||
.update(CredentialTable)
|
||||
.set({ active: false })
|
||||
.where(eq(CredentialTable.integration_id, credential.integrationID))
|
||||
.run()
|
||||
// Legacy rows have no active flag and the newest one is selected, so pin it before inserting a newer row.
|
||||
if (!activate && current && !current.active)
|
||||
yield* tx.update(CredentialTable).set({ active: true }).where(eq(CredentialTable.id, current.id)).run()
|
||||
yield* tx
|
||||
.insert(CredentialTable)
|
||||
.values({
|
||||
@@ -119,9 +135,10 @@ const layer = Layer.effect(
|
||||
integration_id: credential.integrationID,
|
||||
label: credential.label,
|
||||
value: credential.value,
|
||||
active: true,
|
||||
active: activate,
|
||||
})
|
||||
.run()
|
||||
return activate
|
||||
}),
|
||||
)
|
||||
.pipe(
|
||||
@@ -138,13 +155,15 @@ const layer = Layer.effect(
|
||||
credentialID: credential.id,
|
||||
integrationID: credential.integrationID,
|
||||
type: credential.value.type,
|
||||
active: activated,
|
||||
})
|
||||
yield* bus.publish(Event.Updated, {}, { global: true })
|
||||
yield* bus.publish(
|
||||
Event.Switched,
|
||||
{ integrationID: credential.integrationID, credentialID: credential.id },
|
||||
{ global: true },
|
||||
)
|
||||
if (activated)
|
||||
yield* bus.publish(
|
||||
Event.Switched,
|
||||
{ integrationID: credential.integrationID, credentialID: credential.id },
|
||||
{ global: true },
|
||||
)
|
||||
return credential
|
||||
}),
|
||||
activate: Effect.fn("Credential.activate")(function* (id) {
|
||||
|
||||
@@ -5,6 +5,8 @@ import { sqliteLayer, supportsForeignKeyToggle, supportsTuningPragmas } from "#s
|
||||
import { Context, Effect, Layer, Schema, Semaphore } from "effect"
|
||||
import type { SqlClient } from "effect/unstable/sql"
|
||||
import { Global } from "@opencode/util/global"
|
||||
import { closeSync, existsSync, openSync } from "node:fs"
|
||||
import { chmod } from "node:fs/promises"
|
||||
import { isAbsolute, join } from "path"
|
||||
import { DatabaseMigration } from "./migration.js"
|
||||
import { makeGlobalNode } from "@opencode/util/effect/app-node"
|
||||
@@ -70,13 +72,31 @@ export function layer(options: Options = { path: ":memory:" }) {
|
||||
Layer.provide(sqliteLayer({ filename })),
|
||||
)
|
||||
const filename = options.path ?? ":memory:"
|
||||
if (filename === ":memory:" || isAbsolute(filename)) return provide(filename)
|
||||
const global = yield* Global.Service
|
||||
return provide(join(global.data, filename))
|
||||
if (filename === ":memory:") return provide(filename)
|
||||
const file = isAbsolute(filename) ? filename : join((yield* Global.Service).data, filename)
|
||||
yield* Effect.promise(() => restrictToOwner(file))
|
||||
return provide(file)
|
||||
}),
|
||||
)
|
||||
}
|
||||
|
||||
// SQLite creates new sidecars with the database's mode, but does not tighten existing sidecars.
|
||||
// Windows relies on the user profile directory's inherited ACLs instead of POSIX modes.
|
||||
async function restrictToOwner(filename: string) {
|
||||
if (process.platform === "win32") return
|
||||
// Opening and closing an existing database can release another connection's POSIX locks.
|
||||
// Create missing files synchronously so another fiber cannot open one before it is restricted.
|
||||
if (!existsSync(filename)) closeSync(openSync(filename, "a", 0o600))
|
||||
await chmod(filename, 0o600)
|
||||
await Promise.all(
|
||||
[`${filename}-wal`, `${filename}-shm`].map((file) =>
|
||||
chmod(file, 0o600).catch((error: NodeJS.ErrnoException) => {
|
||||
if (error.code !== "ENOENT") throw error
|
||||
}),
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
// The database service over an injected SqlClient, for runtimes that receive
|
||||
// database storage instead of opening a filesystem path. Any client provided
|
||||
// here still goes through the pragma guards and migrations; Global is required
|
||||
|
||||
@@ -286,7 +286,11 @@ const layer = Layer.effect(
|
||||
requestID: item.request.id,
|
||||
reply: "reject",
|
||||
})
|
||||
yield* Deferred.fail(item.deferred, new DeclinedError())
|
||||
// Feedback applies to the whole batch, so parallel asks don't end the step.
|
||||
yield* Deferred.fail(
|
||||
item.deferred,
|
||||
input.message ? new CorrectedError({ feedback: input.message }) : new DeclinedError(),
|
||||
)
|
||||
pending.delete(id)
|
||||
}
|
||||
return
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { AmazonBedrockPlugin } from "./provider/amazon-bedrock.js"
|
||||
import { AzurePlugin } from "./provider/azure.js"
|
||||
import { CerebrasPlugin } from "./provider/cerebras.js"
|
||||
import { ChatGPTPlugin } from "./provider/chatgpt.js"
|
||||
import { CloudflareAIGatewayPlugin } from "./provider/cloudflare-ai-gateway.js"
|
||||
import { CloudflareWorkersAIPlugin } from "./provider/cloudflare-workers-ai.js"
|
||||
import { CoherePlugin } from "./provider/cohere.js"
|
||||
@@ -35,6 +36,7 @@ export const ProviderPlugins: PluginInternal.InternalPlugin[] = [
|
||||
AmazonBedrockPlugin,
|
||||
AzurePlugin,
|
||||
CerebrasPlugin,
|
||||
ChatGPTPlugin,
|
||||
CloudflareAIGatewayPlugin,
|
||||
CloudflareWorkersAIPlugin,
|
||||
CoherePlugin,
|
||||
|
||||
@@ -0,0 +1,516 @@
|
||||
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 { 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 { Model } from "../../model.js"
|
||||
import { OauthCallbackPage } from "../../oauth/page.js"
|
||||
import { Provider } from "../../provider.js"
|
||||
import type { PluginInternal } from "../internal.js"
|
||||
|
||||
// First-time sign-in registers a user-owned client; OpenAI returns its issued client ID on the callback.
|
||||
const registrationClientID = "dynamic_agent_client"
|
||||
const agentName = "OpenCode"
|
||||
const issuer = "https://auth.openai.com"
|
||||
const tokenURL = `${issuer}/api/accounts/oauth/token`
|
||||
const resource = "https://api.openai.com/v1"
|
||||
const tokenSharingScope = "chatgpt.tokens.use.direct"
|
||||
const providerID = Provider.ID.openai
|
||||
const integrationID = Integration.ID.make("openai")
|
||||
const methodID = Integration.MethodID.make("chatgpt-token-sharing")
|
||||
const modelCacheKey = (clientID: string) => `models:${clientID}`
|
||||
const fallbackModels = new Set([
|
||||
"gpt-5.5",
|
||||
"gpt-5.5-fast",
|
||||
"gpt-5.6-luna",
|
||||
"gpt-5.6-luna-fast",
|
||||
"gpt-5.6-sol",
|
||||
"gpt-5.6-sol-fast",
|
||||
"gpt-5.6-terra",
|
||||
"gpt-5.6-terra-fast",
|
||||
"gpt-6-astra",
|
||||
"gpt-6-astra-fast",
|
||||
])
|
||||
const nonRetryableSharingCodes = [
|
||||
"subscription_sharing_usage_limit_exceeded",
|
||||
"subscription_sharing_user_not_eligible",
|
||||
"subscription_sharing_unsupported_capability",
|
||||
"subscription_sharing_route_not_supported",
|
||||
"subscription_sharing_invalid_user",
|
||||
"chatpass_v2_scope_not_authorized",
|
||||
"chatpass_v2_invalid_authorization_context",
|
||||
]
|
||||
type Pkce = {
|
||||
verifier: string
|
||||
challenge: string
|
||||
}
|
||||
|
||||
type TokenResponse = {
|
||||
access_token: string
|
||||
refresh_token: string
|
||||
id_token?: string
|
||||
expires_in?: number
|
||||
scope?: string
|
||||
}
|
||||
|
||||
const RemoteModel = Schema.Struct({
|
||||
slug: Schema.String,
|
||||
display_name: Schema.String,
|
||||
visibility: Schema.String,
|
||||
supported_in_api: Schema.Boolean,
|
||||
context_window: Schema.Int.check(Schema.isGreaterThan(1)),
|
||||
input_modalities: Schema.Array(Schema.String),
|
||||
supported_reasoning_levels: Schema.optional(Schema.Array(Schema.Struct({ effort: Schema.String }))),
|
||||
})
|
||||
type RemoteModel = typeof RemoteModel.Type
|
||||
const RemoteModels = Schema.Struct({ models: Schema.Array(RemoteModel) })
|
||||
const decodeCachedModels = Schema.decodeUnknownOption(Schema.Array(RemoteModel))
|
||||
|
||||
// Credential metadata is merged into provider settings; these keys are not OpenAI request options.
|
||||
const decodeMetadata = Schema.decodeUnknownOption(
|
||||
Schema.Struct({
|
||||
clientID: Schema.String,
|
||||
scopes: Schema.optional(Schema.Array(Schema.String)),
|
||||
models: Schema.optional(Schema.Array(RemoteModel)),
|
||||
}),
|
||||
)
|
||||
|
||||
const signIn = (app: App.Info, savedClientID: () => string | undefined, storage: Context["storage"]) =>
|
||||
({
|
||||
integrationID,
|
||||
method: {
|
||||
id: methodID,
|
||||
type: "oauth",
|
||||
label: "Sign in with ChatGPT",
|
||||
},
|
||||
authorize: () =>
|
||||
Effect.gen(function* () {
|
||||
const storedHostID = yield* storage.get("chatgpt-agent-host-id")
|
||||
const hostID = typeof storedHostID === "string" ? storedHostID : `urn:uuid:${crypto.randomUUID()}`
|
||||
if (typeof storedHostID !== "string") yield* storage.set("chatgpt-agent-host-id", hostID)
|
||||
const pkce = yield* Effect.promise(generatePKCE)
|
||||
const state = randomValue()
|
||||
const nonce = randomValue()
|
||||
const savedID = savedClientID()
|
||||
const received = yield* Deferred.make<{ code: string; clientID?: string; response: ServerResponse }, Error>()
|
||||
// Lazy so runtimes without a loopback listener (workerd) never evaluate node:http.
|
||||
const { createServer } = yield* Effect.promise(() => import("node:http"))
|
||||
const server = createServer((request, response) => {
|
||||
const url = new URL(request.url ?? "/", "http://127.0.0.1")
|
||||
if (url.pathname !== "/auth/callback") {
|
||||
response.writeHead(404).end("Not found")
|
||||
return
|
||||
}
|
||||
const error = url.searchParams.get("error_description") ?? url.searchParams.get("error")
|
||||
const authorizationCode = url.searchParams.get("code")
|
||||
if (error) {
|
||||
Effect.runFork(Deferred.fail(received, new Error(error)))
|
||||
response
|
||||
.writeHead(400, { "Content-Type": "text/html" })
|
||||
.end(OauthCallbackPage.error(error, { provider: "ChatGPT" }))
|
||||
return
|
||||
}
|
||||
if (!authorizationCode || url.searchParams.get("state") !== state) {
|
||||
const message = authorizationCode ? "Invalid OAuth state" : "Missing authorization code"
|
||||
Effect.runFork(Deferred.fail(received, new Error(message)))
|
||||
response
|
||||
.writeHead(400, { "Content-Type": "text/html" })
|
||||
.end(OauthCallbackPage.error(message, { provider: "ChatGPT" }))
|
||||
return
|
||||
}
|
||||
if (
|
||||
!Effect.runSync(
|
||||
Deferred.succeed(received, {
|
||||
code: authorizationCode,
|
||||
clientID: url.searchParams.get("client_id") ?? undefined,
|
||||
response,
|
||||
}),
|
||||
)
|
||||
)
|
||||
response.writeHead(409).end("OAuth callback already received")
|
||||
})
|
||||
const port = yield* listen(server)
|
||||
yield* Effect.addFinalizer(() => Effect.sync(() => server.close()))
|
||||
const redirect = `http://127.0.0.1:${port}/auth/callback`
|
||||
return {
|
||||
mode: "auto" as const,
|
||||
url: authorizeURL(redirect, pkce, state, nonce, savedID, hostID),
|
||||
instructions: "Complete authorization in your browser. This window will close automatically.",
|
||||
callback: Effect.gen(function* () {
|
||||
const result = yield* Deferred.await(received)
|
||||
const respond = (error?: string) =>
|
||||
Effect.sync(() =>
|
||||
result.response
|
||||
.writeHead(error ? 400 : 200, { "Content-Type": "text/html" })
|
||||
.end(
|
||||
error
|
||||
? OauthCallbackPage.error(error, { provider: "ChatGPT" })
|
||||
: OauthCallbackPage.success({ provider: "ChatGPT" }),
|
||||
),
|
||||
)
|
||||
return yield* Effect.gen(function* () {
|
||||
// Reauthorization callbacks may omit the client ID; reuse the one this attempt started with.
|
||||
if (savedID && result.clientID && result.clientID !== savedID)
|
||||
return yield* Effect.fail(
|
||||
new Error("ChatGPT returned a different client than this connection. Connect again."),
|
||||
)
|
||||
const clientID = savedID ?? result.clientID
|
||||
if (!clientID)
|
||||
return yield* Effect.fail(new Error("ChatGPT sign-in did not return a client ID. Connect again."))
|
||||
const tokens = yield* exchange(result.code, clientID, redirect, pkce, app)
|
||||
if (!tokens.scope?.split(" ").includes(tokenSharingScope))
|
||||
return yield* Effect.fail(
|
||||
new Error(
|
||||
"ChatGPT sign-in finished without token sharing. Sign in again and allow token sharing, or connect OpenAI with an API key.",
|
||||
),
|
||||
)
|
||||
if (!tokens.id_token) return yield* Effect.fail(new Error("ChatGPT sign-in did not return an ID token."))
|
||||
yield* verifyIDToken(tokens.id_token, clientID, nonce)
|
||||
return credential(tokens, clientID)
|
||||
}).pipe(
|
||||
Effect.tap(() => respond()),
|
||||
Effect.tapError((error) => respond(error instanceof Error ? error.message : "ChatGPT sign-in failed")),
|
||||
Effect.onInterrupt(() => Effect.sync(() => result.response.destroy())),
|
||||
)
|
||||
}),
|
||||
}
|
||||
}),
|
||||
refresh: (value) => refresh(value, app),
|
||||
}) satisfies IntegrationOAuthMethodRegistration
|
||||
|
||||
function listen(server: Server) {
|
||||
return Effect.callback<number, Error>((resume) => {
|
||||
const onError = (error: Error) => resume(Effect.fail(error))
|
||||
server.once("error", onError)
|
||||
server.listen(0, "127.0.0.1", () => {
|
||||
server.off("error", onError)
|
||||
const address = server.address()
|
||||
if (!address || typeof address === "string") return resume(Effect.fail(new Error("Missing OAuth callback port")))
|
||||
resume(Effect.succeed(address.port))
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
export const ChatGPTPlugin = define({
|
||||
id: "opencode.provider.chatgpt",
|
||||
effect: Effect.fn(function* (ctx) {
|
||||
const bus = yield* Bus.Service
|
||||
const credentials = yield* Credential.Service
|
||||
const loading = Semaphore.makeUnsafe(1)
|
||||
let chatgpt: Credential.OAuth | 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 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))
|
||||
}
|
||||
})
|
||||
|
||||
yield* ctx.integration.transform((editor) => {
|
||||
editor.method.update(
|
||||
signIn(ctx.app, () => Option.getOrUndefined(decodeMetadata(chatgpt?.metadata))?.clientID, ctx.storage),
|
||||
)
|
||||
})
|
||||
yield* Effect.forEach(
|
||||
yield* credentials.list(Integration.ID.make("openai")),
|
||||
(entry) => {
|
||||
const value = entry.value
|
||||
if (value.type !== "oauth" || value.methodID !== Integration.MethodID.make("chatgpt-browser"))
|
||||
return Effect.void
|
||||
const metadata = Option.getOrUndefined(decodeMetadata(value.metadata))
|
||||
if (!metadata) return Effect.void
|
||||
return Effect.gen(function* () {
|
||||
const saved = yield* ctx.storage.get(modelCacheKey(metadata.clientID))
|
||||
if (!Option.isSome(decodeCachedModels(saved)) && metadata.models)
|
||||
yield* ctx.storage.set(modelCacheKey(metadata.clientID), metadata.models)
|
||||
const { models: _, ...rest } = value.metadata ?? {}
|
||||
yield* credentials.update(entry.id, {
|
||||
value: Credential.OAuth.make({ ...value, methodID, metadata: rest }),
|
||||
})
|
||||
})
|
||||
},
|
||||
{ discard: true },
|
||||
)
|
||||
yield* load()
|
||||
yield* ctx.session.hook(
|
||||
"retry",
|
||||
(event) =>
|
||||
Effect.sync(() => {
|
||||
if (!chatgpt || !nonRetryableSharingCodes.some((code) => event.error.response?.body.includes(code))) return
|
||||
event.decision = { retry: false }
|
||||
}),
|
||||
{ providerID },
|
||||
)
|
||||
yield* ctx.provider.transform((providers) => {
|
||||
const item = providers.get(providerID)
|
||||
if (!item) return
|
||||
if (!chatgpt || !source) return
|
||||
providers.update(providerID, (provider) => {
|
||||
provider.settings = Provider.mergeOverlay(provider.settings, {
|
||||
baseURL: resource,
|
||||
transport: "http",
|
||||
compaction: { type: "summary" },
|
||||
})
|
||||
})
|
||||
const updated = providers.get(providerID)
|
||||
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)),
|
||||
sourceConnection: source,
|
||||
})
|
||||
})
|
||||
yield* ctx.model.transform((models) => {
|
||||
for (const model of models.list(providerID)) {
|
||||
models.update(model.providerID, model.id, (draft) => {
|
||||
if (!chatgpt) return
|
||||
// Token sharing does not support native /responses/compact.
|
||||
draft.settings = { ...draft.settings, compaction: { type: "summary" } }
|
||||
if (Schema.is(Schema.Struct({ mode: Schema.Literal("pro") }))(draft.body?.reasoning)) {
|
||||
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)))
|
||||
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)
|
||||
}),
|
||||
} satisfies PluginInternal.InternalPlugin)
|
||||
|
||||
function headers(app: App.Info) {
|
||||
return { "Content-Type": "application/x-www-form-urlencoded", "User-Agent": App.useragent(app) }
|
||||
}
|
||||
|
||||
function exchange(code: string, clientID: string, redirect: string, pkce: Pkce, app: App.Info) {
|
||||
return request<TokenResponse>(tokenURL, {
|
||||
method: "POST",
|
||||
headers: headers(app),
|
||||
body: new URLSearchParams({
|
||||
grant_type: "authorization_code",
|
||||
client_id: clientID,
|
||||
code,
|
||||
code_verifier: pkce.verifier,
|
||||
redirect_uri: redirect,
|
||||
resource,
|
||||
}).toString(),
|
||||
})
|
||||
}
|
||||
|
||||
function refresh(value: Credential.OAuth, app: App.Info) {
|
||||
return Effect.gen(function* () {
|
||||
const metadata = Option.getOrUndefined(decodeMetadata(value.metadata))
|
||||
if (!metadata)
|
||||
return yield* Effect.fail(new Error("This ChatGPT connection has no registered client ID. Connect again."))
|
||||
const tokens = yield* request<TokenResponse>(tokenURL, {
|
||||
method: "POST",
|
||||
headers: headers(app),
|
||||
body: new URLSearchParams({
|
||||
grant_type: "refresh_token",
|
||||
client_id: metadata.clientID,
|
||||
refresh_token: value.refresh,
|
||||
resource,
|
||||
}).toString(),
|
||||
})
|
||||
return credential(tokens, metadata.clientID, metadata.scopes)
|
||||
})
|
||||
}
|
||||
|
||||
export function fetchModels(token: string, app: App.Info, baseURL = resource) {
|
||||
return Effect.gen(function* () {
|
||||
const http = HttpClient.filterStatusOk(yield* HttpClient.HttpClient)
|
||||
const response = yield* http.execute(
|
||||
HttpClientRequest.get(`${baseURL}/models`).pipe(
|
||||
HttpClientRequest.bearerToken(token),
|
||||
HttpClientRequest.setHeader("User-Agent", App.useragent(app)),
|
||||
),
|
||||
)
|
||||
const data = yield* HttpClientResponse.schemaBodyJson(RemoteModels)(response)
|
||||
const models = data.models.filter((model) => model.visibility === "list" && model.supported_in_api)
|
||||
if (!models.length) return yield* Effect.fail(new Error("No ChatGPT models are available for this account."))
|
||||
return models
|
||||
})
|
||||
}
|
||||
|
||||
export function deriveModels(remote: ReadonlyArray<RemoteModel>, existing: ReadonlyArray<Model.Info>) {
|
||||
const byID = new Map(remote.map((model) => [model.slug, model]))
|
||||
const known = new Set(existing.map((model) => model.id))
|
||||
return [
|
||||
...existing.flatMap((model) => {
|
||||
const found = byID.get(model.modelID)
|
||||
return found ? [deriveModel(found, model)] : []
|
||||
}),
|
||||
...remote
|
||||
.filter((model) => !known.has(Model.ID.make(model.slug)))
|
||||
.map((model) => deriveModel(model, Model.Info.default(Provider.ID.openai, Model.ID.make(model.slug)))),
|
||||
]
|
||||
}
|
||||
|
||||
function deriveModel(remote: RemoteModel, previous: Model.Info): Model.Info {
|
||||
return {
|
||||
...previous,
|
||||
name: previous.id === previous.modelID ? remote.display_name : previous.name,
|
||||
package: previous.package ?? "@opencode/ai/providers/openai",
|
||||
capabilities: {
|
||||
...previous.capabilities,
|
||||
input: remote.input_modalities.filter((modality) => modality === "text" || modality === "image"),
|
||||
},
|
||||
variants: [
|
||||
...previous.variants.filter((variant) => typeof variant.settings?.reasoningEffort !== "string"),
|
||||
...(remote.supported_reasoning_levels ?? []).map(
|
||||
({ effort }) =>
|
||||
previous.variants.find(
|
||||
(variant) => variant.id === effort && variant.settings?.reasoningEffort === effort,
|
||||
) ?? { id: Model.VariantID.make(effort), settings: { reasoningEffort: effort } },
|
||||
),
|
||||
],
|
||||
limit: { context: remote.context_window, output: previous.limit.output },
|
||||
}
|
||||
}
|
||||
|
||||
export function verifyIDToken(
|
||||
token: string,
|
||||
clientID: string,
|
||||
nonce: string,
|
||||
jwksURL = new URL(`${issuer}/.well-known/jwks.json`),
|
||||
) {
|
||||
return Effect.tryPromise({
|
||||
try: async () => {
|
||||
const { createRemoteJWKSet, jwtVerify } = await import("jose")
|
||||
const { payload } = await jwtVerify(token, createRemoteJWKSet(jwksURL), {
|
||||
issuer,
|
||||
audience: clientID,
|
||||
algorithms: ["RS256"],
|
||||
requiredClaims: ["exp", "nonce", "sub"],
|
||||
})
|
||||
if (typeof payload.sub !== "string" || !payload.sub.trim()) throw new Error("ID token subject is missing")
|
||||
if (payload.nonce !== nonce) throw new Error("ID token nonce does not match this sign-in attempt")
|
||||
},
|
||||
catch: (cause) => new Error("ChatGPT sign-in returned an invalid ID token.", { cause }),
|
||||
})
|
||||
}
|
||||
|
||||
function request<A>(url: string, init: RequestInit) {
|
||||
return Effect.tryPromise({
|
||||
try: async (signal) => {
|
||||
const response = await fetch(url, { ...init, signal })
|
||||
if (!response.ok) throw new Error(`Request failed: ${response.status}`)
|
||||
return response.json() as Promise<A>
|
||||
},
|
||||
catch: (cause) => cause,
|
||||
})
|
||||
}
|
||||
|
||||
function credential(tokens: TokenResponse, clientID: string, scopes?: ReadonlyArray<string>) {
|
||||
return Credential.OAuth.make({
|
||||
type: "oauth",
|
||||
methodID,
|
||||
refresh: tokens.refresh_token,
|
||||
access: tokens.access_token,
|
||||
expires: Date.now() + (tokens.expires_in ?? 3600) * 1000,
|
||||
metadata: { clientID, scopes: tokens.scope?.split(" ").filter(Boolean) ?? scopes ?? [] },
|
||||
})
|
||||
}
|
||||
|
||||
async function generatePKCE(): Promise<Pkce> {
|
||||
const chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~"
|
||||
const verifier = Array.from(crypto.getRandomValues(new Uint8Array(43)), (byte) => chars[byte % chars.length]).join("")
|
||||
const challenge = base64UrlEncode(await crypto.subtle.digest("SHA-256", new TextEncoder().encode(verifier)))
|
||||
return { verifier, challenge }
|
||||
}
|
||||
|
||||
function randomValue() {
|
||||
return base64UrlEncode(crypto.getRandomValues(new Uint8Array(32)).buffer)
|
||||
}
|
||||
|
||||
function base64UrlEncode(buffer: ArrayBuffer) {
|
||||
return Buffer.from(buffer).toString("base64url")
|
||||
}
|
||||
|
||||
function authorizeURL(
|
||||
redirect: string,
|
||||
pkce: Pkce,
|
||||
state: string,
|
||||
nonce: string,
|
||||
savedID: string | undefined,
|
||||
hostID: string,
|
||||
) {
|
||||
return `${issuer}/api/accounts/authorize?${new URLSearchParams({
|
||||
client_id: savedID ?? registrationClientID,
|
||||
...(savedID ? {} : { agent_name_hint: agentName }),
|
||||
ext_agent_host_id: hostID,
|
||||
// Enable only for user-requested consent retries after OpenAI confirms deployment;
|
||||
// ordinary sign-ins must not force reconsent.
|
||||
// force_reconsent: "true",
|
||||
response_type: "code",
|
||||
redirect_uri: redirect,
|
||||
scope: `openid profile email offline_access resource.invoke ${tokenSharingScope}`,
|
||||
resource,
|
||||
state,
|
||||
nonce,
|
||||
code_challenge_method: "S256",
|
||||
code_challenge: pkce.challenge,
|
||||
})}`
|
||||
}
|
||||
@@ -7,6 +7,24 @@ import { AgentNotFoundError, StepFailedError } from "./error.js"
|
||||
import { ModelResolver } from "../model-resolver.js"
|
||||
import { SessionRunnerModel } from "./runner/model.js"
|
||||
|
||||
const tokenSharingMessages = {
|
||||
subscription_sharing_user_not_eligible:
|
||||
"ChatGPT token sharing isn't available for this account. Connect with an API key or choose another provider.",
|
||||
subscription_sharing_usage_limit_exceeded:
|
||||
"ChatGPT usage limit reached. Try again after your allowance resets; check ChatGPT Settings → Usage for details.",
|
||||
subscription_sharing_usage_unavailable: "ChatGPT usage can't be checked right now. Try again later.",
|
||||
subscription_sharing_unsupported_capability:
|
||||
"This request uses a feature ChatGPT token sharing doesn't support. Remove the unsupported feature and try again.",
|
||||
subscription_sharing_route_not_supported:
|
||||
"ChatGPT token sharing doesn't support this API route. Check the configured endpoint and HTTP method.",
|
||||
subscription_sharing_invalid_user: "This ChatGPT connection is no longer valid. Reconnect to ChatGPT.",
|
||||
subscription_sharing_user_unavailable: "Your ChatGPT account is temporarily unavailable. Try again later.",
|
||||
chatpass_v2_scope_not_authorized:
|
||||
"This ChatGPT connection isn't authorized for this request. Reconnect to ChatGPT or choose another connection.",
|
||||
chatpass_v2_invalid_authorization_context:
|
||||
"This ChatGPT connection isn't authorized for this request. Reconnect to ChatGPT or choose another connection.",
|
||||
}
|
||||
|
||||
export function toSessionError(cause: unknown): SessionError.Error {
|
||||
if (cause instanceof AIError) {
|
||||
switch (cause.reason._tag) {
|
||||
@@ -41,6 +59,7 @@ export function toSessionError(cause: unknown): SessionError.Error {
|
||||
}
|
||||
}
|
||||
if (cause instanceof Permission.BlockedError) return { type: "permission.rejected", message: cause.message }
|
||||
if (cause instanceof Permission.CorrectedError) return { type: "permission.rejected", message: cause.feedback }
|
||||
if (cause instanceof ToolFailure || cause instanceof Tool.Error) {
|
||||
if (cause.error === undefined) return { type: "tool.execution", message: cause.message }
|
||||
// The canonical error is the sole model-visible representation, so a cause
|
||||
@@ -68,5 +87,10 @@ export function toSessionError(cause: unknown): SessionError.Error {
|
||||
|
||||
function providerError(type: string, reason: AIError["reason"]): SessionError.Error {
|
||||
const status = reason.http?.status
|
||||
return { type, message: reason.message, ...(status === undefined ? {} : { status }) }
|
||||
return {
|
||||
type,
|
||||
message: Object.entries(tokenSharingMessages).find(([code]) => reason.body?.includes(code))?.[1] ?? reason.message,
|
||||
...(status === undefined ? {} : { status }),
|
||||
...(reason.body === undefined ? {} : { response: { body: reason.body } }),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -199,4 +199,49 @@ describe("Credential", () => {
|
||||
expect((yield* credentials.list(otherIntegrationID)).at(-1)).toEqual(otherOlder)
|
||||
}),
|
||||
)
|
||||
|
||||
it.effect("creates credentials with a requested ID without taking over the current selection", () =>
|
||||
Effect.gen(function* () {
|
||||
const credentials = yield* Credential.Service
|
||||
const bus = yield* Bus.Service
|
||||
const database = yield* Database.Service
|
||||
const integrationID = Integration.ID.make("openai")
|
||||
const events = new Array<Event.Payload>()
|
||||
yield* bus.listen((event) => Effect.sync(() => events.push(event)))
|
||||
|
||||
const first = yield* credentials.create({
|
||||
id: Credential.ID.make("cred_0000imported"),
|
||||
integrationID,
|
||||
value: Credential.Key.make({ type: "key", key: "first" }),
|
||||
activate: false,
|
||||
})
|
||||
expect(first.id).toBe(Credential.ID.make("cred_0000imported"))
|
||||
expect((yield* credentials.list(integrationID)).at(-1)).toEqual(first)
|
||||
|
||||
const legacy = yield* credentials.create({
|
||||
integrationID,
|
||||
value: Credential.Key.make({ type: "key", key: "legacy" }),
|
||||
})
|
||||
yield* database.db
|
||||
.update(CredentialTable)
|
||||
.set({ active: null })
|
||||
.where(eq(CredentialTable.integration_id, integrationID))
|
||||
.run()
|
||||
.pipe(Effect.orDie)
|
||||
const imported = yield* credentials.create({
|
||||
integrationID,
|
||||
value: Credential.Key.make({ type: "key", key: "imported" }),
|
||||
activate: false,
|
||||
})
|
||||
|
||||
expect(yield* credentials.list(integrationID)).toEqual([first, imported, legacy])
|
||||
expect(events.map((event) => ({ type: event.type, data: event.data }))).toEqual([
|
||||
{ type: Credential.Event.Updated.type, data: {} },
|
||||
{ type: Credential.Event.Switched.type, data: { integrationID, credentialID: first.id } },
|
||||
{ type: Credential.Event.Updated.type, data: {} },
|
||||
{ type: Credential.Event.Switched.type, data: { integrationID, credentialID: legacy.id } },
|
||||
{ type: Credential.Event.Updated.type, data: {} },
|
||||
])
|
||||
}),
|
||||
)
|
||||
})
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
import { describe, expect, test } from "bun:test"
|
||||
import { chmod, stat, writeFile } from "node:fs/promises"
|
||||
import path from "path"
|
||||
import { Effect, Layer } from "effect"
|
||||
import { Database } from "@opencode/core/database/database"
|
||||
import { Global } from "@opencode/util/global"
|
||||
import { tmpdir } from "./fixture/tmpdir"
|
||||
|
||||
// Read while the connection is open: SQLite may remove the sidecars on close.
|
||||
const openModes = (filename: string) =>
|
||||
Effect.runPromise(
|
||||
Effect.gen(function* () {
|
||||
yield* Layer.build(Database.layer({ path: filename }))
|
||||
return yield* Effect.promise(() =>
|
||||
Promise.all(["", "-wal", "-shm"].map(async (suffix) => (await stat(filename + suffix)).mode & 0o777)),
|
||||
)
|
||||
}).pipe(Effect.scoped, Effect.provideService(Global.Service, Global.make({ data: path.dirname(filename) }))),
|
||||
)
|
||||
|
||||
describe.skipIf(process.platform === "win32")("Database file permissions", () => {
|
||||
test("creates the database and sidecars readable only by the owner", async () => {
|
||||
await using tmp = await tmpdir()
|
||||
|
||||
expect(await openModes(path.join(tmp.path, "opencode.db"))).toEqual([0o600, 0o600, 0o600])
|
||||
})
|
||||
|
||||
test("tightens an existing database and sidecars", async () => {
|
||||
await using tmp = await tmpdir()
|
||||
const filename = path.join(tmp.path, "opencode.db")
|
||||
await Promise.all(
|
||||
["", "-wal", "-shm"].map(async (suffix) => {
|
||||
await writeFile(filename + suffix, "")
|
||||
await chmod(filename + suffix, 0o644)
|
||||
}),
|
||||
)
|
||||
|
||||
expect(await openModes(filename)).toEqual([0o600, 0o600, 0o600])
|
||||
})
|
||||
})
|
||||
File diff suppressed because it is too large
Load Diff
@@ -110,6 +110,7 @@ describe("toSessionError", () => {
|
||||
type: "provider.invalid-request",
|
||||
message: "too large",
|
||||
status: 413,
|
||||
response: { body: '{"error":"context limit"}' },
|
||||
})
|
||||
expect(
|
||||
toSessionError(
|
||||
@@ -127,6 +128,38 @@ describe("toSessionError", () => {
|
||||
})
|
||||
})
|
||||
|
||||
test("preserves provider response body without HTTP status", () => {
|
||||
expect(toSessionError(llm(new RateLimitError({ message: "Slow down", body: '{"error":"rate limit"}' })))).toEqual({
|
||||
type: "provider.rate-limit",
|
||||
message: "Slow down",
|
||||
response: { body: '{"error":"rate limit"}' },
|
||||
})
|
||||
})
|
||||
|
||||
test("maps token-sharing failures while preserving HTTP and stream bodies", () => {
|
||||
const cases = [
|
||||
["subscription_sharing_user_not_eligible", "token sharing isn't available for this account"],
|
||||
["subscription_sharing_usage_limit_exceeded", "ChatGPT usage limit reached"],
|
||||
["subscription_sharing_usage_unavailable", "Try again later"],
|
||||
["subscription_sharing_unsupported_capability", "Remove the unsupported feature"],
|
||||
["subscription_sharing_route_not_supported", "Check the configured endpoint"],
|
||||
["subscription_sharing_invalid_user", "Reconnect to ChatGPT"],
|
||||
["subscription_sharing_user_unavailable", "Try again later"],
|
||||
["chatpass_v2_scope_not_authorized", "isn't authorized for this request"],
|
||||
["chatpass_v2_invalid_authorization_context", "isn't authorized for this request"],
|
||||
] as const
|
||||
for (const [code, guidance] of cases) {
|
||||
for (const body of [
|
||||
JSON.stringify({ error: { code, message: "Request failed" } }),
|
||||
JSON.stringify({ type: "response.failed", response: { error: { code, message: "Request failed" } } }),
|
||||
]) {
|
||||
const error = toSessionError(llm(new UnknownProviderError({ message: "Request failed", body })))
|
||||
expect(error.message).toContain(guidance)
|
||||
expect(error.response).toEqual({ body })
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
test("preserves unresolved provider endpoint errors", () => {
|
||||
const error = new ModelResolver.UnresolvedProviderVariablesError({
|
||||
providerID: Provider.ID.make("cloudflare-workers-ai"),
|
||||
|
||||
@@ -1,8 +1,34 @@
|
||||
import { Credential } from "@opencode/schema/credential"
|
||||
import { Schema } from "effect"
|
||||
import { HttpApiEndpoint, HttpApiGroup, HttpApiSchema, OpenApi } from "effect/unstable/httpapi"
|
||||
import { ConflictError } from "../errors.js"
|
||||
|
||||
export const CredentialGroup = HttpApiGroup.make("server.credential")
|
||||
.add(
|
||||
HttpApiEndpoint.get("credential.list", "/api/credential", {
|
||||
success: Schema.Struct({ data: Schema.Array(Credential.Entry) }),
|
||||
}).annotateMerge(
|
||||
OpenApi.annotations({
|
||||
identifier: "credential.list",
|
||||
summary: "List credentials",
|
||||
description: "List every stored integration credential, including its secret value.",
|
||||
}),
|
||||
),
|
||||
)
|
||||
.add(
|
||||
HttpApiEndpoint.post("credential.create", "/api/credential", {
|
||||
payload: Credential.CreateInput,
|
||||
success: Schema.Struct({ data: Credential.Entry }),
|
||||
error: ConflictError,
|
||||
}).annotateMerge(
|
||||
OpenApi.annotations({
|
||||
identifier: "credential.create",
|
||||
summary: "Create credential",
|
||||
description:
|
||||
"Store an integration credential. It becomes the integration's active credential unless activate is false and the integration already has one. Fails with a conflict when the requested ID already exists.",
|
||||
}),
|
||||
),
|
||||
)
|
||||
.add(
|
||||
HttpApiEndpoint.patch("credential.update", "/api/credential/:credentialID", {
|
||||
params: { credentialID: Credential.ID },
|
||||
|
||||
@@ -50,3 +50,21 @@ export const Value = Schema.Union([OAuth, Key])
|
||||
.pipe(Schema.toTaggedUnion("type"))
|
||||
.annotate({ identifier: "Credential.Value" })
|
||||
export type Value = Schema.Schema.Type<typeof Value>
|
||||
|
||||
export interface Entry extends Schema.Schema.Type<typeof Entry> {}
|
||||
export const Entry = Schema.Struct({
|
||||
id: ID,
|
||||
integrationID: IntegrationID,
|
||||
label: Schema.String,
|
||||
active: Schema.Boolean,
|
||||
value: Value,
|
||||
}).annotate({ identifier: "Credential.Entry" })
|
||||
|
||||
export interface CreateInput extends Schema.Schema.Type<typeof CreateInput> {}
|
||||
export const CreateInput = Schema.Struct({
|
||||
id: optional(ID),
|
||||
integrationID: IntegrationID,
|
||||
label: optional(Schema.String),
|
||||
value: Value,
|
||||
activate: optional(Schema.Boolean),
|
||||
}).annotate({ identifier: "Credential.CreateInput" })
|
||||
|
||||
@@ -8,4 +8,5 @@ export const Error = Schema.Struct({
|
||||
type: Schema.String,
|
||||
message: Schema.String,
|
||||
status: Schema.Int.check(Schema.isBetween({ minimum: 100, maximum: 599 })).pipe(optional),
|
||||
response: Schema.Struct({ body: Schema.String }).pipe(optional),
|
||||
}).annotate({ identifier: "Session.StructuredError" })
|
||||
|
||||
@@ -11,6 +11,7 @@ describe("SessionError", () => {
|
||||
test("round trips current and future error types through JSON", () => {
|
||||
const values: SessionError.Error[] = [
|
||||
{ type: "provider.rate-limit", message: "Slow down" },
|
||||
{ type: "provider.rate-limit", message: "Slow down", status: 429, response: { body: '{"error":{}}' } },
|
||||
{ type: "provider.auth", message: "Authentication failed" },
|
||||
{ type: "provider.future-condition", message: "A future provider failure" },
|
||||
{ type: "unknown", message: "Unexpected" },
|
||||
@@ -36,6 +37,9 @@ describe("SessionError", () => {
|
||||
test("rejects missing envelope fields", () => {
|
||||
expect(() => Schema.decodeUnknownSync(SessionError.Error)({ type: "provider.auth" })).toThrow()
|
||||
expect(() => Schema.decodeUnknownSync(SessionError.Error)({ message: "Missing type" })).toThrow()
|
||||
expect(() =>
|
||||
Schema.decodeUnknownSync(SessionError.Error)({ type: "provider.auth", message: "Failed", response: {} }),
|
||||
).toThrow()
|
||||
})
|
||||
})
|
||||
|
||||
|
||||
@@ -1,10 +1,32 @@
|
||||
import { Credential } from "@opencode/core/credential"
|
||||
import { ConflictError } from "@opencode/protocol/errors"
|
||||
import { Effect } from "effect"
|
||||
import { HttpApiBuilder, HttpApiSchema } from "effect/unstable/httpapi"
|
||||
import { Api } from "../api"
|
||||
|
||||
export const CredentialHandler = HttpApiBuilder.group(Api, "server.credential", (handlers) =>
|
||||
handlers
|
||||
.handle(
|
||||
"credential.list",
|
||||
Effect.fn(function* () {
|
||||
const credential = yield* Credential.Service
|
||||
return { data: entries(yield* credential.all()) }
|
||||
}),
|
||||
)
|
||||
.handle(
|
||||
"credential.create",
|
||||
Effect.fn(function* (ctx) {
|
||||
const credential = yield* Credential.Service
|
||||
if (ctx.payload.id && (yield* credential.get(ctx.payload.id)))
|
||||
return yield* new ConflictError({
|
||||
resource: ctx.payload.id,
|
||||
message: `Credential already exists: ${ctx.payload.id}`,
|
||||
})
|
||||
const created = yield* credential.create(ctx.payload)
|
||||
const entry = entries(yield* credential.list(created.integrationID)).find((item) => item.id === created.id)
|
||||
return { data: entry ?? { ...created, active: false } }
|
||||
}),
|
||||
)
|
||||
.handle(
|
||||
"credential.update",
|
||||
Effect.fn(function* (ctx) {
|
||||
@@ -30,3 +52,15 @@ export const CredentialHandler = HttpApiBuilder.group(Api, "server.credential",
|
||||
}),
|
||||
),
|
||||
)
|
||||
|
||||
// Credential listings order each integration's selected credential last.
|
||||
function entries(credentials: Credential.Info[]) {
|
||||
const selected = new Map(credentials.map((item) => [item.integrationID, item.id]))
|
||||
return credentials.map((item) => ({
|
||||
id: item.id,
|
||||
integrationID: item.integrationID,
|
||||
label: item.label,
|
||||
active: selected.get(item.integrationID) === item.id,
|
||||
value: item.value,
|
||||
}))
|
||||
}
|
||||
|
||||
@@ -4,8 +4,11 @@ import { Global } from "@opencode/util/global"
|
||||
import { Effect, FileSystem } from "effect"
|
||||
import { createEventStream, createFetch, json } from "./fixture/tui-client"
|
||||
import { tmpdir } from "./fixture/fixture"
|
||||
import { takeDraft } from "../src/component/prompt/draft-stash"
|
||||
|
||||
test("stats shows only this year and returns after errors or success", async () => {
|
||||
// Other app tests can leave a home draft in the process-wide stash.
|
||||
takeDraft(undefined)
|
||||
await using state = await tmpdir()
|
||||
const setup = await createTestRenderer({ width: 100, height: 34, useThread: false, kittyKeyboard: true })
|
||||
setup.renderer.start()
|
||||
|
||||
@@ -36,6 +36,7 @@ You can also access the models directly through the following API endpoints.
|
||||
| ------------------------------- | ------------------------------- | --------------------------------------------------------- | --------------------------- |
|
||||
| GPT 6 Astra | gpt-6-astra | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` |
|
||||
| GPT 6 Sol | gpt-6-sol | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` |
|
||||
| GPT 6.1 Sol | gpt-6.1-sol | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` |
|
||||
| GPT 6 Luna | gpt-6-luna | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` |
|
||||
| GPT 5.6 Sol | gpt-5.6-sol | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` |
|
||||
| GPT 5.6 Terra | gpt-5.6-terra | `https://opencode.ai/zen/v1/responses` | `@ai-sdk/openai` |
|
||||
@@ -263,6 +264,8 @@ Console uses pay-as-you-go pricing. Below are the prices **per 1M tokens**.
|
||||
| GPT 6 Astra (> 272K tokens) | $20.00 | $75.00 | $2.00 | $25.00 |
|
||||
| GPT 6 Sol (≤ 272K tokens) | $2.00 | $10.00 | $0.20 | $2.50 |
|
||||
| GPT 6 Sol (> 272K tokens) | $4.00 | $15.00 | $0.40 | $5.00 |
|
||||
| GPT 6.1 Sol (≤ 272K tokens) | $2.00 | $10.00 | $0.20 | $2.50 |
|
||||
| GPT 6.1 Sol (> 272K tokens) | $4.00 | $15.00 | $0.40 | $5.00 |
|
||||
| GPT 6 Luna (≤ 272K tokens) | $0.10 | $0.50 | $0.01 | $0.125 |
|
||||
| GPT 6 Luna (> 272K tokens) | $0.20 | $0.75 | $0.02 | $0.25 |
|
||||
| GPT 5.6 Sol (≤ 272K tokens) | $4.00 | $20.00 | $0.40 | $5.00 |
|
||||
|
||||
Reference in New Issue
Block a user