mirror of
https://github.com/anomalyco/opencode.git
synced 2026-10-07 15:58:23 +00:00
Compare commits
4
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b346503924 | ||
|
|
d3b3d5c2bd | ||
|
|
34cf183c4c | ||
|
|
fd99516e51 |
No files matched your search
@@ -285,7 +285,7 @@ const AnthropicThinkingEnabled = Schema.Struct({
|
||||
...AnthropicThinkingFields,
|
||||
})
|
||||
const AnthropicThinkingAdaptive = Schema.Struct({ type: Schema.tag("adaptive"), ...AnthropicThinkingFields })
|
||||
const AnthropicThinkingDisabled = Schema.Struct({ type: Schema.tag("disabled") })
|
||||
const AnthropicThinkingDisabled = Schema.Struct({ type: Schema.Literals(["disabled", "between_tools"]) })
|
||||
const AnthropicThinking = Schema.Union([AnthropicThinkingEnabled, AnthropicThinkingAdaptive, AnthropicThinkingDisabled])
|
||||
type AnthropicThinking = typeof AnthropicThinking.Type
|
||||
|
||||
@@ -1001,18 +1001,21 @@ const lowerMessages = Effect.fnUntraced(function* (request: LLMRequest, breakpoi
|
||||
// TODO: Move per-model capability heuristics (`supportsEffortUpdates`, `supportsNativeSystemUpdates`,
|
||||
// `supportsThinkingBlockBinding`) into explicit model/provider `compatibility` metadata so the protocol
|
||||
// only reads `request.model.compatibility`.
|
||||
const isThinkingOff = Schema.is(AnthropicThinkingDisabled)
|
||||
|
||||
// Per-turn effort started with Claude Opus 5 and every Claude 5.1 model; later versions of any family inherit it.
|
||||
const supportsEffortUpdates = (model: LLMRequest["model"]) => {
|
||||
const override = model.compatibility?.supportsEffortUpdates
|
||||
const supportsEffortUpdates = (request: LLMRequest) => {
|
||||
if (isThinkingOff(request.providerOptions?.thinking)) return false
|
||||
const override = request.model.compatibility?.supportsEffortUpdates
|
||||
if (override !== undefined) return override
|
||||
const version = claudeVersion(model.id)
|
||||
const version = claudeVersion(request.model.id)
|
||||
if (version === undefined) return false
|
||||
if (version.family === "opus" && version.major >= 5) return true
|
||||
return version.major > 5 || (version.major === 5 && version.minor >= 1)
|
||||
}
|
||||
|
||||
const applyThinkingBindingDefault = (model: LLMRequest["model"], thinking: AnthropicThinking | undefined) => {
|
||||
if (thinking?.type === "disabled") return thinking
|
||||
if (isThinkingOff(thinking)) return thinking
|
||||
if (!supportsThinkingBlockBinding(model)) return thinking
|
||||
return {
|
||||
...(thinking ?? { type: "adaptive" as const }),
|
||||
@@ -1607,7 +1610,7 @@ export const protocol = Protocol.make({
|
||||
}),
|
||||
step,
|
||||
},
|
||||
supportsEffortUpdates: (request) => supportsEffortUpdates(request.model),
|
||||
supportsEffortUpdates,
|
||||
})
|
||||
|
||||
export const transport = <
|
||||
@@ -1653,7 +1656,7 @@ function requiredBetaHeaders(body: Pick<AnthropicMessagesBody, "messages" | "con
|
||||
betas.push("mid-conversation-output-config-2026-07-01")
|
||||
|
||||
const thinking = body.thinking
|
||||
if (thinking && thinking.type !== "disabled" && thinking.block_binding) betas.push(THINKING_BINDING_BETA)
|
||||
if (thinking && !isThinkingOff(thinking) && thinking.block_binding) betas.push(THINKING_BINDING_BETA)
|
||||
return betas
|
||||
}
|
||||
|
||||
|
||||
@@ -476,7 +476,9 @@ const MIN_THINKING_BUDGET = 1_024
|
||||
|
||||
const isThinkingDisabled = Schema.is(
|
||||
Schema.Struct({
|
||||
additionalModelRequestFields: Schema.Struct({ thinking: Schema.Struct({ type: Schema.Literal("disabled") }) }),
|
||||
additionalModelRequestFields: Schema.Struct({
|
||||
thinking: Schema.Struct({ type: Schema.Literals(["disabled", "between_tools"]) }),
|
||||
}),
|
||||
}),
|
||||
)
|
||||
|
||||
|
||||
@@ -246,9 +246,23 @@ export const OpenAIChatToolCallDelta = Schema.Struct({
|
||||
})
|
||||
type OpenAIChatToolCallDelta = Schema.Schema.Type<typeof OpenAIChatToolCallDelta>
|
||||
|
||||
// Mistral-style models stream `content` as typed parts instead of a string:
|
||||
// `text` parts carry output, and `thinking` parts nest their own text units.
|
||||
// Other part types (references, media) carry nothing renderable and are skipped.
|
||||
const OpenAIChatThinkingText = Schema.StructWithRest(Schema.Struct({ text: optionalNull(Schema.String) }), [JsonObject])
|
||||
|
||||
const OpenAIChatContentPart = Schema.StructWithRest(
|
||||
Schema.Struct({
|
||||
type: Schema.String,
|
||||
text: optionalNull(Schema.String),
|
||||
thinking: optionalNull(Schema.Union([Schema.String, Schema.Array(OpenAIChatThinkingText)])),
|
||||
}),
|
||||
[JsonObject],
|
||||
)
|
||||
|
||||
export const OpenAIChatDelta = Schema.StructWithRest(
|
||||
Schema.Struct({
|
||||
content: optionalNull(Schema.String),
|
||||
content: optionalNull(Schema.Union([Schema.String, Schema.Array(OpenAIChatContentPart)])),
|
||||
refusal: optionalNull(Schema.String),
|
||||
reasoning_content: optionalNull(Schema.String),
|
||||
reasoning: optionalNull(Schema.String),
|
||||
@@ -953,6 +967,37 @@ const reasoningDelta = (
|
||||
return undefined
|
||||
}
|
||||
|
||||
interface ContentDelta {
|
||||
readonly type: "text" | "reasoning"
|
||||
readonly text: string
|
||||
}
|
||||
|
||||
// Flattens string or part-array content into ordered text and reasoning deltas.
|
||||
const contentDeltas = Effect.fnUntraced(function* (content: Schema.Schema.Type<typeof OpenAIChatDelta>["content"]) {
|
||||
if (!content) return []
|
||||
if (typeof content === "string") return [{ type: "text" as const, text: content }]
|
||||
const deltas: ContentDelta[] = []
|
||||
const skipped: string[] = []
|
||||
for (const part of content) {
|
||||
if (part.type === "text") {
|
||||
if (part.text) deltas.push({ type: "text", text: part.text })
|
||||
} else if (part.type === "thinking") {
|
||||
const text =
|
||||
typeof part.thinking === "string"
|
||||
? part.thinking
|
||||
: (part.thinking ?? []).map((unit) => unit.text ?? "").join("")
|
||||
if (text) deltas.push({ type: "reasoning", text })
|
||||
} else {
|
||||
skipped.push(part.type)
|
||||
}
|
||||
}
|
||||
if (skipped.length > 0)
|
||||
yield* Effect.logDebug("openai-chat.content_parts_skipped").pipe(
|
||||
Effect.annotateLogs({ types: skipped.join(",") }),
|
||||
)
|
||||
return deltas
|
||||
})
|
||||
|
||||
const detailText = (details: ReadonlyArray<ReasoningDetail>, hideKimiSummary: boolean) => {
|
||||
const text = details.flatMap((detail) => {
|
||||
if (detail.type === "reasoning.text") return detail.text ? [detail.text] : []
|
||||
@@ -1078,8 +1123,9 @@ const step = (state: ParserState, event: OpenAIChatEvent) =>
|
||||
let lifecycle = state.lifecycle
|
||||
|
||||
const reasoning = reasoningDelta(delta, state.reasoningField)
|
||||
const content = yield* contentDeltas(delta?.content)
|
||||
const hasLateContent =
|
||||
Boolean(delta?.content) ||
|
||||
content.length > 0 ||
|
||||
Boolean(delta?.refusal) ||
|
||||
reasoning !== undefined ||
|
||||
(Array.isArray(delta?.reasoning_details) && delta.reasoning_details.length > 0) ||
|
||||
@@ -1109,17 +1155,21 @@ const step = (state: ParserState, event: OpenAIChatEvent) =>
|
||||
else if (
|
||||
reasoningDetailsObserved &&
|
||||
!lifecycle.reasoning.has("reasoning-0") &&
|
||||
(Boolean(delta?.content) || Boolean(delta?.refusal) || toolDeltas.length > 0)
|
||||
(content.length > 0 || Boolean(delta?.refusal) || toolDeltas.length > 0)
|
||||
)
|
||||
lifecycle = Lifecycle.reasoningStart(lifecycle, events, "reasoning-0", deltaMetadata)
|
||||
const reasoningEmitted = state.reasoningEmitted || lifecycle.reasoning.has("reasoning-0")
|
||||
|
||||
// Reasoning is one response-wide channel: it stays open alongside text and
|
||||
// refusal output so late reasoning deltas and details join the same block,
|
||||
// and `finishEvents` closes it once with the complete metadata.
|
||||
if (delta?.content) lifecycle = Lifecycle.textDelta(lifecycle, events, "text-0", delta.content)
|
||||
for (const part of content)
|
||||
lifecycle =
|
||||
part.type === "text"
|
||||
? Lifecycle.textDelta(lifecycle, events, "text-0", part.text)
|
||||
: Lifecycle.reasoningDelta(lifecycle, events, "reasoning-0", part.text, deltaMetadata)
|
||||
|
||||
if (delta?.refusal) lifecycle = Lifecycle.textDelta(lifecycle, events, "text-0", delta.refusal)
|
||||
const reasoningEmitted = state.reasoningEmitted || lifecycle.reasoning.has("reasoning-0")
|
||||
|
||||
// Compatible providers may omit indexes. Prefer durable identity, then use
|
||||
// batch position for parallel deltas or the latest call for sparse chunks.
|
||||
|
||||
@@ -65,8 +65,8 @@ const messagesRoute = Route.make({
|
||||
...AnthropicMessages.protocol,
|
||||
// Mantle rejects mid-conversation `output_config` on Opus 5.0; support starts at 5.1+.
|
||||
supportsEffortUpdates: (request) => {
|
||||
const override = request.model.compatibility?.supportsEffortUpdates
|
||||
if (override !== undefined) return override
|
||||
if (!(AnthropicMessages.protocol.supportsEffortUpdates?.(request) ?? false)) return false
|
||||
if (request.model.compatibility?.supportsEffortUpdates !== undefined) return true
|
||||
const version = claudeVersion(request.model.id)
|
||||
return version !== undefined && (version.major > 5 || (version.major === 5 && version.minor >= 1))
|
||||
},
|
||||
|
||||
@@ -268,6 +268,22 @@ describe("Anthropic Messages effort updates", () => {
|
||||
}),
|
||||
)
|
||||
|
||||
it.effect("strips markers when thinking is disabled or between_tools", () =>
|
||||
Effect.gen(function* () {
|
||||
const sonnet = anthropic("claude-sonnet-5-5")
|
||||
const betweenTools = yield* compileRequest(
|
||||
LLM.request({
|
||||
model: sonnet,
|
||||
messages: conversation,
|
||||
providerOptions: { thinking: { type: "between_tools" }, effort: "low" },
|
||||
}),
|
||||
)
|
||||
|
||||
expect(systemMessages(betweenTools.body)).toHaveLength(0)
|
||||
expect(betweenTools.body.output_config).toEqual({ effort: "low" })
|
||||
}),
|
||||
)
|
||||
|
||||
it.effect("strips markers for Opus 5.0 on Bedrock Mantle Messages while lowering Opus 5.5", () =>
|
||||
Effect.gen(function* () {
|
||||
const mantle = AmazonBedrockMantle.configure({ apiKey: "test", region: "us-east-1" })
|
||||
|
||||
@@ -44,6 +44,7 @@ it.effect("preserves explicit thinking settings and combines required beta heade
|
||||
Effect.gen(function* () {
|
||||
for (const thinking of [
|
||||
{ type: "disabled" },
|
||||
{ type: "between_tools" },
|
||||
{ type: "adaptive", block_binding: { prefix_mismatch_behavior: "error" } },
|
||||
] as const) {
|
||||
const request = LLM.request({
|
||||
@@ -55,7 +56,7 @@ it.effect("preserves explicit thinking settings and combines required beta heade
|
||||
const prepared = yield* AnthropicMessages.route.prepareTransport(compiled.body, request)
|
||||
expect(compiled.body.thinking).toEqual(thinking)
|
||||
expect(prepared.request.headers["anthropic-beta"]).toBe(
|
||||
thinking.type === "disabled"
|
||||
thinking.type === "disabled" || thinking.type === "between_tools"
|
||||
? "interleaved-thinking-2025-05-14,compact-2026-01-12"
|
||||
: "interleaved-thinking-2025-05-14,compact-2026-01-12,thinking-binding-controls-2026-08-01",
|
||||
)
|
||||
|
||||
@@ -605,4 +605,123 @@ describe("OpenAI-compatible Chat route", () => {
|
||||
})
|
||||
}),
|
||||
)
|
||||
|
||||
describe("content part arrays", () => {
|
||||
const custom = LLMRequest.update(request, {
|
||||
model: OpenAICompatibleChat.route
|
||||
.with({ provider: "custom", endpoint: { baseURL: "https://api.custom.test/v1" } })
|
||||
.model({ id: "example-model" }),
|
||||
})
|
||||
// Shape recorded from a Mistral-family model served through an
|
||||
// OpenAI-compatible gateway.
|
||||
const partChunk = (content: unknown, finishReason: string | null = null) => ({
|
||||
id: "chunk_fixture",
|
||||
object: "chat.completion.chunk",
|
||||
created: 1791353545,
|
||||
model: "example-model",
|
||||
choices: [{ index: 0, finish_reason: finishReason, logprobs: null, delta: { content } }],
|
||||
})
|
||||
const thinking = (text: string) => ({ type: "thinking", thinking: [{ type: "text", text }] })
|
||||
const generate = (...chunks: ReadonlyArray<unknown>) =>
|
||||
LLMClient.generate(custom).pipe(Effect.provide(fixedResponse(sseEvents(...chunks))))
|
||||
|
||||
it.effect("streams thinking parts as reasoning and text parts as text", () =>
|
||||
Effect.gen(function* () {
|
||||
const response = yield* generate(
|
||||
partChunk([thinking("Let")]),
|
||||
partChunk([thinking(" me think.")]),
|
||||
partChunk([{ type: "text", text: "Hello" }]),
|
||||
partChunk([{ type: "text", text: "!" }]),
|
||||
partChunk(null, "stop"),
|
||||
)
|
||||
|
||||
expect(response.reasoning).toBe("Let me think.")
|
||||
expect(response.text).toBe("Hello!")
|
||||
expect(response.finishReason).toEqual({ normalized: "stop", raw: "stop" })
|
||||
expect(
|
||||
response.events.filter((event) => event.type === "reasoning-delta" || event.type === "text-delta"),
|
||||
).toMatchObject([
|
||||
{ type: "reasoning-delta", id: "reasoning-0", text: "Let" },
|
||||
{ type: "reasoning-delta", id: "reasoning-0", text: " me think." },
|
||||
{ type: "text-delta", id: "text-0", text: "Hello" },
|
||||
{ type: "text-delta", id: "text-0", text: "!" },
|
||||
])
|
||||
|
||||
const replay = yield* compileRequest(LLM.request({ model: custom.model, messages: [response.message] }))
|
||||
expect(replay.body.messages).toEqual([
|
||||
{ role: "assistant", content: "Hello!", reasoning_content: "Let me think." },
|
||||
])
|
||||
}),
|
||||
)
|
||||
|
||||
it.effect("keeps part order within one chunk", () =>
|
||||
Effect.gen(function* () {
|
||||
const response = yield* generate(
|
||||
partChunk([
|
||||
thinking("Plan"),
|
||||
{ type: "thinking", thinking: "ned." },
|
||||
{ type: "text", text: "Done" },
|
||||
{ type: "text", text: "." },
|
||||
]),
|
||||
partChunk([], "stop"),
|
||||
)
|
||||
|
||||
expect(response.reasoning).toBe("Planned.")
|
||||
expect(response.text).toBe("Done.")
|
||||
expect(
|
||||
response.events.filter((event) => event.type === "reasoning-delta" || event.type === "text-delta"),
|
||||
).toMatchObject([
|
||||
{ type: "reasoning-delta", text: "Plan" },
|
||||
{ type: "reasoning-delta", text: "ned." },
|
||||
{ type: "text-delta", text: "Done" },
|
||||
{ type: "text-delta", text: "." },
|
||||
])
|
||||
}),
|
||||
)
|
||||
|
||||
it.effect("skips unknown part types and empty parts", () =>
|
||||
Effect.gen(function* () {
|
||||
const response = yield* generate(
|
||||
partChunk([{ type: "reference", reference_ids: [1, 2] }]),
|
||||
partChunk([
|
||||
{
|
||||
type: "thinking",
|
||||
thinking: [
|
||||
{ type: "reference", reference_ids: [3] },
|
||||
{ type: "text", text: "Hm" },
|
||||
],
|
||||
},
|
||||
]),
|
||||
partChunk([
|
||||
{ type: "text", text: "" },
|
||||
{ type: "image_url", image_url: { url: "https://x.test/a.png" } },
|
||||
]),
|
||||
partChunk([{ type: "text", text: "Hi" }]),
|
||||
partChunk(null, "stop"),
|
||||
)
|
||||
|
||||
expect(response.reasoning).toBe("Hm")
|
||||
expect(response.text).toBe("Hi")
|
||||
expect(response.finishReason).toEqual({ normalized: "stop", raw: "stop" })
|
||||
}),
|
||||
)
|
||||
|
||||
it.effect("accepts empty part arrays after the finish reason", () =>
|
||||
Effect.gen(function* () {
|
||||
const response = yield* generate(partChunk([{ type: "text", text: "Hi" }], "stop"), partChunk([]))
|
||||
|
||||
expect(response.text).toBe("Hi")
|
||||
}),
|
||||
)
|
||||
|
||||
it.effect("rejects part content after the finish reason", () =>
|
||||
Effect.gen(function* () {
|
||||
const error = yield* Effect.flip(
|
||||
generate(partChunk("Hi", "stop"), partChunk([{ type: "text", text: " late" }])),
|
||||
)
|
||||
|
||||
expect(error.message).toContain("OpenAI Chat received content after the finish reason")
|
||||
}),
|
||||
)
|
||||
})
|
||||
})
|
||||
@@ -7,23 +7,14 @@ import type {
|
||||
import { useLanguage } from "@/runtime/i18n/language"
|
||||
import { usePlatform } from "@/runtime/platform/platform"
|
||||
import { useServerSDK } from "@/runtime/server/client"
|
||||
import { formatServerError } from "@/runtime/server/errors"
|
||||
import { useData } from "@/runtime/server/current"
|
||||
import { createEffect, createMemo, on, onCleanup } from "solid-js"
|
||||
import { createStore, produce } from "solid-js/store"
|
||||
|
||||
export type ProviderConnectMethod = Extract<IntegrationMethod, { type: "key" | "oauth" | "external" }>
|
||||
export type ProviderConnectMethod = Extract<IntegrationMethod, { type: "key" | "oauth" }>
|
||||
|
||||
type Authorization = IntegrationOauthConnectOutput["data"]
|
||||
|
||||
type Polling = {
|
||||
generation: number
|
||||
timer?: ReturnType<typeof setTimeout>
|
||||
disposed: boolean
|
||||
// An attempt the server still considers open; cancelled when the dialog goes away.
|
||||
attempt?: Authorization
|
||||
}
|
||||
|
||||
// OpenCode Go and OpenCode Zen both bill through the OpenCode Console, so the
|
||||
// Console sign-in is the connection method for both providers.
|
||||
export const CONSOLE_INTEGRATION = "opencode"
|
||||
@@ -44,7 +35,7 @@ export function providerFormDefaults(fields: ProviderConnectMethod["form"]) {
|
||||
if (actual === undefined) return false
|
||||
|
||||
const equal = Array.isArray(actual)
|
||||
? actual.some((item) => item === condition.value)
|
||||
? typeof condition.value === "string" && actual.includes(condition.value)
|
||||
: actual === condition.value
|
||||
|
||||
return condition.op === "eq" ? equal : !equal
|
||||
@@ -52,7 +43,7 @@ export function providerFormDefaults(fields: ProviderConnectMethod["form"]) {
|
||||
|
||||
if (!active) return answer
|
||||
|
||||
return Object.assign(answer, { [field.key]: field.default })
|
||||
return { ...answer, [field.key]: field.default }
|
||||
}, {})
|
||||
}
|
||||
|
||||
@@ -83,8 +74,9 @@ export function createProviderConnectionController(options: {
|
||||
|
||||
// Not createResource: the dialog is owned by whichever page opened it, so reading a pending
|
||||
// resource here would suspend that page's <Suspense> and blank the screen behind the dialog.
|
||||
const [integration, setIntegration] = createStore<{ loading: boolean; latest?: IntegrationInfo }>({
|
||||
const [integration, setIntegration] = createStore({
|
||||
loading: true,
|
||||
latest: undefined as IntegrationInfo | undefined,
|
||||
})
|
||||
|
||||
createEffect(
|
||||
@@ -108,8 +100,7 @@ export function createProviderConnectionController(options: {
|
||||
|
||||
const methods = createMemo<ProviderConnectMethod[]>(() => {
|
||||
const values = integration.latest?.methods.filter(
|
||||
(method): method is ProviderConnectMethod =>
|
||||
method.type === "key" || method.type === "oauth" || method.type === "external",
|
||||
(method): method is ProviderConnectMethod => method.type === "key" || method.type === "oauth",
|
||||
)
|
||||
|
||||
if (values?.length) return [...values]
|
||||
@@ -117,19 +108,14 @@ export function createProviderConnectionController(options: {
|
||||
return [{ type: "key", label: language.t("provider.connect.method.apiKey") }]
|
||||
})
|
||||
|
||||
const [store, setStore] = createStore<{
|
||||
methodIndex?: number
|
||||
authorization?: Authorization
|
||||
formAnswer?: FormAnswer
|
||||
const [store, setStore] = createStore({
|
||||
methodIndex: undefined as number | undefined,
|
||||
authorization: undefined as Authorization | undefined,
|
||||
formAnswer: undefined as FormAnswer | undefined,
|
||||
// Nothing is in flight until a method is selected; `busy()` reads this, so a truthy initial
|
||||
// value would keep multi-method providers on the spinner instead of the method list.
|
||||
state?: "pending" | "waiting" | "refreshing" | "ready" | "error" | "form"
|
||||
error?: string
|
||||
auto: boolean
|
||||
connected: boolean
|
||||
browserFailed: boolean
|
||||
statusFailed: boolean
|
||||
}>({
|
||||
state: undefined as "pending" | "waiting" | "refreshing" | "ready" | "error" | "form" | undefined,
|
||||
error: undefined as string | undefined,
|
||||
auto: false,
|
||||
// The credential is stored; a retry only needs to reload the catalogs.
|
||||
connected: false,
|
||||
@@ -138,9 +124,12 @@ export function createProviderConnectionController(options: {
|
||||
statusFailed: false,
|
||||
})
|
||||
|
||||
const polling: Polling = {
|
||||
const polling = {
|
||||
generation: 0,
|
||||
timer: undefined as ReturnType<typeof setTimeout> | undefined,
|
||||
disposed: false,
|
||||
// An attempt the server still considers open; cancelled when the dialog goes away.
|
||||
attempt: undefined as Authorization | undefined,
|
||||
}
|
||||
|
||||
const currentMethod = createMemo(() =>
|
||||
@@ -217,6 +206,8 @@ export function createProviderConnectionController(options: {
|
||||
)
|
||||
}
|
||||
|
||||
const errorMessage = (error: unknown) => (error instanceof Error ? error.message : String(error))
|
||||
|
||||
const cancelAttempt = () => {
|
||||
const attempt = polling.attempt
|
||||
polling.attempt = undefined
|
||||
@@ -285,9 +276,7 @@ export function createProviderConnectionController(options: {
|
||||
setStore("statusFailed", true)
|
||||
dispatch({
|
||||
type: "auth.error",
|
||||
error: isConsole()
|
||||
? language.t("provider.connect.console.statusFailed")
|
||||
: formatServerError(result.error, language.t),
|
||||
error: isConsole() ? language.t("provider.connect.console.statusFailed") : errorMessage(result.error),
|
||||
})
|
||||
|
||||
return
|
||||
@@ -369,6 +358,8 @@ export function createProviderConnectionController(options: {
|
||||
return
|
||||
}
|
||||
|
||||
if (selected.type !== "oauth") return
|
||||
|
||||
if (selected.form?.some((field) => field.type !== "string")) {
|
||||
dispatch({ type: "auth.error", error: language.t("provider.connect.error.unsupportedFields") })
|
||||
|
||||
@@ -377,35 +368,11 @@ export function createProviderConnectionController(options: {
|
||||
|
||||
dispatch({ type: "auth.pending" })
|
||||
|
||||
if (selected.type === "external") {
|
||||
const saved = await serverSDK.api.integration.connect
|
||||
.external({
|
||||
integrationID: options.provider(),
|
||||
methodID: selected.id,
|
||||
answer: Object.keys(merged).length ? merged : undefined,
|
||||
location: location(),
|
||||
})
|
||||
.then(() => ({ ok: true as const }))
|
||||
.catch((error) => ({ ok: false as const, error }))
|
||||
|
||||
if (polling.disposed || generation !== polling.generation) return
|
||||
|
||||
if (!saved.ok) {
|
||||
dispatch({ type: "auth.error", error: formatServerError(saved.error, language.t) })
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
await finish()
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
const result = await serverSDK.api.integration.oauth
|
||||
.connect({
|
||||
integrationID: options.provider(),
|
||||
methodID: selected.id,
|
||||
answer: Object.keys(merged).length ? merged : undefined,
|
||||
...(Object.keys(merged).length ? { answer: merged } : {}),
|
||||
location: location(),
|
||||
})
|
||||
.then((response) => {
|
||||
@@ -437,9 +404,7 @@ export function createProviderConnectionController(options: {
|
||||
if (!result.ok) {
|
||||
dispatch({
|
||||
type: "auth.error",
|
||||
error: isConsole()
|
||||
? language.t("provider.connect.console.startFailed")
|
||||
: formatServerError(result.error, language.t),
|
||||
error: isConsole() ? language.t("provider.connect.console.startFailed") : errorMessage(result.error),
|
||||
})
|
||||
|
||||
return
|
||||
@@ -483,7 +448,7 @@ export function createProviderConnectionController(options: {
|
||||
integrationID: options.keyProvider?.() ?? options.provider(),
|
||||
location: location(),
|
||||
key,
|
||||
answer: store.formAnswer,
|
||||
...(store.formAnswer ? { answer: store.formAnswer } : {}),
|
||||
})
|
||||
await finish()
|
||||
}
|
||||
@@ -503,8 +468,7 @@ export function createProviderConnectionController(options: {
|
||||
.then(() => ({ ok: true as const }))
|
||||
.catch((error) => ({ ok: false as const, error }))
|
||||
|
||||
if (!result.ok)
|
||||
return formatServerError(result.error, language.t, language.t("provider.connect.oauth.code.invalid"))
|
||||
if (!result.ok) return errorMessage(result.error) || language.t("provider.connect.oauth.code.invalid")
|
||||
await finish()
|
||||
|
||||
return undefined
|
||||
@@ -532,13 +496,11 @@ export function createProviderConnectionController(options: {
|
||||
authorization: () => store.authorization,
|
||||
browserFailed: () => store.browserFailed,
|
||||
// True while nothing useful can be shown yet: the integration is loading, a method is
|
||||
// about to be picked automatically, the authorization request is in flight, or an external
|
||||
// method, which has no view of its own, is refreshing the catalogs after saving.
|
||||
// about to be picked automatically, or the authorization request is in flight.
|
||||
busy: () =>
|
||||
integration.loading ||
|
||||
(store.methodIndex === undefined && !store.auto && autoIndex() !== undefined) ||
|
||||
store.state === "pending" ||
|
||||
(store.state === "refreshing" && currentMethod()?.type === "external"),
|
||||
store.state === "pending",
|
||||
auth: {
|
||||
state: () => store.state,
|
||||
error: () => store.error,
|
||||
|
||||
@@ -127,29 +127,9 @@ const authenticate = Effect.fn("cli.auth.login.authenticate")(function* (
|
||||
) {
|
||||
if (method.type === "key") return yield* keyLogin(client, integration, method, answer)
|
||||
if (method.type === "command") return yield* commandLogin(client, integration, method)
|
||||
if (method.type === "external") return yield* externalLogin(client, integration, method, answer)
|
||||
return yield* oauthLogin(client, integration, method, answer)
|
||||
})
|
||||
|
||||
const externalLogin = Effect.fn("cli.auth.login.external")(function* (
|
||||
client: OpenCodeClient,
|
||||
integration: IntegrationInfo,
|
||||
method: Extract<ConnectMethod, { type: "external" }>,
|
||||
answer?: FormAnswer,
|
||||
) {
|
||||
const progress = spinner()
|
||||
progress.start("Saving credential...")
|
||||
yield* request((signal) =>
|
||||
client.integration.connect.external(
|
||||
{ integrationID: integration.id, methodID: method.id, answer, location },
|
||||
{ signal },
|
||||
),
|
||||
).pipe(
|
||||
Effect.tap(() => Effect.sync(() => progress.stop(`Connected to ${integration.name}`))),
|
||||
Effect.tapCause(() => Effect.sync(() => progress.stop("Authentication failed", 1))),
|
||||
)
|
||||
})
|
||||
|
||||
const keyLogin = Effect.fn("cli.auth.login.key")(function* (
|
||||
client: OpenCodeClient,
|
||||
integration: IntegrationInfo,
|
||||
|
||||
@@ -1597,18 +1597,6 @@ export type IntegrationConnectKeyOperation<E = never> = (
|
||||
input: IntegrationConnectKeyInput,
|
||||
) => Effect.Effect<IntegrationConnectKeyOutput, E>
|
||||
|
||||
export type IntegrationConnectExternalInput = {
|
||||
readonly integrationID: Integration.ID
|
||||
readonly location?: { readonly directory?: string | undefined } | undefined
|
||||
readonly methodID: Integration.MethodID
|
||||
readonly answer?: Form.Answer | undefined
|
||||
readonly label?: string | undefined
|
||||
}
|
||||
export type IntegrationConnectExternalOutput = void
|
||||
export type IntegrationConnectExternalOperation<E = never> = (
|
||||
input: IntegrationConnectExternalInput,
|
||||
) => Effect.Effect<IntegrationConnectExternalOutput, E>
|
||||
|
||||
export type IntegrationOauthConnectInput = {
|
||||
readonly integrationID: Integration.ID
|
||||
readonly location?: { readonly directory?: string | undefined } | undefined
|
||||
@@ -1699,10 +1687,7 @@ export interface IntegrationApi<E = never> {
|
||||
readonly list: IntegrationListOperation<E>
|
||||
readonly get: IntegrationGetOperation<E>
|
||||
readonly wellknown: { readonly add: IntegrationWellknownAddOperation<E> }
|
||||
readonly connect: {
|
||||
readonly key: IntegrationConnectKeyOperation<E>
|
||||
readonly external: IntegrationConnectExternalOperation<E>
|
||||
}
|
||||
readonly connect: { readonly key: IntegrationConnectKeyOperation<E> }
|
||||
readonly oauth: {
|
||||
readonly connect: IntegrationOauthConnectOperation<E>
|
||||
readonly status: IntegrationOauthStatusOperation<E>
|
||||
|
||||
@@ -127,8 +127,6 @@ import type {
|
||||
IntegrationWellknownAddOutput,
|
||||
IntegrationConnectKeyInput,
|
||||
IntegrationConnectKeyOutput,
|
||||
IntegrationConnectExternalInput,
|
||||
IntegrationConnectExternalOutput,
|
||||
IntegrationOauthConnectInput,
|
||||
IntegrationOauthConnectOutput,
|
||||
IntegrationOauthStatusInput,
|
||||
@@ -899,16 +897,6 @@ const EndpointIntegrationConnectKey = (raw: RawClient["server.integration"]) =>
|
||||
}).pipe(Effect.mapError(mapClientError)),
|
||||
)
|
||||
|
||||
const EndpointIntegrationConnectExternal =
|
||||
(raw: RawClient["server.integration"]) => (input: IntegrationConnectExternalInput) =>
|
||||
preserveEffect<IntegrationConnectExternalOutput>()(
|
||||
raw["integration.connect.external"]({
|
||||
params: { integrationID: input["integrationID"] },
|
||||
query: { location: input["location"] },
|
||||
payload: { methodID: input["methodID"], answer: input["answer"], label: input["label"] },
|
||||
}).pipe(Effect.mapError(mapClientError)),
|
||||
)
|
||||
|
||||
const EndpointIntegrationOauthConnect =
|
||||
(raw: RawClient["server.integration"]) => (input: IntegrationOauthConnectInput) =>
|
||||
preserveEffect<IntegrationOauthConnectOutput>()(
|
||||
@@ -977,7 +965,7 @@ const adaptGroupIntegration = (raw: RawClient["server.integration"]) => ({
|
||||
list: EndpointIntegrationList(raw),
|
||||
get: EndpointIntegrationGet(raw),
|
||||
wellknown: { add: EndpointIntegrationWellknownAdd(raw) },
|
||||
connect: { key: EndpointIntegrationConnectKey(raw), external: EndpointIntegrationConnectExternal(raw) },
|
||||
connect: { key: EndpointIntegrationConnectKey(raw) },
|
||||
oauth: {
|
||||
connect: EndpointIntegrationOauthConnect(raw),
|
||||
status: EndpointIntegrationOauthStatus(raw),
|
||||
|
||||
@@ -121,8 +121,6 @@ import type {
|
||||
IntegrationWellknownAddOutput,
|
||||
IntegrationConnectKeyInput,
|
||||
IntegrationConnectKeyOutput,
|
||||
IntegrationConnectExternalInput,
|
||||
IntegrationConnectExternalOutput,
|
||||
IntegrationOauthConnectInput,
|
||||
IntegrationOauthConnectOutput,
|
||||
IntegrationOauthStatusInput,
|
||||
@@ -1230,19 +1228,6 @@ export function make(options: ClientOptions) {
|
||||
},
|
||||
requestOptions,
|
||||
),
|
||||
external: (input: IntegrationConnectExternalInput, requestOptions?: RequestOptions) =>
|
||||
request<IntegrationConnectExternalOutput>(
|
||||
{
|
||||
method: "POST",
|
||||
path: `/api/integration/${encodeURIComponent(input.integrationID)}/connect/external`,
|
||||
query: { location: input["location"] },
|
||||
body: { methodID: input["methodID"], answer: input["answer"], label: input["label"] },
|
||||
successStatus: 204,
|
||||
declaredStatuses: [400, 401, 404],
|
||||
empty: true,
|
||||
},
|
||||
requestOptions,
|
||||
),
|
||||
},
|
||||
oauth: {
|
||||
connect: (input: IntegrationOauthConnectInput, requestOptions?: RequestOptions) =>
|
||||
|
||||
@@ -2314,8 +2314,6 @@ export type IntegrationOAuthMethod = { id: string; type: "oauth"; label: string;
|
||||
|
||||
export type IntegrationKeyMethod = { type: "key"; label?: string; form?: FormFields }
|
||||
|
||||
export type IntegrationExternalMethod = { id: string; type: "external"; label: string; form?: FormFields }
|
||||
|
||||
export type CredentialEntry = {
|
||||
id: string
|
||||
integrationID: string
|
||||
@@ -2353,7 +2351,6 @@ export type IntegrationMethod =
|
||||
| IntegrationOAuthMethod
|
||||
| IntegrationCommandMethod
|
||||
| IntegrationKeyMethod
|
||||
| IntegrationExternalMethod
|
||||
| IntegrationEnvMethod
|
||||
|
||||
export type FormCreated = {
|
||||
@@ -5691,28 +5688,6 @@ export type IntegrationConnectKeyInput = {
|
||||
|
||||
export type IntegrationConnectKeyOutput = void
|
||||
|
||||
export type IntegrationConnectExternalInput = {
|
||||
readonly integrationID: { readonly integrationID: string }["integrationID"]
|
||||
readonly location?: { readonly location?: { readonly directory?: string | undefined } | undefined }["location"]
|
||||
readonly methodID: {
|
||||
readonly methodID: string
|
||||
readonly answer?: { readonly [x: string]: string | number | boolean | ReadonlyArray<string> } | undefined
|
||||
readonly label?: string | undefined
|
||||
}["methodID"]
|
||||
readonly answer?: {
|
||||
readonly methodID: string
|
||||
readonly answer?: { readonly [x: string]: string | number | boolean | ReadonlyArray<string> } | undefined
|
||||
readonly label?: string | undefined
|
||||
}["answer"]
|
||||
readonly label?: {
|
||||
readonly methodID: string
|
||||
readonly answer?: { readonly [x: string]: string | number | boolean | ReadonlyArray<string> } | undefined
|
||||
readonly label?: string | undefined
|
||||
}["label"]
|
||||
}
|
||||
|
||||
export type IntegrationConnectExternalOutput = void
|
||||
|
||||
export type IntegrationOauthConnectInput = {
|
||||
readonly integrationID: { readonly integrationID: string }["integrationID"]
|
||||
readonly location?: { readonly location?: { readonly directory?: string | undefined } | undefined }["location"]
|
||||
|
||||
@@ -45,9 +45,6 @@ export type CommandMethod = Integration.CommandMethod
|
||||
export const KeyMethod = Integration.KeyMethod
|
||||
export type KeyMethod = Integration.KeyMethod
|
||||
|
||||
export const ExternalMethod = Integration.ExternalMethod
|
||||
export type ExternalMethod = Integration.ExternalMethod
|
||||
|
||||
export const EnvMethod = Integration.EnvMethod
|
||||
export type EnvMethod = Integration.EnvMethod
|
||||
|
||||
@@ -85,11 +82,6 @@ export interface KeyImplementation {
|
||||
readonly method: KeyMethod
|
||||
}
|
||||
|
||||
export interface ExternalImplementation {
|
||||
readonly integrationID: ID
|
||||
readonly method: ExternalMethod
|
||||
}
|
||||
|
||||
export interface CommandImplementation {
|
||||
readonly integrationID: ID
|
||||
readonly method: CommandMethod
|
||||
@@ -100,12 +92,7 @@ export interface EnvImplementation {
|
||||
readonly method: EnvMethod
|
||||
}
|
||||
|
||||
export type Implementation =
|
||||
| OAuthImplementation
|
||||
| CommandImplementation
|
||||
| KeyImplementation
|
||||
| ExternalImplementation
|
||||
| EnvImplementation
|
||||
export type Implementation = OAuthImplementation | CommandImplementation | KeyImplementation | EnvImplementation
|
||||
|
||||
export const Attempt = Integration.Attempt
|
||||
export type Attempt = Integration.Attempt
|
||||
@@ -193,17 +180,6 @@ export interface Interface extends State.Transformable<Editor> {
|
||||
/** User-facing label for the stored credential. */
|
||||
readonly label?: string
|
||||
}) => Effect.Effect<void, AuthorizationError>
|
||||
/** Runs an external method and stores a reference configured by its form answers. */
|
||||
readonly external: (input: {
|
||||
/** Integration receiving the credential. */
|
||||
readonly integrationID: ID
|
||||
/** External method that defines the form and credential source. */
|
||||
readonly methodID: MethodID
|
||||
/** Values collected from the method's form fields. */
|
||||
readonly answer?: Form.Answer
|
||||
/** User-facing label for the stored credential. */
|
||||
readonly label?: string
|
||||
}) => Effect.Effect<void, AuthorizationError>
|
||||
/** Selects a stored credential as the active integration connection. */
|
||||
readonly activate: (credentialID: Credential.ID) => Effect.Effect<void>
|
||||
/** Updates a stored credential exposed as a connection. */
|
||||
@@ -351,8 +327,6 @@ const layer = Layer.effect(
|
||||
return method.id === implementation.method.id
|
||||
if (method.type === "command" && implementation.method.type === "command")
|
||||
return method.id === implementation.method.id
|
||||
if (method.type === "external" && implementation.method.type === "external")
|
||||
return method.id === implementation.method.id
|
||||
return true
|
||||
})
|
||||
if (index === -1) current.methods.push(implementation.method as Types.DeepMutable<Method>)
|
||||
@@ -371,7 +345,6 @@ const layer = Layer.effect(
|
||||
if (candidate.type !== method.type) return false
|
||||
if (candidate.type === "oauth" && method.type === "oauth") return candidate.id === method.id
|
||||
if (candidate.type === "command" && method.type === "command") return candidate.id === method.id
|
||||
if (candidate.type === "external" && method.type === "external") return candidate.id === method.id
|
||||
return true
|
||||
})
|
||||
if (index !== -1) current.methods.splice(index, 1)
|
||||
@@ -763,31 +736,6 @@ const layer = Layer.effect(
|
||||
}),
|
||||
})
|
||||
}),
|
||||
external: Effect.fn("Integration.connection.external")(function* (input) {
|
||||
const method = state
|
||||
.get()
|
||||
.integrations.get(input.integrationID)
|
||||
?.methods.find((method) => method.type === "external" && method.id === input.methodID)
|
||||
if (method?.type !== "external")
|
||||
return yield* new AuthorizationError({ cause: new Error(`External method not found: ${input.methodID}`) })
|
||||
const answer = input.answer ?? {}
|
||||
if (method.form) {
|
||||
const invalid = Form.validateFields(method.form) ?? Form.validateAnswer(method.form, answer)
|
||||
if (invalid) return yield* new AuthorizationError({ cause: new Error(invalid) })
|
||||
}
|
||||
if (!method.form && Object.keys(answer).length > 0) {
|
||||
return yield* new AuthorizationError({ cause: new Error("External method does not accept a form answer") })
|
||||
}
|
||||
yield* createCredential({
|
||||
integrationID: input.integrationID,
|
||||
label: input.label,
|
||||
value: Credential.External.make({
|
||||
type: "external",
|
||||
methodID: method.id,
|
||||
...(Object.keys(answer).length > 0 ? { metadata: answer } : {}),
|
||||
}),
|
||||
})
|
||||
}),
|
||||
activate: Effect.fn("Integration.connection.activate")((credentialID) => credentials.activate(credentialID)),
|
||||
update: Effect.fn("Integration.connection.update")((credentialID, updates) =>
|
||||
credentials.update(credentialID, updates),
|
||||
|
||||
@@ -286,13 +286,6 @@ export const make = Effect.fn("PluginHost.make")(function* (
|
||||
answer: input.answer,
|
||||
label: input.label,
|
||||
}),
|
||||
external: (input) =>
|
||||
integration.connection.external({
|
||||
integrationID: Integration.ID.make(input.integrationID),
|
||||
methodID: Integration.MethodID.make(input.methodID),
|
||||
answer: input.answer,
|
||||
label: input.label,
|
||||
}),
|
||||
},
|
||||
oauth: {
|
||||
connect: (input) =>
|
||||
@@ -672,12 +665,6 @@ function methodImplementation(input: IntegrationMethodRegistration): Integration
|
||||
method: { ...input.method, id: Integration.MethodID.make(input.method.id) },
|
||||
}
|
||||
}
|
||||
if (input.method.type === "external") {
|
||||
return {
|
||||
integrationID: Integration.ID.make(input.integrationID),
|
||||
method: { ...input.method, id: Integration.MethodID.make(input.method.id) },
|
||||
}
|
||||
}
|
||||
return {
|
||||
integrationID: Integration.ID.make(input.integrationID),
|
||||
method: input.method,
|
||||
|
||||
@@ -32,7 +32,6 @@ const integrations = Layer.mock(Integration.Service, {
|
||||
active: () => Effect.undefined,
|
||||
resolve: () => Effect.die("unused"),
|
||||
key: () => Effect.die("unused"),
|
||||
external: () => Effect.die("unused"),
|
||||
activate: () => Effect.die("unused"),
|
||||
update: () => Effect.die("unused"),
|
||||
remove: () => Effect.die("unused"),
|
||||
|
||||
@@ -330,7 +330,6 @@ function resourceMcpLayer(
|
||||
active: unusedIntegration,
|
||||
resolve: unusedIntegration,
|
||||
key: unusedIntegration,
|
||||
external: unusedIntegration,
|
||||
activate: unusedIntegration,
|
||||
update: unusedIntegration,
|
||||
remove: unusedIntegration,
|
||||
|
||||
@@ -372,7 +372,6 @@ describe("ModelResolver", () => {
|
||||
},
|
||||
resolve: () => Effect.die("unused"),
|
||||
key: () => Effect.die("unused"),
|
||||
external: () => Effect.die("unused"),
|
||||
activate: () => Effect.die("unused"),
|
||||
update: () => Effect.die("unused"),
|
||||
remove: () => Effect.die("unused"),
|
||||
|
||||
@@ -78,7 +78,6 @@ export function host(overrides: Overrides = {}): Plugin.Context {
|
||||
get: () => Effect.die("unused integration.get"),
|
||||
connect: {
|
||||
key: () => Effect.die("unused integration.connect.key"),
|
||||
external: () => Effect.die("unused integration.connect.external"),
|
||||
},
|
||||
oauth: {
|
||||
connect: () => Effect.die("unused integration.oauth.connect"),
|
||||
@@ -298,7 +297,6 @@ export function integrationHost(integration: Integration.Interface): Plugin.Cont
|
||||
get: () => Effect.die("unused integration.get"),
|
||||
connect: {
|
||||
key: () => Effect.die("unused integration.connect.key"),
|
||||
external: () => Effect.die("unused integration.connect.external"),
|
||||
},
|
||||
oauth: {
|
||||
connect: () => Effect.die("unused integration.oauth.connect"),
|
||||
@@ -411,16 +409,6 @@ export function integrationHost(integration: Integration.Interface): Plugin.Cont
|
||||
})
|
||||
return
|
||||
}
|
||||
if (input.method.type === "external") {
|
||||
editor.method.update({
|
||||
integrationID: Integration.ID.make(input.integrationID),
|
||||
method: {
|
||||
...input.method,
|
||||
id: Integration.MethodID.make(input.method.id),
|
||||
},
|
||||
})
|
||||
return
|
||||
}
|
||||
editor.method.update({
|
||||
integrationID: Integration.ID.make(input.integrationID),
|
||||
method: input.method,
|
||||
@@ -471,7 +459,7 @@ export function webSearchHost(websearch: WebSearch.Interface): Plugin.Context["w
|
||||
}
|
||||
|
||||
function internalMethod(value: IntegrationMethod): Integration.Method {
|
||||
if (value.type === "oauth" || value.type === "command" || value.type === "external") {
|
||||
if (value.type === "oauth" || value.type === "command") {
|
||||
return { ...value, id: Integration.MethodID.make(value.id) }
|
||||
}
|
||||
return value
|
||||
|
||||
@@ -444,7 +444,7 @@ function ArtifactMarkdown(props: { session: MountedSession; path: string; text:
|
||||
openLocalFile={(href) => void links.open({ href, base: dir(), session: props.session })}
|
||||
>
|
||||
<div class="mx-auto w-full max-w-3xl px-8 py-6">
|
||||
<Markdown text={props.text} cacheKey={props.cacheKey} class="select-text" />
|
||||
<Markdown text={props.text} cacheKey={props.cacheKey} />
|
||||
</div>
|
||||
</MarkdownProvider>
|
||||
)
|
||||
@@ -454,7 +454,7 @@ function ArtifactMarkdown(props: { session: MountedSession; path: string; text:
|
||||
function ArtifactMermaid(props: { text: string; cacheKey?: string }) {
|
||||
return (
|
||||
<div class="mx-auto w-full max-w-4xl px-8 py-6">
|
||||
<Markdown text={`\`\`\`mermaid\n${props.text}\n\`\`\``} cacheKey={props.cacheKey} class="select-text" />
|
||||
<Markdown text={`\`\`\`mermaid\n${props.text}\n\`\`\``} cacheKey={props.cacheKey} />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -28,13 +28,6 @@ export interface IntegrationKeyMethod {
|
||||
readonly form?: Form.Fields
|
||||
}
|
||||
|
||||
export interface IntegrationExternalMethod {
|
||||
readonly id: string
|
||||
readonly type: "external"
|
||||
readonly label: string
|
||||
readonly form?: Form.Fields
|
||||
}
|
||||
|
||||
export interface IntegrationEnvMethod {
|
||||
readonly type: "env"
|
||||
readonly names: ReadonlyArray<string>
|
||||
@@ -44,7 +37,6 @@ export type IntegrationMethod =
|
||||
| IntegrationOAuthMethod
|
||||
| IntegrationCommandMethod
|
||||
| IntegrationKeyMethod
|
||||
| IntegrationExternalMethod
|
||||
| IntegrationEnvMethod
|
||||
|
||||
export type IntegrationOAuthAuthorization = {
|
||||
@@ -78,10 +70,6 @@ export type IntegrationMethodRegistration =
|
||||
readonly integrationID: string
|
||||
readonly method: IntegrationKeyMethod
|
||||
}
|
||||
| {
|
||||
readonly integrationID: string
|
||||
readonly method: IntegrationExternalMethod
|
||||
}
|
||||
| {
|
||||
readonly integrationID: string
|
||||
readonly method: IntegrationEnvMethod
|
||||
|
||||
@@ -356,10 +356,6 @@ export function fromPromise(plugin: Plugin) {
|
||||
get: adaptApiMethod(IntegrationEndpoints["integration.get"], host.integration.get),
|
||||
connect: {
|
||||
key: adaptApiMethod(IntegrationEndpoints["integration.connect.key"], host.integration.connect.key),
|
||||
external: adaptApiMethod(
|
||||
IntegrationEndpoints["integration.connect.external"],
|
||||
host.integration.connect.external,
|
||||
),
|
||||
},
|
||||
oauth: {
|
||||
connect: adaptApiMethod(
|
||||
|
||||
@@ -27,13 +27,6 @@ export interface IntegrationKeyMethod {
|
||||
readonly form?: Form.Fields
|
||||
}
|
||||
|
||||
export interface IntegrationExternalMethod {
|
||||
readonly id: string
|
||||
readonly type: "external"
|
||||
readonly label: string
|
||||
readonly form?: Form.Fields
|
||||
}
|
||||
|
||||
export interface IntegrationEnvMethod {
|
||||
readonly type: "env"
|
||||
readonly names: ReadonlyArray<string>
|
||||
@@ -43,7 +36,6 @@ export type IntegrationMethod =
|
||||
| IntegrationOAuthMethod
|
||||
| IntegrationCommandMethod
|
||||
| IntegrationKeyMethod
|
||||
| IntegrationExternalMethod
|
||||
| IntegrationEnvMethod
|
||||
|
||||
export type IntegrationOAuthAuthorization = {
|
||||
@@ -76,7 +68,6 @@ export type IntegrationMethodRegistration =
|
||||
readonly integrationID: string
|
||||
readonly method: IntegrationKeyMethod
|
||||
}
|
||||
| { readonly integrationID: string; readonly method: IntegrationExternalMethod }
|
||||
| { readonly integrationID: string; readonly method: IntegrationEnvMethod }
|
||||
|
||||
export interface IntegrationEditor {
|
||||
|
||||
@@ -79,27 +79,6 @@ export const IntegrationGroup = HttpApiGroup.make("server.integration")
|
||||
}),
|
||||
),
|
||||
)
|
||||
.add(
|
||||
HttpApiEndpoint.post("integration.connect.external", "/api/integration/:integrationID/connect/external", {
|
||||
params: { integrationID: Integration.ID },
|
||||
query: LocationQuery,
|
||||
payload: Schema.Struct({
|
||||
methodID: Integration.MethodID,
|
||||
answer: Schema.optional(Form.Answer),
|
||||
label: Schema.optional(Schema.String),
|
||||
}),
|
||||
success: HttpApiSchema.NoContent,
|
||||
error: [IntegrationNotFoundError, InvalidRequestError],
|
||||
})
|
||||
.annotateMerge(locationQueryOpenApi)
|
||||
.annotateMerge(
|
||||
OpenApi.annotations({
|
||||
identifier: "integration.connect.external",
|
||||
summary: "Connect with external credentials",
|
||||
description: "Run an external authentication method and store a reference to its credential source.",
|
||||
}),
|
||||
),
|
||||
)
|
||||
.add(
|
||||
HttpApiEndpoint.post("integration.oauth.connect", "/api/integration/:integrationID/connect/oauth", {
|
||||
params: { integrationID: Integration.ID },
|
||||
|
||||
@@ -38,22 +38,13 @@ export const KeyMethod = Schema.Struct({
|
||||
form: optional(Form.Fields),
|
||||
}).annotate({ identifier: "Integration.KeyMethod" })
|
||||
|
||||
/** Saves a reference to credentials managed outside opencode, configured by the form answers. */
|
||||
export interface ExternalMethod extends Schema.Schema.Type<typeof ExternalMethod> {}
|
||||
export const ExternalMethod = Schema.Struct({
|
||||
id: MethodID,
|
||||
type: Schema.Literal("external"),
|
||||
label: Schema.String,
|
||||
form: optional(Form.Fields),
|
||||
}).annotate({ identifier: "Integration.ExternalMethod" })
|
||||
|
||||
export interface EnvMethod extends Schema.Schema.Type<typeof EnvMethod> {}
|
||||
export const EnvMethod = Schema.Struct({
|
||||
type: Schema.Literal("env"),
|
||||
names: Schema.Array(Schema.String),
|
||||
}).annotate({ identifier: "Integration.EnvMethod" })
|
||||
|
||||
export const Method = Schema.Union([OAuthMethod, CommandMethod, KeyMethod, ExternalMethod, EnvMethod])
|
||||
export const Method = Schema.Union([OAuthMethod, CommandMethod, KeyMethod, EnvMethod])
|
||||
.pipe(Schema.toTaggedUnion("type"))
|
||||
.annotate({ identifier: "Integration.Method" })
|
||||
export type Method = typeof Method.Type
|
||||
|
||||
@@ -84,26 +84,6 @@ export const IntegrationHandler = HttpApiBuilder.group(Api, "server.integration"
|
||||
return HttpApiSchema.NoContent.make()
|
||||
}),
|
||||
)
|
||||
.handle(
|
||||
"integration.connect.external",
|
||||
Effect.fn(function* (ctx) {
|
||||
const service = yield* Integration.Service
|
||||
if (!(yield* service.get(ctx.params.integrationID)))
|
||||
return yield* new IntegrationNotFoundError({
|
||||
integrationID: ctx.params.integrationID,
|
||||
message: `Integration not found: ${ctx.params.integrationID}`,
|
||||
})
|
||||
yield* authorize(
|
||||
service.connection.external({
|
||||
integrationID: ctx.params.integrationID,
|
||||
methodID: ctx.payload.methodID,
|
||||
answer: ctx.payload.answer,
|
||||
label: ctx.payload.label,
|
||||
}),
|
||||
)
|
||||
return HttpApiSchema.NoContent.make()
|
||||
}),
|
||||
)
|
||||
.handle(
|
||||
"integration.oauth.connect",
|
||||
Effect.fn(function* (ctx) {
|
||||
|
||||
@@ -36,6 +36,17 @@ story("renders small completed Markdown immediately without skipping sanitizatio
|
||||
await expect(harness.locator("pre.shiki")).toBeVisible()
|
||||
})
|
||||
|
||||
story("keeps Markdown text selectable inside a container that disables selection", async ({ page }) => {
|
||||
await page.evaluate(async (fixture) => {
|
||||
document.body.style.userSelect = "none"
|
||||
const { mountMarkdown } = await import(fixture)
|
||||
await mountMarkdown({ text: "Selectable answer text" })
|
||||
}, fixture)
|
||||
|
||||
await page.getByTestId("markdown-fixture").getByText("Selectable answer text").click({ clickCount: 3 })
|
||||
expect(await page.evaluate(() => getSelection()?.toString().trim())).toBe("Selectable answer text")
|
||||
})
|
||||
|
||||
story("sanitizes raw HTML while preserving supported Markdown markup", async ({ page }) => {
|
||||
const result = await page.evaluate(async (fixture) => {
|
||||
const { sanitizeMarkdown } = await import(fixture)
|
||||
|
||||
@@ -15,6 +15,9 @@
|
||||
font-family: var(--font-family-sans);
|
||||
font-size: var(--font-size-base); /* 14px */
|
||||
line-height: 160%;
|
||||
/* Shells such as the app's turn off selection for chrome; Markdown is content, so it stays selectable. */
|
||||
-webkit-user-select: text;
|
||||
user-select: text;
|
||||
|
||||
[data-markdown-word] {
|
||||
display: inline;
|
||||
|
||||
@@ -309,62 +309,9 @@ function openMethod(
|
||||
))
|
||||
return
|
||||
}
|
||||
if (method.type === "external") {
|
||||
void beginExternal(integration, method, location, dialog, onConnected)
|
||||
return
|
||||
}
|
||||
void beginOAuth(integration, method, location, dialog, onConnected)
|
||||
}
|
||||
|
||||
async function beginExternal(
|
||||
integration: IntegrationInfo,
|
||||
method: Extract<ConnectMethod, { type: "external" }>,
|
||||
location: LocationRef,
|
||||
dialog: ReturnType<typeof useDialog>,
|
||||
onConnected?: OnIntegrationConnected,
|
||||
) {
|
||||
const answer = method.form ? await formAnswer(dialog, method.label, method.form) : undefined
|
||||
if (answer === null) return
|
||||
dialog.replace(() => (
|
||||
<ExternalStarting
|
||||
integration={integration}
|
||||
method={method}
|
||||
location={location}
|
||||
answer={answer}
|
||||
onConnected={onConnected}
|
||||
/>
|
||||
))
|
||||
}
|
||||
|
||||
function ExternalStarting(props: {
|
||||
integration: IntegrationInfo
|
||||
method: Extract<ConnectMethod, { type: "external" }>
|
||||
location: LocationRef
|
||||
answer?: FormAnswer
|
||||
onConnected?: OnIntegrationConnected
|
||||
}) {
|
||||
const data = useData()
|
||||
const dialog = useDialog()
|
||||
const client = useClient()
|
||||
const toast = useToast()
|
||||
|
||||
onMount(() => {
|
||||
void client.api.integration.connect
|
||||
.external({
|
||||
integrationID: props.integration.id,
|
||||
location: locationQuery(props.location),
|
||||
methodID: props.method.id,
|
||||
...(props.answer ? { answer: props.answer } : {}),
|
||||
})
|
||||
.then(() => connected(props.integration, props.location, data, dialog, toast, props.onConnected))
|
||||
.catch((cause) => {
|
||||
toast.show({ variant: "error", message: errorMessage(cause) })
|
||||
dialog.clear()
|
||||
})
|
||||
})
|
||||
return <OAuthView title={props.method.label} message="Connecting…" />
|
||||
}
|
||||
|
||||
async function beginKey(
|
||||
integration: IntegrationInfo,
|
||||
method: Extract<ConnectMethod, { type: "key" }>,
|
||||
|
||||
Reference in new issue
Block a user