mirror of
https://github.com/anomalyco/opencode.git
synced 2026-08-09 10:59:49 -04:00
Compare commits
28 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| ad8f2033a7 | |||
| 15efcf90fa | |||
| 5ae05c1ee2 | |||
| dd6c5fcb7b | |||
| 5cfb70e93a | |||
| 9fed1e9764 | |||
| 2be2993289 | |||
| 3434fd0c6e | |||
| 905ccc3c54 | |||
| b36f50eacf | |||
| d9572f9c0f | |||
| f44e75657d | |||
| a3e8ba9ff3 | |||
| 26ae7d4a6a | |||
| cdae7ccebf | |||
| bab1cceede | |||
| f2d744b55d | |||
| 84fd347afa | |||
| e8f215bfbc | |||
| 445af9ce70 | |||
| bc51baa9a4 | |||
| ff0a0b0786 | |||
| 4eff0ee2db | |||
| cc0061f88b | |||
| f43f2b354c | |||
| c2ba0bef6b | |||
| 83b47693c3 | |||
| 1ca86ad973 |
@@ -45,8 +45,7 @@ const isToolResultValue = (value: unknown): value is ToolResultValue =>
|
|||||||
(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(
|
const toolResultValueSchema = Schema.Union([
|
||||||
Schema.Union([
|
|
||||||
Schema.Struct({
|
Schema.Struct({
|
||||||
type: Schema.Literal("json"),
|
type: Schema.Literal("json"),
|
||||||
value: Schema.Unknown,
|
value: Schema.Unknown,
|
||||||
@@ -63,17 +62,17 @@ export const ToolResultValue = Object.assign(
|
|||||||
type: Schema.Literal("content"),
|
type: Schema.Literal("content"),
|
||||||
value: Schema.Array(Tool.Content),
|
value: Schema.Array(Tool.Content),
|
||||||
}),
|
}),
|
||||||
]).annotate({ identifier: "LLM.ToolResult" }),
|
]).annotate({ identifier: "LLM.ToolResult" })
|
||||||
{
|
export type ToolResultValue = Schema.Schema.Type<typeof toolResultValueSchema>
|
||||||
|
|
||||||
|
export const ToolResultValue = Object.assign(toolResultValueSchema, {
|
||||||
is: isToolResultValue,
|
is: isToolResultValue,
|
||||||
make: (value: unknown, type: ToolResultValue["type"] = "json"): ToolResultValue => {
|
make: (value: unknown, type: ToolResultValue["type"] = "json"): ToolResultValue => {
|
||||||
if (isToolResultValue(value)) return value
|
if (isToolResultValue(value)) return value
|
||||||
if (type === "content") return { type, value: Array.isArray(value) ? value : [] }
|
if (type === "content") return { type, value: Array.isArray(value) ? value : [] }
|
||||||
return { type, value }
|
return { type, value }
|
||||||
},
|
},
|
||||||
},
|
})
|
||||||
)
|
|
||||||
export type ToolResultValue = Schema.Schema.Type<typeof ToolResultValue>
|
|
||||||
|
|
||||||
export interface ToolOutput {
|
export interface ToolOutput {
|
||||||
readonly structured: unknown
|
readonly structured: unknown
|
||||||
|
|||||||
@@ -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["form"]>[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>,
|
formAnswer: 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.answer"; answer: FormAnswer | undefined }
|
||||||
| { 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.formAnswer = 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.formAnswer = 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.answer") {
|
||||||
draft.promptInputs = action.inputs
|
draft.formAnswer = action.answer
|
||||||
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, answer?: 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.form?.length && !answer) {
|
||||||
|
dispatch({ type: "auth.form" })
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if (method.type === "key") {
|
||||||
|
dispatch({ type: "auth.answer", answer })
|
||||||
|
return
|
||||||
|
}
|
||||||
if (method.type === "oauth") {
|
if (method.type === "oauth") {
|
||||||
if (method.prompts?.length && !inputs) {
|
if (method.form?.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 ?? {},
|
...(answer ? { answer } : {}),
|
||||||
location: location(),
|
location: location(),
|
||||||
})
|
})
|
||||||
.then((x) => {
|
.then((x) => {
|
||||||
@@ -564,41 +574,42 @@ function ProviderConnection(props: {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function AuthPromptsView() {
|
function AuthFormView() {
|
||||||
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 fields = createMemo<StringForm[]>(() => {
|
||||||
const value = method()
|
const value = method()
|
||||||
return value?.type === "oauth" ? (value.prompts ?? []) : []
|
return (value?.form ?? []).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 = fields()
|
||||||
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 = fields().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,
|
||||||
|
...(store.formAnswer ? { answer: store.formAnswer } : {}),
|
||||||
})
|
})
|
||||||
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 />
|
<AuthFormView />
|
||||||
</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,12 @@ 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.form?.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: {},
|
|
||||||
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 } : {},
|
...(server ? { answer: { 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, location }),
|
||||||
)
|
)
|
||||||
const attempt = started.data
|
const attempt = started.data
|
||||||
if (attempt.mode === "code")
|
if (attempt.mode === "code")
|
||||||
|
|||||||
@@ -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"
|
||||||
@@ -180,6 +180,7 @@ export type Endpoint5_12Input = {
|
|||||||
readonly text: string
|
readonly text: string
|
||||||
readonly files?: ReadonlyArray<PromptInput.FileAttachment> | undefined
|
readonly files?: ReadonlyArray<PromptInput.FileAttachment> | undefined
|
||||||
readonly agents?: ReadonlyArray<AgentAttachment> | undefined
|
readonly agents?: ReadonlyArray<AgentAttachment> | undefined
|
||||||
|
readonly skills?: ReadonlyArray<PromptInput.SkillAttachment> | undefined
|
||||||
readonly metadata?: { readonly [x: string]: unknown } | undefined
|
readonly metadata?: { readonly [x: string]: unknown } | undefined
|
||||||
readonly delivery?: "steer" | "queue" | undefined
|
readonly delivery?: "steer" | "queue" | undefined
|
||||||
readonly resume?: boolean | undefined
|
readonly resume?: boolean | undefined
|
||||||
@@ -196,6 +197,7 @@ export type Endpoint5_13Input = {
|
|||||||
readonly model?: Model.Ref | undefined
|
readonly model?: Model.Ref | undefined
|
||||||
readonly files?: ReadonlyArray<PromptInput.FileAttachment> | undefined
|
readonly files?: ReadonlyArray<PromptInput.FileAttachment> | undefined
|
||||||
readonly agents?: ReadonlyArray<AgentAttachment> | undefined
|
readonly agents?: ReadonlyArray<AgentAttachment> | undefined
|
||||||
|
readonly skills?: ReadonlyArray<PromptInput.SkillAttachment> | undefined
|
||||||
readonly delivery?: "steer" | "queue" | undefined
|
readonly delivery?: "steer" | "queue" | undefined
|
||||||
readonly resume?: boolean | undefined
|
readonly resume?: boolean | undefined
|
||||||
}
|
}
|
||||||
@@ -1052,6 +1054,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 answer?: Form.Answer | undefined
|
||||||
readonly label?: string | undefined
|
readonly label?: string | undefined
|
||||||
}
|
}
|
||||||
export type Endpoint10_3Output = void
|
export type Endpoint10_3Output = void
|
||||||
@@ -1063,7 +1066,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 answer?: Form.Answer | undefined
|
||||||
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 }
|
||||||
|
|||||||
@@ -412,6 +412,7 @@ const Endpoint5_12 = (raw: RawClient["server.session"]) => (input: Endpoint5_12I
|
|||||||
text: input["text"],
|
text: input["text"],
|
||||||
files: input["files"],
|
files: input["files"],
|
||||||
agents: input["agents"],
|
agents: input["agents"],
|
||||||
|
skills: input["skills"],
|
||||||
metadata: input["metadata"],
|
metadata: input["metadata"],
|
||||||
delivery: input["delivery"],
|
delivery: input["delivery"],
|
||||||
resume: input["resume"],
|
resume: input["resume"],
|
||||||
@@ -434,6 +435,7 @@ const Endpoint5_13 = (raw: RawClient["server.session"]) => (input: Endpoint5_13I
|
|||||||
model: input["model"],
|
model: input["model"],
|
||||||
files: input["files"],
|
files: input["files"],
|
||||||
agents: input["agents"],
|
agents: input["agents"],
|
||||||
|
skills: input["skills"],
|
||||||
delivery: input["delivery"],
|
delivery: input["delivery"],
|
||||||
resume: input["resume"],
|
resume: input["resume"],
|
||||||
},
|
},
|
||||||
@@ -715,7 +717,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"], answer: input["answer"], label: input["label"] },
|
||||||
}).pipe(Effect.mapError(mapClientError)),
|
}).pipe(Effect.mapError(mapClientError)),
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -724,7 +726,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"], answer: input["answer"], label: input["label"] },
|
||||||
}).pipe(Effect.mapError(mapClientError)),
|
}).pipe(Effect.mapError(mapClientError)),
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|||||||
@@ -615,6 +615,7 @@ export function make(options: ClientOptions) {
|
|||||||
text: input["text"],
|
text: input["text"],
|
||||||
files: input["files"],
|
files: input["files"],
|
||||||
agents: input["agents"],
|
agents: input["agents"],
|
||||||
|
skills: input["skills"],
|
||||||
metadata: input["metadata"],
|
metadata: input["metadata"],
|
||||||
delivery: input["delivery"],
|
delivery: input["delivery"],
|
||||||
resume: input["resume"],
|
resume: input["resume"],
|
||||||
@@ -638,6 +639,7 @@ export function make(options: ClientOptions) {
|
|||||||
model: input["model"],
|
model: input["model"],
|
||||||
files: input["files"],
|
files: input["files"],
|
||||||
agents: input["agents"],
|
agents: input["agents"],
|
||||||
|
skills: input["skills"],
|
||||||
delivery: input["delivery"],
|
delivery: input["delivery"],
|
||||||
resume: input["resume"],
|
resume: input["resume"],
|
||||||
},
|
},
|
||||||
@@ -1030,7 +1032,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"], answer: input["answer"], label: input["label"] },
|
||||||
successStatus: 204,
|
successStatus: 204,
|
||||||
declaredStatuses: [400, 401],
|
declaredStatuses: [400, 401],
|
||||||
empty: true,
|
empty: true,
|
||||||
@@ -1045,7 +1047,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"], answer: input["answer"], 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 }
|
||||||
@@ -1080,6 +1076,8 @@ export type PromptFileAttachment = {
|
|||||||
|
|
||||||
export type PromptAgentAttachment = { name: string; mention?: PromptMention }
|
export type PromptAgentAttachment = { name: string; mention?: PromptMention }
|
||||||
|
|
||||||
|
export type PromptSkillAttachment = { id: string; name: string; text: string; mention?: PromptMention }
|
||||||
|
|
||||||
export type SessionMessageAssistantText = { type: "text"; text: string; state?: SessionMessageProviderState }
|
export type SessionMessageAssistantText = { type: "text"; text: string; state?: SessionMessageProviderState }
|
||||||
|
|
||||||
export type SessionMessageAssistantReasoning = {
|
export type SessionMessageAssistantReasoning = {
|
||||||
@@ -1275,45 +1273,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 +1338,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 = {
|
||||||
@@ -1565,6 +1547,7 @@ export type SessionMessageUser = {
|
|||||||
text: string
|
text: string
|
||||||
files?: Array<PromptFileAttachment>
|
files?: Array<PromptFileAttachment>
|
||||||
agents?: Array<PromptAgentAttachment>
|
agents?: Array<PromptAgentAttachment>
|
||||||
|
skills?: Array<PromptSkillAttachment>
|
||||||
type: "user"
|
type: "user"
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1572,6 +1555,7 @@ export type SessionPendingUserData = {
|
|||||||
text: string
|
text: string
|
||||||
files?: Array<PromptFileAttachment>
|
files?: Array<PromptFileAttachment>
|
||||||
agents?: Array<PromptAgentAttachment>
|
agents?: Array<PromptAgentAttachment>
|
||||||
|
skills?: Array<PromptSkillAttachment>
|
||||||
metadata?: { [x: string]: JsonValue }
|
metadata?: { [x: string]: JsonValue }
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1579,6 +1563,7 @@ export type SessionPendingUserData1 = {
|
|||||||
text: string
|
text: string
|
||||||
files?: Array<PromptFileAttachment>
|
files?: Array<PromptFileAttachment>
|
||||||
agents?: Array<PromptAgentAttachment>
|
agents?: Array<PromptAgentAttachment>
|
||||||
|
skills?: Array<PromptSkillAttachment>
|
||||||
metadata?: { [x: string]: any }
|
metadata?: { [x: string]: any }
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1659,13 +1644,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 +1897,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 +1921,13 @@ export type SessionMessageAssistant = {
|
|||||||
retry?: SessionMessageAssistantRetry
|
retry?: SessionMessageAssistantRetry
|
||||||
}
|
}
|
||||||
|
|
||||||
export type IntegrationInfo = {
|
export type IntegrationOAuthMethod = { id: string; type: "oauth"; label: string; form?: FormFields }
|
||||||
id: string
|
|
||||||
name: string
|
export type IntegrationKeyMethod = { type: "key"; label?: string; form?: 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 +1950,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 +2016,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
|
||||||
@@ -2579,6 +2561,12 @@ export type SessionImportInput = {
|
|||||||
readonly name: string
|
readonly name: string
|
||||||
readonly mention?: { readonly start: number; readonly end: number; readonly text: string }
|
readonly mention?: { readonly start: number; readonly end: number; readonly text: string }
|
||||||
}>
|
}>
|
||||||
|
readonly skills?: ReadonlyArray<{
|
||||||
|
readonly id: string
|
||||||
|
readonly name: string
|
||||||
|
readonly text: string
|
||||||
|
readonly mention?: { readonly start: number; readonly end: number; readonly text: string }
|
||||||
|
}>
|
||||||
readonly type: "user"
|
readonly type: "user"
|
||||||
}
|
}
|
||||||
| {
|
| {
|
||||||
@@ -2824,6 +2812,12 @@ export type SessionImportInput = {
|
|||||||
readonly name: string
|
readonly name: string
|
||||||
readonly mention?: { readonly start: number; readonly end: number; readonly text: string }
|
readonly mention?: { readonly start: number; readonly end: number; readonly text: string }
|
||||||
}>
|
}>
|
||||||
|
readonly skills?: ReadonlyArray<{
|
||||||
|
readonly id: string
|
||||||
|
readonly name: string
|
||||||
|
readonly text: string
|
||||||
|
readonly mention?: { readonly start: number; readonly end: number; readonly text: string }
|
||||||
|
}>
|
||||||
readonly type: "user"
|
readonly type: "user"
|
||||||
}
|
}
|
||||||
| {
|
| {
|
||||||
@@ -3069,6 +3063,12 @@ export type SessionImportInput = {
|
|||||||
readonly name: string
|
readonly name: string
|
||||||
readonly mention?: { readonly start: number; readonly end: number; readonly text: string }
|
readonly mention?: { readonly start: number; readonly end: number; readonly text: string }
|
||||||
}>
|
}>
|
||||||
|
readonly skills?: ReadonlyArray<{
|
||||||
|
readonly id: string
|
||||||
|
readonly name: string
|
||||||
|
readonly text: string
|
||||||
|
readonly mention?: { readonly start: number; readonly end: number; readonly text: string }
|
||||||
|
}>
|
||||||
readonly type: "user"
|
readonly type: "user"
|
||||||
}
|
}
|
||||||
| {
|
| {
|
||||||
@@ -3320,6 +3320,10 @@ export type SessionPromptInput = {
|
|||||||
readonly name: string
|
readonly name: string
|
||||||
readonly mention?: { readonly start: number; readonly end: number; readonly text: string }
|
readonly mention?: { readonly start: number; readonly end: number; readonly text: string }
|
||||||
}>
|
}>
|
||||||
|
readonly skills?: ReadonlyArray<{
|
||||||
|
readonly id: string
|
||||||
|
readonly mention?: { readonly start: number; readonly end: number; readonly text: string }
|
||||||
|
}>
|
||||||
readonly metadata?: { readonly [x: string]: JsonValue }
|
readonly metadata?: { readonly [x: string]: JsonValue }
|
||||||
readonly delivery?: "steer" | "queue" | null
|
readonly delivery?: "steer" | "queue" | null
|
||||||
readonly resume?: boolean | null
|
readonly resume?: boolean | null
|
||||||
@@ -3337,6 +3341,10 @@ export type SessionPromptInput = {
|
|||||||
readonly name: string
|
readonly name: string
|
||||||
readonly mention?: { readonly start: number; readonly end: number; readonly text: string }
|
readonly mention?: { readonly start: number; readonly end: number; readonly text: string }
|
||||||
}>
|
}>
|
||||||
|
readonly skills?: ReadonlyArray<{
|
||||||
|
readonly id: string
|
||||||
|
readonly mention?: { readonly start: number; readonly end: number; readonly text: string }
|
||||||
|
}>
|
||||||
readonly metadata?: { readonly [x: string]: JsonValue }
|
readonly metadata?: { readonly [x: string]: JsonValue }
|
||||||
readonly delivery?: "steer" | "queue" | null
|
readonly delivery?: "steer" | "queue" | null
|
||||||
readonly resume?: boolean | null
|
readonly resume?: boolean | null
|
||||||
@@ -3354,6 +3362,10 @@ export type SessionPromptInput = {
|
|||||||
readonly name: string
|
readonly name: string
|
||||||
readonly mention?: { readonly start: number; readonly end: number; readonly text: string }
|
readonly mention?: { readonly start: number; readonly end: number; readonly text: string }
|
||||||
}>
|
}>
|
||||||
|
readonly skills?: ReadonlyArray<{
|
||||||
|
readonly id: string
|
||||||
|
readonly mention?: { readonly start: number; readonly end: number; readonly text: string }
|
||||||
|
}>
|
||||||
readonly metadata?: { readonly [x: string]: JsonValue }
|
readonly metadata?: { readonly [x: string]: JsonValue }
|
||||||
readonly delivery?: "steer" | "queue" | null
|
readonly delivery?: "steer" | "queue" | null
|
||||||
readonly resume?: boolean | null
|
readonly resume?: boolean | null
|
||||||
@@ -3371,10 +3383,35 @@ export type SessionPromptInput = {
|
|||||||
readonly name: string
|
readonly name: string
|
||||||
readonly mention?: { readonly start: number; readonly end: number; readonly text: string }
|
readonly mention?: { readonly start: number; readonly end: number; readonly text: string }
|
||||||
}>
|
}>
|
||||||
|
readonly skills?: ReadonlyArray<{
|
||||||
|
readonly id: string
|
||||||
|
readonly mention?: { readonly start: number; readonly end: number; readonly text: string }
|
||||||
|
}>
|
||||||
readonly metadata?: { readonly [x: string]: JsonValue }
|
readonly metadata?: { readonly [x: string]: JsonValue }
|
||||||
readonly delivery?: "steer" | "queue" | null
|
readonly delivery?: "steer" | "queue" | null
|
||||||
readonly resume?: boolean | null
|
readonly resume?: boolean | null
|
||||||
}["agents"]
|
}["agents"]
|
||||||
|
readonly skills?: {
|
||||||
|
readonly id?: string | null
|
||||||
|
readonly text: string
|
||||||
|
readonly files?: ReadonlyArray<{
|
||||||
|
readonly uri: string
|
||||||
|
readonly name?: string
|
||||||
|
readonly description?: string
|
||||||
|
readonly mention?: { readonly start: number; readonly end: number; readonly text: string }
|
||||||
|
}>
|
||||||
|
readonly agents?: ReadonlyArray<{
|
||||||
|
readonly name: string
|
||||||
|
readonly mention?: { readonly start: number; readonly end: number; readonly text: string }
|
||||||
|
}>
|
||||||
|
readonly skills?: ReadonlyArray<{
|
||||||
|
readonly id: string
|
||||||
|
readonly mention?: { readonly start: number; readonly end: number; readonly text: string }
|
||||||
|
}>
|
||||||
|
readonly metadata?: { readonly [x: string]: JsonValue }
|
||||||
|
readonly delivery?: "steer" | "queue" | null
|
||||||
|
readonly resume?: boolean | null
|
||||||
|
}["skills"]
|
||||||
readonly metadata?: {
|
readonly metadata?: {
|
||||||
readonly id?: string | null
|
readonly id?: string | null
|
||||||
readonly text: string
|
readonly text: string
|
||||||
@@ -3388,6 +3425,10 @@ export type SessionPromptInput = {
|
|||||||
readonly name: string
|
readonly name: string
|
||||||
readonly mention?: { readonly start: number; readonly end: number; readonly text: string }
|
readonly mention?: { readonly start: number; readonly end: number; readonly text: string }
|
||||||
}>
|
}>
|
||||||
|
readonly skills?: ReadonlyArray<{
|
||||||
|
readonly id: string
|
||||||
|
readonly mention?: { readonly start: number; readonly end: number; readonly text: string }
|
||||||
|
}>
|
||||||
readonly metadata?: { readonly [x: string]: JsonValue }
|
readonly metadata?: { readonly [x: string]: JsonValue }
|
||||||
readonly delivery?: "steer" | "queue" | null
|
readonly delivery?: "steer" | "queue" | null
|
||||||
readonly resume?: boolean | null
|
readonly resume?: boolean | null
|
||||||
@@ -3405,6 +3446,10 @@ export type SessionPromptInput = {
|
|||||||
readonly name: string
|
readonly name: string
|
||||||
readonly mention?: { readonly start: number; readonly end: number; readonly text: string }
|
readonly mention?: { readonly start: number; readonly end: number; readonly text: string }
|
||||||
}>
|
}>
|
||||||
|
readonly skills?: ReadonlyArray<{
|
||||||
|
readonly id: string
|
||||||
|
readonly mention?: { readonly start: number; readonly end: number; readonly text: string }
|
||||||
|
}>
|
||||||
readonly metadata?: { readonly [x: string]: JsonValue }
|
readonly metadata?: { readonly [x: string]: JsonValue }
|
||||||
readonly delivery?: "steer" | "queue" | null
|
readonly delivery?: "steer" | "queue" | null
|
||||||
readonly resume?: boolean | null
|
readonly resume?: boolean | null
|
||||||
@@ -3422,6 +3467,10 @@ export type SessionPromptInput = {
|
|||||||
readonly name: string
|
readonly name: string
|
||||||
readonly mention?: { readonly start: number; readonly end: number; readonly text: string }
|
readonly mention?: { readonly start: number; readonly end: number; readonly text: string }
|
||||||
}>
|
}>
|
||||||
|
readonly skills?: ReadonlyArray<{
|
||||||
|
readonly id: string
|
||||||
|
readonly mention?: { readonly start: number; readonly end: number; readonly text: string }
|
||||||
|
}>
|
||||||
readonly metadata?: { readonly [x: string]: JsonValue }
|
readonly metadata?: { readonly [x: string]: JsonValue }
|
||||||
readonly delivery?: "steer" | "queue" | null
|
readonly delivery?: "steer" | "queue" | null
|
||||||
readonly resume?: boolean | null
|
readonly resume?: boolean | null
|
||||||
@@ -3448,6 +3497,10 @@ export type SessionCommandInput = {
|
|||||||
readonly name: string
|
readonly name: string
|
||||||
readonly mention?: { readonly start: number; readonly end: number; readonly text: string }
|
readonly mention?: { readonly start: number; readonly end: number; readonly text: string }
|
||||||
}>
|
}>
|
||||||
|
readonly skills?: ReadonlyArray<{
|
||||||
|
readonly id: string
|
||||||
|
readonly mention?: { readonly start: number; readonly end: number; readonly text: string }
|
||||||
|
}>
|
||||||
readonly delivery?: "steer" | "queue" | null
|
readonly delivery?: "steer" | "queue" | null
|
||||||
readonly resume?: boolean | null
|
readonly resume?: boolean | null
|
||||||
}["id"]
|
}["id"]
|
||||||
@@ -3467,6 +3520,10 @@ export type SessionCommandInput = {
|
|||||||
readonly name: string
|
readonly name: string
|
||||||
readonly mention?: { readonly start: number; readonly end: number; readonly text: string }
|
readonly mention?: { readonly start: number; readonly end: number; readonly text: string }
|
||||||
}>
|
}>
|
||||||
|
readonly skills?: ReadonlyArray<{
|
||||||
|
readonly id: string
|
||||||
|
readonly mention?: { readonly start: number; readonly end: number; readonly text: string }
|
||||||
|
}>
|
||||||
readonly delivery?: "steer" | "queue" | null
|
readonly delivery?: "steer" | "queue" | null
|
||||||
readonly resume?: boolean | null
|
readonly resume?: boolean | null
|
||||||
}["command"]
|
}["command"]
|
||||||
@@ -3486,6 +3543,10 @@ export type SessionCommandInput = {
|
|||||||
readonly name: string
|
readonly name: string
|
||||||
readonly mention?: { readonly start: number; readonly end: number; readonly text: string }
|
readonly mention?: { readonly start: number; readonly end: number; readonly text: string }
|
||||||
}>
|
}>
|
||||||
|
readonly skills?: ReadonlyArray<{
|
||||||
|
readonly id: string
|
||||||
|
readonly mention?: { readonly start: number; readonly end: number; readonly text: string }
|
||||||
|
}>
|
||||||
readonly delivery?: "steer" | "queue" | null
|
readonly delivery?: "steer" | "queue" | null
|
||||||
readonly resume?: boolean | null
|
readonly resume?: boolean | null
|
||||||
}["arguments"]
|
}["arguments"]
|
||||||
@@ -3505,6 +3566,10 @@ export type SessionCommandInput = {
|
|||||||
readonly name: string
|
readonly name: string
|
||||||
readonly mention?: { readonly start: number; readonly end: number; readonly text: string }
|
readonly mention?: { readonly start: number; readonly end: number; readonly text: string }
|
||||||
}>
|
}>
|
||||||
|
readonly skills?: ReadonlyArray<{
|
||||||
|
readonly id: string
|
||||||
|
readonly mention?: { readonly start: number; readonly end: number; readonly text: string }
|
||||||
|
}>
|
||||||
readonly delivery?: "steer" | "queue" | null
|
readonly delivery?: "steer" | "queue" | null
|
||||||
readonly resume?: boolean | null
|
readonly resume?: boolean | null
|
||||||
}["agent"]
|
}["agent"]
|
||||||
@@ -3524,6 +3589,10 @@ export type SessionCommandInput = {
|
|||||||
readonly name: string
|
readonly name: string
|
||||||
readonly mention?: { readonly start: number; readonly end: number; readonly text: string }
|
readonly mention?: { readonly start: number; readonly end: number; readonly text: string }
|
||||||
}>
|
}>
|
||||||
|
readonly skills?: ReadonlyArray<{
|
||||||
|
readonly id: string
|
||||||
|
readonly mention?: { readonly start: number; readonly end: number; readonly text: string }
|
||||||
|
}>
|
||||||
readonly delivery?: "steer" | "queue" | null
|
readonly delivery?: "steer" | "queue" | null
|
||||||
readonly resume?: boolean | null
|
readonly resume?: boolean | null
|
||||||
}["model"]
|
}["model"]
|
||||||
@@ -3543,6 +3612,10 @@ export type SessionCommandInput = {
|
|||||||
readonly name: string
|
readonly name: string
|
||||||
readonly mention?: { readonly start: number; readonly end: number; readonly text: string }
|
readonly mention?: { readonly start: number; readonly end: number; readonly text: string }
|
||||||
}>
|
}>
|
||||||
|
readonly skills?: ReadonlyArray<{
|
||||||
|
readonly id: string
|
||||||
|
readonly mention?: { readonly start: number; readonly end: number; readonly text: string }
|
||||||
|
}>
|
||||||
readonly delivery?: "steer" | "queue" | null
|
readonly delivery?: "steer" | "queue" | null
|
||||||
readonly resume?: boolean | null
|
readonly resume?: boolean | null
|
||||||
}["files"]
|
}["files"]
|
||||||
@@ -3562,9 +3635,36 @@ export type SessionCommandInput = {
|
|||||||
readonly name: string
|
readonly name: string
|
||||||
readonly mention?: { readonly start: number; readonly end: number; readonly text: string }
|
readonly mention?: { readonly start: number; readonly end: number; readonly text: string }
|
||||||
}>
|
}>
|
||||||
|
readonly skills?: ReadonlyArray<{
|
||||||
|
readonly id: string
|
||||||
|
readonly mention?: { readonly start: number; readonly end: number; readonly text: string }
|
||||||
|
}>
|
||||||
readonly delivery?: "steer" | "queue" | null
|
readonly delivery?: "steer" | "queue" | null
|
||||||
readonly resume?: boolean | null
|
readonly resume?: boolean | null
|
||||||
}["agents"]
|
}["agents"]
|
||||||
|
readonly skills?: {
|
||||||
|
readonly id?: string | null
|
||||||
|
readonly command: string
|
||||||
|
readonly arguments?: string | null
|
||||||
|
readonly agent?: string | null
|
||||||
|
readonly model?: { readonly id: string; readonly providerID: string; readonly variant?: string } | null
|
||||||
|
readonly files?: ReadonlyArray<{
|
||||||
|
readonly uri: string
|
||||||
|
readonly name?: string
|
||||||
|
readonly description?: string
|
||||||
|
readonly mention?: { readonly start: number; readonly end: number; readonly text: string }
|
||||||
|
}>
|
||||||
|
readonly agents?: ReadonlyArray<{
|
||||||
|
readonly name: string
|
||||||
|
readonly mention?: { readonly start: number; readonly end: number; readonly text: string }
|
||||||
|
}>
|
||||||
|
readonly skills?: ReadonlyArray<{
|
||||||
|
readonly id: string
|
||||||
|
readonly mention?: { readonly start: number; readonly end: number; readonly text: string }
|
||||||
|
}>
|
||||||
|
readonly delivery?: "steer" | "queue" | null
|
||||||
|
readonly resume?: boolean | null
|
||||||
|
}["skills"]
|
||||||
readonly delivery?: {
|
readonly delivery?: {
|
||||||
readonly id?: string | null
|
readonly id?: string | null
|
||||||
readonly command: string
|
readonly command: string
|
||||||
@@ -3581,6 +3681,10 @@ export type SessionCommandInput = {
|
|||||||
readonly name: string
|
readonly name: string
|
||||||
readonly mention?: { readonly start: number; readonly end: number; readonly text: string }
|
readonly mention?: { readonly start: number; readonly end: number; readonly text: string }
|
||||||
}>
|
}>
|
||||||
|
readonly skills?: ReadonlyArray<{
|
||||||
|
readonly id: string
|
||||||
|
readonly mention?: { readonly start: number; readonly end: number; readonly text: string }
|
||||||
|
}>
|
||||||
readonly delivery?: "steer" | "queue" | null
|
readonly delivery?: "steer" | "queue" | null
|
||||||
readonly resume?: boolean | null
|
readonly resume?: boolean | null
|
||||||
}["delivery"]
|
}["delivery"]
|
||||||
@@ -3600,6 +3704,10 @@ export type SessionCommandInput = {
|
|||||||
readonly name: string
|
readonly name: string
|
||||||
readonly mention?: { readonly start: number; readonly end: number; readonly text: string }
|
readonly mention?: { readonly start: number; readonly end: number; readonly text: string }
|
||||||
}>
|
}>
|
||||||
|
readonly skills?: ReadonlyArray<{
|
||||||
|
readonly id: string
|
||||||
|
readonly mention?: { readonly start: number; readonly end: number; readonly text: string }
|
||||||
|
}>
|
||||||
readonly delivery?: "steer" | "queue" | null
|
readonly delivery?: "steer" | "queue" | null
|
||||||
readonly resume?: boolean | null
|
readonly resume?: boolean | null
|
||||||
}["resume"]
|
}["resume"]
|
||||||
@@ -3914,8 +4022,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 answer?: { readonly [x: string]: string | number | boolean | ReadonlyArray<string> } | undefined
|
||||||
|
readonly label?: string | undefined
|
||||||
|
}["key"]
|
||||||
|
readonly answer?: {
|
||||||
|
readonly key: string
|
||||||
|
readonly answer?: { readonly [x: string]: string | number | boolean | ReadonlyArray<string> } | undefined
|
||||||
|
readonly label?: string | undefined
|
||||||
|
}["answer"]
|
||||||
|
readonly label?: {
|
||||||
|
readonly key: string
|
||||||
|
readonly answer?: { readonly [x: string]: string | number | boolean | ReadonlyArray<string> } | undefined
|
||||||
|
readonly label?: string | undefined
|
||||||
|
}["label"]
|
||||||
}
|
}
|
||||||
|
|
||||||
export type IntegrationConnectKeyOutput = void
|
export type IntegrationConnectKeyOutput = void
|
||||||
@@ -3927,17 +4048,17 @@ export type IntegrationOauthConnectInput = {
|
|||||||
}["location"]
|
}["location"]
|
||||||
readonly methodID: {
|
readonly methodID: {
|
||||||
readonly methodID: string
|
readonly methodID: string
|
||||||
readonly inputs: { readonly [x: string]: string }
|
readonly answer?: { readonly [x: string]: string | number | boolean | ReadonlyArray<string> } | undefined
|
||||||
readonly label?: string | undefined
|
readonly label?: string | undefined
|
||||||
}["methodID"]
|
}["methodID"]
|
||||||
readonly inputs: {
|
readonly answer?: {
|
||||||
readonly methodID: string
|
readonly methodID: string
|
||||||
readonly inputs: { readonly [x: string]: string }
|
readonly answer?: { readonly [x: string]: string | number | boolean | ReadonlyArray<string> } | undefined
|
||||||
readonly label?: string | undefined
|
readonly label?: string | undefined
|
||||||
}["inputs"]
|
}["answer"]
|
||||||
readonly label?: {
|
readonly label?: {
|
||||||
readonly methodID: string
|
readonly methodID: string
|
||||||
readonly inputs: { readonly [x: string]: string }
|
readonly answer?: { readonly [x: string]: string | number | boolean | ReadonlyArray<string> } | undefined
|
||||||
readonly label?: string | undefined
|
readonly label?: string | undefined
|
||||||
}["label"]
|
}["label"]
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -148,6 +148,49 @@ 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 optionally submit a form answer", 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",
|
||||||
|
answer: { accountId: "account" },
|
||||||
|
})
|
||||||
|
await client.integration.oauth.connect({
|
||||||
|
integrationID: "github-copilot",
|
||||||
|
methodID: "device",
|
||||||
|
answer: { deploymentType: "enterprise", enabled: true, scopes: ["read:user"] },
|
||||||
|
})
|
||||||
|
await client.integration.connect.key({ integrationID: "openai", key: "secret" })
|
||||||
|
await client.integration.oauth.connect({ integrationID: "openai", methodID: "device" })
|
||||||
|
|
||||||
|
expect(await requests[0].json()).toEqual({ key: "secret", answer: { accountId: "account" } })
|
||||||
|
expect(await requests[1].json()).toEqual({
|
||||||
|
methodID: "device",
|
||||||
|
answer: { deploymentType: "enterprise", enabled: true, scopes: ["read:user"] },
|
||||||
|
})
|
||||||
|
expect(await requests[2].json()).toEqual({ key: "secret" })
|
||||||
|
expect(await requests[3].json()).toEqual({ methodID: "device" })
|
||||||
|
})
|
||||||
|
|
||||||
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({
|
||||||
|
|||||||
+58
-99
@@ -1,13 +1,9 @@
|
|||||||
{
|
{
|
||||||
"version": "7",
|
"version": "7",
|
||||||
"dialect": "sqlite",
|
"dialect": "sqlite",
|
||||||
"id": "2d214a71-3b0a-48c1-a667-741952c4e188",
|
"id": "15060ec5-05f7-4b86-b2a5-9108609432b3",
|
||||||
"prevIds": ["f14a9b18-8207-487e-a3d3-227e629ba9ad"],
|
"prevIds": ["1551a157-8959-4ba9-a52b-4ea3b7b28cae"],
|
||||||
"ddl": [
|
"ddl": [
|
||||||
{
|
|
||||||
"name": "workspace",
|
|
||||||
"entityType": "tables"
|
|
||||||
},
|
|
||||||
{
|
{
|
||||||
"name": "account_state",
|
"name": "account_state",
|
||||||
"entityType": "tables"
|
"entityType": "tables"
|
||||||
@@ -73,84 +69,8 @@
|
|||||||
"entityType": "tables"
|
"entityType": "tables"
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"type": "text",
|
"name": "workspace",
|
||||||
"notNull": false,
|
"entityType": "tables"
|
||||||
"autoincrement": false,
|
|
||||||
"default": null,
|
|
||||||
"generated": null,
|
|
||||||
"name": "id",
|
|
||||||
"entityType": "columns",
|
|
||||||
"table": "workspace"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"type": "text",
|
|
||||||
"notNull": true,
|
|
||||||
"autoincrement": false,
|
|
||||||
"default": null,
|
|
||||||
"generated": null,
|
|
||||||
"name": "type",
|
|
||||||
"entityType": "columns",
|
|
||||||
"table": "workspace"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"type": "text",
|
|
||||||
"notNull": true,
|
|
||||||
"autoincrement": false,
|
|
||||||
"default": "''",
|
|
||||||
"generated": null,
|
|
||||||
"name": "name",
|
|
||||||
"entityType": "columns",
|
|
||||||
"table": "workspace"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"type": "text",
|
|
||||||
"notNull": false,
|
|
||||||
"autoincrement": false,
|
|
||||||
"default": null,
|
|
||||||
"generated": null,
|
|
||||||
"name": "branch",
|
|
||||||
"entityType": "columns",
|
|
||||||
"table": "workspace"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"type": "text",
|
|
||||||
"notNull": false,
|
|
||||||
"autoincrement": false,
|
|
||||||
"default": null,
|
|
||||||
"generated": null,
|
|
||||||
"name": "directory",
|
|
||||||
"entityType": "columns",
|
|
||||||
"table": "workspace"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"type": "text",
|
|
||||||
"notNull": false,
|
|
||||||
"autoincrement": false,
|
|
||||||
"default": null,
|
|
||||||
"generated": null,
|
|
||||||
"name": "extra",
|
|
||||||
"entityType": "columns",
|
|
||||||
"table": "workspace"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"type": "text",
|
|
||||||
"notNull": true,
|
|
||||||
"autoincrement": false,
|
|
||||||
"default": null,
|
|
||||||
"generated": null,
|
|
||||||
"name": "project_id",
|
|
||||||
"entityType": "columns",
|
|
||||||
"table": "workspace"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"type": "integer",
|
|
||||||
"notNull": true,
|
|
||||||
"autoincrement": false,
|
|
||||||
"default": null,
|
|
||||||
"generated": null,
|
|
||||||
"name": "time_used",
|
|
||||||
"entityType": "columns",
|
|
||||||
"table": "workspace"
|
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"type": "integer",
|
"type": "integer",
|
||||||
@@ -1383,14 +1303,53 @@
|
|||||||
"table": "session_v2"
|
"table": "session_v2"
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"columns": ["project_id"],
|
"type": "text",
|
||||||
"tableTo": "project",
|
"notNull": false,
|
||||||
"columnsTo": ["id"],
|
"autoincrement": false,
|
||||||
"onUpdate": "NO ACTION",
|
"default": null,
|
||||||
"onDelete": "CASCADE",
|
"generated": null,
|
||||||
"nameExplicit": false,
|
"name": "id",
|
||||||
"name": "fk_workspace_project_id_project_id_fk",
|
"entityType": "columns",
|
||||||
"entityType": "fks",
|
"table": "workspace"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"type": "text",
|
||||||
|
"notNull": true,
|
||||||
|
"autoincrement": false,
|
||||||
|
"default": null,
|
||||||
|
"generated": null,
|
||||||
|
"name": "provider",
|
||||||
|
"entityType": "columns",
|
||||||
|
"table": "workspace"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"type": "text",
|
||||||
|
"notNull": true,
|
||||||
|
"autoincrement": false,
|
||||||
|
"default": null,
|
||||||
|
"generated": null,
|
||||||
|
"name": "binding",
|
||||||
|
"entityType": "columns",
|
||||||
|
"table": "workspace"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"type": "integer",
|
||||||
|
"notNull": true,
|
||||||
|
"autoincrement": false,
|
||||||
|
"default": null,
|
||||||
|
"generated": null,
|
||||||
|
"name": "created_at",
|
||||||
|
"entityType": "columns",
|
||||||
|
"table": "workspace"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"type": "integer",
|
||||||
|
"notNull": true,
|
||||||
|
"autoincrement": false,
|
||||||
|
"default": null,
|
||||||
|
"generated": null,
|
||||||
|
"name": "last_used_at",
|
||||||
|
"entityType": "columns",
|
||||||
"table": "workspace"
|
"table": "workspace"
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -1513,13 +1472,6 @@
|
|||||||
"entityType": "pks",
|
"entityType": "pks",
|
||||||
"table": "instruction_entry"
|
"table": "instruction_entry"
|
||||||
},
|
},
|
||||||
{
|
|
||||||
"columns": ["id"],
|
|
||||||
"nameExplicit": false,
|
|
||||||
"name": "workspace_pk",
|
|
||||||
"table": "workspace",
|
|
||||||
"entityType": "pks"
|
|
||||||
},
|
|
||||||
{
|
{
|
||||||
"columns": ["id"],
|
"columns": ["id"],
|
||||||
"nameExplicit": false,
|
"nameExplicit": false,
|
||||||
@@ -1611,6 +1563,13 @@
|
|||||||
"table": "session_v2",
|
"table": "session_v2",
|
||||||
"entityType": "pks"
|
"entityType": "pks"
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
"columns": ["id"],
|
||||||
|
"nameExplicit": false,
|
||||||
|
"name": "workspace_pk",
|
||||||
|
"table": "workspace",
|
||||||
|
"entityType": "pks"
|
||||||
|
},
|
||||||
{
|
{
|
||||||
"columns": [
|
"columns": [
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -1,20 +0,0 @@
|
|||||||
import { sqliteTable, text, integer } from "drizzle-orm/sqlite-core"
|
|
||||||
import { ProjectTable } from "../project/sql"
|
|
||||||
import { Project } from "../project"
|
|
||||||
import { Workspace } from "../workspace"
|
|
||||||
|
|
||||||
export const WorkspaceTable = sqliteTable("workspace", {
|
|
||||||
id: text().$type<Workspace.ID>().primaryKey(),
|
|
||||||
type: text().notNull(),
|
|
||||||
name: text().notNull().default(""),
|
|
||||||
branch: text(),
|
|
||||||
directory: text(),
|
|
||||||
extra: text({ mode: "json" }),
|
|
||||||
project_id: text()
|
|
||||||
.$type<Project.ID>()
|
|
||||||
.notNull()
|
|
||||||
.references(() => ProjectTable.id, { onDelete: "cascade" }),
|
|
||||||
time_used: integer()
|
|
||||||
.notNull()
|
|
||||||
.$default(() => Date.now()),
|
|
||||||
})
|
|
||||||
+1
@@ -42,5 +42,6 @@ export const migrations: DatabaseMigration.Migration[] = (
|
|||||||
import("./migration/20260622202450_simplify_session_input"),
|
import("./migration/20260622202450_simplify_session_input"),
|
||||||
import("./migration/20260804233008_loose_psylocke"),
|
import("./migration/20260804233008_loose_psylocke"),
|
||||||
import("./migration/20260805200742_import_legacy_credentials"),
|
import("./migration/20260805200742_import_legacy_credentials"),
|
||||||
|
import("./migration/20260808023530_workspace_domain"),
|
||||||
])
|
])
|
||||||
).map((module) => module.default)
|
).map((module) => module.default)
|
||||||
|
|||||||
@@ -0,0 +1,22 @@
|
|||||||
|
import { Effect } from "effect"
|
||||||
|
import type { DatabaseMigration } from "../migration"
|
||||||
|
|
||||||
|
const migration: DatabaseMigration.Migration = {
|
||||||
|
id: "20260808023530_workspace_domain",
|
||||||
|
up(tx) {
|
||||||
|
return Effect.gen(function* () {
|
||||||
|
yield* tx.run(`DROP TABLE \`workspace\`;`)
|
||||||
|
yield* tx.run(`
|
||||||
|
CREATE TABLE \`workspace\` (
|
||||||
|
\`id\` text PRIMARY KEY,
|
||||||
|
\`provider\` text NOT NULL,
|
||||||
|
\`binding\` text NOT NULL,
|
||||||
|
\`created_at\` integer NOT NULL,
|
||||||
|
\`last_used_at\` integer NOT NULL
|
||||||
|
);
|
||||||
|
`)
|
||||||
|
})
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
export default migration
|
||||||
@@ -4,19 +4,6 @@ import type { DatabaseMigration } from "./migration"
|
|||||||
const schema: Omit<DatabaseMigration.Migration, "id"> = {
|
const schema: Omit<DatabaseMigration.Migration, "id"> = {
|
||||||
up(tx) {
|
up(tx) {
|
||||||
return Effect.gen(function* () {
|
return Effect.gen(function* () {
|
||||||
yield* tx.run(`
|
|
||||||
CREATE TABLE \`workspace\` (
|
|
||||||
\`id\` text PRIMARY KEY,
|
|
||||||
\`type\` text NOT NULL,
|
|
||||||
\`name\` text DEFAULT '' NOT NULL,
|
|
||||||
\`branch\` text,
|
|
||||||
\`directory\` text,
|
|
||||||
\`extra\` text,
|
|
||||||
\`project_id\` text NOT NULL,
|
|
||||||
\`time_used\` integer NOT NULL,
|
|
||||||
CONSTRAINT \`fk_workspace_project_id_project_id_fk\` FOREIGN KEY (\`project_id\`) REFERENCES \`project\`(\`id\`) ON DELETE CASCADE
|
|
||||||
);
|
|
||||||
`)
|
|
||||||
yield* tx.run(`
|
yield* tx.run(`
|
||||||
CREATE TABLE \`account_state\` (
|
CREATE TABLE \`account_state\` (
|
||||||
\`id\` integer PRIMARY KEY,
|
\`id\` integer PRIMARY KEY,
|
||||||
@@ -216,6 +203,15 @@ const schema: Omit<DatabaseMigration.Migration, "id"> = {
|
|||||||
CONSTRAINT \`fk_session_v2_project_id_project_id_fk\` FOREIGN KEY (\`project_id\`) REFERENCES \`project\`(\`id\`) ON DELETE CASCADE
|
CONSTRAINT \`fk_session_v2_project_id_project_id_fk\` FOREIGN KEY (\`project_id\`) REFERENCES \`project\`(\`id\`) ON DELETE CASCADE
|
||||||
);
|
);
|
||||||
`)
|
`)
|
||||||
|
yield* tx.run(`
|
||||||
|
CREATE TABLE \`workspace\` (
|
||||||
|
\`id\` text PRIMARY KEY,
|
||||||
|
\`provider\` text NOT NULL,
|
||||||
|
\`binding\` text NOT NULL,
|
||||||
|
\`created_at\` integer NOT NULL,
|
||||||
|
\`last_used_at\` integer NOT NULL
|
||||||
|
);
|
||||||
|
`)
|
||||||
yield* tx.run(`CREATE UNIQUE INDEX \`event_aggregate_seq_idx\` ON \`event\` (\`aggregate_id\`,\`seq\`);`)
|
yield* tx.run(`CREATE UNIQUE INDEX \`event_aggregate_seq_idx\` ON \`event\` (\`aggregate_id\`,\`seq\`);`)
|
||||||
yield* tx.run(`CREATE INDEX \`event_aggregate_type_seq_idx\` ON \`event\` (\`aggregate_id\`,\`type\`,\`seq\`);`)
|
yield* tx.run(`CREATE INDEX \`event_aggregate_type_seq_idx\` ON \`event\` (\`aggregate_id\`,\`type\`,\`seq\`);`)
|
||||||
yield* tx.run(
|
yield* tx.run(
|
||||||
|
|||||||
@@ -5,6 +5,8 @@ import { ChildProcessSpawner } from "effect/unstable/process/ChildProcessSpawner
|
|||||||
import type { Files } from "./files"
|
import type { Files } from "./files"
|
||||||
import { makeFiles } from "./index"
|
import { makeFiles } from "./index"
|
||||||
import { makeLocalDriver } from "./local"
|
import { makeLocalDriver } from "./local"
|
||||||
|
import { Location } from "../location"
|
||||||
|
import { Workspace } from "../workspace"
|
||||||
|
|
||||||
export interface Interface {
|
export interface Interface {
|
||||||
readonly files: Files
|
readonly files: Files
|
||||||
@@ -17,10 +19,25 @@ const layer = Layer.effect(
|
|||||||
Service,
|
Service,
|
||||||
Effect.gen(function* () {
|
Effect.gen(function* () {
|
||||||
const spawner = yield* ChildProcessSpawner
|
const spawner = yield* ChildProcessSpawner
|
||||||
return Service.of({ files: makeFiles(makeLocalDriver(spawner)), spawner })
|
const location = yield* Location.Service
|
||||||
|
const workspace = yield* Workspace.Service
|
||||||
|
const driver = location.workspaceID
|
||||||
|
? yield* workspace.connect(location.workspaceID).pipe(
|
||||||
|
// Environment has no error channel; an unknown or destroyed placement is a configuration defect by design.
|
||||||
|
Effect.mapError(
|
||||||
|
(cause) => new Error(`Failed to bind Environment to workspace ${location.workspaceID}`, { cause }),
|
||||||
|
),
|
||||||
|
Effect.orDie,
|
||||||
|
)
|
||||||
|
: makeLocalDriver(spawner)
|
||||||
|
return Service.of({ files: makeFiles(driver), spawner: driver.spawner })
|
||||||
}),
|
}),
|
||||||
)
|
)
|
||||||
|
|
||||||
export const node = makeLocationNode({ service: Service, layer, deps: [CrossSpawnSpawner.node] })
|
export const node = makeLocationNode({
|
||||||
|
service: Service,
|
||||||
|
layer,
|
||||||
|
deps: [CrossSpawnSpawner.node, Location.node, Workspace.node],
|
||||||
|
})
|
||||||
|
|
||||||
export * as EnvironmentService from "./environment"
|
export * as EnvironmentService from "./environment"
|
||||||
|
|||||||
@@ -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(form: ReadonlyArray<Form.Field>, answer: Answer) {
|
||||||
const fields = new Map(form.fields.map((field) => [field.key, field] as const))
|
const fields = new Map(form.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 form) {
|
||||||
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>()
|
||||||
|
|||||||
@@ -70,6 +70,11 @@ type UsableModel = RemoteModel & {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export const Package = {
|
||||||
|
OpenAI: "@ai-sdk/github-copilot",
|
||||||
|
Anthropic: "@ai-sdk/github-copilot/anthropic",
|
||||||
|
} as const
|
||||||
|
|
||||||
export async function get(baseURL: string, headers: RequestInit["headers"], existing: readonly Model.Info[]) {
|
export async function get(baseURL: string, headers: RequestInit["headers"], existing: readonly Model.Info[]) {
|
||||||
const response = await fetch(`${baseURL}/models`, {
|
const response = await fetch(`${baseURL}/models`, {
|
||||||
headers,
|
headers,
|
||||||
@@ -141,7 +146,7 @@ function build(id: Model.ID, remote: UsableModel, baseURL: string, previous?: Mo
|
|||||||
providerID: Provider.ID.githubCopilot,
|
providerID: Provider.ID.githubCopilot,
|
||||||
family: previous?.family ?? Model.Family.make(remote.capabilities.family),
|
family: previous?.family ?? Model.Family.make(remote.capabilities.family),
|
||||||
name: previous?.name ?? remote.name,
|
name: previous?.name ?? remote.name,
|
||||||
package: Provider.aisdk(messages ? "@ai-sdk/anthropic" : "@ai-sdk/github-copilot"),
|
package: Provider.aisdk(messages ? Package.Anthropic : Package.OpenAI),
|
||||||
settings: Provider.mergeOverlay(previous?.settings, {
|
settings: Provider.mergeOverlay(previous?.settings, {
|
||||||
baseURL: messages ? `${baseURL}/v1` : baseURL,
|
baseURL: messages ? `${baseURL}/v1` : baseURL,
|
||||||
...(endpoint ? { endpoint } : {}),
|
...(endpoint ? { endpoint } : {}),
|
||||||
|
|||||||
@@ -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: (answer: 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 answer?: 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 answer?: 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 answer?: 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}`))
|
||||||
}
|
}
|
||||||
|
const answer = input.answer ?? {}
|
||||||
|
if (method.method.form) {
|
||||||
|
const invalid = Form.validateFields(method.method.form) ?? Form.validateAnswer(method.method.form, answer)
|
||||||
|
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(answer)).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,24 @@ 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}`))
|
||||||
|
const answer = input.answer ?? {}
|
||||||
|
if (method.type === "key" && method.form) {
|
||||||
|
const invalid = Form.validateFields(method.form) ?? Form.validateAnswer(method.form, answer)
|
||||||
|
if (invalid) return yield* new AuthorizationError({ cause: new Error(invalid) })
|
||||||
|
}
|
||||||
|
if (method.type === "key" && !method.form && Object.keys(answer).length > 0) {
|
||||||
|
return yield* new AuthorizationError({ cause: new Error("Key method does not accept a form answer") })
|
||||||
|
}
|
||||||
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(answer).length > 0 ? { configuration: answer } : {}),
|
||||||
|
}),
|
||||||
})
|
})
|
||||||
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,
|
||||||
|
answer: input.answer,
|
||||||
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,
|
answer: input.answer,
|
||||||
label: input.label,
|
label: input.label,
|
||||||
}),
|
}),
|
||||||
),
|
),
|
||||||
@@ -260,7 +261,7 @@ export const make = Effect.fn("PluginHost.make")(function* (plugin: import("../p
|
|||||||
update: (id, update) => draft.update(Integration.ID.make(id), update),
|
update: (id, update) => draft.update(Integration.ID.make(id), update),
|
||||||
remove: (id) => draft.remove(Integration.ID.make(id)),
|
remove: (id) => draft.remove(Integration.ID.make(id)),
|
||||||
method: {
|
method: {
|
||||||
list: (id) => mutable(draft.method.list(Integration.ID.make(id))),
|
list: (id) => draft.method.list(Integration.ID.make(id)),
|
||||||
update: (input) => draft.method.update(methodImplementation(input)),
|
update: (input) => draft.method.update(methodImplementation(input)),
|
||||||
remove: (id, method) =>
|
remove: (id, method) =>
|
||||||
draft.method.remove(Integration.ID.make(id), Schema.decodeUnknownSync(Integration.Method)(method)),
|
draft.method.remove(Integration.ID.make(id), Schema.decodeUnknownSync(Integration.Method)(method)),
|
||||||
@@ -363,8 +364,8 @@ function methodImplementation(input: IntegrationMethodRegistration): Integration
|
|||||||
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: { ...input.method, id: Integration.MethodID.make(input.method.id) },
|
||||||
authorize: (inputs) =>
|
authorize: (answer) =>
|
||||||
input.authorize(inputs).pipe(
|
input.authorize(answer).pipe(
|
||||||
Effect.map((authorization) => {
|
Effect.map((authorization) => {
|
||||||
if (authorization.mode === "auto") {
|
if (authorization.mode === "auto") {
|
||||||
return {
|
return {
|
||||||
@@ -385,18 +386,18 @@ function methodImplementation(input: IntegrationMethodRegistration): Integration
|
|||||||
if (input.method.type === "env") {
|
if (input.method.type === "env") {
|
||||||
return {
|
return {
|
||||||
integrationID: Integration.ID.make(input.integrationID),
|
integrationID: Integration.ID.make(input.integrationID),
|
||||||
method: { type: "env", names: input.method.names },
|
method: input.method,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (input.method.type === "command") {
|
if (input.method.type === "command") {
|
||||||
return {
|
return {
|
||||||
integrationID: Integration.ID.make(input.integrationID),
|
integrationID: Integration.ID.make(input.integrationID),
|
||||||
method: Schema.decodeUnknownSync(Integration.CommandMethod)(input.method),
|
method: { ...input.method, id: Integration.MethodID.make(input.method.id) },
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return {
|
return {
|
||||||
integrationID: Integration.ID.make(input.integrationID),
|
integrationID: Integration.ID.make(input.integrationID),
|
||||||
method: { type: "key", label: input.method.label },
|
method: input.method,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -11,6 +11,7 @@ import { Provider } from "@opencode-ai/schema/provider"
|
|||||||
import { AbsolutePath } from "@opencode-ai/schema/schema"
|
import { AbsolutePath } from "@opencode-ai/schema/schema"
|
||||||
import { Session } from "@opencode-ai/schema/session"
|
import { Session } from "@opencode-ai/schema/session"
|
||||||
import { SessionMessage } from "@opencode-ai/schema/session-message"
|
import { SessionMessage } from "@opencode-ai/schema/session-message"
|
||||||
|
import { Skill } from "@opencode-ai/schema/skill"
|
||||||
import { Workspace } from "@opencode-ai/schema/workspace"
|
import { Workspace } from "@opencode-ai/schema/workspace"
|
||||||
import { WebSearch } from "@opencode-ai/schema/websearch"
|
import { WebSearch } from "@opencode-ai/schema/websearch"
|
||||||
import { DateTime, Effect, Scope, Stream } from "effect"
|
import { DateTime, Effect, Scope, Stream } from "effect"
|
||||||
@@ -179,8 +180,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: (answer) =>
|
||||||
Effect.promise(() => input.authorize(inputs)).pipe(
|
Effect.promise(() => input.authorize(answer)).pipe(
|
||||||
Effect.map((authorization) =>
|
Effect.map((authorization) =>
|
||||||
authorization.mode === "auto"
|
authorization.mode === "auto"
|
||||||
? {
|
? {
|
||||||
@@ -296,6 +297,7 @@ export function fromPromise(plugin: Plugin) {
|
|||||||
...input,
|
...input,
|
||||||
sessionID: Session.ID.make(input.sessionID),
|
sessionID: Session.ID.make(input.sessionID),
|
||||||
id: input.id == null ? undefined : SessionMessage.ID.make(input.id),
|
id: input.id == null ? undefined : SessionMessage.ID.make(input.id),
|
||||||
|
skills: input.skills?.map((skill) => ({ ...skill, id: Skill.ID.make(skill.id) })),
|
||||||
delivery: input.delivery ?? undefined,
|
delivery: input.delivery ?? undefined,
|
||||||
resume: input.resume ?? undefined,
|
resume: input.resume ?? undefined,
|
||||||
}),
|
}),
|
||||||
@@ -310,6 +312,7 @@ export function fromPromise(plugin: Plugin) {
|
|||||||
id: input.id == null ? undefined : SessionMessage.ID.make(input.id),
|
id: input.id == null ? undefined : SessionMessage.ID.make(input.id),
|
||||||
agent: input.agent == null ? undefined : Agent.ID.make(input.agent),
|
agent: input.agent == null ? undefined : Agent.ID.make(input.agent),
|
||||||
model: input.model == null ? undefined : model(input.model),
|
model: input.model == null ? undefined : model(input.model),
|
||||||
|
skills: input.skills?.map((skill) => ({ ...skill, id: Skill.ID.make(skill.id) })),
|
||||||
arguments: input.arguments ?? undefined,
|
arguments: input.arguments ?? undefined,
|
||||||
delivery: input.delivery ?? undefined,
|
delivery: input.delivery ?? undefined,
|
||||||
resume: input.resume ?? undefined,
|
resume: input.resume ?? undefined,
|
||||||
@@ -359,12 +362,18 @@ type Wire<Value> = unknown extends Value
|
|||||||
? Value
|
? Value
|
||||||
: Value extends DateTime.DateTime
|
: Value extends DateTime.DateTime
|
||||||
? number
|
? number
|
||||||
|
: Value extends readonly [infer Head, ...infer Tail]
|
||||||
|
? [Wire<Head>, ...WireTuple<Tail>]
|
||||||
: Value extends ReadonlyArray<infer Item>
|
: Value extends ReadonlyArray<infer Item>
|
||||||
? Array<Wire<Item>>
|
? Array<Wire<Item>>
|
||||||
: Value extends object
|
: Value extends object
|
||||||
? { -readonly [Key in keyof Value]: Wire<Value[Key]> }
|
? { -readonly [Key in keyof Value]: Wire<Value[Key]> }
|
||||||
: Value
|
: 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 {
|
||||||
if (DateTime.isDateTime(value)) return DateTime.toEpochMillis(value)
|
if (DateTime.isDateTime(value)) return DateTime.toEpochMillis(value)
|
||||||
|
|||||||
@@ -1,6 +1,9 @@
|
|||||||
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 { Form } from "@opencode-ai/schema/form"
|
||||||
import { Provider } from "../../provider"
|
import { Provider } from "../../provider"
|
||||||
|
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 +16,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 form = iife(() => {
|
||||||
|
if (resolveResourceName(configured) || typeof configured?.baseURL === "string") return
|
||||||
|
return Form.Fields.make([
|
||||||
|
{
|
||||||
|
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",
|
||||||
|
form,
|
||||||
|
},
|
||||||
|
})
|
||||||
|
})
|
||||||
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,53 @@ 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 { Form } from "@opencode-ai/schema/form"
|
||||||
|
import { Provider } from "../../provider"
|
||||||
|
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 form = iife(() => {
|
||||||
|
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 = Form.StringField.make({
|
||||||
|
type: "string",
|
||||||
|
key: "accountId",
|
||||||
|
title: "Enter your Cloudflare Account ID",
|
||||||
|
placeholder: "e.g. 1234567890abcdef1234567890abcdef",
|
||||||
|
required: true,
|
||||||
|
})
|
||||||
|
const gatewayIdForm = Form.StringField.make({
|
||||||
|
type: "string",
|
||||||
|
key: "gatewayId",
|
||||||
|
title: "Enter your Cloudflare AI Gateway ID",
|
||||||
|
placeholder: "e.g. my-gateway",
|
||||||
|
required: true,
|
||||||
|
})
|
||||||
|
if (accountId) return Form.Fields.make([gatewayIdForm])
|
||||||
|
if (gatewayId) return Form.Fields.make([accountIdForm])
|
||||||
|
return Form.Fields.make([accountIdForm, gatewayIdForm])
|
||||||
|
})
|
||||||
|
yield* ctx.integration.transform((draft) => {
|
||||||
|
draft.method.update({
|
||||||
|
integrationID: providerID,
|
||||||
|
method: {
|
||||||
|
type: "key",
|
||||||
|
label: "Gateway API token",
|
||||||
|
form,
|
||||||
|
},
|
||||||
|
})
|
||||||
|
})
|
||||||
yield* ctx.aisdk.hook(
|
yield* ctx.aisdk.hook(
|
||||||
"sdk",
|
"sdk",
|
||||||
Effect.fn(function* (evt) {
|
Effect.fn(function* (evt) {
|
||||||
@@ -46,7 +89,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,39 @@ 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 { Form } from "@opencode-ai/schema/form"
|
||||||
import { Provider } from "../../provider"
|
import { Provider } from "../../provider"
|
||||||
|
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 form = iife(() => {
|
||||||
|
if (typeof configured?.baseURL === "string" || resolveAccountId(configured ?? {})) return
|
||||||
|
return Form.Fields.make([
|
||||||
|
{
|
||||||
|
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",
|
||||||
|
form,
|
||||||
|
},
|
||||||
|
})
|
||||||
|
})
|
||||||
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)
|
||||||
|
})
|
||||||
@@ -15,6 +15,8 @@ import type { PluginInternal } from "../internal"
|
|||||||
const clientID = "Ov23li8tweQw6odWQebz"
|
const clientID = "Ov23li8tweQw6odWQebz"
|
||||||
const apiVersion = "2026-06-01"
|
const apiVersion = "2026-06-01"
|
||||||
const userApiVersion = "2025-04-01"
|
const userApiVersion = "2025-04-01"
|
||||||
|
const copilotVersion = "0.26.7"
|
||||||
|
const editorVersion = "vscode/1.99.3"
|
||||||
const pollingSafetyMargin = 3000
|
const pollingSafetyMargin = 3000
|
||||||
const methodID = Integration.MethodID.make("device")
|
const methodID = Integration.MethodID.make("device")
|
||||||
|
|
||||||
@@ -47,30 +49,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: [
|
form: [
|
||||||
{
|
{
|
||||||
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: (answer) =>
|
||||||
Effect.gen(function* () {
|
Effect.gen(function* () {
|
||||||
const enterprise = inputs.deploymentType === "enterprise"
|
const enterprise = answer.deploymentType === "enterprise"
|
||||||
if (enterprise && !inputs.enterpriseUrl) return yield* Effect.fail(new Error("Enterprise URL is required"))
|
const enterpriseUrl = typeof answer.enterpriseUrl === "string" ? answer.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",
|
||||||
@@ -188,11 +193,28 @@ export const GithubCopilotPlugin = define({
|
|||||||
})
|
})
|
||||||
|
|
||||||
yield* ctx.integration.transform((draft) => {
|
yield* ctx.integration.transform((draft) => {
|
||||||
|
draft.method.remove("github-copilot", { type: "key" })
|
||||||
draft.method.update(oauth(ctx.app))
|
draft.method.update(oauth(ctx.app))
|
||||||
})
|
})
|
||||||
yield* ctx.catalog.transform((evt) => {
|
yield* ctx.catalog.transform((evt) => {
|
||||||
const item = evt.provider.get(Provider.ID.githubCopilot)
|
const item = evt.provider.get(Provider.ID.githubCopilot)
|
||||||
if (!item) return
|
if (!item) return
|
||||||
|
evt.provider.update(item.provider.id, (provider) => {
|
||||||
|
if (Provider.packageName(provider.package) === "@ai-sdk/openai-compatible") {
|
||||||
|
provider.package = Provider.aisdk(CopilotModels.Package.OpenAI)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
for (const model of item.models.values()) {
|
||||||
|
evt.model.update(item.provider.id, model.id, (draft) => {
|
||||||
|
const packageName = Provider.packageName(draft.package)
|
||||||
|
if (packageName === "@ai-sdk/openai-compatible") {
|
||||||
|
draft.package = Provider.aisdk(CopilotModels.Package.OpenAI)
|
||||||
|
}
|
||||||
|
if (packageName === "@ai-sdk/anthropic") {
|
||||||
|
draft.package = Provider.aisdk(CopilotModels.Package.Anthropic)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
if (loaded.models) {
|
if (loaded.models) {
|
||||||
for (const id of item.models.keys()) {
|
for (const id of item.models.keys()) {
|
||||||
if (!loaded.models.has(Model.ID.make(id))) evt.model.remove(item.provider.id, id)
|
if (!loaded.models.has(Model.ID.make(id))) evt.model.remove(item.provider.id, id)
|
||||||
@@ -226,14 +248,14 @@ export const GithubCopilotPlugin = define({
|
|||||||
"sdk",
|
"sdk",
|
||||||
Effect.fn(function* (evt) {
|
Effect.fn(function* (evt) {
|
||||||
if (evt.model.providerID !== Provider.ID.githubCopilot) return
|
if (evt.model.providerID !== Provider.ID.githubCopilot) return
|
||||||
if (evt.package !== "@ai-sdk/github-copilot" && evt.package !== "@ai-sdk/anthropic") return
|
if (evt.package !== CopilotModels.Package.OpenAI && evt.package !== CopilotModels.Package.Anthropic) return
|
||||||
|
const anthropic = evt.package === CopilotModels.Package.Anthropic
|
||||||
evt.options.fetch = copilotFetch(
|
evt.options.fetch = copilotFetch(
|
||||||
typeof evt.options.apiKey === "string" ? evt.options.apiKey : undefined,
|
typeof evt.options.apiKey === "string" ? evt.options.apiKey : undefined,
|
||||||
evt.options.fetch,
|
evt.options.fetch,
|
||||||
evt.package === "@ai-sdk/anthropic",
|
anthropic,
|
||||||
ctx.app,
|
|
||||||
)
|
)
|
||||||
if (evt.package === "@ai-sdk/anthropic") {
|
if (anthropic) {
|
||||||
evt.options.headers = {
|
evt.options.headers = {
|
||||||
...evt.options.headers,
|
...evt.options.headers,
|
||||||
"anthropic-beta": "interleaved-thinking-2025-05-14",
|
"anthropic-beta": "interleaved-thinking-2025-05-14",
|
||||||
@@ -312,12 +334,7 @@ function request(url: string, init: RequestInit) {
|
|||||||
|
|
||||||
type Fetch = (input: Parameters<typeof fetch>[0], init?: RequestInit) => Promise<Response>
|
type Fetch = (input: Parameters<typeof fetch>[0], init?: RequestInit) => Promise<Response>
|
||||||
|
|
||||||
export function copilotFetch(
|
export function copilotFetch(token: string | undefined, upstream: Fetch | undefined, anthropic: boolean): Fetch {
|
||||||
token: string | undefined,
|
|
||||||
upstream: Fetch | undefined,
|
|
||||||
anthropic: boolean,
|
|
||||||
app: App.Info,
|
|
||||||
): Fetch {
|
|
||||||
const send = upstream ?? fetch
|
const send = upstream ?? fetch
|
||||||
return async (input, init) => {
|
return async (input, init) => {
|
||||||
const requestHeaders = new Headers(init?.headers)
|
const requestHeaders = new Headers(init?.headers)
|
||||||
@@ -326,7 +343,10 @@ export function copilotFetch(
|
|||||||
requestHeaders.delete("x-api-key")
|
requestHeaders.delete("x-api-key")
|
||||||
requestHeaders.set("Authorization", `Bearer ${token}`)
|
requestHeaders.set("Authorization", `Bearer ${token}`)
|
||||||
}
|
}
|
||||||
requestHeaders.set("User-Agent", App.useragent(app))
|
requestHeaders.set("User-Agent", `GitHubCopilotChat/${copilotVersion}`)
|
||||||
|
requestHeaders.set("Editor-Version", editorVersion)
|
||||||
|
requestHeaders.set("Editor-Plugin-Version", `copilot-chat/${copilotVersion}`)
|
||||||
|
requestHeaders.set("Copilot-Integration-Id", "vscode-chat")
|
||||||
requestHeaders.set("Openai-Intent", "conversation-edits")
|
requestHeaders.set("Openai-Intent", "conversation-edits")
|
||||||
requestHeaders.set("X-GitHub-Api-Version", apiVersion)
|
requestHeaders.set("X-GitHub-Api-Version", apiVersion)
|
||||||
if (anthropic) requestHeaders.set("anthropic-beta", "interleaved-thinking-2025-05-14")
|
if (anthropic) requestHeaders.set("anthropic-beta", "interleaved-thinking-2025-05-14")
|
||||||
|
|||||||
@@ -43,9 +43,9 @@ function oauth(http: HttpClient.HttpClient) {
|
|||||||
type: "oauth",
|
type: "oauth",
|
||||||
label: "OpenCode Console account",
|
label: "OpenCode Console account",
|
||||||
},
|
},
|
||||||
authorize: (inputs) =>
|
authorize: (answer) =>
|
||||||
Effect.gen(function* () {
|
Effect.gen(function* () {
|
||||||
const server = yield* normalizeServer(inputs.server ?? defaultServer)
|
const server = yield* normalizeServer(answer.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)
|
||||||
@@ -226,9 +226,10 @@ function withoutCredentials(body: Readonly<Record<string, unknown>> | undefined)
|
|||||||
return Object.fromEntries(Object.entries(body ?? {}).filter(([key]) => key !== "apiKey" && key !== "headers"))
|
return Object.fromEntries(Object.entries(body ?? {}).filter(([key]) => key !== "apiKey" && key !== "headers"))
|
||||||
}
|
}
|
||||||
|
|
||||||
function normalizeServer(input: string) {
|
function normalizeServer(input: unknown) {
|
||||||
return Effect.try({
|
return Effect.try({
|
||||||
try: () => {
|
try: () => {
|
||||||
|
if (typeof input !== "string") throw new Error("expected string")
|
||||||
const url = new URL(input)
|
const url = new URL(input)
|
||||||
if (url.protocol !== "http:" && url.protocol !== "https:") throw new Error("expected HTTP(S)")
|
if (url.protocol !== "http:" && url.protocol !== "https:") throw new Error("expected HTTP(S)")
|
||||||
return `${url.origin}${url.pathname.replace(/\/+$/, "")}`
|
return `${url.origin}${url.pathname.replace(/\/+$/, "")}`
|
||||||
|
|||||||
@@ -233,7 +233,7 @@ const layer = Layer.effect(
|
|||||||
const bus = yield* Bus.Service
|
const bus = yield* Bus.Service
|
||||||
const watcher = yield* Watcher.Service
|
const watcher = yield* Watcher.Service
|
||||||
const fs = yield* FSUtil.Service
|
const fs = yield* FSUtil.Service
|
||||||
const ready = yield* Deferred.make<void>()
|
const ready = { current: yield* Deferred.make<void>() }
|
||||||
let observed = 0
|
let observed = 0
|
||||||
|
|
||||||
// Configured local plugin files can live outside config roots, where the
|
// Configured local plugin files can live outside config roots, where the
|
||||||
@@ -291,7 +291,13 @@ const layer = Layer.effect(
|
|||||||
bus.subscribe([Event.Updated, SdkPlugins.Updated]),
|
bus.subscribe([Event.Updated, SdkPlugins.Updated]),
|
||||||
).pipe(
|
).pipe(
|
||||||
// Make accepted work visible to flush before coalescing the burst.
|
// Make accepted work visible to flush before coalescing the burst.
|
||||||
Stream.mapEffect(() => Effect.sync(() => ++observed)),
|
Stream.mapEffect(() =>
|
||||||
|
Effect.gen(function* () {
|
||||||
|
observed++
|
||||||
|
if (yield* Deferred.isDone(ready.current)) ready.current = yield* Deferred.make<void>()
|
||||||
|
return observed
|
||||||
|
}),
|
||||||
|
),
|
||||||
)
|
)
|
||||||
yield* Stream.concat(Stream.succeed(0), updates).pipe(
|
yield* Stream.concat(Stream.succeed(0), updates).pipe(
|
||||||
// Keep observing updates while activation runs, retaining only the latest generation request.
|
// Keep observing updates while activation runs, retaining only the latest generation request.
|
||||||
@@ -300,12 +306,12 @@ const layer = Layer.effect(
|
|||||||
Stream.runForEach((target) =>
|
Stream.runForEach((target) =>
|
||||||
Effect.gen(function* () {
|
Effect.gen(function* () {
|
||||||
yield* activate()
|
yield* activate()
|
||||||
if (observed === target) yield* Deferred.succeed(ready, undefined)
|
if (observed === target) yield* Deferred.succeed(ready.current, undefined)
|
||||||
}).pipe(Effect.catchCause((cause) => Effect.logError("failed to reload plugins", { cause }))),
|
}).pipe(Effect.catchCause((cause) => Effect.logError("failed to reload plugins", { cause }))),
|
||||||
),
|
),
|
||||||
Effect.forkScoped({ startImmediately: true }),
|
Effect.forkScoped({ startImmediately: true }),
|
||||||
)
|
)
|
||||||
return Service.of({ flush: Deferred.await(ready) })
|
return Service.of({ flush: Effect.suspend(() => Deferred.await(ready.current)) })
|
||||||
}),
|
}),
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|||||||
@@ -218,10 +218,11 @@ export interface Interface {
|
|||||||
text: string
|
text: string
|
||||||
files?: PromptInput.Prompt["files"]
|
files?: PromptInput.Prompt["files"]
|
||||||
agents?: PromptInput.Prompt["agents"]
|
agents?: PromptInput.Prompt["agents"]
|
||||||
|
skills?: PromptInput.Prompt["skills"]
|
||||||
metadata?: Record<string, unknown>
|
metadata?: Record<string, unknown>
|
||||||
delivery?: SessionPending.Delivery
|
delivery?: SessionPending.Delivery
|
||||||
resume?: boolean
|
resume?: boolean
|
||||||
}) => Effect.Effect<SessionPending.User, NotFoundError | PromptConflictError | AttachmentError>
|
}) => Effect.Effect<SessionPending.User, NotFoundError | PromptConflictError | AttachmentError | SkillNotFoundError>
|
||||||
/** Generates text from current Session context without admitting input or mutating history. */
|
/** Generates text from current Session context without admitting input or mutating history. */
|
||||||
readonly generate: (input: {
|
readonly generate: (input: {
|
||||||
sessionID: SessionSchema.ID
|
sessionID: SessionSchema.ID
|
||||||
@@ -236,11 +237,17 @@ export interface Interface {
|
|||||||
model?: Model.Ref
|
model?: Model.Ref
|
||||||
files?: PromptInput.Prompt["files"]
|
files?: PromptInput.Prompt["files"]
|
||||||
agents?: PromptInput.Prompt["agents"]
|
agents?: PromptInput.Prompt["agents"]
|
||||||
|
skills?: PromptInput.Prompt["skills"]
|
||||||
delivery?: SessionPending.Delivery
|
delivery?: SessionPending.Delivery
|
||||||
resume?: boolean
|
resume?: boolean
|
||||||
}) => Effect.Effect<
|
}) => Effect.Effect<
|
||||||
SessionPending.User,
|
SessionPending.User,
|
||||||
NotFoundError | PromptConflictError | AttachmentError | Command.NotFoundError | Command.EvaluationError
|
| NotFoundError
|
||||||
|
| PromptConflictError
|
||||||
|
| AttachmentError
|
||||||
|
| SkillNotFoundError
|
||||||
|
| Command.NotFoundError
|
||||||
|
| Command.EvaluationError
|
||||||
>
|
>
|
||||||
readonly shell: (input: {
|
readonly shell: (input: {
|
||||||
id?: Event.ID
|
id?: Event.ID
|
||||||
@@ -565,9 +572,11 @@ const layer = Layer.effect(
|
|||||||
// Resolved lazily so prompt admission only boots location services when an
|
// Resolved lazily so prompt admission only boots location services when an
|
||||||
// image attachment actually needs the resizer.
|
// image attachment actually needs the resizer.
|
||||||
const image = Image.Service.pipe(Effect.provide(locations.get(session.location)))
|
const image = Image.Service.pipe(Effect.provide(locations.get(session.location)))
|
||||||
|
const skills = Skill.Service.pipe(Effect.provide(locations.get(session.location)))
|
||||||
const prompt = yield* resolvePrompt(
|
const prompt = yield* resolvePrompt(
|
||||||
{ text: input.text, files: input.files, agents: input.agents },
|
{ text: input.text, files: input.files, agents: input.agents, skills: input.skills },
|
||||||
image,
|
image,
|
||||||
|
skills,
|
||||||
).pipe(Effect.provideService(FSUtil.Service, fs))
|
).pipe(Effect.provideService(FSUtil.Service, fs))
|
||||||
const messageID = input.id ?? SessionMessage.ID.create()
|
const messageID = input.id ?? SessionMessage.ID.create()
|
||||||
const admittedInput = SessionPending.Message.make({
|
const admittedInput = SessionPending.Message.make({
|
||||||
@@ -633,6 +642,7 @@ const layer = Layer.effect(
|
|||||||
text: evaluated.text,
|
text: evaluated.text,
|
||||||
files: input.files,
|
files: input.files,
|
||||||
agents: input.agents,
|
agents: input.agents,
|
||||||
|
skills: input.skills,
|
||||||
delivery: input.delivery,
|
delivery: input.delivery,
|
||||||
resume: input.resume,
|
resume: input.resume,
|
||||||
})
|
})
|
||||||
@@ -645,9 +655,7 @@ const layer = Layer.effect(
|
|||||||
yield* execution.awaitIdle(input.sessionID)
|
yield* execution.awaitIdle(input.sessionID)
|
||||||
const started = yield* Effect.gen(function* () {
|
const started = yield* Effect.gen(function* () {
|
||||||
const shell = yield* Shell.Service
|
const shell = yield* Shell.Service
|
||||||
return yield* shell
|
return yield* shell.create({ command: input.command, cwd: session.location.directory, timeout: 0 })
|
||||||
.create({ command: input.command, cwd: session.location.directory, timeout: 0 })
|
|
||||||
.pipe(Effect.orDie)
|
|
||||||
}).pipe(Effect.provide(locations.get(session.location)))
|
}).pipe(Effect.provide(locations.get(session.location)))
|
||||||
yield* bus.publish(
|
yield* bus.publish(
|
||||||
SessionEvent.Shell.Started,
|
SessionEvent.Shell.Started,
|
||||||
@@ -897,12 +905,28 @@ function synthesizeTerminalShellInfo(started: ShellSchema.Info): ShellSchema.Inf
|
|||||||
const resolvePrompt = Effect.fn("Session.resolvePrompt")(function* (
|
const resolvePrompt = Effect.fn("Session.resolvePrompt")(function* (
|
||||||
input: PromptInput.Prompt,
|
input: PromptInput.Prompt,
|
||||||
image: Effect.Effect<Image.Interface>,
|
image: Effect.Effect<Image.Interface>,
|
||||||
|
skills: Effect.Effect<Skill.Interface>,
|
||||||
) {
|
) {
|
||||||
const fs = yield* FSUtil.Service
|
const fs = yield* FSUtil.Service
|
||||||
const files = input.files
|
const files = input.files
|
||||||
? yield* Effect.forEach(input.files, (file) => materializeAttachment(fs, file, image), { concurrency: 8 })
|
? yield* Effect.forEach(input.files, (file) => materializeAttachment(fs, file, image), { concurrency: 8 })
|
||||||
: undefined
|
: undefined
|
||||||
return Prompt.make({ text: input.text, agents: input.agents, files })
|
const requested = input.skills
|
||||||
|
const selected = yield* Effect.gen(function* () {
|
||||||
|
if (!requested?.length) return undefined
|
||||||
|
const available = yield* (yield* skills).list()
|
||||||
|
return yield* Effect.forEach(requested, (attachment) => {
|
||||||
|
const skill = available.find((item) => item.id === attachment.id)
|
||||||
|
if (!skill) return Effect.fail(new SkillNotFoundError({ skill: attachment.id }))
|
||||||
|
return Effect.succeed({
|
||||||
|
id: skill.id,
|
||||||
|
name: skill.name,
|
||||||
|
text: Skill.toModelOutput(skill, []),
|
||||||
|
mention: attachment.mention,
|
||||||
|
})
|
||||||
|
})
|
||||||
|
})
|
||||||
|
return Prompt.make({ text: input.text, agents: input.agents, files, skills: selected?.length ? selected : undefined })
|
||||||
})
|
})
|
||||||
|
|
||||||
const MAX_ATTACHMENT_BYTES = 20 * 1024 * 1024
|
const MAX_ATTACHMENT_BYTES = 20 * 1024 * 1024
|
||||||
|
|||||||
@@ -124,7 +124,8 @@ const serialize = (message: SessionMessage.Info) => {
|
|||||||
(file) =>
|
(file) =>
|
||||||
`[Attached ${file.mime}: ${file.name ?? (file.source.type === "uri" ? file.source.uri : "inline attachment")}]`,
|
`[Attached ${file.mime}: ${file.name ?? (file.source.type === "uri" ? file.source.uri : "inline attachment")}]`,
|
||||||
) ?? []
|
) ?? []
|
||||||
return [`[User]: ${message.text}`, ...files].join("\n")
|
const skills = message.skills?.map((skill) => `[Attached skill: ${skill.name}]\n${skill.text}`) ?? []
|
||||||
|
return [`[User]: ${message.text}`, ...skills, ...files].join("\n")
|
||||||
}
|
}
|
||||||
if (message.type === "assistant") {
|
if (message.type === "assistant") {
|
||||||
return message.content
|
return message.content
|
||||||
|
|||||||
@@ -16,7 +16,6 @@ import { SessionPendingTable, SessionMessageTable, SessionTable } from "./sql"
|
|||||||
import { Slug } from "../util/slug"
|
import { Slug } from "../util/slug"
|
||||||
import { Money } from "@opencode-ai/schema/money"
|
import { Money } from "@opencode-ai/schema/money"
|
||||||
import type { SessionSchema } from "./schema"
|
import type { SessionSchema } from "./schema"
|
||||||
import { WorkspaceTable } from "../control-plane/workspace.sql"
|
|
||||||
|
|
||||||
type DatabaseService = Database.Interface["db"]
|
type DatabaseService = Database.Interface["db"]
|
||||||
type CurrentDurableEvent = Extract<SessionEvent.Event, { readonly durable: object }>
|
type CurrentDurableEvent = Extract<SessionEvent.Event, { readonly durable: object }>
|
||||||
@@ -376,13 +375,6 @@ const layer = Layer.effectDiscard(
|
|||||||
.get()
|
.get()
|
||||||
.pipe(Effect.orDie)
|
.pipe(Effect.orDie)
|
||||||
if (!stored) return yield* Effect.die(new SessionAlreadyProjected())
|
if (!stored) return yield* Effect.die(new SessionAlreadyProjected())
|
||||||
if (!event.data.location.workspaceID) return
|
|
||||||
yield* db
|
|
||||||
.update(WorkspaceTable)
|
|
||||||
.set({ time_used: Date.now() })
|
|
||||||
.where(eq(WorkspaceTable.id, event.data.location.workspaceID))
|
|
||||||
.run()
|
|
||||||
.pipe(Effect.orDie)
|
|
||||||
}),
|
}),
|
||||||
)
|
)
|
||||||
yield* bus.project(SessionEvent.Moved, (event) =>
|
yield* bus.project(SessionEvent.Moved, (event) =>
|
||||||
@@ -453,6 +445,7 @@ const layer = Layer.effectDiscard(
|
|||||||
text: input.data.text,
|
text: input.data.text,
|
||||||
files: input.data.files,
|
files: input.data.files,
|
||||||
agents: input.data.agents,
|
agents: input.data.agents,
|
||||||
|
skills: input.data.skills,
|
||||||
time: { created: event.created },
|
time: { created: event.created },
|
||||||
}
|
}
|
||||||
: {
|
: {
|
||||||
|
|||||||
@@ -184,6 +184,7 @@ function toLLMMessage(message: SessionMessage.Info, model: Model.Ref, providerMe
|
|||||||
return []
|
return []
|
||||||
case "user":
|
case "user":
|
||||||
const content = [
|
const content = [
|
||||||
|
...(message.skills ?? []).map((skill) => Message.text(skill.text)),
|
||||||
...(message.text === "" ? [] : [Message.text(message.text)]),
|
...(message.text === "" ? [] : [Message.text(message.text)]),
|
||||||
...(message.files ?? []).flatMap(attachmentContent),
|
...(message.files ?? []).flatMap(attachmentContent),
|
||||||
]
|
]
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ export * as SessionTransfer from "./transfer"
|
|||||||
|
|
||||||
import { SessionTransfer } from "@opencode-ai/schema/session-transfer"
|
import { SessionTransfer } from "@opencode-ai/schema/session-transfer"
|
||||||
import { Tool } from "@opencode-ai/schema/tool"
|
import { Tool } from "@opencode-ai/schema/tool"
|
||||||
|
import { Skill } from "@opencode-ai/schema/skill"
|
||||||
import { eq, isNotNull, isNull, ne, or } from "drizzle-orm"
|
import { eq, isNotNull, isNull, ne, or } from "drizzle-orm"
|
||||||
import { Context, DateTime, Effect, Layer, Schema } from "effect"
|
import { Context, DateTime, Effect, Layer, Schema } from "effect"
|
||||||
import path from "path"
|
import path from "path"
|
||||||
@@ -218,6 +219,14 @@ function sanitizeMessage(message: SessionMessage.Info): SessionMessage.Info {
|
|||||||
? { ...agent.mention, text: redact("agent-mention", String(index), agent.mention.text) }
|
? { ...agent.mention, text: redact("agent-mention", String(index), agent.mention.text) }
|
||||||
: undefined,
|
: undefined,
|
||||||
})),
|
})),
|
||||||
|
skills: message.skills?.map((skill, index) => ({
|
||||||
|
...skill,
|
||||||
|
name: Skill.Name.make(redact("skill-name", String(index), skill.name)),
|
||||||
|
text: redact("skill", String(index), skill.text),
|
||||||
|
mention: skill.mention
|
||||||
|
? { ...skill.mention, text: redact("skill-mention", String(index), skill.mention.text) }
|
||||||
|
: undefined,
|
||||||
|
})),
|
||||||
}
|
}
|
||||||
if (message.type === "synthetic")
|
if (message.type === "synthetic")
|
||||||
return {
|
return {
|
||||||
|
|||||||
@@ -5,7 +5,6 @@ import { Context, Deferred, Duration, Effect, Fiber, Layer, Schema, Stream } fro
|
|||||||
import { ChildProcess } from "effect/unstable/process"
|
import { ChildProcess } from "effect/unstable/process"
|
||||||
import { produce } from "immer"
|
import { produce } from "immer"
|
||||||
import { Shell } from "@opencode-ai/schema/shell"
|
import { Shell } from "@opencode-ai/schema/shell"
|
||||||
import { AppProcess } from "@opencode-ai/util/process"
|
|
||||||
import { makeLocationNode } from "@opencode-ai/util/effect/app-node"
|
import { makeLocationNode } from "@opencode-ai/util/effect/app-node"
|
||||||
import { Config } from "./config"
|
import { Config } from "./config"
|
||||||
import { Bus } from "./bus"
|
import { Bus } from "./bus"
|
||||||
@@ -51,7 +50,7 @@ export interface Interface {
|
|||||||
readonly create: <E = never, R = never>(
|
readonly create: <E = never, R = never>(
|
||||||
input: Shell.CreateInput,
|
input: Shell.CreateInput,
|
||||||
before?: (input: ShellCreateBefore) => Effect.Effect<void, E, R>,
|
before?: (input: ShellCreateBefore) => Effect.Effect<void, E, R>,
|
||||||
) => Effect.Effect<Shell.Info, E | AppProcess.AppProcessError, R>
|
) => Effect.Effect<Shell.Info, E, R>
|
||||||
// Currently running commands only; exited shells are retained for get/output but excluded here.
|
// Currently running commands only; exited shells are retained for get/output but excluded here.
|
||||||
readonly list: () => Effect.Effect<Shell.Info[]>
|
readonly list: () => Effect.Effect<Shell.Info[]>
|
||||||
readonly get: (id: Shell.ID) => Effect.Effect<Shell.Info, NotFoundError>
|
readonly get: (id: Shell.ID) => Effect.Effect<Shell.Info, NotFoundError>
|
||||||
@@ -214,12 +213,11 @@ export const layer = (options?: ShellSelect.Options) =>
|
|||||||
// Spawn through the Environment and stream combined output to the file. The handle is scope-bound, so
|
// Spawn through the Environment and stream combined output to the file. The handle is scope-bound, so
|
||||||
// the managing fiber keeps its scope open until the command terminates (it awaits `done` at the
|
// the managing fiber keeps its scope open until the command terminates (it awaits `done` at the
|
||||||
// end). `create` returns once `ready` resolves with the registered session.
|
// end). `create` returns once `ready` resolves with the registered session.
|
||||||
const ready = Deferred.makeUnsafe<Active, AppProcess.AppProcessError>()
|
const ready = Deferred.makeUnsafe<Active>()
|
||||||
runFork(
|
runFork(
|
||||||
Effect.scoped(
|
Effect.scoped(
|
||||||
Effect.gen(function* () {
|
Effect.gen(function* () {
|
||||||
const handle = yield* environment.spawner
|
const handle = yield* environment.spawner.spawn(
|
||||||
.spawn(
|
|
||||||
ChildProcess.make(invocation.shell, args, {
|
ChildProcess.make(invocation.shell, args, {
|
||||||
cwd: invocation.cwd,
|
cwd: invocation.cwd,
|
||||||
env: invocation.env,
|
env: invocation.env,
|
||||||
@@ -228,9 +226,6 @@ export const layer = (options?: ShellSelect.Options) =>
|
|||||||
forceKillAfter: Duration.seconds(3),
|
forceKillAfter: Duration.seconds(3),
|
||||||
}),
|
}),
|
||||||
)
|
)
|
||||||
.pipe(
|
|
||||||
Effect.mapError((cause) => new AppProcess.AppProcessError({ command: invocation.command, cause })),
|
|
||||||
)
|
|
||||||
const session: Active = {
|
const session: Active = {
|
||||||
info: produce(info, (draft) => {
|
info: produce(info, (draft) => {
|
||||||
draft.pid = handle.pid
|
draft.pid = handle.pid
|
||||||
@@ -332,7 +327,7 @@ export const layer = (options?: ShellSelect.Options) =>
|
|||||||
// release (kill) the process before its exit is observed.
|
// release (kill) the process before its exit is observed.
|
||||||
yield* Deferred.await(session.done).pipe(Effect.catch(() => Effect.void))
|
yield* Deferred.await(session.done).pipe(Effect.catch(() => Effect.void))
|
||||||
}),
|
}),
|
||||||
).pipe(Effect.catchTag("AppProcessError", (error) => Deferred.fail(ready, error))),
|
).pipe(Effect.catch(() => Effect.void)),
|
||||||
)
|
)
|
||||||
|
|
||||||
const session = yield* Deferred.await(ready)
|
const session = yield* Deferred.await(ready)
|
||||||
|
|||||||
@@ -38,6 +38,25 @@ export { Event } from "@opencode-ai/schema/skill"
|
|||||||
export const available = (skills: ReadonlyArray<Info>, agent: Agent.Info) =>
|
export const available = (skills: ReadonlyArray<Info>, agent: Agent.Info) =>
|
||||||
skills.filter((skill) => Permission.evaluate("skill", skill.id, agent.permissions).effect !== "deny")
|
skills.filter((skill) => Permission.evaluate("skill", skill.id, agent.permissions).effect !== "deny")
|
||||||
|
|
||||||
|
export const toModelOutput = (skill: Info, files: ReadonlyArray<string>) => {
|
||||||
|
const directory = path.dirname(skill.location)
|
||||||
|
return [
|
||||||
|
`<skill_content name="${skill.name}">`,
|
||||||
|
`# Skill: ${skill.name}`,
|
||||||
|
"",
|
||||||
|
skill.content.trim(),
|
||||||
|
"",
|
||||||
|
`Base directory for this skill: ${directory}`,
|
||||||
|
"Relative paths in this skill (e.g., scripts/, reference/) are relative to this base directory.",
|
||||||
|
"Note: file list is sampled.",
|
||||||
|
"",
|
||||||
|
"<skill_files>",
|
||||||
|
...files.map((file) => `<file>${file}</file>`),
|
||||||
|
"</skill_files>",
|
||||||
|
"</skill_content>",
|
||||||
|
].join("\n")
|
||||||
|
}
|
||||||
|
|
||||||
const Frontmatter = Schema.Struct({
|
const Frontmatter = Schema.Struct({
|
||||||
name: Schema.String.pipe(Schema.optional),
|
name: Schema.String.pipe(Schema.optional),
|
||||||
description: Schema.String.pipe(Schema.optional),
|
description: Schema.String.pipe(Schema.optional),
|
||||||
|
|||||||
@@ -26,24 +26,7 @@ export const description = [
|
|||||||
"The skill ID must match one of the available skills in the instructions.",
|
"The skill ID must match one of the available skills in the instructions.",
|
||||||
].join("\n")
|
].join("\n")
|
||||||
|
|
||||||
export const toModelOutput = (skill: Skill.Info, files: ReadonlyArray<string>) => {
|
export const toModelOutput = Skill.toModelOutput
|
||||||
const directory = path.dirname(skill.location)
|
|
||||||
return [
|
|
||||||
`<skill_content name="${skill.name}">`,
|
|
||||||
`# Skill: ${skill.name}`,
|
|
||||||
"",
|
|
||||||
skill.content.trim(),
|
|
||||||
"",
|
|
||||||
`Base directory for this skill: ${directory}`,
|
|
||||||
"Relative paths in this skill (e.g., scripts/, reference/) are relative to this base directory.",
|
|
||||||
"Note: file list is sampled.",
|
|
||||||
"",
|
|
||||||
"<skill_files>",
|
|
||||||
...files.map((file) => `<file>${file}</file>`),
|
|
||||||
"</skill_files>",
|
|
||||||
"</skill_content>",
|
|
||||||
].join("\n")
|
|
||||||
}
|
|
||||||
|
|
||||||
const unableToLoad = (name: string, error?: unknown) =>
|
const unableToLoad = (name: string, error?: unknown) =>
|
||||||
new ToolFailure({ message: `Unable to load skill ${name}`, error })
|
new ToolFailure({ message: `Unable to load skill ${name}`, error })
|
||||||
@@ -87,7 +70,7 @@ export const Plugin = {
|
|||||||
return {
|
return {
|
||||||
name: skill.name,
|
name: skill.name,
|
||||||
directory,
|
directory,
|
||||||
output: toModelOutput(skill, files),
|
output: Skill.toModelOutput(skill, files),
|
||||||
}
|
}
|
||||||
}).pipe(Effect.mapError((error) => unableToLoad(input.id, error)))
|
}).pipe(Effect.mapError((error) => unableToLoad(input.id, error)))
|
||||||
}).pipe(
|
}).pipe(
|
||||||
|
|||||||
@@ -1,6 +1,219 @@
|
|||||||
export * as Workspace from "./workspace"
|
export * as Workspace from "./workspace"
|
||||||
|
|
||||||
import { Workspace } from "@opencode-ai/schema/workspace"
|
import { Workspace } from "@opencode-ai/schema/workspace"
|
||||||
|
import { makeGlobalNode } from "@opencode-ai/util/effect/app-node"
|
||||||
|
import { eq } from "drizzle-orm"
|
||||||
|
import { Clock, Context, Duration, Effect, Exit, Layer, Ref, Schedule, Schema, Scope } from "effect"
|
||||||
|
import { systemError } from "effect/PlatformError"
|
||||||
|
import { make } from "effect/unstable/process/ChildProcessSpawner"
|
||||||
|
import type { Driver as EnvironmentDriver } from "./environment/driver"
|
||||||
|
import { Database } from "./database/database"
|
||||||
|
import { KeyedMutex } from "./effect/keyed-mutex"
|
||||||
|
import { WorkspaceDriver } from "./workspace/driver"
|
||||||
|
import { WorkspaceTable } from "./workspace/sql"
|
||||||
|
|
||||||
export const ID = Workspace.ID
|
export const ID = Workspace.ID
|
||||||
export type ID = typeof ID.Type
|
export type ID = Workspace.ID
|
||||||
|
|
||||||
|
export class Info extends Schema.Class<Info>("Workspace.Info")({
|
||||||
|
id: ID,
|
||||||
|
provider: Schema.String,
|
||||||
|
binding: WorkspaceDriver.Binding,
|
||||||
|
createdAt: Schema.Number,
|
||||||
|
lastUsedAt: Schema.Number,
|
||||||
|
}) {}
|
||||||
|
|
||||||
|
export class NotFound extends Schema.TaggedErrorClass<NotFound>()("Workspace.NotFound", { workspaceID: ID }) {}
|
||||||
|
|
||||||
|
export interface Interface {
|
||||||
|
readonly create: (provider: string) => Effect.Effect<Info, WorkspaceDriver.Error | WorkspaceDriver.ProviderNotFound>
|
||||||
|
readonly connect: (
|
||||||
|
workspaceID: ID,
|
||||||
|
) => Effect.Effect<EnvironmentDriver, NotFound | WorkspaceDriver.Error | WorkspaceDriver.ProviderNotFound>
|
||||||
|
readonly destroy: (
|
||||||
|
workspaceID: ID,
|
||||||
|
) => Effect.Effect<void, NotFound | WorkspaceDriver.Error | WorkspaceDriver.ProviderNotFound>
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface Options {
|
||||||
|
readonly idleThreshold?: Duration.Input
|
||||||
|
readonly pollInterval?: Duration.Input
|
||||||
|
}
|
||||||
|
|
||||||
|
export class Service extends Context.Service<Service, Interface>()("@opencode/Workspace") {}
|
||||||
|
|
||||||
|
interface Connection {
|
||||||
|
readonly driver: WorkspaceDriver.Interface
|
||||||
|
readonly environment: EnvironmentDriver
|
||||||
|
readonly saveBinding: (binding: WorkspaceDriver.Binding) => Effect.Effect<void>
|
||||||
|
readonly lastActivity: Ref.Ref<number>
|
||||||
|
readonly active: Ref.Ref<number>
|
||||||
|
readonly scope: Scope.Closeable
|
||||||
|
}
|
||||||
|
|
||||||
|
export const configured = (options: Options = {}) =>
|
||||||
|
makeGlobalNode({
|
||||||
|
service: Service,
|
||||||
|
layer: layer(options),
|
||||||
|
deps: [Database.node, WorkspaceDriver.node],
|
||||||
|
})
|
||||||
|
|
||||||
|
const layer = (options: Options) =>
|
||||||
|
Layer.effect(
|
||||||
|
Service,
|
||||||
|
Effect.gen(function* () {
|
||||||
|
const db = (yield* Database.Service).db
|
||||||
|
const registry = yield* WorkspaceDriver.RegistryService
|
||||||
|
const lifetime = yield* Scope.Scope
|
||||||
|
const connections = new Map<ID, Connection>()
|
||||||
|
const locks = KeyedMutex.makeUnsafe<ID>()
|
||||||
|
const idleThreshold = Duration.toMillis(options.idleThreshold ?? Duration.minutes(20))
|
||||||
|
|
||||||
|
const load = Effect.fn("Workspace.load")(function* (workspaceID: ID) {
|
||||||
|
const row = yield* db
|
||||||
|
.select()
|
||||||
|
.from(WorkspaceTable)
|
||||||
|
.where(eq(WorkspaceTable.id, workspaceID))
|
||||||
|
.get()
|
||||||
|
.pipe(Effect.orDie)
|
||||||
|
if (!row) return yield* new NotFound({ workspaceID })
|
||||||
|
return row
|
||||||
|
})
|
||||||
|
|
||||||
|
const open = Effect.fn("Workspace.open")(function* (workspaceID: ID) {
|
||||||
|
const existing = connections.get(workspaceID)
|
||||||
|
if (existing) return existing
|
||||||
|
|
||||||
|
const row = yield* load(workspaceID)
|
||||||
|
const driver = yield* registry.get(row.provider)
|
||||||
|
const saveBinding = (value: WorkspaceDriver.Binding) =>
|
||||||
|
db
|
||||||
|
.update(WorkspaceTable)
|
||||||
|
.set({ binding: value })
|
||||||
|
.where(eq(WorkspaceTable.id, workspaceID))
|
||||||
|
.run()
|
||||||
|
.pipe(Effect.orDie)
|
||||||
|
const scope = yield* Scope.fork(lifetime)
|
||||||
|
const environment = yield* driver.connect({ workspaceID, binding: row.binding, saveBinding }).pipe(
|
||||||
|
Effect.provideService(Scope.Scope, scope),
|
||||||
|
Effect.onError((cause) => Scope.close(scope, Exit.failCause(cause))),
|
||||||
|
)
|
||||||
|
const now = yield* Clock.currentTimeMillis
|
||||||
|
const connection: Connection = {
|
||||||
|
driver,
|
||||||
|
environment,
|
||||||
|
saveBinding,
|
||||||
|
lastActivity: yield* Ref.make(now),
|
||||||
|
active: yield* Ref.make(0),
|
||||||
|
scope,
|
||||||
|
}
|
||||||
|
connections.set(workspaceID, connection)
|
||||||
|
yield* db
|
||||||
|
.update(WorkspaceTable)
|
||||||
|
.set({ last_used_at: now })
|
||||||
|
.where(eq(WorkspaceTable.id, workspaceID))
|
||||||
|
.run()
|
||||||
|
.pipe(Effect.orDie)
|
||||||
|
return connection
|
||||||
|
})
|
||||||
|
|
||||||
|
yield* Effect.gen(function* () {
|
||||||
|
const now = yield* Clock.currentTimeMillis
|
||||||
|
yield* Effect.forEach(
|
||||||
|
[...connections.entries()],
|
||||||
|
([workspaceID, expected]) =>
|
||||||
|
locks.withLock(workspaceID)(
|
||||||
|
Effect.gen(function* () {
|
||||||
|
const connection = connections.get(workspaceID)
|
||||||
|
if (connection !== expected || (yield* Ref.get(connection.active)) > 0) return
|
||||||
|
const lastActivity = yield* Ref.get(connection.lastActivity)
|
||||||
|
if (now - lastActivity < idleThreshold) return
|
||||||
|
const row = yield* load(workspaceID)
|
||||||
|
// Deliberate: a racing spawn blocks, then wakes cleanly. Unlocking mid-suspend could reattach a sandbox being terminated.
|
||||||
|
yield* connection.driver.suspendForIdle({
|
||||||
|
workspaceID,
|
||||||
|
binding: row.binding,
|
||||||
|
saveBinding: connection.saveBinding,
|
||||||
|
})
|
||||||
|
yield* db
|
||||||
|
.update(WorkspaceTable)
|
||||||
|
.set({ last_used_at: lastActivity })
|
||||||
|
.where(eq(WorkspaceTable.id, workspaceID))
|
||||||
|
.run()
|
||||||
|
.pipe(Effect.orDie)
|
||||||
|
connections.delete(workspaceID)
|
||||||
|
yield* Scope.close(connection.scope, Exit.void)
|
||||||
|
}).pipe(Effect.catchCause((cause) => Effect.logError("workspace idle suspension failed", cause))),
|
||||||
|
),
|
||||||
|
{ concurrency: "unbounded", discard: true },
|
||||||
|
)
|
||||||
|
}).pipe(Effect.repeat(Schedule.spaced(options.pollInterval ?? Duration.minutes(1))), Effect.forkScoped)
|
||||||
|
|
||||||
|
return Service.of({
|
||||||
|
create: Effect.fn("Workspace.create")(function* (provider) {
|
||||||
|
const driver = yield* registry.get(provider)
|
||||||
|
const workspaceID = ID.create()
|
||||||
|
const result = yield* driver.create({ workspaceID })
|
||||||
|
const now = yield* Clock.currentTimeMillis
|
||||||
|
yield* db
|
||||||
|
.insert(WorkspaceTable)
|
||||||
|
.values({ id: workspaceID, provider, binding: result.binding, created_at: now, last_used_at: now })
|
||||||
|
.run()
|
||||||
|
.pipe(Effect.orDie)
|
||||||
|
return new Info({ id: workspaceID, provider, binding: result.binding, createdAt: now, lastUsedAt: now })
|
||||||
|
}),
|
||||||
|
connect: Effect.fn("Workspace.connect")(function* (workspaceID) {
|
||||||
|
const spawner = make((command) =>
|
||||||
|
Effect.acquireRelease(
|
||||||
|
locks.withLock(workspaceID)(
|
||||||
|
Effect.gen(function* () {
|
||||||
|
const connection = yield* open(workspaceID).pipe(
|
||||||
|
Effect.mapError((cause) =>
|
||||||
|
systemError({
|
||||||
|
_tag: "Unknown",
|
||||||
|
module: "Workspace",
|
||||||
|
method: "spawn",
|
||||||
|
description: `Failed to wake workspace ${workspaceID}`,
|
||||||
|
cause,
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
yield* Ref.set(connection.lastActivity, yield* Clock.currentTimeMillis)
|
||||||
|
yield* Ref.update(connection.active, (active) => active + 1)
|
||||||
|
return connection
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
(connection) =>
|
||||||
|
locks.withLock(workspaceID)(
|
||||||
|
Effect.gen(function* () {
|
||||||
|
yield* Ref.update(connection.active, (active) => active - 1)
|
||||||
|
yield* Ref.set(connection.lastActivity, yield* Clock.currentTimeMillis)
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
).pipe(Effect.flatMap((connection) => connection.environment.spawner.spawn(command))),
|
||||||
|
)
|
||||||
|
// Overrides are connection-bound; per-spawn routing is required before any driver ships them, so they are deliberately omitted.
|
||||||
|
return { spawner }
|
||||||
|
}),
|
||||||
|
destroy: Effect.fn("Workspace.destroy")(function* (workspaceID) {
|
||||||
|
yield* locks.withLock(workspaceID)(
|
||||||
|
Effect.gen(function* () {
|
||||||
|
const row = yield* load(workspaceID)
|
||||||
|
const connection = connections.get(workspaceID)
|
||||||
|
connections.delete(workspaceID)
|
||||||
|
if (connection) yield* Scope.close(connection.scope, Exit.void)
|
||||||
|
const driver = yield* registry.get(row.provider)
|
||||||
|
yield* driver.destroy({ workspaceID, binding: row.binding })
|
||||||
|
yield* db.delete(WorkspaceTable).where(eq(WorkspaceTable.id, workspaceID)).run().pipe(Effect.orDie)
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
}),
|
||||||
|
})
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
|
||||||
|
export const node = configured()
|
||||||
|
|
||||||
|
// TODO(workspace-plan): add the boot janitor and ~23h safety snapshot rotation in a later PR.
|
||||||
|
// TODO(workspace-plan): make cold wake interruptible with a re-pin loop against janitor races.
|
||||||
|
// TODO(workspace-plan): consider RcMap at end-of-series consolidation; idle suspend and destroy need distinct finalizers.
|
||||||
|
|||||||
@@ -0,0 +1,70 @@
|
|||||||
|
export * as WorkspaceDriver from "./driver"
|
||||||
|
|
||||||
|
import { Workspace } from "@opencode-ai/schema/workspace"
|
||||||
|
import { makeGlobalNode } from "@opencode-ai/util/effect/app-node"
|
||||||
|
import { Context, Effect, Layer, Schema } from "effect"
|
||||||
|
import type { Scope } from "effect"
|
||||||
|
import type { Driver as EnvironmentDriver } from "../environment/driver"
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Smallest provider-owned JSON value required to reconnect to the same
|
||||||
|
* provider resource. Core stores it opaquely and hands it back; only the
|
||||||
|
* owning driver reads inside.
|
||||||
|
*/
|
||||||
|
export const Binding = Schema.Record(Schema.String, Schema.Json)
|
||||||
|
export type Binding = typeof Binding.Type
|
||||||
|
|
||||||
|
export class Error extends Schema.TaggedErrorClass<Error>()("WorkspaceDriver.Error", {
|
||||||
|
message: Schema.optional(Schema.String),
|
||||||
|
cause: Schema.optional(Schema.Defect()),
|
||||||
|
}) {}
|
||||||
|
|
||||||
|
export class ProviderNotFound extends Schema.TaggedErrorClass<ProviderNotFound>()("WorkspaceDriver.ProviderNotFound", {
|
||||||
|
provider: Schema.String,
|
||||||
|
}) {}
|
||||||
|
|
||||||
|
export interface Interface {
|
||||||
|
readonly create: (input: {
|
||||||
|
readonly workspaceID: Workspace.ID
|
||||||
|
}) => Effect.Effect<{ readonly binding: Binding }, Error>
|
||||||
|
readonly connect: (input: {
|
||||||
|
readonly workspaceID: Workspace.ID
|
||||||
|
readonly binding: Binding
|
||||||
|
readonly saveBinding: (binding: Binding) => Effect.Effect<void>
|
||||||
|
}) => Effect.Effect<EnvironmentDriver, Error, Scope.Scope>
|
||||||
|
readonly suspendForIdle: (input: {
|
||||||
|
readonly workspaceID: Workspace.ID
|
||||||
|
readonly binding: Binding
|
||||||
|
readonly saveBinding: (binding: Binding) => Effect.Effect<void>
|
||||||
|
}) => Effect.Effect<void, Error>
|
||||||
|
readonly destroy: (input: {
|
||||||
|
readonly workspaceID: Workspace.ID
|
||||||
|
readonly binding: Binding
|
||||||
|
}) => Effect.Effect<void, Error>
|
||||||
|
}
|
||||||
|
|
||||||
|
export const make = (driver: Interface) => driver
|
||||||
|
|
||||||
|
export interface Registry {
|
||||||
|
readonly get: (provider: string) => Effect.Effect<Interface, ProviderNotFound>
|
||||||
|
}
|
||||||
|
|
||||||
|
export class RegistryService extends Context.Service<RegistryService, Registry>()(
|
||||||
|
"@opencode/WorkspaceDriverRegistry",
|
||||||
|
) {}
|
||||||
|
|
||||||
|
export const registry = (drivers: Readonly<Record<string, Interface>>): Registry => ({
|
||||||
|
get: (provider) => {
|
||||||
|
const driver = drivers[provider]
|
||||||
|
return driver ? Effect.succeed(driver) : Effect.fail(new ProviderNotFound({ provider }))
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
export const registryNode = (drivers: Readonly<Record<string, Interface>>) =>
|
||||||
|
makeGlobalNode({
|
||||||
|
service: RegistryService,
|
||||||
|
layer: Layer.succeed(RegistryService, RegistryService.of(registry(drivers))),
|
||||||
|
deps: [],
|
||||||
|
})
|
||||||
|
|
||||||
|
export const node = registryNode({})
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
import { Workspace } from "@opencode-ai/schema/workspace"
|
||||||
|
import { integer, sqliteTable, text } from "drizzle-orm/sqlite-core"
|
||||||
|
import type { WorkspaceDriver } from "./driver"
|
||||||
|
|
||||||
|
export const WorkspaceTable = sqliteTable("workspace", {
|
||||||
|
id: text().$type<Workspace.ID>().primaryKey(),
|
||||||
|
provider: text().notNull(),
|
||||||
|
binding: text({ mode: "json" }).$type<WorkspaceDriver.Binding>().notNull(),
|
||||||
|
created_at: integer().notNull(),
|
||||||
|
last_used_at: integer().notNull(),
|
||||||
|
})
|
||||||
@@ -9,11 +9,12 @@ import { Environment } from "@opencode-ai/core/environment"
|
|||||||
import { Location } from "@opencode-ai/core/location"
|
import { Location } from "@opencode-ai/core/location"
|
||||||
import { LocationMutation } from "@opencode-ai/core/location-mutation"
|
import { LocationMutation } from "@opencode-ai/core/location-mutation"
|
||||||
import { AbsolutePath } from "@opencode-ai/core/schema"
|
import { AbsolutePath } from "@opencode-ai/core/schema"
|
||||||
|
import { type EnvironmentFilesTransform, transformEnvironmentFiles } from "./fixture/environment"
|
||||||
import { location } from "./fixture/location"
|
import { location } from "./fixture/location"
|
||||||
import { tmpdir } from "./fixture/tmpdir"
|
import { tmpdir } from "./fixture/tmpdir"
|
||||||
import { it } from "./lib/effect"
|
import { it } from "./lib/effect"
|
||||||
|
|
||||||
function provide(directory: string, environmentLayer = LayerNode.compile(Environment.node)) {
|
function provide(directory: string, transformFiles: EnvironmentFilesTransform = () => ({})) {
|
||||||
const activeLocation = Layer.succeed(
|
const activeLocation = Layer.succeed(
|
||||||
Location.Service,
|
Location.Service,
|
||||||
Location.Service.of(location({ directory: AbsolutePath.make(directory) })),
|
Location.Service.of(location({ directory: AbsolutePath.make(directory) })),
|
||||||
@@ -21,7 +22,7 @@ function provide(directory: string, environmentLayer = LayerNode.compile(Environ
|
|||||||
return Effect.provide(
|
return Effect.provide(
|
||||||
AppNodeBuilder.build(LayerNode.group([LocationMutation.node, FileMutation.node]), [
|
AppNodeBuilder.build(LayerNode.group([LocationMutation.node, FileMutation.node]), [
|
||||||
[Location.node, activeLocation],
|
[Location.node, activeLocation],
|
||||||
[Environment.node, environmentLayer],
|
[Environment.node, transformEnvironmentFiles(activeLocation, transformFiles)],
|
||||||
]),
|
]),
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
@@ -240,18 +241,8 @@ describe("FileMutation", () => {
|
|||||||
)
|
)
|
||||||
})
|
})
|
||||||
|
|
||||||
function instrumentWrites(run: <E>(write: Effect.Effect<void, E>, target: string) => Effect.Effect<void, E>) {
|
function instrumentWrites(
|
||||||
return Layer.effect(
|
run: <E>(write: Effect.Effect<void, E>, target: string) => Effect.Effect<void, E>,
|
||||||
Environment.Service,
|
): EnvironmentFilesTransform {
|
||||||
Effect.gen(function* () {
|
return (files) => ({ write: (target, content) => run(files.write(target, content), target) })
|
||||||
const environment = yield* Environment.Service
|
|
||||||
return Environment.Service.of({
|
|
||||||
...environment,
|
|
||||||
files: {
|
|
||||||
...environment.files,
|
|
||||||
write: (target, content) => run(environment.files.write(target, content), target),
|
|
||||||
},
|
|
||||||
})
|
|
||||||
}),
|
|
||||||
).pipe(Layer.provide(LayerNode.compile(Environment.node)))
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,22 @@
|
|||||||
|
import { AppNodeBuilder } from "@opencode-ai/core/effect/app-node-builder"
|
||||||
|
import { Environment } from "@opencode-ai/core/environment"
|
||||||
|
import { Location } from "@opencode-ai/core/location"
|
||||||
|
import { Effect, Layer } from "effect"
|
||||||
|
|
||||||
|
export type EnvironmentFilesTransform = (files: Environment.Files) => Partial<Environment.Files>
|
||||||
|
|
||||||
|
export function transformEnvironmentFiles(
|
||||||
|
location: Layer.Layer<Location.Service>,
|
||||||
|
transform: EnvironmentFilesTransform = () => ({}),
|
||||||
|
) {
|
||||||
|
return Layer.effect(
|
||||||
|
Environment.Service,
|
||||||
|
Effect.gen(function* () {
|
||||||
|
const current = yield* Environment.Service
|
||||||
|
return Environment.Service.of({
|
||||||
|
...current,
|
||||||
|
files: { ...current.files, ...transform(current.files) },
|
||||||
|
})
|
||||||
|
}),
|
||||||
|
).pipe(Layer.provide(AppNodeBuilder.build(Environment.node, [[Location.node, location]])))
|
||||||
|
}
|
||||||
+1
-1
File diff suppressed because one or more lines are too long
@@ -42,6 +42,18 @@ test("defensively syncs advertised Copilot models", async () => {
|
|||||||
supports: { tool_calls: false },
|
supports: { tool_calls: false },
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
model_picker_enabled: true,
|
||||||
|
id: "claude-sonnet",
|
||||||
|
name: "Claude Sonnet",
|
||||||
|
version: "claude-sonnet-2026-06-01",
|
||||||
|
supported_endpoints: ["/v1/messages"],
|
||||||
|
capabilities: {
|
||||||
|
family: "claude",
|
||||||
|
limits: { max_output_tokens: 16000, max_prompt_tokens: 180000 },
|
||||||
|
supports: { tool_calls: true },
|
||||||
|
},
|
||||||
|
},
|
||||||
{ model_picker_enabled: true, id: "incomplete" },
|
{ model_picker_enabled: true, id: "incomplete" },
|
||||||
],
|
],
|
||||||
}),
|
}),
|
||||||
@@ -68,6 +80,7 @@ test("defensively syncs advertised Copilot models", async () => {
|
|||||||
Model.VariantID.make("high"),
|
Model.VariantID.make("high"),
|
||||||
])
|
])
|
||||||
expect(models.get(Model.ID.make("utility"))?.enabled).toBe(false)
|
expect(models.get(Model.ID.make("utility"))?.enabled).toBe(false)
|
||||||
|
expect(models.get(Model.ID.make("claude-sonnet"))?.package).toBe(Provider.aisdk(CopilotModels.Package.Anthropic))
|
||||||
expect(models.has(Model.ID.make("stale"))).toBe(false)
|
expect(models.has(Model.ID.make("stale"))).toBe(false)
|
||||||
expect(models.has(Model.ID.make("incomplete"))).toBe(false)
|
expect(models.has(Model.ID.make("incomplete"))).toBe(false)
|
||||||
} finally {
|
} finally {
|
||||||
|
|||||||
@@ -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",
|
||||||
|
form: [{ 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" }).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",
|
||||||
|
answer: { 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,6 @@ describe("Integration", () => {
|
|||||||
const attempt = yield* integrations.oauth.connect({
|
const attempt = yield* integrations.oauth.connect({
|
||||||
integrationID,
|
integrationID,
|
||||||
methodID,
|
methodID,
|
||||||
inputs: {},
|
|
||||||
label: "Personal",
|
label: "Personal",
|
||||||
})
|
})
|
||||||
expect(attempt.mode).toBe("code")
|
expect(attempt.mode).toBe("code")
|
||||||
@@ -289,7 +300,7 @@ describe("Integration", () => {
|
|||||||
}),
|
}),
|
||||||
)
|
)
|
||||||
|
|
||||||
const attempt = yield* integrations.oauth.connect({ integrationID, methodID, inputs: {} })
|
const attempt = yield* integrations.oauth.connect({ integrationID, methodID })
|
||||||
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 +338,7 @@ describe("Integration", () => {
|
|||||||
}),
|
}),
|
||||||
)
|
)
|
||||||
|
|
||||||
const attempt = yield* integrations.oauth.connect({ integrationID, methodID, inputs: {} })
|
const attempt = yield* integrations.oauth.connect({ integrationID, methodID })
|
||||||
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 +376,7 @@ describe("Integration", () => {
|
|||||||
}),
|
}),
|
||||||
)
|
)
|
||||||
|
|
||||||
const attempt = yield* integrations.oauth.connect({ integrationID, methodID, inputs: {} })
|
const attempt = yield* integrations.oauth.connect({ integrationID, methodID })
|
||||||
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 +412,7 @@ describe("Integration", () => {
|
|||||||
}),
|
}),
|
||||||
)
|
)
|
||||||
|
|
||||||
const attempt = yield* integrations.oauth.connect({ integrationID, methodID, inputs: {} })
|
const attempt = yield* integrations.oauth.connect({ integrationID, methodID })
|
||||||
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 +453,7 @@ describe("Integration", () => {
|
|||||||
}),
|
}),
|
||||||
)
|
)
|
||||||
|
|
||||||
const attempt = yield* integrations.oauth.connect({ integrationID, methodID, inputs: {} })
|
const attempt = yield* integrations.oauth.connect({ integrationID, methodID })
|
||||||
expect(attempt.time).toEqual({ created, expires: expiresAt })
|
expect(attempt.time).toEqual({ created, expires: expiresAt })
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -305,11 +305,13 @@ describe("LocationServiceMap", () => {
|
|||||||
)
|
)
|
||||||
yield* Deferred.await(started)
|
yield* Deferred.await(started)
|
||||||
|
|
||||||
yield* PluginSupervisor.Service.use((supervisor) => supervisor.flush).pipe(
|
const flushFiber = yield* PluginSupervisor.Service.use((supervisor) => supervisor.flush).pipe(
|
||||||
Effect.provide(context),
|
Effect.provide(context),
|
||||||
Effect.timeout("1 second"),
|
Effect.forkChild({ startImmediately: true }),
|
||||||
)
|
)
|
||||||
|
expect(flushFiber.pollUnsafe()).toBeUndefined()
|
||||||
yield* Deferred.succeed(release, undefined)
|
yield* Deferred.succeed(release, undefined)
|
||||||
|
yield* Fiber.join(flushFiber)
|
||||||
yield* Deferred.await(completed)
|
yield* Deferred.await(completed)
|
||||||
}),
|
}),
|
||||||
),
|
),
|
||||||
|
|||||||
@@ -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 },
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
import { Plugin } from "@opencode-ai/plugin/effect"
|
import { Plugin } from "@opencode-ai/plugin/effect"
|
||||||
import type { IntegrationMethodRegistration } from "@opencode-ai/plugin/effect/integration"
|
import type { IntegrationMethod, IntegrationMethodRegistration } from "@opencode-ai/plugin/effect/integration"
|
||||||
import { Agent } from "@opencode-ai/core/agent"
|
import { Agent } from "@opencode-ai/core/agent"
|
||||||
import { Catalog } from "@opencode-ai/core/catalog"
|
import { Catalog } from "@opencode-ai/core/catalog"
|
||||||
import { Credential } from "@opencode-ai/core/credential"
|
import { Credential } from "@opencode-ai/core/credential"
|
||||||
@@ -15,7 +15,6 @@ import { Effect, 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"]>
|
||||||
}
|
}
|
||||||
|
|
||||||
export function host(overrides: Overrides = {}): Plugin.Context {
|
export function host(overrides: Overrides = {}): Plugin.Context {
|
||||||
return {
|
return {
|
||||||
app: overrides.app ?? { name: "test", version: "test", channel: "test" },
|
app: overrides.app ?? { name: "test", version: "test", channel: "test" },
|
||||||
@@ -278,7 +277,7 @@ export function integrationHost(integration: Integration.Interface): Plugin.Cont
|
|||||||
update: (id, update) => draft.update(Integration.ID.make(id), update),
|
update: (id, update) => draft.update(Integration.ID.make(id), update),
|
||||||
remove: (id) => draft.remove(Integration.ID.make(id)),
|
remove: (id) => draft.remove(Integration.ID.make(id)),
|
||||||
method: {
|
method: {
|
||||||
list: (id) => draft.method.list(Integration.ID.make(id)).map(method),
|
list: (id) => draft.method.list(Integration.ID.make(id)),
|
||||||
update: (input) => {
|
update: (input) => {
|
||||||
if ("authorize" in input) {
|
if ("authorize" in input) {
|
||||||
const methodID = Integration.MethodID.make(input.method.id)
|
const methodID = Integration.MethodID.make(input.method.id)
|
||||||
@@ -286,8 +285,8 @@ 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, id: methodID },
|
method: { ...input.method, id: methodID },
|
||||||
authorize: (inputs) =>
|
authorize: (answer) =>
|
||||||
input.authorize(inputs).pipe(
|
input.authorize(answer).pipe(
|
||||||
Effect.map((authorization) => {
|
Effect.map((authorization) => {
|
||||||
if (authorization.mode === "auto") {
|
if (authorization.mode === "auto") {
|
||||||
return {
|
return {
|
||||||
@@ -336,7 +335,7 @@ export function integrationHost(integration: Integration.Interface): Plugin.Cont
|
|||||||
if (input.method.type === "env") {
|
if (input.method.type === "env") {
|
||||||
draft.method.update({
|
draft.method.update({
|
||||||
integrationID: Integration.ID.make(input.integrationID),
|
integrationID: Integration.ID.make(input.integrationID),
|
||||||
method: { ...input.method, names: [...input.method.names] },
|
method: input.method,
|
||||||
})
|
})
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
@@ -346,7 +345,6 @@ export function integrationHost(integration: Integration.Interface): Plugin.Cont
|
|||||||
method: {
|
method: {
|
||||||
...input.method,
|
...input.method,
|
||||||
id: Integration.MethodID.make(input.method.id),
|
id: Integration.MethodID.make(input.method.id),
|
||||||
command: [...input.method.command],
|
|
||||||
},
|
},
|
||||||
})
|
})
|
||||||
return
|
return
|
||||||
@@ -401,35 +399,11 @@ 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 internalMethod(value: IntegrationMethod): Integration.Method {
|
||||||
if (value.type === "env") return { type: value.type, names: [...value.names] }
|
if (value.type === "oauth" || value.type === "command") {
|
||||||
if (value.type === "key") return { type: value.type, label: value.label }
|
return { ...value, id: Integration.MethodID.make(value.id) }
|
||||||
if (value.type === "command") return { ...value, command: [...value.command] }
|
|
||||||
return {
|
|
||||||
type: value.type,
|
|
||||||
id: value.id,
|
|
||||||
label: value.label,
|
|
||||||
prompts: value.prompts?.map((prompt) => {
|
|
||||||
if (prompt.type === "text") return { ...prompt }
|
|
||||||
return { ...prompt, options: prompt.options.map((option) => ({ ...option })) }
|
|
||||||
}),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function internalMethod(value: IntegrationMethodRegistration["method"]): Integration.Method {
|
|
||||||
if (value.type === "env") return value
|
|
||||||
if (value.type === "key") return value
|
|
||||||
if (value.type === "command") {
|
|
||||||
return {
|
|
||||||
...value,
|
|
||||||
id: Integration.MethodID.make(value.id),
|
|
||||||
command: [...value.command],
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return {
|
|
||||||
...value,
|
|
||||||
id: Integration.MethodID.make(value.id),
|
|
||||||
}
|
}
|
||||||
|
return value
|
||||||
}
|
}
|
||||||
|
|
||||||
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",
|
||||||
|
form: [
|
||||||
|
{
|
||||||
|
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",
|
||||||
|
form: [
|
||||||
|
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",
|
||||||
|
form: [
|
||||||
|
{
|
||||||
|
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")),
|
||||||
|
|||||||
@@ -1,5 +1,4 @@
|
|||||||
import { AISDK } from "@opencode-ai/core/aisdk"
|
import { AISDK } from "@opencode-ai/core/aisdk"
|
||||||
import { App } from "@opencode-ai/core/app"
|
|
||||||
import { describe, expect, test } from "bun:test"
|
import { describe, expect, test } from "bun:test"
|
||||||
import { Effect } from "effect"
|
import { Effect } from "effect"
|
||||||
import { Catalog } from "@opencode-ai/core/catalog"
|
import { Catalog } from "@opencode-ai/core/catalog"
|
||||||
@@ -7,8 +6,11 @@ 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 { copilotBaseURL, copilotFetch, GithubCopilotPlugin } from "@opencode-ai/core/plugin/provider/github-copilot"
|
import { copilotBaseURL, copilotFetch, GithubCopilotPlugin } from "@opencode-ai/core/plugin/provider/github-copilot"
|
||||||
|
import { CopilotModels } from "@opencode-ai/core/github-copilot/models"
|
||||||
import { Provider } from "@opencode-ai/core/provider"
|
import { Provider } from "@opencode-ai/core/provider"
|
||||||
import { Integration } from "@opencode-ai/core/integration"
|
import { Integration } from "@opencode-ai/core/integration"
|
||||||
|
import { Credential } from "@opencode-ai/core/credential"
|
||||||
|
import { ModelResolver } from "@opencode-ai/core/model-resolver"
|
||||||
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"
|
||||||
@@ -57,11 +59,37 @@ 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),
|
form: expect.any(Array),
|
||||||
})
|
})
|
||||||
}),
|
}),
|
||||||
)
|
)
|
||||||
|
|
||||||
|
it.effect("removes the generic key method", () =>
|
||||||
|
Effect.gen(function* () {
|
||||||
|
const integrations = yield* Integration.Service
|
||||||
|
yield* integrations.transform((draft) => {
|
||||||
|
draft.method.update({
|
||||||
|
integrationID: Integration.ID.make("github-copilot"),
|
||||||
|
method: { type: "key" },
|
||||||
|
})
|
||||||
|
draft.method.update({
|
||||||
|
integrationID: Integration.ID.make("github-copilot"),
|
||||||
|
method: { type: "env", names: ["GITHUB_TOKEN"] },
|
||||||
|
})
|
||||||
|
})
|
||||||
|
yield* addPlugin()
|
||||||
|
expect((yield* integrations.get(Integration.ID.make("github-copilot")))?.methods).toEqual([
|
||||||
|
{ type: "env", names: ["GITHUB_TOKEN"] },
|
||||||
|
{
|
||||||
|
id: Integration.MethodID.make("device"),
|
||||||
|
type: "oauth",
|
||||||
|
label: "Login with GitHub Copilot",
|
||||||
|
form: expect.any(Array),
|
||||||
|
},
|
||||||
|
])
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
|
||||||
it.live("adds Copilot authentication and request metadata headers", () =>
|
it.live("adds Copilot authentication and request metadata headers", () =>
|
||||||
Effect.gen(function* () {
|
Effect.gen(function* () {
|
||||||
const requests: Headers[] = []
|
const requests: Headers[] = []
|
||||||
@@ -72,7 +100,6 @@ describe("GithubCopilotPlugin", () => {
|
|||||||
return Response.json({ ok: true })
|
return Response.json({ ok: true })
|
||||||
},
|
},
|
||||||
false,
|
false,
|
||||||
App.make({ name: "test", version: "1.2.3", channel: "beta" }),
|
|
||||||
)
|
)
|
||||||
yield* Effect.promise(() =>
|
yield* Effect.promise(() =>
|
||||||
send("https://api.githubcopilot.com/chat/completions", {
|
send("https://api.githubcopilot.com/chat/completions", {
|
||||||
@@ -88,7 +115,10 @@ describe("GithubCopilotPlugin", () => {
|
|||||||
expect(requests[0]?.get("x-initiator")).toBe("user")
|
expect(requests[0]?.get("x-initiator")).toBe("user")
|
||||||
expect(requests[0]?.get("copilot-vision-request")).toBe("true")
|
expect(requests[0]?.get("copilot-vision-request")).toBe("true")
|
||||||
expect(requests[0]?.get("x-github-api-version")).toBe("2026-06-01")
|
expect(requests[0]?.get("x-github-api-version")).toBe("2026-06-01")
|
||||||
expect(requests[0]?.get("user-agent")).toBe("opencode/beta/1.2.3/test")
|
expect(requests[0]?.get("user-agent")).toBe("GitHubCopilotChat/0.26.7")
|
||||||
|
expect(requests[0]?.get("editor-version")).toBe("vscode/1.99.3")
|
||||||
|
expect(requests[0]?.get("editor-plugin-version")).toBe("copilot-chat/0.26.7")
|
||||||
|
expect(requests[0]?.get("copilot-integration-id")).toBe("vscode-chat")
|
||||||
}),
|
}),
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -120,6 +150,54 @@ describe("GithubCopilotPlugin", () => {
|
|||||||
}),
|
}),
|
||||||
)
|
)
|
||||||
|
|
||||||
|
it.effect("routes all Copilot protocols through Copilot-owned SDK hooks", () =>
|
||||||
|
Effect.gen(function* () {
|
||||||
|
const catalog = yield* Catalog.Service
|
||||||
|
yield* catalog.transform((draft) => {
|
||||||
|
draft.provider.update(Provider.ID.githubCopilot, (provider) => {
|
||||||
|
provider.package = Provider.aisdk("@ai-sdk/openai-compatible")
|
||||||
|
})
|
||||||
|
draft.model.update(Provider.ID.githubCopilot, Model.ID.make("claude-sonnet"), (model) => {
|
||||||
|
model.package = Provider.aisdk("@ai-sdk/anthropic")
|
||||||
|
})
|
||||||
|
})
|
||||||
|
yield* addPlugin()
|
||||||
|
|
||||||
|
expect(required(yield* catalog.provider.get(Provider.ID.githubCopilot)).package).toBe(
|
||||||
|
Provider.aisdk(CopilotModels.Package.OpenAI),
|
||||||
|
)
|
||||||
|
expect(
|
||||||
|
required(yield* catalog.model.get(Provider.ID.githubCopilot, Model.ID.make("claude-sonnet"))).package,
|
||||||
|
).toBe(Provider.aisdk(CopilotModels.Package.Anthropic))
|
||||||
|
|
||||||
|
const fallback = yield* ModelResolver.fromCatalogModel(
|
||||||
|
Model.Info.make({
|
||||||
|
...Model.Info.default(Provider.ID.openai, Model.ID.make("fallback")),
|
||||||
|
package: Provider.aisdk("@ai-sdk/openai"),
|
||||||
|
settings: { baseURL: "https://openai.example/v1" },
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
const resolved = yield* ModelResolver.fromCatalogModel(
|
||||||
|
required(yield* catalog.model.get(Provider.ID.githubCopilot, Model.ID.make("claude-sonnet"))),
|
||||||
|
Credential.OAuth.make({
|
||||||
|
type: "oauth",
|
||||||
|
methodID: Integration.MethodID.make("device"),
|
||||||
|
refresh: "github-token",
|
||||||
|
access: "github-token",
|
||||||
|
expires: 0,
|
||||||
|
}),
|
||||||
|
{
|
||||||
|
loadAISDK: (runtime) =>
|
||||||
|
Effect.sync(() => {
|
||||||
|
expect(runtime.settings?.apiKey).toBe("github-token")
|
||||||
|
return fallback
|
||||||
|
}),
|
||||||
|
},
|
||||||
|
)
|
||||||
|
expect(resolved).toBe(fallback)
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
|
||||||
it.effect("selects languageModel when responses and chat are absent", () =>
|
it.effect("selects languageModel when responses and chat are absent", () =>
|
||||||
Effect.gen(function* () {
|
Effect.gen(function* () {
|
||||||
const plugin = yield* Plugin.Service
|
const plugin = yield* Plugin.Service
|
||||||
|
|||||||
@@ -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` },
|
answer: { 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" },
|
answer: { server: "ftp://console.example.com" },
|
||||||
})
|
})
|
||||||
.pipe(Effect.flip)
|
.pipe(Effect.flip)
|
||||||
expect(error).toBeInstanceOf(Integration.AuthorizationError)
|
expect(error).toBeInstanceOf(Integration.AuthorizationError)
|
||||||
@@ -163,6 +163,21 @@ describe("OpencodePlugin", () => {
|
|||||||
}),
|
}),
|
||||||
)
|
)
|
||||||
|
|
||||||
|
it.effect("rejects non-string OpenCode servers", () =>
|
||||||
|
Effect.gen(function* () {
|
||||||
|
yield* addPlugin()
|
||||||
|
const error = yield* (yield* Integration.Service).oauth
|
||||||
|
.connect({
|
||||||
|
integrationID: Integration.ID.make("opencode"),
|
||||||
|
methodID: Integration.MethodID.make("device"),
|
||||||
|
answer: { server: true },
|
||||||
|
})
|
||||||
|
.pipe(Effect.flip)
|
||||||
|
expect(error).toBeInstanceOf(Integration.AuthorizationError)
|
||||||
|
expect(String(error.cause)).toContain("Invalid OpenCode server URL: expected string")
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
|
||||||
it.live("loads providers and models from the connected OpenCode server", () =>
|
it.live("loads providers and models from the connected OpenCode server", () =>
|
||||||
Effect.acquireUseRelease(
|
Effect.acquireUseRelease(
|
||||||
Effect.sync(() => {
|
Effect.sync(() => {
|
||||||
|
|||||||
@@ -129,7 +129,10 @@ 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",
|
||||||
|
})
|
||||||
|
|
||||||
const output = yield* websearch.query({
|
const output = yield* websearch.query({
|
||||||
query: "effect layers",
|
query: "effect layers",
|
||||||
|
|||||||
@@ -3,12 +3,15 @@ import fs from "fs/promises"
|
|||||||
import path from "path"
|
import path from "path"
|
||||||
import { Effect } from "effect"
|
import { Effect } from "effect"
|
||||||
import { LayerNode } from "@opencode-ai/util/effect/layer-node"
|
import { LayerNode } from "@opencode-ai/util/effect/layer-node"
|
||||||
|
import { AppNodeBuilder } from "@opencode-ai/core/effect/app-node-builder"
|
||||||
|
import { Location } from "@opencode-ai/core/location"
|
||||||
import { Ripgrep } from "@opencode-ai/core/ripgrep"
|
import { Ripgrep } from "@opencode-ai/core/ripgrep"
|
||||||
import { RelativePath } from "@opencode-ai/core/schema"
|
import { RelativePath } from "@opencode-ai/core/schema"
|
||||||
import { tmpdir } from "./fixture/tmpdir"
|
import { tmpdir } from "./fixture/tmpdir"
|
||||||
import { testEffect } from "./lib/effect"
|
import { testEffect } from "./lib/effect"
|
||||||
|
import { tempLocationLayer } from "./fixture/location"
|
||||||
|
|
||||||
const it = testEffect(LayerNode.compile(Ripgrep.node))
|
const it = testEffect(AppNodeBuilder.build(Ripgrep.node, [[Location.node, tempLocationLayer]]))
|
||||||
|
|
||||||
describe("Ripgrep", () => {
|
describe("Ripgrep", () => {
|
||||||
it.live("globs files as an array", () =>
|
it.live("globs files as an array", () =>
|
||||||
|
|||||||
@@ -3,7 +3,8 @@ import { Message } from "@opencode-ai/ai"
|
|||||||
import { Model } from "@opencode-ai/core/model"
|
import { Model } from "@opencode-ai/core/model"
|
||||||
import { Provider } from "@opencode-ai/core/provider"
|
import { Provider } from "@opencode-ai/core/provider"
|
||||||
import { SessionMessage } from "@opencode-ai/core/session/message"
|
import { SessionMessage } from "@opencode-ai/core/session/message"
|
||||||
import { AgentAttachment, Base64, FileAttachment } from "@opencode-ai/schema/prompt"
|
import { AgentAttachment, Base64, FileAttachment, SkillAttachment } from "@opencode-ai/schema/prompt"
|
||||||
|
import { Skill } from "@opencode-ai/schema/skill"
|
||||||
import { toLLMMessages } from "@opencode-ai/core/session/runner/to-llm-message"
|
import { toLLMMessages } from "@opencode-ai/core/session/runner/to-llm-message"
|
||||||
import { Agent } from "@opencode-ai/core/agent"
|
import { Agent } from "@opencode-ai/core/agent"
|
||||||
import { Shell } from "@opencode-ai/schema/shell"
|
import { Shell } from "@opencode-ai/schema/shell"
|
||||||
@@ -184,6 +185,40 @@ Recent work
|
|||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|
||||||
|
test("lowers selected skill instructions with the original user prompt", () => {
|
||||||
|
const messages = toLLMMessages(
|
||||||
|
[
|
||||||
|
SessionMessage.User.make({
|
||||||
|
id: id("user-skill"),
|
||||||
|
type: "user",
|
||||||
|
text: "Design this API",
|
||||||
|
skills: [
|
||||||
|
SkillAttachment.make({
|
||||||
|
id: Skill.ID.make("api-design"),
|
||||||
|
name: Skill.Name.make("API design"),
|
||||||
|
text: "Start from the ideal call site.",
|
||||||
|
}),
|
||||||
|
],
|
||||||
|
time: { created },
|
||||||
|
}),
|
||||||
|
],
|
||||||
|
model,
|
||||||
|
)
|
||||||
|
|
||||||
|
expect(messages).toHaveLength(1)
|
||||||
|
expect(messages[0]).toMatchObject({
|
||||||
|
id: id("user-skill"),
|
||||||
|
role: "user",
|
||||||
|
content: [
|
||||||
|
{
|
||||||
|
type: "text",
|
||||||
|
text: "Start from the ideal call site.",
|
||||||
|
},
|
||||||
|
{ type: "text", text: "Design this API" },
|
||||||
|
],
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
test("decodes inline text attachment content", () => {
|
test("decodes inline text attachment content", () => {
|
||||||
const messages = toLLMMessages(
|
const messages = toLLMMessages(
|
||||||
[
|
[
|
||||||
|
|||||||
@@ -15,6 +15,7 @@ import { SessionExecution } from "@opencode-ai/core/session/execution"
|
|||||||
import { SessionMessage } from "@opencode-ai/core/session/message"
|
import { SessionMessage } from "@opencode-ai/core/session/message"
|
||||||
import { SessionProjector } from "@opencode-ai/core/session/projector"
|
import { SessionProjector } from "@opencode-ai/core/session/projector"
|
||||||
import { SessionStore } from "@opencode-ai/core/session/store"
|
import { SessionStore } from "@opencode-ai/core/session/store"
|
||||||
|
import { SessionPending } from "@opencode-ai/core/session/pending"
|
||||||
import { Skill } from "@opencode-ai/core/skill"
|
import { Skill } from "@opencode-ai/core/skill"
|
||||||
import { testEffect } from "./lib/effect"
|
import { testEffect } from "./lib/effect"
|
||||||
|
|
||||||
@@ -55,6 +56,41 @@ const it = testEffect(
|
|||||||
)
|
)
|
||||||
|
|
||||||
describe("Session.skill", () => {
|
describe("Session.skill", () => {
|
||||||
|
it.effect("attaches a resolved skill snapshot to a normal prompt", () =>
|
||||||
|
Effect.gen(function* () {
|
||||||
|
const sessions = yield* Session.Service
|
||||||
|
const database = yield* Database.Service
|
||||||
|
const bus = yield* Bus.Service
|
||||||
|
const session = yield* sessions.create({ location })
|
||||||
|
const id = SessionMessage.ID.make("msg_skill_attachment")
|
||||||
|
|
||||||
|
yield* sessions.prompt({
|
||||||
|
id,
|
||||||
|
sessionID: session.id,
|
||||||
|
text: "Apply this guidance",
|
||||||
|
skills: [{ id: Skill.ID.make("effect"), mention: { start: 20, end: 27, text: "/effect" } }],
|
||||||
|
resume: false,
|
||||||
|
})
|
||||||
|
yield* SessionPending.promote(database.db, bus, session.id, "steer")
|
||||||
|
|
||||||
|
expect(yield* sessions.messages({ sessionID: session.id })).toContainEqual(
|
||||||
|
expect.objectContaining({
|
||||||
|
id,
|
||||||
|
type: "user",
|
||||||
|
text: "Apply this guidance",
|
||||||
|
skills: [
|
||||||
|
{
|
||||||
|
id: "effect",
|
||||||
|
name: "Effect",
|
||||||
|
text: expect.stringContaining("Use Effect"),
|
||||||
|
mention: { start: 20, end: 27, text: "/effect" },
|
||||||
|
},
|
||||||
|
],
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
|
||||||
it.effect("projects the caller-supplied message ID", () =>
|
it.effect("projects the caller-supplied message ID", () =>
|
||||||
Effect.gen(function* () {
|
Effect.gen(function* () {
|
||||||
const sessions = yield* Session.Service
|
const sessions = yield* Session.Service
|
||||||
|
|||||||
@@ -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],
|
||||||
|
|||||||
@@ -14,6 +14,7 @@ import { AbsolutePath } from "@opencode-ai/core/schema"
|
|||||||
import { Session } from "@opencode-ai/core/session"
|
import { Session } from "@opencode-ai/core/session"
|
||||||
import { Tool } from "@opencode-ai/core/tool"
|
import { Tool } from "@opencode-ai/core/tool"
|
||||||
import { EditTool } from "@opencode-ai/core/tool/plugin/edit"
|
import { EditTool } from "@opencode-ai/core/tool/plugin/edit"
|
||||||
|
import { transformEnvironmentFiles } from "./fixture/environment"
|
||||||
import { location } from "./fixture/location"
|
import { location } from "./fixture/location"
|
||||||
import { tmpdir } from "./fixture/tmpdir"
|
import { tmpdir } from "./fixture/tmpdir"
|
||||||
import { makeLocationNode } from "@opencode-ai/util/effect/app-node"
|
import { makeLocationNode } from "@opencode-ai/util/effect/app-node"
|
||||||
@@ -80,29 +81,6 @@ const reset = () => {
|
|||||||
formatFile = () => Effect.succeed(false)
|
formatFile = () => Effect.succeed(false)
|
||||||
}
|
}
|
||||||
|
|
||||||
const environment = Layer.effect(
|
|
||||||
Environment.Service,
|
|
||||||
Effect.gen(function* () {
|
|
||||||
const current = yield* Environment.Service
|
|
||||||
return Environment.Service.of({
|
|
||||||
...current,
|
|
||||||
files: {
|
|
||||||
...current.files,
|
|
||||||
read: (target, range) =>
|
|
||||||
current.files
|
|
||||||
.read(target, range)
|
|
||||||
.pipe(
|
|
||||||
Effect.tap((result) =>
|
|
||||||
Effect.sync(() => reads++).pipe(Effect.andThen(Effect.suspend(() => afterRead(target, result.bytes)))),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
write: (target, content) =>
|
|
||||||
Effect.sync(() => writes.push(target)).pipe(Effect.andThen(current.files.write(target, content))),
|
|
||||||
},
|
|
||||||
})
|
|
||||||
}),
|
|
||||||
).pipe(Layer.provide(LayerNode.compile(Environment.node)))
|
|
||||||
|
|
||||||
const withTool = <A, E, R>(directory: string, body: (registry: Tool.Interface) => Effect.Effect<A, E, R>) => {
|
const withTool = <A, E, R>(directory: string, body: (registry: Tool.Interface) => Effect.Effect<A, E, R>) => {
|
||||||
const activeLocation = Layer.succeed(
|
const activeLocation = Layer.succeed(
|
||||||
Location.Service,
|
Location.Service,
|
||||||
@@ -115,7 +93,23 @@ const withTool = <A, E, R>(directory: string, body: (registry: Tool.Interface) =
|
|||||||
AppNodeBuilder.build(
|
AppNodeBuilder.build(
|
||||||
LayerNode.group([Tool.node, Tool.node, LocationMutation.node, FileMutation.node, editToolNode]),
|
LayerNode.group([Tool.node, Tool.node, LocationMutation.node, FileMutation.node, editToolNode]),
|
||||||
[
|
[
|
||||||
[Environment.node, environment],
|
[
|
||||||
|
Environment.node,
|
||||||
|
transformEnvironmentFiles(activeLocation, (files) => ({
|
||||||
|
read: (target, range) =>
|
||||||
|
files
|
||||||
|
.read(target, range)
|
||||||
|
.pipe(
|
||||||
|
Effect.tap((result) =>
|
||||||
|
Effect.sync(() => reads++).pipe(
|
||||||
|
Effect.andThen(Effect.suspend(() => afterRead(target, result.bytes))),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
write: (target, content) =>
|
||||||
|
Effect.sync(() => writes.push(target)).pipe(Effect.andThen(files.write(target, content))),
|
||||||
|
})),
|
||||||
|
],
|
||||||
[Location.node, activeLocation],
|
[Location.node, activeLocation],
|
||||||
[Formatter.node, formatter],
|
[Formatter.node, formatter],
|
||||||
[Permission.node, permission],
|
[Permission.node, permission],
|
||||||
|
|||||||
@@ -14,6 +14,7 @@ import { AbsolutePath } from "@opencode-ai/core/schema"
|
|||||||
import { Session } from "@opencode-ai/core/session"
|
import { Session } from "@opencode-ai/core/session"
|
||||||
import { Tool } from "@opencode-ai/core/tool"
|
import { Tool } from "@opencode-ai/core/tool"
|
||||||
import { PatchTool } from "@opencode-ai/core/tool/plugin/patch"
|
import { PatchTool } from "@opencode-ai/core/tool/plugin/patch"
|
||||||
|
import { transformEnvironmentFiles } from "./fixture/environment"
|
||||||
import { location } from "./fixture/location"
|
import { location } from "./fixture/location"
|
||||||
import { tmpdir } from "./fixture/tmpdir"
|
import { tmpdir } from "./fixture/tmpdir"
|
||||||
import { makeLocationNode } from "@opencode-ai/util/effect/app-node"
|
import { makeLocationNode } from "@opencode-ai/util/effect/app-node"
|
||||||
@@ -82,34 +83,6 @@ const reset = () => {
|
|||||||
formatFile = () => Effect.succeed(false)
|
formatFile = () => Effect.succeed(false)
|
||||||
}
|
}
|
||||||
|
|
||||||
const environment = Layer.effect(
|
|
||||||
Environment.Service,
|
|
||||||
Effect.gen(function* () {
|
|
||||||
const current = yield* Environment.Service
|
|
||||||
return Environment.Service.of({
|
|
||||||
...current,
|
|
||||||
files: {
|
|
||||||
...current.files,
|
|
||||||
read: (target, range) =>
|
|
||||||
Effect.sync(() => {
|
|
||||||
if (!editApproved) readsBeforeEditApproval++
|
|
||||||
}).pipe(Effect.andThen(current.files.read(target, range))),
|
|
||||||
remove: (target) => {
|
|
||||||
if (failRemoveTarget && path.basename(target) === failRemoveTarget) return Effect.die("forced remove failure")
|
|
||||||
if (failRemoveErrorTarget && path.basename(target) === failRemoveErrorTarget)
|
|
||||||
return Effect.fail(new Environment.Failed({ path: target, cause: new Error("forced remove failure") }))
|
|
||||||
return current.files.remove(target)
|
|
||||||
},
|
|
||||||
write: (target, content) => {
|
|
||||||
if (failWriteTarget && path.basename(target) === failWriteTarget)
|
|
||||||
return Effect.fail(new Environment.Failed({ path: target, cause: new Error("forced write failure") }))
|
|
||||||
return current.files.write(target, content)
|
|
||||||
},
|
|
||||||
},
|
|
||||||
})
|
|
||||||
}),
|
|
||||||
).pipe(Layer.provide(LayerNode.compile(Environment.node)))
|
|
||||||
|
|
||||||
const withTool = <A, E, R>(
|
const withTool = <A, E, R>(
|
||||||
directory: string,
|
directory: string,
|
||||||
body: (registry: Tool.Interface) => Effect.Effect<A, E, R>,
|
body: (registry: Tool.Interface) => Effect.Effect<A, E, R>,
|
||||||
@@ -126,7 +99,27 @@ const withTool = <A, E, R>(
|
|||||||
}).pipe(
|
}).pipe(
|
||||||
Effect.provide(
|
Effect.provide(
|
||||||
AppNodeBuilder.build(LayerNode.group([Tool.node, FileMutation.node, patchToolNode]), [
|
AppNodeBuilder.build(LayerNode.group([Tool.node, FileMutation.node, patchToolNode]), [
|
||||||
[Environment.node, environment],
|
[
|
||||||
|
Environment.node,
|
||||||
|
transformEnvironmentFiles(activeLocation, (files) => ({
|
||||||
|
read: (target, range) =>
|
||||||
|
Effect.sync(() => {
|
||||||
|
if (!editApproved) readsBeforeEditApproval++
|
||||||
|
}).pipe(Effect.andThen(files.read(target, range))),
|
||||||
|
remove: (target) => {
|
||||||
|
if (failRemoveTarget && path.basename(target) === failRemoveTarget)
|
||||||
|
return Effect.die("forced remove failure")
|
||||||
|
if (failRemoveErrorTarget && path.basename(target) === failRemoveErrorTarget)
|
||||||
|
return Effect.fail(new Environment.Failed({ path: target, cause: new Error("forced remove failure") }))
|
||||||
|
return files.remove(target)
|
||||||
|
},
|
||||||
|
write: (target, content) => {
|
||||||
|
if (failWriteTarget && path.basename(target) === failWriteTarget)
|
||||||
|
return Effect.fail(new Environment.Failed({ path: target, cause: new Error("forced write failure") }))
|
||||||
|
return files.write(target, content)
|
||||||
|
},
|
||||||
|
})),
|
||||||
|
],
|
||||||
[Location.node, activeLocation],
|
[Location.node, activeLocation],
|
||||||
[Formatter.node, formatter],
|
[Formatter.node, formatter],
|
||||||
[Permission.node, permission],
|
[Permission.node, permission],
|
||||||
|
|||||||
@@ -286,31 +286,6 @@ describe("ShellTool", () => {
|
|||||||
),
|
),
|
||||||
)
|
)
|
||||||
|
|
||||||
it.live(
|
|
||||||
"reports a command that fails to spawn",
|
|
||||||
() =>
|
|
||||||
Effect.acquireUseRelease(
|
|
||||||
Effect.promise(() => tmpdir()),
|
|
||||||
(tmp) => {
|
|
||||||
reset()
|
|
||||||
const command = "printf before\0after"
|
|
||||||
return withSession(tmp.path, (registry) =>
|
|
||||||
executeTool(registry, call({ command })).pipe(
|
|
||||||
Effect.andThen((settled) =>
|
|
||||||
Effect.sync(() => {
|
|
||||||
expect(settled.status).toBe("error")
|
|
||||||
if (settled.status !== "error") return
|
|
||||||
expect(settled.error?.message).toContain("Command failed")
|
|
||||||
}),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
)
|
|
||||||
},
|
|
||||||
(tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]().then(() => undefined)),
|
|
||||||
),
|
|
||||||
{ timeout: 2_000 },
|
|
||||||
)
|
|
||||||
|
|
||||||
it.live("permissions compound commands separately", () =>
|
it.live("permissions compound commands separately", () =>
|
||||||
Effect.acquireUseRelease(
|
Effect.acquireUseRelease(
|
||||||
Effect.promise(() => tmpdir()),
|
Effect.promise(() => tmpdir()),
|
||||||
|
|||||||
@@ -105,9 +105,9 @@ describe("SkillTool", () => {
|
|||||||
}),
|
}),
|
||||||
).toMatchObject({
|
).toMatchObject({
|
||||||
status: "completed",
|
status: "completed",
|
||||||
content: [{ type: "text", text: SkillTool.toModelOutput(info, [reference]) }],
|
content: [{ type: "text", text: Skill.toModelOutput(info, [reference]) }],
|
||||||
})
|
})
|
||||||
expect(SkillTool.toModelOutput(info, [reference])).toContain(`Base directory for this skill: ${directory}`)
|
expect(Skill.toModelOutput(info, [reference])).toContain(`Base directory for this skill: ${directory}`)
|
||||||
expect(
|
expect(
|
||||||
yield* executeTool(registry, {
|
yield* executeTool(registry, {
|
||||||
sessionID,
|
sessionID,
|
||||||
@@ -116,8 +116,8 @@ describe("SkillTool", () => {
|
|||||||
}),
|
}),
|
||||||
).toEqual({
|
).toEqual({
|
||||||
status: "completed",
|
status: "completed",
|
||||||
output: { name: "Effect", directory, output: SkillTool.toModelOutput(info, [reference]) },
|
output: { name: "Effect", directory, output: Skill.toModelOutput(info, [reference]) },
|
||||||
content: [{ type: "text", text: SkillTool.toModelOutput(info, [reference]) }],
|
content: [{ type: "text", text: Skill.toModelOutput(info, [reference]) }],
|
||||||
metadata: { name: "Effect", directory },
|
metadata: { name: "Effect", directory },
|
||||||
})
|
})
|
||||||
expect(assertions).toMatchObject([
|
expect(assertions).toMatchObject([
|
||||||
@@ -168,7 +168,7 @@ describe("SkillTool", () => {
|
|||||||
}),
|
}),
|
||||||
).toMatchObject({
|
).toMatchObject({
|
||||||
status: "completed",
|
status: "completed",
|
||||||
content: [{ type: "text", text: SkillTool.toModelOutput(flat, []) }],
|
content: [{ type: "text", text: Skill.toModelOutput(flat, []) }],
|
||||||
})
|
})
|
||||||
}).pipe(Effect.provide(skillToolLayer))
|
}).pipe(Effect.provide(skillToolLayer))
|
||||||
}),
|
}),
|
||||||
|
|||||||
@@ -14,6 +14,7 @@ import { AbsolutePath } from "@opencode-ai/core/schema"
|
|||||||
import { Session } from "@opencode-ai/core/session"
|
import { Session } from "@opencode-ai/core/session"
|
||||||
import { Tool } from "@opencode-ai/core/tool"
|
import { Tool } from "@opencode-ai/core/tool"
|
||||||
import { WriteTool } from "@opencode-ai/core/tool/plugin/write"
|
import { WriteTool } from "@opencode-ai/core/tool/plugin/write"
|
||||||
|
import { transformEnvironmentFiles } from "./fixture/environment"
|
||||||
import { location } from "./fixture/location"
|
import { location } from "./fixture/location"
|
||||||
import { tmpdir } from "./fixture/tmpdir"
|
import { tmpdir } from "./fixture/tmpdir"
|
||||||
import { makeLocationNode } from "@opencode-ai/util/effect/app-node"
|
import { makeLocationNode } from "@opencode-ai/util/effect/app-node"
|
||||||
@@ -68,21 +69,6 @@ const reset = () => {
|
|||||||
denyAction = undefined
|
denyAction = undefined
|
||||||
}
|
}
|
||||||
|
|
||||||
const environment = Layer.effect(
|
|
||||||
Environment.Service,
|
|
||||||
Effect.gen(function* () {
|
|
||||||
const current = yield* Environment.Service
|
|
||||||
return Environment.Service.of({
|
|
||||||
...current,
|
|
||||||
files: {
|
|
||||||
...current.files,
|
|
||||||
write: (target, content) =>
|
|
||||||
Effect.sync(() => writes.push(target)).pipe(Effect.andThen(current.files.write(target, content))),
|
|
||||||
},
|
|
||||||
})
|
|
||||||
}),
|
|
||||||
).pipe(Layer.provide(LayerNode.compile(Environment.node)))
|
|
||||||
|
|
||||||
const withTool = <A, E, R>(directory: string, body: (registry: Tool.Interface) => Effect.Effect<A, E, R>) => {
|
const withTool = <A, E, R>(directory: string, body: (registry: Tool.Interface) => Effect.Effect<A, E, R>) => {
|
||||||
const activeLocation = Layer.succeed(
|
const activeLocation = Layer.succeed(
|
||||||
Location.Service,
|
Location.Service,
|
||||||
@@ -95,7 +81,13 @@ const withTool = <A, E, R>(directory: string, body: (registry: Tool.Interface) =
|
|||||||
AppNodeBuilder.build(
|
AppNodeBuilder.build(
|
||||||
LayerNode.group([Tool.node, Tool.node, LocationMutation.node, FileMutation.node, writeToolNode]),
|
LayerNode.group([Tool.node, Tool.node, LocationMutation.node, FileMutation.node, writeToolNode]),
|
||||||
[
|
[
|
||||||
[Environment.node, environment],
|
[
|
||||||
|
Environment.node,
|
||||||
|
transformEnvironmentFiles(activeLocation, (files) => ({
|
||||||
|
write: (target, content) =>
|
||||||
|
Effect.sync(() => writes.push(target)).pipe(Effect.andThen(files.write(target, content))),
|
||||||
|
})),
|
||||||
|
],
|
||||||
[Location.node, activeLocation],
|
[Location.node, activeLocation],
|
||||||
[Formatter.node, formatter],
|
[Formatter.node, formatter],
|
||||||
[Permission.node, permission],
|
[Permission.node, permission],
|
||||||
|
|||||||
@@ -0,0 +1,106 @@
|
|||||||
|
import { beforeEach, expect } from "bun:test"
|
||||||
|
import { AppNodeBuilder } from "@opencode-ai/core/effect/app-node-builder"
|
||||||
|
import { Database } from "@opencode-ai/core/database/database"
|
||||||
|
import { makeMemoryDriver } from "@opencode-ai/core/environment"
|
||||||
|
import { Workspace } from "@opencode-ai/core/workspace"
|
||||||
|
import { WorkspaceDriver } from "@opencode-ai/core/workspace/driver"
|
||||||
|
import { WorkspaceTable } from "@opencode-ai/core/workspace/sql"
|
||||||
|
import { LayerNode } from "@opencode-ai/util/effect/layer-node"
|
||||||
|
import { eq } from "drizzle-orm"
|
||||||
|
import { Effect } from "effect"
|
||||||
|
import { TestClock } from "effect/testing"
|
||||||
|
import { ChildProcess } from "effect/unstable/process"
|
||||||
|
import { testEffect } from "./lib/effect"
|
||||||
|
|
||||||
|
const calls: Array<{ readonly operation: string; readonly binding?: WorkspaceDriver.Binding }> = []
|
||||||
|
const memory = makeMemoryDriver()
|
||||||
|
let failConnect = false
|
||||||
|
|
||||||
|
const driver = WorkspaceDriver.make({
|
||||||
|
create: ({ workspaceID }) => {
|
||||||
|
calls.push({ operation: "create" })
|
||||||
|
return Effect.succeed({ binding: { workspaceID, generation: 0 } })
|
||||||
|
},
|
||||||
|
connect: ({ binding }) => {
|
||||||
|
calls.push({ operation: "connect", binding })
|
||||||
|
if (failConnect) return Effect.fail(new WorkspaceDriver.Error({ message: "wake failed" }))
|
||||||
|
return Effect.succeed(memory)
|
||||||
|
},
|
||||||
|
suspendForIdle: ({ binding, saveBinding }) => {
|
||||||
|
calls.push({ operation: "suspendForIdle", binding })
|
||||||
|
return saveBinding({ ...binding, generation: Number(binding.generation) + 1, suspended: true })
|
||||||
|
},
|
||||||
|
destroy: ({ binding }) => {
|
||||||
|
calls.push({ operation: "destroy", binding })
|
||||||
|
return Effect.void
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
const it = testEffect(
|
||||||
|
AppNodeBuilder.build(
|
||||||
|
LayerNode.group([Database.node, Workspace.configured({ idleThreshold: "5 minutes", pollInterval: "1 minute" })]),
|
||||||
|
[[WorkspaceDriver.node, WorkspaceDriver.registryNode({ fake: driver })]],
|
||||||
|
),
|
||||||
|
)
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
calls.splice(0)
|
||||||
|
failConnect = false
|
||||||
|
})
|
||||||
|
|
||||||
|
it.effect("persists the workspace lifecycle and reconnects after idle suspension", () =>
|
||||||
|
Effect.gen(function* () {
|
||||||
|
const workspace = yield* Workspace.Service
|
||||||
|
const created = yield* workspace.create("fake")
|
||||||
|
|
||||||
|
expect(created.id.startsWith("wrk_")).toBe(true)
|
||||||
|
expect(created.binding).toEqual({ workspaceID: created.id, generation: 0 })
|
||||||
|
|
||||||
|
const environment = yield* workspace.connect(created.id)
|
||||||
|
expect(calls.map((call) => call.operation)).toEqual(["create"])
|
||||||
|
|
||||||
|
yield* TestClock.adjust("4 minutes")
|
||||||
|
yield* Effect.scoped(environment.spawner.spawn(ChildProcess.make("activity"))).pipe(Effect.exit)
|
||||||
|
yield* TestClock.adjust("4 minutes")
|
||||||
|
expect(calls.map((call) => call.operation)).toEqual(["create", "connect"])
|
||||||
|
|
||||||
|
yield* TestClock.adjust("2 minutes")
|
||||||
|
expect(calls.map((call) => call.operation)).toEqual(["create", "connect", "suspendForIdle"])
|
||||||
|
|
||||||
|
const stored = yield* Database.Service.use(({ db }) =>
|
||||||
|
db.select().from(WorkspaceTable).where(eq(WorkspaceTable.id, created.id)).get(),
|
||||||
|
).pipe(Effect.orDie)
|
||||||
|
expect(stored?.binding).toEqual({ workspaceID: created.id, generation: 1, suspended: true })
|
||||||
|
expect(stored?.last_used_at).toBe(4 * 60 * 1000)
|
||||||
|
|
||||||
|
yield* Effect.scoped(environment.spawner.spawn(ChildProcess.make("wake"))).pipe(Effect.exit)
|
||||||
|
expect(calls.map((call) => call.operation)).toEqual(["create", "connect", "suspendForIdle", "connect"])
|
||||||
|
expect(calls.at(-1)?.binding).toEqual({ workspaceID: created.id, generation: 1, suspended: true })
|
||||||
|
|
||||||
|
yield* workspace.destroy(created.id)
|
||||||
|
expect(calls.at(-1)?.operation).toBe("destroy")
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
|
||||||
|
it.effect("surfaces wake failures through the spawn error channel", () =>
|
||||||
|
Effect.gen(function* () {
|
||||||
|
const workspace = yield* Workspace.Service
|
||||||
|
const created = yield* workspace.create("fake")
|
||||||
|
const environment = yield* workspace.connect(created.id)
|
||||||
|
yield* Effect.scoped(environment.spawner.spawn(ChildProcess.make("connect"))).pipe(Effect.exit)
|
||||||
|
|
||||||
|
yield* TestClock.adjust("6 minutes")
|
||||||
|
failConnect = true
|
||||||
|
|
||||||
|
const error = yield* Effect.scoped(environment.spawner.spawn(ChildProcess.make("wake"))).pipe(Effect.flip)
|
||||||
|
expect(error).toMatchObject({
|
||||||
|
_tag: "PlatformError",
|
||||||
|
reason: {
|
||||||
|
_tag: "Unknown",
|
||||||
|
module: "Workspace",
|
||||||
|
method: "spawn",
|
||||||
|
description: `Failed to wake workspace ${created.id}`,
|
||||||
|
},
|
||||||
|
})
|
||||||
|
}),
|
||||||
|
)
|
||||||
@@ -1316,7 +1316,15 @@ export function write(
|
|||||||
}).pipe(Effect.flatMap((content) => fs.writeFileString(join(directory, file.path), content))),
|
}).pipe(Effect.flatMap((content) => fs.writeFileString(join(directory, file.path), content))),
|
||||||
{ concurrency: 8, discard: true },
|
{ concurrency: 8, discard: true },
|
||||||
)
|
)
|
||||||
yield* fs.writeFileString(manifest, JSON.stringify(output.files.map((file) => file.path).sort(), null, 2) + "\n")
|
// Format the manifest with the same prettier settings as the repo-wide
|
||||||
|
// format pass, so `check:generated` stays clean after the generate bot
|
||||||
|
// reformats the tree.
|
||||||
|
const manifestJson = JSON.stringify(output.files.map((file) => file.path).sort())
|
||||||
|
const manifestContent = yield* Effect.tryPromise({
|
||||||
|
try: () => format(manifestJson, { filepath: manifest, parser: "json", printWidth: 120 }),
|
||||||
|
catch: (error) => new GenerationError({ reason: `Failed to format ${manifest}: ${String(error)}` }),
|
||||||
|
})
|
||||||
|
yield* fs.writeFileString(manifest, manifestContent)
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -16,7 +16,7 @@ describe("HttpApiCodegen.write", () => {
|
|||||||
|
|
||||||
expect(writes).toEqual([
|
expect(writes).toEqual([
|
||||||
{ path: "/generated/session.ts", content: "export const session = {}\n" },
|
{ path: "/generated/session.ts", content: "export const session = {}\n" },
|
||||||
{ path: "/generated/.httpapi-codegen.json", content: '[\n "session.ts"\n]\n' },
|
{ path: "/generated/.httpapi-codegen.json", content: '["session.ts"]\n' },
|
||||||
])
|
])
|
||||||
}).pipe(
|
}).pipe(
|
||||||
Effect.provideService(
|
Effect.provideService(
|
||||||
|
|||||||
@@ -1,19 +1,43 @@
|
|||||||
import type {
|
import type { ConnectionInfo } from "@opencode-ai/client"
|
||||||
ConnectionInfo,
|
|
||||||
IntegrationCommandMethod,
|
|
||||||
IntegrationEnvMethod,
|
|
||||||
IntegrationKeyMethod,
|
|
||||||
IntegrationMethod,
|
|
||||||
IntegrationOAuthMethod,
|
|
||||||
} 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 interface IntegrationOAuthMethod {
|
||||||
|
readonly id: string
|
||||||
|
readonly type: "oauth"
|
||||||
|
readonly label: string
|
||||||
|
readonly form?: Form.Fields
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface IntegrationCommandMethod {
|
||||||
|
readonly id: string
|
||||||
|
readonly type: "command"
|
||||||
|
readonly label: string
|
||||||
|
readonly command: ReadonlyArray<string>
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface IntegrationKeyMethod {
|
||||||
|
readonly type: "key"
|
||||||
|
readonly label?: string
|
||||||
|
readonly form?: Form.Fields
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface IntegrationEnvMethod {
|
||||||
|
readonly type: "env"
|
||||||
|
readonly names: ReadonlyArray<string>
|
||||||
|
}
|
||||||
|
|
||||||
|
export type IntegrationMethod =
|
||||||
|
| IntegrationOAuthMethod
|
||||||
|
| IntegrationCommandMethod
|
||||||
|
| IntegrationKeyMethod
|
||||||
|
| IntegrationEnvMethod
|
||||||
|
|
||||||
export type IntegrationOAuthAuthorization = {
|
export type IntegrationOAuthAuthorization = {
|
||||||
readonly url: string
|
readonly url: string
|
||||||
readonly instructions: string
|
readonly instructions: string
|
||||||
@@ -31,7 +55,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: (answer: 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
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,18 +1,42 @@
|
|||||||
import type {
|
import type { ConnectionInfo } from "@opencode-ai/client"
|
||||||
ConnectionInfo,
|
|
||||||
IntegrationCommandMethod,
|
|
||||||
IntegrationEnvMethod,
|
|
||||||
IntegrationKeyMethod,
|
|
||||||
IntegrationMethod,
|
|
||||||
IntegrationOAuthMethod,
|
|
||||||
} 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 interface IntegrationOAuthMethod {
|
||||||
|
readonly id: string
|
||||||
|
readonly type: "oauth"
|
||||||
|
readonly label: string
|
||||||
|
readonly form?: Form.Fields
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface IntegrationCommandMethod {
|
||||||
|
readonly id: string
|
||||||
|
readonly type: "command"
|
||||||
|
readonly label: string
|
||||||
|
readonly command: ReadonlyArray<string>
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface IntegrationKeyMethod {
|
||||||
|
readonly type: "key"
|
||||||
|
readonly label?: string
|
||||||
|
readonly form?: Form.Fields
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface IntegrationEnvMethod {
|
||||||
|
readonly type: "env"
|
||||||
|
readonly names: ReadonlyArray<string>
|
||||||
|
}
|
||||||
|
|
||||||
|
export type IntegrationMethod =
|
||||||
|
| IntegrationOAuthMethod
|
||||||
|
| IntegrationCommandMethod
|
||||||
|
| IntegrationKeyMethod
|
||||||
|
| IntegrationEnvMethod
|
||||||
|
|
||||||
export type IntegrationOAuthAuthorization = {
|
export type IntegrationOAuthAuthorization = {
|
||||||
readonly url: string
|
readonly url: string
|
||||||
readonly instructions: string
|
readonly instructions: string
|
||||||
@@ -31,7 +55,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: (answer: 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
|
||||||
}
|
}
|
||||||
@@ -39,7 +63,10 @@ export type IntegrationOAuthMethodRegistration = {
|
|||||||
export type IntegrationMethodRegistration =
|
export type IntegrationMethodRegistration =
|
||||||
| IntegrationOAuthMethodRegistration
|
| IntegrationOAuthMethodRegistration
|
||||||
| { readonly integrationID: string; readonly method: IntegrationCommandMethod }
|
| { readonly integrationID: string; readonly method: IntegrationCommandMethod }
|
||||||
| { readonly integrationID: string; readonly method: IntegrationKeyMethod }
|
| {
|
||||||
|
readonly integrationID: string
|
||||||
|
readonly method: IntegrationKeyMethod
|
||||||
|
}
|
||||||
| { readonly integrationID: string; readonly method: IntegrationEnvMethod }
|
| { readonly integrationID: string; readonly method: IntegrationEnvMethod }
|
||||||
|
|
||||||
export interface IntegrationDraft {
|
export interface IntegrationDraft {
|
||||||
|
|||||||
@@ -1809,6 +1809,12 @@
|
|||||||
"$ref": "#/components/schemas/Prompt.AgentAttachment"
|
"$ref": "#/components/schemas/Prompt.AgentAttachment"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"skills": {
|
||||||
|
"type": "array",
|
||||||
|
"items": {
|
||||||
|
"$ref": "#/components/schemas/PromptInput.SkillAttachment"
|
||||||
|
}
|
||||||
|
},
|
||||||
"metadata": {
|
"metadata": {
|
||||||
"type": "object"
|
"type": "object"
|
||||||
},
|
},
|
||||||
@@ -2017,6 +2023,12 @@
|
|||||||
"$ref": "#/components/schemas/Prompt.AgentAttachment"
|
"$ref": "#/components/schemas/Prompt.AgentAttachment"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"skills": {
|
||||||
|
"type": "array",
|
||||||
|
"items": {
|
||||||
|
"$ref": "#/components/schemas/PromptInput.SkillAttachment"
|
||||||
|
}
|
||||||
|
},
|
||||||
"delivery": {
|
"delivery": {
|
||||||
"anyOf": [
|
"anyOf": [
|
||||||
{
|
{
|
||||||
@@ -12841,6 +12853,25 @@
|
|||||||
"required": ["name"],
|
"required": ["name"],
|
||||||
"additionalProperties": false
|
"additionalProperties": false
|
||||||
},
|
},
|
||||||
|
"Prompt.SkillAttachment": {
|
||||||
|
"type": "object",
|
||||||
|
"properties": {
|
||||||
|
"id": {
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
"name": {
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
"text": {
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
"mention": {
|
||||||
|
"$ref": "#/components/schemas/Prompt.Mention"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"required": ["id", "name", "text"],
|
||||||
|
"additionalProperties": false
|
||||||
|
},
|
||||||
"Session.Message.User": {
|
"Session.Message.User": {
|
||||||
"type": "object",
|
"type": "object",
|
||||||
"properties": {
|
"properties": {
|
||||||
@@ -12880,6 +12911,12 @@
|
|||||||
"$ref": "#/components/schemas/Prompt.AgentAttachment"
|
"$ref": "#/components/schemas/Prompt.AgentAttachment"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"skills": {
|
||||||
|
"type": "array",
|
||||||
|
"items": {
|
||||||
|
"$ref": "#/components/schemas/Prompt.SkillAttachment"
|
||||||
|
}
|
||||||
|
},
|
||||||
"type": {
|
"type": {
|
||||||
"type": "string",
|
"type": "string",
|
||||||
"enum": ["user"]
|
"enum": ["user"]
|
||||||
@@ -13837,6 +13874,19 @@
|
|||||||
"required": ["uri"],
|
"required": ["uri"],
|
||||||
"additionalProperties": false
|
"additionalProperties": false
|
||||||
},
|
},
|
||||||
|
"PromptInput.SkillAttachment": {
|
||||||
|
"type": "object",
|
||||||
|
"properties": {
|
||||||
|
"id": {
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
"mention": {
|
||||||
|
"$ref": "#/components/schemas/Prompt.Mention"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"required": ["id"],
|
||||||
|
"additionalProperties": false
|
||||||
|
},
|
||||||
"SessionPending.UserData": {
|
"SessionPending.UserData": {
|
||||||
"type": "object",
|
"type": "object",
|
||||||
"properties": {
|
"properties": {
|
||||||
@@ -13855,6 +13905,12 @@
|
|||||||
"$ref": "#/components/schemas/Prompt.AgentAttachment"
|
"$ref": "#/components/schemas/Prompt.AgentAttachment"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"skills": {
|
||||||
|
"type": "array",
|
||||||
|
"items": {
|
||||||
|
"$ref": "#/components/schemas/Prompt.SkillAttachment"
|
||||||
|
}
|
||||||
|
},
|
||||||
"metadata": {
|
"metadata": {
|
||||||
"type": "object"
|
"type": "object"
|
||||||
}
|
}
|
||||||
@@ -14764,6 +14820,12 @@
|
|||||||
"$ref": "#/components/schemas/Prompt.AgentAttachment"
|
"$ref": "#/components/schemas/Prompt.AgentAttachment"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"skills": {
|
||||||
|
"type": "array",
|
||||||
|
"items": {
|
||||||
|
"$ref": "#/components/schemas/Prompt.SkillAttachment"
|
||||||
|
}
|
||||||
|
},
|
||||||
"metadata": {
|
"metadata": {
|
||||||
"type": "object"
|
"type": "object"
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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,
|
||||||
|
answer: Schema.optional(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,
|
answer: Schema.optional(Form.Answer),
|
||||||
label: Schema.optional(Schema.String),
|
label: Schema.optional(Schema.String),
|
||||||
}),
|
}),
|
||||||
success: Location.response(Integration.Attempt),
|
success: Location.response(Integration.Attempt),
|
||||||
|
|||||||
@@ -345,6 +345,7 @@ export const makeSessionGroup = <I extends HttpApiMiddleware.AnyId, S>(sessionLo
|
|||||||
model: Model.Ref.pipe(Schema.optional),
|
model: Model.Ref.pipe(Schema.optional),
|
||||||
files: PromptInput.Prompt.fields.files,
|
files: PromptInput.Prompt.fields.files,
|
||||||
agents: PromptInput.Prompt.fields.agents,
|
agents: PromptInput.Prompt.fields.agents,
|
||||||
|
skills: PromptInput.Prompt.fields.skills,
|
||||||
delivery: SessionPending.Delivery.pipe(Schema.optional),
|
delivery: SessionPending.Delivery.pipe(Schema.optional),
|
||||||
resume: Schema.Boolean.pipe(Schema.optional),
|
resume: Schema.Boolean.pipe(Schema.optional),
|
||||||
}),
|
}),
|
||||||
|
|||||||
@@ -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)),
|
form: 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),
|
||||||
|
form: 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: {},
|
||||||
|
|||||||
@@ -3,6 +3,7 @@ export * as PromptInput from "./prompt-input.js"
|
|||||||
import { Schema } from "effect"
|
import { Schema } from "effect"
|
||||||
import { AgentAttachment, PromptMention } from "./prompt.js"
|
import { AgentAttachment, PromptMention } from "./prompt.js"
|
||||||
import { optional, statics } from "./schema.js"
|
import { optional, statics } from "./schema.js"
|
||||||
|
import { Skill } from "./skill.js"
|
||||||
|
|
||||||
export interface FileAttachment extends Schema.Schema.Type<typeof FileAttachment> {}
|
export interface FileAttachment extends Schema.Schema.Type<typeof FileAttachment> {}
|
||||||
export const FileAttachment = Schema.Struct({
|
export const FileAttachment = Schema.Struct({
|
||||||
@@ -19,8 +20,15 @@ export const FileAttachment = Schema.Struct({
|
|||||||
)
|
)
|
||||||
|
|
||||||
export interface Prompt extends Schema.Schema.Type<typeof Prompt> {}
|
export interface Prompt extends Schema.Schema.Type<typeof Prompt> {}
|
||||||
|
export interface SkillAttachment extends Schema.Schema.Type<typeof SkillAttachment> {}
|
||||||
|
export const SkillAttachment = Schema.Struct({
|
||||||
|
id: Skill.ID,
|
||||||
|
mention: PromptMention.pipe(optional),
|
||||||
|
}).annotate({ identifier: "PromptInput.SkillAttachment" })
|
||||||
|
|
||||||
export const Prompt = Schema.Struct({
|
export const Prompt = Schema.Struct({
|
||||||
text: Schema.String,
|
text: Schema.String,
|
||||||
files: Schema.Array(FileAttachment).pipe(optional),
|
files: Schema.Array(FileAttachment).pipe(optional),
|
||||||
agents: Schema.Array(AgentAttachment).pipe(optional),
|
agents: Schema.Array(AgentAttachment).pipe(optional),
|
||||||
|
skills: Schema.Array(SkillAttachment).pipe(optional),
|
||||||
}).annotate({ identifier: "PromptInput" })
|
}).annotate({ identifier: "PromptInput" })
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
import { Schema } from "effect"
|
import { Schema } from "effect"
|
||||||
import { optional } from "./schema.js"
|
import { optional } from "./schema.js"
|
||||||
import { statics } from "./schema.js"
|
import { statics } from "./schema.js"
|
||||||
|
import { Skill } from "./skill.js"
|
||||||
|
|
||||||
export interface PromptMention extends Schema.Schema.Type<typeof PromptMention> {}
|
export interface PromptMention extends Schema.Schema.Type<typeof PromptMention> {}
|
||||||
export const PromptMention = Schema.Struct({
|
export const PromptMention = Schema.Struct({
|
||||||
@@ -52,21 +53,31 @@ export const AgentAttachment = Schema.Struct({
|
|||||||
mention: PromptMention.pipe(optional),
|
mention: PromptMention.pipe(optional),
|
||||||
}).annotate({ identifier: "Prompt.AgentAttachment" })
|
}).annotate({ identifier: "Prompt.AgentAttachment" })
|
||||||
|
|
||||||
|
export interface SkillAttachment extends Schema.Schema.Type<typeof SkillAttachment> {}
|
||||||
|
export const SkillAttachment = Schema.Struct({
|
||||||
|
id: Skill.ID,
|
||||||
|
name: Skill.Name,
|
||||||
|
text: Schema.String,
|
||||||
|
mention: PromptMention.pipe(optional),
|
||||||
|
}).annotate({ identifier: "Prompt.SkillAttachment" })
|
||||||
|
|
||||||
export interface Prompt extends Schema.Schema.Type<typeof Prompt> {}
|
export interface Prompt extends Schema.Schema.Type<typeof Prompt> {}
|
||||||
export const Prompt = Schema.Struct({
|
export const Prompt = Schema.Struct({
|
||||||
text: Schema.String,
|
text: Schema.String,
|
||||||
files: Schema.Array(FileAttachment).pipe(optional),
|
files: Schema.Array(FileAttachment).pipe(optional),
|
||||||
agents: Schema.Array(AgentAttachment).pipe(optional),
|
agents: Schema.Array(AgentAttachment).pipe(optional),
|
||||||
|
skills: Schema.Array(SkillAttachment).pipe(optional),
|
||||||
})
|
})
|
||||||
.annotate({ identifier: "Prompt" })
|
.annotate({ identifier: "Prompt" })
|
||||||
.pipe(
|
.pipe(
|
||||||
statics((schema) => ({
|
statics((schema) => ({
|
||||||
equivalence: Schema.toEquivalence(schema),
|
equivalence: Schema.toEquivalence(schema),
|
||||||
fromUserMessage: (input: Pick<Prompt, "text" | "files" | "agents">) =>
|
fromUserMessage: (input: Pick<Prompt, "text" | "files" | "agents" | "skills">) =>
|
||||||
schema.make({
|
schema.make({
|
||||||
text: input.text,
|
text: input.text,
|
||||||
...(input.files === undefined ? {} : { files: input.files }),
|
...(input.files === undefined ? {} : { files: input.files }),
|
||||||
...(input.agents === undefined ? {} : { agents: input.agents }),
|
...(input.agents === undefined ? {} : { agents: input.agents }),
|
||||||
|
...(input.skills === undefined ? {} : { skills: input.skills }),
|
||||||
}),
|
}),
|
||||||
})),
|
})),
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -58,6 +58,7 @@ export const User = Schema.Struct({
|
|||||||
text: Prompt.fields.text,
|
text: Prompt.fields.text,
|
||||||
files: Prompt.fields.files,
|
files: Prompt.fields.files,
|
||||||
agents: Prompt.fields.agents,
|
agents: Prompt.fields.agents,
|
||||||
|
skills: Prompt.fields.skills,
|
||||||
type: Schema.tag("user"),
|
type: Schema.tag("user"),
|
||||||
}).annotate({ identifier: "Session.Message.User" })
|
}).annotate({ identifier: "Session.Message.User" })
|
||||||
|
|
||||||
|
|||||||
@@ -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,
|
||||||
|
answer: ctx.payload.answer,
|
||||||
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,
|
answer: ctx.payload.answer,
|
||||||
label: ctx.payload.label,
|
label: ctx.payload.label,
|
||||||
}),
|
}),
|
||||||
),
|
),
|
||||||
|
|||||||
@@ -313,6 +313,7 @@ export const SessionHandler = HttpApiBuilder.group(Api, "server.session", (handl
|
|||||||
text: ctx.payload.text,
|
text: ctx.payload.text,
|
||||||
files: ctx.payload.files,
|
files: ctx.payload.files,
|
||||||
agents: ctx.payload.agents,
|
agents: ctx.payload.agents,
|
||||||
|
skills: ctx.payload.skills,
|
||||||
metadata: ctx.payload.metadata,
|
metadata: ctx.payload.metadata,
|
||||||
delivery: ctx.payload.delivery,
|
delivery: ctx.payload.delivery,
|
||||||
resume: ctx.payload.resume,
|
resume: ctx.payload.resume,
|
||||||
@@ -337,6 +338,9 @@ export const SessionHandler = HttpApiBuilder.group(Api, "server.session", (handl
|
|||||||
Effect.catchTag("Session.AttachmentError", (error) =>
|
Effect.catchTag("Session.AttachmentError", (error) =>
|
||||||
Effect.fail(new InvalidRequestError({ message: error.message, field: "files" })),
|
Effect.fail(new InvalidRequestError({ message: error.message, field: "files" })),
|
||||||
),
|
),
|
||||||
|
Effect.catchTag("Session.SkillNotFoundError", (error) =>
|
||||||
|
Effect.fail(new InvalidRequestError({ message: `Skill not found: ${error.skill}`, field: "skills" })),
|
||||||
|
),
|
||||||
),
|
),
|
||||||
}
|
}
|
||||||
}),
|
}),
|
||||||
@@ -355,6 +359,7 @@ export const SessionHandler = HttpApiBuilder.group(Api, "server.session", (handl
|
|||||||
model: ctx.payload.model,
|
model: ctx.payload.model,
|
||||||
files: ctx.payload.files,
|
files: ctx.payload.files,
|
||||||
agents: ctx.payload.agents,
|
agents: ctx.payload.agents,
|
||||||
|
skills: ctx.payload.skills,
|
||||||
delivery: ctx.payload.delivery,
|
delivery: ctx.payload.delivery,
|
||||||
resume: ctx.payload.resume,
|
resume: ctx.payload.resume,
|
||||||
})
|
})
|
||||||
@@ -394,6 +399,9 @@ export const SessionHandler = HttpApiBuilder.group(Api, "server.session", (handl
|
|||||||
Effect.catchTag("Session.AttachmentError", (error) =>
|
Effect.catchTag("Session.AttachmentError", (error) =>
|
||||||
Effect.fail(new InvalidRequestError({ message: error.message, field: "files" })),
|
Effect.fail(new InvalidRequestError({ message: error.message, field: "files" })),
|
||||||
),
|
),
|
||||||
|
Effect.catchTag("Session.SkillNotFoundError", (error) =>
|
||||||
|
Effect.fail(new InvalidRequestError({ message: `Skill not found: ${error.skill}`, field: "skills" })),
|
||||||
|
),
|
||||||
),
|
),
|
||||||
}
|
}
|
||||||
}),
|
}),
|
||||||
|
|||||||
@@ -21,9 +21,7 @@ export const ShellHandler = HttpApiBuilder.group(Api, "server.shell", (handlers)
|
|||||||
Effect.fn(function* (ctx) {
|
Effect.fn(function* (ctx) {
|
||||||
const shell = yield* Shell.Service
|
const shell = yield* Shell.Service
|
||||||
const location = yield* Location.Service
|
const location = yield* Location.Service
|
||||||
return yield* response(
|
return yield* response(shell.create({ ...ctx.payload, cwd: ctx.payload.cwd || location.directory }))
|
||||||
shell.create({ ...ctx.payload, cwd: ctx.payload.cwd || location.directory }).pipe(Effect.orDie),
|
|
||||||
)
|
|
||||||
}),
|
}),
|
||||||
)
|
)
|
||||||
.handle(
|
.handle(
|
||||||
|
|||||||
@@ -28,6 +28,7 @@ import { SessionRestart } from "@opencode-ai/core/session/execution/restart"
|
|||||||
import { PluginRuntime } from "@opencode-ai/core/plugin/runtime"
|
import { PluginRuntime } from "@opencode-ai/core/plugin/runtime"
|
||||||
import { SdkPlugins } from "@opencode-ai/core/plugin/sdk"
|
import { SdkPlugins } from "@opencode-ai/core/plugin/sdk"
|
||||||
import { WellKnown } from "@opencode-ai/core/wellknown"
|
import { WellKnown } from "@opencode-ai/core/wellknown"
|
||||||
|
import { WorkspaceDriver } from "@opencode-ai/core/workspace/driver"
|
||||||
import { Watcher } from "@opencode-ai/core/filesystem/watcher"
|
import { Watcher } from "@opencode-ai/core/filesystem/watcher"
|
||||||
import { HttpRouter } from "effect/unstable/http"
|
import { HttpRouter } from "effect/unstable/http"
|
||||||
import { HttpApiBuilder } from "effect/unstable/httpapi"
|
import { HttpApiBuilder } from "effect/unstable/httpapi"
|
||||||
@@ -43,6 +44,7 @@ import { formLocationLayer } from "./middleware/form-location"
|
|||||||
import { sessionLocationLayer } from "./middleware/session-location"
|
import { sessionLocationLayer } from "./middleware/session-location"
|
||||||
import { ServerInfo } from "./server-info"
|
import { ServerInfo } from "./server-info"
|
||||||
import type { ServerOptions } from "./options"
|
import type { ServerOptions } from "./options"
|
||||||
|
import { modalWorkspaceDriver, provider as modalProvider } from "./workspace/modal-workspace"
|
||||||
|
|
||||||
const applicationServices = LayerNode.group([
|
const applicationServices = LayerNode.group([
|
||||||
Database.node,
|
Database.node,
|
||||||
@@ -115,6 +117,10 @@ function makeRoutes<AuthError, AuthServices>(
|
|||||||
],
|
],
|
||||||
[PluginRuntime.node, PluginRuntime.layerWithCell(pluginRuntimeCell)],
|
[PluginRuntime.node, PluginRuntime.layerWithCell(pluginRuntimeCell)],
|
||||||
[PluginRuntime.providerNode, PluginRuntime.providerNodeWithCell(pluginRuntimeCell)],
|
[PluginRuntime.providerNode, PluginRuntime.providerNodeWithCell(pluginRuntimeCell)],
|
||||||
|
[
|
||||||
|
WorkspaceDriver.node,
|
||||||
|
WorkspaceDriver.registryNode({ [modalProvider]: modalWorkspaceDriver({ app: "opencode-workspaces" }) }),
|
||||||
|
],
|
||||||
]
|
]
|
||||||
const serviceLayer = options.simulation
|
const serviceLayer = options.simulation
|
||||||
? Layer.unwrap(
|
? Layer.unwrap(
|
||||||
|
|||||||
@@ -0,0 +1,128 @@
|
|||||||
|
import { WorkspaceDriver } from "@opencode-ai/core/workspace/driver"
|
||||||
|
import { Effect, Option, Schema } from "effect"
|
||||||
|
import type { App, Image, ModalClient, ModalClientParams, Sandbox } from "modal"
|
||||||
|
import { createModalSandboxWithClient, makeModalDriver, type ModalImageSpec, openModalClient } from "./modal"
|
||||||
|
|
||||||
|
export const provider = "modal"
|
||||||
|
|
||||||
|
export const ModalBinding = Schema.Struct({
|
||||||
|
sandboxId: Schema.optional(Schema.String),
|
||||||
|
snapshotImageId: Schema.optional(Schema.String),
|
||||||
|
})
|
||||||
|
export type ModalBinding = typeof ModalBinding.Type
|
||||||
|
|
||||||
|
export interface ModalWorkspaceOptions {
|
||||||
|
readonly app: string
|
||||||
|
readonly client?: ModalClientParams
|
||||||
|
readonly image?: ModalImageSpec
|
||||||
|
}
|
||||||
|
|
||||||
|
export const modalWorkspaceDriver = (options: ModalWorkspaceOptions): WorkspaceDriver.Interface => {
|
||||||
|
const decodeBinding = Schema.decodeUnknownOption(ModalBinding)
|
||||||
|
let clientPromise: Promise<ModalClient> | undefined
|
||||||
|
let appPromise: Promise<App> | undefined
|
||||||
|
// The SDK client and app handle are shared for the process lifetime of this driver.
|
||||||
|
const client = () => (clientPromise ??= openModalClient(options.client))
|
||||||
|
const app = () =>
|
||||||
|
(appPromise ??= client().then((value) => value.apps.fromName(options.app, { createIfMissing: true })))
|
||||||
|
|
||||||
|
const attempt = <A>(run: () => Promise<A>) =>
|
||||||
|
Effect.tryPromise({ try: run, catch: (cause) => new WorkspaceDriver.Error({ cause }) })
|
||||||
|
|
||||||
|
const binding = (value: WorkspaceDriver.Binding): ModalBinding => Option.getOrElse(decodeBinding(value), () => ({}))
|
||||||
|
|
||||||
|
const live = async (lookup: () => Promise<Sandbox>) => {
|
||||||
|
const { NotFoundError } = await import("modal")
|
||||||
|
const sandbox = await lookup().catch((error) => {
|
||||||
|
if (error instanceof NotFoundError) return undefined
|
||||||
|
throw error
|
||||||
|
})
|
||||||
|
if (sandbox && (await sandbox.poll()) === null) return sandbox
|
||||||
|
}
|
||||||
|
|
||||||
|
const findLive = async (modalClient: ModalClient, value: ModalBinding, workspaceID: string) => {
|
||||||
|
if (value.sandboxId) {
|
||||||
|
const sandboxID = value.sandboxId
|
||||||
|
const sandbox = await live(() => modalClient.sandboxes.fromId(sandboxID))
|
||||||
|
if (sandbox) return sandbox
|
||||||
|
}
|
||||||
|
// Name fallback is valid only before the first snapshot; afterward a live named sandbox is stale by design.
|
||||||
|
if (value.snapshotImageId) return
|
||||||
|
return live(() => modalClient.sandboxes.fromName(options.app, workspaceID))
|
||||||
|
}
|
||||||
|
|
||||||
|
const createSandbox = async (workspaceID: string, image?: Image) => {
|
||||||
|
const { AlreadyExistsError } = await import("modal")
|
||||||
|
const modalClient = await client()
|
||||||
|
return createModalSandboxWithClient(
|
||||||
|
modalClient,
|
||||||
|
await app(),
|
||||||
|
{
|
||||||
|
image: options.image,
|
||||||
|
sandbox: {
|
||||||
|
name: workspaceID,
|
||||||
|
tags: { workspace: workspaceID },
|
||||||
|
timeoutMs: 24 * 60 * 60 * 1000,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
image,
|
||||||
|
).catch((error) => {
|
||||||
|
if (error instanceof AlreadyExistsError) return modalClient.sandboxes.fromName(options.app, workspaceID)
|
||||||
|
throw error
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
const deleteImage = (modalClient: ModalClient, imageID?: string) =>
|
||||||
|
imageID ? attempt(() => modalClient.images.delete(imageID)).pipe(Effect.ignore) : Effect.void
|
||||||
|
|
||||||
|
const terminate = (sandbox?: Sandbox) =>
|
||||||
|
sandbox ? attempt(() => sandbox.terminate({ wait: true })).pipe(Effect.ignore) : Effect.void
|
||||||
|
|
||||||
|
return WorkspaceDriver.make({
|
||||||
|
create: ({ workspaceID }) =>
|
||||||
|
attempt(async () => {
|
||||||
|
const sandbox = await createSandbox(workspaceID)
|
||||||
|
return { binding: { sandboxId: sandbox.sandboxId } }
|
||||||
|
}),
|
||||||
|
connect: ({ workspaceID, binding: value, saveBinding }) =>
|
||||||
|
Effect.gen(function* () {
|
||||||
|
const modalBinding = binding(value)
|
||||||
|
const modalClient = yield* attempt(client)
|
||||||
|
const sandbox = yield* attempt(async () => {
|
||||||
|
const existing = await findLive(modalClient, modalBinding, workspaceID)
|
||||||
|
const image =
|
||||||
|
existing || !modalBinding.snapshotImageId
|
||||||
|
? undefined
|
||||||
|
: await modalClient.images.fromId(modalBinding.snapshotImageId)
|
||||||
|
return existing ?? createSandbox(workspaceID, image)
|
||||||
|
})
|
||||||
|
if (modalBinding.sandboxId !== sandbox.sandboxId) {
|
||||||
|
yield* saveBinding({ ...modalBinding, sandboxId: sandbox.sandboxId })
|
||||||
|
}
|
||||||
|
return makeModalDriver(sandbox)
|
||||||
|
}),
|
||||||
|
suspendForIdle: ({ workspaceID, binding: value, saveBinding }) =>
|
||||||
|
Effect.gen(function* () {
|
||||||
|
const modalBinding = binding(value)
|
||||||
|
const modalClient = yield* attempt(client)
|
||||||
|
const sandbox = yield* attempt(() => findLive(modalClient, modalBinding, workspaceID))
|
||||||
|
if (!sandbox) return
|
||||||
|
const snapshot = yield* attempt(() => sandbox.snapshotFilesystem({ ttlMs: null }))
|
||||||
|
yield* saveBinding({ snapshotImageId: snapshot.imageId })
|
||||||
|
yield* Effect.all([deleteImage(modalClient, modalBinding.snapshotImageId), terminate(sandbox)], {
|
||||||
|
concurrency: "unbounded",
|
||||||
|
discard: true,
|
||||||
|
})
|
||||||
|
}),
|
||||||
|
destroy: ({ workspaceID, binding: value }) =>
|
||||||
|
Effect.gen(function* () {
|
||||||
|
const modalBinding = binding(value)
|
||||||
|
const modalClient = yield* attempt(client)
|
||||||
|
const sandbox = yield* attempt(() => findLive(modalClient, modalBinding, workspaceID))
|
||||||
|
yield* Effect.all([terminate(sandbox), deleteImage(modalClient, modalBinding.snapshotImageId)], {
|
||||||
|
concurrency: "unbounded",
|
||||||
|
discard: true,
|
||||||
|
})
|
||||||
|
}),
|
||||||
|
})
|
||||||
|
}
|
||||||
@@ -3,7 +3,7 @@ import { systemError } from "effect/PlatformError"
|
|||||||
import type { Command, KillOptions } from "effect/unstable/process/ChildProcess"
|
import type { Command, KillOptions } from "effect/unstable/process/ChildProcess"
|
||||||
import { ExitCode, make, makeHandle, ProcessId } from "effect/unstable/process/ChildProcessSpawner"
|
import { ExitCode, make, makeHandle, ProcessId } from "effect/unstable/process/ChildProcessSpawner"
|
||||||
import type { Driver } from "@opencode-ai/core/environment"
|
import type { Driver } from "@opencode-ai/core/environment"
|
||||||
import type { ModalClientParams, Sandbox, SandboxCreateParams } from "modal"
|
import type { App, Image, ModalClient, ModalClientParams, Sandbox, SandboxCreateParams } from "modal"
|
||||||
|
|
||||||
const INNER_WRAPPER = `
|
const INNER_WRAPPER = `
|
||||||
pidfile=$1
|
pidfile=$1
|
||||||
@@ -44,13 +44,16 @@ export interface ModalImageSpec {
|
|||||||
readonly dockerfileCommands: ReadonlyArray<string>
|
readonly dockerfileCommands: ReadonlyArray<string>
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface ModalSandboxOptions {
|
export interface ModalSandboxCreateOptions {
|
||||||
readonly app: string
|
|
||||||
readonly client?: ModalClientParams
|
|
||||||
readonly image?: ModalImageSpec
|
readonly image?: ModalImageSpec
|
||||||
readonly sandbox?: SandboxCreateParams
|
readonly sandbox?: SandboxCreateParams
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export interface ModalSandboxOptions extends ModalSandboxCreateOptions {
|
||||||
|
readonly app: string
|
||||||
|
readonly client?: ModalClientParams
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Ubuntu supplies the GNU coreutils and findutils required by the derived Files
|
* Ubuntu supplies the GNU coreutils and findutils required by the derived Files
|
||||||
* scripts. Busybox images do not satisfy the Environment contract.
|
* scripts. Busybox images do not satisfy the Environment contract.
|
||||||
@@ -64,19 +67,11 @@ export const ubuntuImage: ModalImageSpec = {
|
|||||||
|
|
||||||
/** Creates a Modal sandbox lazily, keeping the SDK off the server startup path when Modal is unused. */
|
/** Creates a Modal sandbox lazily, keeping the SDK off the server startup path when Modal is unused. */
|
||||||
export const createModalSandbox = async (options: ModalSandboxOptions) => {
|
export const createModalSandbox = async (options: ModalSandboxOptions) => {
|
||||||
const { ModalClient } = await import("modal")
|
const client = await openModalClient(options.client)
|
||||||
const client = new ModalClient(options.client)
|
|
||||||
const app = await client.apps.fromName(options.app, { createIfMissing: true })
|
const app = await client.apps.fromName(options.app, { createIfMissing: true })
|
||||||
const imageSpec = options.image ?? ubuntuImage
|
const sandbox = await createModalSandboxWithClient(client, app, {
|
||||||
const image = client.images.fromRegistry(imageSpec.registry).dockerfileCommands([...imageSpec.dockerfileCommands])
|
image: options.image,
|
||||||
// Always Modal's Full-VM runtime (beta, enabled per account): a real kernel
|
sandbox: options.sandbox,
|
||||||
// with real device nodes, so workspaces can run Docker and other
|
|
||||||
// kernel-dependent workloads. Costs versus gVisor, measured Aug 2026:
|
|
||||||
// per-exec floor ~285-535ms versus ~90-165ms, and filesystem snapshots only
|
|
||||||
// (no memory snapshots — acceptable; fs-snapshot is the persistence design).
|
|
||||||
const sandbox = await client.sandboxes.create(app, image, {
|
|
||||||
...options.sandbox,
|
|
||||||
experimentalOptions: { ...options.sandbox?.experimentalOptions, vm_runtime: true },
|
|
||||||
})
|
})
|
||||||
return {
|
return {
|
||||||
driver: makeModalDriver(sandbox),
|
driver: makeModalDriver(sandbox),
|
||||||
@@ -85,6 +80,32 @@ export const createModalSandbox = async (options: ModalSandboxOptions) => {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export const openModalClient = async (params?: ModalClientParams) => {
|
||||||
|
const { ModalClient } = await import("modal")
|
||||||
|
return new ModalClient(params)
|
||||||
|
}
|
||||||
|
|
||||||
|
export const createModalSandboxWithClient = async (
|
||||||
|
client: ModalClient,
|
||||||
|
app: App,
|
||||||
|
options: ModalSandboxCreateOptions,
|
||||||
|
existingImage?: Image,
|
||||||
|
) => {
|
||||||
|
const imageSpec = options.image ?? ubuntuImage
|
||||||
|
const image =
|
||||||
|
existingImage ??
|
||||||
|
client.images.fromRegistry(imageSpec.registry).dockerfileCommands([...imageSpec.dockerfileCommands])
|
||||||
|
// Always Modal's Full-VM runtime (beta, enabled per account): a real kernel
|
||||||
|
// with real device nodes, so workspaces can run Docker and other
|
||||||
|
// kernel-dependent workloads. Costs versus gVisor, measured Aug 2026:
|
||||||
|
// per-exec floor ~285-535ms versus ~90-165ms, and filesystem snapshots only
|
||||||
|
// (no memory snapshots — acceptable; fs-snapshot is the persistence design).
|
||||||
|
return client.sandboxes.create(app, image, {
|
||||||
|
...options.sandbox,
|
||||||
|
experimentalOptions: { ...options.sandbox?.experimentalOptions, vm_runtime: true },
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Adapts Modal exec to the Environment driver. Files intentionally has no native
|
* Adapts Modal exec to the Environment driver. Files intentionally has no native
|
||||||
* overrides: exec latency dominates payload work (VM runtime floor measured
|
* overrides: exec latency dominates payload work (VM runtime floor measured
|
||||||
|
|||||||
@@ -0,0 +1,54 @@
|
|||||||
|
import fs from "node:fs"
|
||||||
|
import os from "node:os"
|
||||||
|
import path from "node:path"
|
||||||
|
import { expect, test } from "bun:test"
|
||||||
|
import { AppNodeBuilder } from "@opencode-ai/core/effect/app-node-builder"
|
||||||
|
import { makeFiles } from "@opencode-ai/core/environment"
|
||||||
|
import { Workspace } from "@opencode-ai/core/workspace"
|
||||||
|
import { WorkspaceDriver } from "@opencode-ai/core/workspace/driver"
|
||||||
|
import { Effect, Layer } from "effect"
|
||||||
|
import { TestClock } from "effect/testing"
|
||||||
|
import { modalWorkspaceDriver, provider } from "../src/workspace/modal-workspace"
|
||||||
|
|
||||||
|
const enabled =
|
||||||
|
!!process.env.OPENCODE_TEST_MODAL &&
|
||||||
|
((!!process.env.MODAL_TOKEN_ID && !!process.env.MODAL_TOKEN_SECRET) ||
|
||||||
|
fs.existsSync(path.join(os.homedir(), ".modal.toml")))
|
||||||
|
|
||||||
|
const testLayer = Layer.provideMerge(
|
||||||
|
AppNodeBuilder.build(Workspace.configured({ idleThreshold: "1 minute", pollInterval: "1 minute" }), [
|
||||||
|
[
|
||||||
|
WorkspaceDriver.node,
|
||||||
|
WorkspaceDriver.registryNode({ [provider]: modalWorkspaceDriver({ app: "opencode-workspace-tests" }) }),
|
||||||
|
],
|
||||||
|
]),
|
||||||
|
TestClock.layer(),
|
||||||
|
)
|
||||||
|
const modalTest = enabled ? test : test.skip
|
||||||
|
|
||||||
|
modalTest(
|
||||||
|
"wakes a workspace from its filesystem snapshot",
|
||||||
|
() =>
|
||||||
|
Effect.runPromise(
|
||||||
|
Effect.gen(function* () {
|
||||||
|
const workspace = yield* Workspace.Service
|
||||||
|
yield* Effect.acquireUseRelease(
|
||||||
|
workspace.create(provider),
|
||||||
|
(created) =>
|
||||||
|
Effect.gen(function* () {
|
||||||
|
const environment = yield* workspace.connect(created.id)
|
||||||
|
const files = makeFiles(environment)
|
||||||
|
const file = `/tmp/opencode-workspace-${crypto.randomUUID()}.txt`
|
||||||
|
yield* files.write(file, new TextEncoder().encode("survived snapshot"))
|
||||||
|
|
||||||
|
yield* TestClock.adjust("2 minutes")
|
||||||
|
|
||||||
|
const restored = yield* files.read(file)
|
||||||
|
expect(new TextDecoder().decode(restored.bytes)).toBe("survived snapshot")
|
||||||
|
}),
|
||||||
|
(created) => workspace.destroy(created.id).pipe(Effect.ignore),
|
||||||
|
)
|
||||||
|
}).pipe(Effect.scoped, Effect.provide(testLayer)),
|
||||||
|
),
|
||||||
|
180_000,
|
||||||
|
)
|
||||||
@@ -12,6 +12,7 @@ export function generateSyntax(theme: ResolvedThemeTokens, mode: Mode) {
|
|||||||
rule(["prompt"], theme.hue.accent[step]),
|
rule(["prompt"], theme.hue.accent[step]),
|
||||||
rule(["extmark.file"], feedback.warning.default, { bold: true }),
|
rule(["extmark.file"], feedback.warning.default, { bold: true }),
|
||||||
rule(["extmark.agent"], theme.categorical[0][step], { bold: true }),
|
rule(["extmark.agent"], theme.categorical[0][step], { bold: true }),
|
||||||
|
rule(["extmark.skill"], theme.categorical[1][step], { bold: true }),
|
||||||
// V1 migration preserves its selected/inverse foreground in this action state.
|
// V1 migration preserves its selected/inverse foreground in this action state.
|
||||||
rule(["extmark.paste"], theme.text.action.primary.focused, {
|
rule(["extmark.paste"], theme.text.action.primary.focused, {
|
||||||
background: feedback.warning.default,
|
background: feedback.warning.default,
|
||||||
|
|||||||
@@ -118,6 +118,7 @@ const sessionTabBindingCommands = [
|
|||||||
"session.tab.select.7",
|
"session.tab.select.7",
|
||||||
"session.tab.select.8",
|
"session.tab.select.8",
|
||||||
"session.tab.select.9",
|
"session.tab.select.9",
|
||||||
|
"session.tab.select.10",
|
||||||
] as const
|
] as const
|
||||||
|
|
||||||
const pinnedSessionBindingCommands = [
|
const pinnedSessionBindingCommands = [
|
||||||
@@ -714,7 +715,7 @@ function App(props: { pair?: DialogPairCredentials }) {
|
|||||||
enabled: sessionTabs.enabled,
|
enabled: sessionTabs.enabled,
|
||||||
run: () => sessionTabs.reopen(),
|
run: () => sessionTabs.reopen(),
|
||||||
},
|
},
|
||||||
...Array.from({ length: 9 }, (_, i) => ({
|
...Array.from({ length: 10 }, (_, i) => ({
|
||||||
name: `session.tab.select.${i + 1}`,
|
name: `session.tab.select.${i + 1}`,
|
||||||
title: `Switch to tab ${i + 1}`,
|
title: `Switch to tab ${i + 1}`,
|
||||||
category: "Session",
|
category: "Session",
|
||||||
|
|||||||
@@ -5,6 +5,10 @@ import type {
|
|||||||
IntegrationInfo,
|
IntegrationInfo,
|
||||||
IntegrationOauthConnectOutput,
|
IntegrationOauthConnectOutput,
|
||||||
IntegrationOAuthMethod,
|
IntegrationOAuthMethod,
|
||||||
|
FormAnswer,
|
||||||
|
FormField,
|
||||||
|
FormFields,
|
||||||
|
FormValue,
|
||||||
} 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 +22,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 { formLabel, formToggleMultiselect, formValidateValue, type FormAnswerField } from "../util/form"
|
||||||
|
|
||||||
const INTEGRATION_PRIORITY: Record<string, number> = {
|
const INTEGRATION_PRIORITY: Record<string, number> = {
|
||||||
opencode: 0,
|
opencode: 0,
|
||||||
@@ -32,6 +37,10 @@ type ConnectMethod = Exclude<IntegrationInfo["methods"][number], { type: "env" }
|
|||||||
type IntegrationAttempt = IntegrationOauthConnectOutput["data"]
|
type IntegrationAttempt = IntegrationOauthConnectOutput["data"]
|
||||||
type CommandAttempt = IntegrationCommandConnectOutput["data"]
|
type CommandAttempt = IntegrationCommandConnectOutput["data"]
|
||||||
type OnIntegrationConnected = (providerID?: string) => void
|
type OnIntegrationConnected = (providerID?: string) => void
|
||||||
|
const CANCELLED = Symbol("cancelled")
|
||||||
|
const CUSTOM = Symbol("custom")
|
||||||
|
const OPEN = Symbol("open")
|
||||||
|
const SUBMIT = Symbol("submit")
|
||||||
|
|
||||||
export function integrationOptions(list: IntegrationInfo[]) {
|
export function integrationOptions(list: IntegrationInfo[]) {
|
||||||
return list.toSorted(
|
return list.toSorted(
|
||||||
@@ -181,7 +190,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 +200,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 answer = method.form
|
||||||
|
? await formAnswer(dialog, method.label ?? `Connect ${integration.name}`, method.form)
|
||||||
|
: undefined
|
||||||
|
if (answer === null) return
|
||||||
|
dialog.replace(() => (
|
||||||
|
<KeyMethod integration={integration} method={method} answer={answer} onConnected={onConnected} />
|
||||||
|
))
|
||||||
|
}
|
||||||
|
|
||||||
function CommandStarting(props: {
|
function CommandStarting(props: {
|
||||||
integration: IntegrationInfo
|
integration: IntegrationInfo
|
||||||
method: Extract<ConnectMethod, { type: "command" }>
|
method: Extract<ConnectMethod, { type: "command" }>
|
||||||
@@ -336,6 +360,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" }>
|
||||||
|
answer?: FormAnswer
|
||||||
onConnected?: OnIntegrationConnected
|
onConnected?: OnIntegrationConnected
|
||||||
}) {
|
}) {
|
||||||
const data = useData()
|
const data = useData()
|
||||||
@@ -356,6 +381,7 @@ function KeyMethod(props: {
|
|||||||
integrationID: props.integration.id,
|
integrationID: props.integration.id,
|
||||||
location: location(data),
|
location: location(data),
|
||||||
key,
|
key,
|
||||||
|
...(props.answer ? { answer: props.answer } : {}),
|
||||||
})
|
})
|
||||||
.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 +399,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 answer = method.form ? await formAnswer(dialog, method.label, method.form) : undefined
|
||||||
if (inputs === null) return
|
if (answer === null) return
|
||||||
dialog.replace(() => (
|
dialog.replace(() => (
|
||||||
<OAuthStarting integration={integration} method={method} inputs={inputs} onConnected={onConnected} />
|
<OAuthStarting integration={integration} method={method} answer={answer} onConnected={onConnected} />
|
||||||
))
|
))
|
||||||
}
|
}
|
||||||
|
|
||||||
function OAuthStarting(props: {
|
function OAuthStarting(props: {
|
||||||
integration: IntegrationInfo
|
integration: IntegrationInfo
|
||||||
method: IntegrationOAuthMethod
|
method: IntegrationOAuthMethod
|
||||||
inputs: Record<string, string>
|
answer?: FormAnswer
|
||||||
onConnected?: OnIntegrationConnected
|
onConnected?: OnIntegrationConnected
|
||||||
}) {
|
}) {
|
||||||
const data = useData()
|
const data = useData()
|
||||||
@@ -397,7 +423,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,
|
...(props.answer ? { answer: props.answer } : {}),
|
||||||
})
|
})
|
||||||
.then((result) => {
|
.then((result) => {
|
||||||
if (result.data.mode === "code") {
|
if (result.data.mode === "code") {
|
||||||
@@ -621,49 +647,234 @@ function OAuthView(props: {
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
async function promptInputs(
|
async function formAnswer(dialog: ReturnType<typeof useDialog>, title: string, fields: FormFields) {
|
||||||
dialog: ReturnType<typeof useDialog>,
|
const answer: FormAnswer = {}
|
||||||
prompts: NonNullable<IntegrationOAuthMethod["prompts"]>,
|
for (const field of fields) {
|
||||||
) {
|
if (!active(field, answer)) continue
|
||||||
const inputs: Record<string, string> = {}
|
const value = await fieldAnswer(dialog, title, field)
|
||||||
for (const prompt of prompts) {
|
if (value === CANCELLED) return null
|
||||||
if (prompt.when) {
|
if (value !== undefined) answer[field.key] = value
|
||||||
const value = inputs[prompt.when.key]
|
|
||||||
if (value === undefined) continue
|
|
||||||
const matches = prompt.when.op === "eq" ? value === prompt.when.value : value !== prompt.when.value
|
|
||||||
if (!matches) continue
|
|
||||||
}
|
}
|
||||||
if (prompt.type === "select") {
|
return answer
|
||||||
const value = await new Promise<string | null>((resolve) => {
|
}
|
||||||
|
|
||||||
|
function active(field: FormField, answer: FormAnswer) {
|
||||||
|
if (field.type === "external" || !field.when) return true
|
||||||
|
return field.when.every((when) => {
|
||||||
|
const value = answer[when.key]
|
||||||
|
if (value === undefined) return false
|
||||||
|
const hit = Array.isArray(value) ? value.includes(String(when.value)) : value === when.value
|
||||||
|
return when.op === "eq" ? hit : !hit
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
function fieldAnswer(
|
||||||
|
dialog: ReturnType<typeof useDialog>,
|
||||||
|
title: string,
|
||||||
|
field: FormField,
|
||||||
|
): Promise<FormValue | undefined | typeof CANCELLED> {
|
||||||
|
if (field.type === "external") return externalAnswer(dialog, title, field)
|
||||||
|
if (field.type === "multiselect") return multiselectAnswer(dialog, title, field)
|
||||||
|
if (field.type === "boolean" || (field.type === "string" && field.options)) {
|
||||||
|
return selectAnswer(dialog, title, field)
|
||||||
|
}
|
||||||
|
return textAnswer(dialog, title, field)
|
||||||
|
}
|
||||||
|
|
||||||
|
async function selectAnswer(
|
||||||
|
dialog: ReturnType<typeof useDialog>,
|
||||||
|
title: string,
|
||||||
|
field: Extract<FormAnswerField, { type: "boolean" | "string" }>,
|
||||||
|
): Promise<FormValue | undefined | typeof CANCELLED> {
|
||||||
|
const options =
|
||||||
|
field.type === "boolean"
|
||||||
|
? field.default === false
|
||||||
|
? [
|
||||||
|
{ title: "No", value: false as FormValue },
|
||||||
|
{ title: "Yes", value: true as FormValue },
|
||||||
|
]
|
||||||
|
: [
|
||||||
|
{ title: "Yes", value: true as FormValue },
|
||||||
|
{ title: "No", value: false as FormValue },
|
||||||
|
]
|
||||||
|
: (field.options ?? []).map((option) => ({
|
||||||
|
title: option.label,
|
||||||
|
value: option.value as FormValue,
|
||||||
|
description: option.description,
|
||||||
|
}))
|
||||||
|
const choice = await new Promise<FormValue | typeof CUSTOM | undefined | typeof CANCELLED>((resolve) => {
|
||||||
dialog.replace(
|
dialog.replace(
|
||||||
() => (
|
() => (
|
||||||
<DialogSelect
|
<DialogSelect<FormValue | typeof CUSTOM | undefined>
|
||||||
title={prompt.message}
|
title={formLabel(field) || title}
|
||||||
options={prompt.options.map((option) => ({
|
options={[
|
||||||
title: option.label,
|
...options,
|
||||||
value: option.value,
|
...(field.type === "string" && field.custom
|
||||||
description: option.hint,
|
? [{ title: "Type your own answer", value: CUSTOM as typeof CUSTOM }]
|
||||||
}))}
|
: []),
|
||||||
|
...(!field.required ? [{ title: "Skip", value: undefined }] : []),
|
||||||
|
]}
|
||||||
|
current={field.type === "string" ? field.default : undefined}
|
||||||
onSelect={(option) => resolve(option.value)}
|
onSelect={(option) => resolve(option.value)}
|
||||||
/>
|
/>
|
||||||
),
|
),
|
||||||
() => resolve(null),
|
() => resolve(CANCELLED),
|
||||||
)
|
)
|
||||||
})
|
})
|
||||||
if (value === null) return null
|
if (choice === CUSTOM) {
|
||||||
inputs[prompt.key] = value
|
if (field.type !== "string") return CANCELLED
|
||||||
|
return textAnswer(dialog, title, field, "")
|
||||||
|
}
|
||||||
|
return choice
|
||||||
|
}
|
||||||
|
|
||||||
|
function textAnswer(
|
||||||
|
dialog: ReturnType<typeof useDialog>,
|
||||||
|
title: string,
|
||||||
|
field: Extract<FormAnswerField, { type: "string" | "number" | "integer" }>,
|
||||||
|
initial = field.default === undefined ? undefined : String(field.default),
|
||||||
|
): Promise<FormValue | undefined | typeof CANCELLED> {
|
||||||
|
return new Promise<FormValue | undefined | typeof CANCELLED>((resolve) => {
|
||||||
|
dialog.replace(
|
||||||
|
() => {
|
||||||
|
const theme = useTheme("elevated")
|
||||||
|
const [error, setError] = createSignal<string>()
|
||||||
|
return (
|
||||||
|
<DialogPrompt
|
||||||
|
title={formLabel(field) || title}
|
||||||
|
placeholder={field.type === "string" ? field.placeholder : undefined}
|
||||||
|
value={initial}
|
||||||
|
onConfirm={(input) => {
|
||||||
|
const text = input.trim()
|
||||||
|
const value = text === "" && !field.required ? undefined : field.type === "string" ? text : Number(text)
|
||||||
|
const invalid = formValidateValue(field, value)
|
||||||
|
if (invalid) {
|
||||||
|
setError(invalid)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
resolve(value)
|
||||||
|
}}
|
||||||
|
description={() => (
|
||||||
|
<box gap={1}>
|
||||||
|
<Show when={field.description}>
|
||||||
|
{(description) => <text fg={theme.text.subdued}>{description()}</text>}
|
||||||
|
</Show>
|
||||||
|
<Show when={error()}>{(value) => <text fg={theme.text.feedback.error.default}>{value()}</text>}</Show>
|
||||||
|
</box>
|
||||||
|
)}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
},
|
||||||
|
() => resolve(CANCELLED),
|
||||||
|
)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
async function multiselectAnswer(
|
||||||
|
dialog: ReturnType<typeof useDialog>,
|
||||||
|
title: string,
|
||||||
|
field: Extract<FormAnswerField, { type: "multiselect" }>,
|
||||||
|
): Promise<FormValue | typeof CANCELLED> {
|
||||||
|
const selected = field.default ? [...field.default] : []
|
||||||
|
while (true) {
|
||||||
|
const invalid = formValidateValue(field, selected)
|
||||||
|
const choice = await new Promise<string | typeof CUSTOM | typeof SUBMIT | typeof CANCELLED>((resolve) => {
|
||||||
|
dialog.replace(
|
||||||
|
() => (
|
||||||
|
<DialogSelect<string | typeof CUSTOM | typeof SUBMIT>
|
||||||
|
title={formLabel(field) || title}
|
||||||
|
options={[
|
||||||
|
...field.options.map((option) => ({
|
||||||
|
title: `[${selected.includes(option.value) ? "x" : " "}] ${option.label}`,
|
||||||
|
value: option.value,
|
||||||
|
description: option.description,
|
||||||
|
disabled:
|
||||||
|
!selected.includes(option.value) && field.maxItems !== undefined && selected.length >= field.maxItems,
|
||||||
|
})),
|
||||||
|
...(field.custom ? [{ title: "Type your own answer", value: CUSTOM as typeof CUSTOM }] : []),
|
||||||
|
{
|
||||||
|
title: "Continue",
|
||||||
|
value: SUBMIT as typeof SUBMIT,
|
||||||
|
description: invalid,
|
||||||
|
disabled: invalid !== undefined,
|
||||||
|
},
|
||||||
|
]}
|
||||||
|
onSelect={(option) => resolve(option.value)}
|
||||||
|
/>
|
||||||
|
),
|
||||||
|
() => resolve(CANCELLED),
|
||||||
|
)
|
||||||
|
})
|
||||||
|
if (choice === CANCELLED) return CANCELLED
|
||||||
|
if (choice === SUBMIT) return selected
|
||||||
|
if (choice === CUSTOM) {
|
||||||
|
const value = await customAnswer(dialog, title, field)
|
||||||
|
if (value === CANCELLED) return CANCELLED
|
||||||
|
if (value && !selected.includes(value)) selected.push(value)
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
const value = await new Promise<string | null>((resolve) => {
|
selected.splice(0, selected.length, ...formToggleMultiselect(selected, choice))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function customAnswer(
|
||||||
|
dialog: ReturnType<typeof useDialog>,
|
||||||
|
title: string,
|
||||||
|
field: Extract<FormAnswerField, { type: "multiselect" }>,
|
||||||
|
): Promise<string | typeof CANCELLED> {
|
||||||
|
return new Promise<string | typeof CANCELLED>((resolve) => {
|
||||||
dialog.replace(
|
dialog.replace(
|
||||||
() => <DialogPrompt title={prompt.message} placeholder={prompt.placeholder} onConfirm={resolve} />,
|
() => (
|
||||||
() => resolve(null),
|
<DialogPrompt
|
||||||
|
title={formLabel(field) || title}
|
||||||
|
placeholder="Type your own answer"
|
||||||
|
onConfirm={(value) => {
|
||||||
|
if (value) resolve(value)
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
),
|
||||||
|
() => resolve(CANCELLED),
|
||||||
)
|
)
|
||||||
})
|
})
|
||||||
if (value === null) return null
|
|
||||||
inputs[prompt.key] = value
|
|
||||||
}
|
}
|
||||||
return inputs
|
|
||||||
|
async function externalAnswer(
|
||||||
|
dialog: ReturnType<typeof useDialog>,
|
||||||
|
title: string,
|
||||||
|
field: Extract<FormField, { type: "external" }>,
|
||||||
|
): Promise<true | typeof CANCELLED> {
|
||||||
|
let opened = false
|
||||||
|
while (true) {
|
||||||
|
const choice = await new Promise<true | typeof OPEN | typeof CANCELLED>((resolve) => {
|
||||||
|
dialog.replace(
|
||||||
|
() => (
|
||||||
|
<DialogSelect<true | typeof OPEN>
|
||||||
|
title={formLabel(field) || title}
|
||||||
|
options={[
|
||||||
|
{ title: opened ? "Open link again" : "Open link", value: OPEN as typeof OPEN, description: field.url },
|
||||||
|
{ title: "I finished", value: true as const, description: field.description, disabled: !opened },
|
||||||
|
]}
|
||||||
|
onSelect={(option) => resolve(option.value)}
|
||||||
|
/>
|
||||||
|
),
|
||||||
|
() => resolve(CANCELLED),
|
||||||
|
)
|
||||||
|
})
|
||||||
|
if (choice === CANCELLED) return CANCELLED
|
||||||
|
if (choice === true) return true
|
||||||
|
const result = await new Promise<boolean | typeof CANCELLED>((resolve) => {
|
||||||
|
dialog.replace(
|
||||||
|
() => <OAuthView title={formLabel(field) || title} message="Opening link..." />,
|
||||||
|
() => resolve(CANCELLED),
|
||||||
|
)
|
||||||
|
void open(field.url).then(
|
||||||
|
() => resolve(true),
|
||||||
|
() => resolve(false),
|
||||||
|
)
|
||||||
|
})
|
||||||
|
if (result === CANCELLED) return CANCELLED
|
||||||
|
opened ||= result
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async function connected(
|
async function connected(
|
||||||
|
|||||||
@@ -19,8 +19,9 @@ import { Locale } from "../../util/locale"
|
|||||||
import type { PromptInfo, PromptPartRef } from "../../prompt/history"
|
import type { PromptInfo, PromptPartRef } from "../../prompt/history"
|
||||||
import { useFrecency } from "../../prompt/frecency"
|
import { useFrecency } from "../../prompt/frecency"
|
||||||
import { Keymap } from "../../context/keymap"
|
import { Keymap } from "../../context/keymap"
|
||||||
import { displayCharAt, mentionTriggerIndex } from "../../prompt/display"
|
import { displayCharAt, mentionTriggerIndex, slashTriggerIndex } from "../../prompt/display"
|
||||||
import type { FileSystemEntry } from "@opencode-ai/client"
|
import type { FileSystemEntry } from "@opencode-ai/client"
|
||||||
|
import { Skill } from "@opencode-ai/schema/skill"
|
||||||
import { stringWidth } from "../../util/string-width"
|
import { stringWidth } from "../../util/string-width"
|
||||||
import { parseFileLineRange, stripFileLineRange } from "../../prompt/parse"
|
import { parseFileLineRange, stripFileLineRange } from "../../prompt/parse"
|
||||||
import { moveSelection, revealSelectionOffset } from "../../ui/select-controller"
|
import { moveSelection, revealSelectionOffset } from "../../ui/select-controller"
|
||||||
@@ -39,6 +40,7 @@ export type AutocompleteOption = {
|
|||||||
isDirectory?: boolean
|
isDirectory?: boolean
|
||||||
onSelect?: () => void
|
onSelect?: () => void
|
||||||
path?: string
|
path?: string
|
||||||
|
kind?: "skill"
|
||||||
}
|
}
|
||||||
|
|
||||||
export function Autocomplete(props: {
|
export function Autocomplete(props: {
|
||||||
@@ -51,6 +53,8 @@ export function Autocomplete(props: {
|
|||||||
ref: (ref: AutocompleteRef) => void
|
ref: (ref: AutocompleteRef) => void
|
||||||
fileStyleId: number
|
fileStyleId: number
|
||||||
agentStyleId: number
|
agentStyleId: number
|
||||||
|
skillStyleId: number
|
||||||
|
hasSkill: (id: string) => boolean
|
||||||
promptPartTypeId: () => number
|
promptPartTypeId: () => number
|
||||||
}) {
|
}) {
|
||||||
const editor = useEditorContext()
|
const editor = useEditorContext()
|
||||||
@@ -140,14 +144,17 @@ export function Autocomplete(props: {
|
|||||||
text: string,
|
text: string,
|
||||||
part:
|
part:
|
||||||
| { type: "file"; value: NonNullable<PromptInfo["files"]>[number]; path?: string }
|
| { type: "file"; value: NonNullable<PromptInfo["files"]>[number]; path?: string }
|
||||||
| { type: "agent"; value: NonNullable<PromptInfo["agents"]>[number] },
|
| { type: "agent"; value: NonNullable<PromptInfo["agents"]>[number] }
|
||||||
|
| { type: "skill"; value: NonNullable<PromptInfo["skills"]>[number] },
|
||||||
) {
|
) {
|
||||||
|
if (part.type === "skill" && props.hasSkill(part.value.id)) return
|
||||||
const input = props.input()
|
const input = props.input()
|
||||||
const currentCursorOffset = input.cursorOffset
|
const currentCursorOffset = input.cursorOffset
|
||||||
|
|
||||||
const charAfterCursor = displayCharAt(props.value, currentCursorOffset)
|
const charAfterCursor = displayCharAt(props.value, currentCursorOffset)
|
||||||
const needsSpace = charAfterCursor !== " "
|
const needsSpace = charAfterCursor !== " "
|
||||||
const append = "@" + text + (needsSpace ? " " : "")
|
const prefix = part.type === "skill" ? "/" : "@"
|
||||||
|
const append = prefix + text + (needsSpace ? " " : "")
|
||||||
|
|
||||||
input.cursorOffset = store.index
|
input.cursorOffset = store.index
|
||||||
const startCursor = input.logicalCursor
|
const startCursor = input.logicalCursor
|
||||||
@@ -157,11 +164,12 @@ export function Autocomplete(props: {
|
|||||||
input.deleteRange(startCursor.row, startCursor.col, endCursor.row, endCursor.col)
|
input.deleteRange(startCursor.row, startCursor.col, endCursor.row, endCursor.col)
|
||||||
input.insertText(append)
|
input.insertText(append)
|
||||||
|
|
||||||
const virtualText = "@" + text
|
const virtualText = prefix + text
|
||||||
const extmarkStart = store.index
|
const extmarkStart = store.index
|
||||||
const extmarkEnd = extmarkStart + stringWidth(virtualText)
|
const extmarkEnd = extmarkStart + stringWidth(virtualText)
|
||||||
|
|
||||||
const styleId = part.type === "file" ? props.fileStyleId : props.agentStyleId
|
const styleId =
|
||||||
|
part.type === "file" ? props.fileStyleId : part.type === "skill" ? props.skillStyleId : props.agentStyleId
|
||||||
|
|
||||||
const extmarkId = input.extmarks.create({
|
const extmarkId = input.extmarks.create({
|
||||||
start: extmarkStart,
|
start: extmarkStart,
|
||||||
@@ -195,6 +203,20 @@ export function Autocomplete(props: {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (part.type === "skill") {
|
||||||
|
const skills = (draft.skills ??= [])
|
||||||
|
if (skills.some((skill) => skill.id === part.value.id)) return
|
||||||
|
if (part.value.mention) {
|
||||||
|
part.value.mention.start = extmarkStart
|
||||||
|
part.value.mention.end = extmarkEnd
|
||||||
|
part.value.mention.text = virtualText
|
||||||
|
}
|
||||||
|
const index = skills.length
|
||||||
|
skills.push(part.value)
|
||||||
|
props.setExtmark({ type: "skill", index }, extmarkId)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
const agents = (draft.agents ??= [])
|
const agents = (draft.agents ??= [])
|
||||||
if (part.value.mention) {
|
if (part.value.mention) {
|
||||||
part.value.mention.start = extmarkStart
|
part.value.mention.start = extmarkStart
|
||||||
@@ -433,7 +455,12 @@ export function Autocomplete(props: {
|
|||||||
results.push({
|
results.push({
|
||||||
display: "/" + skill.id,
|
display: "/" + skill.id,
|
||||||
description: skill.description,
|
description: skill.description,
|
||||||
onSelect: () => insertSlash(skill.id),
|
kind: "skill",
|
||||||
|
onSelect: () =>
|
||||||
|
insertPart(skill.id, {
|
||||||
|
type: "skill",
|
||||||
|
value: { id: Skill.ID.make(skill.id), mention: { start: 0, end: 0, text: "" } },
|
||||||
|
}),
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -463,7 +490,11 @@ export function Autocomplete(props: {
|
|||||||
// it shouldn't be additionally sorted by fuzzysort as it will loose the results
|
// it shouldn't be additionally sorted by fuzzysort as it will loose the results
|
||||||
const fileOptions: AutocompleteOption[] = store.visible === "@" ? fileSearch.options : []
|
const fileOptions: AutocompleteOption[] = store.visible === "@" ? fileSearch.options : []
|
||||||
const nonFileOptions: AutocompleteOption[] =
|
const nonFileOptions: AutocompleteOption[] =
|
||||||
store.visible === "@" ? [...referenceAliasesValue, ...agentsValue, ...mcpResources()] : [...commandsValue]
|
store.visible === "@"
|
||||||
|
? [...referenceAliasesValue, ...agentsValue, ...mcpResources()]
|
||||||
|
: store.index === 0
|
||||||
|
? [...commandsValue]
|
||||||
|
: commandsValue.filter((item) => item.kind === "skill")
|
||||||
|
|
||||||
if (!searchValue) {
|
if (!searchValue) {
|
||||||
return [...nonFileOptions, ...fileOptions]
|
return [...nonFileOptions, ...fileOptions]
|
||||||
@@ -520,7 +551,7 @@ export function Autocomplete(props: {
|
|||||||
function select() {
|
function select() {
|
||||||
const selected = options()[store.selected]
|
const selected = options()[store.selected]
|
||||||
if (!selected) return
|
if (!selected) return
|
||||||
hide()
|
hide(true)
|
||||||
selected.onSelect?.()
|
selected.onSelect?.()
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -608,14 +639,18 @@ export function Autocomplete(props: {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
function hide() {
|
function hide(removeToken = false) {
|
||||||
const text = props.input().plainText
|
if (removeToken && store.visible === "/") {
|
||||||
if (store.visible === "/" && !text.endsWith(" ") && text.startsWith("/")) {
|
const input = props.input()
|
||||||
const cursor = props.input().logicalCursor
|
const cursorOffset = input.cursorOffset
|
||||||
props.input().deleteRange(0, 0, cursor.row, cursor.col)
|
input.cursorOffset = store.index
|
||||||
|
const start = input.logicalCursor
|
||||||
|
input.cursorOffset = cursorOffset
|
||||||
|
const end = input.logicalCursor
|
||||||
|
input.deleteRange(start.row, start.col, end.row, end.col)
|
||||||
// Sync the prompt store immediately since onContentChange is async
|
// Sync the prompt store immediately since onContentChange is async
|
||||||
props.setPrompt((draft) => {
|
props.setPrompt((draft) => {
|
||||||
draft.text = props.input().plainText
|
draft.text = input.plainText
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
setStore("visible", false)
|
setStore("visible", false)
|
||||||
@@ -640,9 +675,7 @@ export function Autocomplete(props: {
|
|||||||
// Typed text before the trigger
|
// Typed text before the trigger
|
||||||
props.input().cursorOffset <= store.index ||
|
props.input().cursorOffset <= store.index ||
|
||||||
// There is a space between the trigger and the cursor
|
// There is a space between the trigger and the cursor
|
||||||
props.input().getTextRange(store.index, props.input().cursorOffset).match(/\s/) ||
|
props.input().getTextRange(store.index, props.input().cursorOffset).match(/\s/)
|
||||||
// "/<command>" is not the sole content
|
|
||||||
(store.visible === "/" && value.match(/^\S+\s+\S+\s*$/))
|
|
||||||
) {
|
) {
|
||||||
hide()
|
hide()
|
||||||
}
|
}
|
||||||
@@ -653,10 +686,10 @@ export function Autocomplete(props: {
|
|||||||
const offset = props.input().cursorOffset
|
const offset = props.input().cursorOffset
|
||||||
if (offset === 0) return
|
if (offset === 0) return
|
||||||
|
|
||||||
// Check for "/" at position 0 - reopen slash commands
|
const slash = slashTriggerIndex(value, offset)
|
||||||
if (value.startsWith("/") && !value.slice(0, offset).match(/\s/)) {
|
if (slash !== undefined) {
|
||||||
show("/")
|
show("/")
|
||||||
setStore("index", 0)
|
setStore("index", slash)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -29,6 +29,7 @@ import { parseSlashHead } from "../../prompt/parse"
|
|||||||
import { stringWidth } from "../../util/string-width"
|
import { stringWidth } from "../../util/string-width"
|
||||||
import { createStore, produce, unwrap } from "solid-js/store"
|
import { createStore, produce, unwrap } from "solid-js/store"
|
||||||
import { emptyPrompt, usePromptHistory, type PromptInfo, type PromptPartRef } from "../../prompt/history"
|
import { emptyPrompt, usePromptHistory, type PromptInfo, type PromptPartRef } from "../../prompt/history"
|
||||||
|
import { Skill } from "@opencode-ai/schema/skill"
|
||||||
import { computePromptTraits } from "../../prompt/traits"
|
import { computePromptTraits } from "../../prompt/traits"
|
||||||
import { expandPastedTextPlaceholders, expandTrackedPastedText } from "../../prompt/part"
|
import { expandPastedTextPlaceholders, expandTrackedPastedText } from "../../prompt/part"
|
||||||
import { usePromptStash } from "../../prompt/stash"
|
import { usePromptStash } from "../../prompt/stash"
|
||||||
@@ -273,6 +274,7 @@ export function Prompt(props: PromptProps) {
|
|||||||
}
|
}
|
||||||
const fileStyleId = syntax().getStyleId("extmark.file")!
|
const fileStyleId = syntax().getStyleId("extmark.file")!
|
||||||
const agentStyleId = syntax().getStyleId("extmark.agent")!
|
const agentStyleId = syntax().getStyleId("extmark.agent")!
|
||||||
|
const skillStyleId = syntax().getStyleId("extmark.skill")!
|
||||||
const pasteStyleId = syntax().getStyleId("extmark.paste")!
|
const pasteStyleId = syntax().getStyleId("extmark.paste")!
|
||||||
let promptPartTypeId = 0
|
let promptPartTypeId = 0
|
||||||
const event = useEvent()
|
const event = useEvent()
|
||||||
@@ -493,12 +495,29 @@ export function Prompt(props: PromptProps) {
|
|||||||
<DialogSkill
|
<DialogSkill
|
||||||
location={currentLocation.current}
|
location={currentLocation.current}
|
||||||
onSelect={(skill) => {
|
onSelect={(skill) => {
|
||||||
input.setText(`/${skill} `)
|
if (store.prompt.skills?.some((item) => item.id === skill)) return
|
||||||
setStore("prompt", {
|
const text = `/${skill}`
|
||||||
...emptyPrompt(),
|
const start = input.cursorOffset
|
||||||
text: `/${skill} `,
|
input.insertText(text + " ")
|
||||||
|
const extmarkId = input.extmarks.create({
|
||||||
|
start,
|
||||||
|
end: start + promptOffsetWidth(text),
|
||||||
|
virtual: true,
|
||||||
|
styleId: skillStyleId,
|
||||||
|
typeId: promptPartTypeId,
|
||||||
})
|
})
|
||||||
input.gotoBufferEnd()
|
setStore(
|
||||||
|
produce((draft) => {
|
||||||
|
draft.prompt.text = input.plainText
|
||||||
|
const skills = (draft.prompt.skills ??= [])
|
||||||
|
const index = skills.length
|
||||||
|
skills.push({
|
||||||
|
id: Skill.ID.make(skill),
|
||||||
|
mention: { start, end: start + promptOffsetWidth(text), text },
|
||||||
|
})
|
||||||
|
draft.extmarkToPart.set(extmarkId, { type: "skill", index })
|
||||||
|
}),
|
||||||
|
)
|
||||||
}}
|
}}
|
||||||
/>
|
/>
|
||||||
))
|
))
|
||||||
@@ -639,6 +658,11 @@ export function Prompt(props: PromptProps) {
|
|||||||
ref: { type: "agent" as const, index },
|
ref: { type: "agent" as const, index },
|
||||||
styleId: agentStyleId,
|
styleId: agentStyleId,
|
||||||
})),
|
})),
|
||||||
|
...(prompt.skills ?? []).map((part, index) => ({
|
||||||
|
mention: part.mention,
|
||||||
|
ref: { type: "skill" as const, index },
|
||||||
|
styleId: skillStyleId,
|
||||||
|
})),
|
||||||
...prompt.pasted.map((part, index) => ({
|
...prompt.pasted.map((part, index) => ({
|
||||||
mention: part.source,
|
mention: part.source,
|
||||||
ref: { type: "pasted" as const, index },
|
ref: { type: "pasted" as const, index },
|
||||||
@@ -671,6 +695,7 @@ export function Prompt(props: PromptProps) {
|
|||||||
const newMap = new Map<number, PromptPartRef>()
|
const newMap = new Map<number, PromptPartRef>()
|
||||||
const files: NonNullable<PromptInfo["files"]> = []
|
const files: NonNullable<PromptInfo["files"]> = []
|
||||||
const agents: NonNullable<PromptInfo["agents"]> = []
|
const agents: NonNullable<PromptInfo["agents"]> = []
|
||||||
|
const skills: NonNullable<PromptInfo["skills"]> = []
|
||||||
const pasted: PromptInfo["pasted"] = []
|
const pasted: PromptInfo["pasted"] = []
|
||||||
|
|
||||||
for (const extmark of allExtmarks) {
|
for (const extmark of allExtmarks) {
|
||||||
@@ -696,6 +721,16 @@ export function Prompt(props: PromptProps) {
|
|||||||
newMap.set(extmark.id, { type: "agent", index })
|
newMap.set(extmark.id, { type: "agent", index })
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
|
if (ref.type === "skill") {
|
||||||
|
const part = draft.prompt.skills?.[ref.index]
|
||||||
|
if (!part?.mention) continue
|
||||||
|
part.mention.start = extmark.start
|
||||||
|
part.mention.end = extmark.end
|
||||||
|
const index = skills.length
|
||||||
|
skills.push(part)
|
||||||
|
newMap.set(extmark.id, { type: "skill", index })
|
||||||
|
continue
|
||||||
|
}
|
||||||
const part = draft.prompt.pasted[ref.index]
|
const part = draft.prompt.pasted[ref.index]
|
||||||
if (!part) continue
|
if (!part) continue
|
||||||
part.source.start = extmark.start
|
part.source.start = extmark.start
|
||||||
@@ -708,6 +743,7 @@ export function Prompt(props: PromptProps) {
|
|||||||
draft.extmarkToPart = newMap
|
draft.extmarkToPart = newMap
|
||||||
draft.prompt.files = files
|
draft.prompt.files = files
|
||||||
draft.prompt.agents = agents
|
draft.prompt.agents = agents
|
||||||
|
draft.prompt.skills = skills
|
||||||
draft.prompt.pasted = pasted
|
draft.prompt.pasted = pasted
|
||||||
}),
|
}),
|
||||||
)
|
)
|
||||||
@@ -983,6 +1019,7 @@ export function Prompt(props: PromptProps) {
|
|||||||
)
|
)
|
||||||
const slashHead = parseSlashHead(inputText, /\s/)
|
const slashHead = parseSlashHead(inputText, /\s/)
|
||||||
const isSkill =
|
const isSkill =
|
||||||
|
!(store.prompt.skills?.length ?? 0) &&
|
||||||
slashHead !== undefined &&
|
slashHead !== undefined &&
|
||||||
(data.location.skill.list(currentLocation.ref) ?? []).some(
|
(data.location.skill.list(currentLocation.ref) ?? []).some(
|
||||||
(skill) => skill.slash === true && skill.id === slashHead.name,
|
(skill) => skill.slash === true && skill.id === slashHead.name,
|
||||||
@@ -1080,6 +1117,7 @@ export function Prompt(props: PromptProps) {
|
|||||||
model,
|
model,
|
||||||
files: store.prompt.files,
|
files: store.prompt.files,
|
||||||
agents: store.prompt.agents,
|
agents: store.prompt.agents,
|
||||||
|
skills: store.prompt.skills?.length ? store.prompt.skills : undefined,
|
||||||
delivery,
|
delivery,
|
||||||
})
|
})
|
||||||
.catch((error) => {
|
.catch((error) => {
|
||||||
@@ -1146,6 +1184,7 @@ export function Prompt(props: PromptProps) {
|
|||||||
text: inputText,
|
text: inputText,
|
||||||
files: store.prompt.files,
|
files: store.prompt.files,
|
||||||
agents: store.prompt.agents,
|
agents: store.prompt.agents,
|
||||||
|
skills: store.prompt.skills?.length ? store.prompt.skills : undefined,
|
||||||
delivery,
|
delivery,
|
||||||
})
|
})
|
||||||
.then(
|
.then(
|
||||||
@@ -1685,6 +1724,8 @@ export function Prompt(props: PromptProps) {
|
|||||||
value={store.prompt.text}
|
value={store.prompt.text}
|
||||||
fileStyleId={fileStyleId}
|
fileStyleId={fileStyleId}
|
||||||
agentStyleId={agentStyleId}
|
agentStyleId={agentStyleId}
|
||||||
|
skillStyleId={skillStyleId}
|
||||||
|
hasSkill={(id) => store.prompt.skills?.some((skill) => skill.id === id) ?? false}
|
||||||
promptPartTypeId={() => promptPartTypeId}
|
promptPartTypeId={() => promptPartTypeId}
|
||||||
/>
|
/>
|
||||||
</>
|
</>
|
||||||
|
|||||||
@@ -10,6 +10,7 @@ import {
|
|||||||
moveSessionTab,
|
moveSessionTab,
|
||||||
NEW_SESSION_TAB_TITLE,
|
NEW_SESSION_TAB_TITLE,
|
||||||
sessionTabComplete,
|
sessionTabComplete,
|
||||||
|
sessionTabShortcutLabel,
|
||||||
seedSessionTabMotion,
|
seedSessionTabMotion,
|
||||||
sessionTabOverflowWidth,
|
sessionTabOverflowWidth,
|
||||||
type SessionTab,
|
type SessionTab,
|
||||||
@@ -140,7 +141,7 @@ function VerticalSessionTabs(props: { controller?: SessionTabsController; animat
|
|||||||
const value = session()
|
const value = session()
|
||||||
return value ? data.project.get(value.projectID) : undefined
|
return value ? data.project.get(value.projectID) : undefined
|
||||||
})
|
})
|
||||||
const numberWidth = () => String(index() + 1).length + 1
|
const numberWidth = () => 2
|
||||||
const titleWidth = () => Math.max(1, width() - numberWidth() - 2 - (hovered() === tab.sessionID ? 1 : 0))
|
const titleWidth = () => Math.max(1, width() - numberWidth() - 2 - (hovered() === tab.sessionID ? 1 : 0))
|
||||||
const title = () => tab.title ?? "Untitled session"
|
const title = () => tab.title ?? "Untitled session"
|
||||||
const visibleTitle = createMemo(() => Locale.takeWidth(title(), titleWidth()))
|
const visibleTitle = createMemo(() => Locale.takeWidth(title(), titleWidth()))
|
||||||
@@ -311,7 +312,7 @@ function VerticalSessionTabs(props: { controller?: SessionTabsController; animat
|
|||||||
selectable={false}
|
selectable={false}
|
||||||
attributes={selected() ? TextAttributes.BOLD : undefined}
|
attributes={selected() ? TextAttributes.BOLD : undefined}
|
||||||
>
|
>
|
||||||
{index() + 1}
|
{sessionTabShortcutLabel(index())}
|
||||||
</text>
|
</text>
|
||||||
<text
|
<text
|
||||||
width={titleWidth()}
|
width={titleWidth()}
|
||||||
@@ -555,8 +556,8 @@ function HorizontalSessionTabs(props: { controller?: SessionTabsController; anim
|
|||||||
const glows = () => !selected() && (status().attention || (!status().busy && status().unread !== undefined))
|
const glows = () => !selected() && (status().attention || (!status().busy && status().unread !== undefined))
|
||||||
const title = () => tab.title ?? "Untitled session"
|
const title = () => tab.title ?? "Untitled session"
|
||||||
const tabNumber = createMemo(() => items().findIndex((item) => item.sessionID === tab.sessionID) + 1)
|
const tabNumber = createMemo(() => items().findIndex((item) => item.sessionID === tab.sessionID) + 1)
|
||||||
// The number cell keeps one trailing space, even for double-digit tabs.
|
// Shortcut labels stay one cell wide: 1-9, 0 for ten, then a neutral dot.
|
||||||
const numberWidth = () => String(tabNumber()).length + 1
|
const numberWidth = () => 2
|
||||||
// Hovering reveals the close mark, so the title's right bound shifts left of it.
|
// Hovering reveals the close mark, so the title's right bound shifts left of it.
|
||||||
const availableTitleWidth = () =>
|
const availableTitleWidth = () =>
|
||||||
Math.max(1, width() - 1 - numberWidth() - (hovered() === tab.sessionID ? 2 : 0))
|
Math.max(1, width() - 1 - numberWidth() - (hovered() === tab.sessionID ? 2 : 0))
|
||||||
@@ -639,7 +640,7 @@ function HorizontalSessionTabs(props: { controller?: SessionTabsController; anim
|
|||||||
{" "}
|
{" "}
|
||||||
</text>
|
</text>
|
||||||
<text width={numberWidth()} fg={numberColor()} selectable={false} attributes={bold()}>
|
<text width={numberWidth()} fg={numberColor()} selectable={false} attributes={bold()}>
|
||||||
{tabNumber()}
|
{sessionTabShortcutLabel(tabNumber() - 1)}
|
||||||
</text>
|
</text>
|
||||||
<text
|
<text
|
||||||
width={availableTitleWidth()}
|
width={availableTitleWidth()}
|
||||||
|
|||||||
@@ -126,6 +126,7 @@ export const Definitions = {
|
|||||||
session_tab_select_7: keybind("<leader>7,ctrl+7", "Switch to tab 7"),
|
session_tab_select_7: keybind("<leader>7,ctrl+7", "Switch to tab 7"),
|
||||||
session_tab_select_8: keybind("<leader>8,ctrl+8", "Switch to tab 8"),
|
session_tab_select_8: keybind("<leader>8,ctrl+8", "Switch to tab 8"),
|
||||||
session_tab_select_9: keybind("<leader>9,ctrl+9", "Switch to tab 9"),
|
session_tab_select_9: keybind("<leader>9,ctrl+9", "Switch to tab 9"),
|
||||||
|
session_tab_select_10: keybind("<leader>0,ctrl+0", "Switch to tab 10"),
|
||||||
|
|
||||||
stash_delete: keybind("ctrl+d", "Delete stash entry"),
|
stash_delete: keybind("ctrl+d", "Delete stash entry"),
|
||||||
model_provider_list: keybind("ctrl+a", "Open provider list from model dialog"),
|
model_provider_list: keybind("ctrl+a", "Open provider list from model dialog"),
|
||||||
@@ -329,6 +330,7 @@ export const CommandMap = {
|
|||||||
session_tab_select_7: "session.tab.select.7",
|
session_tab_select_7: "session.tab.select.7",
|
||||||
session_tab_select_8: "session.tab.select.8",
|
session_tab_select_8: "session.tab.select.8",
|
||||||
session_tab_select_9: "session.tab.select.9",
|
session_tab_select_9: "session.tab.select.9",
|
||||||
|
session_tab_select_10: "session.tab.select.10",
|
||||||
stash_delete: "stash.delete",
|
stash_delete: "stash.delete",
|
||||||
model_provider_list: "model.dialog.provider",
|
model_provider_list: "model.dialog.provider",
|
||||||
model_favorite_toggle: "model.dialog.favorite",
|
model_favorite_toggle: "model.dialog.favorite",
|
||||||
|
|||||||
@@ -7,6 +7,12 @@ export type SessionTabUnread = "activity" | "error"
|
|||||||
|
|
||||||
export const NEW_SESSION_TAB_TITLE = "New session"
|
export const NEW_SESSION_TAB_TITLE = "New session"
|
||||||
|
|
||||||
|
export function sessionTabShortcutLabel(index: number) {
|
||||||
|
if (index >= 0 && index < 9) return String(index + 1)
|
||||||
|
if (index === 9) return "0"
|
||||||
|
return "·"
|
||||||
|
}
|
||||||
|
|
||||||
export type SessionTabHistory = {
|
export type SessionTabHistory = {
|
||||||
entries: readonly string[]
|
entries: readonly string[]
|
||||||
index: number
|
index: number
|
||||||
|
|||||||
@@ -21,6 +21,7 @@ import {
|
|||||||
isExitCommand,
|
isExitCommand,
|
||||||
isCompactCommand,
|
isCompactCommand,
|
||||||
mentionTriggerIndex,
|
mentionTriggerIndex,
|
||||||
|
slashTriggerIndex,
|
||||||
isNewCommand,
|
isNewCommand,
|
||||||
movePromptHistory,
|
movePromptHistory,
|
||||||
promptCopy,
|
promptCopy,
|
||||||
@@ -50,7 +51,7 @@ export const TEXTAREA_MIN_ROWS = 1
|
|||||||
const TEXTAREA_MAX_ROWS = 6
|
const TEXTAREA_MAX_ROWS = 6
|
||||||
export const PROMPT_MAX_ROWS = TEXTAREA_MAX_ROWS + AUTOCOMPLETE_ROWS - 1 + AUTOCOMPLETE_BOTTOM_ROWS
|
export const PROMPT_MAX_ROWS = TEXTAREA_MAX_ROWS + AUTOCOMPLETE_ROWS - 1 + AUTOCOMPLETE_BOTTOM_ROWS
|
||||||
|
|
||||||
type Mention = Extract<RunPromptPart, { type: "file" | "agent" }>
|
type Mention = Extract<RunPromptPart, { type: "file" | "agent" | "skill" }>
|
||||||
|
|
||||||
type Auto = RunFooterMenuItem & {
|
type Auto = RunFooterMenuItem & {
|
||||||
kind: "mention"
|
kind: "mention"
|
||||||
@@ -65,7 +66,12 @@ type SlashOption = RunFooterMenuItem & {
|
|||||||
action?: "skill-menu" | "editor" | "settings"
|
action?: "skill-menu" | "editor" | "settings"
|
||||||
}
|
}
|
||||||
|
|
||||||
type PromptOption = Auto | SlashOption
|
type SkillOption = RunFooterMenuItem & {
|
||||||
|
kind: "skill"
|
||||||
|
id: string
|
||||||
|
}
|
||||||
|
|
||||||
|
type PromptOption = Auto | SlashOption | SkillOption
|
||||||
|
|
||||||
type MenuMode = false | "mention" | "slash"
|
type MenuMode = false | "mention" | "slash"
|
||||||
|
|
||||||
@@ -124,12 +130,9 @@ function emptyPrompt(shell: boolean): RunPrompt {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function slashQuery(text: string, cursor: number) {
|
function slashQuery(text: string, cursor: number) {
|
||||||
const head = parseSlashHead(text.slice(0, cursor))
|
const at = slashTriggerIndex(text, cursor)
|
||||||
if (!head || head.end !== cursor) {
|
if (at === undefined) return
|
||||||
return
|
return { at, value: displaySlice(text, at + 1, cursor) }
|
||||||
}
|
|
||||||
|
|
||||||
return head.name
|
|
||||||
}
|
}
|
||||||
|
|
||||||
function parseSlashCommand(text: string, commands: RunCommand[] | undefined) {
|
function parseSlashCommand(text: string, commands: RunCommand[] | undefined) {
|
||||||
@@ -382,10 +385,18 @@ export function createPromptState(input: PromptInput): PromptState {
|
|||||||
)
|
)
|
||||||
const mentionOptions = createMemo(() => [...agents(), ...files(), ...references()])
|
const mentionOptions = createMemo(() => [...agents(), ...files(), ...references()])
|
||||||
const skillCommands = createMemo(() => (input.commands() ?? []).filter((item) => item.source === "skill"))
|
const skillCommands = createMemo(() => (input.commands() ?? []).filter((item) => item.source === "skill"))
|
||||||
|
const skillOptions = createMemo<SkillOption[]>(() =>
|
||||||
|
skillCommands().map((item) => ({
|
||||||
|
kind: "skill",
|
||||||
|
id: item.name,
|
||||||
|
display: `/${item.name}`,
|
||||||
|
description: item.description,
|
||||||
|
})),
|
||||||
|
)
|
||||||
const hasSkillsCommand = createMemo(() =>
|
const hasSkillsCommand = createMemo(() =>
|
||||||
(input.commands() ?? []).some((item) => item.source !== "skill" && item.name === "skills"),
|
(input.commands() ?? []).some((item) => item.source !== "skill" && item.name === "skills"),
|
||||||
)
|
)
|
||||||
const slashOptions = createMemo<SlashOption[]>(() => {
|
const slashOptions = createMemo<Array<SlashOption | SkillOption>>(() => {
|
||||||
const builtins = [
|
const builtins = [
|
||||||
{
|
{
|
||||||
kind: "slash",
|
kind: "slash",
|
||||||
@@ -417,6 +428,7 @@ export function createPromptState(input: PromptInput): PromptState {
|
|||||||
}
|
}
|
||||||
|
|
||||||
return [
|
return [
|
||||||
|
...skillOptions(),
|
||||||
...(showSkillMenu
|
...(showSkillMenu
|
||||||
? [
|
? [
|
||||||
{
|
{
|
||||||
@@ -443,7 +455,7 @@ export function createPromptState(input: PromptInput): PromptState {
|
|||||||
].sort((a, b) => a.display.localeCompare(b.display))
|
].sort((a, b) => a.display.localeCompare(b.display))
|
||||||
})
|
})
|
||||||
const options = createMemo<PromptOption[]>(() => {
|
const options = createMemo<PromptOption[]>(() => {
|
||||||
const mixed: PromptOption[] = mode() === "slash" ? slashOptions() : mentionOptions()
|
const mixed: PromptOption[] = mode() === "slash" ? (at() === 0 ? slashOptions() : skillOptions()) : mentionOptions()
|
||||||
if (!query()) {
|
if (!query()) {
|
||||||
return mixed
|
return mixed
|
||||||
}
|
}
|
||||||
@@ -459,7 +471,11 @@ export function createPromptState(input: PromptInput): PromptState {
|
|||||||
|
|
||||||
return fuzzysort
|
return fuzzysort
|
||||||
.go(next, mixed, {
|
.go(next, mixed, {
|
||||||
keys: [(item) => (item.kind === "mention" ? item.value : item.name).trimEnd(), "display", "description"],
|
keys: [
|
||||||
|
(item) => (item.kind === "mention" ? item.value : item.kind === "skill" ? item.id : item.name).trimEnd(),
|
||||||
|
"display",
|
||||||
|
"description",
|
||||||
|
],
|
||||||
})
|
})
|
||||||
.map((item) => item.obj)
|
.map((item) => item.obj)
|
||||||
})
|
})
|
||||||
@@ -512,17 +528,19 @@ export function createPromptState(input: PromptInput): PromptState {
|
|||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
|
|
||||||
const text = area.plainText.slice(item.start, item.end)
|
const text = displaySlice(area.plainText, item.start, item.end)
|
||||||
const prev =
|
const prev =
|
||||||
part.type === "agent"
|
part.type === "agent"
|
||||||
? (part.source?.value ?? "@" + part.name)
|
? (part.source?.value ?? "@" + part.name)
|
||||||
|
: part.type === "skill"
|
||||||
|
? (part.source?.value ?? "/" + part.id)
|
||||||
: (part.source?.text.value ?? "@" + (part.filename ?? ""))
|
: (part.source?.text.value ?? "@" + (part.filename ?? ""))
|
||||||
if (text !== prev) {
|
if (text !== prev) {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
|
|
||||||
const copy = structuredClone(part)
|
const copy = structuredClone(part)
|
||||||
if (copy.type === "agent") {
|
if (copy.type === "agent" || copy.type === "skill") {
|
||||||
copy.source = {
|
copy.source = {
|
||||||
start: item.start,
|
start: item.start,
|
||||||
end: item.end,
|
end: item.end,
|
||||||
@@ -558,7 +576,7 @@ export function createPromptState(input: PromptInput): PromptState {
|
|||||||
const restoreParts = (value: RunPromptPart[]) => {
|
const restoreParts = (value: RunPromptPart[]) => {
|
||||||
clearParts()
|
clearParts()
|
||||||
parts = value
|
parts = value
|
||||||
.filter((item): item is Mention => item.type === "file" || item.type === "agent")
|
.filter((item): item is Mention => item.type === "file" || item.type === "agent" || item.type === "skill")
|
||||||
.map((item) => structuredClone(item))
|
.map((item) => structuredClone(item))
|
||||||
if (!area || area.isDestroyed || type === 0) {
|
if (!area || area.isDestroyed || type === 0) {
|
||||||
return
|
return
|
||||||
@@ -566,8 +584,8 @@ export function createPromptState(input: PromptInput): PromptState {
|
|||||||
|
|
||||||
const box = area
|
const box = area
|
||||||
parts.forEach((item, idx) => {
|
parts.forEach((item, idx) => {
|
||||||
const start = item.type === "agent" ? item.source?.start : item.source?.text.start
|
const start = item.type === "file" ? item.source?.text.start : item.source?.start
|
||||||
const end = item.type === "agent" ? item.source?.end : item.source?.text.end
|
const end = item.type === "file" ? item.source?.text.end : item.source?.end
|
||||||
if (start === undefined || end === undefined) {
|
if (start === undefined || end === undefined) {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
@@ -627,16 +645,16 @@ export function createPromptState(input: PromptInput): PromptState {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
setAt(0)
|
setAt(slash.at)
|
||||||
setQuery(slash)
|
setQuery(slash.value)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
if (slash !== undefined) {
|
if (slash !== undefined) {
|
||||||
setAt(0)
|
setAt(slash.at)
|
||||||
menu.reset()
|
menu.reset()
|
||||||
setMode("slash")
|
setMode("slash")
|
||||||
setQuery(slash)
|
setQuery(slash.value)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -782,7 +800,7 @@ export function createPromptState(input: PromptInput): PromptState {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const cursor = area.cursorOffset
|
const cursor = area.cursorOffset
|
||||||
const startOffset = mode() === "slash" ? 0 : at()
|
const startOffset = at()
|
||||||
area.cursorOffset = startOffset
|
area.cursorOffset = startOffset
|
||||||
const start = area.logicalCursor
|
const start = area.logicalCursor
|
||||||
area.cursorOffset = cursor
|
area.cursorOffset = cursor
|
||||||
@@ -828,6 +846,39 @@ export function createPromptState(input: PromptInput): PromptState {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (next.kind === "skill") {
|
||||||
|
if (parts.some((part) => part.type === "skill" && part.id === next.id)) {
|
||||||
|
cancelAutocomplete()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
const cursor = area.cursorOffset
|
||||||
|
const tail = displayCharAt(area.plainText, cursor)
|
||||||
|
const append = `/${next.id}${tail === " " ? "" : " "}`
|
||||||
|
area.cursorOffset = at()
|
||||||
|
const start = area.logicalCursor
|
||||||
|
area.cursorOffset = cursor
|
||||||
|
const end = area.logicalCursor
|
||||||
|
area.deleteRange(start.row, start.col, end.row, end.col)
|
||||||
|
area.insertText(append)
|
||||||
|
|
||||||
|
const text = `/${next.id}`
|
||||||
|
const startOffset = at()
|
||||||
|
const endOffset = startOffset + stringWidth(text)
|
||||||
|
const part: Extract<RunPromptPart, { type: "skill" }> = {
|
||||||
|
type: "skill",
|
||||||
|
id: next.id,
|
||||||
|
source: { start: startOffset, end: endOffset, value: text },
|
||||||
|
}
|
||||||
|
const id = area.extmarks.create({ start: startOffset, end: endOffset, virtual: true, typeId: type })
|
||||||
|
marks.set(id, parts.length)
|
||||||
|
parts.push(part)
|
||||||
|
hide()
|
||||||
|
syncDraft()
|
||||||
|
scheduleRows()
|
||||||
|
area.focus()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
if (next.kind === "slash") {
|
if (next.kind === "slash") {
|
||||||
if (next.action === "editor") {
|
if (next.action === "editor") {
|
||||||
void openEditor({
|
void openEditor({
|
||||||
@@ -1193,7 +1244,7 @@ export function createPromptState(input: PromptInput): PromptState {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const parsed =
|
const parsed =
|
||||||
command || next.mode === "shell" || isNewCommand(next.text)
|
command || next.parts.some((part) => part.type === "skill") || next.mode === "shell" || isNewCommand(next.text)
|
||||||
? undefined
|
? undefined
|
||||||
: parseSlashCommand(next.text, input.commands())
|
: parseSlashCommand(next.text, input.commands())
|
||||||
if (parsed?.type === "pending") {
|
if (parsed?.type === "pending") {
|
||||||
|
|||||||
@@ -2,7 +2,7 @@ import type { RunPromptPart } from "./types"
|
|||||||
import { realignPromptMentions } from "../prompt/mention"
|
import { realignPromptMentions } from "../prompt/mention"
|
||||||
import { parseSlashHead } from "../prompt/parse"
|
import { parseSlashHead } from "../prompt/parse"
|
||||||
|
|
||||||
type Mention = Extract<RunPromptPart, { type: "file" | "agent" }>
|
type Mention = Extract<RunPromptPart, { type: "file" | "agent" | "skill" }>
|
||||||
|
|
||||||
export function resolveEditorSlashValue(text: string) {
|
export function resolveEditorSlashValue(text: string) {
|
||||||
const head = parseSlashHead(text)
|
const head = parseSlashHead(text)
|
||||||
@@ -17,13 +17,13 @@ export function realignEditorPromptParts(content: string, parts: RunPromptPart[]
|
|||||||
const matches = realignPromptMentions(
|
const matches = realignPromptMentions(
|
||||||
content,
|
content,
|
||||||
parts.map((part) => {
|
parts.map((part) => {
|
||||||
if (part.type !== "file" && part.type !== "agent") return
|
if (part.type !== "file" && part.type !== "agent" && part.type !== "skill") return
|
||||||
return promptPartMention(part)
|
return promptPartMention(part)
|
||||||
}),
|
}),
|
||||||
)
|
)
|
||||||
|
|
||||||
return parts.flatMap((part, index) => {
|
return parts.flatMap((part, index) => {
|
||||||
if (part.type !== "file" && part.type !== "agent") return [part]
|
if (part.type !== "file" && part.type !== "agent" && part.type !== "skill") return [part]
|
||||||
const mention = promptPartMention(part)
|
const mention = promptPartMention(part)
|
||||||
if (!mention?.text) return [part]
|
if (!mention?.text) return [part]
|
||||||
const match = matches[index]
|
const match = matches[index]
|
||||||
@@ -32,13 +32,13 @@ export function realignEditorPromptParts(content: string, parts: RunPromptPart[]
|
|||||||
}
|
}
|
||||||
|
|
||||||
function promptPartMention(part: Mention) {
|
function promptPartMention(part: Mention) {
|
||||||
const source = part.type === "agent" ? part.source : part.source?.text
|
const source = part.type === "file" ? part.source?.text : part.source
|
||||||
if (!source) return
|
if (!source) return
|
||||||
return { start: source.start, end: source.end, text: source.value }
|
return { start: source.start, end: source.end, text: source.value }
|
||||||
}
|
}
|
||||||
|
|
||||||
function updatePromptPart(part: Mention, start: number, end: number, text: string): Mention {
|
function updatePromptPart(part: Mention, start: number, end: number, text: string): Mention {
|
||||||
if (part.type === "agent") {
|
if (part.type === "agent" || part.type === "skill") {
|
||||||
return {
|
return {
|
||||||
...part,
|
...part,
|
||||||
source: {
|
source: {
|
||||||
|
|||||||
@@ -7,7 +7,7 @@
|
|||||||
// the current browse position. When the user arrows up at cursor offset 0,
|
// the current browse position. When the user arrows up at cursor offset 0,
|
||||||
// the current draft is saved and history begins. Arrowing past the end
|
// the current draft is saved and history begins. Arrowing past the end
|
||||||
// restores the draft.
|
// restores the draft.
|
||||||
export { displayCharAt, displaySlice, mentionTriggerIndex } from "../prompt/display"
|
export { displayCharAt, displaySlice, mentionTriggerIndex, slashTriggerIndex } from "../prompt/display"
|
||||||
import { stringWidth } from "../util/string-width"
|
import { stringWidth } from "../util/string-width"
|
||||||
import type { RunPrompt } from "./types"
|
import type { RunPrompt } from "./types"
|
||||||
|
|
||||||
|
|||||||
@@ -288,6 +288,21 @@ function promptAgents(next: SessionTurnInput) {
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function promptSkills(next: SessionTurnInput) {
|
||||||
|
return next.prompt.parts.flatMap((part) =>
|
||||||
|
part.type === "skill"
|
||||||
|
? [
|
||||||
|
{
|
||||||
|
id: part.id,
|
||||||
|
mention: part.source
|
||||||
|
? { start: part.source.start, end: part.source.end, text: part.source.value }
|
||||||
|
: undefined,
|
||||||
|
},
|
||||||
|
]
|
||||||
|
: [],
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
function streamPartKey(messageID: string, partID: string) {
|
function streamPartKey(messageID: string, partID: string) {
|
||||||
return `${messageID}\u0000${partID}`
|
return `${messageID}\u0000${partID}`
|
||||||
}
|
}
|
||||||
@@ -358,12 +373,12 @@ const catalogEvents = new Set([
|
|||||||
// briefly so the output commit renders inside it.
|
// briefly so the output commit renders inside it.
|
||||||
const SHELL_OUTPUT_GRACE_MS = 1500
|
const SHELL_OUTPUT_GRACE_MS = 1500
|
||||||
|
|
||||||
function skillCommit(messageID: string, name: string): StreamCommit {
|
function skillCommit(messageID: string, name: string, skillID = messageID): StreamCommit {
|
||||||
return {
|
return {
|
||||||
kind: "system",
|
kind: "system",
|
||||||
source: "system",
|
source: "system",
|
||||||
messageID,
|
messageID,
|
||||||
partID: `skill:${messageID}`,
|
partID: `skill:${skillID}`,
|
||||||
text: `→ Skill "${name}"`,
|
text: `→ Skill "${name}"`,
|
||||||
phase: "start",
|
phase: "start",
|
||||||
}
|
}
|
||||||
@@ -637,7 +652,10 @@ export async function createSessionTransport(input: StreamInput): Promise<Sessio
|
|||||||
state.messageIDs.add(message.id)
|
state.messageIDs.add(message.id)
|
||||||
if (!render) return
|
if (!render) return
|
||||||
if (reuseVisibleWait && waiting) return
|
if (reuseVisibleWait && waiting) return
|
||||||
write([{ kind: "user", source: "system", text: message.text, phase: "start", messageID: message.id }])
|
write([
|
||||||
|
...(message.skills ?? []).map((skill) => skillCommit(message.id, skill.name, skill.id)),
|
||||||
|
{ kind: "user", source: "system", text: message.text, phase: "start", messageID: message.id },
|
||||||
|
])
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
if (message.type === "skill") {
|
if (message.type === "skill") {
|
||||||
@@ -1615,6 +1633,7 @@ export async function createSessionTransport(input: StreamInput): Promise<Sessio
|
|||||||
const command = next.prompt.command
|
const command = next.prompt.command
|
||||||
const attachments = await prepareAttachments(next, command ? "command" : "prompt", input.readTextFile)
|
const attachments = await prepareAttachments(next, command ? "command" : "prompt", input.readTextFile)
|
||||||
const agents = promptAgents(next)
|
const agents = promptAgents(next)
|
||||||
|
const skills = promptSkills(next)
|
||||||
if (!command) {
|
if (!command) {
|
||||||
input.trace?.write("send.prompt", { sessionID: input.sessionID, messageID, delivery })
|
input.trace?.write("send.prompt", { sessionID: input.sessionID, messageID, delivery })
|
||||||
return client.session.prompt(
|
return client.session.prompt(
|
||||||
@@ -1624,6 +1643,7 @@ export async function createSessionTransport(input: StreamInput): Promise<Sessio
|
|||||||
text: [next.prompt.text, ...attachments.text].join("\n\n"),
|
text: [next.prompt.text, ...attachments.text].join("\n\n"),
|
||||||
files: attachments.files.length ? attachments.files : undefined,
|
files: attachments.files.length ? attachments.files : undefined,
|
||||||
agents: agents.length ? agents : undefined,
|
agents: agents.length ? agents : undefined,
|
||||||
|
skills: skills.length ? skills : undefined,
|
||||||
delivery,
|
delivery,
|
||||||
},
|
},
|
||||||
{ signal: next.signal },
|
{ signal: next.signal },
|
||||||
@@ -1643,6 +1663,7 @@ export async function createSessionTransport(input: StreamInput): Promise<Sessio
|
|||||||
model: selected,
|
model: selected,
|
||||||
files: attachments.files.length ? attachments.files : undefined,
|
files: attachments.files.length ? attachments.files : undefined,
|
||||||
agents: agents.length ? agents : undefined,
|
agents: agents.length ? agents : undefined,
|
||||||
|
skills: skills.length ? skills : undefined,
|
||||||
delivery,
|
delivery,
|
||||||
},
|
},
|
||||||
{ signal: next.signal },
|
{ signal: next.signal },
|
||||||
|
|||||||
@@ -47,6 +47,7 @@ export type RunPromptPart =
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
| { type: "agent"; name: string; source?: { start: number; end: number; value: string } }
|
| { type: "agent"; name: string; source?: { start: number; end: number; value: string } }
|
||||||
|
| { type: "skill"; id: string; source?: { start: number; end: number; value: string } }
|
||||||
|
|
||||||
export type RunCommand = {
|
export type RunCommand = {
|
||||||
name: string
|
name: string
|
||||||
|
|||||||
@@ -1,9 +1,14 @@
|
|||||||
import type { Prompt, PromptInput } from "@opencode-ai/schema"
|
import type { Prompt, PromptInput } from "@opencode-ai/schema"
|
||||||
|
import { Skill } from "@opencode-ai/schema/skill"
|
||||||
import type { Types } from "effect"
|
import type { Types } from "effect"
|
||||||
|
|
||||||
export type EditablePromptInput = Types.DeepMutable<PromptInput.Prompt>
|
export type EditablePromptInput = Types.DeepMutable<PromptInput.Prompt>
|
||||||
|
|
||||||
export function projectedPromptInput(input: Pick<Prompt, "text" | "files" | "agents">): EditablePromptInput {
|
type ProjectedPrompt = Pick<Prompt, "text" | "files" | "agents"> & {
|
||||||
|
readonly skills?: ReadonlyArray<{ readonly id: string; readonly mention?: PromptInput.SkillAttachment["mention"] }>
|
||||||
|
}
|
||||||
|
|
||||||
|
export function projectedPromptInput(input: ProjectedPrompt): EditablePromptInput {
|
||||||
return {
|
return {
|
||||||
text: input.text,
|
text: input.text,
|
||||||
files: input.files?.map((file) => ({
|
files: input.files?.map((file) => ({
|
||||||
@@ -16,5 +21,9 @@ export function projectedPromptInput(input: Pick<Prompt, "text" | "files" | "age
|
|||||||
name: agent.name,
|
name: agent.name,
|
||||||
mention: agent.mention ? { ...agent.mention } : undefined,
|
mention: agent.mention ? { ...agent.mention } : undefined,
|
||||||
})),
|
})),
|
||||||
|
skills: input.skills?.map((skill) => ({
|
||||||
|
id: Skill.ID.make(skill.id),
|
||||||
|
mention: skill.mention ? { ...skill.mention } : undefined,
|
||||||
|
})),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -48,3 +48,14 @@ export function mentionTriggerIndex(value: string, offset = promptOffsetWidth(va
|
|||||||
return promptOffsetWidth(text.slice(0, index))
|
return promptOffsetWidth(text.slice(0, index))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export function slashTriggerIndex(value: string, offset = promptOffsetWidth(value)) {
|
||||||
|
const text = displaySlice(value, 0, offset)
|
||||||
|
for (let index = text.lastIndexOf("/"); index >= 0; index = text.lastIndexOf("/", index - 1)) {
|
||||||
|
const before = index === 0 ? undefined : text[index - 1]
|
||||||
|
const query = text.slice(index)
|
||||||
|
if (before !== undefined && !/\s/.test(before)) continue
|
||||||
|
if (/\s/.test(query) || query.slice(1).includes("/")) return
|
||||||
|
return promptOffsetWidth(text.slice(0, index))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
import path from "path"
|
import path from "path"
|
||||||
import { onMount } from "solid-js"
|
import { onMount } from "solid-js"
|
||||||
import { createStore, produce, unwrap } from "solid-js/store"
|
import { createStore, produce, unwrap } from "solid-js/store"
|
||||||
import type { SessionPromptInput } from "@opencode-ai/client"
|
import type { PromptInput } from "@opencode-ai/schema"
|
||||||
import type { Types } from "effect"
|
import type { Types } from "effect"
|
||||||
import { createSimpleContext } from "../context/helper"
|
import { createSimpleContext } from "../context/helper"
|
||||||
import { useTuiPaths } from "../context/runtime"
|
import { useTuiPaths } from "../context/runtime"
|
||||||
@@ -16,17 +16,17 @@ export type PastedText = {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export type PromptInfo = Types.DeepMutable<Pick<SessionPromptInput, "text" | "files" | "agents">> & {
|
export type PromptInfo = Types.DeepMutable<Pick<PromptInput.Prompt, "text" | "files" | "agents" | "skills">> & {
|
||||||
pasted: PastedText[]
|
pasted: PastedText[]
|
||||||
mode?: "normal" | "shell"
|
mode?: "normal" | "shell"
|
||||||
}
|
}
|
||||||
|
|
||||||
export type PromptPartRef = {
|
export type PromptPartRef = {
|
||||||
type: "file" | "agent" | "pasted"
|
type: "file" | "agent" | "skill" | "pasted"
|
||||||
index: number
|
index: number
|
||||||
}
|
}
|
||||||
|
|
||||||
export const emptyPrompt = (): PromptInfo => ({ text: "", files: [], agents: [], pasted: [] })
|
export const emptyPrompt = (): PromptInfo => ({ text: "", files: [], agents: [], skills: [], pasted: [] })
|
||||||
|
|
||||||
export const MAX_HISTORY_ENTRIES = 50
|
export const MAX_HISTORY_ENTRIES = 50
|
||||||
|
|
||||||
|
|||||||
@@ -52,9 +52,11 @@ export function realignPromptMentions(
|
|||||||
export function realignPromptInputMentions(content: string, input: PromptInput.Prompt): EditablePromptInput {
|
export function realignPromptInputMentions(content: string, input: PromptInput.Prompt): EditablePromptInput {
|
||||||
const files = input.files ?? []
|
const files = input.files ?? []
|
||||||
const agents = input.agents ?? []
|
const agents = input.agents ?? []
|
||||||
|
const skills = input.skills ?? []
|
||||||
const mentions = realignPromptMentions(content, [
|
const mentions = realignPromptMentions(content, [
|
||||||
...files.map((file) => file.mention),
|
...files.map((file) => file.mention),
|
||||||
...agents.map((agent) => agent.mention),
|
...agents.map((agent) => agent.mention),
|
||||||
|
...skills.map((skill) => skill.mention),
|
||||||
])
|
])
|
||||||
const align = <T extends { mention?: PromptMention }>(items: readonly T[] | undefined, offset = 0) =>
|
const align = <T extends { mention?: PromptMention }>(items: readonly T[] | undefined, offset = 0) =>
|
||||||
items?.flatMap((item, index) => {
|
items?.flatMap((item, index) => {
|
||||||
@@ -67,6 +69,7 @@ export function realignPromptInputMentions(content: string, input: PromptInput.P
|
|||||||
text: content,
|
text: content,
|
||||||
files: align(input.files),
|
files: align(input.files),
|
||||||
agents: align(input.agents, files.length),
|
agents: align(input.agents, files.length),
|
||||||
|
skills: align(input.skills, files.length + agents.length),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -89,6 +92,7 @@ export function expandPromptInputPastedText(
|
|||||||
text: expandTrackedPastedText(input.text, ranges),
|
text: expandTrackedPastedText(input.text, ranges),
|
||||||
files: input.files?.map((file) => ({ ...file, mention: shift(file.mention) })),
|
files: input.files?.map((file) => ({ ...file, mention: shift(file.mention) })),
|
||||||
agents: input.agents?.map((agent) => ({ ...agent, mention: shift(agent.mention) })),
|
agents: input.agents?.map((agent) => ({ ...agent, mention: shift(agent.mention) })),
|
||||||
|
skills: input.skills?.map((skill) => ({ ...skill, mention: shift(skill.mention) })),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user