Compare commits

..
49 changed files with 926 additions and 578 deletions
+84 -86
View File
@@ -304,6 +304,11 @@ export const OpenResponsesUsage = Schema.Struct({
})
type OpenResponsesUsage = Schema.Schema.Type<typeof OpenResponsesUsage>
// The spec requires `id` on every output item, but some gateways drop it from
// later item events (Bedrock Mantle renames it to `item_id` on
// `output_item.done` and `response.completed.output`). Decode it as optional
// and let `normalize` recover or mint it once before the parser runs.
// https://www.openresponses.org/specification#extending-items
export const StreamItem = Schema.StructWithRest(
Schema.Struct({
type: Schema.String,
@@ -316,6 +321,7 @@ export const StreamItem = Schema.StructWithRest(
[Schema.Record(Schema.String, Schema.Unknown)],
)
export type StreamItem = Schema.Schema.Type<typeof StreamItem>
export type OutputItem = StreamItem & { readonly id: string }
// The Responses schema puts streaming error details at the top level and
// response failures under `response.error`. WebSocket failures use an
@@ -395,6 +401,7 @@ export const Event = Schema.StructWithRest(
[Schema.Record(Schema.String, Schema.Unknown)],
)
export type Event = Schema.Schema.Type<typeof Event>
export type NormalizedEvent = Event & { readonly item?: OutputItem | null }
export interface ProviderAdapter {
readonly id: string
@@ -416,14 +423,13 @@ export interface ParserState {
readonly name: string
readonly providerMetadataKey: string
readonly tools: ToolStream.State<string>
// Call ids stay independent of item ids, which may be omitted or reused.
// Item ids are response-scoped identities. Keep completed ids tombstoned so
// reconnect replay cannot reopen fragments already emitted downstream.
readonly completedTools: ReadonlySet<string>
readonly hasFunctionCall: boolean
readonly lifecycle: Lifecycle.State
readonly outputItems: Readonly<Record<number, string>>
readonly message: { readonly id: string; readonly phase: MessagePhase | null | undefined } | undefined
// Item ids are response-scoped identities. Keep completed ids tombstoned so
// reconnect replay cannot reopen fragments already emitted downstream.
readonly completedMessages: ReadonlySet<string>
readonly reasoningItems: Readonly<Record<string, ReasoningStreamItem>>
}
@@ -875,9 +881,6 @@ export const providerMetadata = (state: ParserState, metadata: Record<string, un
[state.providerMetadataKey]: metadata,
})
const isReasoningItem = (item: StreamItem): item is StreamItem & { type: "reasoning"; id: string } =>
item.type === "reasoning" && typeof item.id === "string"
export type StepResult = readonly [ParserState, ReadonlyArray<LLMEvent>]
const NO_EVENTS: StepResult["1"] = []
@@ -921,9 +924,34 @@ const joinReasoningText = (parts: ReadonlyArray<string | undefined>) => {
return parts.filter((part) => part !== undefined).join("\n\n")
}
export const outputItemID = (state: ParserState, event: Event) =>
const outputItemID = (state: ParserState, event: Event) =>
event.output_index === undefined ? event.item_id : (state.outputItems[event.output_index] ?? event.item_id)
const ITEM_ID_PREFIX: Readonly<Record<string, string>> = {
message: "msg",
reasoning: "rs",
function_call: "fc",
compaction: "cmp",
}
// An item without an id adopts the id already open in its output slot,
// otherwise it gets a locally minted one.
const resolveItem = (state: ParserState, item: StreamItem, index: number | undefined): OutputItem => ({
...item,
id:
item.id ??
(index === undefined ? undefined : state.outputItems[index]) ??
`${ITEM_ID_PREFIX[item.type] ?? "item"}_${crypto.randomUUID().replaceAll("-", "")}`,
})
// Registered output slots are authoritative for `item_id` routing, and items
// are resolved here so everything downstream can rely on `item.id`.
export const normalize = (state: ParserState, input: Event): NormalizedEvent => ({
...input,
item_id: input.item_id === undefined ? undefined : outputItemID(state, input),
item: input.item ? resolveItem(state, input.item, input.output_index) : input.item,
})
const startReasoningSummaryPart = (state: ParserState, itemID: string, index: number): StepResult => {
const item = state.reasoningItems[itemID]
if (!item?.open || index === 0 || item.summaryParts[index] !== undefined) return [state, NO_EVENTS]
@@ -997,7 +1025,7 @@ export const onReasoningDone = (state: ParserState, event: Event, itemID: string
return onReasoningDelta(state, { ...event, delta: event.text }, itemID)
}
const reasoningMetadata = (state: ParserState, item: StreamItem & { id: string }) =>
const reasoningMetadata = (state: ParserState, item: OutputItem) =>
providerMetadata(state, { itemId: item.id, reasoningEncryptedContent: item.encrypted_content ?? null })
// Responses APIs normally stream reasoning items in this order:
@@ -1010,18 +1038,18 @@ const reasoningMetadata = (state: ParserState, item: StreamItem & { id: string }
// `onOutputItemAdded` seeds the per-item entry, while each later part start is
// also an implicit boundary for the previous part. This keeps the common event
// lifecycle ordered when a compatible provider omits or delays a part-done event.
const onOutputItemAdded = (state: ParserState, event: Event): StepResult => {
const onOutputItemAdded = (state: ParserState, event: NormalizedEvent): StepResult => {
const item = event.item
if (item?.type === "message" && item.id !== undefined) {
const itemID = item.id
if (state.completedMessages.has(itemID)) return [state, NO_EVENTS]
if (!item) return [state, NO_EVENTS]
if (item.type === "message") {
if (state.completedMessages.has(item.id)) return [state, NO_EVENTS]
const phase = messagePhase(item.phase)
const completedMessages = new Set(state.completedMessages)
if (state.message !== undefined && state.message.id !== itemID) completedMessages.add(state.message.id)
if (state.message !== undefined && state.message.id !== item.id) completedMessages.add(state.message.id)
// A new message closes earlier messages, including ones that never streamed.
const events: LLMEvent[] = []
const lifecycle = [...state.lifecycle.text]
.filter((id) => id !== itemID)
.filter((id) => id !== item.id)
.reduce((lifecycle, id) => {
completedMessages.add(id)
const openPhase = state.message?.id === id ? state.message.phase : undefined
@@ -1038,14 +1066,14 @@ const onOutputItemAdded = (state: ParserState, event: Event): StepResult => {
lifecycle,
completedMessages,
message: {
id: itemID,
phase: phase === undefined && state.message?.id === itemID ? state.message.phase : phase,
id: item.id,
phase: phase === undefined && state.message?.id === item.id ? state.message.phase : phase,
},
},
events,
]
}
if (item && isReasoningItem(item)) {
if (item.type === "reasoning") {
if (state.reasoningItems[item.id] !== undefined) return [state, NO_EVENTS]
const events: LLMEvent[] = []
return [
@@ -1065,18 +1093,16 @@ const onOutputItemAdded = (state: ParserState, event: Event): StepResult => {
events,
]
}
if (item?.type !== "function_call" || !item.call_id) return [state, NO_EVENTS]
const id = item.id ?? item.call_id
if (Object.values(state.tools).some((tool) => tool?.id === item.call_id) || state.completedTools.has(item.call_id))
return [state, NO_EVENTS]
const metadata = item.id !== undefined ? providerMetadata(state, { itemId: item.id }) : undefined
if (item.type !== "function_call" || !item.call_id) return [state, NO_EVENTS]
if (state.tools[item.id] !== undefined || state.completedTools.has(item.id)) return [state, NO_EVENTS]
const metadata = providerMetadata(state, { itemId: item.id })
const events: LLMEvent[] = []
const lifecycle = Lifecycle.stepStart(state.lifecycle, events)
return [
{
...state,
lifecycle,
tools: ToolStream.start(state.tools, id, {
tools: ToolStream.start(state.tools, item.id, {
id: item.call_id,
name: item.name ?? "",
input: item.arguments ?? "",
@@ -1148,13 +1174,13 @@ const onFunctionCallArgumentsDelta = Effect.fn("OpenResponses.onFunctionCallArgu
const onOutputItemDone = Effect.fn("OpenResponses.onOutputItemDone")(function* (
state: ParserState,
item: Event["item"],
item: NormalizedEvent["item"],
) {
if (!item) return [state, NO_EVENTS] satisfies StepResult
if (item.type === "compaction") {
if (!item.id || typeof item.encrypted_content !== "string")
return yield* ProviderShared.eventError(state.id, "Compaction output is missing its id or encrypted content")
if (typeof item.encrypted_content !== "string")
return yield* ProviderShared.eventError(state.id, "Compaction output is missing its encrypted content")
if (state.completedCompactions.has(item.id)) return [state, NO_EVENTS] satisfies StepResult
const events: LLMEvent[] = []
const lifecycle = Lifecycle.stepStart(state.lifecycle, events)
@@ -1171,7 +1197,7 @@ const onOutputItemDone = Effect.fn("OpenResponses.onOutputItemDone")(function* (
] satisfies StepResult
}
if (item.type === "message" && item.id !== undefined) {
if (item.type === "message") {
if (state.completedMessages.has(item.id)) return [state, NO_EVENTS] satisfies StepResult
const completedMessages = new Set(state.completedMessages)
completedMessages.add(item.id)
@@ -1204,36 +1230,23 @@ const onOutputItemDone = Effect.fn("OpenResponses.onOutputItemDone")(function* (
if (item.type === "function_call") {
if (!item.call_id || !item.name) return [state, NO_EVENTS] satisfies StepResult
const callID = item.call_id
if (state.completedTools.has(callID)) return [state, NO_EVENTS] satisfies StepResult
const metadata = item.id !== undefined ? providerMetadata(state, { itemId: item.id }) : undefined
const fallback = item.id ?? callID
// Match the pending tool by call id so item events that disagree on
// whether `item.id` is present still resolve the same call.
const registered =
state.tools[fallback] !== undefined
? fallback
: Object.keys(state.tools).find((key) => state.tools[key]?.id === callID)
const id = registered ?? fallback
const tools =
registered !== undefined
? state.tools
: ToolStream.start(state.tools, id, {
id: callID,
name: item.name,
providerMetadata: metadata,
})
if (state.completedTools.has(item.id)) return [state, NO_EVENTS] satisfies StepResult
const metadata = providerMetadata(state, { itemId: item.id })
const registered = state.tools[item.id] !== undefined
const tools = registered
? state.tools
: ToolStream.start(state.tools, item.id, { id: item.call_id, name: item.name, providerMetadata: metadata })
const result =
item.arguments === undefined
? yield* ToolStream.finish(state.id, tools, id)
: yield* ToolStream.finishWithInput(state.id, tools, id, item.arguments)
? yield* ToolStream.finish(state.id, tools, item.id)
: yield* ToolStream.finishWithInput(state.id, tools, item.id, item.arguments)
const events: LLMEvent[] = []
const finished = result.events ?? []
// A done-only call never streamed a start event, so open its lifecycle here.
const resultEvents =
registered !== undefined || finished.length === 0
registered || finished.length === 0
? finished
: [LLMEvent.toolInputStart({ id: callID, name: item.name, providerMetadata: metadata }), ...finished]
: [LLMEvent.toolInputStart({ id: item.call_id, name: item.name, providerMetadata: metadata }), ...finished]
const lifecycle = resultEvents.length ? Lifecycle.stepStart(state.lifecycle, events) : state.lifecycle
events.push(...resultEvents)
return [
@@ -1244,13 +1257,13 @@ const onOutputItemDone = Effect.fn("OpenResponses.onOutputItemDone")(function* (
resultEvents.some((event) => LLMEvent.is.toolCall(event) || LLMEvent.is.toolInputError(event)) ||
state.hasFunctionCall,
tools: result.tools,
completedTools: new Set([...state.completedTools, callID]),
completedTools: new Set([...state.completedTools, item.id]),
},
events,
] satisfies StepResult
}
if (isReasoningItem(item)) {
if (item.type === "reasoning") {
if (state.reasoningItems[item.id]?.open === false) return [state, NO_EVENTS] satisfies StepResult
const metadata = reasoningMetadata(state, item)
const summaryParts: ReadonlyArray<unknown> = Array.isArray(item.summary) ? item.summary : []
@@ -1334,21 +1347,17 @@ const onResponseFinish = Effect.fn("OpenResponses.onResponseFinish")(function* (
let current = state
const events: LLMEvent[] = []
if (event.type === "response.completed") {
for (const item of event.response?.output ?? []) {
if (item.type !== "compaction" && item.type !== "function_call") continue
if (item.type === "compaction") {
// Terminal recovery cannot insert a checkpoint before already-emitted content.
if (state.lifecycle.stepStarted && !state.completedCompactions.has(item.id ?? ""))
return yield* ProviderShared.eventError(
state.id,
"Cannot recover a compaction checkpoint after output has been emitted",
)
}
if (
item.type === "function_call" &&
(!item.call_id || !Object.values(current.tools).some((tool) => tool?.id === item.call_id))
)
continue
// An output item's array position is its output index.
for (const item of (event.response?.output ?? []).map((item, index) => resolveItem(state, item, index))) {
// Terminal recovery cannot insert a checkpoint before already-emitted content.
if (item.type === "compaction" && state.lifecycle.stepStarted && !state.completedCompactions.has(item.id))
return yield* ProviderShared.eventError(
state.id,
"Cannot recover a compaction checkpoint after output has been emitted",
)
const recoverable =
item.type === "compaction" || (item.type === "function_call" && current.tools[item.id] !== undefined)
if (!recoverable) continue
const [next, emitted] = yield* onOutputItemDone(current, item)
current = next
events.push(...emitted)
@@ -1415,12 +1424,9 @@ export const providerFailure = (event: Event, fallback: string, body = ProviderS
return new AIError({ reason })
}
export const step = (state: ParserState, input: Event) => {
// The OpenAPI requires string IDs but imposes no minLength; empty is not missing.
const event =
input.item_id !== undefined && outputItemID(state, input) !== input.item_id
? { ...input, item_id: outputItemID(state, input) }
: input
// Callers must pass events through `normalize` first. The OpenAPI requires
// string IDs but imposes no minLength; empty is not missing.
export const step = (state: ParserState, event: NormalizedEvent) => {
if (event.type === "response.output_text.delta" || event.type === "response.output_text.done") {
if (event.item_id === undefined) return ProviderShared.eventError(state.id, `${event.type} is missing item_id`)
return Effect.succeed(
@@ -1460,20 +1466,16 @@ export const step = (state: ParserState, input: Event) => {
? Effect.succeed(onReasoningSummaryPartDone(state, event))
: ProviderShared.eventError(state.id, `${event.type} is missing item_id`)
if (event.type === "response.output_item.added") {
if (event.item?.type === "message" && event.item.id === undefined)
return ProviderShared.eventError(state.id, `${event.type} message is missing id`)
if (
event.item &&
isReasoningItem(event.item) &&
event.item?.type === "reasoning" &&
state.reasoningItems[event.item.id] === undefined &&
state.lifecycle.reasoning.size > 0
)
return ProviderShared.eventError(state.id, `${event.type} started reasoning before the previous item ended`)
const id = event.item?.id ?? (event.item?.type === "function_call" ? event.item.call_id : undefined)
return Effect.succeed(
onOutputItemAdded(
event.output_index !== undefined && id !== undefined
? { ...state, outputItems: { ...state.outputItems, [event.output_index]: id } }
event.output_index !== undefined && event.item
? { ...state, outputItems: { ...state.outputItems, [event.output_index]: event.item.id } }
: state,
event,
),
@@ -1483,11 +1485,7 @@ export const step = (state: ParserState, input: Event) => {
return event.item_id !== undefined
? onFunctionCallArgumentsDelta(state, event)
: ProviderShared.eventError(state.id, `${event.type} is missing item_id`)
if (event.type === "response.output_item.done") {
if (event.item?.type === "message" && event.item.id === undefined)
return ProviderShared.eventError(state.id, `${event.type} message is missing id`)
return onOutputItemDone(state, event.item)
}
if (event.type === "response.output_item.done") return onOutputItemDone(state, event.item)
if (event.type === "response.completed" || event.type === "response.incomplete") return onResponseFinish(state, event)
if (event.type === "response.failed") return providerFailure(event, `${state.name} response failed`)
if (event.type === "error")
@@ -1537,7 +1535,7 @@ export const protocol = Protocol.make({
stream: {
event: Protocol.jsonEvent(Event),
initial,
step,
step: (state: ParserState, event: Event) => step(state, normalize(state, event)),
terminal,
},
})
@@ -201,12 +201,11 @@ const HOSTED_TOOLS = {
},
} as const satisfies ResponsesHostedTools.Definitions
const step = (state: OpenResponses.ParserState, event: OpenResponses.Event) => {
const step = (state: OpenResponses.ParserState, input: OpenResponses.Event) => {
const event = OpenResponses.normalize(state, input)
if (event.type === "response.reasoning_text.delta")
return event.item_id !== undefined
? Effect.succeed(
OpenResponses.onReasoningDelta(state, event, OpenResponses.outputItemID(state, event) ?? event.item_id),
)
? Effect.succeed(OpenResponses.onReasoningDelta(state, event, event.item_id))
: ProviderShared.eventError(ADAPTER, `${event.type} is missing item_id`)
if (event.type === "response.output_item.done" && event.item && ResponsesHostedTools.isItem(event.item, HOSTED_TOOLS))
return ResponsesHostedTools.onDone(state, event.item, HOSTED_TOOLS)
@@ -3,8 +3,7 @@ import { LLMEvent, type AIError, type ToolResultPart } from "../../schema/index.
import { OpenResponses } from "../open-responses.js"
import { Lifecycle } from "./lifecycle.js"
export type Item = OpenResponses.StreamItem & {
readonly id: string
export type Item = OpenResponses.OutputItem & {
readonly status?: string
readonly action?: unknown
readonly queries?: unknown
@@ -27,8 +26,8 @@ export interface Definition {
export type Definitions = Readonly<Record<string, Definition>>
export const isItem = <Tools extends Definitions>(item: OpenResponses.StreamItem, tools: Tools): item is Item =>
item.type in tools && typeof item.id === "string" && item.id.length > 0
export const isItem = <Tools extends Definitions>(item: OpenResponses.OutputItem, tools: Tools): item is Item =>
item.type in tools
export const onDone: (
state: OpenResponses.ParserState,
+2 -1
View File
@@ -69,7 +69,8 @@ const HOSTED_TOOLS = {
// Grok speaks the standard Responses reasoning dialect (`reasoning_summary_text.*`,
// handled by the baseline); only its hosted tool vocabulary differs.
const step = (state: OpenResponses.ParserState, event: OpenResponses.Event) => {
const step = (state: OpenResponses.ParserState, input: OpenResponses.Event) => {
const event = OpenResponses.normalize(state, input)
if (event.type === "response.output_item.done" && event.item && ResponsesHostedTools.isItem(event.item, HOSTED_TOOLS))
return ResponsesHostedTools.onDone(state, event.item, HOSTED_TOOLS)
return OpenResponses.step(state, event)
+8 -5
View File
@@ -125,12 +125,15 @@ testEffect(
response: { output: [{ type: "compaction", encrypted_content: "opaque" }] },
}),
),
).effect("rejects terminal checkpoints missing an id", () =>
).effect("mints an id for terminal checkpoints that omit one", () =>
Effect.gen(function* () {
const error = yield* LLMClient.generate(
const response = yield* LLMClient.generate(
LLM.request({ model: OpenAI.configure({ apiKey: "test" }).responses("fixture"), prompt: "hello" }),
).pipe(Effect.flip)
expect(error.reason._tag).toBe("InvalidProviderOutput")
expect(error.message).toContain("missing its id")
)
const part = response.message.content[0]
expect(part?.type).toBe("compaction")
if (part?.type !== "compaction") return
expect(part.id).toMatch(/^cmp_[0-9a-f]{32}$/)
expect(part.encrypted).toBe("opaque")
}),
)
@@ -329,69 +329,126 @@ describe("Open Responses basic-item lifecycles", () => {
])
}),
)
;[undefined, "fc_1"].forEach((id) => {
it.effect(`opens and closes a done-only tool ${id === undefined ? "without" : "with"} an item id`, () =>
Effect.gen(function* () {
const item = {
type: "function_call",
...(id === undefined ? {} : { id }),
call_id: "call_1",
name: "lookup",
arguments: '{"query":"weather"}',
}
const events = yield* collect(
{ type: "response.output_item.done", item },
{ type: "response.output_item.done", item: { ...item, id: "fc_1" } },
{ type: "response.output_item.added", item },
completed,
)
const providerMetadata = id === undefined ? undefined : { "openai-compatible": { itemId: id } }
expect(events.filter((event) => event.type.startsWith("tool-"))).toEqual([
{ type: "tool-input-start", id: "call_1", name: "lookup", providerMetadata },
{ type: "tool-input-end", id: "call_1", name: "lookup", providerMetadata },
{ type: "tool-call", id: "call_1", name: "lookup", input: { query: "weather" }, providerMetadata },
])
expect(events.filter(LLMEvent.is.finish)).toEqual([
{
type: "finish",
reason: { normalized: "tool-calls", raw: undefined },
providerMetadata: { "openai-compatible": { responseId: "resp_1", serviceTier: undefined } },
// Captured from Bedrock Mantle (openai.gpt-oss-120b): the terminal function_call
// items rename `id` to `item_id` and carry a stray `output_index`.
it.effect("recovers a terminal function_call id from its output slot", () =>
Effect.gen(function* () {
const terminal = {
type: "function_call",
item_id: "fc_828bee50dee1d029",
call_id: "call_bc1eb4b42e70ee53",
name: "get_weather",
arguments: '{\n "city": "Paris"\n}',
output_index: 1,
status: "completed",
}
const events = yield* collect(
{
type: "response.output_item.added",
output_index: 0,
item: { type: "reasoning", id: "msg_879a68b589198b4c" },
},
{ type: "response.output_item.done", output_index: 0, item: { type: "reasoning", id: "msg_879a68b589198b4c" } },
{
type: "response.output_item.added",
output_index: 1,
item: {
type: "function_call",
id: "fc_828bee50dee1d029",
call_id: "call_bc1eb4b42e70ee53",
name: "get_weather",
arguments: "",
status: "in_progress",
},
])
}),
)
},
{
type: "response.function_call_arguments.delta",
output_index: 1,
item_id: "fc_828bee50dee1d029",
delta: '{\n "city": "Paris"\n}',
},
{
type: "response.function_call_arguments.done",
output_index: 1,
item_id: "fc_828bee50dee1d029",
arguments: '{\n "city": "Paris"\n}',
},
{ type: "response.output_item.done", output_index: 1, item: terminal },
{
type: "response.completed",
response: { id: "resp_1", output: [{ type: "reasoning", id: "msg_879a68b589198b4c" }, terminal] },
},
)
const providerMetadata = { "openai-compatible": { itemId: "fc_828bee50dee1d029" } }
expect(events.filter((event) => event.type.startsWith("tool-"))).toEqual([
{ type: "tool-input-start", id: "call_bc1eb4b42e70ee53", name: "get_weather", providerMetadata },
{
type: "tool-input-delta",
id: "call_bc1eb4b42e70ee53",
name: "get_weather",
text: '{\n "city": "Paris"\n}',
input: { city: "Paris" },
},
{ type: "tool-input-end", id: "call_bc1eb4b42e70ee53", name: "get_weather", providerMetadata },
{
type: "tool-call",
id: "call_bc1eb4b42e70ee53",
name: "get_weather",
input: { city: "Paris" },
providerMetadata,
},
])
}),
)
it.effect(`deduplicates a pending call whose item id is ${id === undefined ? "introduced" : "omitted"} later`, () =>
Effect.gen(function* () {
const item = { type: "function_call", call_id: "call_1", name: "lookup" }
const first = { ...item, ...(id === undefined ? {} : { id }) }
const duplicate = { ...item, ...(id === undefined ? { id: "fc_1" } : {}) }
const events = yield* collect(
{ type: "response.output_item.added", item: first },
{ type: "response.function_call_arguments.delta", item_id: id ?? "call_1", delta: '{"query":"weather"}' },
{ type: "response.output_item.added", item: duplicate },
{ type: "response.output_item.done", item: duplicate },
{ type: "response.output_item.done", item: first },
{ type: "response.output_item.added", item: duplicate },
completed,
)
// Identity metadata comes from the first admission, not the duplicate.
const providerMetadata = id === undefined ? undefined : { "openai-compatible": { itemId: id } }
expect(events.filter((event) => event.type.startsWith("tool-"))).toEqual([
{ type: "tool-input-start", id: "call_1", name: "lookup", providerMetadata },
{
type: "tool-input-delta",
id: "call_1",
name: "lookup",
text: '{"query":"weather"}',
input: { query: "weather" },
},
{ type: "tool-input-end", id: "call_1", name: "lookup", providerMetadata },
{ type: "tool-call", id: "call_1", name: "lookup", input: { query: "weather" }, providerMetadata },
])
}),
)
})
it.effect("mints an id for a done-only tool that never had one", () =>
Effect.gen(function* () {
const events = yield* collect(
{
type: "response.output_item.done",
output_index: 0,
item: { type: "function_call", call_id: "call_1", name: "lookup", arguments: '{"query":"weather"}' },
},
completed,
)
const call = events.find(LLMEvent.is.toolCall)
expect(call).toMatchObject({ id: "call_1", name: "lookup", input: { query: "weather" } })
expect(call?.providerMetadata?.["openai-compatible"]).toMatchObject({
itemId: expect.stringMatching(/^fc_[0-9a-f]{32}$/),
})
}),
)
it.effect("opens and closes a done-only tool once", () =>
Effect.gen(function* () {
const item = {
type: "function_call",
id: "fc_1",
call_id: "call_1",
name: "lookup",
arguments: '{"query":"weather"}',
}
const events = yield* collect(
{ type: "response.output_item.done", item },
{ type: "response.output_item.done", item },
{ type: "response.output_item.added", item },
completed,
)
const providerMetadata = { "openai-compatible": { itemId: "fc_1" } }
expect(events.filter((event) => event.type.startsWith("tool-"))).toEqual([
{ type: "tool-input-start", id: "call_1", name: "lookup", providerMetadata },
{ type: "tool-input-end", id: "call_1", name: "lookup", providerMetadata },
{ type: "tool-call", id: "call_1", name: "lookup", input: { query: "weather" }, providerMetadata },
])
expect(events.filter(LLMEvent.is.finish)).toEqual([
{
type: "finish",
reason: { normalized: "tool-calls", raw: undefined },
providerMetadata: { "openai-compatible": { responseId: "resp_1", serviceTier: undefined } },
},
])
}),
)
it.effect("recovers pending calls without reconciling terminal reasoning", () =>
Effect.gen(function* () {
@@ -436,21 +493,6 @@ describe("Open Responses basic-item lifecycles", () => {
}),
)
it.effect("preserves call identity and pending order when an item id is reused", () =>
Effect.gen(function* () {
const first = { type: "function_call", id: "fc_1", call_id: "call_1", name: "lookup", arguments: "{}" }
const events = yield* collect(
{ type: "response.output_item.added", item: first },
{ type: "response.output_item.added", item: { ...first, id: "fc_2", call_id: "call_2" } },
{ type: "response.output_item.done", item: first },
{ type: "response.output_item.added", item: { ...first, call_id: "call_3" } },
{ type: "response.output_item.done", item: first },
completed,
)
expect(events.filter(LLMEvent.is.toolCall).map((event) => event.id)).toEqual(["call_1", "call_2", "call_3"])
}),
)
it.effect("keeps text and reasoning identities separate even with empty item ids", () =>
Effect.gen(function* () {
const events = yield* collect(
@@ -500,14 +542,15 @@ describe("Open Responses basic-item lifecycles", () => {
{ type: "response.output_text.delta", item_id: "msg_1", delta: "Answer" },
{
type: "response.output_item.added",
item: { type: "function_call", call_id: "call_1", name: "lookup", arguments: "{}" },
item: { type: "function_call", id: "fc_1", call_id: "call_1", name: "lookup", arguments: "{}" },
},
completed,
)
// Generic terminal closure does not repeat the message's phase metadata.
const providerMetadata = { "openai-compatible": { itemId: "fc_1" } }
expect(events.slice(4, -2)).toEqual([
{ type: "tool-input-end", id: "call_1", name: "lookup" },
{ type: "tool-call", id: "call_1", name: "lookup", input: {} },
{ type: "tool-input-end", id: "call_1", name: "lookup", providerMetadata },
{ type: "tool-call", id: "call_1", name: "lookup", input: {}, providerMetadata },
{ type: "text-end", id: "msg_1" },
])
}),
@@ -586,23 +586,21 @@ describe("Open Responses-compatible route", () => {
Effect.gen(function* () {
yield* Effect.forEach(["response.output_item.added", "response.output_item.done"], (type) =>
Effect.forEach(fixtures, (fixture) =>
Effect.forEach(
fixture.item.type === "message" ? [undefined, null, 0, false, {}, []] : [null, 0, false, {}, []],
(id) =>
Effect.gen(function* () {
const error = yield* LLMClient.generate(request).pipe(
Effect.provide(
fixedResponse(
sseEvents(
{ type, item: { ...fixture.item, id } },
{ type: "response.completed", response: { id: "resp_1" } },
),
Effect.forEach([null, 0, false, {}, []], (id) =>
Effect.gen(function* () {
const error = yield* LLMClient.generate(request).pipe(
Effect.provide(
fixedResponse(
sseEvents(
{ type, item: { ...fixture.item, id } },
{ type: "response.completed", response: { id: "resp_1" } },
),
),
Effect.flip,
)
expect(error.reason._tag).toBe("InvalidProviderOutput")
}),
),
Effect.flip,
)
expect(error.reason._tag).toBe("InvalidProviderOutput")
}),
),
),
)
@@ -610,43 +608,6 @@ describe("Open Responses-compatible route", () => {
)
})
it.effect("streams function calls without optional item ids through the shared baseline", () =>
Effect.gen(function* () {
const model = configure({
apiKey: "test-key",
baseURL: "https://responses.example.test/v1",
provider: "example",
}).model("example-model")
const item = { type: "function_call", call_id: "call_1", name: "lookup", arguments: "" }
const response = yield* LLMClient.generate(LLM.request({ model, prompt: "Look it up." })).pipe(
Effect.provide(
fixedResponse(
sseEvents(
{ type: "response.output_item.added", output_index: 1, item },
{
type: "response.function_call_arguments.delta",
output_index: 1,
item_id: "opaque_item",
delta: '{"query":"shared"}',
},
{
type: "response.output_item.done",
output_index: 1,
item: { ...item, arguments: '{"query":"complete"}' },
},
{ type: "response.completed", response: { id: "resp_1" } },
),
),
),
)
expect(response.events.filter(LLMEvent.is.toolCall)).toEqual([
expect.objectContaining({ id: "call_1", name: "lookup", input: { query: "complete" } }),
])
expect(response.events.find(LLMEvent.is.toolCall)?.providerMetadata).toBeUndefined()
}),
)
it.effect("finalizes pending function calls from completed response output", () =>
Effect.gen(function* () {
const model = configure({
@@ -469,7 +469,7 @@ describe("OpenAI Responses route", () => {
}),
)
it.effect("continues an item-id-less tool call with only the new tool output", () =>
it.effect("continues a streamed tool call with only the new tool output", () =>
Effect.gen(function* () {
const firstRequest = {
type: "response.create",
@@ -485,6 +485,7 @@ describe("OpenAI Responses route", () => {
type: "response.output_item.done",
item: {
type: "function_call",
id: "fc_1",
status: "completed",
call_id: "call_1",
name: "weather",
@@ -2129,47 +2130,6 @@ describe("OpenAI Responses route", () => {
}),
)
it.effect("routes item-id-less function arguments by output index and prefers item completion", () =>
Effect.gen(function* () {
const item = { type: "function_call", call_id: "call_1", name: "lookup", arguments: "" }
const response = yield* LLMClient.generate(request).pipe(
Effect.provide(
fixedResponse(
sseEvents(
{ type: "response.output_item.added", output_index: 2, item },
{
type: "response.function_call_arguments.delta",
output_index: 2,
item_id: "opaque_delta",
delta: '{"query":"streamed"}',
},
{
type: "response.function_call_arguments.done",
output_index: 2,
item_id: "opaque_done",
arguments: '{"query":"arguments-done"}',
},
{
type: "response.output_item.done",
output_index: 2,
item: { ...item, arguments: '{"query":"output-item-done"}' },
},
{ type: "response.completed", response: { id: "resp_1" } },
),
),
),
)
expect(response.events.filter((event) => event.type === "tool-input-delta")).toMatchObject([
{ id: "call_1", text: '{"query":"streamed"}' },
])
expect(response.events.filter(LLMEvent.is.toolCall)).toEqual([
expect.objectContaining({ id: "call_1", name: "lookup", input: { query: "output-item-done" } }),
])
expect(response.events.find(LLMEvent.is.toolCall)?.providerMetadata).toBeUndefined()
}),
)
it.effect("routes reasoning summary events by output index", () =>
Effect.gen(function* () {
const response = yield* LLMClient.generate(request).pipe(
@@ -2389,7 +2349,7 @@ describe("OpenAI Responses route", () => {
{
type: "response.output_item.added",
output_index: 0,
item: { type: "function_call", call_id: "call_1", name: "lookup", arguments: "" },
item: { type: "function_call", id: "fc_1", call_id: "call_1", name: "lookup", arguments: "" },
},
event,
{ type: "response.completed", response: { id: "resp_1" } },
@@ -2931,14 +2891,10 @@ describe("OpenAI Responses route", () => {
arguments: '{"query":"weather"}',
},
},
// Duplicates that drop the item id still resolve the same call.
{
type: "response.output_item.done",
item: { type: "function_call", call_id: "call_1", name: "lookup", arguments: '{"query":"weather"}' },
},
// A completed item that is re-added stays closed.
{
type: "response.output_item.added",
item: { type: "function_call", call_id: "call_1", name: "lookup", arguments: "" },
item: { type: "function_call", id: "fc_1", call_id: "call_1", name: "lookup", arguments: "" },
},
{ type: "response.completed", response: { id: "resp_1" } },
),
@@ -3793,43 +3749,6 @@ describe("OpenAI Responses route", () => {
}),
)
it.effect("finalizes and replays a completed function call without an optional item id", () =>
Effect.gen(function* () {
const response = yield* LLMClient.generate(request).pipe(
Effect.provide(
fixedResponse(
sseEvents(
{
type: "response.output_item.done",
item: { type: "function_call", call_id: "call_1", name: "lookup", arguments: '{"query":"weather"}' },
},
{ type: "response.completed", response: { id: "resp_1" } },
),
),
),
)
expect(response.events.filter(LLMEvent.is.toolCall)).toEqual([
expect.objectContaining({ id: "call_1", name: "lookup", input: { query: "weather" } }),
])
expect(response.events.find(LLMEvent.is.toolCall)?.providerMetadata).toBeUndefined()
const prepared = yield* compileRequest(
LLM.request({
model,
messages: [
response.message,
Message.tool({ id: "call_1", name: "lookup", resultType: "json", result: { forecast: "sunny" } }),
],
}),
)
expect(prepared.body.input).toEqual([
{ type: "function_call", call_id: "call_1", name: "lookup", arguments: '{"query":"weather"}' },
{ type: "function_call_output", call_id: "call_1", output: '{"forecast":"sunny"}' },
])
}),
)
it.effect("emits only missing function arguments from the arguments done event", () =>
Effect.gen(function* () {
const body = sseEvents(
@@ -4017,7 +3936,7 @@ describe("OpenAI Responses route", () => {
}),
)
it.effect("uses completed response output when item completion and its terminal item id are missing", () =>
it.effect("uses completed response output when output item completion is missing", () =>
Effect.gen(function* () {
const body = sseEvents(
{
@@ -4032,6 +3951,7 @@ describe("OpenAI Responses route", () => {
output: [
{
type: "function_call",
id: "fc_item_1",
call_id: "call_1",
name: "lookup",
arguments: '{"query":"weather"}',
@@ -4053,37 +3973,6 @@ describe("OpenAI Responses route", () => {
}),
)
it.effect("reconciles an item-id-less pending function call from completed response output", () =>
Effect.gen(function* () {
const item = { type: "function_call", call_id: "call_1", name: "lookup", arguments: "" }
const response = yield* LLMClient.generate(request).pipe(
Effect.provide(
fixedResponse(
sseEvents(
{ type: "response.output_item.added", output_index: 0, item },
{
type: "response.function_call_arguments.delta",
output_index: 0,
item_id: "opaque_delta",
delta: '{"query":"partial',
},
{
type: "response.completed",
response: { id: "resp_1", output: [{ ...item, arguments: '{"query":"complete"}' }] },
},
),
),
),
)
expect(response.events.filter(LLMEvent.is.toolCall)).toEqual([
expect.objectContaining({ id: "call_1", name: "lookup", input: { query: "complete" } }),
])
expect(response.events.find(LLMEvent.is.toolCall)?.providerMetadata).toBeUndefined()
expect(response.events.filter(LLMEvent.is.toolInputEnd)).toHaveLength(1)
}),
)
it.effect("lets completed response output override arguments done", () =>
Effect.gen(function* () {
const body = sseEvents(
-2
View File
@@ -230,8 +230,6 @@ export function createServerSyncContextInner(serverSDK: ServerSDK, data: Data) {
children.mark(key)
if (event.type === "config.updated" || event.type === "agent.updated") queue.push(key)
if (event.type === "worktree.updated") void bootstrap.refetch()
if (event.type === "reference.updated" && children.active(key))
void data.location.reference.sync({ directory: key }).catch(() => undefined)
})
onCleanup(unsub)
@@ -1634,7 +1634,7 @@ export function make(options: ClientOptions) {
path: `/api/skill`,
query: { location: input?.["location"] },
successStatus: 200,
declaredStatuses: [400, 401],
declaredStatuses: [400, 401, 500],
empty: false,
},
requestOptions,
@@ -2488,6 +2488,15 @@ export type PermissionNotFoundError = {
export const isPermissionNotFoundError = (value: unknown): value is PermissionNotFoundError =>
typeof value === "object" && value !== null && "_tag" in value && value["_tag"] === "PermissionNotFoundError"
export type PluginCallbackError = {
readonly _tag: "PluginCallbackError"
readonly pluginID: string
readonly operation: "skill.transform"
readonly message: string
}
export const isPluginCallbackError = (value: unknown): value is PluginCallbackError =>
typeof value === "object" && value !== null && "_tag" in value && value["_tag"] === "PluginCallbackError"
export type RpcError = {
readonly _tag: "RpcError"
readonly type: string
+2 -2
View File
@@ -1180,8 +1180,8 @@ export function createData(config: CreateDataInput) {
}))
break
case "reference.updated":
result.location.reference.invalidate()
void result.location.reference.sync()
result.location.reference.invalidate(location)
void result.location.reference.sync(location)
break
case "integration.updated":
result.location.integration.invalidate(location)
+17
View File
@@ -15,6 +15,23 @@ import {
const synced = { type: "log.synced" as const, aggregateID: "ses_test", seq: Event.Seq.make(1) }
test("skill.list decodes a declared plugin callback failure", async () => {
const failure = {
_tag: "PluginCallbackError",
pluginID: "broken-skills",
operation: "skill.transform",
message: 'Plugin "broken-skills" failed during skill.transform. Check server logs for details.',
}
const httpClient = HttpClient.make((request) =>
Effect.succeed(HttpClientResponse.fromWeb(request, Response.json(failure, { status: 500 }))),
)
const error = await Effect.gen(function* () {
const client = yield* OpenCode.make({ baseUrl: "http://localhost:3000" })
return yield* client.skill.list().pipe(Effect.flip)
}).pipe(Effect.provideService(HttpClient.HttpClient, httpClient), Effect.runPromise)
expect(error).toMatchObject(failure)
})
test("health.get decodes the readiness response", async () => {
const httpClient = HttpClient.make((request) =>
Effect.succeed(HttpClientResponse.fromWeb(request, Response.json({ healthy: true, version: "old", pid: 123 }))),
+16 -1
View File
@@ -1,5 +1,20 @@
import { expect, test } from "bun:test"
import { isSessionNotFoundError, isUnauthorizedError, OpenCode } from "../src/promise/index"
import { isPluginCallbackError, isSessionNotFoundError, isUnauthorizedError, OpenCode } from "../src/promise/index"
test("skill.list preserves a declared plugin callback failure", async () => {
const failure = {
_tag: "PluginCallbackError",
pluginID: "broken-skills",
operation: "skill.transform",
message: 'Plugin "broken-skills" failed during skill.transform. Check server logs for details.',
}
const client = OpenCode.make({
baseUrl: "http://localhost:3000",
fetch: async () => Response.json(failure, { status: 500 }),
})
await expect(client.skill.list()).rejects.toEqual(failure)
expect(isPluginCallbackError(failure)).toBe(true)
})
test("exposes every standard HTTP API group", () => {
const client = OpenCode.make({ baseUrl: "http://localhost:3000" })
+60
View File
@@ -409,6 +409,66 @@ test("refreshes global credential events across every loaded location and worksp
}
})
test("refreshes references for the location an update names", async () => {
const listeners = new Set<Parameters<CreateDataInput["event"]["listen"]>[0]>()
const requests: URL[] = []
const api = OpenCode.make({
baseUrl: "http://opencode.local",
fetch: async (input, init) => {
const request = input instanceof Request ? input : new Request(input, init)
const url = new URL(request.url)
requests.push(url)
const directory = url.searchParams.get("location[directory]") ?? "/project"
return Response.json({
location: {
directory,
workspaceID: url.searchParams.get("location[workspace]") ?? undefined,
project: { id: "project", directory, canonical: directory },
},
data: [],
})
},
})
const setup = createRoot((dispose) => ({
data: createData({
api: () => api,
directory: "/project",
event: {
on: () => () => {},
listen(handler) {
listeners.add(handler)
return () => listeners.delete(handler)
},
},
connection: { status: () => "connected" },
}),
dispose,
}))
const other = { directory: "/other", workspaceID: "workspace-other" }
try {
await Promise.all([setup.data.location.reference.sync(), setup.data.location.reference.sync(other)])
requests.length = 0
const updated: OpenCodeEvent = {
id: "evt_reference.updated",
created: 1,
type: "reference.updated",
location: other,
data: {},
}
listeners.forEach((listener) => listener({ name: updated.type, details: updated }))
await wait(() => requests.length === 1)
expect([
requests[0]!.pathname,
requests[0]!.searchParams.get("location[directory]"),
requests[0]!.searchParams.get("location[workspace]"),
]).toEqual(["/api/reference", "/other", "workspace-other"])
} finally {
setup.dispose()
}
})
test("reports optimistic sessions as creating until the request settles", async () => {
const release = Promise.withResolvers<void>()
const api = OpenCode.make({
+1
View File
@@ -100,6 +100,7 @@ const layer = Layer.effect(
editor.providers.set(providerID, current)
}
fn(current.provider)
current.provider.id = providerID
},
remove: (providerID) => {
editor.providers.delete(providerID)
+1 -3
View File
@@ -43,9 +43,7 @@ const layer = Layer.effect(
const load = Effect.fnUntraced(function* (plugin: Generation) {
const child = yield* Scope.fork(scope)
const inherit = yield* State.inherit()
const loaded = yield* Effect.suspend(() =>
plugin.effect({ ...host, storage: PluginHost.storage(kv, plugin.id) }),
).pipe(
const loaded = yield* Effect.suspend(() => plugin.effect(PluginHost.forPlugin(host, kv, plugin.id))).pipe(
inherit,
Effect.updateContext((context: Context.Context<never>) =>
Context.make(Scope.Scope, child).pipe(
+14
View File
@@ -0,0 +1,14 @@
export * as PluginCallback from "./callback.js"
import { Data } from "effect"
/** Local failure detail. Transport boundaries must explicitly select public fields. */
export class Error extends Data.TaggedError("PluginCallbackError")<{
readonly pluginID: string
readonly operation: "skill.transform"
readonly cause: unknown
}> {
override get message() {
return `Plugin "${this.pluginID}" failed during ${this.operation}.`
}
}
+22
View File
@@ -33,6 +33,7 @@ import { WebSearch } from "../websearch.js"
import { Generate } from "../generate.js"
import { Permission } from "../permission.js"
import { PluginHooks } from "./hooks.js"
import { PluginCallback } from "./callback.js"
import type { Interface } from "../plugin.js"
import { LayerNode } from "@opencode-ai/util/effect/layer-node"
@@ -397,6 +398,7 @@ export const make = Effect.fn("PluginHost.make")(function* (
add: (name, source) => editor.add(name, Schema.decodeUnknownSync(Reference.Source)(source)),
remove: editor.remove,
list: editor.list,
get: editor.get,
})
}),
},
@@ -407,6 +409,7 @@ export const make = Effect.fn("PluginHost.make")(function* (
skill.transform((editor) => {
callback({
list: () => mutable(editor.list()),
get: editor.get,
add: (value) => editor.add(Schema.decodeUnknownSync(Skill.Info)(value)),
update: editor.update,
remove: editor.remove,
@@ -516,6 +519,25 @@ export const requirements = LayerNode.group([
LocationServiceMap.node,
])
export function forPlugin(host: Plugin.Context, kv: KV.Interface, pluginID: string): Plugin.Context {
return {
...host,
storage: storage(kv, pluginID),
skill: {
...host.skill,
transform: (callback) =>
host.skill.transform((editor) => {
try {
callback(editor)
} catch (cause) {
// Replay happens after setup, potentially in a different consumer's Effect context.
throw new PluginCallback.Error({ pluginID, operation: "skill.transform", cause })
}
}),
},
}
}
export function storage(kv: KV.Interface, pluginID: string): Plugin.Context["storage"] {
const namespace = `plugin:${pluginID
.split("")
+2
View File
@@ -32,6 +32,7 @@ type Editor = {
add(name: string, source: Source): void
remove(name: string): void
list(): readonly [string, Source][]
get(name: string): Source | undefined
}
export interface Interface extends State.Transformable<Editor> {
@@ -98,6 +99,7 @@ const layer = Layer.effect(
add: (name, source) => editor.sources.set(name, source),
remove: (name) => editor.sources.delete(name),
list: () => Array.from(editor.sources),
get: (name) => editor.sources.get(name),
}),
notify: () =>
Effect.gen(function* () {
+1 -4
View File
@@ -18,7 +18,6 @@ import { KV } from "./kv.js"
const Refresh = Schema.Struct({
attemptedAt: Schema.Number,
refreshedAt: Schema.optionalKey(Schema.Number),
})
const refreshInterval = Duration.toMillis(Duration.days(1))
@@ -161,7 +160,7 @@ const layer = Layer.effect(
if (status !== "cached") {
// Record attempts before network work so failures obey the same refresh interval.
yield* kv.set(key, { ...previous, attemptedAt: now })
yield* kv.set(key, { attemptedAt: now })
if (status === "cloned") {
yield* git.repo
@@ -205,8 +204,6 @@ const layer = Layer.effect(
.resetHard(existing, target ? `origin/${target}` : "HEAD")
.pipe(Effect.mapError((error) => new ResetFailedError({ repository, message: error.message })))
}
yield* kv.set(key, { attemptedAt: now, refreshedAt: yield* Clock.currentTimeMillis })
}
const checkout = yield* git.repo.discover(AbsolutePath.make(localPath))
+1 -9
View File
@@ -121,15 +121,7 @@ const layer = Layer.effect(
// The heterogeneous registry erases handlers after their selected schema validates input.
const execution: Effect.Effect<unknown, unknown> = Reflect.apply(handler, undefined, [parsed, callContext])
return execution
}).pipe(
Effect.catch((error) => encodeError(method, error)),
// Normalize handler bugs here so direct callers can recover just like HTTP callers.
Effect.catchDefect((defect) =>
Effect.logError("rpc handler failed", { rpc: rpcID, method: name, defect }).pipe(
Effect.andThen(Effect.fail(failure("rpc.internal", "RPC call failed"))),
),
),
)
}).pipe(Effect.catch((error) => encodeError(method, error)))
return yield* encode(method.output, result).pipe(
Effect.mapError((error) => failure("rpc.invalid_output", errorMessage(error, "Invalid RPC output"))),
)
+2
View File
@@ -74,6 +74,7 @@ export type Data = {
export type Editor = {
list: () => readonly Types.DeepMutable<Info>[]
get: (id: string) => Types.DeepMutable<Info> | undefined
add: (skill: Info) => void
update: (id: string, update: (skill: Types.DeepMutable<Info>) => void) => void
remove: (id: string) => void
@@ -96,6 +97,7 @@ const layer = Layer.effect(
initial: () => ({ skills: new Map() }),
editor: (editor) => ({
list: () => Array.from(editor.skills.values()),
get: (id) => editor.skills.get(ID.make(id)),
add: (skill) => {
editor.skills.set(skill.id, { ...skill } as Types.DeepMutable<Info>)
},
+26
View File
@@ -93,6 +93,32 @@ describe("Catalog", () => {
}),
)
it.effect("preserves provider identity when updating new and existing providers", () =>
Effect.gen(function* () {
const catalog = yield* Catalog.Service
const providerID = Provider.ID.make("original")
const renamed = Provider.ID.make("renamed")
yield* catalog.transform((editor) => {
editor.provider.update(providerID, (provider) => {
provider.id = renamed
provider.name = "Created"
})
expect(editor.provider.get(providerID)?.provider.id).toBe(providerID)
editor.provider.update(providerID, (provider) => {
provider.id = renamed
provider.name = "Updated"
})
})
expect(yield* catalog.provider.get(providerID)).toMatchObject({ id: providerID, name: "Updated" })
expect(yield* catalog.provider.get(renamed)).toBeUndefined()
expect((yield* catalog.provider.all()).map((provider) => provider.id)).toEqual([providerID])
yield* catalog.reload()
expect(yield* catalog.provider.get(providerID)).toMatchObject({ id: providerID, name: "Updated" })
}),
)
it.effect("derives availability from active credentials without changing provider state", () => {
const integrationID = Integration.ID.make("test")
const localCatalogLayer = Layer.fresh(
@@ -0,0 +1,95 @@
import { expect } from "bun:test"
import { Cause, Effect, Exit } from "effect"
import { Plugin } from "@opencode-ai/core/plugin"
import { Skill } from "@opencode-ai/core/skill"
import { AbsolutePath } from "@opencode-ai/schema/schema"
import { testEffect } from "../lib/effect"
import { PluginTestLayer } from "./fixture"
const it = testEffect(PluginTestLayer)
const skill = {
id: Skill.ID.make("review"),
name: Skill.Name.make("Review"),
description: "Review changes",
location: AbsolutePath.make("/fixture/review.md"),
content: "Review changes",
}
for (const cause of [new TypeError("synthetic-private-detail"), "synthetic-private-detail"]) {
it.effect(`attributes a deferred skill transform throwing ${typeof cause}`, () =>
Effect.gen(function* () {
const plugins = yield* Plugin.Service
const skills = yield* Skill.Service
let setup = false
const activation = yield* plugins
.activate([
{
id: "healthy",
revision: "1",
effect: (ctx) => ctx.skill.transform((editor) => editor.add(skill)).pipe(Effect.asVoid),
},
{
id: "broken-skills",
revision: "1",
effect: (ctx) =>
Effect.gen(function* () {
yield* ctx.skill.transform((editor) => {
editor.remove(skill.id)
throw cause
})
setup = true
}),
},
])
.pipe(Effect.exit)
expect(setup).toBe(true)
// Neither a partial fold nor the old value is returned after failure. Every read retries.
for (const exit of [
activation,
yield* skills.list().pipe(Effect.asVoid, Effect.exit),
yield* skills.get(skill.id).pipe(Effect.asVoid, Effect.exit),
]) {
if (Exit.isSuccess(exit)) throw new Error("Expected a failed skill fold")
expect(Cause.hasFails(exit.cause)).toBe(false)
expect(Cause.squash(exit.cause)).toMatchObject({
_tag: "PluginCallbackError",
pluginID: "broken-skills",
operation: "skill.transform",
message: 'Plugin "broken-skills" failed during skill.transform.',
cause,
})
}
// Only an explicit registration change removes the failure; nothing is silently disabled.
yield* plugins.activate([
{
id: "healthy",
revision: "1",
effect: (ctx) => ctx.skill.transform((editor) => editor.add(skill)).pipe(Effect.asVoid),
},
])
expect(yield* skills.list()).toEqual([skill])
}),
)
}
it.effect("keeps setup failures distinct from deferred callback failures", () =>
Effect.gen(function* () {
const plugins = yield* Plugin.Service
const skills = yield* Skill.Service
yield* plugins.activate([
{ id: "setup-failure", revision: "1", effect: () => Effect.die(new Error("fixture setup failed")) },
{
id: "healthy",
revision: "1",
effect: (ctx) => ctx.skill.transform((editor) => editor.add(skill)).pipe(Effect.asVoid),
},
])
expect((yield* plugins.list()).find((plugin) => plugin.id === "setup-failure")?.state).toMatchObject({
status: "failed",
error: expect.stringContaining("fixture setup failed"),
})
expect(yield* skills.list()).toEqual([skill])
}),
)
+20
View File
@@ -19,6 +19,26 @@ const referenceLayer = AppNodeBuilder.build(LayerNode.group([Reference.node, Bus
])
describe("Reference", () => {
it.effect("reads the current editor source by name", () =>
Effect.gen(function* () {
const references = yield* Reference.Service
const source = Reference.LocalSource.make({ type: "local", path: AbsolutePath.make("/docs") })
yield* references.transform((editor) => editor.add("docs", source))
yield* references.transform((editor) => {
expect(editor.get("docs")).toBe(editor.list()[0]?.[1])
expect(editor.get("docs")).toEqual(source)
expect(editor.get("missing")).toBeUndefined()
const replacement = Reference.GitSource.make({ type: "git", repository: "owner/repo" })
editor.add("docs", replacement)
expect(editor.get("docs")).toBe(replacement)
editor.remove("docs")
expect(editor.get("docs")).toBeUndefined()
})
expect(yield* references.list()).toEqual([])
}).pipe(Effect.provide(referenceLayer)),
)
it.effect("reads batched references before cache work and update events", () => {
const operations: RepositoryCache.EnsureInput[] = []
const started = Deferred.makeUnsafe<void>()
+30 -15
View File
@@ -2,7 +2,7 @@ import { describe, expect, setDefaultTimeout } from "bun:test"
import fs from "fs/promises"
import path from "path"
import { pathToFileURL } from "url"
import { Clock, Duration, Effect, Layer, Schema } from "effect"
import { Clock, Duration, Effect, Layer } from "effect"
import { AppNodeBuilder } from "@opencode-ai/core/effect/app-node-builder"
import { Global } from "@opencode-ai/util/global"
import { Repository } from "@opencode-ai/core/repository"
@@ -35,7 +35,7 @@ describe("RepositoryCache", () => {
expect((yield* cache.ensure({ reference: fixture.reference, refresh: "daily" })).status).toBe("cached")
expect(yield* read(path.join(initial.localPath, "README.md"))).toBe("one\n")
const yesterday = (yield* Clock.currentTimeMillis) - Duration.toMillis(Duration.days(1))
yield* kv.set(`repository-cache:${initial.localPath}`, { attemptedAt: yesterday, refreshedAt: yesterday })
yield* kv.set(`repository-cache:${initial.localPath}`, { attemptedAt: yesterday })
}).pipe(Effect.provide(cacheLayer(fixture.root)))
const results = yield* Effect.all(
@@ -61,7 +61,30 @@ describe("RepositoryCache", () => {
),
)
it.live("throttles failed refresh attempts without marking them successful", () =>
it.live("honors legacy attempt records while allowing forced refreshes", () =>
withRemote((fixture) =>
Effect.gen(function* () {
const cache = yield* RepositoryCache.Service
const kv = yield* KV.Service
const initial = yield* cache.ensure({ reference: fixture.reference, refresh: "daily" })
yield* Effect.promise(() => commit(fixture.source, "two\n", "advance main"))
// Persisted records from older versions include an unused success timestamp.
yield* kv.set(`repository-cache:${initial.localPath}`, {
attemptedAt: yield* Clock.currentTimeMillis,
refreshedAt: 0,
})
expect((yield* cache.ensure({ reference: fixture.reference, refresh: "daily" })).status).toBe("cached")
expect(yield* read(path.join(initial.localPath, "README.md"))).toBe("one\n")
expect((yield* cache.ensure({ reference: fixture.reference, refresh: true })).status).toBe("refreshed")
expect(yield* read(path.join(initial.localPath, "README.md"))).toBe("two\n")
expect((yield* cache.ensure({ reference: fixture.reference, refresh: "daily" })).status).toBe("cached")
}).pipe(Effect.provide(cacheLayer(fixture.root))),
),
)
it.live("throttles failed refresh attempts until the next interval", () =>
withRemote((fixture) =>
Effect.gen(function* () {
const cache = yield* RepositoryCache.Service
@@ -69,31 +92,23 @@ describe("RepositoryCache", () => {
const initial = yield* cache.ensure({ reference: fixture.reference, refresh: "daily" })
const key = `repository-cache:${initial.localPath}`
const yesterday = (yield* Clock.currentTimeMillis) - Duration.toMillis(Duration.days(1))
yield* kv.set(key, { attemptedAt: yesterday, refreshedAt: yesterday })
yield* kv.set(key, { attemptedAt: yesterday })
yield* Effect.promise(() =>
fs.rename(path.join(fixture.root, "origin.git"), path.join(fixture.root, "offline.git")),
)
const error = yield* Effect.flip(cache.ensure({ reference: fixture.reference, refresh: "daily" }))
expect(error).toBeInstanceOf(RepositoryCache.FetchFailedError)
const stored = yield* kv.get(key)
const stamp = Schema.decodeUnknownSync(
Schema.Struct({ attemptedAt: Schema.Number, refreshedAt: Schema.Number }),
)(stored)
expect(stamp.attemptedAt).toBeGreaterThan(yesterday)
expect(stamp.refreshedAt).toBe(yesterday)
expect((yield* cache.ensure({ reference: fixture.reference, refresh: "daily" })).status).toBe("cached")
expect(yield* kv.get(key)).toEqual(stored)
expect(yield* read(path.join(initial.localPath, "README.md"))).toBe("one\n")
yield* Effect.promise(async () => {
await fs.rename(path.join(fixture.root, "offline.git"), path.join(fixture.root, "origin.git"))
await commit(fixture.source, "two\n", "advance main")
})
yield* kv.set(key, { attemptedAt: yesterday, refreshedAt: yesterday })
yield* kv.set(key, { attemptedAt: yesterday })
expect((yield* cache.ensure({ reference: fixture.reference, refresh: "daily" })).status).toBe("refreshed")
expect(yield* read(path.join(initial.localPath, "README.md"))).toBe("two\n")
expect(yield* kv.get(key)).not.toEqual(stored)
}).pipe(Effect.provide(cacheLayer(fixture.root))),
),
)
@@ -157,13 +172,13 @@ describe("RepositoryCache", () => {
withRemote((fixture) =>
Effect.gen(function* () {
const cache = yield* RepositoryCache.Service
const initial = yield* cache.ensure({ reference: fixture.reference })
const initial = yield* cache.ensure({ reference: fixture.reference, refresh: "daily" })
yield* Effect.promise(async () => {
await git(initial.localPath, "config", "remote.origin.url", "https://github.com/other/repo.git")
await fs.writeFile(path.join(initial.localPath, "stale.txt"), "stale")
})
const replaced = yield* cache.ensure({ reference: fixture.reference })
const replaced = yield* cache.ensure({ reference: fixture.reference, refresh: "daily" })
expect(replaced.status).toBe("cloned")
expect(yield* exists(path.join(replaced.localPath, "stale.txt"))).toBe(false)
@@ -1,62 +0,0 @@
import { expect } from "bun:test"
import { AppNodeBuilder } from "@opencode-ai/core/effect/app-node-builder"
import { Location } from "@opencode-ai/core/location"
import { Rpc } from "@opencode-ai/core/rpc"
import { AbsolutePath } from "@opencode-ai/core/schema"
import { Effect, Layer, Logger, Schema } from "effect"
import { location } from "./fixture/location"
import { testEffect } from "./lib/effect"
const it = testEffect(
AppNodeBuilder.build(Rpc.node, [
Location.node.replace(Layer.succeed(Location.Service, location({ directory: AbsolutePath.make("/rpc-project") }))),
]),
)
const Broken = Rpc.define({
id: "broken",
methods: {
dies: { input: Schema.Undefined, output: Schema.String },
throws: { input: Schema.Undefined, output: Schema.String },
raw: { input: Schema.Undefined, output: Schema.String },
undeclared: { input: Schema.Undefined, output: Schema.String },
invalidError: {
input: Schema.Undefined,
output: Schema.String,
errors: { known: Schema.Struct({ count: Schema.Int }) },
},
},
events: {},
})
for (const method of ["dies", "throws", "raw", "undeclared", "invalidError"] as const) {
it.effect(`recovers from ${method} through the typed rpc.internal failure`, () =>
Effect.gen(function* () {
const rpc = yield* Rpc.Service
yield* rpc.register(Broken, {
dies: () => Effect.die(new Error("handler defect")),
throws: () => {
throw new Error("handler threw")
},
// Raw Promise rejections reach this boundary as failed Effects.
// @ts-expect-error intentionally exercise an undeclared failure
raw: () => Effect.fail(new Error("raw failure")),
// @ts-expect-error intentionally exercise an undeclared error name
undeclared: (_input, context) => Effect.fail(context.error("unknown", "Unknown")),
invalidError: (_input, context) => Effect.fail(context.error("known", "Invalid count", { count: 1.5 })),
})
const logged: unknown[] = []
const result = yield* rpc
.client(Broken)
[method]()
.pipe(
Effect.catchIf(
(error) => "type" in error && error.type === "rpc.internal",
(error) => Effect.succeed(error),
),
Effect.provideService(Logger.CurrentLoggers, new Set([Logger.make((entry) => logged.push(entry.message))])),
)
expect(result).toEqual({ type: "rpc.internal", message: "RPC call failed" })
expect(logged).toHaveLength(1)
}),
)
}
+19
View File
@@ -20,6 +20,25 @@ const info = (id: string, description: string) =>
})
describe("Skill", () => {
it.effect("reads the current editor entry by ID", () =>
Effect.gen(function* () {
const skill = yield* Skill.Service
yield* skill.transform((editor) => editor.add(info("review", "Initial")))
yield* skill.transform((editor) => {
expect(editor.get("review")).toBe(editor.list()[0])
expect(editor.get("missing")).toBeUndefined()
editor.update("review", (value) => {
value.description = "Updated"
})
expect(editor.get("review")?.description).toBe("Updated")
editor.remove("review")
expect(editor.get("review")).toBeUndefined()
})
expect(yield* skill.list()).toEqual([])
}),
)
it.effect("registers values with last-write-wins precedence", () =>
Effect.gen(function* () {
const skill = yield* Skill.Service
+1
View File
@@ -7,6 +7,7 @@ export interface ReferenceEditor {
add(name: string, source: ReferenceLocalSource | ReferenceGitSource): void
remove(name: string): void
list(): readonly (readonly [string, ReferenceLocalSource | ReferenceGitSource])[]
get(name: string): ReferenceLocalSource | ReferenceGitSource | undefined
}
export interface ReferenceDomain extends ReferenceApi<unknown> {
+1
View File
@@ -5,6 +5,7 @@ import type { Transform } from "./registration.js"
export interface SkillEditor {
list(): readonly Types.DeepMutable<Skill.Info>[]
get(id: string): Types.DeepMutable<Skill.Info> | undefined
add(skill: Skill.Info): void
update(id: string, update: (skill: Types.DeepMutable<Skill.Info>) => void): void
remove(id: string): void
+1
View File
@@ -6,6 +6,7 @@ export interface ReferenceEditor {
add(name: string, source: ReferenceLocalSource | ReferenceGitSource): void
remove(name: string): void
list(): readonly (readonly [string, ReferenceLocalSource | ReferenceGitSource])[]
get(name: string): ReferenceLocalSource | ReferenceGitSource | undefined
}
export interface ReferenceDomain extends ReferenceApi {
+1
View File
@@ -5,6 +5,7 @@ import type { DeepMutable } from "./types.js"
export interface SkillEditor {
list(): readonly DeepMutable<Skill.Info>[]
get(id: string): DeepMutable<Skill.Info> | undefined
add(skill: Skill.Info): void
update(id: string, update: (skill: DeepMutable<Skill.Info>) => void): void
remove(id: string): void
+1 -1
View File
@@ -22,7 +22,7 @@ export type Info<
) => Promise<Tool.Result<Output>>
}
interface ToolEditor {
export interface ToolEditor {
list(): readonly (Info & { readonly id: string })[]
get(id: string): (Info & { readonly id: string }) | undefined
namespace(namespace: Tool.Namespace): void
+31
View File
@@ -9259,6 +9259,16 @@
}
}
}
},
"500": {
"description": "PluginCallbackError",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/PluginCallbackErrorEncoded"
}
}
}
}
},
"description": "Retrieve currently registered skills.",
@@ -16984,6 +16994,27 @@
}
]
},
"PluginCallbackErrorEncoded": {
"type": "object",
"properties": {
"_tag": {
"type": "string",
"enum": ["PluginCallbackError"]
},
"pluginID": {
"type": "string"
},
"operation": {
"type": "string",
"enum": ["skill.transform"]
},
"message": {
"type": "string"
}
},
"required": ["_tag", "pluginID", "operation", "message"],
"additionalProperties": false
},
"Project": {
"type": "object",
"properties": {
+11
View File
@@ -1,5 +1,16 @@
import { Schema } from "effect"
import { Skill } from "@opencode-ai/schema/skill"
import { Plugin } from "@opencode-ai/schema/plugin"
export class PluginCallbackError extends Schema.TaggedError<PluginCallbackError>()(
"PluginCallbackError",
{
pluginID: Plugin.ID,
operation: Schema.Literal("skill.transform"),
message: Schema.String,
},
{ httpApiStatus: 500 },
) {}
export class InvalidRequestError extends Schema.TaggedError<InvalidRequestError>()(
"InvalidRequestError",
+2
View File
@@ -3,12 +3,14 @@ import { Location } from "@opencode-ai/schema/location"
import { Schema } from "effect"
import { HttpApiEndpoint, HttpApiGroup, OpenApi } from "effect/unstable/httpapi"
import { LocationQuery, locationQueryOpenApi } from "./location.js"
import { PluginCallbackError } from "../errors.js"
export const SkillGroup = HttpApiGroup.make("server.skill")
.add(
HttpApiEndpoint.get("skill.list", "/api/skill", {
query: LocationQuery,
success: Location.response(Schema.Array(Skill.Info)),
error: PluginCallbackError,
})
.annotateMerge(locationQueryOpenApi)
.annotateMerge(
+7 -5
View File
@@ -14,7 +14,7 @@ export const RpcHandler = HttpApiBuilder.group(Api, "server.rpc", (handlers) =>
return output === undefined ? {} : { output }
}).pipe(
Effect.mapError((error) =>
error.type === "rpc.invalid_output" || error.type === "rpc.internal"
error.type === "rpc.invalid_output"
? new RpcInternalError({ type: error.type, message: error.message })
: new RpcError({
type: error.type,
@@ -22,10 +22,12 @@ export const RpcHandler = HttpApiBuilder.group(Api, "server.rpc", (handlers) =>
...(error.data === undefined ? {} : { data: error.data }),
}),
),
// Defects outside handler execution are still logged, never echoed to the client.
Effect.catchDefect((defect) =>
Effect.logError("rpc call failed", { rpc: params.rpcID, method: params.method, defect }).pipe(
Effect.andThen(Effect.fail(new RpcInternalError({ type: "rpc.internal", message: "RPC call failed" }))),
Effect.catchDefect((error) =>
Effect.fail(
new RpcInternalError({
type: "rpc.internal",
message: error instanceof Error ? error.message : "RPC call failed",
}),
),
),
),
+22 -1
View File
@@ -1,8 +1,29 @@
import { Skill } from "@opencode-ai/core/skill"
import { PluginCallback } from "@opencode-ai/core/plugin/callback"
import { PluginCallbackError } from "@opencode-ai/protocol/errors"
import { Plugin } from "@opencode-ai/schema/plugin"
import { Effect } from "effect"
import { HttpApiBuilder } from "effect/unstable/httpapi"
import { Api } from "../api"
import { response } from "../location"
export const SkillHandler = HttpApiBuilder.group(Api, "server.skill", (handlers) =>
handlers.handle("skill.list", () => response(Skill.Service.use((skill) => skill.list()))),
handlers.handle("skill.list", () =>
response(Skill.Service.use((skill) => skill.list())).pipe(
Effect.catchDefect((error) => {
if (!(error instanceof PluginCallback.Error)) return Effect.die(error)
return Effect.logError("Plugin callback failed", error).pipe(
Effect.andThen(
Effect.fail(
new PluginCallbackError({
pluginID: Plugin.ID.make(error.pluginID),
operation: error.operation,
message: `${error.message} Check server logs for details.`,
}),
),
),
)
}),
),
),
)
@@ -1,74 +0,0 @@
import { expect } from "bun:test"
import { SdkPlugins } from "@opencode-ai/core/plugin/sdk"
import { define } from "@opencode-ai/plugin/effect/plugin"
import { Rpc } from "@opencode-ai/schema/rpc"
import { Context, Effect, Layer, Schema } from "effect"
import { HttpEffect, HttpRouter, HttpServer } from "effect/unstable/http"
import { tmpdirScoped } from "../../core/test/fixture/tmpdir"
import { it } from "../../core/test/lib/effect"
import { createEmbeddedRoutes } from "../src/routes"
const Broken = Rpc.define({
id: "broken",
methods: {
handler: { input: Schema.String, output: Schema.String },
schema: {
input: Schema.String.check(
Schema.makeFilter(() => {
throw new Error("private schema detail")
}),
),
output: Schema.String,
},
},
events: {},
})
for (const method of ["handler", "schema"] as const) {
it.live(`returns HTTP 500 without exposing the ${method} defect`, () =>
Effect.gen(function* () {
const directory = yield* tmpdirScoped()
const context = yield* Layer.build(
createEmbeddedRoutes({
database: { path: ":memory:" },
models: { fetch: false },
config: { directory: directory.path, project: false, content: "{}" },
fs: { filewatcher: false },
}).pipe(Layer.provide(HttpServer.layerServices)),
)
const sdk = Context.get(context, SdkPlugins.Service)
yield* sdk.register(
define({
id: "broken-rpc",
effect: (ctx) =>
ctx.rpc
.register(Broken, {
handler: () => Effect.die(new Error("private handler detail")),
schema: Effect.succeed,
})
.pipe(Effect.asVoid, Effect.orDie),
}),
)
const handler = Context.get(context, HttpRouter.HttpRouter)
.asHttpEffect()
.pipe(HttpEffect.toWebHandlerWith(context))
const url = new URL(`/api/rpc/broken/${method}`, "http://opencode.local")
url.searchParams.set("location[directory]", directory.path)
const response = yield* Effect.promise(() =>
handler(
new Request(url, {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({ input: "hello" }),
}),
),
)
expect(response.status).toBe(500)
expect(yield* Effect.promise(() => response.json())).toEqual({
_tag: "RpcInternalError",
type: "rpc.internal",
message: "RPC call failed",
})
}),
)
}
+129
View File
@@ -0,0 +1,129 @@
import { expect } from "bun:test"
import path from "node:path"
import { SdkPlugins } from "@opencode-ai/core/plugin/sdk"
import { Skill } from "@opencode-ai/core/skill"
import { Plugin } from "@opencode-ai/plugin/effect"
import { Context, Effect, Layer, Logger } from "effect"
import { HttpEffect, HttpRouter, HttpServer } from "effect/unstable/http"
import { tmpdirScoped } from "../../core/test/fixture/tmpdir"
import { it } from "../../core/test/lib/effect"
import { createRoutes } from "../src/routes"
it.live("skill.list reports the failing plugin without exposing its exception", () =>
Effect.gen(function* () {
const tmp = yield* tmpdirScoped("opencode-skill-failures-")
const messages: unknown[] = []
const logger = Logger.make((options) => messages.push(options.message))
const context = yield* Layer.build(
createRoutes({
password: "secret",
database: { path: ":memory:" },
models: { fetch: false },
fs: { filewatcher: false },
config: { directory: path.join(tmp.path, "config"), project: false },
}).pipe(
Layer.provide(HttpServer.layerServices),
Layer.provideMerge(Logger.layer([logger], { mergeWithExisting: false })),
),
)
const sdk = Context.get(context, SdkPlugins.Service)
const cause = new TypeError("synthetic-private-detail")
yield* sdk.register(
Plugin.define({
id: "broken-skills",
effect: (ctx) =>
ctx.skill
.transform(() => {
throw cause
})
.pipe(Effect.asVoid),
}),
)
const handler = Context.get(context, HttpRouter.HttpRouter)
.asHttpEffect()
.pipe(HttpEffect.toWebHandlerWith(context))
const request = (method: string, route: string) =>
Effect.promise(() =>
handler(
new Request(`http://opencode.local${route}?location[directory]=${encodeURIComponent(tmp.path)}`, {
method,
headers: { authorization: `Basic ${btoa("opencode:secret")}` },
}),
),
)
expect((yield* request("POST", "/api/plugin/await-activation")).status).toBe(204)
// The directory is valid. A skill failure is not a location-not-found error.
expect((yield* request("GET", "/api/location")).status).toBe(200)
for (const attempt of [1, 2]) {
const response = yield* request("GET", "/api/skill")
expect(response.status).toBe(500)
const body = yield* Effect.promise(() => response.text())
expect(body).toContain('"PluginCallbackError"')
expect(JSON.parse(body)).toEqual({
_tag: "PluginCallbackError",
pluginID: "broken-skills",
operation: "skill.transform",
message: 'Plugin "broken-skills" failed during skill.transform. Check server logs for details.',
})
expect(body).not.toContain("synthetic-private-detail")
expect(body).not.toContain("TypeError")
expect(body).not.toContain(tmp.path)
expect(
messages.filter((message) => Array.isArray(message) && message[0] === "Plugin callback failed"),
).toHaveLength(attempt)
}
expect(messages).toContainEqual([
"Plugin callback failed",
expect.objectContaining({ pluginID: "broken-skills", operation: "skill.transform", cause }),
])
}).pipe(Effect.timeout("10 seconds")),
)
for (const scenario of [
{ name: "unrelated defects", effect: Effect.die(new Error("unrelated-private-detail")), status: 500 },
// Effect's HTTP boundary maps server interruption to 503 (a client abort is 499).
{ name: "interruption", effect: Effect.interrupt, status: 503 },
]) {
it.live(`skill.list does not label ${scenario.name} as plugin callback failures`, () =>
Effect.gen(function* () {
const tmp = yield* tmpdirScoped("opencode-skill-control-")
const context = yield* Layer.build(
createRoutes(
{
password: "secret",
database: { path: ":memory:" },
models: { fetch: false },
fs: { filewatcher: false },
config: { directory: tmp.path, project: false },
},
() => [],
[
Skill.node.replace(
Layer.succeed(
Skill.Service,
Skill.Service.of({
list: () => scenario.effect,
get: () => Effect.undefined,
reload: () => Effect.void,
transform: () => Effect.succeed({ dispose: Effect.void }),
}),
),
),
],
).pipe(Layer.provide(HttpServer.layerServices)),
)
const handler = Context.get(context, HttpRouter.HttpRouter)
.asHttpEffect()
.pipe(HttpEffect.toWebHandlerWith(context))
const response = yield* Effect.promise(() =>
handler(
new Request(`http://opencode.local/api/skill?location[directory]=${encodeURIComponent(tmp.path)}`, {
headers: { authorization: `Basic ${btoa("opencode:secret")}` },
}),
),
)
expect(response.status).toBe(scenario.status)
expect(yield* Effect.promise(() => response.text())).toBe("")
}).pipe(Effect.timeout("10 seconds")),
)
}
@@ -252,13 +252,25 @@
justify-content: center;
flex-shrink: 0;
color: var(--v2-text-text-faint);
margin-left: auto;
margin-inline-start: auto;
opacity: 0;
transform: translateX(-4px);
transition:
opacity 0.15s ease,
color 0.15s ease;
color 0.15s ease,
transform 0.15s ease;
@media (hover: hover) {
opacity: 0;
:dir(rtl) & {
transform: translateX(4px);
}
@media (hover: none) {
opacity: 1;
transform: none;
}
@media (prefers-reduced-motion: reduce) {
transition: none;
}
}
@@ -285,6 +297,7 @@
[data-component="task-tool-action"] {
opacity: 1;
transform: none;
}
}
}
@@ -1398,13 +1398,13 @@ ToolRegistry.register({
<span data-slot="basic-tool-tool-subtitle">{subtitle()}</span>
</Show>
</div>
<Show when={clickable()}>
<div data-component="task-tool-action">
<Icon name="chevron-right" size="small" />
</div>
</Show>
</div>
</div>
<Show when={clickable()}>
<div data-component="task-tool-action">
<Icon name="square-arrow-top-right" size="small" />
</div>
</Show>
</div>
)
@@ -1,5 +1,6 @@
import type { PluginInfo } from "@opencode-ai/client"
import { Plugin } from "@opencode-ai/plugin/tui"
import path from "path"
import { createEffect, createMemo, createResource, createSignal, onCleanup, onMount, Show } from "solid-js"
import { DialogErrorDetails } from "../../component/dialog-error-details"
import { Spinner } from "../../component/spinner"
@@ -37,7 +38,7 @@ export function PluginsDialog(props: {
() => (props.server ? undefined : (props.context.location ?? props.context.data.location.default())),
(location) => props.context.client.plugin.list({ location }).then((result) => result.data),
)
onMount(() => dialog.setSize("medium"))
onMount(() => dialog.setSize("large"))
onCleanup(props.context.data.on("plugin.updated", () => void refetch()))
const updating = (entry: Entry) =>
pending().includes(entry.key) ||
@@ -167,13 +168,6 @@ export function PluginsDialog(props: {
.check({ location: props.context.location ?? props.context.data.location.default() })
.then((result) => {
mutate(result.data)
const count = result.data.filter(
(plugin) => plugin.source.type === "package" && plugin.source.outdated === true,
).length
props.context.ui.toast.show({
variant: count ? "info" : "success",
message: count ? `${count} plugin update${count === 1 ? "" : "s"} available` : "All plugins are up to date",
})
})
.catch((cause) => {
props.context.ui.toast.show({
@@ -218,19 +212,7 @@ export function PluginsDialog(props: {
}}
actions={[
{
title: toggleTitle(),
command: "plugins.toggle",
hidden: !focusedTui(),
onTrigger: (option) => toggle(entries().find((entry) => entry.key === option.value)),
},
{
title: "update",
command: "dialog.plugins.update",
hidden: !updatable(focusedEntry()),
onTrigger: (option) => update(entries().find((entry) => entry.key === option.value)),
},
{
title: checking() ? "checking" : "check",
title: checking() ? "checking for updates" : "check for updates",
command: "dialog.plugins.check",
selection: "none",
hidden: !entries().some(
@@ -239,6 +221,20 @@ export function PluginsDialog(props: {
disabled: checking(),
onTrigger: check,
},
{
title: toggleTitle(),
command: "plugins.toggle",
side: "right",
hidden: !focusedTui(),
onTrigger: (option) => toggle(entries().find((entry) => entry.key === option.value)),
},
{
title: "update",
command: "dialog.plugins.update",
side: "right",
hidden: !updatable(focusedEntry()),
onTrigger: (option) => update(entries().find((entry) => entry.key === option.value)),
},
]}
footer={
<Show when={pluginError(focusedEntry())}>
@@ -262,7 +258,7 @@ export function PluginsDialog(props: {
context={`Plugin: ${label(entry(), props.context)}\nStatus: failed\nRuntime: ${entry().runtime}\nSource: ${pluginSource(entry(), props.context)}`}
onBack={() => {
setDetail()
dialog.setSize("medium")
dialog.setSize("large")
}}
/>
)}
@@ -287,6 +283,14 @@ function source(plugin: PluginInfo, context: Plugin.Context) {
return plugin.source.type
}
function isLocal(entry: Entry) {
if (entry.runtime === "server") return entry.plugin.source.type === "local"
const target = entry.target
return (
target.startsWith("file://") || target.startsWith("./") || target.startsWith("../") || path.isAbsolute(target)
)
}
function status(entry: Entry) {
if (entry.runtime === "server") return entry.plugin.state.status
return entry.status
@@ -299,6 +303,7 @@ function outdated(entry: Entry) {
function footer(entry: Entry) {
const details = [
...(status(entry) === "active" ? [] : [status(entry)]),
...(isLocal(entry) ? ["local"] : []),
...(entry.runtime === "server" && entry.plugin.source.type === "package" && entry.plugin.source.version
? [displayVersion(entry.plugin.source.version)]
: []),
@@ -93,7 +93,7 @@ async function renderPlugins(root: string, inventory: { list: PluginInfo[]; chec
const app = await testRender(() => <Harness />, { width: 80, height: 20, kittyKeyboard: true })
app.renderer.start()
await app.waitForFrame((frame) => frame.includes("Plugins"))
await app.waitForFrame((frame) => frame.includes("team.plugins") || frame.includes("local.plugin"))
return { app, requests, toasts }
}
@@ -102,16 +102,16 @@ test("checking for updates refreshes the inventory and reveals the update action
const fixture = await renderPlugins(tmp.path, { list: [packagePlugin(false)], check: [packagePlugin(true)] })
try {
const initial = await fixture.app.waitForFrame((frame) => frame.includes("dadba13"))
expect(initial).toContain("check ctrl+r")
expect(initial).not.toContain("update available")
expect(initial).not.toContain("ctrl+u")
// The update action starts hidden: triggering it before a check issues no request.
fixture.app.mockInput.pressKey("u", { ctrl: true })
await fixture.app.flush()
expect(fixture.requests).toEqual([])
fixture.app.mockInput.pressKey("r", { ctrl: true })
const checked = await fixture.app.waitForFrame((frame) => frame.includes("update available"))
expect(checked).toContain("ctrl+u")
await fixture.app.waitFor(() => fixture.requests.length === 1)
expect(fixture.requests).toEqual([{ path: "/api/plugin/check", body: {} }])
expect(fixture.toasts).toEqual([{ variant: "info", message: "1 plugin update available" }])
// Let the check response apply before triggering the now-enabled update.
await fixture.app.flush()
fixture.app.mockInput.pressKey("u", { ctrl: true })
await fixture.app.waitFor(() => fixture.requests.length === 2)
@@ -126,12 +126,12 @@ test("checking for updates reports an up-to-date inventory", async () => {
const fixture = await renderPlugins(tmp.path, { list: [packagePlugin(false)], check: [packagePlugin(false)] })
try {
await fixture.app.waitForFrame((frame) => frame.includes("dadba13"))
fixture.app.mockInput.pressKey("r", { ctrl: true })
await fixture.app.waitFor(() => fixture.toasts.length === 1)
await fixture.app.waitFor(() => fixture.requests.length === 1)
await fixture.app.flush()
expect(fixture.toasts).toEqual([{ variant: "success", message: "All plugins are up to date" }])
expect(fixture.requests).toEqual([{ path: "/api/plugin/check", body: {} }])
expect(fixture.toasts).toEqual([])
} finally {
fixture.app.renderer.destroy()
}
@@ -148,9 +148,6 @@ test("the check action stays hidden without package plugins", async () => {
const fixture = await renderPlugins(tmp.path, { list: [local], check: [] })
try {
const frame = await fixture.app.waitForFrame((frame) => frame.includes("local.plugin"))
expect(frame).not.toContain("ctrl+r")
fixture.app.mockInput.pressKey("r", { ctrl: true })
await fixture.app.flush()
expect(fixture.requests).toEqual([])
+31
View File
@@ -9259,6 +9259,16 @@
}
}
}
},
"500": {
"description": "PluginCallbackError",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/PluginCallbackErrorEncoded"
}
}
}
}
},
"description": "Retrieve currently registered skills.",
@@ -16984,6 +16994,27 @@
}
]
},
"PluginCallbackErrorEncoded": {
"type": "object",
"properties": {
"_tag": {
"type": "string",
"enum": ["PluginCallbackError"]
},
"pluginID": {
"type": "string"
},
"operation": {
"type": "string",
"enum": ["skill.transform"]
},
"message": {
"type": "string"
}
},
"required": ["_tag", "pluginID", "operation", "message"],
"additionalProperties": false
},
"Project": {
"type": "object",
"properties": {
+31
View File
@@ -9259,6 +9259,16 @@
}
}
}
},
"500": {
"description": "PluginCallbackError",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/PluginCallbackErrorEncoded"
}
}
}
}
},
"description": "Retrieve currently registered skills.",
@@ -16984,6 +16994,27 @@
}
]
},
"PluginCallbackErrorEncoded": {
"type": "object",
"properties": {
"_tag": {
"type": "string",
"enum": ["PluginCallbackError"]
},
"pluginID": {
"type": "string"
},
"operation": {
"type": "string",
"enum": ["skill.transform"]
},
"message": {
"type": "string"
}
},
"required": ["_tag", "pluginID", "operation", "message"],
"additionalProperties": false
},
"Project": {
"type": "object",
"properties": {
@@ -644,7 +644,8 @@ effect: (ctx) =>
}),
```
Add or remove local and Git references, then reload after external state changes.
Add or remove local and Git references, then reload after external state changes. `get(name)` returns the current configured
source, or `undefined` when the name is absent.
```ts
effect: (ctx) =>
@@ -653,6 +654,7 @@ effect: (ctx) =>
yield* reference.transform((editor) => {
editor.add("handbook", { type: "local", path: "/workspace/docs/handbook" })
editor.add("standards", { type: "git", repository: "https://github.com/acme/standards", branch: "main" })
const handbook = editor.get("handbook")
editor.remove("legacy")
})
yield* reference.reload()
@@ -667,6 +669,7 @@ interface ReferenceEditor {
add(name: string, source: ReferenceLocalSource | ReferenceGitSource): void
remove(name: string): void
list(): readonly (readonly [string, ReferenceLocalSource | ReferenceGitSource])[]
get(name: string): ReferenceLocalSource | ReferenceGitSource | undefined
}
interface ReferenceDomain extends ReferenceApi<unknown> {
@@ -747,7 +750,8 @@ effect: (ctx) =>
}),
```
Transform and reload skills. Use the re-exported Effect schema constructors for branded values.
Transform and reload skills. Use the re-exported Effect schema constructors for branded values. `get(id)` returns the
current editor entry, or `undefined` when the skill is absent.
```ts
effect: (ctx) =>
@@ -761,6 +765,7 @@ effect: (ctx) =>
location: "/workspace/.opencode/skills/review.md",
content: "Review the current changes for correctness and missing tests.",
}))
const review = editor.get("review")
editor.update("review", (item) => (item.autoinvoke = true))
editor.remove("legacy")
})
@@ -773,6 +778,7 @@ Schema: [`Skill.Info`](/api#schema-Skill.Info).
```ts
interface SkillEditor {
list(): readonly Types.DeepMutable<Skill.Info>[]
get(id: string): Types.DeepMutable<Skill.Info> | undefined
add(skill: Skill.Info): void
update(id: string, update: (skill: Types.DeepMutable<Skill.Info>) => void): void
remove(id: string): void
@@ -596,13 +596,15 @@ Read the references available at a location.
const references = await ctx.reference.list()
```
Register a transform to inspect, add, or remove local and Git references.
Register a transform to inspect, add, or remove local and Git references. `get(name)` returns the current configured source,
or `undefined` when the name is absent.
```ts
await ctx.reference.transform((editor) => {
const references = editor.list()
editor.add("handbook", { type: "local", path: "/workspace/docs/handbook" })
editor.add("standards", { type: "git", repository: "https://github.com/acme/standards", branch: "main" })
const handbook = editor.get("handbook")
editor.remove("legacy")
})
```
@@ -627,6 +629,7 @@ interface ReferenceContext {
interface ReferenceEditor {
list(): readonly (readonly [string, ReferenceLocalSource | ReferenceGitSource])[]
get(name: string): ReferenceLocalSource | ReferenceGitSource | undefined
add(name: string, source: ReferenceLocalSource | ReferenceGitSource): void
remove(name: string): void
}
@@ -717,7 +720,8 @@ Read the skills available at a location.
const skills = await ctx.skill.list()
```
Register a transform to inspect, add, update, or remove skills.
Register a transform to inspect, add, update, or remove skills. `get(id)` returns the current editor entry, or `undefined`
when the skill is absent.
```ts
await ctx.skill.transform((editor) => {
@@ -729,6 +733,7 @@ await ctx.skill.transform((editor) => {
location: "/workspace/.opencode/skills/review.md",
content: "Review the current changes for correctness and missing tests.",
})
const review = editor.get("review")
editor.update("review", (skill) => {
skill.autoinvoke = true
})
@@ -755,6 +760,7 @@ interface SkillContext {
interface SkillEditor {
list(): readonly SkillInfo[]
get(id: string): SkillInfo | undefined
add(skill: SkillInfo): void
update(id: string, update: (skill: SkillInfo) => void): void
remove(id: string): void