mirror of
https://github.com/anomalyco/opencode.git
synced 2026-08-08 01:59:46 -04:00
Compare commits
8 Commits
v2
..
auth-forms
| Author | SHA1 | Date | |
|---|---|---|---|
| 42606a4d87 | |||
| c0852c27b2 | |||
| c97058580c | |||
| 6f1dc83c69 | |||
| 3bf13ef366 | |||
| 0ed9ed5ec8 | |||
| 4e6f8af46b | |||
| 3350dd6ade |
@@ -371,13 +371,12 @@ const lowerAssistantMessage = Effect.fn("OpenAIChat.lowerAssistantMessage")(func
|
|||||||
return text
|
return text
|
||||||
})()
|
})()
|
||||||
const cached = message.content.findLast((part) => "cache" in part && part.cache !== undefined)
|
const cached = message.content.findLast((part) => "cache" in part && part.cache !== undefined)
|
||||||
const cacheControl = options.cacheControl?.(cached && "cache" in cached ? cached.cache : undefined)
|
|
||||||
const result = {
|
const result = {
|
||||||
role: "assistant" as const,
|
role: "assistant" as const,
|
||||||
content: content.length > 0 ? content.map((part) => part.text).join("") : toolCalls.length > 0 ? null : "",
|
content: content.length === 0 ? null : ProviderShared.joinText(content),
|
||||||
...(toolCalls.length > 0 ? { tool_calls: toolCalls } : {}),
|
tool_calls: toolCalls.length === 0 ? undefined : toolCalls,
|
||||||
...(details !== undefined ? { reasoning_details: details } : {}),
|
reasoning_details: details,
|
||||||
...(cacheControl !== undefined ? { cache_control: cacheControl } : {}),
|
cache_control: options.cacheControl?.(cached && "cache" in cached ? cached.cache : undefined),
|
||||||
}
|
}
|
||||||
if (field === undefined || reasoningText === undefined) return result
|
if (field === undefined || reasoningText === undefined) return result
|
||||||
return { ...result, [field]: reasoningText }
|
return { ...result, [field]: reasoningText }
|
||||||
@@ -717,13 +716,14 @@ const step = (state: ParserState, event: OpenAIChatEvent) =>
|
|||||||
return [{ ...state, usage }, events] as const
|
return [{ ...state, usage }, events] as const
|
||||||
}
|
}
|
||||||
|
|
||||||
const reasoningField = state.reasoningField ?? reasoning?.field
|
const reasoningField = state.reasoningField ?? (!state.lifecycle.text.has("text-0") ? reasoning?.field : undefined)
|
||||||
const detailDelta = Array.isArray(delta?.reasoning_details) ? delta.reasoning_details : undefined
|
const detailDelta = Array.isArray(delta?.reasoning_details) ? delta.reasoning_details : undefined
|
||||||
if (detailDelta !== undefined) appendReasoningDetails(state.reasoningDetails, detailDelta)
|
if (detailDelta !== undefined) appendReasoningDetails(state.reasoningDetails, detailDelta)
|
||||||
const reasoningDetailsObserved = state.reasoningDetailsObserved || detailDelta !== undefined
|
const reasoningDetailsObserved = state.reasoningDetailsObserved || detailDelta !== undefined
|
||||||
const deltaMetadata = reasoningMetadata(reasoningField)
|
const deltaMetadata = reasoningMetadata(reasoningField)
|
||||||
const text = detailDelta?.length ? (detailText(detailDelta) ?? reasoning?.text) : reasoning?.text
|
const text = detailDelta?.length ? (detailText(detailDelta) ?? reasoning?.text) : reasoning?.text
|
||||||
if (text !== undefined) lifecycle = Lifecycle.reasoningDelta(lifecycle, events, "reasoning-0", text, deltaMetadata)
|
if (!state.lifecycle.text.has("text-0") && text !== undefined)
|
||||||
|
lifecycle = Lifecycle.reasoningDelta(lifecycle, events, "reasoning-0", text, deltaMetadata)
|
||||||
else if (
|
else if (
|
||||||
reasoningDetailsObserved &&
|
reasoningDetailsObserved &&
|
||||||
!lifecycle.reasoning.has("reasoning-0") &&
|
!lifecycle.reasoning.has("reasoning-0") &&
|
||||||
@@ -812,18 +812,14 @@ const step = (state: ParserState, event: OpenAIChatEvent) =>
|
|||||||
|
|
||||||
const finishEvents = (state: ParserState): ReadonlyArray<LLMEvent> => {
|
const finishEvents = (state: ParserState): ReadonlyArray<LLMEvent> => {
|
||||||
const events: LLMEvent[] = []
|
const events: LLMEvent[] = []
|
||||||
const toolCallEvents =
|
const hasToolCalls = state.toolCallEvents.length > 0
|
||||||
state.finishReason === undefined && Object.keys(state.tools).length > 0
|
|
||||||
? Effect.runSync(ToolStream.finishAll(ADAPTER, state.tools)).events
|
|
||||||
: state.toolCallEvents
|
|
||||||
const hasToolCalls = toolCallEvents.length > 0
|
|
||||||
const reason = state.finishReason
|
const reason = state.finishReason
|
||||||
? {
|
? {
|
||||||
...state.finishReason,
|
...state.finishReason,
|
||||||
normalized:
|
normalized:
|
||||||
state.finishReason.normalized === "stop" && hasToolCalls ? "tool-calls" : state.finishReason.normalized,
|
state.finishReason.normalized === "stop" && hasToolCalls ? "tool-calls" : state.finishReason.normalized,
|
||||||
}
|
}
|
||||||
: { normalized: hasToolCalls ? ("tool-calls" as const) : ("unknown" as const) }
|
: undefined
|
||||||
const metadata = reasoningMetadata(
|
const metadata = reasoningMetadata(
|
||||||
state.reasoningField,
|
state.reasoningField,
|
||||||
state.reasoningDetailsObserved ? state.reasoningDetails : undefined,
|
state.reasoningDetailsObserved ? state.reasoningDetails : undefined,
|
||||||
@@ -833,9 +829,9 @@ const finishEvents = (state: ParserState): ReadonlyArray<LLMEvent> => {
|
|||||||
? Lifecycle.reasoningStart(state.lifecycle, events, "reasoning-0", reasoningMetadata(state.reasoningField))
|
? Lifecycle.reasoningStart(state.lifecycle, events, "reasoning-0", reasoningMetadata(state.reasoningField))
|
||||||
: state.lifecycle
|
: state.lifecycle
|
||||||
const ended = Lifecycle.reasoningEnd(started, events, "reasoning-0", metadata)
|
const ended = Lifecycle.reasoningEnd(started, events, "reasoning-0", metadata)
|
||||||
const lifecycle = toolCallEvents.length ? Lifecycle.stepStart(ended, events) : ended
|
const lifecycle = state.toolCallEvents.length ? Lifecycle.stepStart(ended, events) : ended
|
||||||
events.push(...toolCallEvents)
|
events.push(...state.toolCallEvents)
|
||||||
Lifecycle.finish(lifecycle, events, { reason, usage: state.usage })
|
if (reason) Lifecycle.finish(lifecycle, events, { reason, usage: state.usage })
|
||||||
return events
|
return events
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -40,40 +40,39 @@ export const MediaPart = Schema.Struct({
|
|||||||
}).annotate({ identifier: "LLM.Content.Media" })
|
}).annotate({ identifier: "LLM.Content.Media" })
|
||||||
export type MediaPart = Schema.Schema.Type<typeof MediaPart>
|
export type MediaPart = Schema.Schema.Type<typeof MediaPart>
|
||||||
|
|
||||||
|
const toolResultValueSchema = Schema.Union([
|
||||||
|
Schema.Struct({
|
||||||
|
type: Schema.Literal("json"),
|
||||||
|
value: Schema.Unknown,
|
||||||
|
}),
|
||||||
|
Schema.Struct({
|
||||||
|
type: Schema.Literal("text"),
|
||||||
|
value: Schema.Unknown,
|
||||||
|
}),
|
||||||
|
Schema.Struct({
|
||||||
|
type: Schema.Literal("error"),
|
||||||
|
value: Schema.Unknown,
|
||||||
|
}),
|
||||||
|
Schema.Struct({
|
||||||
|
type: Schema.Literal("content"),
|
||||||
|
value: Schema.Array(Tool.Content),
|
||||||
|
}),
|
||||||
|
]).annotate({ identifier: "LLM.ToolResult" })
|
||||||
|
export type ToolResultValue = Schema.Schema.Type<typeof toolResultValueSchema>
|
||||||
|
|
||||||
const isToolResultValue = (value: unknown): value is ToolResultValue =>
|
const isToolResultValue = (value: unknown): value is ToolResultValue =>
|
||||||
isRecord(value) &&
|
isRecord(value) &&
|
||||||
(value.type === "text" || value.type === "json" || value.type === "error" || value.type === "content") &&
|
(value.type === "text" || value.type === "json" || value.type === "error" || value.type === "content") &&
|
||||||
"value" in value
|
"value" in value
|
||||||
|
|
||||||
export const ToolResultValue = Object.assign(
|
export const ToolResultValue = Object.assign(toolResultValueSchema, {
|
||||||
Schema.Union([
|
is: isToolResultValue,
|
||||||
Schema.Struct({
|
make: (value: unknown, type: ToolResultValue["type"] = "json"): ToolResultValue => {
|
||||||
type: Schema.Literal("json"),
|
if (isToolResultValue(value)) return value
|
||||||
value: Schema.Unknown,
|
if (type === "content") return { type, value: Array.isArray(value) ? value : [] }
|
||||||
}),
|
return { type, value }
|
||||||
Schema.Struct({
|
|
||||||
type: Schema.Literal("text"),
|
|
||||||
value: Schema.Unknown,
|
|
||||||
}),
|
|
||||||
Schema.Struct({
|
|
||||||
type: Schema.Literal("error"),
|
|
||||||
value: Schema.Unknown,
|
|
||||||
}),
|
|
||||||
Schema.Struct({
|
|
||||||
type: Schema.Literal("content"),
|
|
||||||
value: Schema.Array(Tool.Content),
|
|
||||||
}),
|
|
||||||
]).annotate({ identifier: "LLM.ToolResult" }),
|
|
||||||
{
|
|
||||||
is: isToolResultValue,
|
|
||||||
make: (value: unknown, type: ToolResultValue["type"] = "json"): ToolResultValue => {
|
|
||||||
if (isToolResultValue(value)) return value
|
|
||||||
if (type === "content") return { type, value: Array.isArray(value) ? value : [] }
|
|
||||||
return { type, value }
|
|
||||||
},
|
|
||||||
},
|
},
|
||||||
)
|
})
|
||||||
export type ToolResultValue = Schema.Schema.Type<typeof ToolResultValue>
|
|
||||||
|
|
||||||
export interface ToolOutput {
|
export interface ToolOutput {
|
||||||
readonly structured: unknown
|
readonly structured: unknown
|
||||||
|
|||||||
@@ -102,24 +102,6 @@ describe("OpenAI Chat route", () => {
|
|||||||
}),
|
}),
|
||||||
)
|
)
|
||||||
|
|
||||||
it.effect("concatenates assistant text parts without adding separators", () =>
|
|
||||||
Effect.gen(function* () {
|
|
||||||
const prepared = yield* compileRequest(
|
|
||||||
LLM.request({
|
|
||||||
model,
|
|
||||||
messages: [
|
|
||||||
Message.assistant([
|
|
||||||
{ type: "text", text: "Hello" },
|
|
||||||
{ type: "text", text: " world" },
|
|
||||||
]),
|
|
||||||
],
|
|
||||||
}),
|
|
||||||
)
|
|
||||||
|
|
||||||
expect(prepared.body.messages).toEqual([{ role: "assistant", content: "Hello world" }])
|
|
||||||
}),
|
|
||||||
)
|
|
||||||
|
|
||||||
it.effect("writes reasoning to a configured custom field on every assistant message", () =>
|
it.effect("writes reasoning to a configured custom field on every assistant message", () =>
|
||||||
Effect.gen(function* () {
|
Effect.gen(function* () {
|
||||||
const prepared = yield* compileRequest(
|
const prepared = yield* compileRequest(
|
||||||
@@ -596,7 +578,7 @@ describe("OpenAI Chat route", () => {
|
|||||||
}),
|
}),
|
||||||
)
|
)
|
||||||
|
|
||||||
expect(prepared.body.messages).toEqual([{ role: "assistant", content: "", reasoning_content: "hidden" }])
|
expect(prepared.body.messages).toEqual([{ role: "assistant", content: null, reasoning_content: "hidden" }])
|
||||||
}),
|
}),
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -845,7 +827,7 @@ describe("OpenAI Chat route", () => {
|
|||||||
}),
|
}),
|
||||||
)
|
)
|
||||||
|
|
||||||
it.effect("preserves scalar reasoning after content starts", () =>
|
it.effect("ignores scalar reasoning after content starts", () =>
|
||||||
Effect.gen(function* () {
|
Effect.gen(function* () {
|
||||||
const details = [{ type: "reasoning.text", text: "detail", format: "unknown", index: 0 }]
|
const details = [{ type: "reasoning.text", text: "detail", format: "unknown", index: 0 }]
|
||||||
const response = yield* LLMClient.generate(request).pipe(
|
const response = yield* LLMClient.generate(request).pipe(
|
||||||
@@ -861,11 +843,11 @@ describe("OpenAI Chat route", () => {
|
|||||||
),
|
),
|
||||||
)
|
)
|
||||||
|
|
||||||
expect(response.reasoning).toBe("detailscalar")
|
expect(response.reasoning).toBe("detail")
|
||||||
expect(response.events.filter(LLMEvent.is.reasoningStart)).toHaveLength(2)
|
expect(response.events.filter(LLMEvent.is.reasoningStart)).toHaveLength(1)
|
||||||
expect(response.events.filter(LLMEvent.is.reasoningEnd)).toHaveLength(2)
|
expect(response.events.filter(LLMEvent.is.reasoningEnd)).toHaveLength(1)
|
||||||
expect(response.message.content.find((part) => part.type === "reasoning")?.providerMetadata).toEqual({
|
expect(response.message.content.find((part) => part.type === "reasoning")?.providerMetadata).toEqual({
|
||||||
openai: { reasoningField: "reasoning", reasoningDetails: details },
|
openai: { reasoningDetails: details },
|
||||||
})
|
})
|
||||||
}),
|
}),
|
||||||
)
|
)
|
||||||
@@ -965,7 +947,7 @@ describe("OpenAI Chat route", () => {
|
|||||||
expect(response.events.filter(LLMEvent.is.reasoningEnd)).toHaveLength(1)
|
expect(response.events.filter(LLMEvent.is.reasoningEnd)).toHaveLength(1)
|
||||||
|
|
||||||
const replay = yield* compileRequest(LLM.request({ model, messages: [response.message] }))
|
const replay = yield* compileRequest(LLM.request({ model, messages: [response.message] }))
|
||||||
expect(replay.body.messages).toEqual([{ role: "assistant", content: "", reasoning_details: details }])
|
expect(replay.body.messages).toEqual([{ role: "assistant", content: null, reasoning_details: details }])
|
||||||
}),
|
}),
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -1015,7 +997,7 @@ describe("OpenAI Chat route", () => {
|
|||||||
)
|
)
|
||||||
|
|
||||||
expect(replay.body.messages).toEqual([
|
expect(replay.body.messages).toEqual([
|
||||||
{ role: "assistant", content: "", reasoning: "firstsecond", reasoning_details: [first, second] },
|
{ role: "assistant", content: null, reasoning: "firstsecond", reasoning_details: [first, second] },
|
||||||
])
|
])
|
||||||
}),
|
}),
|
||||||
)
|
)
|
||||||
@@ -1040,7 +1022,7 @@ describe("OpenAI Chat route", () => {
|
|||||||
)
|
)
|
||||||
|
|
||||||
expect(replay.body.messages).toEqual([
|
expect(replay.body.messages).toEqual([
|
||||||
{ role: "assistant", content: "", reasoning_content: "AB", reasoning_details: [detail] },
|
{ role: "assistant", content: null, reasoning_content: "AB", reasoning_details: [detail] },
|
||||||
])
|
])
|
||||||
}),
|
}),
|
||||||
)
|
)
|
||||||
@@ -1062,7 +1044,7 @@ describe("OpenAI Chat route", () => {
|
|||||||
)
|
)
|
||||||
|
|
||||||
expect(replay.body.messages).toEqual([
|
expect(replay.body.messages).toEqual([
|
||||||
{ role: "assistant", content: "", reasoning_content: "thinking", reasoning_details: details },
|
{ role: "assistant", content: null, reasoning_content: "thinking", reasoning_details: details },
|
||||||
])
|
])
|
||||||
}),
|
}),
|
||||||
)
|
)
|
||||||
@@ -1170,7 +1152,7 @@ describe("OpenAI Chat route", () => {
|
|||||||
}),
|
}),
|
||||||
)
|
)
|
||||||
|
|
||||||
it.effect("finalizes a streamed tool call when the provider ends without a finish reason", () =>
|
it.effect("fails a streamed tool call when the provider ends without a finish reason", () =>
|
||||||
Effect.gen(function* () {
|
Effect.gen(function* () {
|
||||||
const body = sseEvents(
|
const body = sseEvents(
|
||||||
deltaChunk({
|
deltaChunk({
|
||||||
@@ -1182,31 +1164,27 @@ describe("OpenAI Chat route", () => {
|
|||||||
const input = LLMRequest.update(request, {
|
const input = LLMRequest.update(request, {
|
||||||
tools: [ToolDefinition.make({ name: "lookup", description: "Lookup data", inputSchema: { type: "object" } })],
|
tools: [ToolDefinition.make({ name: "lookup", description: "Lookup data", inputSchema: { type: "object" } })],
|
||||||
})
|
})
|
||||||
const response = yield* LLMClient.generate(input).pipe(Effect.provide(fixedResponse(body)))
|
const events: LLMEvent[] = []
|
||||||
|
const streamError = yield* LLMClient.stream(input).pipe(
|
||||||
|
Stream.runForEach((event) => Effect.sync(() => events.push(event))),
|
||||||
|
Effect.flip,
|
||||||
|
Effect.provide(fixedResponse(body)),
|
||||||
|
)
|
||||||
|
const error = yield* LLMClient.generate(input).pipe(Effect.provide(fixedResponse(body)), Effect.flip)
|
||||||
|
|
||||||
expect(response.events).toEqual([
|
expect(events).toEqual([
|
||||||
{ type: "step-start", index: 0 },
|
{ type: "step-start", index: 0 },
|
||||||
{ type: "tool-input-start", id: "call_1", name: "lookup", providerMetadata: undefined },
|
{ type: "tool-input-start", id: "call_1", name: "lookup", providerMetadata: undefined },
|
||||||
{ type: "tool-input-delta", id: "call_1", name: "lookup", text: '{"query"' },
|
{ type: "tool-input-delta", id: "call_1", name: "lookup", text: '{"query"' },
|
||||||
{ type: "tool-input-delta", id: "call_1", name: "lookup", text: ':"weather"}' },
|
{ type: "tool-input-delta", id: "call_1", name: "lookup", text: ':"weather"}' },
|
||||||
{ type: "tool-input-end", id: "call_1", name: "lookup", providerMetadata: undefined },
|
|
||||||
{
|
|
||||||
type: "tool-call",
|
|
||||||
id: "call_1",
|
|
||||||
name: "lookup",
|
|
||||||
input: { query: "weather" },
|
|
||||||
providerExecuted: undefined,
|
|
||||||
providerMetadata: undefined,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
type: "step-finish",
|
|
||||||
index: 0,
|
|
||||||
reason: { normalized: "tool-calls" },
|
|
||||||
usage: undefined,
|
|
||||||
providerMetadata: undefined,
|
|
||||||
},
|
|
||||||
{ type: "finish", reason: { normalized: "tool-calls" }, usage: undefined },
|
|
||||||
])
|
])
|
||||||
|
expect(events.filter(LLMEvent.is.toolCall)).toEqual([])
|
||||||
|
expect(streamError.reason).toMatchObject({
|
||||||
|
_tag: "InvalidProviderOutput",
|
||||||
|
classification: "incomplete-stream",
|
||||||
|
})
|
||||||
|
expect(streamError.message).toContain("The provider response ended unexpectedly.")
|
||||||
|
expect(error.message).toContain("The provider response ended unexpectedly.")
|
||||||
}),
|
}),
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import type { IntegrationMethod, IntegrationOauthConnectOutput } from "@opencode-ai/client/promise"
|
import type { FormAnswer, IntegrationMethod, IntegrationOauthConnectOutput } from "@opencode-ai/client/promise"
|
||||||
import { Button } from "@opencode-ai/ui/button"
|
import { Button } from "@opencode-ai/ui/button"
|
||||||
import { useDialog } from "@opencode-ai/ui/context/dialog"
|
import { useDialog } from "@opencode-ai/ui/context/dialog"
|
||||||
import { Dialog } from "@opencode-ai/ui/dialog"
|
import { Dialog } from "@opencode-ai/ui/dialog"
|
||||||
@@ -40,6 +40,8 @@ import { decode64 } from "@/utils/base64"
|
|||||||
|
|
||||||
const CUSTOM_ID = "_custom"
|
const CUSTOM_ID = "_custom"
|
||||||
type ConnectMethod = Extract<IntegrationMethod, { type: "key" | "oauth" }>
|
type ConnectMethod = Extract<IntegrationMethod, { type: "key" | "oauth" }>
|
||||||
|
type IntegrationForm = NonNullable<ConnectMethod["forms"]>[number]
|
||||||
|
type StringForm = Extract<IntegrationForm, { type: "string" }>
|
||||||
|
|
||||||
export function useProviderConnectController(options: { onBack?: () => void } = {}) {
|
export function useProviderConnectController(options: { onBack?: () => void } = {}) {
|
||||||
const [store, setStore] = createStore({ selected: undefined as string | undefined })
|
const [store, setStore] = createStore({ selected: undefined as string | undefined })
|
||||||
@@ -434,16 +436,16 @@ function ProviderConnection(props: {
|
|||||||
const [store, setStore] = createStore({
|
const [store, setStore] = createStore({
|
||||||
methodIndex: undefined as undefined | number,
|
methodIndex: undefined as undefined | number,
|
||||||
authorization: undefined as undefined | IntegrationOauthConnectOutput["data"],
|
authorization: undefined as undefined | IntegrationOauthConnectOutput["data"],
|
||||||
promptInputs: undefined as undefined | Record<string, string>,
|
formAnswers: undefined as FormAnswer | undefined,
|
||||||
state: "pending" as undefined | "pending" | "complete" | "error" | "prompt",
|
state: "pending" as undefined | "pending" | "complete" | "error" | "form",
|
||||||
error: undefined as string | undefined,
|
error: undefined as string | undefined,
|
||||||
})
|
})
|
||||||
|
|
||||||
type Action =
|
type Action =
|
||||||
| { type: "method.select"; index: number }
|
| { type: "method.select"; index: number }
|
||||||
| { type: "method.reset" }
|
| { type: "method.reset" }
|
||||||
| { type: "auth.prompt" }
|
| { type: "auth.form" }
|
||||||
| { type: "auth.inputs"; inputs: Record<string, string> }
|
| { type: "auth.answers"; answers: FormAnswer }
|
||||||
| { type: "auth.pending" }
|
| { type: "auth.pending" }
|
||||||
| { type: "auth.complete"; authorization: IntegrationOauthConnectOutput["data"] }
|
| { type: "auth.complete"; authorization: IntegrationOauthConnectOutput["data"] }
|
||||||
| { type: "auth.error"; error: string }
|
| { type: "auth.error"; error: string }
|
||||||
@@ -454,7 +456,7 @@ function ProviderConnection(props: {
|
|||||||
if (action.type === "method.select") {
|
if (action.type === "method.select") {
|
||||||
draft.methodIndex = action.index
|
draft.methodIndex = action.index
|
||||||
draft.authorization = undefined
|
draft.authorization = undefined
|
||||||
draft.promptInputs = undefined
|
draft.formAnswers = undefined
|
||||||
draft.state = undefined
|
draft.state = undefined
|
||||||
draft.error = undefined
|
draft.error = undefined
|
||||||
return
|
return
|
||||||
@@ -462,18 +464,18 @@ function ProviderConnection(props: {
|
|||||||
if (action.type === "method.reset") {
|
if (action.type === "method.reset") {
|
||||||
draft.methodIndex = undefined
|
draft.methodIndex = undefined
|
||||||
draft.authorization = undefined
|
draft.authorization = undefined
|
||||||
draft.promptInputs = undefined
|
draft.formAnswers = undefined
|
||||||
draft.state = undefined
|
draft.state = undefined
|
||||||
draft.error = undefined
|
draft.error = undefined
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
if (action.type === "auth.prompt") {
|
if (action.type === "auth.form") {
|
||||||
draft.state = "prompt"
|
draft.state = "form"
|
||||||
draft.error = undefined
|
draft.error = undefined
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
if (action.type === "auth.inputs") {
|
if (action.type === "auth.answers") {
|
||||||
draft.promptInputs = action.inputs
|
draft.formAnswers = action.answers
|
||||||
draft.state = undefined
|
draft.state = undefined
|
||||||
draft.error = undefined
|
draft.error = undefined
|
||||||
return
|
return
|
||||||
@@ -531,7 +533,7 @@ function ProviderConnection(props: {
|
|||||||
return fallback
|
return fallback
|
||||||
}
|
}
|
||||||
|
|
||||||
async function selectMethod(index: number, inputs?: Record<string, string>) {
|
async function selectMethod(index: number, answers?: FormAnswer) {
|
||||||
if (timer.current !== undefined) {
|
if (timer.current !== undefined) {
|
||||||
clearTimeout(timer.current)
|
clearTimeout(timer.current)
|
||||||
timer.current = undefined
|
timer.current = undefined
|
||||||
@@ -540,9 +542,17 @@ function ProviderConnection(props: {
|
|||||||
const method = methods()[index]
|
const method = methods()[index]
|
||||||
dispatch({ type: "method.select", index })
|
dispatch({ type: "method.select", index })
|
||||||
|
|
||||||
|
if (method.forms?.length && !answers) {
|
||||||
|
dispatch({ type: "auth.form" })
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if (method.type === "key") {
|
||||||
|
dispatch({ type: "auth.answers", answers: answers ?? {} })
|
||||||
|
return
|
||||||
|
}
|
||||||
if (method.type === "oauth") {
|
if (method.type === "oauth") {
|
||||||
if (method.prompts?.length && !inputs) {
|
if (method.forms?.some((field) => field.type !== "string")) {
|
||||||
dispatch({ type: "auth.prompt" })
|
dispatch({ type: "auth.error", error: "This authentication form contains unsupported fields" })
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
dispatch({ type: "auth.pending" })
|
dispatch({ type: "auth.pending" })
|
||||||
@@ -550,7 +560,7 @@ function ProviderConnection(props: {
|
|||||||
.api.integration.oauth.connect({
|
.api.integration.oauth.connect({
|
||||||
integrationID: props.provider,
|
integrationID: props.provider,
|
||||||
methodID: method.id,
|
methodID: method.id,
|
||||||
inputs: inputs ?? {},
|
answers: answers ?? {},
|
||||||
location: location(),
|
location: location(),
|
||||||
})
|
})
|
||||||
.then((x) => {
|
.then((x) => {
|
||||||
@@ -564,41 +574,42 @@ function ProviderConnection(props: {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function AuthPromptsView() {
|
function AuthFormsView() {
|
||||||
const [formStore, setFormStore] = createStore({
|
const [formStore, setFormStore] = createStore({
|
||||||
value: {} as Record<string, string>,
|
value: {} as Record<string, string>,
|
||||||
index: 0,
|
index: 0,
|
||||||
})
|
})
|
||||||
|
|
||||||
const prompts = createMemo(() => {
|
const forms = createMemo<StringForm[]>(() => {
|
||||||
const value = method()
|
const value = method()
|
||||||
return value?.type === "oauth" ? (value.prompts ?? []) : []
|
return (value?.forms ?? []).flatMap((field) => (field.type === "string" ? [field] : []))
|
||||||
})
|
})
|
||||||
const matches = (prompt: NonNullable<ReturnType<typeof prompts>[number]>, value: Record<string, string>) => {
|
const matches = (field: StringForm, value: Record<string, string>) => {
|
||||||
if (!prompt.when) return true
|
return (field.when ?? []).every((condition) => {
|
||||||
const actual = value[prompt.when.key]
|
const actual = value[condition.key]
|
||||||
if (actual === undefined) return false
|
if (actual === undefined) return false
|
||||||
return prompt.when.op === "eq" ? actual === prompt.when.value : actual !== prompt.when.value
|
return condition.op === "eq" ? actual === condition.value : actual !== condition.value
|
||||||
|
})
|
||||||
}
|
}
|
||||||
const current = createMemo(() => {
|
const current = createMemo(() => {
|
||||||
const all = prompts()
|
const all = forms()
|
||||||
const index = all.findIndex((prompt, index) => index >= formStore.index && matches(prompt, formStore.value))
|
const index = all.findIndex((field, index) => index >= formStore.index && matches(field, formStore.value))
|
||||||
if (index === -1) return
|
if (index === -1) return
|
||||||
return {
|
return {
|
||||||
index,
|
index,
|
||||||
prompt: all[index],
|
field: all[index],
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
const valid = createMemo(() => {
|
const valid = createMemo(() => {
|
||||||
const item = current()
|
const item = current()
|
||||||
if (!item || item.prompt.type !== "text") return false
|
if (!item || item.field.options) return false
|
||||||
const value = formStore.value[item.prompt.key] ?? ""
|
if (!item.field.required) return true
|
||||||
return value.trim().length > 0
|
return (formStore.value[item.field.key] ?? "").trim().length > 0
|
||||||
})
|
})
|
||||||
|
|
||||||
async function next(index: number, value: Record<string, string>) {
|
async function next(index: number, value: Record<string, string>) {
|
||||||
if (store.methodIndex === undefined) return
|
if (store.methodIndex === undefined) return
|
||||||
const next = prompts().findIndex((prompt, i) => i > index && matches(prompt, value))
|
const next = forms().findIndex((field, i) => i > index && matches(field, value))
|
||||||
if (next !== -1) {
|
if (next !== -1) {
|
||||||
setFormStore("index", next)
|
setFormStore("index", next)
|
||||||
return
|
return
|
||||||
@@ -609,60 +620,60 @@ function ProviderConnection(props: {
|
|||||||
async function handleSubmit(e: SubmitEvent) {
|
async function handleSubmit(e: SubmitEvent) {
|
||||||
e.preventDefault()
|
e.preventDefault()
|
||||||
const item = current()
|
const item = current()
|
||||||
if (!item || item.prompt.type !== "text") return
|
if (!item || item.field.options) return
|
||||||
if (!valid()) return
|
if (!valid()) return
|
||||||
await next(item.index, formStore.value)
|
await next(item.index, formStore.value)
|
||||||
}
|
}
|
||||||
|
|
||||||
const item = () => current()
|
const item = () => current()
|
||||||
const text = createMemo(() => {
|
const text = createMemo(() => {
|
||||||
const prompt = item()?.prompt
|
const field = item()?.field
|
||||||
if (!prompt || prompt.type !== "text") return
|
if (!field || field.options) return
|
||||||
return prompt
|
return field
|
||||||
})
|
})
|
||||||
const select = createMemo(() => {
|
const select = createMemo(() => {
|
||||||
const prompt = item()?.prompt
|
const field = item()?.field
|
||||||
if (!prompt || prompt.type !== "select") return
|
if (!field?.options) return
|
||||||
return prompt
|
return field
|
||||||
})
|
})
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<form onSubmit={handleSubmit} class="flex flex-col items-start gap-4">
|
<form onSubmit={handleSubmit} class="flex flex-col items-start gap-4">
|
||||||
<Switch>
|
<Switch>
|
||||||
<Match when={item()?.prompt.type === "text"}>
|
<Match when={item()?.field.options === undefined}>
|
||||||
<TextField
|
<TextField
|
||||||
type="text"
|
type="text"
|
||||||
label={text()?.message ?? ""}
|
label={text()?.title ?? ""}
|
||||||
placeholder={text()?.placeholder}
|
placeholder={text()?.placeholder}
|
||||||
value={text() ? (formStore.value[text()!.key] ?? "") : ""}
|
value={text() ? (formStore.value[text()!.key] ?? "") : ""}
|
||||||
onChange={(value) => {
|
onChange={(value) => {
|
||||||
const prompt = text()
|
const field = text()
|
||||||
if (!prompt) return
|
if (!field) return
|
||||||
setFormStore("value", prompt.key, value)
|
setFormStore("value", field.key, value)
|
||||||
}}
|
}}
|
||||||
/>
|
/>
|
||||||
<Button class="w-auto" type="submit" size="large" variant="primary" disabled={!valid()}>
|
<Button class="w-auto" type="submit" size="large" variant="primary" disabled={!valid()}>
|
||||||
{language.t("common.continue")}
|
{language.t("common.continue")}
|
||||||
</Button>
|
</Button>
|
||||||
</Match>
|
</Match>
|
||||||
<Match when={item()?.prompt.type === "select"}>
|
<Match when={item()?.field.options !== undefined}>
|
||||||
<div class="w-full flex flex-col gap-1.5">
|
<div class="w-full flex flex-col gap-1.5">
|
||||||
<div class="text-14-regular text-text-base">{select()?.message}</div>
|
<div class="text-14-regular text-text-base">{select()?.title}</div>
|
||||||
<div>
|
<div>
|
||||||
<List
|
<List
|
||||||
class="px-3"
|
class="px-3"
|
||||||
items={select()?.options ?? []}
|
items={select()?.options ?? []}
|
||||||
key={(x) => x.value}
|
key={(x) => x.value}
|
||||||
current={select()?.options.find((x) => x.value === formStore.value[select()!.key])}
|
current={select()?.options?.find((x) => x.value === formStore.value[select()!.key])}
|
||||||
onSelect={(value) => {
|
onSelect={(value) => {
|
||||||
if (!value) return
|
if (!value) return
|
||||||
const prompt = select()
|
const field = select()
|
||||||
if (!prompt) return
|
if (!field) return
|
||||||
const nextValue = {
|
const nextValue = {
|
||||||
...formStore.value,
|
...formStore.value,
|
||||||
[prompt.key]: value.value,
|
[field.key]: value.value,
|
||||||
}
|
}
|
||||||
setFormStore("value", prompt.key, value.value)
|
setFormStore("value", field.key, value.value)
|
||||||
void next(item()!.index, nextValue)
|
void next(item()!.index, nextValue)
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
@@ -672,7 +683,7 @@ function ProviderConnection(props: {
|
|||||||
<div class="w-2.5 h-0.5 ml-0 bg-icon-strong-base hidden" data-slot="list-item-extra-icon" />
|
<div class="w-2.5 h-0.5 ml-0 bg-icon-strong-base hidden" data-slot="list-item-extra-icon" />
|
||||||
</div>
|
</div>
|
||||||
<span>{option.label}</span>
|
<span>{option.label}</span>
|
||||||
<span class="text-14-regular text-text-weak">{option.hint}</span>
|
<span class="text-14-regular text-text-weak">{option.description}</span>
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
</List>
|
</List>
|
||||||
@@ -820,6 +831,7 @@ function ProviderConnection(props: {
|
|||||||
integrationID: props.provider,
|
integrationID: props.provider,
|
||||||
location: location(),
|
location: location(),
|
||||||
key: apiKey,
|
key: apiKey,
|
||||||
|
answers: store.formAnswers ?? {},
|
||||||
})
|
})
|
||||||
await complete()
|
await complete()
|
||||||
}
|
}
|
||||||
@@ -1143,8 +1155,8 @@ function ProviderConnection(props: {
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</Match>
|
</Match>
|
||||||
<Match when={store.state === "prompt"}>
|
<Match when={store.state === "form"}>
|
||||||
<AuthPromptsView />
|
<AuthFormsView />
|
||||||
</Match>
|
</Match>
|
||||||
<Match when={store.state === "error"}>
|
<Match when={store.state === "error"}>
|
||||||
<div class="text-14-regular text-text-base">
|
<div class="text-14-regular text-text-base">
|
||||||
|
|||||||
@@ -662,13 +662,13 @@ export function createServerSyncContextInner(serverSDK: ServerSDK) {
|
|||||||
integrationID: server.integrationID,
|
integrationID: server.integrationID,
|
||||||
location: { directory: key },
|
location: { directory: key },
|
||||||
})
|
})
|
||||||
const method = integration.data?.methods.find((item) => item.type === "oauth" && !item.prompts?.length)
|
const method = integration.data?.methods.find((item) => item.type === "oauth" && !item.forms?.length)
|
||||||
if (!method || method.type !== "oauth")
|
if (!method || method.type !== "oauth")
|
||||||
throw new Error(`MCP server ${name} requires an interactive authentication form`)
|
throw new Error(`MCP server ${name} requires an interactive authentication form`)
|
||||||
const attempt = await serverSDK.api.integration.oauth.connect({
|
const attempt = await serverSDK.api.integration.oauth.connect({
|
||||||
integrationID: server.integrationID,
|
integrationID: server.integrationID,
|
||||||
methodID: method.id,
|
methodID: method.id,
|
||||||
inputs: {},
|
answers: {},
|
||||||
location: { directory: key },
|
location: { directory: key },
|
||||||
})
|
})
|
||||||
platform.openLink(attempt.data.url)
|
platform.openLink(attempt.data.url)
|
||||||
|
|||||||
@@ -50,7 +50,7 @@ const login = Effect.fn("cli.console.login.run")(function* (timeline: TimelineHo
|
|||||||
{
|
{
|
||||||
integrationID,
|
integrationID,
|
||||||
methodID: method.id,
|
methodID: method.id,
|
||||||
inputs: server ? { server } : {},
|
answers: server ? { server } : {},
|
||||||
location,
|
location,
|
||||||
},
|
},
|
||||||
{ signal },
|
{ signal },
|
||||||
|
|||||||
@@ -32,7 +32,7 @@ export default Runtime.handler(
|
|||||||
return yield* Effect.fail(new Error(`MCP server "${input.name}" is not an OAuth-capable remote server`))
|
return yield* Effect.fail(new Error(`MCP server "${input.name}" is not an OAuth-capable remote server`))
|
||||||
|
|
||||||
const started = yield* Effect.promise(() =>
|
const started = yield* Effect.promise(() =>
|
||||||
client.integration.oauth.connect({ integrationID: integration.id, methodID: method.id, inputs: {}, location }),
|
client.integration.oauth.connect({ integrationID: integration.id, methodID: method.id, answers: {}, location }),
|
||||||
)
|
)
|
||||||
const attempt = started.data
|
const attempt = started.data
|
||||||
if (attempt.mode === "code")
|
if (attempt.mode === "code")
|
||||||
|
|||||||
@@ -1 +1,3 @@
|
|||||||
["api.ts"]
|
[
|
||||||
|
"api.ts"
|
||||||
|
]
|
||||||
|
|||||||
@@ -23,9 +23,9 @@ import type { Shell } from "@opencode-ai/schema/shell"
|
|||||||
import type { DateTime } from "effect"
|
import type { DateTime } from "effect"
|
||||||
import type { Provider } from "@opencode-ai/schema/provider"
|
import type { Provider } from "@opencode-ai/schema/provider"
|
||||||
import type { Integration } from "@opencode-ai/schema/integration"
|
import type { Integration } from "@opencode-ai/schema/integration"
|
||||||
|
import type { Form } from "@opencode-ai/schema/form"
|
||||||
import type { Mcp } from "@opencode-ai/schema/mcp"
|
import type { Mcp } from "@opencode-ai/schema/mcp"
|
||||||
import type { Credential } from "@opencode-ai/schema/credential"
|
import type { Credential } from "@opencode-ai/schema/credential"
|
||||||
import type { Form } from "@opencode-ai/schema/form"
|
|
||||||
import type { Permission } from "@opencode-ai/schema/permission"
|
import type { Permission } from "@opencode-ai/schema/permission"
|
||||||
import type { PermissionSaved } from "@opencode-ai/schema/permission-saved"
|
import type { PermissionSaved } from "@opencode-ai/schema/permission-saved"
|
||||||
import type { FileSystem } from "@opencode-ai/schema/filesystem"
|
import type { FileSystem } from "@opencode-ai/schema/filesystem"
|
||||||
@@ -1052,6 +1052,7 @@ export type Endpoint10_3Input = {
|
|||||||
readonly integrationID: Integration.ID
|
readonly integrationID: Integration.ID
|
||||||
readonly location?: { readonly directory?: string | undefined; readonly workspace?: string | undefined } | undefined
|
readonly location?: { readonly directory?: string | undefined; readonly workspace?: string | undefined } | undefined
|
||||||
readonly key: string
|
readonly key: string
|
||||||
|
readonly answers: Form.Answer
|
||||||
readonly label?: string | undefined
|
readonly label?: string | undefined
|
||||||
}
|
}
|
||||||
export type Endpoint10_3Output = void
|
export type Endpoint10_3Output = void
|
||||||
@@ -1063,7 +1064,7 @@ export type Endpoint10_4Input = {
|
|||||||
readonly integrationID: Integration.ID
|
readonly integrationID: Integration.ID
|
||||||
readonly location?: { readonly directory?: string | undefined; readonly workspace?: string | undefined } | undefined
|
readonly location?: { readonly directory?: string | undefined; readonly workspace?: string | undefined } | undefined
|
||||||
readonly methodID: Integration.MethodID
|
readonly methodID: Integration.MethodID
|
||||||
readonly inputs: { readonly [x: string]: string }
|
readonly answers: Form.Answer
|
||||||
readonly label?: string | undefined
|
readonly label?: string | undefined
|
||||||
}
|
}
|
||||||
export type Endpoint10_4Output = { readonly location: Location.Info; readonly data: Integration.Attempt }
|
export type Endpoint10_4Output = { readonly location: Location.Info; readonly data: Integration.Attempt }
|
||||||
|
|||||||
@@ -1 +1,5 @@
|
|||||||
["client-error.ts", "client.ts", "index.ts"]
|
[
|
||||||
|
"client-error.ts",
|
||||||
|
"client.ts",
|
||||||
|
"index.ts"
|
||||||
|
]
|
||||||
|
|||||||
@@ -715,7 +715,7 @@ const Endpoint10_3 = (raw: RawClient["server.integration"]) => (input: Endpoint1
|
|||||||
raw["integration.connect.key"]({
|
raw["integration.connect.key"]({
|
||||||
params: { integrationID: input["integrationID"] },
|
params: { integrationID: input["integrationID"] },
|
||||||
query: { location: input["location"] },
|
query: { location: input["location"] },
|
||||||
payload: { key: input["key"], label: input["label"] },
|
payload: { key: input["key"], answers: input["answers"], label: input["label"] },
|
||||||
}).pipe(Effect.mapError(mapClientError)),
|
}).pipe(Effect.mapError(mapClientError)),
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -724,7 +724,7 @@ const Endpoint10_4 = (raw: RawClient["server.integration"]) => (input: Endpoint1
|
|||||||
raw["integration.oauth.connect"]({
|
raw["integration.oauth.connect"]({
|
||||||
params: { integrationID: input["integrationID"] },
|
params: { integrationID: input["integrationID"] },
|
||||||
query: { location: input["location"] },
|
query: { location: input["location"] },
|
||||||
payload: { methodID: input["methodID"], inputs: input["inputs"], label: input["label"] },
|
payload: { methodID: input["methodID"], answers: input["answers"], label: input["label"] },
|
||||||
}).pipe(Effect.mapError(mapClientError)),
|
}).pipe(Effect.mapError(mapClientError)),
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|||||||
@@ -1 +1,6 @@
|
|||||||
["client-error.ts", "client.ts", "index.ts", "types.ts"]
|
[
|
||||||
|
"client-error.ts",
|
||||||
|
"client.ts",
|
||||||
|
"index.ts",
|
||||||
|
"types.ts"
|
||||||
|
]
|
||||||
|
|||||||
@@ -1030,7 +1030,7 @@ export function make(options: ClientOptions) {
|
|||||||
method: "POST",
|
method: "POST",
|
||||||
path: `/api/integration/${encodeURIComponent(input.integrationID)}/connect/key`,
|
path: `/api/integration/${encodeURIComponent(input.integrationID)}/connect/key`,
|
||||||
query: { location: input["location"] },
|
query: { location: input["location"] },
|
||||||
body: { key: input["key"], label: input["label"] },
|
body: { key: input["key"], answers: input["answers"], label: input["label"] },
|
||||||
successStatus: 204,
|
successStatus: 204,
|
||||||
declaredStatuses: [400, 401],
|
declaredStatuses: [400, 401],
|
||||||
empty: true,
|
empty: true,
|
||||||
@@ -1045,7 +1045,7 @@ export function make(options: ClientOptions) {
|
|||||||
method: "POST",
|
method: "POST",
|
||||||
path: `/api/integration/${encodeURIComponent(input.integrationID)}/connect/oauth`,
|
path: `/api/integration/${encodeURIComponent(input.integrationID)}/connect/oauth`,
|
||||||
query: { location: input["location"] },
|
query: { location: input["location"] },
|
||||||
body: { methodID: input["methodID"], inputs: input["inputs"], label: input["label"] },
|
body: { methodID: input["methodID"], answers: input["answers"], label: input["label"] },
|
||||||
successStatus: 200,
|
successStatus: 200,
|
||||||
declaredStatuses: [400, 401],
|
declaredStatuses: [400, 401],
|
||||||
empty: false,
|
empty: false,
|
||||||
|
|||||||
@@ -195,12 +195,18 @@ export type ProviderInfo = {
|
|||||||
body?: { [x: string]: any }
|
body?: { [x: string]: any }
|
||||||
}
|
}
|
||||||
|
|
||||||
export type IntegrationWhen = { key: string; op: "eq" | "neq"; value: string }
|
export type FormWhen = {
|
||||||
|
key: string
|
||||||
|
op: "eq" | "neq"
|
||||||
|
value: string | number | "Infinity" | "-Infinity" | "NaN" | boolean
|
||||||
|
}
|
||||||
|
|
||||||
|
export type FormOption = { value: string; label: string; description?: string }
|
||||||
|
|
||||||
|
export type FormExternalField = { key: string; type: "external"; url: string; title?: string; description?: string }
|
||||||
|
|
||||||
export type IntegrationCommandMethod = { id: string; type: "command"; label: string; command: Array<string> }
|
export type IntegrationCommandMethod = { id: string; type: "command"; label: string; command: Array<string> }
|
||||||
|
|
||||||
export type IntegrationKeyMethod = { type: "key"; label?: string }
|
|
||||||
|
|
||||||
export type IntegrationEnvMethod = { type: "env"; names: Array<string> }
|
export type IntegrationEnvMethod = { type: "env"; names: Array<string> }
|
||||||
|
|
||||||
export type ConnectionCredentialInfo = { type: "credential"; id: string; label: string }
|
export type ConnectionCredentialInfo = { type: "credential"; id: string; label: string }
|
||||||
@@ -285,16 +291,6 @@ export type ProjectDirectory = { directory: string; strategy?: string }
|
|||||||
|
|
||||||
export type FormMetadata = { [x: string]: JsonValue }
|
export type FormMetadata = { [x: string]: JsonValue }
|
||||||
|
|
||||||
export type FormWhen = {
|
|
||||||
key: string
|
|
||||||
op: "eq" | "neq"
|
|
||||||
value: string | number | "Infinity" | "-Infinity" | "NaN" | boolean
|
|
||||||
}
|
|
||||||
|
|
||||||
export type FormOption = { value: string; label: string; description?: string }
|
|
||||||
|
|
||||||
export type FormExternalField = { key: string; type: "external"; url: string; title?: string; description?: string }
|
|
||||||
|
|
||||||
export type FormValue = string | number | boolean | Array<string>
|
export type FormValue = string | number | boolean | Array<string>
|
||||||
|
|
||||||
export type PermissionSource = { type: "tool"; messageID: string; id: string }
|
export type PermissionSource = { type: "tool"; messageID: string; id: string }
|
||||||
@@ -1275,45 +1271,6 @@ export type ModelCost = {
|
|||||||
cache: { read: MoneyUSDPerMillionTokens; write: MoneyUSDPerMillionTokens }
|
cache: { read: MoneyUSDPerMillionTokens; write: MoneyUSDPerMillionTokens }
|
||||||
}
|
}
|
||||||
|
|
||||||
export type IntegrationTextPrompt = {
|
|
||||||
type: "text"
|
|
||||||
key: string
|
|
||||||
message: string
|
|
||||||
placeholder?: string
|
|
||||||
when?: IntegrationWhen
|
|
||||||
}
|
|
||||||
|
|
||||||
export type IntegrationSelectPrompt = {
|
|
||||||
type: "select"
|
|
||||||
key: string
|
|
||||||
message: string
|
|
||||||
options: Array<{ label: string; value: string; hint?: string }>
|
|
||||||
when?: IntegrationWhen
|
|
||||||
}
|
|
||||||
|
|
||||||
export type ConnectionInfo = ConnectionCredentialInfo | ConnectionEnvInfo
|
|
||||||
|
|
||||||
export type McpServer = {
|
|
||||||
name: string
|
|
||||||
status: McpStatusConnected | McpStatusPending | McpStatusDisabled | McpStatusFailed | McpStatusNeedsAuth
|
|
||||||
integrationID?: string
|
|
||||||
}
|
|
||||||
|
|
||||||
export type McpResourceCatalog = { resources: Array<McpResource>; templates: Array<McpResourceTemplate> }
|
|
||||||
|
|
||||||
export type Project = {
|
|
||||||
id: string
|
|
||||||
canonical: string
|
|
||||||
vcs?: ProjectVcs
|
|
||||||
name?: string
|
|
||||||
icon?: ProjectIcon
|
|
||||||
commands?: ProjectCommands
|
|
||||||
time: ProjectTime
|
|
||||||
sandboxes: Array<string>
|
|
||||||
}
|
|
||||||
|
|
||||||
export type ProjectDirectories = Array<ProjectDirectory>
|
|
||||||
|
|
||||||
export type FormNumberField = {
|
export type FormNumberField = {
|
||||||
key: string
|
key: string
|
||||||
title?: string
|
title?: string
|
||||||
@@ -1379,6 +1336,29 @@ export type FormMultiselectField = {
|
|||||||
default?: Array<string>
|
default?: Array<string>
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export type ConnectionInfo = ConnectionCredentialInfo | ConnectionEnvInfo
|
||||||
|
|
||||||
|
export type McpServer = {
|
||||||
|
name: string
|
||||||
|
status: McpStatusConnected | McpStatusPending | McpStatusDisabled | McpStatusFailed | McpStatusNeedsAuth
|
||||||
|
integrationID?: string
|
||||||
|
}
|
||||||
|
|
||||||
|
export type McpResourceCatalog = { resources: Array<McpResource>; templates: Array<McpResourceTemplate> }
|
||||||
|
|
||||||
|
export type Project = {
|
||||||
|
id: string
|
||||||
|
canonical: string
|
||||||
|
vcs?: ProjectVcs
|
||||||
|
name?: string
|
||||||
|
icon?: ProjectIcon
|
||||||
|
commands?: ProjectCommands
|
||||||
|
time: ProjectTime
|
||||||
|
sandboxes: Array<string>
|
||||||
|
}
|
||||||
|
|
||||||
|
export type ProjectDirectories = Array<ProjectDirectory>
|
||||||
|
|
||||||
export type FormAnswer = { [x: string]: FormValue }
|
export type FormAnswer = { [x: string]: FormValue }
|
||||||
|
|
||||||
export type PermissionRequest = {
|
export type PermissionRequest = {
|
||||||
@@ -1659,13 +1639,6 @@ export type ModelInfo = {
|
|||||||
limit: { context: number; input?: number; output: number }
|
limit: { context: number; input?: number; output: number }
|
||||||
}
|
}
|
||||||
|
|
||||||
export type IntegrationOAuthMethod = {
|
|
||||||
id: string
|
|
||||||
type: "oauth"
|
|
||||||
label: string
|
|
||||||
prompts?: Array<IntegrationTextPrompt | IntegrationSelectPrompt>
|
|
||||||
}
|
|
||||||
|
|
||||||
export type FormField =
|
export type FormField =
|
||||||
| FormStringField
|
| FormStringField
|
||||||
| FormNumberField
|
| FormNumberField
|
||||||
@@ -1919,15 +1892,9 @@ export type SessionMessageAssistantTool = {
|
|||||||
time: { created: number; ran?: number; completed?: number }
|
time: { created: number; ran?: number; completed?: number }
|
||||||
}
|
}
|
||||||
|
|
||||||
export type IntegrationMethod =
|
|
||||||
| IntegrationOAuthMethod
|
|
||||||
| IntegrationCommandMethod
|
|
||||||
| IntegrationKeyMethod
|
|
||||||
| IntegrationEnvMethod
|
|
||||||
|
|
||||||
export type FormFields = [FormField, ...Array<FormField>]
|
export type FormFields = [FormField, ...Array<FormField>]
|
||||||
|
|
||||||
export type FormFields1 = [FormField1, ...Array<FormField1>]
|
export type FormFields3 = [FormField1, ...Array<FormField1>]
|
||||||
|
|
||||||
export type SessionPendingInfo = SessionPendingUser | SessionPendingSynthetic | SessionPendingCompaction
|
export type SessionPendingInfo = SessionPendingUser | SessionPendingSynthetic | SessionPendingCompaction
|
||||||
|
|
||||||
@@ -1949,16 +1916,13 @@ export type SessionMessageAssistant = {
|
|||||||
retry?: SessionMessageAssistantRetry
|
retry?: SessionMessageAssistantRetry
|
||||||
}
|
}
|
||||||
|
|
||||||
export type IntegrationInfo = {
|
export type IntegrationOAuthMethod = { id: string; type: "oauth"; label: string; forms?: FormFields }
|
||||||
id: string
|
|
||||||
name: string
|
export type IntegrationKeyMethod = { type: "key"; label?: string; forms?: FormFields }
|
||||||
methods: Array<IntegrationMethod>
|
|
||||||
connections: Array<ConnectionInfo>
|
|
||||||
}
|
|
||||||
|
|
||||||
export type FormInfo = { id: string; sessionID: string; title: string; metadata?: FormMetadata; fields: FormFields }
|
export type FormInfo = { id: string; sessionID: string; title: string; metadata?: FormMetadata; fields: FormFields }
|
||||||
|
|
||||||
export type FormInfo1 = { id: string; sessionID: string; title: string; metadata?: FormMetadata1; fields: FormFields1 }
|
export type FormInfo1 = { id: string; sessionID: string; title: string; metadata?: FormMetadata1; fields: FormFields3 }
|
||||||
|
|
||||||
export type SessionInputAdmitted = {
|
export type SessionInputAdmitted = {
|
||||||
id: string
|
id: string
|
||||||
@@ -1981,6 +1945,12 @@ export type SessionMessageInfo =
|
|||||||
| SessionMessageAssistant
|
| SessionMessageAssistant
|
||||||
| SessionMessageCompaction
|
| SessionMessageCompaction
|
||||||
|
|
||||||
|
export type IntegrationMethod =
|
||||||
|
| IntegrationOAuthMethod
|
||||||
|
| IntegrationCommandMethod
|
||||||
|
| IntegrationKeyMethod
|
||||||
|
| IntegrationEnvMethod
|
||||||
|
|
||||||
export type FormCreated = {
|
export type FormCreated = {
|
||||||
id: string
|
id: string
|
||||||
created: number
|
created: number
|
||||||
@@ -2041,6 +2011,13 @@ export type SessionMessagesResponse = {
|
|||||||
cursor: { previous?: string | null; next?: string | null }
|
cursor: { previous?: string | null; next?: string | null }
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export type IntegrationInfo = {
|
||||||
|
id: string
|
||||||
|
name: string
|
||||||
|
methods: Array<IntegrationMethod>
|
||||||
|
connections: Array<ConnectionInfo>
|
||||||
|
}
|
||||||
|
|
||||||
export type V2Event =
|
export type V2Event =
|
||||||
| ModelsDevRefreshed
|
| ModelsDevRefreshed
|
||||||
| IntegrationUpdated
|
| IntegrationUpdated
|
||||||
@@ -3914,8 +3891,21 @@ export type IntegrationConnectKeyInput = {
|
|||||||
readonly location?: {
|
readonly location?: {
|
||||||
readonly location?: { readonly directory?: string | undefined; readonly workspace?: string | undefined } | undefined
|
readonly location?: { readonly directory?: string | undefined; readonly workspace?: string | undefined } | undefined
|
||||||
}["location"]
|
}["location"]
|
||||||
readonly key: { readonly key: string; readonly label?: string | undefined }["key"]
|
readonly key: {
|
||||||
readonly label?: { readonly key: string; readonly label?: string | undefined }["label"]
|
readonly key: string
|
||||||
|
readonly answers: { readonly [x: string]: string | number | boolean | ReadonlyArray<string> }
|
||||||
|
readonly label?: string | undefined
|
||||||
|
}["key"]
|
||||||
|
readonly answers: {
|
||||||
|
readonly key: string
|
||||||
|
readonly answers: { readonly [x: string]: string | number | boolean | ReadonlyArray<string> }
|
||||||
|
readonly label?: string | undefined
|
||||||
|
}["answers"]
|
||||||
|
readonly label?: {
|
||||||
|
readonly key: string
|
||||||
|
readonly answers: { readonly [x: string]: string | number | boolean | ReadonlyArray<string> }
|
||||||
|
readonly label?: string | undefined
|
||||||
|
}["label"]
|
||||||
}
|
}
|
||||||
|
|
||||||
export type IntegrationConnectKeyOutput = void
|
export type IntegrationConnectKeyOutput = void
|
||||||
@@ -3927,17 +3917,17 @@ export type IntegrationOauthConnectInput = {
|
|||||||
}["location"]
|
}["location"]
|
||||||
readonly methodID: {
|
readonly methodID: {
|
||||||
readonly methodID: string
|
readonly methodID: string
|
||||||
readonly inputs: { readonly [x: string]: string }
|
readonly answers: { readonly [x: string]: string | number | boolean | ReadonlyArray<string> }
|
||||||
readonly label?: string | undefined
|
readonly label?: string | undefined
|
||||||
}["methodID"]
|
}["methodID"]
|
||||||
readonly inputs: {
|
readonly answers: {
|
||||||
readonly methodID: string
|
readonly methodID: string
|
||||||
readonly inputs: { readonly [x: string]: string }
|
readonly answers: { readonly [x: string]: string | number | boolean | ReadonlyArray<string> }
|
||||||
readonly label?: string | undefined
|
readonly label?: string | undefined
|
||||||
}["inputs"]
|
}["answers"]
|
||||||
readonly label?: {
|
readonly label?: {
|
||||||
readonly methodID: string
|
readonly methodID: string
|
||||||
readonly inputs: { readonly [x: string]: string }
|
readonly answers: { readonly [x: string]: string | number | boolean | ReadonlyArray<string> }
|
||||||
readonly label?: string | undefined
|
readonly label?: string | undefined
|
||||||
}["label"]
|
}["label"]
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -148,6 +148,45 @@ test("experimental wellknown integration add uses the public HTTP contract", asy
|
|||||||
expect(await request?.json()).toEqual({ url: "https://example.com" })
|
expect(await request?.json()).toEqual({ url: "https://example.com" })
|
||||||
})
|
})
|
||||||
|
|
||||||
|
test("integration connections submit form answers", async () => {
|
||||||
|
const requests: Request[] = []
|
||||||
|
const client = OpenCode.make({
|
||||||
|
baseUrl: "http://localhost:3000",
|
||||||
|
fetch: async (input, init) => {
|
||||||
|
const request = input instanceof Request ? input : new Request(input, init)
|
||||||
|
requests.push(request)
|
||||||
|
if (request.url.endsWith("/connect/key")) return new Response(null, { status: 204 })
|
||||||
|
return Response.json({
|
||||||
|
location: { directory: "/tmp/project", project: { id: "proj_test", directory: "/tmp/project" } },
|
||||||
|
data: {
|
||||||
|
attemptID: "con_test",
|
||||||
|
url: "https://example.com/authorize",
|
||||||
|
instructions: "Authorize",
|
||||||
|
mode: "auto",
|
||||||
|
time: { created: 1, expires: 2 },
|
||||||
|
},
|
||||||
|
})
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
await client.integration.connect.key({
|
||||||
|
integrationID: "cloudflare-workers-ai",
|
||||||
|
key: "secret",
|
||||||
|
answers: { accountId: "account" },
|
||||||
|
})
|
||||||
|
await client.integration.oauth.connect({
|
||||||
|
integrationID: "github-copilot",
|
||||||
|
methodID: "device",
|
||||||
|
answers: { deploymentType: "enterprise", enabled: true, scopes: ["read:user"] },
|
||||||
|
})
|
||||||
|
|
||||||
|
expect(await requests[0].json()).toEqual({ key: "secret", answers: { accountId: "account" } })
|
||||||
|
expect(await requests[1].json()).toEqual({
|
||||||
|
methodID: "device",
|
||||||
|
answers: { deploymentType: "enterprise", enabled: true, scopes: ["read:user"] },
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
test("health.stop sends exact replacement identity", async () => {
|
test("health.stop sends exact replacement identity", async () => {
|
||||||
let request: Request | undefined
|
let request: Request | undefined
|
||||||
const client = OpenCode.make({
|
const client = OpenCode.make({
|
||||||
|
|||||||
@@ -180,7 +180,7 @@ export const layer = Layer.effect(
|
|||||||
Effect.gen(function* () {
|
Effect.gen(function* () {
|
||||||
const entry = yield* find(input.id)
|
const entry = yield* find(input.id)
|
||||||
if (entry.state.status !== "pending") return yield* new AlreadySettledError({ id: input.id })
|
if (entry.state.status !== "pending") return yield* new AlreadySettledError({ id: input.id })
|
||||||
const invalid = validateAnswer(entry.form, input.answer)
|
const invalid = validateAnswer(entry.form.fields, input.answer)
|
||||||
if (invalid) return yield* new InvalidAnswerError({ id: input.id, message: invalid })
|
if (invalid) return yield* new InvalidAnswerError({ id: input.id, message: invalid })
|
||||||
const next: TerminalState = { status: "answered", answer: input.answer }
|
const next: TerminalState = { status: "answered", answer: input.answer }
|
||||||
yield* bus.publish(Form.Event.Replied, {
|
yield* bus.publish(Form.Event.Replied, {
|
||||||
@@ -227,12 +227,12 @@ export const locationLayer = layer
|
|||||||
|
|
||||||
export const node = makeLocationNode({ service: Service, layer, deps: [Bus.node] })
|
export const node = makeLocationNode({ service: Service, layer, deps: [Bus.node] })
|
||||||
|
|
||||||
function validateAnswer(form: Info, answer: Answer) {
|
export function validateAnswer(forms: ReadonlyArray<Form.Field>, answer: Answer) {
|
||||||
const fields = new Map(form.fields.map((field) => [field.key, field] as const))
|
const fields = new Map(forms.map((field) => [field.key, field] as const))
|
||||||
for (const key of Object.keys(answer)) {
|
for (const key of Object.keys(answer)) {
|
||||||
if (!fields.has(key)) return `Unknown form field: ${key}`
|
if (!fields.has(key)) return `Unknown form field: ${key}`
|
||||||
}
|
}
|
||||||
for (const field of form.fields) {
|
for (const field of forms) {
|
||||||
const value = answer[field.key]
|
const value = answer[field.key]
|
||||||
if (field.type === "external") {
|
if (field.type === "external") {
|
||||||
if (value !== true) return `External form field must be acknowledged: ${field.key}`
|
if (value !== true) return `External form field must be acknowledged: ${field.key}`
|
||||||
@@ -268,7 +268,7 @@ function matches(when: Form.When, value: Form.Value | undefined) {
|
|||||||
// carry a value matching that field's type, and use a declared option when the field's options
|
// carry a value matching that field's type, and use a declared option when the field's options
|
||||||
// are closed. Rejecting these at creation surfaces authoring mistakes to the caller instead of
|
// are closed. Rejecting these at creation surfaces authoring mistakes to the caller instead of
|
||||||
// silently never matching.
|
// silently never matching.
|
||||||
function validateFields(fields: ReadonlyArray<Form.Field>) {
|
export function validateFields(fields: ReadonlyArray<Form.Field>) {
|
||||||
if (fields.length === 0) return "Form must have at least one field"
|
if (fields.length === 0) return "Form must have at least one field"
|
||||||
const earlier = new Map<string, InputField>()
|
const earlier = new Map<string, InputField>()
|
||||||
const keys = new Set<string>()
|
const keys = new Set<string>()
|
||||||
|
|||||||
@@ -24,6 +24,7 @@ import { Bus } from "./bus"
|
|||||||
import { IntegrationConnection } from "./integration/connection"
|
import { IntegrationConnection } from "./integration/connection"
|
||||||
import { AppProcess } from "@opencode-ai/util/process"
|
import { AppProcess } from "@opencode-ai/util/process"
|
||||||
import { ChildProcess } from "effect/unstable/process"
|
import { ChildProcess } from "effect/unstable/process"
|
||||||
|
import { Form } from "./form"
|
||||||
|
|
||||||
export const ID = Integration.ID
|
export const ID = Integration.ID
|
||||||
export type ID = Integration.ID
|
export type ID = Integration.ID
|
||||||
@@ -34,18 +35,6 @@ export type MethodID = Integration.MethodID
|
|||||||
export const AttemptID = Integration.AttemptID
|
export const AttemptID = Integration.AttemptID
|
||||||
export type AttemptID = typeof AttemptID.Type
|
export type AttemptID = typeof AttemptID.Type
|
||||||
|
|
||||||
export const When = Integration.When
|
|
||||||
export type When = Integration.When
|
|
||||||
|
|
||||||
export const TextPrompt = Integration.TextPrompt
|
|
||||||
export type TextPrompt = Integration.TextPrompt
|
|
||||||
|
|
||||||
export const SelectPrompt = Integration.SelectPrompt
|
|
||||||
export type SelectPrompt = Integration.SelectPrompt
|
|
||||||
|
|
||||||
export const Prompt = Integration.Prompt
|
|
||||||
export type Prompt = Integration.Prompt
|
|
||||||
|
|
||||||
export const OAuthMethod = Integration.OAuthMethod
|
export const OAuthMethod = Integration.OAuthMethod
|
||||||
export type OAuthMethod = Integration.OAuthMethod
|
export type OAuthMethod = Integration.OAuthMethod
|
||||||
|
|
||||||
@@ -64,9 +53,6 @@ export type Method = Integration.Method
|
|||||||
export const Info = Integration.Info
|
export const Info = Integration.Info
|
||||||
export type Info = Integration.Info
|
export type Info = Integration.Info
|
||||||
|
|
||||||
export const Inputs = Integration.Inputs
|
|
||||||
export type Inputs = Integration.Inputs
|
|
||||||
|
|
||||||
export type OAuthAuthorization = {
|
export type OAuthAuthorization = {
|
||||||
readonly url: string
|
readonly url: string
|
||||||
readonly instructions: string
|
readonly instructions: string
|
||||||
@@ -85,7 +71,7 @@ export type OAuthAuthorization = {
|
|||||||
export interface OAuthImplementation {
|
export interface OAuthImplementation {
|
||||||
readonly integrationID: ID
|
readonly integrationID: ID
|
||||||
readonly method: OAuthMethod
|
readonly method: OAuthMethod
|
||||||
readonly authorize: (inputs: Inputs) => Effect.Effect<OAuthAuthorization, unknown, Scope.Scope>
|
readonly authorize: (answers: Form.Answer) => Effect.Effect<OAuthAuthorization, unknown, Scope.Scope>
|
||||||
readonly refresh?: (credential: Credential.OAuth) => Effect.Effect<Credential.OAuth, unknown>
|
readonly refresh?: (credential: Credential.OAuth) => Effect.Effect<Credential.OAuth, unknown>
|
||||||
readonly label?: (credential: Credential.OAuth) => string | undefined
|
readonly label?: (credential: Credential.OAuth) => string | undefined
|
||||||
}
|
}
|
||||||
@@ -175,6 +161,8 @@ export interface Interface extends State.Transformable<Draft> {
|
|||||||
readonly integrationID: ID
|
readonly integrationID: ID
|
||||||
/** Secret entered by the user. */
|
/** Secret entered by the user. */
|
||||||
readonly key: string
|
readonly key: string
|
||||||
|
/** Values collected from the method's form fields. */
|
||||||
|
readonly answers: Form.Answer
|
||||||
/** User-facing label for the stored credential. */
|
/** User-facing label for the stored credential. */
|
||||||
readonly label?: string
|
readonly label?: string
|
||||||
}) => Effect.Effect<void, AuthorizationError>
|
}) => Effect.Effect<void, AuthorizationError>
|
||||||
@@ -191,7 +179,7 @@ export interface Interface extends State.Transformable<Draft> {
|
|||||||
readonly connect: (input: {
|
readonly connect: (input: {
|
||||||
readonly integrationID: ID
|
readonly integrationID: ID
|
||||||
readonly methodID: MethodID
|
readonly methodID: MethodID
|
||||||
readonly inputs: Inputs
|
readonly answers: Form.Answer
|
||||||
readonly label?: string
|
readonly label?: string
|
||||||
}) => Effect.Effect<Attempt, AuthorizationError>
|
}) => Effect.Effect<Attempt, AuthorizationError>
|
||||||
/** Returns the current state of an OAuth attempt. */
|
/** Returns the current state of an OAuth attempt. */
|
||||||
@@ -356,7 +344,7 @@ const layer = Layer.effect(
|
|||||||
return [...credentials, ...env]
|
return [...credentials, ...env]
|
||||||
}
|
}
|
||||||
|
|
||||||
const project = (entry: Entry, connections: IntegrationConnection.Info[]) =>
|
const project = (entry: Entry, connections: IntegrationConnection.Info[]): Info =>
|
||||||
Info.make({
|
Info.make({
|
||||||
id: entry.ref.id,
|
id: entry.ref.id,
|
||||||
name: entry.ref.name,
|
name: entry.ref.name,
|
||||||
@@ -547,15 +535,20 @@ const layer = Layer.effect(
|
|||||||
const connectOAuth = Effect.fn("Integration.oauth.connect")(function* (input: {
|
const connectOAuth = Effect.fn("Integration.oauth.connect")(function* (input: {
|
||||||
readonly integrationID: ID
|
readonly integrationID: ID
|
||||||
readonly methodID: MethodID
|
readonly methodID: MethodID
|
||||||
readonly inputs: Inputs
|
readonly answers: Form.Answer
|
||||||
readonly label?: string
|
readonly label?: string
|
||||||
}) {
|
}) {
|
||||||
const method = state.get().integrations.get(input.integrationID)?.implementations.get(input.methodID)
|
const method = state.get().integrations.get(input.integrationID)?.implementations.get(input.methodID)
|
||||||
if (!method) {
|
if (!method) {
|
||||||
return yield* Effect.die(new Error(`OAuth method not found: ${input.integrationID}/${input.methodID}`))
|
return yield* Effect.die(new Error(`OAuth method not found: ${input.integrationID}/${input.methodID}`))
|
||||||
}
|
}
|
||||||
|
if (method.method.forms) {
|
||||||
|
const invalid =
|
||||||
|
Form.validateFields(method.method.forms) ?? Form.validateAnswer(method.method.forms, input.answers)
|
||||||
|
if (invalid) return yield* new AuthorizationError({ cause: new Error(invalid) })
|
||||||
|
}
|
||||||
const attemptScope = yield* Scope.fork(scope)
|
const attemptScope = yield* Scope.fork(scope)
|
||||||
const authorization = yield* authorize(method.authorize(input.inputs)).pipe(
|
const authorization = yield* authorize(method.authorize(input.answers)).pipe(
|
||||||
Scope.provide(attemptScope),
|
Scope.provide(attemptScope),
|
||||||
Effect.onExit((exit) => (Exit.isFailure(exit) ? Scope.close(attemptScope, exit) : Effect.void)),
|
Effect.onExit((exit) => (Exit.isFailure(exit) ? Scope.close(attemptScope, exit) : Effect.void)),
|
||||||
)
|
)
|
||||||
@@ -699,12 +692,23 @@ const layer = Layer.effect(
|
|||||||
const method = state
|
const method = state
|
||||||
.get()
|
.get()
|
||||||
.integrations.get(input.integrationID)
|
.integrations.get(input.integrationID)
|
||||||
?.methods.some((method) => method.type === "key")
|
?.methods.find((method) => method.type === "key")
|
||||||
if (!method) return yield* Effect.die(new Error(`Key method not found: ${input.integrationID}`))
|
if (!method) return yield* Effect.die(new Error(`Key method not found: ${input.integrationID}`))
|
||||||
|
if (method.type === "key" && method.forms) {
|
||||||
|
const invalid = Form.validateFields(method.forms) ?? Form.validateAnswer(method.forms, input.answers)
|
||||||
|
if (invalid) return yield* new AuthorizationError({ cause: new Error(invalid) })
|
||||||
|
}
|
||||||
|
if (method.type === "key" && !method.forms && Object.keys(input.answers).length > 0) {
|
||||||
|
return yield* new AuthorizationError({ cause: new Error("Key method does not accept form answers") })
|
||||||
|
}
|
||||||
yield* credentials.create({
|
yield* credentials.create({
|
||||||
integrationID: input.integrationID,
|
integrationID: input.integrationID,
|
||||||
label: input.label,
|
label: input.label,
|
||||||
value: Credential.Key.make({ type: "key", key: input.key }),
|
value: Credential.Key.make({
|
||||||
|
type: "key",
|
||||||
|
key: input.key,
|
||||||
|
...(Object.keys(input.answers).length > 0 ? { configuration: input.answers } : {}),
|
||||||
|
}),
|
||||||
})
|
})
|
||||||
yield* bus.publish(Integration.Event.ConnectionUpdated, { integrationID: input.integrationID })
|
yield* bus.publish(Integration.Event.ConnectionUpdated, { integrationID: input.integrationID })
|
||||||
yield* bus.publish(Integration.Event.Updated, {})
|
yield* bus.publish(Integration.Event.Updated, {})
|
||||||
|
|||||||
@@ -149,6 +149,7 @@ export const fromCatalogModel = (
|
|||||||
})
|
})
|
||||||
const packageName = Provider.packageName(resolved.package)
|
const packageName = Provider.packageName(resolved.package)
|
||||||
const key = apiKey(resolved, credential)
|
const key = apiKey(resolved, credential)
|
||||||
|
const configuration = credential?.type === "key" ? credential.configuration : undefined
|
||||||
|
|
||||||
if (Provider.isAISDK(resolved.package) && packageName === "@ai-sdk/openai") {
|
if (Provider.isAISDK(resolved.package) && packageName === "@ai-sdk/openai") {
|
||||||
return Effect.succeed(
|
return Effect.succeed(
|
||||||
@@ -175,7 +176,7 @@ export const fromCatalogModel = (
|
|||||||
.model({ id: resolved.modelID ?? resolved.id, compatibility: resolved.compatibility }),
|
.model({ id: resolved.modelID ?? resolved.id, compatibility: resolved.compatibility }),
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
const configured = { ...resolved.settings, ...credential?.metadata }
|
const configured = { ...resolved.settings, ...credential?.metadata, ...configuration }
|
||||||
const mapping = Provider.isAISDK(resolved.package)
|
const mapping = Provider.isAISDK(resolved.package)
|
||||||
? AISDKNative.map({
|
? AISDKNative.map({
|
||||||
packageName,
|
packageName,
|
||||||
@@ -190,6 +191,7 @@ export const fromCatalogModel = (
|
|||||||
draft.settings = Provider.mergeOverlay(draft.settings, {
|
draft.settings = Provider.mergeOverlay(draft.settings, {
|
||||||
...nativeCredentialSettings(resolved.package ?? "", credential),
|
...nativeCredentialSettings(resolved.package ?? "", credential),
|
||||||
...credential?.metadata,
|
...credential?.metadata,
|
||||||
|
...configuration,
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
return dependencies.loadAISDK(runtime).pipe(Effect.mapError(() => unsupported(resolved)))
|
return dependencies.loadAISDK(runtime).pipe(Effect.mapError(() => unsupported(resolved)))
|
||||||
|
|||||||
@@ -190,6 +190,7 @@ export const make = Effect.fn("PluginHost.make")(function* (plugin: import("../p
|
|||||||
integration.connection.key({
|
integration.connection.key({
|
||||||
integrationID: Integration.ID.make(input.integrationID),
|
integrationID: Integration.ID.make(input.integrationID),
|
||||||
key: input.key,
|
key: input.key,
|
||||||
|
answers: input.answers,
|
||||||
label: input.label,
|
label: input.label,
|
||||||
}),
|
}),
|
||||||
},
|
},
|
||||||
@@ -199,7 +200,7 @@ export const make = Effect.fn("PluginHost.make")(function* (plugin: import("../p
|
|||||||
integration.oauth.connect({
|
integration.oauth.connect({
|
||||||
integrationID: Integration.ID.make(input.integrationID),
|
integrationID: Integration.ID.make(input.integrationID),
|
||||||
methodID: Integration.MethodID.make(input.methodID),
|
methodID: Integration.MethodID.make(input.methodID),
|
||||||
inputs: input.inputs,
|
answers: input.answers,
|
||||||
label: input.label,
|
label: input.label,
|
||||||
}),
|
}),
|
||||||
),
|
),
|
||||||
@@ -362,9 +363,14 @@ function methodImplementation(input: IntegrationMethodRegistration): Integration
|
|||||||
const refresh = input.refresh
|
const refresh = input.refresh
|
||||||
return {
|
return {
|
||||||
integrationID: Integration.ID.make(input.integrationID),
|
integrationID: Integration.ID.make(input.integrationID),
|
||||||
method: { ...input.method, id: Integration.MethodID.make(input.method.id) },
|
method: Schema.decodeUnknownSync(Integration.OAuthMethod)({
|
||||||
authorize: (inputs) =>
|
id: Integration.MethodID.make(input.method.id),
|
||||||
input.authorize(inputs).pipe(
|
type: "oauth",
|
||||||
|
label: input.method.label,
|
||||||
|
...(input.method.forms === undefined ? {} : { forms: input.method.forms }),
|
||||||
|
}),
|
||||||
|
authorize: (answers) =>
|
||||||
|
input.authorize(answers).pipe(
|
||||||
Effect.map((authorization) => {
|
Effect.map((authorization) => {
|
||||||
if (authorization.mode === "auto") {
|
if (authorization.mode === "auto") {
|
||||||
return {
|
return {
|
||||||
@@ -396,7 +402,11 @@ function methodImplementation(input: IntegrationMethodRegistration): Integration
|
|||||||
}
|
}
|
||||||
return {
|
return {
|
||||||
integrationID: Integration.ID.make(input.integrationID),
|
integrationID: Integration.ID.make(input.integrationID),
|
||||||
method: { type: "key", label: input.method.label },
|
method: Schema.decodeUnknownSync(Integration.KeyMethod)({
|
||||||
|
type: "key",
|
||||||
|
...(input.method.label === undefined ? {} : { label: input.method.label }),
|
||||||
|
...(input.method.forms === undefined ? {} : { forms: input.method.forms }),
|
||||||
|
}),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -179,8 +179,8 @@ export function fromPromise(plugin: Plugin) {
|
|||||||
const refresh = input.refresh
|
const refresh = input.refresh
|
||||||
draft.method.update({
|
draft.method.update({
|
||||||
...input,
|
...input,
|
||||||
authorize: (inputs) =>
|
authorize: (answers) =>
|
||||||
Effect.promise(() => input.authorize(inputs)).pipe(
|
Effect.promise(() => input.authorize(answers)).pipe(
|
||||||
Effect.map((authorization) =>
|
Effect.map((authorization) =>
|
||||||
authorization.mode === "auto"
|
authorization.mode === "auto"
|
||||||
? {
|
? {
|
||||||
@@ -359,11 +359,17 @@ type Wire<Value> = unknown extends Value
|
|||||||
? Value
|
? Value
|
||||||
: Value extends DateTime.DateTime
|
: Value extends DateTime.DateTime
|
||||||
? number
|
? number
|
||||||
: Value extends ReadonlyArray<infer Item>
|
: Value extends readonly [infer Head, ...infer Tail]
|
||||||
? Array<Wire<Item>>
|
? [Wire<Head>, ...WireTuple<Tail>]
|
||||||
: Value extends object
|
: Value extends ReadonlyArray<infer Item>
|
||||||
? { -readonly [Key in keyof Value]: Wire<Value[Key]> }
|
? Array<Wire<Item>>
|
||||||
: Value
|
: Value extends object
|
||||||
|
? { -readonly [Key in keyof Value]: Wire<Value[Key]> }
|
||||||
|
: Value
|
||||||
|
|
||||||
|
type WireTuple<Value extends ReadonlyArray<unknown>> = {
|
||||||
|
-readonly [Key in keyof Value]: Wire<Value[Key]>
|
||||||
|
}
|
||||||
|
|
||||||
function wire<Value>(value: Value): Wire<Value>
|
function wire<Value>(value: Value): Wire<Value>
|
||||||
function wire(value: unknown): unknown {
|
function wire(value: unknown): unknown {
|
||||||
|
|||||||
@@ -1,6 +1,10 @@
|
|||||||
import { Effect } from "effect"
|
import { Effect } from "effect"
|
||||||
import { define } from "@opencode-ai/plugin/effect/plugin"
|
import { define } from "@opencode-ai/plugin/effect/plugin"
|
||||||
|
import type { Form } from "@opencode-ai/schema/form"
|
||||||
import { Provider } from "../../provider"
|
import { Provider } from "../../provider"
|
||||||
|
import type { DeepMutable } from "../../schema"
|
||||||
|
import { iife } from "../../util/iife"
|
||||||
|
import { configuredSettings } from "./configured"
|
||||||
|
|
||||||
function selectLanguage(sdk: any, modelID: string, useChat: boolean) {
|
function selectLanguage(sdk: any, modelID: string, useChat: boolean) {
|
||||||
if (useChat && sdk.chat) return sdk.chat(modelID)
|
if (useChat && sdk.chat) return sdk.chat(modelID)
|
||||||
@@ -13,6 +17,29 @@ function selectLanguage(sdk: any, modelID: string, useChat: boolean) {
|
|||||||
export const AzurePlugin = define({
|
export const AzurePlugin = define({
|
||||||
id: "opencode.provider.azure",
|
id: "opencode.provider.azure",
|
||||||
effect: Effect.fn(function* (ctx) {
|
effect: Effect.fn(function* (ctx) {
|
||||||
|
const configured = yield* configuredSettings(Provider.ID.azure)
|
||||||
|
const forms = iife((): DeepMutable<Form.Fields> | undefined => {
|
||||||
|
if (resolveResourceName(configured) || typeof configured?.baseURL === "string") return
|
||||||
|
return [
|
||||||
|
{
|
||||||
|
type: "string",
|
||||||
|
key: "resourceName",
|
||||||
|
title: "Enter Azure Resource Name",
|
||||||
|
placeholder: "e.g. my-models",
|
||||||
|
required: true,
|
||||||
|
},
|
||||||
|
]
|
||||||
|
})
|
||||||
|
yield* ctx.integration.transform((draft) => {
|
||||||
|
draft.method.update({
|
||||||
|
integrationID: Provider.ID.azure,
|
||||||
|
method: {
|
||||||
|
type: "key",
|
||||||
|
label: "API key",
|
||||||
|
forms,
|
||||||
|
},
|
||||||
|
})
|
||||||
|
})
|
||||||
yield* ctx.catalog.transform((evt) => {
|
yield* ctx.catalog.transform((evt) => {
|
||||||
for (const item of evt.provider.list()) {
|
for (const item of evt.provider.list()) {
|
||||||
if (item.provider.id !== Provider.ID.azure && Provider.packageName(item.provider.package) !== "@ai-sdk/azure")
|
if (item.provider.id !== Provider.ID.azure && Provider.packageName(item.provider.package) !== "@ai-sdk/azure")
|
||||||
|
|||||||
@@ -2,10 +2,54 @@ import os from "os"
|
|||||||
import { App } from "../../app"
|
import { App } from "../../app"
|
||||||
import { Effect, Option, Schema } from "effect"
|
import { Effect, Option, Schema } from "effect"
|
||||||
import { define } from "@opencode-ai/plugin/effect/plugin"
|
import { define } from "@opencode-ai/plugin/effect/plugin"
|
||||||
|
import type { Form } from "@opencode-ai/schema/form"
|
||||||
|
import { Provider } from "../../provider"
|
||||||
|
import type { DeepMutable } from "../../schema"
|
||||||
|
import { iife } from "../../util/iife"
|
||||||
|
import { configuredSettings } from "./configured"
|
||||||
|
|
||||||
|
const providerID = Provider.ID.make("cloudflare-ai-gateway")
|
||||||
|
|
||||||
export const CloudflareAIGatewayPlugin = define({
|
export const CloudflareAIGatewayPlugin = define({
|
||||||
id: "opencode.provider.cloudflare-ai-gateway",
|
id: "opencode.provider.cloudflare-ai-gateway",
|
||||||
effect: Effect.fn(function* (ctx) {
|
effect: Effect.fn(function* (ctx) {
|
||||||
|
const configured = yield* configuredSettings(providerID)
|
||||||
|
const forms = iife((): DeepMutable<Form.Fields> | undefined => {
|
||||||
|
if (typeof configured?.baseURL === "string") return
|
||||||
|
const accountId = process.env.CLOUDFLARE_ACCOUNT_ID || stringOption(configured ?? {}, "accountId")
|
||||||
|
const gatewayId =
|
||||||
|
process.env.CLOUDFLARE_GATEWAY_ID ||
|
||||||
|
stringOption(configured ?? {}, "gatewayId") ||
|
||||||
|
stringOption(configured ?? {}, "gateway")
|
||||||
|
if (accountId && gatewayId) return
|
||||||
|
const accountIdForm = {
|
||||||
|
type: "string",
|
||||||
|
key: "accountId",
|
||||||
|
title: "Enter your Cloudflare Account ID",
|
||||||
|
placeholder: "e.g. 1234567890abcdef1234567890abcdef",
|
||||||
|
required: true,
|
||||||
|
} satisfies DeepMutable<Form.Field>
|
||||||
|
const gatewayIdForm = {
|
||||||
|
type: "string",
|
||||||
|
key: "gatewayId",
|
||||||
|
title: "Enter your Cloudflare AI Gateway ID",
|
||||||
|
placeholder: "e.g. my-gateway",
|
||||||
|
required: true,
|
||||||
|
} satisfies DeepMutable<Form.Field>
|
||||||
|
if (accountId) return [gatewayIdForm]
|
||||||
|
if (gatewayId) return [accountIdForm]
|
||||||
|
return [accountIdForm, gatewayIdForm]
|
||||||
|
})
|
||||||
|
yield* ctx.integration.transform((draft) => {
|
||||||
|
draft.method.update({
|
||||||
|
integrationID: providerID,
|
||||||
|
method: {
|
||||||
|
type: "key",
|
||||||
|
label: "Gateway API token",
|
||||||
|
forms,
|
||||||
|
},
|
||||||
|
})
|
||||||
|
})
|
||||||
yield* ctx.aisdk.hook(
|
yield* ctx.aisdk.hook(
|
||||||
"sdk",
|
"sdk",
|
||||||
Effect.fn(function* (evt) {
|
Effect.fn(function* (evt) {
|
||||||
@@ -46,7 +90,7 @@ const decodeJson = Schema.decodeUnknownOption(Schema.UnknownFromJsonString)
|
|||||||
|
|
||||||
function gatewayConfig(options: Record<string, unknown>): GatewayConfig | undefined {
|
function gatewayConfig(options: Record<string, unknown>): GatewayConfig | undefined {
|
||||||
const accountId = process.env.CLOUDFLARE_ACCOUNT_ID ?? stringOption(options, "accountId")
|
const accountId = process.env.CLOUDFLARE_ACCOUNT_ID ?? stringOption(options, "accountId")
|
||||||
// Credential projection copies key metadata into options. The prompt stores the
|
// Credential projection copies key metadata into options. The form stores the
|
||||||
// gateway as gatewayId, while older config examples may use gateway.
|
// gateway as gatewayId, while older config examples may use gateway.
|
||||||
const gatewayId =
|
const gatewayId =
|
||||||
process.env.CLOUDFLARE_GATEWAY_ID ?? stringOption(options, "gatewayId") ?? stringOption(options, "gateway")
|
process.env.CLOUDFLARE_GATEWAY_ID ?? stringOption(options, "gatewayId") ?? stringOption(options, "gateway")
|
||||||
|
|||||||
@@ -2,13 +2,40 @@ import os from "os"
|
|||||||
import { App } from "../../app"
|
import { App } from "../../app"
|
||||||
import { Effect } from "effect"
|
import { Effect } from "effect"
|
||||||
import { define } from "@opencode-ai/plugin/effect/plugin"
|
import { define } from "@opencode-ai/plugin/effect/plugin"
|
||||||
|
import type { Form } from "@opencode-ai/schema/form"
|
||||||
import { Provider } from "../../provider"
|
import { Provider } from "../../provider"
|
||||||
|
import type { DeepMutable } from "../../schema"
|
||||||
|
import { iife } from "../../util/iife"
|
||||||
|
import { configuredSettings } from "./configured"
|
||||||
|
|
||||||
const providerID = Provider.ID.make("cloudflare-workers-ai")
|
const providerID = Provider.ID.make("cloudflare-workers-ai")
|
||||||
|
|
||||||
export const CloudflareWorkersAIPlugin = define({
|
export const CloudflareWorkersAIPlugin = define({
|
||||||
id: "opencode.provider.cloudflare-workers-ai",
|
id: "opencode.provider.cloudflare-workers-ai",
|
||||||
effect: Effect.fn(function* (ctx) {
|
effect: Effect.fn(function* (ctx) {
|
||||||
|
const configured = yield* configuredSettings(providerID)
|
||||||
|
const forms = iife((): DeepMutable<Form.Fields> | undefined => {
|
||||||
|
if (typeof configured?.baseURL === "string" || resolveAccountId(configured ?? {})) return
|
||||||
|
return [
|
||||||
|
{
|
||||||
|
type: "string",
|
||||||
|
key: "accountId",
|
||||||
|
title: "Enter your Cloudflare Account ID",
|
||||||
|
placeholder: "e.g. 1234567890abcdef1234567890abcdef",
|
||||||
|
required: true,
|
||||||
|
},
|
||||||
|
]
|
||||||
|
})
|
||||||
|
yield* ctx.integration.transform((draft) => {
|
||||||
|
draft.method.update({
|
||||||
|
integrationID: providerID,
|
||||||
|
method: {
|
||||||
|
type: "key",
|
||||||
|
label: "API key",
|
||||||
|
forms,
|
||||||
|
},
|
||||||
|
})
|
||||||
|
})
|
||||||
yield* ctx.catalog.transform((evt) => {
|
yield* ctx.catalog.transform((evt) => {
|
||||||
const item = evt.provider.get(providerID)
|
const item = evt.provider.get(providerID)
|
||||||
if (!item) return
|
if (!item) return
|
||||||
|
|||||||
@@ -0,0 +1,15 @@
|
|||||||
|
import { Effect, Option } from "effect"
|
||||||
|
import type { Document } from "@opencode-ai/schema/config"
|
||||||
|
import { Catalog } from "../../catalog"
|
||||||
|
import { Config } from "../../config"
|
||||||
|
import { Provider } from "../../provider"
|
||||||
|
|
||||||
|
export const configuredSettings = Effect.fn("ProviderPlugin.configuredSettings")(function* (id: Provider.ID) {
|
||||||
|
const catalog = yield* Catalog.Service
|
||||||
|
const current = (yield* catalog.provider.get(id))?.settings
|
||||||
|
const service = yield* Effect.serviceOption(Config.Service)
|
||||||
|
const entries = Option.isSome(service) ? yield* service.value.entries() : []
|
||||||
|
return entries
|
||||||
|
.filter((entry): entry is Document => entry.type === "document")
|
||||||
|
.reduce((settings, entry) => Provider.mergeOverlay(settings, entry.info.providers?.[id]?.settings), current)
|
||||||
|
})
|
||||||
@@ -47,30 +47,33 @@ const oauth = (app: App.Info) =>
|
|||||||
id: methodID,
|
id: methodID,
|
||||||
type: "oauth",
|
type: "oauth",
|
||||||
label: "Login with GitHub Copilot",
|
label: "Login with GitHub Copilot",
|
||||||
prompts: [
|
forms: [
|
||||||
{
|
{
|
||||||
type: "select",
|
type: "string",
|
||||||
key: "deploymentType",
|
key: "deploymentType",
|
||||||
message: "Select GitHub deployment type",
|
title: "Select GitHub deployment type",
|
||||||
|
required: true,
|
||||||
options: [
|
options: [
|
||||||
{ label: "GitHub.com", value: "github.com", hint: "Public" },
|
{ label: "GitHub.com", value: "github.com", description: "Public" },
|
||||||
{ label: "GitHub Enterprise", value: "enterprise", hint: "Data residency or self-hosted" },
|
{ label: "GitHub Enterprise", value: "enterprise", description: "Data residency or self-hosted" },
|
||||||
],
|
],
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
type: "text",
|
type: "string",
|
||||||
key: "enterpriseUrl",
|
key: "enterpriseUrl",
|
||||||
message: "Enter your GitHub Enterprise URL or domain",
|
title: "Enter your GitHub Enterprise URL or domain",
|
||||||
placeholder: "company.ghe.com or https://company.ghe.com",
|
placeholder: "company.ghe.com or https://company.ghe.com",
|
||||||
when: { key: "deploymentType", op: "eq", value: "enterprise" },
|
required: true,
|
||||||
|
when: [{ key: "deploymentType", op: "eq", value: "enterprise" }],
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
},
|
},
|
||||||
authorize: (inputs) =>
|
authorize: (answers) =>
|
||||||
Effect.gen(function* () {
|
Effect.gen(function* () {
|
||||||
const enterprise = inputs.deploymentType === "enterprise"
|
const enterprise = answers.deploymentType === "enterprise"
|
||||||
if (enterprise && !inputs.enterpriseUrl) return yield* Effect.fail(new Error("Enterprise URL is required"))
|
const enterpriseUrl = typeof answers.enterpriseUrl === "string" ? answers.enterpriseUrl : undefined
|
||||||
const domain = enterprise ? normalizeDomain(inputs.enterpriseUrl ?? "") : "github.com"
|
if (enterprise && !enterpriseUrl) return yield* Effect.fail(new Error("Enterprise URL is required"))
|
||||||
|
const domain = enterprise ? normalizeDomain(enterpriseUrl ?? "") : "github.com"
|
||||||
const urls = oauthURLs(domain)
|
const urls = oauthURLs(domain)
|
||||||
const device = yield* request(urls.device, {
|
const device = yield* request(urls.device, {
|
||||||
method: "POST",
|
method: "POST",
|
||||||
|
|||||||
@@ -43,9 +43,9 @@ function oauth(http: HttpClient.HttpClient) {
|
|||||||
type: "oauth",
|
type: "oauth",
|
||||||
label: "OpenCode Console account",
|
label: "OpenCode Console account",
|
||||||
},
|
},
|
||||||
authorize: (inputs) =>
|
authorize: (answers) =>
|
||||||
Effect.gen(function* () {
|
Effect.gen(function* () {
|
||||||
const server = yield* normalizeServer(inputs.server ?? defaultServer)
|
const server = yield* normalizeServer(typeof answers.server === "string" ? answers.server : defaultServer)
|
||||||
const device = yield* post(http, `${server}/auth/device/code`, { client_id: clientID }, Device)
|
const device = yield* post(http, `${server}/auth/device/code`, { client_id: clientID }, Device)
|
||||||
const verification = URL.canParse(device.verification_uri_complete)
|
const verification = URL.canParse(device.verification_uri_complete)
|
||||||
? new URL(device.verification_uri_complete)
|
? new URL(device.verification_uri_complete)
|
||||||
|
|||||||
@@ -140,7 +140,11 @@ describe("Integration", () => {
|
|||||||
yield* integrations.transform((editor) =>
|
yield* integrations.transform((editor) =>
|
||||||
editor.method.update({
|
editor.method.update({
|
||||||
integrationID,
|
integrationID,
|
||||||
method: { type: "key", label: "API key" },
|
method: {
|
||||||
|
type: "key",
|
||||||
|
label: "API key",
|
||||||
|
forms: [{ type: "string", key: "accountId", title: "Account ID", required: true }],
|
||||||
|
},
|
||||||
}),
|
}),
|
||||||
)
|
)
|
||||||
const updated = yield* bus
|
const updated = yield* bus
|
||||||
@@ -148,9 +152,17 @@ describe("Integration", () => {
|
|||||||
.pipe(Stream.take(1), Stream.runCollect, Effect.forkScoped)
|
.pipe(Stream.take(1), Stream.runCollect, Effect.forkScoped)
|
||||||
yield* Effect.yieldNow
|
yield* Effect.yieldNow
|
||||||
|
|
||||||
|
expect(
|
||||||
|
yield* integrations.connection.key({ integrationID, key: "secret", answers: {} }).pipe(
|
||||||
|
Effect.flip,
|
||||||
|
Effect.map((error) => error.cause),
|
||||||
|
),
|
||||||
|
).toEqual(expect.objectContaining({ message: "Missing required form field: accountId" }))
|
||||||
|
|
||||||
yield* integrations.connection.key({
|
yield* integrations.connection.key({
|
||||||
integrationID,
|
integrationID,
|
||||||
key: "secret",
|
key: "secret",
|
||||||
|
answers: { accountId: "account" },
|
||||||
label: "Work",
|
label: "Work",
|
||||||
})
|
})
|
||||||
|
|
||||||
@@ -158,7 +170,7 @@ describe("Integration", () => {
|
|||||||
expect.objectContaining({
|
expect.objectContaining({
|
||||||
integrationID,
|
integrationID,
|
||||||
label: "Work",
|
label: "Work",
|
||||||
value: Credential.Key.make({ type: "key", key: "secret" }),
|
value: Credential.Key.make({ type: "key", key: "secret", configuration: { accountId: "account" } }),
|
||||||
}),
|
}),
|
||||||
])
|
])
|
||||||
expect((yield* Fiber.join(updated)).length).toBe(1)
|
expect((yield* Fiber.join(updated)).length).toBe(1)
|
||||||
@@ -243,7 +255,7 @@ describe("Integration", () => {
|
|||||||
const attempt = yield* integrations.oauth.connect({
|
const attempt = yield* integrations.oauth.connect({
|
||||||
integrationID,
|
integrationID,
|
||||||
methodID,
|
methodID,
|
||||||
inputs: {},
|
answers: {},
|
||||||
label: "Personal",
|
label: "Personal",
|
||||||
})
|
})
|
||||||
expect(attempt.mode).toBe("code")
|
expect(attempt.mode).toBe("code")
|
||||||
@@ -289,7 +301,7 @@ describe("Integration", () => {
|
|||||||
}),
|
}),
|
||||||
)
|
)
|
||||||
|
|
||||||
const attempt = yield* integrations.oauth.connect({ integrationID, methodID, inputs: {} })
|
const attempt = yield* integrations.oauth.connect({ integrationID, methodID, answers: {} })
|
||||||
expect(
|
expect(
|
||||||
yield* integrations.oauth.complete({ integrationID, attemptID: attempt.attemptID }).pipe(Effect.flip),
|
yield* integrations.oauth.complete({ integrationID, attemptID: attempt.attemptID }).pipe(Effect.flip),
|
||||||
).toBeInstanceOf(Integration.CodeRequiredError)
|
).toBeInstanceOf(Integration.CodeRequiredError)
|
||||||
@@ -327,7 +339,7 @@ describe("Integration", () => {
|
|||||||
}),
|
}),
|
||||||
)
|
)
|
||||||
|
|
||||||
const attempt = yield* integrations.oauth.connect({ integrationID, methodID, inputs: {} })
|
const attempt = yield* integrations.oauth.connect({ integrationID, methodID, answers: {} })
|
||||||
yield* Effect.yieldNow
|
yield* Effect.yieldNow
|
||||||
expect(yield* integrations.oauth.status({ integrationID, attemptID: attempt.attemptID })).toEqual({
|
expect(yield* integrations.oauth.status({ integrationID, attemptID: attempt.attemptID })).toEqual({
|
||||||
status: "complete",
|
status: "complete",
|
||||||
@@ -365,7 +377,7 @@ describe("Integration", () => {
|
|||||||
}),
|
}),
|
||||||
)
|
)
|
||||||
|
|
||||||
const attempt = yield* integrations.oauth.connect({ integrationID, methodID, inputs: {} })
|
const attempt = yield* integrations.oauth.connect({ integrationID, methodID, answers: {} })
|
||||||
const exit = yield* integrations.oauth
|
const exit = yield* integrations.oauth
|
||||||
.complete({ integrationID, attemptID: attempt.attemptID, code: "1234" })
|
.complete({ integrationID, attemptID: attempt.attemptID, code: "1234" })
|
||||||
.pipe(Effect.exit)
|
.pipe(Effect.exit)
|
||||||
@@ -401,7 +413,7 @@ describe("Integration", () => {
|
|||||||
}),
|
}),
|
||||||
)
|
)
|
||||||
|
|
||||||
const attempt = yield* integrations.oauth.connect({ integrationID, methodID, inputs: {} })
|
const attempt = yield* integrations.oauth.connect({ integrationID, methodID, answers: {} })
|
||||||
expect(attempt.time.expires - attempt.time.created).toBe(Duration.toMillis(Duration.minutes(10)))
|
expect(attempt.time.expires - attempt.time.created).toBe(Duration.toMillis(Duration.minutes(10)))
|
||||||
yield* TestClock.adjust(Duration.minutes(10))
|
yield* TestClock.adjust(Duration.minutes(10))
|
||||||
yield* Effect.yieldNow
|
yield* Effect.yieldNow
|
||||||
@@ -442,7 +454,7 @@ describe("Integration", () => {
|
|||||||
}),
|
}),
|
||||||
)
|
)
|
||||||
|
|
||||||
const attempt = yield* integrations.oauth.connect({ integrationID, methodID, inputs: {} })
|
const attempt = yield* integrations.oauth.connect({ integrationID, methodID, answers: {} })
|
||||||
expect(attempt.time).toEqual({ created, expires: expiresAt })
|
expect(attempt.time).toEqual({ created, expires: expiresAt })
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -736,7 +736,11 @@ describe("ModelResolver", () => {
|
|||||||
headers: { "x-aisdk": "header" },
|
headers: { "x-aisdk": "header" },
|
||||||
body: { custom: true },
|
body: { custom: true },
|
||||||
}),
|
}),
|
||||||
Credential.Key.make({ type: "key", key: "fallback-secret" }),
|
Credential.Key.make({
|
||||||
|
type: "key",
|
||||||
|
key: "fallback-secret",
|
||||||
|
configuration: { accountId: "account" },
|
||||||
|
}),
|
||||||
{
|
{
|
||||||
loadAISDK: (runtime) =>
|
loadAISDK: (runtime) =>
|
||||||
Effect.sync(() => {
|
Effect.sync(() => {
|
||||||
@@ -745,7 +749,7 @@ describe("ModelResolver", () => {
|
|||||||
modelID: "mistral-api-model",
|
modelID: "mistral-api-model",
|
||||||
providerID: "test-provider",
|
providerID: "test-provider",
|
||||||
package: Provider.aisdk("@ai-sdk/mistral"),
|
package: Provider.aisdk("@ai-sdk/mistral"),
|
||||||
settings: { project: "test", apiKey: "fallback-secret" },
|
settings: { project: "test", apiKey: "fallback-secret", accountId: "account" },
|
||||||
headers: { "x-aisdk": "header" },
|
headers: { "x-aisdk": "header" },
|
||||||
body: { custom: true },
|
body: { custom: true },
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -10,7 +10,7 @@ import { Project } from "@opencode-ai/core/project"
|
|||||||
import { Provider } from "@opencode-ai/core/provider"
|
import { Provider } from "@opencode-ai/core/provider"
|
||||||
import { AbsolutePath } from "@opencode-ai/core/schema"
|
import { AbsolutePath } from "@opencode-ai/core/schema"
|
||||||
import { WebSearch } from "@opencode-ai/core/websearch"
|
import { WebSearch } from "@opencode-ai/core/websearch"
|
||||||
import { Effect, Stream } from "effect"
|
import { Effect, Schema, Stream } from "effect"
|
||||||
|
|
||||||
type Overrides = Partial<Omit<Plugin.Context, "options" | "session">> & {
|
type Overrides = Partial<Omit<Plugin.Context, "options" | "session">> & {
|
||||||
readonly session?: Partial<Plugin.Context["session"]>
|
readonly session?: Partial<Plugin.Context["session"]>
|
||||||
@@ -285,9 +285,9 @@ export function integrationHost(integration: Integration.Interface): Plugin.Cont
|
|||||||
const refresh = input.refresh
|
const refresh = input.refresh
|
||||||
draft.method.update({
|
draft.method.update({
|
||||||
integrationID: Integration.ID.make(input.integrationID),
|
integrationID: Integration.ID.make(input.integrationID),
|
||||||
method: { ...input.method, id: methodID },
|
method: oauthMethod(input.method, methodID),
|
||||||
authorize: (inputs) =>
|
authorize: (answers) =>
|
||||||
input.authorize(inputs).pipe(
|
input.authorize(answers).pipe(
|
||||||
Effect.map((authorization) => {
|
Effect.map((authorization) => {
|
||||||
if (authorization.mode === "auto") {
|
if (authorization.mode === "auto") {
|
||||||
return {
|
return {
|
||||||
@@ -353,7 +353,7 @@ export function integrationHost(integration: Integration.Interface): Plugin.Cont
|
|||||||
}
|
}
|
||||||
draft.method.update({
|
draft.method.update({
|
||||||
integrationID: Integration.ID.make(input.integrationID),
|
integrationID: Integration.ID.make(input.integrationID),
|
||||||
method: input.method,
|
method: keyMethod(input.method),
|
||||||
})
|
})
|
||||||
},
|
},
|
||||||
remove: (id, item) => draft.method.remove(Integration.ID.make(id), internalMethod(item)),
|
remove: (id, item) => draft.method.remove(Integration.ID.make(id), internalMethod(item)),
|
||||||
@@ -401,24 +401,21 @@ function oauthCredential(value: Credential.OAuth) {
|
|||||||
return Credential.OAuth.make({ ...value, methodID: Integration.MethodID.make(value.methodID) })
|
return Credential.OAuth.make({ ...value, methodID: Integration.MethodID.make(value.methodID) })
|
||||||
}
|
}
|
||||||
|
|
||||||
function method(value: Integration.Method) {
|
function method(value: Integration.Method): IntegrationMethodRegistration["method"] {
|
||||||
if (value.type === "env") return { type: value.type, names: [...value.names] }
|
if (value.type === "env") return { type: value.type, names: [...value.names] }
|
||||||
if (value.type === "key") return { type: value.type, label: value.label }
|
if (value.type === "key") return { type: value.type, label: value.label, forms: mutable(value.forms) }
|
||||||
if (value.type === "command") return { ...value, command: [...value.command] }
|
if (value.type === "command") return { ...value, command: [...value.command] }
|
||||||
return {
|
return {
|
||||||
type: value.type,
|
type: value.type,
|
||||||
id: value.id,
|
id: value.id,
|
||||||
label: value.label,
|
label: value.label,
|
||||||
prompts: value.prompts?.map((prompt) => {
|
forms: mutable(value.forms),
|
||||||
if (prompt.type === "text") return { ...prompt }
|
|
||||||
return { ...prompt, options: prompt.options.map((option) => ({ ...option })) }
|
|
||||||
}),
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function internalMethod(value: IntegrationMethodRegistration["method"]): Integration.Method {
|
function internalMethod(value: IntegrationMethodRegistration["method"]): Integration.Method {
|
||||||
if (value.type === "env") return value
|
if (value.type === "env") return value
|
||||||
if (value.type === "key") return value
|
if (value.type === "key") return keyMethod(value)
|
||||||
if (value.type === "command") {
|
if (value.type === "command") {
|
||||||
return {
|
return {
|
||||||
...value,
|
...value,
|
||||||
@@ -426,10 +423,41 @@ function internalMethod(value: IntegrationMethodRegistration["method"]): Integra
|
|||||||
command: [...value.command],
|
command: [...value.command],
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return {
|
return oauthMethod(value, Integration.MethodID.make(value.id))
|
||||||
...value,
|
}
|
||||||
id: Integration.MethodID.make(value.id),
|
|
||||||
}
|
type Mutable<Value> = Value extends readonly [infer Head, ...infer Tail]
|
||||||
|
? [Mutable<Head>, ...MutableTuple<Tail>]
|
||||||
|
: Value extends ReadonlyArray<infer Item>
|
||||||
|
? Array<Mutable<Item>>
|
||||||
|
: Value extends object
|
||||||
|
? { -readonly [Key in keyof Value]: Mutable<Value[Key]> }
|
||||||
|
: Value
|
||||||
|
|
||||||
|
type MutableTuple<Value extends ReadonlyArray<unknown>> = {
|
||||||
|
-readonly [Key in keyof Value]: Mutable<Value[Key]>
|
||||||
|
}
|
||||||
|
|
||||||
|
function mutable<Value>(value: Value): Mutable<Value>
|
||||||
|
function mutable(value: unknown): unknown {
|
||||||
|
return structuredClone(value)
|
||||||
|
}
|
||||||
|
|
||||||
|
function keyMethod(value: IntegrationMethodRegistration["method"] & { type: "key" }) {
|
||||||
|
return Schema.decodeUnknownSync(Integration.KeyMethod)({
|
||||||
|
type: "key",
|
||||||
|
...(value.label === undefined ? {} : { label: value.label }),
|
||||||
|
...(value.forms === undefined ? {} : { forms: value.forms }),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
function oauthMethod(value: IntegrationMethodRegistration["method"] & { type: "oauth" }, id: Integration.MethodID) {
|
||||||
|
return Schema.decodeUnknownSync(Integration.OAuthMethod)({
|
||||||
|
id,
|
||||||
|
type: "oauth",
|
||||||
|
label: value.label,
|
||||||
|
...(value.forms === undefined ? {} : { forms: value.forms }),
|
||||||
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
function agentInfo(value: Agent.Info) {
|
function agentInfo(value: Agent.Info) {
|
||||||
|
|||||||
@@ -8,6 +8,7 @@ import { Plugin } from "@opencode-ai/core/plugin"
|
|||||||
import { PluginHost } from "@opencode-ai/core/plugin/host"
|
import { PluginHost } from "@opencode-ai/core/plugin/host"
|
||||||
import { AzurePlugin } from "@opencode-ai/core/plugin/provider/azure"
|
import { AzurePlugin } from "@opencode-ai/core/plugin/provider/azure"
|
||||||
import { Provider } from "@opencode-ai/core/provider"
|
import { Provider } from "@opencode-ai/core/provider"
|
||||||
|
import { Integration } from "@opencode-ai/core/integration"
|
||||||
import { testEffect } from "../lib/effect"
|
import { testEffect } from "../lib/effect"
|
||||||
import { PluginTestLayer } from "./fixture"
|
import { PluginTestLayer } from "./fixture"
|
||||||
|
|
||||||
@@ -60,6 +61,27 @@ function fakeSelectorSdk(calls: string[]) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
describe("AzurePlugin", () => {
|
describe("AzurePlugin", () => {
|
||||||
|
it.effect("registers a resource name form when the environment does not provide one", () =>
|
||||||
|
withEnv({ AZURE_RESOURCE_NAME: undefined, AZURE_COGNITIVE_SERVICES_RESOURCE_NAME: undefined }, () =>
|
||||||
|
Effect.gen(function* () {
|
||||||
|
yield* addPlugin()
|
||||||
|
expect((yield* (yield* Integration.Service).get(Integration.ID.make("azure")))?.methods).toContainEqual({
|
||||||
|
type: "key",
|
||||||
|
label: "API key",
|
||||||
|
forms: [
|
||||||
|
{
|
||||||
|
type: "string",
|
||||||
|
key: "resourceName",
|
||||||
|
title: "Enter Azure Resource Name",
|
||||||
|
placeholder: "e.g. my-models",
|
||||||
|
required: true,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
})
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
|
||||||
it.effect("resolves resourceName from env", () =>
|
it.effect("resolves resourceName from env", () =>
|
||||||
withEnv({ AZURE_RESOURCE_NAME: "from-env" }, () =>
|
withEnv({ AZURE_RESOURCE_NAME: "from-env" }, () =>
|
||||||
Effect.gen(function* () {
|
Effect.gen(function* () {
|
||||||
@@ -195,7 +217,17 @@ describe("AzurePlugin", () => {
|
|||||||
Effect.gen(function* () {
|
Effect.gen(function* () {
|
||||||
const plugin = yield* Plugin.Service
|
const plugin = yield* Plugin.Service
|
||||||
const aisdk = yield* AISDK.Service
|
const aisdk = yield* AISDK.Service
|
||||||
|
const catalog = yield* Catalog.Service
|
||||||
|
yield* catalog.transform((catalog) =>
|
||||||
|
catalog.provider.update(Provider.ID.azure, (provider) => {
|
||||||
|
provider.settings = { ...provider.settings, baseURL: "https://proxy.example.com/openai" }
|
||||||
|
}),
|
||||||
|
)
|
||||||
yield* addPlugin()
|
yield* addPlugin()
|
||||||
|
expect((yield* (yield* Integration.Service).get(Integration.ID.make("azure")))?.methods).toContainEqual({
|
||||||
|
type: "key",
|
||||||
|
label: "API key",
|
||||||
|
})
|
||||||
const result = yield* aisdk.runSDK({
|
const result = yield* aisdk.runSDK({
|
||||||
model: Model.Info.make({
|
model: Model.Info.make({
|
||||||
...Model.Info.default(Provider.ID.azure, Model.ID.make("deployment")),
|
...Model.Info.default(Provider.ID.azure, Model.ID.make("deployment")),
|
||||||
|
|||||||
@@ -1,11 +1,13 @@
|
|||||||
import { AISDK } from "@opencode-ai/core/aisdk"
|
import { AISDK } from "@opencode-ai/core/aisdk"
|
||||||
import { describe, expect, mock } from "bun:test"
|
import { describe, expect, mock } from "bun:test"
|
||||||
import { Effect } from "effect"
|
import { Effect } from "effect"
|
||||||
|
import { Catalog } from "@opencode-ai/core/catalog"
|
||||||
import { Model } from "@opencode-ai/core/model"
|
import { Model } from "@opencode-ai/core/model"
|
||||||
import { Plugin } from "@opencode-ai/core/plugin"
|
import { Plugin } from "@opencode-ai/core/plugin"
|
||||||
import { PluginHost } from "@opencode-ai/core/plugin/host"
|
import { PluginHost } from "@opencode-ai/core/plugin/host"
|
||||||
import { CloudflareAIGatewayPlugin } from "@opencode-ai/core/plugin/provider/cloudflare-ai-gateway"
|
import { CloudflareAIGatewayPlugin } from "@opencode-ai/core/plugin/provider/cloudflare-ai-gateway"
|
||||||
import { Provider } from "@opencode-ai/core/provider"
|
import { Provider } from "@opencode-ai/core/provider"
|
||||||
|
import { Integration } from "@opencode-ai/core/integration"
|
||||||
import { testEffect } from "../lib/effect"
|
import { testEffect } from "../lib/effect"
|
||||||
import { PluginTestLayer } from "./fixture"
|
import { PluginTestLayer } from "./fixture"
|
||||||
|
|
||||||
@@ -102,6 +104,24 @@ mock.module("ai-gateway-provider/providers/unified", () => ({
|
|||||||
}))
|
}))
|
||||||
|
|
||||||
describe("CloudflareAIGatewayPlugin", () => {
|
describe("CloudflareAIGatewayPlugin", () => {
|
||||||
|
it.effect("registers account and gateway forms when the environment does not provide them", () =>
|
||||||
|
withEnv({ CLOUDFLARE_ACCOUNT_ID: undefined, CLOUDFLARE_GATEWAY_ID: undefined }, () =>
|
||||||
|
Effect.gen(function* () {
|
||||||
|
yield* addPlugin()
|
||||||
|
expect(
|
||||||
|
(yield* (yield* Integration.Service).get(Integration.ID.make("cloudflare-ai-gateway")))?.methods,
|
||||||
|
).toContainEqual({
|
||||||
|
type: "key",
|
||||||
|
label: "Gateway API token",
|
||||||
|
forms: [
|
||||||
|
expect.objectContaining({ type: "string", key: "accountId", required: true }),
|
||||||
|
expect.objectContaining({ type: "string", key: "gatewayId", required: true }),
|
||||||
|
],
|
||||||
|
})
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
|
||||||
it.effect("requires account, gateway, and token before creating the unified SDK", () =>
|
it.effect("requires account, gateway, and token before creating the unified SDK", () =>
|
||||||
withEnv(
|
withEnv(
|
||||||
{
|
{
|
||||||
@@ -357,7 +377,16 @@ describe("CloudflareAIGatewayPlugin", () => {
|
|||||||
resetCalls()
|
resetCalls()
|
||||||
const plugin = yield* Plugin.Service
|
const plugin = yield* Plugin.Service
|
||||||
const aisdk = yield* AISDK.Service
|
const aisdk = yield* AISDK.Service
|
||||||
|
const catalog = yield* Catalog.Service
|
||||||
|
yield* catalog.transform((catalog) =>
|
||||||
|
catalog.provider.update(Provider.ID.make("cloudflare-ai-gateway"), (provider) => {
|
||||||
|
provider.settings = { ...provider.settings, baseURL: "https://proxy.example/v1" }
|
||||||
|
}),
|
||||||
|
)
|
||||||
yield* addPlugin()
|
yield* addPlugin()
|
||||||
|
expect(
|
||||||
|
(yield* (yield* Integration.Service).get(Integration.ID.make("cloudflare-ai-gateway")))?.methods,
|
||||||
|
).toContainEqual({ type: "key", label: "Gateway API token" })
|
||||||
|
|
||||||
const result = yield* aisdk.runSDK({
|
const result = yield* aisdk.runSDK({
|
||||||
model: Model.Info.make({
|
model: Model.Info.make({
|
||||||
|
|||||||
@@ -7,6 +7,7 @@ import { Plugin } from "@opencode-ai/core/plugin"
|
|||||||
import { PluginHost } from "@opencode-ai/core/plugin/host"
|
import { PluginHost } from "@opencode-ai/core/plugin/host"
|
||||||
import { CloudflareWorkersAIPlugin } from "@opencode-ai/core/plugin/provider/cloudflare-workers-ai"
|
import { CloudflareWorkersAIPlugin } from "@opencode-ai/core/plugin/provider/cloudflare-workers-ai"
|
||||||
import { Provider } from "@opencode-ai/core/provider"
|
import { Provider } from "@opencode-ai/core/provider"
|
||||||
|
import { Integration } from "@opencode-ai/core/integration"
|
||||||
import type { LanguageModelV3 } from "@ai-sdk/provider"
|
import type { LanguageModelV3 } from "@ai-sdk/provider"
|
||||||
import { testEffect } from "../lib/effect"
|
import { testEffect } from "../lib/effect"
|
||||||
import { PluginTestLayer } from "./fixture"
|
import { PluginTestLayer } from "./fixture"
|
||||||
@@ -79,6 +80,29 @@ function cloudflareHeaders(sdk: unknown, modelID = "@cf/model") {
|
|||||||
}
|
}
|
||||||
|
|
||||||
describe("CloudflareWorkersAIPlugin", () => {
|
describe("CloudflareWorkersAIPlugin", () => {
|
||||||
|
it.effect("registers an account form when the environment does not provide one", () =>
|
||||||
|
withEnv({ CLOUDFLARE_ACCOUNT_ID: undefined }, () =>
|
||||||
|
Effect.gen(function* () {
|
||||||
|
yield* addPlugin()
|
||||||
|
expect(
|
||||||
|
(yield* (yield* Integration.Service).get(Integration.ID.make("cloudflare-workers-ai")))?.methods,
|
||||||
|
).toContainEqual({
|
||||||
|
type: "key",
|
||||||
|
label: "API key",
|
||||||
|
forms: [
|
||||||
|
{
|
||||||
|
type: "string",
|
||||||
|
key: "accountId",
|
||||||
|
title: "Enter your Cloudflare Account ID",
|
||||||
|
placeholder: "e.g. 1234567890abcdef1234567890abcdef",
|
||||||
|
required: true,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
})
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
|
||||||
it.effect("maps account ID to endpoint URL and creates an OpenAI-compatible SDK", () =>
|
it.effect("maps account ID to endpoint URL and creates an OpenAI-compatible SDK", () =>
|
||||||
withEnv({ CLOUDFLARE_ACCOUNT_ID: "acct", CLOUDFLARE_API_KEY: "key" }, () =>
|
withEnv({ CLOUDFLARE_ACCOUNT_ID: "acct", CLOUDFLARE_API_KEY: "key" }, () =>
|
||||||
Effect.gen(function* () {
|
Effect.gen(function* () {
|
||||||
@@ -91,6 +115,9 @@ describe("CloudflareWorkersAIPlugin", () => {
|
|||||||
}),
|
}),
|
||||||
)
|
)
|
||||||
yield* addPlugin()
|
yield* addPlugin()
|
||||||
|
expect(
|
||||||
|
(yield* (yield* Integration.Service).get(Integration.ID.make("cloudflare-workers-ai")))?.methods,
|
||||||
|
).toContainEqual({ type: "key", label: "API key" })
|
||||||
const provider = required(yield* catalog.provider.get(Provider.ID.make("cloudflare-workers-ai")))
|
const provider = required(yield* catalog.provider.get(Provider.ID.make("cloudflare-workers-ai")))
|
||||||
const sdk = yield* aisdk.runSDK({
|
const sdk = yield* aisdk.runSDK({
|
||||||
model: Model.Info.make({
|
model: Model.Info.make({
|
||||||
@@ -135,7 +162,16 @@ describe("CloudflareWorkersAIPlugin", () => {
|
|||||||
Effect.gen(function* () {
|
Effect.gen(function* () {
|
||||||
const plugin = yield* Plugin.Service
|
const plugin = yield* Plugin.Service
|
||||||
const aisdk = yield* AISDK.Service
|
const aisdk = yield* AISDK.Service
|
||||||
|
const catalog = yield* Catalog.Service
|
||||||
|
yield* catalog.transform((catalog) =>
|
||||||
|
catalog.provider.update(Provider.ID.make("cloudflare-workers-ai"), (provider) => {
|
||||||
|
provider.settings = { ...provider.settings, baseURL: "https://proxy.example/v1" }
|
||||||
|
}),
|
||||||
|
)
|
||||||
yield* addPlugin()
|
yield* addPlugin()
|
||||||
|
expect(
|
||||||
|
(yield* (yield* Integration.Service).get(Integration.ID.make("cloudflare-workers-ai")))?.methods,
|
||||||
|
).toContainEqual({ type: "key", label: "API key" })
|
||||||
const result = yield* aisdk.runSDK({
|
const result = yield* aisdk.runSDK({
|
||||||
model: Model.Info.make({
|
model: Model.Info.make({
|
||||||
...Model.Info.default(Provider.ID.make("cloudflare-workers-ai"), Model.ID.make("@cf/model")),
|
...Model.Info.default(Provider.ID.make("cloudflare-workers-ai"), Model.ID.make("@cf/model")),
|
||||||
|
|||||||
@@ -57,7 +57,7 @@ describe("GithubCopilotPlugin", () => {
|
|||||||
id: Integration.MethodID.make("device"),
|
id: Integration.MethodID.make("device"),
|
||||||
type: "oauth",
|
type: "oauth",
|
||||||
label: "Login with GitHub Copilot",
|
label: "Login with GitHub Copilot",
|
||||||
prompts: expect.any(Array),
|
forms: expect.any(Array),
|
||||||
})
|
})
|
||||||
}),
|
}),
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -128,7 +128,7 @@ describe("OpencodePlugin", () => {
|
|||||||
const attempt = yield* integrations.oauth.connect({
|
const attempt = yield* integrations.oauth.connect({
|
||||||
integrationID,
|
integrationID,
|
||||||
methodID: Integration.MethodID.make("device"),
|
methodID: Integration.MethodID.make("device"),
|
||||||
inputs: { server: `${server.url.origin}/console///?ignored=true#ignored` },
|
answers: { server: `${server.url.origin}/console///?ignored=true#ignored` },
|
||||||
})
|
})
|
||||||
expect(attempt.url).toBe(`${server.url.origin}/verify`)
|
expect(attempt.url).toBe(`${server.url.origin}/verify`)
|
||||||
yield* eventually(
|
yield* eventually(
|
||||||
@@ -155,7 +155,7 @@ describe("OpencodePlugin", () => {
|
|||||||
.connect({
|
.connect({
|
||||||
integrationID: Integration.ID.make("opencode"),
|
integrationID: Integration.ID.make("opencode"),
|
||||||
methodID: Integration.MethodID.make("device"),
|
methodID: Integration.MethodID.make("device"),
|
||||||
inputs: { server: "ftp://console.example.com" },
|
answers: { server: "ftp://console.example.com" },
|
||||||
})
|
})
|
||||||
.pipe(Effect.flip)
|
.pipe(Effect.flip)
|
||||||
expect(error).toBeInstanceOf(Integration.AuthorizationError)
|
expect(error).toBeInstanceOf(Integration.AuthorizationError)
|
||||||
|
|||||||
@@ -67,7 +67,7 @@ describe("built-in web search providers", () => {
|
|||||||
name: "Exa",
|
name: "Exa",
|
||||||
methods: [{ type: "key" }, { type: "env", names: ["EXA_API_KEY"] }],
|
methods: [{ type: "key" }, { type: "env", names: ["EXA_API_KEY"] }],
|
||||||
})
|
})
|
||||||
yield* integrations.connection.key({ integrationID: Integration.ID.make("exa"), key: "exa secret" })
|
yield* integrations.connection.key({ integrationID: Integration.ID.make("exa"), key: "exa secret", answers: {} })
|
||||||
expect(yield* websearch.query({ query: "effect typescript", providerID: WebSearch.ID.make("exa") })).toEqual(
|
expect(yield* websearch.query({ query: "effect typescript", providerID: WebSearch.ID.make("exa") })).toEqual(
|
||||||
new WebSearch.Response({
|
new WebSearch.Response({
|
||||||
providerID: WebSearch.ID.make("exa"),
|
providerID: WebSearch.ID.make("exa"),
|
||||||
@@ -129,7 +129,11 @@ describe("built-in web search providers", () => {
|
|||||||
yield* WebSearchParallel.Plugin.effect(
|
yield* WebSearchParallel.Plugin.effect(
|
||||||
host({ integration: integrationHost(integrations), websearch: webSearchHost(websearch) }),
|
host({ integration: integrationHost(integrations), websearch: webSearchHost(websearch) }),
|
||||||
)
|
)
|
||||||
yield* integrations.connection.key({ integrationID: Integration.ID.make("parallel"), key: "parallel-secret" })
|
yield* integrations.connection.key({
|
||||||
|
integrationID: Integration.ID.make("parallel"),
|
||||||
|
key: "parallel-secret",
|
||||||
|
answers: {},
|
||||||
|
})
|
||||||
|
|
||||||
const output = yield* websearch.query({
|
const output = yield* websearch.query({
|
||||||
query: "effect layers",
|
query: "effect layers",
|
||||||
|
|||||||
@@ -90,15 +90,10 @@ test("Core reuses the canonical shared schemas", async () => {
|
|||||||
[coreFileSystem.Match, FileSystem.Match],
|
[coreFileSystem.Match, FileSystem.Match],
|
||||||
[coreIntegration.ID, Integration.ID],
|
[coreIntegration.ID, Integration.ID],
|
||||||
[coreIntegration.MethodID, Integration.MethodID],
|
[coreIntegration.MethodID, Integration.MethodID],
|
||||||
[coreIntegration.When, Integration.When],
|
|
||||||
[coreIntegration.TextPrompt, Integration.TextPrompt],
|
|
||||||
[coreIntegration.SelectPrompt, Integration.SelectPrompt],
|
|
||||||
[coreIntegration.Prompt, Integration.Prompt],
|
|
||||||
[coreIntegration.OAuthMethod, Integration.OAuthMethod],
|
[coreIntegration.OAuthMethod, Integration.OAuthMethod],
|
||||||
[coreIntegration.KeyMethod, Integration.KeyMethod],
|
[coreIntegration.KeyMethod, Integration.KeyMethod],
|
||||||
[coreIntegration.EnvMethod, Integration.EnvMethod],
|
[coreIntegration.EnvMethod, Integration.EnvMethod],
|
||||||
[coreIntegration.Method, Integration.Method],
|
[coreIntegration.Method, Integration.Method],
|
||||||
[coreIntegration.Inputs, Integration.Inputs],
|
|
||||||
[coreIntegration.Ref, Integration.Ref],
|
[coreIntegration.Ref, Integration.Ref],
|
||||||
[coreLocation.Ref, Location.Ref],
|
[coreLocation.Ref, Location.Ref],
|
||||||
[coreAI.ProviderMetadata, AI.ProviderMetadata],
|
[coreAI.ProviderMetadata, AI.ProviderMetadata],
|
||||||
|
|||||||
@@ -8,10 +8,10 @@ import type {
|
|||||||
} from "@opencode-ai/client"
|
} from "@opencode-ai/client"
|
||||||
import type { IntegrationApi } from "@opencode-ai/client/effect/api"
|
import type { IntegrationApi } from "@opencode-ai/client/effect/api"
|
||||||
import { Credential } from "@opencode-ai/schema/credential"
|
import { Credential } from "@opencode-ai/schema/credential"
|
||||||
|
import { Form } from "@opencode-ai/schema/form"
|
||||||
import type { Effect, Scope } from "effect"
|
import type { Effect, Scope } from "effect"
|
||||||
import type { Transform } from "./registration.js"
|
import type { Transform } from "./registration.js"
|
||||||
|
|
||||||
type IntegrationInputs = Record<string, string>
|
|
||||||
type IntegrationRef = { id: string; name: string }
|
type IntegrationRef = { id: string; name: string }
|
||||||
|
|
||||||
export type IntegrationOAuthAuthorization = {
|
export type IntegrationOAuthAuthorization = {
|
||||||
@@ -31,7 +31,7 @@ export type IntegrationOAuthAuthorization = {
|
|||||||
export type IntegrationOAuthMethodRegistration = {
|
export type IntegrationOAuthMethodRegistration = {
|
||||||
readonly integrationID: string
|
readonly integrationID: string
|
||||||
readonly method: IntegrationOAuthMethod
|
readonly method: IntegrationOAuthMethod
|
||||||
readonly authorize: (inputs: IntegrationInputs) => Effect.Effect<IntegrationOAuthAuthorization, unknown, Scope.Scope>
|
readonly authorize: (answers: Form.Answer) => Effect.Effect<IntegrationOAuthAuthorization, unknown, Scope.Scope>
|
||||||
readonly refresh?: (credential: Credential.OAuth) => Effect.Effect<Credential.OAuth, unknown>
|
readonly refresh?: (credential: Credential.OAuth) => Effect.Effect<Credential.OAuth, unknown>
|
||||||
readonly label?: (credential: Credential.OAuth) => string | undefined
|
readonly label?: (credential: Credential.OAuth) => string | undefined
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -8,9 +8,9 @@ import type {
|
|||||||
} from "@opencode-ai/client"
|
} from "@opencode-ai/client"
|
||||||
import type { IntegrationApi } from "@opencode-ai/client/promise/api"
|
import type { IntegrationApi } from "@opencode-ai/client/promise/api"
|
||||||
import { Credential } from "@opencode-ai/schema/credential"
|
import { Credential } from "@opencode-ai/schema/credential"
|
||||||
|
import { Form } from "@opencode-ai/schema/form"
|
||||||
import type { Transform } from "./registration.js"
|
import type { Transform } from "./registration.js"
|
||||||
|
|
||||||
type IntegrationInputs = Record<string, string>
|
|
||||||
type IntegrationRef = { id: string; name: string }
|
type IntegrationRef = { id: string; name: string }
|
||||||
|
|
||||||
export type IntegrationOAuthAuthorization = {
|
export type IntegrationOAuthAuthorization = {
|
||||||
@@ -31,7 +31,7 @@ export type IntegrationOAuthAuthorization = {
|
|||||||
export type IntegrationOAuthMethodRegistration = {
|
export type IntegrationOAuthMethodRegistration = {
|
||||||
readonly integrationID: string
|
readonly integrationID: string
|
||||||
readonly method: IntegrationOAuthMethod
|
readonly method: IntegrationOAuthMethod
|
||||||
readonly authorize: (inputs: IntegrationInputs) => Promise<IntegrationOAuthAuthorization>
|
readonly authorize: (answers: Form.Answer) => Promise<IntegrationOAuthAuthorization>
|
||||||
readonly refresh?: (credential: Credential.OAuth) => Promise<Credential.OAuth>
|
readonly refresh?: (credential: Credential.OAuth) => Promise<Credential.OAuth>
|
||||||
readonly label?: (credential: Credential.OAuth) => string | undefined
|
readonly label?: (credential: Credential.OAuth) => string | undefined
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,12 +1,11 @@
|
|||||||
import { Integration } from "@opencode-ai/schema/integration"
|
import { Integration } from "@opencode-ai/schema/integration"
|
||||||
import { Location } from "@opencode-ai/schema/location"
|
import { Location } from "@opencode-ai/schema/location"
|
||||||
|
import { Form } from "@opencode-ai/schema/form"
|
||||||
import { Schema } from "effect"
|
import { Schema } from "effect"
|
||||||
import { HttpApiEndpoint, HttpApiGroup, HttpApiSchema, OpenApi } from "effect/unstable/httpapi"
|
import { HttpApiEndpoint, HttpApiGroup, HttpApiSchema, OpenApi } from "effect/unstable/httpapi"
|
||||||
import { InvalidRequestError } from "../errors.js"
|
import { InvalidRequestError } from "../errors.js"
|
||||||
import { LocationQuery, locationQueryOpenApi } from "./location.js"
|
import { LocationQuery, locationQueryOpenApi } from "./location.js"
|
||||||
|
|
||||||
const Inputs = Schema.Record(Schema.String, Schema.String)
|
|
||||||
|
|
||||||
export const IntegrationGroup = HttpApiGroup.make("server.integration")
|
export const IntegrationGroup = HttpApiGroup.make("server.integration")
|
||||||
.add(
|
.add(
|
||||||
HttpApiEndpoint.get("integration.list", "/api/integration", {
|
HttpApiEndpoint.get("integration.list", "/api/integration", {
|
||||||
@@ -59,6 +58,7 @@ export const IntegrationGroup = HttpApiGroup.make("server.integration")
|
|||||||
query: LocationQuery,
|
query: LocationQuery,
|
||||||
payload: Schema.Struct({
|
payload: Schema.Struct({
|
||||||
key: Schema.String,
|
key: Schema.String,
|
||||||
|
answers: Form.Answer,
|
||||||
label: Schema.optional(Schema.String),
|
label: Schema.optional(Schema.String),
|
||||||
}),
|
}),
|
||||||
success: HttpApiSchema.NoContent,
|
success: HttpApiSchema.NoContent,
|
||||||
@@ -79,7 +79,7 @@ export const IntegrationGroup = HttpApiGroup.make("server.integration")
|
|||||||
query: LocationQuery,
|
query: LocationQuery,
|
||||||
payload: Schema.Struct({
|
payload: Schema.Struct({
|
||||||
methodID: Integration.MethodID,
|
methodID: Integration.MethodID,
|
||||||
inputs: Inputs,
|
answers: Form.Answer,
|
||||||
label: Schema.optional(Schema.String),
|
label: Schema.optional(Schema.String),
|
||||||
}),
|
}),
|
||||||
success: Location.response(Integration.Attempt),
|
success: Location.response(Integration.Attempt),
|
||||||
|
|||||||
@@ -5,6 +5,7 @@ import { optional } from "./schema.js"
|
|||||||
import { IntegrationMethodID } from "./integration-id.js"
|
import { IntegrationMethodID } from "./integration-id.js"
|
||||||
import { ascending } from "./identifier.js"
|
import { ascending } from "./identifier.js"
|
||||||
import { NonNegativeInt, statics } from "./schema.js"
|
import { NonNegativeInt, statics } from "./schema.js"
|
||||||
|
import { Form } from "./form.js"
|
||||||
|
|
||||||
export const ID = Schema.String.pipe(
|
export const ID = Schema.String.pipe(
|
||||||
Schema.brand("Credential.ID"),
|
Schema.brand("Credential.ID"),
|
||||||
@@ -27,6 +28,7 @@ export const Key = Schema.Struct({
|
|||||||
type: Schema.Literal("key"),
|
type: Schema.Literal("key"),
|
||||||
key: Schema.String,
|
key: Schema.String,
|
||||||
metadata: optional(Schema.Record(Schema.String, Schema.Unknown)),
|
metadata: optional(Schema.Record(Schema.String, Schema.Unknown)),
|
||||||
|
configuration: optional(Form.Answer),
|
||||||
}).annotate({ identifier: "Credential.Key" })
|
}).annotate({ identifier: "Credential.Key" })
|
||||||
|
|
||||||
export const Value = Schema.Union([OAuth, Key])
|
export const Value = Schema.Union([OAuth, Key])
|
||||||
|
|||||||
@@ -7,6 +7,7 @@ import { Connection } from "./connection.js"
|
|||||||
import { ascending } from "./identifier.js"
|
import { ascending } from "./identifier.js"
|
||||||
import { statics } from "./schema.js"
|
import { statics } from "./schema.js"
|
||||||
import { IntegrationID, IntegrationMethodID } from "./integration-id.js"
|
import { IntegrationID, IntegrationMethodID } from "./integration-id.js"
|
||||||
|
import { Form } from "./form.js"
|
||||||
|
|
||||||
export const ID = IntegrationID
|
export const ID = IntegrationID
|
||||||
export type ID = typeof ID.Type
|
export type ID = typeof ID.Type
|
||||||
@@ -14,46 +15,12 @@ export type ID = typeof ID.Type
|
|||||||
export const MethodID = IntegrationMethodID
|
export const MethodID = IntegrationMethodID
|
||||||
export type MethodID = typeof MethodID.Type
|
export type MethodID = typeof MethodID.Type
|
||||||
|
|
||||||
export interface When extends Schema.Schema.Type<typeof When> {}
|
|
||||||
export const When = Schema.Struct({
|
|
||||||
key: Schema.String,
|
|
||||||
op: Schema.Literals(["eq", "neq"]),
|
|
||||||
value: Schema.String,
|
|
||||||
}).annotate({ identifier: "Integration.When" })
|
|
||||||
|
|
||||||
export interface TextPrompt extends Schema.Schema.Type<typeof TextPrompt> {}
|
|
||||||
export const TextPrompt = Schema.Struct({
|
|
||||||
type: Schema.Literal("text"),
|
|
||||||
key: Schema.String,
|
|
||||||
message: Schema.String,
|
|
||||||
placeholder: optional(Schema.String),
|
|
||||||
when: optional(When),
|
|
||||||
}).annotate({ identifier: "Integration.TextPrompt" })
|
|
||||||
|
|
||||||
export interface SelectPrompt extends Schema.Schema.Type<typeof SelectPrompt> {}
|
|
||||||
export const SelectPrompt = Schema.Struct({
|
|
||||||
type: Schema.Literal("select"),
|
|
||||||
key: Schema.String,
|
|
||||||
message: Schema.String,
|
|
||||||
options: Schema.Array(
|
|
||||||
Schema.Struct({
|
|
||||||
label: Schema.String,
|
|
||||||
value: Schema.String,
|
|
||||||
hint: optional(Schema.String),
|
|
||||||
}),
|
|
||||||
),
|
|
||||||
when: optional(When),
|
|
||||||
}).annotate({ identifier: "Integration.SelectPrompt" })
|
|
||||||
|
|
||||||
export const Prompt = Schema.Union([TextPrompt, SelectPrompt]).pipe(Schema.toTaggedUnion("type"))
|
|
||||||
export type Prompt = typeof Prompt.Type
|
|
||||||
|
|
||||||
export interface OAuthMethod extends Schema.Schema.Type<typeof OAuthMethod> {}
|
export interface OAuthMethod extends Schema.Schema.Type<typeof OAuthMethod> {}
|
||||||
export const OAuthMethod = Schema.Struct({
|
export const OAuthMethod = Schema.Struct({
|
||||||
id: MethodID,
|
id: MethodID,
|
||||||
type: Schema.Literal("oauth"),
|
type: Schema.Literal("oauth"),
|
||||||
label: Schema.String,
|
label: Schema.String,
|
||||||
prompts: optional(Schema.Array(Prompt)),
|
forms: optional(Form.Fields),
|
||||||
}).annotate({ identifier: "Integration.OAuthMethod" })
|
}).annotate({ identifier: "Integration.OAuthMethod" })
|
||||||
|
|
||||||
export interface CommandMethod extends Schema.Schema.Type<typeof CommandMethod> {}
|
export interface CommandMethod extends Schema.Schema.Type<typeof CommandMethod> {}
|
||||||
@@ -68,6 +35,7 @@ export interface KeyMethod extends Schema.Schema.Type<typeof KeyMethod> {}
|
|||||||
export const KeyMethod = Schema.Struct({
|
export const KeyMethod = Schema.Struct({
|
||||||
type: Schema.Literal("key"),
|
type: Schema.Literal("key"),
|
||||||
label: optional(Schema.String),
|
label: optional(Schema.String),
|
||||||
|
forms: optional(Form.Fields),
|
||||||
}).annotate({ identifier: "Integration.KeyMethod" })
|
}).annotate({ identifier: "Integration.KeyMethod" })
|
||||||
|
|
||||||
export interface EnvMethod extends Schema.Schema.Type<typeof EnvMethod> {}
|
export interface EnvMethod extends Schema.Schema.Type<typeof EnvMethod> {}
|
||||||
@@ -81,9 +49,6 @@ export const Method = Schema.Union([OAuthMethod, CommandMethod, KeyMethod, EnvMe
|
|||||||
.annotate({ identifier: "Integration.Method" })
|
.annotate({ identifier: "Integration.Method" })
|
||||||
export type Method = typeof Method.Type
|
export type Method = typeof Method.Type
|
||||||
|
|
||||||
export const Inputs = Schema.Record(Schema.String, Schema.String).annotate({ identifier: "Integration.Inputs" })
|
|
||||||
export type Inputs = typeof Inputs.Type
|
|
||||||
|
|
||||||
const Updated = ephemeral({
|
const Updated = ephemeral({
|
||||||
type: "integration.updated",
|
type: "integration.updated",
|
||||||
schema: {},
|
schema: {},
|
||||||
|
|||||||
@@ -58,6 +58,7 @@ export const IntegrationHandler = HttpApiBuilder.group(Api, "server.integration"
|
|||||||
service.connection.key({
|
service.connection.key({
|
||||||
integrationID: ctx.params.integrationID,
|
integrationID: ctx.params.integrationID,
|
||||||
key: ctx.payload.key,
|
key: ctx.payload.key,
|
||||||
|
answers: ctx.payload.answers,
|
||||||
label: ctx.payload.label,
|
label: ctx.payload.label,
|
||||||
}),
|
}),
|
||||||
)
|
)
|
||||||
@@ -73,7 +74,7 @@ export const IntegrationHandler = HttpApiBuilder.group(Api, "server.integration"
|
|||||||
service.oauth.connect({
|
service.oauth.connect({
|
||||||
integrationID: ctx.params.integrationID,
|
integrationID: ctx.params.integrationID,
|
||||||
methodID: ctx.payload.methodID,
|
methodID: ctx.payload.methodID,
|
||||||
inputs: ctx.payload.inputs,
|
answers: ctx.payload.answers,
|
||||||
label: ctx.payload.label,
|
label: ctx.payload.label,
|
||||||
}),
|
}),
|
||||||
),
|
),
|
||||||
|
|||||||
@@ -5,6 +5,8 @@ import type {
|
|||||||
IntegrationInfo,
|
IntegrationInfo,
|
||||||
IntegrationOauthConnectOutput,
|
IntegrationOauthConnectOutput,
|
||||||
IntegrationOAuthMethod,
|
IntegrationOAuthMethod,
|
||||||
|
FormAnswer,
|
||||||
|
FormFields,
|
||||||
} from "@opencode-ai/client"
|
} from "@opencode-ai/client"
|
||||||
import open from "open"
|
import open from "open"
|
||||||
import { createMemo, createSignal, onCleanup, onMount, Show } from "solid-js"
|
import { createMemo, createSignal, onCleanup, onMount, Show } from "solid-js"
|
||||||
@@ -18,6 +20,7 @@ import { DialogPrompt } from "../ui/dialog-prompt"
|
|||||||
import { DialogSelect } from "../ui/dialog-select"
|
import { DialogSelect } from "../ui/dialog-select"
|
||||||
import { Link } from "../ui/link"
|
import { Link } from "../ui/link"
|
||||||
import { useToast } from "../ui/toast"
|
import { useToast } from "../ui/toast"
|
||||||
|
import { FormInput } from "../routes/session/form"
|
||||||
|
|
||||||
const INTEGRATION_PRIORITY: Record<string, number> = {
|
const INTEGRATION_PRIORITY: Record<string, number> = {
|
||||||
opencode: 0,
|
opencode: 0,
|
||||||
@@ -181,7 +184,7 @@ function openMethod(
|
|||||||
onConnected?: OnIntegrationConnected,
|
onConnected?: OnIntegrationConnected,
|
||||||
) {
|
) {
|
||||||
if (method.type === "key") {
|
if (method.type === "key") {
|
||||||
dialog.replace(() => <KeyMethod integration={integration} method={method} onConnected={onConnected} />)
|
void beginKey(integration, method, dialog, onConnected)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
if (method.type === "command") {
|
if (method.type === "command") {
|
||||||
@@ -191,6 +194,21 @@ function openMethod(
|
|||||||
void beginOAuth(integration, method, dialog, onConnected)
|
void beginOAuth(integration, method, dialog, onConnected)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async function beginKey(
|
||||||
|
integration: IntegrationInfo,
|
||||||
|
method: Extract<ConnectMethod, { type: "key" }>,
|
||||||
|
dialog: ReturnType<typeof useDialog>,
|
||||||
|
onConnected?: OnIntegrationConnected,
|
||||||
|
) {
|
||||||
|
const answers = method.forms
|
||||||
|
? await formAnswers(dialog, method.label ?? `Connect ${integration.name}`, method.forms)
|
||||||
|
: {}
|
||||||
|
if (answers === null) return
|
||||||
|
dialog.replace(() => (
|
||||||
|
<KeyMethod integration={integration} method={method} answers={answers} onConnected={onConnected} />
|
||||||
|
))
|
||||||
|
}
|
||||||
|
|
||||||
function CommandStarting(props: {
|
function CommandStarting(props: {
|
||||||
integration: IntegrationInfo
|
integration: IntegrationInfo
|
||||||
method: Extract<ConnectMethod, { type: "command" }>
|
method: Extract<ConnectMethod, { type: "command" }>
|
||||||
@@ -336,6 +354,7 @@ function CommandView(props: { title: string; output: string; message: string })
|
|||||||
function KeyMethod(props: {
|
function KeyMethod(props: {
|
||||||
integration: IntegrationInfo
|
integration: IntegrationInfo
|
||||||
method: Extract<ConnectMethod, { type: "key" }>
|
method: Extract<ConnectMethod, { type: "key" }>
|
||||||
|
answers: FormAnswer
|
||||||
onConnected?: OnIntegrationConnected
|
onConnected?: OnIntegrationConnected
|
||||||
}) {
|
}) {
|
||||||
const data = useData()
|
const data = useData()
|
||||||
@@ -356,6 +375,7 @@ function KeyMethod(props: {
|
|||||||
integrationID: props.integration.id,
|
integrationID: props.integration.id,
|
||||||
location: location(data),
|
location: location(data),
|
||||||
key,
|
key,
|
||||||
|
answers: props.answers,
|
||||||
})
|
})
|
||||||
.then(() => connected(props.integration, data, dialog, toast, props.onConnected))
|
.then(() => connected(props.integration, data, dialog, toast, props.onConnected))
|
||||||
.catch((cause) => setError(message(cause)))
|
.catch((cause) => setError(message(cause)))
|
||||||
@@ -373,17 +393,17 @@ async function beginOAuth(
|
|||||||
dialog: ReturnType<typeof useDialog>,
|
dialog: ReturnType<typeof useDialog>,
|
||||||
onConnected?: OnIntegrationConnected,
|
onConnected?: OnIntegrationConnected,
|
||||||
) {
|
) {
|
||||||
const inputs = method.prompts?.length ? await promptInputs(dialog, method.prompts) : {}
|
const answers = method.forms ? await formAnswers(dialog, method.label, method.forms) : {}
|
||||||
if (inputs === null) return
|
if (answers === null) return
|
||||||
dialog.replace(() => (
|
dialog.replace(() => (
|
||||||
<OAuthStarting integration={integration} method={method} inputs={inputs} onConnected={onConnected} />
|
<OAuthStarting integration={integration} method={method} answers={answers} onConnected={onConnected} />
|
||||||
))
|
))
|
||||||
}
|
}
|
||||||
|
|
||||||
function OAuthStarting(props: {
|
function OAuthStarting(props: {
|
||||||
integration: IntegrationInfo
|
integration: IntegrationInfo
|
||||||
method: IntegrationOAuthMethod
|
method: IntegrationOAuthMethod
|
||||||
inputs: Record<string, string>
|
answers: FormAnswer
|
||||||
onConnected?: OnIntegrationConnected
|
onConnected?: OnIntegrationConnected
|
||||||
}) {
|
}) {
|
||||||
const data = useData()
|
const data = useData()
|
||||||
@@ -397,7 +417,7 @@ function OAuthStarting(props: {
|
|||||||
integrationID: props.integration.id,
|
integrationID: props.integration.id,
|
||||||
location: location(data),
|
location: location(data),
|
||||||
methodID: props.method.id,
|
methodID: props.method.id,
|
||||||
inputs: props.inputs,
|
answers: props.answers,
|
||||||
})
|
})
|
||||||
.then((result) => {
|
.then((result) => {
|
||||||
if (result.data.mode === "code") {
|
if (result.data.mode === "code") {
|
||||||
@@ -621,49 +641,23 @@ function OAuthView(props: {
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
async function promptInputs(
|
async function formAnswers(dialog: ReturnType<typeof useDialog>, title: string, forms: FormFields) {
|
||||||
dialog: ReturnType<typeof useDialog>,
|
return new Promise<FormAnswer | null>((resolve) => {
|
||||||
prompts: NonNullable<IntegrationOAuthMethod["prompts"]>,
|
dialog.replace(
|
||||||
) {
|
() => (
|
||||||
const inputs: Record<string, string> = {}
|
<FormInput
|
||||||
for (const prompt of prompts) {
|
form={{ title, fields: forms }}
|
||||||
if (prompt.when) {
|
onSubmit={resolve}
|
||||||
const value = inputs[prompt.when.key]
|
onCancel={() => {
|
||||||
if (value === undefined) continue
|
dialog.clear()
|
||||||
const matches = prompt.when.op === "eq" ? value === prompt.when.value : value !== prompt.when.value
|
resolve(null)
|
||||||
if (!matches) continue
|
}}
|
||||||
}
|
/>
|
||||||
if (prompt.type === "select") {
|
),
|
||||||
const value = await new Promise<string | null>((resolve) => {
|
() => resolve(null),
|
||||||
dialog.replace(
|
)
|
||||||
() => (
|
dialog.setSize("large")
|
||||||
<DialogSelect
|
})
|
||||||
title={prompt.message}
|
|
||||||
options={prompt.options.map((option) => ({
|
|
||||||
title: option.label,
|
|
||||||
value: option.value,
|
|
||||||
description: option.hint,
|
|
||||||
}))}
|
|
||||||
onSelect={(option) => resolve(option.value)}
|
|
||||||
/>
|
|
||||||
),
|
|
||||||
() => resolve(null),
|
|
||||||
)
|
|
||||||
})
|
|
||||||
if (value === null) return null
|
|
||||||
inputs[prompt.key] = value
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
const value = await new Promise<string | null>((resolve) => {
|
|
||||||
dialog.replace(
|
|
||||||
() => <DialogPrompt title={prompt.message} placeholder={prompt.placeholder} onConfirm={resolve} />,
|
|
||||||
() => resolve(null),
|
|
||||||
)
|
|
||||||
})
|
|
||||||
if (value === null) return null
|
|
||||||
inputs[prompt.key] = value
|
|
||||||
}
|
|
||||||
return inputs
|
|
||||||
}
|
}
|
||||||
|
|
||||||
async function connected(
|
async function connected(
|
||||||
|
|||||||
@@ -4,7 +4,7 @@ import { useRenderer, useTerminalDimensions } from "@opentui/solid"
|
|||||||
import type { ScrollBoxRenderable, TextareaRenderable } from "@opentui/core"
|
import type { ScrollBoxRenderable, TextareaRenderable } from "@opentui/core"
|
||||||
import open from "open"
|
import open from "open"
|
||||||
import { useTheme, useThemes } from "../../context/theme"
|
import { useTheme, useThemes } from "../../context/theme"
|
||||||
import type { FormField, FormValue } from "@opencode-ai/client"
|
import type { FormAnswer, FormField, FormValue } from "@opencode-ai/client"
|
||||||
import type { FormWithLocation } from "../../context/data"
|
import type { FormWithLocation } from "../../context/data"
|
||||||
import { useClient } from "../../context/client"
|
import { useClient } from "../../context/client"
|
||||||
import { useClipboard } from "../../context/clipboard"
|
import { useClipboard } from "../../context/clipboard"
|
||||||
@@ -44,6 +44,27 @@ function requestOptions(form: FormWithLocation) {
|
|||||||
|
|
||||||
export function FormPrompt(props: { form: FormWithLocation }) {
|
export function FormPrompt(props: { form: FormWithLocation }) {
|
||||||
const client = useClient()
|
const client = useClient()
|
||||||
|
return (
|
||||||
|
<FormInput
|
||||||
|
form={props.form}
|
||||||
|
onSubmit={(answer) =>
|
||||||
|
client.api.form.reply(
|
||||||
|
{ sessionID: props.form.sessionID, formID: props.form.id, answer },
|
||||||
|
requestOptions(props.form),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
onCancel={() =>
|
||||||
|
client.api.form.cancel({ sessionID: props.form.sessionID, formID: props.form.id }, requestOptions(props.form))
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export function FormInput(props: {
|
||||||
|
form: Pick<FormWithLocation, "title" | "fields" | "metadata">
|
||||||
|
onSubmit: (answer: FormAnswer) => Promise<unknown> | void
|
||||||
|
onCancel: () => Promise<unknown> | void
|
||||||
|
}) {
|
||||||
const themes = useThemes()
|
const themes = useThemes()
|
||||||
const theme = useTheme("elevated")
|
const theme = useTheme("elevated")
|
||||||
const themeMode = themes.mode
|
const themeMode = themes.mode
|
||||||
@@ -181,23 +202,14 @@ export function FormPrompt(props: { form: FormWithLocation }) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function replySingle(field: FormAnswerField, value: FormValue) {
|
function replySingle(field: FormAnswerField, value: FormValue) {
|
||||||
client.api.form
|
Promise.resolve(props.onSubmit({ [field.key]: value })).catch((error: unknown) => {
|
||||||
.reply(
|
setStore(
|
||||||
{
|
"error",
|
||||||
sessionID: props.form.sessionID,
|
typeof error === "object" && error !== null && "message" in error && typeof error.message === "string"
|
||||||
formID: props.form.id,
|
? error.message
|
||||||
answer: { [field.key]: value },
|
: "Invalid answer",
|
||||||
},
|
|
||||||
requestOptions(props.form),
|
|
||||||
)
|
)
|
||||||
.catch((error: unknown) => {
|
})
|
||||||
setStore(
|
|
||||||
"error",
|
|
||||||
typeof error === "object" && error !== null && "message" in error && typeof error.message === "string"
|
|
||||||
? error.message
|
|
||||||
: "Invalid answer",
|
|
||||||
)
|
|
||||||
})
|
|
||||||
}
|
}
|
||||||
|
|
||||||
function pick(value: FormValue, customValue?: string) {
|
function pick(value: FormValue, customValue?: string) {
|
||||||
@@ -350,7 +362,7 @@ export function FormPrompt(props: { form: FormWithLocation }) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function cancel() {
|
function cancel() {
|
||||||
void client.api.form.cancel({ sessionID: props.form.sessionID, formID: props.form.id }, requestOptions(props.form))
|
void props.onCancel()
|
||||||
}
|
}
|
||||||
|
|
||||||
function openExternal() {
|
function openExternal() {
|
||||||
@@ -402,28 +414,23 @@ export function FormPrompt(props: { form: FormWithLocation }) {
|
|||||||
setStore("error", formValidateValue(invalid, store.answers[invalid.key]) ?? "Invalid answer")
|
setStore("error", formValidateValue(invalid, store.answers[invalid.key]) ?? "Invalid answer")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
client.api.form
|
Promise.resolve(
|
||||||
.reply(
|
props.onSubmit(
|
||||||
{
|
Object.fromEntries(
|
||||||
sessionID: props.form.sessionID,
|
fields().flatMap((field) => {
|
||||||
formID: props.form.id,
|
const value = store.answers[field.key]
|
||||||
answer: Object.fromEntries(
|
return value === undefined ? [] : [[field.key, value] as const]
|
||||||
fields().flatMap((field) => {
|
}),
|
||||||
const value = store.answers[field.key]
|
),
|
||||||
return value === undefined ? [] : [[field.key, value] as const]
|
),
|
||||||
}),
|
).catch((error: unknown) => {
|
||||||
),
|
setStore(
|
||||||
},
|
"error",
|
||||||
requestOptions(props.form),
|
typeof error === "object" && error !== null && "message" in error && typeof error.message === "string"
|
||||||
|
? error.message
|
||||||
|
: "Invalid answer",
|
||||||
)
|
)
|
||||||
.catch((error: unknown) => {
|
})
|
||||||
setStore(
|
|
||||||
"error",
|
|
||||||
typeof error === "object" && error !== null && "message" in error && typeof error.message === "string"
|
|
||||||
? error.message
|
|
||||||
: "Invalid answer",
|
|
||||||
)
|
|
||||||
})
|
|
||||||
}
|
}
|
||||||
|
|
||||||
onMount(() => onCleanup(keymap.mode.push(FORM_MODE)))
|
onMount(() => onCleanup(keymap.mode.push(FORM_MODE)))
|
||||||
@@ -451,10 +458,7 @@ export function FormPrompt(props: { form: FormWithLocation }) {
|
|||||||
group: "Form",
|
group: "Form",
|
||||||
run: () => {
|
run: () => {
|
||||||
if (textual()) {
|
if (textual()) {
|
||||||
void client.api.form.cancel(
|
void props.onCancel()
|
||||||
{ sessionID: props.form.sessionID, formID: props.form.id },
|
|
||||||
requestOptions(props.form),
|
|
||||||
)
|
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
setStore("editing", false)
|
setStore("editing", false)
|
||||||
|
|||||||
Reference in New Issue
Block a user